input_text
stringlengths 1
40.1k
| target_text
stringlengths 1
29.4k
⌀ |
---|---|
Unicode in Python In Python 2 7's documentation three rules about Unicode are described as follows: <blockquote> If the code point is <128 itâs represented by the corresponding byte value If the code point is between 128 and `0x7ff` itâs turned into two byte values between 128 and 255 Code points >`0x7ff` are turned into three- or four-byte sequences where each byte of the sequence is between 128 and 255 </blockquote> Then I made some tests about it: ````>>>> unichr(40960) you'\ua000' >>> ord(you'\ua000') 40960 ```` In my view 40960 is a code point > `0x7ff` so it should be turned into three- or four-byte sequences where each byte of the sequence is between 128 and 255 but it only be turned into two-bytes sequence and the value '00' in you'\a000' is lower than 128 not matched with the rules mentioned above Why? What is more I found some more Unicode characters such as `you'\u1234'` etc I found that the value ("12" && "34") in it is also lower than 128 but according to the thoery mentioned first they should not be lower than 128 Any other theories that I lost? Thanks for all answers | Those rules only apply for UTF-8 Python uses UCS-2 or UCS-4 internally which have fixed sizes <a href="http://www joelonsoftware com/articles/Unicode html" rel="nofollow">"The Absolute Minimum Every Software Developer Absolutely Positively Must Know About Unicode and Character Sets (No Excuses!)"</a> <blockquote> and the value '00' in you'\a000' is lower than 128 not matched with the rules mentioned above </blockquote> I do not even want to <strong>know</strong> why you think they can be split up like this |
Python convert binary file into string while ignoring non-ascii characters I have a binary file and I want to extract all ascii characters while ignoring non-ascii ones Currently I have: ````with open(filename 'rb') as fobj: text = fobj read() decode('utf-16-le') file = open("text txt" "w") file write("{}" format(text)) file close ```` However I am encountering an error when writing to file `UnicodeEncodeError: 'ascii' codec cannot encode character you'\xa0' in position 0: ordinal not in range(128)` How would I get Python to ignore non-ascii? | Use the built-in ASCII codec and tell it to ignore any errors like: ````with open(filename 'rb') as fobj: text = fobj read() decode('utf-16-le') file = open("text txt" "w") file write("{}" format(text encode('ascii' 'ignore')) file close() ```` You can test & play around with this in the Python interpreter: ````>>> s = you'hello \u00a0 there' >>> s you'hello \xa0 there' ```` Just trying to convert to a string throws an exception ````>>> str(s) Traceback (most recent call last): File "<stdin>" line 1 in <module> UnicodeEncodeError: 'ascii' codec cannot encode character you'\xa0' in position 6: ordinal not in range(128) ```` as does just trying to encode that unicode string to ASCII: ````>>> s encode('ascii') Traceback (most recent call last): File "<stdin>" line 1 in <module> UnicodeEncodeError: 'ascii' codec cannot encode character you'\xa0' in position 6: ordinal not in range(128) ```` but telling the codec to ignore the characters it cannot handle works okay: ````>>> s encode('ascii' 'ignore') 'hello there' ```` |
caffe installation : opencv libpng16 so 16 linkage issues I am trying to compile caffe with python interface on an Ubuntu 14 04 machine I have installed Anaconda and opencv with `conda install opencv` I have also installed all the requirement stipulated in the coffee and changed the commentary blocks in `makefile config` so that PYTHON_LIB and PYTHON_INCLUDE point towards Anaconda distributions When I am calling `make all` the following command is issued: ````g++ build_release/tools/caffe o -o build_release/tools/caffe bin -pthread -fPIC -DNDEBUG -O2 -DWITH_PYTHON_LAYER -I/home/andrei/anaconda/include -I/home/andrei/anaconda/include/python2 7 -I/home/andrei/anaconda/lib/python2 7/site-packages/numpy/core/include -I/usr/local/include -I/home/andrei/anaconda/lib -I/lib/x86_64-linux-gnu -I/lib64 -I/usr/lib/x86_64-linux-gnu -I build_release/src -I /src -I /include -I/usr/include -Wall -Wno-sign-compare -lcaffe -L/home/andrei/anaconda/lib -L/home/andrei/anaconda/lib/ / / -L/usr/local/lib -L/usr/lib -L/home/andrei/anaconda/lib/ / /libpng16 so 16 -L/lib/x86_64-linux-gnu -L/lib64 -L/usr/lib/x86_64-linux-gnu -L/usr/lib -L build_release/lib -lcudart -lcublas -lcurand -lglog -lgflags -lprotobuf -lleveldb -lsnappy -llmdb -lboost_system -lhdf5_hl -lhdf5 -lm -lopencv_core -lopencv_highgui -lopencv_imgproc -lboost_thread -lstdc++ -lboost_python -lpython2 7 -lcblas -latlas \ -Wl -rpath \$ORIGIN/ /lib ```` However it is stopped by the following set of errors: ````/usr/bin/ld: warning: libpng16 so 16 needed by /home/andrei/anaconda/lib/libopencv_highgui so not found (try using -rpath or -rpath-link) /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_create_read_struct@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_interlace_handling@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_IHDR@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_get_io_ptr@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_longjmp_fn@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_gray_to_rgb@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_compression_level@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_bgr@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_filter@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_rgb_to_gray@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_init_io@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_destroy_read_struct@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_swap@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_get_IHDR@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_palette_to_rgb@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_compression_strategy@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_get_tRNS@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_write_info@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_packing@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_read_fn@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_create_info_struct@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_read_end@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_read_update_info@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_write_image@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_write_end@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_expand_gray_1_2_4_to_8@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_create_write_struct@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_read_image@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_read_info@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_strip_alpha@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_write_fn@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_destroy_write_struct@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_error@PNG16_0' /home/andrei/anaconda/lib/libopencv_highgui so: undefined reference to `png_set_strip_16@PNG16_0' ```` Following the advice from this question: <a href="http://stackoverflow com/questions/31962975/caffe-install-on-ubuntu-for-anaconda-with-python-2-7-fails-with-libpng16-so-16-n">Caffe install on ubuntu for anaconda with python 2 7 fails with libpng16 so 16 not found</a> I tired running the `ldd /home/andrei/anaconda/lib/libopencv_highgui` and obtained the following output: ````linux-vdso so 1 => (0x00007fff1a104000) libopencv_core so 2 4 => /home/andrei/anaconda/lib/ / /libopencv_core so 2 4 (0x00007ff18e8a0000) libopencv_imgproc so 2 4 => /home/andrei/anaconda/lib/ / /libopencv_imgproc so 2 4 (0x00007ff18e3f0000) libdl so 2 => /lib/x86_64-linux-gnu/libdl so 2 (0x00007ff18e1ec000) libpthread so 0 => /lib/x86_64-linux-gnu/libpthread so 0 (0x00007ff18dfce000) librt so 1 => /lib/x86_64-linux-gnu/librt so 1 (0x00007ff18ddc6000) libz so 1 => /home/andrei/anaconda/lib/ / /libz so 1 (0x00007ff18dbb0000) libjpeg so 8 => /home/andrei/anaconda/lib/ / /libjpeg so 8 (0x00007ff18d979000) libpng16 so 16 => /home/andrei/anaconda/lib/ / /libpng16 so 16 (0x00007ff18d737000) libgthread-2 0 so 0 => /usr/lib/x86_64-linux-gnu/libgthread-2 0 so 0 (0x00007ff18d535000) libglib-2 0 so 0 => /lib/x86_64-linux-gnu/libglib-2 0 so 0 (0x00007ff18d22d000) libstdc++ so 6 => /usr/lib/x86_64-linux-gnu/libstdc++ so 6 (0x00007ff18cf29000) libm so 6 => /lib/x86_64-linux-gnu/libm so 6 (0x00007ff18cc23000) libgcc_s so 1 => /lib/x86_64-linux-gnu/libgcc_s so 1 (0x00007ff18ca0d000) libc so 6 => /lib/x86_64-linux-gnu/libc so 6 (0x00007ff18c648000) /lib64/ld-linux-x86-64 so 2 (0x00007ff18f0d0000) libpcre so 3 => /lib/x86_64-linux-gnu/libpcre so 3 (0x00007ff18c40a000) ```` I then proceeded to add all the required directories into the `INCLUDE_DIRS` and `LIBRARY_DIRS` of the `make config` file (hence additional `-I` and `-L` in the `g++` call above) including the explicit link to `libpng16 so 16` already present in anaconda libraries This have however not resolved the issue I also tried adding the file to `$LD_LIBRARY_PATH` and `$LD_RUN_PATH` but without any effect What might the problem be and how could I resolve it? | I am guessing you have added `/home/andrei/anaconda/bin` to the `PATH` environment variable so that `libpng-config` resolves to `/home/andrei/anaconda/bin/libpng16-config` which is what is causing `cmake` to try and link with libpng v1 6 Strip the `anaconda` dir from your `PATH` environment variable and `libpng-config` should default to libpng v1 2 in `/usr/lib` or similar |
gridlib cell format in python I am using a gridlib within wxpanel I am creating the following grid: ```` myGrid = gridlib Grid(panel) myGrid CreateGrid(120 9) ```` I want to be able to change the format of the 5th column and make it a dropdown (meaning the options the user can enter are pre-defined) Is there a way to do that ? Basically I am looking for a call like the following: myGrid setFormat(5 wx Dropdown ("I" "you" "they")) or something like that Is that possible or do I need to look for a different grid object in python If so what is that one? | The wxPython demo includes a grid editor for creating custom editors / renderers In that demo it shows how to add a dropdown (combobox) called the GridCellChoiceEditor I would recommend taking a look at that and integrating it into your own application |
zen of Python vs with statement - philosophical pondering I do not intend to simply waste your time but: <strong>has it occurred to you too while using Python's `with` statement that it really is contrary to the 5th line of "The Zen of Python" that goes "Flat is better than nested"? Can any enlightened Python guru share me some of their insights on this?</strong> (I always find that one more level of indentation pops up in my code every time I use `with` instead of `f close()` and it is not like I am not going to use `try: finally: ` anyways and thus the benefits of `with` still elude me even as I grow to like and understand Python more and more ) <hr> @glglgl (sorry I cannot find a way to write code in comments): yes but if you go the `with` way your code becomes: ````try: with file( ) as f: except IOError: ```` and using just with without the `try` is what people end up doing in the type of hacky "one use" code where they use `f close()` instead of with anyways (which is bad because the file may not be closed if an exception is thrown before their `f close()`) so for "hacky" code people just do not use `with` because I do not know I guess they just find it too "fancy" and for well structured code it does not bring any benefits anyways so it seems to me there is no real world use case left for it that was my pondering about really | You mention it already: It is cleaner to do ````f = file( ) try: # do work on file finally: f close() ```` than just closing after the file operations - which would not be reached if an exception occurs If you compare the `try/finally` to `with` you have the same level of indentation so you do not lose anything If however you do exception handling you have one more level of indentation which is indeed against the said Zen point OTOH `with` encapsulates things and makes using them easier and more readable which are other Zen aspects It seems impossible to me to always follow every Zen aspect exactly; sometimes you have to weigh one against the other In this case you "lose" one level of indentation but you get a better readability and maintainability The latter seems to be an advantage to me |
Unable to load images/files pisa pdf Django python I had a problem before where it would not show Chinese characters even when I specified `@font-face` to use a UTF-8 font It turns out I cannot display images as well so I seems like I am unable to get any of the files embeded into my pdf This is the code I use: ````def render_to_pdf(template_src context_dict): """Function to render html template into a pdf file""" template = get_template(template_src) context = Context(context_dict) html = template render(context) result = StringIO StringIO() pdf = pisa pisaDocument(StringIO StringIO(html encode("UTF-8")) dest=result encoding='UTF-8' link_callback=fetch_resources) if not pdf err: response = http HttpResponse(result getvalue() mimetype='application/pdf') return response return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) def fetch_resources(uri rel): import os path from django conf import settings path = os path join( settings STATIC_ROOT uri replace(settings STATIC_URL "")) return path ```` html ````<img src="/static/images/bc_logo_bw_pdf png" /> ```` and ```` @font-face { font-family: "Wingdings"; src: url("/static/fonts/wingdings ttf"); } ```` I looked at the other quests on SO but it was no help There are also no exceptions happening in the two functions Also in `fetch_resources` function the path returned was the correct full path to the file i e `/home/<user>/project/static/images/bc_logo_bw_pdf png` and `/home/<user>/project/static/fonts/wingdings ttf` and I am at a loss as to what is wrong <strong>UPDATE</strong> Everytime I create a pdf I get this message on the console ````No handlers could be found for logger "ho pisa" ```` could this be related? <strong>UPDATE #2</strong> The font works now I made a dumb mistake The font I was using did not have the Chinese unicode But I still cannot embed any images onto the pdf be it jpeg gif or png | I have the same problem here Do not give up with XHTML2PDF Pisa <br/> Pisa use PIL for generate PDF and use lib zip decoder to inserting images <br/> You should check if your PIL already installed properly with zip decoder fonts and several components<br/> I have solve this problem by installing PIL with zip decoder <br/> <a href="http://obroll com/install-python-pil-python-image-library-on-ubuntu-11-10-oneiric/" rel="nofollow">http://obroll com/install-python-pil-python-image-library-on-ubuntu-11-10-oneiric/</a> If you need more detail information you can read my article here : <a href="http://obroll com/how-to-load-images-files-style-css-in-pdf-using-pisa-xhtml2pdf-on-django/" rel="nofollow">http://obroll com/how-to-load-images-files-style-css-in-pdf-using-pisa-xhtml2pdf-on-django/</a> |
Wrapping an instance in a subclass's constructor before returning I hope the title is not too wrong or misleading; I am not entirely sure what the name is for this kind of thing Basically I have been doing a lot of work with dictionaries (and some subclasses thereof: `defaultdict` and `OrderedDict` for instance) and am trying to just make a few helper functions which will do some of this lifting for me while still operating across a number of different types of dictionary Ideally I would like to do this quickly (that is with some amount of optimization) and of course elegantly Here is an example of what I have now: ````def filter_dict(old_dict keep_keys): return {k:v for k v in old_dict items() if k in keep_keys} ```` This works well but if `old_dict` is anything other than a basic dictionary I lose that Okay so I can do something like `type(old_dict)({ })` to wrap the newly created dictionary in old_dict's class's constructor but that still does not work for defaultdicts which take <them>as a first argument</them> a function returning default value If it were second argument I could just pass some `*args` or something to a constructor but this complicates things I guess my question is: can I get a partial application to a constructor? Can I get the guts of that instance and call its class constructor with everything intact except for the `items`? In Haskell I would do something like `reverse = lambda f x *args: f(*args x)` but that is not even allowed in Python What am I missing? Some introspection into the classes? Tinkering with `__new__`? Factory somethingoranother? I feel really dumb here trying to get something pretty but functional (har) Thanks in advance for any insight | I would copy the original object then change the copy In your example: ````def filter_dict(old_dict keep_keys): res = old_dict copy() for k in res keys(): if k not in keep_keys: res pop(k) return res ```` It sounds like your helper functions only know about the things they want to change in `old_dict` not the things they want to keep the same So the safest way seems to be to rely on the `copy` method (or the `copy` module) and then remove or change what you do not want Otherwise you need some way to recall exactly what arguments were used to create the object and I do not know if a general method for doing this exists |
date type changed after strptime and then strftime? New to Python so I have question as following Why a is not equal to b? Thank you ````fundData['SigDate'] 0 31DEC2008 1 31JAN2009 2 28FEB2009 3 31MAR2009 4 30APR2009 a=fundData['SigDate'] b=fundData['SigDate'] apply(lambda x : datetime strptime(x '%d%b%Y') strftime('%d%b%Y')) a==b 0 False 1 False 2 False 3 False ```` | The `'strptime/strftime'` transformation returns a string in <them>sentence case</them> for the month entry so your comparison is rightly `False`: ````>>> from datetime import datetime as dt >>> >>> x = "31DEC2008" >>> dt strptime(x '%d%b%Y') strftime('%d%b%Y') '31Dec2008' >>> >>> '31Dec2008' == '31DEC2008' False ```` <hr> You can call `upper` on the string returned in your <them>lambda</them> function to make them match: ````>>> dt strptime(x '%d%b%Y') strftime('%d%b%Y') upper() '31DEC2008' ```` |
How to make Python's findall regular expression method inclusive I have a string that looks as follows `s = 'string with %%substring1%% and %%substring2%%'` I want to extract the text in the substrings <them>including the `%%`</them> and I cannot figure out how to make a regular expression inclusive For example `re findall('%%( *?)%%' s re DOTALL)` will output `['substring1' 'substring2']` but what I really want is for it to return `['%%substring1%%' '%%substring2%%']` Any suggestions? | You were quite near Put the group to match the entire required portion rather than only the string in between ````>>> s = 'string with %%substring1%% and %%substring2%%' >>> import re >>> re findall('(%% *?%%)' s re DOTALL) ['%%substring1%%' '%%substring2%%'] ```` You actually do not need the parens at all! ````>>> re findall('%% *?%%' s re DOTALL) # Even this works !!! ['%%substring1%%' '%%substring2%%'] ```` And for some visualization check this out <img src="https://www debuggex com/i/HFb9DVAVtl2UTXz_ png" alt="Regular expression visualization"> <a href="https://www debuggex com/r/HFb9DVAVtl2UTXz_" rel="nofollow">Debuggex Demo</a> And check the explaination <a href="https://regex101 com/r/bQ6pA5/1#python" rel="nofollow">here</a> |
What organization ranked New Delhi 39th in economic activity in 2011? | World Wealth Report |
Python login to my cpanel with python I want to create a script with python that test if my combination (username and password) is correct but I always get a 401 HTTP response so i think the script cannot submit the login data (the cpanel login is not a traditional login panel so i will use the demo login panel as our example-site com) : ````import urllib urllib2 os sys re site = 'http://cpanel demo cpanel net/' username = 'demo' password = 'demo' headers = { "User-Agent" : "Mozilla/5 0 (Windows NT 6 1; WOW64; rv:28 0) Gecko/20100101 Firefox/28 0" "Accept" : "text/html application/xhtml+xml application/xml;q=0 9 */*;q=0 8" "Accept-Encoding" : "gzip deflate" "Accept-Charset" : "ISO-8859-1 utf-8;q=0 7 *;q=0 7"} data = [ ("user" username) ("pass" password) ("testcookie" 1) ("submit" "Log In") ("redirect_to" 'http://cpanel demo cpanel net/') ("rememberme" "forever")] req = urllib2 Request(site urllib urlencode(dict(data)) dict(headers)) response = urllib2 urlopen(req) if any('index html' in v for v in response headers values()) == True : print "Correct login" else : print "incorrect" ```` I get this error : ````Traceback (most recent call last): File "C:\Python27\cp\cp4 py" line 19 in <module> response = urllib2 urlopen(req) File "C:\Python27\lib\urllib2 py" line 126 in urlopen return _opener open(url data timeout) File "C:\Python27\lib\urllib2 py" line 400 in open response = meth(req response) File "C:\Python27\lib\urllib2 py" line 513 in http_response 'http' request response code message hdrs) File "C:\Python27\lib\urllib2 py" line 438 in error return self _call_chain(*args) File "C:\Python27\lib\urllib2 py" line 372 in _call_chain result = func(*args) File "C:\Python27\lib\urllib2 py" line 521 in http_error_default raise HTTPError(req get_full_url() code message hdrs fp) urllib2 HTTPError: HTTP Error 401: Access Denied ```` Any ideas to solve the problem and test the login details? | Consider using <a href="http://python-requests org" rel="nofollow">Requests</a> a much more user-friendly HTTP client library for Python ````import requests url = 'http://cpanel demo cpanel net/login/' username = 'demo' password = 'demo' headers = { 'User-Agent': 'Mozilla/5 0 (Windows NT 6 1; WOW64; rv:31 0) Gecko/20100101 Firefox/31 0' } data = { 'user': username 'pass': password } response = requests post(url headers=headers data=data) if response status_code == 200: print "Successfully logged in as {username}" format(username=username) else: print "Login unsuccessful: HTTP/{status_code}" format(status_code=response status_code) ```` Edited to check for HTTP/200 as CPanel does throw an HTTP/401 if the login is incorrect |
Using Logging with Multiprocessing Module I need to create a single logger that can be used throughout my python package but some of the functions implement multiprocessing I want all those functions to write to the same log file just like everything else I know at Python 3 2+ there is a built in way to do this but I need to back port to Python 2 7 x as well Is there any code out there that works well with both multiprocessing and non-multiprocessing functions for logging? Normally I would create a log as such: ````module = sys modules['__main__'] __file__ logging basicConfig(stream=sys stderr level=logging DEBUG format='%(name)s (%(levelname)s): %(message)s') log = logging getLogger(module) fh = RotatingFileHandler(arguments o mode='a' maxBytes=2*1024*1024 backupCount=2 encoding=None delay=0) formatter = logging Formatter('%(asctime)s - %(name)s - %(levelname)s - % (message)s') fh setFormatter(formatter) fh setLevel(logging DEBUG) log addHandler(fh) ```` Then the output would write to a single file It works great but when I implement this this code will create multiple files which I do not want Any ideas? Thank you | The functionality to do this in Python >= 3 2 (via the `QueueHandler` and `QueueListener` classes as described <a href="http://plumberjack blogspot co uk/2010/09/using-logging-with-multiprocessing html" rel="nofollow">here</a>) is available for Python 2 7 through the <a href="https://pypi python org/pypi/logutils" rel="nofollow">`logutils`</a> project |
How to combine an index "prefix" to the data in a Pandas series? Does one create a numpy array? I have a pandas series: ````import pandas ser = pd Series( ) ser idx1 23421535123415135 idx2 98762981356281343 idx3 394123942916498173 idx4 41234189756983411 idx50 123412938479283419 ```` I would like to combined the index append to the front of each data row The output I am looking for is: ````idx1 23421535123415135 idx2 98762981356281343 idx3 394123942916498173 idx4 41234189756983411 idx50 123412938479283419 ```` This could either be a pandas Series (where the array is naturally indexed) or a numpy array For a dataframe in order to combine two columns you use: ````df["newcolumn"] = df[['columnA' 'columnB']] astype(str) sum(axis=1) ```` but I am confused how to accomplish this with a pandas series | Say you start with your Series: ```` In [34]: s = pd Series(data=[1 2] index=['idx0' 'idx1']) ```` Then you can do ````In [35]: t = s reset_index() In [36]: t['index'] astype(str) ' ' t[0] astype(str) Out[36]: 0 idx0 1 1 idx1 2 dtype: object ```` Note that if you do not need to introduce the space in between it is shorter: ````In [37]: s reset_index() astype(str) sum(axis=1) Out[37]: 0 idx01 1 idx12 dtype: object ```` |
Who redesigned Blore's 1820 West Front? | null |
Exit while loop by user hitting ENTER key I am a python newbie and have been asked to carry out some exercises using while and for loops I have been asked to make a program loop until exit is requested by the user hitting `<Return>` only So far I have: ````User = raw_input('Enter <Carriage return> only to exit: ') running = 1 while running == 1: Run my program if User == # Not sure what to put here Break else running == 1 ```` I have tried: (as instructed in the exercise) ````if User == <Carriage return> ```` and also ````if User == <Return> ```` but this only results in invalid syntax Please could you advise me on how to do this in the simplest way possible Thanks | Use a print statement to see what `raw_input` returns when you hit `enter` Then change your test to compare to that |
Running Google AppEngine Python SDK on Raspberry Pi I am trying to run GAE for Python 2 7 on my Raspberry Pi Model B and I am following the tutorial exactly but any time I enter the "dev_appserver py" command it comes back: bash: dev_appserver py: command not found or sudo: dev_appserver py: command not found Is it not possible to run this on the Pi? | I do not have any experience with the Raspberry Pi but you could try prefixing it with `python` to indicate you want to execute the file with Python (your error means it is trying to execute the `dev_appserver py` command which it does not recognize): ````python /path/to/dev_appserver py /path/to/your/app ```` You could also adjust your paths to include `/path/to/google_appengine/` so that that location was searched and the command was found but again I am not familiar with Raspberry Pi so that may not be an option :) It appears (at least anecdotally) that <a href="https://groups google com/forum/#!message/google-appengine/oAFns0vAaXE/14lnjwk1RQEJ" rel="nofollow">someone</a> got it running but I imagine the performance would be lacking a bit |
Using hasattr and not hasattr in python I need to use python `hasattr` for my very specific purpose I need to check that an object is having an attribute and <them>not</them> having another attribute Consider the class object named `model` I need to check that whether it is having an attribute called `domain_id`: ````if hasattr(model 'domain_id'): ```` I also need to check for one more condition that it should not have attribute called `type` ````if not hasattr(model 'type'): ```` How to combine the two checks here? | Just combine the two conditions with `and`: ````if hasattr(model 'domain_id') and not hasattr(model 'type'): ```` The `if` block will only execute if both conditions are true |
How would one go about having a python script run automatically across all platforms? I am writing a fairly simple script that backs up files to AWS S3 But that is fairly irrelevant to my question at hand The user is going to specify how often they want the script to run probably through command line inputs I just want to run the one script just the once The other requirement is it needs to run on all platforms I discovered the CronTab module but that is only relevant to Linux and sometimes OSX Basically I am looking for a set it and forget it approach to a python script My other question does the scheduling have to happen in a separate script or is there a way to include the scheduling of running the script in the script itself? | This is in general a Platform dependent Scheduler Question For instance <a href="http://en wikipedia org/wiki/Cron" rel="nofollow">Cron</a> in *nix Windows <a href="http://windows microsoft com/en-in/windows7/schedule-a-task" rel="nofollow">Task Scheduler</a> in Windows <a href="http://publib boulder ibm com/infocenter/zos/v1r11/index jsp?topic=/com ibm zos r11 hasa300/ch2scen htm" rel="nofollow">JES2</a> in zOS Basically you need a demon process to automatically trigger Job You can also create a simple Python Script using <a href="http://docs python org/2/library/threading html#timer-objects" rel="nofollow">threading Timer</a> If you need a platform independent solution you can look forward to the following solution <a href="http://pythonhosted org/APScheduler/" rel="nofollow"> Advanced Python Scheduler</a> |
why am I getting an error using math sin(math pi) in python? I noticed a glitch while using math sin(math pi) The answer should have been 0 but instead it is 1 2246467991473532e-16 If the statement is math sin(math pi/2) the answer is 1 0 which is correct why this error? | Python does not do symbolic computation and pi is irrational So rounding error should not be surpising |
How to pass a parameter to only one part of a pipeline object in scikit learn? I need to pass a parameter `sample_weight` to my `RandomForestClassifier` like so: ````X = np array([[2 0 2 0 1 0 0 0 1 0 3 0 3 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 5 0 3 0 2 0 '0'] [15 0 2 0 5 0 5 0 0 466666666667 4 0 3 0 2 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 7 0 14 0 2 0 '0'] [3 0 4 0 3 0 1 0 1 33333333333 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 9 0 8 0 2 0 '0'] [3 0 2 0 3 0 0 0 0 666666666667 2 0 2 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 5 0 3 0 1 0 '0']] dtype=object) y = np array([ 0 0 1 0 ]) m = sklearn ensemble RandomForestClassifier( random_state=0 oob_score=True n_estimators=100 min_samples_leaf=5 max_depth=10) m fit(X y sample_weight=np array([3 4 2 3])) ```` The above code works perfectly fine Then I try to do this in a pipeline object like so using pipeline object instead of only random forest: ````m = sklearn pipeline Pipeline([ ('feature_selection' sklearn feature_selection SelectKBest( score_func=sklearn feature_selection f_regression k=25)) ('model' sklearn ensemble RandomForestClassifier( random_state=0 oob_score=True n_estimators=500 min_samples_leaf=5 max_depth=10))]) m fit(X y sample_weight=np array([3 4 2 3])) ```` Now this breaks in the `fit` method with "`ValueError: need more than 1 value to unpack`" ````ValueError Traceback (most recent call last) <ipython-input-212-c4299f5b3008> in <module>() 25 max_depth=10))]) 26 --> 27 m fit(X y sample_weights=np array([3 4 2 3])) /usr/local/lib/python2 7/dist-packages/sklearn/pipeline pyc in fit(self X y **fit_params) 128 data then fit the transformed data using the final estimator 129 """ -> 130 Xt fit_params = self _pre_transform(X y **fit_params) 131 self steps[-1][-1] fit(Xt y **fit_params) 132 return self /usr/local/lib/python2 7/dist-packages/sklearn/pipeline pyc in _pre_transform(self X y **fit_params) 113 fit_params_steps = dict((step {}) for step _ in self steps) 114 for pname pval in six iteritems(fit_params): -> 115 step param = pname split('__' 1) 116 fit_params_steps[step][param] = pval 117 Xt = X ValueError: need more than 1 value to unpack ```` I am using <them>`sklearn` version `0 14`</them> I think that the problem is that the `F selection` step in the pipeline does not take in an argument for sample_weights how do I pass this parameter to only one step in the pipeline with I run "`fit`"? Thanks | <a href="http://scikit-learn org/stable/modules/generated/sklearn pipeline Pipeline html" rel="nofollow">From the documentation:</a> <blockquote> The purpose of the pipeline is to assemble several steps that can be cross-validated together while setting different parameters For this it enables setting parameters of the various steps <strong>using their names and the parameter name separated by a â__â</strong> as in the example below </blockquote> So you can simply insert `model__` in front of whatever fit parameter kwargs you want to pass to your `'model'` step: ````m fit(X y model__sample_weight=np array([3 4 2 3])) ```` |
Double buffering with wxpython I am working on an multiplatform application with wxpython and I had flickering problems on windows while drawing on a Panel I used to draw on a buffer (wx Bitmap) during mouse motions events and my OnPaint method was composed of just on line: ````dc = wx BufferedPaintDC(self self buffer) ```` Pretty standard but still I had flickering problems on Windows while everything worked fine on Linux I <strong>solved my problem</strong> calling `SetDoubleBuffered(True)` in the `__init__` method The strange thing is that now everything works even if I do not use BufferedPaintDC anymore I changed my application so that all the drawing part is done in the OnPaint method I do not use a buffer and drawing is done directly on a wx PaintDC with no flickering problems at all So my question is: is BufferedPaintDC totally useless? Or deprecated somehow? I am owner of the book "WxPython in Action" (2006) and it does not even mention SetDoubleBuffered | There is a high probability that the SetDoubleBuffered actually makes your panel use a buffered dc automatically the documentation does not mention that those classes are deprecated (and I rather think they would if that were the case) About wxPython in Action 2006 was a long time ago it is possible that the SetDoubleBuffered method did not exist back then or that the author wanted to show how things work at the lower level |
Executing a command and storing its output in a variable I am currently trying to write a python script that among many things calls an executable and stores what that executable sends to stdout in a variable Here is what I have: ```` 1 #!/usr/bin/python 2 import subprocess 3 4 subprocess call(" /pmm" she will=True) ```` How would I get the output of pmm to be stored in a variable? | ````p = subprocess Popen([" /pmm"] she will=False stdout=subprocess PIPE) output = p stdout read() ```` |
Which is the closest Python equivalent to Perl::Tidy? Coming from Perl I have been used to hitting <kbd>C-c t</kbd> to reformat my code according to pre-defined `Perl::Tidy` rules Now with Python I am astonished to learn that there is nothing that even remotely resembles the power of `Perl::Tidy` PythonTidy 1 20 looks almost appropriate but barfed at first mis-aligned line ("unexpected indent") In particular I am looking for the following: - Put PEP-8 into use as far as possible (the following items are essentially derivations of this one) - Convert indentation tabs to spaces - Remove trailing spaces - Break up code according to the predefined line-length as far as it goes (Eclipse-style string splitting and splitting method chains) - Normalize whitespace around - (bonus feature optional) Re-format code including indentation Right now I am going throught someone else's code and correct everything `pep8` and `pyflakes` tell me which is mostly "remove trailing space" and "insert additional blank line" While I know that re-indentation is not trivial in Python (even though it should be possible just by going through the code and remembering the indentation) other features seem easy enough that I cannot believe nobody has implemented this before Any recommendations? <strong>Update</strong>: I am going to take a deeper look at PythonTidy since it seems to go into the right direction Maybe I can find out why it barfs at me | There is a `reindent py` script distributed with python in the `scripts` directory |
How to scrape AJAX website? In the past I have used the urllib2 library to get source codes from websites However I have noticed that for a recent website I have been trying to play with I cannot find the information I need in the source code <a href="http://www wgci com/playlist" rel="nofollow">http://www wgci com/playlist</a> is the site that I have been looking at and I want to get the most recently played song and the playlist of recent songs I essentially want to copy and paste the visible displayed text on a website and put it in a string Alternatively being able to access the element that holds these values in plaintext and get them using urllib2 normally would be nice Is there anyway to do either of these things? Thanks kindly | The website you want to scrap is using ajax calls to populate it is pages with data You have 2 ways to scrapping data from it: - Use a headless browser that supports javascript (ZombieJS for instance) and scrap the generated output but that is complicated and overkill - Understand how their API work and call that directly which is way simpler Use Chrome dev tools (network tab) to see the calls while browsing their website For example the list of last played songs for a given stream is available in JSON at <a href="http://www wgci com/services/now_playing html?streamId=841&limit=12" rel="nofollow">http://www wgci com/services/now_playing html?streamId=841&limit=12</a> |
Python: namedtuple _replace() does not work as descrbed in the documentation I was having trouble implementing `namedtuple _replace()` so I copied the code right off of the documentation: ````Point = namedtuple('Point' 'x y') p = Point(x=11 y=22) p _replace(x=33) print p ```` and I got: ````Point(x=11 y=22) ```` instead of: ````Point(x=33 y=22) ```` as is shown in the doc I am using Python 2 6 on Windows 7 What is going on? | <a href="http://docs python org/library/collections html#collections somenamedtuple _replace">`namedtuple _replace()`</a> returns a new tuple; the original is unchanged |
Treating an int like a class and giving it properties I want to give an `int` a function e g : ````>>> def x converttostring(): return str(self) >>> x = 1 >>> print x converttostring() '1' >>> print x 1 ```` ideally I want to have it operating on select ints not all ints e g ````>>> x converttostring() '1' >>> y converttostring() Traceback (most recent call last): AttributeError: 'int' object has no attribute 'converttostring' ```` Is it possible? The function part is essential (not `str(x)`) and creating a class is out of the question | I do not see any scenario where this is a correct solution but you may try creating a subclass: ````class MyInt(int): def custom_method(self): return "Int: " str(self) i = MyInt(3) assert i == 3 assert i+2 == 5 assert i custom_method() == "Int: 3" ```` |
py2exe sqlalchemy and cx_oracle: ImportError: No module named oracle I am trying to create a binary with py2exe here are last lines of py2exe output: ````*** copy dlls *** copying C:\Apps\Python27\python27 dll > C:\Documents and Settings\nikolay derka ch\Desktop\UMTScellsChecking\UMTScellsChecking\dist setting sys winver for 'C:\Documents and Settings\nikolay derkach\Desktop\UMTSce llsChecking\UMTScellsChecking\dist\python27 dll' to 'py2exe' copying C:\Apps\Python27\w9xpopen exe > C:\Documents and Settings\nikolay derka ch\Desktop\UMTScellsChecking\UMTScellsChecking\dist copying C:\Apps\Python27\lib\site-packages\py2exe\run exe > C:\Documents and Se ttings\nikolay derkach\Desktop\UMTScellsChecking\UMTScellsChecking\dist\UMTSCell Test exe The following modules appear to be missing ['_scproxy' 'sqlalchemy cprocessors' 'sqlalchemy cresultproxy' 'win32api' 'w in32con' 'win32pipe'] *** binary dependencies *** Your executable(s) also depend on these dlls which are not included you may or may not need to distribute them Make sure you have the license if you distribute any of them and make sure you do not distribute files belonging to the operating system USER32 dll - C:\WINDOWS\system32\USER32 dll SHELL32 dll - C:\WINDOWS\system32\SHELL32 dll WSOCK32 dll - C:\WINDOWS\system32\WSOCK32 dll ADVAPI32 dll - C:\WINDOWS\system32\ADVAPI32 dll WS2_32 dll - C:\WINDOWS\system32\WS2_32 dll KERNEL32 dll - C:\WINDOWS\system32\KERNEL32 dll ```` My original python script runs just fine but when I execute resulting binary I get the following: ````C:\Documents and Settings\nikolay derkach\Desktop\UMTScellsChecking\UMTScellsChe cking\dist>UMTSCellTest exe Traceback (most recent call last): File "UMTSCellTest py" line 53 in <module> File "sqlalchemy\engine\__init__ pyc" line 244 in create_engine File "sqlalchemy\engine\strategies pyc" line 46 in create File "sqlalchemy\engine\url pyc" line 99 in get_dialect ImportError: No module named oracle ```` Also here is my setup py which I use for py2exe: ````from distutils core import setup import py2exe sys sys argv append('py2exe') setup( options = {"py2exe": { 'bundle_files': 2 'compressed': True 'dll_excludes': ['oci dll']}} console=[{'script': 'UMTSCellTest py'}] ) ```` Any ideas what that ImportError could mean? Thanks in advance | You may need to specify explicitly to py2exe to import the package with the `packages` option A good way to check is to look in the build directory and see of the oracle module is actually there ````options = dict(optimize=2 bundle_files=2 compressed=True packages=["oracle"] dll_excludes=['oci dll']) setup_dict['options'] = {"py2exe":options} ```` |
IOError for oauth2 request when used with mod_wsgi Apache For a third party API I am using oauth2 module I have following code: Which works well when I use `python run py` but throws `IOError` permission denied when using `apache mod_wsgi` configuration Here is the error: ````ERROR: Traceback (most recent call last): File "/home/trex/workspace/scripts/flaskapp py" line 32 in getTwitter_acc_audiences _ content = client request(uri=uri method="GET") File "build/bdist linux-x86_64/egg/oauth2/__init__ py" line 687 in request connection_type=connection_type) File "/home/trex/workspace/myenv/lib/python2 7/site-packages/httplib2-0 9 2-py2 7 egg/httplib2/__init__ py" line 1609 in request (response content) = self _request(conn authority uri request_uri method body headers redirections cachekey) File "/home/trex/workspace/myenv/lib/python2 7/site-packages/httplib2-0 9 2-py2 7 egg/httplib2/__init__ py" line 1351 in _request (response content) = self _conn_request(conn request_uri method body headers) File "/home/trex/workspace/myenv/lib/python2 7/site-packages/httplib2-0 9 2-py2 7 egg/httplib2/__init__ py" line 1272 in _conn_request conn connect() File "/home/trex/workspace/myenv/lib/python2 7/site-packages/httplib2-0 9 2-py2 7 egg/httplib2/__init__ py" line 1036 in connect self disable_ssl_certificate_validation self ca_certs) File "/home/trex/workspace/myenv/lib/python2 7/site-packages/httplib2-0 9 2-py2 7 egg/httplib2/__init__ py" line 80 in _ssl_wrap_socket cert_reqs=cert_reqs ca_certs=ca_certs) File "/usr/lib/python2 7/ssl py" line 911 in wrap_socket ciphers=ciphers) File "/usr/lib/python2 7/ssl py" line 520 in __init__ self _context load_verify_locations(ca_certs) IOError: [Errno 13] Permission denied ```` api_manager py ```` import oauth2 as oauth from settings import * #-- All global params class APIManager(object): """ """ #init function goes here def get_api_content(self consumer_key consumer_secret access_token access_secret): """ Fetch API response using Oauth2 """ try: consumer = oauth Consumer(key=consumer_key secret=consumer_secret) token = oauth Token(key=access_token secret=access_secret) client = oauth Client(consumer token) uri = APIURL APIURI format(account_id=SOME_ACC_ID) _ content = client request(uri=uri method="GET") except Exception as e: logerror("ERROR:" e) content = {} return content ```` flaskapp py ````from flask import Flask jsonify from api_manager import APIManager from settings import * app = Flask(__name__) @app route("/") def callapi(): try: apiobj = APIManager() response = apiobj get_api_content(CONSUMER_KEY CONSUMER_SECRET ACCESS_TOKEN ACCESS_SECRET) except Exception e: logerror("ERROR:" e) return jsonify({}) return jsonify(response) ```` Apache WSGI Configuration: ````<VirtualHost _default_:443> # Default other config goes here WSGIScriptAlias / /home/trex/workspace/scripts/appwsgi py WSGIScriptReloading On <Directory "/home/trex/workspace/scripts"> <Files "appwsgi py"> Require all granted </Files> </Directory> </VirtualHost> ```` Let me know if anything else I can give you the details | There was an issue with permissions to my virtualenv Following file had permission issues ````myenv/lib/python2 7/site-packages/httplib2-0 9 2-py2 7 egg/httplib2/cacerts txt ```` And this simple fix fixed my issue: ````chmod -R 755 /home/trex/workspace/myenv ```` |
Strange python behaviour involving floats ints and sqlite I have a very strange bug that I cannot explain It occurs when I combine python and sqlite I have a table that contains a REAL field called stop_lat When I run the following code: ````c = conn cursor() c execute("select stop_lat from stops;") for (stop_lat ) in c: print stop_lat print type(stop_lat) stop_lat = int(stop_lat*1000) ```` I get the following output ````stop_lat <type 'unicode'> Traceback (most recent call last): File " /extract_data_tools/extract_trips py" line 47 in <module> stop_lat = int(stop_lat*1000) ValueError: invalid literal for int() with base 10: 'stop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_latstop_lat' ```` Now when I comment out the last line meaning I execute ````c = conn cursor() c execute("select stop_lat from stops;") for (stop_lat ) in c: print stop_lat print type(stop_lat) #stop_lat = int(stop_lat*1000) ```` I get the following output: ````37 743804 <type 'float'> 37 780889 <type 'float'> 37 772006 <type 'float'> 37 723433 <type 'float'> 37 783026 <type 'float'> ```` Meaning the type of stop_lat depends on whether I pass it to int that does not really make any sense to me It even gets stranger The following code ````c = conn cursor() c execute("select stop_lat from stops;") for (stop_lat ) in c: print stop_lat print type(stop_lat) stop_lat = stop_lat*1000 print stop_lat print type(stop_lat) ```` outputs ````37 780889 <type 'float'> 37780 889 <type 'float'> 37 772006 <type 'float'> 37772 006 <type 'float'> 37 723433 <type 'float'> 37723 433 <type 'float'> 37 783026 <type 'float'> 37783 026 <type 'float'> ```` Can anyone explain to me what is going on here? I can not reproduce the problem without sqlite being in the game (i e Code literals work as expected) | It looks to me like more is changing that the commented out line The first SQL statement appears to be running `select "stop_lat" from stops` and the other running without quotes: `select stop_lat from stops` |
What is the approximate modern value of two guineas in 1830? | £168 |
Python 3 - float(X) * i = int(Z) I have a very large number both before and after the decimal but for this I will just call it 4 58 I want to know the number Y that will yield me an integer if multiplied by X and not any sort of float number Here is my code: ````from decimal import * setcontext(ExtendedContext) getcontext() prec = 300 x=Decimal('4 58') while True: i=1 a=Decimal(i*x) if float(a) is_integer(): print(i*x) break else: i=+1 ```` However this method is incredibly slow and inefficient I was wondering how could I implement continued fractions or some other method to make it predict the value of Y? <them>Edit</them> The decimal module stores float numbers more accurately (As strings) so 0 5 <them>will not</them> become 0 499999999 <them>Edit 2</them> I have got X (4 58) I want to know what number will multiply by X to make an integer; as efficiently as possible <strong>Edit 3</strong> Okay maybe not my best question yet Here is my dilemma I have got a number spat out from a trivial programme I made That number is a decimal number 1 5 All I want to do is find what integer will multiply by my decimal to yield another integer For 1 5 the best answer will be 2 (1 5*2=3) (float*int=int) My while-loop above will do that eventually but I just wanted to know whether there was a better way to do this such as continued fractions; and if there was how could I implement it <them>Edit 4</them> Here is my code thanks to user6794072 It is lengthy but functional ````from gmpy2 import mpz isqrt from fractions import Fraction import operator import functools from decimal import * setcontext(ExtendedContext) getcontext() prec = 300 def factors(n): n = mpz(n) result = set() result |= {mpz(1) n} def all_multiples(result n factor): z = n f = mpz(factor) while z % f == 0: result |= {f z // f} f = factor return result result = all_multiples(result n 2) result = all_multiples(result n 3) for i in range(1 isqrt(n) 1 6): i1 = i 1 i2 = i 5 if not n % i1: result |= {mpz(i1) n // i1} if not n % i2: result |= {mpz(i2) n // i2} return result j=Decimal('4 58') a=(Fraction(j) numerator) b=(Fraction(j) denominator) y=(factors(a)) x=(factors(b)) q=([item for item in x if item not in y]) w=([item for item in y if item not in x]) q extend(w) p=(functools reduce(operator mul q 1)) ans=(p*j) print(ans) ```` | Well think of what if you wanted to reach `z = 1` and then use the fact that `z == z * 1` to scale the answer For any float `x != 0 0` `y = 1/x` will yield `z = 1` so for arbitrary integer `z` just use `y = z/x` |
XSL short `value-of` with `disable-output-escaping`? I am processing the following (example) XML: ````<?xml version="1 0"?> <root>&amp; &amp; &amp;</root> ```` through the following (example) XSL: ````<?xml version="1 0"?> <xsl:stylesheet version="1 0"> <xsl:output method="html" version="4 0" encoding="UTF-8" omit-xml-declaration="yes" /> <xsl:template match="/"> <input value="{/root}" /> </xsl:template> </xsl:stylesheet> ```` using Python and `lxml` (`libxslt-1 1 17`) and I am getting the following output: ````<input value="&amp;amp; &amp;amp; &amp;amp;" /> ```` I understand that I can get around this with the following template: ```` <xsl:template match="/"> <input> <xsl:attribute name="value"> <xsl:value-of select="/root" disable-output-escaping="yes" /> </xsl:attribute> </input> </xsl:template> ```` but that is a <strong>lot</strong> of typing Having worked with XSL within PHP I do not remember ever having to use this work-around for unquoting XML entities using the short-form `value-of` Is there a short fix for this so we do not have to keep typing the whole of the above? | DOE in fact <strong>is designed</strong> for such cases Sorry if you know that just to be consecutive <a href="http://www w3 org/TR/xslt#disable-output-escaping" rel="nofollow">http://www w3 org/TR/xslt#disable-output-escaping</a> <blockquote> Normally the xml output method escapes & and < (and possibly other characters) when outputting text nodes This ensures that the output is well-formed XML However it is sometimes convenient to be able to produce output that is almost but not quite well-formed XML; for example the output may include ill-formed sections which are intended to be transformed into well-formed XML by a subsequent non-XML aware process For this reason XSLT provides a mechanism for disabling output escaping An xsl:value-of or xsl:text element may have a disable-output-escaping attribute </blockquote> I guess the real pain is that you <strong>cannot</strong> use DOE in atrribute value's expression e g `{disable-output-escaping(root)}` So I cannot think of any way to shorten this |
pygame: using pygame mixer simultaneously from 2 threads fails I am trying to build a little sound generator with pygame and numpy The following code plays the data out of my numpy arrays correctly but when I try to use this code in a module and access it either from different threads or from different processes to play two sounds at a time one of the sounds is played <them>before</them> the other one instead of <them>both at the same time</them> ````def _play_array(array ms vol): sound = pygame sndarray make_sound(_intern _as_int16(array)) channel = sound play(-1) channel set_volume(vol) if ms > 50: pygame time delay(ms-50) channel fadeout(50) else: pygame time delay(ms) sound stop() ```` update: I have tried installing audiere but all that happens is that it comes up with a ridiculously long error traceback but this apparently is the problem the installer encountered: `/Developer/SDKs/MacOSX10 6 sdk/usr/include/stdarg h:4:25: error: stdarg h: No such file or directory` (edit) Now I found out it does not work on Mac OS X update 2: trying to use snack/tkSnack: `RuntimeError: Tk not intialized or not registered with Snack` update 3: trying to install wxPython to play the sound after writing it to a file - `import wx` just fails: `/usr/local/lib/wxPython-unicode-2 8 12 1/lib/python2 7/site-packages/wx-2 8-mac-unicode/wx/_core_ so: no matching architecture in universal wrapper` I am getting slightly annoyed by this problem <strong>update 4:</strong> see post | To completely bypass your problem you could use py audiere to make your sounds with it you could have two different tones at once Using your code I do not think you can have two tones at once This is a snippet from my frequency generator: ````speakers = audiere open_device() tone = speakers create_square(start_freq *2) tone pan = 1 tone stop() tone play() ```` Just have two sounds instead of one Sorry it does not use your code but perhaps this could be useful to you :) |
Scipy/Numpy/scikits - calculating precision/recall scores based on two arrays - I fit a Logistic Regression Model and train the model based on training dataset using the following <blockquote> ````import scikits as sklearn from sklearn linear_model import LogisticRegression lr = LogisticRegression(C=0 1 penalty='l1') model = lr fit(training[: 0:-1] training[: -1) ```` </blockquote> - I have a cross validation dataset which contains a labels associated in input matrix and can be accessed as <blockquote> cv[: -1] </blockquote> - I run my cross validation dataset against the trained model which returns me the list of 0s and 1s based on prediction <blockquote> cv_predict = model predict(cv[: 0:-1]) </blockquote> <strong>Question</strong> I want to calculate the precision and recall scores based on acutal labels and predicted labels Is there a standard method to do it using numpy/scipy/scikits? Thank you | Yes there are see the documentation: <a href="http://scikit-learn org/stable/modules/classes html#classification-metrics">http://scikit-learn org/stable/modules/classes html#classification-metrics</a> You should also have a look at the `sklearn metrics classification_report` utility: ````>>> from sklearn metrics import classification_report >>> from sklearn linear_model import SGDClassifier >>> from sklearn datasets import load_digits >>> digits = load_digits() >>> n_samples n_features = digits data shape >>> n_split = n_samples / 2 >>> clf = SGDClassifier() fit(digits data[:n_split] digits target[:n_split]) >>> predictions = clf predict(digits data[n_split:]) >>> expected = digits target[n_split:] >>> print classification_report(expected predictions) precision recall f1-score support 0 0 90 0 98 0 93 88 1 0 81 0 69 0 75 91 2 0 94 0 98 0 96 86 3 0 94 0 85 0 89 91 4 0 90 0 93 0 91 92 5 0 92 0 92 0 92 91 6 0 92 0 97 0 94 91 7 1 00 0 85 0 92 89 8 0 71 0 89 0 79 88 9 0 89 0 83 0 86 92 average / total 0 89 0 89 0 89 899 ```` |
Xlsxwriter: format three cell ranges in same worksheet I would like to format `A1:E14` as US Dollars `F1:K14` as percentages and `A15:Z1000` as US Dollars Is there a way to do this in XlsxWriter? I know how to format full columns as Dollars/Percentages but I do not know how to format parts of columns -- whatever I do last will overwrite Columns `F:K` Data is starting in pandas so happy to solve the problem there The following does not seem to work: ````sheet set_column('A1:E14' None money_format) ```` More Code: ````with pd ExcelWriter(write_path) as writer: book = writer book money_fmt = book add_format({'num_format': '$# ##0'}) pct_fmt = book add_format({'num_format': '0 00%'}) # call func that creates a worksheet named total with no format df to_excel(writer sheet_name='Total' startrow=0) other_df to_excel(writer sheet_name='Total' startrow=15) writer sheets['Total'] set_column('A1:E14' 20 money_fmt) writer sheets['Total'] set_column('F1:K14' 20 pct_fmt) writer sheets['Total'] set_column('F15:Z1000' 20 money_fmt) ```` | I cannot see a way to achieve per cell formatting using just `xlsxwriter` with Pandas but it would be possible to apply the formatting in a separate step using `openpyxl` as follows: ````import openpyxl def write_format(ws cell_range format): for row in ws[cell_range]: for cell in row: cell number_format = format sheet_name = "Total" with pd ExcelWriter(write_path) as writer: write_worksheet(df writer sheet_name=sheet_name) wb = openpyxl load_workbook(write_path) ws = wb get_sheet_by_name(sheet_name) money_fmt = '$# ##0_-' pct_fmt = '0 00%' write_format(ws 'A1:G1' money_fmt) write_format(ws 'A1:E14' money_fmt) write_format(ws 'F1:K14' pct_fmt) write_format(ws 'F15:Z1000' money_fmt) wb save(write_path) ```` When attempted with `xlsxwriter` it always overwrites the existing data from Pandas But if Pandas is then made to re-write the data it then overwrites any applied formatting There does not appear to be any method to apply formatting to an existing cell without overwriting the contents For example the <a href="https://xlsxwriter readthedocs org/worksheet html#write_blank" rel="nofollow">write_blank()</a> function states: <blockquote> This method is used to add formatting to a cell which doesnât contain a string or number value </blockquote> |
What is the average number of pups in a litter? | about six |
Why is it important to protect the main loop when using joblib Parallel? The joblib docs contain the following warning: <blockquote> Under Windows it is important to protect the main loop of code to avoid recursive spawning of subprocesses when using joblib Parallel In other words you should be writing code like this: ````import def function1( ): def function2( ): if __name__ == '__main__': # do stuff with imports and functions defined about ```` No code should run outside of the âif __name__ == â__main__ââ blocks only imports and definitions </blockquote> Initially I assumed this was just to prevent against the occasional odd case where a function passed to `joblib Parallel` called the module recursively which would mean it was generally good practice but often unnecessary However it does not make sense to me why this would only be a risk on Windows Additionally <a href="http://stackoverflow com/a/21029356/3204472">this answer</a> seems to indicate that failure to protect the main loop resulted in the code running several times slower than it otherwise would have for a very simple non-recursive problem Out of curiosity I ran the super-simple example of an embarrassingly parallel loop from the joblib docs without protecting the main loop on a windows box My terminal was spammed with the following error until I closed it: ````ImportError: [joblib] Attempting to do parallel computing without protecting your import on a system that does not suppo rt forking To use parallel-computing in a script you must protect you main loop using "if __name__ == '__main__'" Ple ase see the joblib documentation on Parallel for more information ```` <strong>My question is </strong> what about the windows implementation of joblib requires the main loop to be protected in every case? Apologies if this is a super basic question I am new to the world of parallelization so I might just be missing some basic concepts but I could not find this issue discussed explicitly anywhere Finally I want to note that this is purely academic; I understand why it is <a href="http://stackoverflow com/questions/419163/what-does-if-name-main-do">generally good practice</a> to write one's code in this way and will continue to do so regardless of joblib | This is necessary because Windows does not have `fork()` Because of this limitation Windows needs to re-import your `__main__` module in all the child processes it spawns in order to re-create the parent's state in the child This means that if you have the code that spawns the new process at the module-level it is going to be recursively executed in all the child processes The `if __name__ == "__main__"` guard is used to prevent code at the module scope from being re-executed in the child processes This is not necessary on Linux because it <them>does</them> have `fork()` which allows it to fork a child process that maintains the same state of the parent without re-importing the `__main__` module |
Where is it the most difficult to find a family doctor? | rural regions with increased need of health care provision because of overageing. |
Segmentation fault in python while using ctypes I am trying to read some registers in hardware (FPGA) using Python I already have a C code to read the registers and it works fine I want to use them in python using ctypes rdaxi c ````#include <fcntl h> #include <sys/ioctl h> #include <stdio h> #include <stdint h> #include <string h> #define NF10_IOCTL_CMD_READ_STAT (SIOCDEVPRIVATE+0) #define NF10_IOCTL_CMD_WRITE_REG (SIOCDEVPRIVATE+1) #define NF10_IOCTL_CMD_READ_REG (SIOCDEVPRIVATE+2) int main(int argc char* argv[]){ int f; uint64_t v; uint64_t addr; if(argc < 2){ printf("usage: rdaxi reg_addr(in hex)\n\n"); return 0; } else{ sscanf(argv[1] "%llx" &addr); } //---------------------------------------------------- //-- open nf10 file descriptor //---------------------------------------------------- f = open("/dev/nf10" O_RDWR); if(f < 0){ perror("/dev/nf10"); return 0; } printf("\n"); v = addr; if(ioctl(f NF10_IOCTL_CMD_READ_REG &v) < 0){ perror("nf10 ioctl failed"); return 0; } // upper 32bits contain the address and are masked away here // lower 32bits contain the data v &= 0xffffffff; printf("AXI reg 0x%llx=0x%llx\n" addr v); printf("\n"); close(f); return 0; } ```` After comilation and getting the executable I just do the following to get my result ```` /rdaxi 0x5a000008 AXI reg 0x5a000008 = 2 ```` I want to do the same thing using Python I came to know that I have to use Ctypes Then I created shared library ( so) for my c file The following is the python code i wrote I am a beginner in python so pardon me for my errors I get a segmentation fault How can I solve this and read the registers rdaxi py ````#!/usr/bin/env python # For creating shared library # gcc -c -Wall -fPIC rdaxi c # gcc -shared -o librdaxi so rdaxi o import os import sys from ctypes import * print "opening device descriptor" nf = os open( "/dev/nf10" os O_RDWR ) print "loading the so file" librdaxi=cdll LoadLibrary('/root/Desktop/apps/librdaxi so') librdaxi main(nf 0x5b000008) ```` For more information about my application Please see below <a href="http://stackoverflow com/questions/16372769/reading-registers-in-hw-using-python">reading registers in hw using python</a> thanks | `main()` takes two parameters `argc` and `argv` but you are passing it a single parameter which is your address Here is an example of how you might call it: ````librdaxi main argtypes = [c_int POINTER(c_char_p)] argv=(c_char_p*2)() argv[0]='rdaxi' argv[1]='0x5a000008' librdaxi main(2 argv) ```` |
Which group was specifically unknown in Freemasonry in the printed constitutions? | null |
Python Edit with IDLE Sublime Text 3 issue Today suddenly 'Edit with IDLE' option is gone from context menu I tried so many things on Regedit keys not worked So I downloaded Sublime Text First I could not even run `print("hello")` in sublime text it threw `SystemError: Parent module '' not loaded cannot perform relative import` I deleted Python and re-installed it That problem is still occuring but right now I have another problem on Sublime text I opened a script (that working perfectly without any error) with Sublime Text for editing First of all `input()` is not working When I run the script on Sublime Text I see input line but that is all It is like Sublime Text prints only the input not taking data or anything happens after then I do not know why Second problem is weirdly it raises `TabError` for <strong>EVERY</strong> line in the script <a href="http://i stack imgur com/zvvPN png" rel="nofollow"><img src="http://i stack imgur com/zvvPN png" alt="enter image description here"></a> As you see in the picture `break` is excatly on the same line with `print` and `time sleep()` I tried everything and still no solution How can I fix this nonsense TabError? How can I fix `input()` issue? (I downloaded sublimeRepl but it is not working there is no option 'Edit with SublimeRepl' or else) After all why `Edit with IDLE` option is gone suddenly and not coming back? I have tons of scripts and I cannot even open a single one I cannot edit anything Cannot run anything | More than likely you have a mix of spaces and tabs For Python I have a syntax specific Sublime-settings that shows whitespace characters `draw_white_space": "all" ` so that these issues can be quickly seen I also have it so that tabs are changed to spaces My settings are below feel free to modify as you wish: ````{ // editor options "draw_white_space": "all" // tabs and whitespace "auto_indent": true "rulers": [79] "smart_indent": true "tab_size": 4 "trim_automatic_white_space": true "use_tab_stops": true "word_wrap": true "wrap_width": 80 "translate_tabs_to_spaces": true } ```` As for the `Edit with IDLE` context missing you may want to take a look at this <a href="http://superuser com/a/343565/570687">answer</a> or this <a href="http://stackoverflow com/a/34321586/6061947">answer</a> to see if you can add it back |
commands to send messages in Python via the Poplib module? I have found a number of tutorials online involving downloading messages via Poplib but have not been able to find anything explaining how to create new messages Does this exist? | Send yourself an email to create a message SMTP is the protocol the email uses to send In Python you would find this in <a href="http://docs python org/library/smtplib html" rel="nofollow">smtplib</a> There are numerous email RFC's Here are a few SMTP - <a href="http://www faqs org/rfcs/rfc821 html" rel="nofollow">RFC 821</a> POP - <a href="http://www faqs org/rfcs/rfc1939 html" rel="nofollow">RFC 1939</a> IMAP - <a href="http://www faqs org/rfcs/rfc1730 html" rel="nofollow">RFC 1730</a> |
JQuery cookie access has stopped working for GAE app I have a google app engine app that has been running for some time and some javascript code that checks for a login cookie has suddenly stopped working As far as I can tell NO code has changed The relevant code uses the jquery cookies plugin (jquery cookies 2 2 0 min js) ````// control the default screen depending // if someone is logged in if( $ cookies get('dev_appserver_login') != null || $ cookies get('ACSID') != null ) { alert("valid cookie!") $("#inventory-container") show(); } else { alert("INvalid cookie!") $("#welcome-container") show(); } ```` The reason for the two checks is that in the GAE SDK the cookies are named differently The production system uses 'ACSID' This if statement works in the SDK and now fails 100% of the time in production I have verified that the cookie is in fact present when I inspect the page Thoughts? | Possibly the ACSID cookie is now being marked as 'secure' and hence unavailable to Javascript Why the devil are you doing this in the first place though? |
Sum all columns but one in a numpy array Basically all columns except a particular one must be summed I came up with two closely related solutions: ````def collapse(arr i): return np hstack((arr[: i None] np sum(arr[: [j for j in xrange(arr shape[1]) if j != i]] axis=1 keepdims=True))) def collapse_transpose(arr i): return np vstack((arr[: i] np sum(arr[: [j for j in xrange(arr shape[1]) if j != i]] axis=1))) T ```` Example: ````In [42]: arr = np arange(9) reshape(3 3) In [43]: arr Out[43]: array([[0 1 2] [3 4 5] [6 7 8]]) In [44]: collapse(arr 0) Out[44]: array([[ 0 3] [ 3 9] [ 6 15]]) ```` I thought the later would be faster but it came out to be slower Anyway I do not like the `vstack` and `hstack` calls since they can be slow on huge inputs Are there any ways to get rid of them? | You are concatenating just 2 arrays ````In [282]: (arr[: i] np sum(arr[: [j for j in xrange(3) if j != i]] axis=1))Out[282]: (array([0 3 6]) array([ 3 9 15])) In [283]: (arr[: i None] np sum(arr[: [j for j in xrange(3) if j != i]] axis=1 keepdims=True)) Out[283]: (array([[0] [3] [6]]) array([[ 3] [ 9] [15]])) ```` `vstack` and `hstack` both use `concatenate` They just work on different axes and massage the inputs in different ways to ensure they have the correct number of dimensions It seems to me that the versions are basically equivalent You could call `concatenate` directly which might shave a % or two off But the concatenation is not the biggest time consumer in this case ````np concatenate((arr[: i None] np sum(arr[: [j for j in xrange(3) if j != i]] axis=1 keepdims=True)) axis=1) ```` Beyond that look at the timing for the individual pieces Is `arr[: [j for j in xrange(3) if j != i]] axis=1)` as fast as it could be? How about summing it all and subtracting the `ith` row? ````In [310]: timeit arr sum(1)-arr[: i] 10000 loops best of 3: 22 7 us per loop In [311]: timeit np sum(arr[: [j for j in xrange(3) if j != i]] axis=1) 10000 loops best of 3: 29 1 us per loop ```` |
In which type of migration do birds use the sun to navigate by day and a stellar compass at night? | diurnal migrants |
What does the city host on Sundays | To promote culture Utrecht city organizes cultural Sundays |
Ajax Posts but does not call Django View <h2>The Problem</h2> <them>After posting to my django view the code seems to just stop halfway through </them> I have an ajax post to a Django view that is hard coded to render a specific response (see below) When I post to that view it should always return that response but for some reason the view out puts all of the print statements but not the query or the render I know I am being redirected by my sever log (shown below) <strong>Any idea what could be causing this behavior?</strong> Server log: ````127 0 0 1 - - [26/Aug/2013 21:27:23] "GET / HTTP/1 1" 200 - 127 0 0 1 - - [26/Aug/2013 21:27:23] "GET /static/css/style css HTTP/1 1" 304 - 127 0 0 1 - - [26/Aug/2013 21:27:23] "GET /static/js/map js HTTP/1 1" 200 - 127 0 0 1 - - [26/Aug/2013 21:27:23] "GET /static/js/home_jquery js HTTP/1 1" 304 - 127 0 0 1 - - [26/Aug/2013 21:27:23] "GET /static/js/jquery_cookie/jquery cookie js HTTP/1 1" 304 - 127 0 0 1 - - [26/Aug/2013 21:27:23] "GET /favicon ico HTTP/1 1" 404 - I have been posted Here are my values <QueryDict: {you'name': [you'Mission Chinese Food'] you'address': [you'154 Orchard Street Manhattan']}> Mission Chinese Food 154 Orchard Street Manhattan Fish 127 0 0 1 - - [26/Aug/2013 21:27:32] "POST /results/ HTTP/1 1" 200 - ```` Simple Django View: ````def results(request): if request method == 'POST': print "I have been posted Here are my values" print request POST print request POST get('name') print request POST get('address') restaurant = Restaurant objects filter(name='Fish' address='280 Bleecker St')[0] print restaurant return render(request "stamped/restaurant html" {'restaurant': restaurant} ```` Simple ajax post: ````var send_data = { 'name': place name 'address': address}; var csrftoken = $ cookie('csrftoken'); alert(csrftoken); alert(send_data); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/ test(method)); } $ ajaxSetup({ crossDomain: false // obviates need for sameOrigin test beforeSend: function(xhr settings) { if (!csrfSafeMethod(settings type)) { xhr setRequestHeader("X-CSRFToken" csrftoken); } } }); $ ajax({ url: '/results/' type: 'POST' data: send_data success: function(response) { console log("everything worked!"); } error: function(obj status err) { alert(err); console log(err); } }); }); ```` | Solved by using: ````$ ajax({ url: '/results/' type: 'POST' data: send_data success: function(response) { console log("everything worked!"); $("#results") html(response); } error: function(obj status err) { alert(err); console log(err); } }); ```` I was trying to use Django to redirect me to the render response like it ussually does Because I am calling from javascript to response is redriceted to javascript and the the typical django functions This part of the function ```` success: function(response) { $("#results") html(response); } ```` renders the response to my chosen results div |
Python Django Form: Setting initial values for CharFields I am writing a webpage as part of a larger django project that allows an existing user to change his personal information The issue is that the form needs to access the user's existing information I want to set it so that the existing info appears in each CharField when the page loads and the user can make their appropriate changes and accept The page loads but the charfields do not appear at all This is what I have so far: class EditPersonForm(forms Form): ````""" Form that allows for editing an existing user's (of Person class) personal information Same structure as the RegistrationForm The CharField's look the same as the registration page but have the existing info already filled out """ #the following line are all indented under the class definition do not know why it is showing up weird here def __init__(self person): profile = person profile_default = {"username" : profile user username "email" : profile user email "first_name" : profile user first_name \ "last_name" : profile user last_name "street_address" : profile street_address "apt_number" : profile apt_number \ "city" : profile city "state" : profile city "zipcode" : profile zipcode} username = forms CharField(label =('User Name') max_length = constants MAX_LEN_NAME initial = profile_default username) email = forms EmailField(label = ('Email Address') initial = profile_default email) first_name = forms CharField(label = ('First Name') max_length = constants MAX_LEN_NAME initial = profile_default first_name) last_name = forms CharField(label = ('Last Name') max_length = constants MAX_LEN_NAME initial = profile_default last_name) street_address = forms CharField(label = ('Street Address') max_length = constants MAX_LEN_NAME initial = profile_default street_address) apt_number = forms CharField(label = ('Apartment Number') required = False max_length = constants MAX_LEN_SHORTF initial = profile_default apt_number) city = forms CharField(label = ('City') max_length = constants MAX_LEN_NAME initial = profile_default city) state = forms ChoiceField(widget = forms Select() choices = constants STATE_CHOICES initial = profile_default state) zipcode = forms CharField(label = ('Zipcode') max_length = constants MAX_LEN_SHORTF initial = profile_default zipcode) password = forms CharField(label = ('Password') widget=forms PasswordInput(render_value=False) max_length = constants MAX_LEN_NAME) class Meta: """ Class that allows the form to use the Person object model as a guideline """ model = Person exclude = ('user' ) ```` | For each field in the `__init__` method you need to this: ````class EditPersonForm(forms Form): def __init__(self person *args **kwargs): super(EditPersonForm self) __init__(*args **kwargs) profile = person [ ] #ommited code for simplification self fields['username']= forms CharField( label =('User Name') max_length = constants MAX_LEN_NAME initial = profile_default username) [ ] # do the same for rest of the fields ```` Also since you are defining a `model` in class `Meta` are you suppose to be using a `ModelForm` ````class EditPersonForm(forms ModelForm): def __init__(self *args **kwargs): super(EditPersonForm self) __init__(*args **kwargs) [ ] class Meta: model = Person exclude = ('user' ) ```` Hope this helps :-) |
Having trouble in creating 2D array/list I am having difficulty creating a 2D list of permutations Here is a minimal code to reproduce the problem ````class Solution: def permute(self A): A = sorted(A) print A A_out = [] A_out append(A) for iter0 in range(4): A[0] = A[0] 1 print A A_out append(A) return A_out sol = Solution() A = [1 2 3] print sol permute(A) ```` For this particular input(1 2 3) the output is ````[1 2 3] [2 2 3] [3 2 3] [4 2 3] [5 2 3] [[5 2 3] [5 2 3] [5 2 3] [5 2 3] [5 2 3]] ```` but the desired output is ````[1 2 3] [2 2 3] [3 2 3] [4 2 3] [5 2 3] [[1 2 3] [2 2 3] [3 2 3] [4 2 3] [5 2 3]] ```` I think it has something to do deep copy/ shallow copy thing but I am not sure how to correct this as I am not very familiar with Python How can I fix it? | It is indeed about shallow copies The list `A` you keep appending always refers to the same value This is related to the mutability of lists in Python You need to append a new copy of the list each time to make them independent of each other You can do that using the slice operator `[:]` because it creates a new copy of the list So you can just use it when calling `append` ````def permute(self A): A = sorted(A) print A A_out = [] A_out append(A[:]) while (self checkVal(A) != -1) : A = self nextState(A self checkVal(A)) print A A_out append(A[:]) return A_out ```` |
How to hide an ActionButton in Kivy? I am trying to modify the visibility of an ActionButton accordingly to the current screen (using Screen Manager) I could not find a Visible property or something like that that can simply toggle visibility (neither for ActionButton nor for Widgets in general) <a href="http://stackoverflow com/questions/16722971/kivy-how-to-make-widget-behave-like-overflowhidden">A post from 2013</a> suggests changing the texture of the button but I do not want to rely on such a hack to accomplish such a simple task besides the background of my app will be variable <a href="http://stackoverflow com/questions/14699280/switching-kivy-widgets">Another post</a> suggest removing the widget and adding it again as needed Despite its unnecessary complexity I modified to work in my case (ActionBar and ActionButton) so I clear the widgets from the ActionView and then try to add the ActionButton I tried storing both a weakref and the <strong>self</strong> member with both I got the following error: ````WidgetException: Cannot add <kivy uix actionbar ActionButton object at 0x7fcd3fe22ce8> it already has a parent <kivy uix actionbar ActionView object at 0x7fcd3fe22870> ```` Any idea would be greatly appreciated I am working with the dev version but it neither work with 1 8 <strong>EDIT</strong> I tried the following code: ````<AppActionBar>: ActionView: id: av ActionButton: id: btn_next text: 'Next screen' icon: 'data/icons/next_dark png' important: True on_release: app go_next() ```` This function is run after the scene is loaded: ````def _initialize(self): self next = self ids btn_next __self__ # same result if I do not use __self__ ```` This code raises the exception posted above: ````self ids av clear_widgets() self ids av add_widget(self next) ```` Here is the full exception trace: ```` self _mainloop() File "/usr/local/lib/python2 7/dist-packages/kivy/core/window/window_pygame py" line 266 in _mainloop EventLoop idle() File "/usr/local/lib/python2 7/dist-packages/kivy/base py" line 330 in idle Clock tick_draw() File "/usr/local/lib/python2 7/dist-packages/kivy/clock py" line 429 in tick_draw self _process_events_before_frame() File "/usr/local/lib/python2 7/dist-packages/kivy/clock py" line 562 in _process_events_before_frame if event tick(self _last_tick) is False: File "/usr/local/lib/python2 7/dist-packages/kivy/clock py" line 309 in tick ret = callback(self _dt) File "/usr/local/lib/python2 7/dist-packages/kivy/uix/boxlayout py" line 174 in do_layout c width = w File "properties pyx" line 345 in kivy properties Property __set__ (kivy/properties c:3589) File "properties pyx" line 377 in kivy properties Property set (kivy/properties c:4064) File "properties pyx" line 431 in kivy properties Property dispatch (kivy/properties c:4657) File "/usr/local/lib/python2 7/dist-packages/kivy/uix/actionbar py" line 552 in on_width self _layout_all() File "/usr/local/lib/python2 7/dist-packages/kivy/uix/actionbar py" line 441 in _layout_all super_add(child) File "/usr/local/lib/python2 7/dist-packages/kivy/uix/boxlayout py" line 212 in add_widget return super(BoxLayout self) add_widget(widget index) File "/usr/local/lib/python2 7/dist-packages/kivy/uix/layout py" line 78 in add_widget return super(Layout self) add_widget(widget index) File "/usr/local/lib/python2 7/dist-packages/kivy/uix/widget py" line 466 in add_widget % (widget parent)) WidgetException: Cannot add <kivy uix actionbar ActionButton object at 0x7fecb5d6ed50> it already has a parent <kivy uix actionbar ActionView object at 0x7fecb5d6e8d8> ```` | I am still learning kivy but it appears that surprisingly there is no property or member function to do this Instead you have to remove the widget from its parent or set its color alpha to 0 (which will only work in cases where you have one color) <strong>Update</strong>: The traceback indicates that `self next` still has a parent when `self ids av add_widget(self next)` is called Since this call is preceded by a `self ids av clear_widgets()` the only way that `self next` is still in widget tree is that it is actually not a child of `self ids av` Maybe it is a child of the default layout used by `av` and layout does not immediately get garbage collected Try ````print 'next in av children:' self next in self ids av children print 'parent of next:' self next parent # self ids av clear_widgets() # self ids av add_widget(self next) parent = self next parent parent remove_widget(self next) parent add_widget(self next) ```` |
multiprocessing imap suprress child process print While I am running the following code in Jupyter notebook (python3 5): ````def process(doc): print('Process Hey!') with Pool() as pool: results = pool imap(process docs) ```` This would not give the print to the notebook but if I try using pool map instead it will spit out the words So I am really curious what is going on up here Thanks! | From the docs <a href="https://docs python org/3 5/library/multiprocessing html#multiprocessing pool Pool imap" rel="nofollow">imap</a> `A lazier version of map()` `imap` returns an iterator `map` returns a list: ````In [24]: with Pool() as pool: results = pool map(process docs) print(type(results)) : Process Hey! Process Hey! <class 'list'> In [25]: with Pool() as pool: results = pool imap(process docs) print(type(results)) : <class 'multiprocessing pool IMapIterator'> In [27]: with Pool() as pool: results = pool imap(process docs) for _ in results: pass : Process Hey! Process Hey! In [28]: with Pool() as pool: results = pool imap(process docs) list(results) : Process Hey! Process Hey! ```` It is equivalent to the difference between `itertools imap` and `map` in python2 i e lazily evaluated vs greedily evaluated: ````In [3]: from itertools import imap In [4]: are = imap(lambda x: x+1 [1 2 3]) In [4]: r Out[5]: <itertools imap at 0x7f09170f1e10> In [6]: list(r) Out[6]: [2 3 4] In [7]: are = map(lambda x: x+1 [1 2 3]) In [8]: r Out[8]: [2 3 4] ```` |
change a variable in a for loop from 0 to 2 and back again to 0 Hi I am looking for a smart way to get a for loop in Python in which one variable say k has to shift from 0 to 2 and than back to 0 up to the end of the loop Something like ````k = 0 for j in range(15): fancycode k = k 1 ```` In which for each loop k has the following values ````loop1 k = 0 loop2 k = 1 loop3 k = 2 loop4 k = 0 loop5 k = 1 loop6 k = 2 loop7 k = 0 ```` I may use an if statement but I would like to know whether there could be something smart that does not burden my code | Simply using modulo! (%) ````for j in range(15): fancycode k = j % 3 print(k) ```` |
Sending and receiving data to and from the same page with Flask I want to send data to a page(as radio buttons) and then record the input Right now I am having a problem as I cannot figure out how to do both using flask Python: ```` @app route('/' methods=['GET' 'POST']) def index(): data = adb fetch() return render_template('index html' data=data) @app route('/' methods=['POST']) def handle_data(): name = request form['option'] print name ```` and in HTML: ````<form accept-charset="UTF-8" action="#" class="form-horizontal" id="names" method ="post"> <div class="control-group"> {% for row in data %} <div class="controls"> <label class="radio"> <input type="radio" name="option" id="{{row['lid']}}" value="{{row['name']}}"> {{row['name']}} </label> </div> {% endfor %} </div> <input type="submit" value="Submit"> </form> ```` I am getting proper output to the site but result is not printed to my console How can I send and receive data on the same page? | So this is a pretty basic property of flask but the answer is: ```` if request method == 'GET': return render_template('index html' data=data) elif request method == 'POST': name = request form['option'] print name return "Page submitted" ```` |
Page break with dynamic content(printing) My webpage gets generated dynamically so the height of my content is unknown My question is how do I go about splitting the page up for printing without the layout being cut in half or have my labels be on one page and the text boxes on the other One option I was thinking was counting the number of section and splitting the page after every 2 sections or so (section is a big width: 100% height: auto; block that contains a few input boxes and I have multiple sections) <img src="http://i stack imgur com/VAQ8t png" alt="enter image description here"> | Try css ````/* create `page-break-after` `odd` index elements i e g first third fifth elements etc */ section:odd { page-break-after : always; } ```` See <a href="https://developer mozilla org/en-US/docs/Web/CSS/page-break-after" rel="nofollow">page-break-after</a> <a href="https://developer mozilla org/en-US/docs/Web/CSS/page-break-inside" rel="nofollow">page-break-inside</a> |
Append duplicate items at the end of list whithout changing the order I am new to python and was trying to Append duplicate items at the end of list whithout changing the order ````testlist = [1 2 32 8 1 17 5 2 42 13 56] def duplicate(alist): p = len(alist) duplicate = False for i in range(0 p): for j in range (i 1 p): if alist[i] == alist[j]: b = alist index(alist[j]) a = alist pop(b) alist append(a) p -= 1 duplicate = True print alist if duplicate == False: print "No duplicate item found" duplicate(testlist) ```` OUTPUT : `[32 8 1 17 5 2 42 13 56 1 2]` DESIRED OUTPUT : `[1 2 32 8 17 5 42 13 56 1 2]` Any help what wrong I am doing here | I think that in this case the creation of a new list is more efficient and clear in comparison with the permutations in the original list: ````testlist = [1 2 32 8 1 17 5 2 42 13 56] def duplicate(alist): filtered duplicates = [] [] for element in alist: if element in filtered: duplicates append(element) continue filtered append(element) if not duplicates: print "No duplicate item found" return alist return filtered duplicates new_list = duplicate(testlist) print new_list ```` |
Parse SQL Query Text to Extract Table Names Used I have a sqlite database that gets populated by a different process This process generates tables in the db and fills them with data I am trying to apply a set of pre-written queries against this db but I need to make sure that all of the tables referenced in the query are created in the db before I run it to prevent errors I am trying to determine all of the possible ways that a table can be referenced in a SQL to make sure I cover all of the options simple: ````select col1 from table1 ```` joins: ````select col1 col2 from table1 join table2 on col1 = col2 select col1 col2 from table1 left outer join table2 on col1 = col2 select col1 col2 from table1 table2 on col1 = col2 select col1 col2 from table1 table2 where col1 = col2 ```` subqueries: ````select col1 (select col2 from table2 where col1 = col2) as ag2 from table1 select col1 from table1 where col1 in (select col2 from table2) ```` alias: ````select col1 col2 from table1 t1 table2 t2 where col1 = col2 select col1 col2 col3 from table1 t1 table2 t2 table3 t3 where col1 = col2 ```` I am thinking to use a RegEx to identify the few occurrences ````from [table] [alias] join [table] [alias] from [table] [alias] [table] [alias] ```` This RegEx seems to account for most of the variances Table names appear in group2 or group3: ````(from|join)\s+([\w]+)| \s*([\w]+)\s*([\w]\s*)?(on|where) ```` <a href="http://regexr com/3aq8j" rel="nofollow">http://regexr com/3aq8j</a> My questions: - Have I identified all of the possible ways for a table to be used in a query? - Are there any other false positives from my expression? - I cannot get all of the table names from the alias section Help? - Is there a better approach than RegEx? I will be using this in Python code if that affects the format of the RegEx | You can use a <a href="http://www regular-expressions info/lookaround html" rel="nofollow"><them>positive look-behind</them></a> : ````(?<=from|join)\s+(\w+)( \s*(\w+))?(?:(\s*\w+ \s*(\w+))+)? ```` <them>Note</them> that you need to use grouping correctly In your pattern you have putted `from` and `join` within group so the result will be contain them |
Originally, no electronic component had what? | null |
What are forensic anthropologists very good at identifying? | races |
What does LPC stand for? | linear predictive coding |
What was upgraded in 1940? | null |
django 1 10 custom user model and user manager I Am trying to create a custom user model and his manager <a href="https://gist github com/bitgandtter/9fc0de497a3cc13440e24a86ba6626b1" rel="nofollow">gist with code</a> But for some reason when y try to create a user with the `python manage py createsuperuser` It rise an error ````django db utils OperationalError: (1054 "Unknown column 'jmessages_customer last_login' in 'field list'") ```` Its like its not using my custom manager at the moment | The solition was to specify the missing property on the model ````last_login = None ```` the same as ````is_active = True ```` In deed those need to be correctly handled in the future but at list this issue was fixed |
Image and Sound (Media) not showing on django I am trying to play an audio in django but it cannot find the audio file I have setup the MEDIA_URL and MEDIA_ROOT but it still does not work Please help me Below is the code snippet settings py ````STATIC_ROOT = os path join(BASE_DIR 'static') STATIC_URL = '/static/' MEDIA_ROOT = os path join(BASE_DIR 'media') MEDIA_URL = '/media/' ```` urls py ````urlpatterns = [ url(r'^admin/' include(admin site urls)) url(r'^$' home) ] if settings DEBUG: urlpatterns = static(settings STATIC_URL document_root=settings STATIC_ROOT) urlpatterns = static(settings MEDIA_URL document_root=settings MEDIA_ROOT ```` home html ````{% extends "layout/base html" %} {% block content %} <h1> Sound Assessment Toolset </h1> <audio src="{{MEDIA_URL}}master_sound/piano mp3"></audio> <img src="{{ MEDIA_URL }}images/batman jpg"/> {% endblock %} ```` <a href="http://i stack imgur com/AA2I9 png" rel="nofollow">Image of Project Directory</a> the log file : ````Django version 1 8 7 using settings 'Sound_Assessment settings' Starting development server at http://127 0 0 1:8800/ Quit the server with CONTROL-C [17/Jun/2016 15:18:43] "GET / HTTP/1 1" 200 746 [17/Jun/2016 15:18:43] "GET /images/batman jpg HTTP/1 1" 404 2321 [17/Jun/2016 15:18:43] "GET /master_sound/piano mp3 HTTP/1 1" 404 2336 [17/Jun/2016 15:18:43] "GET /images/batman jpg HTTP/1 1" 404 2321 ```` | You are not actually requesting those elements under MEDIA_URL as you can see from the log file That is because you have not actually passed those variables to the template so they are being ignored |
Python - "'NoneType' object is not iterable" error assigning values to a def in a loop I have been looking all over the place and I do not understand why I keep getting the same error I have read that it has something to do with 'return' but it does not makes sense to me ````Traceback: File "/tmp/vmuser_mlgewmyusy/main py" line 47 in daysBetweenDates new_year new_month new_day=nextDay(new_year new_month new_day) TypeError: 'NoneType' object is not iterable ```` Code: ````def nextDay(year month day): if month!=12: if month==1 or month==3 or month==5 or month==7 or month==8 or month==10: if day!=31: return year month day+1 else: return year month+1 1 elif month==4 or month==6 or month==9 or month==11: if day!= 30: return year month day+1 else: return year month+1 1 elif month==2: if day!= 28: return year month day+1 else: return year month+1 1 elif month==22: if day!= 29: return year month day+1 else: return year month+1 1 else: if day!= 31: return year month day+1 else: return year+1 1 1 def daysBetweenDates(year1 month1 day1 year2 month2 day2): i=0 new_year new_month new_day=year1-100 month1-100 day1-100 if year1==year2 and month1==month2 and day1==day2: return 0 while new_year!=year2 and new_month!=month2 and new_day!=day2: if i==0: `new_year new_month new_day`=year1+100 month1+100 day1+100 i+=1 new_year new_month new_day=nextDay(new_year new_month new_day) return i # Test routine def test(): test_cases = [((2012 1 1 2012 2 28) 58) ((2012 1 1 2012 3 1) 60) ((2011 6 30 2012 6 30) 366) ((2011 1 1 2012 8 8) 585 ) ((1900 1 1 1999 12 31) 36523)] for (args answer) in test_cases: result = daysBetweenDates(*args) if result != answer: print "Test with data:" args "failed" print 'ANSWER = {}' format(answer) print 'RESULT = {}' format(result) else: print "Test case passed!" test() ```` I want to assign a new value to 'new_year new_month new_day' every times the loop iterates | I added these two print lines into the `daysBetweenDates` function: ```` if i==0: new_year new_month new_day=year1+100 month1+100 day1+100 i+=1 print(new_month) print(nextDay(new_year new_month new_day)) new_year new_month new_day=nextDay(new_year new_month new_day) ```` I try this input `daysBetweenDates(2015 6 1 2014 4 1)` and find that `print(new_month)` gives `106` and `print(nextDay(new_year new_month new_day))` gives `None` Looking at the code block for `nextDay` there is no condition to catch `month==106` so the function returns the Python default of `None` While your values may vary it appears that `new_month` is not in the set {1 2 3 4 5 6 7 8 9 10 11 22} so the function is returning `None` and that is where your error is coming from So you can either ensure that a tuple is always returned or debug your code to see why you are getting input data different from those you have coded for |
What was the federal Government responsible for? | matters concerning the whole nation. |
how to print only lines which contain a substring i have a file with strings: ````REALSTEP 12342 {2012-7-20 15:10:39};[{416 369 338};{423 432 349};{383 380 357};{399 401 242};{0 454 285};{457 433 115};{419 455 314};{495 534 498};][{428 377 336};{433 456 345};{386 380 363};{384 411 REALSTEP 7191 {2012-7-20 15:10:41};[{416 370 361};{406 417 376};{377 368 359};{431 387 251};{0 461 366};{438 409 134};{429 411 349};{424 505 364};][{423 372 353};{420 433 374};{379 365 356};{431 387 2 REALSTEP 12123 {2012-7-20 15:10:42};[{375 382 329};{386 402 347};{374 378 357};{382 384 259};{0 397 357};{442 424 188};{398 384 356};{392 420 355};][{404 405 359};{420 432 372};{405 408 383};{413 407 REALSTEP 27237 {2012-7-20 15:10:44};[{431 375 329};{416 453 334};{387 382 349};{397 403 248};{0 451 300};{453 422 131};{433 401 317};{434 505 326};][{443 384 328};{427 467 336};{391 386 344};{394 413 FAKE 32290 {2012-7-20 15:10:48};[{424 399 364};{408 446 366};{397 394 389};{415 409 261};{0 430 374};{445 428 162};{432 416 375};{431 473 380};][{424 398 376};{412 436 372};{401 400 390};{417 409 261} FAKE 32296 {2012-7-20 15:10:53};[{409 326 394};{445 425 353};{401 402 357};{390 424 250};{0 420 353};{447 423 143};{404 436 351};{421 527 420};][{410 332 400};{450 429 356};{402 403 356};{391 425 250} FAKE 32296 {2012-7-20 15:10:59};[{381 312 387};{413 405 328};{320 387 376};{388 387 262};{0 402 326};{417 418 177};{407 409 335};{443 502 413};][{412 336 417};{446 437 353};{343 417 403};{417 418 258} FAKE 32295 {2012-7-20 15:11:4};[{377 314 392};{416 403 329};{322 388 375};{385 391 261};{0 403 329};{425 420 168};{414 393 330};{458 502 397};][{408 338 421};{449 435 355};{345 418 403};{413 420 257}; FAKE 32295 {2012-7-20 15:11:9};[{371 318 411};{422 385 333};{342 379 352};{394 395 258};{0 440 338};{418 414 158};{420 445 346};{442 516 439};][{401 342 441};{456 415 358};{367 407 377};{420 420 255}; FAKE 32296 {2012-7-20 15:11:15};[{373 319 412};{423 386 333};{344 384 358};{402 402 257};{0 447 342};{423 416 151};{422 450 348};{447 520 442};][{403 342 442};{456 416 358};{366 409 379};{422 421 255} REALSTEP 7191 {2012-7-20 15:10:41};[{416 370 361};{406 417 376};{377 368 359};{431 387 251};{0 461 366};{438 409 134};{429 411 349};{424 505 364};][{423 372 353};{420 433 374};{379 365 356};{431 387 2 REALSTEP 12123 {2012-7-20 15:10:42};[{375 382 329};{386 402 347};{374 378 357};{382 384 259};{0 397 357};{442 424 188};{398 384 356};{392 420 355};][{404 405 359};{420 432 372};{405 408 383};{413 407 REALSTEP 27237 {2012-7-20 15:10:44};[{431 375 329};{416 453 334};{387 382 349};{397 403 248};{0 451 300};{453 422 131};{433 401 317};{434 505 326};][{443 384 328};{427 467 336};{391 386 344};{394 413 ```` I read the file with readlines() and want to then loop over the lines and print only when there is a consecutive block of lines larger than 3 containing the string "REALSTEP" So in the example the expected result is: ````REALSTEP 12342 {2012-7-20 15:10:39};[{416 369 338};{423 432 349};{383 380 357};{399 401 242};{0 454 285};{457 433 115};{419 455 314};{495 534 498};][{428 377 336};{433 456 345};{386 380 363};{384 411 REALSTEP 7191 {2012-7-20 15:10:41};[{416 370 361};{406 417 376};{377 368 359};{431 387 251};{0 461 366};{438 409 134};{429 411 349};{424 505 364};][{423 372 353};{420 433 374};{379 365 356};{431 387 2 REALSTEP 12123 {2012-7-20 15:10:42};[{375 382 329};{386 402 347};{374 378 357};{382 384 259};{0 397 357};{442 424 188};{398 384 356};{392 420 355};][{404 405 359};{420 432 372};{405 408 383};{413 407 REALSTEP 27237 {2012-7-20 15:10:44};[{431 375 329};{416 453 334};{387 382 349};{397 403 248};{0 451 300};{453 422 131};{433 401 317};{434 505 326};][{443 384 328};{427 467 336};{391 386 344};{394 413 ```` I tried this: ````lines = f readlines() idx = -1 #loop trough all lines in the file for i line in enumerate(lines): if idx > i: continue else: if "REALSTEP" in line: steps = lines[i:i+3] #check for blokc of realsteps if is_block(steps "REALSTEP") == 3: #prints the block up to the first next "FAKE STEP" lst = get_block(lines[i:-1]) for l in lst: print l[:200] idx = i len(lst) print "next block============" ```` where the function is_block is this: ````def is_block(lines check): #print len(lines) bool = 1 for l in lines: if check in l: bool = 1 else: bool = 0 bool = bool bool return bool ```` and the function get_block: ````def get_block(lines): lst = [] for l in lines: if "REALSTEP" in l: #print l[:200] lst append(l) else: break return lst ```` While this works it prints all lines containing the string "REALSTEPS" The print len(lines) in is_block(lines) is always 10 when the function is called so that is not it I am confused please help me out here! | This part: ```` if "REALSTEP" in line: steps = lines[i:i+3] for s in steps: print s[:200] # <- right here ```` Whenever you find `"REALSTEP"` in a line you retrieve the following three lines and print them right away That is probably not what you wanted |
python 3 4 string manipulation - truncating leading zeros There are a number of existing posts on this topic but I cannot get this simple piece of code to work correctly I have tried many many times with no success ````per = 5 if per < 10 == True: ms = 'fwd_%sd' % str(per) zfill(2) else: ms = 'fwd_%sd' % per ```` and ````if per < 10 == True: a = format(per 'fwd_02d') else: a = 'fwd_%sd' % per ```` The result should be 'fwd_05d' but I can only get 'fwd_5d' Among others I have seen: <a href="http://stackoverflow com/questions/134934/display-number-with-leading-zeros">Display number with leading zeros</a> <a href="http://stackoverflow com/questions/21620602/add-leading-zero-python">Add leading zero python</a> Please help! | You can use str format if you are actually doing nothing else but padding just use `ms = 'fwd_{:02}d' format(per)` and forget the if/else only numbers less than 10 will be padded with a 0 The 0 in `{:02}` is what to pad with and the 2 is the size to pad to ````ms = 'fwd_{:02}d' format(per) ```` On another note `if per < 10 == True:` is the same as `if per < 10:` |
limit plot title to only show a certain number of decimal places For a plot that I am making I have: ```` plt suptitle('Name:{0} MJD:{1} std dev > {2}' format(pname mjd[i] rmslevel) fontsize=12 fontweight='bold') ```` I want the number that will appear in the place of {2} (aka rmslevel) to only show 2 decimal places I have seen similar questions to this of course and the solutions: ````print "% 1f" % number ```` But I cannot figure out how to get this to work in the context of the format things that I have going on in the same line Thank you! | Maybe you can do this - ````plt suptitle('Name:{0} MJD:{1} std dev > {2}' format( pname mjd[i] ("% 2f" % rmslevel) ) fontsize=12 fontweight='bold') ```` |
Python proxy -> dansguardian: How to send original source ip? I have a python proxy for DNS When I get a DNS request I need to pass an http request to dansguardian on behalf of the original source let it to decide what happens to the request get the result and redirect client to elsewhere based on the response from dansguardian The network skeleton is like this: ````Client > DNS Proxy > DG > Privoxy > Web ```` Client requests `A` DNS Proxy intercepts asks DG on behalf of the client get's answer: 1 If DG filtered it proxy send a local ip address instead of actual IP for `A` question 2 If DG did not filter DNS proxy let us the client's net to flow naturally Here is the sample python code that I have tried: ```` data addr = sock recvfrom(1024) OriginalDNSPacket = data # I get OriginalDNSPacket from a socket # to which iptables redirected all port 53 packets UDPanswer = sendQues(OriginalDNSPacket '8 8 8 8') proxies = {'http': 'http://127 0 0 1:8080'} # DG Port s = requests Session() d = DNSRecord parse(UDPanswer) print d ques_domain = str(d questions[0] get_qname())[:-1] ques_tld = tldextract extract(ques_domain) ques_tld = "{} {}" format(ques_tld domain ques_tld suffix) print ques_tld for rr in d rr: try: s mount("http://"+ques_tld SourceAddressAdapter(addr[0])) # This was a silly try I know s proxies update(proxies) response = s get("http://"+ques_tld) print dir(response content) print response content if "Access Denied" in response content: d rr = [] d add_answer(*RR fromZone(ques_domain " A " SERVER_IP)) d add_answer(*RR fromZone(ques_domain " AAAA fe80::a00:27ff:fe4a:c8ec")) print d socket sendto(d pack() addr) return else: socket sendto(UDPanswer addr) return except Exception e: print e pass ```` The question is how can I send the request to DG and fool it like the req comes from a client? | In dansguardian conf `usexforwardedfor` is needed to enabled So the conf now looks like this: ```` # if on it adds an X-Forwarded-For: <clientip> to the HTTP request # header This may help solve some problem sites that need to know the # source ip on | off forwardedfor = on # if on it uses the X-Forwarded-For: <clientip> to determine the client # IP This is for when you have squid between the clients and DansGuardian # Warning - headers are easily spoofed on | off usexforwardedfor = on ```` And on proxy server I just needed to add the following which I tried before but because of the DG conf it did not work: ````response = s get("http://"+ques_tld headers={'X-Forwarded-For': addr[0]}) ```` It worked like a charm Thanks @boardrider |
How can I end while loop and skip for loop? How do I make it where if the user enters 'no' the program will not go through the for loop either I do not want it to tmpfile write(line) if the user enters 'no' ````def remove(): coname = raw_input('What company do you want to remove? ') # company name f = open('codilist txt') tmpfile = open('codilist tmp' 'w') for line in f: if coname upper() in line: while True: answer = raw_input('Are you sure you want to remove ' line upper() '?') if answer == 'yes': print line upper() ' has been removed ' elif answer == 'no': break # HERE IS WHERE I NEED HELP else: print 'Please choose yes or no ' else: tmpfile write(line) else: print 'Company name is not listed ' f close() tmpfile close() os rename('codilist tmp' 'codilist txt') ```` | Set a flag variable and then break out of the while loop Then in the for loop check if the flag is set and then break PS: if is <strong>not</strong> a loop |
How to find index of string in List Sorry if this is a noob question But I am new to programming so I am still learning I have a string ````string = "Hello Bye Hi" ```` I split it up: ````new_list_string = string split ```` output: ````["Hello" "Bye" "Hi"] ```` My question is how can I use this newly generated list for example if I do this: ```` new_list_string[1] ```` I do not get "Bye" instead I get an error: ````builtins TypeError: 'builtin_function_or_method' object is not iterable ```` | the problem is you did `string split` and not `string split()` Deeper explanation: when you do `string split` you never actually <them>call</them> `split` Therefore it returns the function rather than the list You need to call it with the syntax `string split()` |
Python property not working I have an object which inherits from ndb Model (a Google App Engine thing) This object has a property called commentid: ````class Comment(ndb Model): commentid = ndb StringProperty() ```` Reading a bunch of articles they all say this is the way to implement a property: ````@property def commentid(self): if not self _commentid: self _commentid = "1" return self _commentid ```` but I get an error saying `Comment object has no attribute _commentid` What am I doing wrong? Edit: Ok obviously I am a bit confused here I come from Objective-C where if you have a property called `x` then you automatically get a variable called `_x` in your getters and setters So I thought this is what was happening here in Python too But apparently I need to manually set a value for the variable with an underscore prefix All I want is to implement a getter where I do some checking of the value before returning it How would I do this? | If you access `self _commentid` directly it needs to be defined or it will raise an exception Since you are instead checking if `_commentid` is defined at all (to give it a default value) I would use `hasattr`: ````@property def commentid(self): if not hasattr(self "_commentid"): self _commentid = "1" return self _commentid ```` |
How to convolve two distirbutions from scipy library I have seen (by researching) convolution being done via numpy but if I wish to convolve two standard distributions (specifically a normal with a uniform) which are readily available in the scipy library is there a direct way of doing it rather than creating two arrays via numpy and convolve? | In general computing convolutions for distributions requires solving integrals I worked on this problem as part of the work for my dissertation [1] and wrote some Java (rather idiosyncratic) to carry out the operations Basically my approach was to make a catalog of distributions for which there are known results and fall back on a numerical method (convolution via discretization and FFT) if there is no known result For the combination of a Gaussian and a uniform the result is like a Gaussian bump split into two and pasted onto each end of a uniform distribution when the uniform is wide enough otherwise it just looks like a bump I can try to find formulas for that if you are interested You can try to compute the integrals via a symbolic computation system such as Maxima [2] For example Maxima says the convolution of a unit Gaussian with a unit uniform is: ````-(erf((sqrt(2)*s-sqrt(2))/2)-erf(s/sqrt(2)))/2 ```` [1] <a href="http://riso sourceforge net/docs/dodier-dissertation pdf" rel="nofollow">http://riso sourceforge net/docs/dodier-dissertation pdf</a> (in particular section C 3 17) [2] <a href="http://sourceforge net/p/maxima" rel="nofollow">http://sourceforge net/p/maxima</a> |
At what temperature does the metal become malleable? | 100 and 150 °C |
Installed pygraphviz on Windows 7 but unable to import it; cannot find _graphviz I am trying to install pygraphviz on my 64-bit installation of Windows 7 SP1 I was able to get the usual `python setup py install` command to work by correcting the following lines of the `setup py` file: ````include_dirs = r"C:\Program Files (x86)\Graphviz2 38\include" library_dirs = r"C:\Program Files (x86)\Graphviz2 38\lib\release\lib" ```` When I try to import it though I get the following error: ````Python 2 7 3 (default Apr 10 2012 23:31:26) [MSC v 1500 32 bit (Intel)] on win32 Type "help" "copyright" "credits" or "license" for more information >>> import pygraphviz Traceback (most recent call last): File "<stdin>" line 1 in <module> File "pygraphviz\__init__ py" line 58 in <module> from agraph import AGraph Node Edge Attribute ItemAttribute File "pygraphviz\agraph py" line 26 in <module> from import graphviz as gv File "pygraphviz\graphviz py" line 28 in <module> _graphviz = swig_import_helper() File "pygraphviz\graphviz py" line 20 in swig_import_helper import _graphviz ImportError: No module named _graphviz ```` This is puzzling because the directory pygraphviz gets installed to does contain a `_graphviz pyd` file If I go to that directory and try to import it I get a different ImportError: ````C:\Python27\Lib\site-packages\pygraphviz>python Python 2 7 3 (default Apr 10 2012 23:31:26) [MSC v 1500 32 bit (Intel)] on win32 Type "help" "copyright" "credits" or "license" for more information >>> import _graphviz Traceback (most recent call last): File "<stdin>" line 1 in <module> ImportError: DLL load failed: The specified module could not be found ```` So as far as I can tell the _graphviz pyd file seems to have been improperly compiled (I am using mingw32 having edited my distutils cfg file accordingly) I cannot find any other instances of this problem from other pygraphviz users What am I doing wrong? | Here is what I did for a perfectly working install Running Python 2 7 8 using the Anaconda distribution on Windows 64-bit SP1 as well - Download and install `Graphviz 2 38` from <a href="http://www graphviz org/Download_windows php" rel="nofollow">here</a> - Download the binary installer for `pygraphviz` from <a href="http://www lfd uci edu/~gohlke/pythonlibs/#pygraphviz" rel="nofollow">here</a> Use the appropriate version (`pygraphvizâ1 2 winâamd64âpy2 7 exe`) Install Make sure the installer detects your correct `PYTHONPATH` Result: <img src="http://i stack imgur com/J3r2x png" alt="enter image description here"> |
performing sum of outer products on sparse matrices I am trying to implement the following equation using scipy's sparse package: ````W = x[: 1] * y[: 1] T x[: 2] * y[: 2] T ```` where x & y are a nxm csc_matrix Basically I am trying to multiply each col of x by each col of y and sum the resulting nxn matrices together I then want to make all non-zero elements 1 This is my current implementation: ```` c = sparse csc_matrix((n n)) for i in xrange(0 m): tmp = bam id2sym_thal[: i] * bam id2sym_cort[: i] T minimum(tmp data ones_like(tmp data) tmp data) maximum(tmp data ones_like(tmp data) tmp data) c = c tmp ```` This implementation has the following problems: - Memory usage seems to explode As I understand it memory should only increase as c becomes less sparse but I am seeing that the loop starts eating up >20GB of memory with a n=10 000 m=100 000 (each row of x & y only has around 60 non-zero elements) - I am using a python loop which is not very efficient My question: Is there a better way to do this? Controlling memory usage is my first concern but it would be great to make it faster! Thank you! | In terms of memory and performance this might be a prime candidate for using <a href="http://cython org/" rel="nofollow">Cython</a> There is a section of the following paper describing its use with sparse scipy matricies: <a href="http://folk uio no/dagss/cython_cise pdf" rel="nofollow">http://folk uio no/dagss/cython_cise pdf</a> |
Python - C embedded Segmentation fault I am facing a problem similar to the <a href="http://stackoverflow com/questions/7676314/py-initialize-py-finalize-not-working-twice-with-numpy">Py_initialize / Py_Finalize not working twice with numpy</a> The basic coding in C: ````Py_Initialize(); import_array(); //Call a python function which imports numpy as a module //Py_Finalize() ```` The program is in a loop and it gives a seg fault if the python code has numpy as one of the imported module If I remove numpy it works fine As a temporary work around I tried not to use Py_Finalize() but that is causing huge memory leaks [ observed as the memory usage from TOP keeps on increasing ] And I tried but did not understand the suggestion in that link I posted Can someone please suggest the best way to finalize the call while having imports such as numpy Thanks santhosh | I am not quite sure how you do not seem to understand the solution posted in <a href="http://stackoverflow com/questions/7676314/py-initialize-py-finalize-not-working-twice-with-numpy">Py_initialize / Py_Finalize not working twice with numpy</a> The solution posted is quite simple: call Py_Initialize and Py_Finalize only once for each time your program executes Do not call them every time you run the loop I assume that your program when it starts runs some initialization commands (which are only run once) Call Py_Initialize there Never call it again Also I assume that when your program terminates it has some code to tear down things dump log files etc Call Py_Finalize there Py_Initialize and Py_Finalize are not intended to help you manage memory in the Python interpreter Do not use them for that as they because your program to crash Instead use Python's own functions to get rid of objects you do not want to keep If you really MUST create a new environment every time you run your code you can use Py_NewInterpreter and to create a sub-interpreter and Py_EndInterpreter to destroy that sub-interpreter later They are documented near the bottom of the <a href="http://docs python org/2/c-api/init html" rel="nofollow">Python C API</a> page This works similarly to having a new interpreter except that modules are not re-initialized each time a sub-interpreter starts |
How do I import other python code from a directory? I am very new to python and I have a directory structure like this: ````root --child -----config py example py ```` In `example py` I just tried: ````import child ```` but that does not seems to be working Where I am making the mistake! | If you want to import `config py`Â with importing `child`Â you need to define `child`Â as a package To do so you need to create an `__init__ py` file in your `child` directory Check this about <a href="http://docs python org/2/tutorial/modules html#packages" rel="nofollow">packages</a> |
Running script on every text file in folder I am looking to run my script on all text files in a directory but I am having a lot of trouble Here is the code I have so far: ````data = {} date = ID = values = None infile = "z140327b txt" outfile = "oz140327b txt" sample = 1 with open(infile) as datafile open(outfile 'w') as f2: for line in datafile: if line lstrip() startswith('!'): date = line[1:] strip() elif line lstrip() startswith('?'): sample = 2 elif line lstrip() startswith('@'): ID = line[1:] strip() data[ID] = {} data[ID]['date'] = date tedtime = ID[0:2] ":" ID[2:] str_1 = str(data[ID]) f2 write(tedtime ' ' date ' ' str(sample)) elif line strip(): if not ID: continue try: words = line split() value = float(words[-1]) # last word unit = words[-2] lstrip('(') rstrip(')') item = {'value': value 'unit': unit} key = ' ' join(words[:-2]) data[ID][key] = item except (ValueError) as err: print("Could not parse this line:") print(line) continue else: # if 'empty' line ca_str = str(data[ID]['Contact Angle']['value']) f2 write(' ' ca_str '\n') ID = None ca_str2 = str(data[ID]['Contact Angle']['value']) f2 write(' ' ca_str2 '\n') ```` At the minute I am manually adding the filename (infile) and the output filename (outfile) I would like the output file name to be the same as the input file preceded by an 'of as shown in the example code | You can use glob to get all the files in the directory: ````from glob import glob files=glob('* txt') for filename in files: with open(filename 'r') as f open('of+filename 'w') as f1: #read from f #write to f1 ```` Simply iterate over each filename do what you want to it and write it to a new file Make sure your script is run from the directory you are in or you need to pass the path to glob |
Find and copy a line using regex in Python I am new to this forum and to programming and apologize in advance if I violate any of the forum rules I have researched this extensively but I could not find a solution for my problem So I have a very long file that has this general structure: ````data=""" 20 020001 563410 9 20 520001 577410 20 21 022001 591466 9 21 522001 605466 120 23 196001 652338 2 25 278001 710634 7 25 780001 724690 144 26 280001 738690 9 26 782001 752746 40 27 282001 766746 9 27 784001 780802 140 29 372001 825266 2 31 458001 883674 7 31 958002 897674 8 32 458002 911674 9 32 958002 925674 10 """ ```` I imported the file using ````with open("C:\blablabla\text txt" 'r+') as infile: data = infile read() ```` Now I am trying to use a regular expression to find all lines that end with 140 through 146 so I did this: ````items=re findall(' 14[0-6]\n' data re MULTILINE) for x in items: print x ```` This works but when I now try to copy those lines that contain the regular expression ````for x in items: if items in data: data write(items) ```` I get the following error: ````if items in data: TypeError: 'in <string>' requires string as left operand not list ```` I understand what the problem is but I do not know how to solve it How can I feed the left operand a string when the outcome of my regex is a list? Any help is much appreciated! | You should simply handle each line separately: ````data = infile readlines() for line in data: if re match(' 14[0-6]\n' line): print line[:-1] ```` The last character of the line is a trailing newline which would be duplicated by the one the `print` statement includes |
How to get minecraft status? What is wrong? I recieve nothing I have also tried with other Minecraft-servers ````import socket from struct import pack unpack host = socket gethostbyname("localhost") port = 25565 s = socket socket(socket AF_INET socket SOCK_STREAM) s connect((host port)) packet = "" packet = pack('i' 4) packet = pack('p' host) packet = pack('H' port) packet = pack('i' 1) s send(packet) print s recv(1024) # Recv nothing ? ```` | I guess this is wrong : ````packet = pack('p' host) packet = pack('H' port) ```` Replace with this : ````packet = pack('p' port) packet = pack('H' host) ```` |
What did James Glimm have to say about von Nuemann? | he is regarded as one of the giants of modern mathematics |
What method did temples and churches use to measure time? | Incense sticks and candles |
python inactive system detect keyboard activity I am trying to make a simple python program that will detect if either my keyboard or mouse are idle and if so to move the mouse this is to circumvent an idle logout timeout on a macbook I cannot change these settings as they are policies pushed by my employer It is set to like 3 minutes which is extremely annoying I have it working for mouse inactivity but not keyboard How would I or what library would i use to detect if no keyboard activity has happened? ````#!/usr/bin/env python import pyautogui import time from random import randrange def timer(): get_time = int(time time()) return get_time def main(): while True: snapshot = { "time" : timer() "position" : pyautogui position() } time sleep(5) if snapshot["position"] == pyautogui position(): pyautogui moveTo(400 randrange(1 50)) else: pass main() ```` | I did something similar here <a href="https://gitlab com/shakerloops/shakerloops" rel="nofollow">https://gitlab com/shakerloops/shakerloops</a> But I do not think I was detecting key events Even so you could theoretically just use keyevent from pygame or wxpython both can detect keyboard events without actually launching a GUI Example: <a href="https://gitlab com/makerbox/alluvial/raw/master/usr/local/bin/alluvial/alluvial py" rel="nofollow">https://gitlab com/makerbox/alluvial/raw/master/usr/local/bin/alluvial/alluvial py</a> Those two combined ought to work! |
Web app starts many times - web py I have this code where it loads necessary files and prints necessary information when the server starts but inside `if __name__ == "__main__":` I am starting a background process as well then finally app run() is executed My problem is after loading all and comes to the starting of background process it starts to print and load everything from beginning again And also it does the same when the server get its first request (GET/POST) How can I make it load only once? ````import web from multiprocessing import Process import scripts print 'Engine Started' # Code to load and print necessary stuff goes here urls = ( '/test( *)' 'Test' ) class Test(): def GET(self r): tt = web input() t print tt return tt if __name__ == "__main__": try: print 'Cache initializing ' p = Process(target=scripts initiate_cleaner) p start() # Starts the background process except Exception err: print "Error initializing cache" print err app = web application(urls globals()) app run() ```` So this loads thrice ('Engine Started' prints thrice) after starting process and requesting from localhost:8080/test?t=er I went through <a href="http://stackoverflow com/questions/25504149/why-does-running-the-flask-dev-server-run-itself-twice">this</a> but it solves the problem in flask and I use web py | I am not sure why this surprises you or why it would be a problem A background process is by definition a separate process from the web process; each of those will import the code and therefore print that message If you do not want to see that message put it inside the `if __name__` block |
Cannot scrape nested html using BeautifulSoup I have am interested in scraping "0 449" from the following source code from <a href="http://hdsc nws noaa gov/hdsc/pfds/pfds_map_cont html?Lat=33 146425&Lon=-87 5805543" rel="nofollow">http://hdsc nws noaa gov/hdsc/pfds/pfds_map_cont html?Lat=33 146425&Lon=-87 5805543</a> ````<td class="tblInner" id="0-0"> <div style="font-size:110%"> <b>0 449</b> </div> "(0 364-0 545)" </td> ```` Using BeautifulSoup I currently have written: ````storm=soup find("td" {"class":"tblInner" "id":"0-0"}) ```` which results in: ````<td class="tblInner" id="0-0">-</td> ```` I am unsure of why everything nested within the td is not showing up When I search the contents of the td my result is simply "-" How can I scrape the value that I want from this code? | You are likely scraping a website that uses javascript to update the DOM after the initial load You have a couple choices: - Find out where did the javascript code that fills the HTML page got the data from and call this instead The data most likely comes from an API that you can call directly with CURL That is the best method 99% of the time - Use a headless browser (zombie js ) to retrieve the HTML code after the javascript changes it Convenient and fast but few tools in python to do this (google `python headless browser`) - Use selenium or splinter to remote control a real browser (chrome firefox ) It is convenient and works in python but slow as hell <strong>Edit:</strong> I did not see that you posted the url you wanted to scrap In your particular case the data you want comes from an AJAX call to this URL: <a href="http://hdsc nws noaa gov/cgi-bin/hdsc/new/cgi_readH5 py?lat=33 1464&lon=-87 5806&type=pf&data=depth&units=english&series=pds" rel="nofollow">http://hdsc nws noaa gov/cgi-bin/hdsc/new/cgi_readH5 py?lat=33 1464&lon=-87 5806&type=pf&data=depth&units=english&series=pds</a> You now only need to understand what each parameter does and parse the output of that instead of writing an HTML scrapper |
Iterating through a python list of list and creating a new list Basically I have a dictionary of the form: ````'the trip':('The Trip' 'www SearchHero com' "See sponsored listings for 'The Trip ' Click here!" 0 1 'The Trip' '3809466') 'post office':('Post Office' 'www SearchHero com' "See sponsored listings for 'Post Office ' Click here!" 0 1 'Post Office' '5803938') 'balanced diets':('Last Minute Deals' 'www SearchHero com' "See sponsored listings for 'Last Minute Deals ' Click here!" 0 1 'Last Minute Deals' '1118375') ```` I want to output a list of the form: `{' 1 3809466' ' 1 5803938' ' 1 '1118375'}` I am new to Python but in Ruby I know I would use the map function What is the equivalent in python? Thanks in advance | ````[' ' join((value[3] value[5])) for value in my_dict iteritems()] ```` |
Python: Sort a list into multiple lists or dictionary I have a list of strings here is an example: ````wallList = ['wall_l0' 'wall_l1' 'wall_broken_l0' 'wall_broken_l1' 'wall_vwh_l0' 'wall_vwh_l1' 'wall_vwh_broken_l0' 'wall_vwh_broken_l1' 'wall_vpi_l0' 'wall_vpi_l1' 'wall_vpi_broken_l0' 'wall_vpi_broken_l1'] ```` And I would like to group them together by wall type and state (default / broken): ````[['wall_l0' 'wall_l1'] ['wall_broken_l0' 'wall_broken_l1']] [['wall_vwh_l0' 'wall_vwh_l1'] ['wall_vwh_broken_l0' 'wall_vwh_broken_l1']] [['wall_vpi_l0' 'wall_vpi_l1'] ['wall_vpi_broken_l0' 'wall_vpi_broken_l1']] ```` Anyone know how best to do this or know of a python recipe? | Split on _: `string split('_')` If you get 2 fields back you have the degenerate case If you get 3 group by the middle field of 3 A dictionary of lists would probably help or better a collections defaultdict(list) |
curly bracket issue when inserting scrapy crawler results to postgresql when using the scrapy she will: ````scrapy she will âhttp://blogs reuters com/us/â ```` and trying to extract the title of the url: ````response xpath('(//title/text())') extract() ```` i get: ````[youâAnalysis & Opinion | Reuters'] ```` and when i run my crawler i get the following in my postgresql database: ````{âAnalysis & Opinion | Reutersâ} ```` what I want is: ````Analysis & Opinion | Reuters ```` How can I make that happen? Also hereâs the pipeline iâm using if that helps: ````import scrapy from scrapy contrib spiders import CrawlSpider Rule from scrapy contrib linkextractors import LinkExtractor from targets items import TargetsItem class MySpider(CrawlSpider): name = 'reuters' allowed_domains = ['blogs reuters com'] start_urls = [ 'http://blogs reuters com/us/' ] rules = ( Rule(LinkExtractor(allow_domains=('blogs reuters com' )) callback='parse_item') ) def parse_item(self response): item = TargetsItem() item['title'] = response xpath('(//title/text())') extract() item['link'] = response url return item ```` | `[youâAnalysis & Opinion | Reuters']` is the textual representation of a Python list containing the unicode string `'Analysis & Opinion | Reuters'` Replace ````item['title'] = response xpath('(//title/text())') extract() ```` with ````item['title'] = response xpath('(//title/text())') extract()[0] ```` and you should be fine (as long as `response xpath('(//title/text())') extract()` returns a list of length >= 1 of course) |
In recent years, what usage has risen dramatically? | 3G/4G mobile internet |
Django manage py cannot find an INSTALLED_APP even though the module is in the path When I run python manage py she will I get an error about the last app I have added to INSTALLED_APPS namely django-evolution saying it is an undefined module This is despite the fact that I have added the path to django-evolution to the system path In fact right after this error I can run python and do an import on django_evolution and everything is fine Why is not django or python seeing this module when clearly it is been setup and even added to the path? EDIT: This only happens when running from iPython When I run from the cmd prompt it works fine Go figure | You need to add it to your INSTALLED_APPS section of settings py |
Not throwing exception while xpath is not available on page using selenium and python? If xpath is not available on a page then it should throw exception but it breaks the whole program with errors I have loaded complete page using selenium and then I am trying to click on all read-more link but not working <strong>Page Link</strong> <a href="https://www zomato com/ncr/k3-jw-marriott-new-delhi-igi-airport-new-delhi" rel="nofollow">https://www zomato com/ncr/k3-jw-marriott-new-delhi-igi-airport-new-delhi</a> <strong>sample code</strong> ````xpath_content=" //*[@id='reviews-container']/div[1]/div[3]/div[1]/div/div/div[3]/div/div[1]/div[2]/div/span" temp="true" while temp: try: WebDriverWait(driver 20) until(EC presence_of_element_located((By XPATH xpath_content))) urls=driver find_element_by_xpath(xpath_content) text=urls text if text: temp=text print "XPATH read_more=" temp driver find_element_by_xpath(xpath_content) click() except TimeoutException: print driver title "no Read more review" temp="" ```` <strong>Got Error</strong> ```` File "zomato_delhi py" line 31 in read_more_content driver find_element_by_xpath(xpath_content) click() File "/usr/local/lib/python2 7/dist- packages/selenium/webdriver/remote/webelement py" line 65 in click self _execute(Command CLICK_ELEMENT) File "/usr/local/lib/python2 7/dist- packages/selenium/webdriver/remote/webelement py" line 402 in _execute return self _parent execute(command params) File "/usr/local/lib/python2 7/dist-packages/selenium/webdriver/remote/webdriver py" line 175 in execute self error_handler check_response(response) File "/usr/local/lib/python2 7/dist-packages/selenium/webdriver/remote/errorhandler py" line 166 in check_response raise exception_class(message screen stacktrace) selenium common exceptions ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with Stacktrace: at fxdriver preconditions visible (file:///tmp/tmpKtHaW3/extensions/fxdriver@googlecode com/components/command-processor js:9587) at DelayedCommand prototype checkPreconditions_ (file:///tmp/tmpKtHaW3/extensions/fxdriver@googlecode com/components/command-processor js:12257) at DelayedCommand prototype executeInternal_/h (file:///tmp/tmpKtHaW3/extensions/fxdriver@googlecode com/components/command-processor js:12274) at DelayedCommand prototype executeInternal_ (file:///tmp/tmpKtHaW3/extensions/fxdriver@googlecode com/components/command-processor js:12279) at DelayedCommand prototype execute/< (file:///tmp/tmpKtHaW3/extensions/fxdriver@googlecode com/components/command-processor js:12221) ```` | Remove the while loop It is working after removing the While loop |
Generate all subsets of a string using recursion `string = 'abc'` All subsets of said string are: `[a b c ab abc ac because '(empty string)']` I need to generate all of these subsets using a recursive function but I cannot figure out how | For each char recur to use and not use ````s = 'abc' def recur(s prefix out): if len(s) > 0: recur(s[1:] prefix+s[0] out) recur(s[1:] prefix out) out append(prefix+s[0]) return out print recur(s '' ['']) ```` outputs ````['' 'abc' 'ac' 'ab' 'because' 'c' 'b' 'a'] ```` |
What is the largest private university in the United States? | null |
Which entity supports that the right to vote is a hallmark of economic status? | null |
Ways to save django model using nested dictionary I will try to make this as simple as I can: <strong>I have 2 models</strong> ````from django db import models class OrderDetail(models Model): product = models CharField(max_length=100) price = models CharField(max_length=50) class Order(models Model): url = models CharField(max_length=255 unique=True) loaded_info = models BooleanField(default=False) status = models CharField(max_length=100 null=True) details = models OneToOneField(OrderDetail) ```` <strong>And I whish to save using a dict like this:</strong> ````data = { "order": { "url": "http://stackoverflow com/" "loaded_info": True "status": "complete" "details": { "product": "Fresh answer" "price": "50 points" } } } ```` <strong>I would like to do something close to:</strong> ````order = Order(**data) save() ```` And get `Order` and `OrderDetail` saved using a single line | Have a look at <a href="https://docs djangoproject com/en/1 9/topics/serialization/" rel="nofollow">https://docs djangoproject com/en/1 9/topics/serialization/</a> In this case you would do something like: ````qs = Order objects select_related('details') get(pk=1) data = serializers serialize("json" qs) ```` |
Python SocketServer TCPServer errno 10054 I am running a python server using the socketserver module in python 2 7 OmniPeek packet analysis tool shows the TCP handshake completes but the server immediately sends a reset packet killing the connection Simplified server code which shows the problem is: ````from threading import Lock Thread Condition import SocketServer import socket import sys import time class ThreadedTCPRequestHandler(SocketServer BaseRequestHandler): def __init__(self state *args **keys): try: state['lock'] acquire() state['client_count'] = 1 finally: state['lock'] release() self state = state SocketServer BaseRequestHandler __init__(self *args **keys) def handle(self): self state['lock'] acquire() count = self state['client_count'] self state['lock'] release() while True: try: self state['lock'] acquire() running = self state['running'] self state['lock'] release() if not running: break; time sleep(1) # do some work except Exception as message: print message print "ThreadedTCPRequestHandler shutting down " class ThreadedTCPServer(SocketServer ThreadingMixIn SocketServer TCPServer): pass def handler_factory(state): def createHandler(*args **keys): return ThreadedTCPRequestHandler(state *args **keys) return createHandler if __name__ == "__main__": lock = Lock() cv = Condition(lock) state = {'running': True 'client_count': 0 'lock': lock 'cv': cv} server = ThreadedTCPServer(('localhost' 12345) handler_factory(state)) server_thread = Thread(target=server serve_forever) server_thread daemon = True server_thread start() print "Server loop running in thread:" server_thread name # wait for a client to connect cv acquire() while state['client_count'] == 0 and state['running']: cv wait(1 0) # print message cv release() # substitute real work here time sleep(5) lock acquire() state['running'] = False lock release() server shutdown() ```` and the client code: ````import socket if __name__ == "__main__": try: client = socket socket(socket AF_INET socket SOCK_STREAM) print 'ip: {} port {}' format('10 4 2 54' 12345) client connect(('10 4 2 54' 12345)) while True: data = client recv(4096) if len(data) == 0: break; print 'data: {}' format(data) client shutdown(socket SHUT_RDWR) client close() except Exception as message: print message ```` The server code is based off python 2 7 docs serversocket Mixin example and seems pretty straightforward but Thanks | not sure what your expected behaviour is but if you make a couple of changes you will be able to see that it can work replace your handle method ````def handle(self): while True: try: data = self request recv(1024) strip() if len(data) != 0: print data time sleep(1) # do some work self request send('test data') except Exception as message: print message break print "ThreadedTCPRequestHandler shutting down " ```` and client(inside main): ````try: client = socket socket(socket AF_INET socket SOCK_STREAM) print 'ip: {} port {}' format('localhost' 1232) client connect(('localhost' 1232)) client send('test') n = 0 while True: data = client recv(4096) if len(data) != 0: print 'data: {}' format(data) time sleep(1) n = 1 client send('keep-alive' str(n) '\n') print 'here' client shutdown(socket SHUT_RDWR) client close() except Exception as message: print message ```` I just modded it to send stuff and print stuff But it does not crash I think there is an issue with your self state['lock'] acquire() and release() calls I took out the 'running' check as it is not really used except at the end of the server code Also without any action sockets will time out Once again I am not claiming to have 'fixed' your problem and I am not sure exactly what you are looking for just helping you brainstorm! |
What Empire was followed by native Sumerian rule? | null |
Change color based on recursion depth Python Turtle I have a coding problem I am having trouble with I am learning recursion and so far having a pretty good time with it We have starting with basic turtle drawings using the python turtle graphics module I have got the picture code down but I am also supposed to change the color of the turtle's pen based on depth My professor only briefly touched on mod (%) to achieve this but I have no idea where to begin and was hoping for some assistance Thanks in advance I cannot add pics because my rep is not high enough but basically if you run the code it draws "S" figures The first "S" should be green second two red third three green etc Thanks again Here is the code: ````from turtle import * def drawzig2(depth size): if depth == 0: pass elif depth: left(90) fd(size/2) right(90) fd(size) left(45) drawzig2(depth-1 size/2) right(45) fd(-size) left(90) fd(-size) right(90) fd(-size) left(45) drawzig2(depth-1 size/2) right(45) fd(size) left(90) fd(size/2) right(90) drawzig2(4 100) ```` | try this ````from turtle import * colors = ['green' 'red'] def drawzig2(depth size): if depth == 0: pass elif depth: pencolor(colors[depth % len(colors)]) left(90) fd(size/2) right(90) fd(size) left(45) drawzig2(depth-1 size/2) right(45) fd(-size) left(90) fd(-size) right(90) fd(-size) left(45) drawzig2(depth-1 size/2) right(45) fd(size) left(90) fd(size/2) right(90) drawzig2(4 100) ```` |
requests GET saves not entirely file Need to download artefact from Artifactory using <a href="https://www jfrog com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-RetrieveArtifact" rel="nofollow">Artifactory REST API</a> My code is: ````with open(jfrog_testfile 'wb') as outfile: data = requests get(baseurl auth=(jfrog_user jfrog_pswd) stream=True) shutil copyfileobj(data raw outfile) data raise_for_status() ```` And another one attempt with same result: ````with open(jfrog_testfile 'wb') as outfile: data = requests get(baseurl auth=(jfrog_user jfrog_pswd) stream=True) for chunk in data iter_content(65536): outfile write(chunk) data raise_for_status() ```` `baseurl` is correct i e : ````baseurl = os path join(jfrog_url jfrog_api jfrog_repo jfrog_tetstdir jfrog_testfile) print(baseurl) ```` returns: ````https://project artifactoryonline com/project/api/storage/project-releases-local/ppp/artefact war ```` Problem is - exactly artefact size is 5 7 MB but after that reqeust - I got only 841 bytes: ````$ ls -l artefact war -rw-r--r-- 1 username staff 841 Jan 21 11:47 artefact war ```` Even if I run same request with `curl -o` - I have same 841 bytes Using `wget` - I have whole file 5 7 MB What is wrong with m(e)y request? | My error was in URL for GET URL consist from: ````jfrog_url = 'https://project artifactoryonline com/project/' jfrog_api = 'api/storage/' jfrog_repo = 'project-releases-local' jfrog_tetstdir = 'artefact' jfrog_testfile = 'artefact war' ```` And: `baseurl = os path join(jfrog_url jfrog_repo jfrog_tetstdir jfrog_testfile)` For `GET` do not need insert `jfrog_api` in request So instead of: `requests get('https://project artifactoryonline com/project/api/storage/project-releases-local/ppp/artefact war')` must be used: `requests get(https://project artifactoryonline com/project/project-releases-local/ppp/artefact war')` `'api/storage/'` will be necessary for `PUT`/`POST` requests as I remember |
How to print Tkinter variables as part of a string? In regular Python 3 4 if you want to print a variable in the middle of a string you do something like this: ````x = 31 print("The value of x is %s" % (x)) ```` And it will print `The value of x is 31` In Tkinter if you want to have a label read a certain variable you simply define the label and if at any point the variable of the label changes the label updates automatically if it is a Tkinter label For example: ````var = StringVar() var set("Label") label = Label(main text=var) ```` However if I want part of a string to be a variable in Tkinter ````items = IntVar() items set(14) b = Button(main text="I have %s items" % (items get()) command=additem) def additem(): items set(items get() 1) ```` The button does not update When I press it the printed value remains `"I have 14 items"` instead of changing to `"I have 15 items"` as it should How should I go about doing this? | <blockquote> When I press it the printed value remains "I have 14 items" instead of changing to "I have 15 items" as it should </blockquote> No it should not You defined the text of the button as a string with the number that `items` had at that time Nowhere are you telling the text to update The `text` and `textvariable` attributes do very different things `text` sets the text which does not update `textvariable` takes a `StringVar` or other Tkinter variable and keeps the text updated to the contents of this variable So also please note that your first example is wrong you have to use the `textvariable` attribute there to bind a `StringVar`'s contents to a button not `text` I think the best solution is to not use an `IntVar` just update the text manually using `configure`: ````root = Tk() def additem(): global items items = 1 b configure(text="I have %s items" % (items)) items = 14 b = Button(root text="I have %s items" % (items) command=additem) b pack() root mainloop() ```` <hr> Another option would be to split up the label into three labels and put them together in a frame like: ````root = Tk() def additem(): items set(items get() 1) f = Frame(root) items = IntVar() items set(14) l0 = Label(f text="I have") l1 = Label(f textvariable=items) l2 = Label(f text="items") b = Button(root text="Add item" command=additem) l0 pack(side=LEFT) l1 pack(side=LEFT) l2 pack(side=LEFT) f pack() b pack() root mainloop() ```` |