text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : What is the best way for me to create a dictionary from a string that key is each character and its upper case and value is its opposite case ? I can use two line dictionary comprehensive but any better way ? ex : string : abc = > { ' a ' : ' A ' , ' b ' : ' B ' , ' c ' : ' C ' , ' C ' : ' c ' , ' B ' : ' b ' ...
create a dictionary from string that each character is key and value
Python : I was trying to print the result of a loop in the same line using python 3 and after reading Python : for loop - print on the same line I managed to do it.The problem now is when I insert before the print.I would like to print the first character , wait two seconds , then the second , wait two more seconds , e...
Interpolate sleep ( ) and print ( ) in the same line inside a for loop using python 3
Python : Firstly , there is class A with two class variables and two instance variables : We can see that both class variable and instance variable of int type works fine : However , things have changed if we check the function type variables : I known that python has translated a.cfun ( 1,2 ) to A.cfun ( a,1,2 ) and t...
What 's the difference between class variables of different types ?
Python : I have a range of values ( L , R , U , D ) and two variables , d and newd , containing one of them . I need to check if d and newd are in the same subset ( L , R or U , D ) or not.I know I can do this : this indeed returns False if they both have values in L , R or U , D , and True otherwise . Still , I find i...
Check if two variables have values from two different sets , the DRY way
Python : I recently received a bundle of Python code , written by a graduate student at an academic lab , and consisting of a Python script and about half dozen single-file Python modules , used by by the script . All these files ( script and modules ) are on the same directory.I wanted to use pip to install this code ...
How does the value of the name parameter to setuptools.setup affect the results ?
Python : I want to slice by range in Python and it seems like it 's not possible.Why do I want to do this ? I want to define `` what to slice '' in one part of my script , put that in a variable , and do the actual slicing elsewhere . Like this : Is it possible , and if not , how to do something similar correctly and `...
Slicing by range
Python : I 'm trying to find a good interval of colors for color masking in order to extract skin from images.I have a database with images and masks to extract skin from those images . here 's an example of a sample : I 'm applying the mask for each image in order to get something like this : I 'm getting all the pixe...
How to use an optimization algorithm to find the best possible parameter
Python : Here is an example class : As you can see , I 'm using exec to optimize the creation of multiple property ( ) objects . I often read that using exec is bad and that it is a security hole in your program . In this case , is it ? <code> from datetime import datetimeclass Article : published = datetime.now ( ) fo...
Is using 'exec ' under controlled conditions a security threat ?
Python : I tried to google something about it . Why do non-data descriptors work with old-style classes ? Docs say that they should not : '' Note that descriptors are only invoked for new style objects or classes ( ones that subclass object ( ) or type ( ) ) . `` .Thanks . <code> class Descriptor ( object ) : def __ini...
Python descriptors with old-style classes
Python : I would like to add a semi-transparent rectangle filled with a solid colour to an already loaded semi-transparent PNG . Here 's an example input image I am using : That image is loaded with a standard cv2.IMREAD_UNCHANGED flag so that alpha channel is perfectly preserved . That input image is stored in the ima...
Alpha blending two images with OpenCV and/or Numpy
Python : I am trying to make a simple drawing application using Python and gnomecanvas . Sadly , there appears to be no documentation for the Python bindings for gnomecanvas whatsoever . Thus , I am bumbling around using code samples and trying to guess from the C bindings.As it is , I have the code working by keeping ...
Is there a way to append to an existing gnome canvas bpath in Python ?
Python : From Python : When I check through Bash : Why does this return a different result ? <code> > > > import os > > > s = os.stat ( '/etc/termcap ' ) > > > print ( oct ( s.st_mode ) ) **0o100444** $ stat -f `` % p % N '' /etc/termcap**120755** /etc/termcap
Why do file permissions show different in Python and bash ?
Python : I 'm trying to make a code to rewrite a specific line from a .txt file.I can get to write in the line i want , but i ca n't erase the previous text on the line.Here is my code : ( i 'm trying a couple of things ) You can use this code to make a test file for testing : Edit : For Some reason , if i use 'if coun...
How to erase line from text file in Python ?
Python : What is & = in python ? For example : I found it in the twilio python library : https : //github.com/twilio/twilio-python/blob/master/twilio/util.py # L62Why do n't they just compare the strings directly return string1 == string2 and compare each character ? <code> for c1 , c2 in izip ( string1 , string2 ) : r...
What is the `` & = '' operator and why does Twilio use it when comparing strings ?
Python : Here 's a bit of a program I 'm writing that will create a csv categorizing a directory of files : Basically , the user picks a folder and the program denotes problem files , which can be of several types ( just two listed here : no files with uppercase letters , no php or python files ) . There will be probab...
Pythonic way to process multiple for loops with different filters against the same list ?
Python : A easier way has updated in the end of the question . What I haveI have a user-user correlation matrix called matrixcorr_of_user like the one below : What I want For every user , I just want to keep the 2 other users that are the most similar to him ( the highest correlation values per row after excluding the ...
Is there a elegant way to only keep top [ 2~3 ] value for each row in a matrix ?
Python : I am working on a custom file path class , which should always execute a functionafter the corresponding system file has been written to and its file objectclosed . The function will upload the contents of file path to a remote location.I want the upload functionality to happen entirely behind the scenes from ...
Python Callback for File Object Close
Python : I have an array A : The length of consecutive '1s ' would be : with the corresponding starting indices : The original arrays are huge and I prefer a solution with less for-loop.Edit ( Run time ) : Quang 's solution : Jacco 's solution : Dan 's solution ( works with special cases as well ) : Run time analysis w...
Fast way to find length and start index of repeated elements in array
Python : I have a form with a dependent drop-down . This secondary drop-down is hidden whenever the primary option selected does not have any secondary options , and when the page first loads . Whenever the form is submitted , only the first field gets cleared out , since most of the time the drop-downs remain the same...
How to `` load '' dependent drop down upon page load ?
Python : My question is about the rule that pandas uses to compare a column with type `` object '' with an integer . Here is my code : Why does the `` c2 '' column get True for all ? P.S . I also tried : <code> In [ 334 ] : dfOut [ 334 ] : c1 c2 c3 c4id1 1 li -0.367860 5id2 2 zhao -0.596926 5id3 3 sun 0.493806 5id4 4 w...
How does the Pandas deal with the situation when a column with type `` object '' is compared with an integer ?
Python : I have a script , which parses a few arguments , and has some expensive imports , but those imports are only needed if the user gives valid input arguments , otherwise the program exits . Also , when the user says python script.py -- help , there is no need for those expensive imports to be executed at all.I c...
how to elegantly parse argumens in python before expensive imports ?
Python : I would like to generate a random potential in 1D or 2D spaces with a specified autocorrelation function , and according to some mathematical derivations including the Wiener-Khinchin theorem and properties of the Fourier transforms , it turns out that this can be done using the following equation : where phi ...
Generating correlated random potential using fast Fourier transform
Python : I 'm trying to develop a Python script to examine every sentence in Barack Obama 's second inaugural address and find similar sentences in past inaugurals . I 've developed a very crude fuzzy match , and I 'm hoping to improve it.I start by reducing all inaugurals to lists of stopword-free sentences . I then b...
detect allusions ( e.g . very fuzzy matches ) in language of inaugural addresses
Python : I 'm using the python module subprocess to call a program and redirect the possible std error to a specific file with the following command : I want that the `` std.err '' file is created only if there are errors , but using the command above if there are no errors the code will create an empty file.How i can ...
Subprocess error file
Python : I have a dataframe df1 that contains rows of tokenized strings : I also have a dataframe df2 that contains single-word strings as well as a score pertaining to each word : What is the best way to use df2 as a sort of lookup `` table '' that I can also use to help perform calculations ? For each row in df1 , I ...
How to check a dataframe consisting of a list of strings against a lookup dataframe and perform calculations ?
Python : type ( 3 , ) returns the int type , while returns the tuple type.Why ? <code> t = 3 , type ( t )
Type ( 3 , ) returns an integer instead of a tuple in python , why ?
Python : A callable object is supposed to be so by defining __call__ . A class is supposed to be an object… or at least with some exceptions . This exception is what I 'm failing to formally clarify , thus this question posted here.Let A be a simple class : The first function is purposely named “ call ” , to make clear...
How do Python tell “ this is called as a function ” ?
Python : When I do the following in IPython notebookI seeWhat 's going on here ? How do I print a list of Unicode strings ? ( ie I want to see [ ' ½ ' ] ) EditSo from comments , looks like the difference is that `` print s '' uses s.__str__ and `` s '' , `` print [ s ] '' uses it 's s.__repr__ <code> s= ' ½'sprint spri...
Different encodings used in in `` print s '' vs `` print [ s ] '' ?
Python : Today I noticed something odd in my code , and discovered that in certain situations it run down to the execution of the following : which results in my_list being the following : At the beginning I was quite confused , than I understood that the interpreter is first converting the list to a numpy array , and ...
python list + empty numpy array = empty numpy array ?
Python : I am trying to overcome the flaws of sub-classing Python 's float by using a different class hierarchy of numbers . However the following code : yields the error : AttributeError : 'module ' object has no attribute 'numbers'How can I overcome this ? <code> from sympy import *import sympy.core.numbersf = 1.1234...
How can I override the __str__ method of sympy.core.numbers.Float ?
Python : So I have a dataframe that contains some wrong information that I want to fix : id refers to a business , and this DataFrame is a small example slice of a much larger one that shows how a business moves . Each record is a unique location , and I want to capture the first and last year it was there . The curren...
Python Pandas Groupby Resetting Values Based on Index
Python : I am making a game in which the player has to use a bowl to catch falling items . I have some images of items in a list and an image of a bowl that is used to catch the items . The items keep on falling and reset to the top of the screen if they reach the boundary ( bottom edge ) . I got this logic done which ...
How to detect collisions between two rectangular objects or images in pygame
Python : If I create hdf5 file with pandas with following code : all series are empty , so why `` store.h5 '' file takes 1.1GB space on hardrive ? <code> import pandas as pdstore = pd.HDFStore ( `` store.h5 '' ) for x in range ( 1000 ) : store [ `` name '' +str ( x ) ] = pd.Series ( )
Why if I put multiple empty Pandas series into hdf5 the size of hdf5 is so huge ?
Python : The following does not raise : although this does : Is this a known problem ? What can I do to fix it ? I need to inherit from something that looks exactly like a list and create an abstract inheritor . Thank you . <code> from abc import ABCMeta , abstractmethodclass Test ( list , metaclass=ABCMeta ) : @ abstr...
Python 3.7 : Inheriting list , abstract ignored
Python : Is it possible to patch together a copy-and-pastable invocation for a python program from the invoked program itself ? It does n't have to be exactly the same invocation string , but the arguments should parse to the same thing.Note that ' '.join ( sys.argv ) wo n't cut it , unfortunately . The main problem I ...
Re-creating a python invocation
Python : I have a growing number of scripts that make up a program I am writing and decided it was time to clean up my source tree and package them up correctly . I 'm sure this is a simple question but I ca n't find out how to do it.If I have a group of modules , that fit together , but one should be a top-level modul...
Packages `` within '' modules
Python : Below is a list of hostnames that is stored in a text file.for the sake of displaying it shortly it needs to be parsed and rewritten/displayed as can you guys help me on this , any suggestions will be helpful . <code> web1.maxi.comweb3.maxi.comweb4.maxi.comweb5.maxi.comweb6.maxi.comweb7.maxi.comweb8.maxi.comwe...
parse and rearrange hostnames
Python : I have a very big list of words ( around 200k ) : I created this regex , with fuzziness : I have input sentences : What I want to get is this : I tried this for example : But this outputs me : Any idea how to get the right answer with corrected words ? What I want is to get the regex capturing group for each m...
Get regex group with fuzziness
Python : We 've run into a problem with some markdown content . A few jquery editors we used did not write proper markdown syntax . Embedded Links used the 'label ' format , which drops the links at the bottom of the document ( Just like the StackOverflow editor ) . The problem we encountered , is that the links were s...
using regex to fix markdown input - link labels
Python : There are some operations that needs to be done before running some routes . For example : check if we recognise the user , check the language , check the location , set variables in the navbar ( here after named header ) of the htmland so on , then make decisions based on the outcome and lastly run the reques...
bottle : how to set a cookie inside a python decorator ?
Python : After inputting I get the value However if I enter Decimal ( 1.0/7 ) I get <code> from decimal import *getcontext ( ) .prec = 6Decimal ( 1 ) / Decimal ( 7 ) Decimal ( ' 0.142857 ' ) Decimal ( ' 0.142857142857142849212692681248881854116916656494140625 ' )
Why is Python 's Decimal function defaulting to 54 places ?
Python : Okay I 'm new to OOP , and my problem is that I have this parent class and it has a method info in it.I want to reuse the two print statements within that method for its subclass inside a method of the same name and add more information to it . but I ca n't get it to workI thought of just rewriting the lines o...
how to add contents of a parent class method into a subclass method
Python : My module has two functions in it : do_something ( ) , and change_behavior ( ) .The function do_something ( ) does Thing A by default . After change_behavior ( ) has been called , do_something ( ) does Thing B instead.I want this transition to be thread-specific . That is , any new thread will have Thing A hap...
Set behavior to be executed when a thread would otherwise finish
Python : I am creating a number of slices [ -WINDOW-i : -i ] of a list , where i ranges between 32 and 0 : When i == 0 , this returns a slice of length 0 : I do n't want to have to do this to solve it : … because if I have many lists to append to vals , it gets messy.Is there a clean way to do this ? <code> vals = [ ] ...
How to avoid inconsistent s [ i : -j ] slicing behaviour when j is sometimes 0 ?
Python : I was playing around with clever ways to create a python generator for sequence A003602This appears to work , but I ca n't figure out why . It seems to me like it should hit infinite recursion . Is python doing some lazy evaluation somewhere that I do n't recognize ? To me it seems like since RZ instantly call...
Clever streams-based python program does n't run into infinite recursion
Python : I am trying to make a program to solve a puzzle an . My attempts work good with sample puzzles I made to test . Now I am trying to make one for a actual puzzle . The puzzle pieces of this new puzzle do n't really have a proper shape . I managed to make the image into black and white and finally in to array of ...
find specific points on an image
Python : Given a string , I need to replace a substring with another in an area not located between two given words.For example : Currently , the only solution I have is extremely unclean:1 ) Replace the string located between the two words to a temporary substring , via Replace a string located between2 ) replace the ...
Python Regex - replace a string not located between two specific words
Python : I 'm trying to build a list of tiles for a board game from an xml file which contains a description of the tiles . The xml file describes each tile type , and the number of tiles of that type . So far , I 've got the following code which creates a list with exactly one of each tile type : I 'd like to create a...
Create single list with multiple instances of objects from second list in Python
Python : I have a DataFrame that looks like this : I want to extract the number from the Dimension column and split it into multiple column : How to do that using the Pandas module in Python ? Thank you ! <code> |Index| Dimension || -- -- -| -- -- -- -- -- -||0 |1 @ 43X32X34 ||1 |1 @ 120X80X74||2 |2 @ 26X26X32 ||3 |1 @...
How to extract multiple numbers from Pandas Dataframe
Python : List comprehensions have their code placed directly in the function where they are used , like this : Whereas generator expressions and dict/set comprehensions are mostly placed in a separate nested function , like this : In Python 3 , all of these are placed in a nested function.Why is the code placed in a se...
Why do generator expressions and dict/set comprehensions in Python 2 use a nested function unlike list comprehensions ?
Python : I am trying to add a straight line down which would have date printed vertically on the line . I have added a picture of how i am trying to accomplish this below . I have also included the code which i am trying to annotate with.My code : For some reason i am getting warning : But the line is not plotting . Co...
Annoting date on chart
Python : I have been working with creating some code that I can use in future in order to embed a pygame window within a tkinter window in order to make use of tkinter menus and buttons . I am currently having some issues with dealing with key presses . i want all key presses to be dealt with by pygame rather than tkin...
Dispatching keypresses to embedded Pygame
Python : I am trying to use the next function on an iterator , however , I have a local variable in the same scope that is also named next . The obvious solution is to rename the local variable , however , I 'm fairly new to Python so I 'm curious to learn how to prefix the next function so I achieve the desired behavi...
Scope of next ( ) in Python
Python : I need a fast element-wise maximum that compares each row of an n-by-m scipy sparse matrix element-wise to a sparse 1-by-m matrix . This works perfectly in Numpy using np.maximum ( mat , vec ) via Numpy 's broadcasting.However , Scipy 's .maximum ( ) does not have broadcasting . My matrix is large , so I can n...
Elementwise maximum of sparse Scipy matrix & vector with broadcasting
Python : I want a regex that matches any set of digits , with one possible dot . If there is another dot and more digits after it , do an overlapping match with the previous digits , the dot , and the following digits.example string = 'aa323aa232.02.03.23.99aa87..0.111111.mm'desired results = [ 323 , 232.02 , 02.03 , 0...
Overlapping regex
Python : An unhashable object can not be inserted into a dict . It is documented , there is good reason for it.However , I do not understand why it affects a membership test : I was assuming that a membership test can return only True or False . But when the value is unhashable , it fails with TypeError : unhashable ty...
unexpected behaviour of dictionary membership check
Python : I have a very simple package , which I eventually want to release through PyPI , which has a directory tree like the following : parse_date_range.py defines a function called parse.What is the easiest and most pythonic way for me to set up the package for easy importing of the parse function , and how can I do...
Pythonic way to write package for easy importing
Python : I have a class which contains a list like so : I populate the list of animals with animal objects that have various properties : You can imagine subclasses of Animal that have other properties . I want to be able to write methods that perform the same calculation but on different attributes of the Animal . For...
Python : object with a list of objects - create methods based on properties of list members
Python : I know there is an easy , elegant solution to this problem but I am struggling to find it . All I 'm trying to do is add a third column to df2 with the corresponding values from df2 , based on Date and PN . There may be values in df2 that do n't match to df1 , and vice versa ( fill NaN where there is no match ...
Python Pandas - Add values from one dataframe to another by matching labels to columns
Python : After reading A LOT of data on the subject I still could n't find any actual solution to my problem ( there might not be any ) .My problem is as following : In my project I have multiple drivers working with various hardware 's ( IO managers , programmable loads , power supplies and more ) .Initializing connec...
Guaranteeing calling to destruction on process termination
Python : My question in brief : given a 1d distribution in Python , how can one identify regions of that distribution that have a sine-like , undulating pattern ? I 'm working to identify images within page scans of historic documents . These images are essentially always full-width within the scans ( that is , they 'r...
Python : Identifying undulating patterns in 1d distribution
Python : I have the following list which I want to convert into a dictionary.I want to create a dictionary like this : What will be the easiest method to do this ? <code> newData = [ 'John ' , 4.52 , 'Jane ' , 5.19 , 'Ram ' , 4.09 , 'Hari ' , 2.97 , 'Sita ' , 3.58 , 'Gita ' , 4.1 ] newDict = [ { 'name ' : 'John ' , 'He...
How to create a dictionary with new KEY with data from list ?
Python : Up to now , we manage the crontabs of our servers by hand.I have seen this : http : //django-extensions.readthedocs.org/en/latest/jobs_scheduling.htmlIt is a nice django app , since you just need to edit your crontab once.You enter lines like this once , and for the future a software update is enough , no need...
Cronjobs per package
Python : I have recently started to learn Python and have encountered something a little strange when playing with sets . The following code sample does n't produce the expected results.I expected a_set to have the values { True , 1 , 2 , 3 , 4 } but instead this code produced { True , 2 , 3 , 4 } . Trying variations o...
Adding 1 to a set containing True does not work
Python : related to why should I make a copy of a data frame in pandasI noticed that in the popular backtesting library , in row 631 . What 's the purpose of such a copy ? <code> def __init__ ( self , data : pd.DataFrame ) data = data.copy ( False )
why should I make a *shallow* copy of a dataframe ?
Python : So I have three Dataframes , X , Y and Events . df_X has X Co-ordinates , df_Y has Y Co-ordinates and Events_df has a list of events that has happened ( The Data is Basketball related ) . You 'll see how they link together by looking below : I want to record patterns of events across time and then take the X ,...
How to BEST extract information from multiple dataframes based on a series of if\else conditions and matching values ? ( Guidance needed ! ) )
Python : I 've been searching for a way ( more efficient that just writing loops to traverse the matrix ) to create matrices from elements given in a wrapped diagonal order , and to extract values back out in this order . As an example , given a = [ 2,3,4,5,6,7 ] , I would like to be able to generate the arrayand also ...
Wrapping/unwrapping a vector along array diagonals
Python : I have a big python script where multiple print statements and warnings ( e.g . deprecation warnings ) are being printed to the IPython console . For debugging purposes I want to write all print statements and warnings/error to an output file . Is there a way to do this in Spyder ? I have tried in the console ...
Write print statements including errors/warnings to file in Spyder
Python : Both of the following code give the same result . But I 'm not sure where should I put the raise statement.Or <code> def bisection ( f , start , stop , eps = 1e-5 , max_iteration = 100 ) : for __ in range ( max_iteration ) : half = start + ( stop - start ) /2 if abs ( f ( half ) ) < eps or half - start < eps :...
raising an exception in else part of a for loop in Python
Python : I 'm calculating the euclidean distance between two vectors represented by tuples.The hard-coded way of doing this is pretty fast . However , I would like to make no assumptions about the length of these vectors . That results in solutions like : orwhich turn out to be much ( at least twice ) slower than the f...
Can simple calculations on variable length iterables be made faster in Python ?
Python : I have a DataFrame similar to the below : , and I want to add a Streak column to it ( see example below ) : The DataFrame is approximately 200k rows going from 2005 to 2020.Now , what I am trying to do is find the number of consecutive games the Home Team has won PRIOR to the date in in the Date column in the ...
Efficiently finding consecutive streaks in a pandas DataFrame column ?
Python : I have two serializers ... MyRegisterSerializer inherits and extends a popular app/package , django-rest-auth , which connects to a fairly standard user table . I also have a Model and serializer for a custom app , TeamSerializer ( a one-to-many relationship with users ) . When a user signs up , I would like t...
Combining serializer and model functions
Python : In the full python grammar specification with statement is defined as : Where expr is : Why does with_item contains expr rule instead of plain name ? This is valid python code : According to the grammar this code is also valid ? <code> with_stmt : 'with ' with_item ( ' , ' with_item ) * ' : ' suitewith_item : ...
Python grammar : with_stmt
Python : In the following python script , why the second assert goes through ( i.e. , when adding 0 to 257 and stores the result in y , then x and y become different objects ) ? Thanks ! <code> x = 257y = 257assert x is yx = 257 y = 257 + 0assert x is not y
Python integer caching
Python : Consider the following example : Here , after the breakpoint is entered , the debugger does n't have access to the exception instance bound to err : Why is this the case ? How can I access the exception instance ? Currently I 'm using the following workaround but it feels awkward : Interestingly , using this v...
breakpoint in except clause does n't have access to the bound exception
Python : I want to make visiting websites much faster with Selenium . Does someone know , What I can do here ? I already know that I should switch off Javascript or images , for example , but what else is there ? Here is my code . You can ignore the fact that I am using the Tor Browser ( that is why it is very slow ) :...
What options are there to make visiting a website faster with Selenium and Tor browser ?
Python : On my computer , I can check thatevaluates to False.More generally , I can estimate that the formula ( a + b ) + c == a + ( b + c ) fails roughly 17 % of the time when a , b , c are chosen uniformly and independently on [ 0,1 ] , using the following simulation : I wonder if it is possible to arrive at this pro...
Probability that a formula fails in IEEE 754
Python : I have a pandas dataframe df : I want to transform this datafarme ( DF ) based on values in the list ( values ) . In df , first number 250 . It is between 200 and 400 in list values , such that ( |200-250| ) / ( 400-200 ) = 0.25 and ( 400-250 ) / ( 400-200 ) =0.75 , respectively . If data is missing ( np.nan )...
pandas int or float column to percentage distribution
Python : I am trying to roll up daily data into fiscal quarter data . For example , I have a table with fiscal quarter end dates : and a table of daily data : And I would like to create the table below.However , I do n't know how to group by varying dates without looping through each record . Any help is greatly apprec...
How to group pandas DataFrame by varying dates ?
Python : I tried using set ( ) method of python to find the unique elements in the List . It works fine removing all the duplicates . But here is my requirement , I want to get the elements which are removed by using set ( ) method . Could any one please assist me in this ? My expected output is [ 1 ] .The element whic...
How to Identify the elements which are removed from set ( ) in python ?
Python : For example , in the following code : Python would automatically print 'hi ' . Sorry if this is an obvious question , but I ca n't find out why Python would do that unless a 'test ' object was initiated . * I just started programming in general a few months ago and Python is my first language , so please spare...
Why does a class get `` called '' when not initiated ? - Python
Python : I have an int-derived class with overloaded comparison operator.In the body of the overloaded methods I need to use the original operator.The toy example : works fine with Python 3.3+ , but fails with Python 2.7 with exception AttributeError : 'super ' object has no attribute '__eq__'.I can think about several...
Accessing original int comparison from int-derived class with overloaded comparison operator
Python : I 'm trying to fetch some tabular content from a webpage using the script below . To populate the content manually , it is necessary to choose the options from the dropdown shown in this image before hitting the Submit button . I 've tried to mimic the post http requests accordingly . However , I might have go...
Ca n't parse tabular content from some search results using post requests
Python : The excel file generated can not be open when my project started with uwsgi when lxml installed in my environment as it can be opened successfully with django manage.py runserver and gunicornMy main codes like below : urls.py wsgi.py test_excel.iniThen if i start the project like uwsgi -- ini test_excel.ini as...
lxml + django + uwsgi failed to generate a right format excel file?
Python : A generator-returning function ( i.e . one with a yield statement in it ) in one of our libraries fails some tests due to an unhandled StopIteration exception . For convenience , in this post I 'll refer to this function as buggy.I have not been able to find a way for buggy to prevent the exception ( without a...
How can I prevent or trap StopIteration exception in the yield-calling function ?
Python : I would like to visualize the number of required machines in a jobshop at a certain time in graph with on the x-axis a continuous time axis and on the y-axis the number of shifts . In the dataframe below , you find an example of my data . Here , you see Shift_IDs ( which are unique ) and the start and end time...
Calculate required equipment on shifts in timespans
Python : With a list containing some missing values such as this : How can you subset the values that are positioned between two missing ( nan ) values ? I know how to do it with a for loop : Any suggestions on how to do this in a less cumbersome way ? <code> [ 10 , 11 , 12 , np.nan , 14 , np.nan , 16 , 17 , np.nan , 1...
How to subset list elements that lie between two missing values ?
Python : This question is making me pull my hair out.if I do : and call it from one thousand threads , how does the generator knows what to send next for each thread ? Everytime I call it , does the generator save a table with the counter and the caller reference or something like that ? It 's weird . Please , clarify ...
How Python Generators know who 's calling ?
Python : In the mathematical sense , a set ( or type ) is closed under an operation if the operation always returns a member of the set itself.This question is about making a class that is closed under all operations inherited from its superclasses.Consider the following class.Since __add__ has not been overridden , it...
How to create a type that is closed under inherited operations ?
Python : if arr = [ 4,3,2,1 ] and i want to swap the first value with the minimum of the array , if am using this on python they are not working but if i do thisthis works fine . Can anyone explain why ? <code> arr [ 0 ] , arr [ arr.index ( min ( arr ) ) ] = min ( arr ) , arr [ 0 ] # or arr [ 0 ] , arr [ arr.index ( mi...
Swapping list elements in python where the expressions contain function calls
Python : I am new to Python and trying to generate 5 numbers with 2 conditions : There must be 3 even and 2 odd numbersFrom those 5 numbers 3 must be low ( 1,51 ) and 2 high ( 51,100 ) . Which number will be low or high is not of interest.I have managed to solve the first part : Obviously this is not getting me anywher...
Random number generator with conditions - Python
Python : I am new to python . I have the following data frame . I am able to pivot in Excel.I want to add the difference column ( in the image , I added it manually ) .The difference is B-A value . I am able to replicate except difference column and Grand Total using Python pivot table . Below is my code.How can I add ...
Python pivot_table - Add difference column
Python : I am doing car tracking on a video . I am trying to determine how many meters it traveled.I randomly pulled 7 points from a video frame . I made point1 as my originThen on the corresponding Google Maps perspective , I calcculated the distances of the 6 points from the orgin ( delta x and delta y ) Then I ran t...
finding the mapping between video point and real world point
Python : I 'd like to be able to open a Python shell , execute some code defined in a module , then modify the module , then re-run it in the same shell without closing/reopening.I 've tried reimporting the functions/objects after modifying the script , and that does n't work : Clearly reimporting did not get me the 'n...
Run code from a Python module , modify module , then run again without exiting interpeter
Python : I have two 2D numpy arrays ( simplified in this example with respect to size and content ) with identical sizes.An ID matrix : and a value matrix : My goal is to count and sum the values from the second matrix grouped by the IDs from the first matrix : I can do this in a for loop but when the matrices have siz...
Summing data from array based on other array in Numpy
Python : I have a program that finds the highest and lowest values in an array , excludes them , then sums up the rest of the numbers in that array . It works with most random inputs , except for cases when there are duplicates of the highest or the lowest number in that arrayIn which case if I print ( sum_array ( [ 6 ...
Sum of an array while ignoring one minimum and one maximum
Python : Just wanted to ask why this ( list comprehension , if I 'm not mistaken ) : is twice as fast ( 108 steps on visualize python ) as this ( 202 steps ) : ? And also , although the first code is faster , does the second code have any advantages in any cases ? Maybe , uses less memory ? Just spitballing , don '' t ...
Python quick question about comprehensions vs list comprehensions
Python : Given a replacement map like { search : replace , search : replace , ... } and a string , how to generate a list of all possible replacements of that string ( first substring replaced , second substring replaced , both replaced etc ) . Example : The order is not important . <code> map = { 'bee ' : 'BETA ' , 'z...
Generate all possible replacements
Python : required output : Above is the code I have been trying but it gives an error zip argument # 1 must support iteration <code> d = { ' a ' : [ [ 1 , 2 , 3 ] , [ 1 , 2 , 3 ] ] , ' b ' : [ [ 2 , 4 , 1 ] , [ 1 , 6 , 1 ] ] , } def add_element ( lst ) : ad = [ sum ( i ) for i in zip ( *lst ) ] return addef csv_reducer...
Summation of elements of dictionary that are list of lists
Python : Im new to python and trying to work on looping through data : I am using the sendgrid api global stats endpoint and I am successful in getting my output for one API key.My code : Output : However , this is the output of one API key . I have several API keys under the same account and have different data associ...
How do I loop through API keys to get output for them in separate rows in my final dataframe ?