text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : I am working on a project where I have to use a combination of numeric and text data in a neural network to make predictions of a system 's availability for the next hour . Instead of trying to use separate neural networks and doing something weird/unclear ( to me ) at the end to produce the desired output , I...
Training on sequences of sentences using Keras
Python : I 'm using AE socket API and I have done the following test : App Engine instance : 0:00:04.022290 and 0:00:04.209410Local Python environment : 0:00:00.509000 and 0:00:00.511000 I 've started to do some testing after I noticed that a single request took about 400ms to 500ms . The server that is answering the r...
App Engine Socket API factor 8 slower than native python
Python : I need to draw a punchcard with matplotlib which seem to not have such a function.So I have coded the following one : However it does not exactly work as expected . If it is evaluated on the following example : we obtain the following result : You can notice there are a lot of empty vertical space between the ...
Matplotlib : How to remove the vertical space when displaying circles on a grid ?
Python : I 've installed django using the pip command ( pip install Django ) , but i ca n't run it using the py command , as it ca n't find the module . I can only make it works using 'python ' command.Here is a summary of the screenshot I have atttachedIt also looks like django works only with 3.6.1 . Is there any way...
Why do python and py commands run different python 3 versions ?
Python : So I 'm using the django-jcrop plugin to crop an image . Inside my HTML file I have this line : When this is passed , I get the following error : { { ratio } } is passed correctly outside of the tag , and gives the correct intended value , 400x400 . When I remove the single quotes from the max_size= ' { { rati...
Django - Tag inside a Template tag
Python : I have 3 dimensional array of integers ( ~4000 x 6000 x 3 ) that I need to classify in a particular way . I 'm hoping for something like a k-means clustering method , but instead of inputting the number of clusters I would like to input the maximum radius of a cluster.Said another way , given a sphere of a def...
distance based classification
Python : Are Python Empty Immutables Singletons ? If you review the CPython implementation of builtin types , you 'll find comments on all the immutable builtin objects that their empty versions are singletons . This would make a lot of sense as Python could avoid wasting memory on redundant items that would never chan...
Are Python Empty Immutables Singletons ?
Python : I wrote an adaptive color thresholding function in Python ( because OpenCV 's cv2.adaptiveThreshold did n't fit my needs ) and it is way too slow . I 've made it as efficient as I can , but it still takes almost 500 ms on a 1280x720 image.I would greatly appreciate any suggestions that will make this function ...
Python : How to make this color thresholding function more efficient
Python : I learnt that in some immutable classes , __new__ may return an existing instance - this is what the int , str and tuple types sometimes do for small values . But why do the following two snippets differ in the behavior ? With a space at the end : Without a space : Why does the space bring the difference ? <co...
Python string with space and without space at the end and immutability
Python : I was playing with couchdb and the recommended `` couchdbkit '' python package . I felt it was a bit slow and decided to do some measurements . If i did n't do something wrong , then using the popular `` requests '' package is more than 10 times faster than going through couchdbkit . Why ? Here is the timing s...
couchdbkit 10x slower than requests ?
Python : I 'm seeing non-deterministic behavior when trying to select a pseudo-random element from sets , even though the RNG is seeded ( example code shown below ) . Why is this happening , and should I expect other Python data types to show similar behavior ? Notes : I 've only tested this on Python 2.7 , but it 's b...
Seeded Python RNG showing non-deterministic behavior with sets
Python : For each element in a randomized array of 2D indices ( with potential duplicates ) , I want to `` +=1 '' to the corresponding grid in a 2D zero array . However , I do n't know how to optimize the computation . Using the standard for loop , as shown here , The runtime can be quite significant : Is there a way t...
Vectorize iterative addition in NumPy arrays
Python : I am pickling , compressing , and saving python objects . I want to be able to double-check that that the object I saved is the exact same object that is returned after decompression and depickling . I thought there was an error in my code , but when I boiled the problem down to a reproducible example I found ...
Python does not consider equivalent objects to be equivalent
Python : The scope of the variables created in a with statement is outside the with block ( refer : Variable defined with with-statement available outside of with-block ? ) . But when I run the following code : The output shows that Foo.__del__ is called before printing foo ( at # line 1 above ) : My question is , why ...
Why is __del__ called at the end of a with block ?
Python : i have dataframe with each row having a list value.i have to do a calculate a score with one row and against all the other rowsFor eg : repeat step 2,3 between id 0 and id 1,2,3 , similarly for all the ids.and create a N x N dataframe ; such as this : Right now my code has just one for loop : Is there a better...
create a NxN matrix from one column pandas
Python : If I try to load the d3.js library into my jupyter notebook it works fine with version 3.x . I can then go to the chrome console and the d3 object is available.If I do the same with version 4.x it is not available even though it is displayed in the sources tab of the chrome developer tools.What am I doing wron...
d3.js Loading version 3 vs version 4 in Jupyter Notebook
Python : I have a collection of images with a circle drawn as a white outline . However , I want to fill the complete circle with white color . What is a fast way to do it ? The following is the sample of the image : I have tried using nested loops to achieve this , but it takes a lot of time , and I have around 1.5 mi...
Filling an outlined circle
Python : Using the functionality in pyviz , it 's easy to generate an hvplot/panel interactive dashboard for a gridded xarray dataset , like this air temperature data example : which automatically creates a slider for the time dimension : If I take a look at the object created : I can see that a DiscreteSlider widget w...
What is the best way to change the widget type in an hvplot/holoviews/panel object ?
Python : I have a list like thislets call this list as 'years_list'When I did groupby year , I got the desired output : Then , I slightly changed my implementation like this , I have just added a dict , but the output is different , I could n't find out why . Please help me to find what the dict is doing actually . ( P...
difference between dict ( groupby ) and groupby
Python : hello im trying to achieve this raw query with sqlalchemy : so far i get the result i want with this raw query but i want to be able to .paginate them so i could keep working properlywith my other queries what i did was this : fairly simple and i got what i wanted , i belive i have to do something likebut im n...
from raw sql to flask-sqlalchemy
Python : I have a pandas dataframe like below : I want to create a new `` z_gauss '' column by applying a convolution ( numpy.convolve ) with a gaussian filter on vectors ( column z ) corresponding to a group of rows in my dataframe with the same `` profile_index '' .I 've tried to do something like data [ `` z_gauss '...
Pandas apply convolve by group of rows
Python : I am trying to understand and solve the following problem : Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot . Aman , their friend has been helping them out . But as it goes , Sameer and Arpit have got bored of problems involving factorials . ...
Boring Factorials in python
Python : PEP 8 states : Imports are always put at the top of the file , just after any module comments and docstrings , and before module globals and constants.However if the class/method/function that I am importing is only used by a child process , surely it is more efficient to do the import when it is needed ? My c...
Using multiprocessing in Python , what is the correct approach for import statements ?
Python : Tl ; dr is bold-faced text.I 'm working with an image dataset that comes with boolean `` one-hot '' image annotations ( Celeba to be specific ) . The annotations encode facial features like bald , male , young . Now I want to make a custom one-hot list ( to test my GAN model ) . I want to provide a literate in...
Literate way to index a list where each element has an interpretation ?
Python : I am trying to have pexepct stdout logs via logger that I have defined . Below is the codeWith above code , logger is printing what pexepct is sending commands on the console but I am not getting response of pexpect . Is there a way I can log pexpect response too via loggerBelow is the outputWaiting for respon...
Not able to print pexpect response via python logger
Python : I have a Python code that creates a report for a data frame from Reddit , and converts it to simple HTML and then email 's it out . Below is the code : The email that is received is very simple in format . I wanted that email to look good so wrote a HTML code with header image logo etc using HTML Tables inline...
How do I integrate a HTML code in a Python Script ?
Python : I have an equation system like the following : For this specific system , I know that a nontrivial solution ( s ) only exists if p1 == p2 , which is .However , how can I determine this in the general case using Sympy ? For this example , my implementation is as follows : The result is If I set the result isIs ...
Symbolic solution of equation system using Sympy with trivial solutions depending on symbols
Python : In twisted 's sourcecode , many docstrings contain formats like this : L { xxx } or C { xxx } or a line begin with an ' @ ' , what 's their meanings ? for example , in twisted/internet/interfaces.py : L { IPullProducer } , C { resumeProducing } , @ type producer ? By the way , are these formats a part of stand...
What 's meaning of these formats in twisted 's docstring ?
Python : The python language reference states in section 7.4 : For an except clause with an expression , that expression is evaluated , and the clause matches the exception if the resulting object is “ compatible ” with the exception . An object is compatible with an exception if it is the class or a base class of the ...
Why does n't except object catch everything in Python ?
Python : I 've been using arrays lately and really missing Python 's `` in '' operator.e.g . : I 've made up for it a little bit by creating a `` ThereExists-Object '' function , like so : e.g . : obviously I could define another function for this as well ... but I 'd like to know if there 's some syntactical sugar tha...
Powershell equivalent to Python `` in '' ?
Python : I have data ( mostly a series of numpy arrays ) that I want to convert into text that can be copied/pasted/emailed etc.. I created the following formula which does this.My issue is that the string it produces is longer than it needs to be because it only uses a subset of letters , numbers , and symbols . If I ...
Compress data into smallest amount of text ?
Python : I have a list of dictionaries . Each Dictionary has an integer key and tuple value . I would like to sum all the elements located at a certain position of the tuple.Example : I know i could do something like : Is there a more pythonic way of doing this ? Thanks <code> myList = [ { 1000 : ( `` a '' ,10 ) } , { ...
Python List of Dictionaries [ int : tuple ] Sum
Python : I modified sys.modules [ __name__ ] to a class Hello , like this : Then , I imported hello.py in another python file test.py like : But , I got an error said `` AttributeError : 'NoneType ' object has no attribute 'time ' '' when I run python test.py.It seemed that hello.py could not import the time module.I r...
can not find time module when changed sys.modules [ __name__ ]
Python : In python2.7 , following the pympler example : This is the first code after the imports . It results inI get the same error when I try to initialize a SummaryTracker object.It looks like a bug in Pympler , but the fact that I ca n't find any mentions of it contradicts this . According to the official documenta...
pympler raises TypeError
Python : Using DataArray objects in xarray what is the best way to find all cells that have values ! = 0.For example in pandas I would do My specific example I 'm trying to look at 3 dimensional brain imaging data.Looking at the documentation for xarray.DataArray.where it seems I want something like this : But I still ...
Sparse DataArray Xarray search
Python : How can I concatenate two items when yielding from a function in python ? The base case : What if I want to yield both the number and its square number**2However doing itertools.chain.from_iterable ( [ generator1 , generator2 ] ) from the outside gives the expected result . <code> import itertoolsdef test ( ) ...
Concatenate while yielding
Python : In python ( tested on 2.7.6 ) all variables arestatically bound to a scope at compile time . This process is welldescribed in http : //www.python.org/dev/peps/pep-0227/ andhttp : //docs.python.org/2.7/reference/executionmodel.htmlIt is explicitly stated that `` If a name binding operation occursanywhere within...
Why static binding works differently for class and function ?
Python : I want to write a function which returns a list of functions . As a MWE , here 's my attempt at function that gives three functions that add 0 , 1 , and 2 to an input number : Contrary to my expectation , each function ends up using the last value taken by i. I 've experienced similar behavior when e.g . a lis...
How can I return a function that uses the value of a variable ?
Python : I am plotting journey time for a series of roads at hourly resolution , with data over a few weeks . I can plot using unix time , but that is n't very intuitive . This is 7 days worth of data . I used a function to manipulate the time field in order to give the date and hour : However , this results in ggplot ...
ggplot python handling time data over many weeks at hourly resolution
Python : Consider this sample python code . It reads from stdin and writes to a file . Suppose I want to modify this same program to write to stdout instead . Then , I 'll have to replace each instance of f.write ( ) with sys.stdout.write ( ) . But that would be too tedious . I want to know if there is a way to specify...
Is it possible to have an alias for sys.stdout in python ?
Python : I am currently doing a merge over a set of variables that I 'd like to parallelize . My code looks something like this : Ordinarily , to speed up long loops , I would replace the for m in mergelist with something like ... .But since I 'm using the star to unpack the tuple , it 's not clear to me how to map thi...
How to use a map with *args to unpack a tuple in a python function call
Python : Given an array : And given its indices : How would I be able to stack them neatly one against the other to form a new 2D array ? This is what I 'd like : This is my current solution : It works , but is there something shorter/more elegant to carry this operation out ? <code> arr = np.array ( [ [ 1 , 3 , 7 ] , ...
Create a 2D array from another array and its indices with NumPy
Python : In a project I 'm working in I need to cover a Tornado service with Behave so I want to start an instance of my tornado service before running each scenario.Naively trying to run the loop as part before all seems to lock the excecution : So it 's probably not what I need . <code> from tornado import ioloopfrom...
How to run Tornado IO Loop during Behave environment setup
Python : I have a client app that interacts with a web service to retrieve account information . There 's a requirement that the user is notified if they mistyped the username/password . I 'm modifying the web service to return something to my client to provide a hint to the user that there 's an error in input.How do ...
How to implement `` Incorrect username/password '' hint for a webservice using Flask HTTP Auth ?
Python : i 've started using pdb through gud in emacs 23.3 , how can i hook command messages sent to the debugger from the buffer ? i wrote the advice below for use with gdb , in order to persist comint 's ring , but ca n't find an equivalent function to hook for pdb . i 'm using python-mode.el as my major mode.thanks ...
how do i hook commands sent to pdb through gud ?
Python : I have a jpeg from where I want to crop a portion containing graph ( the one in the bottom portion ) .As of now I used this code to achieve the same : But I achieved this by guessing the x1 , y1 , x2 , y2 multiple times to arrive at this ( guess work ) .Image before cropping : Image after cropping : I 'm total...
How to crop multiple rectangles or squares from JPEG ?
Python : I 'm sorting a list of dicts by a key : some of the dicts have name set to None , and Python 2 places None values before any other , so they 're placed at the front of the sorted list . A naive fix would bebut , obviously , that would not work for any non-Latin names.What is a nice and Pythonic way of sorting ...
How do I sort a list with `` Nones last ''
Python : In Clojure I can do something like this : instead of doing this : This is called threading in Clojure terminology and helps getting rid of a lot of parentheses.In Python if I try to use functional constructs like map , any , or filter I have to nest them to each other . Is there a construct in Python with whic...
Is there something like the threading macro from Clojure in Python ?
Python : I have a txt file with data in this format . The first 3 lines repeat over and over.I would like to output the data in a table format , for example : I am struggling to set the headers and just loop over the data . What I have tried so far is : The output from that is Not really what I am looking for . <code> ...
Read file of repeated `` key=value '' pairs into DataFrame
Python : Maybe I 'm missing the obvious.I have a pandas dataframe that looks like this : I 'd like to use the groupby function to count the number of appearances of each element in the categories column , so here the result would beHowever when I try using a groupby function , pandas counts the occurrences of the entir...
Pandas : Use groupby on each element of list
Python : Context : I 'm using a fully convolutional network to perform image segmentation . Typically , the input is an RGB image shape = [ 512 , 256 ] and the target is a 2 channels binary mask defining the annotated regions ( 2nd channel is the opposite of the fist channel ) .Question : I have the same CNN implementa...
Deep Learning implementation in Tensorflow or Keras give drastic different results
Python : I am using Ubuntu 14.04 LTS . I tried Polipo , but it kept refusing Firefox 's connections even if I added myself as allowedClient and hours of researching with no solution . So instead , I installed Privoxy and I verified it work with Firefox by going to the Tor website and it said Congrats this browser is co...
Scrapy gets NoneType Error when using Privoxy Proxy for Tor
Python : I have a list of particular words ( 'tokens ' ) and need to find all of them ( if any of them are present ) in plain texts . I prefer using Pandas , to load text and perform the search . I 'm using pandas as my collection of short text are timestamped and it is quite easy to organise these short text in a sing...
Searching for all matches in texts with Pandas
Python : I have a Django 1.9.6 site deployed to Heroku . When DEBUG=False I was getting a server error ( 500 ) . The logs contained no useful information , so I tried running it with DEBUG=True . Now it works fine . I think the issue may be tied to my scss file processing , which really confuses me and I was struggling...
Ca n't use django-compress with Heroku
Python : I am following the following gensim tutorial to transform my word2vec model to tensor.Link to the tutorial : https : //radimrehurek.com/gensim/scripts/word2vec2tensor.htmlMore specifically , I ran the following commandHowever , I get the following error for the above command.When I use model.wv.save_word2vec_f...
How to use word2vec2tensor in gensim ?
Python : I used opencv 's minAreaRect to deskew the mnist digits.It worked well for most of the digits but , in some cases the minAreaRect was not detected correctly and it lead to further skewing of the digits.Images with which this code worked : Input image : minAreaRect Image : deskewed image : But , for this the di...
Deskewing MNIST dataset images using minAreaRect ( ) of opencv
Python : Is it pythonic to mimic method overloading as found in statically typed languages ? By that I mean writing a function that checks the types of its arguments and behaves differently based on those types.Here is an example : <code> class EmployeeCollection ( object ) : @ staticmethod def find ( value ) : if isin...
Is it Pythonic to mimic method overloading ?
Python : python 3.7.3 , rpy2 3.2.0 , the following code : from rpy2 import robjectsWhat 's going on ? This looks like standard procedure for rypy2 , and indeed how we used it under python 2.Same issue applies for any kind of rpy2 import : import rpy2.robjects.tests etc . <code> Traceback ( most recent call last ) : Fil...
rpy2 3.2.0 on python 3.7 issues w/ importing robjects
Python : I am hitting an obscure problem ( bug ? ) with my Python3 QML program.I implemented a QAbstractListModel with a custom get method to get to the underlying QObject items . The moment I try to get the same Python QObject at two different places in QML I get : The get method looks like this : And the model like t...
Access Python QObject from QML fails to convert on second call
Python : I 'm trying to have a rotated text in matplotlib . unfortunately the rotation seems to be in the display coordinate system , and not in the data coordinate system . that is : will give a line that will be in a 45 deg in the data coordinate system , but the accompanied text will be in a 45 deg in the display co...
keeps text rotated in data coordinate system after resizing ?
Python : Pytest 's output for failed asserts is much more informative and useful than the default in Python . I would like to leverage this when normally running my Python program , not just when executing tests . Is there a way to , from within my script , overwrite Python 's assert behavior to use pytest to print the...
Can I patch Python 's assert to get the output that py.test provides ?
Python : I 've just written a small recursive programme to generate all the possible subdivisions of a list : I 've brute forced this and it 's taken me a long time to figure out . I 'm wondering what this is called , as I 'm sure there is a name for it.In general I 'm wondering how to learn this stuff from a mathemati...
All possible subdivisions of a list
Python : I am trying to download the html of a page that is requested through a javascript action when you click a link in the browser . I can download the first page because it has a general URL : But there are links along the bottom of the page that are numbers ( 1 to 10 ) . So if you click on one , it goes to , for ...
Download html in python ?
Python : I have a list of items aprox 60,000 items - i would like to send queries to the database to check if they exist and if they do return some computed results . I run an ordinary query , while iterating through the list one-by-one , the query has been running for the last 4 days . I thought i could use the thread...
python , how to incrementally create Threads
Python : I am doing a Kernel Density Estimation in Python and getting the contours and paths as shown below . ( here is my sample data : https : //pastebin.com/193PUhQf ) .There is a similar way to get the contours using R , which is described here : http : //bl.ocks.org/diegovalle/5166482Question : how can I achieve t...
python KDE get contours and paths into specific json format leaflet-friendly
Python : I know someone explain why when I createequal unicode strings in Python 2.7they do not point to the same location in memoryAs in `` normal '' stringsok that was what I expected , but why ? how ? <code> > > > a1 = ' a ' > > > a2 = ' a ' > > > a1 is a2True > > > ua1 = u ' a ' > > > ua2 = u ' a ' > > > ua1 is ua2...
memory location in unicode strings
Python : Some libraries like numpy , pandas or even python lists implement fancy indexing for its objects . This means I can do things like : If I want to offer this functionality in my class I could try to overload the __getitem__ and the __setitem__ methods : but I do n't see how this could work as 1:3 is not a valid...
Implementing fancy indexing in a class
Python : Is it possible to apply code from imported module to module which import it ? For example , I have module Debug where defined some decorator for debugging , for example : What 's the idea : It 's would be useful if I can justand all functions from current module will wrapped with decorator.Is it possible ? <co...
Python introspection
Python : Assume I have a list of this type : I want to find each index for which the value is the same for the n following indices.I can do it ( laboriously ) this way : Prints : Is there a better way to do this ? <code> # 0 1 2 3 4 5 6 7 8 9 10 11 -- list indexli= [ -1 , -1 , 2 , 2 , -1 , 1 , 1 , 1 , 1 , 1 , -1 , -1 ]...
Sequence of elements in a list satisfying a condition
Python : I am using the python urllib2 library for opening URL , and what I want is to get the complete header info of the request . When I use response.info I only get this : I am expecting the complete info as given by live_http_headers ( add-on for firefox ) , e.g : My request function is : Is it possible to achieve...
how can I get complete header info from urlib2 request ?
Python : With this code we have two instances of callable class , one is decorated and one is plain : I wonder if it is somehow supported to use the @ decorator syntax on a callable for just one instance - as opposed to decorating the class / method , which would apply to every instance . According to this popular answ...
How can I decorate an instance of a callable class ?
Python : I wonder , where does the function Read_Edgelist store the original id 's from the the edge list ? or under which attribute name ? Assume that I am reading an edge list like : where the numbers 1,2,3 are the ids ( or names ) of the nodes . Where does the iGraph ( python version ) stores these ids ? I tried ret...
Initial node 's ids when creating graph from edge list
Python : This prints What is the difference between _ value_ and value ? <code> from enum import Enumclass Type ( Enum ) : a = 1 b = 2print Type.a.value , Type.a._value_ 1 1
python enum.Enum _value_ vs value
Python : I am seeing the following phenomenon , could n't seem to figure it out , and did n't find anything with some search through archives : if I type in : I will get : However , if I type in : Then I will get : ( The first one only has one backslash on the r'\n ' whereas the second one has two backslashes in a row ...
python `` re '' package , strange phenomenon with `` raw '' string
Python : There is a strange behavior of map when using Python 's multiprocessing.Pool . In the example below a pool of 4 processors will work on 28 tasks . This should take seven passes , each taking 4 seconds.However , it takes 8 passes . In the first six passes all processors are engaged . In the 7th pass only two ta...
python multiprocessing map mishandling of last processes
Python : As stated in scipy lecture notes , this will not work as expected : But why ? How does being a view affect this behavior ? <code> a = np.random.randint ( 0 , 10 , ( 1000 , 1000 ) ) a += a.Tassert np.allclose ( a , a.T )
Numpy : Why does n't ' a += a.T ' work ?
Python : In particular , it outputs : Why ? <code> > > > dis.dis ( None ) 22 0 LOAD_FAST 0 ( x ) 3 LOAD_CONST 1 ( None ) 6 COMPARE_OP 8 ( is ) 9 POP_JUMP_IF_FALSE 23 23 12 LOAD_GLOBAL 1 ( distb ) 15 CALL_FUNCTION 0 18 POP_TOP 24 19 LOAD_CONST 1 ( None ) 22 RETURN_VALUE 25 > > 23 LOAD_GLOBAL 2 ( isinstance ) 26 LOAD_FAS...
Why does dis.dis ( None ) return output ?
Python : I want to find the offset between two arrays of timestamps . They could represent , let 's say , the onset of beeps in two audio tracks.Note : There may be extra or missing onsets in either track.I found some information about cross-correlation ( e.g . https : //dsp.stackexchange.com/questions/736/how-do-i-imp...
Does it make sense to use cross-correlation on arrays of timestamps ?
Python : This question is in continue to a previous question I 've asked.I 've trained an LSTM model to predict a binary class ( 1 or 0 ) for batches of 100 samples with 3 features each , i.e : the shape of the data is ( m , 100 , 3 ) , where m is the number of batches.Data : Target : Model code : For the training stag...
LSTM - Making predictions on partial sequence
Python : I ca n't understand why the following code behaves a particular way , which is described below : Why does repr ( MyClass2 ) says abc.MyClass2 ( which is by the way not true ) ? Thank you ! <code> from abc import ABCMeta class PackageClass ( object ) : __metaclass__ = ABCMeta class MyClass1 ( PackageClass ) : p...
Python inheritance , metaclasses and type ( ) function
Python : I am considering moving from Matlab to Python/numpy for data analysis and numerical simulations . I have used Matlab ( and SML-NJ ) for years , and am very comfortable in the functional environment without side effects ( barring I/O ) , but am a little reluctant about the side effects in Python . Can people sh...
side effect gotchas in python/numpy ? horror stories and narrow escapes wanted
Python : I 'm working on an application that must support client-server connections . In order to do that , I 'm using the module of tornado that allows me to create WebSockets . I intend to be always in operation , at least the server-side . So I am very worried about the performance and memory usage of each of the ob...
python - When are WebSocketHandler and TornadoWebSocketClient completely deleted ?
Python : I have a dummy example of an iterator container below ( the real one reads a file too large to fit in memory ) : This allows me to iterate over the value more than once so that I can implement something like this : How do I check in the normalise function that I am being passed an iterator container rather tha...
How do I check if an iterator is actually an iterator container ?
Python : If I have `` a.py '' and another file `` b.py '' It would appear that Python simply does not allow circular dependencies . Normally I guess you would alter the code such that the two classes actually can resolve themselves without importing one another directly . Perhaps by consolidating their reference to one...
How should I deal with a circular import in Google App Engine ?
Python : I 'd like to compare multiple objects and return True only if all objects are not equal among themselves . I tried using the code below , but it does n't work . If obj1 and obj3 are equal and obj2 and obj3 are not equal , the result is True.I have more than 3 objects to compare . Using the code below is out of...
Python : determining whether any item in sequence is equal to any other
Python : Finally block runs just before the return statement in the try block , as shown in the below example - returns False instead of True : Similarly , the following code returns value set in the Finally block : However , for variable assignment without return statement in the finally block , why does value of vari...
Finally always runs just before the return in try block , then why update in finally block not affect value of variable returned by try block ?
Python : I am trying to sort a list of tuples like these : The sorted list should be : So , here 1st the list should be sorted based on tuple [ 1 ] in descending order , then if the tuple values ( tuple [ 1 ] ) match like forApple , Banana & Pineapple - list should be further sorted based on tuple [ 0 ] in ascending or...
Sort at various levels in Python
Python : I have a data frame that looks like this : Basically what I want to do is replace the value of the one hot encoded elements with the value from the `` value '' column and then delete the `` value '' column . The resulting data frame should be like this : <code> df = pd.DataFrame ( { `` value '' : [ 4 , 5 , 3 ]...
Replace ones in binary columns with values from another column
Python : The Python Cookbook suggests the following tree structure for a `` typical library package '' : You 'll notice that the examples/ are not part of the actual package , which resides under projectname/projectname/ ( that 's where you 'll find the top-level __init__.py of the package ) .Well , examples/helloworld...
How to include examples or test programs in a package ?
Python : I 'm trying to parse this datetime string , without success yet , how can I get it ? <code> d = '2014-05-01 18:10:38-04:00'datetime.datetime.strptime ( d , ' % Y- % m- % d % H : % M : % S- % Z ' ) ValueError : time data '2014-05-01 18:10:38-04:00 ' does not match format ' % Y- % m- % d % H : % M : % S % Z '
Python 2.7 how parse a date with format 2014-05-01 18:10:38-04:00
Python : I have the following toy grammar in Pyparsing : However , running this program will infinitely recurse , which is n't what I wanted . Rather , I wanted my grammar to be able to handle nested phrases so that the above program would resolve to something equivalent to the below : I attempted to modify the definit...
Nesting delimited lists in pyparsing without causing infinite recursion ?
Python : I have a data in a text file that contains `` Test DATA_g004 , Test DATA_g003 , Test DATA_g001 , Test DATA_g002 '' .Is it possible to sort it without the word `` Test DATA_ '' so the data will be sorted like g001 , g002 , g003 etc ? I tried the .split ( `` Test DATA_ '' ) method but it does n't work . <code> d...
How to split a mixed string with numbers
Python : I 've just begun playing around with Python 's Data Classes , and I would like confirm that I am declaring Class Variables in the proper way . Using regular python classesUsing python Data ClassThe class variable I am referring to is raise_amount . Is this a properly declared class variable using Data Classes ...
Proper way to create class variable in Data Class
Python : Using tflite and getting properties of interpreter like : What does 'quantization ' : ( 0.003921568859368563 , 0 ) mean ? <code> print ( interpreter.get_input_details ( ) ) [ { 'name ' : 'input_1_1 ' , 'index ' : 47 , 'shape ' : array ( [ 1 , 128 , 128 , 3 ] , dtype=int32 ) , 'dtype ' : < class 'numpy.uint8 ' ...
What does 'quantization ' mean in interpreter.get_input_details ( ) ?
Python : As a simple example , assume a utility method , which accepts a python object input_obj , and out_type , a python type to convert ( typecast ) the object into-ExamplesThe method only supports objects of specific types like str , list , tuple , and then checks if that can be converted to the out_type specified....
Find which other python types can an object be converted to ?
Python : I occasionally spend a considerable amount of time tracking down brainfarts in my code ... while I normally run pylint against it , there are some things that slip past pylint . The easiest problem for me to overlook is this ... Neither pylint nor Python bark about this ... is there a python code-checking tool...
Python code checker for comparing a function as an attribute
Python : I am attempting to take a list of objects , and turn that list into a dict . The dict values would be each object in the list , and the dict keys would be a value found in each object.Here is some code representing what im doing : Now that code works , but its a bit ugly , and a bit slow . Could anyone give an...
Best way to turn a list into a dict , where the keys are a value of each object ?
Python : I was wondering if it is possible to insert something in .bashrc or .vimrc so that whenever I create a new Python file via vim it automatically creates a file with this already inserted before I edit it : A vast majority of my Python scripts use those lines , and if there is a way to include those for every ne...
Bash or vim alias/command to use a certain template when creating Python files ?
Python : I 'm porting a MATLAB code to Python 3.5.1 and I found a float round-off issue.In MATLAB , the following number is rounded up to the 6th decimal place : In Python , on the other hand , the following number is rounded off to the 6th decimal place : Interestingly enough , if the number is '-67.6000625 ' , then i...
Round-off / round-up criteria in Python
Python : I am attempting to using part of a regular expression as input for a later part of the regular expression . What I have so far ( which fails the assertions ) : Breaking this down , the first digit ( s ) signify how many digits should be matched afterward . In the first assertion , I get a 3 , as the first char...
Using a regular expression backreference as part of the regular expression in Python