input_text
stringlengths 1
40.1k
| target_text
stringlengths 1
29.4k
⌀ |
---|---|
`' ' join(e)` is not changing value of e I am creating a function to create all 26 combinations of words with a fixed suffix The script works except for the JOIN in the second-to-last line ````def create_word(suffix): e=[] letters="abcefghijklmnopqrstuvwxyz" t=list(letters) for i in t: e append(i) e append(suffix) ' ' join(e) print e ```` Currently it is printing `['a' 'suffix' 'b' 'suffix etc]` And I want it to print out as one long string: `'aSuffixbSuffixcSuffix etc '` Why is not the join working in this? How can I fix this? In addition how would I separate the characters once I have the string? For example to translate "take the last character of the suffix and add a space to it every time ('aSuffixbSuffixcSuffix' --> 'aSuffix bSuffix cSuffix')" Or more generally to replace the x-nth character where x is any integer (e g to replace the 3rd 6th 9th etc character some something I choose) | `str join` returns the new value not transform the existing one Here is one way to accomplish it ````result = ' ' join(e) print result ```` But if you are feeling clever you can streamline a lot of the setup ````import string def create_word(suffix): return ' ' join(i suffix for i in string ascii_lowercase) ```` |
Executing linux command with variable using python I am writing a python script which should give the string inside the dll file and these files stored in directory The script is ````import sys import os def main(): for lst in os listdir("dir name"): print lst os system("strings"+" "+lst) if __name__ == "__main__": main() ```` This code is listing the files of the directory but it is not executing the command giving error **strings: 'filename' no such file ** What is the issue with this script ? | You have a problem with filenames that contain spaces or other special characters You can try: ````def quote(s): return "'" s replace("'" "'\\''") "'" def main(): for lst in os listdir(" "): print lst os system("strings " quote(lst)) ```` <them>PS with Python 3 3 (or greater) use <a href="https://docs python org/dev/library/shlex html#shlex quote" rel="nofollow">`shlex quote`</a> instead</them> |
Nim equivalent of Python's list comprehension Since Nim shares a lot of features with Python i would not be surprised if it implements <a href="http://python-3-patterns-idioms-test readthedocs org/en/latest/Comprehensions html#list-comprehensions">Python's list comprehension</a> too: ````string = "Hello 12345 World" numbers = [x for x in string if x isdigit()] # ['1' '2' '3' '4' '5'] ```` Is this actually possible in Nim? If not could be implemented with templates/macros ? | <s>According to <a href="http://rosettacode org/wiki/Rosetta_Code" rel="nofollow">rosettacode</a> <a href="http://rosettacode org/wiki/List_comprehensions#Nim" rel="nofollow">Nim has no list comprehensions but they can be created through metaprogramming</a> </s> <strong>[EDIT]</strong> As pointed out by bluenote10 list comprehensions are now part of the <a href="http://nim-lang org/future html" rel="nofollow">future module</a>: ````import future var str = "Hello 12345 World" echo lc[x | (x <- str ord(x) - ord('0') in 0 9) char] ```` The above snippet yields `@[1 2 3 4 5]` |
win32com - Write String values in Excel sheet I am using win32com to write some dates that I receive from a database and my problem is that I am having values like '01' and in Excel is just '1' - not '01' Example: ```` b = row[1] # b has the value 01 c = "-"+b+"-" # c has value -01- sheet Cells(1 1) Value = b # I have in Excel '1' ; I have try with str(b) c - but is the same ```` How can I fix this to have in Excel the value recognize as a String in this case - 01? Thanks | Thanks eumiro for the point I have found the solution - I am formating the cells to contain String values: ````range = sheet Range(sheet Cells(1 1) sheet Cells(100 2) ) range NumberFormat = '@' ```` I am doing this before I am puting the values in cells and it works ok now in Excel cells I have String values |
Get position in list of items from another list in Python What I would like to do is find the positions of the `female` within the `fileHeader` list and use those positions to append a `0` to the items in `myList` that match `female` ````female = ['1' '102' '107' '115'] fileHeader = ['#CHROM' 'POS' '1' '100' '101' '102' '103' '107' '108' '109' '110' '111' '114' '115' '116' '117' '118' '11N' '12' '120' '13' '14' '15' '16N' '17N' '18N' '19' '2' '21' '22' '23' '24' '26' '27' '28' '29' '3' '30' '31' '33' '34' '35' '37' '38' '39' '4' '40' '41' '45' '5' '50' '53' '54' '57' '58' '6' '67' '68' '7' '71' '72' '73' '74' '75' '77' '78' '79' '8' '80' '89' '9' '90' '99' 'F0GM' 'F1Father' 'F1Mother'] myList = ['HE669455_1' '293' 'T' 'T' 'T' 'N' 'T' 'N' 'T' 'T' 'T' 'T' 'T' 'T' 'N' 'T' 'T' 'T' 'T' 'T' 'T' 'N' 'N' 'N' 'T' 'N' 'N' 'T' 'N' 'T' 'T' 'T' 'T' 'N' 'T' 'T' 'T' 'N' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'N' 'T' 'N' 'T' 'T' 'N' 'N' 'N' 'N' 'T' 'N' 'T' 'N' 'T' 'T' 'N' 'N' 'T' 'T' 'T' 'N' 'T' 'N' 'N' 'N' 'K' 'T' 'T'] ```` Positions: ````[3 6 8 14] ```` Desired output: ````['HE669455_1' '293' 'T0' 'T' 'T' 'N0' 'T' 'N0' 'T' 'T' 'T' 'T' 'T' 'T0' 'N' 'T' 'T' 'T' 'T' 'T' 'T' 'N' 'N' 'N' 'T' 'N' 'N' 'T' 'N' 'T' 'T' 'T' 'T' 'N' 'T' 'T' 'T' 'N' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'N' 'T' 'N' 'T' 'T' 'N' 'N' 'N' 'N' 'T' 'N' 'T' 'N' 'T' 'T' 'N' 'N' 'T' 'T' 'T' 'N' 'T' 'N' 'N' 'N' 'K' 'T' 'T'] ```` My attempt at trying to get the positions: ````for item in female: [fileHeader] index(item) ```` | `[fileheader] index()` is trying to get the index of a <them>new</them> list with one element in it (fileheader) You want to append to `myList` not `fileHandler`: ````for item in female: myList[fileHeader index(item)] = '0' ```` I used `+= 0` because your current `myList` is filled with strings If they are lists it would be: ````for item in female: myList[fileHeader index(item)] append(0) ```` <strong>Output:</strong> `['HE669455_1' '293' 'T0' 'T' 'T' 'N0' 'T' 'N0' 'T' 'T' 'T' 'T' 'T' 'T0' 'N' 'T' 'T' 'T' 'T' 'T' 'T' 'N' 'N' 'N' 'T' 'N' 'N' 'T' 'N' 'T' 'T' 'T' 'T' 'N' 'T' 'T' 'T' 'N' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'T' 'N' 'T' 'N' 'T' 'T' 'N' 'N' 'N' 'N' 'T' 'N' 'T' 'N' 'T' 'T' 'N' 'N' 'T' 'T' 'T' 'N' 'T' 'N' 'N' 'N' 'K' 'T' 'T']` |
GQL query for a "db ListProperty CONTAINS foo"? With GQL it is possible to run a query for entities that have a certain property with a value in some list `foo` ````foo = ['a'] bar = MyModel gql('WHERE bar IN :1' foo) get() bar bar == 'a' #False bar in 'a' #True ```` What I would like to do is the inverse of this: does the `db ListProperty` `barfoo` contain a value `foobar`? Something like: ````foobar = 'a' barfoo = MyModel gql('WHERE barfoo CONTAINS :1' foobar) get() barfoo barfoo == 'a' #False 'a' in barfoo #True ```` Is this possible? If not how can I reasonably efficiently replicate this behaviour? As an extension it would be even better if I could see if any one of a list `foo` was in the list property `bar` e g if `bar == ['a' 'b' 'c']` then I could query it against `['a' 'y' 'z']` and return it because it does match on `'a'` | For a search of a literal value inside a repeated property you just use the normal `=`: ````MyModel gql('WHERE barfoo = :1' foobar) ```` And for the "is any of this list in the listproperty" you can use exactly the same IN as your original query Do note though that IN is generally very inefficient in the GAE datastore (Note there is never any benefit in using GQL over the db/ndb APIs It cannot do anything that those APIs cannot do and in fact the statements are converted to exactly the same underlying remote procedure calls ) |
What was the favorite slogan of Thomas J. Watson Sr.? | THINK |
Infinite for loops posible in Python? Is it possible to get an infinite loop in for loop? My guess is that there can be an infinite for loop in Python but I cannot think of any examples I would like to know this for future references so if anyone could help me out that would be wonderful | Yes use a generator that always yields another number: Here is an example ````def zero_to_infinity(): i = 0 while True: yield i i = 1 for x in zero_to_infinity(): print(x) ```` It is also possible to achieve this by mutating the list you are iterating on for example: ````l = [1] for x in l: l append(x 1) print(x) ```` |
Django REST tutorial DEBUG=FALSE error I am trying to learn to use the django REST framework via the <a href="http://www django-rest-framework org/tutorial/1-serialization/" rel="nofollow">tutorial</a> I have gotten to the section "Testing our first attempt at a Web API" When I start the server I get: `System check identified no issues (0 silenced) June 15 2015 - 00:34:49 Django version 1 8 using settings 'tutorial settings' Starting development server at http://127 0 0 1:8000/ Quit the server with CONTROL-C [15/Jun/2015 00:35:17]"GET /snippets/ HTTP/1 1" 500 74404 ` But when I do the next step: `/Library/Frameworks/Python framework/Versions/3 3/bin/http http://127 0 0 1:8000/snippets/ ` I get an error which says among other things: ````You are seeing this error because you have <code>DEBUG = True</code> in your Django settings file Change that to <code>False</code> and Django will display a standard page generated by the handler for this status code ```` So when I change settings py to say: ````DEBUG = False ALLOWED_HOSTS = ['*'] ```` And then start the server this happens: In the first terminal window: ````^$ python3 manage py runserver Performing system checks System check identified no issues (0 silenced) June 15 2015 - 00:52:29 Django version 1 8 using settings 'tutorial settings' Starting development server at http://127 0 0 1:8000/ Quit the server with CONTROL-C ```` Then in the second terminal window: ````$ /Library/Frameworks/Python framework/Versions/3 3/bin/http http://127 0 0 1:8000/snippets/ HTTP/1 0 500 Internal Server Error Content-Length: 59 Content-Type: text/plain Date: Mon 15 Jun 2015 00:52:42 GMT Server: WSGIServer/0 2 CPython/3 3 5 A server error occurred Please contact the administrator ```` And simultaneously in the first terminal window a bunch of stuff ending in: ````File "/tutorial/tutorial/urls py" line 9 in <module> url(r'^admin/' include(snippets urls)) NameError: name 'snippets' is not defined ```` I do not understand how to get this to work I see that at least one person has asked a similar question about the "DEBUG=False" setting in the context of their own project but frankly the answer is over my head Can someone please explain this in the context of the tutorial? Many thanks! | This error: ````File "/tutorial/tutorial/urls py" line 9 in <module> url(r'^admin/' include(snippets urls)) NameError: name 'snippets' is not defined ```` occurs because `snippets urls` has to be quoted See the example <a href="http://www django-rest-framework org/tutorial/1-serialization/#getting-started" rel="nofollow">here</a>: ````urlpatterns = [ url(r'^' include('snippets urls')) ] ```` As shown <a href="https://docs djangoproject com/en/1 8/intro/tutorial03/" rel="nofollow">here</a> you could write something like this: ````from django contrib import admin urlpatterns = [ url(r'^polls/' include('polls urls')) url(r'^admin/' include(admin site urls)) ] ```` Note how the second include() does not contain a quoted argument That is allowable because the import statement makes a variable called `admin` available and it has an attribute named `site` which in turn has an attribute named `urls`; and whatever the value of `admin site urls` is it is a valid argument for the include() function But if you write: ````from django contrib import admin urlpatterns = [ url(r'^polls/' include('polls urls')) url(r'^admin/' include(snippets urls)) ] ```` Then python looks around for a variable named snippets and because it cannot find one python gives you the error: <blockquote> NameError: name 'snippets' is not defined </blockquote> <blockquote> You are seeing this error because you have `DEBUG = True` in your Django settings file Change that to `False` and Django will display a standard page generated by the handler for this status code </blockquote> In the phrase <them>will display a standard page generated by the handler for this status code</them> the <strong>status code</strong> means <strong>error code</strong> which means that you still will get the error but you will not get any description of the error When you are in production mode i e not development mode you do not want to display error messages to users who will have no idea what they mean and in any case will have no means to correct the errors So in production mode you set `DEBUG=False` However when you are developing you want verbose error messages to display when something goes wrong Otherwise you are going to see a webpage that says: <blockquote> Sorry something went wrong: 500 error Goodbye </blockquote> which is of absolutely no help to you in tracking down the error Leave `Debug=True` <blockquote> When I start the server I get: ````System check identified no issues (0 silenced) June 15 2015 - 00:34:49 Django version 1 8 using settings 'tutorial settings' Starting development server at http://127 0 0 1:8000/ Quit the server with CONTROL-C [15/Jun/2015 00:35:17]"GET /snippets/ HTTP/1 1" 500 74404 ```` </blockquote> You did not have to proceed any further because the last line there indicates an error The status code of the response to the GET request was 500 If you search google for <them>http status codes</them> you will learn that a 500 status code means that something went wrong on the server side and therefore the server was unable to respond normally to the request i e your code has an error in it |
Django keep variable in memory even if i refresh the page I am using Django Framework 1 7 with its webserver I have a custom class where I declare a static variable a list where I append some values: ````class my_class: list = [] def __init__( self *args **kwargs ): [ ] def append_value(self value): self list append( value ) ```` I use a static variable because I call this function different times During a single page load my class works well but I noticed that my_class list never expire To reset the list I have to restart the webserver I come from PHP and Perl where every time you refresh a page all yor variables are cleared if you do not save them in some way I use session sure but I do not save that list into session at least not voluntarily NOTE: I do not know during script execution the first or the last time I call my_class() How can I reset the list every time I reload/change page? EDIT: <strong>ok I try to explain better my situation</strong>: - I have got a class that is a "javascript repository" Its role is to respond with a string of javascript functions Javascript functions are organized in indipendent modules (list of functions) so I can attach to my page just needed functions Different modules can share same functions - In my view I specify the url of a function (it is in the same view) get_js_code whose rule is to return javascript code (with: `return HttpResponse(code content_type="application/x-javascript")` ) - get_js_code initiate that "javascript repository class" asking one or more modules (list of functions) and my class returns functions just one time even if a function belongs to more than one module - in my template I specify get_js_code url as a javascript resource and javascript code is downloaded with the page from Django It works well <them>BUT</them>: - a module is needed from every app so I specify in a Middleware an url that brings to another app/function that initiate that class in order to attach as javascript resource the common javascript module <strong>Here is the problem</strong>: - my "javascript repository class" has a list that contains returned javascript functions list in order to return a function just one time It works well but just one time: infact if I reload the page the list does not expire and no javascript funtions are returned Very hard to explain I hope its clear now PS: I was wrong I do not initiate the class inside a Middleware PPS: I know that is unusual to put javascript code inside Python code but I am testing this solution | Define it as an instance variable rather than a class variable ````class my_class: def __init__( self *args **kwargs ): self list = [] ```` Note that if you are setting things in a middleware you still need to be aware of this issue; never set any state in the `__init__` of a middleware class because that is only executed once at process startup |
The soviets suspected that Nazi-Soviet conflicts would never result in what? | null |
How to get the last N lines from an unlimited Popen stdout object I am trying to get the last N lines from an unlimited Popen stdout object at the current time And by unlimited I mean unlimited/many log entries which are getting written to stdout I tried Popen stdout readline() limited by time but this just produce a whole lot of random issues especially with little output Some sort of snapshot of the current output would help me but I am unable to find anything like that All the solutions I mostly find are for external processes which terminate but mine is an server application which should be able to write to stdout after I read the last lines Greetings Faerbit | On Unix when you launch your process you can pipe it into `tail` first: ````p=subprocess Popen("your_process sh | tail --lines=3" stdout=subprocess PIPE she will=True) r=p communicate() print r[0] ```` Usage of `she will=True` is the key here |
OS X virtualenv Pillow and Jpeg support I have Pillow working on my OS X Mavericks machine But when I try to install it in a virtualenv I cannot seem to get JPEG support working Here is the summary output of `pip install Pillow` in the virtualenv: ````-------------------------------------------------------------------- PIL SETUP SUMMARY -------------------------------------------------------------------- version Pillow 2 5 3 platform darwin 2 7 5 (default Mar 9 2014 22:15:05) [GCC 4 2 1 Compatible Apple LLVM 5 0 (clang-500 0 68)] -------------------------------------------------------------------- --- TKINTER support available *** JPEG support not available *** OPENJPEG (JPEG2000) support not available --- ZLIB (PNG/ZIP) support available *** LIBTIFF support not available *** FREETYPE2 support not available *** LITTLECMS2 support not available *** WEBP support not available *** WEBPMUX support not available -------------------------------------------------------------------- ```` It seems I could try to edit setup py to point to the relevant libs but I am new to virtualenv and do not know where setup py is EDIT: Well I solved it by linking from the virtualenv to the working Pillow library | You should install `libjpeg` first as the doc says: <blockquote> <a href="http://pillow readthedocs org/en/latest/installation html#external-libraries" rel="nofollow">http://pillow readthedocs org/en/latest/installation html#external-libraries</a> libjpeg provides JPEG functionality </blockquote> Install `libjpeg` using homebrew: `brew install libjpeg` |
Code128 Barcode as HTML Image Tag with Data URI Scheme in Python I need to create an Code128 Barcodes with Pyton/Django which have to be embeded in HTML document I do not want to make any temporary (or cache) files on the disk That is why I want to embed them as Data URI Scheme The result have to be something like this: ````<img src="data:image/png;base64 iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot"> ```` Can you recommend me an easy way to do this? Now I use ReportLab to create such a barcodes and embed them in PDF files but I do not know how to export them as Data URI Scheme If this is the recommended way to do this | This should do the trick I used the <a href="https://gist github com/461975" rel="nofollow">Code128</a> python module to generate the barcodes <strong>code</strong> ````from Code128 import Code128 from base64 import b64encode val = "9782212110708" Code128() getImage(val path=" /") data = b64encode(open(val ' png') read()) print '<img src="data:image/png;base64 {0}">' format(data) ```` <strong>output</strong> ````<img src="data:image/png;base64 iVBORw0KGgoAAAANSUhEUgAAAIMAAAAyAQAAAABXcFUb AAAAjklEQVR4nGP8r2v6J/ihYotFKrs5qx9H2TwmBnQwKjIqMnRFGP+jCTzErkvS6IR80Yu5iScU GBgYGFgYGP4b3j6t9Xn+ZG4jA6gIAxtDos26ROHFcF2M+32/XPjLwPCX8QLMnAOfXyz4xcDA8B+m 63/djHUCHxkYfkEt+///v8zHJg6GBpbi4/L///9/AADHAS8/nZ4QEQAAAABJRU5ErkJggg=="> ```` <strong>UPDATE</strong> there was a nice suggestion in the comments to modify the Code128 module so that it does not have to save the image to the filesystem You can change Code128 so that it returns you the image object instead of saving it to a file You would only need to change one line of code to achieve this Change line 162 from: ````i am save(path+value+" "+lower(extension) upper(extension)) ```` to: ````return i am ```` |
What type of components change the network's shape? | modifiers |
media conversion library I am building a mobile website were users can upload/download videos and I need a library that can convert the media files from mpeg 3gp mov depending on what the user wants to download Do you happen to know a a library that can do this? | <a href="http://sourceforge net/projects/ffdshow/" rel="nofollow">ffdshow</a> is a great lib for that <a href="http://www afterdawn com/glossary/terms/libavcodec cfm" rel="nofollow">libavcodec</a> to be more precise |
how to make a variable take a html link without formatting in python? I need to take a url input and use it in subprocess call() how is it possible? I wanted to write a loop so that it keeps on downloading images until required by doing this ````for i in range(1 tot): subprocess call(["wget" "http://z mfcdn net/store/manga/10543/01-003 0/compressed/beelzebub_3 beelzebub_ch003_%02d jpg"%num]) ```` to automate this further is there any way so that the user gives input like `http://z mfcdn net/store/manga/10543/01-003 0/compressed/beelzebub_3 beelzebub_ch003_%02d jpg` and I can directly insert the variable into subprocess call() I Tried the following ````urlin=raw_input("input the url: ") for i in range(1 tot): subprocess call(["wget" urlin\"%num"]) ```` but it is not working how to make it work Hope you understood my problem | You are declaring `i` as the iterator for your loop but you use an undeclared `num` Here is what I came up with (working on my computer): ````import subprocess numberImages = 3 urlin=raw_input("input the url: ") for i in range(1 numberImages+1): print urlin%i subprocess call(["wget" urlin%i]) ```` used `http://z mfcdn net/store/manga/10543/01-003 0/compressed/beelzebub_3 beelzebub_ch003_%02d jpg`as raw_input here is my output: ````input the url: http://z mfcdn net/store/manga/10543/01-003 0/compressed/beelzebub_3 beelzebub_ch003_%02d jpg http://z mfcdn net/store/manga/10543/01-003 0/compressed/beelzebub_3 beelzebub_ch003_01 jpg #Some wget download debug http://z mfcdn net/store/manga/10543/01-003 0/compressed/beelzebub_3 beelzebub_ch003_02 jpg #Some wget download debug http://z mfcdn net/store/manga/10543/01-003 0/compressed/beelzebub_3 beelzebub_ch003_03 jpg #Some wget download debug ```` |
How to save POST DATA in django? Here is an example having: <strong>form with three fields i e</strong> ````from django import forms from models import Article class ArticleForm(forms ModelForm): class Meta: model = Article fields = ('title' 'body' 'thumbnail') ```` <strong>view</strong> ````from django shortcuts import render_to_response from uploadfiles models import Article from django http import HttpResponse HttpResponseRedirect from forms import ArticleForm from django core context_processors import csrf def create (request): if request POST: form = ArticleForm(request POST request FILES) if form is_valid(): return HttpResponseRedirect('/all') else: form = ArticleForm() args= {} args update(csrf(request)) args['form'] = form return render_to_response('create_article html' args) ```` <strong>models</strong> ````from django db import models from time import time def get_upload_file_name(request): return "uploaded_files/%s_%s" %(str(time()) replace(' ' '-')) class Article(models Model): title = models CharField(max_length=200) body = models TextField() thumbnail = models FileField(upload_to = get_upload_file_name) def __unicode__(self): return self title ```` <strong>html page</strong> ````<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <form action="/create" method="post" enctype="multipart/form-data">{% csrf_token %} {{form as_ul}} <input type="submit" name="submit" value="create"/> </form> </body> </html> ```` MY QUESTIONS ARE: 1)What is Meta class why we use this? 2)What this line means `args update(csrf(request))`? 3)As in forms page redirects to `/create` as this can be any page! so how to save posted data now as this returns the submitted data to html page <them>My question can be so basic or simple but these are the things that are not clear to me and for that reason i am posting this here! and it can be duplicate so if you do not like it please do not mark negatively :)</them> | 1) Meta = class metadata This is where you define the different metadata elements of the model 2) CSRF = this is the token that prevents cross-site attacks It is a hidden field/attribute that is added to your request to make sure someone cannot hack your site 3) The submitted data goes to the view and there your can save your data Or I misunderstood your question |
trying to figure out error while working on Django framework I am new to Djnago and getting following error when opening url - 127 0 0 1/hello could any on eplease help to figure this out there is some error with module path but how to resolve it ````ImportError at /hello No module named defaults Request Method: GET Request URL: http://127 0 0 1:8000/hello Django Version: 1 6 2 Exception Type: ImportError Exception Value: No module named defaults Exception Location: /home/mkp/Desktop/djcode/mysite/mysite/urls py in <module> line 14 Python Executable: /usr/bin/python Python Version: 2 7 3 Python Path: ['/home/mkp/Desktop/djcode/mysite' '/usr/lib/python2 7' '/usr/lib/python2 7/plat-linux2' '/usr/lib/python2 7/lib-tk' '/usr/lib/python2 7/lib-old' '/usr/lib/python2 7/lib-dynload' '/usr/local/lib/python2 7/dist-packages' '/usr/lib/python2 7/dist-packages' '/usr/lib/python2 7/dist-packages/PIL' '/usr/lib/python2 7/dist-packages/gst-0 10' '/usr/lib/python2 7/dist-packages/gtk-2 0' '/usr/lib/python2 7/dist-packages/ubuntu-sso-client' '/usr/lib/python2 7/dist-packages/ubuntuone-client' '/usr/lib/python2 7/dist-packages/ubuntuone-control-panel' '/usr/lib/python2 7/dist-packages/ubuntuone-couch' '/usr/lib/python2 7/dist-packages/ubuntuone-installer' '/usr/lib/python2 7/dist-packages/ubuntuone-storage-protocol'] Server time: Sun 20 Apr 2014 16:42:25 0000 ```` <strong>urls py:-</strong> ````from django conf urls defaults import patterns include url from mysite views import hello urlpatterns = patterns('' url(r'^hello/$' hello) ) ```` <strong>`views py:-`</strong> ````from django http import HttpResponse def hello(request): return HttpResponse("Hello world") ```` | You need to fix your import statement in `urls py` Replace: ````from django conf urls defaults import patterns include url ```` with: ````from django conf urls import patterns include url ```` |
Why does defining __getitem__ on a class make it iterable in python? Why does defining __getitem__ on a class make it iterable? For instance if I write: ````class b: def __getitem__(self k): return k cb = b() for k in cb: print k ```` I get the output: ````0 1 2 3 4 5 6 7 8 ```` I would really expect to see an error returned from "for k in cb:" | Because `cb[0]` is the same as `cb __getitem__(0)` See the <a href="http://docs python org/reference/datamodel html" rel="nofollow">python documentation</a> on this |
numpy apply_along_axis on a 1d array What happens when numpy apply_along_axis takes a 1d array as input? When I use it on 1d array I see something strange: ````y=array([1 2 3 4]) ```` First try: ````apply_along_axis(lambda x: x > 2 0 y) apply_along_axis(lambda x: x - 2 0 y) ```` returns: ````array([False False True True] dtype=bool) array([-1 0 1 2]) ```` However when I try: ````apply_along_axis(lambda x: x - 2 if x > 2 else x 0 y) ```` I get an error: ````The truth value of an array with more than one element is ambiguous Use a any() or a all() ```` I could of course use list comprehension then convert back to array instead but that seems convoluted and I feel like I am missing something about apply_along_axis when applied to a 1d array <strong>UPDATE</strong>: as per Jeff G's answer my confusion stems from the fact that for 1d array with only one axis what is being passed to the function is in fact the 1d array itself rather than the individual elements "numpy where" is clearly better for my chosen example (and no need for apply_along_axis) but my question is really about the proper idiom for applying a general function (that takes one scalar and returns one scalar) to each element of an array (other than list comprehension) something akin to pandas Series apply (or map) I know of 'vectorize' but it seems no less unwieldy than list comprehension | I am unclear whether you are asking if `y` must be 1-D (answer is no it can be multidimensional) or if you are asking about the function passed into `apply_along_axis` To that the answer is yes: the function you pass must take a 1-D array (This is stated clearly <a href="http://docs scipy org/doc/numpy/reference/generated/numpy apply_along_axis html" rel="nofollow">in the function's documentation</a>) In your three examples the `type` of `x` is always a 1-D array The reason your first two examples work is because Python is implicitly broadcasting the `>` and `-` operators along that array Your third example fails because there is no such broadcasting along an array for `if` / `else` For this to work with `apply_along_axis` you need to pass a function that takes a 1-D array `numpy where` would work for this: ````>>> apply_along_axis(lambda x: numpy where(x > 2 x - 2 x) 0 y) array([1 2 1 2]) ```` P S In all these examples `apply_along_axis` is unnecessary thanks to broadcasting You could achieve the same results with these: ````>>> y > 2 >>> y - 2 >>> numpy where(y > 2 y - 2 y) ```` |
Menu input of letters return an error In my python game I am playing around with I have a menu where you can select to either play the game load a saved game save a game and quit The input of numbers works fine but when you accidentally or purposefully enter a letter or symbol it returns the error: ````Choice = eval(input()) File "string" line 1 in module NameError: name 'y' is not defined" ```` How would I go about fixing this issue? Function where the error occurs: ````def DisplayMenu(): print('1 Start new game') print('2 Load game') print('3 Save game') print('9 Quit') print('Please enter your choice: ') def GetMainMenuChoice(): Choice = eval(input()) return Choice if not (Choice in ['1' '2' '3' '4' '9']): print("\n Invalid choice Enter your option again \n") Choice = False else: Choice = True ```` | You need `raw_input` if you are using python2 and <strong>do not</strong> use eval just cast to int if you need an int etc Unless you have a variable `y` defined somewhere when you try to `eval` the string `y` you will get the error you see either way eval should rarely if ever be used The fact your list is full of strings makes trying to make `Choice` and `int` illogical ````choice = raw_input() # input python3 if choice not in {'1' '2' '3' '4' '9'} ```` Use lowercase for variable/function names You may also find a while loop to be a nicer approach: ````def get_main_menu_choice(): while True: choice = raw_input("Please choose an option") if choice not in {'1' '2' '3' '4' '9'}: print("Invalid choice Enter your option again ") else: return choice ```` <a href="http://stackoverflow com/questions/9383740/what-does-pythons-eval-do">what-does-pythons-eval-do</a> |
multiple arguments with PySide QtCore Slot decorator How do you define multiple arguments? What types are supported? And why does it sometimes fail when I combine it with another decorator? | I could not find real documentation on this so I went to the source -- <a href="http://qt gitorious org/pyside/pyside/blobs/ec45601aa14400b3d3e13f3f326e57d534da6ad2/libpyside/pysideslot cpp" rel="nofollow">pysideslot cpp</a> `Slot` takes two keyword args `name` (a string to name the slot) and `result` (a python type object or string naming a Qt type used to specify the return type of the function) If `name` is not supplied it will try to read it from the function you are decorating but be careful: other decorators will sometimes ruin the name of your function so if you are combining Slot with another decorator you may want to explicitly specify the `name` arg Any positional arguments you feed to Slot will get converted to strings by PySide::Signal::getTypeName and then joined into a comma-separated string This will become the signature of the slot and is used for routing calls For example given this decorator: ````@QtCore Slot(int str result=float) def func(a b): assert len(b)==a; upload(b); return 2 5 ```` The PySide internals will create a call signature string of 'int QString' and a resultType string of 'double' I hope this helps the next person struggling to debug their slots |
Which part of a tree can have vertical or horizontal variation in its specific gravity? | bole |
Restarting program in python I have been trying to make a Tamagotchi clone in python recently but I need help as I just cannot figure out how to make the code go back to the start after a certain point I tried the ````while == True: ```` kind of method and I understand it I just do not know how to get it working with my code Below is my code - It is quite long so please excuse the length I commented it pretty thoroughly and it should be easy to read Any help would be greatly appreciated :) ````# Modules import os # Used for cls function - clean screen import time # Used for delaying messages etc import sys # Pet details running = True petType = "" petName = "" activity = "" # Pet well being pet = [60 60 0] # 0 = energy 1 = happiness 2 = training # Loop counter i = 0 # # Animal Art for the activity loop and other parts # def cat(): # Stores cat ASCII art - credit to 'jgs' - https://user xmission com/~emailbox/ascii_cats htm print('''| | \ /_ | ) ( ') | ( / ) | \(__)| |''') def bird(): # Cat ASCII - credit to 'as' - http://chris com/ascii/index php?art=animals/birds print('''| | >\_/< | _\*v*/_ | \\ // | ===="==== | /^\ | |''') def bunny(): # Bunny ASCII - credit to 'Felix Lee' - http://www chris com/ascii/index php?art=animals/rabbits print('''| | /\ /| | \ V / | | "") | / ` | | / \) | (__\_\) |''') def dog(): # Dog ASCII - credit 'jgs' - http://www chris com/ascii/index php?art=animals/dogs print('''| | - _ | {_}^ )o | {\_______//~` | ( ) | /||~~~~~||\ | |_\ \_ \ \_\_ |''') def mouse(): # Mouse ASCII - credit 'jgs' - http://www chris com/ascii/index php?art=animals/rodents/mice print('''| | (\- | / _`> | _) / _)= | ( / _/ | `- __(___)_ |''') ################### # 'Sleep' are made to be easier to write than 'time sleep(1) def sleep(): time sleep(1) # Clears the console def cls(): os system('cls') # Shows the pet's statistics from user's previous inputs like name type energy etc def printStats(): sleep() print("|-----------------------------") print("| " petName "'s Stats: ") if petType == "Cat": cat() elif petType == "Bird": bird() elif petType == "Bunny": bunny() elif petType == "Dog": dog() elif petType == "Mouse": mouse() print("| Breed: " petType) print("| Energy: " str(pet[0])) print("| Happiness: " str(pet[1])) print("| Training: " str(pet[2])) print("|-----------------------------") def limiter(): if pet[0] >= 100: pet[0] = 100 elif pet[1] >= 100: pet[1] = 100 elif pet[2] >= 100: pet[2] = 100 # # # Introduction Message and start of the actual game # # print("""|------------------- | Welcome to Tamagotchi! |-------------------""") sleep() print("""Please choose a type of pet from the list below: (enter a b c d or e) a Bird b Bunny c Cat d Dog e Mouse """) # Getting pet's type and processing it while i == 0: sleep() petType = input("Which one would you like?: ") if petType == "a": petType = "Bird" sleep() print("You chose a " petType) sleep() print("Congratulations! Your new pet is ready ") bird() sleep() break # stops loop elif petType == "b": petType = "Bunny" sleep() print("You chose a " petType) sleep() print("Congratulations! Your new pet is ready ") bunny() sleep() break # stops loop elif petType == "c": petType = "Cat" sleep() print("You chose a " petType) sleep() print("Congratulations! Your new pet is ready ") cat() sleep() break # stops loop elif petType == "d": petType = "Dog" sleep() print("You chose a " petType) sleep() print("Congratulations! Your new pet is ready ") dog() sleep() break # stops loop elif petType == "e": petType = "Mouse" sleep() print("You chose a " petType) sleep() print("Congratulations! Your new pet is ready ") mouse() sleep() break # stops loop else: print("ERROR: That is not a valid pet type ") # Error message sleep() petType = input("Which one would you like?: ") continue # Continues the loop # Name loop while i == 0: petName = input("Please choose a name for your new pet: ") if petName isnumeric(): print("ERROR: That is not a valid name Please use only letters ") petName = input("Please choose a name for your new pet: ") continue # continues loop elif len(petName) >= 25: # Checks if the entry for name is too long print("ERROR: Please do not enter more than 25 characters ") petName = input("Please choose a name for your new pet: ") continue # continues loop elif petName == "": print("ERROR: Please enter a name") petName = input("Please choose a name for your new pet: ") continue # continues loop else: print(petName "! That is a nice name") break # stops loop cls() # Activity loop while i == 0: activity = input("Do you want to (f)eed (p)lay (s)leep or (t)rain?: ") if activity isdigit(): print("ERROR: That is not a valid activity ") activity = input("Do you want to (f)eed (p)lay (s)leep or (t)rain?: ") elif activity == "f": pet[0] = 5 print("") print("You fed " petName " 5 Energy ") limiter() printStats() time sleep(2) cls() elif activity == "p": pet[1] = 10 pet[0] -= 10 print("") print("You played with " petName " -10 Energy 10 Happiness ") limiter() printStats() time sleep(2) cls() elif activity == "s": pet[0] = 20 pet[1] -= 5 print("") print("You decided to let " petName " sleep 20 Energy -5 Happiness ") limiter() printStats() time sleep(2) cls() elif activity == "t": pet[2] = 10 pet[0] -= 10 pet[1] -= 5 print("") print("You decided to train " petName " -10 Energy -5 Happiness 10 Training ") limiter() printStats() time sleep(2) cls() elif pet[0] <= 0: print(petName " died because he reached 0 energy :(") break elif pet[1] <= 0: print(petName " ran away because he was unhappy :(") break elif pet[2] == 100: print("Congratulations! " petName " has reached 100 training!") else: print("ERROR: That is not a valid activity ") ```` I need to have the code restart after all three of these if statements (so after it reaches 0 energy happiness or if the pet reaches 100 training) ```` elif pet[0] <= 0: print(petName " died because he reached 0 energy :(") break elif pet[1] <= 0: print(petName " ran away because he was unhappy :(") break elif pet[2] == 100: print("Congratulations! " petName " has reached 100 training!") ```` Thank you very much in advance :) Marcell | ````while True: # # # Introduction Message and start of the actual game # # print("""|------------------- | Welcome to Tamagotchi! |-------------------""") #[ ] # Activity loop while True: #[ ] elif pet[0] <= 0: print(petName " died because he reached 0 energy :(") break elif pet[1] <= 0: print(petName " ran away because he was unhappy :(") break elif pet[2] == 100: print("Congratulations! " petName " has reached 100 training!") else: print("ERROR: That is not a valid activity ") ```` |
How can you reset variables to their original value in python? I am making a hangman game and I want to be able to reset the lives and score back to their original value (6&0) This code does not seem to work ````def newwords(): newgamewords append(input('Enter new word: ')) print('Do you want to add any more words? yes or no?') answer=input() if answer == 'yes': newwords() else: while len(guessedletters) > 0 : guessedletters pop() while len(displayletters) > 0 : displayletters pop() lives = 6 finalscore=0 score gamewords[:] = newgamewords hangmangame() ```` Here is the code at the beginning of the game (these variables are not in any definition i have made every variable in my code global just to be sure): ````lives=6 score=0 ```` | To change a global variable you have to declare them global or they will be considered a local variable Example: ````lives = 6 def change(): global lives lives = 0 ```` |
how to get current model name from url odoo I need to get current model name from this url: ````http://localhost:8069/web#view_type=form&model=system audit&menu_id=221&action=229 ```` Here the model name is system audit Please Help | In python 3 try this: ````from urllib import parse result = parse parse_qs("http://localhost:8069/web#view_type=form&model=system audit&menu_id=221&action=229")['model'][0] print(result) ```` For python 2 use `urlparse urlparse parse_qs()` |
Python: How to convert all values in a list to their ascii values? ````def encrypt_message(text x): text = list(text) for y in text: ord(text) ```` returns ord() expected a string of length 1 but list found | The problem is that you passed the `text` to `ord` function you need to pass the `y` But as strings are iterable objects you can just loop over your string : ````def encrypt_message(text x): return [ord(i) for i in text] ```` |
Python: For-loop will not finish Before I start let me just say that I am really new to programming so please do not kill me As an exercise I wrote a script that is supposed to take a list of hex numbers from a txt convert them to decimal and write them to another file This is what I came up with: ````hexdata = open(raw_input("Sourcefile:")) read() split(' ') dec_data = [] print hexdata x = -1 for i in hexdata: next_one = hexdata pop(x+1) decimal = int(next_one 16) print "Converting: " next_one "Converted:" decimal dec_data append(decimal) print dec_data target = open(raw_input("Targetfile: ") 'w') for n in dec_data: output = str(n) target write(output) target write(" ") ```` When I run the script it finishes whithout errors however it only converts and writes the first 30 numbers from my sourcefile and ignores all the other ones even though they are loaded into the 'hexdata' list I have tried several variations but it never works with all the numbers (48) What am I doing wrong? | Your first loop is trying to iterate over hexdata while at the same time pulling values out of the list using hexdata pop() Just change it to something like: ````for next_one in hexdata: decimal = int(next_one 16) print "Converting: " next_one "Converted:" decimal dec_data append(decimal) ```` |
Django py test does not find settings module I do have the following project structure ````base __init py settings __init__ py settings py tests pytest ini test_module py ```` My `pytest ini` looks like this: ````[pytest] #DJANGO_SETTINGS_MODULE =base settings settings ```` My `test_module py` looks like this: ````def test_django(): from base settings import settings as base_settings from django conf import settings as django_settings assert 3==5 ```` When I now run: ````py test ```` it will run the imports without issue and will raise an error at `assert 3==5` (as expected) This tells me that base is on `sys path` and that `base settings settings` can be imported Now I change `test_module py` to: ````def test_django(): from base settings import settings as base_settings from django conf import settings as django_settings print django_settings xxx assert 3==5 ```` When I now run: ````py test --ds=base settings settings ```` I get the error: <blockquote> ERROR: Could not import settings 'base settings settings' (Is it on sys path?): No module named base settings settings </blockquote> The same effect when I do not set the settings via command line but via the `pytest ini` file (by uncommenting the line) It looks like I miss something here??? | <a href="http://pytest-django readthedocs org/en/latest/configuring_django html#command-line-option-ds-settings" rel="nofollow">From the docs</a> it seems that `base` is already in your path - so maybe you want to be using ````py test --ds=settings settings ```` |
How can I remove POS tags before slashes in nltk? This is part of my project where I need to represent the output after phrase detection like this - (a x b) where a x b are phrases I constructed the code and got the output like this: ````(CLAUSE (NP Jack/NNP) (VP loved/VBD) (NP Peter/NNP)) (CLAUSE (NP Jack/NNP) (VP stayed/VBD) (NP in/IN London/NNP)) (CLAUSE (NP Tom/NNP) (VP is/VBZ) (NP in/IN Kolkata/NNP)) ```` I want to make it just like the previous representation which means I have to remove 'CLAUSE' 'NP' 'VP' 'VBD' 'NNP' etc tags How to do that? <h2>What I tried</h2> First wrote this in a text file tokenize and used `list remove('word')` But that is not at all helpful I am clarifying a bit more <h2>My Input</h2> `(CLAUSE (NP Jack/NNP) (VP loved/VBD) (NP Peter/NNP)) (CLAUSE (NP Jack/NNP) (VP stayed/VBD) (NP in/IN London/NNP))` <h2>Output will be</h2> [Jack loved Peter] [Jack stayed in London] The output is just according to the braces and without the tags | I am trying something like this: ````import re tmp = '(CLAUSE (NP Jack/NNP) (VP loved/VBD) (NP Peter/NNP))' tmp = re split(r'[()/ ]' tmp) #Use are split()' to split by character that was not a letter >>> ['' 'CLAUSE' '' 'NP' 'Jack' 'NNP' '' '' 'VP' 'loved' 'VBD' '' '' 'NP' 'Peter' 'NNP' '' ''] result = (tmp[4] tmp[9] tmp[14]) >>> ('Jack' 'loved' 'Peter') ```` Is this what you want? <strong>EDIT:</strong> I should thought it through:( ````import re tmp = '(CLAUSE (NP Jack/NNP) (VP loved/VBD) (NP Peter/NNP))' tmp = re sub(r'[()]' '' tmp) >>> 'CLAUSE NP Jack/NNP VP loved/VBD NP Peter/NNP' result = re findall(r'[a-zA-Z]*/' tmp) >>> ['Jack/' 'loved/' 'Peter/'] ï¼Now create a generator gen = (i[:-1] for i in result) tuple(gen) >>> ('Jack' 'loved' 'Peter') ```` |
Path Not Found in CherryPy I have been working on implementing a test API in CherryPy I have read a few forums tutorials and pieced together the code that the old Python developer at work had written and this is what I have got: ````import json import cherrypy class person: def default(self *args): are = { 'firstName': args[0] 'lastName': args[1] 'age': args[2] } return json dumps(r) default exposed = True class api: def __init__(self): self person = person() class Root: def __init__(self): self api = api() conf = { '/': { 'request dispatch': cherrypy dispatch MethodDispatcher()} } cherrypy config update(conf) cherrypy tree mount(Root()) cherrypy quickstart() ```` The result of running this code is the following error: <blockquote> 404 Not Found The path '/api/person/Blake/Williams/27' was not found Traceback (most recent call last): File "/Users/blakewilliams/Programming/Practice/Python/VirtualEnv/foo/lib/python2 7/site-packages/cherrypy/_cprequest py" line 656 in respond response body = self handler() File "/Users/blakewilliams/Programming/Practice/Python/VirtualEnv/foo/lib/python2 7/site-packages/cherrypy/lib/encoding py" line 188 in <strong>call</strong> self body = self oldhandler(*args **kwargs) File "/Users/blakewilliams/Programming/Practice/Python/VirtualEnv/foo/lib/python2 7/site-packages/cherrypy/_cperror py" line 386 in <strong>call</strong> raise self NotFound: (404 "The path '/api/person/Blake/Williams/27' was not found ") </blockquote> I am not sure what I am doing wrong Thanks in advance for any help | If you start your cherrypy server like this then it works: ````cherrypy quickstart(cherrypy Application(Root()) '/' {}) ```` ! <them>Caution</them>: The path you indicate is still not found: you forget the `api` level: ````http://127 0 0 1:8080/api/person/Blake/Williams/27 ```` |
(Py)Qt: problem with image downloading guys I want to display some images with their captions in `QTextEdit` I have a dictionary with captions and corresponding URLs The problem is when I post a request with `QNetworkAccessManager` and wait for a signal `finished(QNetworkReply*)` I get reply with image only How can I determine a corresponding caption this image was requested for? ````def _init_(self) manager = QNetworkAccessManager(self); self connect(manager SIGNAL("finished(QNetworkReply*)") self add_record) for record in dict: manager get(QNetworkRequest(QUrl(status['caption']))) def add_record(self reply): img = QImage() img loadFromData(reply readAll()) self textEdit textCursor() insertImage(img) #I do not know at this point for which caption #I have received this image #self textEdit append(record['text'] '\n'); ```` Are there any design patterns for this problem? I would appreciate any ideas | Assuming a recent Qt version the <a href="http://doc trolltech com/latest/qnetworkreply html#request" rel="nofollow">`QNetworkReply::request()`</a> will give you a pointer to the `QNetworkRequest` that triggered this reply So you can access the information you are after with <a href="http://doc trolltech com/latest/qnetworkrequest html#url" rel="nofollow">`QNetworkRequest::url()`</a> |
KeyError when iterating on lists I am sorry if this is a stupid question but I have been thinking about it a lot and looked through Jinja docs but so far to no avail Short background: I have just completed Udacity's CS101 and CS253 and am about to help a friend build a booking system for a yoga studio It is all on Google Appengine just like I want to have a list of available yoga classes similar to this: ````Monday Dynamic Yoga with Mary 6pm Soft yoga with Susie 8pm Wednesday Hatha yoga with Bob 5pm Hot yoga with Alice 7pm ```` So I want to fetch the list of classes then see if there is a yoga class on Monday If there is one I add 'Monday' to the list and all the Monday classes and so on with all the other days Like this: `day_output1 = ['Monday' ['Dynamic Yoga with Mary 6pm'] ['Soft yoga with Su ']]` ````day_output2 = ['Wednesday' ['Hatha yoga with Bob 5pm'] ['Hot yoga with Al ']] ```` And then add these to a list for the whole week which is then sent to the template: ````weekly_classes = [day_output1 day_output2] ```` Right now I am getting a KeyError which means it does not find the Key but I do not understand why? ```` File "/Users/username/YogaSchemat/yogaschema/main py" line 113 in get day = d[n] KeyError: 1 ```` With this code Thanks in advance guys! ````d = { "1": 'Monday' "2": 'Tuesday' "3": 'Wednesday' "4": 'Thursday' "5": 'Friday' "6": 'Saturday' "7": 'Sunday' } def get_classes(): yoga_classes = Schema all() #appengine DB request if yoga_classes: weekly_classes = [] #list that will be sent to template for n in range(1 8): for e in yoga_classes: if e weekday == n: day = d[n] #getting weekday from d class_details = [] # class_details append(e) day_output = [day class_details] weekly_classes append(day_output) self response out write(weekly_classes) ```` | You are using string keys in your `d` mapping but are looking up a <them>integer</them> instead In this case you should use a list instead: ````d = ['Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday' 'Saturday' 'Sunday'] # for n in range(7): day = d[n] ```` with `n` between 0 and 6 mapping directly to the names of the week at those positions in the `d` list Alternatively you could use integers as keys instead: ````d = { 1: 'Monday' 2: 'Tuesday' 3: 'Wednesday' 4: 'Thursday' 5: 'Friday' 6: 'Saturday' 7: 'Sunday' } ```` but since your keys are sequential you may as well save the space |
Python Service launched with Popen have logging stderr & stdout redirection problems I want log all from my service I am launching it with: launcher py: ````subprocess Popen(['myservice py']) ```` service py: ````import logging log = logging getLogger(__name__) log setLevel(logging DEBUG) handler = logging FileHandler('/var/log/myservice log') handler setLevel(logging DEBUG) formatter = logging Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler setFormatter(formatter) log addHandler(handler) ```` But the problem is that stdout and stderr are not writing in myservice log I was testing with: ````with open("/var/log/myservice_out log" "w+") as out open("/var/log/myservice_err log" "w+") as err: subprocess Popen(['myservice py'] stdout=out stderr=err) ```` But this is not using logging and I want to log all messages(stderror stdout) in only one file Thanks in advance | Everything is normal The logging module does NOT redirect stdout and stderr It CAN write to stdout/stderr depending on what handler you configured but it is not supposed to redirect stdout or stderr It seems you really want to use <a href="https://docs python org/2/library/os html#os dup2" rel="nofollow">os dup2()</a> in `service py` or specify the `stdout` and `stderr` arguments to <a href="https://docs python org/2/library/subprocess html#subprocess Popen" rel="nofollow">subprocess Popen</a> in `launcher py` |
Python Pandas XlsxWriter Center Across Selection <strong>Background Info</strong> I have a script which works fine for creating a merged header but I need to center across selection instead of merging I followed the official documentation but it is not working I have tried a large number of possible combinations some of which I have included below in pictures Any help would be greatly appreciated <strong>Code</strong> I wrote the code such that you can just paste it in and run it with the exception of the `xlsFilepath` For now I just hard-coded the text to center across the selection for simplicity but ideally I am going to change this to the `Title` variable ````import pandas as pd import numpy as np #Create a random dataframe for this example All_Columns_DF = pd DataFrame(np random randn(100 3) columns=['Title' 'Col_A' 'Col_B']) #Set file path for local machine xlsFilepath = r'H:\myfile xlsx' #Create writer writer = pd ExcelWriter(xlsFilepath engine='xlsxwriter') #Write the DF to excel All_Columns_DF to_excel(writer startrow = 1 sheet_name='Sheet1' index=False) #Extract the header from the DF which I want to Center Across Selection in Row 1 Title_DF = All_Columns_DF[["Title"]] Title_DF_Unique = Title_DF drop_duplicates() Title = Title_DF_Unique iloc[0]['Title'] #Define WB and WS workbook = writer book worksheet = writer sheets['Sheet1'] #Start Formatting Attempt format = workbook add_format() format set_center_across() ''' Hard coding using row col syntax does not work worksheet write(1 1 'Center across selection' format) worksheet write_blank(1 2 '' format) ''' '''Every combination of the below i try does not center across the columns I Have put write_blank above below started at col A B etc not thing i have tried works ''' worksheet write_blank("B1:F1" '' format) worksheet write("A1" 'Center across selection' format) writer save() ```` <strong>Attempts</strong> <a href="http://i stack imgur com/AsleJ png">Not Working</a> <a href="http://i stack imgur com/31eHu png">Works but not centered</a> Lastly I want to stick with this package so please do not recommend another package | It looks like there is a bug in the `center_across()` method that I did not know about I will fix it but in the meantime you can use the `set_align()` method to get the same effect: ````import pandas as pd df = pd DataFrame({'Data': [10 20 30 20 15 30 45]}) writer = pd ExcelWriter('pandas_centered xlsx' engine='xlsxwriter') df to_excel(writer startrow=1 sheet_name='Sheet1' index=False) workbook = writer book worksheet = writer sheets['Sheet1'] center_format = workbook add_format() center_format set_align('center_across') worksheet write('A1' 'Center across selection' center_format) worksheet write('B1' '' center_format) worksheet write('C1' '' center_format) writer save() ```` Output: <a href="http://i stack imgur com/7H9VR png" rel="nofollow"><img src="http://i stack imgur com/7H9VR png" alt="enter image description here"></a> Update: The `set_centered_across()` issue is now fixed in XlsxWriter version 0 8 5 |
What discipline is game theory derived from? | mathematical discipline. |
Why will not Perceptron Learning Algorithm converge? I have implemented the Perceptron Learning Algorithm in Python as below Even with 500 000 iterations it still will not converge I have a training data matrix X with target vector Y and a weight vector w to be optimized My update rule is: ````while(exist_mistakes): # dot product to check for mistakes output = [np sign(np dot(X[i] w)) == Y[i] for i in range(0 len(X))] # find index of mistake (choose randomly in order to avoid repeating same index ) n = random randint(0 len(X)-1) while(output[n]): # if output is true here choose again n = random randint(0 len(X)-1) # once we have found a mistake update w = w Y[n]*X[n] ```` Is this wrong? Or why is it not converging even after 500 000 iterations? | <a href="http://en wikipedia org/wiki/Perceptrons_%28book%29">Perceptrons</a> by Minsky and Papert (in)famously demonstrated in 1969 that the perceptron learning algorithm is not guaranteed to converge for datasets that are not linearly separable If you are sure that your dataset is linearly separable you might try adding a bias to each of your data vectors as described by the question: <a href="http://stackoverflow com/questions/1697243/perceptron-learning-algorithm-not-converging-to-0?rq=1">Perceptron learning algorithm not converging to 0</a> -- adding a bias can help model decision boundaries that do not pass through the origin Alternatively if you would like to use a variant of the perceptron learning algorithm that is guaranteed to converge to a margin of specified width even for datasets that are not linearly separable have a look at the <a href="http://ciml info/dl/v0_8/ciml-v0_8-ch03 pdf">Averaged Perceptron -- PDF</a> The averaged perceptron is an approximation to the voted perceptron which was introduced (as far as I know) in a nice paper by Freund and Schapire <a href="http://cseweb ucsd edu/~yfreund/papers/LargeMarginsUsingPerceptron pdf">"Large Margin Classification Using the Perceptron Algorithm" -- PDF</a> Using an averaged perceptron you make a copy of the parameter vector after each presentation of a training example during training The final classifier uses the mean of all parameter vectors |
Python update object from dictionary Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables? This is what I intend to do: ````c = MyClass() c foo = 123 c bar = 123 # c foo == 123 and c bar == 123 d = {'bar': 456} c update(d) # c foo == 123 and c bar == 456 ```` Something akin to dictionary `update()` which load values from another dictionary but for plain object/class instance? | Have you tried ````f __dict__ update( b ) ```` ? |
how to extend model User? please help to solve this problem I expanded in django1 6 User model as follows: ````class UserProfile(User): family = models CharField( max_length=30 blank=True ) skype = models CharField( max_length=50 blank=False ) email_address = models EmailField( max_length=50 blank=True ) objects = UserManager() ```` resulting in adminpanel appeared a form with the above fields after filling the data is stored in the database table "<a href="http://prozaik 16mb com/misc/up png" rel="nofollow">app_userprofile</a>" This table is linked to the table "<a href="http://prozaik 16mb com/misc/au png" rel="nofollow">auth_user</a>" using the foreign key the problem is that the table "auth_user" fields "username" and "password" empty but each user needed please tell me how to do so after the new user registration ( of the admin panel and from the site ) data "username" and "password" fell into the table "auth_user" | Use a one to one field User profile will create the Profile object the first time user profile it is accessed: ````from django contrib auth models import User from django db import models class Profile(models Model): user = models OneToOneField(User unique=True) User profile = property(lambda you: Profile objects get_or_create(user=you)[0]) ```` |
How to extract variable name and value from string in python I have a string ````data = "var1 = {'id': '12345' 'name': 'John White'}" ```` Is there any way in python to extract var1 as a python variable More specifically I am interested in the dictionary variables so that I can get value of vars: id and name python | This is the functionality provided by <a href="https://docs python org/3/library/functions html#exec" rel="nofollow">`exec`</a> ````>>> my_scope = {} >>> data = "var1 = {'id': '12345' 'name': 'John White'}" >>> exec(data my_scope) >>> my_scope['var1'] {'id': '12345' 'name': 'John White'} ```` |
BeautifulSoup not seeing nobr tag I am scraping a page with beautifulsoup of the following format ````<tr class="bgWhite"> <td align="center" width="50"><nobr>A</nobr></td> <td align="center"> 0</td> <td align="left" width="*"> 1</td> <td align="center"> 2</td> <td align="center"> 3</td> <td align="center"> 4</td> <td align="center"><nobr> 23-Apr-13 </nobr></td> </tr> ```` When I call `col[5] string` or for that manner any index between 1-5 it works fine However nobr tags seem to cause a problem and return None value when I try do `col[6] string` I search throught the table with ````for r_index row in enumerate(table findAll('tr')): col = row findAll('td') ```` Idea how to get that data? | You have two options depending on the version of BeautifulSoup: BeautifulSoup 4 use the ` stripped_strings` attribute to find all text elements that are not empty: ````print ' ' join(col[6] stripped_strings) ```` In BeautifulSoup 3 you need to search for all contained text instead: ````print ' ' join(el strip() for col[6] findAll(text=True) if el strip()) ```` |
How much was the second contract worth over a three season period? | null |
Calling defintions from inside a class I am currently having an issue with calling on definitions from inside a class how do I fix the issue of `slideShow()` in line 32 not opening the slideshow sequence? ````import tkinter as tk from itertools import cycle root = "" #create a splash screen 80% of display screen size centered #quickly diplaying a cycle of images disapearing after 10 seconds #lists the images that will be cycled images = ["pic1 gif" "pic2 gif" "pic3 gif" "pic gif" "pic5 gif" "pic6 gif"] photos = cycle(tk PhotoImage(file=image) for image in images) class splashscreen(): def slideShow(): img = next(photos) displayCanvas config(image=img) #after 0 05 seconds begin the slideshow root after(1 slideShow) #creates the canvas for the image to go on global root root = tk Tk() root overrideredirect(True) width = root winfo_screenwidth() height = root winfo_screenwidth() #sets the size of the splash screen and its distance from the sides of the screen root geometry('%dx%d+%d+%d' % (1536 864 width/10 height/20)) displayCanvas = tk Label(root) displayCanvas pack() #after 10 milliseconds the slideshow will begin and after 10 seconds be destroyed #this is the thing that is not working root after(10 lambda: slideShow()) root after(10000 root destroy) ```` Why does not `slideshow()` open the `def slideShow()`? It says that name slideshow is undefined how do I fix this issue so my code works? | You have to use `self ` inside class ````def slideShow(self): ```` and ````root after(1 self slideShow) ```` But probably you have problem with second `after` too You have to create instance of class `splashscreen` ````my_slides = splashscreen() ```` and then you can use `splashscreen slideShow` ````root after(10 splashscreen slideShow) ```` You have mess in code so I am not sure which part is inside class and which not <hr> BY THE WAY: to make code more readable use `CamelCase` names for classes - `SplashScreen` - `lower_case` namese for variables and functions - `display_canvas` `show_slide` |
if loop syntax error Is the following syntax right in Python? ````(if 'SU' in line or 'AU' in line or 'VU' in line or 'rf' in line and line find('/*') == -1) and (BUILDROOT in line): lineMatch = False ```` | No the `if` should not be inside the brackets |
Case insensitive matching python I want to match items from one list in another without worrying about case sensitivity ````mylist1 = ['fbH_q1ba8' 'fHh_Q1ba9' 'fbh_q1bA10' 'hoot'] mylist2 = ['FBH_q1ba8' 'trick' 'FBH_q1ba9' 'FBH_q1ba10' 'maj' 'joe' 'civic'] ```` I was doing this before: ````for item in mylist2: if item in mylist1: print "true" else: print "false" ```` But this fails because it is not case sensitive I am aware of re match("TeSt" "Test" re IGNORECASE) but how can I apply that to my example? | Normalize the case with <a href="https://docs python org/2/library/stdtypes html#str lower" rel="nofollow">`str lower()`</a>: ````for item in mylist2: print item lower() in mylist1 ```` The `in` containment operator already returns `True` or `False` easiest just to print that: ````>>> mylist1 = ['fbh_q1ba8' 'fhh_q1ba9' 'fbh_q1ba10' 'hoot'] >>> mylist2 = ['FBH_q1ba8' 'trick' 'FBH_q1ba9' 'FBH_q1ba10' 'maj' 'joe' 'civic'] >>> for item in mylist2: print item lower() in mylist1 True False False True False False False ```` If `mylist1` contains mixed case values you will need to make the loop explicit; use a <them>generator expression</them> to produce lowercased values; testing against this ensures only as many elements are lowercased as needed to find a match: ````for item in mylist2: print item lower() in (element lower() for element in mylist1) ```` Demo ````>>> mylist1 = ['fbH_q1ba8' 'fHh_Q1ba9' 'fbh_q1bA10' 'hoot'] >>> for item in mylist2: print item lower() in (element lower() for element in mylist1) True False False True False False False ```` Another approach is to use <a href="https://docs python org/2/library/functions html#any" rel="nofollow">`any()`</a>: ````for item in mylist2: print any(item lower() == element lower() for element in mylist1) ```` `any()` also short-circuits; as soon as a `True` value has been found (a matching element is found) the generator expression iteration is stopped early This does have to lowercase `item` each iteration so is slightly less efficient Another demo: ````>>> for item in mylist2: print any(item lower() == element lower() for element in mylist1) True False False True False False False ```` |
Django - How do I download data once a day using Pandas for my site? I am a beginner to Django and am currently building a site that displays stock prices To do that I need to download (or update) the stock prices once a day I know that I can retrieve stock prices using Pandas However I would like my site to do it once everyday at a specific time instead of retrieving data every time a visitor visits the view I am a bit stuck here and did a lot of Google searches Can someone please point me to a link that I can read up on? EDIT: I am currently making this site on my own computer so I have not uploaded my files yet | If you are using a Linux box (like Debian[0]) and have cron[1] up and running: - Create a She Will Script to call a program you will write to get the data using Pandas - Use `crontab -l` to edit your crontab file and add you script to execute at any time you need - [0] <a href="https://www debian org/" rel="nofollow">https://www debian org/</a> - [1] <a href="http://linux die net/man/1/crontab" rel="nofollow">http://linux die net/man/1/crontab</a> |
xlrd data extraction python I am working on data extraction using xlrd and I have extracted 8 columns of inputs for my project Each column of data has around 100 rows My code is as follows: ````wb = xlrd open_workbook('/Users/Documents/Sample_data/AI_sample xlsx') sh = wb sheet_by_name('Sample') x1 = sh col_values( 0)[1:] x2 = sh col_values( 1)[1:] x3 = sh col_values( 2)[1:] x4 = sh col_values( 3)[1:] x5 = sh col_values( 4)[1:] x6 = sh col_values( 5)[1:] x7 = sh col_values( 6)[1:] x8 = sh col_values( 7)[1:] ```` Now I want to create an array of inputs which gives each row of the 8 columns For eg: if this is my 8 columns of data ````x1 x2 x3 x4 x5 x6 x7 x8 1 2 3 4 5 6 7 8 7 8 6 5 2 4 8 8 9 5 6 4 5 1 7 5 7 5 6 3 1 4 5 6 ```` i want something like: x1 x2 x3 x4 x5 x6 ([1 2 3 4 5 6 7 8]) for all the 100+ rows I could have done a row wise extraction but doing that for 100+ rows is practically very difficult So how do i do that i also understand that it could be done using np array but i do not know how | You can also try <strong>openpyxl</strong> something similar to <strong>xlrd</strong> ````from openpyxl import load_workbook Workbook book = load_workbook(filename=file_name) sheet = book['sheet name'] for row in sheet rows: col_0 = row[0] value col_1 = row[1] value ```` I used to prefer openpyxl instead of xlrd |
rstrip not removing newline char what am I doing wrong? Pulling my hair out here have been playing around with this for the last hour but I cannot get it to do what I want ie remove the newline sequence ````def add_quotes( fpath ): ifile = open( fpath 'r' ) ofile = open( 'ofile txt' 'w' ) for line in ifile: if line == '\n': ofile write( "\n\n" ) elif len( line ) > 1: line rstrip('\n') convertedline = "\"" line "\" " ofile write( convertedline ) ifile close() ofile close() ```` | The clue is in the signature of `rstrip` It returns a copy of the string but with the desired characters stripped thus you will need to assign `line` the new value: ````line = line rstrip('\n') ```` This allows for the sometimes very handy chaining of operations: ````"a string" strip() upper() ```` As <a href="http://stackoverflow com/users/181765/max-s">Max S</a> says in the comments Python strings are immutable which means that any "mutating" operation will yield a mutated copy This is how it works in many frameworks and languages If you really need to have a mutable string type (usually for performance reasons) there are string buffer classes |
In what city can KU's Edwards campus be found? | Overland Park |
pybox2d dynamic fixtures not colliding with static fixtures I am trying to get a 2D soccer simulation working in pyBox2D but cannot get the ball to collide with the posts or multiple versions of the ball (but it does bounce off the walls?) Here the initialisation for the ball: ````def init_body(self center_point=Point(0 0) radius=10): self body = Body world CreateDynamicBody( position=center_point as_tuple() friction=0 5 linearDamping=0 5 userData=self ) self fixture = self body CreateCircleFixture( pos=(0 0) # position relative to body position radius=radius restitution=0 8 density=1 0 ) ```` the post: ````def init_body(self center_point=Point(0 0) radius=10): self body = Body world CreateStaticBody( position=center_point as_tuple() userData=self ) self fixture = self body CreateCircleFixture( pos=(0 0) radius=radius * 10 ) ```` and the wall (that is working): ```` self body = Body world CreateStaticBody(position=(width height)) self body CreateEdgeChain([ (-width -height) (width -height) (width height) (-width height) (-width -height) ]) ```` I created 200 balls which bounce off the walls but not each other or the Posts? Is there something obvious i am doing wrong here? | cannot figure out anything wrong with what you posted Any more code please? |
Python blogging wordpress_xmlrpc doesnât âpublishâ I am trying the lines in Python wordpress_xmlrpc documentation <a href="http://python-wordpress-xmlrpc readthedocs org/en/latest/overview html" rel="nofollow">http://python-wordpress-xmlrpc readthedocs org/en/latest/overview html</a> Here is what I have: ````wp = Client('https://remembertochange wordpress com/xmlrpc php' 'user' 'pass') posts = wp call(GetPosts()) post = WordPressPost() post title = 'My new title' post content = 'This is the body of my new post ' post terms_names = { 'post_tag': ['test' 'firstpost'] 'category': ['Introductions' 'Tests'] } wp call(NewPost(post)) post post_status = 'publish' ```` The problem is it only adds a draft to the blog and doesnât publish it as a new post to the blog Whatâs wrong with it and how can I correct it? Thanks | According to <a href="http://python-wordpress-xmlrpc readthedocs org/en/latest/examples/posts html" rel="nofollow">official documentation</a> posts will be sent as drafts by default Here you modify the post_status property of WordPressPost object <them>after</them> you sent that post to the server Thus it is only changed in local memory and server does not see the change Simply putting ````post post_status = 'publish' ```` before you make the call wp call(NewPost(post)) will make it work as the way you want |
Trying to check multiple qt radio buttons with python I need to check multiple radio buttons from a qt ui with python Up to now we are using something similar to: ````if main ui radioButton_1 isChecked(): responses["q1"] = "1" elif main ui radioButton_2 isChecked(): responses["q1"] = "2" elif main ui radioButton_3 isChecked(): responses["q1"] = "3" if main ui radioButton_4 isChecked(): responses["q2"] = "1" elif main ui radioButton_5 isChecked(): responses["q2"] = "2" elif main ui radioButton_6 isChecked(): responses["q2"] = "3" ```` Since there are very many buttons and many different categories (q1 q2 ) I was thinking of optimizing it a bit So this is what I hoped would work (adopted from <a href="http://stackoverflow com/questions/17402452/how-to-get-the-checked-radiobutton-from-a-groupbox-in-pyqt">How to get the checked radiobutton from a groupbox in pyqt</a>): ````for i button in enumerate(["main ui radioButton_" str(1) for i in range(1 8)]): if button isChecked(): responses["q1"] = str(i - 1) ```` I get why this does not work but writing it I hoped it would So I tried to iterate through the buttons using something similar to (<a href="http://stackoverflow com/questions/2597827/is-there-a-way-to-loop-through-and-execute-all-of-the-functions-in-a-python-clas">Is there a way to loop through and execute all of the functions in a Python class?</a>): ````for idx name val in enumerate(main ui __dict__ iteritems()): ```` and then use some modulo 3 and such to assign the results But that does not work either Not sure if it is because i used __ dict __ or something else The error I got was: ````TypeError: 'QLabel' object is not iterable ```` Now some people could say that implicit is better that explicit and also because of readability the if elif chain is good the way it is but there are 400+ lines of that Also after reading this post <a href="http://stackoverflow com/questions/17166074/most-efficient-way-of-making-an-if-elif-elif-else-statement-when-the-else-is-don">Most efficient way of making an if-elif-elif-else statement when the else is done the most?</a> I thought there must be a better and more efficient way of doing this (see examples 3 py and 4 py of the of the accepted answer) Because I need to check the Boolean value of main ui radioButton_1 isChecked() and then assign thevalue according to the Buttons group (q1 q2 ) I have not managed to implement the solution using dictionaries as described in the post Am I stuck with the if elif chain or is there a way to not only reduce the LOC but also make the code more efficient (faster)? | It looks like you have used Qt Designer to create your ui so I would suggest putting each set of radio buttons in a <a href="http://doc qt io/qt-4 8/qbuttongroup html" rel="nofollow">QButtonGroup</a> This will give you a simple ready-made API for getting the checked button in a group without having to query each button individually In Qt Designer buttons can be added to a button-group by selecting them and then choosing <strong>Assign to button group > New button group</strong> from the context menu The button IDs (which you will need to use later) are assigned in the order the buttons are selected So use Ctrl+Click to select each button of a group in the correct order The IDs start at `1` for each group and just increase by one for each button that is added to that group When a new button-group is added it will appear in the Object Inspector This will allow you to select it and give it a more meaningful name Once you have created all the groups you can get the checked button of a group like this: ```` responses["q1"] = str(main ui groupQ1 checkedId()) responses["q2"] = str(main ui groupQ2 checkedId()) # etc ```` This could be simplified even further to process all the groups in a loop: ```` for index in range(1 10): key = 'q%d' % index group = 'groupQ%d' % index responses[key] = str(getattr(main ui group) checkedId()) ```` |
Connection django-select2 with django-filters I want to connect with select2 django with django-filters I want to have a nice selector to select users I do not know where to put the following code in the code django-filters ````from django_select2 import * class UserChoices(AutoModelSelect2Field): queryset = User objects search_fields = ['word__icontains' ] ```` | Here is how I did it sticking to the <a href="http://django-filter readthedocs org/en/latest/usage html" rel="nofollow">django-filter example</a> and using <a href="http://django-select2 readthedocs org/" rel="nofollow">django-select2</a>: ````import django_filters from django_select2 widgets import Select2Widget from models import Product class ProductFilter(django_filters FilterSet): name = django_filters ModelChoiceFilter( queryset=Product objects all() widget=Select2Widget ) class Meta: model = Product fields = ['name' 'price' ] ```` Make sure you have jquery in your (base) template Then this is what you will get: <img src="http://i stack imgur com/vhuRu png" alt="enter image description here"> |
How to correctly use pandas agg function when running groupby on a column of type timestamp/datetime/datetime64? I am trying to understand why calling count() directly on a group returns the correct answer (in this example 2 rows in that group) but calling count via a lambda in the agg() function returns the beginning of epoch ("1970-01-01 00:00:00 000000002") ````# Using groupby(lambda x: True) in the code below just as an illustrative example # It will always create a single group x = DataFrame({'time': [np datetime64('2005-02-25') np datetime64('2006-03-30')]}) groupby(lambda x: True) display(x count()) >>time >>True 2 display(x agg(lambda x: x count())) >>time >>True 1970-01-01 00:00:00 000000002 ```` Could this be a bug in pandas? I am using Pandas version: 0 16 1 IPython version: 3 1 0 numpy version: 1 9 2 I get the same result regardless of whether I use the standard python datetime vs np datetime64 vs the pandas Timestamp EDIT (as per the accepted answer from @jeff it looks like I may need to coerce to dtype object before applying an aggregation function that does not return a datetime type): ````dt = [datetime datetime(2012 5 1)] * 2 x = DataFrame({'time': dt}) x['time2'] = x['time'] astype(object) display(x) y = x groupby(lambda x: True) y agg(lambda x: x count()) >>time time2 >>True 1970-01-01 00:00:00 000000002 2 ```` | Here x is the original frame from above (not with your groupby) Passing a UDF e g the lambda calls this on each Series So this is the result of the function ````In [35]: x count() Out[35]: time 2 dtype: int64 ```` Then coercion to the original dtype of the Series happens So the result is: ````In [36]: Timestamp(2) Out[36]: Timestamp('1970-01-01 00:00:00 000000002') ```` which is exactly what you are seeing The point of the coercion to the original dtype is to preserve it if at all possible Not doing this would be even more magic on the groupby results |
Python Float String Formatting Not Working Right I am pretty sure that I am doing this correctly but not getting the results that I expect from Python 2 7 3 string formatting mini-language I am trying to format the output of a float to 3 integer values and a varying number of decimal values Everything works except the integer values By itself the following code works to get me 3 integer values ````num = 3 value = '{:03}' format(num) returns '003' ```` And floats work ````num = 3 12345 value = '{:01 2f}' format(num) returns '3 12' ```` However combining the two does not seem to work properly The decimal precision works but the integer precision does not ````num = '3 12345' value = '{:03 2f}' format(num) returns '3 12' instead of the expected '003 12' ```` The same is true if I try any of the following formats ````value = '{:03 02f}' format(num) - or - value = '{0:3 2f}' format(num) - or - value = '{:3 02f}' format(num) - or - value = '{0:3 02f}' format(num) - or - value = '{0:03 2f}' format(num) - or - value = '{0:03 02f}' format(num) - or - value = '{:0>3 2f}' format(num) etc Which all return the same '3 12' instead of '003 12' ```` If you are curious about what I am doing for the varying / dynamic decimal precision the point is to keep all the values the same length but different sets of values may not have the same precision So I take the smaller of the longest precision value or 10 and force the others to match like this ````from decimal import Decimal dVals = [ abs(Decimal(val1) as_tuple() exponent) # Get the number of decimal points abs(Decimal(val2) as_tuple() exponent) # "" "" abs(Decimal(val3) as_tuple() exponent) # "" "" abs(Decimal(val4) as_tuple() exponent) # "" "" ] p = max(dVals) # Get the largest value p = min(p 10) # Get the smaller of the largest value or 10 vals = [val1 val2 val3 val4] for val in vals: value = '{:0>3 {prec}f}' format(val prec = p) # do whatever with value here ```` Again this all works perfectly except that the integer value never returns with 3 precision places when I combine it with float precision So all my efforts to ensure the values output with the same formatted length are all for naught Ultimately the output should look similar to ````'009 123456700' '180 101010101' '054 987654321' ```` Instead it looks like this ````'9 123456700' '180 101010101' '54 987654321' ```` In other words ugly :-| At the very least I would accept the following output ````' 9 123456700' '180 101010101' ' 54 987654321' ```` Any ideas what I am doing wrong here? Your help is much appreciated! Regards -RMWChaos | The first digit is the total width of the result not the width before the decimal point ````>>> '{:06 2f}' format(3 12345) '003 12' ```` |
Returning when any Future in a list finishes I have a coroutine that should perform a few tasks concurrently: ````@gen coroutine def scrape_trackers(self): yield [self scrape_tracker(tracker) for tracker in self torrent trackers] ```` Some trackers will never respond (or maybe respond in an hour) so my code never gets past this method as Tornado is waiting for <them>all</them> of them to complete How do I wait for only <them>one</them> to complete and keep trying the other ones in the background? Something like: ````yield WhenAnyComplete(map(self scrape_tracker self torrent trackers)) ```` I was thinking of calling each of those methods with `IOLoop add_callback()` and doing something when they finish but I am not entirely sure where to go from there: ````for tracker in self torrent trackers: future = self scrape_tracker(tracker) IOLoop add_future(future self tracker_scraped) ```` Any help is appreciated | The best I can come up with is returning a new `Future` and having the first successful function call give it a result: ````def scrape_trackers(self): result = Future() for tracker in self torrent trackers: future = self scrape_tracker(tracker) future add_done_callback(lambda f: self tracker_done(f result)) return result def tracker_done(self future result_future): if future exception(): logging warning('Tracker could not be scraped: %s' future exception()) return logging info('Scraped tracker %s' future) if self unconnected_peers: result_future set_result(True) ```` |
Verifying a Digitally Signed PDF in Python I am currently working on some PDF processing code in Python For this project the software needs to be able to verify that a PDF has a valid digital signature In my searching so far I have found a few Java API's that do the trick (iText for example) but nothing in Python If anyone has a link for either of the following it would be most appreciated: - An API I can use to verify a digital signature - Instructions/general guidance for how I could write my own code to verify a digital signature Miscellaneous Details: - The Digital Certificate for the PDF is issued by GlobalSign CA for Adobe (if that matters) - This code will eventually run on Google App Engine | I am also annoyed by a lack of such library As far as I know there is no open library for Python to do that There is a <a href="http://www kryptokoder com/index html" rel="nofollow">MyPDFSigner</a> library but it seems closed source and as I understand is a binary library Not sure how that fits with app engine A lot of people recommend using another language such as <a href="http://sourceforge net/projects/itext/" rel="nofollow">iText</a> which is a Java library for doing the same thing Verifying a signature basically means nearly re-doing the signing process since you need to re-calculate the hashes Also there are different "levels" of signature - such as certification which includes not only a signature but also specifies allowed changes to keep the document signature valid Consequently you need to be able to know which level of verification you need If one would go about implementing such feature <a href="http://www adobe com/devnet/pdf/pdf_reference html" rel="nofollow">Adobe's PDF reference</a> is a key resource while <a href="http://www adobe com/devnet-docs/acrobatetk/tools/DigSig/Acrobat_DigitalSignatures_in_PDF pdf" rel="nofollow">Digital signatures in a PDF</a> is an overview to get you started |
Killing a script launched in a Process via os system() I have a python script which launches several processes Each process basically just calls a she will script: ````from multiprocessing import Process import os import logging def thread_method(n = 4): global logger command = "~/Scripts/run sh " str(n) " >> /var/log/mylog log" if (debug): logger debug(command) os system(command) ```` I launch several of these threads which are meant to run in the background I want to have a timeout on these threads such that if it exceeds the timeout they are killed: ````t = [] for x in range(10): try: t append(Process(target=thread_method args=(x ) ) ) t[-1] start() except Exception as e: logger error("Error: unable to start thread") logger error("Error message: " str(e)) logger info("Waiting up to 60 seconds to allow threads to finish") t[0] join(60) for n in range(len(t)): if t[n] is_alive(): logger info(str(n) " is still alive after 60 seconds forcibly terminating") t[n] terminate() ```` The problem is that calling terminate() on the process threads is not killing the launched run sh script - it continues running in the background until I either force kill it from the command line or it finishes internally Is there a way to have terminate also kill the subshell created by os system()? | Use <a href="http://docs python org/library/subprocess html#replacing-os-system" rel="nofollow">`subprocess`</a> instead whose objects have a <a href="http://docs python org/library/subprocess html#subprocess Popen terminate" rel="nofollow">`terminate()` method</a> explicitly for this |
circle detection in open cv using python I was trying to detect circles from a black background with red circular kind objects ````import cv2 import cv2 cv as cv import numpy as np img = cv2 imread('extracted jpg' 0) img = cv2 medianBlur(img 5) cimg = cv2 cvtColor(img cv2 COLOR_BGR2GRAY) circles = cv2 HoughCircles(img cv CV_HOUGH_GRADIENT 1 20 param1=50 param2=30 minRadius=0 maxRadius=0) circles = np uint8(np around(circles)) for i in circles[0 :]: # draw the outer circle cv2 circle(cimg (i[0] i[1]) i[2] (0 255 0) 2) # draw the center of the circle cv2 circle(cimg (i[0] i[1]) 2 (0 0 255) 3) cv2 imshow('detected circles' cimg) cv2 waitKey(0) cv2 destroyAllWindows() ```` I have loaded the image in grayscale mode still it gives me an error ````"circles = np uint8(np around(circles)) File "/usr/lib/python2 7/dist-packages/numpy/core/fromnumeric py" line 2277 in around return _wrapit(a 'round' decimals out) File "/usr/lib/python2 7/dist-packages/numpy/core/fromnumeric py" line 37 in _wrapit result = getattr(asarray(obj) method)(*args **kwds) AttributeError: rint" ```` I cannot post the image because of my present reputation | There is a small correction to be made in your code You are loading image in grayscale and then again converting it to grayscale using `cv2 cvtColor` which is invalid operation Alternatively OpenCV provides a <a href="https://github com/Itseez/opencv/blob/master/samples/python2/houghcircles py">sample for circle detection using Hough Circles method</a> You can try that If you are using OpenCV 2 x version just change the `cv2 LINE_AA` to `cv2 CV_AA` or any other lineType you prefer |
Who did Nasser recruit to be Prime Minister? | Ali Maher |
Where did the Taliban regroup in 2002? | western Pakistan |
Where did a Han revolt occur? | Liaodong |
Dropbox in stealth mode I have not tried anything since I do not know from where to start How can I implement code so that I do not get anything which shows that dropbox is syncing or updating In other words I want to create an application which works stealthly and automatically updates dropbox without the user even noticing anything? | I do not think you can change this yourself(unless there is an api avail for it) but the settings for notifications is in the dropbox preferences I believe the user would have to go there and turn it off globally since any change within dropbox will be reported to the end user based on the global preference settings I am not sure if you can disable the dropbox icon from changing while updating but you maybe able to do something to growl(how it displays) changes Not sure but worth a look in your case |
any() function in Python with a callback The Python standard library defines an <a href="http://docs python org/library/functions html#any">`any()`</a> function that <blockquote> Return True if any element of the iterable is true If the iterable is empty return False </blockquote> It checks only if the elements evaluate to `True` What I want it to be able so specify a callback to tell if an element fits the bill like: ````any([1 2 'joe'] lambda e: isinstance(e int) and e > 0) ```` | How about: ````>>> any(isinstance(e int) and e > 0 for e in [1 2 'joe']) True ```` It also works with `all()` of course: ````>>> all(isinstance(e int) and e > 0 for e in [1 2 'joe']) False ```` |
Reshaping Error in python I am new to python and I am trying to execute the following code but I get the following error: ````i am[: : 0] = f ValueError: could not broadcast input array from shape (700 900 3) into shape (700 900) ```` Can someone assist me with it? ````img = numpy zeros((700 900)) row_idx = 160 curve = [] count = 0 for i in range(0 900): contour append((row_idx i)) values num_values = get_values(curve); a = imread('20091016_seg1_26_18245948_1chop png') f = numpy rot90(a 2) f = numpy rot90(a 2) size_vec = numpy shape(img) i am = numpy zeros((size_vec[0] size_vec[1] 3)); i am[: : 0] = f i am[: : 1] = f i am[: : 2] = f for i in range(0 num_values): i am[values[i] y values[i] x 0] = 0 0 i am[values[i] y values[i] x 1] = 1 0 i am[values[i] y values[i] x 2] = 0 0 imsave('OUTPUT png' i am) ```` (eliminated semicolons) | It should work with: ````i am[ 0] = f[ 0] ```` The problem is that you were trying to put the whole `f` into `i am[ 0]` giving the `ValeError` due to the dimension incompatibilty |
Merging arrays of versioned dictionaries Given the following two arrays of dictionaries how can I <them>merge</them> them such that the resulting array of dictionaries contains only those dictionaries whose <them>version</them> is greatest? ````data1 = [{'id': 1 'name': you'Oneeee' 'version': 2} {'id': 2 'name': you'Two' 'version': 1} {'id': 3 'name': you'Three' 'version': 2} {'id': 4 'name': you'Four' 'version': 1} {'id': 5 'name': you'Five' 'version': 1}] data2 = [{'id': 1 'name': you'One' 'version': 1} {'id': 2 'name': you'Two' 'version': 1} {'id': 3 'name': you'Threeee' 'version': 3} {'id': 6 'name': you'Six' 'version': 2}] ```` The <them>merged</them> result should look like this: ````data3 = [{'id': 1 'name': you'Oneeee' 'version': 2} {'id': 2 'name': you'Two' 'version': 1} {'id': 3 'name': you'Threeee' 'version': 3} {'id': 4 'name': you'Four' 'version': 1} {'id': 5 'name': you'Five' 'version': 1} {'id': 6 'name': you'Six' 'version': 2}] ```` | If you want to get the highest version according to the dictionaries `id`s then you can use <a href="http://docs python org/2/library/itertools html?highlight=itertools#itertools groupby" rel="nofollow">`itertools groupby`</a> method like this: ````sdata = sorted(data1 data2 key=lambda x:x['id']) res = [] for _ v in itertools groupby(sdata key=lambda x:x['id']): v = list(v) if len(v) > 1: # happened that the same id was in both datas # append the one with higher version res append(v[0] if v[0]['version'] > v[1]['version'] else v[1]) else: # the id was in one of the two data res append(v[0]) ```` The solution is not a one liner but I think is simple enough (once you understand `groupby()` which is not trivial) This will result in `res` containing this list: ````[{'id': 1 'name': you'Oneeee' 'version': 2} {'id': 2 'name': you'Two' 'version': 1} {'id': 3 'name': you'Threeee' 'version': 3} {'id': 4 'name': you'Four' 'version': 1} {'id': 5 'name': you'Five' 'version': 1} {'id': 6 'name': you'Six' 'version': 2}] ```` I think is possible to <them>shrink</them> the solution even more but it could be quite hard to understand Hope this helps! |
How to record audio in gstreamer for pre-defined time? I have python gstreamer - 1 0 code that records audio using "autoaudiosrc" element My question is to stop the pipeline after few 'predefined' seconds and preferably I want to add it in gstelement format The current pipeline used to record : ````gst-launch-1 0 autoaudiosrc num-buffers=100 ! audioconvert ! vorbisenc ! oggmux ! filesink location="sit ogg" ```` corresponding python code ````import sys os import gi gi require_version('Gst' '1 0') from gi repository import GObject Gst Gtk GObject threads_init() Gst init(None) pipeline = Gst Pipeline() current_state = "STATE_NULL" autoaudiosrc = Gst ElementFactory make("autoaudiosrc" "autoaudiosrc") audioconvert = Gst ElementFactory make("audioconvert" "audioconvert") vorbisenc = Gst ElementFactory make("vorbisenc" "vorbisenc") oggmux = Gst ElementFactory make("oggmux" "oggmux") filesink = Gst ElementFactory make("filesink" "filesink") url = "1 ogg" filesink set_property("location" url) pipeline add( autoaudiosrc) pipeline add( audioconvert) pipeline add( vorbisenc) pipeline add( oggmux) pipeline add( filesink) autoaudiosrc link( audioconvert) audioconvert link( vorbisenc) vorbisenc link( oggmux) oggmux link( filesink) pipeline set_state(Gst State PLAYING) Gtk main() ```` ~ | Yes You can start a timer (g_timeout_add or using the gstreamer clock via gst_clock_new_single_shot_id) When the timer/clock callback fires send an eos event to the pipeline (gst_element_send_event(pipeline gst_event_new_eos()) |
What year was the National Archives Establishment established in? | 1934 |
Scrapy authenticating with aspx page I am trying to find the best way of login in to a site using aspx pages and then redirecting to a new page within that site to start scraping I am confident the scraping part is working as I have tried it out on a mocked up page but I have not done authentication before and I am finding that the site is redirecting to a search url The only thing I can think is happening is scrapy is triggering the search box? The site is howdidido co uk and my spider code is as follows: ````from scrapy spider import BaseSpider from scrapy selector import Selector from pgcmh items import PgcmhItem from scrapy http import Request from scrapy http import FormRequest from scrapy selector import HtmlXPathSelector from scrapy contrib spiders init import InitSpider class LoginSpider(BaseSpider): name = 'pgcmh' allowed_domains = ["howdidido co uk"] login_page = 'http://howdidido co uk/Widgets aspx' start_urls = ["http://howdidido co uk/ClubDetails aspx?section=55&pagesection=handicaplist&cid=74"] def start_requests(self): return self init_request() def init_request(self): return [Request(url=self login_page callback=self login)] def login(self response): return FormRequest from_response(response formdata={'username': 'dummyemail' 'password': 'dummypass'} callback=self check_login_response) def check_login_response(self response): if "Logout" in response body: for url in self start_urls: yield self make_requests_from_url(url) else: self log("Could not log in ") def make_requests_from_url(url): sel = Selector(response) for tablerow in sel css('table basictable tr'): item = PgcmhItem() item["name"] = tablerow xpath('td[1]') extract() item["handicap"] = tablerow xpath('td[2]') extract() item["exact"] = tablerow xpath('td[3]') extract() item["category"] = tablerow xpath('td[4]') extract() yield item ```` | ````return FormRequest from_response(response formdata={'ctl00$WrappedContent$txtUser': 'dummyemail' 'ctl00$WrappedContent$txtPass': 'dummypass'} callback=self check_login_response) ```` |
json loads does not print list from text file (Data: <a href="http://paste ubuntu com/7605667/" rel="nofollow">http://paste ubuntu com/7605667/</a>) I am trying to create a json object from a txt file and print it as a list of python dicts The code I am using is: ````records=[json loads(line) for line in open(path)] records[0] ```` This gives me: ````{you'a': you'Mozilla/5 0 (Windows NT 6 1; WOW64) AppleWebKit/535 11 (KHTML like Gecko) Chrome/17 0 963 78 Safari/535 11' you'c': you'US' you'nk': 1 you'tz': you'America/New_York' you'gr': you'MA' you'g': you'A6qOVH' you'h': you'wfLQtf' you'cy': you'Danvers' you'l': you'orofrog' you'al': you'en-US en;q=0 8' you'hh': you'1 usa gov' you'r': you'http://www facebook com/l/7AQEFzjSi/1 usa gov/wfLQtf' you'you': you'http://www ncbi nlm nih gov/pubmed/22415991' you't': 1331923247 you'hc': 1331822918 you will': [42 576698 -70 954903]} ```` But when I use pprint I get the desired results: ````pprint(records[0]) {you'a': you'Mozilla/5 0 (Windows NT 6 1; WOW64) AppleWebKit/535 11 (KHTML like Gecko) Chrome/17 0 963 78 Safari/535 11' you'al': you'en-US en;q=0 8' you'c': you'US' you'cy': you'Danvers' you'g': you'A6qOVH' you'gr': you'MA' you'h': you'wfLQtf' you'hc': 1331822918 you'hh': you'1 usa gov' you'l': you'orofrog' you will': [42 576698 -70 954903] you'nk': 1 you'r': you'http://www facebook com/l/7AQEFzjSi/1 usa gov/wfLQtf' you't': 1331923247 you'tz': you'America/New_York' you'you': you'http://www ncbi nlm nih gov/pubmed/22415991'} ```` How can this be done with json loads? I tried using "records[0] split(' ')" but keep getting the error message: ````AttributeError: 'dict' object has no attribute 'split' ```` | The pretty-print output is not a list of dicts; it is the same dict as what you got with a regular print just displayed with the keys sorted and each key-value pair on its own line If you want to print a list of dicts as you say you probably want ````print records ```` If you want to go through the key-value pairs of each dict you can loop over their `iteritems()`: ````for record in records: for key value in record iteritems(): do_whatever_with(key value) # e g print '{}: {}' format(key value) ```` If you do not have a solid understanding of what you want to do figuring that out should be step 1 |
Python 3 0 using turtle onclick So here is my problem I have to make a picture for my CS class and it is really frustrating estimating in turtle I planed to use onclick() to show me to position ````import turtle as t def getPos(x y): print("(" x " " y ")") return def main(): t onclick(getPos) t mainloop() main() ```` The turtle documentation seems to say that the onclick will pass the coordinates in a function that takes in two variables <a href="http://docs python org/3 1/library/turtle html#turtle onclick" rel="nofollow">http://docs python org/3 1/library/turtle html#turtle onclick</a> NOTE: It works when I click on the arrow head but that is not what I want I want to click some other position on the screen to find out what coordinates I should send the arrow head to! Any help would be appreciated | Alright I figured out a work around Its not a perfect solution but it works pretty well Because onclick will only respond if you click on the arrow head I made the arrow head encompass the entire screen Then I hid it What you need to do is hover over the position you want to go to press "a" and when it goes black click the screen The she will will then display the coordinates you need Make sure you always go back to (1000 0) ````import turtle as t def showTurtle(): t st() return def getPos(x y): print("(" x " " y ")") return def hideTurtle(x y): t ht() return def main(): t speed(20) t shapesize(1000 1000) t up() t goto(1000 0) t ht() t onkey(showTurtle "a") t listen() t onclick(getPos) t onrelease(hideTurtle) t mainloop() main() ```` Also in case anyone from my class finds this I am a CS student in binghamton and if you use this I recommend leaving no trace The prof has seen this and will recognize it |
crontab to run python file if not running already I want to execute my python file via crontab only if its down or not running already I tried adding below entry in cron tab but it does not work ````24 07 * * * pgrep -f test py || nohup python /home/dp/script/test py & > /var/tmp/test out ```` test py works fine if i run `pgrep -f test py || nohup python /home/dp/script/test py & > /var/tmp/test out` manually and it also works in crontab if i remove pgrep -f test py || from my crontab and just keep `24 07 * * * nohup python /home/dp/script/test py & > /var/tmp/test out` Any idea why crontab does not work if i add pgrep -f? is there any other way i can run test py just one time to avoid multiple running processes of test py? Thanks Deepak | cron may be seeing the `pgrep -f test py` process as well as the `test py` process giving you the wrong result from `pgrep` Try the command without the `-f` this should just look for an occurrence of `test py` or replace `-f` with `-o` which will look for the oldest occurrence Your other option is to insert into test py something along the lines of: ````Pid = os popen('pgrep -f test py') read(5) strip() ```` which will allow you to check within the code itself if it is already running |
Variable for location of turtle I am trying to make a game using turtle in python I am trying to code some sort of collision My original idea is to have a variable be the location of a turtle so for example if turtle 1's location/coordinates are equal to that of turtle 2's the game ends So in layman's terms I want to know if there is a way to turn the location of a turtle into a variable | Use the `pos` method or other methods defined <a href="https://docs python org/2/library/turtle html#tell-turtle-s-state" rel="nofollow">here</a> to get the location of the turtle `pos` returns the position as a `Vec2D` vector `xcor` and `ycor` return the current x and y coordinates of turtle as `float` |
How to debug python script that is crashing python I am trying to help debug a python script that is causing python (2 7) itself to crashes - The script logs some info to a file and it ends at a different stop on each run or at least what it writes out is at a different spot - The script already have a try\catch's - The script has worked previously without errors - This is on Window 2008 servers with a fair bit of RAM and when run not much CPU usage So my question: - Are there tools or techniques that could help? - I see that there is a pdb module I could import but not sure if that would help this issue - When a py script crashes python itself how would you debug that? GB | So there are no exceptions in the log? It just exits randomly at different spots? To see every statement as it is executed use the <a href="https://docs python org/2/library/trace html" rel="nofollow">trace</a> module: ````python -you -m trace -t program py ```` To run the program in the debugger use <a href="https://docs python org/2/library/pdb html" rel="nofollow">pdb</a>: ````python -m pdb program py ```` With those two you should be able to see if it is something within the program causing it to exit If you do not see any evidence or pattern then it could be something outside of the program causing it to die On Linux I would also try running the program with `strace` and also watching the OOM killer Not sure what similar steps would be in Windows (Windows does not have an OOM killer) |
Union of 2 SearchQuerySet in django haystack Is there any way to get an union of two or more searchqueryset ? For example :- ````query1 = SearchQuerySet() filter(authors=query) query2 = SearchQuerySet() filter(title=query) ```` How do I combine both the queries together so that i get a <strong><them>union</them></strong> of the 2 queries ? | `SearchQuerySet` implements the `QuerySet` interface <a href="https://django-haystack readthedocs org/en/v2 4 1/searchqueryset_api html?highlight=#why-follow-queryset" rel="nofollow"><them>to some extent</them></a> so you can try: ````query1 | query2 ```` |
Defining Python Classes I am a beginner with Python as I have probably stated in my previous questions and some of the topics that I have been comming across are not given the in depth explanations that I would require to underswtand the material so I have a question The question that is beign asked is " Add method distance() to the class Point It takes another Point object as input and returns the distance to that point (from the point invoking the method) What it is looking for is the following result when this is all input into the module ````>>> c = Point() >>> c setx(0) >>> c sety(1) >>> d = Point() >>> d setx(1) >>> d sety(0) >>> c distance(d) 1 4142135623730951 ```` Here is what I have: ````class Point: def setx(self xcoord): self x = xcoord def sety(self ycoord): self y = ycoord def get(self): return(self x self y) def move(self dx dy): self x = dx self y = dy ```` And then I am not sure if I would need to define distance in what way Thank you I have a clear baseline of how I am pretty sure I would begin this but then when it comes to defining distance I am very much stuck | You need a method like this ````def distance(self other): dist = math hypot(self x - other x self y - other y) return dist ```` You also need to `import math` at the start of your program Aside: It is not pythonic at all to have your `setx` and `sety` methods You should just assign to the attributes directly eg `c x = 0` ``` Help on built-in function hypot in module math: hypot( ) hypot(x y) Return the Euclidean distance sqrt(x*x y*y) ``` |
Using Selenium with Django server is not properly created I recently reinstalled both Django and Selenium and most things seem to be working correctly but when I try to run my functional tests the webdriver apparently cannot find the LiveServer address The code looks like this: ````from selenium import webdriver from selenium webdriver common keys import Keys from django test import LiveServerTestCase import unittest class GeneralFunctionalTests(LiveServerTestCase): def setUp(self): self browser = webdriver Firefox() self browser implicitly_wait(3) def tearDown(self): self browser quit() def test_can_navigate_site(self): self browser get(self live_server_url) # some tests from here ```` The webdriver starts but the home page fails to load (it loads correctly on the normal browser with `python manage py runserver`) so all tests fail as no elements can be found `self live_server_url` equals `http://localhost:8081` which looks right to me Any clue about what I am missing here? | Well never mind that Once again it was the antivirus messing in places where it should not be If you are having the same problem and your antivirus is <them>Avast!</them> try deactivating <them>Web Shield</them> in the <them>Active Protection Settings</them> tab |
What was Peter the Great's goal for writing War and Peace? | null |
Pass information from javascript to django app and back So I am trying to basically set up a webpage where a user chooses an id the webpage then sends the id information to python where python uses the id to query a database and then returns the result to the webpage for display I am not quite sure how to do this I know how to use an ajax call to call the data generated by python but I am unsure of how to communicate the initial id information to the django app Is it possible to say query a url like /app/id (IE /app/8) and then use the url information to give python the info? How would I go about editing urls py and views py to do that? Thanks | Yes it is possible If you pass the id as a parameter to the view you will use inside your app like: `def example_view (request id)` and in urls py you can use something like this: `url(r'^example_view/(?P<id>\d+)/' 'App views example_view')` The id in the url `/example_view_template/8` will get access to the result using the id which is related to the number 8 Like the 8th record of a specific table in your database for example |
Python: Installation of MPlayer/MEncoder for Windows I am trying to install MPlayer for Windows and using the command line ````os system("mencoder ") ```` I want to be able to compile a series of images into a time-lapse video The problem is that I am getting the following error: ````'C:\Python27\Lib\MPlayer-1 1\mencoder' is not recognized as an internal or external command operable program or batch file ```` So my question is when extracting the MPlayer-1 1 tar gz file where are you supposed to put the folder so that the command line will run properly in Windows? I downloaded MPlayer from here: <a href="http://www mplayerhq hu/design7/dload html" rel="nofollow">http://www mplayerhq hu/design7/dload html</a> | From my understanding you downloaded the source code of MPlayer which you cannot run via command line You have to compile the whole project perhaps Otherwise download the binaries just like Dan D said |
sort dict by value python Assume that I have a dict ````data = {1:'b' 2:'a'} ```` And I want to sort data by 'b' and 'a' so I get the result ````'a' 'b' ```` How do I do that? Any ideas? | To get the values use ````sorted(data values()) ```` To get the matching keys use a `key` function ````sorted(data key=data get) ```` To get a list of tuples ordered by value ````sorted(data items() key=lambda x:x[1]) ```` |
Redirect to the POST form page I am developing an application using Django The main page contains a textarea input where you must enter a list of IDs(this list can be large so I submit the form using POST) After submiting the form the server will render a page with a table where you can find informations about every ID If you click on an ID you will go to a page where you can modify some fields For saving the modified fields into the database the form action is: 'manage_ids/<>/save' and on the server I have a view for this url How can I redirect the user back to the page with the table? I am submiting the form using POST so a simple redirect would not work Or to remain on the page where you can modify the fields(in this case if you press the 'Back' browser button to be redirected to the table page) Workflow: ````/ POST /manage_ids GET /manage_ids/<<md5>> POST(save) /manage_ids/<<md5>>/save Now I should be redirected to: /manage_ids ```` | If you need to preserve a long list of IDs across multiple page requests you should use the <a href="https://docs djangoproject com/en/1 5/topics/http/sessions/" rel="nofollow">session</a> |
Google App Engine TextProperty and UTF-8: When to Encode/Decode I am on Google App Engine 2 5 with Django Template and Webapp Frame The db TextProperty and UTF-8 and Unicode and Decode/Encode have confused me so much I would really appreciate some experts can offer some suggestions I have googled for the whole night and still have so many questions What I am trying to do: ````[utf-8 form input] => [Python Store in db TextProperty] => [When Needed Replace Japanese with English] => [HTML UTF-8] ```` According to this answer <a href="http://stackoverflow com/questions/10650004/zipping-together-unicode-strings-in-python/10650469#10650469">Zipping together unicode strings in Python</a> ````# -*- coding: utf-8 -*- ```` and all py files saved in utf-8 format Here is my code: ````#Model py class MyModel(db Model): content = db TextProperty() #Main py def post(self): content=cgi escape(self request get('content')) #what is the type of content? Unicode? Str? or Other? obj = MyModel(content=content) #obj = MyModel(content=unicode(content)) #obj = MyModel(content=unicode(content 'utf-8')) #which one is the best? obj put() #Replace one Japanese word with English word in the content content=obj content #what is the type of content here? db Text? Unicode? Str? or Other? #content=unicode(obj content 'utf-8') #Is this necessary? content=content replace(you'ã²ã¨' you'hito') #Output to HTML self response out write(template render(path {'content':content}) #self response out write(template render(path {'content':content encode('utf-8')}) ```` Hope some Google App Engine engineer can see this question and offer some help Thanks a lot! | First <a href="http://www joelonsoftware com/articles/Unicode html" rel="nofollow">read this</a> <a href="http://blog notdot net/2010/07/Getting-unicode-right-in-Python" rel="nofollow">And this</a> In a nutshell whenever you are dealing with a text string in your app it should be a unicode string You should encode into a byte string (an instance of 'str' instead of 'unicode') when you want to send data as bytes - for instance over HTTP and you should decode from a byte string when you receive bytes that represent text (and you know their encoding) The only operations you should ever be doing on a byte string that contains encoded text are to decode or encode them Fortunately most frameworks get this right; webapp and webapp2 for instance (I can see you are using webapp) should return unicode strings from all the request methods and encode any strings you pass to them appropriately Make sure all the strings you are responsible for are unicode and you should be fine Note that a byte string can store any sort of data - encoded text an executable an image random bytes encrypted data and so forth Without metadata such as the knowledge that it is text and what encoding it is in you cannot sensibly do anything with it other than store and retrieve it Do not ever try to decode a unicode string or encode a byte string; it will not do what you expect and things will go horribly wrong Regarding the datastore `db Text` is a subclass of `unicode`; to all intents and purposes it <them>is</them> a unicode string - it is only different so the datastore can tell it should not be indexed Likewise `db Blob` is a subclass of `str` for storing byte strings |
How to change DEFAULT CURRENT_TIMESTAMP format Currently i am using the following code to create a table in mysql `CREATE TABLE example(id INT ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP); ` so whenever i insert data into this table i get the value of ts in (YEAR-MONTH-DATE HOURS-MINUTE-SECOND) format and i want to change it in (DATE-MONTH-YEAR HOURS-MINUTE-SECOND) let us suppose i have inserted data in above created table by using `insert into example (id) values (123); `when i retrieve the information by using `select * from example; ------+---------------------+ | id | ts | ------+---------------------+ | 123 | 2014-07-28 17:17:10 | ------+---------------------+ `i get the datetime in this format `2014-07-28 17:17:10` i want to change this to `28-07-2014 17:17:10` Is it possible to change format of timestamp? If yes then how do we do it ? | You should format ts output for example: ````SELECT id DATE_FORMAT(ts '%d-%m-%Y %H:%i:%s') FROM example ```` Here is what you need to understand A `TIMESTAMP` data type has a well-defined internal format That internal format is designed so MySQL can search and manipulate it easily (It is a variant of the UNIX/Linux `time_t` datatype if you care ) You cannot change that format When you ask MySQL to render a timestamp it displays it using the default format shown in your question What you CAN do is format it for display like the example in this answer demonstrates |
Can I open an application using python during run time I was wondering if i could open any kind of application in Python during run time ? | Try having a look at `subprocess call` <a href="http://docs python org/2/library/subprocess html#using-the-subprocess-module" rel="nofollow">http://docs python org/2/library/subprocess html#using-the-subprocess-module</a> |
What is "instrumentation" in the context of SQLAlchemy? In <a href="http://docs sqlalchemy org/en/latest/orm/tutorial html" rel="nofollow">SQLAlchemy's tutorial</a> it mentions "instrumentation" but does not appear to properly define what instrumentation is: <blockquote> These class attributes exist as Python descriptors and define instrumentation for the mapped class The functionality of this instrumentation includes the ability to fire on change events track modifications and to automatically load new data from the database when needed </blockquote> What is instrumentation in this context? | instrumentation is the process of attaching attributes to a class which are implemented as <a href="http://docs python org/howto/descriptor html">Python Descriptors</a> (this link is mentioned in that sentence) such that any attribute get set or delete operation that is: ````# __get__ print myobject someattribute # __set__ myobject someattribute = "foo" # __del__ del myoject someattribute ```` will invoke Python code for each event rather than using Python's default behavior of accessing/manipulating `myobject __dict__` directly SQLAlchemy takes advantage of these hooks to provide behaviors such as <a href="http://martinfowler com/eaaCatalog/lazyLoad html">lazy loading</a> as well as to record when the value of an attribute changes for the purpose of implementing the <a href="http://martinfowler com/eaaCatalog/unitOfWork html">unit of work</a> pattern where only those elements that have changed are rolled into UPDATE statements to be emitted to the database upon flush |
How can I store lock objects in MongoDB? I have a put and get function that inserts into MongoDB: ````def put(self key value): key = self path+"&&"+key value1 = Binary(pickle dumps(value)) entry = {"keyname":key "info":value1} self filenode update({"keyname":key} { "$set" : entry } upsert=True) def get(self key): key1 = key key = self path+"&&"+key res = self filenode find_one({"keyname":key}) if "info" in res: x = res["info"] res1 = pickle loads(x) return res1 else: return None ```` This works if value in put is of simple type such as string dict etc But if value is an object it is not able to pickle inside the put function The error I am getting is: ````raise TypeError "cannot pickle %s objects" % base __name__ ```` TypeError: cannot pickle lock objects | Have a read of Python's documentation on serialization - <a href="https://docs python org/2/library/pickle html" rel="nofollow" title="pickle â Python object serialization">pickle â Python object serialization</a> If you control the definition of the object you can provide a `__getstate__()` method that can remove un-serializable attributes like locks I use this to set a lock to `None` then use `__setstate__()` as a de-serializing hook to re-initialize the lock |
What year saw the death of Gundobad? | 516 |
Different Index in python I am a newbie to python and I have a question that I cannot answer it Please help me! For example I have an array in python: index: 1 | 2 | 3 | 4 | 5 | 6 | value: a | b | c | d | e | f | I can read value from the 5th slot of this array by using 2 ways: - print array[4] - print array[-2] So what is the fastest way to access into the 5th position on this array? Thank you so much | They are both very close to constant time You may find this helpful: <a href="https://wiki python org/moin/TimeComplexity" rel="nofollow">https://wiki python org/moin/TimeComplexity</a> When I run this many times and average the results a[-2] actually runs a bit faster but the difference is so small it probably will not matter even on huge data sets ````from datetime import datetime a = ['a' 'b' 'c' would' 'e' 'f'] startTime = datetime now() for i in xrange(0 10000000): a[4] print(datetime now()-startTime) startTime = datetime now() for i in xrange(0 10000000): a[-2] print(datetime now()-startTime) ```` |
Using Regular Expression with Twill I am currently using urllib2 and BeautifulSoup to open and parse html data However I have ran into a problem with a site that uses javascript to load the images after the page has been rendered (I am trying to find the image source for a certain image on the page) I am thinking Twill could be a solution and am trying to open the page and use a regular expression with 'find' to return the html string I am looking for I am having some trouble getting this to work though and cannot seem to find any documentation or examples on how to use regular expressions with Twill Any help or advice on how to do this or solve this problem in general would be much appreciated | I would rather user CSS selectors or "real" regexps on page source Twill is AFAIK not being worked on Have you tried BS or PyQuery with CSS selectors? |
HMMlearn Gaussian Mixture: set mean weight and variance of each mixture component I am using the HMMlearn module to generate a HMM with a Gaussian Mixture Model The problem is I want to initialize the mean variance and weight of each mixture component before I fit the model to any data How would I go about doing this? | From the <a href="http://hmmlearn readthedocs io/en/stable/tutorial html#building-hmm-and-generating-samples" rel="nofollow">HHMlean documentation</a> <blockquote> Each HMM parameter has a character code which can be used to customize its initialization and estimation THEM algorithm needs a starting point to proceed thus prior to training each parameter is assigned a value either random or computed from the data It is possible to hook into this process and provide a starting point explicitly To do so - ensure that the character code for the parameter is missing from init_params and then - set the parameter to the desired value </blockquote> Here is an example: ````model = hmm GaussianHMM(n_components=3 n_iter=100 init_params="t") model startprob_ = np array([0 6 0 3 0 1]) model means_ = np array([[0 0 0 0] [3 0 -3 0] [5 0 10 0]]) model covars_ = np tile(np identity(2) (3 1 1)) ```` Another example for initializing a `GMMHMM` ````model = hmm GMMHMM(n_components=3 n_iter=100 init_params="smt") model gmms_ = [sklearn mixture GMM() sklearn mixture GMM() sklearn mixture GMM()] ```` The GMMs themselves can be initialised in a very similar way using its attributes and by providing in the `init_params` string which attributes should be initialize by the constructor |
port forwarding django development server - URL is being doubled I have a Django development server running on a remote centos VM on another lan I have set up port forwarding using Secure CRT to access the web page through my browser from my desk pc I am currently not using apache with the development server and is shutdown I start the server by running `python manage py runserver 0 0 0 0:80` When I type either the ip or `www localhost com` into the web browser my URL is read as if it has been doubled with the host being read as if it was also the path ````Page not found (404)## Request Method: GET Request URL: http://www localhost com/http://www localhost com/ ```` When I try to access the development server from within the same LAN the page loads up fine I have been searching through the django documentation and stack overflow but I have yet to find a similar problem to this Does anyone have any thoughts on why this may be happening and what could be a possible solution? Thank you very much in advance! | It looks like the request URL is incorrect: <strong><a href="http://www localhost com/http://www localhost com/" rel="nofollow">http://www localhost com/http://www localhost com/</a></strong> should probably be <strong>http://<them>actual_machine_IP</them> com/</strong> I would start searching there You will not be able to access the VM's port 80 from a different lan using localhost as the hostname since localhost is <strong>probably</strong> already set in your hosts file If you want to test your dev environ remotely can I suggest either setting up Apache properly with port 80 (as opposed to using django's dev server--privilege restrictions and all that can be circumvented with sudo and other bad practice) or use a pre-built shared dev service like <strong>vagrant share</strong> |
What reason did David Quammen believe that On the Origin of Species was weakened in later editions? | Darwin making concessions and adding details to address his critics |
Django Tastypie: including relationship with the same model I am really stuck with this issue Here is a simplified version of a model: ````# models py class CustomComment(models Model): comment = models CharField(max_length=500) parent_comment = models ForeignKey('self' blank=True null=True) active = models BooleanField() ```` So the comments can have children comments (there are only two levels though) So in the api when I query a comment I want to include the children I have other models with relationship with other models but I cannot find how to make a relationship within the same model Here is what I tried: ````# api py class CustomCommentResource(ModelResource): children = fields ToManyField('self' 'children' related_name='parent_comment' null=True blank=True full=True) # returns an empty array class Meta: queryset = CustomComment objects filter(parent_comment=None active=True) resource_name = 'comment' ```` With this code when I call the api the objects does have a `children` property but it is an empty array Any idea how to get the comments each comment including its own children? Thanks | <blockquote> What I have not thought about at first though is that in the query I also specify `parent_comment=None` And the children will not have any parents </blockquote> Does not matter The children will always be accessible from each parent via the related manager `parent customcomment_set` <blockquote> But I do not know if it is the same query that is used for the relationships </blockquote> No It will do a separate query for each parent to get to its children although you might be able to do it in one query by using <a href="https://docs djangoproject com/en/dev/ref/models/querysets/#prefetch-related" rel="nofollow">`prefetch_related()`</a> The following code ````# api py class CustomCommentResource(ModelResource): children = fields ToManyField('self' lambda bundle: bundle obj customcomment_set all() null=True blank=True full=True) class Meta: queryset = CustomComment objects filter(parent_comment=None active=True) resource_name = 'comment' ```` works for me but the docs for <a href="http://django-tastypie readthedocs org/en/latest/fields html#tomanyfield" rel="nofollow">`ToManyField`</a> are not particularly good so I am not sure if that is the best way to do it |
Weird sum coming out of complex dictionary Having trouble with this python code (dealing with data from midi files if you are curious about the variable names) `song getIntervals()` is a matrix of assorted integers e g : ````[[-2 0 0 5 3] [2] [4 3 0]] ```` except much longer `chrom` is defined as: ````def createIntfunc(a b): temp1={} temp2={} for x in range(a b): temp1[x]=0 for x in temp1: temp2[x]=dict(temp1) return temp2 chrom=createIntfunc(-17 18) ```` So it is a dictionary where the keys are integers and the values are dictionaries which have integers for both keys and values Here is the piece of code of concern: ````for phrase in song getIntervals(): for noteind in range(1 len(phrase)): chrom[phrase[noteind-1]][phrase[noteind]]+=(1/float(sum([len(a) for a in song getIntervals()]))) print sum([sum(a) for a in [b values() for b in chrom values()]]) ```` which prints a value that is close to 0 8 depending on what song getIntervals() is But I do not see how it would not just always return 1 Essentially I am repeatedly adding to a value that starts at zero a fraction that is defined as the inverse of however many times I am going to add it So that should be 0+(1/x)*x=1 What am I not seeing? | Here is your problem: Your value of "1/x" is not actually getting added "x" times because the inside of your loop is not running "x" times For example when the length of a phrase is only 1 "1/x" is not added into the dictionary because the inner loop only runs on indices which satisfy the inequality 1 <= noteind < len(phrase) When len(phrase)==1 no index can satisfy this inequality so the inside of the loop does not execute I am not sure what your intention is for this to do so I am not sure exactly how to fix it without knowing the intended behavior but that is why it is performing the way it is |
Elliptic curve brute forcing I have all parameter of elliptic curve And the coordinate of points <strong>Q</strong> and <strong>P</strong> I want to solve <strong>Q=k*P</strong> (where <strong>k</strong> is the unknown) by testing all possible <strong>k</strong> So i used this <a href="https://github com/jschendel/elliptic-curve-steganography/blob/master/ecs/ellipticcurve py" rel="nofollow">class</a> then: ````a=-1 b=0 p=134747661567386867366256408824228742802669457 curve = EllipticCurve(a b p) P=[18185174461194872234733581786593019886770620 74952280828346465277451545812645059041440154] Q=[76468233972358960368422190121977870066985660 33884872380845276447083435959215308764231090] for i in range(2902021510595963727029): result = curve multPoint(i P) if result[0]==Q[0] and result[1]==Q[1]: print (i) break ```` Is this the right approach to solve this problem? | This is not a good approach because you are trying to do 2902021510595963727029 operations Even if you managed to do a billion operations per second it would take <a href="https://www google com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=2902021510595963727029%2F1000000000%2F60%2F60%2F24%2F365" rel="nofollow">92 thousand years</a> to finish You are basically trying to break the security of ECDSA If you figure out a way to do this then it would be possible to figure out an ECDSA private key given the corresponding public key It would be a breakthrough in cryptography and you would be famous There are many smart people that have thought about this problem before you and failed to find a solution The problem you are trying to solve is called the <a href="http://en wikipedia org/wiki/Discrete_logarithm" rel="nofollow">discrete logarithm</a> problem |
Python: multi-dimensional lists - appending one 2D list into another list I am looking to create a master array/list that takes several two dimensional lists and integrates them into the larger list For example I have a `TableA[]` which has `dates` as one array/list and `prices` as another array/list I have another as TableB[] which has the same TableA[0][0] has the first date; TableA[0][1] has the first price; TableA[1][0] has the second date and so on I would like to create `BigTabe[]` that has `BigTable[0][0][0] = TableA[0][0]` and `BigTable[1][0][0] = TableB[0][0]` Any guidance would be much appreciated Thank you! | Python's fairly friendly about this sort of thing and will let you have lists as elements of lists Here is an example of one way to do it `TableA = [['01/01/2000' '$10'] ['02/01/2000' '$11']]` If you entered this straight into the python interpreter you would define TableA as a list with two elements Both of these elements are also lists If you then entered in `TableA[0]` you would get `['01/01/2000' '$10']` Furthermore by entering `TableA[0][0]` you would get `'01/01/2000'` as that is the first element of the first list in TableA Extending this further you can have lists of lists of lists (and so on) First let us define `TableA` and `TableB` `TableA = [['01/01/2000' '$10'] ['02/01/2000' '$11']]` `TableB = [['03/01/2000' '$13'] ['04/01/2000' '$14']]` Now we can simply define `BigTable` as having `TableA` and `TableB` as its elements `BigTable = [TableA TableB]` Now `BigTable[0]` is just `TableA` so `BigTable[0][0][0]` will be the same as `TableA[0][0]` If at some point down the line you realise that you want `BigTable` to have more lists in it say a `TableC` or `TableD` Just use the append function `BigTable append(TableC)` By the way you will probably want to have prices and dates expressed as numbers rather than strings but it is easier to follow the example this way |
Python for loop does not execute last iteration List inputed: `["a" "b" "c" "d" "e" "f" "g" "h"]` List expected: `["a" 99 "b" 99 "c" 99 "d" 99 "e" 99 "f" 99 "g" 99 "h"]` List actual: `["a" 99 "b" 99 "c" 99 "d" 99 "e" "f" "g" "h"]` Python code: ````m_o = ["a" "b" "c" "d" "e" "f" "g" "h"] m = ["a" "b" "c" "d" "e" "f" "g" "h"] m_expected = ["a" 99 "b" 99 "c" 99 "d" 99 "e" 99 "f" 99 "g" 99 "h"] num = 99 count = 0 m_l = range(len(m)) for i in m_l: if i==(1+count): m insert(i num) count = count 2 m_l = range(len(m)) #print("1+count : " str(1+count)) #print(m) #print("m_l: " str(m_l)) print("List inputed: ") print(m_o) print("\nList expected: ") print(m_expected) print("\nList actual: ") print(m) ```` | The `for` loop derefences `m_l` <strong>once</strong>; rebinding `m_l` will not change the loop I would use some <a href="http://docs python org/2/library/itertools html" rel="nofollow">`itertools` module</a> magic here: ````from itertools import repeat chain m = list(chain from_iterable(zip(m repeat(99))))[:-1] ```` Demo: ````>>> from itertools import repeat chain >>> m = ["a" "b" "c" "d" "e" "f" "g" "h"] >>> list(chain from_iterable(zip(m repeat(99))))[:-1] ['a' 99 'b' 99 'c' 99 would' 99 'e' 99 'f' 99 'g' 99 'h'] ```` or using insertions to alter `m` in-place: ````for i in range(len(m) - 1 0 -1): m insert(i 99) ```` Demo: ````>>> m = ["a" "b" "c" "d" "e" "f" "g" "h"] >>> for i in range(len(m) - 1 0 -1): m insert(i 99) >>> m ['a' 99 'b' 99 'c' 99 would' 99 'e' 99 'f' 99 'g' 99 'h'] ```` By looping over the indices <them>in reverse</them> you do not have to account for the extra elements being inserted into the list |
wxMessageBox with an auto-close timer in wxPython **Platforms: Windows OS X Python Version: Active State Python 2 7 wxPython Version: Version 2 9** Here is a sample code in which I use a wxMessageBox: ````import wx os class Frame(wx Frame): def __init__(self parent id title): wx Frame __init__(self parent id title size=(100 100) style=wx MINIMIZE_BOX | wx SYSTEM_MENU | wx CAPTION | wx CLOSE_BOX | wx CLIP_CHILDREN) host=os system('hostname') if host!='superman': self dialogBox=wx MessageBox('The host name should be superman Closing this dialog box in 2s ' 'Info') self Destroy() else: self Center() self Show() if __name__ == '__main__': app = wx App(redirect=False) frame = Frame(None -1 'Sample') app MainLoop() ```` According to the above piece of code If the host name is not 'superman' then the user is displayed a message box and prompted to press 'OK' If the user presses 'OK' button on the message box then the control moves to the next line in the code (i e line number 10) where the frame is destroyed I want to be to able to automatically close the dialog box and go to the next line in the code i e `self Destroy()` if the user does not press the 'OK' button in the next 2 seconds Any thoughts on how do I do that in wxpython ? | I think you might have to use a custom `wx Dialog` for this You can use `wx FutureCall` to call trigger an event in the future Something like: ````class MessageDialog(wx Dialog): def __init__(self message title): wx Dialog __init__(self None -1 title size=(300 120)) self CenterOnScreen(wx BOTH) ok = wx Button(self wx ID_OK "OK") ok SetDefault() text = wx StaticText(self -1 message) vbox = wx BoxSizer(wx VERTICAL) vbox Add(text 1 wx ALIGN_CENTER|wx TOP 10) vbox Add(ok 1 wx ALIGN_CENTER|wx BOTTOM 10) self SetSizer(vbox) class Frame(wx Frame): def __init__(self parent id title): wx Frame __init__(self parent id title size=(100 100) style=wx MINIMIZE_BOX | wx SYSTEM_MENU | wx CAPTION | wx CLOSE_BOX | wx CLIP_CHILDREN) host=os system('hostname') if host!='superman': dlg = MessageDialog('The host name should be superman Closing this dialog box in 2s ' 'Info') wx FutureCall(2000 dlg Destroy) dlg ShowModal() else: self Center() self Show() ```` |