signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _decode_signed_user ( encoded_sig , encoded_data ) : """Decodes the ` ` POST ` ` ed signed data"""
decoded_sig = _decode ( encoded_sig ) decoded_data = loads ( _decode ( encoded_data ) ) if decoded_sig != hmac . new ( app . config [ 'CANVAS_CLIENT_SECRET' ] , encoded_data , sha256 ) . digest ( ) : raise ValueError ( "sig doesn't match hash" ) return decoded_sig , decoded_data
def add_site_amplification ( self , C , C_SITE , sites , sa_rock , idx , rup ) : """Applies the site amplification scaling defined in equations from 10 to 15"""
n_sites = sites . vs30 . shape # Convert from reference rock to hard rock hard_rock_sa = sa_rock - C [ "lnSC1AM" ] # Gets the elastic site amplification ratio ln_a_n_max = self . _get_ln_a_n_max ( C , n_sites , idx , rup ) # Retrieves coefficients needed to determine smr sreff , sreffc , f_sr = self . _get_smr_coeffs (...
def get_admin_ids ( self ) : """Method to get the administrator id list ."""
admins = self . json_response . get ( "admin_list" , None ) admin_ids = [ admin_id for admin_id in admins [ "userid" ] ] return admin_ids
def pull ( self , platform = None ) : """Pull the image digest . Args : platform ( str ) : The platform to pull the image for . Default : ` ` None ` ` Returns : ( : py : class : ` Image ` ) : A reference to the pulled image ."""
repository , _ = parse_repository_tag ( self . image_name ) return self . collection . pull ( repository , tag = self . id , platform = platform )
def partitionBy ( self , * cols ) : """Partitions the output by the given columns on the file system . If specified , the output is laid out on the file system similar to Hive ' s partitioning scheme . : param cols : name of columns > > > df . write . partitionBy ( ' year ' , ' month ' ) . parquet ( os . pa...
if len ( cols ) == 1 and isinstance ( cols [ 0 ] , ( list , tuple ) ) : cols = cols [ 0 ] self . _jwrite = self . _jwrite . partitionBy ( _to_seq ( self . _spark . _sc , cols ) ) return self
def get_pres_features ( self , features = None ) : """Returns a df of features for presented items"""
if features is None : features = self . dist_funcs . keys ( ) elif not isinstance ( features , list ) : features = [ features ] return self . pres . applymap ( lambda x : { k : v for k , v in x . items ( ) if k in features } if x is not None else None )
def format_return_text ( self , data , function , ** kwargs ) : # pylint : disable = unused - argument '''Print out YAML using the block mode'''
# emulate the yaml _ out output formatter . It relies on a global _ _ opts _ _ object which # we can ' t obviously pass in try : try : outputter = data [ next ( iter ( data ) ) ] . get ( 'out' ) except ( StopIteration , AttributeError ) : outputter = None return salt . output . string_format...
def addAxes ( axtype = None , c = None ) : """Draw axes on scene . Available axes types : : param int axtype : - 0 , no axes , - 1 , draw three gray grid walls - 2 , show cartesian axes from ( 0,0,0) - 3 , show positive range of cartesian axes from ( 0,0,0) - 4 , show a triad at bottom left - 5 , show...
vp = settings . plotter_instance if axtype is not None : vp . axes = axtype # overrride r = vp . renderers . index ( vp . renderer ) if not vp . axes : return if c is None : # automatic black or white c = ( 0.9 , 0.9 , 0.9 ) if numpy . sum ( vp . renderer . GetBackground ( ) ) > 1.5 : c = ( 0.1 ...
def _AsynchronouslyGetProcessOutput ( formattedCmd , printStdOut , printStdErr , ** kwargs ) : '''Asynchronously read the process'''
opts = filterKWArgsForFunc ( kwargs , subprocess . Popen ) opts [ 'stdout' ] = subprocess . PIPE opts [ 'stderr' ] = subprocess . PIPE process = subprocess . Popen ( formattedCmd , ** opts ) # Launch the asynchronous readers of the process ' stdout and stderr . stdout_queue = Queue . Queue ( ) stdout_reader = _Asynchro...
def Rphideriv ( self , R , Z , phi = 0. , t = 0. ) : """NAME : Rphideriv PURPOSE : evaluate the mixed radial , azimuthal derivative INPUT : R - Galactocentric radius ( can be Quantity ) Z - vertical height ( can be Quantity ) phi - Galactocentric azimuth ( can be Quantity ) t - time ( can be Quantit...
try : return self . _amp * self . _Rphideriv ( R , Z , phi = phi , t = t ) except AttributeError : # pragma : no cover if self . isNonAxi : raise PotentialError ( "'_phiforce' function not implemented for this non-axisymmetric potential" ) return 0.
def push ( self , statsDict = None , prefix = None , path = None ) : """Push stat values out to Graphite ."""
if statsDict is None : statsDict = scales . getStats ( ) prefix = prefix or self . prefix path = path or '/' for name , value in list ( statsDict . items ( ) ) : name = str ( name ) subpath = os . path . join ( path , name ) if self . _pruned ( subpath ) : continue if hasattr ( value , '__ca...
def group_order ( tlist ) : """Group together Identifier and Asc / Desc token"""
tidx , token = tlist . token_next_by ( t = T . Keyword . Order ) while token : pidx , prev_ = tlist . token_prev ( tidx ) if imt ( prev_ , i = sql . Identifier , t = T . Number ) : tlist . group_tokens ( sql . Identifier , pidx , tidx ) tidx = pidx tidx , token = tlist . token_next_by ( t = ...
def _optionalPrompt ( self , mode ) : """Interactively prompt for parameter if necessary Prompt for value if (1 ) mode is hidden but value is undefined or bad , or (2 ) mode is query and value was not set on command line Never prompt for " u " mode parameters , which are local variables ."""
if ( self . mode == "h" ) or ( self . mode == "a" and mode == "h" ) : # hidden parameter if not self . isLegal ( ) : self . getWithPrompt ( ) elif self . mode == "u" : # " u " is a special mode used for local variables in CL scripts # They should never prompt under any circumstances if not self . isLega...
def all_state_variables_read ( self ) : """recursive version of variables _ read"""
if self . _all_state_variables_read is None : self . _all_state_variables_read = self . _explore_functions ( lambda x : x . state_variables_read ) return self . _all_state_variables_read
def check_args ( args ) : """Checks the arguments and options ."""
# Checking that only VCF can have a - ( stdout ) as output if args . output_format not in _streamable_format and args . output == "-" : logger . error ( "{} format cannot be streamed to standard output" "" . format ( args . output_format ) ) sys . exit ( 1 ) # Checking the file extensions if args . output_forma...
def read_adjacency_matrix ( file_path , separator , undirected ) : """Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format . Inputs : - file _ path : The path where the adjacency matrix is stored . - separator : The delimiter among values ( e . g . " , " , " \t " ,...
# Open file file_row_generator = get_file_row_generator ( file_path , separator ) # Initialize lists for row and column sparse matrix arguments . row = list ( ) col = list ( ) data = list ( ) append_row = row . append append_col = col . append append_data = data . append # Initialize node anonymizer . id_to_node = dict...
def Search ( star , pos_tol = 2.5 , neg_tol = 50. , ** ps_kwargs ) : '''NOTE : ` pos _ tol ` is the positive ( i . e . , above the median ) outlier tolerance in standard deviations . NOTE : ` neg _ tol ` is the negative ( i . e . , below the median ) outlier tolerance in standard deviations .'''
# Smooth the light curve t = np . delete ( star . time , np . concatenate ( [ star . nanmask , star . badmask ] ) ) f = np . delete ( star . flux , np . concatenate ( [ star . nanmask , star . badmask ] ) ) f = SavGol ( f ) med = np . nanmedian ( f ) # Kill positive outliers MAD = 1.4826 * np . nanmedian ( np . abs ( f...
def add_readgroups ( job , bamfile , sample_type , univ_options ) : """This module adds the appropriate read groups to the bam file ARGUMENTS 1 . bamfile : < JSid for a bam file > 2 . sample _ type : string of ' tumor _ dna ' or ' normal _ dna ' 3 . univ _ options : Dict of universal arguments used by almos...
job . fileStore . logToMaster ( 'Running add_read_groups on %s:%s' % ( univ_options [ 'patient' ] , sample_type ) ) work_dir = job . fileStore . getLocalTempDir ( ) input_files = { 'aligned_fixpg.bam' : bamfile } get_files_from_filestore ( job , input_files , work_dir , docker = True ) parameters = [ 'AddOrReplaceReadG...
def serialise ( self ) : """Creates standard market book json response , will error if EX _ MARKET _ DEF not incl ."""
return { 'marketId' : self . market_id , 'totalAvailable' : None , 'isMarketDataDelayed' : None , 'lastMatchTime' : None , 'betDelay' : self . market_definition . get ( 'betDelay' ) , 'version' : self . market_definition . get ( 'version' ) , 'complete' : self . market_definition . get ( 'complete' ) , 'runnersVoidable...
def version ( ) : """Return the version number tuple from the ` ` stderr ` ` output of ` ` dot - V ` ` . Returns : Two or three ` ` int ` ` version ` ` tuple ` ` . Raises : graphviz . ExecutableNotFound : If the Graphviz executable is not found . subprocess . CalledProcessError : If the exit status is non...
cmd = [ 'dot' , '-V' ] out , _ = run ( cmd , check = True , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) info = out . decode ( 'ascii' ) ma = re . search ( r'graphviz version (\d+\.\d+(?:\.\d+)?) ' , info ) if ma is None : raise RuntimeError return tuple ( int ( d ) for d in ma . group ( 1 ) . split ...
def qos_rcv_queue_multicast_threshold_traffic_class7 ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) qos = ET . SubElement ( config , "qos" , xmlns = "urn:brocade.com:mgmt:brocade-qos" ) rcv_queue = ET . SubElement ( qos , "rcv-queue" ) multicast = ET . SubElement ( rcv_queue , "multicast" ) threshold = ET . SubElement ( multicast , "threshold" ) traffic_class7 = ET . SubElement ( th...
def set ( self , item , column = None , value = None ) : """Query or set the value of given item . With one argument , return a dictionary of column / value pairs for the specified item . With two arguments , return the current value of the specified column . With three arguments , set the value of given colu...
if value is not None : self . _visual_drag . set ( item , ttk . Treeview . column ( self , column , 'id' ) , value ) return ttk . Treeview . set ( self , item , column , value )
def make_properties_list ( self , field ) : """Fill the ` ` field ` ` into a properties list and return it . : param dict field : the content of the property list to make : return : field _ list instance filled with given field : rtype : nodes . field _ list"""
properties_list = nodes . field_list ( ) # changing the order of elements in this list affects # the order in which they are displayed property_names = [ 'label' , 'type' , 'description' , 'required' , 'disabled' , 'hidden' , 'default' , 'placeholder' , 'validate_regex' , 'choices' , 'collapse' , 'group' ] for name in ...
def add_tgt ( self , as_rep , enc_as_rep_part , override_pp = True ) : # from AS _ REP """Creates credential object from the TGT and adds to the ccache file The TGT is basically the native representation of the asn1 encoded AS _ REP data that the AD sends upon a succsessful TGT request . This function doesn ' t...
c = Credential ( ) c . client = CCACHEPrincipal . from_asn1 ( as_rep [ 'cname' ] , as_rep [ 'crealm' ] ) if override_pp == True : self . primary_principal = c . client c . server = CCACHEPrincipal . from_asn1 ( enc_as_rep_part [ 'sname' ] , enc_as_rep_part [ 'srealm' ] ) c . time = Times . from_asn1 ( enc_as_rep_pa...
def from_tuples ( cls , tuples ) : """Creates a clamping from tuples of the form ( variable , sign ) Parameters tuples : iterable [ ( str , int ) ] An iterable of tuples describing clamped variables Returns caspo . core . clamping . Clamping Created object instance"""
return cls ( it . imap ( lambda ( v , s ) : Literal ( v , s ) , tuples ) )
def top_level ( self ) : """Print just the top level of an object , being sure to show where it goes deeper"""
output = { } if isinstance ( self . obj , dict ) : for name , item in self . obj . items ( ) : if isinstance ( item , dict ) : if item : output [ name ] = StrReprWrapper ( '{...}' ) else : output [ name ] = StrReprWrapper ( '{}' ) elif isinstan...
def landing_view ( request ) : '''The external landing .'''
revision = None can_edit = False edit_url = None if "farnswiki" in settings . INSTALLED_APPS : from wiki . models import Page from wiki . hooks import hookset binder = settings . WIKI_BINDERS [ 0 ] wiki = binder . lookup ( ) try : if wiki : page = wiki . pages . get ( slug = "lan...
def assignBranchRegisters ( inodes , registerMaker ) : """Assign temporary registers to each of the branch nodes ."""
for node in inodes : node . reg = registerMaker ( node , temporary = True )
def levenshtein_distance_metric ( a , b ) : """1 - farthest apart ( same number of words , all diff ) . 0 - same"""
return ( levenshtein_distance ( a , b ) / ( 2.0 * max ( len ( a ) , len ( b ) , 1 ) ) )
def transformToNative ( obj ) : """Turn obj . value into a list of dates , datetimes , or ( datetime , timedelta ) tuples ."""
if obj . isNative : return obj obj . isNative = True if obj . value == '' : obj . value = [ ] return obj tzinfo = getTzid ( getattr ( obj , 'tzid_param' , None ) ) valueParam = getattr ( obj , 'value_param' , "DATE-TIME" ) . upper ( ) valTexts = obj . value . split ( "," ) if valueParam == "DATE" : obj ...
def contains_all ( self , other ) : """Return ` ` True ` ` if all strings in ` ` other ` ` have size ` length ` ."""
dtype = getattr ( other , 'dtype' , None ) if dtype is None : dtype = np . result_type ( * other ) dtype_str = np . dtype ( 'S{}' . format ( self . length ) ) dtype_uni = np . dtype ( '<U{}' . format ( self . length ) ) return dtype in ( dtype_str , dtype_uni )
def commands ( self ) : """Memoize and return the flattened list of commands"""
if not getattr ( self , "_commands" , None ) : self . _commands = [ ] for command in self . orig_commands : if isinstance ( command , Command ) : command = [ command ] for instruction in command : self . _commands . append ( instruction ) return self . _commands
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : TriggerContext for this TriggerInstance : rtype : twilio . rest . api . v2010 . account . usage . trigger . TriggerContext...
if self . _context is None : self . _context = TriggerContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def _get_variables ( self ) : """Get the requested variables ."""
if self . _specs_in [ _VARIABLES_STR ] == 'all' : return _get_all_objs_of_type ( Var , getattr ( self . _obj_lib , 'variables' , self . _obj_lib ) ) else : return set ( self . _specs_in [ _VARIABLES_STR ] )
def parse ( timestring ) : """Convert a statbank time string to a python datetime object ."""
for parser in _PARSERS : match = parser [ 'pattern' ] . match ( timestring ) if match : groups = match . groups ( ) ints = tuple ( map ( int , groups ) ) time = parser [ 'factory' ] ( ints ) return time raise TimeError ( 'Unsupported time format {}' . format ( timestring ) )
def pairwise_intersection ( boxlist1 , boxlist2 ) : """Compute pairwise intersection areas between boxes . Args : boxlist1 : Nx4 floatbox boxlist2 : Mx4 Returns : a tensor with shape [ N , M ] representing pairwise intersections"""
x_min1 , y_min1 , x_max1 , y_max1 = tf . split ( boxlist1 , 4 , axis = 1 ) x_min2 , y_min2 , x_max2 , y_max2 = tf . split ( boxlist2 , 4 , axis = 1 ) all_pairs_min_ymax = tf . minimum ( y_max1 , tf . transpose ( y_max2 ) ) all_pairs_max_ymin = tf . maximum ( y_min1 , tf . transpose ( y_min2 ) ) intersect_heights = tf ....
def show_version_info ( self , version ) : """Summarizes info of a particular version ( a la " git show version " )"""
if version in self . versions : stdout = self . repo . show ( version , '--summary' ) . stdout logger . info ( stdout ) else : logger . info ( 'Version {0} not found' . format ( version ) )
def do_track ( self , arg ) : """track expression Display a graph showing which objects are referred by the value of the expression . This command requires pypy to be in the current PYTHONPATH ."""
try : from rpython . translator . tool . reftracker import track except ImportError : print ( '** cannot import pypy.translator.tool.reftracker **' , file = self . stdout ) return try : val = self . _getval ( arg ) except : pass else : track ( val )
def _to_pywintypes ( row ) : """convert values in a row to types accepted by excel"""
def _pywintype ( x ) : if isinstance ( x , dt . date ) : return dt . datetime ( x . year , x . month , x . day , tzinfo = dt . timezone . utc ) elif isinstance ( x , ( dt . datetime , pa . Timestamp ) ) : if x . tzinfo is None : return x . replace ( tzinfo = dt . timezone . utc ) ...
def _add_to_tbz ( tfile , filename , data_str ) : '''Adds string data to a tarfile'''
# Create a bytesio object for adding to a tarfile # https : / / stackoverflow . com / a / 52724508 encoded_data = data_str . encode ( 'utf-8' ) ti = tarfile . TarInfo ( name = filename ) ti . size = len ( encoded_data ) tfile . addfile ( tarinfo = ti , fileobj = io . BytesIO ( encoded_data ) )
def _filter_or_exclude ( self , negate , * args , ** kwargs ) : """Overrides default behavior to handle linguist fields ."""
from . models import Translation new_args = self . get_cleaned_args ( args ) new_kwargs = self . get_cleaned_kwargs ( kwargs ) translation_args = self . get_translation_args ( args ) translation_kwargs = self . get_translation_kwargs ( kwargs ) has_linguist_args = self . has_linguist_args ( args ) has_linguist_kwargs =...
def experimental_designs ( df , filepath = None ) : """For each experimental design it plot all the corresponding experimental conditions in a different plot Parameters df : ` pandas . DataFrame ` _ DataFrame with columns ` id ` and starting with ` TR : ` filepath : str Absolute path to a folder where t...
axes = [ ] bw = matplotlib . colors . ListedColormap ( [ 'white' , 'black' ] ) cols = df . columns for i , dd in df . groupby ( "id" ) : cues = dd . drop ( [ c for c in cols if not c . startswith ( "TR:" ) ] + [ "id" ] , axis = 1 ) . reset_index ( drop = True ) cues . columns = [ c [ 3 : ] for c in cues . colum...
def merge_hex_executables ( target , source , env ) : """Combine all hex files into a singular executable file ."""
output_name = str ( target [ 0 ] ) hex_final = IntelHex ( ) for image in source : file = str ( image ) root , ext = os . path . splitext ( file ) file_format = ext [ 1 : ] if file_format == 'elf' : file = root + '.hex' hex_data = IntelHex ( file ) # merge will throw errors on mismatched ...
def settle ( self , transferred_amount : TokenAmount , locked_amount : TokenAmount , locksroot : Locksroot , partner_transferred_amount : TokenAmount , partner_locked_amount : TokenAmount , partner_locksroot : Locksroot , block_identifier : BlockSpecification , ) : """Settles the channel ."""
self . token_network . settle ( channel_identifier = self . channel_identifier , transferred_amount = transferred_amount , locked_amount = locked_amount , locksroot = locksroot , partner = self . participant2 , partner_transferred_amount = partner_transferred_amount , partner_locked_amount = partner_locked_amount , par...
def user_post_save ( sender , ** kwargs ) : """After User . save is called we check to see if it was a created user . If so , we check if the User object wants account creation . If all passes we create an Account object . We only run on user creation to avoid having to check for existence on each call to U...
# Disable post _ save during manage . py loaddata if kwargs . get ( "raw" , False ) : return False user , created = kwargs [ "instance" ] , kwargs [ "created" ] disabled = getattr ( user , "_disable_account_creation" , not settings . ACCOUNT_CREATE_ON_SAVE ) if created and not disabled : Account . create ( user...
def send_error ( self , code , message = None ) : """Send and log an error reply . Arguments are the error code , and a detailed message . The detailed message defaults to the short entry matching the response code . This sends an error response ( so it must be called before any output has been generated ...
try : shortmsg , longmsg = self . responses [ code ] except KeyError : shortmsg , longmsg = '???' , '???' if message is None : message = shortmsg explain = longmsg self . log_error ( "code %d, message %s" , code , message ) # using _ quote _ html to prevent Cross Site Scripting attacks ( see bug # 1100201) ...
def bus_get ( celf , type , private , error = None ) : "returns a Connection to one of the predefined D - Bus buses ; type is a BUS _ xxx value ."
error , my_error = _get_error ( error ) result = ( dbus . dbus_bus_get , dbus . dbus_bus_get_private ) [ private ] ( type , error . _dbobj ) my_error . raise_if_set ( ) if result != None : result = celf ( result ) # end if return result
def execute_read_only ( * args , ** kwargs ) : # TODO : consolidate with execute """Executes the sql statement , but does not commit . Returns the cursor to commit @ return : DB and cursor instance following sql execution"""
# Inspect the call stack for the originating call args = CoyoteDb . __add_query_comment ( args [ 0 ] ) # Execute the query db = CoyoteDb . __get_db_read_instance ( ) cursor = db . cursor ( ) try : cursor . execute ( * args , ** kwargs ) except OperationalError , e : raise OperationalError ( '{} when executing: ...
def stringToDateTime ( s , tzinfo = None ) : """Returns datetime . datetime object ."""
try : year = int ( s [ 0 : 4 ] ) month = int ( s [ 4 : 6 ] ) day = int ( s [ 6 : 8 ] ) hour = int ( s [ 9 : 11 ] ) minute = int ( s [ 11 : 13 ] ) second = int ( s [ 13 : 15 ] ) if len ( s ) > 15 : if s [ 15 ] == 'Z' : tzinfo = utc except : raise ParseError ( "'%s' is ...
def rank ( self , issue , next_issue ) : """Rank an issue before another using the default Ranking field , the one named ' Rank ' . : param issue : issue key of the issue to be ranked before the second one . : param next _ issue : issue key of the second issue ."""
if not self . _rank : for field in self . fields ( ) : if field [ 'name' ] == 'Rank' : if field [ 'schema' ] [ 'custom' ] == "com.pyxis.greenhopper.jira:gh-lexo-rank" : self . _rank = field [ 'schema' ] [ 'customId' ] break elif field [ 'schema' ] [ 'c...
def optimize ( self , G , params0 = None , n_times = 10 , verbose = False , vmax = 5 , perturb = 1e-3 , factr = 1e7 ) : """Optimize the model considering G"""
# set params0 from null if params0 is None if params0 is None : if self . null is None : if verbose : print ( ".. fitting null model" ) self . fitNull ( ) if self . bgRE : params0 = sp . concatenate ( [ self . null [ 'params0_g' ] , self . null [ 'params0_n' ] ] ) else : ...
def throw_random_intervals ( lengths , regions , save_interval_func = None , allow_overlap = False ) : """Generates a set of non - overlapping random intervals from a length distribution . ` lengths ` : list containing the length of each interval to be generated . We expect this to be sorted by decreasing len...
# Copy regions regions = [ ( x [ 1 ] - x [ 0 ] , x [ 0 ] , x ) for x in regions ] # Sort ( long regions first ) regions . sort ( ) regions . reverse ( ) # Throw if ( save_interval_func != None ) : throw_random_private ( lengths , regions , save_interval_func , allow_overlap ) return else : intervals = [ ] ...
def color_stream_st ( istream = sys . stdin , save_palette = False , ** kwargs ) : """Read filenames from the input stream and detect their palette ."""
for line in istream : filename = line . strip ( ) try : palette = extract_colors ( filename , ** kwargs ) except Exception as e : print ( filename , e , file = sys . stderr ) continue print_colors ( filename , palette ) if save_palette : save_palette_as_image ( filena...
def encrypt_template ( self , enc_key , mac_key , enc_offset ) : """Encrypts current tpl _ buf according to the protocol - symmetric encryption : param enc _ key : : param mac _ key : : param enc _ offset : : return :"""
# AES - 256 - CBC / PKCS7Padding to_encrypt = self . tpl_buff [ enc_offset : ] encrypted = aes_enc ( enc_key , PKCS7 . pad ( to_encrypt ) ) # Mac the whole buffer to_mac = PKCS7 . pad ( self . tpl_buff [ : enc_offset ] + encrypted ) mac = cbc_mac ( mac_key , to_mac ) return to_mac + mac
def trigger ( self ) : '''return True if we should trigger now'''
tnow = time . time ( ) if tnow < self . last_time : print ( "Warning, time moved backwards. Restarting timer." ) self . last_time = tnow if self . last_time + ( 1.0 / self . frequency ) <= tnow : self . last_time = tnow return True return False
def remove ( self , child ) : """Removes the child element"""
if not isinstance ( child , AbstractElement ) : raise ValueError ( "Expected AbstractElement, got " + str ( type ( child ) ) ) if child . parent == self : child . parent = None self . data . remove ( child ) # delete from index if child . id and self . doc and child . id in self . doc . index : del self . d...
def from_offset ( cls , chunk_type , stream_rdr , offset ) : """Return a _ pHYsChunk instance containing the image resolution extracted from the pHYs chunk in * stream * at * offset * ."""
horz_px_per_unit = stream_rdr . read_long ( offset ) vert_px_per_unit = stream_rdr . read_long ( offset , 4 ) units_specifier = stream_rdr . read_byte ( offset , 8 ) return cls ( chunk_type , horz_px_per_unit , vert_px_per_unit , units_specifier )
def conv_variant ( self , column , name , ** kwargs ) : """Convert variants ."""
return self . convert ( str ( column . type ) , column , name , ** kwargs )
def group_exists ( groupname ) : """Check if a group exists"""
try : grp . getgrnam ( groupname ) group_exists = True except KeyError : group_exists = False return group_exists
def set_format_options ( fmt , format_options ) : """Apply the desired format options to the format description fmt"""
if not format_options : return for opt in format_options : try : key , value = opt . split ( '=' ) except ValueError : raise ValueError ( "Format options are expected to be of the form key=value, not '{}'" . format ( opt ) ) if key not in _VALID_FORMAT_OPTIONS : raise ValueError ...
def deleteInactiveDevicesByQuota ( self , per_jid_max = 15 , global_max = 0 ) : """Delete inactive devices by setting a quota . With per _ jid _ max you can define the amount of inactive devices that are kept for each jid , with global _ max you can define a global maximum for inactive devices . If any of the q...
if per_jid_max < 1 and global_max < 1 : return if per_jid_max < 1 : per_jid_max = None if global_max < 1 : global_max = None bare_jids = yield self . _storage . listJIDs ( ) if not per_jid_max == None : for bare_jid in bare_jids : devices = yield self . __loadInactiveDevices ( bare_jid ) ...
def avail_sizes ( conn = None , call = None ) : '''List available sizes for OpenStack CLI Example . . code - block : : bash salt - cloud - f avail _ sizes myopenstack salt - cloud - - list - sizes myopenstack'''
if call == 'action' : raise SaltCloudSystemExit ( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) if conn is None : conn = get_conn ( ) return conn . list_flavors ( )
def ParseRecord ( self , parser_mediator , key , structure ) : """Parses a structure of tokens derived from a line of a text file . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . key ( str ) : name of the parsed structur...
if key != 'line' : raise errors . ParseError ( 'Unable to parse record, unknown structure: {0:s}' . format ( key ) ) msg_value = structure . get ( 'msg' ) if not msg_value : parser_mediator . ProduceExtractionWarning ( 'missing msg value: {0!s}' . format ( structure ) ) return try : seconds = int ( msg_...
def device_filter ( self ) : """The device filter to use . : rtype : dict"""
if isinstance ( self . _device_filter , str ) : return self . _decode_query ( self . _device_filter ) return self . _device_filter
def main ( requirements_file , skip_requirements_file , pipfile , skip_pipfile ) : # type : ( str , bool , str , bool ) - > None """Update the requirements . txt file and reformat the Pipfile ."""
pipfile_path = path . Path ( pipfile ) pf = load_pipfile ( pipfile_path ) if not skip_requirements_file : requirements_file_path = path . Path ( requirements_file ) update_requirements ( requirements_file_path , pf ) if not skip_pipfile : dump_pipfile ( pipfile_path , pf )
def expand_curlys ( s ) : """Takes string and returns list of options : Example > > > expand _ curlys ( " py { 26 , 27 } " ) [ " py26 " , " py27 " ]"""
from functools import reduce curleys = list ( re . finditer ( r"{[^{}]*}" , s ) ) return reduce ( _replace_curly , reversed ( curleys ) , [ s ] )
def resonator ( freq , bandwidth ) : """Resonator filter with 2 - poles ( conjugated pair ) and no zeros ( constant numerator ) , with exponential approximation for bandwidth calculation . Parameters freq : Resonant frequency in rad / sample ( max gain ) . bandwidth : Bandwidth frequency range in rad / ...
bandwidth = thub ( bandwidth , 1 ) R = exp ( - bandwidth * .5 ) R = thub ( R , 5 ) cost = cos ( freq ) * ( 2 * R ) / ( 1 + R ** 2 ) cost = thub ( cost , 2 ) gain = ( 1 - R ** 2 ) * sqrt ( 1 - cost ** 2 ) denominator = 1 - 2 * R * cost * z ** - 1 + R ** 2 * z ** - 2 return gain / denominator
def create_from_binary ( cls , mft_config , binary_data , entry_number ) : # TODO test carefully how to find the correct index entry , specially with NTFS versions < 3 '''Creates a MFTEntry from a binary stream . It correctly process the binary data extracting the MFTHeader , all the attributes and the slack in...
bin_view = memoryview ( binary_data ) entry = None # test if the entry is empty if bin_view [ 0 : 4 ] != b"\x00\x00\x00\x00" : try : header = MFTHeader . create_from_binary ( mft_config . ignore_signature_check , bin_view [ : MFTHeader . get_representation_size ( ) ] ) except HeaderError as e : ...
def extract_rpm ( archive , compression , cmd , verbosity , interactive , outdir ) : """Extract a RPM archive ."""
# also check cpio cpio = util . find_program ( "cpio" ) if not cpio : raise util . PatoolError ( "cpio(1) is required for rpm2cpio extraction; please install it" ) path = util . shell_quote ( os . path . abspath ( archive ) ) cmdlist = [ util . shell_quote ( cmd ) , path , "|" , util . shell_quote ( cpio ) , '--ext...
def do_make ( self , subcmd , opts , path ) : """$ { cmd _ name } : make a maildir at the specified path . $ { cmd _ usage } If the path is relative then create under MAILDIR else create at the absolute location ."""
# Do we need to make this " . path " if it ' s relative ? d = path if path [ 0 ] == "/" else joinpath ( self . maildir , "." + path ) os . makedirs ( joinpath ( d , "cur" ) ) os . makedirs ( joinpath ( d , "new" ) ) os . makedirs ( joinpath ( d , "tmp" ) ) os . makedirs ( joinpath ( d , "store" ) )
def cjkFragSplit ( frags , maxWidths , calcBounds , encoding = 'utf8' ) : """This attempts to be wordSplit for frags using the dumb algorithm"""
from reportlab . rl_config import _FUZZ U = [ ] # get a list of single glyphs with their widths etc etc for f in frags : text = f . text if not isinstance ( text , unicode ) : text = text . decode ( encoding ) if text : U . extend ( [ cjkU ( t , f , encoding ) for t in text ] ) else : ...
def _get_multiplier ( samples ) : """Get multiplier to get jobs only for samples that have input"""
to_process = 1.0 to_skip = 0 for sample in samples : if dd . get_phenotype ( sample [ 0 ] ) == "chip" : to_process += 1.0 elif dd . get_chip_method ( sample [ 0 ] ) . lower ( ) == "atac" : to_process += 1.0 else : to_skip += 1.0 mult = ( to_process - to_skip ) / len ( samples ) if mu...
def get ( self , url , params = None , ** kwargs ) : """Encapsulte requests . get to use this class instance header"""
return requests . get ( url , params = params , headers = self . add_headers ( ** kwargs ) )
def dKdiag_dX ( self , dL_dKdiag , X , target ) : """Gradient of diagonal of covariance with respect to X ."""
target += 2. * self . mapping . df_dX ( dL_dKdiag [ : , None ] , X ) * self . mapping . f ( X )
def killCells ( self , killCellPercent ) : """kill a fraction of LSTM cells from the network : param killCellPercent : : return :"""
if killCellPercent <= 0 : return inputLayer = self . net [ 'in' ] lstmLayer = self . net [ 'hidden0' ] numLSTMCell = lstmLayer . outdim numDead = round ( killCellPercent * numLSTMCell ) zombiePermutation = numpy . random . permutation ( numLSTMCell ) deadCells = zombiePermutation [ 0 : numDead ] # remove connection...
def home ( self ) : """Homes the robot ."""
self . _log . debug ( "home" ) self . _location_cache = None self . _hw_manager . hardware . home ( )
def cmd ( command , ignore_stderr = False , raise_on_return = False , timeout = None , encoding = "utf-8" ) : """Run a shell command and have it automatically decoded and printed : param command : Command to run as str : param ignore _ stderr : To not print stderr : param raise _ on _ return : Run CompletedPr...
result = run ( command , timeout = timeout , shell = True ) if raise_on_return : result . check_returncode ( ) print ( result . stdout . decode ( encoding ) ) if not ignore_stderr and result . stderr : print ( result . stderr . decode ( encoding ) )
def download ( self , media_id , as_stream = False ) : """Скачивает указанный файл : param media _ id : string : rtype : requests . Response"""
response = self . __app . native_api_call ( 'media' , 'd/' + media_id , { } , self . __options , False , None , as_stream , http_path = "/api/meta/v1/" , http_method = 'GET' ) return response
def _stringify_path ( filepath_or_buffer ) : """Attempt to convert a path - like object to a string . Parameters filepath _ or _ buffer : object to be converted Returns str _ filepath _ or _ buffer : maybe a string version of the object Notes Objects supporting the fspath protocol ( python 3.6 + ) are c...
try : import pathlib _PATHLIB_INSTALLED = True except ImportError : _PATHLIB_INSTALLED = False try : from py . path import local as LocalPath _PY_PATH_INSTALLED = True except ImportError : _PY_PATH_INSTALLED = False if hasattr ( filepath_or_buffer , '__fspath__' ) : return filepath_or_buffer...
def call_rpc_external ( self , address , rpc_id , arg_payload , timeout = 10.0 ) : """Call an RPC from outside of the event loop and block until it finishes . This is the main method by which a caller outside of the EmulationLoop can inject an RPC into the EmulationLoop and wait for it to complete . This meth...
self . verify_calling_thread ( False , "call_rpc_external is for use **outside** of the event loop" ) response = CrossThreadResponse ( ) self . _loop . call_soon_threadsafe ( self . _rpc_queue . put_rpc , address , rpc_id , arg_payload , response ) try : return response . wait ( timeout ) except RPCRuntimeError as ...
def eth_getCode ( self , address , block = BLOCK_TAG_LATEST ) : """https : / / github . com / ethereum / wiki / wiki / JSON - RPC # eth _ getcode : param address : Address of contract : type address : str : param block : Block tag or number ( optional ) : type block : int or BLOCK _ TAGS : return : code ...
block = validate_block ( block ) return ( yield from self . rpc_call ( 'eth_getCode' , [ address , block ] ) )
def reshape ( self , dims ) : """reshape an existing image to the requested dimensions parameters dims : sequence Any sequence convertible to i8"""
adims = numpy . array ( dims , ndmin = 1 , dtype = 'i8' ) self . _FITS . reshape_image ( self . _ext + 1 , adims )
def open ( cls , title , conn = None , google_user = None , google_password = None ) : """Open the spreadsheet named ` ` title ` ` . If no spreadsheet with that name exists , a new one will be created ."""
spreadsheet = cls . by_title ( title , conn = conn , google_user = google_user , google_password = google_password ) if spreadsheet is None : spreadsheet = cls . create ( title , conn = conn , google_user = google_user , google_password = google_password ) return spreadsheet
def read_mutating_webhook_configuration ( self , name , ** kwargs ) : # noqa : E501 """read _ mutating _ webhook _ configuration # noqa : E501 read the specified MutatingWebhookConfiguration # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please p...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . read_mutating_webhook_configuration_with_http_info ( name , ** kwargs ) # noqa : E501 else : ( data ) = self . read_mutating_webhook_configuration_with_http_info ( name , ** kwargs ) # noqa : E501 return data
def download_file_part_run ( download_context ) : """Function run by CreateProjectCommand to create the project . Runs in a background process . : param download _ context : UploadContext : contains data service setup and project name to create ."""
destination_dir , file_url_data_dict , seek_amt , bytes_to_read = download_context . params project_file = ProjectFile ( file_url_data_dict ) local_path = project_file . get_local_path ( destination_dir ) retry_chunk_downloader = RetryChunkDownloader ( project_file , local_path , seek_amt , bytes_to_read , download_con...
def frommatrix ( cls , apart , dpart , init_matrix , ** kwargs ) : """Create an instance of ` Parallel2dGeometry ` using a matrix . This alternative constructor uses a matrix to rotate and translate the default configuration . It is most useful when the transformation to be applied is already given as a matri...
# Get transformation and translation parts from ` init _ matrix ` init_matrix = np . asarray ( init_matrix , dtype = float ) if init_matrix . shape not in ( ( 2 , 2 ) , ( 2 , 3 ) ) : raise ValueError ( '`matrix` must have shape (2, 2) or (2, 3), ' 'got array with shape {}' '' . format ( init_matrix . shape ) ) traf...
def _connect ( self , address ) : """Connect to a device given its uuid"""
latency = 0 conn_interval_min = 6 conn_interval_max = 100 timeout = 1.0 try : # Allow passing either a binary address or a hex string if isinstance ( address , str ) and len ( address ) > 6 : address = address . replace ( ':' , '' ) address = bytes ( bytearray . fromhex ( address ) [ : : - 1 ] ) exc...
def calc_point_distance_vary ( self , chi_coords , point_fupper , mus ) : """Calculate distance between point and the bank allowing the metric to vary based on varying upper frequency cutoff . Slower than calc _ point _ distance , but more reliable when upper frequency cutoff can change a lot . Parameters ...
chi1_bin , chi2_bin = self . find_point_bin ( chi_coords ) min_dist = 1000000000 indexes = None for chi1_bin_offset , chi2_bin_offset in self . bin_loop_order : curr_chi1_bin = chi1_bin + chi1_bin_offset curr_chi2_bin = chi2_bin + chi2_bin_offset # No points = Next iteration curr_bank = self . massbank ...
def put ( self , key , value , minutes ) : """Store an item in the cache for a given number of minutes . : param key : The cache key : type key : str : param value : The cache value : type value : mixed : param minutes : The lifetime in minutes of the cached value : type minutes : int"""
value = self . serialize ( value ) minutes = max ( 1 , minutes ) self . _redis . setex ( self . _prefix + key , minutes * 60 , value )
def convert_pattern_to_pil ( pattern , version = 1 ) : """Convert Pattern to PIL Image ."""
from PIL import Image mode = get_pil_mode ( pattern . image_mode . name , False ) # The order is different here . size = pattern . data . rectangle [ 3 ] , pattern . data . rectangle [ 2 ] channels = [ _create_channel ( size , c . get_data ( version ) , c . pixel_depth ) . convert ( 'L' ) for c in pattern . data . chan...
def stem ( self , text ) : """Stem each word of the Latin text ."""
stemmed_text = '' for word in text . split ( ' ' ) : if word not in self . stops : # remove ' - que ' suffix word , in_que_pass_list = self . _checkremove_que ( word ) if not in_que_pass_list : # remove the simple endings from the target word word , was_stemmed = self . _matchremove_simp...
def get_cities_by_name ( self , name ) : """Get a list of city dictionaries with the given name . City names cannot be used as keys , as they are not unique ."""
if name not in self . cities_by_names : if self . cities_items is None : self . cities_items = list ( self . get_cities ( ) . items ( ) ) self . cities_by_names [ name ] = [ dict ( { gid : city } ) for gid , city in self . cities_items if city [ 'name' ] == name ] return self . cities_by_names [ name ]
def getXML ( self , CorpNum , NTSConfirmNum , UserID = None ) : """전자세금계산서 상세정보 확인 - XML args CorpNum : 팝빌회원 사업자번호 NTSConfirmNum : 국세청 승인번호 UserID : 팝빌회원 아이디 return 전자세금계산서 정보객체 raise PopbillException"""
if NTSConfirmNum == None or len ( NTSConfirmNum ) != 24 : raise PopbillException ( - 99999999 , "국세청승인번호(NTSConfirmNum)가 올바르지 않습니다." ) return self . _httpget ( '/HomeTax/Taxinvoice/' + NTSConfirmNum + '?T=xml' , CorpNum , UserID )
def left_hash ( msg , func = "HS256" ) : """Calculate left hash as described in https : / / openid . net / specs / openid - connect - core - 1_0 . html # CodeIDToken for at _ hash and in for c _ hash : param msg : The message over which the hash should be calculated : param func : Which hash function that...
if func == 'HS256' : return as_unicode ( b64e ( sha256_digest ( msg ) [ : 16 ] ) ) elif func == 'HS384' : return as_unicode ( b64e ( sha384_digest ( msg ) [ : 24 ] ) ) elif func == 'HS512' : return as_unicode ( b64e ( sha512_digest ( msg ) [ : 32 ] ) )
def resource_permissions_for_users ( models_proxy , perm_names , resource_ids = None , user_ids = None , group_ids = None , resource_types = None , limit_group_permissions = False , skip_user_perms = False , skip_group_perms = False , db_session = None , ) : """Returns permission tuples that match one of passed per...
db_session = get_db_session ( db_session ) # fetch groups and their permissions ( possibly with users belonging # to group if needed ) query = db_session . query ( models_proxy . GroupResourcePermission . perm_name , models_proxy . User , models_proxy . Group , sa . literal ( "group" ) . label ( "type" ) , models_proxy...
def setup ( self ) : """instantiates all report formats that have been added to this reporter , and calls their setup methods ."""
if self . _formats : # setup has been run already . return basedir = self . basedir options = self . options crumbs = self . get_relative_breadcrumbs ( ) fmts = list ( ) for fmt_class in self . formats : fmt = fmt_class ( basedir , options , crumbs ) fmt . setup ( ) fmts . append ( fmt ) self . _formats...
def _EncodeString ( self , string ) : """Encodes the string . Args : string ( str ) : string to encode . Returns : bytes : encoded string ."""
try : # Note that encode ( ) will first convert string into a Unicode string # if necessary . encoded_string = string . encode ( self . _encoding , errors = self . _errors ) except UnicodeEncodeError : if self . _errors == 'strict' : logging . error ( 'Unable to properly write output due to encoding err...
def _gettags ( self , codes = None , lock = None ) : """Return list of ( code , TiffTag ) ."""
tags = [ ] for tag in self . tags . values ( ) : code = tag . code if not codes or code in codes : tags . append ( ( code , tag ) ) return tags
def auth_grant ( self , client , role = None , mode = None ) : """Used to get a grant token . Grant tokens expire after 5 minutes for role " grant _ verify " and 10 minutes for the " grant _ enroll " and " grant _ enroll _ verify " roles . Grant tokens can be used to start enrollments and verifications . Uses P...
body = { "name" : client } if role : body [ "role" ] = role if mode : body [ "mode" ] = mode response = self . _post ( url . auth_grant , body = body ) self . _check_response ( response , 200 ) return self . _create_response ( response )
def get ( self , key , default = None , with_age = False ) : "Return the value for key if key is in the dictionary , else default ."
try : return self . __getitem__ ( key , with_age ) except KeyError : if with_age : return default , None else : return default