signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def auth_user_oauth ( self , userinfo ) : """OAuth user Authentication : userinfo : dict with user information the keys have the same name as User model columns ."""
if "username" in userinfo : user = self . find_user ( username = userinfo [ "username" ] ) elif "email" in userinfo : user = self . find_user ( email = userinfo [ "email" ] ) else : log . error ( "User info does not have username or email {0}" . format ( userinfo ) ) return None # User is disabled if us...
def heightmap_get_interpolated_value ( hm : np . ndarray , x : float , y : float ) -> float : """Return the interpolated height at non integer coordinates . Args : hm ( numpy . ndarray ) : A numpy . ndarray formatted for heightmap functions . x ( float ) : A floating point x coordinate . y ( float ) : A flo...
return float ( lib . TCOD_heightmap_get_interpolated_value ( _heightmap_cdata ( hm ) , x , y ) )
def _dep_type ( self , target , dep , declared_deps , eligible_unused_deps , is_used ) : """Returns a tuple of a ' declared ' / ' undeclared ' boolean , and ' used ' / ' unused ' boolean . These values are related , because some declared deps are not eligible to be considered unused . : param target : The sourc...
if target == dep : return True , True return ( dep in declared_deps ) , ( is_used or dep not in eligible_unused_deps )
def final_paragraph ( metadata ) : """Describes dicom - to - nifti conversion process and methods generation . Parameters metadata : : obj : ` dict ` The metadata for the scan . Returns desc : : obj : ` str ` Output string with scanner information ."""
if 'ConversionSoftware' in metadata . keys ( ) : soft = metadata [ 'ConversionSoftware' ] vers = metadata [ 'ConversionSoftwareVersion' ] software_str = ' using {soft} ({conv_vers})' . format ( soft = soft , conv_vers = vers ) else : software_str = '' desc = ''' Dicoms were converted to NIfTI...
def create_paramnames_file ( self ) : """The param _ names file lists every parameter ' s analysis _ path and Latex tag , and is used for * GetDist * visualization . The parameter names are determined from the class instance names of the model _ mapper . Latex tags are properties of each model class ."""
paramnames_names = self . variable . param_names paramnames_labels = self . param_labels with open ( self . file_param_names , 'w' ) as paramnames : for i in range ( self . variable . prior_count ) : line = paramnames_names [ i ] line += ' ' * ( 70 - len ( line ) ) + paramnames_labels [ i ] ...
def _call_custom_creator ( self , config ) : """Call a custom driver creator . : param config : The driver configuration : type config : dict : rtype : Repository"""
creator = self . _custom_creators [ config [ 'driver' ] ] ( config ) if isinstance ( creator , Store ) : creator = self . repository ( creator ) if not isinstance ( creator , Repository ) : raise RuntimeError ( 'Custom creator should return a Repository instance.' ) return creator
def get_light_by_name ( self , name ) : """Retrieves a light object by its name : param name : The name of the light to return : return : A light object"""
return next ( ( light for light in self . lights if light . name . lower ( ) == name . lower ( ) ) , None )
def list ( self ) : """Lists all sessions in the store . . . versionadded : : 0.6"""
before , after = self . filename_template . split ( '%s' , 1 ) filename_re = re . compile ( r'%s(.{5,})%s$' % ( re . escape ( before ) , re . escape ( after ) ) ) result = [ ] for filename in os . listdir ( self . path ) : # : this is a session that is still being saved . if filename . endswith ( _fs_transaction_su...
def until ( timeout = 10 , step = 0.5 , action = None , silent = False ) : """Yield until timeout"""
yield started = time . time ( ) while True : if action and not silent : log . info ( action ) if time . time ( ) - started > timeout : if action and not silent : log . error ( "Timedout %s" , action ) return else : time . sleep ( step ) yield
def macro_state ( self , micro_state ) : """Translate a micro state to a macro state Args : micro _ state ( tuple [ int ] ) : The state of the micro nodes in this coarse - graining . Returns : tuple [ int ] : The state of the macro system , translated as specified by this coarse - graining . Example :...
assert len ( micro_state ) == len ( self . micro_indices ) # TODO : only reindex if this coarse grain is not already from 0 . . n ? # make _ mapping calls this in a tight loop so it might be more efficient # to reindex conditionally . reindexed = self . reindex ( ) micro_state = np . array ( micro_state ) return tuple ...
def write ( self , filename , entities , sortkey = None , columns = None ) : """Write entities out to filename in csv format . Note : this doesn ' t write directly into a Zip archive , because this behavior is difficult to achieve with Zip archives . Use make _ zip ( ) to create a new GTFS Zip archive ."""
if os . path . exists ( filename ) : raise IOError ( 'File exists: %s' % filename ) # Make sure we have all the entities loaded . if sortkey : entities = sorted ( entities , key = lambda x : x [ sortkey ] ) if not columns : columns = set ( ) for entity in entities : columns |= set ( entity . key...
def deserialize ( self , obj ) : """Deserialize an object from the front - end ."""
if obj [ 'immutable' ] : return obj [ 'value' ] else : guid = obj [ 'value' ] if not guid in object_registry : instance = JSObject ( self , guid ) object_registry [ guid ] = instance return object_registry [ guid ]
def track_from_filename ( filename , filetype = None , timeout = DEFAULT_ASYNC_TIMEOUT , force_upload = False ) : """Create a track object from a filename . NOTE : Does not create the detailed analysis for the Track . Call Track . get _ analysis ( ) for that . Args : filename : A string containing the path ...
filetype = filetype or filename . split ( '.' ) [ - 1 ] file_object = open ( filename , 'rb' ) result = track_from_file ( file_object , filetype , timeout , force_upload ) file_object . close ( ) return result
def grant_access ( self , agreement_id , did , grantee_address , account ) : """Grant access condition . : param agreement _ id : id of the agreement , hex str : param did : DID , str : param grantee _ address : Address , hex str : param account : Account : return :"""
return self . _keeper . access_secret_store_condition . fulfill ( agreement_id , add_0x_prefix ( did_to_id ( did ) ) , grantee_address , account )
def own_time ( self ) : """The exclusive execution time ."""
sub_time = sum ( stats . deep_time for stats in self ) return max ( 0. , self . deep_time - sub_time )
def get_configured_provider ( ) : '''Return the first configured instance .'''
return config . is_provider_configured ( opts = __opts__ , provider = __active_provider_name__ or __virtualname__ , aliases = __virtual_aliases__ , required_keys = ( 'personal_access_token' , ) )
def geojson_to_wkt ( geojson_obj , feature_number = 0 , decimals = 4 ) : """Convert a GeoJSON object to Well - Known Text . Intended for use with OpenSearch queries . In case of FeatureCollection , only one of the features is used ( the first by default ) . 3D points are converted to 2D . Parameters geojson...
if 'coordinates' in geojson_obj : geometry = geojson_obj elif 'geometry' in geojson_obj : geometry = geojson_obj [ 'geometry' ] else : geometry = geojson_obj [ 'features' ] [ feature_number ] [ 'geometry' ] def ensure_2d ( geometry ) : if isinstance ( geometry [ 0 ] , ( list , tuple ) ) : return...
def _col_widths2xls ( self , worksheets ) : """Writes col _ widths to xls file Format : < col > \t < tab > \t < value > \n"""
xls_max_cols , xls_max_tabs = self . xls_max_cols , self . xls_max_tabs dict_grid = self . code_array . dict_grid for col , tab in dict_grid . col_widths : if col < xls_max_cols and tab < xls_max_tabs : pys_width = dict_grid . col_widths [ ( col , tab ) ] xls_width = self . pys_width2xls_width ( pys...
def set_lan_port ( self , port_id , mac = None ) : """Set LAN port information to configuration . : param port _ id : Physical port ID . : param mac : virtual MAC address if virtualization is necessary ."""
port_handler = _parse_physical_port_id ( port_id ) port = self . _find_port ( port_handler ) if port : port_handler . set_lan_port ( port , mac ) else : self . _add_port ( port_handler , port_handler . create_lan_port ( mac ) )
def t_surf_parameter ( self , num_frame , xax ) : """Surface parameter evolution as a function of time or model . Parameters num _ frame : integer Number of frame to plot this plot into . xax : string Either model or time to indicate what is to be used on the x - axis"""
pyl . figure ( num_frame ) if xax == 'time' : xaxisarray = self . get ( 'star_age' ) elif xax == 'model' : xaxisarray = self . get ( 'model_number' ) else : print ( 'kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"' ) logL = self . get ( 'log_L' ) logTeff = self . get ( 'l...
def find_window_classes ( ) -> List [ str ] : """Find available window packages Returns : A list of avaialble window packages"""
return [ path . parts [ - 1 ] for path in Path ( __file__ ) . parent . iterdir ( ) if path . is_dir ( ) and not path . parts [ - 1 ] . startswith ( '__' ) ]
async def CreateVolumeAttachmentPlans ( self , volume_plans ) : '''volume _ plans : typing . Sequence [ ~ VolumeAttachmentPlan ] Returns - > typing . Sequence [ ~ ErrorResult ]'''
# map input types to rpc msg _params = dict ( ) msg = dict ( type = 'StorageProvisioner' , request = 'CreateVolumeAttachmentPlans' , version = 4 , params = _params ) _params [ 'volume-plans' ] = volume_plans reply = await self . rpc ( msg ) return reply
def is_driver ( self ) : """Check whether the file is a Windows driver . This will return true only if there are reliable indicators of the image being a driver ."""
# Checking that the ImageBase field of the OptionalHeader is above or # equal to 0x800000 ( that is , whether it lies in the upper 2GB of # the address space , normally belonging to the kernel ) is not a # reliable enough indicator . For instance , PEs that play the invalid # ImageBase trick to get relocated could be i...
def causally_significant_nodes ( cm ) : """Return indices of nodes that have both inputs and outputs ."""
inputs = cm . sum ( 0 ) outputs = cm . sum ( 1 ) nodes_with_inputs_and_outputs = np . logical_and ( inputs > 0 , outputs > 0 ) return tuple ( np . where ( nodes_with_inputs_and_outputs ) [ 0 ] )
def decode_from_dataset ( estimator , problem_name , hparams , decode_hp , decode_to_file = None , dataset_split = None , checkpoint_path = None ) : """Perform decoding from dataset ."""
tf . logging . info ( "Performing local inference from dataset for %s." , str ( problem_name ) ) # We assume that worker _ id corresponds to shard number . shard = decode_hp . shard_id if decode_hp . shards > 1 else None # Setup output directory for any artifacts that may be written out . output_dir = os . path . join ...
def p_align ( p ) : """asm : ALIGN expr | ALIGN pexpr"""
align = p [ 2 ] . eval ( ) if align < 2 : error ( p . lineno ( 1 ) , "ALIGN value must be greater than 1" ) return MEMORY . set_org ( MEMORY . org + ( align - MEMORY . org % align ) % align , p . lineno ( 1 ) )
def convert_to_rgb ( img ) : """Convert an image to RGB if it isn ' t already RGB or grayscale"""
if img . mode == 'CMYK' and HAS_PROFILE_TO_PROFILE : profile_dir = os . path . join ( os . path . dirname ( __file__ ) , 'profiles' ) input_profile = os . path . join ( profile_dir , "USWebUncoated.icc" ) output_profile = os . path . join ( profile_dir , "sRGB_v4_ICC_preference.icc" ) return profileToPr...
def chconfig ( cmd , * args , ** kwargs ) : '''This function is called by the : mod : ` salt . modules . chassis . cmd < salt . modules . chassis . cmd > ` shim . It then calls whatever is passed in ` ` cmd ` ` inside the : mod : ` salt . modules . dracr < salt . modules . dracr > ` module . : param cmd : T...
# Strip the _ _ pub _ keys . . . is there a better way to do this ? for k in list ( kwargs ) : if k . startswith ( '__pub_' ) : kwargs . pop ( k ) # Catch password reset if 'dracr.' + cmd not in __salt__ : ret = { 'retcode' : - 1 , 'message' : 'dracr.' + cmd + ' is not available' } else : ret = __sa...
def get_or_create ( self , log_name , bucket_size ) : """Gets or creates a log . : rtype : Timebucketedlog"""
try : return self [ log_name ] except RepositoryKeyError : return start_new_timebucketedlog ( log_name , bucket_size = bucket_size )
def assert_text_visible ( self , text , selector = "html" , by = By . CSS_SELECTOR , timeout = settings . SMALL_TIMEOUT ) : """Same as assert _ text ( )"""
if self . timeout_multiplier and timeout == settings . SMALL_TIMEOUT : timeout = self . __get_new_timeout ( timeout ) return self . assert_text ( text , selector , by = by , timeout = timeout )
def child_element ( self , by = By . ID , value = None , el_class = None ) : """Doesn ' t rise NoSuchElementException in case if there are no element with the selector . In this case ` ` exists ( ) ` ` and ` ` is _ displayed ( ) ` ` methods of the element will return * False * . Attempt to call any other method...
el , selector = define_selector ( by , value , el_class ) return self . _init_element ( el ( selector ) )
def get_assessment_offered_query_session ( self ) : """Gets the ` ` OsidSession ` ` associated with the assessment offered query service . return : ( osid . assessment . AssessmentOfferedQuerySession ) - an ` ` AssessmentOfferedQuerySession ` ` raise : OperationFailed - unable to complete request raise : Un...
if not self . supports_assessment_offered_query ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . AssessmentOfferedQuerySession ( runtime = self . _runtime )
def acquire_hosting_device_slots ( self , context , hosting_device , resource , resource_type , resource_service , num , exclusive = False ) : """Assign < num > slots in < hosting _ device > to logical < resource > . If exclusive is True the hosting device is bound to the resource ' s tenant . Otherwise it is n...
bound = hosting_device [ 'tenant_bound' ] if ( ( bound is not None and bound != resource [ 'tenant_id' ] ) or ( exclusive and not self . _exclusively_used ( context , hosting_device , resource [ 'tenant_id' ] ) ) ) : LOG . debug ( 'Rejecting allocation of %(num)d slots in tenant %(bound)s ' 'hosting device %(device...
def get_formatter ( self , handler ) : """Return formatters according to handler . All handlers are the same format , except syslog . We omit time when syslogging ."""
if isinstance ( handler , logging . handlers . SysLogHandler ) : formatter = '[%(levelname)-9s]' else : formatter = '[%(asctime)s] [%(levelname)-9s]' for p in self . prefix : formatter += ' [%s]' % ( p ) formatter = formatter + ' %(message)s' return logging . Formatter ( formatter )
def set_password ( self , password = None ) : """This method is used to set the password . password must be a string ."""
if password is None or type ( password ) is not str : raise KPError ( "Need a new image number" ) else : self . password = password self . last_mod = datetime . now ( ) . replace ( microsecond = 0 ) return True
def morphAveragePitch ( fromDataList , toDataList ) : '''Adjusts the values in fromPitchList to have the same average as toPitchList Because other manipulations can alter the average pitch , morphing the pitch is the last pitch manipulation that should be done After the morphing , the code removes any values ...
timeList , fromPitchList = zip ( * fromDataList ) toPitchList = [ pitchVal for _ , pitchVal in toDataList ] # Zero pitch values aren ' t meaningful , so filter them out if they are # in the dataset fromListNoZeroes = [ val for val in fromPitchList if val > 0 ] fromAverage = sum ( fromListNoZeroes ) / float ( len ( from...
def set_payg_billing ( self , currency , can_purchase_credits , client_pays , markup_percentage , markup_on_delivery = 0 , markup_per_recipient = 0 , markup_on_design_spam_test = 0 ) : """Sets the PAYG billing settings for this client ."""
body = { "Currency" : currency , "CanPurchaseCredits" : can_purchase_credits , "ClientPays" : client_pays , "MarkupPercentage" : markup_percentage , "MarkupOnDelivery" : markup_on_delivery , "MarkupPerRecipient" : markup_per_recipient , "MarkupOnDesignSpamTest" : markup_on_design_spam_test } response = self . _put ( se...
def _start_data_json ( self ) -> str : """Output json with start data to write for external revocation registry builder process pickup . : return : logging and wallet init data json"""
rv = { 'logging' : { 'paths' : [ ] } , 'wallet' : { } } logger = LOGGER while not logger . level : logger = logger . parent if logger is None : break rv [ 'logging' ] [ 'level' ] = logger . level logger = LOGGER log_paths = [ realpath ( h . baseFilename ) for h in logger . handlers if hasattr ( h , 'bas...
def delete ( self , collector_id = None ) : """Delete a collector from inventory . Args : collector _ id ( int ) : id of collector ( optional )"""
cid = self . collector_id if collector_id : cid = collector_id # param to delete id url = '{0}/{1}' . format ( self . url , cid ) request = requests . delete ( url , auth = self . auth ) try : # unable to delete collector response = request . json ( ) except ValueError : # returns when collector is deleted # ap...
def _approximate_unkown_bond_lengths ( self ) : """Completes the bond length database with approximations based on VDW radii"""
dataset = self . lengths [ BOND_SINGLE ] for n1 in periodic . iter_numbers ( ) : for n2 in periodic . iter_numbers ( ) : if n1 <= n2 : pair = frozenset ( [ n1 , n2 ] ) atom1 = periodic [ n1 ] atom2 = periodic [ n2 ] # if ( pair not in dataset ) and hasattr ( a...
def md5 ( self ) : """Return an MD5 hash of the current array . Returns md5 : str , hexadecimal MD5 of the array"""
if self . _modified_m or not hasattr ( self , '_hashed_md5' ) : if self . flags [ 'C_CONTIGUOUS' ] : hasher = hashlib . md5 ( self ) self . _hashed_md5 = hasher . hexdigest ( ) else : # the case where we have sliced our nice # contiguous array into a non - contiguous block # for example ...
def _psi ( self , m ) : """\psi(m) = -\int_m^\infty d m^2 \r ho ( m ^ 2)"""
if self . twominusalpha == 0. : return - 2. * self . a ** 2 * ( self . a / m ) ** self . betaminusalpha / self . betaminusalpha * special . hyp2f1 ( self . betaminusalpha , self . betaminusalpha , self . betaminusalpha + 1 , - self . a / m ) else : return - 2. * self . a ** 2 * ( self . psi_inf - ( m / self . a...
def transform_non_affine ( self , x , mask_out_of_range = True ) : """Transform a Nx1 numpy array . Parameters x : array Data to be transformed . mask _ out _ of _ range : bool , optional Whether to mask input values out of range . Return array or masked array Transformed data ."""
# Mask out - of - range values if mask_out_of_range : x_masked = np . ma . masked_where ( ( x < self . _xmin ) | ( x > self . _xmax ) , x ) else : x_masked = x # Calculate s and return return np . interp ( x_masked , self . _x_range , self . _s_range )
def run_server ( self ) : """Runs a server to handle queries to the index without creating the javascript table ."""
app = build_app ( ) run ( app , host = 'localhost' , port = self . port )
def add_months ( start , months ) : """Returns the date that is ` months ` months after ` start ` > > > df = spark . createDataFrame ( [ ( ' 2015-04-08 ' , ) ] , [ ' dt ' ] ) > > > df . select ( add _ months ( df . dt , 1 ) . alias ( ' next _ month ' ) ) . collect ( ) [ Row ( next _ month = datetime . date ( ...
sc = SparkContext . _active_spark_context return Column ( sc . _jvm . functions . add_months ( _to_java_column ( start ) , months ) )
def geocode ( self , query , exactly_one = True , timeout = DEFAULT_SENTINEL , proximity = None , country = None , bbox = None , ) : """Return a location point by address : param str query : The address or query you wish to geocode . : param bool exactly _ one : Return one result or a list of results , if ava...
params = { } params [ 'access_token' ] = self . api_key query = self . format_string % query if bbox : params [ 'bbox' ] = self . _format_bounding_box ( bbox , "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s" ) if not country : country = [ ] if isinstance ( country , string_compare ) : country = [ country ] if country...
def y_tic_points ( self , interval ) : "Return the list of Y values for which tick marks and grid lines are drawn ."
if type ( interval ) == FunctionType : return interval ( * self . y_range ) return self . y_coord . get_tics ( self . y_range [ 0 ] , self . y_range [ 1 ] , interval )
def apply_actions ( self , actions ) : """Applies a list of actions to the Vasp Input Set and rewrites modified files . Args : actions [ dict ] : A list of actions of the form { ' file ' : filename , ' action ' : moddermodification } or { ' dict ' : vaspinput _ key , ' action ' : moddermodification }"""
modified = [ ] for a in actions : if "dict" in a : k = a [ "dict" ] modified . append ( k ) self . vi [ k ] = self . modify_object ( a [ "action" ] , self . vi [ k ] ) elif "file" in a : self . modify ( a [ "action" ] , a [ "file" ] ) else : raise ValueError ( "Unreco...
def prompt_input ( self , prompt , key = False ) : """Display a text prompt at the bottom of the screen . Params : prompt ( string ) : Text prompt that will be displayed key ( bool ) : If true , grab a single keystroke instead of a full string . This can be faster than pressing enter for single key prompt...
n_rows , n_cols = self . stdscr . getmaxyx ( ) v_offset , h_offset = self . stdscr . getbegyx ( ) ch , attr = str ( ' ' ) , self . attr ( 'Prompt' ) prompt = self . clean ( prompt , n_cols - 1 ) # Create a new window to draw the text at the bottom of the screen , # so we can erase it when we ' re done . s_row = v_offse...
def find_kihs ( assembly , hole_size = 4 , cutoff = 7.0 ) : """KnobIntoHoles between residues of different chains in assembly . Notes A KnobIntoHole is a found when the side - chain centre of a Residue a chain is close than ( cutoff ) Angstroms from at least ( hole _ size ) side - chain centres of Residues of...
pseudo_group = side_chain_centres ( assembly = assembly , masses = False ) pairs = itertools . permutations ( pseudo_group , 2 ) kihs = [ ] for pp_1 , pp_2 in pairs : for r in pp_1 : close_atoms = pp_2 . is_within ( cutoff , r ) # kihs occur between residue and ( hole _ size ) closest side - chains ...
def rank_selection ( random , population , args ) : """Return a rank - based sampling of individuals from the population . This function behaves similarly to fitness proportionate selection , except that it uses the individual ' s rank in the population , rather than its raw fitness value , to determine its p...
num_selected = args . setdefault ( 'num_selected' , 1 ) # Set up the roulette wheel len_pop = len ( population ) population . sort ( ) psum = list ( range ( len_pop ) ) den = ( len_pop * ( len_pop + 1 ) ) / 2.0 for i in range ( len_pop ) : psum [ i ] = ( i + 1 ) / den for i in range ( 1 , len_pop ) : psum [ i ]...
def cmd_cuts ( self , lo = None , hi = None , ch = None ) : """cuts lo = val hi = val ch = chname If neither ` lo ` nor ` hi ` is provided , returns the current cut levels . Otherwise sets the corresponding cut level for the given channel . If ` ch ` is omitted , assumes the current channel ."""
viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return loval , hival = viewer . get_cut_levels ( ) if ( lo is None ) and ( hi is None ) : self . log ( "lo=%f hi=%f" % ( loval , hival ) ) else : if lo is not None : loval = lo if hi is not None...
def Write ( self , string ) : """Writes a string to the output . Args : string ( str ) : output ."""
try : # Note that encode ( ) will first convert string into a Unicode string # if necessary . encoded_string = codecs . encode ( string , self . _encoding , self . _errors ) except UnicodeEncodeError : if self . _errors == 'strict' : logger . error ( 'Unable to properly write output due to encoding erro...
def save_configuration_dict ( h5_file , configuation_name , configuration , ** kwargs ) : '''Stores any configuration dictionary to HDF5 file . Parameters h5 _ file : string , file Filename of the HDF5 configuration file or file object . configuation _ name : str Configuration name . Will be used for tabl...
def save_conf ( ) : try : h5_file . remove_node ( h5_file . root . configuration , name = configuation_name ) except tb . NodeError : pass try : configuration_group = h5_file . create_group ( h5_file . root , "configuration" ) except tb . NodeError : configuration_group =...
def set_lines ( lines , target_level , indent_string = " " , indent_empty_lines = False ) : """Sets indentation for the given set of : lines : ."""
first_non_empty_line_index = _get_first_non_empty_line_index ( lines ) first_line_original_level = get_line_level ( lines [ first_non_empty_line_index ] , indent_string ) for i in range ( first_non_empty_line_index , len ( lines ) ) : if not indent_empty_lines and lines [ i ] == "" : continue line_i_uni...
def _error_code_to_str ( mod , type_ , code ) : """This method is registered as ofp _ error _ code _ to _ str ( type _ , code ) method into ryu . ofproto . ofproto _ v1 _ * modules . And this method returns the error code as a string value for given ' type ' and ' code ' defined in ofp _ error _ msg structure...
( _ , c_name ) = _get_error_names ( mod , type_ , code ) return '%s(%d)' % ( c_name , code )
def __findRange ( self , excelLib , start , end ) : '''return low and high as excel range'''
inc = 1 low = 0 high = 0 dates = excelLib . readCol ( 0 , 1 ) for index , date in enumerate ( dates ) : if int ( start ) <= int ( date ) : low = index + inc break if low : for index , date in reversed ( list ( enumerate ( dates ) ) ) : if int ( date ) <= int ( end ) : high = ...
def cyvcf_remove_filter ( rec , name ) : """Remove filter with the given name from a cyvcf2 record"""
if rec . FILTER : filters = rec . FILTER . split ( ";" ) else : filters = [ ] new_filters = [ x for x in filters if not str ( x ) == name ] if len ( new_filters ) == 0 : new_filters = [ "PASS" ] rec . FILTER = new_filters return rec
def normalize_constraints ( constraints , flds ) : """This method renders local constraints such that return value is : * a list , not None * a list of dicts * a list of non - optional constraints or optional with defined field . . note : : We use a new variable ' local _ constraints ' because the constrain...
local_constraints = constraints or [ ] local_constraints = [ dict ( ** c ) for c in local_constraints ] local_constraints = [ c for c in local_constraints if c . get ( 'field' ) in flds or not c . get ( 'optional' ) ] return local_constraints
def destroyTempFiles ( self ) : """Destroys all temp temp file hierarchy , getting rid of all files ."""
os . system ( "rm -rf %s" % self . rootDir ) logger . debug ( "Temp files created: %s, temp files actively destroyed: %s" % ( self . tempFilesCreated , self . tempFilesDestroyed ) )
def enable_pretty_logging ( options : Any = None , logger : logging . Logger = None ) -> None : """Turns on formatted logging output as configured . This is called automatically by ` tornado . options . parse _ command _ line ` and ` tornado . options . parse _ config _ file ` ."""
if options is None : import tornado . options options = tornado . options . options if options . logging is None or options . logging . lower ( ) == "none" : return if logger is None : logger = logging . getLogger ( ) logger . setLevel ( getattr ( logging , options . logging . upper ( ) ) ) if options ....
def create ( cls , description = "" , message = "" ) : """: param description : : type description : str : param message : : type message : str"""
instance = cls ( ) instance . revision_id = make_hash_id ( ) instance . release_date = datetime . datetime . now ( ) if len ( description ) > 0 : instance . description = description if len ( message ) > 0 : instance . message = message return instance
def reset ( self ) -> None : """Reset the timers ."""
self . _overallstart = get_now_utc_pendulum ( ) self . _starttimes . clear ( ) self . _totaldurations . clear ( ) self . _count . clear ( ) self . _stack . clear ( )
def from_args ( cls , args ) : """Initialize a WorkflowConfigParser instance using the command line values parsed in args . args must contain the values provided by the workflow _ command _ line _ group ( ) function . If you are not using the standard workflow command line interface , you should probably init...
# Identify the config files confFiles = [ ] # files and URLs to resolve if args . config_files : confFiles += args . config_files # Identify the deletes confDeletes = args . config_delete or [ ] # and parse them parsedDeletes = [ ] for delete in confDeletes : splitDelete = delete . split ( ":" ) if len ( sp...
def compute_metrics ( self ) : """Computes metrics for each point Returns : : obj : ` Segment ` : self"""
for prev , point in pairwise ( self . points ) : point . compute_metrics ( prev ) return self
def encode_collection ( collection , encoding = 'utf-8' ) : """Encodes all the string keys and values in a collection with specified encoding"""
if isinstance ( collection , dict ) : return dict ( ( encode_collection ( key ) , encode_collection ( value ) ) for key , value in collection . iteritems ( ) ) elif isinstance ( collection , list ) : return [ encode_collection ( element ) for element in input ] elif isinstance ( collection , unicode ) : ret...
def reverse_transform ( self , col ) : """Converts data back into original format . Args : col ( pandas . DataFrame ) : Data to transform . Returns : pandas . DataFrame"""
if isinstance ( col , pd . Series ) : col = col . to_frame ( ) output = pd . DataFrame ( index = col . index ) output [ self . col_name ] = col . apply ( self . safe_date , axis = 1 ) return output
def is_treshold_reached ( self , scraped_request ) : """Check if similar requests to the given requests have already been crawled X times . Where X is the minimum treshold amount from the options . Args : scraped _ request ( : class : ` nyawc . http . Request ` ) : The request that possibly reached the minimu...
for route in self . __routing_options . routes : if re . compile ( route ) . match ( scraped_request . url ) : count_key = str ( route ) + scraped_request . method if count_key in self . __routing_count . keys ( ) : return self . __routing_count [ count_key ] >= self . __routing_options ...
def load_dataset_items ( test_file , predict_file_lst , nonfeature_file ) : """This function is used to read 3 kinds of data into list , 3 kinds of data are stored in files given by parameter : param test _ file : path string , the testing set used for SVm rank : param predict _ file _ lst : filename lst , all ...
print 'Reading baseline feature & bleu...' with open ( test_file , 'r' ) as reader : for line in reader : items = line . split ( ' ' ) label = float ( items [ 0 ] ) id_list . append ( items [ 1 ] ) bleu_list . append ( label ) word_count_list . append ( float ( items [ 2 ] . ...
def generate_list_table_result ( lexicon_logger , output = None , without_header = None ) : """Convert returned data from list actions into a nice table for command line usage"""
if not isinstance ( output , list ) : lexicon_logger . debug ( 'Command output is not a list, and then cannot ' 'be printed with --quiet parameter not enabled.' ) return None array = [ [ row . get ( 'id' , '' ) , row . get ( 'type' , '' ) , row . get ( 'name' , '' ) , row . get ( 'content' , '' ) , row . get ( ...
def locally_linear_embedding ( geom , n_components , reg = 1e-3 , eigen_solver = 'auto' , random_state = None , solver_kwds = None ) : """Perform a Locally Linear Embedding analysis on the data . Parameters geom : a Geometry object from megaman . geometry . geometry n _ components : integer number of coordi...
if geom . X is None : raise ValueError ( "Must pass data matrix X to Geometry" ) if geom . adjacency_matrix is None : geom . compute_adjacency_matrix ( ) W = barycenter_graph ( geom . adjacency_matrix , geom . X , reg = reg ) # we ' ll compute M = ( I - W ) ' ( I - W ) # depending on the solver , we ' ll do thi...
def is_class_or_module ( self ) : """Determines if the object is a class or a module : return : True if the object is a class or a module , False otherwise . : rtype : bool"""
if isinstance ( self . obj , ObjectDouble ) : return self . obj . is_class return isclass ( self . doubled_obj ) or ismodule ( self . doubled_obj )
def _registerPickleType ( name , typedef ) : '''Register a type with the specified name . After registration , NamedStruct with this type ( and any sub - types ) can be successfully pickled and transfered .'''
NamedStruct . _pickleNames [ typedef ] = name NamedStruct . _pickleTypes [ name ] = typedef
async def gather ( self , * cmds : str ) -> Tuple [ int ] : """Coroutine to spawn subprocesses and block until completion . Note : The same ` max _ concurrency ` restriction that applies to ` spawn ` also applies here . Returns : The exit codes of the spawned subprocesses , in the order they were passed...
subprocs = self . spawn ( * cmds ) subproc_wait_coros = [ subproc . wait_done ( ) for subproc in subprocs ] return await asyncio . gather ( * subproc_wait_coros )
def send_sticker ( self , chat_id = None , sticker = None , reply_to_message_id = None , reply_markup = None ) : """Use this method to send . webp stickers . On success , the sent Message is returned ."""
payload = dict ( chat_id = chat_id , reply_to_message_id = reply_to_message_id , reply_markup = reply_markup ) files = dict ( sticker = open ( sticker , 'rb' ) ) return Message . from_api ( api , ** self . _post ( 'sendSticker' , payload , files ) )
def destroyCommit ( self , varBind , ** context ) : """Destroy Managed Object Instance . Implements the second of the multi - step workflow similar to the SNMP SET command processing ( : RFC : ` 1905 # section - 4.2.5 ` ) . The goal of the second phase is to actually remove requested Managed Object Instance...
name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: destroyCommit(%s, %r)' % ( self , name , val ) ) ) instances = context [ 'instances' ] . setdefault ( self . name , { self . ST_CREATE : { } , self . ST_DESTROY : { } } ) idx = context [ 'idx' ] # NOTE : multiple names are possible in a ...
def wait_for_provision_state ( baremetal_client , node_uuid , provision_state , loops = 10 , sleep = 1 ) : """Wait for a given Provisioning state in Ironic Discoverd Updating the provisioning state is an async operation , we need to wait for it to be completed . : param baremetal _ client : Instance of Ironic...
for _ in range ( 0 , loops ) : node = baremetal_client . node . get ( node_uuid ) if node is None : # The node can ' t be found in ironic , so we don ' t need to wait for # the provision state return True if node . provision_state == provision_state : return True time . sleep ( sleep...
def which ( program ) : """A python implementation of which . https : / / stackoverflow . com / a / 2969007"""
path_ext = [ "" ] ext_list = None if sys . platform == "win32" : ext_list = [ ext . lower ( ) for ext in os . environ [ "PATHEXT" ] . split ( ";" ) ] def is_exe ( fpath ) : exe = os . path . isfile ( fpath ) and os . access ( fpath , os . X_OK ) # search for executable under windows if not exe : ...
def fisher_mean ( data ) : """Calculates the Fisher mean and associated parameter from a di _ block Parameters di _ block : a nested list of [ dec , inc ] or [ dec , inc , intensity ] Returns fpars : dictionary containing the Fisher mean and statistics dec : mean declination inc : mean inclination r :...
R , Xbar , X , fpars = 0 , [ 0 , 0 , 0 ] , [ ] , { } N = len ( data ) if N < 2 : return fpars X = dir2cart ( data ) for i in range ( len ( X ) ) : for c in range ( 3 ) : Xbar [ c ] += X [ i ] [ c ] for c in range ( 3 ) : R += Xbar [ c ] ** 2 R = np . sqrt ( R ) for c in range ( 3 ) : Xbar [ c ] ...
def evaluate_classifier_fraction ( input_ , labels , per_example_weights = None , topk = 1 , name = PROVIDED , phase = Phase . train ) : """Calculates the total of correct predictions and example count . In test and infer mode , this creates variables in the graph collection pt . GraphKeys . TEST _ VARIABLES an...
_ = name # Suppress lint if not ( tf . float32 . is_compatible_with ( labels . dtype ) or tf . float64 . is_compatible_with ( labels . dtype ) ) : raise ValueError ( 'labels must be floating point: %s.' % labels . dtype ) correct_predictions , examples = _compute_average_correct ( input_ , labels , per_example_weig...
def _change_iscsi_settings ( self , iscsi_info ) : """Change iSCSI settings . : param iscsi _ info : A dictionary that contains information of iSCSI target like target _ name , lun , ip _ address , port etc . : raises : IloError , on an error from iLO ."""
headers , bios_uri , bios_settings = self . _check_bios_resource ( ) # Get the Mappings resource . map_settings = self . _get_bios_mappings_resource ( bios_settings ) nics = [ ] for mapping in map_settings [ 'BiosPciSettingsMappings' ] : for subinstance in mapping [ 'Subinstances' ] : for association in sub...
def profile_func ( filename = None ) : '''Decorator for adding profiling to a nested function in Salt'''
def proffunc ( fun ) : def profiled_func ( * args , ** kwargs ) : logging . info ( 'Profiling function %s' , fun . __name__ ) try : profiler = cProfile . Profile ( ) retval = profiler . runcall ( fun , * args , ** kwargs ) profiler . dump_stats ( ( filename or '{0...
def get_note_list ( self , data = True , since = None , tags = [ ] ) : """Method to get the note list The method can be passed optional arguments to limit the list to notes containing a certain tag , or only updated since a certain Simperium cursor . If omitted a list of all notes is returned . By default d...
# initialize data status = 0 ret = [ ] response_notes = { } notes = { "index" : [ ] } # get the note index params = '/index?limit=%s' % ( str ( NOTE_FETCH_LENGTH ) ) if since is not None : params += '&since=%s' % ( since ) # Fetching data is the default if data : params += '&data=true' # perform initial HTTP re...
def get_help_values ( self ) : """Returns dict of help _ context values ( example values submitted in ` EmailRegistry . register ( ) ` method ) ."""
help_values = { } for k , v in self . help_context . items ( ) : if isinstance ( v , tuple ) and len ( v ) == 2 : help_values [ k ] = v [ 1 ] else : help_values [ k ] = u"<%s>" % k return help_values
def save_lastfile ( self , tfi ) : """Save the taskfile in the config : param tfi : the last selected taskfileinfo : type tfi : class : ` jukeboxcore . filesys . TaskFileInfo ` : returns : None : rtype : None : raises : None"""
tf = models . TaskFile . objects . get ( task = tfi . task , version = tfi . version , releasetype = tfi . releasetype , descriptor = tfi . descriptor , typ = tfi . typ ) c = self . get_config ( ) c [ 'lastfile' ] = tf . pk c . write ( )
def filter_exclude_dicts ( filter_dict = None , exclude_dict = None , name = 'acctno' , values = [ ] , swap = False ) : """Produces kwargs dicts for Django Queryset ` filter ` and ` exclude ` from a list of values The last , critical step in generating Django ORM kwargs dicts from a natural language query . Pro...
filter_dict = filter_dict or { } exclude_dict = exclude_dict or { } if not name . endswith ( '__in' ) : name += '__in' filter_dict [ name ] , exclude_dict [ name ] = [ ] , [ ] for v in values : # " NOT " means switch from include ( filter ) to exclude for that one account number if v . startswith ( 'NOT ' ) : ...
def output ( self ) -> None : """Pretty print travel times ."""
print ( "%s - %s" % ( self . station , self . now ) ) print ( self . products_filter ) for j in sorted ( self . journeys , key = lambda k : k . real_departure ) [ : self . max_journeys ] : print ( "-------------" ) print ( f"{j.product}: {j.number} ({j.train_id})" ) print ( f"Richtung: {j.direction}" ) ...
def number ( description , ** kwargs ) -> typing . Type : """Create a : class : ` ~ doctor . types . Number ` type . : param description : A description of the type . : param kwargs : Can include any attribute defined in : class : ` ~ doctor . types . Number `"""
kwargs [ 'description' ] = description return type ( 'Number' , ( Number , ) , kwargs )
def reduce_by ( fn : Callable [ [ T1 , T1 ] , T1 ] ) -> Callable [ [ ActualIterable [ T1 ] ] , T1 ] : """> > > from Redy . Collections import Traversal , Flow > > > def mul ( a : int , b : int ) : return a * b > > > lst : Iterable [ int ] = [ 1 , 2 , 3] > > > x = Flow ( lst ) [ Traversal . reduce _ by ( mul )...
return lambda collection : functools . reduce ( fn , collection )
def get_attrs_by_path ( self , field_path , stop_first = False ) : """It returns list of values looked up by field path . Field path is dot - formatted string path : ` ` parent _ field . child _ field ` ` . : param field _ path : field path . It allows ` ` * ` ` as wildcard . : type field _ path : list or Non...
fields , next_field = self . _get_fields_by_path ( field_path ) values = [ ] for field in fields : if next_field : try : res = self . get_field_value ( field ) . get_attrs_by_path ( next_field , stop_first = stop_first ) if res is None : continue values . ...
def virtual_hubs ( self ) : """Instance depends on the API version : * 2018-04-01 : : class : ` VirtualHubsOperations < azure . mgmt . network . v2018_04_01 . operations . VirtualHubsOperations > ` * 2018-06-01 : : class : ` VirtualHubsOperations < azure . mgmt . network . v2018_06_01 . operations . VirtualHubs...
api_version = self . _get_api_version ( 'virtual_hubs' ) if api_version == '2018-04-01' : from . v2018_04_01 . operations import VirtualHubsOperations as OperationClass elif api_version == '2018-06-01' : from . v2018_06_01 . operations import VirtualHubsOperations as OperationClass elif api_version == '2018-07-...
def _reverse ( self ) : """reverse patch direction ( this doesn ' t touch filenames )"""
for p in self . items : for h in p . hunks : h . startsrc , h . starttgt = h . starttgt , h . startsrc h . linessrc , h . linestgt = h . linestgt , h . linessrc for i , line in enumerate ( h . text ) : # need to use line [ 0:1 ] here , because line [ 0] # returns int instead of bytes...
def get_tags ( self , entry ) : """Return the tags linked in HTML ."""
try : return format_html_join ( ', ' , '<a href="{}" target="blank">{}</a>' , [ ( reverse ( 'zinnia:tag_detail' , args = [ tag ] ) , tag ) for tag in entry . tags_list ] ) except NoReverseMatch : return conditional_escape ( entry . tags )
def get_file_perms ( self , filename , note = None , loglevel = logging . DEBUG ) : """Returns the permissions of the file on the target as an octal string triplet . @ param filename : Filename to get permissions of . @ param note : See send ( ) @ type filename : string @ rtype : string"""
shutit = self . shutit shutit . handle_note ( note ) cmd = ' command stat -c %a ' + filename self . send ( ShutItSendSpec ( self , send = ' ' + cmd , check_exit = False , echo = False , loglevel = loglevel , ignore_background = True ) ) res = shutit . match_string ( self . pexpect_child . before , '([0-9][0-9][0-9])' )...
def visit_Call ( self , node ) : """Create adjoint for call . We don ' t allow unpacking of parameters , so we know that each argument gets passed in explicitly , allowing us to create partials for each . However , templates might perform parameter unpacking ( for cases where the number of arguments is vari...
# Find the function we are differentiating func = anno . getanno ( node , 'func' ) if func in non_differentiable . NON_DIFFERENTIABLE : return node , [ ] if func == tracing . Traceable : return self . primal_and_adjoint_for_tracing ( node ) if func in grads . UNIMPLEMENTED_ADJOINTS : raise errors . ReverseN...
def sync_counts ( ** kwargs ) : """Iterates over registered recipes and denormalizes ` ` Badge . users . count ( ) ` ` into ` ` Badge . users _ count ` ` field ."""
badges = kwargs . get ( 'badges' ) excluded = kwargs . get ( 'exclude_badges' ) instances = registry . get_recipe_instances ( badges = badges , excluded = excluded ) updated_badges , unchanged_badges = [ ] , [ ] for instance in instances : reset_queries ( ) badge , updated = instance . update_badge_users_count ...
def __load ( self , redirect = True , preload = False ) : '''Load basic information from Wikipedia . Confirm that page exists and is not a disambiguation / redirect . Does not need to be called manually , should be called automatically during _ _ init _ _ .'''
query_params = { 'prop' : 'info|pageprops' , 'inprop' : 'url' , 'ppprop' : 'disambiguation' , 'redirects' : '' , } if not getattr ( self , 'pageid' , None ) : query_params [ 'titles' ] = self . title else : query_params [ 'pageids' ] = self . pageid request = _wiki_request ( query_params ) query = request [ 'qu...
def _update_mean_in_window ( self ) : """Compute mean in window the slow way . useful for first step . Considers all values in window See Also _ add _ observation _ to _ means : fast update of mean for single observation addition _ remove _ observation _ from _ means : fast update of mean for single observa...
self . _mean_x_in_window = numpy . mean ( self . _x_in_window ) self . _mean_y_in_window = numpy . mean ( self . _y_in_window )
def com_google_fonts_check_monospace_max_advancewidth ( ttFont , glyph_metrics_stats ) : """Monospace font has hhea . advanceWidthMax equal to each glyph ' s advanceWidth ?"""
from fontbakery . utils import pretty_print_list seems_monospaced = glyph_metrics_stats [ "seems_monospaced" ] if not seems_monospaced : yield SKIP , ( "Font is not monospaced." ) return # hhea : advanceWidthMax is treated as source of truth here . max_advw = ttFont [ 'hhea' ] . advanceWidthMax outliers = [ ] z...
def _set_logging_rate_memory ( self , v , load = False ) : """Setter method for logging _ rate _ memory , mapped from YANG variable / rbridge _ id / resource _ monitor / memory / logging _ rate _ memory ( uint32) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ logging _...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , restriction_dict = { 'range' : [ u'10 .. 120' ] } ) , is_leaf = True , yang_n...