lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
Consider the following code : Running mypy v0.782 on the above code under Python 3.6.9 fails with the following error : However , I feel that this code should not be regarded as an error , as ZipFile.open ( ) returns a binary filehandle , which TextIOWrapper accepts . Moreover , IO [ bytes ] and BinaryIO are ( as far a...
from io import TextIOWrapperfrom typing import Listfrom zipfile import ZipFiledef read_zip_lines ( zippath : str , filename : str ) - > List [ str ] : with ZipFile ( zippath ) as zf : with zf.open ( filename ) as bfp : with TextIOWrapper ( bfp , 'utf-8 ' ) as fp : return fp.readlines ( ) zfopen.py:8 : error : Argument ...
mypy declares IO [ bytes ] incompatible with BinaryIO
Python
What 's a shorter way of writing this if statement ? Tried : But this seems to be incorrect . What 's the correct way ? Python 3
l = [ `` a '' , `` b '' , `` c '' , `` d '' , `` e '' ] if `` a '' in l and `` b '' in l and `` c '' in l and `` d '' in l : pass if ( `` a '' and `` b '' and `` c '' and `` d '' ) in l : pass
Shorter way of if statements in python
Python
I 'm using the Python 3.5.2 shell . I am confused about why this works as it does ? The order of the operations defines that ** is executed before > which is before == so it should work .
5 > 5**2False5 > 5**2 == FalseFalse ( 5 > 5**2 ) == FalseTrue
Order of operations Incorrect ?
Python
In a python discusion , I saw a function to convert IP string into an integer in functional progamming way . Here is the Link .The function is implemented in a single line.However , I have few ideas of funcional programming . Could anybody explain the function in detail ? I 've some knowledge of `` map '' and `` reduce...
def ipnumber ( ip ) : return reduce ( lambda sum , chunk : sum < < 8 | chunk , map ( int , ip.split ( `` . '' ) ) )
How to understand the functional programming code for converting IP string to an integer ?
Python
Why does numpy return different results with missing values when using a Pandas series compared to accessing the series ' values as in the following :
import pandas as pdimport numpy as npdata = pd.DataFrame ( dict ( a= [ 1 , 2 , 3 , np.nan , np.nan , 6 ] ) ) np.sum ( data [ ' a ' ] ) # 12.0np.sum ( data [ ' a ' ] .values ) # nan
Numpy inconsistent results with Pandas and missing values
Python
I am attempting to implement a simple Pygame script that is supposed to : First , check for when the user presses the Space key ; On Space keypress , display some text ; thenPauses for 2 seconds and then update the screen to its original state.Note that all of the above events must occur sequentially , and can not be o...
import pygameimport sysfrom pygame.locals import *WHITE = ( 255 , 255 , 255 ) BLACK = ( 0 , 0 , 0 ) pygame.init ( ) wS = pygame.display.set_mode ( ( 500 , 500 ) , 0 , 32 ) # Method works as intended by itselfdef create_text ( x , y , phrase , color ) : `` '' '' Create and displays text onto the globally-defined ` wS ` ...
Pygame Surface updates non-sequentially
Python
I have to append elements to a list only if the current iterated element is not already in the list.vsThe list comprehension gives the result is what I want , just the returned list is useless . Is this a good use case for list comprehensions ? The iteration is a good solution , but I 'm wondering if there is a more id...
> > > l = [ 1 , 2 ] > > > for x in ( 2 , 3 , 4 ) : ... if x not in l : ... l.append ( x ) ... > > > l [ 1 , 2 , 3 , 4 ] > > > l = [ 1 , 2 ] > > > [ l.append ( i ) for i in ( 2 , 3 , 4 ) if i not in l ] [ None , None ] > > > l [ 1 , 2 , 3 , 4 ]
Is list comprehension appropriate here ?
Python
I have a dataframe that looks like this : I want to add 3 more columns that show the ratio of positive and negative values by a certain number . For example , if the number is 8 : If the number is 5 : I 've been doing the calculation with a loop and several conditional statements and it 's pretty slow . I wonder if the...
> > > df valuetime2020-01-31 07:59:43.232 -62020-01-31 07:59:43.232 -22020-01-31 07:59:43.232 -12020-01-31 07:59:43.264 12020-01-31 07:59:43.389 02020-01-31 07:59:43.466 12020-01-31 07:59:43.466 52020-01-31 07:59:43.466 -12020-01-31 07:59:43.467 -12020-01-31 07:59:43.467 -12020-01-31 07:59:43.467 52020-01-31 07:59:43.4...
How to make a dataframe that shows the ratio of different types of values ?
Python
I use a tokenizer to split french sentences into words and had problems with words containing the french character â.I tried to isolate the problem and it eventually boiled down to this simple fact : â is matched by a pattern containing ’ if it 's put in an ensemble matcher.Is there something wrong on my part regarding...
> > > re.match ( r '' ’ '' , u ' â ' , re.U ) > > > re.match ( r '' [ ’ ] '' , u ' â ' , re.U ) < _sre.SRE_Match object at 0x21d41d0 > Python 2.7.3 ( default , Jan 2 2013 , 13:56:14 ) [ GCC 4.7.2 ] on linux2
Python extremely puzzling regex unicode behaviour
Python
Why ca n't I call os.stat on the special Windows file nul ? I can open it : I was hoping to check for special files like /dev/null and nul in a cross-platform way with stat.S_ISCHR and was surprised to find that I ca n't stat a file that I can open .
> > > import os > > > os.stat ( 'nul ' ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > WindowsError : [ Error 87 ] The parameter is incorrect : 'nul ' > > > f = open ( 'nul ' , ' r ' ) > > > f.read ( 10 ) ''
os.stat on Windows `` nul '' file
Python
I have fit a series of SciPy continuous distributions for a Monte-Carlo simulation and am looking to take a large number of samples from these distributions . However , I would like to be able to take correlated samples , such that the ith sample takes the e.g. , 90th percentile from each of the distributions . In doin...
# very fast way to many uncorrelated samples of length nfor shape , loc , scale , in distro_props : sp.stats.norm.rvs ( *shape , loc=loc , scale=scale , size=n ) # verrrrryyyyy slow way to take correlated samples of length ncorrelate = np.random.uniform ( size=n ) for shape , loc , scale , in distro_props : sp.stats.no...
Is there a fast alternative to scipy _norm_pdf for correlated distribution sampling ?
Python
I 've defined a function that receives an optional parameter , using a fractional default value : Now when typing foo ( in the IDLE shell , the tool-tip that pops out to help me complete the call reads ( x=0 < tuple > ) , instead of the expected ( x=0.1 ) . I 've never encountered this before , though I find it hard to...
def foo ( x=0.1 ) : pass def foo ( x= [ ( 1,0.1 ) , 2 , .3 ] ) : pass
Python 's IDLE behavior while defining fractional default values to function parameters
Python
Is it possible to cast a number behalf of a other number ? I tried this one , but type returns a string .
n = 1.34i = 10type ( i ) ( n )
Cast a value with a other values type
Python
Similar to a question asked here : SSH and telnet to localhost using pythonI 'm trying to find a solution to the following problem : From Server A ( full rights ) over Jumhost B ( no sudo ) , I want to connect to several Network devices using Python ( one after another is enough , it does n't have to be in the same tim...
class SSHTool ( ) : def __init__ ( self , host , user , auth , via=None , via_user=None , via_auth=None ) : if via : t0 = ssh.Transport ( via ) t0.start_client ( ) t0.auth_password ( via_user , via_auth ) # setup forwarding from 127.0.0.1 : < free_random_port > to |host| channel = t0.open_channel ( 'direct-tcpip ' , ho...
How do I use Python libs such as Paramiko for chain connections with Telnet and SSH
Python
I have a scenario where I 'm dynamically running functions at run-time and need to keep track of a `` localized '' scope . In the example below , `` startScope '' and `` endScope '' would actually be creating levels of `` nesting '' ( in reality , the stuff contained in this localized scope is n't print statements ... ...
def startScope ( ) : # Increment our control object 's ( not included in this example ) nesting depth control.incrementNestingDepth ( ) def endScope ( ) : # Decrement our control object 's ( not included in this example ) nesting depth control.decrementNestingDepth ( ) def myFunction ( ) : print `` A '' print `` B '' s...
Is it possible to create a dynamic localized scope in Python ?
Python
I was just revisiting some of my code to improve the performance and stumpled over something strange : Ok it seems to have some overhead when using the power-operator ( ** ) but otherwise they seem identical ( I guess NumPy is doing that ) but then it got strange : So there is no problem but it seems a bit inconsistent...
a = np.linspace ( 10,1000,1000000 ) .reshape ( 1000,1000 ) % timeit np.square ( a ) 100 loops , best of 3 : 8.07 ms per loop % timeit a*a100 loops , best of 3 : 8.18 ms per loop % timeit a**2100 loops , best of 3 : 8.32 ms per loop In [ 46 ] : % timeit np.power ( a , 2 ) 10 loops , best of 3 : 121 ms per loop % timeit ...
Wrapping np.arrays __pow__ method
Python
I 've been learning python for my hobby and empirical research into NP-complete problems such as Subset Product . The algorithm I have works , but it 's not doing it the way I intend to do.What I 'm trying to do is to stop itertools ' combinations once it arrives to a subset product of the input variable target . This ...
res_2 = [ ] ; for i in range ( 1 , len ( s ) +1 ) : var = ( findsubsets ( s , i ) ) kk = list ( map ( numpy.prod , var ) ) res_2.append ( kk ) if target in kk : print ( 'yes ' ) print ( var ) break Enter numbers WITH SPACES : 4 4 3 12enter target integer:16yes [ ( 4 , 4 ) , ( 4 , 3 ) , ( 4 , 12 ) , ( 4 , 3 ) , ( 4 , 12...
How to make python halt once target product is found in subset ?
Python
In Python , you can do : Is there a shorthand for this ? In other words , a way to do integer division that throws an exception if there is a remainder ? The reason I ask is that it would be convenient in situations like this : Right now I have to make temporary variables : which does not seem very pythonic.I know that...
assert a % b == 0c = a // b count = len ( self.rawr.foo ) / self.this.is.a.long.variable a = len ( self.rawr.foo ) b = self.this.is.a.long.variableassert a % b == 0count = a // b
Python - throw exception if division has remainder ?
Python
I need to find if items from a list appear in a string , and then add the items to a different list . This code works : However , the code iterates over line ( which could be long ) multiple times- as many times as there are item in _legal ( which could be a lot ) . That 's too slow for me , and I 'm searching for a wa...
data = [ ] line = 'akhgvfalfhda.dhgfa.lidhfalihflaih**Thing1**aoufgyafkugafkjhafkjhflahfklh**Thing2**dlfkhalfhafli ... '_legal = [ 'thing1 ' , 'thing2 ' , 'thing3 ' , 'thing4 ' , ... ] for i in _legal : if i in line : data.append ( i )
Finding multiple substrings in a string without iterating over it multiple times
Python
I 'm in doubt how the objects are stored . Say I have a class defined like : My guess is that the only thing stored in the data store is the name/value/type of some_number together with the fully qualified name of the class ( SomeEntity ) . However I have not stumbled upon any information that confirms this . 1 ) Can a...
class SomeEntity ( db.Model ) : some_number = db.IntegerProperty ( required=True ) def calculate_something ( self ) : return self.some_number * 2
How are Google App Engine model classes stored ?
Python
I want an expression whose value is a Boolean array , with the same shape of data ( or , at least , can be reshaped to the same shape ) , that tells me if the corresponding term in data is in set.E.g. , if I want to know which elements of data are strictly less than 6 , I can use a single vectorized expression , that c...
import numpydata = numpy.random.randint ( 0 , 10 , ( 6,8 ) ) test = set ( numpy.random.randint ( 0 , 10 , 5 ) ) a = data < 6 b = data in test TypeError : unhashable type : 'numpy.ndarray ' In [ 1 ] : import numpy as npIn [ 2 ] : nr , nc = 100 , 100In [ 3 ] : top = 3000In [ 4 ] : data = np.random.randint ( 0 , top , ( n...
are elements of an array in a set ?
Python
I 'm using ropemacs and company-mode for code completion in emacs.However , I oftern found ropemacs slow , for example , when I type inThen ropemacs will try to do the completion for the methods under os modular , which will make the emacs stuck for 5~6 seconds.Is there a way to avoid this situation ?
import osos .
How to make ropemacs faster in emacs ?
Python
Suppose I have a list : How can I iterate over the list , taking each item along with its complement from the list ? That is , would printIdeally I 'm looking for a concise expression that I can use in a comprehension .
l = [ 0 , 1 , 2 , 3 ] for item , others in ... print ( item , others ) 0 [ 1 , 2 , 3 ] 1 [ 0 , 2 , 3 ] 2 [ 0 , 1 , 3 ] 3 [ 0 , 1 , 2 ]
Iterate over ( item , others ) in a list
Python
Using the C converted to python Radial Positions algorithm from this question , I have been successful in creating a radial graph based on a root node , all the way to the last child of each node . Now I have a new problem where I have multiple root nodes and will need them to be centered around the first root found , ...
def RadialPositions ( node , id ) : children_in_node = len ( timelinedatta.neighbors ( id , mode= '' out '' ) ) def rotate_node ( x , y , nangle ) : nx = x * math.cos ( nangle ) - y * math.sin ( nangle ) ny = x * math.sin ( nangle ) + y * math.cos ( nangle ) return nx , ny def get_depth ( id ) : count = 0 for v in time...
How do I make a circular tree with multiple root trees
Python
I start with a list full of False elements.Then those elements are switched to True independently over the course of iterations.I need to know when the list is fully True . Let 's say I have 3 elements , they start asthen I check them over the iterations like : The list of elements is fixed and should not grow ( or shr...
[ False , False , False ] elements == [ True , True , True ]
python lowest cost of checking various equalities at once
Python
The docs for itertools.combinations state : Combinations are emitted in lexicographic sort order . So , if the input iterable is sorted , the combination tuples will be produced in sorted order.Elements are treated as unique based on their position , not on their value . So if the input elements are unique , there will...
for i in range ( len ( iterable ) ) : for j in range ( i + 1 , len ( iterable ) ) : for k in range ( j + 1 , len ( iterable ) ) : ... yield iterable [ i ] , iterable [ j ] , iterable [ k ] , ...
What is the guarantee made by itertools.combinations ?
Python
I 've created an iterative function which outputs 4 3 2 1 0 1 2 3 4.If I want a recursive function that does the exact same thing , how should I think ?
def bounce2 ( n ) : s = n for i in range ( n ) : print ( n ) n = n-1 if n < = 0 : for i in range ( s+1 ) : print ( -n ) n = n-1 returnbounce2 ( 4 )
Python , Make an iterative function into a recursive function
Python
I started using TK in python to build a graphical interface for my program . I 'm not able to fix 2 issues concerning ( 1 ) the position of a button in the window and ( 2 ) use a value of a radiobutton inside a fucntion.This is my current code : I would like that the buttons `` Links '' and `` Comments '' were position...
root = tk.Tk ( ) root.title ( `` START '' ) root.geometry ( `` 500x200+500+200 '' ) v = tk.IntVar ( ) v.set ( 0 ) # initializing the choicemy_choise = [ ( `` Basic '' ,1 ) , ( `` Advanced '' ,2 ) , ( 'Extreme',3 ) ] def ShowChoice ( ) : print ( v.get ( ) ) tk.Label ( root , text= '' '' '' Choose your configuration : ''...
Graphical user interface with TK - button position and actions
Python
I am running a test suite with hypothesis-4.24.6 and pytest-5.0.0 . My test has a finite set of possible inputs , but hypothesis never finishes testing.I have reduced it to the following minimal example , which I run as pytest test.pyI would expect it to try all six combinations here and then succeed . Or possibly a sm...
from hypothesis import givenimport hypothesis.strategies as st @ given ( x=st.just ( 0 ) | st.just ( 1 ) , y=st.just ( 0 ) | st.just ( 1 ) | st.just ( 2 ) ) def test_x_y ( x , y ) : assert True
Why does my simple , finite hypothesis test never stop ?
Python
I am a new user of Django , and I am trying to figure out how to created a model which can support many kind ( type ) of elements.This is the plot : I want to create a Blog module on my application.To do this , I created a model Page , which describe a Blog Page . And a model PageElement , which describe a Post on the ...
class Page ( models.Model ) : uuid = models.UUIDField ( default=uuid.uuid4 , editable=False , unique=True ) # Basical informations title = models.CharField ( max_length=150 ) description = models.TextField ( blank=True ) # Foreign links user = models.ForeignKey ( settings.AUTH_USER_MODEL , on_delete=models.SET_NULL , n...
Create a Blog which support multiple type of post
Python
Alright , this is doing my head in . I have two dictionaries with object groups as shown below : The output I 'm looking for is : The problem I 'm having is that I do n't know beforehand how much levels of recursion there are , as nested groups can theoretically go on infinitely . Additionally , I 'm having trouble wit...
groups = { 'servers ' : [ 'unix_servers ' , 'windows_servers ' ] , 'unix_servers ' : [ 'server_a ' , 'server_b ' , 'server_group ' ] , 'windows_servers ' : [ 'server_c ' , 'server_d ' ] , 'server_group ' : [ 'server_e ' , 'server_f ' ] } hosts = { 'server_a ' : '10.0.0.1 ' , 'server_b ' : '10.0.0.2 ' , 'server_c ' : '1...
Recursively combine dictionaries
Python
I need to be able to set a flag on a class ( not on an instance of a class ) which is not visible to a subclass . The question is , is it possible , and how would I do it if it is ? To illustrate , I want something like this : ... where hasattr ( Master , `` __flag__ '' ) should return True for Master but False for Chi...
class Master ( SomeOtherClass ) : __flag__ = Trueclass Child ( Master ) : pass @ hide_thisclass Master ( SomeOtherClass ) : pass @ hide_thisclass Child ( Master ) : passclass GrandChild ( Child ) : pass ... for cls in ( Master , Child , GrandChild ) if cls.__hidden__ : # Master , Child else : # GrandChild
How to add attribute to python *class* that is _not_ inherited ?
Python
Trying to get a double-precision floating point score from a UTF-8 encoded string object in Python . The idea is to grab the first 8 bytes of the string and create a float , so that the strings , ordered by their score , would be ordered lexicographically according to their first 8 bytes ( or possibly their first 63 bi...
get_score ( u'aaaaaaa ' ) < get_score ( u'aaaaaaab ' ) < get_score ( u'zzzzzzzz ' )
How to compute a double precision float score from the first 8 bytes of a string in Python ?
Python
For larger Python packages which might interfere with other packages it is recommended to install them into their own virtual environment and some Python packages expose CLI commands to the shell.Is there a way to pip-install such a package into its own virtual environment , but have the CLI commands accessible from a ...
pip install csvkit
How to pip-install Python package into virtual env and have CLI commands accessible in normal shell
Python
I have a list of sorted values that represents angles ( in degrees ) , all in the range [ 0,360 ) My goal is to find the best range ( minimum range ) that fit all the angles in the list.Some examples : Given the list angles = [ 0,1,2,10,20,35 ] the answer would be ( 0,35 ) . Given the list angles = [ 10,20,340,355 ] , ...
MAX_ANGLE = 360def get_best_range ( angles ) : number_of_angles = len ( angles ) # Append the list of angles with the same angles plus 360 ( max value ) angles = angles + [ angle + MAX_ANGLE for angle in angles ] # Create a list of all possible ranges possible_ranges = [ ( angles [ i ] , angles [ i+number_of_angles - 1...
find the minimum range that includes all angles in a list
Python
I have a voxel ( np.array ) with size 3x3x3 , filled with some values , this setup is essential for me . I want to have rotation-invariant representation of it . For this case , I decided to try PCA representation which is believed to be invariant to orthogonal transformations . anotherFor simplicity , I took some axes...
import numpy as npvoxel1 = np.random.normal ( size= ( 3,3,3 ) ) voxel2 = np.transpose ( voxel1 , ( 1,0,2 ) ) # np.rot90 ( voxel1 ) # basis = [ ] for i in range ( 3 ) : for j in range ( 3 ) : for k in range ( 3 ) : basis.append ( [ i+1 , j+1 , k+1 ] ) # avoid 0basis = np.array ( basis ) voxel1 = voxel1.reshape ( ( 27,1 ...
Why my PCA is not invariant to rotation and axis swap ?
Python
I really hope this is n't a duplicate . I tried to search for my question and I could n't seem to find it.So I have a fairly simple function that converts feet to meters : This works nicely and accepts ints , floats , arrays , and lists . However , if I put in a list ( instead of a numpy array ) , I 'd like to have a l...
def feetToMeters ( val ) : return numpy.array ( val ) * 0.3048 def feetToMeters ( val ) : try : return val * 0.3084 except TypeError : return [ 0.3084 * v for v in val ]
How to properly incorporate duck-typing to return original type ?
Python
I have two lists of equal length . The first list l1 contains data.The second list l2 contains the category the data in l1 belongs to : How can I partition the first list based on the positions defined by numbers such as 1 , 2 , 3 , 4 in the second list , using a list comprehension or lambda function . For example , 2 ...
l1 = [ 2 , 3 , 5 , 7 , 8 , 10 , ... , 23 ] l2 = [ 1 , 1 , 2 , 1 , 3 , 4 , ... , 3 ]
Mapping two list without looping
Python
I have two datasets that I need to validate against . All records should match . I am having trouble in determining how to iterate through each different column . For example , in the above code , I want to compare A_1 to A_2 , and B_1 to B_2 , to return a new column , A_check and B_check respectively , that return Tru...
import pandas as pd import numpy as npdf = pd.DataFrame ( [ [ 'charlie ' , 'charlie ' , 'beta ' , 'cappa ' ] , [ 'charlie ' , 'charlie ' , 'beta ' , 'delta ' ] , [ 'charlie ' , 'charlie ' , 'beta ' , 'beta ' ] ] , columns= [ 'A_1 ' , 'A_2 ' , 'B_1 ' , 'B_2 ' ] ) df.head ( ) Out [ 83 ] : A_1 A_2 B_1 B_20 charlie charlie...
Find entries that do not match between columns and iterate through columns
Python
I have array : I would like find this pattern and return booelan mask : I use strides : I find positions of first values only : And positions another vals : Last return mask by in1d : Verify mask : I think my solution is a bit over-complicated . Is there some better , more pythonic solution ?
arr = np.array ( [ 1,2,3,2,3,4,3,2,1,2,3,1,2,3,2,2,3,4,2,1 ] ) print ( arr ) [ 1 2 3 2 3 4 3 2 1 2 3 1 2 3 2 2 3 4 2 1 ] pat = [ 1,2,3 ] N = len ( pat ) # https : //stackoverflow.com/q/7100242/2901002def rolling_window ( a , window ) : shape = a.shape [ : -1 ] + ( a.shape [ -1 ] - window + 1 , window ) strides = a.stri...
Find boolean mask by pattern
Python
I get following result when i execute stanford parser from nltk.but i need it in the form How can I get this result , perhaps using recursive function.Is there in-built function already ?
( S ( VP ( VB get ) ( NP ( PRP me ) ) ( ADVP ( RB now ) ) ) ) S - > VPVP - > VB NP ADVPVB - > getPRP - > meRB - > now
Grammar rule extraction from parsed result
Python
I 'm trying to plot a line over a bar chart.Here is my dataframe : When I run these two lines I get : However if I remove kind='bar ' I get three lines and if I change kind='line ' for kind='bar ' I get three bars ...
meh fiches ratio2007 1412 1338 0.9475922008 1356 1324 0.9764012009 1394 1298 0.9311332010 1352 1275 0.9430472011 1398 1325 0.9477832012 1261 1215 0.9635212013 1144 845 0.7386362014 1203 1167 0.9700752015 1024 1004 0.9804692016 1197 1180 0.985798 ax = graph [ [ 'meh ' , 'fiches ' ] ] .plot ( kind='bar ' , color= [ ' # 6...
Line does n't show over barplot
Python
Halfway through Architecture Patterns with Python , I have two questions about how should the Domain Model Classes be structured and instantiated . Assume on my Domain Model I have the class DepthMap : According to what I understood from the book , this class is not correct since it depends on Numpy , and it should dep...
class DepthMap : def __init__ ( self , map : np.ndarray ) : self.map = map class DepthMap : def __init__ ( self , map : List ) : self.map = map @ classmethod def from_numpy ( cls , map : np.ndarray ) : return cls ( map.tolist ( ) ) @ classmethod def from_str ( cls , map : str ) : return cls ( [ float ( i ) for i in s.s...
Should Domain Model Classes always depend on primitives ?
Python
I have to work with time series data imported from some CSVs which may look like this : As you can see , we have 3 sensors . Each sensor has its own time series with measures of temperature , humidity and pressure . However , the data is fragmented in two CSVs and it can have many gaps , etc.The objetive is to join all...
import pandas as pdcsv_a = [ [ `` Sensor_1 '' , '2019-05-25 10:00 ' , 25 , 60 ] , [ `` Sensor_2 '' , '2019-05-25 10:00 ' , 30 , 45 ] , [ `` Sensor_1 '' , '2019-05-25 10:05 ' , 26 , None ] , [ `` Sensor_2 '' , '2019-05-25 10:05 ' , 30 , 46 ] , [ `` Sensor_1 '' , '2019-05-25 10:10 ' , 27 , 63 ] , [ `` Sensor_1 '' , '2019...
How to join many fragmented time series in one regular Pandas DataFrame in Python
Python
Reading about Python coroutines , I came across this code : which curiously outputs : In particular , it misses printing the 3 . Why ? The referenced question does not answer this question because I am not asking what send does . It sends values back into the function . What I am asking is why , after I issue send ( 3 ...
def countdown ( n ) : print ( `` Start from { } '' .format ( n ) ) while n > = 0 : print ( `` Yielding { } '' .format ( n ) ) newv = yield n if newv is not None : n = newv else : n -= 1c = countdown ( 5 ) for n in c : print ( n ) if n == 5 : c.send ( 2 ) Start from 5Yielding 55Yielding 3Yielding 22Yielding 11Yielding 0...
Why does this Python generator/coroutine lose a value ?
Python
I have a list of points with their coordinates , looking like this : What is the Pythonic way to iterate over them and choose three different every time ? I ca n't find simpler solution than using three for loops like this : So I 'm asking for help .
[ ( 0,1 ) , ( 2,3 ) , ( 7 , -1 ) and so on . ] for point1 in a : for point2 in a : if not point1 == point2 : for point3 in a : if not point1 == point3 and not point2 == point3 :
Choose three different values from list in Python
Python
I am trying to load the whole content of this link ( clicking on المزيد ) I tried so many tutorials like this one here , which teaches how to work with a similar issue ( Infinite Scrolling Pages ) .My issue is that I could n't manage to specify the load more class on this page to click it . But , if I am not mistaken ,...
< ng-include src= '' 'loader.html ' '' class= '' ng-scope '' > < div class= '' loading-div ng-scope ng-hide '' ng-show= '' ! loadingMoreData '' > < div class= '' spinner '' > < div class= '' bounce1 '' > < /div > < div class= '' bounce2 '' > < /div > < div class= '' bounce3 '' > < /div > < /div > < /div > < /ng-include...
Clicking `` Load More '' on webpages by using python
Python
I 'm trying to re-compile a ttf glyph-font based on it 's source svg files.I 'm using python and FontForge and struggling with converting SVG shape into FontForge 's SplineSet format . For example , this SVG fileIs represented in a font generated by FontForge as this SplineSet formatI want to create a function that rec...
SplineSet85 235 m 1,0 , -1 85 85 l 1,1 , -1 235 85 l 1,2 , -1 235 43 l 1,3 , -1 85 43 l 2,4,5 68 43 68 43 55.5 55.5 c 128 , -1,6 43 68 43 68 43 85 c 2,7 , -1 43 235 l 1,8 , -1 85 235 l 1,0 , -1427 85 m 1,9 , -1 427 235 l 1,10 , -1 469 235 l 1,11 , -1 469 85 l 2,12,13 469 68 469 68 456.5 55.5 c 128 , -1,14 444 43 444 43...
converting an SVG to FontForge 's SplineSet format
Python
How can I match 'suck ' only if not part of 'honeysuckle ' ? Using lookbehind and lookahead I can match suck if not 'honeysuck ' or 'suckle ' , but it also fails to catch something like 'honeysucker ' ; here the expression should match , because it does n't end in le :
re.search ( r ' ( ? < ! honey ) suck ( ? ! le ) ' , 'honeysucker ' )
Regex match if not before and after
Python
I 'm building a debugging tool.IPython lets me do stuff likeAnd it will show me the source .
MyCls ? ?
Given a Python class , how can I inspect and find the place in my code where it is defined ?
Python
I am manipulating the creation of classes via Python 's metaclasses . However , although a class has a attribute thanks to its parent , I can not delete it.The execution of the above code yield an AttributeError when class B is created : Why ca n't I delete the existing attribute ? EDIT : I think my question is differe...
class Meta ( type ) : def __init__ ( cls , name , bases , dct ) : super ( ) .__init__ ( name , bases , dct ) if hasattr ( cls , `` x '' ) : print ( cls.__name__ , `` has x , deleting '' ) delattr ( cls , `` x '' ) else : print ( cls.__name__ , `` has no x , creating '' ) cls.x = 13class A ( metaclass=Meta ) : passclass...
Deleting existing class variable yield AttributeError
Python
After a few hours of isolating a bug , I have come up with the following MCVE example to demonstrate the problem I 've had : a.py : b.py : The expected output of a.py is : The actual output is : Moreover , if I create a separate module c.py , the output is as expected : Clearly , the interaction between isinstance and ...
from b import get_foo_indirectlyclass Foo : passif __name__ == '__main__ ' : print ( `` Indirect : '' , isinstance ( get_foo_indirectly ( ) , Foo ) ) print ( `` Direct : '' , isinstance ( Foo ( ) , Foo ) ) def get_foo_indirectly ( ) : from a import Foo return Foo ( ) Indirect : TrueDirect : True Indirect : FalseDirect ...
Why do circular imports cause problems with object identity using ` isinstance ` ?
Python
I want to run vectorization on images using multiple GPUs ( for now my script use only one GPU ) . I have a list of images , graph and session . THe script 's output is saved vector . My machine has 3 NVIDIA GPU . Environment : Ubuntu , python 3.7 , Tensorflow 2.0 ( with GPU support ) .Here is my code example ( initial...
def load_graph ( frozen_graph_filename ) : # We load the protobuf file from the disk and parse it to retrieve the # unserialized graph_def with tf.io.gfile.GFile ( frozen_graph_filename , `` rb '' ) as f : graph_def = tf.compat.v1.GraphDef ( ) graph_def.ParseFromString ( f.read ( ) ) # Then , we import the graph_def in...
How to run classify_image on multiple GPU ?
Python
I would like to interleave multiple numpy arrays with differing dimensions along a particular axis . In particular , I have a list of arrays of shape ( _ , *dims ) , varying along the first axis , which I would like to interleave to obtain another array of shape ( _ , *dims ) . For instance , given the inputthe desired...
a1 = np.array ( [ [ 11,12 ] , [ 41,42 ] ] ) a2 = np.array ( [ [ 21,22 ] , [ 51,52 ] , [ 71,72 ] , [ 91,92 ] , [ 101,102 ] ] ) a3 = np.array ( [ [ 31,32 ] , [ 61,62 ] , [ 81,82 ] ] ) interweave ( a1 , a2 , a3 ) np.array ( [ [ 11,12 ] , [ 21,22 ] , [ 31,32 ] , [ 41,42 ] , [ 51,52 ] , [ 61,62 ] , [ 71,72 ] , [ 81,82 ] , [...
Interleaving NumPy arrays with mismatching shapes
Python
Normally a picture is gladly displayed via an ID . But in my example these images are displayed as content / character : What can I do here ?
.fa-calendar-alt : before { Synchro : `` \f073 '' ;
Python + Selenium - How to check an image which is styled with CSS and displayed as content ?
Python
I 'm analyzing a set of python scripts and came across this snippet . I 'm not sure if my interpretation is correct , since I have n't come across any similar C or Java code and I do n't know Python.My interpretation goes like this : Essentially , I think the original unpack operation extracts 8 bytes , dumps 4 of them...
for i in xrange ( self.num_sections ) : offset , a1 , a2 , a3 , a4 = struct.unpack ( ' > LBBBB ' , self.data_file [ 78+i*8:78+i*8+8 ] ) flags , val = a1 , a2 < < 16|a3 < < 8|a4 self.sections.append ( ( offset , flags , val ) ) for each item in num_sections convert the data_file range into a big-endian unsigned long , a...
Verify my interpretation of this python code snippet is correct
Python
I 'm new to programming and am learning Python with the book Learning Python the Hard Way . I 'm at exercise 36 , where we 're asked to write our own simple game.http : //learnpythonthehardway.org/book/ex36.html ( The problem is , when I 'm in the hallway ( or more precisely , in 'choices ' ) and I write 'gate ' the ga...
experiences = [ ] def choices ( ) : while True : choice = raw_input ( `` What do you wish to do ? `` ) .lower ( ) if `` oldman '' in choice or `` man '' in choice or `` ask '' in choice : print oldman elif `` gate '' in choice or `` fight '' in choice or `` try '' in choice and not `` pissedoff '' in experiences : prin...
Python ( LPTHW ) Exercise 36
Python
What I wantFrom a yaml config I get a python dictionary that looks like this : As you see the keyword 'subselect ' is common to all sub level and its value is always a dict , but its existance is optional . The amount of nesting might change . I 'm searching for a function , that allows me to do the following : where '...
conf = { 'cc0 ' : { 'subselect ' : { 'roi_spectra ' : [ 0 ] , 'roi_x_pixel_spec ' : 'slice ( 400 , 1200 ) ' } , 'spec ' : { 'subselect ' : { 'x_property ' : 'wavenumber ' } } , 'trace ' : { 'subselect ' : { 'something ' : 'jaja ' , 'roi_spectra ' : [ 1 , 2 ] } } } } # desired function that uses recursion I belive.colle...
Inheritance in a configuration dict
Python
I have a list of lists which is nested in multiple layers of lists.possible inputs : [ [ [ [ 1,2,3 ] , [ a , b , c ] ] ] ] or [ [ [ 1,2,3 ] , [ a , b , c ] ] ] or [ [ [ 1,2,3 ] ] , [ [ a , b , c ] ] ] when I use flat ( ) it will just flatten everything which is not what I want . [ 1,2,3 , a , b , c ] What I need instea...
def flat ( S ) : if S == [ ] : return S if isinstance ( S [ 0 ] , list ) : return flat ( S [ 0 ] ) + flat ( S [ 1 : ] ) return S [ :1 ] + flat ( S [ 1 : ] )
python : flatten to a list of lists but no more
Python
Running AquaEmacs , I want to execute a buffer ( C-c C-c ) in Python . The buffer starts with : The execution in AquaEmacs starts with : where test_one_liners.py is my file . This gives this error : Anyone know where and how to fix this ? Let me add the information again to make it clear . Create this buffer : Use File...
from __future__ import print_function import sys , impif'test_one_liners ' in sys.modules : imp.reload ( test_one_liners ) else : import test_one_liners SyntaxError : from __future__ imports must occur at the beginning of the file from __future__ import print_function print ( `` Hello '' )
Execute AquaMacs buffer that has `` from __future__ import ... ''
Python
Is it possible to make either jedi.el or anaconda-mode complete base class methods ? For example , when subclassing html.parser.HTMLParser I expect it to complete the following code at point ( 1 ) ( base class has methods like handle_data or handle_starttag ) :
import html.parserclass MyParser ( html.parser.HTMLParser ) : def handle_ # ( 1 )
Emacs : Complete base class methods for Python
Python
So when I run this ... the error is on this line bomb=pd.DataFrame ( here,0 ) but the trace shows me a bunch of code from the pandas library to get to the error . How do I suppress all that and have the error just look like this : I just want what 's relevant to me and the last line of code that I wrote which was bad.T...
import traceback , sysimport pandas as pd def error_handle ( err_var , instance_name=None ) : # err_var list of variables , instance_name print ( traceback.format_exc ( ) ) a= sys._getframe ( 1 ) .f_locals for i in err_var : # selected var for instance t= a [ instance_name ] print i , '' -- - > '' , getattr ( t , i.spl...
python : how to get up until the last error made by my code
Python
I have 2 heatmaps I 'm trying to join together , one contains week over week data and the other contains 6W/YTD information . I keep them separate so their colors are n't skewed.When they 're put together in a subplot , the yaxis label on the right is the first row label on the leftI would like to remove that yaxis lab...
fig1 [ 'layout ' ] [ 'yaxis ' ] [ 'title ' ] ='This works with a single plot'fig1.show ( ) annotations=wow_annot+totals_annot wow [ 'data_labels ' ] = int_to_str ( wow [ 'data ' ] ) totals [ 'data_labels ' ] = int_to_str ( totals [ 'data ' ] ) ( Pdb ) [ i for i in fig1.layout.annotations if i.text == ' A ' ] [ ] ( Pdb ...
Suppress y axis label in plotly subplot , annotation misalignment
Python
I want to use condition GANs with the purpose of generated images for one domain ( noted as domain A ) and by having input images from a second domain ( noted as domain B ) and the class information as well . Both domains are linked with the same label information ( every image of domain A is linked to an image to doma...
def generator_model_v2 ( ) : global BATCH_SIZE inputs = Input ( ( IN_CH , img_cols , img_rows ) ) e1 = BatchNormalization ( mode=0 ) ( inputs ) e2 = Flatten ( ) ( e1 ) e3 = BatchNormalization ( mode=0 ) ( e2 ) e4 = Dense ( 1024 , activation= '' relu '' ) ( e3 ) e5 = BatchNormalization ( mode=0 ) ( e4 ) e6 = Dense ( 512...
Add class information to Generator model in keras
Python
I 'm new with Python ( with Java as a basic ) . I read Dive Into Python books , in the Chapter 3 I found about Multi-Variable Assignment . Maybe some of you can help me to understand what happen in this code bellow : What I understand so far is the # 1 and # 2 has same output , that display the values of tuple . # 3 di...
> > > params = { 1 : ' a ' , 2 : ' b ' , 3 : ' c ' } > > > params.items ( ) # To display list of tuples of the form ( key , value ) . [ ( 1 , ' a ' ) , ( 2 , ' b ' ) , ( 3 , ' c ' ) ] > > > [ a for b , a in params.items ( ) ] # 1 [ ' a ' , ' b ' , ' c ' ] > > > [ a for a , a in params.items ( ) ] # 2 [ ' a ' , ' b ' , ...
Lack Understanding of Multi-Variable Assignments Python
Python
I am trying to apply a function , cumulatively , to values that lie within a window defined by 'start ' and 'finish ' columns . So , 'start ' and 'finish ' define the intervals where the value is 'active ' ; for each row , I want to get a sum of all 'active ' values at the time.Here is a 'bruteforce ' example that does...
df = pd.DataFrame ( data= [ [ 1,3,100 ] , [ 2,4,200 ] , [ 3,6,300 ] , [ 4,6,400 ] , [ 5,6,500 ] ] , columns= [ 'start ' , 'finish ' , 'val ' ] ) df [ 'dummy ' ] = 1df = df.merge ( df , on= [ 'dummy ' ] , how='left ' ) df = df [ ( df [ 'start_y ' ] < = df [ 'start_x ' ] ) & ( df [ 'finish_y ' ] > df [ 'start_x ' ] ) ] v...
Cumulative apply within window defined by other columns
Python
I am writing a module that provides one function and needs an initialization step , however due to certain restrictions I need to initialize on first call , so I am looking for the proper idiom in python that would allow me to get rid of the conditional.I 'd like to get rid of that conditional with something like this ...
# with conditionalmodule.pyinitialized = Falsedef function ( *args ) : if not initialized : initialize ( ) do_the_thing ( *args ) # with no conditionalmodule.pydef function ( *args ) : initialize ( ) do_the_thing ( *args ) function = do_the_thing
Changing a function implementation in Python
Python
What I want to accomplish : What I have thought of so far : Is there a more Pythonic way of accomplishing this ?
[ a , b , c , d ] - > [ ( a , x ) , ( b , x ) , ( c , x ) , ( d , x ) ] done = [ ] for i in [ a , b , c , d ] : done.append ( ( i , x ) )
Python turning a list into a list of tuples
Python
I have a dataframe like below : I want the number of occurence of zeroes from df [ ' B ' ] under the following condition : expected output : I dont know how to formulate the count part . Any help is really appreciated
A B C1 1 12 0 13 0 04 1 05 0 16 0 07 1 0 if ( df [ ' B ' ] < df [ ' C ' ] ) : # count number of zeroes in df [ ' B ' ] until it sees 1 . A B C output1 1 1 Nan2 0 1 13 0 0 Nan4 1 0 Nan5 0 1 16 0 1 07 1 0 Nan
How to count the number of occurences before a particular value in dataframe python ?
Python
I just learned that the new walrus operator ( : = ) ca n't be used to set instance attributes , it 's supposedly invalid syntax ( raises a SyntaxError ) .Why is this ? ( And can you provide a link to official docs mentioning this ? ) I looked through PEP 572 , and could n't find if/where this is documented.ResearchThis...
class Foo : def __init__ ( self ) : self.foo : int = 0 def bar ( self , value : int ) - > None : self.spam ( self.foo : = value ) # Invalid syntax def baz ( self , value : int ) - > None : self.spam ( temp : = value ) self.foo = temp def spam ( self , value : int ) - > None : `` '' '' Do something with value . '' '' ''...
Why ca n't Python 's walrus operator be used to set instance attributes ?
Python
I 'm having trouble understanding the output of a piece of python code.The output isI ca n't for the life of me understand why it is notAny help much appreciated .
mani= [ ] nima= [ ] for i in range ( 3 ) nima.append ( i ) mani.append ( nima ) print ( mani ) [ [ 0,1,2 ] , [ 0,1,2 ] , [ 0,1,2 ] ] [ [ 0 ] , [ 0,1 ] , [ 0,1,2 ] ]
Python issue with for loop and append
Python
So I 'm making a PyGame that baseball is falling from up , and users in the bottom have to catch the ball . The balls are falling in a random speed , but I 'm having hard time getting balls falling in different speed . For example , my current code for the ball is : Here , when I run the program , the ball is falling i...
def update ( self ) : if self.is_falling : `` '' '' Move the ball down . '' '' '' self.y += random.randint ( 10 , 200 ) / 100 self.rect.y = self.y
Python choose random number in specific interval
Python
consider pd.Series sHow do I interpolate to get : note : I want the first and last np.nan to remainI only want to fill in values when I have values on both sides to do the the interpolation.In other words , I want to interpolate , not extrapolate .
import pandas as pdimport numpy as nps = pd.Series ( [ np.nan , 1 , np.nan , 3 , np.nan ] ) pd.Series ( [ np.nan , 1 , 2 , 3 , np.nan ] ) 0 NaN1 1.02 2.03 3.04 NaNdtype : float64
pandas interpolate only when values exist on both sides
Python
Question : Overview : I 'm looking for a vectorised way to get the first date that a certain condition is seen . The condition is found when the price in dfDays is > the target price specified in dfWeeks.target . This condition has to be hit after the date the target was set.Is there a way to do the following time seri...
np.random.seed ( seed=1 ) rng = pd.date_range ( ' 1/1/2000 ' , '2000-07-31 ' , freq='D ' ) weeks = np.random.uniform ( low=1.03 , high=3 , size= ( len ( rng ) , ) ) ts2 = pd.Series ( weeks , index=rng ) dfDays = pd.DataFrame ( { 'price ' : ts2 } ) dfWeeks = dfDays.resample ( '1W-Mon ' ) .first ( ) dfWeeks [ 'target ' ]...
Vectorised way to query date and price data
Python
Lets say I have the following 2 classes in module ain module b it uses the Real classHow do I monkey patch so that when b imports Real it 's actually swapped with Fake ? I was trying to do like this in initialize script but it does n't work.My purpose is to use the Fake class in development mode .
class Real ( object ) : ... def print_stuff ( self ) : print 'real'class Fake ( Real ) : def print_stff ( self ) : print 'fake ' from a import RealReal ( ) .print_stuff ( ) if env == 'dev ' : from a import Real , Fake Real = Fake
Python : how to monkey patch ( swap ) classes
Python
I wrote a function that takes a degree and returns the orientation as ' N ' , 'NE ' , ... etc . Very simple , but it 's ugly - is there any way to rewrite this to make it ... prettier ?
def orientation ( tn ) : if 23 < = tn < = 67 : o = 'NE ' elif 68 < = tn < = 113 : o = ' E ' elif 114 < = tn < = 158 : o = 'SE ' elif 159 < = tn < = 203 : o = 'S ' elif 204 < = tn < = 248 : o = 'SW ' elif 249 < = tn < = 293 : o = ' W ' elif 294 < = tn < = 338 : o = 'NW ' else : o = ' N ' return o
Simple , ugly function to produce an orientation from an angle .
Python
I want to subclass a numeric type ( say , int ) in python and give it a shiny complex constructor . Something like this : This works fine under Python 2.4 , but Python 2.6 gives a deprecation warning . What is the best way to subclass a numeric type and to redefine constructors for builtin types in newer Python version...
class NamedInteger ( int ) : def __init__ ( self , value ) : super ( NamedInteger , self ) .__init__ ( value ) self.name = 'pony ' def __str__ ( self ) : return self.namex = NamedInteger ( 5 ) print x + 3print str ( x ) class NamedInteger ( int ) : def __init__ ( self , value ) : self.name = 'pony ' def __str__ ( self ...
How to add a constructor to a subclassed numeric type ?
Python
How do I retrieve the values of an enumerated variable v ? For example , Now , given just the above variable v , how would I retrieve a list of values [ val1 , val2 , val3 ] of v ( where val1 , val3 , val3 are expressions as above ) ? I have tried [ v.sort ( ) .constructor ( 0 ) , ... ( 1 ) , ... ( 2 ) ] but the constr...
vTyp , ( val1 , val2 , val3 ) = EnumSort ( 'vTyp ' , [ 'val1 ' , 'val2 ' , 'val3 ' ] ) v = Const ( 'my variable ' , vTyp )
retrieving value of an enumerated type in Z3Py
Python
Imagine I have a list of tuples in this format : How could I sort the list by the first element of the tuples , and then by the second ? I 'd like to get to this list : I was thinking to do a sort for the first element , and then go through the list , and build a hash with subarrays . I will probably overcomplicate thi...
( 1 , 2 , 3 ) ( 1 , 0 , 2 ) ( 3 , 9 , 11 ) ( 0 , 2 , 8 ) ( 2 , 3 , 4 ) ( 2 , 4 , 5 ) ( 2 , 7 , 8 ) ... . ( 0 , 2 , 8 ) ( 1 , 0 , 2 ) ( 1 , 2 , 3 ) ( 2 , 3 , 4 ) ( 2 , 4 , 5 ) ( 2 , 7 , 8 ) ( 3 , 9 , 11 )
What 's the standard way of doing this sort in Python ?
Python
I want to remove item from a list called mom . I have another list called cutHow do I remove what in cut from mom , except for zero ? My desire result is
mom= [ [ 0,8,1 ] , [ 0 , 6 , 2 , 7 ] , [ 0 , 11 , 12 , 3 , 9 ] , [ 0 , 5 , 4 , 10 ] ] cut = [ 0 , 9 , 8 , 2 ] mom= [ [ 0,1 ] , [ 0,6,7 ] , [ 0,11,12,3 ] , [ 0,5,4,10 ] ]
Python- Removing items
Python
I am trying to create a generic Python class for a Pub/Sub type app , where the model definition specified three methods for each type of resource X that we have : I 've abstracted the code to a single method , that accepts parameters about the type and action : But this then requires me to hand-write each of the defin...
new_Xchanged_Xdeleted_X def _pub_wrapper ( self , verb , obj_type , id_list ) : ids = [ str ( i ) for i in id_list ] self._pub ( ids , ' { 0 } . { 1 } '.format ( verb , obj_type.lower ( ) ) ) def new_resources ( self , id_list ) : self._pub_wrapper ( 'new ' , 'resources ' , id_list ) def changed_resources ( self , id_l...
Writing a generic getattr ( ) and populate method parameters based on attr name
Python
I 'm using a PolyCollection to plot data of various sizes . Sometimes the polygons are very small . If they are too small , they do n't get plotted at all . I would expect the outline at least to show up so you 'd have an idea that some data is there . Is there a a setting to control this ? Here 's some code to reprodu...
import matplotlib.pyplot as pltfrom matplotlib.collections import PolyCollectionfrom matplotlib import colorsfig = plt.figure ( ) ax = fig.add_subplot ( 111 ) verts = [ ] edge_col = colors.colorConverter.to_rgb ( 'lime ' ) face_col = [ ( 2.0 + val ) / 3.0 for val in edge_col ] # a little lighterfor i in range ( 10 ) : ...
plot with polycollection disappears when polygons get too small
Python
I want to find a way to make faster the computation of the pairwise accuracy , that is going to compare elements of the same array ( in this case it 's a panda df column ) computing their difference and then comparing the two results obtained . I would have a dataframe df with 3 column ( id of the document , Jugment th...
def pairwise ( agree , disagree ) : return ( agree/ ( agree+disagree ) ) def pairwise_computing_array ( df ) : humanScores = np.array ( df [ 'Judgement ' ] ) pagerankScores = np.array ( df [ 'PR_Score ' ] ) total = 0 agree = 0 disagree = 0 for i in range ( len ( df ) -1 ) : for j in range ( i+1 , len ( df ) ) : total +...
Faster double iteration over a single array in Python
Python
I 'm well aware that there are differences between lists and tuples and that tuples are n't just constant lists , but there are few examples where the two are actually treated differently by the code ( as opposed to by a coding convention ) , so I ( sloppily ) have used them interchangeably . Then I came across a case ...
> > > import numpy as np > > > a = np.arange ( 9 ) .reshape ( 3,3 ) > > > aarray ( [ [ 0 , 1 , 2 ] , [ 3 , 4 , 5 ] , [ 6 , 7 , 8 ] ] ) > > > idx = ( 1,1 ) > > > a [ idx ] 4 > > > idx = [ 1,1 ] > > > a [ idx ] array ( [ [ 3 , 4 , 5 ] , [ 3 , 4 , 5 ] ] )
List and tuple behave differently
Python
I think this is safe : but is this safe ? It should do the same thing because condition checking is lazy in python . It wo n't try to get the value ( and raise an exception because there 's no such key in the dict ) because the first condition is already not satisfied . But can I rely on the lazyness and use the second...
if key in test_dict : if test_dict [ key ] == 'spam ' : print ( 'Spam detected ! ' ) if key in test_dict and test_dict [ key ] == 'spam ' : print ( 'Spam detected ! ' )
Is checking if key is in dictionary and getting it 's value in the same `` if '' safe ?
Python
I am trying to change the default error message Django generates for ArrayField ( Specifically too many items entered error message ) If a user enters too many items to my ArrayField the following message generates in the template : List contains 4 items , it should contain no more than 3.I want to change this message ...
error_messages = { 'topic ' : { 'invalid ' : ( `` You ca n't have more than 3 topics . `` ) , } , from django.contrib.postgres.fields import ArrayFieldfrom django.db import modelsclass Topic ( models.Model ) topic = ArrayField ( models.CharField ( max_length=20 ) , size=3 , blank=True , null=True ) from django import f...
How to override ArrayField default error messages in template ?
Python
Something that can converttoor something similarand accepting in 2 or 5
r '' a+| ( ? : ab+c ) '' { ( 1 , ' a ' ) : [ 2 , 3 ] , ( 2 , ' a ' ) : [ 2 ] , ( 3 , ' b ' ) : [ 4 , 3 ] , ( 4 , ' c ' ) : [ 5 ] }
is there any compiler that can convert regexp to fsm ? or could convert to human words ?
Python
I want to simulate basic cell division using python arrays . I have u , which is an array of arrays as defined by : each u [ i ] represents a cell in the system and u is the entire system.Next , I define some functions which I will use for my cell division algorithm later . Here I am initializing my cells so they take ...
n=2 # number of elements that can describe each cellN=2 # number of cellsu= [ np.zeros ( ( n , n ) ) for i in range ( N ) ] V=2.0epsilon=2.0 Mx=np.zeros ( ( n , n ) ) My=np.zeros ( ( n , n ) ) for x in range ( n ) : Mx [ x ] =x-n/2for y in range ( n ) : My [ y ] =y-n/2 for i in range ( N ) : for x in range ( n ) : for ...
change one element of an array into two and then delete the original ( cell division simulation )
Python
Coming from a C++ world I got used to write conditional compilation based on flags that are determined at compilation time with tools like CMake and the like . I wonder what 's the most Pythonic way to mimic this functionality . For instance , this is what I currently set depending on whether a module is found or not :...
import imptry : imp.find_module ( 'petsc4py ' ) HAVE_PETSC=Trueexcept ImportError : HAVE_PETSC=False
What 's the Pythonic way to write conditional statements based on installed modules ?
Python
I want to create some kind of descriptor on a class that returns a proxy object . The proxy object , when indexed retrieves members of the object and applies the index to them . Then it returns the sum.E.g. , This solution worked fine while I had actual arrays as member variables : Now I 've changed my arrays into Pyth...
class NDArrayProxy : def __array__ ( self , dtype=None ) : retval = self [ : ] if dtype is not None : return retval.astype ( dtype , copy=False ) return retvalclass ArraySumProxy ( NDArrayProxy ) : def __init__ ( self , arrays ) : self.arrays = arrays @ property def shape ( self ) : return self.arrays [ 0 ] .shape def ...
Adaptable descriptor in Python
Python
I 'm a newbie to Regular expression in Python : I have a list that i want to search if it 's contain a employee name.The employee name can be : it can be at the beginning followed by space . followed by ® OR followed by space OR Can be at the end and space before itnot a case sensitiveThe output from the ListSentence ...
ListSentence = [ `` Steve® '' , `` steveHotel '' , `` Rob spring '' , `` Car Daniel '' , `` CarDaniel '' , '' Done daniel '' ] ListEmployee = [ `` Steve '' , `` Rob '' , `` daniel '' ] [ `` Steve® '' , `` Rob spring '' , `` Car Daniel '' , `` Done daniel '' ]
How can I use regex to search inside sentence -not a case sensitive
Python
There are several columns in the data , three are named `` candidate_id '' , `` enddate '' , `` TitleLevel '' .Within the same id , if the enddate is the same , I will delete the lower level record.For example , given : What I want is : I will delete candidate_id=1 , enddate=2013.5.1 , and titlelevel=2.I have come up w...
candidate_id startdate enddate TitleLevel 1 2012.1.1 2013.5.1 2 1 2011.1.1 2013.5.1 4 1 2008.12.1 2010.1.1 3 2 2010.10.1 2012.12.1 2 candidate_id startdate enddate TitleLevel 1 2011.1.1 2013.5.1 4 1 2008.12.1 2010.1.1 3 2 2010.10.1 2012.12.1 2 for i in range ( nrow-2 , -1 , -1 ) : if ( JobData [ 'enddate ' ] [ i ] == J...
how to use groupby to avoid loop in python
Python
Why do instances of the object class not have a __dict__ , causing it to behave as semantically immutable ? What were the reasons for choosing this design ? Specifically , why : instances of types defined in C do n't have a __dict__ attribute by default.As noted in this question .
> > > a = object ( ) > > > a.x = 5Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > AttributeError : 'object ' object has no attribute ' x ' > > > b = lambda:0 > > > b.x = 5 > > > b.x5
Why are instances of the ` object ` class immutable in Python ?
Python
I have a standard nested json file which looks like the below : They are multi level nested and I have to eliminate all the nesting by creating new objects . Nested json file . The new objects that needs to be createdMy approach : I used a normalise function to make all the lists into dicts . Added another function whi...
{ `` persons '' : [ { `` id '' : `` f4d322fa8f552 '' , `` address '' : { `` building '' : `` 710 '' , `` coord '' : `` [ 123 , 465 ] '' , `` street '' : `` Avenue Road '' , `` zipcode '' : `` 12345 '' } , `` cuisine '' : `` Chinese '' , `` grades '' : [ { `` date '' : `` 2013-03-03T00:00:00.000Z '' , `` grade '' : `` B...
Eliminate nesting by creating new objects from json
Python
So lets say i have a numpy array that holds points in 2d space , like the followingI also have a numpy array that labels each point to a number , this array is a 1d array with the length as the number of points in the point array.Now i want to take the mean value of each point that have an index from the labels array ....
np.array ( [ [ 3 , 2 ] , [ 4 , 4 ] , [ 5 , 4 ] , [ 4 , 2 ] , [ 4 , 6 ] , [ 9 , 5 ] ] ) np.array ( [ 0 , 1 , 1 , 0 , 2 , 1 ] ) return np.array ( [ points [ labels==k ] .mean ( axis=0 ) for k in range ( k ) ] )
Numpy split array based on condition without for loop
Python
Is there a clever way to iterate over two lists in Python ( without using list comprehension ) ? I mean , something like this : instead of :
# ( a , b ) is the cartesian product between the two lists ' elementsfor a , b in list1 , list2 : foo ( a , b ) for a in list1 : for b in list2 : foo ( a , b )
Python multi-lists iteration
Python
I have a problem.I have list of lists that look something like this : I need sorting to be on date field ( 1st one ) , but each set of same dates must be sorted in reverse order.Resulting list must look like this : As you can see list is ordered by date but , for the same dates list is reversed.dates are still descendi...
[ [ datetime.date ( 2019 , 3 , 29 ) , Decimal ( '44819.75 ' ) ] , [ datetime.date ( 2019 , 3 , 29 ) , Decimal ( '45000.00 ' ) ] , [ datetime.date ( 2019 , 3 , 28 ) , Decimal ( ' 0.00 ' ) ] , [ datetime.date ( 2019 , 3 , 22 ) , Decimal ( '-275.00 ' ) ] , [ datetime.date ( 2019 , 3 , 22 ) , Decimal ( '-350.00 ' ) ] , [ d...
Python sort list of lists partially reverse based on date
Python
I 'm working on a project where I need to create a preview of nx.Graph ( ) which allows to change position of nodes dragging them with a mouse . My current code is able to redraw whole figure immediately after each motion of mouse if it 's clicked on specific node . However , this increases latency significantly . How ...
import networkx as nximport matplotlib.pyplot as pltimport numpy as npimport scipy.spatialdef refresh ( G ) : plt.axis ( ( -4 , 4 , -1 , 3 ) ) nx.draw_networkx_labels ( G , pos = nx.get_node_attributes ( G , 'pos ' ) , bbox = dict ( fc= '' lightgreen '' , ec= '' black '' , boxstyle= '' square '' , lw=3 ) ) nx.draw_netw...
Plotting networkx.Graph : how to change node position instead of resetting every node ?
Python
Is there a better way to insert , one by one , elements in an array to all posible positions ( n+1 positions ) .E.g inserting [ 1 ] to [ 6 7 8 9 ] should produce : So if I insert A = [ 1 2 3 ] one by one to B = [ 6 7 8 9 ] it should produce : Currently I use numpy.roll like this :
[ 1 6 7 8 9 ] [ 9 1 6 7 8 ] [ 8 9 1 6 7 ] [ 7 8 9 1 6 ] [ 6 7 8 9 1 ] [ 1 6 7 8 9 ] [ 9 1 6 7 8 ] [ 8 9 1 6 7 ] [ 7 8 9 1 6 ] [ 6 7 8 9 1 ] -- -- -- -- -- -- -- -- -- -- [ 2 6 7 8 9 ] [ 9 2 6 7 8 ] [ 8 9 2 6 7 ] [ 7 8 9 2 6 ] [ 6 7 8 9 2 ] -- -- -- -- -- -- -- -- -- -- [ 3 6 7 8 9 ] [ 9 3 6 7 8 ] [ 8 9 3 6 7 ] [ 7 8 9 ...
Insert element into numpy array and get all rolled permutations
Python
Possible Duplicate : Python '== ' vs 'is ' comparing strings , 'is ' fails sometimes , why ? Hi . I have a question about how Python works when it comes how and when references are used.I have an example here that I understand.This makes sense . But here comes something I do n't understand.Why does a is b return True a...
a = `` cat '' b = aa is b True a = `` cat '' b = `` cat '' a is b Truec = 1.2d = 1.2c is d Falsee = `` cat '' f = `` '' .join ( a ) e is f False a = `` cat '' b = `` c '' c = b+ '' at '' a is c False # Why not same as setting c = `` cat '' d = `` cat '' + '' '' a is d True # Probably same as setting d = `` cat '' e = `...
Python strings references