input_text
stringlengths
1
40.1k
target_text
stringlengths
1
29.4k
How to deploy a bottle webapp in production? I wrote a little bottle web application played around with setup py and I am ready to deploy I had two questions: - How do I deploy this new web app in production? Do I need a a webserver or reverse proxy? Can my `main py` be run as a service? How is this typically done? - My web app uses a mongodb backend Is there a way to package that with my application or to require it / look for it / alert the user when the installer runs? How is this typically done?
<a href="https://www pythonanywhere com/batteries_included/" rel="nofollow">Pythonanywhere</a> allows you for free to test/deploy a `Bottle` app with `Pymongo` driver This is one of the webhostings which is python-deployers friendly If you need something for a serious trafic then you have to consider a paid programm or your own (virtual/dedicated) hosted server
Summation of a list using eval I have a list like this ````yy = ['A1' 'B1' 'C1'] ```` with the values for `A1` `B1` and `C1` in a dict like this ````ff = { 'A1': 10 'B1': 20 'C1': 30 } ```` Now I want to do sum of the list with values from `ff` This is what I tried to do ````p = "sum(lst)" eval(p {'lst': yy} ff) ```` But I get `TypeError: unsupported operand type(s) for : 'int' and 'str'` During debugging I found out that if I do like this `p = "sum([A1 B1 C1])"` and eval It works Not sure why this happens? Full code: ````ff = { 'A1': 10 'B1': 20 'C1': 30 } yy = ['A1' 'B1' 'C1'] p = "sum(lst)" eval(p {'lst': yy} ff) ```` I know `eval`'s consequences I filter everything before it reaches `eval`
Do you have to use <a href="http://stackoverflow com/questions/1832940/is-using-eval-in-python-a-bad-practice">eval</a>? why not use `sum()`; ````yy = ['A1' 'B1' 'C1'] ff = { 'A1': 10 'B1': 20 'C1': 30 } print sum([ff[key] for key in yy]) ```` if you really need to use `eval` here how to do it: ````print eval('+' join(str(ff[key]) for key in yy)) # or for short print eval("+" join(yy) globals=ff) # or the way you are doing print eval("sum(lst)" {'lst': [ff[key] for key in yy]}) ```` The reason you were getting a `TypeError` is because `"sum(lst)"` is essently `sum(['A1' 'B1' 'C1'])` which Python does not know how to handle By changing `lst` to `[ff[key] for key in yy]` we are making a new list that is of the number referenced(by key) by `yy` in `ff` I see your comment: <blockquote> I am using eval to parse Excel formulas like this one '=SUM(AY92:BI92)/SUM(AL92:AX92)' where I first expand the list from Ay92 to BI92 and then do a sum using eval </blockquote> Why not get the values of `AY92:BI92` into a list and the values of `AL92:AX92` into a second list and them use `sum(lst1)/sum(lst2)`? Eval is nasty if this excel file contains malicious code inside the cell it will be run
Django Signal vs Python Threading Its hard to explain what I am trying to achieve Please have the patience to go through this And let me know if you have any questions Say I have a Django project with two applications which I would like to have them coupled loosely One of the application is 'Jobs' and other is 'Notifications' Now I want to create notifications when the Job instance is updated So I was thinking of using Django Signals But some of the reservations I have are: - If I use the build-in signals like post_save I could validate the conditions on job instance and generate notification(which is good) But the problem comes when in the same view logic I call the save method on job instance multiple times This would generate notifications multiple times Else I use the home made signals I would be required to call it manually which is not good for loose coupling - Moreover the signals are not asynchronous so I would have to wait for the notification generation to complete before I can proceed Can anyone please suggest a good implementation strategy using Signals One solution I was looking into was Python Threading which seems to take care of the asynchronous problem But are there any other consequences of using Threading
I would suggest you to use django-celery with RabbitMQ You can add the notifications thing in the tasks of celery and have your view start the task queque Have a look I hope it will be helpful to you
Django Model Relationship with Multiple Classes Sure the answer's out there but I have struggled to find the search terms! This is my first Django project and I cannot seem to come up with a logical model structure ````Domain->* Region->* [Domain]Network ```` Within a <strong>Domain</strong> there are various <strong>Regions</strong> and each region can have a number of <strong>Networks</strong> (that should only be of the underlying <strong>Domain</strong> specific model as each <strong>Domain</strong> has a specific <strong>Network</strong> layout) Each <strong>Network</strong> has it is own specific fields (although also share some common so could inherit somehow?) More <strong>Domains</strong> (and so <strong>Networks</strong>) will be created in the future so should be able to scale <strong>Regions</strong> may overlap (so Region2 may also be in DomainABC) but again Domain-specific Networks will be applied <h2>Example:</h2> If the Domain is ABC you should only be able to associate ABCNetworks to Regions within that domain Likewise the XYZ Domain should contain regions that can only have XYZNetworks <blockquote> <strong>DomainXYZ:</strong> - Region1 - XYZNetwork1 - XYZNetwork2 - XYZNetwork3 - Region2 - XYZNetwork4 - XYZNetwork5 - Region3 - XYZNetwork6 - XYZNetwork7 <strong>DomainABC:</strong> - Region101 - ABCNetwork1 - ABCNetwork2 - ABCNetwork3 - Region102 - ABCNetwork4 - ABCNetwork5 - Region103 - ABCNetwork6 - ABCNetwork7 </blockquote> Maybe a drop down when creating the Domain to select the Network model (OneToOne?) that then forces the Region to only be able to create [Domain]Networks? Or just a complete rethink!? <h2>Code:</h2> ````class Domain(models Model): domain_name = models CharField(max_length=20) def __str__(self): return self domain_name class Region(models Model): domain = models ForeignKey(Domain on_delete=models CASCADE) region_name = models CharField(max_length=20) def __str__(self): return self region_name class XYZNetwork(models Model): region = models ForeignKey(Region on_delete=models CASCADE) network_name = models CharField(max_length=3) network_data = models GenericIPAddressField() useless_number = models IntegerField() network_secondary = models GenericIPAddressField() crazy_network = models GenericIPAddressField() def __str__(self): return self network_name class ABCNetwork(models Model): region = models ForeignKey(Region on_delete=models CASCADE) network_name = models CharField(max_length=3) network_data = models GenericIPAddressField() def __str__(self): return self network_name ````
If I understand your question I would just add some validation to your `Domain`s See: <a href="https://docs djangoproject com/en/dev/ref/forms/validation/" rel="nofollow">https://docs djangoproject com/en/dev/ref/forms/validation/</a>
Error when passing 2 variables in template django I have the following view ````@login_required def myview(request): my_strings = ['0' '1' '2' '3' '4' '5'] var ='12' return render(request 'index html' {'my_strings':my_strings} {'var': var }) ```` But when I try to display `{{ my_strings|random }}` and `{{ var }}` variables in index html template I get an error message: <blockquote> 'dict' object has no attribute 'push' </blockquote> Is there any way to solve this?
You need to pass all the values in the same dict ````return render(request 'index html' {'my_strings': my_strings 'var': var }) ````
Pygame mixer clicking sound Okay here is my code: ````import pygame pygame init() pygame mixer init() track1 = pygame mixer Sound("boink ogg") track1 play() ```` So I am using a mac and I used homebrew to download the pygame 64 bit version Everything works well but when I try to make sounds using the mixer all that I hear is a clicking sound Has anyone experienced this in the past that may be able to help? Also I have tried this with many different ogg files so it is not something wrong with the sound file
Can you try this? ````import pygame import time pygame mixer init(frequency=22050 size=-16 channels=2 buffer=4096) song = pygame mixer Sound('boink ogg') song play() time sleep(song get_length()) ````
Querying GAE Datastore returns property types instead of values I have stored data in the gae datastore but when I query the data and reference the properties I seem to be getting a reference to the object rather than the value of the attribute ````class ClassDefinitions(db Model): class_name = db StringProperty class_definition = db TextProperty class FlexEntityAdminHandler(webapp RequestHandler): def get(self): query = db GqlQuery("SELECT * FROM ClassDefinitions") definitions = query fetch(1000 0) for definition in definitions: logging info("Name: %s" definition class_name) logging info("Def: %s" definition class_definition) ```` When I reference definition class_name I get: ````<class 'google appengine ext db StringProperty'&gt; ```` Instead of the value that I stored I know that it is getting stored because each time I add a new entry the number of results from the query increases by 1 Does anyone know what I am doing wrong?
When creating the model you need to create actual instances of the property type classes: ````class ClassDefinitions(db Model): class_name = db StringProperty() class_definition = db TextProperty() ```` (Note the `()` )
I am using a straight forward regex pattern ('\s+') that is not ignoring white space I am not sure why this regex pattern ('\s+') is not ignoring whitespace: the code below searches all of the txt and log files in a directory and returns the matched string entered by the user It takes the string and converts it into hex and ASCII then concurrently searches all txt and log files for the string hex and ASCII match I entered the values of a converted string in 3 different txt files: string in one hex in another and ascii in the third Initially all files were matched However I added the `regex search(re sub(r'\s+' '' line))` below in the second major if statement and went into the txt file where the string converted to ASCII was entered and I added a space in the string I then attempted another search with the same string and only found two matches: string and hex The search "ignoring whitespace" did not match the altered ASCII string Am I overlooking or doing something wrong? Enter string: Rozelle07 (matched) Hex conversion: 526f7a656c6c653037 (matched) ascii conversion: 821111221011081081014855 (matched) Altered ascii string: 8211112210110810810148 55 (regexp did not match when I tried this) ```` print " Directory to be searched: c:\Python27 " directory = os path join("c:\\" "SQA_log") userstring = raw_input("Enter a string name to search: ") userStrHEX = userstring encode('hex') userStrASCII = '' join(str(ord(char)) for char in userstring) regex = re compile(r"(%s|%s|%s)" % ( re escape( userstring ) re escape( userStrHEX ) re escape( userStrASCII ))) choice = raw_input("Type 1: search with respect to whitespace Type 2: search ignoring whitespace: ") if choice == '1': for root dirname files in os walk(directory): for file in files: if file endswith(" log") or file endswith(" txt"): f=open(os path join(root file)) for i line in enumerate(f readlines()): result = regex search(line) if regex search(line): print " " print "Line: " str(i) print "File: " os path join(root file) print "String Type: " result group() print " " f close() re purge() if choice == '2': for root dirname files in os walk(directory): for file in files: if file endswith(" log") or file endswith(" txt"): f=open(os path join(root file)) for i line in enumerate(f readlines()): result = regex search(re sub(r'\s+' '' line)) if regex search(line): print " " print "Line: " str(i) print "File: " os path join(root file) print "String Type: " result group() print " " f close() ````
I have not tested it myself but I think <them>if regex search(line):</them> should be <them>if result:</them>
How to compute smallest non-zero eigenvalue Given a positive semi-definite matrix M I would like to find its smallest non-zero eigenvalue In python this code looks tempting ````import numpy as np (w v) = np linalg eigh(M) minw = np amin(w) if (np isclose(minw 0) and minw &gt; 0): print M minw ```` Here is an example small input matrix ````[ 6 2 -4 -2] [ 2 6 0 -6] [-4 0 6 0] [-2 -6 0 6] ```` Unfortunately if you try this you will get `8 90238403828e-16` I do not know in general how to tell if very small numbers are meant to be zero or not How can you find the smallest non-zero eigenvalue of a matrix (and be sure it really is non-zero)?
It is likely a floating problem in the function The solution will depend on the severity of the problem You can try loop the results and look for the minimum using for example the function (<a href="http://docs scipy org/doc/numpy-dev/reference/generated/numpy isclose html" rel="nofollow">numpy</a>): ```` np isclose(a b) ```` giving you similarity between two values within a tolerance It is not a clean solution but it is generally considered a safe comparison As for the "eigh" code itself perhaps some issue with convergence but I really cannot tell
Python if statements not reading correctly So I am working on a text based game and I have a shop where you can sell ores I have an if statement checking if the amount of ore you want to sell is greater than the amount you have No matter what number I type in it says I do not have enough ````copore = 100 #testing op = raw_input(p) if op lower() == "copper": print""" You have %r copper ore How much would you like to sell? """ % copore op = raw_input(p) if op lower() &gt; copore: print""" You do not have that much copper ore You have %r copper ore """ % copore menu() elif op lower() <= copore: copore = copore - op gold = gold (op * 2) print""" You sell your copper ore for 2 gold each You now have %r copper ore and %r gold """ % (copore gold) menu() else: print""" That is not a valid number """ menu() ```` This could very easily be my own stupidity but I figured it could not hurt to get someone else to look at it Thank you
When you want a number from input text you need to wrap it in the conversion function like `int(op)`
How to assign scipy sparse matrix to NumPy array via indexing? When I try to assign a <a href="http://docs scipy org/doc/scipy-0 14 0/reference/sparse html" rel="nofollow">`scipy sparse`</a> matrix `s` (any of the available sparse types) to a NumPy array `a` like this: ````a[:] = s ```` I get a `TypeError`: <blockquote> TypeError: float() argument must be a string or a number </blockquote> Is there a way to get around this? I know about the `todense()` and `toarray()` methods but I would really like to avoid the unnecessary copy and I would prefer to use the same code for both NumPy arrays and SciPy sparse matrices For now I am not concerned with getting the values from the sparse matrix being inefficient Is there probably some kind of wrapper around sparse matrices that works with NumPy indexing assignment? If not any advice how I could build such a thing by myself? Is there a different sparse array library that cooperates with NumPy in this situation? <strong>UPDATE:</strong> I poked around in the NumPy sources and searching for the error message string I think I found the section where the indexing assignment happens in <a href="https://github com/numpy/numpy/blob/master/numpy/core/src/multiarray/arraytypes c src#L187" rel="nofollow">`numpy/core/src/multiarray/arraytypes c src` around line 187</a> in the function `@TYPE@_setitem()` I still do not really get it but at some point the `float()` function seems to be called (if `a` is a floating-point array) So I tried to monkey-patch one of the SciPy sparse matrix classes to allow this function to be called: ````import scipy s = scipy sparse dok_matrix((5 1)) def myfloat(self): assert self shape == (1 1) return self[0 0] scipy sparse dok dok_matrix __float__ = myfloat a[:] = s ```` Sadly this does not work because `float()` is called on the whole sparse matrix and not on the individual items thereof So I guess my new question is: how can I further change the sparse matrix class to make NumPy iterate over all the items and call `float()` on each of them? <strong>ANOTHER UPDATE:</strong> I found a sparse array module on Github (<a href="https://github com/FRidh/sparse" rel="nofollow">https://github com/FRidh/sparse</a>) which allows assignment to a NumPy array Sadly the features of the module are quite limited (e g slicing does not really work yet) but it might help to understand how assigning to NumPy arrays can be achieved I will investigate that further <strong>YET ANOTHER UPDATE:</strong> I did some more digging and found that a more interesting source file is probably <a href="https://github com/numpy/numpy/blob/master/numpy/core/src/multiarray/ctors c" rel="nofollow">`numpy/core/src/multiarray/ctors c`</a> I suspect that the function `PySequence_Check()` (<a href="https://docs python org/3 4/c-api/sequence html#c PySequence_Check" rel="nofollow">docs</a>/<a href="https://github com/python/cpython/blob/c71e8b81f1f4d349d1a24a6fe162cbbecedff8f0/Objects/abstract c#L1370" rel="nofollow">code</a>) is called sometime during the assignment The simple sparse array class from <a href="https://github com/FRidh/sparse" rel="nofollow">https://github com/FRidh/sparse</a> passes the test but it looks like the sparse matrix classes from SciPy do not (although in my opinion they are sequences) They get checked for `__array_struct__` `__array_interface__` and `__array__` and then it is somehow decided that they are not sequences The attributes `__getitem__` and `__len__` (which all the sparse array classes have!) are not checked This leads me to yet another question: How can I manipulate the sparse matrix classes (or objects thereof) in a way that they pass `PySequence_Check()`? I think as soon as they are recognized as sequences assignment should work because `__getitem__()` and `__len__()` should be sufficient for that
How about using `nonzero` to identify which elements are not zero? ````x = np ones((3 4)) s = sparse csr_matrix((3 4)) s[0 0] = 2 s[1 2] = 3 I J = s nonzero() x[:] = 0 # omit if just changing nonzero values x[I J] = s data x ```` `nonzero` functions the same for both dense and `csr` arrays I have not tried it with the other formats <hr> For a csr (and coo) sparse matrix values are stored the `s data` array In this example it looks like: ````array([ 2 4 ]) ```` `x` values are in a `data` buffer `x data` In this case it is 12 contiguous floats ````x ravel() # array([ 2 0 0 0 0 0 4 0 0 0 0 0 ]) ```` There is no way that those 2 values of `s` can be mapped on to the 12 values of `x` without copying The sparse data values do not in general match with a contiguous block of values in its dense equivalent You worry about the size of the `I` and `J` arrays If the sparse matrix was in `coo` format its `row` and `col` attributes could be used in the same way: ````sc=s tocoo() x[sc row sc col]=sc data ```` But converting from one sparse format to another involves copying data And coo arrays are not subscriptable <hr> ````x = np zeros((3 4)) x[:]=['123' '321' '0' '1'] ```` produces ````array([[ 123 321 0 1 ] [ 123 321 0 1 ] [ 123 321 0 1 ]]) ```` It does apply `float` to each item one the right side and then 'broadcasts' it to fit the `x` size The `[]` translates into a call to `-_setitem__` ````x __setitem__((1 2) 3) # same as x[1 2]=3 x __setitem__((None 2) '3') # sets the last row ```` It appears to call `float` on each item of any iterable (need to double check this) But if the value is some other object we get an error similar to your original one: ````class Foo(): pass x __setitem__((1 2) Foo()) # TypeError: float() argument must be a string or a number not 'Foo' ```` sparse `coo` and `dok` formats produce a similar error while `csr` and `lil` produce a ````ValueError: setting an array element with a sequence ```` I have not figured out which method or attribute of the sparse matrix is being used here Take a look at `np broadcast` I think that replicates the kind of iteration used in these assignments ````b = np broadcast(x[:] [1 2 3 4]) list(b) ```` We could remove the float conversion complication by starting with an array with dtype object which can hold anything: ````xa=np zeros((3 4) dtype=object) xa[:]=s ```` But now `s` appears in each element of `xa` It has not distributed the values of `s` over `xa` I am guessing that when `s` is not an `np array` `numpy` first wraps it when doing the assignment e g : ````x[:] = np array(s) ```` When `s` is a scalar or list this produces an array that can be broadcast to fit `x` But when it is an object (a sparse array is not a numpy array) this wrapping is just a 0d array with dtype=object You need to pass `s` through a function that turns it into an iterable that can be broadcast The most obvious one is `toarray()`
verify_grad function: 'TensorVariable' object is not callable I would like to use the verify_grad function but I am getting errors of the form "'TensorVariable' object is not callable" ````theano gradient verify_grad(fun pt n_tests=2 rng=None eps=None out_type=None abs_tol=None rel_tol=None mode=None cast_to_output_type=False) ```` In the doc it says that fun is "a Python function that takes Theano variables as inputs and returns a Theano variable For instance an Op instance with a single output " I have gone through the graph structures section in the docs and I thought I understood what an op node is but apparently I do not E g if I have two TensorVariables x and y and I would like to take the product of them then * is the op node correct? But if I declare z=x*y then z is again a TensorVariable right? So is there any way how to define an op for e g a negative log likelihood function in order to evaluate the correctness of the gradient for that function? Or is there any other way to get the numerical gradient in theano for a function that you constructed?
Here is an example of `verify_grad` in use: ````import numpy import theano def something_complicated(x y): z = x * y return z x_value = numpy array([[1 2 3 ] [4 5 6 ]] dtype=theano config floatX) y_value = numpy array([[7 8 9 ] [10 11 12 ]] dtype=theano config floatX) theano gradient verify_grad(something_complicated (x_value y_value) rng=numpy random) ```` As required `something_complicated` is "a Python function that takes Theano variables as inputs [`x` and `y` in this case] and returns a Theano variable [`z` in this case] " You can construct any symbolic expression inside `something_complicated` such as the computation for a negative log likelihood A Theano operation can be anything as long as - It is <them>callable</them> (objects are callable if they implement the special <a href="https://docs python org/2/reference/datamodel html#object __call__" rel="nofollow">`__call__` function</a>) - When it is called it treats all inputs as Theano variables - When it is called it only returns Theano variables `something_complicated` clearly meets these requirements It is callable by virtue of being a Python function it assumes `x` and `y` are Theano variables and its return value `z` is also a Theano variable
How many teams did the Arena Football League originally have?
four
IOError: [Errno 13] when installing virtualwrapper After successfully installling virtualenv in terminal with 'pip install virtualenv' I tried installing virtualwrapper with 'pip install virtualenvwrapper' and something seems to have gone wrong with some code presenting in red instead of the usual white There was about 20-30 lines of code in essence it said the following: Installing collected packages: virtualenv-clone pbr stevedore virtualenvwrapper Exception: Traceback (most recent call last): Then there is a list of file paths shown followed by <blockquote> IOError: [Errno 13] Permission denied: '/usr/local/lib/python2 7/dist-packages/clonevirtualenv py' </blockquote> <img src="http://i stack imgur com/ekllf png" alt="see screenshot of the code for more detail"> Does anyone know what could have gone wrong and how I can fix it? Thanks
when it is about permission problem you have try with sudo(super user) if Linux `$ sudo pip install virtualenvwrapper` if Windows open cmd with administration privilege and then `pip install virtualenvwrapper`
How to split the first entry of a string that has a letter and number i am python? If I have this small python program: ````str1 = ("S8 10 -945 1689 -950 230 -25 1 1e-13") print(str1[0 1] split(' ')) ```` How would I split the first character from S8 to an individual "S" and "8" instead of just printing"S8"?
You could try appending each character to a list Then calling int() on each item in the list within a try/except structure Then use "isint" and if it returns true insert a space between the int and the character
Google fit data via google python api libraries I am using <a href="https://developers google com/resources/api-libraries/documentation/fitness/v1/python/latest/fitness_v1 users dataset html" rel="nofollow">this python library</a> from google but I cannot figure out what to use for the 'body' argument Is there an example body that I can draw from to create the dict that this tool will need? Here is the code that I am using: ````flow = client flow_from_clientsecrets( workLaptop scope='https://www googleapis com/auth/fitness activity read' redirect_uri='oauth:code:from:somehwere') auth_uri = flow step1_get_authorize_url() webbrowser open_new(auth_uri) auth_code = "a;ldskjfa;lsdkfja;ldsfkja;lsdkfjaldgha;" credentials = flow step2_exchange(auth_code) http_auth = credentials authorize(httplib2 Http()) service = discovery build('fitness' 'v1' http_auth) fitData = service users() dataset() aggregate(userId='me' body=body) execute() ```` It is all fine until the part where I need to define the body Here is the body that I am trying: ````body = { "aggregateBy": [ { "dataSourceId": "derived:com google step_count delta:com google android gms:estimated_steps" "dataTypeName": "com google step_count delta" } ] "bucketByActivitySegment": { "minDurationMillis": "A String" # Only activity segments of duration longer than this is used } "endTimeMillis": "1435269600000000000" "bucketBySession": { "minDurationMillis": "10" # Only sessions of duration longer than this is used } "bucketByActivityType": { "minDurationMillis": "10" # Only activity segments of duration longer than this is used } "startTimeMillis": "1435183200000000000" # required time range "bucketByTime": { # apparently oneof is not supported by reduced_nano_proto "durationMillis": "10" } } ```` What is wrong with my body dict? Here is the error code: https://www googleapis com/fitness/v1/users/me/dataset:aggregate?alt=json returned "Internal Error"> Here is an example of the object in the API explorer: <img src="http://i stack imgur com/gOcSB png" alt="enter image description here">
Although I am not 100% o fey with the Google API for the Google Fit there definitely some issues with your JSON body request in the first instance For example: ```` body = { "aggregateBy": [ { "dataSourceId": "derived:com google step_count delta:com google android gms:estimated_steps" "dataTypeName": "com google step_count delta" } ] "bucketByActivitySegment": { "minDurationMillis": "A String" # Only activity segments of duration longer than this is used } "endTimeMillis": "1435269600000000000" "bucketBySession": { "minDurationMillis": "10" # Only sessions of duration longer than this is used } "bucketByActivityType": { "minDurationMillis": "10" # Only activity segments of duration longer than this is used } "startTimeMillis": "1435183200000000000" # required time range "bucketByTime": { # apparently oneof is not supported by reduced_nano_proto "durationMillis": "10" } } ```` Should actually be this; ```` body = { "aggregateBy": [ { "dataSourceId": "derived:com google step_count delta:com google android gms:estimated_steps" "dataTypeName": "com google step_count delta" } ] "bucketByActivitySegment": { "minDurationMillis": "A String" # Only activity segments of duration longer than this is used } "endTimeMillis": "1435269600000000000" "bucketBySession": { "minDurationMillis": "10" # Only sessions of duration longer than this is used } "bucketByActivityType": { "minDurationMillis": "10" # Only activity segments of duration longer than this is used } "startTimeMillis": "1435183200000000000" # required time range "bucketByTime": { # apparently oneof is not supported by reduced_nano_proto "durationMillis": "10" } } ```` JSON Based rest services are really unforgiving for the use of extra comma's where they should not be it renders the string un-jsonable which will lead to a 500 failure Give that a try in the first instance ;)
The 1998 Good Friday Agreement resulted in what arrangement?
policies common across the island of Ireland
How to tweak my tooltips in wxpython? I was trying to add a tooltip to show the full content of a truncated ObjectListView until it turned out it had such a feature built-in: <img src="http://i stack imgur com/dtkYl png" alt="enter image description here"> I tried making my own tool tips using wx TipWindow wx PopupWindow and SuperToolTip but none of them looked as 'native' as this one <img src="http://i stack imgur com/wtzOy png" alt="enter image description here"> <img src="http://i stack imgur com/HJPZ3 png" alt="enter image description here"> While <a href="http://wiki wxpython org/wxListCtrl%20ToolTips" rel="nofollow">I am aware of this wiki article</a> that supposedly enables the tooltip for truncated wx Listrctrls I did not really understand how to get it working I also expect that it only works when something is truncated whereas I would like to be able to use it to display some more information I guess the SuperToolTip comes close but when you remove the 'header' it leaves it with empty space at the top rather than centering the text in the middle of the tooltip and making it fit I tried looking through the source code of ObjectListView SuperToolTip and wxpython to try and find how tooltips are being created but I cannot really find the low level parts that make it happen <strong>So how can I tweak tooltips so they look more like native tooltips?</strong> The code to generate my current popups was: ````text = "I am a popup" class PopUp(wx TipWindow): def __init__(self parent text): wx TipWindow __init__(self parent text) class PopUp2(wx PopupWindow): def __init__(self parent text): wx PopupWindow __init__(self parent) st = wx StaticText(self parent text) # Import `from agw import supertooltip as STT` popup3 = STT SuperToolTip(text) ````
I am not sure if we have a way to create a native Win7 tooltip yet as you have seen wx TipWindow looks like the tooltips from older versions of Windows so there are probably some newer APIs that we should be using instead Please create a ticket at trac wxwidgets org to find out for sure or to request the change if it is not possible some other way that I am not thinking of at the moment
The movement included atomists such as what?
Pakudha Kaccayana
removing duplicates of a list of sets I have a list of sets : ````L = [set([1 4]) set([1 4]) set([1 2]) set([1 2]) set([2 4]) set([2 4]) set([5 6]) set([5 6]) set([3 6]) set([3 6]) set([3 5]) set([3 5])] ```` (actually in my case a conversion of a list of reciprocal tuples) and I want to remove duplicates to get : ````L = [set([1 4]) set([1 2]) set([2 4]) set([5 6]) set([3 6]) set([3 5])] ```` But if I try : ````&gt;&gt;&gt; list(set(L)) TypeError: unhashable type: 'set' ```` Or ````&gt;&gt;&gt; list(np unique(L)) TypeError: cannot compare sets using cmp() ```` So do you have a solution to "uniquify" my list of sets ?
The best way is to convert your sets to `frozenset`s (which are hashable) and then use `set` to get only the unique sets like this ````&gt;&gt;&gt; list(set(frozenset(item) for item in L)) [frozenset({2 4}) frozenset({3 6}) frozenset({1 2}) frozenset({5 6}) frozenset({1 4}) frozenset({3 5})] ```` If you want them as sets then you can convert them back to `set`s like this ````&gt;&gt;&gt; [set(item) for item in set(frozenset(item) for item in L)] [{2 4} {3 6} {1 2} {5 6} {1 4} {3 5}] ```` <hr> If you want the order also to be maintained while removing the duplicates then you can use <a href="https://docs python org/3/library/collections html#collections OrderedDict">`collections OrderedDict`</a> like this ````&gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; [set(i) for i in OrderedDict fromkeys(frozenset(item) for item in L)] [{1 4} {1 2} {2 4} {5 6} {3 6} {3 5}] ````
PyScripter - cannot termiate Run with KeyboardInterrupt I write alot of small apps where I use ````try: print "always does this until I Ctrl+C" Except KeyboardInterrupt: print "finish program" ```` I have just began to move away from using IDLE and booted up PyScripter However CTRL+C no longer works Is it possible to still send in a `KeyboardInterrupt` while using the built-in interpreter?
I keep answering my own questions but I believe they are valid The PyScripter google group has one implementation where they import a progress bar and kill it simulating an interrupt however this is not the same as a keyboard interrupt Looks like i am out of luck until a new implementation Having Said That can anyone suggest another novel way to terminate programs at a user's discretion (without using threads :p)?
What this OS indicate January 1 is?
null
2D Game Engine - Implementing a Camera So I have been making a game using `Python` specifically the `PyGame module` Everything has been going fairly well (except `Python`'s speed am I right :P) and I have got a nice list of accomplishments from this but I just ran into a speedbump Maybe a mountain I am not to sure yet The problem is: <blockquote> How do I go about implementing a Camera with my current engine? </blockquote> That probably means nothing to you though so let me explain what my `current engine` is doing: I have a spritesheet that I use for all images The map is made up of a double array of `Tile` objects which fills up the display (800 x 640) The map also contains references to all `Entity`'s and `Particles` So now I want to create a a camera so that the map object can be <strong>Larger</strong> than the display To do this I have devised that I will need some kind of camera that follows the player (with the player at the center of the screen) I have seen this implemented before in games and even read a few other similar posts but I need to also know <strong><them>Will I have to restructure all game code to work this in?</them></strong> My first attempt was to make all object move on the screen when the player moves but I feel that there is a better way to do this as this screws up collision detection and such So if anyone knows any good references to problems like this or a way to fix it I am all ears er eyes Thanks
You may find <a href="http://gamedev stackexchange com/q/46228">this link</a> to be of interest In essence what you need to do is to distinguish between the "actual" coordinates and the "display" coordinates of each object What you would do is do the bulk of the work using the actual coordinates of each entity in your game If it helps imagine that you have a gigantic screen that can show everything at once and calculate everything as normal It might help if you also designed the camera to be an entity so that you can update the position of your camera just like any other object Once everything is updated you go to the camera object and determine what tiles objects particles etc are visible within the window and convert their actual world coordinates to the pixel coordinates you need to display them correctly If this is done correctly you can also do things like scale and otherwise modify the image your camera is displaying without affecting gameplay In essence you want to have a very clear distinction between gameplay and physics logic/code and your rendering/display code so your game can do whatever it wants and you can render it however you want with minimal crossover between the two So the good news is you probably do not need to change anything about how your game itself works The bad news is you will probably have to go in and rewrite your rendering/drawing code so that everything is drawn relative to the camera not to the world
For and lists in Python I have a problem with Python I have this main: ````def main(): cats = [] for x in range(1 11): x = Cat(x) cats append(x) listPussa = [] for x in range(1 21): x = Pussa(x) listPussa append(x) PussaIndex = 0 for cat in cats: num = cat getcatNum() if num % 2 != 0: for i in range(4): cat addPussa(listPussa[PussaIndex]) PussaIndex = 1 for cat in cats: print cat mixeta() ```` The problem is that when I use this function in the main to print the list of cats: ````def mixeta(self): #This is a method of the class Cat it returns a few strings depending on how many objects Pussa has the object if len(self __listPussa) is 0: #When the cat has no one it returns that return "Miau!" self getcatNum() "La llista de pusses esta buida" #The string menas that the list of Pussa is empty else: #When it has at least 1 listIdPussa = [] #I created a new list for pussa in self __listPussa: #And for every objcet Pussa in the list of Pussa listIdPussa append(pussa getIdPussa()) #I save every idPussa in the list return "Miau!" self getcatNum() "El gat esta infectat El nombre total de pusses es " len(self __listPussa) listIdPussa #So at the end it returns "Meow" the number of the cat and it says that the cat is "infected" and the total number of objects Pussa is X and each id from every object ```` The result it has to be that: ````('Miau!' 1 'El gat esta infectat El nombre total de pusses es ' 4[0 1 2 3]) ('Miau!' 2 'La llista esta buida') # It means the list has no objects Pussa ('Miau!' 3 'El gat esta infectat El nombre total de pusses es ' 4[4 5 6 7]) ('Miau!' 4 'La llista esta buida') ```` And this way until it reach Miau 10 But the problem is that my main prints that: ````('Miau!' 1 'El gat esta infectat El nombre total de pusses es ' 20 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]) ('Miau!' 2 'El gat esta infectat El nombre total de pusses es ' 20 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]) ('Miau!' 3 'El gat esta infectat El nombre total de pusses es ' 20 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]) ('Miau!' 4 'El gat esta infectat El nombre total de pusses es ' 20 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]) ```` And that for all cats What can I do?
This probably happens because you declared `__listPussa` as a class member and not as object member In this case it is shared between all the instances of `Cat` ````class Cat: __listPussa = [] def __init__(self num): self num = num ```` Each time you add some Pussa to cats their are added to the same variable shared accross all cats (yeek cats share their Pussa :) ) To achieve what you want you need to make `__listPussa` an instance member like this: ````class Cat: def __init__(self num): self num = num self __listPussa = [] ````
Is it possible to use argsort in descending order Consider the following code: ````avgDists = [1 8 6 9 4] ids = np array(avgDists) argsort()[:n] ```` This gives me indices of the `n` smallest elements Is it possible to use this same `argsort` in descending order to get the indices of `n` highest elements ?
Just like Python in that `[::-1]` reverses the array returned by `argsort()` and `[:n]` gives that last n elements: ````&gt;&gt;&gt; avgDists=np array([1 8 6 9 4]) &gt;&gt;&gt; n=3 &gt;&gt;&gt; ids = avgDists argsort()[::-1][:n] &gt;&gt;&gt; ids array([3 1 2]) ```` The advantage of this method is that `ids` is a <a href="http://docs scipy org/doc/numpy/glossary html#term-view">view</a> of avgDists: ````&gt;&gt;&gt; ids flags C_CONTIGUOUS : False F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False ```` (The 'OWNDATA' being False indicates this is a view not a copy) Another way to do this is something like: ````(-avgDists) argsort()[:n] ```` The problem is that the way this works is to create negative of each element in the array: ````&gt;&gt;&gt; (-avgDists) array([-1 -8 -6 -9 -4]) ```` ANd creates a copy to do so: ````&gt;&gt;&gt; (-avgDists_n) flags['OWNDATA'] True ```` So if you time each even with this very small data set: ````&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit timeit('(-avgDists) argsort()[:3]' setup="from __main__ import avgDists") 4 2879798610229045 &gt;&gt;&gt; timeit timeit('avgDists argsort()[::-1][:3]' setup="from __main__ import avgDists") 2 8372560259886086 ```` The view method is substantially faster
Input a Unix directory address in Python and not triggering str error I was trying to write a Python 2 7 script that processes a Unix directory input and use the input as a parameter to start another program However I run into a problem that python's str() function does not like slashes in the input When I am trying to str() a input with slashes just like: ````inputData = str(input('Put directory here:')) // OS is Mac OS X &gt; Put directory here: /User/username/abc file SyntaxError: invalid syntax ```` I think this is due to str() cannot naturally process a string with slashes because if I manually add quotes on each site during the input (keyboard input "/User/username/abc file") this error will not be triggered As this script needs to process user input I hope it can add quotes automatically I tried the following walk-around: ````inputDataRaw = input('Put directory here:') if (not inputDataRaw startswith('"')) and (not inputDataRaw startswith("'")): inputDataRaw = '"' inputDataRaw if (not inputDataRaw endswith("'")) and (not inputDataRaw endswith('"')): inputDataRaw = inputDataRaw '"' inputData = str(inputDataRaw) ```` But apparently the input value cannot be stored in inputDataRaw without str()ing it and the first line directly triggered the same error It looks like all functions that escape a slash in python cannot work without forming a string first Would anyone please point out the correct way to walk-around this problem? Thanks
`input` attempts to `eval` the given input That is it is expecting something that would be a valid Python literal - including quotes for a string value Use `raw_input` instead - that always returns the string the user entered leaving conversions to your code From the <a href="http://docs python org/2/library/functions html#input" rel="nofollow">docs</a>: <blockquote> ````Equivalent to eval(raw_input(prompt)) ```` This function does not catch user errors If the input is not syntactically valid a SyntaxError will be raised Other exceptions may be raised if there is an error during evaluation If the readline module was loaded then input() will use it to provide elaborate line editing and history features Consider using the raw_input() function for general input from users </blockquote>
Replacing part of string in python pandas dataframe I have a similar problem to the one posted here: <a href="http://stackoverflow com/questions/13682044/pandas-dataframe-remove-unwanted-parts-from-strings-in-a-column">Pandas DataFrame: remove unwanted parts from strings in a column</a> I need to remove newline characters from within a string in a DataFrame Basically I have accessed an api using python's json module and that is all ok Creating the DataFrame works amazingly too However when I want to finally output the end result into a csv I get a bit stuck because there are newlines that are creating false 'new rows' in the csv file So basically I am trying to turn this: ' this is a paragraph And this is another paragraph ' into this: ' this is a paragraph And this is another paragraph ' I do not care about preserving any kind of '\n' or any special symbols for the paragraph break So it can be stripped right out I have tried a few variations: ````misc['product_desc'] = misc['product_desc'] strip('\n') AttributeError: 'Series' object has no attribute 'strip' ```` here is another ````misc['product_desc'] = misc['product_desc'] str strip('\n') TypeError: wrapper() takes exactly 1 argument (2 given) misc['product_desc'] = misc['product_desc'] map(lambda x: x strip('\n')) misc['product_desc'] = misc['product_desc'] map(lambda x: x strip('\n\t')) ```` There is no error message but the newline characters do not go away either Same thing with this: ````misc = misc replace('\n' '') ```` The write to csv line is this: ````misc_id to_csv('C:\Users\jlalonde\Desktop\misc_w_id csv' sep=' ' na_rep='' index=False encoding='utf-8') ```` Version of Pandas is 0 9 1 Thanks! :)
`strip` only removes the specified characters at the beginning and end of the string If you want to remove <them>all</them> `\n` you need to use `replace` ````misc['product_desc'] = misc['product_desc'] str replace('\n' '') ````
Where to exclude retweets in this tweepy script? I have the following code which allows me to view a stream of 1% of the twitter firehose via python: ````import sys import tweepy consumer_key="" consumer_secret="" access_key = "" access_secret = "" auth = tweepy OAuthHandler(consumer_key consumer_secret) auth set_access_token(access_key access_secret) api = tweepy API(auth) class CustomStreamListener(tweepy StreamListener): def on_status(self status): if '' in status text lower(): print status text print status coordinates def on_error(self status_code): print &gt;&gt; sys stderr 'Encountered error with status code:' status_code return True # Do not kill the stream def on_timeout(self): print &gt;&gt; sys stderr 'Timeout ' return True # Do not kill the stream sapi = tweepy streaming Stream(auth CustomStreamListener()) sapi filter(track=['example']) ```` I know the syntax `include_rts = False` will remove retweets from the stream I am viewing but I am not sure where to add it to the above code Can anyone assist? Thanks
Add the following condition to the on_status function in your listener: ````def on_status(self status): if '' in status text lower() and 'retweeted_status' not in status: print status text print status coordinates ````
Django http response code 500 error I am trying to order a bunch of coordinates by their distance to another input coordinate Whenever I try to order I get the error code 500 Any ideas? Here is an image of the response codes and I circled the error code associated with my GET request <img src="http://i stack imgur com/UimhZ png" alt="enter image description here"> Here is the Javascript in the Django template: ````function searchWaypoints() { geocoder geocode({ 'address': $('#address') val() } function(results status) { if (status == google maps GeocoderStatus OK) { var position = results[0] geometry location; $ get("{% url 'waypoints-search' %}" { lat: position lat() lng: position lng() } function (data) { if (data isOk) { $('#waypoints') html(data content); waypointByID = data waypointByID; activateWaypoints(); } else { alert(data message); } } 'json'); } else { alert('Could not find geocoordinates for the following reason: ' status); } }); } $('#searchWaypoints') click(searchWaypoints); $('#address') keydown(function(e) { if (e keyCode == 13) searchWaypoints(); }); ```` Here is the urls py" ````urlpatterns = patterns('waypoints views' url(r'^$' 'index' name='waypoints-index') url(r'^save$' 'save' name='waypoints-save') url(r'^search$' 'search' name='waypoints-search') ) ```` Here is the view in views py: ````def search(request): 'Search waypoints' # Build searchPoint try: searchPoint = Point(float(request GET get('lng')) float(request GET get('lat'))) except: return HttpResponse(simplejson dumps(dict(isOk=0 message='Could not parse search point'))) # Search database waypoints = Waypoint objects distance(searchPoint) order_by('distance') # Return return HttpResponse(simplejson dumps(dict( isOk=1 content=render_to_string('waypoints/waypoints html' { 'waypoints': waypoints }) waypointByID=dict((x id { 'name': x name 'lat': x geometry y 'lng': x geometry x }) for x in waypoints) )) mimetype='application/json') ````
Change `mimetype='application/json'` to `content_type="application/json"` or you can just use JsonResponse in Django <a href="https://docs djangoproject com/en/1 8/ref/request-response/#jsonresponse-objects" rel="nofollow">https://docs djangoproject com/en/1 8/ref/request-response/#jsonresponse-objects</a>
Python Kivy: Buttons not updating text I am trying to make an app for android that resembles: Would you rather <strong>(everything in</strong> <strong><them>italic</them></strong> <strong>is not essential)</strong> <them>In the end i made a total of 4 apps (technicaly duplicates) with differences in the kivy code </them> <them>The original problem was the the buttons with the options to chose from either not triggering the function or the textures disappeared all that has been fixed </them> The problem i have now is that the buttons are not updating after they are pressed The output file is updated thus the function is called and executed The text on the buttons themselves however is not updating after button press Here is the code: ````#Imports import kivy kivy require('1 9 0') from kivy app import App from kivy clock import Clock from kivy uix widget import Widget from kivy uix boxlayout import BoxLayout from kivy properties import StringProperty from os import system as Sys #Variables QuestionsDict = {0:["Te faire couper une jambe" "Te faire couper un bras"] 1:["Lire les penses d'une personne une fois par jour" "Voir jusqu'à un jour dans le futur pendant maximum 1 heure"]} #Complex variables try: PlayerData = eval(open("TPLocal dat" "r") read()) #PlayerData is a base 3 number 0 = not answered question 1 = chose option 1 2 = chose option 2 except: PlayerData = str() # if file id not present (1st time opening app) finally: PlayerData = list(str(PlayerData)) #for editing purposes if len(PlayerData) < len(QuestionsDict): PlayerData = "0" * (len(QuestionsDict) - len(PlayerData)) #in case questions have been added to app since last open #Functions def b58encode(): #smaller text to send to us for statistical analysis (App is for a e-con student) number = int("" join(PlayerData) 3) alphabet='0123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnoqrstuvwxyz' base36 = str() while not number == 0: number i = divmod(number 58) base36 = alphabet[i] base36 return base58 #Classes class TPGame(BoxLayout): Question1 = StringProperty(QuestionsDict[PlayerData index("0")][0]) Question2 = StringProperty(QuestionsDict[PlayerData index("0")][1]) def Q1(self): PlayerData[PlayerData index("0")] = "1" open("TPLocal dat" "w") write(str("" join(PlayerData))) def Q2(self): PlayerData[PlayerData index("0")] = "2" open("TPLocal dat" "w") write(str("" join(PlayerData))) def copytoclipboard(self): Sys('echo|set /p=' b58encode(PlayerData) '|clip') class TuPreferesApp(App): def build(self): return TPGame() #Core if __name__ in ('__main__' '__android__'): TuPreferesApp() run() ```` kv file: ````#:kivy 1 9 0 <TPGame&gt;: orientation: "vertical" Label: text: you"Tu pr\u00E9f\u00E8res?" text_size: self size halign: "center" valign: "middle" Button: background_normal: "Op1 png" background_down: "Op1D png" text: root Question1 text_size: self size halign: "center" valign: "middle" on_press: root Q1() Button: id: B2 background_normal: "Op2 png" background_down: "Op2D png" text: root Question2 text_size: self size halign: "center" valign: "middle" on_press: root Q2() Button: background_normal: "Black png" background_down: "Black png" text: "Si vous voulez nous envoyer vos reponses\n Appuyez ici" #translates to "if you want to sent us your answers press here" text_size: self size halign: "center" valign: "bottom" on_press: root copytoclipboard() ```` I was not able to change the text on the buttons every time you press a button I tried with <them>Clock</them> and <them>setter</them> but without success What i want to do is update the text on the first two buttons to show the next two options to choose from (the will be more questions later in the QuestionsDicts unlimited amount) Sorry the text in the app is in french (I am french) Thanks in advance Steph
Well maybe you should bind your button to some function which will update text? Like ````Button(on_release = do something) # do something is a function ```` or in kv file: ````button: on_release: root something ```` Of course you can also use on_press but this will cut fancy animation of pressed button EDIT: Ok I was wrong and now I have a questions: ````def b58encode(*args): #smaller text to send to us for statistical analysis (App is for a e-con student) number = int("" join(PlayerData) 3) alphabet='0123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnoqrstuvwxyz' base36 = str() while not number == 0: number i = divmod(number 58) base36 = alphabet[i] base36 return base58 ```` Where is base58? when I use clipboard i have an error maybe I should be base36? ok maybe this: Kivy file ````<TPGame&gt;: orientation: "vertical" button2: B2 ```` and main py file: ````class TPGame(BoxLayout): Question1 = StringProperty(QuestionsDict[PlayerData index("0")][0]) Question2 = StringProperty(QuestionsDict[PlayerData index("0")][1]) button2 = ObjectProperty() def Q2(self): PlayerData[PlayerData index("0")] = "2" open("TPLocal dat" "w") write(str("" join(PlayerData))) self button2 text = 'PRESSED' ````
What is the use of returning self in the __iter__ method? ````def __iter__(self): return self ```` Just wanted to know what does the above code do in general why is it required I went through many code tutorial and blocks was getting mutiple answers without any proper specification just a brief explanation would be great
EDIT: for 2 7 instead of 3 Here is my understanding In below example code we can say that class Testing is an iterable object because we implemented it with `__iter__` Method `__iter__` returns an iterator The iterator uses the next method to determine the next value on the iteration If I were to remove the `next` method from the class below the code would fail iterable = an object that can be iterated over implemented with `__iter__` iterator = object that defines how to iterate literally what is the next value This is implemented with `__next__` So the piece of code you questioned actually takes the class object (self is the argument) and returns an iterator which makes the class object iterable So in the example below we can actually iterate over the class object myObj ````class Testing: def __init__(self a b): self a = a self b = b def __iter__ (self): return self def next(self): if self a <= self b: self a = 1 return self a-1 else: raise StopIteration myObj = Testing(1 5) for i in myObj: print i ````
Pass commands from one docker container to another I have a helper container and an app container The helper container handles mounting of code via git to a shared mount with the app container I need for the helper container to check for a `package json` or `requirements txt` in the cloned code and if one exists to run `npm install` or `pip install -r requirements txt` storing the dependencies in the shared mount Thing is the npm command and/or the pip command needs to be run from the app container to keep the helper container as generic and as agnostic as possible One solution would be to mount the docker socket to the helper container and run `docker exec <command&gt; <app container&gt;` but what if I have thousands of such apps on a single host Will there be issues having hundreds of containers all accessing the docker socket at the same time? And is there a better way to do this? Get commands run on another container?
Well there is no "container to container" internal communication layer like "ssh" In this regard the containers are as standalone as 2 different VMs ( beside the network part in general ) You might go the usual way install opensshd-server on the "receiving" server configure it key-based only You do not need to export the port to the host just connect to the port using the docker-internal network Deploy the ssh private key on the 'caller server' and the public key into ssh/authorized_keys on the 'receiving server' during container start time ( volume mount ) so you do not keep the secrets in the image (build time) Probably also create a ssh-alias in ssh/config and also set HostVerify to no since the containers could be rebuild Then do ````ssh <alias&gt; your-command ````
How long have railroads been important since in Montana
1880s
Python creating new Dictionary from older one between indexes I am new to python but I was wondering how I can approach this I want to copy all the lines between the indexes 4 and 20 20 and 25 and put that as the value in a new dictionary ````def cutting(my_sequence): code={} text=dict(my_sequence) #converts my sequence which has line numbers as key and line as value list=[4 20 25] #holds line numbers I want to cut between #now what?Here is where I have to find out how to make a new dict with all the lines in between as value return code ```` For example If the text takes the form of something like ````{0:'hello guys this is the start\n' 1:'this is the first line\n' 2:'this is the second line\n'} ```` and I want something like this for my output dictionary code: ````{0:'hello guys this is the start\n this is the first line\n' 1:'this is the second line\n'} ````
It seems like dictionaries are the wrong choice here Let us use lists instead Since we are ignoring original line numbers we can infer them from their position in the list ````def cutting(my_sequence: "list of tuples of form: (int str)"): > list flat_lst = [v for _ v in my_sequence] ```` This builds a list of JUST the text Now let us build a list of ranges to work with ```` lines_to_join = [5 20 25] ranges = [range(lines_to_join[i] lines_to_join[i+1]) for i in range(len(lines_to_join)-1)] # ranges is now [range(5 20) range(20 25)] ```` There are prettier ways to do that (see the `pairwise` function in the <a href="https://docs python org/2/library/itertools html#recipes" rel="nofollow">itertools recipes</a>) but this will work for this small application Next let us use `"\n" join` to glue together the lines you want ```` result = ["\n" join([flat_lst[idx] for idx in r]) for r in ranges] # you might want to strip the natural newlines out of the values so # # result = ["\n" join([flat_lst[idx] strip() for idx in r]) ] # I will leave that for you return result ```` Note that this will throw `IndexError` if any of your indexes in `ranges` fall outside of `flat_lst` All together we should have something like: ````def cutting(my_sequence: "list of tuples of form: (int str)"): > list flat_lst = [v for _ v in my_sequence]lines_to_join = [5 20 25] ranges = [range(lines_to_join[i] lines_to_join[i+1]) for i in range(len(lines_to_join)-1)] # ranges is now [range(5 20) range(20 25)] result = ["\n" join([flat_lst[idx] for idx in r]) for r in ranges] return result ````
Adjust right margin width to fit margin text I am creating a figure that has text in the right margin but that text is being cut off in the figure I have tried adjusting `figsize` but to no avail Is there a way to increase the right margin width so that all margin text is visible? ````models = ['GISS-E2-H' 'MRI-CGCM3' 'bcc-csm1-1-m' 'IPSL-CM5A-LR' \ 'CanESM2' 'CESM1-BGC' 'IPSL-CM5B-LR' 'inmcm4' 'GISS-E2-R' \ 'IPSL-CM5A-MR' 'MPI-ESM-MR' 'GFDL-CM3' 'CCSM4' 'bcc-csm1-1' \ 'NorESM1-M' 'GFDL-ESM2M' 'CESM1-CAM5' 'HadGEM2-ES' \ 'CSIRO-Mk3-6-0' 'CNRM-CM5' 'ACCESS1-3' 'CMCC-CESM' 'CMCC-CMS' \ 'NorESM1-ME' 'MPI-ESM-LR' 'ACCESS1-0' 'BNU-ESM' 'MIROC5' \ 'CMCC-CM' 'EC-EARTH' 'GFDL-ESM2G' 'MIROC-ESM' 'MIROC-ESM-CHEM' \ 'FGOALS-g2'] for idx model in enumerate(models): # Plot the marker as the model number plt text(stdv_changes[idx] mean_changes[idx] str(idx+1) fontsize=12) # Add right margin text (model number - model) y_loc = 9 - (1 /40 )*int(idx) plt figtext( 925 y_loc '{0:2d} - {1}' format(idx+1 models[idx]) fontsize=8) plt ylim(-10 15) plt xlim(-5 10) plt axvline(linewidth= 25 linestyle='dashed' color='black') plt axhline(linewidth= 25 linestyle='dashed' color='black') plt xlabel('Standard deviation change (cm)') plt ylabel('Mean change (cm)') plt show() ```` <img src="http://i stack imgur com/7krKT png" alt="enter image description here">
Have a look at this <a href="http://stackoverflow com/questions/10101700">question</a> You could do this just before calling `plt show()`: ````plt subplots_adjust(right= 8) # or even smaller number to shift the right edge to the left ````
What industries can you find these applications?
automotive, chemical, power generation, aerospace, and telecommunications
How to correctly access elements of a nested list in python I am trying to evaluate and alter the elements of a nested list within nested for loops in python but my code breaks when I try to access list[i-1][j] This works: ````for i in range(HEIGHT): for j in range(WIDTH): if nested_list[i+1][j] foo == 'bar' and nested_list[i][j+1] foo == 'bar': nested_list[i][j] foo = 'bar' ```` but when I use i-1 or j-1 instead of 1 above it breaks (inserts bar as value for all elements) ````for i in range(2 HEIGHT): for j in range(2 WIDTH): if nested_list[i-1][j] foo == 'bar' and nested_list[i][j-1] foo == 'bar': nested_list[i][j] foo = 'bar' ```` Edit: the nested list holds a map like this: ````################## #### ######### #### ######### #### ######### ############ ## ############ ## ############ ## ################## ```` when using the first bit of code the expected result occurs the corners on the right hand side of the rectangles are turned into #s when trying to do it 'the other way' i e evaluating the left hand sides the whole array is populated with #s (I hope that makes sense)
The problem you are having is because you are modifying the values of your nested list as you iterate over it After you turn the top-left corner of an open space into a `#` the open spaces to either side of it (right and down) now see themselves as being top-left corners too and so get turned into `#`s when their turn comes This does not happen when you are modifying the bottom left corner because by the time you get to it you have already processed the squares above and to its left To work around this issue there are a few different approaches The simplest might be to simply iterate in reverse starting with `WIDTH` and `LENGTH` and counting down to `1` However this approach is similarly fragile (it will only work for the top-left square) An alternative which would be a bit more complicated but would work if you wanted to fill in any kind of of corner (not just the top left) would be to create a new nested list rather than modifying the existing one Because you are looking at the original list the whole time you will never see the results of previous operations when determining the appropriate value for a square Here is some code that uses a list comprehension to do this: ````def is_corner(lst i j): return i &gt;= 0 and j &gt; 0 and lst[i-1][j] == "bar" and lst[i][j-1] == "bar" new_nested_list = [["bar" if is_corner(nested_list i j) else nested_list[i][j] for j in range(WIDTH)] for i in range(HEIGHT)] ```` You can modify the `is_corner` predicate function however you want and only the squares for which it returns `True` will have their values replaced You could check for <them>any</them> corner with: ````def is_corner(lst i j): return (0 < i < len(lst) and 0 < j < len(lst[0]) and (lst[i-1][j] == "bar" or lst[i+1][j] == "bar") and (lst[i][j-1] == "bar" or lst[i][j+1] == "bar")) ````
Sqlalchemy adds unwanted columns to query when a foreign key table is added In a Sqlalchemy query you can select specific rows like this: ````q = session query(Equipment name) ```` That will return one column for each row You can add more column descriptors from model The value of `len(q column_descriptions)` is one in this case However as soon as you add a column that is a foreign key you suddenly get all the columns of the table even though I did not ask for them ````q = dbsession query(models Equipment name models Equipment model) ```` This should be two columns but now `len(q column_descriptions)` is 15 (for this table that is all of them plus the addidtional one) The query (q statement) ends up looking like this: ````SELECT public equipment name public equipment id public equipment model_id public equipment serno public equipment location_id public equipment sublocation public equipment addeddate public equipment comments public equipment language_id public equipment owner_id public equipment vendor_id public equipment account_id public equipment parent_id public equipment active FROM public equipment ```` I think this is a bug in Sqlalchemy but maybe I am doing something wrong and somebody here might know what it is
"name" is a column "model" is not - its a relationship() (based on the observed behavior above) The current default `__clause_element__()` for relationship is the full table so that is why all columns get spit out As you noted in ticket #1328 this is related but the proposal there is that you would be getting back ('name' SomeModelObject) so not a foreign key column there either The difference between "foreign key" and "relationship" is different in SQLAlchemy in constrast to other ORM tools which may conceal the fact that "foreign key" columns exist To query for the FK column only you want to say query(Equipment name Equipment model_id) or whatever the name of the foreign key column that references "model" is If you are using Elixir then you may have to dig into their docs to see what name they use
What languages do residents of Norfolk Island restrict?
null
how to get a property of all records in django sqlite3 My model ````class Article(models Model) : title = models CharField(max_length = 100) category = models CharField(max_length = 50 blank = True) date_time = models DateTimeField(auto_now_add = True) content = models TextField(blank = True null = True) def __unicode__(self) : return self title class Meta: ordering = ['-date_time'] ```` How to make a list contain all category and without repeat? using the syntax just like: ````post_list = Article objects filter(category__iexact = tag) ````
You can use `values_list` to extract all values of a particular field ````category_list = Article objects values_list('category' flat=True) ```` To remove duplicates from the list: ````categories = list(set(category_list)) ```` or as <a href="http://stackoverflow com/users/548562/iain-shelvington">@Iain</a> pointed out you can use ` distinct()` ````category_list = Article objects values_list('category' flat=True) distinct() ````
How do I combat this django error Page not found (404) I am creating this django app using the tutorial and i am up to part 4 <a href="https://docs djangoproject com/en/dev/intro/tutorial04/" rel="nofollow">https://docs djangoproject com/en/dev/intro/tutorial04/</a> The app display a basic poll and when you click on it it display some choices and a button to vote <img src="http://i stack imgur com/m9rbq jpg" alt="enter image description here"> The problem is when I click on vote It display Page not found I think the problem is the redirection but I do not know where to pin point the problem The first page is the index html which display the questions then it is the detail html which display the choices and question I know when I click on vote it goes back to the app URLconf then the urlconf execute the view function and the view function execute the results My detail html are ```` <h1&gt;{{ poll question }}</h1&gt; {% if error_message %}<p&gt;<strong&gt;{{ error_message }}</strong&gt;</p&gt;{% endif %} <form action="/myapp/{{ poll id }}/vote/" method="post"&gt; {% csrf_token %} {% for choice in poll choice_set all %} <input type="radio" name="choice" id="choice{{ forloop counter }}" value="{{ choice id }}" /&gt; <label for="choice{{ forloop counter }}"&gt;{{ choice choice_text }}</label&gt;<br /&gt; {% endfor %} <input type="submit" value="Vote" /&gt; </form&gt; ```` My urls py inside myapp are : ````from django conf urls import patterns include url from django contrib import admin from django conf import settings from django conf urls import patterns include url urlpatterns = patterns('myapp views' url(r'^$' 'index') url(r'^(?P<poll_id&gt;\d+)/$' 'detail') url(r'^(?P<poll_id&gt;\d+)/results/$' 'results') url(r'^(?P<poll_id&gt;\d+)/vote/$' 'vote') ) ```` My views py are : ````from django http import HttpResponse from myapp models import Poll choice from django template import Context loader from django http import Http404 from django shortcuts import render_to_response get_object_or_404 from django template import RequestContext def index(request): latest_poll_list = Poll objects all() order_by('-pub_date')[:5] return render_to_response('myapp/index html' {'latest_poll_list': latest_poll_list}) def results(request poll_id): p = get_object_or_404(Poll pk=poll_id) return render_to_response('myapp/results html' {'poll': p}) def vote(request poll_id): p = get_object_or_404(Poll pk=poll_id) try: selected_choice = p choice_set get(pk=request POST['choice']) except (KeyError Choice DoesNotExist): # Redisplay the poll voting form return render_to_response('myapp/detail html' { 'poll': p 'error_message': "You did not select a choice " } context_instance=RequestContext(request)) else: selected_choice votes = 1 selected_choice save() # Always return an HttpResponseRedirect after successfully dealing # with POST data This prevents data from being posted twice if a # user hits the Back button return HttpResponseRedirect(reverse('myapp views results' args=(p id ))) def detail(request poll_id): p = get_object_or_404(Poll pk=poll_id) return render_to_response('myapp/detail html' {'poll': p} context_instance=RequestContext(request)) ```` My results html are: ````<h1&gt;{{ poll question }}</h1&gt; <ul&gt; {% for choice in poll choice_set all %} <li&gt;{{ choice choice_text }} -- {{ choice votes }} vote{{ choice votes|pluralize }}</li&gt; {% endfor %} </ul&gt; <a href="/myapp/{{ poll id }}/"&gt;Vote again?</a&gt; ```` Thank you for helping me This will be my first breakthrough app if I can get this to work My Main URLconf is : ````from django conf urls import patterns include url from django contrib import admin from django conf import settings # Uncomment the next two lines to enable the admin: # from django contrib import admin admin autodiscover() urlpatterns = patterns('' url(r'^polls/' include('myapp urls')) url(r'^admin/' include(admin site urls)) ) ```` <img src="http://i stack imgur com/V2f7f jpg" alt="enter image description here">
Loose the myapp bit of the form action It should be ````<form action="polls/{{poll id}}/vote" method="post"&gt; ```` This matches the regex in your urls py file - ````url(r'^polls/' include('myapp urls')) ```` and then in myapp urls - ````url(r'^(?P<poll_id&gt;\d+)/vote/$' 'vote') ```` The `include` function means that django is trying to match `^polls/(?P<poll_id&gt;\d+)/vote/$` If you look at the error page your getting you can see the url's that django's trying to match against (none of them contain 'myapp' it should be polls) <strong>IMPORTANT</strong> When you get further on in the tutorial you will see that you should not be hardcoding urls in your templates (as jpic rightly points out) At this stage you need to swap out the form action for `{% url 'polls:vote' poll id %}`
Add Preprocessor to HTML (Probably in Apache) I would like to add a preprocessor to HTML pages Basically I have a program that takes the name of an HTML file containing preprocessor instructions and outputs the contents of the file after preprocessing to stdout This mechanism could change if it makes things easier All I want to do is hook this into Apache so that all the files that my website serves get put through the preprocessor before going out to the browser A solution that works with other HTTP servers than Apache would be preferred but is not required If my understanding is correct this is roughly what PHP does If it makes any difference the preprocessor is written in Python
If you have Apache and a "preprocessor" written in python why not go for <a href="http://www modpython org/" rel="nofollow">mod_python</a>?
Get daily averages of monthly database I have a long list of data structured in the following way ````Date Time Temperature Moisture Accumulated precipitation 1/01/2011 00:00 23 50 2 1/01/2011 00:15 22 45 1 1/01/2011 00:30 20 39 0 1/01/2011 01:00 25 34 0 1/01/2011 01:15 23 50 0 1/01/2011 23:45 22 40 0 31/01/2011 00:00 23 45 0 ```` How I can get the daily averages of the variables `Temperature` and `Moisture` for the 31st day of the month?
This is the sort of thing that the <a href="http://pandas pydata org" rel="nofollow">pandas</a> library is good at The basic idea is that you can read data into objects called `DataFrames` kind of like an Excel sheet and then you can do neat things to them Starting from a `temps csv` file I made up to look like yours: ````&gt;&gt;&gt; df = pd read_csv("temps csv" index_col=False parse_dates=[[0 1]] skipinitialspace=True) &gt;&gt;&gt; df = df rename(columns={"Date _Time": "Time"}) &gt;&gt;&gt; df = df set_index("Time") &gt;&gt;&gt; df Temperature Moisture Accumulated precipitation Time 2011-01-01 00:00:00 23 50 2 2011-01-01 00:15:00 22 45 1 2011-01-01 00:30:00 20 39 0 2011-01-01 01:00:00 25 34 0 2011-01-01 01:15:00 23 50 0 2011-01-01 23:45:00 22 40 0 2011-01-02 00:00:00 123 250 32 2011-01-02 00:15:00 122 245 31 2011-01-02 00:30:00 120 239 30 2011-01-02 01:00:00 125 234 30 2011-01-02 01:15:00 123 250 30 2011-01-02 23:45:00 122 240 30 ```` Once we have the frame in a nice shape we can easily resample (the default is the mean): ````&gt;&gt;&gt; df resample("D") Temperature Moisture Accumulated precipitation Time 2011-01-01 22 5 43 0 5 2011-01-02 122 5 243 30 5 ```` Or get the max or min: ````&gt;&gt;&gt; df resample("D" how="max") Temperature Moisture Accumulated precipitation Time 2011-01-01 25 50 2 2011-01-02 125 250 32 &gt;&gt;&gt; df resample("D" how="min") Temperature Moisture Accumulated precipitation Time 2011-01-01 20 34 0 2011-01-02 120 234 30 ```` Et cetera Note that this is just the brute average of the recorded data points each day: if you want to resample differently to account for the different distance between measurements that is easy too If you are going to be doing data processing in Python it is definitely worth reading through the <a href="http://pandas pydata org/pandas-docs/stable/10min html" rel="nofollow">10 minute overview</a> to see if it might be helpful
What language does she mainly sing?
English
How do you delete a node in networkx? I have a dataset that I am uploading as a graph for various timeframes and trying to figure relationships between them I want to delete all the nodes that do not have edges but I am not sure the command to remove or delete nodes Any idea how to do this?
````import networkx as nx import matplotlib pyplot as plt G=nx Graph() G add_edges_from([('A' 'B') ('A' 'C') ('B' WOULD') ('C' WOULD')]) nx draw(G) plt show() ```` <img src="http://i stack imgur com/8MkUw png" alt="enter image description here"> ````G remove_node('B') nx draw(G) plt show() ```` <img src="http://i stack imgur com/KE55x png" alt="enter image description here"> To remove multiple nodes there is also the <a href="http://networkx lanl gov/reference/classes graph html#adding-and-removing-nodes-and-edges">Graph remove_nodes_from()</a> method
Installing/uninstalling my module with pip I am going through the <them>Learn Python the Hard Way 2nd Edition</them> book and I am stuck on this problem: "Use your setup py to install your own module and make sure it works then use pip to uninstall it " If I type ````setup py install ```` in the command line I can install the module But when I type ````pip uninstall setup py ```` it says: ````Cannot uninstall requirement setup py not installed ```` The pip package index says <a href="http://pypi python org/pypi/pip">http://pypi python org/pypi/pip</a> says: <blockquote> pip is able to uninstall most installed packages with pip uninstall package-name Known exceptions include pure-distutils packages installed with python setup py install >(such packages leave behind no metadata allowing determination of what files were >installed) </blockquote> Is there another way to install my module that pip will recognize? By the way I am using a windows computer Just wanted to mention that in case there are different solutions for Windows Linux and Mac
You are giving pip a Python file and not a package name so it does not know what to do If you want pip to remove it try providing the name of the package this setup py file is actually part of There are some good suggestions in this related thread: <a href="http://stackoverflow com/questions/1550226/python-setup-py-uninstall">python setup py uninstall</a>
How to get the indices list of all NaN value in numpy array? Say now I have a numpy array which is defined as ````[[1 2 3 4] [2 3 NaN 5] [NaN 5 2 3]] ```` Now I want to have a list that contains all the indices of the missing values which is `[(1 2) (2 0)]` at this case Is there any way I can do that?
<a href="http://docs scipy org/doc/numpy-1 10 1/reference/generated/numpy isnan html">np isnan</a> combined with <a href="http://docs scipy org/doc/numpy-1 10 0/reference/generated/numpy argwhere html">np argwhere</a> ````x = np array([[1 2 3 4] [2 3 np nan 5] [np nan 5 2 3]]) np argwhere(np isnan(x)) ```` output: ````array([[1 2] [2 0]]) ````
How debug or trace DBus? I writing Dbus service implementing some protocol My service sends to client message with unexpected data (library i used has some bugs that i want to overwrite) How to inspect trace client calls? I want to determine what client wants and locate buggy method Or how to trace all calls in service? I has much of `logger debug()` inserted Service is python client is c How to specify path or service to monitor in `dbus-monitor` with sender and reciever?
`dbus-monitor "sender=org freedesktop Telepathy Connection ******"`
Invalid syntax object I/O ````# -*- coding: utf-8 -*- import easygui file = open("data txt"[ "r+"]) Msg1 = easygui multenterbox(title = 'ข้อมูล' fieldName=['ชื่อ' 'นามสกุล' 'ที่อยู่'] file write(Msgl) ```` Running this code I get the error ````file write(Msgl) ^ invalid syntax ```` It is too ````file = open("data txt"[ "r+"]) ^ SyntaxError: invalid syntax Script terminated ```` Error again SyntaxError
Try this: ````# -*- coding: utf-8 -*- import easygui file = open("data txt"[ "r+"]) Msg1 = easygui multenterbox(title = 'ข้อมูล' fieldName=['ชื่อ' 'นามสกุล' 'ที่อยู่']) file write(Msgl) ```` As another poster said you are missing a closing parenthesis and it is wrapping to the next line causing an error
UnicodeDecodeError with xlwt I am using python with xlwt and have a problem <strong>My code:</strong> ````tickets = cursor fetchall () largo = len(tickets) cursor close () conn close () row = 4 for t in tickets: hoja write(row 1 t[0]) hoja write(row 2 epoch2fecha(t[1])) hoja write(row 3 epoch2fecha(t[12])) hoja write(row 6 t[10]) hoja write(row 7 t[9]) hoja write(row 8 t[6]) hoja write(row 9 t[3]) row = 1 if(row == largo+1): break libro save('Informe xls') ```` <strong>Error:</strong> ````libro save('informe xlsx') File "build/bdist linux-x86_64/egg/xlwt/Workbook py" line 662 in save File "build/bdist linux-x86_64/egg/xlwt/Workbook py" line 637 in get_biff_data File "build/bdist linux-x86_64/egg/xlwt/Workbook py" line 599 in __sst_rec File "build/bdist linux-x86_64/egg/xlwt/BIFFRecords py" line 76 in get_biff_record File "build/bdist linux-x86_64/egg/xlwt/BIFFRecords py" line 91 in _add_to_sst File "build/bdist linux-x86_64/egg/xlwt/UnicodeUtils py" line 50 in upack2 UnicodeDecodeError: 'ascii' codec cannot decode byte 0xf3 in position 6: ordinal not in range(128) ````
Have you tried encoding latin-1 for workbook?? ````from xlwt import Workbook hoja = Workbook(encoding='latin-1') ````
Parse email fields I want to parse email adresses from a `To:` email field Indeed when looping on the emails in a mbox: ````mbox = mailbox mbox('test mbox') for m in mbox: print m['To'] ```` we can get things like: ````info@test org Blahblah <blah@test com&gt; <another@blah org&gt; "Hey" <last@one com&gt; ```` that should be parsed into: ````[{email: "info@test org" name: ""} {email: "blah@test com" name: "Blahblah"} {email: "another@blah org" name: ""} {email: "last@one com" name: "Hey"}] ```` Is there something already built-in (in `mailbox` or another module) for this or nothing? <them>I read a few times <a href="https://docs python org/2/library/email message html#module-email message" rel="nofollow">this doc</a> but I did not find something relevant </them>
<strong>`email parser` has the modules you are looking for</strong> `email message` is still relevant because the parser will return messages using this structure so you will be getting your header data from that But to actually <them>read</them> the files in `email parser` is the way to go
What routes used Oklahoma City as a major route change?
I-35, I-40 and I-44
Edit text from html with BeautifulSoup I am currently trying to extract the html elements which have a text on their own and wrap them with a special tag For example my HTML looks like this: ````<ul class="myBodyText"&gt; <li class="fields"&gt; This text still has children <b&gt; Simple Text </b&gt; <div class="s"&gt; <ul class="section"&gt; <li style="padding-left: 10px;"&gt; Hello <br/&gt; World </li&gt; </ul&gt; </div&gt; </li&gt; </ul&gt; ```` I am trying to wrap tags only around the tags so I can further parse them at a later time so I tried to make it look like this: ````<ul class="bodytextAttributes"&gt; <li class="field"&gt; [Editable]This text still has children[/Editable] <b&gt; [Editable]Simple Text[/Editable] </b&gt; <div class="sectionFields"&gt; <ul class="section"&gt; <li style="padding-left: 10px;"&gt; [Editable]Hello [/Editable]<br/&gt; [Editable]World[/Editable] </li&gt; </ul&gt; </div&gt; </li&gt; </ul&gt; ```` My script so far which iterates just fine but the placement of the edit placeholders is not working and I have currently no idea how I can check this: ````def parseSection(node): b = str(node) changes = set() tag_start tag_end = extractTags(b) # index 0 is the element itself for cell in node findChildren()[1:]: if cell findChildren(): cell = parseSection(cell) else: # safe to extract with regular expressions only 1 standardized tag created by BeautifulSoup subtag_start subtag_end = extractTags(str(cell)) changes add((str(cell) "[/EditableText]{0}[EditableText]{1}[/EditableText]{2}[EditableText]" format(subtag_start str(cell text) subtag_end))) text = extractText(b) for change in changes: text = text replace(change[0] change[1]) return bs("{0}[EditableText]{1}[/EditableText]{2}" format(tag_start text tag_end) "html parser") ```` The script generates following: ````<ul class="myBodyText"&gt; [EditableText] <li class="fields"&gt; This text still has children [/EditableText] <b&gt; [EditableText] Simple Text [/EditableText] </b&gt; [EditableText] <div class="s"&gt; <ul class="section"&gt; <li style="padding-left: 10px;"&gt; Hello [/EditableText] <br/&gt; [EditableText][/EditableText] <br/&gt; [EditableText] World </li&gt; </ul&gt; </div&gt; </li&gt; [/EditableText] </ul&gt; ```` How I can check this and fix it? I am grateful for every possible answer
There is a built-in <a href="http://www crummy com/software/BeautifulSoup/bs4/doc/#replace_with" rel="nofollow">`replace_with()`</a> method that fits the use case nicely: ````soup = BeautifulSoup(data) for node in soup find_all(text=lambda x: x strip()): node replace_with("[Editable]{}[/Editable]" format(node)) print soup prettify() ````
A module of Python-2 7 not getting imported when it is definitely installed My pandas package is not getting imported When I try to check if I have pandas using the command ````python -c "import pandas" ```` It shows some strange error like ````<module 'numpy' from 'numpy pyc'&gt; 'module' object has no attribute 'dtype' Traceback (most recent call last): File "<string&gt;" line 1 in <module&gt; File "/usr/lib/python2 7/dist-packages/pandas/__init__ py" line 6 in <module&gt; from import hashtable tslib lib File "numpy pxd" line 157 in init pandas hashtable (pandas/hashtable c:21706) AttributeError: 'module' object has no attribute 'dtype' ````
You have a <them>local</them> file named `numpy py` which is being imported instead of the globally installed NumPy project: ````<module 'numpy' from 'numpy pyc'&gt; ```` Remove or rename that file and delete the associated `numpy pyc` file next to it Your local file has no name `dtype` only the `numpy` <them>package</them> installed in your `site-packages` does but it cannot be loaded when your file is found first every time
What form of speech shows that Sanskrit and Prakrits existed together?
Sanskrit dramas
I need to use a function in order to get a return instead printing the output A catering company has hired you to help with organizing and preparing customer's orders You are given a list of each customer's desired items and must write a program that will count the number of each items needed for the chefs to prepare The items that a customer can order are: salad hamburger and water Write a function called item_order that takes as input a string named order The string contains only words for the items the customer can order separated by one space The function returns a string that counts the number of each item and consolidates them in the following order: salad:[# salad] hamburger:[# hambruger] water:[# water] If an order does not contain an item then the count for that item is 0 Notice that each item is formatted as [name of the item][a colon symbol][count of the item] and all item groups are separated by a space For example: • If order = "salad water hamburger salad hamburger" then the function returns "salad:2 hamburger:2 water:1" • If order = "hamburger water hamburger" then the function returns "salad:0 hamburger:2 water:1" This is the code so far: ````s = '"hamburger water hamburger water salad "' #The value of s will be received by the user only with the options in s subs = 'salad' count =0 flag=True start=0 while flag: a = s find(subs start) if a==-1: flag=False else: count+=1 start=a+1 if count==0: salad="salad:0" else: b=str(count) c=subs+':' salad=c+b subs = 'water' count =0 flag=True start=0 while flag: a = s find(subs start) if a==-1: flag=False else: count+=1 start=a+1 if count==0: water="water:0" else: b=str(count) c=subs+':' water=c+b subs = 'hamburger' count =0 flag=True start=0 while flag: a = s find(subs start) if a==-1: flag=False else: count+=1 start=a+1 if count==0: hamburger="hamburger:0" else: b=str(count) c=subs+':' hamburger=c+b print salad hamburger water ````
````def item_order(order): new_order = order split() sal = 0 wat = 0 hum = 0 for a in range(len(new_order)): if new_order[a] == 'salad': sal = sal 1 elif new_order[a] == 'water': wat = wat 1 elif new_order[a] == 'hamburger': hum = hum 1 return ('salad:' str(sal) ' ' 'hamburger:' str(hum) ' ' 'water:' str(wat)) ````
translate python method to ruby What would be the correct translation of the following Python method to Ruby? ````def uniqueCombinations(self items n): """ items: list of elements n: number in a group """ if n == 0: yield [] else: for i in range(len(items)-n+1): for cc in uniqueCombinations(items[i+1:] n-1): yield [items[i]]+cc ```` What I want to do is call ````uniqueCombinations(['01' '02' '03'] 2) ```` and get ````[['01' '02'] ['01' '03'] ['02' '03']] ```` This is what I have so far ````def uniq_c(items n) if n == 0 yield [] else puts items inspect range_max = items length-n+1 for i in (0 range_max) you = uniq_c(items[(i+1) -1] n-1) { |x| x } you each do |cc| yield [items[i]] cc end end end end ```` but I get this: ````in `+': cannot convert Fixnum into Array (TypeError) ````
````yield [items[i]] cc ```` You are attempting to concatenate an array ([items[i]]) and a Fixnum (cc) You could instead turn both into an array or use the << method to push cc onto [items[i]] ````yield [items[i]] << cc ````
Asynchronous interactive Python script I am trying to write a simple Python script to interface with a chat server It would poll the server for updates and allow the user to enter text to send to the server as chat I can kind of get something hacked together with multithreading but it looks terrible Is there a nice simple way to display updating information on the screen while also accepting user input? I would prefer to do it without curses
Let the display window/screen be powered by a temp local db Code 1: Updates the screen from db You can use infinite loop with or without a pause (screen refresh rate) Code 2: Updates the db no sooner the user enters something Code 3: Continuously check for updates from Chat Server and updates the db no sooner a new resposes are received
When did Catalan develop in the Eastern Pyrenees?
9th century
What is the name Of the U.S. Patent office in Detroit?
Elijah J. McCoy Satellite Office
Robust weighted random string generator I have implemented the following class to generate either 'p' or 'q' based on a input frequency of 'p' However this implementation breaks if the frequency gets smaller than the size of the list used to store the options Is there a way in which I can implement this to work for any value of p? ````from random import random class AlleleGenerator(object): """ allele generator - will break if p < 0 001 """ def __init__(self p): """construct class and creates list to select from""" self values = list() for i in xrange(int(1000*p)): self values append('p') while len(self values) <= 1000: self values append('q') def next(self): """Returns p or q based on allele frequency""" rnd = int(random() * 1000) return self values[rnd] def __call__(self): return self next() ````
Do not use `self values` In `next` just generate a random number between 0 and 1 and return `'p'` if the random number is less than `p`: ````from random import random class AlleleGenerator(object): def __init__(self p): """construct class and creates list to select from""" self p = p def next(self): """Returns p or q based on allele frequency""" return 'p' if random() < self p else 'q' def __call__(self): return self next() ```` Also be careful <a href="https://www youtube com/watch?v=o9pEzgHorH0#t=9m26s">not to use classes</a> when a function suffices For example you might consider using a <a href="https://wiki python org/moin/Generators">generator function</a>: ````from random import random def allele_generator(p): while True: yield 'p' if random() < p else 'q' agen = allele_generator(0 001) for i in range(3): print(next(agen)) ````
importing a JPEG image into an IPython (notebook) program I am using a IPython notebook to write a program using pygame library Here I want to import an image file to the programme Following is the code piece I would have used ````car = pygame image load('car jpg') ```` But to do this the image has to be in the same directory as the python file Where are these IPython notebook files saved? Or is there any other way I can import this file to program in IPython notebook? I am using windows 7
There are an number of ways to change directories or specify full paths: - <a href="http://ipython org/ipython-doc/dev/interactive/reference html#magic-command-system" rel="nofollow">IPython understands</a> the `cd` command to change directories (if 'automagic' is enabled; use `%cd` if not) or - use <a href="http://docs python org/2/library/os html#os chdir" rel="nofollow">os chdir</a> or - specify a path: ````load('/path/to/car jpg') ```` or ````import os load(os path expanduser('~/path/to/car jpg')) # relative to user's home directory ```` or ```` IMAGEDIR = '/path/to/images' load(os path join(IMAGEDIR 'car jpg')) ```` Although `cd` is convenient while working in IPython for your program you are better off specifying a full path to `car jpg`
Sharing a result queue among several processes The documentation for the `multiprocessing` module shows how to pass a queue to a process started with `multiprocessing Process` But how can I share a queue with asynchronous worker processes started with `apply_async`? I do not need dynamic joining or anything else just a way for the workers to (repeatedly) report their results back to base ````import multiprocessing def worker(name que): que put("%d is done" % name) if __name__ == '__main__': pool = multiprocessing Pool(processes=3) q = multiprocessing Queue() workers = pool apply_async(worker (33 q)) ```` This fails with: `RuntimeError: Queue objects should only be shared between processes through inheritance` I understand what this means and I understand the advice to inherit rather than require pickling/unpickling (and all the special Windows restrictions) But how <them>do</them> I pass the queue in a way that works? I cannot find an example and I have tried several alternatives that failed in various ways Help please?
Try using <a href="http://docs python org/library/multiprocessing html#sharing-state-between-processes">multiprocessing Manager</a> to manage your queue and to also make it accessible to different workers ````import multiprocessing def worker(name que): que put("%d is done" % name) if __name__ == '__main__': pool = multiprocessing Pool(processes=3) m = multiprocessing Manager() q = m Queue() workers = pool apply_async(worker (33 q)) ````
to use charts in app (created using django) created using pylab in the html file My code: ````<html&gt; <style type="text/css"&gt; h1 { position: absolute; top: 5px; left: 200px; } form #Edit1 { position: absolute; top: 37px; left: 410px; } form #Edit2 { position: absolute; top: 37px; left: 840px; } </style&gt; <font size="4" face="arial" color="#0000FF"&gt; <h1&gt;XML Search</h1&gt; </font&gt; <br/&gt; <br/&gt; <Form Action ="/search/" Method ="POST"&gt; <div id="Edit1"&gt; <INPUT TYPE = 'VARCHAR' name ='word' VALUE ="" size = "50"&gt; </div&gt; <div id="Edit2"&gt; <INPUT TYPE = "Submit" VALUE = "Search"&gt; </div&gt; <br/&gt; <hr/&gt; {% csrf_token %} </Form&gt; {% if list1 %} <br/&gt; <head&gt; #!/usr/bin/python # make a horizontal bar chart from pylab import * val = 3+10*rand(5) # the bar lengths pos = arange(5)+ 5 # the bar centers on the x axis figure(1) barh(pos val align='center') {% for l in list1 %} xticks(pos ({{l file_name}} )) {% endfor %} xlabel('Performance') title('How fast do you want to go today?') grid(True) show() </head&gt; <body&gt; <div id="chart_div" style="width: 1000px; height: 500px;"&gt;</div&gt; </body&gt; {% endif %} </html&gt; ```` I have created an app in django called 'search' which searches the keywords entered by the user in 10xml documents and maintain the frequency of their occurrence for each file When user enters the words he gets the results as graphs This above mentioned html code file is redirected from views py file On running the app on the server the python code employed alongwith the html code gets printed as it is when user enters the keywords How can I display the charts created in pylab in html page? //////////////////////////////////////////////////////////// I have another idea I used up google charts earlier and they are working fine The only problem with them is that they will not work if there is no internet and this will be a drawback in may app Is there any way out to solve this I mean how can we use google charts statically ? If anyone of you want you want me to upload my google charts code I can do that Please help It is urgent Please help I am new to django python and charts
You need to use the FigureCanvasAgg backend and return a HttpResponse See for instance: [Django with Matplotlib][1] <a href="http://stackoverflow com/questions/1874642/how-to-use-matplotlib-in-django">how to use matplotlib in django?</a>
What was Burke made chairman of in 1781?
the Commons Select Committee on East Indian Affairs
Async http request with python3 Is there any way to make async python3 like node js do? I want a minimal example I have tried the below but still works with sync mode ````import urllib request class MyHandler(urllib request HTTPHandler): @staticmethod def http_response(request response): print(response code) return response opener = urllib request build_opener(MyHandler()) try: opener open('http://www google com/') print('exit') except Exception as e: print(e) ```` If the async mode works the `print('exit')` should display first Can anyone help?
Using threading (based on your own code): ````import urllib request import threading class MyHandler(urllib request HTTPHandler): @staticmethod def http_response(request response): print(response code) return response opener = urllib request build_opener(MyHandler()) try: thread = threading Thread(target=opener open args=('http://www google com' )) thread start() #begin thread execution print('exit') # other program actions thread join() #ensure thread in finished before program terminates except Exception as e: print(e) ````
error in inaugural corpus in nltk I have an error while running a program given in NLP with python as follows ```` import nltk from nltk corpus import inaugural &gt;&gt;&gt; cfd = nltk ConditionalFreqDist( (target file[:4]) for fileid in inaugural fileids() for w in inaugural words(fileid) for target in ['america' 'citizen'] if w lower() startswith(target)) Traceback (most recent call last): File "<stdin&gt;" line 3 in <module&gt; File "/usr/local/lib/python2 7/dist-packages/nltk/probability py" line 1729 in __init__ for (cond sample) in cond_samples: File "<stdin&gt;" line 6 in <genexpr&gt; TypeError: 'type' object has no attribute '__getitem__' ```` I am new to python what does this error exactly means
The problem is `file[:4]` <a href="https://docs python org/2/library/stdtypes html#file-objects" rel="nofollow">`file`</a> is an object that does not support slicing (`[:4]`) <a href="https://nltk googlecode com/svn/trunk/doc/api/nltk probability ConditionalFreqDist-class html" rel="nofollow">nltk ConditionalFreqDist</a> seems to take a list of tuples Eventually you wanted to write `fileid` instead of `file`?
Issues trying to insert string to SQL Server I am trying to insert a string to a SQL DB starting with `0x` but it keeps failing on the insert The characters that come after `0x` are random characters that range from A-Z a-z and 0-9 with no set length I tried to get around it by adding a letter in front of the string and update it afterwards but it does not work I am using SQL statement I am trying to mimic ````insert into [TestDB] [dbo] [S3_Files] ([Key] [IsLatest] [LastModified] [MarkedForDelete] [VersionID]) values ('pmtg-dox/CCM/Trades/Buy/Seller_Provided_-_Raw_Data/C''Ds_v2/NID3153422 pdf' '1' '2015-10-11' 'Yes' '0xih91kjhdaoi23ojsdpf') ```` Python Code ````import pymssql as mssql cursor execute("insert into [TestDB] [dbo] [S3_Files] ([Key] [IsLatest] [LastModified] [MarkedForDelete] [VersionID]) values (%s %s %s %s %s)" (deleteitems['Key'] deleteitems['IsLatest'] deleteitems['LastModified'] MarkedforDelete deleteitems['VersionId'])) conn_db commit() ```` <blockquote> pymssql ProgrammingError: (102 "Incorrect syntax near 'qb_QWQDrabGr7FTBREfhCLMZLw4ztx' DB-Lib error message 20018 severity 15: General SQL Server error: Check messages from the SQL Server") </blockquote> Is there a way to make Python pymssql\mysql force insert the string? Is there a string manipulation technique that I am not using? I have tried pypyodbc but no luck Edit: My current patch is to alter the string and add a flag to the row so I remember that the string starts with `0x`
This is the solution that I came up with Since running the insert command with the appropriate values worked I created a stored procedure in SQL to handle my request ````USE [TestDB] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo] [stp_S3Files] @Key_ varchar(4000) @IsLatest_ varchar(200) @Size_ varchar(200) @LastModified_ varchar(200) @MarkedForDelete_ varchar(200) @VersionID_ varchar(200) AS insert into [TestDB] [dbo] [S3_Files] ([Key] [IsLatest] [Size(Bytes)] [LastModified] [MarkedForDelete] [VersionID]) values (@Key_ @IsLatest_ @Size_ @LastModified_ @MarkedForDelete_ @VersionID_) ```` Then I call it through Python ````modkey = deleteitems['Key'] replace("'" "''") cursor execute("""exec TestDB dbo stp_S3Files @Key_ = '%s' @IsLatest_ = %s @Size_ = '%s' @LastModified_ = '%s' @MarkedForDelete_ = '%s' @VersionID_ = '%s' """ %(modkey deleteitems['IsLatest'] deleteitems['Size'] deleteitems['LastModified'] MarkedforDelete deleteitems['VersionId'])) conn_db commit() ```` Note: the string replace is to handle path names with ' to escape the character I hope this helps someone who has the same issue down the road
How to find and uninstall the numpy duplicate versions I am trying to install the library GPy Although the installation is successful I have a question on my numpy version GPy library can be found here <a href="https://github com/SheffieldML/GPy" rel="nofollow">https://github com/SheffieldML/GPy</a> The current version of my numpy is 1 9 3 ````&gt;&gt;&gt; import numpy &gt;&gt;&gt; numpy version version '1 9 3' ```` But when I perform `python setup py install` for GPy it refers to numpy 1 10 0 I checked in python 2 7/site-packages there only one version of numpy exist that too 1 9 3 ````Using /home/vinod/anaconda/lib/python2 7/site-packages Searching for scipy==0 16 0 Best match: scipy 0 16 0 Adding scipy 0 16 0 to easy-install pth file Using /home/vinod/anaconda/lib/python2 7/site-packages Searching for numpy==1 10 0 Best match: numpy 1 10 0 Adding numpy 1 10 0 to easy-install pth file Using /home/vinod/anaconda/lib/python2 7/site-packages Finished processing dependencies for GPy==0 8 8 vinod@vinod-Lenovo-G580:~/GPy$ ```` Since it is referring to another version am getting error like ````File"__init__ pxd" line 155 in init GPy util linalg_cython (GPy/util/linalg_cython c:4238) ValueError: numpy dtype has the wrong size try recompiling ```` Could anyone tell me how to find and remove the numpy 1 10 0 ?
From the <a href="http://conda pydata org/docs/faq html#pinning-packages" rel="nofollow">conda FAQ</a>: ````conda update numpy --no-pin ````
How to define a (n 0) sparse matrix in scipy or how to assemble a sparse matrix column wise? I have a loop that in each iteration gives me a column `c` of a sparse matrix `N` To assemble/grow/accumulate `N` column by column I thought of using ````N = scipy sparse hstack([N c]) ```` To do this it would be nice to initialize the matrix with with rows of length 0 However ````N = scipy sparse csc_matrix((4 0)) ```` raises a `ValueError: invalid shape` Any suggestions how to do this right?
You must use at least `1` in your shape ````N = scipy sparse csc_matrix((4 1)) ```` Which you can stack: ````print scipy sparse hstack( (N N) ) #<4x2 sparse matrix of type '<type 'numpy float64'&gt;' # with 0 stored elements in COOrdinate format&gt; ````
How to translate entire txt file using Google Translate API in Python? I am trying to translate an entire ` txt` file using Google Translate API in Python The default code is: ````print(service translations() list(source='zh' target='en' q=['上海熙缘节能环保科技服务有限公司' '广东宏德科技物业有限公司']) execute()) if __name__ == '__main__': main() ```` How can I modify this code so it can translate a txt file?
The simple and efficient solution from my own perspective without knowing the complex details and I assume the parameter `q` is the sequence of sentences/words that you want to translate will be: ````print(service translations() list( source='zh' target='en' q= (line rstrip() for line in open('file txt') ) execute()) ```` I see your expression to be really unpythonic you nest a lot of expressions into one single line
IOError: [Errno 22] invalid mode ('wb') or filename: I keep getting the following error ````IOError: [Errno 22] invalid mode ('wb') or filename: 'C:\\Users\\Viral Patel\\Documents\\GitHub\\3DPhotovoltaics\\Data_Output\\Simulation_Data\\Raw_Data\\Raw_Simulation_Data_2014-03-24 17:21:20 545000 csv' ```` I think it is due to the timestamp at the end of the filename Any ideas?
You cannot use `:` in Windows filenames see <a href="http://msdn microsoft com/en-us/library/windows/desktop/aa365247%28v=vs 85%29 aspx">Naming Files Paths and Namespaces </a>; it is one of the reserved characters: <blockquote> - The following reserved characters: - `<` (less than) - `&gt;` (greater than) - `:` (colon) - `"` (double quote) - `/` (forward slash) - `\` (backslash) - `|` (vertical bar or pipe) - `?` (question mark) - `*` (asterisk) </blockquote> Use a different character not on the reserved character list
task with number of task can run along that in celery As I see in celery It can get number of tasks for a worker that can run them at a same time I need run a task and set number of tasks can run simultaneously with this task <img src="http://i stack imgur com/Gw9rY png" alt="celery with workers"> Therefore If I set this number to 2 and this task send to worker with 10 threads worker can run just one another task
Worker will reserve tasks for each worker's tread If you want to limit the number of tasks worker can execute the same time you should configure your concurrency (e g to limit 1 task at the time you need worker with 1 process `-c 1`) You can also check prefetch configuration but it only defines the number of tasks reserved for each process of the worker Here is Celery documentation where prefetch configuration explained: <a href="http://celery readthedocs org/en/latest/userguide/optimizing html" rel="nofollow">http://celery readthedocs org/en/latest/userguide/optimizing html</a>
What was the US policy when France declared war on England in 1793?
to remain neutral
What popular color was imported from France in the 18th century?
null
Why do I have to write this import statement twice? Here is my folder structure: ````/ Thermal_Formatter Thermal_Formatter py __init__ py test py ```` In `Thermal_Formatter py` I have this method: ````def processAndPrint(text): ```` in `test py` this does NOT work: ````import Thermal_Formatter Thermal_Formatter processAndPrint(something) ```` but this does: ````import Thermal_Formatter Thermal_Formatter Thermal_Formatter Thermal_Formatter processAndPrint(something) ```` Why does it work when I write the module name twice both in the import statement and the module call?
Because `Thermal_Formatter` module is inside a package with same name Try: ````from Thermal_Formatter import Thermal_Formatter Thermal_Formatter processAndPrint(something) ```` If you want a more saner way to use it
How long have historians been hiding information about the Masonic movement?
null
Model and Validation Confusion - Looking for advice I am somewhat new to Python Django and I would like some advice on how to layout the code I would like to write I have the model written that allows a file to be uploaded In the models save method I am checking if the file has a specific extension If it has an XML extension I am opening the file and grabbing some information from the file to save in the database I have this model working I have tested it in the built-in administration It works Currently when there is an error (it is not an XML file; the file cannot be opened; a specific attribute does not exist) I am throwing an custom "Exception" error What I <them>would</them> like to do is some how pass these "Exception" error messages to the view (whether that is a custom view or the built-in administration view) and have an error message displayed like if the forms library was being used Is that possible? I am starting to think I am going to have to write the validation checks again using the forms library If that is the case is it possible to still use the built-in administration template but extend the form it uses to add these custom validations? Anything to help my confusion would be appreciated <hr /> <strong>UPDATE:</strong> Here is my model so far for those who are asking "nzb" is the XML file field <br /> <a href="http://dpaste com/hold/6101/" rel="nofollow">http://dpaste com/hold/6101/</a> <blockquote> The admin interface will use the Form you associate with your model; your own views can also use the form </blockquote> This is exactly what I would like to do However I do not know how to associate my forms with my models When ever I have created forms in the past they have always acted as their own entity I could never get the administration views to use them while using the ModelForm class Can you shead any light on this? I have read over the link you gave me and it seams to be what I have done in the past with no luck <blockquote> Getting attributes from the file should probably be a method </blockquote> Sorry could you please elaborate on this? A method where? <hr /> <strong>UPDATE:</strong> It seams I have been compleatly missing this step to link a form to the administration view <a href="http://docs djangoproject com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">http://docs djangoproject com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin</a> This should now allow me to do the validation in a Form However I am still confused about how to actually handle the validation S Lott says it should be a method?
The Form errors are automatically part of the administrative view See <a href="http://docs djangoproject com/en/dev/ref/forms/validation/#ref-forms-validation" rel="nofollow">http://docs djangoproject com/en/dev/ref/forms/validation/#ref-forms-validation</a> You are happiest if you validate in a Form -- that is what Forms are for The admin interface will use the Form you associate with your model; your own views can also use the form Getting attributes from the file should probably be a separate method of the model class The separate method of the model class can be used by the `save()` method of the model class or invoked at other times by view functions <hr /> "I could never get the administration views to use them while using the ModelForm class " <a href="http://docs djangoproject com/en/dev/ref/contrib/admin/#form" rel="nofollow">http://docs djangoproject com/en/dev/ref/contrib/admin/#form</a> <a href="http://docs djangoproject com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">http://docs djangoproject com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin</a> <hr /> "I am still confused about how to actually handle the validation S Lott says it should be a method?" Validation in a form is done with a `clean()` method or a `clean_somefield()` method The "Adding custom validation to the admin" link (above) shows how to add the `clean_name` method to the "MyArticleAdminForm" form If you are still confused trying actually typing the code from the Django web page and see what it does
Python setuptools - clean does not work I created a python package using setup tools and it installs fine but when I try to clean (using verbose mode) the following message shows and <strong>nothing is cleaned (the build and dist directories are NOT removed)</strong>: ````running clean 'build/temp linux-i686-2 7' does not exist -- cannot clean it ```` The contents of the build package are the following: ````bdist linux-i686 lib linux-i686-2 7 ```` So my question is why does not this temp linux-i686-2 7 folder exist? Should it? Why does clean think it should be there? By the way my setup py file is very simple I just copied supervisord's file (<a href="https://github com/Supervisor/supervisor/blob/master/setup py" rel="nofollow">https://github com/Supervisor/supervisor/blob/master/setup py</a>) and modified just the names
The 'build/temp linux-i686-2 7' is one of the normal place for py and so files to be stored if you do: ````python setup py build ```` THat is probably why it try to cleans it just to be sure Without verbose you do not get that warning
Can I set a header with python's SimpleHTTPServer? I am using `SimpleHTTPServer` to test some webpages I am working on It works great however I need to do some cross-domain requests That requires setting a `Access-Control-Allow-Origin` header with the domains the page is allowed to access Is there an easy way to set a header with SimpleHTTPServer and serve the original content? The header would be the same on each request
````# coding: utf-8 import SimpleHTTPServer import SocketServer PORT = 9999 def do_GET(self): self send_response(200) self send_header('Access-Control-Allow-Origin' 'http://example com') self end_headers() Handler = SimpleHTTPServer SimpleHTTPRequestHandler Handler do_GET = do_GET httpd = SocketServer TCPServer(("" PORT) Handler) httpd serve_forever() ````
Extracting table data from html with python and BeautifulSoup I am new with python and beautifulsopu lib I have tried many things but no luck My html code could be like: ````<form method = "post" id="FORM1" name="FORM1"&gt; <table cellpadding=0 cellspacing=1 border=0 align="center" bgcolor="#cccccc"&gt; <tr&gt; <td class="producto"&gt;<b&gt;Club</b&gt;<br&gt; <input value="CLUB TENIS DE MESA PORTOBAIL" disabled class="txtmascaraform" type="TEXT" name="txtClub" size="60" maxlength="55"&gt; </td&gt; <tr&gt; <td colspan="2" class="producto"&gt;<b&gt;Nombre Equipo</b&gt;<br&gt; <input value="C T M PORTOBAIL" disabled class="txtmascaraform" type="TEXT" name="txtNomEqu" size="100" maxlength="80"&gt; </td&gt; </tr&gt; <tr&gt; <td class="producto"&gt;<b&gt;Telefono fijo</b&gt;<br&gt; <input value="63097005534" disabled class="txtmascaraform" type="TEXT" name="txtTelf" size="15" maxlength="10"&gt; </td ```` and I need JUST to take what is within <"b"><"/b"> and its "input value" Many thanks!!
First <a href="http://www crummy com/software/BeautifulSoup/bs4/doc/#find" rel="nofollow">find()</a> your form by id then <a href="http://www crummy com/software/BeautifulSoup/bs4/doc/#find-all" rel="nofollow">find_all()</a> inputs inside and get the value of `value` <a href="http://www crummy com/software/BeautifulSoup/bs4/doc/#attributes" rel="nofollow">attribute</a>: ````from bs4 import BeautifulSoup data = """<form method = "post" id="FORM1" name="FORM1"&gt; <table cellpadding=0 cellspacing=1 border=0 align="center" bgcolor="#cccccc"&gt; <tr&gt; <td class="producto"&gt;<b&gt;Club</b&gt;<br&gt; <input value="CLUB TENIS DE MESA PORTOBAIL" disabled class="txtmascaraform" type="TEXT" name="txtClub" size="60" maxlength="55"&gt; </td&gt; <tr&gt; <td colspan="2" class="producto"&gt;<b&gt;Nombre Equipo</b&gt;<br&gt; <input value="C T M PORTOBAIL" disabled class="txtmascaraform" type="TEXT" name="txtNomEqu" size="100" maxlength="80"&gt; </td&gt; </tr&gt; <tr&gt; <td class="producto"&gt;<b&gt;Telefono fijo</b&gt;<br&gt; <input value="63097005534" disabled class="txtmascaraform" type="TEXT" name="txtTelf" size="15" maxlength="10"&gt; </td&gt; </tr&gt; </table&gt; </form&gt;""" soup = BeautifulSoup(data) form = soup find("form" {'id': "FORM1"}) print [item get('value') for item in form find_all('input')] # UPDATE for getting table cell values table = form find("table") print [item text strip() for item in table find_all('td')] ```` prints: ````['CLUB TENIS DE MESA PORTOBAIL' 'C T M PORTOBAIL' '63097005534'] [you'Club' you'Nombre Equipo' you'Telefono fijo'] ````
Unable to install PyRFC I would like to install pyrfc but the package does not seem to exist anymore: ````C:\&gt;easy_install pyrfc-1 9 3-py2 7-win32 egg Searching for pyrfc-1 9 3-py2 7-win32 egg Reading https://pypi python org/simple/pyrfc-1 9 3-py2 7-win32 egg/ Could not find index page for 'pyrfc-1 9 3-py2 7-win32 egg' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi python org/simple/ No local packages or download links found for pyrfc-1 9 3-py2 7-win32 egg error: Could not find suitable distribution for Requirement parse('pyrfc-1 9 3-py2 7-win32 egg') ```` I have also searched the site <a href="https://pypi python org/simple/" rel="nofollow">https://pypi python org/simple/</a> no success there is no such thing like pyrfc I have tried with pip but no luck either Does pyrfc still exist? Any obvious mistakes in what I am doing? Thanks
See <a href="https://github com/SAP/PyRFC" rel="nofollow">https://github com/SAP/PyRFC</a> <strong>A prerequisite to download is having a customer or partner account on SAP Service Marketplace</strong> and if you are SAP employee please check SAP OSS note 1037575 - Software download authorizations for SAP employees If you press on "Download" in this link <a href="http://sap github io/PyRFC/install html" rel="nofollow">http://sap github io/PyRFC/install html</a> - you will be asked for username/password
How to save in * xlsx long URL in cell using Pandas For example I read excel file into DataFrame with 2 columns(id and URL) URLs in input file are like text(without hyperlinks): ````input_f = pd read_excel("input xlsx") ```` Watch what inside this DataFrame - everything was successfully read all URLs are ok in `input_f` After that when I wan't to save this file to_excel ````input_f to_excel("output xlsx" index=False) ```` I got warning <blockquote> <strong>Path</strong>\worksheet py:836: UserWarning: Ignoring URL <strong>'http:// here long URL'</strong> with link or location/anchor > 255 characters since it exceeds Excel's limit for URLS force_unicode(url)) </blockquote> And in output xlsx cells with long URL were empty and URLs become hyperlinks How to fix this?
I tried it myself and got the same problem You could try to create a temp csv file and then use xlsxwriter to create an excel file Once done then delete the tmp file xlsxwriter has a write_string method that will override the auto hyperlinking that excel does This worked for me ````import pandas as pd import csv import os from xlsxwriter workbook import Workbook inData = "C:/Users/martbar/Desktop/test xlsx" tmp = "C:/Users/martbar/Desktop/tmp csv" exFile = "C:/Users/martbar/Desktop/output xlsx" #read in data df = pd read_excel(inData) #send to csv df to_csv(tmp index=False) #convert to excel workbook = Workbook(exFile) worksheet = workbook add_worksheet() with open(tmp 'r') as f: reader = csv reader(f) for are row in enumerate(reader): for c col in enumerate(row): #if you use write instead of write_string you will get the error worksheet write_string(are c col) workbook close() #delete tmp file os remove(tmp) ````
How to authenticate user in Django Comment framework? I am using Django's comment framework as a part of my project With default settings anonymous users can make comments at will I want to change this feature such that only authenticated users can post comments Moreover I want this authenticated user's name to show up next to the comment How do I go about doing so? I have read up on the documentation and I understand the pre-defined comment model has a "user" field which is a ForeignKey to the User model / user who posted the comment (<a href="https://docs djangoproject com/en/dev/ref/contrib/comments/models/" rel="nofollow">Link here</a>) However I do not understand how to assign request user (i e the current authenticated user) to this user field that belongs to the instance of the comment In other words how does Django process the form data on the front-end to the Comment model in the back-end and how can I edit this process such as to assign request user to the user field in the comment model Thanks for the help!
Start from the <a href="https://docs djangoproject com/en/dev/topics/auth/" rel="nofollow">documentation</a> Basically you need to (at least): - enable `django contrib auth` in your `settings py` - define login view - use `@login_required` decorator on the views you want restrict - check `if request user is_authenticated()` in your form processing code
SQLAlchemy self-referential secondary table association I am trying to create a "Product" object in SQLAlchemy and so far I have gotten everything working accept the Product's "accessories" What I have is a Product with a list of field/value pairs (ie Capacity : 12 L etc ) and integer ID and a catalog number I would like to be able to associate certain "accessories" with a given product where these accessories are <them>also</them> products Essentially I just want an association table that has product_id and accessory_id which both reference the ID in the Products table This is what I have so far: ````product_accessories=Table('product_accesssories' Base metadata \ Column('product_id' Integer ForeignKey('product product_id')) \ Column('accessory_id' Integer ForeignKey('product product_id'))) class Product(Base): __tablename__='product' id=Column('product_id' Integer primary_key=True) catNo=Column('catalog_number' String(20)) fields=relationship('ProductField') accessories=relationship('Product' secondary=product_accessories) ```` I get the error "Could not determine join condition between parent/child tables on relationship Product accessories" I have tried fiddling around a bunch with this and have not been able to get anywhere I do not want to lose the unique reference to a product and I feel like there should be an easier way to do this other than wrapping accessories in another class Any help would be greatly appreciated!
````import sqlalchemy as sa from sqlalchemy import orm products_table = sa Table('products' metadata sa Column('id' sa Integer() primary_key=True) sa Column('catalog_number' sa String(20)) ) accessories_table = sa Table('product_accessories' metadata sa Column('product_id' sa ForeignKey(products_table c id) primary_key=True) sa Column('accessory_id' sa ForeignKey(products_table c id) primary_key=True) ) class Product(object): pass class Accessory(object): pass orm mapper(Product products_table properties=dict( accessories=orm relation(Accessory primaryjoin=(products_table c id == accessories_table c product_id) secondaryjoin=(products_table c id == accessories_table c accessory_id) ) )) orm mapper(Accessory accessories_table) ````
How to get background from cv2 BackgroundSubtractorMOG2? Is there any way to obtain background from cv2 BackgroundSubtractorMOG2 in python? In other words is there any technique to compute an image based on last n frames of a video which can be used as background?
Such a technique would be pretty complicated but you might want to look at some keywords: image-stitching gradient-based methods patch-match image filling Matlab for example <a href="http://www mathworks com/help/images/ref/roifill html" rel="nofollow">has a function</a> that tries to interpolate missing values from nearby pixels You could extend this method to work with 3D (should not be so difficult in linear case) More generally it is sort of an ill-posed problem since there is no way to know what goes in the missing region Specifically to address your question you might first take the difference between the original frame and the extracted image which should reveal the background Then use ROI fill in or similar method There is likely some examples you can find on the web such as <a href="https://github com/f3anaro/computer-vision-2/blob/master/1-patch-match/patchmatch py" rel="nofollow">this</a>
python Regex match exact word I am trying to match different expressions for addresses: Example: '398 W Broadway' I would like to match W or E (east) or Pl for place etc It is very simple using this regex `(W |West)` for example Yet python re module does not match anything when I input that ````&gt;&gt;&gt; a '398 W Broadway' &gt;&gt;&gt; x = re match('(W |West)' a) &gt;&gt;&gt; x &gt;&gt;&gt; x == None True &gt;&gt;&gt; ````
<a href="http://docs python org/2/library/re html#re match">`re match`</a> matches at the beginning of the input string To match anywhere use <a href="http://docs python org/2/library/re html#re search">`re search`</a> instead ````&gt;&gt;&gt; import re &gt;&gt;&gt; re match('a' 'abc') <_sre SRE_Match object at 0x0000000001E18578&gt; &gt;&gt;&gt; re match('a' 'bac') &gt;&gt;&gt; re search('a' 'bac') <_sre SRE_Match object at 0x0000000002654370&gt; ```` See <a href="http://docs python org/2/library/re html#search-vs-match">`search() vs match()`</a>: <blockquote> Python offers two different primitive operations based on regular expressions: re match() checks for a match only at the beginning of the string while re search() checks for a match anywhere in the string (this is what Perl does by default) </blockquote>
Button Label change on EVT_BUTTON in wxpython? Some system info before proceeding further: Platform: Mac OS X 10 7 1 Python Version: ActiveState Python 2 7 1 wxPython Version: wxPython2 9-osx-cocoa-py2 7 I want the button label to be changed while performing a task So here is what I did/want: ````self run_button=wx Button(self panel ID_RUN_BUTTON label='Install') self Bind(wx EVT_BUTTON self OnRun id=ID_RUN_BUTTON) def OnRun(self evt): self run_button SetLabel('Installing ') #call a function that does the installation task installation_task() #After task completion set the button label back to "Install" self run_button SetLabel('Install')[/code] ```` When I try doing this it does not set the label to "Installing" while the task is being performed Any suggestions how do I achieve this?
The button never gets a chance to redraw itself with the new label because you are running your logic (installation_task()) on the GUI thread You need to run installation_task() on a background thread so you do not lock up the GUI
How do I use opencv to fit a line into a curve like this I am wondering how can I achieve this? <a href="http://i stack imgur com/UkxK7 jpg" rel="nofollow"><img src="http://i stack imgur com/UkxK7 jpg" alt="tangent line"></a> This is is the line I want to fit to the image I have tried Houghline transform But I am unable to achieve this result and I got something like this: <a href="http://i stack imgur com/P8G3F jpg" rel="nofollow"><img src="http://i stack imgur com/P8G3F jpg" alt="tangent line attempt"></a> properties of the line: The line has to be tangent to the black region not cutting through it
The image is already thresholded therefore you can easily <a href="http://docs opencv org/2 4/modules/imgproc/doc/structural_analysis_and_shape_descriptors html?highlight=findcontours#findcontours" rel="nofollow">findContours()</a> This will give you a detailed list of points for the largest contours (you can choose to retrieve the largest as a flag) If you want to simplify it you can using <a href="http://docs opencv org/2 4/modules/imgproc/doc/structural_analysis_and_shape_descriptors html?highlight=findcontours#approxpolydp" rel="nofollow">approxPolyDP</a> Play with the epsilon parameter to get a simpler path I am not sure how a single line can be a tangent to the majority of this complex outline
Who restored the Church of the Holy Sepulchre in the 1040's?
Constantine Monomachos
Writing binary data to a file in Python I am trying to write data (text floating point data) to a file in binary which is to be read by another program later The problem is that this program (in Fort95) is incredibly particular; each byte has to be in exactly the right place in order for the file to be read correctly I have tried using Bytes objects and encode() to write but have not had much luck (I can tell from the file size that it is writing extra bytes of data) Some code I have tried: ````mgcnmbr='42' bts=bytes(mgcnmbr) test_file=open(PATH_HERE/test_file dat' 'ab') test_file write(bts) test_file close() ```` I have also tried: ````mgcnmbr='42' bts=mgcnmbr encode(utf_32_le) test_file=open(PATH_HERE/test_file dat' 'ab') test_file write(bts) test_file close() ```` To clarify what I need is the integer value 42 written as a 4 byte binary Next I would write the numbers 1 and 0 in 4 byte binary At that point I should have exactly 12 bytes Each is a 4 byte signed integer written in binary I am pretty new to Python and cannot seem to get it to work out Any suggestions? Soemthing like <a href="http://stackoverflow com/questions/23781823/how-to-write-binary-and-asci-data-into-a-file-in-python">this</a>? I need complete control over how many bytes each integer (and later 4 byte floating point ) is Thanks
Assuming that you want it in little-endian you could do something like this to write 42 in a four byte binary ````test_file=open(PATH_HERE/test_file dat' 'ab') test_file write(b'\xA2\0\0\0') test_file close() ```` A2 is 42 in hexadecimal and the bytes `'\xA2\0\0\0'` makes the first byte equal to 42 followed by three empty bytes This code writes the byte: 42 0 0 0 Your code writes the bytes to represent the character '4' in UTF 32 and the bytes to represent 2 in UTF 32 This means it writes the bytes: 52 0 0 0 50 0 0 0 because each character is four bytes when encoded in UTF 32 Also having a hex editor for debugging could be useful for you then you could see the bytes that your program is outputting and not just the size
What type of clothing does Parkwood Topshop Athletic Ltd produce?
activewear
How to identify which pyd files are required for the execution of exe files generated using py2exe module I have written a python script and generated an exe using py2exe on Windows 32 bit OS While I am trying to execute the generated exe file I am getting the below error: <hr> ````Traceback (most recent call last): File "program01 py" line 3 in <module&gt; File "PIL\Image pyc" line 67 in <module&gt; File "PIL\_imaging pyc" line 12 in <module&gt; File "PIL\_imaging pyc" line 10 in __load ImportError: DLL load failed: The specified module could not be found ```` <hr> Is there any way to identify the complete list what pyd files are required for my program to be executed Below is my program import statements ````from __future__ import division import os sys math aggdraw from PIL import Image import xml etree ElementTree as ET import lxml etree as LETREE ```` Any kind of help would be appreciated!!! Thanks Ram
You can include modules by adding `options` argument into `setup`: ```` options = {'py2exe': {'bundle_files': 1 'compressed': True "includes" : ['os' 'sys' 'math' 'aggdraw' 'PIL' 'xml etree ElementTree' 'lxml etree' ]} } ```` Only thing that could be different in code above is that you might need to replace `xml etree ElementTree` with `xml` and `lxml etree` with `lxml` as I am not quite sure about those
Restructuring Dataframe I have a dataframe that currently looks as follows and has 262800 rows and 3 columns My dataframe is currently as follows: ```` Currency Maturity value 0 GBP 0 08333333 4 709456 1 GBP 0 08333333 4 713099 2 GBP 0 08333333 4 707237 3 GBP 0 08333333 4 705043 4 GBP 0 08333333 4 697150 5 GBP 0 08333333 4 710647 6 GBP 0 08333333 4 701150 7 GBP 0 08333333 4 694639 8 GBP 0 08333333 4 686111 9 GBP 0 08333333 4 714750 262770 GBP 25 2 432869 ```` I want the dataframe to be of the form below I have taken some steps towards this which included using `melt` in the code below but for some reason that got rid of my `Date` Column and resulted in the dataframe above I am unsure how to get the Date Column back and obtain the Dataframe below: ```` Maturity Date Currency Yield_pct 0 0 08333333 2005-01-04 GBP 4 709456 1 0 08333333 2005-01-05 GBP 4 713099 2 0 08333333 2005-01-06 GBP 4 707237 9 25 2005-01-04 GBP 2 432869 ```` My code is as follows: ````from pandas io excel import read_excel import pandas as pd import numpy as np url = 'http://www bankofengland co uk/statistics/Documents/yieldcurve/uknom05_mdaily xls' # check the sheet number spot: 9/9 short end 7/9 spot_curve = read_excel(url sheetname=8) short_end_spot_curve = read_excel(url sheetname=6) # do some cleaning keep NaN for now as forward fill NaN is not recommended for yield curve spot_curve columns = spot_curve loc['years:'] spot_curve columns name = 'Maturity' valid_index = spot_curve index[4:] spot_curve = spot_curve loc[valid_index] # remove all maturities within 5 years as those are duplicated in short-end file col_mask = spot_curve columns values &gt; 5 spot_curve = spot_curve iloc[: col_mask] short_end_spot_curve columns = short_end_spot_curve loc['years:'] short_end_spot_curve columns name = 'Maturity' valid_index = short_end_spot_curve index[4:] short_end_spot_curve = short_end_spot_curve loc[valid_index] # merge these two time index are identical # ============================================== combined_data = pd concat([short_end_spot_curve spot_curve] axis=1 join='outer') # sort the maturity from short end to long end combined_data sort_index(axis=1 inplace=True) def filter_func(group): return group isnull() sum(axis=1) <= 50 combined_data = combined_data groupby(level=0) filter(filter_func) idx = 0 values = ['GBP'] * len(combined_data index) combined_data insert(idx 'Currency' values) #print combined_data columns values #I had to do the melt combined_data = pd melt(combined_data id_vars=['Currency'])#Arbitrarily melted on 'Currency' as for some reason when I do print combined_data columns values I see that 'Currency' corresponds to 0 08333333 etc print combined_data ````
Can you not add the currency identifier following the `melt`? ````# Copy up to this stage combined_data = combined_data groupby(level=0) filter(filter_func) # My code from here combined_data reset_index(inplace=True drop=False) combined_data rename(columns={'index': 'Date'} inplace=True) # This line assumes you want datetime ignore if you do not combined_data['Date'] = pd to_datetime(combined_data['Date']) result = pd melt(combined_data id_vars=['Date']) result['Currency'] = 'GBP' ```` Output of `result head()` ```` Date Maturity value Currency 0 2005-01-04 0 08333333 4 709456 GBP 1 2005-01-05 0 08333333 4 713099 GBP 2 2005-01-06 0 08333333 4 707237 GBP 3 2005-01-07 0 08333333 4 705043 GBP 4 2005-01-10 0 08333333 4 697150 GBP ````
remove the default select in ForeignKey Field of django admin There are 150k entries in User model When i am using it in django-admin without the raw_id_fields it is causing problem while loading all the entries as a select menu of foreign key is there alternate way so that it could be loaded easily or could become searchable? I have these models as of defined above and there is a User model which is used as ForeignKey in ProfileRecommendation models The database entry for user model consist of around 150k entries I do not want default select option for these foreign fields Instead if can filter them out and load only few entries of the user table How I can make them searchable like autocomplete suggestion? admin py ````class ProfileRecommendationAdmin(admin ModelAdmin): list_display = ('user' 'recommended_by' 'recommended_text') raw_id_fields = ("user" 'recommended_by') search_fields = ['user__username' 'recommended_by__username' ] admin site register(ProfileRecommendation ProfileRecommendationAdmin) ```` models py ````class ProfileRecommendation(models Model): user = models ForeignKey(User related_name='recommendations') recommended_by = models ForeignKey(User related_name='recommended') recommended_on = models DateTimeField(auto_now_add=True null=True) recommended_text = models TextField(default='') ````
you can use method formfield_for_foreignkey something like this: ````class ProfileRecommendationAdmin(admin ModelAdmin): def formfield_for_foreignkey(self db_field request **kwargs): if db_field name == "user": kwargs["queryset"] = User objects filter(is_superuser=True) return super(ProfileRecommendationAdmin self) formfield_for_foreignkey(db_field request **kwargs) ```` or other way is to override the form for that modeladmin class ````from django import forms from django contrib import admin from myapp models import Person class PersonForm(forms ModelForm): class Meta: model = Person exclude = ['name'] class PersonAdmin(admin ModelAdmin): exclude = ['age'] form = PersonForm ```` you can change the widget and use something like the selectize with autocomplete and ajax
GUI apps in python 3 4 I have been looking for a GUI system for python applications for a while and have found these 2 Tkinter and PyQT The issue I am having is that I cannot work out whether PyQT requires the end user to have QT installed and whether Tkinter will work properly on another computer as I have read a lot about it being touchy when it comes to Tk/Tcl version What I am trying to do with it is create an application for a friend so that he can keep track of his beehives more easily and I did not think that having it in a terminal would be the way to go Thanks
I have worked with both in the past and from my observations: <blockquote> whether PyQT requires the end user to have QT installed </blockquote> Yes it does However you can bundle your app along with the dependencies (Python QT) using tools like PyInstaller You will get a single package that you can distribute to your users They can run it without installing anything You can also create custom installers which install Python and QT on the target systems for you Then the users can just run the Python script <blockquote> whether Tkinter will properly on another computer as I have read a lot about it being touchy when it comes to Tk/Tcl version </blockquote> I have never faced any issues with it since I mostly deployed my Tkinter apps to Windows and I installed the same version of Python on the target systems that I used to develop However there might be version conflicts on other platforms (eg Linux/OS X) <blockquote> What I am tying to do with it is create an application for a friend so that he can keep track of his beehives more easily </blockquote> Have you thought about web based GUI? A python script running a webserver on a local machine? You can use the "webbrowser" module to open up a browser to load the url when the script is run There is another alternative: <a href="http://kivy org/" rel="nofollow">Kivy</a>
unittest web scraper in python I am new to unit test I want to write unit test for web scraper that I wrote My scraper collects the data from website which is on local disk where inputting different date gives different results I have the following function in script ````get_date [returns date mentioned on web page] get_product_and_cost [returns product mentioned and their cost] ```` I am not sure what to test in these functions So far I have written this ````class SimplisticTest(unittest TestCase): def setUp(self): data = read_file("path to file") self soup = BeautifulSoup(data 'html5lib') def test_date(self): self assertIsInstance(get_date(self soup) str) def test_date_length(self): self assertEqual(len(get_date(self soup)) 10) if __name__ == '__main__': unittest main() ````
Usually it is good to test a known output from a known input In your case you test for the return type but it would be even better to test if the returned object corresponds to what you would expect from the input and that is where static test data (a test web page in your case) becomes useful You can also test for exceptions with self assertRaises(ExceptionType method args) Refer to <a href="https://docs python org/3 4/library/unittest html" rel="nofollow">https://docs python org/3 4/library/unittest html</a> if you have not already Basically you want to test at least one explicit case (like the test page) the exceptions that can be raised like bad argument type (TypeError or ValueError) or a possible None return type depending on your function Make sure not to test only for the type of the return or the amount of the return but explicitly for the data such that if a change is made that breaks the feature it is found (whereas a change could still return 10 elements yet the elements might contain invalid data) I would also suggest to have one test method for each method: get_date would have its test method test_get_date Keep in mind that what you want to find is if the method does its job so test for extreme cases (big input data as much as it can support or at least the method defines it can) and try to create them such that if the method outputs differently from what is expected based on its definition (documentation) the test fails and breaking changes are caught early on
How to extract sheet from * xlsm and save it as * csv in Python? I have a * xlsm file which has 20 sheets in it I want to save few sheets as * csv (formatting loss is fine) individually Already tried xlrd-xlwt and win32com libraries but could not get through Can anybody please provide a code snippet which does the above processing in Python? I have other python dependencies so no other language would work Thanks
<a href="http://www python-excel org/" rel="nofollow">xlrd</a> should work fine on xlsm files as well I tested the code with a random xlsm file and it worked perfectly ````import csv import xlrd workbook = xlrd open_workbook('test xlsx') for sheet in workbook sheets(): with open('{} csv' format(sheet name) 'wb') as f: writer = csv writer(f) writer writerows(sheet row_values(row) for row in range(sheet nrows)) ```` <hr> If you have encoding issues try the code below: ````import csv import xlrd workbook = xlrd open_workbook('test xlsm') for sheet in workbook sheets(): if sheet == "Sheet_name_to_be_saved": with open('{} csv' format(sheet name) 'wb') as f: writer = csv writer(f) for row in range(sheet nrows): out = [] for cell in sheet row_values(row): try: out append(cell encode('utf8')) except: out append(cell) writer writerow(out) ````
Efficient way for appending numpy array I will keep it simple I have a loop that appends new row to a numpy array what is the efficient way to do this ````n=np zeros([1 2]) for x in [[2 3] [4 5] [7 6]] n=np append(n x axis=1) ```` Now the thing is there is a [0 0] sticking to it so I have to remove it by ```` del n[0] ```` Which seems dumb So please tell me an efficient way to do this ```` n=np empty([1 2]) ```` is even worse it creates an uninitialised value
There are three ways to do this if you already have everything in a list: ````data = [[2 3] [4 5] [7 6]] n = np array(data) ```` If you know how big the final array will be: ````exp = np array([2 3]) n = np empty((3 2)) for i in range(3): n[i :] = i ** exp ```` If you do not know how big the final array will be: ````exp = np array([2 3]) n = [] i = np random random() while i < 9: n append(i ** exp) i = np random random() n = np array(n) ```` Just or the record you can start with `n = np empty((0 2))` but I would not suggest appending to that array in a loop
Test if user has entered a word equal to a word in a text file Let us say that I have a file with this in it: ````passcode ```` Now what I want to do is have some code with user input that should test if what the user entered what is equal to what is in the file Is there a any way I can do this? Here is the code that I already have: ````with file('test txt') as f: s strip('\n') s = f read() inp = raw_input() if inp == s: print "Access granted" else: print "Access denied!" ````
I took your code and added the following line at the end: ````print repr(inp) repr(s) ```` The output I got was ````'passcode' 'passcode\n' ```` Apparently `raw_input()` included the newline at the end Strip that off and it should work