input_text
stringlengths 1
40.1k
| target_text
stringlengths 1
29.4k
⌀ |
---|---|
Getting Top N items per group in pySpark I am using Spark 1 6 2 I have the following data structure: ````sample = sqlContext createDataFrame([ (1 ['potato' 'orange' 'orange']) (1 ['potato' 'orange' 'yogurt']) (2 ['vodka' 'beer' 'vodka']) (2 ['vodka' 'beer' 'juice' 'vinegar']) ] ['cat' 'terms']) ```` I would like to extract top N most frequent terms per cat I have developed the following solution which seems to work however I wanted to see if there is a better way to do this ````from collections import Counter def get_top(it terms=200): c = Counter(it __iter__()) return [x[0][1] for x in c most_common(terms)] ( sample select('cat' sf explode('terms')) rdd map(lambda x: (x cat x col)) groupBy(lambda x: x[0]) map(lambda x: (x[0] get_top(x[1] 2))) collect() ) ```` It provides the following output: ````[(1 ['orange' 'potato']) (2 ['vodka' 'beer'])] ```` Which is in line with what I am looking for but I really do not like the fact that I am resorting to using Counter How can I do it with spark alone? Thanks | If this is working it is probably better to post this to <a href="http://codereview stackexchange com/">Code Review</a> Just as an exercise I did this without the Counter but largely you are just replicating the same functionality - Count each occurrence of (`cat` `term`) - Group by `cat` - Sort the values based on Count and slice to number of terms (`2`) Code: ````from operator import add (sample select('cat' sf explode('terms')) rdd map(lambda x: (x 1)) reduceByKey(add) groupBy(lambda x: x[0][0]) mapValues(lambda x: [r[1] for are _ in sorted(x key=lambda a: -a[1])[:2]]) collect()) ```` Output: ````[(1 ['orange' 'potato']) (2 ['vodka' 'beer'])] ```` |
Interpolate data Hello i am trying to obtain the following interpolate function below ````data1 = [15000 11000 8000 4000 1000 552 0 -708 -8000 -8 10000 15000] data2 = [10 9 8 7 6 5 4 0 3 2 1] data1 data2 15000 10 11000 9 8000 8 4000 7 1000 6 552 5 ```` I tried the following Code but the graph is constant because i used line space as its step How can i obtain the table above ````x = np linspace(-15000 15000 10) y = [10 9 8 7 6 5 4 3 2 1] f = interpolate interp1d(x y) f2 = interpolate interp1d(x y kind='linear') xnew = np linspace(0 10 40) plt plot(x y 'of xnew f(xnew) '-' xnew f2(xnew) '--') plt show() ```` Output shown <img src="http://i stack imgur com/iRJSL png" alt="enter image description here"> | Perhaps this is what you are looking for: ````data1 = [15000 11000 8000 4000 1000 552 0 -708 -8000 -8 10000 15000] data2 = [10 9 8 7 6 5 4 0 3 2 1] print "{0:10}{1:10}" format("Data 1" "Data 2") for var1 var2 in zip(data1 data2): print "{0:<10}{1:<10}" format(var1 var2) ```` Running <a href="http://ideone com/2zzGNM" rel="nofollow">example</a> The above code simple combines the two lists using <a href="http://docs python org/2/library/functions html#zip" rel="nofollow">`zip`</a> that means you can get both their values side by side as a tuple To quote from the documentation: <blockquote> This function returns a list of tuples where the i-th tuple contains the i-th element from each of the argument sequences or iterables The returned list is truncated in length to the length of the shortest argument sequence When there are multiple arguments which are all of the same length zip() is similar to map() with an initial argument of None With a single sequence argument it returns a list of 1-tuples With no arguments it returns an empty list </blockquote> Here is a console example: ````>> zip([2 3 11 3] [5 6 77 1]) [(2 5) (3 6) (11 77) (3 1)] ```` |
How to visualize continuous time spent in a location in pandas? I have some data with timestamps and location data like follows: ````A 2013-02-05 19:45:00 (39 94 -86 159) A 2013-02-05 19:55:00 (39 94 -86 159) A 2013-02-05 20:00:00 (39 777 -85 995) A 2013-02-05 20:05:00 (39 775 -85 978) B 2013-02-05 22:20:00 (39 935 -86 159) B 2013-02-05 22:25:00 (39 935 -86 159) B 2013-02-05 23:55:00 (39 951 -86 151) B 2013-02-06 00:00:00 (39 951 -86 151) B 2013-02-06 00:05:00 (39 906 -86 196) C 2013-02-06 00:25:00 (39 82 -86 249) C 2013-02-06 00:30:00 (39 82 -86 249) C 2013-02-06 02:45:00 (41 498 -81 527) C 2013-02-06 02:55:00 (41 498 -81 527) C 2013-02-06 04:35:00 (39 82 -86 249) C 2013-02-06 04:40:00 (39 82 -86 249) ```` What I need to do is that for each user for each day get a histogram of the number of times someone was in one location continuously Hence I want to mark each continuous period where the location remains the same for each user each day How would I go about that in python pandas? Cases that the location repeats for a user in one day is possible as shown for user C the location (39 82 -86 249) occurs again So those cases are to be considered separate continuous times | I think you are looking for pd Series shift ````x = pd Series([1 3 3 2 3 3]) x 0 1 1 3 2 3 3 2 4 3 5 3 x shift(-1) 0 3 1 3 2 2 3 3 4 3 5 NaN (x != x shift(-1)) sum() 4 ```` Assuming the data in the question is the ouput of ````df[['COL1' 'COL2' 'COL3']] ```` Then this should work to give you number of unique places per user/per day I am not sure if that is exactly what you want but should help get started ````df['DATE'] = df COL2 apply(lambda s: pd to_datetime(s) date()) df groupby(['COL1' 'DATE']) apply(lambda sdf: (sdf COL3 != sdf COL3) sum()) ```` |
Ctrl+D equivalent in IPython and bpython? In the standard Python interactive she will I can press <kbd>Ctrl</kbd>+<kbd>D</kbd> to close stdin and it shows the output: <pre class="lang-py prettyprint-override">`$ python Python 2 7 2 (default Mar 7 2012 21:18:58) [GCC 4 5 3] on linux2 Type "help" "copyright" "credits" or "license" for more information >>> for f in range(5): print f (I press Enter here) (I press Ctrl+D here) 0 1 2 3 4 >>> ```` But in IPython and bpython <kbd>Ctrl</kbd>+<kbd>D</kbd> does not work I must press <kbd>Enter</kbd> twice to get the results: IPython: <pre class="lang-py prettyprint-override">`In [1]: for f in range(5): : print f (I press Enter here) : (I press Enter here) : (I press Enter here) 0 1 2 3 4 ```` bpython: <pre class="lang-py prettyprint-override">`>>> for f in range(5): print f (I press Enter here) (I press Enter here) (I press Enter here) 0 1 2 3 4 ```` The version which I am using: ````[I] dev-python/ipython Available versions: 0 10 0 10 1 0 10 2 ~0 12-r1 {doc emacs examples gnuplot matplotlib mongodb notebook qt4 readline (+)smp sqlite test wxwidgets} Installed versions: 0 10 2(03:54:09 PM 08/12/2011)(examples readline -doc -emacs -gnuplot -smp -test -wxwidgets) Homepage: http://ipython org/ Description: Advanced interactive she will for Python [I] dev-python/bpython Available versions: 0 9 7 1 0 10 1 {gtk urwid} Installed versions: 0 10 1(10:34:17 AM 03/14/2012)(gtk -urwid) Homepage: http://www bpython-interpreter org/ https://bitbucket org/bobf/bpython/ http://pypi python org/pypi/bpython Description: Syntax highlighting and autocompletion for the Python interpreter ```` | you just need to press <kbd>Enter</kbd> key twice the standard Python interactive she will and IPython provide the same result effect here |
What type of God did Whitehead believe existed? | dipolar |
Is __del__ really a destructor? I do things much in C++ where Dtor is really meant for destruction of an acquired resource when I start off with python (which is really a fun and fantastic) I came to learn it has GC like java So there is no heavy emphasize on object ownership(construction and destruction) in python as far as i learned the `__init__()` makes me more sense in python as it does for ruby too but Hmmmmm `__del__()` do we really need to implement this built-in function in our class? Will my class lack something if I miss `__del__()`?The one scenario I could see `__del__()` useful is if I want to log something when destroying an object is there anything other than this? | <blockquote> Is <strong>del</strong> really a destructor? </blockquote> No `__del__` method is not a destructor is just a normal method you can call whenever you want to perform any operation but it is always called before the garbage collector destroys the object Think of it like a clean or last will method |
python 27 - Creating and running instances of another script in parallel I am attempting to build a multiprocessing script that retrieves dicts of attributes from a MySQL table and then runs instances of my main script in <strong>parallel</strong> using each dict retrieved from the MySQL table as an argument to each instance of the main script The main script has a method called queen_bee() that is responsible for ensuring that all the other methods have the correct information and are executed in the proper order I have tried to iterate through the list of dicts in order to create/run parallel processes of the main script using the multiprocessing library But they end up running consecutively not concurrently: ````from my_main_script import my_main_class as main import multiprocessing as mp def create_list_of_attribute_dicts(): return list_of_dicts for each_dict in list_of_dicts: instance = main(each_dict) p = mp Process(target=instance queen_bee() args=(each_dict )) p start() ```` I have also tried using the multiprocessing library's Pool map() method But I cannot figure out how to instantiate the main script one time for each dict using Pool map(): ```` pool = mp Pool() jobs = pool map(main queen_bee() list_of_dicts) ```` The Pool map method seems to be the cleanest most pythonic way to get these instances to run in parallel but I am hung up on the proper way to do that in this case I know the above 'jobs' variable will fail because 'main' has not been instantiated However I cannot figure out how to pass each dict as an argument to separate instances of the main class and then run those instances using the map method I am open to trying a different approach Thanks in advance for your help | You could store your dictionaries in a list and then try something like that: ````from multiprocessing import Pool as ThreadPool # def parallel_function(list_of_dictionaries threads=20): thread_pool = ThreadPool(threads) results = thread_pool map(SC queen_bee() list_of_dictionaries) thread_pool close() thread_pool join() return results ```` <strong>Note:</strong> I had problem using multiprocessing due to my pc so for me worked by replacing `multiprocessing` with the `multiprocessing dummy` in the `import` statement |
Who sent deserters families to concentration camps? | Germans |
Python Writing Weird Unicode to CSV I am attempting to extract article information using the python <a href="https://github com/codelucas/newspaper" rel="nofollow">newspaper3k</a> package and then write to a CSV file While the info is downloaded correctly I am having issues with the output to CSV I do not think I fully understand unicode despite my efforts to read about it ````from newspaper import Article Source import csv first_article = Article(url="http://www bloomberg com/news/articles/2016-09-07/asian-stock-futures-deviate-as-s-p-500-ends-flat-crude-tops-46") first_article download() if first_article is_downloaded: first_article parse() first_article nlp article_array = [] collate = {} collate['title'] = first_article title collate['content'] = first_article text collate['keywords'] = first_article keywords collate['url'] = first_article url collate['summary'] = first_article summary print(collate['content']) article_array append(collate) keys = article_array[0] keys() with open('bloombergtest csv' 'w') as output_file: csv_writer = csv DictWriter(output_file keys) csv_writer writeheader() csv_writer writerows(article_array) output_file close() ```` When I print collate['content'] which is first_article text the console outputs the article's content just fine Everything shows up correctly apostrophes and all When I write to the CVS the content cell text has odd characters in it For example: ââ¬ÅAt the end of the day Europeââ¬â¢s economy isnââ¬â¢t in great shape inflation doesnââ¬â¢t look exciting and there are a bunch of political risks to reckon with So far I have tried: ````with open('bloombergtest csv' 'w' encoding='utf-8') as output_file: ```` to no avail I also tried utf-16 instead of 8 but that just resulted in the cells writing in an odd order It did not create the cells correctly in the CSV although the output looked correct I have also tried encode('utf-8') are various variable but nothing has worked What is going on? Why would the console print the text correctly while the CSV file has odd characters? How can I fix this? | That is most probably a problem with the software that you use to open or print the CSV file - it does not "understand" that CSV is encoded in UTF-8 and assumes ASCII latin-1 ISO-8859-1 or a similar encoding for it You can aid that software in recognizing the CSV file's encoding by <a href="http://stackoverflow com/a/934203/6394138">placing a BOM sequence</a> in the beginning of your file (which in general is not recommended for UTF-8) |
I want to pip install myFile env I have a env file that I used to create a virtual environment I want to install the same packages (as specified in the env file) but this time I do not want it to be a virtual environment How can I do this? Many thanks Note: A env file can be used by miniconda or anaconda to create virtual environments like so: ````conda create --name optimus --file alpha env ```` then you can run ````source activate optimus ```` to activate your virtualEnv But how can I do something similar to: ````pip install -r myFile env ```` to install all packages specified in myFile env but not in a virtual environment Here is my alpha env file: ````cairo=1 12 2=2 dateutil=2 1=py27_2 freetype=2 4 10=0 numpy=1 6 2=py27 4 ```` | If you have access to your original virtual env or can create a new one as you describe I think a very simple solution would be to simply create a requirements txt file This is simply a file that names all the packages that you have installed in a specific python environment The file can be created by simply running ````pip freeze > requirements txt ```` This will create a file in your working directory called requirements txt You have to have your virtual environment active To then install the packages in your new environment you just have to enter it (deactivate your virtualenv or what ever you need to do) and run ````pip install -r requirements txt ```` I have never seen a env file but by the sound of it it could actually be exactly the same as a requirements txt file but under a different name See if the output of pip freeze looks the same (as far as format etc) as what you have in your env file In that case you could also just run the command you would in your virtual env ie ````pip install -r myFile env ```` EDIT: After seeing your env file output I am convinced that you can simply run the pip install -r myFile env command |
Regex OR expression in Python I am new to regex expressions and to python How can I write a script in python where it finds multiple spaces or tabs and replace them with single space how do I write `or` expression? I wrote the line below for multiple spaces how do i include the tab too? ````ModCon = re sub('\s{2 }' ' ' content) ```` | Try this ````ModCon = re sub('(\ |\t)+' ' ' content) ```` If there is one or more spaces or tabs it becomes only one |
Implementing "Starts with" and "Ends with" queries with Google App Engine Am wondering if anyone can provide some guidance on how I might implement a starts with or ends with query against a Datastore model using Python? In pseudo code it would work something like Query for all entities A where property P starts with X or Query for all entities B where property P ends with X Thanks Matt | Seems you cannot do it for the general case but can do it for prefix searches (starts with): <a href="http://stackoverflow com/questions/1402769/wildcard-search-on-appengine-in-python">http://stackoverflow com/questions/1402769/wildcard-search-on-appengine-in-python</a> |
python socket connect timeout error in mulithread or multiprocess Like the following I would like to communicate with many PC's in a specific IP range ````My PC ---+-----> Client A PC -----> Client B PC -----> Client C PC -----> Client Z PC ```` Because there are too many clients to communicate I tried it by mulit-threading socket connect() continuously produces time-out error If I try it in a single-thread there is no problem I googled and found the below : <a href="http://stackoverflow com/questions/1212716/python-interpreter-blocks-multithreaded-dns-requests">Python Interpreter blocks Multithreaded DNS requests?</a> saying that in some platform socket module could be thread unsafe So I changed my code into multi-processing However it still produces the same error In the following code sample test_single() finishes normal test_mp() and test_mt() both make time-out error Have you ever experienced such abnormal behavior? The testing environment is Windows XP SP3 python 2 5 4 Also tried on python 2 6 6 and 2 7 0 same error ````import multiprocessing import Queue import socket import threading PROCESS_NUM = 5 PORT = 8888 def search_proc(ip): try: csock = socket socket(socket AF_INET socket SOCK_STREAM) csock setsockopt(socket SOL_SOCKET socket SO_REUSEADDR 1) csock settimeout(5 0) csock connect((ip PORT)) csock shutdown(socket SHUT_RDWR) csock close() return ip "ok" except socket error message: return ip "fail" message def mp_connect(ip_range): pool = multiprocessing Pool( PROCESS_NUM ) for output in pool imap_unordered(search_proc ip_range): print output def test_mp(): ip_range = [] for i in range(256): ip_range append("192 168 123 %d"%(i )) mp_connect(ip_range) def test_mt(): def search_thread(ip_queue): while True: ip = ip_queue get() print search_proc(ip) ip_queue task_done() ip_queue = Queue Queue() for i in range(256): ip_queue put("192 168 123 %d"%(i )) for i in range(PROCESS_NUM): th = threading Thread(target=search_thread args=(ip_queue )) th setDaemon(True) th start() ip_queue join() def test_single(): ip_range = [] for i in range(256): print search_proc("192 168 123 %d"%(i )) if __name__ == "__main__": multiprocessing freeze_support() test_mp() #test_single() #test_mt() ```` | David Beazley has done some great research around the Python GIL and how that affects IO and multithreading You can find information about his research <a href="http://www dabeaz com/GIL/">here</a> <a href="http://blip tv/file/2232410">here</a> |
5 maximum values in a python dictionary I have a dictionary like this: ````A = {'a':10 'b':843 'c': 39 } ```` I want to get the 5 maximum values of this dict and store a new dict with this To get the maximum value I did: ````max(A iteritems() key=operator itemgetter(1))[0:] ```` Perhaps it is an easy task but I am stuck on it for a long time Please help!!! | You are close You can <them>sort</them> the list using <a href="http://docs python org/library/functions html#sorted">`sorted` <them><sup>[docs]</sup></them></a> and take the first five elements: ````newA = dict(sorted(A iteritems() key=operator itemgetter(1) reverse=True)[:5]) ```` See also: <a href="http://wiki python org/moin/HowTo/Sorting/">Python Sorting HowTo</a> |
Python: Read file with list as list I have placed a list in a text file I want python to read the text file and return the contents as a list However it is instead reading the content as a string: Text file: ````['a' 'b' 'c'] ```` Python: ````ids=[] writtenFile =open('file txt') readFile=writtenFile read() ids= readFile writtenFile close() print ids ```` What is returned is ['a' 'b' 'c'] as a string not as a list or just text Is there a way I can retrieve ['a' 'b' 'c'] from the text file and then store this in the ids string so that ids is a list ['a' 'b' 'c'] and not the string ? "['a' 'b' 'c']"? | Use `ast literal_eval` to literally evaluate the contents of file as is written though really a string: ````data = ast literal_eval(open('data txt') read()) # create file read contents evaluate ```` |
Django CONN_MAX_AGE option does not open persistent connection I set DATABASE setting like below and run Django App ````DATABASES = { 'default': { 'ENGINE': 'django db backends oracle' 'NAME': 'orcl' 'USER': 'smkim' 'PASSWORD': '1123' 'HOST': '168 192 15 18' 'PORT': '1521' 'CONN_MAX_AGE': 10 'OPTIONS': {'threaded': True} } } ```` To make sure that if Django open 10 persistent connections I send a SQL like the below ````SELECT username FROM v$session WHERE username='SMKIM'; ```` However this command just returns 2 records(This is because I spawn a process as a result two processes has one connection respectively) Why does Django only open 2 connections even I set 10 persistent connections? (ps the app is using a thread pool(5) ) | `'CONN_MAX_AGE'` sets the age of one connection before it is closed and not how many of them there should be see the <a href="https://docs djangoproject com/en/1 9/ref/settings/#std:setting-CONN_MAX_AGE" rel="nofollow">docs</a>: <blockquote> CONN_MAX_AGE Default: 0 The lifetime of a database connection in seconds Use 0 to close database connections at the end of each request â Djangoâs historical behavior â and None for unlimited persistent connections </blockquote> So the connection will be opened when Django needs one and there is no other open connection though DB can close such 'persistent' connection on it is side See the <a href="https://docs djangoproject com/en/1 9/ref/databases/#persistent-connections" rel="nofollow">docs section</a> for more details |
Cannot click on Login using Appium Can click manually ````Appium 1 5 0 Xcode 7 3 IOS 10 11 4 OSX EI Capitan Using on:Simulator iOS 8 1 ```` Facing a strange issue I can click via touchpad but not through Appium <strong>Appium Logs:</strong> ````[debug] [Instruments] [INST] 2016-04-19 04:30:54 0000 Debug: Got new command 14 from instruments: au tapById('3') [debug] [Instruments] [INST] 2016-04-19 04:30:54 0000 Debug: evaluating au tapById('3') [debug] [Instruments] [INST] 2016-04-19 04:30:54 0000 Debug: UIAButton tap() [debug] [Instruments] [INST] 2016-04-19 04:30:54 0000 Debug: UIAButton scrollToVisible() [iOSLog] [IOS_SYSLOG_ROW] Apr 19 10:00:54 Macbook local securityd[29291]: SecTaskCopyAccessGroups No keychain access group specified whilst running in simulator falling back to default set [iOSLog] [IOS_SYSLOG_ROW] Apr 19 10:00:54 Macbook local TT Mobile[29305]: *** -[NSKeyedUnarchiver initForReadingWithData:]: data is empty; did you forget to send -finishEncoding to the NSKeyedArchiver? [iOSLog] [IOS_SYSLOG_ROW] Apr 19 10:00:54 Macbook local securityd[29291]: SecTaskCopyAccessGroups No keychain access group specified whilst running in simulator falling back to default set [debug] [Instruments] [INST] 2016-04-19 04:30:54 0000 Debug: evaluation finished [debug] [Instruments] [INST] 2016-04-19 04:30:54 0000 Debug: responding with: [debug] [Instruments] [INST] 2016-04-19 04:30:54 0000 Debug: Running system command #15: /usr/local/bin/node /usr/local/lib/node_modules/appium/node_modules/appium-uiauto/build/lib/bin/command-proxy-client js /var/folders/4x/vy1bbyh92l9czkyswl5wypt80000gn/T/instruments_sock 2 {"status":0 "value":""} [debug] [UIAuto] Socket data received (25 bytes) [debug] [UIAuto] Got result from instruments: {"status":0 "value":""} [MJSONWP] Responding to client with driver click() result: null [HTTP] <-- POST /wd/hub/session/3957fc67-82da-4e57-b920-005ee0228cd7/element/3/click 200 1231 ms - 76 [HTTP] -> POST /wd/hub/session/3957fc67-82da-4e57-b920-005ee0228cd7/element [MJSONWP] Calling AppiumDriver findElement() with args: ["id" "LOG IN" "3957fc67-82da-4e57-b920-005ee0228cd7"] [debug] [iOS] Executing iOS command 'findElement' [debug] [BaseDriver] Waiting up to 60000 ms for condition [debug] [UIAuto] Sending command to instruments: au getElementByAccessibilityId('LOG IN') [iOSLog] [IOS_SYSLOG_ROW] Apr 19 10:00:55 Macbook local lsd[29289]: LaunchServices: Currently 0 installed placeholders: ( [iOSLog] [IOS_SYSLOG_ROW] ) [debug] [Instruments] [INST] 2016-04-19 04:30:55 0000 Debug: Got new command 15 from instruments: au getElementByAccessibilityId('LOG IN') [debug] [Instruments] [INST] 2016-04-19 04:30:55 0000 Debug: evaluating au getElementByAccessibilityId('LOG IN') [debug] [Instruments] [INST] 2016-04-19 04:30:55 0000 Debug: evaluation finished [debug] [Instruments] [INST] 2016-04-19 04:30:55 0000 Debug: Lookup returned [object UIAButton] with the name "LOG IN" (id: 4) [debug] [Instruments] [INST] 2016-04-19 04:30:55 0000 Debug: responding with: [debug] [Instruments] [INST] 2016-04-19 04:30:55 0000 Debug: Running system command #16: /usr/local/bin/node /usr/local/lib/node_modules/appium/node_modules/appium-uiauto/build/lib/bin/command-proxy-client js /var/folders/4x/vy1bbyh92l9czkyswl5wypt80000gn/T/instruments_sock 2 {"status":0 "value":{"ELEMENT":"4"}} [debug] [UIAuto] Socket data received (38 bytes) [debug] [UIAuto] Got result from instruments: {"status":0 "value":{"ELEMENT":"4"}} [MJSONWP] Responding to client with driver findElement() result: {"ELEMENT":"4"} [HTTP] <-- POST /wd/hub/session/3957fc67-82da-4e57-b920-005ee0228cd7/element 200 1344 ms - 87 [HTTP] -> POST /wd/hub/session/3957fc67-82da-4e57-b920-005ee0228cd7/element/4/click [MJSONWP] Calling AppiumDriver click() with args: ["4" "3957fc67-82da-4e57-b920-005ee0228cd7"] [debug] [iOS] Executing iOS command 'click' [debug] [UIAuto] Sending command to instruments: au tapById('4') [debug] [Instruments] [INST] 2016-04-19 04:30:56 0000 Debug: Got new command 16 from instruments: au tapById('4') [debug] [Instruments] [INST] 2016-04-19 04:30:56 0000 Debug: evaluating au tapById('4') [debug] [Instruments] [INST] 2016-04-19 04:30:56 0000 Debug: UIAButton tap() [debug] [Instruments] [INST] 2016-04-19 04:30:57 0000 Debug: evaluation finished [debug] [Instruments] [INST] 2016-04-19 04:30:57 0000 Debug: responding with: [debug] [Instruments] [INST] 2016-04-19 04:30:57 0000 Debug: Running system command #17: /usr/local/bin/node /usr/local/lib/node_modules/appium/node_modules/appium-uiauto/build/lib/bin/command-proxy-client js /var/folders/4x/vy1bbyh92l9czkyswl5wypt80000gn/T/instruments_sock 2 {"status":0 "value":""} [debug] [UIAuto] Socket data received (25 bytes) [debug] [UIAuto] Got result from instruments: {"status":0 "value":""} [MJSONWP] Responding to client with driver click() result: null [HTTP] <-- POST /wd/hub/session/3957fc67-82da-4e57-b920-005ee0228cd7/element/4/click 200 1164 ms - 76 [HTTP] -> POST /wd/hub/session/3957fc67-82da-4e57-b920-005ee0228cd7/element ```` <strong>XML of the App</strong> <div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override">`<?xml version="1 0" encoding="UTF-8"?> <AppiumAUT> <UIAApplication name="TT Mobile α" label="TT Mobile α" value="" dom="" enabled="true" valid="true" visible="true" hint="" path="/0" x="0" y="20" width="320" height="548"> <UIAWindow name="" label="" value="" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0" x="0" y="0" width="320" height="568"> <UIAImage name="bg-login" label="" value="" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/0" x="0" y="0" width="320" height="568"> </UIAImage> <UIATextField name="" label="" value="Email address" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/1" x="27 5" y="178" width="265" height="40"> <UIATextField name="" label="" value="Email address" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/1/0" x="27 5" y="178" width="265" height="40"> </UIATextField> </UIATextField> <UIASecureTextField name="" label="" value="Password" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/2" x="27 5" y="218" width="265" height="40"> <UIASecureTextField name="" label="" value="Password" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/2/0" x="27 5" y="218" width="265" height="40"> </UIASecureTextField> </UIASecureTextField> <UIAButton name="unchecked" label="unchecked" value="" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/3" x="27 5" y="280" width="28" height="25 5"> </UIAButton> <UIAStaticText name="Remember me" label="Remember me" value="Remember me" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/4" x="59 5" y="282 5" width="110" height="21"> </UIAStaticText> <UIAButton name="forgot password?" label="forgot password?" value="" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/5" x="186 5" y="282 5" width="106" height="21"> </UIAButton> <UIAButton name="LOG IN" label="LOG IN" value="" dom="" enabled="false" valid="true" visible="true" hint="" path="/0/0/6" x="27 5" y="341" width="265" height="43"> </UIAButton> <UIAActivityIndicator name="In progress" label="In progress" value="1" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/7" x="150" y="352 5" width="20" height="20"> <UIAImage name="" label="" value="" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/7/0" x="150" y="352 5" width="20" height="20"> </UIAImage> </UIAActivityIndicator> <UIAStaticText name="Don&apos;t have an ID?" label="Don&apos;t have an ID?" value="Don&apos;t have an ID?" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/8" x="27 5" y="396" width="151" height="24"> </UIAStaticText> <UIAButton name="Sign Up" label="Sign Up" value="" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/9" x="183 5" y="396 5" width="78" height="23 5"> </UIAButton> <UIAButton name="Demo" label="Demo" value="" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/10" x="27 5" y="485" width="265" height="33"> </UIAButton> <UIAImage name="login-ttmobile" label="" value="" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/0/11" x="34" y="71" width="252" height="34"> </UIAImage> <UIAStaticText name="TWO-FACTOR AUTHENTICATION" label="TWO-FACTOR AUTHENTICATION" value="TWO-FACTOR AUTHENTICATION" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/12" x="28" y="154" width="264" height="21"> </UIAStaticText> <UIASecureTextField name="" label="" value="Enter code" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/13" x="27 5" y="250" width="265" height="40"> <UIASecureTextField name="" label="" value="Enter code" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/13/0" x="27 5" y="250" width="265" height="40"> </UIASecureTextField> </UIASecureTextField> <UIAButton name="VERIFY" label="VERIFY" value="" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/14" x="27 5" y="314" width="265" height="43"> <UIAStaticText name="VERIFY" label="VERIFY" value="VERIFY" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/14/0" x="125 5" y="321" width="68" height="29"> </UIAStaticText> </UIAButton> <UIAActivityIndicator name="In progress" label="In progress" value="1" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/15" x="150" y="325 5" width="20" height="20"> </UIAActivityIndicator> <UIAButton name="unchecked" label="unchecked" value="" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/16" x="27 5" y="372" width="28" height="25 5"> <UIAImage name="unchecked png" label="" value="" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/16/0" x="29" y="373 5" width="24 5" height="22"> </UIAImage> </UIAButton> <UIAStaticText name="Remember device for 30 days" label="Remember device for 30 days" value="Remember device for 30 days" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/17" x="59 5" y="374 5" width="233" height="21"> </UIAStaticText> <UIAButton name="BACK" label="BACK" value="" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/18" x="27 5" y="445 5" width="102" height="30"> <UIAImage name="icon-swipeleft png" label="" value="" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/18/0" x="27 5" y="452 5" width="9 5" height="15 5"> </UIAImage> <UIAStaticText name="BACK" label="BACK" value="BACK" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/18/1" x="44" y="451 5" width="35" height="18"> </UIAStaticText> </UIAButton> <UIAButton name="request new code" label="request new code" value="" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/19" x="186 5" y="450" width="106" height="21"> <UIAStaticText name="request new code" label="request new code" value="request new code" dom="" enabled="true" valid="true" visible="false" hint="" path="/0/0/19/0" x="187 5" y="451" width="105" height="18"> </UIAStaticText> </UIAButton> </UIAWindow> <UIAWindow name="" label="" value="" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/1" x="0" y="0" width="320" height="568"> <UIAStatusBar name="" label="" value="" dom="" enabled="true" valid="true" visible="true" hint="" path="/0/1/0" x="0" y="0" width="320" height="20"> <UIAElement name="Swipe down with three fingers to reveal the notification center Swipe up with three fingers to reveal the control center Double-tap to scroll to top" label="" value="" dom="" enabled="true" valid="true" visible="true" hint="Swipe down with three fingers to reveal the notification center Swipe up with three fingers to reveal the control center Double-tap to scroll to top" path="/0/1/0/0" x="6" y="0" width="38" height="20"> </UIAElement> <UIAElement name="3 of 3 Wi-Fi bars" label="3 of 3 Wi-Fi bars" value="" dom="" enabled="true" valid="true" visible="true" hint="Swipe down with three fingers to reveal the notification center Swipe up with three fingers to reveal the control center Double-tap to scroll to top" path="/0/1/0/1" x="49" y="0" width="13" height="20"> </UIAElement> <UIAElement name="10:19 AM" label="10:19 AM" value="" dom="" enabled="true" valid="true" visible="true" hint="Swipe down with three fingers to reveal the notification center Swipe up with three fingers to reveal the control center Double-tap to scroll to top" path="/0/1/0/2" x="135" y="0" width="50" height="20"> </UIAElement> <UIAElement name="100% battery power" label="100% battery power" value="" dom="" enabled="true" valid="true" visible="true" hint="Swipe down with three fingers to reveal the notification center Swipe up with three fingers to reveal the control center Double-tap to scroll to top" path="/0/1/0/3" x="290" y="0" width="25" height="20"> </UIAElement> </UIAStatusBar> </UIAWindow> </UIAApplication> </AppiumAUT>```` </div> </div> <strong>Some logs which i could not decipher:</strong> ````[IOS_SYSLOG_ROW] Apr 19 10:00:40 Macbook com apple CoreSimulator SimDevice 55BBCE9D-8F75-47DC-BC87-3DD28FB4F874 launchd_sim[29262] (com apple imfoundation IMRemoteURLConnectionAgent): The _DirtyJetsamMemoryLimit key is not available on this platform [iOSLog] [IOS_SYSLOG_ROW] Apr 19 10:00:41 Macbook local filecoordinationd[29326]: (Error) FileProvider: Could not load bundle com apple CloudDocsFileProvider Error: The bundle âCloudDocsFileProviderâ couldnât be loaded because it is damaged or missing necessary resources [iOSLog] [IOS_SYSLOG_ROW] Apr 19 10:00:54 Macbook local securityd[29291]: SecTaskCopyAccessGroups No keychain access group specified whilst running in simulator falling back to default set [iOSLog] [IOS_SYSLOG_ROW] Apr 19 10:00:54 Macbook local TT Mobile[29305]: *** -[NSKeyedUnarchiver initForReadingWithData:]: data is empty; did you forget to send -finishEncoding to the NSKeyedArchiver? [iOSLog] [IOS_SYSLOG_ROW] Apr 19 10:00:54 Macbook local securityd[29291]: SecTaskCopyAccessGroups No keychain access group specified whilst running in simulator falling back to default set ```` Any clues or help? Build created using xcode for arch i386 | I was using `set_value` on ios for `password` which does not use `keyboard` The `LOG IN` button is disabled until there is some text in `password` field So somehow `set_value` was not generating the event Problem solved by using `send_keys` which uses `keyboard` |
Exception Value: type object 'Discipline' has no attribute 'description' So I am building my first Django project using the Django Rest Framework and I have these 3 models on it: ````class Student(models Model): user = models OneToOneField(User unique=True) ra = models IntegerField() class Discipline (models Model): description = models CharField(max_length=150) professor = models ForeignKey(Professor related_name='disciplines') learners = models ManyToManyField('students Student' through='enrollments enrollment' related_name='disciplines') class Enrollment (models Model): discipline = models ForeignKey('disciplines Discipline') student = models ForeignKey(Student) enroll_date = models DateField(auto_now_add=True) ```` And for these models I have these serializers: ````class StudentSerializer (serializers ModelSerializer): ra = serializers IntegerField(source=Student ra) disciplines = EnrolledDisciplinesSerializer(source="enrollment_set" many=True) activities = RealizedActivitiesSerializer(source='activities_set' many=True) class Meta: model = User fields = ('id' 'username' 'email' 'password' 'ra' 'disciplines' 'activities') class DisciplineSerializer (serializers ModelSerializer): professor = serializers StringRelatedField() learners = LearnersSerializer(source="enrollment_set" many=True) class Meta: model = Discipline fields = ('id' 'description' 'professor' 'learners') class EnrolledDisciplinesSerializer(serializers ModelSerializer): id = serializers ReadOnlyField(source=Discipline pk) description = serializers ReadOnlyField(source=Discipline description) class Meta: model = Enrollment fields = ('id' 'description' 'enroll_date') class LearnersSerializer(serializers ModelSerializer): id = serializers ReadOnlyField(source=Student pk) ra = serializers ReadOnlyField(source=Student ra) class Meta: model = Enrollment fields = ('id' 'ra' 'enroll_date') ```` And on my views py for my students app I have the following code: ````class StudentList (generics ListCreateAPIView): model = Student serializer_class = StudentSerializer permission_classes = [ permissions IsAuthenticatedOrReadOnly ] class StudentDetail (generics RetrieveAPIView): model = Student serializer_class = StudentSerializer class StudentDisciplineList (generics ListAPIView): model = Enrollment serializer_class = EnrolledDisciplinesSerializer def get_queryset(self): queryset = super(StudentDisciplineList self) get_queryset() return queryset filter(student__pk=self kwargs get('pk')) class StudentActivitiesList (generics ListAPIView): model = Activity serializer_class = ActivitiesSerializer def get_queryset(self): queryset = super(StudentActivitiesList self) get_queryset() return queryset filter(student__pk=self kwargs get('pk')) ```` After creating the views I added the following to my urls py file in my students app: ````url_patterns = [ '' url(r'^/(?P<pk>\d+)/disciplines$' StudentDisciplineList as_view() name='studentdiscipline-list') url(r'^/(?P<pk>\d+)/activities$' StudentActivitiesList as_view() name='studentactivities-list') url(r'^/(?P<pk>\d+)$' StudentDetail as_view() name='student-detail') url(r'^$' StudentList as_view() name='student-list') ] ```` Then I added this to my main urls py file: ````import students urls urlpatterns = [ url(r'^admin/' include(admin site urls)) url(r'^students/' include(students urls)) ] ```` After doing this I went to <a href="http://127 0 0 1:8000/students" rel="nofollow">http://127 0 0 1:8000/students</a> and got the following: ````File "C:\Users\Douglas\tg_project\enrollments\serializers py" in EnrolledDisciplinesSerializer 9 description = serializers ReadOnlyField(source=Discipline description) Exception Type: AttributeError at /admin Exception Value: type object 'Discipline' has no attribute 'description' ```` I have already searched about this on both Google and StackOverflow but I could not find something to help me I also looked through the entire code to see if I have not made any typos but it seems that everything is ok I am really thankful for any help to solve this problem | The `source` should be a string containing the attributes to get from the `Enrollment` instance So in your `EnrolledDisciplinesSerializer` for the `description` you need `'discipline description'` `discipline` (lower-cased) is the attribute name to access the discipline for that enrollment `description` the name to get the description for that Discipline instance Same for the other fields Django uses metaclasses to construct models The way this works the fields you define in the model do not end up as attributes on the class That means the `Discipline` class will not have an attribute `Discipline description` Only instances of `Discipline` have a `description` attribute |
Who launched Sputnik 1? | the Soviet Union. |
Python - Split pdf by pages I am using `PyPdf2` to split large `PDF` to pages The problem is that this process is very slow This is the code i use: ````import os from PyPDF2 import PdfFileWriter PdfFileReader with open(input_pdf_path "rb") as input_file: input_pdf = PdfFileReader(input_file) directory = "%s/paging/" % os path dirname(input_pdf_path) if not os path exists(directory): os makedirs(directory) page_files = [] for i in range(0 input_pdf numPages): output = PdfFileWriter() output addPage(input_pdf getPage(i)) file_name = "%s/#*#*#*##-%s pdf" % (directory i) page_files append(file_name) with open(file_name "wb") as outputStream: output write(outputStream) ```` Using this code it takes about 35 to 55 seconds to split a 177 pages pdf Is there a way i can improve this code? Is there any other library that is more suitable for this job? | <h3>Refactoring</h3> I have refactored the code like this: ````import os import PyPDF2 def split_pdf_pages(input_pdf_path target_dir fname_fmt=you"{num_page:04d} pdf"): if not os path exists(target_dir): os makedirs(target_dir) with open(input_pdf_path "rb") as input_stream: input_pdf = PyPDF2 PdfFileReader(input_stream) if input_pdf flattenedPages is None: # flatten the file using getNumPages() input_pdf getNumPages() # or call input_pdf _flatten() for num_page page in enumerate(input_pdf flattenedPages): output = PyPDF2 PdfFileWriter() output addPage(page) file_name = os path join(target_dir fname_fmt format(num_page=num_page)) with open(file_name "wb") as output_stream: output write(output_stream) ```` <them>note:</them> it is difficult to do better⦠<h3>Profiling</h3> With this `split_pdf_pages` function you can do profiling: ````import cProfile import pstats import io pdf_path = "path/to/file pdf" directory = os path join(os path dirname(pdf_path) "pages") pr = cProfile Profile() pr enable() split_pdf_pages(pdf_path directory) pr disable() s = io StringIO() ps = pstats Stats(pr stream=s) sort_stats('cumulative') ps print_stats() print(s getvalue()) ```` Run the profiling with your own PDF file and analyse the result⦠<h3>Profiling result</h3> The profiling gave me this result: ```` 159696614 function calls (155047949 primitive calls) in 57 818 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 1 0 899 0 899 57 818 57 818 $HOME/workspace/pypdf2_demo/src/pypdf2_demo/split_pdf_pages py:14(split_pdf_pages) 2136 0 501 - --- 53 851 0 025 $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/pdf py:445(write) 103229/96616 1 113 - --- 36 924 - --- $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/generic py:544(writeToStream) 27803 9 066 - --- 25 381 0 001 $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/generic py:445(writeToStream) 4185807/2136 5 054 - --- 14 635 0 007 $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/pdf py:541(_sweepIndirectReferences) 50245/41562 0 117 - --- 9 028 - --- $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/pdf py:1584(getObject) 31421489 6 898 - --- 8 193 - --- $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/utils py:231(b_) 56779 2 070 - --- 7 882 - --- $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/generic py:142(writeToStream) 8683 0 322 - --- 7 020 0 001 $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/pdf py:1531(_getObjectFromStream) 459978/20068 1 098 - --- 6 490 - --- $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/generic py:54(readObject) 26517/19902 0 484 - --- 6 360 - --- $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/generic py:553(readFromStream) 27803 3 893 - --- 5 565 - --- $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/generic py:1162(encode_pdfdocencoding) 15735379 4 173 - --- 5 412 - --- $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/utils py:268(chr_) 3617738 2 105 - --- 4 956 - --- $HOME/virtualenv/py3-pypdf2_demo/lib/site-packages/PyPDF2/generic py:265(writeToStream) 18882076 3 856 - --- 3 856 - --- {method 'write' of '_io BufferedWriter' objects} ```` It appears that: - The `writeToStream` function is heavily called but I do not know how to optimize this - The `write` method directly write to the stream not in memory => an optimisation is possible <h3>Improvement</h3> Serialize the PDF page in a buffer (in memory) then write the buffer to the file: ````buffer = io BytesIO() output write(buffer) with open(file_name "wb") as output_stream: output_stream write(buffer getvalue()) ```` I processed the 2135 pages in 35 seconds instead of 40 Poor optimization indeed :-( |
How to sort dictionary on first element of the key (tuple) I have a dictionary where each key is a tuple of values I want to use the `sorted()` method to sort the dictionary on the very first element of my tuple My code looks like this: ````def mapData(header_list dict_obj): master_dict = {} client_section_list = [] for element in header_list: for row in dict_obj: if (row['PEOPLE_ID'] row['DON_DATE']) == element: client_section_list append(row) element = list(element) element_list = [client_section_list[0]['DEDUCT_AMT'] client_section_list[0]['ND_AMT'] client_section_list[0]['DEDUCT_YTD'] client_section_list[0]['NONDEDUCT_YTD'] ] try: element_list append((float(client_section_list[0]['DEDUCT_YTD']) float(client_section_list[0]['NONDEDUCT_YTD']) )) except ValueError: pass element extend(element_list) element = tuple(element) master_dict[element] = client_section_list client_section_list = [] return sorted(master_dict key=lambda key: key[master_dict[(1)]] ```` The last line is where I am trying to find a way to sort it My tuple looks like this: ````(312178078 6/22/15 25 0 25 0 25 0) ```` | As @tobias_k has mentioned `sorted` sorts tuples by its elements with decreasing priority e g if you take a tuple `(a b c)` the highest sorting priority goes to `a` then goes `b` etc (by default `sorted` uses object's comparison methods and this is how `tuple` comparison works) So `sorted(master_dict)` is all you need if you want a list of sorted keys yet I believe you really want to leave the values ````sorted(master_dict items() key=lambda key: key[0]) ```` `dict items` returns tuples of form `(key value)` so here you need to specify the sorting `key` |
What is Spielberg's net worth? | more than $3 billion |
how to run py files in command prompt (Windows 7) I am facing an extremly tiresome and difficult problem for me one for which i was anable to find any solution for quite some time my google searching skills failing me miserably I have tried to open a py file with a single line of code in it print "Hello" with various methods including IDLE (Python GUI) Python (Command Line) and finally command prompt but to no avail I was eventually able to set the PATH variable in Windows and access the python interpreter through the cmd but when typing the name of the file I keep getting the same error message: ````>>> new pyTraceback (most recent call last): File "<stdin>" line 1 in <module> NameError: name 'new ' is not defined ```` What could I do to solve it and finally be able to run my py file? | You should use the plain CMD (command prompt) console not the python interpreter and then type: ````python new py ```` Hope that works! |
Opening raw images on Python resulting in a different image compared to ImageJ I wrote this script to open a raw image and do some processing ````import numpy as np import matplotlib pyplot as plt PATH = "C:\Users\Documents\script_testing_folder\\" IMAGE_PATH = PATH "simulation01\\15x15_output_det_00001_raw_df_00000 bin" raw_image = np fromfile(IMAGE_PATH dtype=np uint64) raw_image shape = (15 15) plt imshow(raw_image cmap = 'gray') total_intensity = ndimage sum(raw_image) print total_intensity plt show() ```` Using this script I get an Image such as this: <a href="http://i stack imgur com/DqJP3 jpg" rel="nofollow"><img src="http://i stack imgur com/DqJP3 jpg" alt="enter image description here"></a> In contrast when I open the same image on ImageJ(file>import>raw (64bit real 15x15 length and width)) I have this: <a href="http://i stack imgur com/JUprq jpg" rel="nofollow"><img src="http://i stack imgur com/JUprq jpg" alt="enter image description here"></a> I have tried looking around but I am not sure where I am going wrong when trying to reproduce the same image on python Any help would be greatly appreciated Additionally when I sum the intensity in the image using: ````total_intensity = ndimage sum(raw_image) print total_intensity ```` y I get 4200794456581938015 whereas on ImageJ I get 0 585 I am not sure where I am going wrong on these steps Thanks ! Edit: The original file if anyone wants to reproduce the results I got <a href="https://www dropbox com/s/po82z4uf2ku7k0e/15x15_output_det_00001_raw_df_00000 bin?dl=0" rel="nofollow">https://www dropbox com/s/po82z4uf2ku7k0e/15x15_output_det_00001_raw_df_00000 bin?dl=0</a> | The problem is the <a href="https://en wikipedia org/wiki/Endianness" rel="nofollow">endianness</a> of your data (the order of the single bytes of a 64bit float) Fortunately numpy has the <a href="http://docs scipy org/doc/numpy/user/basics byteswapping html" rel="nofollow">functionality</a> to solve this issue: ````import numpy as np import matplotlib pyplot as plt # load the image raw_image = np fromfile('15x15_output_det_00001_raw_df_00000 bin') raw_image = np reshape(raw_image (15 15)) # swap the byte order raw_image = raw_image byteswap() # output the sum of the intensities to check total_intensity = np sum(raw_image) print "total intensity:" total_intensity # plot the image plt imshow(raw_image cmap = 'gray' interpolation='nearest') plt show() ```` Output: <blockquote> total intensity: 0 585123878711 </blockquote> Result: <a href="http://i stack imgur com/yqVvL png" rel="nofollow"><img src="http://i stack imgur com/yqVvL png" alt="enter image description here"></a> |
Cannot call save() in Django Model? Gets: AttributeError: 'unicode' object has no attribute 'save' Thanks for the time for helping me out I am pretty new to django and python So I have a model that I am trying to pull some data from another model to build out a landing page of sorts I was trying to make it completely customizatable in the admin but I discovered for what I wanted do I was going to have to involve AJAX I have scrapped that and resorted to mostly removing the admin customization because this is really just for my own personal site So to boil down the overall goal: - There are many "gallery" pages I want to pull the first image from - Each gallery on my "landing" page will be a single image from each gallery title and url to the gallery This is part of my model: class AggeragateImages(Orderable): ```` aggeragate = models ForeignKey("AggeragatePage" related_name="thumbnails") gallery_titles = models CharField(editable=False max_length=1000) gallery_slug = models CharField(editable=False max_length=1000) def getGallery(): """ Returns PK of all Gallery content type pages """ galleryPK = [] for e in Page objects filter(content_model='gallery'): galleryPK append(e pk) return galleryPK galleryPK = getGallery() for e in galleryPK: gallery_titles = Gallery objects get(pk=e) titles gallery_titles save() gallery_slug = Gallery objects get(pk=e) slug gallery_slug save() def __unicode__(self): return self name ```` However why I run a syncdb I get: AttributeError: 'unicode' object has no attribute 'save' I have also trying doing this through the interactive she will to and I get the same error when calling 'save()' Am I really far off base? I really appreciate your help | The problem is at: ````gallery_titles = Gallery objects get(pk=e) titles gallery_titles save() ```` When you do `Gallery objects get(pk=e)` it returns you a model instance however then you retrieve it is `titles` attribute which I guess is a string (`unicode`) So at that point `gallery_titles` is a sting which you try to save on the next line but `unicode` class does not have a method `save` which causes an error As a side note it is probably not the best idea to put logic code directly inside a class definition You can factor your logic into class methods which would be much more appropriate When you call a class method inside it is definition you are still defining a class attribute |
Python cannot create mpf from phi After fixing the imports in the previous question (<a href="http://stackoverflow com/questions/13336048/python-attributeerrorcos">Python AttributeError:cos</a>) and changing a little bit the functions using the sympy ones: ````from sympy import * from sympy import Symbol from sympy solvers import nsolve # Symbols theta = Symbol('theta') phi = Symbol('phi') phi0 = Symbol('phi0') H0 = Symbol('H0') # Constants a = 0 05 b = 0 05**2/(8*pi*1e-7) c = 0 001/(4*pi*1e-7) phi0 = 60*pi/180 H0 = -0 03/(4*pi*1e-7) def m(theta phi): return Matrix([[sin(theta)*cos(phi) sin(theta)*cos(phi) cos(phi)]]) def h(phi0): return Matrix([[cos(phi0) sin(phi0) 0]]) def k(theta phi phi0): return m(theta phi) dot(h(phi0)) def F(theta phi phi0 H0): return -(a*H0)*k(theta phi phi0)+b*(cos(theta)**2)+c*(sin(2*theta)**2)+sin(theta)**4*sin(2*phi)**2 def F_phi(theta phi phi0 H0): return simplify(different(F(theta phi phi0 H0) phi)) def G(phi): return F_phi(pi/2 phi phi0 H0) solution = nsolve(G(phi) phi) print solution ```` I get this Traceback: ````Traceback (most recent call last): File "Test py" line 31 in <module> solution = nsolve(G(phi) phi) File "/usr/lib64/python2 7/site-packages/sympy/solvers/solvers py" line 2050 in nsolve return findroot(f x0 **kwargs) File "/usr/lib64/python2 7/site-packages/mpmath/calculus/optimization py" line 908 in findroot x0 = [ctx convert(x0)] File "/usr/lib64/python2 7/site-packages/mpmath/ctx_mp_python py" line 662 in convert return ctx _convert_fallback(x strings) File "/usr/lib64/python2 7/site-packages/mpmath/ctx_mp py" line 561 in _convert_fallback raise TypeError("cannot create mpf from " repr(x)) TypeError: cannot create mpf from phi ```` | The second argument to `nsolve` should be an initial guess not a Symbol From the docstring ````Solve a nonlinear equation system numerically:: nsolve(f [args ] x0 modules=['mpmath'] **kwargs) f is a vector function of symbolic expressions representing the system args are the variables If there is only one variable this argument can be omitted x0 is a starting vector close to a solution ```` So you want something like `nsolve(G(phi) 0)` or `nsolve(G(phi) 3)` etc (depending on what solution you want) |
Where was the Thomson-Houston Electric Company based? | Lynn, Massachusetts |
Filter and sort music info on Google App Engine I have enjoyed building out a couple simple applications on the GAE but now I am stumped about how to architect a music collection organizer on the app engine In brief I cannot figure out how to filter on multiple properties while sorting on another Let us assume the core model is an Album that contains several properties including: - Title - Artist - Label - Publication Year - Genre - Length - List of track names - List of moods - Datetime of insertion into database Let us also assume that I would like to filter the entire collection using those properties and then sorting the results by one of: - Publication year - Length of album - Artist name - When the info was added into the database I do not know how to do this without running into the exploding index conundrum Specifically I would love to do something like: ````Albums all() filter('publication_year <' 1980) order('artist_name') ```` I know that is not possible but what is the workaround? This seems like a fairly general type of application The music albums could be restaurants bottles of wine or hotels I have a collection of items with descriptive properties that I would like to filter and sort Is there a best practice data model design that I am overlooking? Any advice? | As you say you cannot have an inequality condition on one field and an order by another (or inequalities on two fields etc etc) The workaround is simply to use the "best" inequality condition to get data in memory (where "best" means the one that is expected to yield the least data) and then further refine it and order it by Python code in your application Python's list comprehensions (and other forms of loops &c) list's `sort` method and the `sorted` built-in function the `itertools` module in the standard library and so on all help a lot to make these kinds of tasks quite simple to perform in Python itself |
selenium common exceptions StaleElementReferenceException: Message: stale element reference: element is not attached to the page document I use Python Beautiful Soup to move through DOM elements and Selenium to open page in chrome and ActionChains to scroll in page It worked fine but the website changed something and now I run into two kinds of error on the way it worked before and on a new way as a possible solution Old solution: ````submit_button = driver find_element_by_name('quantity') elementList = submit_button find_elements_by_tag_name("option") elementList[int(column)-1] click() ```` Old Error: ````Traceback (most recent call last): File "C:/Users/Felix_P/PycharmProjects/Price_Tool/Combination_14_6_2016 py" line 205 in <module> elementList[int(column)-1] click() File "C:\Python35-32\lib\site-packages\selenium\webdriver\remote\webelement py" line 75 in click self _execute(Command CLICK_ELEMENT) File "C:\Python35-32\lib\site-packages\selenium\webdriver\remote\webelement py" line 469 in _execute return self _parent execute(command params) File "C:\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver py" line 201 in execute self error_handler check_response(response) File "C:\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler py" line 193 in check_response raise exception_class(message screen stacktrace) selenium common exceptions ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated (Session info: chrome=51 0 2704 103) (Driver info: chromedriver=2 21 371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4) platform=Windows NT 6 1 SP1 x86_64) ```` New Solution: ````submit_button = driver find_element_by_name('quantity') elementList = submit_button find_elements_by_tag_name("option") actions move_to_element(elementList[int(column)-1]) click() perform() ```` New Error: ````Traceback (most recent call last): File "C:/Users/Felix_P/PycharmProjects/Price_Tool/Combination_14_6_2016 py" line 201 in <module> actions move_to_element(elementList[int(column)-1]) click() perform() File "C:\Python35-32\lib\site-packages\selenium\webdriver\common\action_chains py" line 72 in perform action() File "C:\Python35-32\lib\site-packages\selenium\webdriver\common\action_chains py" line 217 in <lambda> self _driver execute(Command MOVE_TO {'element': to_element id})) File "C:\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver py" line 201 in execute self error_handler check_response(response) File "C:\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler py" line 193 in check_response raise exception_class(message screen stacktrace) selenium common exceptions StaleElementReferenceException: Message: stale element reference: element is not attached to the page document (Session info: chrome=51 0 2704 103) (Driver info: chromedriver=2 21 371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4) platform=Windows NT 6 1 SP1 x86_64) ```` | I think I see the problem If you show all of your code it will probably show that last line is within a for loop that is navigating away from the page then coming back to the same page (or some ajax has refreshed that set of options on the page) The problem is that the page has reloaded so the target element from elementList does not exist any longer You will need to define your elementList by keeping track of a list of something like value on the option then use find_element within the loop to find each unique option element again |
Long-term Recurrent Convolutional Networks paper reproduction error in LSTM? I am trying to reproduce the <a href="http://arxiv org/abs/1411 4389" rel="nofollow">Long-term Recurrent Convolutional Networks paper </a> I have used their <a href="https://github com/LisaAnne/lisa-caffe-public/tree/lstm_video_deploy" rel="nofollow">given code</a> And followed their instructions and generated the single frame model But when trying to train the LSTM hybrid network it fails I have already made necessary changes as mentioned in the <a href="http://www eecs berkeley edu/~lisa_anne/LRCN_video" rel="nofollow">instructions </a> The command i run is the `caffe train -solver lstm_solver_flow prototxt -weights singleframe_flow/snaps/snapshots_singleFrame_flow_v2_iter_50000 caffemodel` the output I get is ````I0323 18:16:30 685951 9123 net cpp:205] This network produces output loss I0323 18:16:30 685967 9123 net cpp:446] Collecting Learning Rate and Weight Decay I0323 18:16:30 685976 9123 net cpp:218] Network initialization done I0323 18:16:30 685982 9123 net cpp:219] Memory required for data: 817327112 I0323 18:16:30 686339 9123 solver cpp:42] Solver scaffolding done I0323 18:16:30 686388 9123 caffe cpp:86] Finetuning from singleframe_flow/snaps/snapshots_singleFrame_flow_v2_iter_50000 caffemodel I0323 18:16:33 377488 9123 solver cpp:247] Solving lstm_joints I0323 18:16:33 377518 9123 solver cpp:248] Learning Rate Policy: step I0323 18:16:33 391726 9123 solver cpp:291] Iteration 0 Testing net (#0) Traceback (most recent call last): File "/home/anilil/projects/lstm/lisa-caffe-public/examples/LRCN_activity_recognition/sequence_input_layer py" line 220 in forward new_result_data = [None]*len(self batch_advancer result['data']) KeyError: 'data' terminate called after throwing an instance of 'boost::python::error_already_set' *** Aborted at 1458753393 (unix time) try "date -d @1458753393" if you are using GNU date *** PC: @ 0x7f243731bcc9 (unknown) *** SIGABRT (@0x23a3) received by PID 9123 (TID 0x7f24389077c0) from PID 9123; stack trace: *** @ 0x7f243731bd40 (unknown) @ 0x7f243731bcc9 (unknown) @ 0x7f243731f0d8 (unknown) @ 0x7f2437920535 (unknown) @ 0x7f243791e6d6 (unknown) @ 0x7f243791e703 (unknown) @ 0x7f243791e976 (unknown) @ 0x7f2397bb5bfd caffe::PythonLayer<>::Forward_cpu() @ 0x7f243821d87f caffe::Net<>::ForwardFromTo() @ 0x7f243821dca7 caffe::Net<>::ForwardPrefilled() @ 0x7f243822fd77 caffe::Solver<>::Test() @ 0x7f2438230636 caffe::Solver<>::TestAll() @ 0x7f243823837b caffe::Solver<>::Step() @ 0x7f2438238d5f caffe::Solver<>::Solve() @ 0x4071c8 train() @ 0x405701 main @ 0x7f2437306ec5 (unknown) @ 0x405cad (unknown) @ 0x0 (unknown) run_lstm_flow sh: line 8: 9123 Aborted (core dumped) GLOG_logtostderr=1 $TOOLS/caffe train -solver lstm_solver_flow prototxt -weights singleframe_flow/snaps/snapshots_singleFrame_flow_v2_iter_50000 caffemodel Done ```` This is my changed <a href="http://pastebin com/ZuRb3tQR" rel="nofollow">sequence_input_layer py</a> and <a href="http://pastebin com/Ha4S1ZBU" rel="nofollow">prototext</a> files My input train and test txts to the network is of this <a href="http://pastebin com/4gNPFssb" rel="nofollow">format</a> I think the main problem is the `##rearrange the data: The LSTM takes inputs as [video0_frame0 video1_frame0 ] but the data is currently arranged as [video0_frame0 video0_frame1 ]` I was not able to solve this is confused me quite a bit But I might be wrong | I encounter the same question I adapt several places in `sequence_input_layer py` and it works well for me at now: 1 I change line 95 and remove `%i` at the end since I do not know what it is used for i e change ` frames append(self video_dict[key]['frames'] %i) ` to ` frames append(self video_dict[key]['frames']) ` 2 I change line around 157 to make sure the `frames` variable is right for my data since the data directory of author is different of mine Hope this will be helpful |
ValueError: dictionary update sequence element #0 has length 1; 2 is required I am returning '5' for my computational field "old_default_code" and I am getting the following error: ````ValueError: dictionary update sequence element #0 has length 1; 2 is required ```` What am I doing wrong? Here is the Python code of the function: ````def _old_default_code(self cr uid ids name arg context=None): return '5' _columns = { 'old_default_code' : fields function(_old_default_code type='char' size=32 method=True store=False multi=False) } ```` and here is the XML code: ````<?xml version="1 0" encoding="utf-8"?> <openerp> <data> <!-- mrp_bom -> <record id="adamson_mrp_bom_form_view" model="ir ui view"> <field name="name">adamson mrp bom form view</field> <field name="model">mrp bom</field> <field name="type">form</field> <field name="inherit_id" ref="mrp mrp_bom_form_view" /> <field name="arch" type="xml"> <xpath expr="//notebook/page[@string='Components']/field/tree[@string='Components']/field[@name='sequence']" position="before" > <field name="old_default_code" /> <button class="oe_inline oe_stat_button" type="object" string="Go!" icon="gtk-go-forward" name="action_go" attrs="{'invisible':[('old_default_code' '=' '5')]}" /> </xpath> ```` | @Nebojsa The field function always expect a dictionary to be returned and in your case you are just return an "Integer" The default behaviour of the system is that it expects a dictionary where the key is the "id" of the record and value is the value you want to return For example: If you want to return '5' in your case and the record id is 2 then following will be the dictionary {2:5} Note: While doing calculation whatever ids you have got in your method for all those ids you should return a value in the dictionary even if no value can be found/calculated then you should return at least false against those ids but make sure you at least return some value against all the ids that you have got in your function Let me know if you find trouble in this Hope this helps |
git clone install in Python Is there a one-liner shortcut for: ````git clone https://github com/user/mypythonmodule git cd mypythonmodule python setup py install cd ```` like ````git clone install https://github com/user/mypythonmodule git ```` or does not this exist? | If you use pip it supports installing from git URLs From the <a href="https://pip pypa io/en/stable/reference/pip_install html#git" rel="nofollow" title="pip documentation">pip documentation</a> "pip currently supports cloning over git git+https and git+ssh" So you would do ````pip install git+https://github com/user/mypythonmodule git ```` |
Check if OneToOneField is None in Django I have two models like this: ````class Type1Profile(models Model): user = models OneToOneField(User unique=True) class Type2Profile(models Model): user = models OneToOneField(User unique=True) ```` I need to do something if the user has Type1 or Type2 profile: ````if request user type1profile != None: # do something elif request user type2profile != None: # do something else else: # do something else ```` But for users that do not have either type1 or type2 profiles executing code like that produces the following error: ````Type1Profile matching query does not exist ```` How can I check the type of profile a user has? Thanks | How about using try/except blocks? ````def get_profile_or_none(user profile_cls): try: profile = getattr(user profile_cls __name__ lower()) except profile_cls DoesNotExist: profile = None return profile ```` Then use like this! ````you = request user if get_profile_or_none(you Type1Profile) is not None: # do something elif get_profile_or_none(you Type2Profile) is not None: # do something else else: # d'oh! ```` I suppose you could use this as a generic function to get any reverse OneToOne instance given an originating class (here: your profile classes) and a related instance (here: request user) |
Postgres trigger does not find return Here is my trigger: ````CREATE OR REPLACE FUNCTION update_played () RETURNS trigger AS $BODY$ DECLARE v_count_played integer; BEGIN SELECT count(*) INTO STRICT v_count_played FROM history WHERE song_id = NEW song_id; EXCEPTION WHEN NO_DATA_FOUND THEN RAISE EXCEPTION 'history count for song % not found' NEW song_id; WHEN TOO_MANY_ROWS THEN RAISE EXCEPTION 'history count did not aggregate'; EXECUTE 'UPDATE song SET count_played = $1 WHERE id = $2' USING v_count_played NEW song_id; RETURN NULL; END; $BODY$ LANGUAGE plpgsql VOLATILE; create trigger update_played_trigger after insert on history for each row execute procedure update_played(); ```` It gives the error: <blockquote> sqlalchemy exc InternalError: (psycopg2 InternalError) control reached end of trigger procedure without RETURN </blockquote> | You have misunderstood the `EXCEPTION` keyword If I change your indenting to match how it works it might help you understand `EXCEPTION` appears with `BEGIN` and `END` as part of a block like a `try {} catch {}` in other languages So it works like this: ````BEGIN SELECT count(*) INTO STRICT v_count_played FROM history WHERE song_id = NEW song_id; EXCEPTION WHEN NO_DATA_FOUND THEN RAISE EXCEPTION 'history count for song % not found' NEW song_id; WHEN TOO_MANY_ROWS THEN RAISE EXCEPTION 'history count did not aggregate'; EXECUTE 'UPDATE song SET count_played = $1 WHERE id = $2' USING v_count_played NEW song_id; RETURN NULL; END; ```` What happens here is that you run the `SELECT` If there is a `NO_DATA_FOUND` exception you `RAISE` If there is a `TOO_MANY_ROWS` exception you `RAISE` then in the same block there is <them>unreachable code</them> after the `RAISE EXCEPTION` that does an `EXECUTE` and `RETURN` If there is no exception from the `SELECT` then no further action is taken the procedure simply exits returning nothing What I think you intended to write was: ````BEGIN BEGIN SELECT count(*) INTO STRICT v_count_played FROM history WHERE song_id = NEW song_id; EXCEPTION WHEN NO_DATA_FOUND THEN RAISE EXCEPTION 'history count for song % not found' NEW song_id; WHEN TOO_MANY_ROWS THEN RAISE EXCEPTION 'history count did not aggregate'; END; EXECUTE 'UPDATE song SET count_played = $1 WHERE id = $2' USING v_count_played NEW song_id; RETURN NULL; END; ```` |
What did Burke think a social hierarchy should be based on? | property |
Require BeautifulSoup in a Python Package - What is needed in setup py? I am writing a setup script for a python distribution `foo` My code requires `BeautifulSoup` so currently my directory is structured like so: ````<root>/ setup py __init__ py foo py BeautifulSoup/ __init__ py BeautifulSoup py etc ```` And setup py currently looks like this (less meta info): ````setup(name='foo' version='0 9 0' py_modules=['foo'] ) ```` I want to include `BeautifulSoup` in case the user does not have it installed already but I also do not want to install it if they already have it installed at a particular version I noticed in the <a href="http://docs python org/distutils/setupscript html" rel="nofollow">Python 2 7 2 docs</a> that I should included `packages=[ ]` in my setup py file However <a href="http://docs python org/distutils/setupscript html#relationships-between-distributions-and-packages" rel="nofollow">Section 2 4 Relationships between Distributions and Packages</a> mentions that there is a way to specify that a particular version of the package is required I could not find any examples of how to use a "requires expression" within setup py so I am not sure if this is what I need In short I need a way to say: <blockquote> This package requires `BeautifulSoup` with at least X X X version If that version is not installed use the one that is provided </blockquote> How do I do that? | Directory structure: ````<root>/ setup py foo py ```` Note: there is no `__init__ py` file You could use <a href="http://packages python org/distribute/" rel="nofollow">`distribute`</a> to specify dependencies `setup py`: ````from setuptools import setup setup(name='foo' version='0 9 0' py_modules=['foo'] install_requires=['BeautifulSoup >= X X X'] ) ```` This will install required version of `BeautifulSoup` if it is not already present You do not need to provide `BeautifulSoup` in this case If you do not want to install `BeautifulSoup` automatically: ````<root>/ setup py foobar/ __init__ py foo py BeautifulSoup/ __init__ py BeautifulSoup py etc ```` setup py: ````from setuptools import setup find_packages setup(name='foobar' version='0 9 0' packages=find_packages() ) #NOTE: no install_requires ```` Somewhere in in your modules: ````import pkg_resources try: pkg_resources require("BeautifulSoup>=X X X") except pkg_resources ResolutionError: from foobar import BeautifulSoup else: import BeautifulSoup ```` It is a less desirable and unusual method |
from django db import utils ImportError cannot import name utils? I am in the plain python she will and I am getting this error when trying to import my project models: ````from results models import TestResult Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 3 2\src\debug\tserver\_sandbox py" line 1 in <module> # Used internally for debug sandbox under external interpreter File "C:\Users\audrey_moreau\myProject\results\models py" line 1 in <module> from django db import models File "c:\Python27\Lib\site-packages\django\db\__init__ py" line 40 in <module> backend = load_backend(connection settings_dict['ENGINE']) File "c:\Python27\Lib\site-packages\django\db\__init__ py" line 34 in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS] item) File "c:\Python27\Lib\site-packages\django\db\utils py" line 92 in __getitem__ backend = load_backend(db['ENGINE']) File "c:\Python27\Lib\site-packages\django\db\utils py" line 54 in load_backend return import_module(' base' backend_name) File "c:\Python27\Lib\site-packages\django\utils\importlib py" line 35 in import_module __import__(name) File "c:\Python27\Lib\site-packages\django\db\backends\sqlite3\base py" line 14 in <module> from django db import utils ImportError: cannot import name utils ```` Can anyone give me a pointer on how to fix this? I am using Python 2 7 | I had this bug and it was caused by django_nose I was trying to import django_nose from settings py to determine if it exists on the system like this: ````try: import django_nose INSTALLED_APPS = ['django_nose'] TEST_RUNNER = 'django_nose NoseTestSuiteRunner' except ImportError: pass ```` I modified this to ````from imp import find_module try: find_module('django_nose') INSTALLED_APPS = ['django_nose'] TEST_RUNNER = 'django_nose NoseTestSuiteRunner' except ImportError: pass ```` and my issue was resolved |
How to dereference an object in Python? I have a function with returns a tuple: ````def gradiant(params data): Q1 = params[0] Q2 = params[1] dQ1 = sum(2*(y_i - Q1*x_i - Q2)*(x_i) for x_i y_i in data) dQ2 = sum(-2*(y-i - Q1*x_i - Q2) for x_i y_i in data) return (dQ1 dQ2) ```` I am trying to print the returned values: ````grad = gradiant(params Data) for x in grad: print(x) ```` Output: ````<generator object <genexpr> at 0x7fdfe009adc0> <generator object <genexpr> at 0x7fdfe009a5f0> ```` How do I get to print the integer values? | You have a `y-i` instead of `y_i` It produced a `NameError` for me I fixed the typo and it worked fine (I assume anyway - it printed two numbers) However the more interesting issue is how errors are handled within generator expressions (as the typo was part of the generator expression you sent to `sum()`) I got a `NameError` but you got generator expression objects Look at this function call with an unpacked generator that should contain a `TypeError`: ````>>> print(*('' join(item2) for item2 in range(3))) Traceback (most recent call last): File "<stdin>" line 1 in <module> TypeError: print() argument after * must be a sequence not generator ```` Now let us see what we get by printing the actual object: ````>>> print('' join(item2) for item2 in range(3)) <generator object <genexpr> at 0x00000000028945E8> ```` That makes some sense as generators are lazily evaluated and it was never actually called But let us see what happens when we send it to `list()` which should force evaluation: ````>>> print(list('' join(item2) for item2 in range(3))) Traceback (most recent call last): File "<stdin>" line 1 in <module> File "<stdin>" line 1 in <genexpr> TypeError: can only join an iterable ```` There is the expected error How about a valid generator that contains an invalid generator? ````>>> print(*(list('' join(item2) for item2 in range(3)) for i in range(1))) Traceback (most recent call last): File "<stdin>" line 1 in <module> TypeError: print() argument after * must be a sequence not generator ```` The same uninformative error What if we use a `list` comprehension instead of a generator expression? ````>>> print(*['' join(item2) for item2 in range(3)]) Traceback (most recent call last): File "<stdin>" line 1 in <module> File "<stdin>" line 1 in <listcomp> TypeError: can only join an iterable ```` We get the informative error we were expecting Unfortunately I do not know why this happens but be extra-careful with generator expressions |
Timeout handling while using run_in_executor and asyncio I am using asyncio to run a piece of blocking code like this: ````result = await loop run_in_executor(None long_running_function) ```` My question is: Can I impose a timeout for the execution of `long_running_function`? Basically I do not want `long_running_function` to last more than 2 seconds and I cannot do proper timeout handling within it because that function comes from a third-party library | You could use <a href="https://docs python org/3/library/asyncio-task html#asyncio wait_for" rel="nofollow">asyncio wait_for</a>: ````future = loop run_in_executor(None long_running_function) result = await asyncio wait_for(future timeout loop=loop) ```` |
Why does the pattern matching return this result in Python? Here are the codes I read in <a href="https://developers google com/edu/python/regular-expressions" rel="nofollow">https://developers google com/edu/python/regular-expressions</a> ````match = re search(r'\d\s*\d\s*\d' 'xx1 2 3xx') => found match group() == "1 2 3" match = re search(r'\d\s*\d\s*\d' 'xx12 3xx') => found match group() == "12 3" match = re search(r'\d\s*\d\s*\d' 'xx123xx') => found match group() == "123" ```` I understand that `\d\s*\d\s*\d` will match 1 2 3 but I do not know why `\d\s*\d\s*\d` and `\d\s*\d\s*\d` can also match 12 3 and 123 respectively? Can anyone help me on this? Thanks | The '*' after the \s will match zero to many whitespace characters |
How to rename a node with Python LXML? How do I rename a node using LXML? Specifically how to rename a parent node i e a `<body>` tag while preserving all the underlying structure? I am parsing using the `lxml html` module but supposedly there should not be any difference between xml and html in terms of renaming between `lxml html HtmlElement` and its XML counterpart I have searched through the docs at the <a href="http://lxml de/" rel="nofollow">LXML</a> site but did not find any reference to renaming of nodes | Once you have the `<body>` element just change its `tag` attribute ````import lxml etree import lxml html doc = lxml html fromstring("<html><body><p></body></html>") body = doc find('body') body tag = "body-not" print(lxml etree tostring(doc)) ```` This prints ````b'<html><body-not><p/></body-not></html>' ```` |
What is the center of the Florida population | Polk County since the 1960 census |
When did Egypt mass it's army near the border with Israel? | 1967 |
Get objects in scope in the order they are defined I have a factory function that defines several classes and returns them in a list Is it possible to obtain such a list where the classes appear in the order in which they are defined? The following factory uses `locals()` to get classes defined in its scope but `locals()` returns a dictionary so there is not a definite ordering ````import inspect def factory() : class Base(object): pass class A(Base): pass class B(Base): pass class C(Base): pass local_classes = [obj for obj in locals() values() if inspect isclass(obj)] return [cls for cls in local_classes if issubclass(cls Base)] factory() # [<class '__main__ A'> <class '__main__ Base'> <class '__main__ C'> <class '__main__ B'>] ```` The desired output would be ````# [<class '__main__ Base'> <class '__main__ A'> <class '__main__ B'> <class '__main__ C'>] ```` | I have come across this problem a couple of times My solution generally uses a class decorator to explicitly add each class to the factory I generally use instances of a factory class as the factory However if you case a simple factory class derived from list may suffice to achieve your goal: ````class Factory (list): def append(self cls): super(Factory self) append(cls) return cls factory = Factory() @factory append class Base (object): pass @factory append class A (Base): pass @factory append class B (Base): pass print factory ```` Running this yields: ````[<class '__main__ Base'> <class '__main__ A'> <class '__main__ B'>] ```` |
Invalid characters for python output file I have this little script: ````from numpy import * import numpy as np import scipy spatial as spt X= np loadtxt('edm') myfile = open('edm txt' 'w') V= spt distance pdist(X T 'sqeuclidean') P = spt distance squareform(V) print P myfile write(P) ```` And this matrix: ```` 0 199 778354301 201 857546133 0 ```` If I run my program; I get this in the terminal (according to the "print"): ````[[ 0 80657 85977805] [ 80657 85977805 0 ]] ```` But in my output file; I get invalid characters as following : ````��������z°¶¡±Ã@z°¶¡±Ã@�������� ```` Do you know why? Thanks | You can use <a href="http://docs scipy org/doc/numpy/reference/generated/numpy savetxt html" rel="nofollow">NumPy</a> `savetxt` method to save arrays and not worry about codification As in the Docs ````>>> np savetxt('edm txt' x) # x is an array ```` |
Unittest failed with sys exit I am trying to run my tests with unittest Here is my structure : ````projectname/ projectname/ foo py bar py tests/ test_foo py test_bar py ```` I run it with : ````cd tests/ python -m unittest discover ```` But in one file for example <strong>foo py</strong> I use a `sys exit(0)` and unittest does not really like it : ````$ python -m unittest discover E ====================================================================== ERROR: test_foo ( ) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/ /projectname/foo py" line 12 in write sys exit(0) SystemExit: 0 ---------------------------------------------------------------------- Ran 6 tests in 0 018s FAILED (errors=1) ```` The `sys exit()` use is voluntary I cannot remove it I know there is an option called `exit` for the unittest main function : ````if __name__ == "__main__": unittest main(exit=False) ```` But I want to test all the files in the <them>tests</them> directory Another way is to do : ````if __name__ == '__main__': tests = unittest TestLoader() discover(' ') unittest TextTestRunner(verbosity=1) run(tests) ```` It finds all the <them>test_</them> files but the `sys exit()` makes unittest crash | I do not think using sys exit() in a module is a good idea But if you must what you should do is write a test case that wraps the module as a subprocess probably using the subprocess module and verity the exit code You will probably also need a wrapper script to call In other words you call an external Python script that imports that module then it exits The unittest framework can then report pass/fail by checking the return value of the subprocess |
Using poppler to extract annotations g_free() / get_color() issue I borrowed this python code <a href="http://stackoverflow com/questions/1106098/parse-annotations-from-a-pdf">here</a> (first answer by enno groper) to automate the extraction of annotations from pdfs I want to make some modifications to the code Trying to fetch the color of annotations with `annot_mapping annot get_color()` I ran into the first issue What the command returns is objects like this one `<PopplerColor at 0x1a85180>` rather than rgb values (<a href="https://people freedesktop org/~ajohnson/docs/poppler-glib/poppler-PopplerColor html#PopplerColor" rel="nofollow">promised here</a>) According to <a href="https://people freedesktop org/~ajohnson/docs/poppler-glib/PopplerAnnot html#poppler-annot-get-color" rel="nofollow">poppler docs</a> `poppler_annot_get_color()` returns "a new allocated PopplerColor with the color values of poppler_annot or NULL It must be freed with g_free() when done" Is this correct and if yes how do I achieve this in python? | `annot_mapping annot get_color()` gives you a PopplerColor which is a structure with three members (of type guint16): red green and blue For example: ````PopplerColor *color = poppler_annot_get_color (annot); g_printf ("%d\n" color>red); ```` gives you the red value of your annotation `annot` the gb values can be obtained similarly In python this is achieved through `annot_mapping annot get_color() red` assuming you have `import poppler` |
What is the average time for freezing temps? | November 6 thru April 2 |
What kind of milk has been replaced with coconut milk on Tuvalu? | animal |
What did Avicenna consider when explaining his theories on philosophy? | null |
Having Problems with Django Context Processors I am new to django context processors I wanted to create something which would give me famous quotes in every page of my blog app When I deployed it to Heroku it started giving errors few minutes after its launching These errors were : ````could not fork new process for connection: Cannot allocate memory SSL SYSCALL error: EOF detected FATAL: out of memory DETAIL: Failed on request of size 112 ```` Then the app restarts - back to normal I could generate the same with javascript but still I wanted to do it with a context processor Is it advisable to create a context processor like one given below ? ````from blog models import Post from random import randrange def recent_posts(request): you = Post objects all()[:5] return { 'recent_posts': you } def quotes(request): var = randrange(3) quotes = { '0' : "Quote 1" '1' : "Quote 2" '2' : "Quote 3" } quoted_by = { '0' : "Person 1" '1' : "Person 2" '2' : "Person 3" } return { 'quotes': quotes[str(var)] 'quoted_by': quoted_by[str(var)] } ```` | This is not an answer to your question it is some observations on your code - Your function `quotes` ignores its argument `request` Why bother passing it? - Each time your function `quotes` is called it builds dictionaries `quotes` and `quoted_by` that are then thrown away when the function returns Put this data in global variables instead so that it only needs to be built once - You organize your quotations into two dictionaries one mapping strings to quotations the other mapping strings to authors Then you generate a random number convert it to a string and look it up in both dictionaries This is error-prone in several ways: when updating the dictionaries you might update one but not the other or put a quotation and author under different keys You might add entries to the dictionaries but forget to update the argument to `randrange` Remember the DRY principle ("<a href="http://en wikipedia org/wiki/Don%27t_repeat_yourself" rel="nofollow">Do not Repeat Yourself</a>") Here is how I would write this code: ````from random import choice # List of pairs (quotation author) quotations = [ ("Focusing is about saying no " "Steve Jobs") ("First make it run then make it run fast " "Brian Kernighan") ("It is easier to ask forgiveness than it is to get permission " "Grace Hopper") # etc ] def quotes(): """Pick a random quotation and return a context dictionary with keys 'quotes' and 'quoted_by' """ quotation author = choice(quotations) return dict(quotes = quotation quoted_by = author) ```` |
None type in _init_ method I am beginner in python I cannot understand simple thing with type None When I assign None values to my parameters in constructor I get error What is the trick Code with error: ````class A(object): def __init__(self): self root = None def method_a(self foo): if self root is None: print self root ' ' foo a = A() # We do not pass any argument to the __init__ method a method_a('Sailor!') # We only pass a single argument ```` The error: ````Traceback (most recent call last): File "C:/Users/Dmitry/PycharmProjects/Algorithms/final_bst py" line 11 in <module> a method_a('Sailor!') # We only pass a single argument File "C:/Users/Dmitry/PycharmProjects/Algorithms/final_bst py" line 7 in method_a print self root ' ' foo TypeError: unsupported operand type(s) for : 'NoneType' and 'str' ```` As soon as I change None type in <them>init</them> for something like string variable it works correctly | The error is <strong>not</strong> in `__init__` but later in the expression you are trying to `print`: ````print self root ' ' foo ```` You can use `+` to concatenate strings but `None` is <strong>not</strong> a string So use string formatting: ````print '{} {}' format(self root foo) ```` or far less elegantly <strong>make</strong> a string explicitly: ````print str(self root) ' ' foo ```` |
How to df groupby sum only one column I have a pandas dataframe df (see example) that has columns: `master ID` `sub ID` (child of `master ID`) prices of sub ID and scenarios count for each master ID/SubID I would like to find the prices pct_change between scenarios for each master ID as displayed in example master ID price are the sums of their child sub ID prices Sorry if this is not clear what have been tried so far: ````df sort_values(by="scenario" ascending=False) groupby('subID') head(n=1) ```` Example of df and desired result <img src="http://i stack imgur com/ocqLW png" alt="Example of df and desired result"> | try this: ````In [38]: df Out[38]: id master_id price scenario 0 101 1 400 1 1 102 1 550 1 2 101 1 650 2 3 102 1 400 2 4 201 2 500 1 5 201 2 600 2 6 301 2 500 3 7 301 2 600 3 In [39]: g = df groupby(['master_id' 'scenario'] as_index=False)['price']\ : sum()\ : pivot(index='master_id' columns='scenario' values='price')\ : reset_index() In [40]: g Out[40]: scenario master_id 1 2 3 0 1 950 0 1050 0 NaN 1 2 500 0 600 0 1100 0 ```` |
Searching for a word in a nested list I am trying to write a function that searches for something specifically in a list: ````def search(inlist matches): for li in inlist: for m in matches: if m in li: return li return none l = [("daniel" "20th november" "tenochtitlan") ("Arturo" 17 "17th october")] ```` Here for example looking for the birthdate of daniel I have this to define the search but I am not sure how to go from here | From the code written there i got this: ````l = [("daniel" "20th november" "tenochtitlan") ("Arturo" 17 "17th october")] data = search(l ['daniel']) #data will be ("daniel" "20th november" "tenochtitlan") for d in data: #regexp to find something specific return that value if SomeRegexp match(d): return d ```` But you will have to be more specific if you want a more specific answer |
Passing In Value for Title Variable in Django Template I am dealing with the following code in a Django template: ````<!-- Override title of base -> {% block title %}{{ title }} | {{ site_title|default:_('Hello World') }}{% endblock %} ```` For the Django admin web site the value of the title variable above (i e `{{ title }}`) defaults to "Log in" Where is this value being defined? I would like to change this value but pass it in rather than hard code it | You can use the variable {{title}} in the template and use the view to pass the content like this: ````template html <title>{{ title }}</title> views py def something(request): #Do something return render_to_response('template html' context_instance=RequestContext(request {'title':'Here is what you want to show as title'})) ```` |
How to to optimize this python problem? <a href="http://www codechef com/problems/TSORT" rel="nofollow">Here</a> is the problem And my solution is: ````import sys LIST_ITEM = [] NUMBER_OF_TEST_CASES = int(raw_input()) def non_decreasing(my_list): if len(my_list) < 2: return my_list my_list sort() return my_list if __name__ == "__main__": if NUMBER_OF_TEST_CASES >= 1000001 or NUMBER_OF_TEST_CASES <= 0: sys exit() for val in range(1 NUMBER_OF_TEST_CASES+1): x = int(raw_input()) if x >= 1000001 or x<0: sys exit() else: LIST_ITEM append(x) values = non_decreasing(LIST_ITEM) for i in values: print i ```` But it tell me `Time Limit Exceeded` <a href="http://www codechef com/status/TSORT tauquir" rel="nofollow">Here is my solution link</a> | Do not sort! Just create a length-1e6 array of zeros (in numpy perhaps) read through the list setting a[i]=1 whenever you encounter the number i and then print out all the nonzero entries I think this works: ````import numpy as np import sys nn = 1000000 a = np zeros(nn+1 dtype=np int) for l in sys stdin: a[np int(l)]=1 for i in xrange(nn+1): if a[i]: print i ```` I expect there is a way to speed up the i/o |
Unicode portability with PyQT4/numpy on linux I am developing a multiplatform application in pyQT4 and numpy and actually it does not work on my linux system (Xubuntu 12 04) even so it seems work great on windows 7 So the problem comes from my import files method (It is in a PyQT4 class) : ````def import_folder(self abs_path folder_list): for folder_i in folder_list: filenames = glob glob("%s/%s/* txt" %( abs_path folder_i )) aa =list(filenames)[1] print filenames data_fichier = np genfromtxt("%s" %(aa) delimiter=';' skip_header=35 usecols=[8]) data_fichier2 = np zeros((data_fichier shape[0] )) ```` And this is the error I get : ```` data_fichier = np genfromtxt("%s" %aa delimiter=';' skip_header=35 usecols=[8]) File "/usr/lib/python2 7/dist-packages/numpy/lib/npyio py" line 1241 in genfromtxt fhd = iter(np lib _datasource open(fname 'rbU')) File "/usr/lib/python2 7/dist-packages/numpy/lib/_datasource py" line 145 in open return ds open(path mode) File "/usr/lib/python2 7/dist-packages/numpy/lib/_datasource py" line 472 in open found = self _findfile(path) File "/usr/lib/python2 7/dist-packages/numpy/lib/_datasource py" line 315 in _findfile filelist = self _possible_names(self abspath(path)) File "/usr/lib/python2 7/dist-packages/numpy/lib/_datasource py" line 364 in abspath splitpath = path split(self _destpath 2) UnicodeDecodeError: 'ascii' codec cannot decode byte 0xc3 in position 14: ordinal not in range(128) ```` I have printed my "filenames" variables : ```` [you'/home/*****/Documents/Plate_test/Track-Arousal_experiment_24_06_13_track_1-Trial 2-7-Subject 1 txt' you'/home/*****/Documents/Plate_test/Track-Arousal_experiment_24_06_13_track_1-Trial 2-5-Subject 1 txt'] ```` Therefore the problem comes from the unicode mode (the "you" at the begining of the list elements) And I do not know at all why I get this unicode mode with my linux system Have you any ideas how I can remove it and turn of in the "regular" mode (sorry for the terminology I am not an expert) ? (Or others ideas about my problem) (Just for you know when I have launched the method as a simple function without the PyQT class it works great so I suspect it ) Thanks Lem | It seems that the `loadtxt` method expects a `str` and not a `unicode` since it tries to decode it glob in your case is returning unicode strings so try encoding your filenames: ````filenames = map(str filenames) ```` Or ````filenames = map(lambda f: f encode('utf-8') filenames) ```` Or even: ````def safe_str(s): if isinstance(s unicode): return s encode('utf-8') return s filenames = map(safe_str filenames) ```` |
is there a way to change the return value of a function without changing the function's body? ````def f(x): return (x - 2)/2 def g(x): return x ```` this code will do this: ````func = g(f) ```` now func(1) = -1/2 what if I want to modify g(x) (and not f(x)) so that ````func = g(f) func(1) = 1/2 ```` is there a way to do this? thank you Edit: f(x) can be any function that possibly returns a negative number | ````>>> def f(x): return (x - 2)/2 >>> def g(function): return lambda x: abs(function(x)) >>> func = g(f) >>> func(1) 0 5 ```` |
Who currently holds the power to grant royal assent to measures? | the lieutenant governor |
What did Britain gain in North America from the war? | Great Britain, which gained the bulk of New France in North America, Spanish Florida |
What was historian Martin Lyons' term for the political system created by Napoleon? | "dictatorship by plebiscite." |
Check at once the boolean values from a set of variables I am having around 10 boolean variables I need to set a new boolean variable `x=True` if all those ten variable values are True If one of them is False then set `x= False` I can do this in a manner ````if (a and b and c and d and e and f ): x = True else: x=False ```` which obviously looks very ugly Please suggest some more pythonic solutions The ugly part is `a and b and c and d and e and f ` | Assuming you have the bools in a list/tuple: ````x = all(list_of_bools) ```` or just as suggested by @minopret ````x= all((a b c d e f)) ```` example: ````>>> list_of_bools = [True True True False] >>> all(list_of_bools) False >>> list_of_bools = [True True True True] >>> all(list_of_bools) True ```` |
Send information from server to view without reloading django In my application the user can launch a crawl action from the interface who will be executed in a thread on the server-side This crawl is performed in a `while` loop and will send some information (for the moment as a print in the console) What I want to do is to send this information displayed in the console to the view This diagram sum up the process ````View Server | | | Call the async function with ajax | crawl Thread |--------------------------------------->|----------->| | | | | | | | send back information | information | |<----------------------------------------|<------------| | | |------| | | | refresh view | | |<------ ```` Is there a way to do this ? I have no idea how to do this (signals ? websockets ?) Thanks ! | There are basically two approaches you can take: polling or pushing If you are going to poll which is the easier choice you can use several things from updating the DOM with jQuery to something more elegant like Observables/ObservableArrays in Knockout js If you are going to push I would recommend using socket io and Redis in a pub/sub fashion Either way you are going to end up using JavaScript to update the DOM |
What increased the power in the House of Commons? | Reforms of the voting system |
Append data into dictionary i am reading file txt which has following data : ```` Arjun 10th 20 88+ 77 76 36 ```` How to make class as a key and add other values to corresponding key which will look like {'10th' :['20' [88 77 76 36]]} Note : values in line ends with sign and next line starts with sign How can we insert them into same list? | Despite that the question is not well explained I suppose that what you try to do is something like this Check the function `words` please and tell me whether this is more or less in the proper direction ````def words(d auxList): # Variables to save state between lines curKey = None values = [] for line in auxList: items = line split() # Check if we have values already from a previous line if curKey is None: # Check if we see a continuation symbol (+) if items[-1][-1] == '+': # and remove it from the value items[-1] = items[-1][:-1] # Save the info in this line curKey = items[1] values = items[2:] else: # If all the information is in one simple line d[items[1]] = items[2:] else: # Check if we see a continuation symbol (+) if items[-1][-1] == '+': # and remove it from the value items[-1] = items[-1][:-2] # Save the info in this line and accumulate it # with the previous ones values extend(items[1:]) else: # Update dictionary when we have all the values d[curKey] = values items[1:] # and reset state curKey = None values = [] # Be sure to save the last line if there is no more info # Maybe it is not necessary if curKey is not None: d[curKey] = values d = {} a2 = [line strip() for line in myfile readlines()] words(d a2) ```` |
How many tourists visited Israel in 2013? | 3.54 million |
Correct way of using root after and root mainloop in Tkinter I have a tkinter interface that needs to be automatically refreshed every 5 minutes So far there is no problem you would just have to do something like: ````root after(300000 function_to_run args_of_fun_to_run) ```` The problem is that I have to do this for an "infinite" amount of time The scenario is that the GUI will running on a PC attached to a TV displaying some info 24/7 in my office This works for around 8 hours and then I get the following error: <img src="http://i stack imgur com/XcCug png" alt="enter image description here"> Now I know that the traceback goes all the way to a line in one of my custom modules that uses matplotlib None of my custom modules uses any loops so I knw that the error does not directly come from one of them (please correct me if I am wrong) so it must be from me repeating the function an infinite amount of time This is the code from my main function: ````from tkinter import * from tkinter import ttk import logging import datetime import sys sys path append(r'C:\Users\me\Desktop\seprated sla screens') import sla_main as sla import main_frame as mf import sla_grid as sg import incoming_volume as iv import outgoing_volume as ov import read_forecast as fc import get_headers as hd import vol_graph as vg import out_graph as og import add_graph as ag import sla_reduction_email as sre ################################### ################################### ################################### ################################### runs = 0 def maininterface(f_size pic_x pic_y): global runs global root start = str(datetime datetime now() date()) ' ' str(datetime timedelta(hours=6)) screen = sla slamain(start) if runs == 0: root = mf mainframe(f_size) sg sla_grid(screen f_size root) file = open('titles in queue txt' 'r') in_q = file read() file close ttk Label(root text=in_q anchor=CENTER width=15 font=('times' f_size 'bold')) grid(column=6 row=2 sticky=E) if runs > 0: ################################### #deletes all rows before making the calculations for label in root grid_slaves(): if int(label grid_info()["row"]) > 1: label grid_forget() sg sla_grid(screen f_size root) file = open('titles in queue txt' 'r') in_q = file read() file close ttk Label(root text=in_q anchor=CENTER width=15 font=('times' f_size 'bold')) grid(column=6 row=2 sticky=E) ################################### #all this part is just info for the graph and the graph incoming = iv incomingvolume(start) outgoing = ov outgoingvolume(start) forecast = fc readforecast() headers = hd getheaders() vg volgraph(forecast incoming headers pic_x pic_y) #og outgraph(forecast outgoing headers pic_x pic_y) ag addgraph("vol_graph png" root 1) #ag addgraph("out_graph png" root 2) runs = runs 1 globals() update(locals()) print(str(datetime datetime now())) root after(300000 maininterface f_size pic_x pic_y) root mainloop() logging basicConfig(level=logging DEBUG filename='error_log txt') try: maininterface(28 23 5 6) except: logging exception("Oops:") ```` What can I modify here to avoid this error?? Thanks! <strong>EDIT:</strong> As many have suggested I have moved the mainloop call outside of the main function The las few lines of my code look like this now: ````try: maininterface(28 23 5 6) root mainloop() except: logging exception("Oops:") ```` The root after call remains inside the function After running it like this it closes after 5 minutes Does anyone know why the mainloop is not being called? | Call the mainloop outside of the function |
Subclassing User to differentiate between an admin and an App with an API key? This is my first API so please forgive/correct me if I make any wrong claims I have an app that has an API I would only like external apps (mobile clients etc ) with a valid API key to have access to it and I think django-rest-framework's TokenAuthentication is the right fit for it I would also like users to be able to log in with their username & password and I am looking to use OAuth2Authentication for that But I do not want apps that use TokenAuthentication to have a "User" instance in the database (as they are not users in the traditional sense) so I am thinking about doing something like this: ````class Client(User): pass ```` - django-rest-framework says that request user will be an instance of User Will I bump into any problems if I use Client instead? - Is this the standard way of handling this situation? It just does not feel right to me (mainly because of question 1) | For mobile clients to have access to your API using django-restframework's TokenAuthentication will work just fine As you have already ascertained You need to design a mechanism for handing out your tokens If you are doing this dynamically then you will need to have your API request handle this <strong>Mobile Client: ( initial API request )</strong> - request /API/rabbit/1/ - ( no token) <strong>Server: 401</strong> - test for the token ( fails ) - 'login please' via HTTP 401 response ( or some other custom header or response information ) You can define your api on how to accomplish this most folks use the http: <a href="http://www w3 org/Protocols/rfc2616/rfc2616-sec10 html" rel="nofollow">401 Unauthorized</a> error code I point this out because its clearly a design decision <strong>Mobile Client: ( request login)</strong> - prompts user for username and password and makes a request too /login/ this could be a special mobileclient login like /mobile/login/ whose difference is that it hands back a token on a successful login <strong>Server: 200</strong> - verifies valid user and hands out token you could write this logic or you could use 'rest_framework authtoken views obtain_auth_token' which I recommend See rest-frameworks <a href="http://django-rest-framework org/api-guide/authentication#tokenauthentication" rel="nofollow">token authentication</a> for details on this Heed its warning about https <strong>Mobile Client: ( re-request API with token in http header)</strong> - receives token - now remakes initial request to /API/rabbit/1/ with its token in the header <strong>Server: 200</strong> - verifies valid token in the header and provides access to API You will be writing this code <strong>Finally:</strong> You will need to design a strategy to 'age-out' your tokens and or lock out users <strong>Also:</strong> make sure you add 'rest_framework authtoken' to your INSTALLED_APPS and make sure you call `manage py syncdb` <strong>Aside:</strong> you do not specifically have to use the TokenAuthentication ( request user request auth) you can write your own code to peek in the header and see if the token is set This is fairly easy to do with the python Cookie lib You are still using-heavly the token management features of django-rest-framework To be honest I think there documentation is a bit incomplete on configuring the 'TokenAuthentication' authentication back-ends Hope this helps! |
How to write log info() to console in django using gunicorn? I have configured Django logging to print to console as well as log file When I use `python manage py runserver` it works But when I run this using `gunicorn` as `gunicorn app wsgi:application` `print` statement goes to console but `log info()` does not go anywhere Any ideas? | It is working now I do not know how My `settings py` section: ````LOGGING = { 'version': 1 'disable_existing_loggers': True # How to format the output 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s" 'datefmt' : "%d/%b/%Y %H:%M:%S" } } # Log handlers (where to go) 'handlers': { 'null': { 'level':'DEBUG' 'class':'django utils log NullHandler' } 'logfile': { 'level':'DEBUG' 'class':'logging handlers RotatingFileHandler' 'filename': PROJECT_ROOT "/repackager log" 'maxBytes': 50000 'backupCount': 2 'formatter': 'standard' } 'console':{ 'level':'INFO' 'class':'logging StreamHandler' 'formatter': 'standard' } 'celery': { 'level': 'DEBUG' 'class': 'logging handlers RotatingFileHandler' 'filename': PROJECT_ROOT "/celery log" 'formatter': 'standard' 'maxBytes': 1024 * 1024 * 100 # 100 mb } } # Loggers (where does the log come from) 'loggers': { 'repackager': { 'handlers': ['console' 'logfile'] 'level': 'DEBUG' 'propagate': True } 'django': { 'handlers':['console'] 'propagate': True 'level':'WARN' } 'django db backends': { 'handlers': ['console' 'logfile'] 'level': 'WARN' 'propagate': False } '': { 'handlers': ['console' 'logfile'] 'level': 'DEBUG' } 'raven': { 'level': 'DEBUG' 'handlers': ['console'] 'propagate': False } 'sentry errors': { 'level': 'DEBUG' 'handlers': ['console'] 'propagate': False } 'gunicorn error': { 'level': 'INFO' 'handlers': ['logfile'] 'propagate': True } 'gunicorn access': { 'level': 'INFO' 'handlers': ['logfile'] 'propagate': False } 'celery': { 'handlers': ['celery'] 'level': 'DEBUG' } } } ```` `views py` ````# Logger import logging log = logging getLogger(__name__) ```` |
Give parameters to Pycharm I am completly new to Python and have written no script in this language But I need help with the following line (I know the line is for running the script in the interpreter) I need to run exactly this program where I can do decompile the gwc file I do not want to learn Python now I just want to run this programm in Pycharm Here is the line: ````$ python gwcd py [OPTIONS] <gwc file> ```` The Options are: ````-h --help show this help message and exit --output OUTPUT Output directory where gwcd will store extracted data --lua Extract compiled lua file --completion Show the completion code --media Extract media files --verbose -v Show all data related to the cartridge --all Do everything ```` The Question is also for me where the gwc file has to be stored Thanks in advance! P S : The Github Link for the Project is: <a href="https://github com/driquet/gwcd git" rel="nofollow">https://github com/driquet/gwcd git</a> | Presumably you are running this under PyCharm meaning you made a Run Configuration and you then click the green "Run" button If so edit the Run Configuration and add your arguments to the "Script parameters" field You might (or might not) need to set the "Working directory" field if you want your gwc file to be relative instead of supplying the full path |
Comparing a list of different sizes and data to output the difference I am working on a program for a personal project to better understand how list and dictionaries in python work I am an amateur programmer still learning The programs goal is to be able to read two files and compare the parameters of these two files with one another if the parameter of one of the files is incorrect or does NOT match it will create a new file with the incorrect/Not matched parameters I have already created this and the program does what it is suppose to However I am running into an error when trying to compare a file that has more or less parameters than the compared file In short my lists that were being compared with one another had the same number of elements; however if the elements of the list are not equal I run into an error usually a list index out of range The gist of it as best as I could put it is the following: I have 2 Text Documents: TextA txt: ````Data1="123 212 2 312" Dog=12 Cat="127 0 0 1" Data2=9498 Fish="" Tiger=9495 Data3=5 Data4=2 Game=55 Tree=280 Falcon=67 Bear=2 ```` TextB txt: ````Dog=123 Cat="127 0 0 1" Data2=9498 Eagle="" Tiger=9495 Data3=5 Data4=2 Rock=52 Mountain=380 Falcon=627 ```` As we can see there are missing parameters from both Text documents and some of the parameters that are in both are incorrect so I would like to output the differences from <strong>textA txt ONLY</strong> into another text document So the program would do the following course of action: <them>(This is currently how the program works when comparing two texts with the <strong>same</strong> number of parameters please take this flow chart with a grain of salt its not meant to fully represent the program just give a general idea of how the program works)</them>: <a href="http://i stack imgur com/ipzzm png" rel="nofollow"><img src="http://i stack imgur com/ipzzm png" alt="Flowchart"></a> So in the end my output <them>should</them> be: <a href="http://i stack imgur com/0nG7m png" rel="nofollow"><img src="http://i stack imgur com/0nG7m png" alt="outputext"></a> Remember I do not care if a parameter exists in TextB txt but not in textA txt; what I care is that if a parameter exists in textA txt and NOT in textB txt Confusing I know but hopefully the picture will clear things up As for my code it is a very long piece of code but the important parts are the following: Please note I am also using PYQT4 for the gui ````with open(compareResults 'wb') as fdout: for index tabName in enumerate(setNames): tabWidget = QtGui QWidget() tabLabel = QtGui QTextEdit() print "Tab Name is :{}" format(tabName) fdout write('{}' format(tabName) '\r\n') nameData = lst[index] print 'name data = {}' format(nameData) for k in nameData: if nameData[k] != correct_parameters[k]: tabLabel setTextColor(QtGui QColor("Red")) tabLabel append('This Parameter is Incorrect: {} = {}' format(k nameData[k])) fdout write('\t' '|' 'This Parameter is Incorrect: {} = {}' format(k nameData[k]) '\t' '|' '\r\n') print ('{} = {}' format(k nameData[k])) elif nameData[k] == correct_parameters[k]: tabLabel setTextColor(QtGui QColor("Black")) tabLabel append('{} = {}' format(k nameData[k])) fdout write('\t' '|' '{} = {}' format(k nameData[k]) '\t' '|' '\r\n') print ('{} = {}' format(k nameData[k])) tabLayout = QtGui QVBoxLayout() tabLayout addWidget(tabLabel) tabWidget setLayout(tabLayout) self tabWidget addTab(tabWidget tabName) ```` I believe my downfall with the code is that I am looping through a set number of elements and expecting the same number of elements when looping through both lists How would I be able to Loop through the lists when they do not have the same number of elements? If the question is too confusing or you need more information/code please let me know and I will edit the question <strong>EDIT:</strong> Just to clarify I ended up using @CarsonCrane 's answer because it helped me create the loop that I needed This is what my code looks like now: ````for k in nameData: if k in correct_parameters: if nameData[k] != correct_parameters[k]: tabLabel setTextColor(QtGui QColor("Red")) tabLabel append('This Parameter is Incorrect: {} = {}' format(k nameData[k])) fdout write('\t' '|' 'This Parameter is Incorrect: {} = {}' format(k nameData[k]) '\t' '|' '\r\n') print ('{} = {}' format(k nameData[k])) elif nameData[k] == correct_parameters[k]: tabLabel setTextColor(QtGui QColor("Black")) tabLabel append('{} = {}' format(k nameData[k])) fdout write('\t' '|' '{} = {}' format(k nameData[k]) '\t' '|' '\r\n') print ('{} = {}' format(k nameData[k])) else: tabLabel setTextColor(QtGui QColor("Blue")) tabLabel append('{} = {} does not appear in our default' format(k nameData[k])) fdout write('\t' '|' '{} = {} does not appear in our default' format(k nameData[k]) '\t' '|' '\r\n') print ('{} = {} does not appear in our default' format(k nameData[k])) ```` | You will benefit pretty considerably from a couple of things First off you can quickly create dictionaries from each file using something like this: ````d1 = dict(l strip() split('=') for l in open('file1 txt')) ```` That is going to give you a much cleaner way of accessing your individual values Next when comparing the two dictionaries something like this is pretty reasonable: ````for key value in d1 items(): if key not in d2: print "Key '%s' from d1 not in d2" % key continue value2 = d2[key] # other comparison / output code here ```` |
django:error with the custom inclusiong_tag error info:Invalid block tag I am trying to write a custom inclusion_tag in django Following the example on <a href="http://docs djangoproject com/en/dev/howto/custom-template-tags/" rel="nofollow">http://docs djangoproject com/en/dev/howto/custom-template-tags/</a> I am just writing ````from django import template from libmas import models register = template Library() @register inclusion_tag('records html') def display_records(book_id): book = models book objects get(id__exact=book_id) records = models objects filter(books=book)[0:10] return {'records':records} ```` But I am getting a ````Invalid block tag: 'libmas_tags' ```` error in ie 'records html' file: ````{% for record in records %} <blockquote>{{record id}}</blockquote> {% endfor %} ```` my other html file is : ````{% extends "admin/change_form html" %} {% libmas_tags %} {% block after_field_sets %} {% if object_id %} {% display_records object_id %} {% endif %} {% endlock %} ```` | The problem lies in your template Its calling `{% libmas_tags %}` Have you created template tags called libmas_tags? If so you might need to change it to ````{% load libmas_tags %} ```` |
How to redistribute points evenly over a curve I have some arbitrary curve in 3 dimensions made up of a list of XYZ cartesian points The points are not evenly distributed (there is a time factor) How can I 'rebuild' the curve with a given number of points that should make up the curve I see this done in 3D modeling programs so i am pretty sure its possible I just do not know how <img src="http://i stack imgur com/GEEeD jpg" alt="enter image description here"> Based on the answer i needed it in python so i started working to convert interparc into python I got as far as the linear interpolation It is probably inefficient and has redundancies but maybe it will be useful to someone <a href="http://pastebin com/L9NFvJyA" rel="nofollow">http://pastebin com/L9NFvJyA</a> | Not sure I am following but instead of storing the actual data maybe store the delta from point to point then rebuild the curve from the deltas so there would not be any empty spots? This would however change the shape of the curve |
How can I tell what directory an imported library comes from in python? I am trying to modify a python library that I downloaded and am using But the changes I am making are not doing anything So I suspect that python is importing a different copy of this library from somewhere else on the filesystem So When I run `import foolib` in python how can I tell where on the filesystem it is getting that library from? | Look at the `foolib __file__` |
How to use standard toolbar icons with WxPython? I am designing a simple text editor using WxPython and I want to put the platform's native icons in the toolbar It seems that the only way to make toolbars is with custom images which are not good for portability Is there some kind of (e g ) GetSaveIcon()? | I do not think wxPython provides native images on each platform but just for consistency sake you can use wx ArtProvider e g wx ArtProvider GetBitmap(wx ART_FILE_OPEN) |
Unable to use math lib functions in my class I am writing a python class to handle vectors for my physics course However for some reason I cannot access the functions from the`math` library As I am not sure what I am doing wrong I will just include the entirety of the class: ````class vector: from math import sqrt cos sin atan degrees def __init__(self x=0 y=0): self components = (x y) self printmode = ('c') #sets a preexisting vector to the given magnitude and direction #uses cartesian rotation (+x is zero goes counter-clockwise) #Takes radians def rotmag (self magnitude direction): self components[0] = cos(direction) * magnitude self components[1] = sin(direction) * magnitude #this overrides the built-in addition function so you can just #add vector a and vector b by typing a+b def __add__(self other): newX = self components[0]+other components[0] newY = self components[1]+other components[1] return vector(newX newY) #returns the rotation and direction of the specified vector #returns a tuple same standards as rotmag def getrotmag (self) : mag = sqrt(self components[0]**2+self components[1]**2) dir = atan(self components[1]/self components[0]) return (mag dir) def __str__(self): if(self printmode == 'r'): tempray = self getrotmag() return(str(round(tempray[0] 4))+' @ '+str(round(tempray[1] 4))+' radians') if(self printmode == would'): tempray = self getrotmag() return(str(round(degrees(tempray[0]) 4))+' @ '+str(round(degrees(tempray[1]) 4))+' radians') if(self printmode == 'c'): return('x component: '+str(round(self components[0] 4))+' y component: '+str(round(self components[1] 4))) ```` Any help that you can give is much apprecaited | This is worked: ````from math import sqrt cos sin atan degrees class vector: ```` This is error: ````class vector: from math import sqrt cos sin atan degrees ```` |
Wireframe joins the wrong way in numpy matplotlib mplot3d I am trying to create a 3D wireframe in Python using matplotlib When I get to the actual graph plotting however the wireframe joins the wrong way as shown in the images below How can I force matplotlib to join the wireframe along a certain axis? My code is below: ````import numpy as np import matplotlib pyplot as plt from mpl_toolkits mplot3d import axes3d def rossler(x_n y_n z_n h a b c): #defining the rossler function x_n1=x_n+h*(-y_n-z_n) y_n1=y_n+h*(x_n+a*y_n) z_n1=z_n+h*(b+z_n*(x_n-c)) return x_n1 y_n1 z_n1 #defining a b and c a = 1 0/5 0 b = 1 0/5 0 c = 5 #defining time limits and steps t_0 = 0 t_f = 32*np pi h = 0 01 steps = int((t_f-t_0)/h) #3dify c_list = np linspace(5 10 6) c_size = len(c_list) c_array = np zeros((c_size steps)) for i in range (0 c_size): for j in range (0 steps): c_array[i][j] = c_list[i] #create plotting values t = np zeros((c_size steps)) for i in range (0 c_size): t[i] = np linspace(t_0 t_f steps) x = np zeros((c_size steps)) y = np zeros((c_size steps)) z = np zeros((c_size steps)) binvar array_size = x shape #initial conditions x[0] = 0 y[0] = 0 z[0] = 0 for j in range(0 c_size-1): for i in range(array_size-1): c = c_list[j] #re-evaluate the values of the x-arrays depending on the initial conditions [x[j][i+1] y[j][i+1] z[j][i+1]]=rossler(x[j][i] y[j][i] z[j][i] t[j][i+1]-t[j][i] a b c) fig = plt figure() ax = fig add_subplot(111 projection='3d') ax plot_wireframe(t x c_array rstride=10 cstride=10) plt show() ```` I am getting this as an output: <a href="http://i stack imgur com/mZXRG png" rel="nofollow"><img src="http://i stack imgur com/mZXRG png" alt="enter image description here"></a> The same output from another angle: <a href="http://i stack imgur com/VwAlC png" rel="nofollow"><img src="http://i stack imgur com/VwAlC png" alt="enter image description here"></a> Whereas I would like the wireframe to join along the wave-peaks Sorry I cannot give you an image I would like to see that is my problem but I guess it would be more like the tutorial image | I am quite unsure about what you are exactly trying to achieve but I do not think it will work Here is what your data looks like when plotted layer by layer (without and with filling): <a href="http://i stack imgur com/mkbEq png" rel="nofollow"><img src="http://i stack imgur com/mkbEqm png" alt="no filling"></a> <a href="http://i stack imgur com/qdcRF png" rel="nofollow"><img src="http://i stack imgur com/qdcRFm png" alt="filling"></a> You are trying to plot this as a wireframe plot Here is how a wireframe plot looks like as per <a href="http://matplotlib org/mpl_toolkits/mplot3d/tutorial html#mpl_toolkits mplot3d Axes3D plot_wireframe" rel="nofollow">the manual</a>: <a href="http://i stack imgur com/mBXla png" rel="nofollow"><img src="http://i stack imgur com/mBXla png" alt="sample wireframe"></a> Note the huge differene: a wireframe plot is essentially a proper surface plot the only difference is that the faces of the surface are fully transparent This also implies that you can only plot - single-valued functions of the form z(x y) which are furthermore - specified on a rectangular mesh (at least topologically) Your data is neither: your points are given along <them>lines</them> and they are stacked on top of each other so there is no chance that this is a single surface that can be plotted If you just want to visualize your functions above each other here is how I plotted the above figures: ````from mpl_toolkits mplot3d art3d import Poly3DCollection fig = plt figure() ax = fig add_subplot(111 projection='3d') for zind in range(t shape[0]): tnow xnow cnow = t[zind :] x[zind :] c_array[zind :] hplot = ax plot(tnow xnow cnow) # alternatively fill: stride = 10 tnow xnow cnow = tnow[::stride] xnow[::stride] cnow[::stride] slice_from = slice(None -1) slice_to = slice(1 None) xpoly = np array([tnow[slice_from] tnow[slice_to] tnow[slice_to] tnow[slice_from]] ) T ypoly = np array([xnow[slice_from] xnow[slice_to] np zeros_like(xnow[slice_to]) np zeros_like(xnow[slice_from])] ) T zpoly = np array([cnow[slice_from] cnow[slice_to] cnow[slice_to] cnow[slice_from]] ) T tmppoly = [tuple(zip(xrow yrow zrow)) for xrow yrow zrow in zip(xpoly ypoly zpoly)] poly3dcoll = Poly3DCollection(tmppoly linewidth=0 0) poly3dcoll set_edgecolor(hplot[0] get_color()) poly3dcoll set_facecolor(hplot[0] get_color()) ax add_collection3d(poly3dcoll) plt xlabel('t') plt ylabel('x') plt show() ```` There is one other option: switching your coordinate axes such that the (x t) pair corresponds to a vertical plane rather than a horizontal one In this case your functions for various `c` values are drawn on parallel planes This allows a wireframe plot to be used properly but since your functions have extrema in different time steps the result is as confusing as your original plot You <them>can</them> try using very few plots along the `t` axis and hoping that the extrema are close This approach needs so much guesswork that I did not try to do this myself You can plot each function as a filled surface instead though: ````from matplotlib collections import PolyCollection fig = plt figure() ax = fig add_subplot(111 projection='3d') for zind in range(t shape[0]): tnow xnow cnow = t[zind :] x[zind :] c_array[zind :] hplot = ax plot(tnow cnow xnow) # alternative to fill: stride = 10 tnow xnow cnow = tnow[::stride] xnow[::stride] cnow[::stride] slice_from = slice(None -1) slice_to = slice(1 None) xpoly = np array([tnow[slice_from] tnow[slice_to] tnow[slice_to] tnow[slice_from]] ) T ypoly = np array([xnow[slice_from] xnow[slice_to] np zeros_like(xnow[slice_to]) np zeros_like(xnow[slice_from])] ) T tmppoly = [tuple(zip(xrow yrow)) for xrow yrow in zip(xpoly ypoly)] polycoll = PolyCollection(tmppoly linewidth=0 5) polycoll set_edgecolor(hplot[0] get_color()) polycoll set_facecolor(hplot[0] get_color()) ax add_collection3d(polycoll zdir='y' zs=cnow[0]) hplot[0] set_color('none') ax set_xlabel('t') ax set_zlabel('x') plt show() ```` This results in something like this: <a href="http://i stack imgur com/DNsGG png" rel="nofollow"><img src="http://i stack imgur com/DNsGG png" alt="rotated filled plot"></a> There are a few things to note however - 3d scatter and wire plots are very hard to comprehend due to the lacking depth information You might be approaching your visualization problem in a fundamentally wrong way: maybe there are other options with which you can visualize your data - Even if you do something like the plots I showed you should be aware that matplotlib has historically been failing to plot complicated 3d objects properly Now by "properly" I mean "with physically reasonable apparent depth" see also <a href="http://matplotlib org/mpl_toolkits/mplot3d/faq html#my-3d-plot-doesn-t-look-right-at-certain-viewing-angles" rel="nofollow">the mplot3d FAQ note</a> describing exactly this The core of the problem is that matplotlib projects every 3d object to 2d and draws these pancakes on the sreen one after the other Sometimes the asserted drawing order of the pancakes does not correspond to their actual relative depth which leads to artifacts that are both very obvious to humans and uncanny to look at If you take a closer look at the first filled plot in this post you will see that the gold flat plot is behind the magenta one even though it should be on top of it Similar things often happen with <a href="http://stackoverflow com/questions/35246780/is-it-possible-to-superimpose-3-d-bar-charts-in-matplotlib/35248519#35248519">3d bar plots</a> and <a href="http://stackoverflow com/a/35101731/5067311">convoluted surfaces</a> - When you are saying "<them>Sorry I cannot give you an image I would like to see that is my problem</them>" you are very wrong It is not just your problem It might be crystal clear in your head what you are trying to achieve but unless you <them>very</them> clearly describe what you see in your head the outside world will have to resort to guesswork You can make the work of others and yourself alike easier by trying to be as informative as possible |
How can I build an RPM package with dependencies? I would like to create an RPM package from a python project on CentOS with setuptools But I am not able to include some dependencies via a spec in a correct way I would like to Install OS dependencies (and integrate in RPM) ```` - gcc - python-devel - python-setuptools ```` and Install Python dependencies (and integrate in RPM) ```` - psutil - rsa - pyaes - pyyaml ```` So anyone have an idea or some hints for the right way to include this dependencies? | in your spec file you just need to say your rpm needs other packages to be installed: ````Requires: gcc python-devel python-setuptools ```` same for the python dependencies: ````Requires: python-psutil python-rsa python-pyaes python-PyYAML ```` Note that you need to know the exact rpm names (for example on opensuse I found rpm <strong>python-PyYAML</strong> but did not find any rpm yet containing python pyaes) For further reading: <a href="http://rpm5 org/docs/rpm-guide html#id3037649" rel="nofollow">http://rpm5 org/docs/rpm-guide html#id3037649</a> |
What is one of the most important qualifications for a communications professional to have? | excellent writing ability |
Python function - Global variable not defined I joined a course to learn programming with Python For a certain assignment we had to write the code which I have pasted below This part of the code consist of two functions the first one being `make_str_from_row` and the second one being `contains_word_in_row` As you might have noticed the second function reuses the first function I already have passed the first function but I cannot pass the second one because when it has to reuse it gives an error about the first function which is confusing because I did not get any errors for my first function It says that global variable `row_index` is not defined By the way the second function has been given in a starter code so it cannot be wrong I do not know what is wrong especially because I have passed the code which presumable has to be wrong I tried asking the team for some feedback in case it might be some error in the grader but it has been a week and I have had no reply while the deadline is 2 days away I am not asking for answers here I only would like to ask somebody for an explanation about the given error so I can figure out a solution myself I would really appreciate the help ````def makestrfromrow(board rowindex): """ (list of list of str int) > str Return the characters from the row of the board with index row_index as a single string >>> make_str_from_row([['A' 'N' 'T' 'T'] ['X' 'S' 'OF 'B']] 0) 'ANTT' """ string = '' for i in board[row_index]: string = string i return string def boardcontainswordinrow(board word): """ (list of list of str str) > bool Return True if and only if one or more of the rows of the board contains word Precondition: board has at least one row and one column and word is a valid word >>> board_contains_word_in_row([['A' 'N' 'T' 'T'] ['X' 'S' 'OF 'B']] 'SOB') True """ for row_index in range(len(board)): if word in make_str_from_row(board row_index): return True return False ```` | You named the argument `rowindex` but use the name `row_index` in the function body Fix one or the other Demo fixing the name used in the body of the function to match the argument: ````>>> def makestrfromrow(board rowindex): string = '' for i in board[rowindex]: string = string i return string >>> makestrfromrow([['A' 'N' 'T' 'T'] ['X' 'S' 'OF 'B']] 0) 'ANTT' ```` Do note that both this function and `boardcontainswordinrow` are <them>not</them> consistent with the docstring; there they are named as `make_str_from_row` and `board_contains_word_in_row` Your `boardcontainswordinrow` function <them>uses</them> `make_str_from_row` not `makestrfromrow` so you will have to correct that as well; one direction or the other |
PHP socket client not returning full response I have a Python socket server and a PHP socket client The client sends a command to the server and then displays the response on the page It works perfectly almost all the time Now the issue I have is that when it comes to long responses the response seems to cut of It is not the Python server as you get the complete response via Telnet It is something with the PHP script that I cannot for the life of me figure out <strong>Output from Telnet:</strong> ````{ "status":1 "ramPerc":25 "console":"[12:49:18 INFO]: --------- Help: Index ---------------------------\n[12:49:18 INFO]: Use /help [n] to get page n of help \n[12:49:18 INFO]: Aliases: Lists command aliases\n[12:49:18 INFO]: Bukkit: All commands for Bukkit\n[12:49:18 INFO]: Minecraft: All commands for Minecraft\n[12:49:18 INFO]: /achievement: Gives the specified player an achievement or changes a statistic value Use '*' to give all achievements \n[12:49:18 INFO]: /ban: Prevents the specified player from using this server\n[12:49:18 INFO]: /ban-ip: Prevents the specified IP address from using this server\n[12:49:18 INFO]: /banlist: View all players banned from this server\n[12:49:18 INFO]: /clear: Clears the player's inventory Can specify item and data filters too \n[12:49:18 INFO]: /defaultgamemode: Set the default gamemode\n[12:49:18 INFO]: /deop: Takes the specified player's operator status\n[12:49:18 INFO]: /difficulty: Sets the game difficulty\n[12:49:18 INFO]: /effect: Adds/Removes effects on players\n[12:49:18 INFO]: /enchant: Adds enchantments to the item the player is currently holding Specify 0 for the level to remove an enchantment Specify force to ignore normal enchantment restrictions\n[12:49:18 INFO]: /gamemode: Changes the player to a specific game mode\n[12:49:18 INFO]: /gamerule: Sets a server's game rules\n[12:49:18 INFO]: /give: Gives the specified player a certain amount of items\n[12:49:18 INFO]: /help: Shows the help menu\n[12:49:18 INFO]: /kick: Removes the specified player from the server\n[12:49:18 INFO]: /kill: Commits suicide only usable as a player\n[12:49:18 INFO]: /list: Lists all online players\n[12:49:18 INFO]: /me: Performs the specified action in chat\n[12:49:18 INFO]: /minecraft:achievement: A Mojang provided command \n[12:49:18 INFO]: /minecraft:ban: A Mojang provided command \n[12:49:18 INFO]: /minecraft:ban-ip: A Mojang provided command \n[12:49:18 INFO]: /minecraft:banlist: A Mojang provided command \n[12:49:18 INFO]: /minecraft:clear: A Mojang provided command \n[12:49:18 INFO]: /minecraft:defaultgamemode: A Mojang provided command \n[12:49:18 INFO]: /minecraft:deop: A Mojang provided command \n[12:49:18 INFO]: /minecraft:difficulty: A Mojang provided command \n[12:49:18 INFO]: /minecraft:effect: A Mojang provided command \n[12:49:18 INFO]: /minecraft:enchant: A Mojang provided command \n[12:49:18 INFO]: /minecraft:gamemode: A Mojang provided command \n[12:49:18 INFO]: /minecraft:gamerule: A Mojang provided command \n[12:49:18 INFO]: /minecraft:give: A Mojang provided command \n[12:49:18 INFO]: /minecraft:help: A Mojang provided command \n[12:49:18 INFO]: /minecraft:kick: A Mojang provided command \n[12:49:18 INFO]: /minecraft:kill: A Mojang provided command \n[12:49:18 INFO]: /minecraft:list: A Mojang provided command \n[12:49:18 INFO]: /minecraft:me: A Mojang provided command \n[12:49:18 INFO]: /minecraft:op: A Mojang provided command \n[12:49:18 INFO]: /minecraft:pardon: A Mojang provided command \n[12:49:18 INFO]: /minecraft:pardon-ip: A Mojang provided command \n[12:49:18 INFO]: /minecraft:playsound: A Mojang provided command \n[12:49:18 INFO]: /minecraft:say: A Mojang provided command \n[12:49:18 INFO]: /minecraft:scoreboard: A Mojang provided command \n[12:49:18 INFO]: /minecraft:seed: A Mojang provided command \n[12:49:18 INFO]: /minecraft:setidletimeout: A Mojang provided command \n[12:49:18 INFO]: /minecraft:setworldspawn: A Mojang provided command \n[12:49:18 INFO]: /minecraft:spawnpoint: A Mojang provided command \n[12:49:18 INFO]: /minecraft:spreadplayers: A Mojang provided command \n[12:49:18 INFO]: /minecraft:tell: A Mojang provided command \n[12:49:18 INFO]: /minecraft:testfor: A Mojang provided command \n[12:49:18 INFO]: /minecraft:time: A Mojang provided command \n[12:49:18 INFO]: /minecraft:toggledownfall: A Mojang provided command \n[12:49:18 INFO]: /minecraft:tp: A Mojang provided command \n[12:49:18 INFO]: /minecraft:weather: A Mojang provided command \n[12:49:18 INFO]: /minecraft:whitelist: A Mojang provided command \n[12:49:18 INFO]: /minecraft:xp: A Mojang provided command \n[12:49:18 INFO]: /netstat: A Mojang provided command \n[12:49:18 INFO]: /op: Gives the specified player operator status\n[12:49:18 INFO]: /pardon: Allows the specified player to use this server\n[12:49:18 INFO]: /pardon-ip: Allows the specified IP address to use this server\n[12:49:18 INFO]: /playsound: Plays a sound to a given player\n[12:49:18 INFO]: /plugins: Gets a list of plugins running on the server\n[12:49:18 INFO]: /reload: Reloads the server configuration and plugins\n[12:49:18 INFO]: /restart: Restarts the server\n[12:49:18 INFO]: /save-all: Saves the server to disk\n[12:49:18 INFO]: /save-off: Disables server autosaving\n[12:49:18 INFO]: /save-on: Enables server autosaving\n[12:49:18 INFO]: /say: Broadcasts the given message as the sender\n[12:49:18 INFO]: /scoreboard: Scoreboard control\n[12:49:18 INFO]: /seed: Shows the world seed\n[12:49:18 INFO]: /setblock: A Mojang provided command \n[12:49:18 INFO]: /setidletimeout: Sets the server's idle timeout\n[12:49:18 INFO]: /setworldspawn: Sets a worlds's spawn point If no coordinates are specified the player's coordinates will be used \n[12:49:18 INFO]: /spawnpoint: Sets a player's spawn point\n[12:49:18 INFO]: /spreadplayers: Spreads players around a point\n[12:49:18 INFO]: /stop: Stops the server with optional reason\n[12:49:18 INFO]: /summon: A Mojang provided command \n[12:49:18 INFO]: /tell: Sends a private message to the given player\n[12:49:18 INFO]: /tellraw: A Mojang provided command \n[12:49:18 INFO]: /testfor: Tests whether a specifed player is online\n[12:49:18 INFO]: /testforblock: A Mojang provided command \n[12:49:18 INFO]: /time: Changes the time on each world\n[12:49:18 INFO]: /timings: Manages Spigot Timings data to see performance of the server \n[12:49:18 INFO]: /toggledownfall: Toggles rain on/off on a given world\n[12:49:18 INFO]: /tp: Teleports the given player (or yourself) to another player or coordinates\n[12:49:18 INFO]: /tps: Gets the current ticks per second for the server\n[12:49:18 INFO]: /version: Gets the version of this server including any plugins in use\n[12:49:18 INFO]: /weather: Changes the weather\n[12:49:18 INFO]: /whitelist: Manages the list of players allowed to use this server\n[12:49:18 INFO]: /xp: Gives: the specified player a certain amount of experience Specify <amount>L to give levels instead with a negative amount resulting in taking levels \n" "ram":517 "players":[ ] "ramMax":2048 "cpu":1 } ```` <strong>And output from PHP script:</strong> ````{ "status": 1 "ramPerc": 16 "console": "[12:57:42 INFO]: --------- Help: Index ---------------------------\n[12:57:42 INFO]: Use /help [n] to get page n of help \n[12:57:42 INFO]: Aliases: Lists command aliases\n[12:57:42 INFO]: Bukkit: All commands for Bukkit\n[12:57:42 INFO]: Minecraft: All commands for Minecraft\n[12:57:42 INFO]: /achievement: Gives the specified player an achievement or changes a statistic value Use '*' to give all achievements \n[12:57:42 INFO]: /ban: Prevents the specified player from using this server\n[12:57:42 INFO]: /ban-ip: Prevents the specified IP address from using this server\n[12:57:42 INFO]: /banlist: View all players banned from this server\n[12:57:42 INFO]: /clear: Clears the player's inventory Can specify item and data filters too \n[12:57:42 INFO]: /defaultgamemode: Set the default gamemode\n[12:57:42 INFO]: /deop: Takes the specified player's operator status\n[12:57:42 INFO]: /difficulty: Sets the game difficulty\n[12:57:42 INFO]: /effect: Adds/Removes effects on players\n[12:57:42 INFO]: /enchant: Adds enchantments to the item the player is currently holding Specify 0 for the level to remove an enchantment Specify force to ignore normal enchantment restrictions\n[12:57:42 INFO]: /gamemode: Changes the player to a specific game mode\n[12:57:42 INFO]: /gamerule: Sets a server's game rules\n[12:57:42 INFO]: /give: Gives the specified player a certain amount of items\n[12:57:42 INFO]: ```` I have searched around for a few weeks and tried everything but cannot figure out the issue <strong>Here is the PHP script behind all this:</strong> ````public function send($cmd $host $port $timeout = 1 5){ // Get time of function start $startTime = time(); //Try to create a socket if(!($socket = socket_create(AF_INET SOCK_STREAM SOL_TCP))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); //If failed die with error (Check docs) die("Error (#300)"); } if(!socket_set_nonblock($socket)){ die("Error (#301)"); } while(!@socket_connect($socket $host $port)){ if ((time() - $startTime) >= $timeout){ die("Error (#302)"); } continue; } if(!socket_set_block($socket)){ die("Error (#303)"); } if(!socket_write($socket $cmd strlen($cmd))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Error (#304)"); } $reply = socket_read($socket 16384) or die("Error (#305)"); socket_close($socket); return $reply; } ```` If anyone knows how to solve this issue please help me Thanks in advance! | You should test the return value of <a href="http://php net/manual/en/function socket-write php" rel="nofollow">`socket_write()`</a> whether it did send as much data as it was told to send that is `strlen($cmd)` bytes If this is not the case write the rest to the socket until all data was send out From the <a href="http://php net/manual/en/function socket-write php" rel="nofollow">`socket_write()`</a>'s documentation: <blockquote> <strong>socket_write()</strong> does not necessarily write all bytes from the given buffer It is valid that depending on the network buffers etc only a certain amount of data even one byte is written though your buffer is greater You have to watch out so you do not unintentionally forget to transmit the rest of your data </blockquote> |
Is encryption exposed in pisa at all? I need to be able to allow a user to save and preview a PDF file but <them>not</them> print it The reportlab instructions seem pretty straightforward but I did not see it in the docs for pisa Thanks! | Previously I was using POD Appy Framework It is very ease and clean to handle You can check the document <a href="http://appyframework org/pod html" rel="nofollow">http://appyframework org/pod html</a> |
Running "IDLE3 2 -s" from the "Finder" in OS X 10 6 I want to run IDLE3 2 with the argument "-s" so it can read " pythonstartup" and export relevant modules change the working directory and etc Here is what I have tried: - Created a she will script: ````/usr/local/bin/idle3 2 -s ```` this works allright however running the script from the Finder opens up the Terminal which is not the desired behavior - Created an applescript: ````do she will script "/bin/bash; cd /usr/local/bin/; /idle3 2 -s" ```` this get rids of the terminal however fails to pass "-s" argument to idle3 2 so the configuration file is not loaded any suggestions? <strong>EDIT: turns out environment variables are not properly set</strong> even though /bin/bash is called so the following solves the problem: ````do she will script "/bin/bash; source ~/ profile; /usr/local/bin/idle3 2 -s" ```` | I think your `do she will script "/bin/bash; cd /usr/local/bin; /idle3 2 -s"` is doing extra work and can probably be done more simply Try: ````do she will script "/usr/local/bin/idle3 2 -s" ```` |
Is there a way to make rfind() case insensitive? I am parsing a bunch of files for specific urls The subdirectory can be upper-case lower-case or camel-case in these: ````search = "http://website com/content/" subdirectory "/?" begin = contents rfind(search) ```` It would be great for this to work regardless of the case of the sub-directory | ````begin = contents lower() rfind(search lower()) ```` |
parsing c++ in python I am looking to parse c++ code files in python I am mostly concerned with only the function declarations not the definitions The kind of output GCCXML gives seems perfect to me but the thing is I cannot get GCCXML to work I cannot find proper documentation All the articles I found online are old and possibly outdated Can anyone suggest any other alternative? Or and updated links regarding GCCXML I am using Python 3 4 2 and IDLE | Clang has an API that can be used for code completion and more AFAIK with python bindings |
sqlalchemy unicode issue Hi I am dvelopping an application in python with sqlalchemy and mysql 5 1 58-1ubuntu1 I can get data from db without problem except that I can not read not ascii characters like è ò or the euro symbol instead of the euro I get \u20ac this is how I create the engine for mysqlalchemy ````dbfile="root:########@localhost/parafarmacie" engine = create_engine("mysql+mysqldb://"+dbfile+"?charset=utf8&use_unicode=0") ```` all my columns that work with text are declared as Unicode I googled for days but without any luck someone could tell me where is my mistake? thanks in advance | When you get your unicode objects from the database before you output them you need to encode them: ````my_unicode_object encode("utf-8") ```` What you are seeing now is the raw repr of the unicode object which shows you the code point (since it has not been converted to bytes yet) :-) |
How to use pymongo for writing/reading to two different mongo servers (with different versions of mongo 2 4 and 3 0 3) I have two mongo databases on two different servers One server is mongo 2 4 and the other is mongo 3 0 3 How would I get a single python app server to connect and read from both? From pip it looks like I can only install one version of pymongo thus making it impossible to access both databases Does anyone know of a way this can be done? | According to <a href="http://docs mongodb org/ecosystem/drivers/python/" rel="nofollow">documentation</a> PyMongo 3 0 supports both MongoDB 2 4 and MongoDB 3 0 Thus you just need to create two corresponding <a href="http://api mongodb org/python/current/api/pymongo/mongo_client html" rel="nofollow">MongoClient</a> instances and use them as you need to |
serializing a json file from list of list So i have a list of elements: ````elements = [room1 room2 room3] ```` I also have a list of key/value attributes that each room has: ````keys = ["level" "finish1" "finish2"] values = [["ground" "paint1" "carpet1"] ["ground" "paint1" "paint2"] ["second level" "paint1" "paint2"]] ```` is there a way to serialize this two lists into a json file structured like this: ````{'room1': [{'level': 'ground' 'finish1': 'paint1' 'finish2': 'carpet1'}] 'room2': [{'level': 'ground' 'finish1': 'paint1' 'finish2': 'paint2'}] 'room3': [{'level': 'second level' 'finish1': 'paint1' 'finish2': 'paint2'}]} ```` I am on this weird platform that does not support dictionaries so I created a class for them: ````class collection(): def __init__(self name key value): self name = name self dict = {} self dict[key] = value def __str__(self): x = str(self name) " collection" for key value in self dict iteritems(): x = x '\n'+ ' %s= %s ' % (key value) return x ```` then i found a peiece of code that would allow me to create a basic json code from two parallel lists: ````def json_list(keys values): lst = [] for pn dn in zip(values keys): d = {} d[dn]=pn lst append(d) return json dumps(lst) ```` but this code desnt give me the {room1: [{ structure Any ideas would be great This software I am working with is based on IronPython2 7 Ok so the above worked great I got a great feedback from Comments I have one more variation that I did not account for Sometimes when I try to mix more than singe element type (rooms columns etc) they might not have the same amount of attributes For example a room can have (level finish and finish) while column might have only thickness and material If i kept it all organized in parallel lists key/value is it possible to modify the definition below: ````keys = [[thickness material] [level finish finish]] values = [[100 paint] [ground paint paint]] elements = [column room] ```` How would i need to modify the definition below to make it work? Again I want to export a json file | I do not know how Python can even work without dictionaries so please just test this and tell me the error it shows you: ````import json elements = ['r1' 'r2' 'r3'] keys = ["level" "finish1" "finish2"] values = [["ground" "paint1" "carpet1"] ["ground" "paint1" "paint2"] ["second level" "paint1" "paint2"]] d = dict() for (index room) in enumerate(elements): d[room] = dict() for (index2 key) in enumerate(keys): d[room][key] = values[index][index2] print json dumps(d) ```` |
Sqlite manipulates the string out of the database In my login method I am trying to check wether the password in the database corresponds to the password submitted by the user I use this code: ````@app route('/login' methods=['GET' 'POST']) def login(): error = None db = get_db() if request method == 'POST': cur = db execute('select password from users where username = ?' (request form['username'] )) password = cur fetchone() print password print request form['password'] if request form['password'] != password: error = 'Invalid username/password combination' else: session['logged_in'] = True flash('You were logged in') return redirect(url_for('show_entries')) return render_template('login html' error=error) ```` For example when the password is default this what the print commands show me: ````print password : (you'default' ) print request form['password'] : default ```` So they are indeed not equal Does anybody knows how to fix this? | Each row returned by the database is a tuple of columns You retrieved one row (` fetchone()`) and that row is a tuple with one element (you selected only the `password` column) Simply take it <them>out</them> from the tuple using it is index: ````password = cur fetchone()[0] ```` |
Replace element text I read <a href="http://stackoverflow com/questions/1812764/replacing-elements-with-lxml-html">here</a> that in order to replace an element text I would just have to use `replace` For some reason in my code it throws this error: ````AttributeError: 'lxml etree _ElementTree' object has no attribute 'replace' ```` Here is the code: ````from lxml import etree old = 'Hello' new = 'bye' xml replace(currentText newText) ```` The code above is simplified What I want is to replace one tag text with another text | No no _ElementTree replace actualy replaces subelement with element passed as second argument All you need to is: ````xml text = new_text ```` By the way <a href="http://lxml de" rel="nofollow">http://lxml de</a> can be wery useful it have a lot of information and code examples for such cases |
Django Override password encryption I am currently developing a tool in Python using Django in which I have to import an existing User database Obviously password for these existing users have not the same encryption than the default password encryption used by Django I want to override the encryption for the password method to keep my passwords unmodified I do not find how to override existing method in the documentation just found how to add information about user (I do not find how to remove information - like first name or last name - about user either so if someone knows tell me please) Thank you for your help | In Django the way user is authenticated is not done in the User model itself Django uses other modules to do just that In your case you can create your custom module for checking the password and add it in your `settings py` (<a href="https://docs djangoproject com/en/1 5/ref/settings/#std%3asetting-PASSWORD_HASHERS" rel="nofollow">docs</a>) One cool thing about Django is that you can supply multiple of these hashers to do that auth Let Us say your current hash method is not as secure as some of the methods Django uses Then if you add your custom hasher to the bottom of `PASSWORD_HASHERS` the following can happen If the user's password who is trying to login is stored using your custom method then Django will try the first hasher and it will fail Then it will try the rest of the hashes and they all will fail except your custom hasher However since the user is successfully authenticated and since the successful hasher is not the first hasher then Django will automatically rehash the password using the first defined hasher This way you can gracefully upgrade to a more secure hash algorithm for the passwords as users keep logging in Also if you are migrating your current database and the users table does not match the Django user model keep in mind that starting with Django 1 5 you can define your custom `User` model instead of Django's |
Python - creating a struct with ' ' from an array of strings I am new to python and wondering if how I can create data struct using ' ' For example given an array of strings ````mystr=['aaa' 'bbb' 'ccc'] commonstr = 'zzz' for str in mystr # something like creating ' ' struct self = __create_dot_struct_with_value__(self str str+commonstr) ```` So the result will look like ````self aaa = 'aaazzz' self bbb = 'bbbzzz' self ccc = 'ccczzz' ```` How can I do this? Thanks! | Use <a href="https://docs python org/2/library/functions html#setattr" rel="nofollow">`setattr`</a>: ````class x(object): pass for item in mystr: setattr(x item item commonstr) ```` Now you can do things like `x aaa` and have it return `aaazzz` `setattr` let us you add object attributes dynamically I would be very wary of using it inside an existing class unless you are absolutely sure it will not mess up the rest of your class but if you just want a dummy class this is a good way to do it |
Python (2 7) dictionary Jinja confusion Here is what I thought would work: I have a dictionary indexed by game and containing gameSlots Confirmed that: {{gameSlot game name}} is valid (and other gameSlot game x properties are also fine) Confirmed that: assignedGameSlotsInMyGames was holding a {game: [gameSlot1 gameSlot1]} But: {% for gameSlot2 in assignedGameSlotsInMyGames[gameSlot game] %} has no iterations Am I doing something obviously wrong? (I can post more complete code if needed - I have swapped out the code with a pretty ugly workaround but would be happy to bring it back to show test results etc ) More details added Data is: assignedGameSlotsInMyGames contains one game (named "Later") which has two assigned gameSlots The workaround prints the contents of those gameSlots: ````{% for game gameSlots in assignedGameSlotsInMyGames iteritems() %} {% if gameSlot game name == game name %} {% for gameSlot2 in gameSlots %} <tr> <td> {{gameSlot2 user email}} </td> <td> {{gameSlot2 gameCharacter characterType}} </td> </tr> {% endfor %} {% endif %} {% endfor %} ```` Additional Note: The reason that there is: ````if gameSlot game name == game name ```` is that I am iterating through all the gameSlots that belong to a particular user As I display that gameSlot I want to include additional information about the game referred to by that gameSlot Since my attempt (below) to directly reference that game did not work I loop through all the games and use the one that matches the current game in the "outer loop" (lame yes - which is why I am posting the question) Note: for the example I was testing there is just one game with the name "Later" There is an outer loop that is moving through all the gameSlot games - the only iteration is when gameSlot game name == "Later" Rather than all this extra loop I thought I could use: ````{% for gameSlot2 in assignedGameSlotsInMyGames[gameSlot game] %} <tr><td>Iteration</td></tr> {% endfor %} ```` I was thinking that since assignedGameSlotsInMyGames is a Dictionary indexed by a game object with values that are gameSlots this should work But there are no iterations printed Debugging code of: ````<tr><td colspan="6">TestCode - gameSlot game = {{gameSlot game}} assignedGameSlotsInMyGames[gameSlot game] = {{assignedGameSlotsInMyGames[gameSlot game]}} </td></tr> <tr><td colspan="6">TestCode - gameSlot game name = {{gameSlot game name}} assignedGameSlotsInMyGames = {{assignedGameSlotsInMyGames}}</td></tr> <tr><td colspan="6">Test from Ellochka - assignedGameSlotsInMyGames game = {{assignedGameSlotsInMyGames game}}</td></tr> ```` Has output: ````TestCode - gameSlot game = assignedGameSlotsInMyGames[gameSlot game] = TestCode - gameSlot game name = Later assignedGameSlotsInMyGames = {: [ ]} Test from Ellochka - assignedGameSlotsInMyGames game = ```` This is my first experience with Jinja2 templates (and Python) so I could be very confused | ````from jinja2 import Template ts = """ {% for game gameSlots in assignedGameSlotsInMyGames iteritems() %} {% for gameSlot2 in gameSlots %} <tr> <td> {{gameSlot2 user email}} </td> <td> {{gameSlot2 gameCharacter characterType}} </td> </tr> {% endfor %} {% endfor %} """ t = Template(ts) d = {'assignedGameSlotsInMyGames': {'game1': [{'user': {'email': 'a@a ru'} 'gameCharacter':{'characterType':'testCharacterType1'}} {'user': {'email': 'b@b ru'} 'gameCharacter':{'characterType':'testCharacterType2'}}] 'game2': [{'user': {'email': 'a2@a ru'} 'gameCharacter':{'characterType':'testCharacterType12'}} {'user': {'email': 'b2@b ru'} 'gameCharacter':{'characterType':'testCharacterType22'}}] } } print t render(d) ```` The output is: ````<tr> <td> a2@a ru </td> <td> testCharacterType12 </td> </tr> <tr> <td> b2@b ru </td> <td> testCharacterType22 </td> </tr> <tr> <td> a@a ru </td> <td> testCharacterType1 </td> </tr> <tr> <td> b@b ru </td> <td> testCharacterType2 </td> </tr> ```` In your template I do not understand what `{% if gameSlot game name == game name %}` is You pass the key gameSlot separately or is it just a typo and you meant to write gameSlots? For quite a clear answer you can write about the structure of the dictionary (example) that you pass to the render function(or etc) and I will tell where the error if still is not clear <strong>UPDATED</strong> ````ts = """ {% for g in games %} {% for v in ags[g game]%} {{ v }} {% endfor %} {% endfor %} """ d = { 'games':[{'game':'A'} {'game':'B'} {'game':'C'}] 'ags':{'A':['ONE' 'TWO' 'THREE'] 'B':['1' '2' '3']} } t = Template(ts) print t render(d) ```` Output: ````ONE TWO THREE 1 2 3 ```` The only thing I can suggest you pass data to function uncorrectly and inappropriately handle them See the <a href="http://jinja pocoo org/docs/templates/#variables" rel="nofollow">documentation</a> |
multiple bar plots from pandas dataframe So I have a data frame like ````exp_name index items clicks "foo" 0 "apple" 200 "foo" 0 "banana" 300 "foo" 0 "melon" 220 "foo" 1 "apple" 10 "foo" 1 "peach" 20 "bar" 0 "apple" 400 "bar" 0 'banana' 500 "bar" 0 "melon" 240 "bar" 1 "apple" 500 ```` and so on I want to plot for each experiment name bar plots of number of clicks for each item in each index but colored by index So basically plot 1 for experiment "foo" a bar plots where index == 0 all the barplots for index 0 in one color index 1 in another color if the item is missing (for example peach is in "foo" 1 but not in any other place) replace "peach" to be zero in other places | I copy/paste your data into a txt file called 'test txt' and rename "index" as "status" to avoid confusion with the DataFrame index Then I use the <a href="https://stanford edu/~mwaskom/software/seaborn/tutorial/categorical html?highlight=estimator" rel="nofollow">Seaborn</a> library to make barplots with the contingencies you mention (and as I understand them) I use subplots rather than use color to set apart "status" because I personally think it looks cleaner but I use colors below since that is what you asked about ````import pandas as pd import seaborn as sns from matplotlib import pyplot as plt df = pd read_csv('test txt') fig ax = sns plt subplots(1 1 figsize=(7 5)) sns factorplot(x="items" y="clicks" hue="exp_name" col="status" data=df kind="bar") plt show() ```` Gives the following:<a href="http://i stack imgur com/19i2T png" rel="nofollow"><img src="http://i stack imgur com/19i2T png" alt="enter image description here"></a> If you really want to distinguish "index" (what I call "status") by color you might define a new variable which combines "exp_name" with "status" ````df['exp'] = df exp_name df status astype(str) sns factorplot(x="items" y="clicks" hue="exp" data=df kind="bar") ```` Gives something like this <a href="http://i stack imgur com/B9t8D png" rel="nofollow"><img src="http://i stack imgur com/B9t8D png" alt="enter image description here"></a> Check out the docs for <a href="https://stanford edu/~mwaskom/software/seaborn/tutorial/categorical html?highlight=estimator" rel="nofollow">seaborn</a> if you have more questions It is a really great library for categorical data Changing the legend labels and other settings follows matplotlib conventions |
What is the official journal of New York City? | the City Record |
Python threading flow control in concise way I want to upload a file to two ftp sites After both finishing I need to delete the file In case not to block the main function running both ftp and deletion functions will be implemented by threading which means there will be 3 threads running in background simultaneously An easy problem becomes complicated because of threading Following are possible solutions: - Use a queue and put all three threads in order - Use mutex Both work but I do not think they are the best way to do that Can anyone share his/her idea? | Use a <them>semaphore</them> In your parent handler create a semaphore of 0 and hand it off to the threads ````import threading sem = threading Semaphore(0) hostThread = threading Thread(target=uploadToHost args=(sem )) backupThread = threading Thread(target=uploadToBackup args=(sem )) sem acquire() # Wait for one of them to finish sem acquire() # Wait for the other to finish ```` In your children you will just have to call `sem release` once the upload is finished |
How do I use cvxopt for mean variance optimization with constraints? I am able to use cvxopt to calculate an efficient frontier per the docs: <a href="http://cvxopt org/examples/book/portfolio html" rel="nofollow">http://cvxopt org/examples/book/portfolio html</a> However I cannot figure out how to add a constraint so that there is an upper bound on a particular asset's maximum allowed weight Is that possible using cvxopt? Here is my code so far that produces an efficient frontier with no constraints except I believe b which sets the max sum of weights to 1 I am not sure what G h A and mus do and the docs do not really explain Where does the 10**(5 0*t/N-1 0) in the formula for mus come from? ````from math import sqrt from cvxopt import matrix from cvxopt blas import dot from cvxopt solvers import qp options # Number of assets n = 4 # Convariance matrix S = matrix( [[ 4e-2 6e-3 -4e-3 0 0 ] [ 6e-3 1e-2 0 0 0 0 ] [-4e-3 0 0 2 5e-3 0 0 ] [ 0 0 0 0 0 0 0 0 ]] ) # Expected return pbar = matrix([ 12 10 07 03]) # nxn matrix of 0s G = matrix(0 0 (n n)) # Convert G to negative identity matrix G[::n+1] = -1 0 # nx1 matrix of 0s h = matrix(0 0 (n 1)) # 1xn matrix of 1s A = matrix(1 0 (1 n)) # scalar of 1 0 b = matrix(1 0) N = 100 mus = [ 10**(5 0*t/N-1 0) for t in range(N) ] options['show_progress'] = False xs = [ qp(mu*S -pbar G h A b)['x'] for mu in mus ] returns = [ dot(pbar x) for x in xs ] risks = [ sqrt(dot(x S*x)) for x in xs ] #Efficient frontier plt plot(risks returns) ```` | You are using the quadratic programming solver of the cvxopt package check out the <a href="http://cvxopt org/userguide/coneprog html#quadratic-programming" rel="nofollow">documentation</a> As you can see from the formula there `Gx <= h` are the inequality constraints and `Ax = b` are the equality constraints `G` and `A` are matrices while `h` and `b` and are vectors Let us assume you want to restrict you are first asset to weights between 2% and 5% you would formulate this as follows: ````G = matrix([[-1 0 0 0] [ 1 0 0 0]]) h = matrix([[-0 02] [0 05]]) ```` Note that the first row is turning the inequality condition into `Gx >= h` by multiplying by -1 The conditions you have above set all assets to bounds between 0% and 100% the common no short selling condition The formula your using is explained <a href="http://en wikipedia org/wiki/Modern_portfolio_theory#The_efficient_frontier_with_no_risk-free_asset" rel="nofollow">here</a>: your `mu`is `q`in the Wikipedia article and therefore a risk-tolerance parameter It does not really matter if you attach it to the covariance or return part of the target function It just means that you are either walking from the top right corner to the bottom left or the other way round for each value of `mu` So it is just a function that gives you a risk-tolerance from very small to very big I think there is a mistake though in that the series start at 0 1 but should really start at 0 |
wxGrid Scroll method Is there anyway to set the grid position using a function other than Scroll Scroll function will not do anything if Grid Scrollbars are set to to wx SHOW_SB_NEVER ````import wx import wx grid as gridlib grid = gridlib Grid(parent wx ID_ANY) grid ShowScrollbars(wx SHOW_SB_NEVER wx SHOW_SB_NEVER) # now Scroll method will not work anymore and scrolling to certain position does nothing grid Scroll(100 100) # it does nothing anymore ```` The same way there is grid GetViewStart() method is there anything or any turnaround to Scroll or something like grid SetViewStart thanks | I think using something like `MakeCellVisible()` may be a better choice rather than the arbitrary `Scroll()` |
When was it announced a tri would be a television series? | null |
How did Hume view inductive vs deductive reasoning? | competitive |