input_text
stringlengths 1
40.1k
| target_text
stringlengths 1
29.4k
⌀ |
---|---|
Why and where python interned strings when executing `a = 'python'` while the source code does not show that? I am trying to learn the intern mechanism of python using in the implementation of string object But in both `PyObject *PyString_FromString(const char *str)`and`PyObject *PyString_FromStringAndSize(const char *str Py_ssize_t size)` python interned strings only when its size is 0 or 1 ````PyObject * PyString_FromString(const char *str) { fprintf(stdout "creating %s\n" str);------------[1] // //creating /* share short strings */ if (size == 0) { PyObject *t = (PyObject *)op; PyString_InternInPlace(&t); op = (PyStringObject *)t; nullstring = op; Py_INCREF(op); } else if (size == 1) { PyObject *t = (PyObject *)op; PyString_InternInPlace(&t); op = (PyStringObject *)t; characters[*str & UCHAR_MAX] = op; Py_INCREF(op); } return (PyObject *) op; } ```` But for longer strings like `a ='python'` if I modified the `string_print` to print the address it is identical to the one of another string varable `b = 'python` And at the line marked as [1] above I print a piece of log when python creating a string object showing multiple strings are created when executing `a ='python'` just without 'python' ````>>> a = 'python' creating stdin creating stdin string and size creating (null) string and size creating a = 'python' ? creating a string and size creating (null) string and size creating (null) creating __main__ string and size creating (null) string and size creating (null) creating <stdin> string and size creating d creating __lltrace__ creating stdout [26691 refs] creating ps1 creating ps2 ```` So where is string 'python' created and interned? <strong>Update 1</strong> Plz refer to the comment by @Daniel Darabos for a better interpretation It is a more understandable way to ask this question The following is the output of `PyString_InternInPlace` after adding a log print command ````PyString_InternInPlace(PyObject **p) { register PyStringObject *s = (PyStringObject *)(*p); fprintf(stdout "Interning "); PyObject_Print(s stdout 0); fprintf(stdout "\n"); // } >>> x = 'python' Interning 'cp936' Interning 'x' Interning 'cp936' Interning 'x' Interning 'python' [26706 refs] ```` | The string literal is turned into a string object by the compiler The function that does that is `PyString_DecodeEscape` at least in Py2 7 you have not said what version you are working with Update: The compiler interns some strings during compilation but it is very confusing when it happens The string needs to have only identifier-ok characters: ````>>> a = 'python' >>> b = 'python' >>> a is b True >>> a = 'python!' >>> b = 'python!' >>> a is b False ```` Even in functions string literals can be interned: ````>>> def f(): return 'python' >>> def g(): return 'python' >>> f() is g() True ```` But not if they have funny characters: ````>>> def f(): return 'python!' >>> def g(): return 'python!' >>> f() is g() False ```` And if I return a pair of strings none of them are interned I do not know why: ````>>> def f(): return 'python' 'python!' >>> def g(): return 'python' 'python!' >>> a b = f() >>> c d = g() >>> a is c False >>> a == c True >>> b is d False >>> b == d True ```` Moral of the story: interning is an implementation-dependent optimization that depends on many factors It can be interesting to understand how it works but never depend on it working any particular way |
Convert decimal range to Numpy array with each bit being an array element I have created a small function that takes as input an integer `length` and returns a `numpy` `array` of the binary representation of all `2**length` integer numbers in the range `[0:2**length-1]` ````import numpy as np def get_bitstrings(length): # We need to binary-fy 2^length numbers iterations = 2**length # Pre-allocate memory the_array = np zeros((iterations length)) # Go through all decimals in the range [0:iterations-1] for num in range(iterations): # Get binary representation in string format with 'length' zeroes padded t_string = '{f_num:0{f_width}b}' format(f_num=num f_width=length) # Convert to a Python list t_list = list(t_string) # Convert to Numpy array and store the_array[num :] = np array(t_list) return the_array if __name__ == '__main__': var1 = get_bitstrings(2) var2 = get_bitstrings(3) print('var1:\n{}\n' format(var1)) print('var2:\n{}\n' format(var2)) ```` which yields: ````var1: [[ 0 0 ] [ 0 1 ] [ 1 0 ] [ 1 1 ]] var2: [[ 0 0 0 ] [ 0 0 1 ] [ 0 1 0 ] [ 0 1 1 ] [ 1 0 0 ] [ 1 0 1 ] [ 1 1 0 ] [ 1 1 1 ]] ```` The process includes getting a binary representation of each integer number as a string (with 0s padded before it such that the length is constant at `length`) converting the string into a Python list and then converting the list into a `numpy` `array` I found that to be the only way to satisfy the requirement that each bit is an entry in the array â i e bitstring `1010` is a `1x4` `numpy` `array` and not simply an integer in a `1x1` array But I am sure there are better alternatives hence the question The problem as you can imagine is that this is inefficient I was wondering whether I can improve this by using Python/Numpy trickery <them>Edit</them>: I used to do this in MATLAB with this snippet: <blockquote> t_length = 5; dc = [0:2^t_length-1]'; because = rem(floor(dc*pow2(-(t_length-1):0)) 2); </blockquote> But I am a complete noob when it comes to Python/Numpy! Maybe it will inspire someone `:-)` | One way is to use `numpy binary_repr` It will result in a string but you can easily convert that to an array of ints or floats (just change the `dtype` argument) For example: ````import numpy as np k = 4 print np array([list(np binary_repr(x k)) for x in range(2**k)] dtype=int) ```` This yields: ````[[0 0 0 0] [0 0 0 1] [0 0 1 0] [0 0 1 1] [0 1 0 0] [0 1 0 1] [0 1 1 0] [0 1 1 1] [1 0 0 0] [1 0 0 1] [1 0 1 0] [1 0 1 1] [1 1 0 0] [1 1 0 1] [1 1 1 0] [1 1 1 1]] ```` Or if you wanted a more readable version: ````def bitstrings(k): binary = [np binary_repr(item width=k) for item in range(2**k)] return np array([list(item) for item in binary] dtype=int) ```` |
SqlAlchemy Join Query I have tables like this: Box |- issues[] Issue |- status_id |- status (related through status_id) Status |- id I want to get all the boxes where the âissuesâ field for each box will only contain issues that donât have a status_id = 5 The following isnât working db session query(Box) join(Issue) filter(Issue status_id != 5) all() What is wrong with the above code? | If I have understood your situation correctly I think the following is what you are looking for: ````db session query(Box) outerjoin(Box issues) filter(or_(Issue status_id is_(None) Issue status_id != 5)) options(contains_eager(Box issues)) all() ```` |
Python Xarray add DataArray to Dataset Very simple question but I cannot find the answer online I have a `Dataset` and I just want to add a named `DataArray` to it Something like `dataset add({"new_array": new_data_array})` I know about `merge` and `update` and `concatenate` but my understanding is that `merge` is for merging two or more `Dataset`s and `concatenate` is for concatenating two or more `DataArray`s to form another `DataArray` and I have not quite fully understood `update` yet I have tried `dataset update({"new_array": new_data_array})` but I get the following error ````InvalidIndexError: Reindexing only valid with uniquely valued Index objects ```` I have also tried `dataset["new_array"] = new_data_array` and I get the same error <h1>Update</h1> I have now found out that the problem is that some of my coordinates have duplicate values which I did not know about Coordinates are used as index so Xarray gets confused (understandably) when trying to combine the shared coordinates Below is an example that works ````names = ["joaquin" "manolo" "xavier"] n = xarray DataArray([23 98 23] coords={"name": names}) print(n) print("======") m = numpy random randint(0 256 (3 4 4)) astype(numpy uint8) mm = xarray DataArray(m dims=["name" "row" "column"] coords=[names range(4) range(4)]) print(mm) print("======") n_dataset = n rename("number") to_dataset() n_dataset["mm"] = mm print(n_dataset) ```` Output: ````<xarray DataArray (name: 3)> array([23 98 23]) Coordinates: * name (name) <U7 'joaquin' 'manolo' 'xavier' ====== <xarray DataArray (name: 3 row: 4 column: 4)> array([[[ 55 63 250 211] [204 151 164 237] [182 24 211 12] [183 220 35 78]] [[208 7 91 114] [195 30 108 130] [ 61 224 105 125] [ 65 1 132 137]] [[ 52 137 62 206] [188 160 156 126] [145 223 103 240] [141 38 43 68]]] dtype=uint8) Coordinates: * name (name) <U7 'joaquin' 'manolo' 'xavier' * row (row) int64 0 1 2 3 * column (column) int64 0 1 2 3 ====== <xarray Dataset> Dimensions: (column: 4 name: 3 row: 4) Coordinates: * name (name) object 'joaquin' 'manolo' 'xavier' * row (row) int64 0 1 2 3 * column (column) int64 0 1 2 3 Data variables: number (name) int64 23 98 23 mm (name row column) uint8 55 63 250 211 204 151 164 237 182 24 ```` The above code uses `names` as the index If I change the code a little bit so that `names` has a duplicate say `names = ["joaquin" "manolo" "joaquin"]` then I get an `InvalidIndexError` Code: ````names = ["joaquin" "manolo" "joaquin"] n = xarray DataArray([23 98 23] coords={"name": names}) print(n) print("======") m = numpy random randint(0 256 (3 4 4)) astype(numpy uint8) mm = xarray DataArray(m dims=["name" "row" "column"] coords=[names range(4) range(4)]) print(mm) print("======") n_dataset = n rename("number") to_dataset() n_dataset["mm"] = mm print(n_dataset) ```` Output: ````<xarray DataArray (name: 3)> array([23 98 23]) Coordinates: * name (name) <U7 'joaquin' 'manolo' 'joaquin' ====== <xarray DataArray (name: 3 row: 4 column: 4)> array([[[247 3 20 141] [ 54 111 224 56] [144 117 131 192] [230 44 174 14]] [[225 184 170 248] [ 57 105 165 70] [220 228 238 17] [ 90 118 87 30]] [[158 211 31 212] [ 63 172 190 254] [165 163 184 22] [ 49 224 196 244]]] dtype=uint8) Coordinates: * name (name) <U7 'joaquin' 'manolo' 'joaquin' * row (row) int64 0 1 2 3 * column (column) int64 0 1 2 3 ====== --------------------------------------------------------------------------- InvalidIndexError Traceback (most recent call last) <ipython-input-12-50863379cefe> in <module>() 8 print("======") 9 n_dataset = n rename("number") to_dataset() --> 10 n_dataset["mm"] = mm 11 print(n_dataset) /Library/Frameworks/Python framework/Versions/3 5/lib/python3 5/site-packages/xarray/core/dataset py in __setitem__(self key value) 536 raise NotImplementedError('cannot yet use a dictionary as a key ' 537 'to set Dataset values') -> 538 self update({key: value}) 539 540 def __delitem__(self key): /Library/Frameworks/Python framework/Versions/3 5/lib/python3 5/site-packages/xarray/core/dataset py in update(self other inplace) 1434 dataset 1435 """ > 1436 variables coord_names dims = dataset_update_method(self other) 1437 1438 return self _replace_vars_and_dims(variables coord_names dims /Library/Frameworks/Python framework/Versions/3 5/lib/python3 5/site-packages/xarray/core/merge py in dataset_update_method(dataset other) 492 priority_arg = 1 493 indexes = dataset indexes -> 494 return merge_core(objs priority_arg=priority_arg indexes=indexes) /Library/Frameworks/Python framework/Versions/3 5/lib/python3 5/site-packages/xarray/core/merge py in merge_core(objs compat join priority_arg explicit_coords indexes) 373 coerced = coerce_pandas_values(objs) 374 aligned = deep_align(coerced join=join copy=False indexes=indexes -> 375 skip_single_target=True) 376 expanded = expand_variable_dicts(aligned) 377 /Library/Frameworks/Python framework/Versions/3 5/lib/python3 5/site-packages/xarray/core/alignment py in deep_align(list_of_variable_maps join copy indexes skip_single_target) 162 163 aligned = partial_align(*targets join=join copy=copy indexes=indexes -> 164 skip_single_target=skip_single_target) 165 166 for key aligned_obj in zip(keys aligned): /Library/Frameworks/Python framework/Versions/3 5/lib/python3 5/site-packages/xarray/core/alignment py in partial_align(*objects **kwargs) 122 valid_indexers = dict((k v) for k v in joined_indexes items() 123 if k in obj dims) -> 124 result append(obj reindex(copy=copy **valid_indexers)) 125 126 return tuple(result) /Library/Frameworks/Python framework/Versions/3 5/lib/python3 5/site-packages/xarray/core/dataset py in reindex(self indexers method tolerance copy **kw_indexers) 1216 1217 variables = alignment reindex_variables( > 1218 self variables self indexes indexers method tolerance copy=copy) 1219 return self _replace_vars_and_dims(variables) 1220 /Library/Frameworks/Python framework/Versions/3 5/lib/python3 5/site-packages/xarray/core/alignment py in reindex_variables(variables indexes indexers method tolerance copy) 234 target = utils safe_cast_to_index(indexers[name]) 235 indexer = index get_indexer(target method=method -> 236 **get_indexer_kwargs) 237 238 to_shape[name] = len(target) /Library/Frameworks/Python framework/Versions/3 5/lib/python3 5/site-packages/pandas/indexes/base py in get_indexer(self target method limit tolerance) 2080 2081 if not self is_unique: > 2082 raise InvalidIndexError('Reindexing only valid with uniquely' 2083 ' valued Index objects') 2084 InvalidIndexError: Reindexing only valid with uniquely valued Index objects ```` So it is not a bug in Xarray as such Nevertheless I wasted many hours trying to find this bug and I wish the error message was more informative I hope the Xarray collaborators will fix this soon (Put in a uniqueness check on the coordinates before attempting to merge ) In any case the method provided by my answer below still works | OK I found one way to do it but I do not know if this is the canonical way or the best way so please criticise and advise It does not feel like a good way of doing it ````dataset = xarray merge([dataset new_data_array rename("new_array")]) ```` |
socket error: [Errno 10054] ````import socket sys if len(sys argv) !=3 : print "Usage: /supabot py <host> <port>" sys exit(1) irc = sys argv[1] port = int(sys argv[2]) sck = socket socket(socket AF_INET socket SOCK_STREAM) sck connect((irc port)) sck send('NICK supaBOT\r\n') sck send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n') sck send('JOIN #darkunderground' '\r\n') data = '' while True: data = sck recv(1024) if data find('PING') != -1: sck send('PONG ' data split() [1] '\r\n') print data elif data find('!info') != -1: sck send('PRIVMSG #darkunderground supaBOT v1 0 by sourD' '\r\n') print sck recv(1024) ```` when I run this code I get this error <blockquote> socket error: [Errno 10054] An existing connection was forcibly closed by the remote host </blockquote> it says that the error is in line 16 in data = sck recv(1024) | That probably means that you are not supplying the expected handshake or protocol exchange for the server and it is closing the connection What happens if you telnet to the same machine and port and type in the same text? |
outputting characters to a spot in the terminal in python I am using python and I was wondering how do I output characters to specific positions in the terminal (i am using windows for this) | The <a href="http://effbot org/zone/console-handbook htm" rel="nofollow">Console</a> module has support for this (Windows only) |
Add new lines to CSV file at each iteration in Python I have the following code in Python I need to execute the function `dd save()` `N` times each time adding some new lines to the file `test csv` My current code just overrides the content of the file `N` times How can I fix this issue? ````def save(self): f = csv writer(open("test csv" "w")) with open("test csv" "w") as f: f write("name\n") for k v in tripo items(): if v: f write("{}\n" format(k split(" ")[0])) f write("\n" join([s split(" ")[0] for s in v])+"\n") if __name__ == "__main__": path="data/allData" entries=os listdir(path) for i in entries: dd=check(dataPath=path entry=i) dd save() print(i) ```` | Open the file in append mode: ````with open("test csv" "a") as f: f write("name\n") ```` Check docs <a href="https://docs python org/2/library/functions html#open" rel="nofollow">here</a> |
Identifying the Data transferred from XBee when using Python and python-xbee A Xbee Series 2 in Router AT configuration with a potentiometer wiper output connected to XBee's pin 20 `AD0` is supposed to send the analog data every 100 ms It was set with `ATD02` and `ATIR64` A Xbee Series 2 in Coordinator API config is connected to the computer Using XCTU terminal we can see that the Coordinator is constantly receiving `Explicit RX Indicator` frames from the Router However there are no frames containing the analog data read by `AD0` on the Router XBee <img src="http://i stack imgur com/MMhpr png" alt="enter image description here"> <img src="http://i stack imgur com/eSXI8 png" alt="enter image description here"> Using Python with the `XBee` module we also notice the same thing just `rx_explicit` frames being received and nothing containing the analog data samples! ````{'profile': '\xc1\x05' 'source_addr': '6T' 'dest_endpoint': '\xe8' 'rf_data': '\x01\x00\x00\x01\x02(' 'source_endpoint': '\xe8' 'options': '\x01' 'source_addr_long': '\x00\x13\xa2\x00@\xb1\x92\x13' 'cluster': '\x00\x92' 'id': 'rx_explicit'} {'profile': '\xc1\x05' 'source_addr': '6T' 'dest_endpoint': '\xe8' 'rf_data': '\x01\x00\x00\x01\x02I' 'source_endpoint': '\xe8' 'options': '\x01' 'source_addr_long': '\x00\x13\xa2\x00@\xb1\x92\x13' 'cluster': '\x00\x92' 'id': 'rx_explicit'} {'profile': '\xc1\x05' 'source_addr': '6T' 'dest_endpoint': '\xe8' 'rf_data': '\x01\x00\x00\x01\x01\xeb' 'source_endpoint': '\xe8' 'options': '\x01' 'source_addr_long': '\x00\x13\xa2\x00@\xb1\x92\x13' 'cluster': '\x00\x92' 'id': 'rx_explicit'} {'profile': '\xc1\x05' 'source_addr': '6T' 'dest_endpoint': '\xe8' 'rf_data': '\x01\x00\x00\x01\x01\xce' 'source_endpoint': '\xe8' 'options': '\x01' 'source_addr_long': '\x00\x13\xa2\x00@\xb1\x92\x13' 'cluster': '\x00\x92' 'id': 'rx_explicit'} ```` What do you think may have happened? I checked the value at `AD0` by reading it with an Arduino and indeed there is a value to be read | What frame type were you expecting? The `rx_explicit` frames will have your I/O data You might need to change the `ATAO` (API Options) setting to control whether frames come in as RX Explicit or some other frame type Provide a hex dump of the payload on the frames you are receiving and we can probably figure out the format of the data I imagine it will look like the format of an `ATIS` response |
MinGW or Cygwin for Python development on Windows? I am using vanilla Python 3 x on Windows using Pycharm as IDE Although this is working; I need to install different packages and modules; and I did notice that windows has no pip from what I can tell I am familiar with Python on Linux and most of the time it is a matter of use pip to install new packages and modules for Python; but on windows it seems more daunting and complex I was told to use either MinGW or Cygwin so I can be in a full unix environment using terminal commands that I am used to and the unix console; althought I do not get the difference related to python The code that I write will be eventually deployed on Linux OSX and Windows; would matter if I use CygWin or MinGW? If this is too much of a trouble it is probably easier to just install Ubuntu as VM and work there; but I am hoping that I can do the same on a standard W10 machine | In Pycharms you also have access to a terminal in which you can run `pip install` on <a href="https://www jetbrains com/help/pycharm/2016 1/working-with-embedded-local-terminal html" rel="nofollow">Check this link out</a> |
Who worked adapting the score for performance by an orchestra? | Michiru Ōshima |
What was Hugo Loudon's brother? | null |
When did interest in studying ancient texts start to weaken? | null |
Searching a python list quickly? I have a dictionary and a list The list is made up of values The dictionary has all of the values plus some more values I am trying to count the number of times the values in the list show up in the dictionary per key/values pair It looks something like this: ````for k in dict: count = 0 for value in dict[k]: if value in list: count = 1 list remove(value) dict[k] append(count) ```` I have something like ~1 million entries in the list so searching through each time is ultra slow Is there some faster way to do what I am trying to do? Thanks Rohan | ````for val in my_list: if val in my_dict: my_dict[val] = my_dict[val] 1 else: my_dict[val] = 0 ```` What you still need - Handle case when val is not in dict |
How to get XML tag value in Python I have some XML in a unicode-string variable in Python as follows: ````<?xml version='1 0' encoding='UTF-8'?> <results preview='0'> <meta> <fieldOrder> <field>count</field> </fieldOrder> </meta> <result offset='0'> <field k='count'> <value><text>6</text></value> </field> </result> </results> ```` How do I extract the `6` in `<value><text>6</text></value>` using Python? | With lxml: ````import lxml # xmlstr is your xml in a string root = lxml fromstring(xmlstr) textelem = root find('result/field/value/text') print textelem text ```` Edit: But I imagine there could be more than one result ````import lxml # xmlstr is your xml in a string root = lxml fromstring(xmlstr) results = root findall('result') textnumbers = [r find('field/value/text') text for r in results] ```` |
How to get Flask/Gunicorn to handle concurrent requests for the same Route? <strong>tl;dr</strong> A method decorated with `route` cannot handle concurrent requests while Flask is served behind a gunicorn started with multiple workers and threads while two different methods handle concurrent requests fine Why is this the case and how can the same route be served concurrently? <hr> I have this simple flask app: ````from flask import Flask jsonify import time app = Flask(__name__) @app route('/foo') def foo(): time sleep(5) return jsonify({'success': True}) 200 @app route('/bar') def bar(): time sleep(5) return jsonify({'success': False}) 200 ```` If I run this via: ````gunicorn test:app -w 1 --threads 1 ```` If I quickly open up `/bar` and `/foo` in two different tabs in a browser whichever tab I hit enter on first will load in 5 seconds and the second tab will load in 10 seconds This makes sense because gunicorn is running one worker with one thread If I run this via either: ````gunicorn test:app -w 1 --threads 2 gunicorn test:app -w 2 --threads 1 ```` In this case opening up `/foo` and `/bar` in two different tabs both take 5 seconds This makes sense because gunicorn is running either 1 worker with two threads or two workers with one thread each and can serve up the two routes at the same time <strong>However If I open up two `/foo` at the same time regardless of the gunicorn configuration the second tab will always take 10 seconds </strong> How can I get the same method decorated by `route` to serve concurrent requests? | This problem is probably not caused by Gunicorn or Flask but by the browser I just tried to reproduce it With two Firefox tabs it works; but if I run two `curl` processes in different consoles then they get served as expected (in parallel) and their requests are handled by different workers - this can be checked by enabling `--log-level DEBUG` while starting gunicorn I think this is because Firefox (and maybe other browsers) open a single connection to the server for each URL; and when you open one page on two tabs their requests are sent through the same (kept-alive) connection and as a result come to the same worker As a result even using async worker like `eventlet` will not help: async worker may handle multiple <them>connections</them> at a time but when two requests land on the same connection then they will necessarily be handled one-by-one |
How can I run site js function with custom arguments? I need to scrape google suggestions from search input Now I use selenium+phantomjs webdriver ````search_input = selenium find_element_by_xpath(" //input[@id='lst-ib']") search_input send_keys('phantomjs har python') time sleep(1 5) from lxml html import fromstring etree = fromstring(selenium page_source) output = [] for suggestion in etree xpath(" //ul[@role='listbox']/li//div[@class='sbqs_c']"): output append(" " join([s strip() for s in suggestion xpath(" //text()") if s strip()])) ```` but I see in firebug XHR request like <a href="https://www google com/complete/search?client=serp&hl=en-UA&gs_rn=64&gs_ri=serp&tok=1yZuCM_-3JaE4SLqJRPUjQ&pq=phantomjs%20har%20python&cp=9&gs_id=6mr&q=phantomjs&xhr=t" rel="nofollow">this</a> And response - simple text file with data that I need Then I look at log: ````selenium get_log("har") ```` I cannot see this request How can I catch it? I need this url for using as template for requests lib to use it with other search words Or may be possible run js that initiate this request with other(not from input field) arguments is it possible? | You can solve it with Python+Selenium+PhantomJS only Here is the list of things I have done to make it work: - pretend to be a browser with a head by changing the PhantomJS's User-Agent through <them>Desired Capabilities</them> - use <a href="https://selenium-python readthedocs org/waits html#explicit-waits" rel="nofollow">Explicit Waits</a> - ask for the direct <a href="https://www google com/?gws_rd=ssl#q=phantomjs+har+python" rel="nofollow">https://www google com/?gws_rd=ssl#q=phantomjs+har+python</a> url <strong>Working solution:</strong> ````from selenium webdriver common by import By from selenium webdriver common keys import Keys from selenium webdriver support ui import WebDriverWait from selenium webdriver support import expected_conditions as EC from selenium import webdriver desired_capabilities = webdriver DesiredCapabilities PHANTOMJS desired_capabilities["phantomjs page customHeaders User-Agent"] = "Mozilla/5 0 (Linux; YOU; Android 2 3 3; en-us; LG-LU3000 Build/GRI40) AppleWebKit/533 1 (KHTML like Gecko) Version/4 0 Mobile Safari/533 1" driver = webdriver PhantomJS(desired_capabilities=desired_capabilities) driver get("https://www google com/?gws_rd=ssl#q=phantomjs+har+python") wait = WebDriverWait(driver 10) # focus the input and trigger the suggestion list to be shown search_input = wait until(EC visibility_of_element_located((By NAME "q"))) search_input send_keys(Keys ARROW_DOWN) search_input click() # wait for the suggestion box to appear wait until(EC presence_of_element_located((By CSS_SELECTOR "ul[role=listbox]"))) # parse suggestions print "List of suggestions: " for suggestion in driver find_elements_by_css_selector("ul[role=listbox] li[dir]"): print suggestion text ```` Prints: ````List of suggestions: python phantomjs screenshot python phantomjs ghostdriver python phantomjs proxy unable to start phantomjs with ghostdriver ```` |
Python - querying tables from database and having conditions in data frame I have made the connection to Teradata Database using : ````import pyodbc conn = pyodbc connect('DRIVER={Teradata};DBCNAME="";UID="";PWD="";QUIETMODE=YES;') ```` Teradata has a customer table : ````Customer ID CreateDate ```` I need to run a query for a list of customers (stored in python list) ````Select * from customer where Customer in (Python List) ```` Is it possible to do this ? Thanks | This should work I have converted the list to a `tuple` so that it has round brackets to match the SQL syntax for an array instead of square brackets of a Python list: ````import pandas as pd query = "Select * from customer where Customer in {}" format(tuple(customerlist)) df = pd read_sql(query conn) ```` |
django filtering on a field in a foreign key object Given the following models from the django polls tutorial: ````class Question(models Model): question_text = models CharField(max_length=200) pub_date = models DateTimeField('date published') def __str__(self): return self question_text def was_published_recently(self): now = timezone now() return now - datetime timedelta(days=1) <= self pub_date <= now was_published_recently admin_order_field = 'pub_date' was_published_recently boolean = True was_published_recently short_description = 'Published recently' class Choice(models Model): question = models ForeignKey(Question) choice_text = models CharField(max_length=200) votes = models IntegerField(default=0) def __str__(self): return self choice_text ```` I want to be able exclude questions without and choices like suggested in the tutorial I have been playing around with Filter but I cannot figure it out I tried: ````def get_queryset(self): return Question objects filter(pub_date__lte=timezone now() choice__count__gt=0) ```` but I am getting ````Relation fields do not support nested lookups ```` How can I filter by Questions that do not have any Choices? | Use choice__isnull=True where choice is the related_name ````def get_queryset(self): return Question objects filter(pub_date__lte=timezone now() choice__isnull=False) ```` |
How to understand numpy's combined slicing and indexing example I am trying to understand numpy's combined slicing and indexing concept however I am not sure how to correctly get the below results from numpy's output (by hand so that we can understand how numpy process combined slicing and indexing which one will be process first?): ````>>> import numpy as np >>> a=np arange(12) reshape(3 4) >>> a array([[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]]) >>> i=np array([[0 1] [2 2]]) >>> a[i :] array([[[ 0 1 2 3] [ 4 5 6 7]] [[ 8 9 10 11] [ 8 9 10 11]]]) >>> j=np array([[2 1] [3 3]]) >>> a[: j] array([[[ 2 1] [ 3 3]] [[ 6 5] [ 7 7]] [[10 9] [11 11]]]) >>> aj=a[: j] >>> aj shape (3L 2L 2L) ```` I am bit confused about how aj's shape becomes (3 2 2) with the above output any detailed explanations are very appreciated thanks! | `a[: j][0]` is equivalent to `a[0 j]` or `[0 1 2 3][j]` which gives you `[[2 1] [3 3]])` `a[: j][1]` is equivalent to `a[1 j]` or `[4 5 6 7][j]` which gives you `[[6 5] [7 7]])` `a[: j][2]` is equivalent to `a[2 j]` or `[8 9 10 11][j]` which gives you `[[10 9] [11 11]])` |
How to directly access class instances through class dictionary in Python I need a way of accessing directly an instance of a class through an ID number As I tried to explain <a href="http://stackoverflow com/questions/10583195/how-can-i-dynamically-generate-class-instances-with-single-attributes-read-from/10583317#comment13785524_10583317">here</a> I am importing a csv file and I want to create an instance of my class Person() for every line in the csv file plus I want to be able to directly access these instances using as a key a unique identifier already present in the csv file What I have done so far thanks to the help of user433831 is this: ````from sys import argv from csv import DictReader from person import Person def generateAgents(filename): reader = DictReader(open(filename 'rU')) persons = [Person(**entry) for entry in reader] return persons ```` where person is just the module where I define the class Person() as: ````class Person: def __init__(self **kwds): self __dict__ update(kwds) ```` Now I have a list of my person instances namely `persons` which is already something neat But now I need to create a network among these persons using the `networkx` module and I definitely need a way to access directly every person (at present my instances do not have any name) For example every person has an attribute called "father_id" which is the unique ID of the father Persons not having a father alive in the current population has a "father_id" equal to "-1" Now to link every person to his/her father I would do something like: ````import networkx as nx G=nx Graph() for person in persons: G add_edge(person person_with_id_equal_to_father_id) ```` My problem is that I am unable to access directly this "person_with_id_equal_to_father_id" Keep in mind that I will need to do this direct access many many times so I would need a pretty efficient way of doing it and not some form of searching in the list (also considering that I have around 150000 persons in my population) It would be great to implement something like a dictionary feature in my class Person() with the key of every instance being a unique identifier This unique identifier is already present in my csv file and therefore I already have it as an attribute of every person Thank you for any help as always greatly appreciated Also please keep in mind I am a total python newbie (as you can probably tell ;) ) | Simply use a dictionary: ````persons_by_id = {p id: p for p in persons} ```` This requires a recent version of Python If yours does not support this syntax use the following: ````persons_by_id = dict((p id p) for p in persons) ```` Having done either of the above you can locate the person by their id like so: ````persons_by_id[id] ```` The `networkx` example becomes: ````import networkx as nx G=nx Graph() for person in persons: if person father_id != -1: G add_edge(person persons_by_id[person father_id]) ```` |
What was Gerald Ford most interested in talking about when campaigning? | null |
Extracting Description Of A Debian Package I am trying to extract the description of debian packages from the Packages gz file using Python Is there any way to get only the description of the package i e the content after the Description: field The source file is : ````Package: 2vcard Priority: optional Section: utils Installed-Size: 108 Maintainer: Martin Albisetti <argentina@gmail com> Architecture: all Version: 0 5-3 Filename: pool/main/2/2vcard/2vcard_0 5-3_all deb Size: 14300 MD5sum: d831fd82a8605e9258b2314a7d703abe SHA1: e903a05f168a825ff84c87326898a182635f8175 SHA256: 2be9a86f0ec99b1299880c6bf0f4da8257c74a61341c14c103b70c9ec04b10ec Description: perl script to convert an addressbook to VCARD file format 2vcard is a little perl script that you can use to convert the popular vcard file format Currently 2vcard can only convert addressbooks and alias files from the following formats: abook eudora juno ldif mutt mh and pine The VCARD format is used by gnomecard for example which is used by the balsa email client Tag: implemented-in::perl role::program use::converting ```` | Maybe <a href="http://pypi python org/pypi/python-debian" rel="nofollow">http://pypi python org/pypi/python-debian</a> would be helpful? In detail assume that `data` is a string containing the source file contents then: ````from debian import deb822 print deb822 Deb822(data split("\n"))['Description'] ```` would output the description |
IndexError using python-ntlm I am trying to use `urllib2` and `python-ntlm` to connect to an NT authenticated server but I am getting an error Here is the code I am using from <a href="http://code google com/p/python-ntlm/" rel="nofollow">the python-ntlm site</a>: ````user = 'DOMAIN\user name' password = 'Password123' url = 'http://corporate domain com/page aspx?id=foobar' passman = urllib2 HTTPPasswordMgrWithDefaultRealm() passman add_password(None url user password) # create the NTLM authentication handler auth_NTLM = HTTPNtlmAuthHandler HTTPNtlmAuthHandler(passman) # create and install the opener opener = urllib2 build_opener(auth_NTLM) urllib2 install_opener(opener) # retrieve the result response = urllib2 urlopen(url) return response read() ```` And here is the error I get: ````Traceback (most recent call last): File "C:\Python27\test py" line 112 in get_ntlm_data response = urllib2 urlopen(url) File "C:\Python27\lib\urllib2 py" line 126 in urlopen return _opener open(url data timeout) File "C:\Python27\lib\urllib2 py" line 398 in open response = meth(req response) File "C:\Python27\lib\urllib2 py" line 511 in http_response 'http' request response code message hdrs) File "C:\Python27\lib\urllib2 py" line 430 in error result = self _call_chain(*args) File "C:\Python27\lib\urllib2 py" line 370 in _call_chain result = func(*args) File "C:\Python27\lib\site-packages\python_ntlm-1 0 1-py2 7 egg\ntlm\HTTPNtlmAuthHandler py" line 99 in http_error_401 return self http_error_authentication_required('www-authenticate' req fp headers) File "C:\Python27\lib\site-packages\python_ntlm-1 0 1-py2 7 egg\ntlm\HTTPNtlmAuthHandler py" line 35 in http_error_authentication_required return self retry_using_http_NTLM_auth(req auth_header_field None headers) File "C:\Python27\lib\site-packages\python_ntlm-1 0 1-py2 7 egg\ntlm\HTTPNtlmAuthHandler py" line 72 in retry_using_http_NTLM_auth UserName = user_parts[1] IndexError: list index out of range ```` Any idea what I am doing wrong? | Try: ````user = r'DOMAIN\user name' ```` |
What broke away from the Armenian Apostolic Church? | Armenian Evangelical Church |
Python: write coordinates numpy shape In my python script I want to write coordinates of a numpy shape to a text file I import coordinates and element definitions and then use the numpy shapes to adjust the coordinates Then I want to write an text file where I write the adjusted coordinates With my current script however it only generates 6 coordinates I think this is due to my defninition of `s = new_triangle shape` (see the script below) How should this be defined so that all new coordinates are written into the output file? ````newcoords = [[0 0 0 0] [1 0 0 0] [0 0 1 0] [0 0 0 0] [1 0 1 0] [0 0 1 0] [0 0 1 0] [1 0 1 0] [0 0 2 0] [0 0 2 0] [1 0 1 0] [1 0 2 0] [1 0 1 0] [2 0 1 0] [1 0 2 0] [1 0 2 0] [2 0 1 0] [2 0 2 0] [1 0 1 0] [2 0 0 0] [2 0 1 0] [1 0 0 0] [2 0 0 0] [1 0 1 0]] newelems = [[0 1 2] [3 4 5] [6 7 8] [9 10 11] [12 13 14] [15 16 17] [18 19 20] [21 22 23]] import numpy as np #define triangles triangles = np array([[newcoords[e] for e in newelem] for newelem in newelems]) #find centroid of each triangle CM = np mean(triangles axis=1) #find vector from each point in triangle pointing towards centroid point_to_CM_vectors = CM[: np newaxis] - triangles #calculate similar triangles 1% smaller new_triangle = triangles 0 01*point_to_CM_vectors #Define new coordinates newcoord = [] newcoord append(list(zip(*new_triangle))) s = new_triangle shape print 'newcoords =' newcoords print 'newcoord =' newcoord print s #generate output fout = open('_PartInput4 inp' 'w') fout write('*Node-new_triangle\n') for i x in enumerate(new_triangle reshape(s[1]*s[2] len(newelems))): fout write("{} {} {}\n" format(i+1 x[0] x[1])) fout close() ```` Thanks in advance for any help! | <a href="http://stackoverflow com/users/553404/mr-e">Mr E</a> gave the answer previously: ````#generate output with open('_PartInput3 inp' 'w') as fout: fout write('*Node-new_triangle\n') s = new_triangle shape for i x in enumerate(new_triangle reshape(s[0]*s[1] 2)): fout write("{} {} {}\n" format(i+1 x[0] x[1])) ```` |
How to add characters to filename using glob in Python? The following is a snippet of code The script takes the input files from a "Test" folder runs a function and then outputs the files with the same name in the "Results" folder (i e `"Example_Layer shp")` How could I set it so that the output file would instead read `"Example_Layer(A) shp"`? ````#Set paths path_dir = home "\Desktop\Test\\" path_res = path_dir "Results\\" def run(): #Set definitions input = path_res "/" "input shp" output = path_res "/" fname #Set current path to path_dir and search for only shp files then run function os chdir(path_dir) for fname in glob glob("* shp"): run_function input output run() ```` | You currently calculate the `output` variable once (which I AM GOING TO would not work since you do not have any `fname` defined yet) Move the statement where you compute the output variable within the for loop like below: ````#Set paths path_dir = home "\Desktop\Test\\" path_res = path_dir "Results\\" def run(): #Set definitions input = path_res "/" "input shp" #Set current path to path_dir and search for only shp files then run function os chdir(path_dir) for fname in glob glob("* shp"): output = path_res "/" fname run_function input output run() ```` |
Who attacked Armenia when they became too distant from Seleucid rule? | Antiochus III the Great |
Tkinter Toplevel TypeError I am trying to create a new TopLevel through a button command however I am having some difficulty With the following code: ```` initial_state_button = Button(current_state text=current_state_text command = partial(initial_state_display aatsplusv)) initial_state_button pack(side = TOP) def initial_state_display(dictionary): top = Toplevel() top title = "About this State:" count = 0 for key value in dictionary["initial states"] iteritems(): proposition = Message(top text = key) proposition grid(row=count column=0 padx=5 pady=5) colon = Message(top text = " : ") colon grid(row=count column=1 padx=5 pady=5) boolean = Message(top text = str(value)) colon grid(row=count column=2 padx=5 pady=5) count = 1 ```` I receive the following error: ````Exception in Tkinter callback Traceback (most recent call last): File "C:\Python27\lib\lib-tk\Tkinter py" line 1536 in __call__ return self func(*args) File "Assignmentest py" line 400 in initial_state_display top = Toplevel() File "C:\Python27\lib\lib-tk\Tkinter py" line 2136 in __init__ self title(root title()) TypeError: 'str' object is not callable ```` I have no clue what is wrong top = Toplevel is written exactly how the effbot example shows Is toplevel not available in Python 2 7? If so is there an 2 7 equivalent? | The line you are declaring `top`'s title is wrong Your line ````top title = "About this State:" ```` should be something like this: ````top title("About this State:") ```` See <a href="http://effbot org/tkinterbook/toplevel htm" rel="nofollow">effbot docs</a> for further information <hr> Edit due to comment: I just have a Python3 installation on my system but something like this blueprint should work The code is not that nice but shows how to deal with toplevel windows: ````#!/usr/bin/env python3 # coding: utf-8 from tkinter import * def btn_callback(): top = Toplevel() top title("Toplevel window") root = Tk() root title('Main window') b = Button(root text="Open Toplevel" command=btn_callback) b pack() root mainloop() ```` If you are using Python2 you should change `tkinter` into `Tkinter` and the code should work as desired |
How to use startproject (django-admin py) if there is already a django project? I am trying to start a new django project (using `django-admin py`) but unfortunately I am always getting the following error: ````C:\Users\NAME\dev\django>django-admin py startproject foo Usage: django-admin py subcommand [options] [args] [ ] ```` The same applies to any other command of `django-admin py` - every command does not exist I already have a django projects (in `C:\Users\NAME\dev\django\blog`) and I know that the startproject command is disabled if `DJANGO_SETTINGS_MODULE` is set but when I try this: ````>>> import os >>> os environ['DJANGO_SETTINGS_MODULE'] Traceback (most recent call last): File "<stdin>" line 1 in <module> File "C:\Python26\lib\os py" line 423 in __getitem__ return self data[key upper()] KeyError: 'DJANGO_SETTINGS_MODULE' ```` Or even better this: ````>>> from django conf import settings >>> dir(settings) Traceback (most recent call last): File "<stdin>" line 1 in <module> File "C:\Python26\lib\site-packages\django\utils\functional py" line 306 in __dir__ self _setup() File "C:\Python26\lib\site-packages\django\conf\__init__ py" line 38 in _set up raise ImportError("Settings cannot be imported because environment variable %s is undefined " % ENVIRONMENT_VARIABLE) ImportError: Settings cannot be imported because environment variable DJANGO_SE TTINGS_MODULE is undefined ```` It seems that `DJANGO_SETTINGS_MODULE` is undefined Does anyone have an idea why I cannot use `django-admin py`? <them>Django 1 2 3 Windows 7 (64bit)</them> | DJANGO_SETTINGS_MODULE is only needed when you want to use django-admin py with an existing Django project Your issue seems to be different it seems like django-admin py does not honor the command line parameters for some reason Never tried it on Windows but have you tried doing something like: ````python django-admin py startproject blog ```` Now I also see you saying you already have blog project in that folder Why do you need to start project with the same name in the same folder then? Please clarify what you are trying to achieve |
How can I save the array to a text file and import it back? Basically I want to know how to get my array that gets data from peoples input saved to a text file and automatically imported back into the array when the program starts again Edit: Now after this it seems saving and reopening adds data to the same subarrays My code: ````import json import time datastore=[] datastore = json load(open("file json")) menuon = 1 def add_user(): userdata = input("How many users do you wish to input?") print("\n") if (userdata == 0): print("Thank you have a nice day!") else: def add_data(users): for i in range(users): datastore append([]) datastore[i] append(input("Enter Name: ")) datastore[i] append(input("Enter Email: ")) datastore[i] append(input("Enter DOB: ")) add_data(int(userdata)) def print_resource(array): for entry in datastore: print("Name: "+entry[0]) print("Email: "+entry[1]) print("DOB: "+entry[2]) print("\n") def search_function(value): for eachperson in datastore: if value in eachperson: print_resource(eachperson) while menuon == 1: print("Hello There What would you like to do?") print("") print("Option 1: Add Users") print("Option 2: Search Users") print("Option 3: Replace Users") print("Option 4: End the program") menuChoice = input() if menuChoice == '1': add_user() if menuChoice == '2': searchflag = input("Do you wish to search the user data? y/n") if(searchflag == 'y'): criteria = input("Enter Search Term: ") search_function(criteria) if menuChoice == '3': break if menuChoice == '4': print("Ending in 3 ") time sleep(1) print("2") time sleep(1) print("1") json dump(datastore open("file json" "w")) menuon=0 ```` | Python docs have a beautiful explanation on how to handle text files among other files to read/write Here is the link: <a href="http://docs python org/2/tutorial/inputoutput html" rel="nofollow">http://docs python org/2/tutorial/inputoutput html</a> Hope it helps! |
removing "none" result from the function which prints the prime number i want to write a function that if the number is prime the function gives it as a result but for non prime numbers i get a None here is my code: ````def isprime(n): a=0 if n==1: a=1 if n==2: a=1 for i in range(2 n): if n%i==0: a=0 break else: a=1 break if a==1: return n if a==0: return print(isprime(68)) ```` the result for 68 is None | In the case of not a prime number (a=0) you return nothing: ````if a==0: return ```` and if you print the value of a function which returns nothing it prints `None` To solve this return a number or in this case a boolean would be more logical So instead of setting `a=0` or `a=1` you can use `a=False` and `a=True` Then you can do `return a` |
Python: Calculating difference of values in a nested list by using a While Loop I have a list that is composed of nested lists each nested list contains two values - a float value (file creation date) and a string (a name of the file) For example: ````n_List = [[201609070736L 'GOPR5478 MP4'] [201609070753L 'GP015478 MP4'] [201609070811L 'GP025478 MP4']] ```` The nested list is already sorted in order of ascending values (creation dates) I am trying to use a While loop to calculate the difference between each sequential float value For Example: 201609070753 - 201609070736 = 17 The goal is to use the time difference values as the basis for grouping the files The problem I am having is that when the count reaches the last value for `len(n_List)` it throws an `IndexError` because `count+1` is out of range ````IndexError: list index out of range ```` I cannot figure out how to work around this error no matter what i try the count is always of range when it reaches the last value in the list Here is the While loop I have been using ````count = 0 while count <= len(n_List): full_path = source_folder "/" n_List[count][1] time_dif = n_List[count+1][0] - n_List[count][0] if time_dif < 100: f_List write(full_path "\n") count = count 1 else: f_List write(full_path "\n") f_List close() f_List = open(source_folder 'GoPro' '_' str(count) ' txt' 'w') f_List write(full_path "\n") count = count 1 ```` PS The only work around I can think of is to assume that the last value will always be appended to the final group of files so when the count reaches `len(n_List - 1)` I skip the time dif calculation and just automatically add that final value to the last group While this will probably work most of the time I can see edge cases where the final value in the list may need to go in a separate group | n_list(len(n_list)) will always return an index out of range error ````while count < len(n_List): ```` should be enough because you are starting count at 0 not 1 |
python forked processes not executing with os execlp I have got this simple python script that ought to fork new processes and then have each execute a command using os execlp but the execution only occurs once I am curious if there is a timing issue going on that is preventing the additional forks from executing: ````import os for n in range(5): PID = os fork() if PID == 0: #the child print("This child's PID is: %s" % os getpid()) os execlp('open' '-n' '-a' 'Calculator') # os popen('open -n -a Calculator') # os _exit(0) else: print("new child forked: %d" % PID) ```` For this the "open -n -a Appname" command in OS X launches a new instance of the specified application so the above code should replace the forked process with the "open" command and this should run 5 times However it only runs once so only one instance of Calculator is opened Despite this the parent lists 5 child PIDs forked If I comment out the os execlp line and uncomment the os popen and os _exit lines following it then this works properly and the child processes all run the "open" command; however I am wondering why the approach of replacing the forked process using execlp (or execvp and other similar variants) is not working? Clearly the child process is running as I can use piping to run the "open" command just fine This is with python 3 4 3 | The first argument after the executable is arg[0] which is by convention the name of the executable This is useful if you have symbolic links which determine the behavior of the programm In your case you name the programm `'-n'` and the real arguments are only `-a` and `Calculator` So you have to repeat `'open'`: ````os execlp('open' 'open' '-n' '-a' 'Calculator') ```` |
Batching threads in python I am updating some existing code that looks like this: ````for i in list thread start_new_thread(main (i[0] i[1] i[2] 2)) ```` This causes threads to be created for every item in the list but not executed until all the threads are created I would like to either execute the threads in small groups or just have them execute directly after they are created (There are a lot of python threads discussion on here so sorry if I missed this type of question already being asked ) | You may find the <a href="http://docs python org/dev/library/concurrent futures html#threadpoolexecutor" rel="nofollow">`concurrent futures`</a> module useful It is available also for Python 2 under the name <a href="http://pypi python org/pypi/futures/2 1 3" rel="nofollow">`futures`</a> For example to invoke a function `main` for every item on `MY_LIST` concurrently but with at most 5 threads you can write: ````from concurrent futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=5) as executor: for result in executor map(main MY_LIST): # Do something with result print(result) ```` |
What year did Dell launch its first products that weren't free of toxic chemicals? | null |
Shove giving KeyError when assigning value I am using shove to avoid loading a huge dictionary into memory ````from shove import Shove lemmaDict = Shove('file://storage') with open(str(sys argv[1])) as lemmaCPT:\ for line in lemmaCPT: line = line rstrip('\n') lineAr = string split(line ' ||| ') lineKey = lineAr[0] ' ||| ' lineAr[1] lineValue = lineAr[2] print lineValue lemmaDict[lineKey] = lineValue ```` However I am getting the following KeyError and Traceback partway through reading `lemmaCPT` What is going on? ````Traceback (most recent call last): File " /stemmer py" line 19 in <module> lemmaDict[lineKey] = lineValue File "/opt/Python-2 7 6/lib/python2 7/site-packages/shove/core py" line 44 in __setitem__ self sync() File "/opt/Python-2 7 6/lib/python2 7/site-packages/shove/core py" line 74 in sync self _store update(self _buffer) File "/opt/Python-2 7 6/lib/python2 7/_abcoll py" line 542 in update self[key] = other[key] File "/opt/Python-2 7 6/lib/python2 7/site-packages/shove/base py" line 123 in __setitem__ raise KeyError(key) KeyError: '! ! ! \xd1\x87\xd0\xb8\xd1\x82\xd0\xb0\xd0\xb5\xd1\x82\xd1\x81\xd1\x8f \xd1\x82\xd1\x80\xd0\xbe\xd0\xb5\xd0\xba\xd1\x80\xd0\xb0\xd1\x82\xd0\xbd\xd1\x8b\xd0\xbc \xd0\xbf\xd0\xbe\xd0\xb2\xd1\x82\xd0\xbe\xd1\x80\xd0\xb5\xd0\xbd\xd0\xb8\xd0\xb5\xd0\xbc \xd0\xbb\xd1\x8e\xd0\xb1\xd0\xbe\xd0\xb3\xd0\xbe ||| ! ! ! is pronounced by' ```` Sample input: ````! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением ||| ! ! ! is pronounced by repeating ||| 0 00744887 8 53148e-39 0 00989281 8 53148e-39 ! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением ||| ! ! ! is pronounced by ||| 0 00744887 8 53148e-39 0 00989281 8 53148e-39 ! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением ||| ! ! ! is pronounced ||| 0 00744887 8 53148e-39 0 00989281 8 53148e-39 ! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением ||| ! ! ! is ||| 0 00819374 8 53148e-39 0 00989281 0 0128612 ! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением ||| ! ! ! ||| 0 000119622 8 53148e-39 0 0098932 0 590703 ! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением ||| ! ! ! is pronounced by ||| 0 00819374 8 53148e-39 0 00989281 8 53148e-39 ! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением ||| ! ! ! is pronounced ||| 0 00819374 8 53148e-39 0 00989281 8 53148e-39 ! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением ||| ! ! ! is ||| 0 00819374 8 53148e-39 0 00989281 0 00154241 ! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением ||| ! ! ! ||| 0 0074488 8 53148e-39 0 00989281 0 070842 ! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением лÑбого ||| ! ! ! is pronounced by repeating ||| 0 00744887 8 53148e-39 0 00989281 8 53148e-39 ! ! ! ÑиÑаеÑÑÑ ÑÑоекÑаÑнÑм повÑоÑением лÑбого ||| ! ! ! is pronounced by ||| 0 00744887 8 53148e-39 0 00989281 8 53148e-39 ```` Running `code py sampleinput` will yield the aforementioned KeyError and Traceback | Well if this is the actual input then the problem is with length of `LemmaDict` and the `input` ````aftnix@dev:~â« cat input | wc -l 11 ```` My changed code ````from shove import Shove import sys import string lemmaDict = Shove('file://storage') i = 0 with open(str(sys argv[1])) as lemmaCPT: for line in lemmaCPT: line = line rstrip('\n') lineAr = string split(line ' ||| ') lineKey = lineAr[0] ' ||| ' lineAr[1] lineValue = lineAr[2] print lineValue print len(lemmaDict) #print len(lemmaCPT) i+=1 print i #lemmaDict[lineKey] = lineValue ```` Gives the following output ````0 00744887 8 53148e-39 0 00989281 8 53148e-39 9 1 0 00744887 8 53148e-39 0 00989281 8 53148e-39 9 2 0 00744887 8 53148e-39 0 00989281 8 53148e-39 9 3 0 00819374 8 53148e-39 0 00989281 0 0128612 9 4 0 000119622 8 53148e-39 0 0098932 0 590703 9 5 0 00819374 8 53148e-39 0 00989281 8 53148e-39 9 6 0 00819374 8 53148e-39 0 00989281 8 53148e-39 9 7 0 00819374 8 53148e-39 0 00989281 0 00154241 9 8 0 0074488 8 53148e-39 0 00989281 0 070842 9 9 0 00744887 8 53148e-39 0 00989281 8 53148e-39 9 10 0 00744887 8 53148e-39 0 00989281 8 53148e-39 9 ```` So you are simply overrunning the `Dict` If you delete two lines from the input it will stop throwing exception I do not know about shove but a quick check in she will tells me it always returns a line keyed dict There has to be a way to grow it maybe there is a method or something like it you should dig it is Doc more closely I just have a feeling you are using `Shove` in a wrong way EDIT: It is kind of bizarre after reviewing the `Shove` code it turns out it should have synced it is memory content when buffer limit is reached ````def __setitem__(self key value): self _cache[key] = self _buffer[key] = value # when buffer reaches self _limit write buffer to store if len(self _buffer) >= self _sync: self sync() ```` EDIT 2 Well i was totally wrong in my earlier point But I have got some interesting pointer One of the problem with is is that `shove` raised a confusing exception The real exception happened because ````def __setitem__(self key value): 118 # (per Larry Meyn) 119 try: 120 with open(self _key_to_file(key) 'wb') as item: 121 item write(self dumps(value)) 122 except (IOError OSError): 123 raise KeyError(key) ```` So the exception actually came from `open` system call That means it has troubles writing files I have a new suspicion with the length of the string The look of the `storage` folder ```` aftnix@dev:~â« ls -l storage/ total 36 -rw-rw-r-- 1 aftnix aftnix 49 ডিসৠ4 01:35 %21+%21+%21+%D1%87%D0%B8%D1%82%D0%B0%D0%B5%D1%82%D1%81%D1%8F+%D1%82%D1%80%D0%BE%D0%B5%D0%BA%D1%80%D0%B0%D1%82%D0%BD%D1%8B%D0%BECAUSE+%D0%BF%D0%BE%D0%B2%D1%82%D0%BE%D1%80%D0%B5%D0%BD%D0%B8%D0%B5%D0%BECAUSE+%7C%7C%7C+%21+%21+%21 -rw-rw-r-- 1 aftnix aftnix 52 ডিসৠ4 01:35 %21+%21+%21+%D1%87%D0%B8%D1%82%D0%B0%D0%B5%D1%82%D1%81%D1%8F+%D1%82%D1%80%D0%BE%D0%B5%D0%BA%D1%80%D0%B0%D1%82%D0%BD%D1%8B%D0%BECAUSE+%D0%BF%D0%BE%D0%B2%D1%82%D0%BE%D1%80%D0%B5%D0%BD%D0%B8%D0%B5%D0%BECAUSE+%7C%7C%7C+%2C+%21+%21+%21+is+pronounced ```` So `shove` is using key as file name So it might get very ugly as your string is very large in the last two entries especially the penultimate entry So for a test i deleted some characters from the last two lines of the input And the code ran as expected without any exception Linux kernel has a limit of file name length ````aftnix@dev:~â« cat /usr/include/linux/limits h #ifndef _LINUX_LIMITS_H #define _LINUX_LIMITS_H #define NR_OPEN 1024 #define NGROUPS_MAX 65536 /* supplemental group IDs are available */ #define ARG_MAX 131072 /* # bytes of args environ for exec() */ #define LINK_MAX 127 /* # links a file may have */ #define MAX_CANON 255 /* size of the canonical input queue */ #define MAX_INPUT 255 /* size of the type-ahead buffer */ #define NAME_MAX 255 /* # chars in a file name */ ```` So to get around it you have to do something else You cannot put the vanilla parsed key into `Shove` |
How to use string as a y-axis value in openpyxl's ScatterChart? It seems that currently only integer is supported as a value in y-axis I cannot use BarChart because it did not accept xvalues in Series ```` # the columns value here is int values = Reference(ws (2 2) (10 2)) # the columns value here is string values2 = Reference(ws (2 1) (10 1)) series = Series(values xvalues=values2 title="Chart") chart = ScatterChart() chart append(series) ws add_chart(chart) wb save(file_name) # exception File "/lib/python3 4/site-packages/openpyxl/charts/graph py" line 31 in compute_axes mini maxi = self _get_extremes('xvalues') File "/lib/python3 4/site-packages/openpyxl/charts/graph py" line 58 in _get_extremes return min(series_min) max(series_max) TypeError: unorderable types: NoneType() < int() ```` | Without sample data it is hard to say much but one thing to note that a data series have both data sets and labels A ScatterChart cannot really work with non-numerical axes There is an example of a BarChart with labels in the project's sample code |
Are `a argmin(axis=0)` and `np argmin(a axis=0)` the same? In numpy are `a argmin(axis=0)` and `np argmin(a axis=0)` the same? <a href="http://wiki scipy org/Numpy_Example_List#argmin" rel="nofollow">http://wiki scipy org/Numpy_Example_List#argmin</a> seems to suggest that they are not | If `a` is a NumPy array they are the same The `argmin` function also supports array-like objects whereas the method only exists on actual arrays This is true for most cases where a NumPy function and method have the same name aside from a few differences like the `sort` method operating in-place when the `sort` function makes a copy |
What happens to the paper after it is sold to end customers? | null |
How to max and min value of birthday in forms ModelForm of Django? I use Django 1 8 version my model has birthday column ````class UserProfile(models Model): user = models OneToOneField(User) birthday = models DateField (verbose_name=you'birthday') # ```` it is form for model ````class UserProfileForm(forms ModelForm): slug_field = 'user_slug' class Meta: model = UserProfile fields = ( 'birthday' ) ```` I would like to set who are 10-100 age person I guess I should use `SelectDateWidget` ````import datetime from django forms import extras class UserProfileForm(forms ModelForm): slug_field = 'user_slug' now = datetime datetime now() DOY = tuple(n for n in range(now year-100 now year-9)) birthday = forms DateField(widget=extras SelectDateWidget(years = DOY)) ```` Is it good way? or Could you tell me nice idea? | To validate a form field you could use a clean_FIELDNAME() method inside your form class Check out the <a href="https://docs djangoproject com/en/1 8/ref/forms/validation/#cleaning-a-specific-field-attribute" rel="nofollow">documentation</a> and <a href="http://stackoverflow com/a/7948998/1428235">this answer</a> |
FlaskApp returning http 500 in apache with mod_wsgi I am trying to host my python 3 4 flask app through apache and mod_wsgi Running the app through flasks own server works fine The app was made in a virtual environment pyvenv-3 4 However when trying to connect to the apache server in a browser it throws a 500 http error Configs and logs are attached I think this has to do with using pyvenv and not virtualenv (from pip) Flask documentation tells me to activate the virtual environment using this line ````activate_this = '/path/to/env/bin/activate_this py' ```` however that produces an IOError as the file does not exist I tried pointing it to the 'activate'-file instead and activate csh activate fish with no luck All files produces SyntaxError on the deactivate-line How can I run this app through Apache with my virtualenv? <strong>flaskapp wsgi</strong> ````#!/usr/bin/python activate_this = '/var/www/FlaskApp/FlaskApp/bin/activate' execfile(activate_this dict(__file__=activate_this)) import sys import logging logging basicConfig(stream=sys stderr) sys path insert(0 "/var/www/FlaskApp/") from FlaskApp import app as application application secret_key = 'some secret key' ```` <strong>Apache VirtualHost</strong> ````<VirtualHost *:80> ServerName example org # my server name ServerAlias gallifrey 192 168 0 84 ServerAdmin admin@example org # my admin WSGIScriptAlias /flask /var/www/FlaskApp/flaskapp wsgi <Directory /var/www/FlaskApp/FlaskApp/> Order allow deny Allow from all </Directory> Alias /static /var/www/FlaskApp/FlaskApp/static <Directory /var/www/FlaskApp/FlaskApp/static/> Order allow deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access log combined </VirtualHost> ```` <strong>Hierarchy</strong> ````/var/www/FlaskApp flaskapp wsgi FlaskApp/ bin/ activate activate csh activate fish easy_install easy_install-3 4 pip pip3 pip3 4 python python3 python3 4 include/ lib/ scripts/ static/ templates/ app py __init__ py ```` Trying to open the webpage I get a http 500 error: <strong>Apache error log</strong> ````[Fri May 02 10:22:58 2014] [error] [client 192 168 0 81] mod_wsgi (pid=31629): Target WSGI script '/var/www/FlaskApp/flaskapp wsgi' cannot be loaded as Python module [Fri May 02 10:22:58 2014] [error] [client 192 168 0 81] mod_wsgi (pid=31629): Exception occurred processing WSGI script '/var/www/FlaskApp/flaskapp wsgi' [Fri May 02 10:22:58 2014] [error] [client 192 168 0 81] Traceback (most recent call last): [Fri May 02 10:22:58 2014] [error] [client 192 168 0 81] File "/var/www/FlaskApp/flaskapp wsgi" line 3 in <module> [Fri May 02 10:22:58 2014] [error] [client 192 168 0 81] execfile(activate_this dict(__file__=activate_this)) [Fri May 02 10:22:58 2014] [error] [client 192 168 0 81] File "/var/www/FlaskApp/FlaskApp/bin/activate" line 4 [Fri May 02 10:22:58 2014] [error] [client 192 168 0 81] deactivate () { [Fri May 02 10:22:58 2014] [error] [client 192 168 0 81] ^ [Fri May 02 10:22:58 2014] [error] [client 192 168 0 81] SyntaxError: invalid syntax ```` | You can either follow the <a href="https://code google com/p/modwsgi/wiki/VirtualEnvironments" rel="nofollow">VirtualEnvironments instructions</a> or you can replicate what `virtualenv`'s `activate_this py` script does: ````import sys import os old_os_path = os environ['PATH'] os environ['PATH'] = os path dirname(os path abspath(__file__)) os pathsep old_os_path base = os path dirname(os path dirname(os path abspath(__file__))) if sys platform == 'win32': site_packages = os path join(base 'Lib' 'site-packages') else: site_packages = os path join(base 'lib' 'python%s' % sys version[:3] 'site-packages') prev_sys_path = list(sys path) import site site addsitedir(site_packages) sys real_prefix = sys prefix sys prefix = base # Move the added items to the front of the path: new_sys_path = [] for item in list(sys path): if item not in prev_sys_path: new_sys_path append(item) sys path remove(item) sys path[:0] = new_sys_path ```` You could make this a more general function: ````import sys import os def activate_venv(path): if sys platform == 'win32': bin_dir = os path join(path 'Scripts') site_packages = os path join(base 'Lib' 'site-packages') else: bin_dir = os path join(path 'bin') site_packages = os path join(BASE 'lib' 'python%s' % sys version[:3] 'site-packages') os environ['PATH'] = bin_dir os pathsep os environ['PATH'] prev_sys_path = list(sys path) import site site addsitedir(site_packages) sys prefix sys real_prefix = path sys prefix # Move the added items to the front of the path: new_sys_path = [] for item in list(sys path): if item not in prev_sys_path: new_sys_path append(item) sys path remove(item) sys path[:0] = new_sys_path ```` Put that in a module on your default Python module search path import `activate_venv` and pass in the result of `os path dirname(os path abspath(__file__))`: ````from somemodule import activate_venv import os path activate_venv(os path dirname(os path abspath(__file__))) ```` |
Django CSRF Error PW Reset and Login I am using django contrib auth views for password reset I get the CSRF error when I try to submit the password change form It let us me enter my email sends me a link with uidb64 and token and then let us me enter a new password twice When I submit this password_reset_confirm form I get the CSRF invalid error Here is my template for password reset confirm: ````<div class="reset-page"> <h3 class="reset-header">{% blocktrans %}Reset Password - Step 2 of 2{% endblocktrans %}</h3> <form class="login-form" action="" method="post"> <div class='form'> {% csrf_token %} {% if validlink %} <input id="id_new_password1" name="new_password1" type="password" class="text-login" placeholder="Password" /> <input id="id_new_password2" name="new_password2" type="password" class="text-login" placeholder="Confirm Password" /> <input type="submit" class="submit-login" value="{% trans 'Submit' %}" /> {% if error_messages %} <p class="reset-error">Error: {{ error_messages }}</p> {% endif %} {% else %} <p class="reset-bad-link">{% blocktrans %}Error: This reset link is no longer valid!{% endblocktrans %}</p> {% endif %} </div> </form> <p class="reset-info">{% blocktrans %}Enter your new password twice {% endblocktrans %}</p> </div> ```` I have no idea how to debug this help would be appreciated greatly There is not any custom code just the contrib views One last question in the source code of django contrib auth views password_reset_confirm it says that it does not need CSRF since noone can guess the URL I have tried removing the {% csrf_token %} tag and it still did not work Do I need it or not? EDIT: The django contrib auth views confirm view: ````# Does not need csrf_protect since no-one can guess the URL @sensitive_post_parameters() @never_cache def password_reset_confirm(request uidb64=None token=None template_name='registration/password_reset_confirm html' token_generator=default_token_generator set_password_form=SetPasswordForm post_reset_redirect=None current_app=None extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password """ UserModel = get_user_model() assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel _default_manager get(pk=uid) except (TypeError ValueError OverflowError UserModel DoesNotExist): user = None if user is not None and token_generator check_token(user token): validlink = True title = _('Enter new password') if request method == 'POST': form = set_password_form(user request POST) if form is_valid(): form save() return HttpResponseRedirect(post_reset_redirect) else: form = set_password_form(user) else: validlink = False form = None title = _('Password reset unsuccessful') context = { 'form': form 'title': title 'validlink': validlink } if extra_context is not None: context update(extra_context) if current_app is not None: request current_app = current_app return TemplateResponse(request template_name context) ```` | Remove the `<div class='form'>` tag Place `{% csrf_token %}` right after `<form class="login-form" action="" method="post">` |
Django Pinax-Project-Account github setup So I am fairly new to Github and Django for that matter I was digging around for a template of a website using Django offering user authentication and cam across this <a href="https://github com/pinax/pinax-project-account" rel="nofollow">pinax-project-account</a> I setup django and python for use within my cmd and using a virtual env and I stepped through the setup list but I am stuck using: `chmod x manage py` I understand this is for use in Unix just wondering how I get the same desired function in windows? as if I skip this step it will not work at all | You do not need to do that as Windows has no executable bit Instead of running ```` /manage py whatever ```` just run ````python manage py whatever ```` making sure that `python exe` is on your `PATH` |
What the difference between dict_proxy in python2 and mappingproxy in python3? I notice when I create class in python2 it stores attributes in `dict_proxy` object: ````>>> class A(object): pass >>> A __dict__ dict_proxy({ }) ```` But in python3 `__dict__` returns `mappingproxy`: ````>>> class A(object): pass >>> A __dict__ mappingproxy({ }) ```` Is there any difference between two of them? | There is no real difference it <a href="https://hg python org/cpython/different/c3a0197256ee/Objects/descrobject c" rel="nofollow">just got renamed</a> When it was proposed to expose the type in the `typing` module in <a href="http://bugs python org/issue14386" rel="nofollow">issue #14386</a> the object was renamed too: <blockquote> I would like to bikeshed a little on the name I think it should be MappingProxy (We do not use "view" much but the place where we do use it for keys/values/items views is very different I think Also collections abc already defines MappingView as the base class for KeysView and friends ) </blockquote> and <blockquote> Anyway you are not the first one who remarks that we already use "view" to define something else so I wrote a new patch to use the "mappingproxy" name (exposed as types MappingProxyType) </blockquote> The change <a href="https://docs python org/3/whatsnew/3 3 html#types" rel="nofollow">made it into Python 3 3</a> so in Python 3 2 you will still see the old name |
TurtleGraphics Python - Constraining random-moving turtle in a circle? How would I be able to make a randomly moving turtle be constrained inside a circle with a radius of 50 the circles center being at (0 0)? So if the turtle is currently at location (x y) it is distance from the center is math sqrt(x ** 2 y ** 2) Whenever the turtle's distance from the center is more than 50 have it turn around and continue I have gotten the code to work with the screen size but where do I put math sqrt(x ** 2 y ** 2) to get it to be constrained in a circle? Here is the code I have so far: ````import turtle random math def bounded_random_walk(num_steps step_size max_turn): turtle reset() width = turtle window_width() height = turtle window_height() for step in range(num_steps): turtle forward(step_size) turn = random randint(-max_turn max_turn) turtle left(turn) x y = turtle position() if -width/2 <= x <= width/2 and -height/2 <= y <= height/2: pass else: # turn around! turtle left(180) turtle forward(step_size) ```` This code works for a turtle in the screen but not in a circle | Where you are coding: ```` if -width/2 <= x <= width/2 and -height/2 <= y <= height/2: ```` you really mean "if point(x y) is inside the permitted area" So when "the permitted area" is "a circle with radius 50 centered at origin" comparing the squares of distances and radius (it is clearer than taking square roots !-) you would have: ```` if (x*x y*y) <= 50*50: ```` leaving all the rest of your code unchanged <strong>Edit</strong>: since the OP commented that this does not work for him I changed the if/else to: ```` x y = turtle position() # if -width/3 <= x <= width/3 and -height/3 <= y <= height/3: if (x*x y*y) <= 50*50: pass else: # turn around! print 'Bounce' step x y turtle left(180) turtle forward(step_size) ```` and ran it as `bounded_random_walk(200 10 30)` from a Terminal App on Mac OS X so the `print` would show The result is I get about 50 to 60 prints of "Bounce" and the turtle clearly IS being bounded inside the desired circle as logic and geometry also say it must So I hope the OP will edit their own answer along these lines (ideally on a system and in an arrangement where he can see the results of `print` or some other way of giving output and ideally show them to us) so that I can help him debug his code |
Selectively create sessions with web py I have a web py app running under OpenShift with scaling enabled The HAProxy process is constantly checking the index document over HTTP 1 0 to see if my app is up For example the logs look like: ```` ==> python/logs/appserver log <== 127 2 1 129 - - [2013-12-25 13:32:09] "GET / HTTP/1 0" 200 7297 1 240403 127 2 1 129 - - [2013-12-25 13:32:12] "GET / HTTP/1 0" 200 7297 0 676904 127 2 1 129 - - [2013-12-25 13:32:15] "GET / HTTP/1 0" 200 7297 1 421824 127 2 1 129 - - [2013-12-25 13:32:18] "GET / HTTP/1 0" 200 7297 0 730807 127 2 1 129 - - [2013-12-25 13:32:21] "GET / HTTP/1 0" 200 7297 1 153252 127 2 1 129 - - [2013-12-25 13:32:24] "GET / HTTP/1 0" 200 7297 0 828387 127 2 1 129 - - [2013-12-25 13:32:28] "GET / HTTP/1 0" 200 7297 1 390523 127 2 1 129 - - [2013-12-25 13:32:31] "GET / HTTP/1 0" 200 7297 0 964495 127 2 1 129 - - [2013-12-25 13:32:35] "GET / HTTP/1 0" 200 7297 2 574379 127 2 1 129 - - [2013-12-25 13:32:39] "GET / HTTP/1 0" 200 7297 2 011549 ```` Here is the problem For every request my app is creating a separate session instance I am using the DiskStore for sessions and so a separate file is created for every request and I am quickly hitting up against OpenShift's 80 000 file limit (after 3 days or so of constantly creating sessions like this) The weird thing is that my index getter does not utilize or access the session variable at all In fact I have tried changing it to just return "Hello World" and the objects still get created every 2-5 seconds I need to either A) Limit how often HAProxy is testing my site or more ideally B) Not create a session for every connection Any ideas? I have a pretty standard web py session initializer at the top of my main app file (not within any method): ````session = web session Session(app web session DiskStore(os path join(curdir 'sessions')) initializer={'request_token': '' 'request_token_secret': ''}) ```` | I guess just delete old sessions Not sure why they are not getting cleaned up for you EDIT: I mean have your app clean up old sessions of course |
Multiple save() in django FormView I am trying to make it easier for users to input just two dates and then calculate days from them in form_valid() Database model accepts each day as separate record ````def form_valid(self form): time = form cleaned_data['begin_time'] end_time = form cleaned_data['end_time'] is_first_day = True while time timedelta(hours=24) < end_time: data = form save(commit=False) data begin_time = time data end_time = time timedelta(hours=24) data is_first_day = is_first_day data save() is_first_day = False time = time timedelta(hours=24) data = form save(commit=False) data settlement = settlement data begin_time = time data end_time = end_time data is_first_day = is_first_day data save() return super(FormView self) form_valid(form) ```` Unfortunately only the last day has been saved Is there any chance I can do data save() multiple times in FormView without overriding it? | I think you should not rely on `form save()` and try to save different records You should use `Model objects create()` to create new records |
How do I write a Python Selenium test script that contains more than one test case? I am working on a Selenium Webdriver script in Python which only partially does what I want it to I want it to run through a set of test cases each in its own method in the class So in the case of my script here I want it to test the discount form (<strong>test_add_discount</strong>) then test the add unit form (<strong>test_add_unit_type</strong>) Each time I run it all I get is the first one then it closes with the message; <blockquote> Ran 1 test in 12 948s </blockquote> If I run it verbose with -v parameter I still do not see any reference to the second test case at all Here is my script; ````from selenium import webdriver from selenium webdriver common by import By from selenium webdriver common keys import Keys from selenium webdriver support ui import Select from selenium common exceptions import NoSuchElementException import unittest time re class AdminTestCase(unittest TestCase): def setUp(self): self driver = webdriver Firefox() self driver implicitly_wait(30) self base_url = "http://mysite local" def test_discount_test_case(self): driver = self driver driver get(self base_url "/admin/login") driver find_element_by_id("username") clear() driver find_element_by_id("username") send_keys("admin") driver find_element_by_id("password") clear() driver find_element_by_id("password") send_keys("p@ssw0rd") driver find_element_by_xpath("//button[@type='submit']") click() driver find_element_by_xpath("//li[4]/a/span") click() driver find_element_by_link_text("Add Discount") click() driver find_element_by_name("title") clear() driver find_element_by_name("title") send_keys("Selenium Test Discount") driver find_element_by_name("body") clear() driver find_element_by_name("body") send_keys("Test discount text") driver find_element_by_name("start_date") clear() driver find_element_by_name("start_date") send_keys("01/01/2014") driver find_element_by_name("end_date") clear() driver find_element_by_name("end_date") send_keys("01/03/2014") driver find_element_by_name("discount_percentage") clear() driver find_element_by_name("discount_percentage") send_keys("33") driver find_element_by_xpath("//button[@type='submit']") click() def test_add_unit_type(self): driver = self driver driver get(self base_url "/maxsys/unit_types") driver find_element_by_link_text("Add Unit type") click() driver find_element_by_name("title") clear() driver find_element_by_name("title") send_keys("Selenium Test Unit Type") driver find_element_by_name("height") clear() driver find_element_by_name("height") send_keys("22 5") driver find_element_by_name("width") clear() driver find_element_by_name("width") send_keys("Non-numeric") driver find_element_by_name("depth") clear() driver find_element_by_name("depth") send_keys("Test discount text") driver find_element_by_name("body") clear() driver find_element_by_name("body") send_keys("unit type description") driver find_element_by_xpath("//button[@type='submit']") click() def is_element_present(self how what): try: self driver find_element(by=how value=what) except NoSuchElementException e: return False return True def is_alert_present(self): try: self driver switch_to_alert() except NoAlertPresentException e: return False return True def close_alert_and_get_its_text(self): try: alert = self driver switch_to_alert() alert_text = alert text if self accept_next_alert: alert accept() else: alert dismiss() return alert_text finally: self accept_next_alert = True if __name__ == "__main__": unittest main() ```` | Ok it turns out my code is fine The problem was Python's indenting rules The indents in the second test case were tabs not spaces I have now set my editor to replace tab characters with 4 spaces and it all runs as expected Pretty infuriating and worse than that invisible to the human eye However when I type swear words into the internet about Python's indenting I am told that I will learn to love it eventually so I am trying to keep an open mind To catch this I have just learned about the <strong>-t</strong> parameter when invoking a python script from command line which will give warnings about mixed space and tab characters in Python 2 Using <strong>-tt</strong> will escalate them from warnings to errors |
Django Is it possible to combine the dictionary values? Hi am creating a quiz application in django I retrieved the database as json format for using in mobile application The retrieved json format is ````{ "quiz": [ { "category": "Python" "section": "Programming" "qtype": "Mcs" "id": 1 "level": 0 } { "category": "Html" "section": "Programming" "qtype": "Mc" "id": 2 "level": 1 } { "category": "Php" "section": "Theory" "qtype": "Yn" "id": 3 "level": 2 } ] } ```` Inside list having three dictionaries I want to convert this to ````{ "quiz": [ { "category": "Python > Programming > Mcs > level(0)" "id": 1 } { "category": "Html > Programming > Mc > level(1)" "id": 2 } { "category": "Php > Theory > Yn > level(2)" "id": 3 } ] } ```` Is it possible to convert the values to string? If yes please share your ideas <strong>models py</strong> ````class Quiz(models Model): category = models ForeignKey(Category) section = models ForeignKey(Section) qtype = models ForeignKey(QType) LEVELS = ( (0 'Beginner') (1 'Intermediate') (2 'Expert') ) level=models IntegerField(default=0 choices=LEVELS) class Category(models Model): name= models CharField(max_length=100) class Section(models Model): name= models CharField(max_length=100 unique=True) class QType(models Model): name= models CharField(max_length=100 unique=True) ```` <strong>views py</strong> ````def ajaxdashboard(request): quizs=Quiz objects all() n={'quiz': dict(id=x id category=x category name section=x section name qtype=x qtype name level=x level) for x in quizs]} return HttpResponse(json dumps(n) mimetype="application/json") ```` | Sure just generate the string in your view: ````n = { 'quiz': [ { 'id': x id 'category': ' > ' join([x category name x section name x qtype name 'level({0})' format(x level)]) } for x in quizs ] } ```` |
Replacing Empty Cells with 0 in Python 3 I am using the csv module to read in csv files to do data analysis ````data = [] c1 = [] c2 = [] c3 = [] data_file = csv reader(open('file csv')) for row in data_file: data append(row) for i in data: c1 append(data[i][0]) c2 append(data[i][1]) c3 append(data[i][2]) ```` How do I replace the empty cells with 0? | before appending your data you could do a check similar to what is found here : <a href="http://stackoverflow com/questions/34192705/python-how-to-check-if-cell-in-csv-file-is-empty">Python: How to check if cell in CSV file is empty?</a> When the condition is true simply append 0 to your corresponding cell (c1 c2 c3) |
What do groups with less power often find themselves? | excluded or oppressed |
How to change the color of single characters in a cell in excel with python win32com? I have a question regarding the win32com bindings for excel I set up early bindings and followed some examples from the "Python Programming on Win32" book from O'Reilly The following code works fine: ````book2 xlApp Worksheets('Sheet1') Cells(1 1) Font ColorIndex = 1 book2 xlApp Worksheets('Sheet1') Cells(1 1) Font ColorIndex = 2 ```` It changes the font color of the whole cell according to the number However this does not work: ````book2 xlApp Worksheets('Sheet1') Cells(1 1) Characters(start length) Font ColorIndex = 1 ```` I get the following callback: ````Traceback (most recent call last): File "<interactive input>" line 1 in <module> AttributeError: Characters instance has no __call__ method ```` However in Excels VBA the code works Can anybody point me to the solution? I really need to change parts of a string in an excel cell Thank you very much | use GetCharacters: ````Cells(1 1) GetCharacters(start length) Font ColorIndex = 1 ```` |
Django install as local app all I am trying to use the Django-Plupload in my project(src:<a href="https://github com/vellonce/django-plupload" rel="nofollow">https://github com/vellonce/django-plupload</a>) And I need to customize the view py of this external app Since I am developing in my localhost and I need to deploy it on server in the future I do not want it to stay in site package Instead I want to install it as local app May I know what is the suitable way to do this? Thank you | If you need to modify it download the source and include it in your project (you will have to check license terms of the package) Simply paste the app folder inside your project and add it to "installed apps" |
Which building was listed as the 13th tallest residential building in the world in January 2014? | Eureka Tower |
Who taught and accepted the belief that biologically distinct races were isomorphic? | many anthropologists |
Django where is the save command in this code? I tried to run this example on my computer but when I restart the python surprisingly the created polls are saved to the database without a visible save statement Here is the code: ````>>> from polls models import Poll Choice >>> Poll objects all()[0] choice_set create(choice='Not much' votes=0) <Choice: Not much> ```` So I wonder by which statements save instructions are implied ? Because if I create it like this it will not survive a restart ````>>> c = Choice(choice='Not much3' votes=0) >>> c poll_id = 1 ```` I am creating a choice and I am assigning the foreign key poll_id to the first poll I know this should not last because I did not save It is the first one that tricks me I assume if I create it within the associated set it also automatically saves not only gives it is proper foreign id I am also new to python and semantics seemed just a little bit loose based on my prior experience on this issue I would expect first code to just assign the proper foreign id not also save it to the database | Using the create() method on a QuerySet will automatically save the object as specified in the <a href="https://docs djangoproject com/en/dev/ref/models/querysets/#create" rel="nofollow">documentation</a> You can think of it as effectively an SQL INSERT statement |
cx-freeze fails to include modules even when included specifically I am trying to use cx-freeze to create a static self-contained distribution of my app (The Spye Python Engine <a href="http://www spye dk">www spye dk</a>) however when I run cx-freeze it says: ````Missing modules: ? _md5 imported from hashlib ? _scproxy imported from urllib ? _sha imported from hashlib ? _sha256 imported from hashlib ? _sha512 imported from hashlib ? _subprocess imported from subprocess ? configparser imported from apport fileutils ? usercustomize imported from site ```` This is my setup py: ````#!/usr/bin/env python from cx_Freeze import setup Executable includes = ["hashlib" "urllib" "subprocess" "fileutils" "site"] includes = ["BaseHTTPServer" "cgi" "cgitb" "fcntl" "getopt" "httplib" "inspect" "json" "math" "operator" "os" "os " "psycopg2" "re" "smtplib" "socket" "SocketServer" "spye" "spye config" "spye config file" "spye config merge" "spye config section" "spye editor" "spye framework" "spye frontend" "spye frontend cgi" "spye frontend http" "spye input" "spye output" "spye output console" "spye output stdout" "spye pluginsystem" "spye presentation" "spye util html" "spye util rpc" "ssl" "stat " "struct" "subprocess" "sys" "termios" "time" "traceback" "tty" "urllib2" "urlparse" "uuid"] includefiles=[] excludes = [] packages = [] target = Executable( # what to build script = "spye-exe" initScript = None #base = 'Win32GUI' targetDir = r"dist" targetName = "spye exe" compress = True copyDependentFiles = True appendScriptToExe = False appendScriptToLibrary = False icon = None ) setup( version = "0 1" description = "No Description" author = "No Author" name = "cx_Freeze Sample File" options = {"build_exe": {"includes": includes "excludes": excludes "packages": packages #"path": path } } executables = [target] ) ```` Please note that I clearly specify the missing modules in the includes list How do I fix this? | I guess you can not simply `+=` on lists You should probably use the list method `extend` - otherwise the original list will not be modified: ````includes extend(["BaseHTTPServer" "<rest of your modules>"]) ```` <strong>EDIT: (Thank @ThomasK)</strong> `+=` works fine - I only had an online Python interpreter that did not work correctly (I have no python install on my Windows installation so I had to check online) |
What db/fileformat to use for append-only LIFO mostly-read operations from python script? I am going to receive a daily list of product prices and I need to: - store it (single process once every night does not matter if it takes hours reads stopped all data is ready to be written in a single batch) - quickly read the latest price for a given product (multithreaded web app must be fast) - sometimes read the whole price history for a given product (cron job script to draw graphs does not matter if it is slow) - keep the whole history for years (never forget anything) - bonus points if the nightly (write) job is a simple python script not depending on external services - just to be clear: there are no writes other than the nightly job and the latter runs in a single process and can run with reads disabled from the actual db/file I am looking for recommendations for the most efficient way to achieve that programming language is <a href="http://www python org/" rel="nofollow">Python-2 7</a> with 3 x being available if needed I was thinking about storing on [possibly multiple] file[s] the actual data with whole history and maybe updating a <a href="http://dev mysql com/downloads/mysql/5 5 html" rel="nofollow">MySQL</a> db with only the latest prices for every item (for the web app to consume) The file could be <a href="http://www sqlite org/" rel="nofollow">sqlite</a> (stable proven and "fast enough" for us bonus: can be used via <a href="http://www sqlalchemy org/" rel="nofollow">SQLAlchemy</a> which we love) or some other file format (<a href="http://pypi python org/pypi/python-cdb" rel="nofollow">CDB</a> or the like) if there are enough reasons and I can manage some sort of "rotation" (i e one file per year) if that is needed to achieve fast reads of the latest data | I would start with sqlite since it is included directly with python Slap on SQLAlchemy and it should be easy enough to swap out the underlying DB as needed Test with that and if it is not enough move to a more powerful db (I prefer postgres) |
Change image and label on keypress in kivy I am learning using kivy right now on my Raspberry-Pi I installed the most recent kivypie image and I do want to make a simle app which changes an image content and some label on buttonpress and keypress The buttonpress works as expected but the after pressing uo/down keys on the keyboard only the label text changes and no image is being displayed Also I can quit the App pressing the q button but not the escape button as I would like Here is my current code: ````from kivy app import App from kivy uix widget import Widget from kivy uix button import Button from kivy uix label import Label from kivy uix boxlayout import BoxLayout from kivy uix image import Image from kivy core window import Window class MyApp(App): def build(self): self _keyboard = Window request_keyboard(self _keyboard_closed self) self _keyboard bind(on_key_down=self _on_keyboard_down) root = BoxLayout(orientation='vertical') self image = Image(source='test png' allow_stretch=True keep_ratio=True) root add_widget(self image) self label = Label(text='Some long and very explanatory text This is a representation of a custom image description' ' coming with the image This text can split over several lines and will fit in a box' 'defined by the text_size property ' font_size=28 text_size=(600 None) color=(0 1 1 1) size_hint=(1 2)) root add_widget(self label) button = Button(text="Change" size_hint=(1 07)) button bind(on_press=self callback) root add_widget(button) return root def callback(self value): self image source = 'test jpg' self label text = 'No text' def _keyboard_closed(self): self _keyboard unbind(on_key_down=self _on_keyboard_down) self _keyboard = None def _on_keyboard_down(self keyboard keycode text modifiers): #print('### ----------------------------------- ###') #print('The key' keycode 'have been pressed') #print(' - text is %r' % text) #print(' - modifiers are %r' % modifiers) if text == 'escape': App get_running_app() stop() #keyboard release() elif text == 'q': App get_running_app() stop() #keyboard release() elif text == 'up': self image source = 'test jpg' self label text = 'No text' #keyboard release() elif text == 'down': self image source = 'test jpg' self label text = 'No text' #keyboard release() return True if __name__ == '__main__': MyApp() run() ```` | If you uncomment your print statements you will see the information you are looking for is in `keycode` not `text` `text` will only match lettered keys for special keys (escape up down etc) it will not Try changing it such that: ````def _on_keyboard_down(self keyboard keycode text modifiers): print('### ----------------------------------- ###') print('The key' keycode 'have been pressed') print(' - text is %r' % text) print(' - modifiers are %r' % modifiers) key = keycode[1] if key == 'escape': App get_running_app() stop() #keyboard release() elif key == 'q': App get_running_app() stop() #keyboard release() elif key == 'up': self image source = 'test2 png' self label text = 'No text' #keyboard release() elif key == 'down': self image source = 'test2 png' self label text = 'No text' #keyboard release() return True ```` |
Houston ranked 23rd in which category by Forbes magazine in 2006? | null |
What character-shifting / pseudo-encryption algorithm is used here? This is a cry for help from all you cryptologists out there Scenario: I have a Windows application (likely built with VC++ or VB and subsequently moved to Net) that saves some passwords in an XML file Given a password `A0123456789abcDEFGH` the resulting "encrypted" value is `04077040940409304092040910409004089040880408704086040850404504044040430407404073040720407104070` Looking at the string I have figured out that this is just character shifting: '04' delimits actual character values which are decimal; if I then subtract these values from 142 I get back the original ASCII code In Jython (2 2) my decryption routine looks like this (EDITED thanks to suggestions in comments): ````blocks = [ pwd[i:i+5] for i in range(0 len(pwd) 5) ] # now a block looks like '04093' decrypted = [ chr( 142 - int(block[3:] lstrip('0')) ) for block in blocks ] ```` This is fine for ASCII values (127 in total) and a handful of accented letters but 8-bit charsets have another 128 characters; limiting accepted values to 142 does not make sense from a decimal perspective EDIT: I have gone rummaging through our systems and found three non-ASCII chars: ````è 03910 à 03926 à 03929 ```` From these values it looks like actually subtracting the 4-number block from 4142 (leaving only '0' as separator) gives me the correct character So my question is: - is anybody familiar with this sort of obfuscation scheme in the Windows world? Could this be the product of a standard library function? I am not very familiar with Win32 and Net development to be honest so I might be missing something very simple - If it is not a library function can you think of a better method to de-obfuscate these values without resorting to the magic 142 number i e a scheme that can actually be applied on non-ASCII characters without special-casing them? I am crap at bit shifting and all that so again I might be missing something obvious to the trained eye | <blockquote> is anybody familiar with this sort of obfuscation scheme in the Windows world? </blockquote> Once you understand it correctly it is just a trivial rotation cipher like <a href="http://en wikipedia org/wiki/ROT13" rel="nofollow">ROT13</a> Why would anyone use this? Well in general this is very common Let us say you have some data that you need to obfuscate But the decryption algorithm and key have to be embedded in software that the viewers have There is no point using something fancy like AES because someone can always just dig the algorithm and key out of your code instead of cracking AES An encryption scheme that is even marginally harder to crack than finding the hidden key is just as good as a perfect encryption schemeâthat is good enough to deter casual viewers and useless against serious attackers (Often you are not even really worried about <them>stopping</them> attacks but about proving after the fact that your attacker must have acted in bad faith for contractual/legal reasons ) So you use either a simple rotation cipher or a simple xor cipherâit is fast it is hard to get wrong and easy to debug and if worst comes to worst you can even decrypt it manually to recover corrupted data As for the particulars: If you want to handle non-ASCII characters you pretty much have to use Unicode If you used some fixed 8-bit charset or the local system's OEM charset you would not be able to handle passwords from other machines A Python script would almost certainly handle Unicode characters because in Python you either deal in bytes in a `str` or Unicode characters in a `unicode` But a Windows C or NET app would be much more likely to use UTF-16 because Windows native APIs deal in UTF-16-LE code points in a `WCHAR *` (aka a string of 16-bit words) So why 4142? Well it really does not matter what the key is I am guessing some programmer suggested <a href="http://en wikipedia org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#Answer_to_the_Ultimate_Question_of_Life 2C_the_Universe 2C_and_Everything_ 2842 29" rel="nofollow">42</a> His manager then said "That does not sound very secure " He sighed and said "I already explained why no key is going to be any more secure than⦠you know what forget it what about 4142?" The manager said "Ooh that sounds like a really secure number!" So that is why 4142 <hr> <blockquote> If it is not a library function can you think of a better method to de-obfuscate these values without resorting to the magic 142 number </blockquote> You do need to resort to the magic 4142 but you can make this a lot simpler: ````def decrypt(block): return struct pack('>H' (4142 - int(block 10)) % 65536) ```` So each block of 5 characters is the decimal representation of a UTF-16 code unit subtracted from 4142 using C unsigned-short wraparound rules This would be trivial to implement in native Windows C but it is slightly harder in Python The best transformation function I can come up with is: ````def decrypt_block(block): return struct pack('>H' (4142 - int(block 10)) % 65536) def decrypt(pwd): blocks = [pwd[i:i+5] for i in range(0 len(pwd) 5)] return '' join(map(decrypt_block blocks)) decode('utf-16-be') ```` This would be a lot more trivial in C or C# which is probably what they implemented things in so let me explain what I am doing You already know how to transform the string into a sequence of 5-character blocks My `int(block 10)` is doing the same thing as your `int(block lstrip('0'))` making sure that a `'0'` prefix does not make Python treat it as an octal numeral instead of decimal but more explicitly I do not think this is actually necessary in Jython 2 2 (it definitely is not in more modern Python/Jython) but I left it just in case Next in C you would just do `unsigned short x = 4142U - y;` which would automatically underflow appropriately Python does not have `unsigned short` values just signed `int` so we have to do the underflow manually (Because Python uses floored division and remainder the sign is always the same as the divisorâthis would not be true in C at least not C99 and most platforms' C89 ) Then in C we would just cast the unsigned short to a 16-bit "wide character"; Python does not have any way to do that so we have to use <a href="http://docs python org/2 6/library/struct html" rel="nofollow">`struct pack`</a> (Note that I am converting it to big-endian because I think that makes this easier to debug; in C you would convert to native-endian and since this is Windows that would be little-endian ) So now we have got a sequence of 2-character UTF-16-BE code points I just `join` them into one big string then `decode` it as UTF-16-BE <hr> If you really want to test that I have got this right you will need to find characters that are not just non-ASCII but non-Western In particular you need: - A character that is > YOU+4142 but < YOU+10000 Most CJK ideographs like YOU+7000 (ç) fit the bill This should appear as `'41006'` because that is 4142-0x7000 rolled over as an unsigned short - A character that is >= YOU+10000 This includes uncommon CJK characters specialized mathematical characters characters from ancient scripts etc For example the Old Italic character YOU+10300 (í í¼) encodes to the surrogate pair (0xd800 0xdf00); 4142-0xd800=14382 and 4142-0xdf00=12590 so you would get `'1438212590'` The first will be hard to findâeven most Chinese- and Japanese-native programmers I have dealt with use ASCII passwords And the second even more so; nobody but a historical linguistics professor is likely to even think of using archaic scripts in their passwords By Murphy's Law if you write the correct code it will never be used but if you do not it is guaranteed to show up as soon as you ship your code |
More efficient way of transforming items in a list I have a list of strings I needed to combined a few of the items Each item that would be combined is listed in consecutive order like so: ````info = [you'1' you'be/4' you'root' you'0 00' you'B' you'0 00' you'B' you'0 00' you'%' you'0 00' you'%' you'init'] info[3] = info[3] info[4] info pop(4) info[4] = info[4] info[5] info pop(5) info[5] = info[5] info[6] info pop(6) info[6] = info[6] info[7] info pop(7) >>> info [you'1' you'be/4' you'root' you'0 00B' you'0 00B' you'0 00%' you'0 00%' you'init'] ```` The last line being the desired output but I wanted to get some ideas of a better way without all the popping and assignment? UPDATE: Wow! These are all great I want to test and time them all ;) | Well a rather simple method is just: ````>>> lst[:] = lst[:3] [lst[3] lst[4] lst[5] lst[6] lst[7] lst[8] lst[9] lst[10] lst[11]] [lst[11]] [you'1' you'be/4' you'root' you'0 00B' you'0 00B' you'0 00%' you'0 00%' you'init'] ```` This just constructs a new list from the existing list then makes `lst` be that new list Could write some snazzy function that deals with the pairings though And to make it clearer you could format the code to be something like ````lst[:] = ( lst[:3] [ lst[3] lst[4] lst[5] lst[6] lst[7] lst[8] lst[9] lst[10] ] [lst[11]] ) ```` Which makes it fairly clear where the slicing pairings and endings are Another option which move single characters fields but not extensively tested: ````>>> text = '\t' join(lst) >>> re sub('\t( )\t' r'\1\t' text) split('\t') # or use ([B%]) instead maybe [you'1' you'be/4' you'root' you'0 00B' you'0 00B' you'0 00%' you'0 00%' you'init'] ```` |
decode content while reading from socket in Python Assume I read some content from socket in Python and have to decode it to UTF-8 on-the-fly I can not afford to keep all the content in memory so I must decode it as I receive and save to file It can happen that I will only receive partial bytes of character (â¬-sign is represented by three bytes for example in Python as '\xe2\x82\xac') Assume I have received only the first two bytes (\xe2\x82) if I try to decode it I am getting 'UnicodeDecodeError' as expected I could always try to decode the current content and check if it throws an Exception - But how reliable is this approach? - How can I know or determine if I can decode the current content? - How to do it correct? Thanks | Guido's time machine strikes again ````>>> dec = codecs getincrementaldecoder('utf-8')() >>> dec decode('foo\xe2\x82') you'foo' >>> dec decode('\xac') you'\u20ac' ```` |
How to run Python3 project on Azure? I am trying to run my Python3 project on Azure However if I choose python version on Azure portal getting script request (e g <a href="http://xxxxx azurewebsites net/static/app/scripts/jquery-1 10 2 js" rel="nofollow">http://xxxxx azurewebsites net/static/app/scripts/jquery-1 10 2 js</a>) receive 404 error ) Actually it happens whenever I choose python version not only python 3 4 even though if I choose "off" as Python version it runs correctly <a href="http://i stack imgur com/AcyRY png" rel="nofollow">Azure Portal image</a> I created this project using "Django Web Project" in Visual Studio and deploy it from Command Line I would appreciate it if you could help me | Well since you are using Visual Studio to manage your Django Web Project I believe that you are using Virtual Environment The Python Version you configure in the Azure Portal is for none-Virtual Environment Setting this Version will change the path of static file requesting That is why it returns 404 If you want to change the python version for your app you should change your Virtual Environment instead of setting the python version in the Azure Portal It is always a good practice to use Virtual Environment so I do not suggest you to delete your Environment and use the default one Here are the steps for adding a new Virtual Environment to your Django Project and switching between Environments - Right click the <strong>Python Environment</strong> of you Project and choose <strong>Add Virtual Environment </strong> <a href="http://i stack imgur com/GG8jr png" rel="nofollow"><img src="http://i stack imgur com/GG8jr png" alt="enter image description here"></a> - Select the python version you want for your project <a href="http://i stack imgur com/eVkQV png" rel="nofollow"><img src="http://i stack imgur com/eVkQV png" alt="enter image description here"></a> - Wait for your packages being installed - Right click the <strong>Python Environment</strong> of you Project again and choose <strong>Add/Remove Python Environment </strong> - Select the Environment you want for your project and unselect the others <a href="http://i stack imgur com/39opx png" rel="nofollow"><img src="http://i stack imgur com/39opx png" alt="enter image description here"></a> |
When was the doctrine of fallibilism published? | null |
Python: cannot remove \n I want to remove `\n` from the beginning lines like this `\n id int(10) NOT NULL` I tried `strip()` `rstrip()` `lstrip()` `replace('\n' '')` I do not get it What am I doing wrong? ````print(column) print(column __class__) x = column rstrip('\n') print(x) x = column lstrip('\n') print(x) x = column strip('\n') print(x) print(repr(column)) ```` gives ````\n id int(10) NOT NULL <type 'str'> \n id int(10) NOT NULL \n id int(10) NOT NULL \n id int(10) NOT NULL \n id int(10) NOT NULL '\\n `id` int(10) NOT NULL' ```` | Are you sure that `\n` is a newline instead of a literal `\` followed by a literal `n`? In that case you would want: ````s = r'\nthis is a string' s = s strip() print s s = s strip(r'\n') print s ```` Probably a better way is to check if it starts with `\n` before stripping and then use slicing: ````if s startswith(r'\n'): s = s[2:] ```` or even more robustly `re sub`: ````re sub(r'^(?:\\n)+' '' r'\n\nfoobar') ```` Based on the symptoms you describe above I am almost positive this is the case |
Saving a matplotlib graph as an image field in database I just started learning `matplotlib` and I want to use it in one of my django apps So I wanted to know how I can save the graph generated in an image field of my models so that I can retrive whenever needed | <a href="http://matplotlib org/api/pyplot_api html#matplotlib pyplot savefig" rel="nofollow">`matplotlib pyplot savefig`</a> accepts file-like object as the first parameter You can pass `StringIO`/`BytesIO` (according to your python version) ````f = StringIO() plt savefig(f) ```` Then use <a href="https://docs djangoproject com/en/dev/ref/files/file/#the-contentfile-class" rel="nofollow">`django core files ContentFile`</a> to convert the string to <a href="https://docs djangoproject com/en/dev/ref/files/file/#django core files File" rel="nofollow">`django core files File`</a> (because <a href="https://docs djangoproject com/en/dev/ref/models/fields/#django db models fields files FieldFile save" rel="nofollow">`FieldFile save`</a> accepts only accept an instance of `django core files File`) ````content_file = ContentFile(f getvalue()) model_object = Model( ) model_object image_field save('name_of_image' content_file) model_object save() ```` |
John Glenn's spaceship was named what when he orbited the Earth? | Friendship 7 |
IO ERROR(ERRNO 20) while Accessing a file inside a folder in python <strong><them>This is a code for accessing a file inside a folder using with open() as:{} option </them></strong> ````with open("DATABASE\password txt") as _2_: password=_2_ readlines() with open("DATABASE/names txt") as _3_: names=_3_ readlines() with open("DATABASE\email txt") as _4_: email=_4_ readlines() ```` In this code if I put "DATABASE\names txt" as I did for password and email; instead of "DATABASE/names txt"; it does not work Please Tell me the reason for the same | You need to escape the \ use raw string r or forward slashes as you have already tried: ````"DATABASE\\names txt" # double \ r"DATABASE\names txt" # raw string "DATABASE/names txt" # use forward slashes ```` `\n` is a newline character ````In [7]: print "DATABASE\names txt" # interpreted as two lines DATABASE ames txt In [8]: print r"DATABASE\names txt" DATABASE\names txt ```` A backslash has a special meaning in python it is used to <a href="https://docs python org/2/reference/lexical_analysis html#string-literals" rel="nofollow">escape</a> characters |
Type Error when using custom clean_<fieldname> method in django I am using the inbuilt User model to store user information in my application However while registering a new user I want that the username should be unique For this purpose I decided to override the clean_username method in my modelform Here is my forms py file ````from django import forms from django contrib auth models import User class Registration_Form(forms ModelForm): password=forms CharField(widget=forms PasswordInput()) class Meta: model=User fields=['first_name' 'last_name' 'username' 'email' 'password'] def clean_username(self): value=self cleaned_data['username'] if User objects filter(username=value[0]): raise ValidationError(you'The username %s is already taken' %value) return value ```` And here is my views py file ````from django shortcuts import render from django shortcuts import redirect # Create your views here from django contrib auth models import User from registration forms import Registration_Form def register(request): if request method=="POST": form=Registration_Form(request POST) if form is_valid(): unm=form cleaned_data('username') pss=form cleaned_data('password') fnm=form cleaned_data('first_name') lnm=form cleaned_data('last_name') eml=form cleaned_data('email') you=User objects create_user(username=unm password=pss email=eml first_name=fnm last_name=lnm) you save() return render(request 'success_register html' {'you':you}) else: form=Registration_Form() return render(request 'register_user html' {'form':form}) ```` However on clicking the submit button of the form I am getting this error Exception Type: TypeError Exception Value: 'dict' object is not callable Exception Location: /home/srai/project_x/registration/views py in register line 12 The line in question is this unm=form cleaned_data('username') Can anyone please tell me why this error occurs and how do I solve it Thanks | Firstly the error is not anything to do with your custom clean method it is happening in the view It is simply that you should use square brackets to access dict items not parentheses: ````unm=form cleaned_data['username'] ```` |
Updating MySQL row headers from dictionary key (Python) I have compiled the below script in Python 2 x which to recursively search a directory and for each JPEG found parse out the metadata and place it into a dictionary At present the output is simply printed to console:- ````import os import fnmatch import pyexiv2 matches = [] dict1 = {} # The aim of this script is to recursively search across a directory for all # JPEG files Each time a JPEG image is detected the script used the PYEXIV2 # module to extract all EXIF IPTC and XMP data from the image Once extracted # the key (ie "camera make" is generated and it is respective value # (ie Canon) is then added as the value in a dictionary for root dirnames filenames in os walk('C:\Users\XXX\Desktop'): for filename in fnmatch filter(filenames '* jpg'): matches append(os path join(root filename)) for entry in matches: metadata = pyexiv2 ImageMetadata(entry) metadata read() keys = metadata exif_keys metadata iptc_keys metadata xmp_keys for key in keys: dict1[key] = metadata[key] raw_value print entry print str(dict1) ```` What I am looking to do is output the results to a MySQL DB Now my problem is that I do not have an indefinite list of the metadata headers and indeed I have struggled to locate one and so for my table row headers I am looking to compare each value in the dictionary key (ie date taken make model etc ) and if it does not exist in the table for it to be added to my table as a header and for the EXIF data (the key value) to then be entered into the respective columns I have had a play with MySQL through Python previously but never to compare row headers and dynamically create new ones from variables Can anybody point me in the right direction? | Instead of adding new data keys as new columns in MySQL table create a fixed single table with three columns `file` `data_name` `data_value` and then you can have dynamic data per file You can then easily query the table e g ````select file from file_data where data_name = 'Serial' and data_value = 'ABCDE' ```` For multiple field matching you can do a self join e g ````SELECT * from data t1 JOIN data t2 on t1 file_name = t2 file_name and t1 data_name = "data1" and t1 data_value="value1" and t2 data_name = "data2" and t2 data_value="value2" ```` <strong>Alternatively</strong> you can just keep on appending columns to MySQL table dynamically e g ````ALTER TABLE data ADD Serial VARCHAR(60); ```` You can get the existing columns name using ````SHOW COLUMNS FROM `data`; ```` So every-time you see a new data field add it as column |
Python C API: How to get PyRun_String with Py_eval_input to use imported modules? ````PyRun_String("random randint(1 10)" Py_eval_input globals globals); ```` returns error with: ````Traceback (most recent call last): File "<string>" line 1 in <module> NameError: name 'random' is not defined ```` earlier in the code I did: ````PyImport_ImportModule("random"); ```` I guess this is not the way to get it work What is the correct way? Thank you! | `PyImport_ImportModule` returns the imported value You need to save it in `globals` under the name `random` In summary: ````PyMapping_SetItemString(globals "random" PyImport_ImportModule("random")); ```` but do not forget to also check the result of the import in case it throws an exception |
Python 2 7 Tkinter: loop through labels to display data on new row I currently trying to create a weather application and I have code that prints out the day forecast and maxtemperture for the next 7 days ````weather_req_url = "https://api forecast io/forecast/%s/%s %s?units=uk2" % (weather_api_token lat lon) are = requests get(weather_req_url) weather_obj = json loads(r text) t = datetime now() for i x in enumerate(weather_obj["daily"]["data"][1:8]): print (t+timedelta(days=i+1)) strftime("\t%a") x['icon'] ("% 0f" % x['temperatureMax']) ```` This codes prints this information in the she will: ````Sat rain 20 Sun partly-cloudy-day 21 Mon clear-day 26 Tue partly-cloudy-night 29 Wed rain 28 Thu rain 24 Fri rain 23 ```` I currently have a frame and a label for it however I do not want to manually create a label for each row ````self degreeFrm = Frame(self bg="black") self degreeFrm grid(row = 0 column = 0) self temperatureLbl = Label(self degreeFrm font=('Helvetica Neue UltraLight' 80) fg="white" bg="black") self temperatureLbl grid(row = 0 column = 0 sticky = E) ```` Is there a way to run the first chunk of code that creates and displays a label with the information from each iteration of the for loop | As in the comment above something along these lines should do the trick: ````forecasts = [] for i x in enumerate(weather_obj["daily"]["data"][1:8]): forecasts append((t+timedelta(days=i+1)) strftime("\t%a") x['icon'] ("% 0f" % x['temperatureMax'])) row_num = 0 for forecast in forecasts: l = Label(self degreeFrm font=('Helvetica Neue UltraLight' 80) text = forecast) l grid(row = row_num column = 0 sticky= E) row_num =1 ```` Hope this helps |
Using Django Framework to compare User form answer as an input and comparing it with a evaluation for a math expression using eval I am having problem coding and figuring out how to compare a value as an answer from the user input of a form and using that input to compare it with eval(puzzle) which puzzle is a simple expression like 2+2 Here is some code Url: is fine Views: def play(request): ````if request user is_authenticated(): number_of_records = Puzzles objects count() random_index = int(random random()*number_of_records)+1 rand_puzz = Puzzles objects get(id = random_index) puzzle solution = eval(rand_puzz) if solution = request GET['a']: message = "correct" return render(request 'play html' {'rand_puzz': rand_puzz 'message':message}) else: message = "incorrect" return render(request 'play html' {'rand_puzz': rand_puzz message':message}) else: return render_to_response('home html') ```` HTML: ```` <form action= '/play/' method ="GET"> <table style="margin-left:auto; margin-right:auto; width:auto;"> <table style="margin-left:auto; margin-right:auto; width:auto; border:solid 1px"> <tr><td><label for="username">Question:</label></td> <td>{{rand_puzz}}</td></tr> <td><input type="number" name="a" value="a" id="a"></td></tr> <td>{{solution}}</td></tr> <td> Your answer is:{{message}}</td></tr> <tr><td></td><td><input type="submit" value="submit"/></td></tr> </table> </table> </form> </div> ```` | i do not know if it going to solve your problem but replace ````from django shortcuts import get_object_or_404 rand_puzz = Puzzles objects get(id = random_index) puzzle by rand_puzz = get_object_or_404(Puzzles id = random_index) ```` |
Issue with Scikit Learn Package for SVR Regression I am trying to fit a SVM regression model using Scikit Learn Package but it is not working like I am expecting Could you please help me to find the error? The code that I would like to use is: ````from sklearn svm import SVR import numpy as np X = [] x = np arange(0 20) y = [3 4 8 4 6 9 8 12 15 26 35 40 45 54 49 59 60 62 63 68] X append(x) clf = SVR(verbose=1) clf fit(np transpose(X) y) print("Expecting Result:") print(y) print("Predicted Result:") print(clf predict(np transpose(X))) ```` The Output that I have is: ````[LibSVM]* optimization finished #iter = 10 obj = -421 488272 rho = -30 500000 nSV = 20 nBSV = 20 Expecting Result: [3 4 8 4 6 9 8 12 15 26 35 40 45 54 49 59 60 62 63 68] Predicted Result: [ 29 1136814 28 74580196 28 72748632 28 72736291 28 7273628 28 7273628 28 72736302 28 72760984 28 76424112 29 5 31 5 32 23575888 32 27239016 32 27263698 32 2726372 32 2726372 32 27263709 32 27251368 32 25419804 31 8863186 ] ```` We can see that the predicted results are very far from the training data How can I improve the fitting? Thanks David | This is an edge case where RBF (default for SVM on scikit-learn) kernels do not work very well Change the SVR line to this: `clf = SVR(verbose=1 kernel='linear')` and you will see much more reasonable results ` [LibSVM]Expecting Result: [3 4 8 4 6 9 8 12 15 26 35 40 45 54 49 59 60 62 63 68] Predicted Result: [ -6 9 -2 9 1 1 5 1 9 1 13 1 17 1 21 1 25 1 29 1 33 1 37 1 41 1 45 1 49 1 53 1 57 1 61 1 65 1 69 1] ` I understand that you are just trying to get a feel for how SVM's work Take a look at <a href="https://charlesmartin14 wordpress com/2012/02/06/kernels_part_1/" rel="nofollow">this</a> blog post for how RBF kernels work |
Do anaconda packages interfere with system python I have a system with certain python version and packages installed suing the distribution repositories For some project (calculation) I need newer version the the packages I am thinking of installing anaconda and use conda virtual environments Will this broke programs that must use the system packages? (note: I tried virtual enviroment but I could not install a newver version of matplotlib because of problems with pygtk) | No this will not break your system's python As long as you do not tick the option "register miniconda as the default system python" (or whatever that option is called depending on your OS) One of the key benefits of conda is that you can create isolated python environments fully independent of each other |
sympy count_roots: type mismatch when working with real polynomial I am using sympy and trying to compute number of roots of a polynomial ````from sympy abc import x from sympy import Poly p = Poly(x**4+0 1 x) ```` At this point p is polynomial with domain 'RR': `Poly(1 0*x**4 0 1 x domain='RR')` If I try to compute number of roots in the interval I get: ````p count_roots(0 2) TypeError: unsupported operand type(s) for *=: 'RealElement' and 'PythonRational' ```` However if I define ````q = Poly(x**3-1 x) ans: Poly(x**3 - 1 x domain='ZZ') q count_roots(0 2) ans: 1 ```` Similarly if I ask for number of roots of `p` on the whole domain that works as well ````p count_roots() ans: 1 ```` What should I do to supply correct types to count_roots? | When possible use exact (instead of floating point) numbers in your symbolic expressions (this principle is true for all symbolic math software not only sympy) In this case the constant term `0 1` in the definition of `p` can be replaced by the (exact) ratio representation `1/10` Sympy uses `Rational` to describe ratios of numbers (since an input `1/10` is interpreted by python as a floating point division and automatically transformed to `0 1`) The following code works ````from sympy abc import x from sympy import Poly Rational p = Poly( x**4 Rational(1 10) x) p count_roots(0 2) ```` <blockquote> `0` </blockquote> See also `sympy nsimplify` for transforming arbitrary floating point numbers such as e g `12 21525` to (approximately equal) rationals |
What kind of clock have genetic functions? | biological clock |
Usefulness of @property in this case Given the following class: ````class BasicRNNCell(RNNCell): """The most basic RNN cell """ def __init__(self num_units input_size=None): self _num_units = num_units self _input_size = num_units if input_size is None else input_size @property def input_size(self): return self _input_size @property def output_size(self): return self _num_units @property def state_size(self): return self _num_units def __call__(self inputs state scope=None): """Most basic RNN: output = new_state = tanh(W * input YOU * state B) """ with vs variable_scope(scope or type(self) __name__): # "BasicRNNCell" output = tanh(linear([inputs state] self _num_units True)) return output output ```` I do not understand why they use the property function in this case Using the property decorator for the input_size function allows one to call input_size on an object let us call it cell of that class but why do not they just simply call cell _input_size? Can anybody tell me why this is useful please? | The use of Python properties has advantages compared to the direct member access you suggest Consider the implementation ````class Foo(object): def __init__(self): self bar = ```` vs ````class Foo(object): def __init__(self): self _bar = @property def bar(self): return self _bar ```` Suppose you have `foo = Foo()` In the former case you access the member as `foo bar` This means that you can do ````print foo bar foo bar = 3 ```` I e you have no control of limiting modifications to `bar` In the latter case though - relying on the <a href="http://stackoverflow com/questions/7609508/is-it-a-convention-to-prefix-private-classes-with-underscores">convention not to access things prefixed with `_`</a> admittedly - you can do ````print foo bar ```` but ````foo bar = 3 ```` will raise an exception Moreover using <a href="https://docs python org/2/library/functions html#property" rel="nofollow">property setters</a> you can control how `bar` is modified and do validations and other cool stuff: ````class Foo(object): def __init__(self): self _bar = @property def bar(self): return self _bar @bar setter def bar(self value): if something_of_value(value): raise Whatever self _bar = value ```` |
How to find a specific file in Python I have a directory with files of the following structure ````A2ML1_A8K2U0_MutationOutput txt A4GALT_Q9NPC4_MutationOutput txt A4GNT_Q9UNA3_MutationOutput txt ```` The first few letters represent the gene the next few the Uniprot Number (a unique protein identifier) and MutationOutput is self explanatory In Python I want to execute the following line: ````f_outputfile write(mutation_directory SOMETHING line[1+i]+"_MutationOutput txt\n") ```` here `line[1+i]` correctly identifies the Uniprot ID What I need to do is correctly identify the gene name So somehow I need to quickly search over that directory find the file that has the `line[i+1]` value in it is uniprot field and then pull out the gene name I know I can list all the files in the directory then I can do `str split()` on each string and find it But is there a way I can do that smarter? Should I use a dictionary? Can I just do a quick regex search? The entire directory is about 8 116 files -- so not that many Thank you for your help! | <blockquote> What I need to do is correctly identify the gene name So somehow I need to quickly search over that directory find the file that has the line[i+1] value in it is uniprot field and then pull out the gene name </blockquote> Think about how you would do this in the she will: ````$ ls mutation_directory/*_A8K2U0_MutationOutput txt mutation_directory/A2ML1_A8K2U0_MutationOutput txt ```` Or if you are on Windows: ````D:\Somewhere> dir mutation_directory\*_A8K2U0_MutationOutput txt A2ML1_A8K2U0_MutationOutput txt ```` And you can do the exact same thing in Python with the <a href="https://docs python org/3/library/glob html" rel="nofollow">`glob`</a> module: ````>>> import glob >>> glob glob('mutation_directory/*_A8K2U0_MutationOutput txt') ['mutation_directory/A2ML1_A8K2U0_MutationOutput txt'] ```` And of course you can wrap this up in a function: ````>>> def find_gene(uniprot): pattern = 'mutation_directory/*_{}_MutationOutput txt' format(uniprot) return glob glob(pattern)[0] ```` <hr> <blockquote> But is there a way I can do that smarter? Should I use a dictionary? </blockquote> Whether that is "smarter" depends on your use pattern If you are looking up thousands of files per run it would certainly be <them>more efficient</them> to read the directory just once and use a dictionary instead of repeatedly searching But if you are planning on e g reading in an entire file anyway that is going to take orders of magnitude longer than looking it up so it probably will not matter And you know what they say about premature optimization But if you want to you can make a dictionary keyed by the Uniprot number pretty easily: ````d = {} for f in os listdir('mutation_directory'): gene uniprot suffix = f split('_') d[uniprot] = f ```` And then: ````>>> d['A8K2U0'] 'mutation_directory/A2ML1_A8K2U0_MutationOutput txt' ```` <hr> <blockquote> Can I just do a quick regex search? </blockquote> For your simple case you do not need regular expressions * More importantly what are you going to search? Either you are going to loopâin which case you might as well use `glob`âor you are going to have to build up an artificial giant string to searchâin which case you are better off just building the dictionary <hr> <sub>* In fact at least on some platforms/implementations `glob` is implemented by making a regular expression out of your simple wildcard pattern but you do not have to worry about that </sub> |
django mysql connection issue I am trying to connect Django with a Mysql db so I change my settings py file as follows: ````DATABASES = { 'default': { 'ENGINE': 'django db backends mysql' 'NAME': 'mysite' 'USER': 'root' 'PASSWORD': '1234' 'HOST': 'localhost' 'PORT': '3306' } } ```` and when I try to run the server I get this: ![enter image description here][1] so I fllowed the post <a href="http://stackoverflow com/questions/2952187/getting-error-loading-mysqldb-module-no-module-named-mysqldb-have-tried-pre">getting-error-loading-mysqldb-module-no-module-named-mysqldb</a> and now when I do : pip install MySql=python I get this error: ````$ pip install MySQL-python Collecting MySQL-python Using cached MySQL-python-1 2 5 zip Building wheels for collected packages: MySQL-python Running setup py bdist_wheel for MySQL-python Complete output from command c:\Python27\python exe -c "import setuptools;__file__='c:\\users\\rafa\\appdata\\local\\temp\\pip-build-sfr5rp\\MySQL-python\\setup py';exec(compile(open(__file__) read( ) replace('\r\n' '\n') __file__ 'exec'))" bdist_wheel -d c:\users\rafa\appdata\local\temp\tmpxuok6wpip-wheel-: running bdist_wheel running build running build_py creating build creating build\lib win32-2 7 copying _mysql_exceptions py > build\lib win32-2 7 creating build\lib win32-2 7\MySQLdb copying MySQLdb\__init__ py > build\lib win32-2 7\MySQLdb copying MySQLdb\converters py > build\lib win32-2 7\MySQLdb copying MySQLdb\connections py > build\lib win32-2 7\MySQLdb copying MySQLdb\cursors py > build\lib win32-2 7\MySQLdb copying MySQLdb\release py > build\lib win32-2 7\MySQLdb copying MySQLdb\times py > build\lib win32-2 7\MySQLdb creating build\lib win32-2 7\MySQLdb\constants copying MySQLdb\constants\__init__ py > build\lib win32-2 7\MySQLdb\constants copying MySQLdb\constants\CR py > build\lib win32-2 7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE py > build\lib win32-2 7\MySQLdb\constants copying MySQLdb\constants\ER py > build\lib win32-2 7\MySQLdb\constants copying MySQLdb\constants\FLAG py > build\lib win32-2 7\MySQLdb\constants copying MySQLdb\constants\REFRESH py > build\lib win32-2 7\MySQLdb\constants copying MySQLdb\constants\CLIENT py > build\lib win32-2 7\MySQLdb\constants running build_ext building '_mysql' extension creating build\temp win32-2 7 creating build\temp win32-2 7\Release C:\Users\Rafa\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9 0\VC\Bin\cl exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1 2 5 'final' 1) -D__version__=1 2 5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6 0 2\include" -Ic:\Python27\include -Ic:\Python27\PC /Tc_mysql c /Fobuild\temp win32-2 7\Release\_mysql obj /Zl _mysql c _mysql c(42) : fatal error C1083: Cannot open include file: 'config-win h': No such file or directory error: command 'C:\\Users\\Rafa\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9 0\\VC\\Bin\\cl exe' failed with exit status 2 ---------------------------------------- â[31m Failed building wheel for MySQL-pythonâ[0m Failed to build MySQL-python Installing collected packages: MySQL-python Running setup py install for MySQL-python Complete output from command c:\Python27\python exe -c "import setuptools tokenize;__file__='c:\\users\\rafa\\appdata\\local\\temp\\pip-build-sfr5rp\\MySQL-python\\setup py';exec(compile(getattr( tokenize 'open' open)(__file__) read() replace('\r\n' '\n') __file__ 'exec'))" install --record c:\users\rafa\appdata\local\temp\pip-p1pfvy-record\install-record txt --single-version-externally-m anaged --compile: running install running build running build_py copying MySQLdb\release py > build\lib win32-2 7\MySQLdb running build_ext building '_mysql' extension C:\Users\Rafa\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9 0\VC\Bin\cl exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1 2 5 'final' 1) -D__version__=1 2 5 "-IC:\Progra m Files (x86)\MySQL\MySQL Connector C 6 0 2\include" -Ic:\Python27\include -Ic:\Python27\PC /Tc_mysql c /Fobuild\temp win32-2 7\Release\_mysql obj /Zl _mysql c _mysql c(42) : fatal error C1083: Cannot open include file: 'config-win h': No such file or directory error: command 'C:\\Users\\Rafa\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9 0\\VC\\Bin\\cl exe' failed with exit status 2 ---------------------------------------- â[31mCommand "c:\Python27\python exe -c "import setuptools tokenize;__file__='c:\\users\\rafa\\appdata\\local\\temp\\pip-build-sfr5rp\\MySQL-python\\setup py';exec(compile(getattr(tokenize 'open' o pen)(__file__) read() replace('\r\n' '\n') __file__ 'exec'))" install --record c:\users\rafa\appdata\local\temp\pip-p1pfvy-record\install-record txt --single-version-externally-managed --compile" f ailed with error code 1 in c:\users\rafa\appdata\local\temp\pip-build-sfr5rp\MySQL-pythonâ[0m ```` I appreciatte if someone can help me | If you are on Windows I would recommend installing the Mysql-python binaries ( exe) instead using pip to compile the source files or use a wheel that matches your platform and architecture Check the link: <a href="https://pypi python org/pypi/MySQL-python/1 2 5" rel="nofollow">https://pypi python org/pypi/MySQL-python/1 2 5</a> |
Which group of people were released by the Russians to Algiers? | malgré-nous |
Python: Surpass SSL verification with urllib3 Connectiing to SSL server is throwing an error: <blockquote> error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed </blockquote> I am using this urllib3 python library for connecting to server using this method: ````urllib3 connectionpool connection_from_url(['remote_server_url'] maxsize=2) ```` How can i ignore SSL verification? Or is there another step for doing this? Thanks | You should be able to force urllib3 to use an unverified HTTPSConnection object by overriding the static `ConnectionCls` property of any ConnectionPool instance For example: ````from urllib3 connection import UnverifiedHTTPSConnection from urllib3 connectionpool import connection_from_url # Get a ConnectionPool object same as what you are doing in your question http = connection_from_url(remote_server_url maxsize=2) # Override the connection class to force the unverified HTTPSConnection class http ConnectionCls = UnverifiedHTTPSConnection # Make requests as normal are = http request( ) ```` For additional reference you can <a href="https://github com/shazow/urllib3/blob/ba06933310dbd5764e2baa53f3505cf54eae56f7/test/with_dummyserver/test_https py#L106" rel="nofollow">check some of our tests</a> which do similar overriding I have <a href="https://github com/shazow/urllib3/issues/403#issuecomment-45660345" rel="nofollow">opened an issue to improve our documentation</a> on how and when this should be done We always appreciate pull requests if you would like to contribute :) |
Combine two Pandas dataframes resample on one time column interpolate This is my first question on stackoverflow Go easy on me! I have two data sets acquired simultaneously by different acquisition systems with different sampling rates One is very regular and the other is not I would like to create a single dataframe containing both data sets using the regularly spaced timestamps (in seconds) as the reference for both The irregularly sampled data should be interpolated on the regularly spaced timestamps Here is some toy data demonstrating what I am trying to do: ````import pandas as pd import numpy as np # evenly spaced times t1 = np array([0 0 5 1 0 1 5 2 0]) y1 = t1 # unevenly spaced times t2 = np array([0 0 34 1 01 1 4 1 6 1 7 2 01]) y2 = 3*t2 df1 = pd DataFrame(data={'y1':y1 't':t1}) df2 = pd DataFrame(data={'y2':y2 't':t2}) ```` df1 and df2 look like this: ````df1: t y1 0 0 0 0 0 1 0 5 0 5 2 1 0 1 0 3 1 5 1 5 4 2 0 2 0 df2: t y2 0 0 00 0 00 1 0 34 1 02 2 1 01 3 03 3 1 40 4 20 4 1 60 4 80 5 1 70 5 10 6 2 01 6 03 ```` I am trying to merge df1 and df2 interpolating y2 on df1 t The desired result is: ````df_combined: t y1 y2 0 0 0 0 0 0 0 1 0 5 0 5 1 5 2 1 0 1 0 3 0 3 1 5 1 5 4 5 4 2 0 2 0 6 0 ```` I have been reading documentation for pandas resample as well as searching previous stackoverflow questions but have not been able to find a solution to my particular problem Any ideas? Seems like it should be easy UPDATE: I figured out one possible solution: interpolate the second series first then append to the first data frame: ````from scipy interpolate import interp1d f2 = interp1d(t2 y2 bounds_error=False) df1['y2'] = f2(df1 t) ```` which gives: ````df1: t y1 y2 0 0 0 0 0 0 0 1 0 5 0 5 1 5 2 1 0 1 0 3 0 3 1 5 1 5 4 5 4 2 0 2 0 6 0 ```` That works but I am still open to other solutions if there is a better way | It is not exactly clear to me how you are getting rid of some of the values in y2 but it seems like if there is more than one for a given timepoint you only want the first one Also it seems like your time values should be in the index I also added column labels It looks like this: ````import pandas as pd # evenly spaced times t1 = [0 0 5 1 0 1 5 2 0] y1 = t1 # unevenly spaced times t2 = [0 0 34 1 01 1 4 1 6 1 7 2 01] # round t2 values to the nearest half new_t2 = [round(num * 2)/2 for num in t2] # set y2 values y2 = [3*z for z in new_t2] # eliminate entries that have the same index value for x in range(1 len(new_t2) -1): if new_t2[x] == new_t2[x-1]: new_t2 delete(x) y2 delete(x) ser1 = pd Series(y1 index=t1) ser2 = pd Series(y2 index=new_t2) df = pd concat((ser1 ser2) axis=1) df columns = ('Y1' 'Y2') print df ```` This prints: ```` Y1 Y2 0 0 0 0 0 0 0 5 0 5 1 5 1 0 1 0 3 0 1 5 1 5 4 5 1 5 1 5 4 5 1 5 1 5 4 5 2 0 2 0 6 0 ```` |
How to trim white space in MySQLdb using python I have a web form taking user data and putting it into a mysql database I need to trim leading and trailing blanks/spaces I currently am utilizing the strip() method but it only trims them for the fields NOT for the mysql database My code is: ````first_name = first_name strip() last_name = last_name strip() ```` so on and so forth It strips it perfectly fine for the webpage but not when it is entered into the SQL database The spaces still exist How do I remove them? EDIT: ```` db = MySQLdb connect("localhost" "user" "pass" "db_name") cursor = db cursor() cursor execute("Select * FROM registrants") cursor execute("INSERT INTO registrants VALUES( " "'" first_name "'" " " "'" last_name "'" ");") db commit() db close() ```` | I think you should be passing the values into the INSERT differently ````cursor execute("INSERT INTO registrants (fname lname) VALUES (%s %s)" (first_name last_name) ```` I am not sure if that is where you are getting the whitespace but it opens you up to sql injection so it is bad form to put the variables straight into the query |
Python - replace multiline string in a file I am writing a script which finds in a file a few lines of text <strong>I wonder how to replace exactly that text with other given</strong> (new string might be shorter or longer) I am using `re compile()` to create a multiple line pattern then looking for any match in a file I do like this: ````for match in pattern finditer(text_in_file) #if it would be possible I wish to change #text in a file here by (probably) replacing match group(0) ```` <strong>Is it possible to accomplish in this way</strong> (if yes then how to do it in the easiest way?) or my approach is wrong or hard to do it right (if yes then how to do it right?) | Use `pattern sub('replacement text' text_in_file)` to replace matches You can use back references in the replacement pattern as needed It does not matter if the string is shorter or longer; the method returns a <them>new</them> string value with the replacements made If the text came from a file you will need to write back the text to that file to replace the contents You could use the <a href="http://docs python org/2/library/fileinput html" rel="nofollow">`fileinput` module</a> if you need to make the replacement in-place; the module takes care of moving the original file aside and write a new file in it is place |
Python-mode in Vim not autoindenting on newline I have the python-mode vim plugin installed and it checks syntax correctly but it does not automatically indent code when I start a new line I am not sure what might be preventing this so here is my vimrc vimrc: ````"" Pathogen settings filetype off call pathogen#infect() call pathogen#helptags() filetype plugin on set nocompatible " Change leader let mapleader = " " " Set color scheme colorscheme badwolf " Code settings syntax on set textwidth=100 set colorcolumn=100 set tabstop=8 set softtabstop=4 set shiftwidth=4 set autoindent set expandtab set nowrap set textwidth=0 wrapmargin=0 set relativenumber set number set ruler " Make it so jk returns to normal mode inoremap jk <esc> " Easy editing/sourcing of vimrc nnoremap <leader>ev :vsplit $MYVIMRC<cr> nnoremap <leader>sv :source $MYVIMRC<cr> " Useful shortcuts nnoremap <leader>w :w<cr> nnoremap <leader>q :q<cr> nnoremap <leader><space> bi<space><esc>ea<space><esc> " Plugin shortcuts nnoremap <c-n> :NERDTreeToggle<cr> nnoremap <c-k> <c-w>k nnoremap <c-j> <c-w>j nnoremap <c-l> <c-w>l nnoremap <c-h> <c-w>h nnoremap <leader>l :TagbarToggle<cr> nnoremap <leader>td <Plug>TaskList nnoremap <leader>g :GundoToggle<cr> " Vimscript file settings ---------- {{{ augroup filetype_vim autocmd! autocmd FileType vim setlocal foldmethod=marker augroup END " }}} " Python file settings ---------- {{{ augroup filetype_python autocmd! autocmd FileType python setlocal foldmethod=indent autocmd FileType python set foldlevel=99 " }}} ```` Plugins I have installed: ````ack git minibufexpl vim snipmate tagbar command-t gundo nerdtree supertab tasklist fugitive makegreen python-mode surround vim-airline ```` | Change `filetype plugin on` to `filetype indent plugin on` |
How to get match result by given range using regular expression? I am stucking with my code to get all return match by given range My data sample is: ```` comment 0 [intj74 you are whipping people is a grea 1 [home near kcil2 meniaga who intj47 a l 2 [thematic budget kasi smooth sweep] 3 [budget 2 intj69 most people think of e ```` I want to get the result as: (where the given range is intj1 to intj75) ```` comment 0 [intj74] 1 [intj47] 2 [nan] 3 [intj69] ```` My code is: ````df comment = df comment apply(lambda x: [t for t in x if t=='intj74']) df ix[df comment apply(len) == 0 'comment'] = [[np nan]] ```` I am not sure how to use regular expression to find the range for t=='range' Or any other idea to do this? Thanks in advance Pandas Python Newbie | you could replace `[t for t in x if t=='intj74']` with e g ````[t for t in x if re match('intj[0-9]+$' t)] ```` or even ````[t for t in x if re match('intj[0-9]+$' t)] or [np nan] ```` which would also handle the case if there are no matches (so that one would not need to check for that explicitly using `df ix[df comment apply(len) == 0 'comment'] = [[np nan]]`) The "trick" here is that an empty list evaluates to `False` so that the `or` in that case returns its right operand |
python mocking third party modules i am trying to test some classes that process tweets I Am using sixohsix twitter to deal with Twitter API I have a class that acts as a facade for the Twitter classes and my idea was to mock the actual sixohsix classes to simulate the arrival of tweets by randomly generate new tweets or retrieving them from a database My facade looks something like: ````from twitter import TwitterStream class TwitterFacade(object): def __init__(self dev='soom'): self _auth = OAuth(dev_keys["ACCESS_TOKEN"] dev_keys["ACCESS_SECRET"] dev_keys["CONSUMER_KEY"] dev_keys["CONSUMER_SECRET"]) def tweets(self callback=None users=[] terms=[] locations=[] count=5): t = TwitterStream(auth=self _auth) args = {} if users: args['follow'] = " " join(users) if terms: args['track'] = " " join(terms) if locations: args['locations'] = " " join(str(l) for l in locations) # this controls the general loop it re-enters if there was an exception # otherwise the for loop should take care of looping trough the tweets cannot = count while cannot > 0: try: iterator = t statuses filter(**args) for twit in iterator: if twit get('text'): callback(twit) cannot -= 1 if cannot == 0: iterator close() break except Exception as e: print e #some error handling code ```` So if in an unittest i want to test some module that does something with the tweets how would i mock the TwitterStream class ? I have tried using Mock: ````from mock import patch from twitter_facade import TwitterFacade class TwitterStreamProxy(object): def __init__(self): pass #some code for dealing with statuses filter( ) @patch('twitter TwitterStream' TwitterStreamProxy()) def test_filter_on_tweets(): facade = TwitterFacade() facade tweets(somemethod [] ['term1' 'term2'] [] count=50) def somemethod(tweet): #some logic in here ```` This is not working twitter api is still been called I would have expected that sincen i did not add any code to the mock class i would have gotten an error or something but sixohsix twitter classes where called instead | You need to patch the <them>local object</them>; your module has a reference to the `TwitterStream` object patch that: ````@patch('yourmodule TwitterStream' TwitterStreamProxy()) ```` See the mock <a href="http://www voidspace org uk/python/mock/patch html#where-to-patch" rel="nofollow">Where to Patch</a> documentation |
Python TCP Sockets Not Working Properly Not too long ago I asked <a href="http://stackoverflow com/questions/31366089/twisted-framework-server-making-connections-as-a-client/31376742?noredirect=1#comment51016299_31376742">this</a> question I was very surprised that no one came up with any answers so I am pretty sure my issue is fairly rare Yesterday as I was self-diagnosing the issue I began connecting the dots My Twisted TCP server will not work IDLE fails at startup because of a "Socket Error" and returns the message: "IDLE Subprocess: socket error: No connection could be made because the target machine actively refused it" and I get this same error when I try running a (local) TCP client connecting to a (local) TCP server So I came to the conclusion Yesterday that these were not just individual issues but rather a larger issue with creating and running TCP endpoints using Python Sockets Keep in mind UDP servers and clients that I run both on a local network and locally work so I do not think it is a problem with the Socket module as a whole but just the TCP side of things Some info on my computer: Windows 64bit running Python 2 7 9 (for some reason 32bit) Laptop connected to a network via (built in) Wireless card ISP is Comcast (if it makes a difference) and the Router/Modem (it is an all-in-one) is a TechniColor provided by Comcast (again if it makes a difference) Things I have tried: - Reset my /etc/hosts file - Reinstalled Python 2 months ago (while trying to troubleshoot) - Turned off all Firewall (I only have 1) - No antivirus other than Microsoft Security Essentials - The issue was still present when I still had Bitdefender installed but I installed it to be sure I also went through a <a href="http://pastebin com/PPHxH9zU" rel="nofollow">small troubleshooting session</a> on the previous thread I mentioned earlier The biggest error I get when using TCP Sockets is: `socket error: [Errno 10061] No connection could be made because the target machine actively refused it` So anyone have an idea as to what is wrong here? Thanks <strong>EDIT:</strong> Looks like I missed something the port is 45002 which is out of the range of default Windows ports and I am pretty sure nothing uses it as I have been able to run a UDP server on that port with good results The port is also port forwarded just in case | This type of error usually happens when the initial <a href="https://en wikipedia org/wiki/SYN_%28TCP%29#Connection_establishment" rel="nofollow">TCP SYN</a> is replied to with a RST (reset) Unless something is seriously wrong with your OS `socket` or Twisted that message must have occurred on the wire - someone must have sent it and that is the person to blame! :) My advice is running <a href="https://www wireshark org" rel="nofollow">wireshark</a> on your computer in order to figure out where the RST is coming from If it comes from another device inside or outside your network you must investigate that device If it comes from your computer and you <them>do</them> have a socket listening at that address the blame rests on your OS (or some program that meddles with it such as a firewall antivirus or virus) If there is no RST message something is wrong with your application (or Twisted or python or your OS) and you must investigate what caused the exception to be raised (check your stack trace) |
Pandas str contains regex I am trying to learn Pandas and MatPlotLib As a challenge I decided it would be fun to try and graph the results of profession type based on the comments My thought process is to get comments find a small dataset of professions and check the comment against the dataset I am sure there has to be a better way still learning <strong>Is there a difference in how Pandas regex matches compared to regular regex results? `0` should be true should it not?</strong> ````#! /usr/bin/python from __future__ import print_function from __future__ import division from __future__ import absolute_import import pandas as pd import matplotlib pyplot as plt import praw are = praw Reddit(user_agent='my_cool_application') submissions = r get_submission(submission_id = '2owaba') s = pd Series(submissions comments) pattern = r'Programmer' print (s str contains(pattern)) print (s) ```` Output is not as expected ````$ python reddit py 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 NaN 9 NaN 10 NaN 11 NaN 12 NaN 13 NaN 14 NaN 57 NaN 58 NaN 59 NaN 60 NaN 61 NaN 62 NaN 63 NaN 64 NaN 65 NaN 66 NaN 67 NaN 68 NaN 69 NaN 70 NaN 71 NaN Length: 72 dtype: float64 0 Programmer/Project Lead for a railroad company 1 I deliver pizza part time while I go to colleg 2 Graduate student (molecular biologist) cat mom 3 Systems Analyst at a big boring corporation 4 I work in IT I wear many hats at my (small) 5 I am a professional desk jobber 6 medical pot producer pretty much your typic 7 Research tech for the federal govt Water leve 8 Karate instructor 9 I own a Vape shop and an E-Liquid manufacturin 10 Guidance counselor If only my students knew 11 Graduate student and chemist 12 Regulatory Affairs for a medical device manufa 13 restaurant manager (for the moment looking to 14 Logistics and technician manager for a radon m 57 Technical Support for a big credit card proces 58 Class action settlement administration Been t 59 IT Consultant here 8) Lot's of IT folk at EF i 60 This will be my first year staying in the Back 61 Research assistant in the epidemiology departm 62 IT undergrad and this will be my second time a 63 Commercial construction foreman at a tiny company 64 I am actually a web developer for a company tha 65 Install cameras tv's and phone systems 66 Animation/design/anything creative Graduated 67 Career bartender 68 I work in the Traveling Hospitality Business f 69 Assisstant Manager at a major retail chain t 70 Barista :) 71 Hi I am Pasquale Rotella (CEO Insomniac Event Length: 72 dtype: object ```` | Your series contains `praw objects Comment` objects not strings Extracting body should give you what you want: ````s = pd Series(comment body for comment in submissions comments) ```` |
Who created the account of Jesus? | author of the Mark Gospel |
Who had dominated CARICOM? | null |
How to keep a wxpython frame always on screen? I made a music player Once the main frame is iconized another frame appears and once that frame is iconized a smaller frame appears Is there a way to get the last small frame to always be on the screen? now if I click outside of the frame it disappears until I click on it in the taskbar I want it to always be on screen until the user clicks a button to open up the frame before the final small frame | To make the dialog stay in the foreground until the user interacts with it use the `ShowModal()` method: <blockquote> There are two types of dialogs Modal and modeless Modal dialog does not allow a user to work with the rest of the application until it is destroyed Modal dialogs are created with the ShowModal() method Dialogs are modeless when called with Show() </blockquote> <a href="http://wiki wxpython org/AnotherTutorial/" rel="nofollow">http://wiki wxpython org/AnotherTutorial/</a> If you just want the window to stay in the foreground you can use the `setFocus()` method on the dialog because it is a child of the `Window` class: ````SetFocus(self) ```` <blockquote> Set's the focus to this window allowing it to receive keyboard input </blockquote> <a href="http://wxpython org/docs/api/wx Window-class html#SetFocus" rel="nofollow">http://wxpython org/docs/api/wx Window-class html#SetFocus</a> |
Python regex to match and remove a specific pattern I have a file with the following grammar: ````<whitespace_sequence><string><whitespace_sequence><--More-><whitespace_sequence><string_sequence><newline> ```` Using Python (2 4) I would like to remove the sequence: ```` "<whitespace_sequence><--More-><whitespace_sequence>" from the above grammar ```` I am using the following regex pattern: ````x = re compile("(\s+)("--More--")(\s+)") ```` but it is not matching the sequence that I need to remove | It looks like the problem with your regex is the double quotes Without them it works fine: ````>>> sample = ' string --More-- anotherstring \n' >>> import re >>> re search(r'(\s+)(--More--)(\s+)' sample) groups() (' ' '--More--' ' ') ```` FWIW here is a great resource for developing a regex directly from a sample string: <a href="http://txt2re com/" rel="nofollow">http://txt2re com/</a> Another good resource to learn more about regular expressions is: <a href="http://www regular-expressions info/" rel="nofollow">http://www regular-expressions info/</a> |
Calculation in Kivy with inputs from several widgets (and output to a different one) I am trying to build an app with kivy that asks for some numbers and then returns a calculation but I need the input numbers to be provided on different widgets I have been searching for a way to do that and it seems that it can be done with ObjectProperty() or NumericProperty() but I cannot figure the correct way For a barebone example (not working obviously) below is the code for an app where two numbers are introduced and it calculates the sum The main py is ```` from kivy app import App from kivy uix boxlayout import BoxLayout class SumRoot(BoxLayout): pass class FirstInput(BoxLayout): pass class SecondInput(BoxLayout): pass class OutputSlide(BoxLayout): def sum_of_inputs(self): self resultado text = str(float(self first_input text)+float(self second_input text)) class SumApp(App): pass if __name__ == '__main__': SumApp() run() ```` and the sum kv files is ```` SumRoot: <SumRoot>: carousel: carousel first_slide: first_slide second_slide: second_slide third_slide: third_slide Carousel: id: carousel FirstInput: id: first_slide SecondInput: id: second_slide OutputSlide: id: third_slide <FirstInput>: orientation: "vertical" first: first_input TextInput: id: first_input Button: text: "Next" on_release: app root carousel load_slide(app root second_slide) <SecondInput>: orientation: "vertical" second: second_input TextInput: id: second_input Button: text: "Sum" on_press: root sum_of_inputs() on_release: app root carousel load_slide(app root third_slide) <OutputSlide>: orientation: "vertical" result: result_output Label: id: result_output ```` The intended behavior is that when one presses the "sum" button it calculates the sum goes to the next slide and displays the sum All suggestions are welcomed | 1) Pass references of the inputs to the `OutputSlide` which does calculations: ````OutputSlide: id: third_slide first_input: first_slide first second_input: second_slide second ```` 2) Add object properties in <them>py</them> file which will hold them: ````from kivy properties import ObjectProperty class OutputSlide(BoxLayout): first_input = ObjectProperty() second_input = ObjectProperty() result = ObjectProperty() # this one aswell do not leave bare ids ```` 3) Calculate the result `on_press` correctly: ````<SecondInput>: on_press: app root third_slide sum_of_inputs() ```` Additionally fix naming bugs in `OutputScreen` |
Python Tastypie pass params to GET request I need to pass filters to the api via XML and not via GET query params I have doing this: ````curl --dump-header - \ -H "Content-Type: application/xml" -X GET \ --data '<object><title>Hello XML</title><date>200-01-01</date></object>' \ http://x x x x/api/entry/ ```` which I want to be the same as: `http://x x x x/api/entry/?format=xml&title=Hello XML&date=200-01-01` but `--data` gets ignored for GET request So my question is how to I pass XML to a GET request using tastypie? Thanks in advance for the help <h1>EDIT</h1> I also should note that in the XML data I want to be able to set the limit and offset along with filter | Your best bet is probably to override <a href="http://django-tastypie readthedocs org/en/latest/resources html#dispatch-list" rel="nofollow">`Resource dispatch_list()`</a> to parse the filters out of the request body and bring them into the keyword arguments Something like this: ````def dispatch_list(self request **kwargs): body_filters = parse_xml_get_data(request) # <- MAGIC: returns a dict() kwargs update(body_filters) return super(MyResource self) dispatch_list(request **kwargs) ```` When you are subverting the framework this deeply I would highly recommend reading through TastyPie's <a href="http://django-tastypie readthedocs org/en/latest/resources html#flow-through-the-request-response-cycle" rel="nofollow">request-response cycle</a> and <a href="https://github com/toastdriven/django-tastypie/blob/master/tastypie/resources py" rel="nofollow">resources py</a> so you can completely understand what you are doing Also for writing your `parse_xml_get_data()` function there <a href="https://docs djangoproject com/en/1 4/ref/request-response/#django http HttpRequest body" rel="nofollow">you will need to get at the raw request body</a> |
TA-Lib in Ctypes help calling functions So for the past three days I have been trying to figure out getting <a href="http://ta-lib org/d_api/d_api html" rel="nofollow">TA-Lib</a> to work with python This is the source I compiled into a dylib (mac version of a so) and have been calling it from a python script coded as follows: ````from ctypes import * import numpy c_float_p = POINTER(c_float) data = numpy array([1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]) data = data astype(numpy float32) data_p = data ctypes data_as(c_float_p) dylib = CDLL('libta_lib dylib') value = dylib TA_S_SMA(c_int(0) c_int(data size - 1) data_p 0 19 data_p) ```` Printing value returns 2 no matter what the array values are I cannot change the fourth argument of TA_S_SMA from 0 or 1 or else I get a python 138 error followed by a python crash Can anyone explain to me the proper way to call this function? My C skills are limited (read 0) Useful links: - <a href="http://tadoc org/indicator/SMA htm" rel="nofollow">SMA function source code</a> - <a href="http://stackoverflow com/questions/5081875/ctypes-beginner">Tut I used as a guide</a> - <a href="http://prdownloads sourceforge net/ta-lib/ta-lib-0 4 0-src tar gz" rel="nofollow">TA-Lib source download link</a> Thanks! | I had the same problem a couple of weeks ago and I found these <a href="http://blog mediafederation com/andy-hawkins/getting-ta-lib-to-work-with-python-2-6-swig-interface/" rel="nofollow">instructions</a> Now they are not using ctypes but it works better in my opinion SWIG will do all the wrapping for you A Couple of things to watch out for When you get to the `Single:` `Multi:` sections if you do not know which on start with the Multi and if that does not work go to the single A little further down you will see he is replacing Python 2 3 to Python 2 6 I was using python 2 7 and just replaced the 2 6 with 2 7 and it worked I am not sure if this will work for higher versions of python but worth a shot if that is what you are using Hope it helps |
How many of the Saints reject the Protestants? | null |
Django - Convert value get from HTML select in POST request back to number before validate ModelForm In my model I have a field which is populated from 'choices' like following: ````PRIORITY = ( (0 'Low') (1 'Medium') (2 'High') ) priority = models IntegerField(choices=PRIORITY default=0) ```` So in my DB it will be stored as 0 1 or 2 This <strong>priority</strong> field will be displayed by HTML <strong>select</strong> tag I am using <strong>instance get__priority__display</strong> to get the display of the <strong>priority</strong> field Now I have a model form that will take this <strong>priority</strong>: ````class NewItemForm(forms ModelForm): class Meta: model = Item fields = ['priority'] ```` In my view when user click a button my function in <strong>views py</strong> will take the value selected by user and store it in a new item in database But my problem now is that because the value I got from POST request is <strong>Low Medium</strong> or <strong>High</strong> not <strong>0 1 or 2</strong> so when I use <strong>is_valid()</strong> it said my form is not valid and I can not create the new item and store it in database Is there any way I can convert those POST data from HTML select tag back to number as in my <strong>choices</strong> and validate my ModelForm after that? Thanks | Well you should not be attempting to create the select element manually whether with `get_priority_display` or not You have a Django form; one of its two responsibilities[*] is to display the field So: ````{{ form priority }} ```` will give you the select with its internal and display values correctly set And in the view ````form cleaned_data['priority'] ```` will get you the correct value for that field [*] along with validation |
Subsets and Splits