signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _get_deltas ( self , sites ) : """Return delta ' s for equation 4 delta _ C = 1 for site class C , 0 otherwise delta _ D = 1 for site class D , 0 otherwise"""
siteclass = sites . siteclass delta_C = np . zeros_like ( siteclass , dtype = np . float ) delta_C [ siteclass == b'C' ] = 1 delta_D = np . zeros_like ( siteclass , dtype = np . float ) delta_D [ siteclass == b'D' ] = 1 return delta_C , delta_D
def get_branch ( self , repository_id , name , project = None , base_version_descriptor = None ) : """GetBranch . Retrieve statistics about a single branch . : param str repository _ id : The name or ID of the repository . : param str name : Name of the branch . : param str project : Project ID or project n...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if repository_id is not None : route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' ) query_parameters = { } if name is not None : q...
def get_bbox ( self ) : """Returns ( ( top , left ) , ( bottom , right ) ) of bounding box A bounding box is the smallest rectangle that contains all selections . Non - specified boundaries are None ."""
bb_top , bb_left , bb_bottom , bb_right = [ None ] * 4 # Block selections for top_left , bottom_right in zip ( self . block_tl , self . block_br ) : top , left = top_left bottom , right = bottom_right if bb_top is None or bb_top > top : bb_top = top if bb_left is None or bb_left > left : ...
def put_manifest ( self , manifest ) : """Store the manifest ."""
logger . debug ( "Putting manifest" ) text = json . dumps ( manifest , indent = 2 , sort_keys = True ) key = self . get_manifest_key ( ) self . put_text ( key , text )
def updateTargetState ( self , newState ) : """Updates the system target state and propagates that to all devices . : param newState : : return :"""
self . _targetStateProvider . state = loadTargetState ( newState , self . _targetStateProvider . state ) for device in self . deviceController . getDevices ( ) : self . updateDeviceState ( device . payload )
def _closest_location ( self , location_map , target ) : """Return path of font whose location is closest to target ."""
def dist ( a , b ) : return math . sqrt ( sum ( ( a [ k ] - b [ k ] ) ** 2 for k in a . keys ( ) ) ) paths = iter ( location_map . keys ( ) ) closest = next ( paths ) closest_dist = dist ( target , location_map [ closest ] ) for path in paths : cur_dist = dist ( target , location_map [ path ] ) if cur_dist ...
def get_configuration ( self , uri ) : '''get the configuration of a PartStudio Args : - uri ( dict ) : points to a particular element Returns : - requests . Response : Onshape response data'''
req_headers = { 'Accept' : 'application/vnd.onshape.v1+json' , 'Content-Type' : 'application/json' } return self . _api . request ( 'get' , '/api/partstudios/d/' + uri [ "did" ] + '/' + uri [ "wvm_type" ] + '/' + uri [ "wvm" ] + '/e/' + uri [ "eid" ] + '/configuration' , headers = req_headers )
def save_as_cytoscape_html ( tree , out_html , column2states , layout = 'dagre' , name_feature = 'name' , name2colour = None , n2tooltip = None , years = None , is_compressed = True , n2date = None , date_column = 'Dist. to root' ) : """Converts a tree to an html representation using Cytoscape . js . If categorie...
graph_name = os . path . splitext ( os . path . basename ( out_html ) ) [ 0 ] json_dict , clazzes = _tree2json ( tree , column2states , name_feature = name_feature , node2tooltip = n2tooltip , years = years , is_compressed = is_compressed , n2date = n2date ) env = Environment ( loader = PackageLoader ( 'pastml' ) ) tem...
def _python_to_mod_modify ( changes : Changeset ) -> Dict [ str , List [ Tuple [ Operation , List [ bytes ] ] ] ] : """Convert a LdapChanges object to a modlist for a modify operation ."""
table : LdapObjectClass = type ( changes . src ) changes = changes . changes result : Dict [ str , List [ Tuple [ Operation , List [ bytes ] ] ] ] = { } for key , l in changes . items ( ) : field = _get_field_by_name ( table , key ) if field . db_field : try : new_list = [ ( operation , fiel...
def get_spontaneous_environment ( * args ) : """Return a new spontaneous environment . A spontaneous environment is an unnamed and unaccessible ( in theory ) environment that is used for templates generated from a string and not from the file system ."""
try : env = _spontaneous_environments . get ( args ) except TypeError : return Environment ( * args ) if env is not None : return env _spontaneous_environments [ args ] = env = Environment ( * args ) env . shared = True return env
def view ( azimuth = None , elevation = None , distance = None ) : """Set camera angles and distance and return the current . : param float azimuth : rotation around the axis pointing up in degrees : param float elevation : rotation where + 90 means ' up ' , - 90 means ' down ' , in degrees : param float dist...
fig = gcf ( ) # first calculate the current values x , y , z = fig . camera . position r = np . sqrt ( x ** 2 + y ** 2 + z ** 2 ) az = np . degrees ( np . arctan2 ( x , z ) ) el = np . degrees ( np . arcsin ( y / r ) ) if azimuth is None : azimuth = az if elevation is None : elevation = el if distance is None :...
def filter_regex ( names , regex ) : """Return a tuple of strings that match the regular expression pattern ."""
return tuple ( name for name in names if regex . search ( name ) is not None )
def get_context ( self ) : """Add mails to the context"""
context = super ( MailListView , self ) . get_context ( ) mail_list = registered_mails_names ( ) context [ 'mail_map' ] = mail_list return context
def get_machine_usage ( machine , start , end ) : """Return a tuple of cpu hours and number of jobs for a machine for a given period Keyword arguments : machine - - start - - start date end - - end date"""
try : cache = MachineCache . objects . get ( machine = machine , date = datetime . date . today ( ) , start = start , end = end ) return cache . cpu_time , cache . no_jobs except MachineCache . DoesNotExist : return 0 , 0
def _get_numdiff_hessian_steps_func ( objective_func , nmr_steps , step_ratio ) : """Get a function to compute the multiple step sizes for a single element of the Hessian ."""
return SimpleCLFunction . from_string ( ''' /** * Compute one element of the Hessian for a number of steps. * * This uses the initial steps in the data structure, indexed by the parameters to change (px, py). * * Args: * data: the data container *...
def subunits ( self ) : """DictList : Subunits represented as a DictList of Protein objects"""
# TODO : [ VizRecon ] # TODO : will need to adapt this to allow for input of previously created Protein objects subunits = DictList ( ) for s in self . subunit_dict : subunits . append ( Protein ( ident = s , description = 'Subunit of complex {}' . format ( self . id ) , root_dir = self . complex_dir , pdb_file_typ...
def Target_setAutoAttach ( self , autoAttach , waitForDebuggerOnStart ) : """Function path : Target . setAutoAttach Domain : Target Method name : setAutoAttach Parameters : Required arguments : ' autoAttach ' ( type : boolean ) - > Whether to auto - attach to related targets . ' waitForDebuggerOnStart '...
assert isinstance ( autoAttach , ( bool , ) ) , "Argument 'autoAttach' must be of type '['bool']'. Received type: '%s'" % type ( autoAttach ) assert isinstance ( waitForDebuggerOnStart , ( bool , ) ) , "Argument 'waitForDebuggerOnStart' must be of type '['bool']'. Received type: '%s'" % type ( waitForDebuggerOnStart ) ...
def connect ( host = "localhost" , port = 1113 , discovery_host = None , discovery_port = 2113 , username = None , password = None , loop = None , name = None , selector = select_random , ) -> Client : """Create a new client . Examples : Since the Client is an async context manager , we can use it in a with b...
discovery = get_discoverer ( host , port , discovery_host , discovery_port , selector ) dispatcher = MessageDispatcher ( name = name , loop = loop ) connector = Connector ( discovery , dispatcher , name = name ) credential = msg . Credential ( username , password ) if username and password else None return Client ( con...
def percentAt ( self , value ) : """Returns the percentage where the given value lies between this rulers minimum and maximum values . If the value equals the minimum , then the percent is 0 , if it equals the maximum , then the percent is 1 - any value between will be a floating point . If the ruler is a cus...
if value is None : return 0.0 values = self . values ( ) try : return float ( values . index ( value ) ) / ( len ( values ) - 1 ) except ValueError : return 0.0 except ZeroDivisionError : return 1.0
def convert ( files , ** kwargs ) : """Wrap directory to pif as a dice extension : param files : a list of files , which must be non - empty : param kwargs : any additional keyword arguments : return : the created pif"""
if len ( files ) < 1 : raise ValueError ( "Files needs to be a non-empty list" ) if len ( files ) == 1 : if os . path . isfile ( files [ 0 ] ) : return files_to_pif ( files , ** kwargs ) else : return directory_to_pif ( files [ 0 ] , ** kwargs ) else : return files_to_pif ( [ x for x in ...
def create_port_binding ( self , port , host ) : """Enqueue port binding create"""
if not self . get_instance_type ( port ) : return for pb_key in self . _get_binding_keys ( port , host ) : pb_res = MechResource ( pb_key , a_const . PORT_BINDING_RESOURCE , a_const . CREATE ) self . provision_queue . put ( pb_res )
def spkpds ( body , center , framestr , typenum , first , last ) : """Perform routine error checks and if all check pass , pack the descriptor for an SPK segment http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / spkpds _ c . html : param body : The NAIF ID code for the body of th...
body = ctypes . c_int ( body ) center = ctypes . c_int ( center ) framestr = stypes . stringToCharP ( framestr ) typenum = ctypes . c_int ( typenum ) first = ctypes . c_double ( first ) last = ctypes . c_double ( last ) descr = stypes . emptyDoubleVector ( 5 ) libspice . spkpds_c ( body , center , framestr , typenum , ...
def train ( self , env_fn , hparams , simulated , save_continuously , epoch , sampling_temp = 1.0 , num_env_steps = None , env_step_multiplier = 1 , eval_env_fn = None , report_fn = None ) : """Train ."""
raise NotImplementedError ( )
def X_length ( self , new_window_length ) : """Use presets for length of the window ."""
self . parent . value ( 'window_length' , new_window_length ) self . parent . overview . update_position ( )
def get_all_accounts ( self ) : """iterates through trie to and yields non - blank leafs as accounts ."""
for address_hash , rlpdata in self . secure_trie . trie . iter_branch ( ) : if rlpdata != trie . BLANK_NODE : yield rlp . decode ( rlpdata , Account , db = self . db , addr = address_hash )
def _request_get_helper ( self , url , params = None ) : '''API GET request helper'''
if not isinstance ( params , dict ) : params = dict ( ) if self . api_key : params [ 'api_key' ] = self . api_key return requests . get ( url , params = params , timeout = 60 )
def _write_tfrecords_from_generator ( generator , output_files , shuffle = True ) : """Writes generated str records to output _ files in round - robin order ."""
if do_files_exist ( output_files ) : raise ValueError ( "Pre-processed files already exists: {}." . format ( output_files ) ) with _incomplete_files ( output_files ) as tmp_files : # Write all shards writers = [ tf . io . TFRecordWriter ( fname ) for fname in tmp_files ] with _close_on_exit ( writers ) as w...
def _get_LMv2_response ( user_name , password , domain_name , server_challenge , client_challenge ) : """[ MS - NLMP ] v28.0 2016-07-14 2.2.2.4 LMv2 _ RESPONSE The LMv2 _ RESPONSE structure defines the NTLM v2 authentication LmChallengeResponse in the AUTHENTICATE _ MESSAGE . This response is used only when N...
nt_hash = comphash . _ntowfv2 ( user_name , password , domain_name ) lm_hash = hmac . new ( nt_hash , ( server_challenge + client_challenge ) ) . digest ( ) response = lm_hash + client_challenge return response
def replay_block ( self , block_to_replay , limit = 5 ) : """Replay all transactions in parent currency to passed in " source " currency . Block _ to _ replay can either be an integer or a block object ."""
if block_to_replay == 'latest' : if self . verbose : print ( "Getting latest %s block header" % source . upper ( ) ) block = get_block ( self . source , latest = True , verbose = self . verbose ) if self . verbose : print ( "Latest %s block is #%s" % ( self . source . upper ( ) , block [ 'bl...
def _upcase_word ( text , pos ) : """Uppercase the current ( or following ) word ."""
text , new_pos = _forward_word ( text , pos ) return text [ : pos ] + text [ pos : new_pos ] . upper ( ) + text [ new_pos : ] , new_pos
def focusout ( self , event ) : """Change style on focus out events ."""
bc = self . style . lookup ( "TEntry" , "bordercolor" , ( "!focus" , ) ) dc = self . style . lookup ( "TEntry" , "darkcolor" , ( "!focus" , ) ) lc = self . style . lookup ( "TEntry" , "lightcolor" , ( "!focus" , ) ) self . style . configure ( "%s.spinbox.TFrame" % self . frame , bordercolor = bc , darkcolor = dc , ligh...
def delete_forecast ( self , job_id , forecast_id = None , params = None ) : """` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / ml - delete - forecast . html > ` _ : arg job _ id : The ID of the job from which to delete forecasts : arg forecast _ id : The ID of the forecas...
if job_id in SKIP_IN_PATH : raise ValueError ( "Empty value passed for a required argument 'job_id'." ) return self . transport . perform_request ( "DELETE" , _make_path ( "_ml" , "anomaly_detectors" , job_id , "_forecast" , forecast_id ) , params = params , )
def describe ( id_or_link , ** kwargs ) : ''': param id _ or _ link : String containing an object ID or dict containing a DXLink , or a list of object IDs or dicts containing a DXLink . Given an object ID , calls : meth : ` ~ dxpy . bindings . DXDataObject . describe ` on the object . Example : : describe (...
# If this is a list , extract the ids . # TODO : modify the procedure to use project ID when possible if isinstance ( id_or_link , basestring ) or is_dxlink ( id_or_link ) : handler = get_handler ( id_or_link ) return handler . describe ( ** kwargs ) else : links = [ ] for link in id_or_link : # If this...
def unpack_rsp ( cls , rsp_pb ) : """Convert from PLS response to user response"""
if rsp_pb . retType != RET_OK : return RET_ERROR , rsp_pb . retMsg , None raw_order_list = rsp_pb . s2c . orderList order_list = [ OrderListQuery . parse_order ( rsp_pb , order ) for order in raw_order_list ] return RET_OK , "" , order_list
def _percent_match ( date_classes , tokens ) : """For each date class , return the percentage of tokens that the class matched ( floating point [ 0.0 - 1.0 ] ) . The returned value is a tuple of length patterns . Tokens should be a list ."""
match_count = [ 0 ] * len ( date_classes ) for i , date_class in enumerate ( date_classes ) : for token in tokens : if date_class . is_match ( token ) : match_count [ i ] += 1 percentages = tuple ( [ float ( m ) / len ( tokens ) for m in match_count ] ) return percentages
def predict ( self , data , output_margin = False , ntree_limit = 0 , pred_leaf = False , pred_contribs = False , approx_contribs = False , pred_interactions = False , validate_features = True ) : """Predict with data . . . note : : This function is not thread safe . For each booster object , predict can only b...
option_mask = 0x00 if output_margin : option_mask |= 0x01 if pred_leaf : option_mask |= 0x02 if pred_contribs : option_mask |= 0x04 if approx_contribs : option_mask |= 0x08 if pred_interactions : option_mask |= 0x10 if validate_features : self . _validate_features ( data ) length = c_bst_ulong (...
def itemsize_bits ( self ) : """Number of bits per element"""
if self . dtype is not None : return self . dtype . itemsize * 8 else : return sum ( x [ 1 ] for x in self . format )
def get_field_references ( ctx , field_names , simplify = False ) : """Create a mapping from fields to corresponding child indices : param ctx : ANTLR node : param field _ names : list of strings : param simplify : if True , omits fields with empty lists or None this makes it easy to detect nodes that only ...
field_dict = { } for field_name in field_names : field = get_field ( ctx , field_name ) if ( not simplify or field is not None and ( not isinstance ( field , list ) or len ( field ) > 0 ) ) : if isinstance ( field , list ) : value = [ ctx . children . index ( el ) for el in field ] e...
def ocrd_cli_options ( f ) : """Implement MP CLI . Usage : : import ocrd _ click _ cli from ocrd . utils @ click . command ( ) @ ocrd _ click _ cli def cli ( mets _ url ) : print ( mets _ url )"""
params = [ click . option ( '-m' , '--mets' , help = "METS URL to validate" ) , click . option ( '-w' , '--working-dir' , help = "Working Directory" ) , click . option ( '-I' , '--input-file-grp' , help = 'File group(s) used as input.' , default = 'INPUT' ) , click . option ( '-O' , '--output-file-grp' , help = 'File g...
def __reorganize_chron_header ( line ) : """Reorganize the list of variables . If there are units given , log them . : param str line : : return dict : key : variable , val : units ( optional )"""
d = { } # Header variables should be tab - delimited . Use regex to split by tabs m = re . split ( re_tab_split , line ) # If there was an output match from the line , then keep going if m : # Loop once for each variable in the line for s in m : # Match the variable to the ' variable ( units ) ' regex to look for u...
def scheduled ( ) : '''List scheduled jobs .'''
for job in sorted ( schedulables ( ) , key = lambda s : s . name ) : for task in PeriodicTask . objects ( task = job . name ) : label = job_label ( task . task , task . args , task . kwargs ) echo ( SCHEDULE_LINE . format ( name = white ( task . name . encode ( 'utf8' ) ) , label = label , schedule ...
def framewise ( self ) : """Property to determine whether the current frame should have framewise normalization enabled . Required for bokeh plotting classes to determine whether to send updated ranges for each frame ."""
current_frames = [ el for f in self . traverse ( lambda x : x . current_frame ) for el in ( f . traverse ( lambda x : x , [ Element ] ) if f else [ ] ) ] current_frames = util . unique_iterator ( current_frames ) return any ( self . lookup_options ( frame , 'norm' ) . options . get ( 'framewise' ) for frame in current_...
def _get_repo_filter ( self , query ) : """Apply repository wide side filter / mask query"""
if self . filter is not None : return query . extra ( where = [ self . filter ] ) return query
def _get_attribute_dimension ( trait_name , mark_type = None ) : """Returns the dimension for the name of the trait for the specified mark . If ` mark _ type ` is ` None ` , then the ` trait _ name ` is returned as is . Returns ` None ` if the ` trait _ name ` is not valid for ` mark _ type ` ."""
if ( mark_type is None ) : return trait_name scale_metadata = mark_type . class_traits ( ) [ 'scales_metadata' ] . default_args [ 0 ] return scale_metadata . get ( trait_name , { } ) . get ( 'dimension' , None )
def update_objective ( self , objective_form ) : """Updates an existing objective . arg : objective _ form ( osid . learning . ObjectiveForm ) : the form containing the elements to be updated raise : IllegalState - ` ` objective _ form ` ` already used in an update transaction raise : InvalidArgument - th...
# Implemented from template for # osid . resource . ResourceAdminSession . update _ resource _ template collection = JSONClientValidated ( 'learning' , collection = 'Objective' , runtime = self . _runtime ) if not isinstance ( objective_form , ABCObjectiveForm ) : raise errors . InvalidArgument ( 'argument type is ...
def qualifier_encoded ( self ) : """Union [ str , bytes ] : The qualifier encoded in binary . The type is ` ` str ` ` ( Python 2 . x ) or ` ` bytes ` ` ( Python 3 . x ) . The module will handle base64 encoding for you . See https : / / cloud . google . com / bigquery / docs / reference / rest / v2 / jobs # ...
prop = self . _properties . get ( "qualifierEncoded" ) if prop is None : return None return base64 . standard_b64decode ( _to_bytes ( prop ) )
def fetch ( self ) : """Fetch a FeedbackInstance : returns : Fetched FeedbackInstance : rtype : twilio . rest . api . v2010 . account . call . feedback . FeedbackInstance"""
params = values . of ( { } ) payload = self . _version . fetch ( 'GET' , self . _uri , params = params , ) return FeedbackInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , call_sid = self . _solution [ 'call_sid' ] , )
def propagate ( cls , date ) : """Compute the position of the sun at a given date Args : date ( ~ beyond . utils . date . Date ) Return : ~ beyond . orbits . orbit . Orbit : Position of the sun in MOD frame Example : . . code - block : : python from beyond . utils . date import Date SunPropagator . ...
date = date . change_scale ( 'UT1' ) t_ut1 = date . julian_century lambda_M = 280.460 + 36000.771 * t_ut1 M = np . radians ( 357.5291092 + 35999.05034 * t_ut1 ) lambda_el = np . radians ( lambda_M + 1.914666471 * np . sin ( M ) + 0.019994643 * np . sin ( 2 * M ) ) r = 1.000140612 - 0.016708617 * np . cos ( M ) - 0.0001...
def update_asset ( self , asset_form = None ) : """Updates an existing asset . : param asset _ form : the form containing the elements to be updated : type asset _ form : ` ` osid . repository . AssetForm ` ` : raise : ` ` IllegalState ` ` - - ` ` asset _ form ` ` already used in anupdate transaction : rais...
if asset_form is None : raise NullArgument ( ) if not isinstance ( asset_form , abc_repository_objects . AssetForm ) : raise InvalidArgument ( 'argument type is not an AssetForm' ) if not asset_form . is_for_update ( ) : raise InvalidArgument ( 'form is for create only, not update' ) try : if self . _fo...
def _send_request ( self ) : """Sends the request to the backend ."""
if isinstance ( self . _worker , str ) : classname = self . _worker else : classname = '%s.%s' % ( self . _worker . __module__ , self . _worker . __name__ ) self . request_id = str ( uuid . uuid4 ( ) ) self . send ( { 'request_id' : self . request_id , 'worker' : classname , 'data' : self . _args } )
def print_plugin_list ( plugins : Dict [ str , pkg_resources . EntryPoint ] ) : """Prints all registered plugins and checks if they can be loaded or not . : param plugins : plugins : type plugins : Dict [ str , ~ pkg _ resources . EntryPoint ]"""
for trigger , entry_point in plugins . items ( ) : try : plugin_class = entry_point . load ( ) version = str ( plugin_class . _info . version ) print ( f"{trigger} (ok)\n" f" {version}" ) except Exception : print ( f"{trigger} (failed)" )
def info ( context , keywords , x86 , x64 , x32 , common ) : """Find in the Linux system calls ."""
logging . info ( _ ( 'Current Mode: Find in Linux' ) ) database = context . obj [ 'database' ] for one in keywords : abis = [ 'i386' , 'x64' , 'common' , 'x32' ] if x86 : abis = [ 'i386' ] if x64 : abis = [ 'x64' , 'common' ] if x32 : abis = [ 'x32' , 'common' ] if common : ...
def _update_property_keys ( cls ) : """Set unspecified property _ keys for each ConfigProperty to the name of the class attr"""
for attr_name , config_prop in cls . _iter_config_props ( ) : if config_prop . property_key is None : config_prop . property_key = attr_name
def _validate_resource_dict ( cls , logical_id , resource_dict ) : """Validates that the provided resource dict contains the correct Type string , and the required Properties dict . : param dict resource _ dict : the resource dict to validate : returns : True if the resource dict has the expected format : rty...
if 'Type' not in resource_dict : raise InvalidResourceException ( logical_id , "Resource dict missing key 'Type'." ) if resource_dict [ 'Type' ] != cls . resource_type : raise InvalidResourceException ( logical_id , "Resource has incorrect Type; expected '{expected}', " "got '{actual}'" . format ( expected = cl...
def get_row_metadata ( gctx_file_path , convert_neg_666 = True ) : """Opens . gctx file and returns only row metadata Input : Mandatory : - gctx _ file _ path ( str ) : full path to gctx file you want to parse . Optional : - convert _ neg _ 666 ( bool ) : whether to convert - 666 values to num Output : ...
full_path = os . path . expanduser ( gctx_file_path ) # open file gctx_file = h5py . File ( full_path , "r" ) row_dset = gctx_file [ row_meta_group_node ] row_meta = parse_metadata_df ( "row" , row_dset , convert_neg_666 ) gctx_file . close ( ) return row_meta
def _wrap ( text , wrap_max = 80 , indent = 4 ) : """Wrap text at given width using textwrap module . text ( unicode ) : Text to wrap . If it ' s a Path , it ' s converted to string . wrap _ max ( int ) : Maximum line length ( indent is deducted ) . indent ( int ) : Number of spaces for indentation . RETURN...
indent = indent * ' ' wrap_width = wrap_max - len ( indent ) if isinstance ( text , Path ) : text = path2str ( text ) return textwrap . fill ( text , width = wrap_width , initial_indent = indent , subsequent_indent = indent , break_long_words = False , break_on_hyphens = False )
def POST ( self , ** kwargs ) : r'''Easily generate keys for a minion and auto - accept the new key Accepts all the same parameters as the : py : func : ` key . gen _ accept < salt . wheel . key . gen _ accept > ` . . . note : : A note about ` ` curl ` ` Avoid using the ` ` - i ` ` flag or HTTP headers will...
lowstate = cherrypy . request . lowstate lowstate [ 0 ] . update ( { 'client' : 'wheel' , 'fun' : 'key.gen_accept' , } ) if 'mid' in lowstate [ 0 ] : lowstate [ 0 ] [ 'id_' ] = lowstate [ 0 ] . pop ( 'mid' ) result = self . exec_lowstate ( ) ret = next ( result , { } ) . get ( 'data' , { } ) . get ( 'return' , { } ...
def user_organization_memberships ( self , user_id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / organization _ memberships # list - memberships"
api_path = "/api/v2/users/{user_id}/organization_memberships.json" api_path = api_path . format ( user_id = user_id ) return self . call ( api_path , ** kwargs )
def download_dataset ( self , dataset_name , local_path , how = "stream" ) : """It downloads from the repository the specified dataset and puts it in the specified local folder : param dataset _ name : the name the dataset has in the repository : param local _ path : where you want to save the dataset : par...
if not os . path . isdir ( local_path ) : os . makedirs ( local_path ) else : raise ValueError ( "Path {} already exists!" . format ( local_path ) ) local_path = os . path . join ( local_path , FILES_FOLDER ) os . makedirs ( local_path ) if how == 'zip' : return self . download_as_zip ( dataset_name , local...
def setnil ( self , flag = True ) : """Set this node to I { nil } as defined by having an I { xsi : nil } = I { flag } attribute . @ param flag : A flag indicating how I { xsi : nil } will be set . @ type flag : boolean @ return : self @ rtype : L { Element }"""
p , u = Namespace . xsins name = ":" . join ( ( p , "nil" ) ) self . set ( name , str ( flag ) . lower ( ) ) self . addPrefix ( p , u ) if flag : self . text = None return self
def _fadn_orth ( vec , geom ) : """First non - zero Atomic Displacement Non - Orthogonal to Vec Utility function to identify the first atomic displacement in a geometry that is ( a ) not the zero vector ; and ( b ) not normal to the reference vector . Parameters vec length - 3 | npfloat _ | - - Referenc...
# Imports import numpy as np from scipy import linalg as spla from . . const import PRM from . . error import InertiaError from . vector import orthonorm_check as onchk # Geom and vec must both be the right shape if not ( len ( geom . shape ) == 1 and geom . shape [ 0 ] % 3 == 0 ) : raise ValueError ( "Geometry is ...
def find ( self , * params ) : """按照简单 、 一般 、 特殊的顺序寻找新闻发布时间 Keyword * params : params - - 可以接收多个含有时间的文本 , str类型"""
for string in params : self . easy_time_extrator ( string ) if self . check_time_extrator ( ) : log ( 'debug' , '通过简单模式找到时间信息' ) return self . check_time_extrator ( ) for string in params : self . common_time_extrator ( string ) if self . check_time_extrator ( ) : log ( 'debug' ,...
def p_field_expr ( p ) : """expr : expr FIELD"""
p [ 0 ] = node . expr ( op = "." , args = node . expr_list ( [ p [ 1 ] , node . ident ( name = p [ 2 ] , lineno = p . lineno ( 2 ) , lexpos = p . lexpos ( 2 ) ) ] ) )
def md5 ( filename ) : '''Return MD5 hex digest of local file , or None if file is not present .'''
if not os . path . exists ( filename ) : return None digest = _md5 ( ) blocksize = 64 * 1024 infile = open ( filename , 'rb' ) block = infile . read ( blocksize ) while block : digest . update ( block ) block = infile . read ( blocksize ) infile . close ( ) return digest . hexdigest ( )
def log_init ( ) : """Function that sets log levels and format strings . Checks for the OT _ API _ LOG _ LEVEL environment variable otherwise defaults to DEBUG ."""
fallback_log_level = 'INFO' ot_log_level = hardware . config . log_level if ot_log_level not in logging . _nameToLevel : log . info ( "OT Log Level {} not found. Defaulting to {}" . format ( ot_log_level , fallback_log_level ) ) ot_log_level = fallback_log_level level_value = logging . _nameToLevel [ ot_log_lev...
def get_token ( self , token ) : '''Request a token from the master'''
load = { } load [ 'token' ] = token load [ 'cmd' ] = 'get_token' tdata = self . _send_token_request ( load ) return tdata
def _get_item ( self , question_id ) : """we need a middle - man method to convert the unique " assessment - session " authority question _ ids into " real " itemIds BUT this also has to return the " magic " item , so we can ' t rely on question = self . get _ question ( question _ id ) ils = self . _ get...
question_map = self . _get_question_map ( question_id ) # Throws NotFound ( ) real_question_id = Id ( question_map [ 'questionId' ] ) return self . _get_item_lookup_session ( ) . get_item ( real_question_id )
def replace_braces ( s , env ) : """Makes tox substitutions to s , with respect to environment env . Example > > > replace _ braces ( " echo { posargs : { env : USER : } passed no posargs } " ) " echo andy passed no posargs " Note : first " { env : USER : } " is replaced with os . environ . get ( " USER " ,...
def replace ( m ) : return _replace_match ( m , env ) for _ in range ( DEPTH ) : s = re . sub ( r"{[^{}]*}" , replace , s ) return s
def iter_links_object_element ( cls , element ) : '''Iterate ` ` object ` ` and ` ` embed ` ` elements . This function also looks at ` ` codebase ` ` and ` ` archive ` ` attributes .'''
base_link = element . attrib . get ( 'codebase' , None ) if base_link : # lxml returns codebase as inline link_type = element . attrib . get ( base_link ) yield LinkInfo ( element = element , tag = element . tag , attrib = 'codebase' , link = base_link , inline = True , linked = False , base_link = None , value...
def publishAsync ( self , topic , payload , QoS , ackCallback = None ) : """* * Description * * Publish a new message asynchronously to the desired topic with QoS and PUBACK callback . Note that the ack callback configuration for a QoS0 publish request will be ignored as there are no PUBACK reception . * * Sy...
return self . _mqtt_core . publish_async ( topic , payload , QoS , False , ackCallback )
def get_room_info ( self , room_id , ** kwargs ) : """Get various information about a specific channel / room : param room _ id : : param kwargs : : return :"""
return GetRoomInfo ( settings = self . settings , ** kwargs ) . call ( room_id = room_id , ** kwargs )
def restrict ( self , point ) : """Apply the ` ` restrict ` ` method to all functions . Returns a new farray ."""
items = [ f . restrict ( point ) for f in self . _items ] return self . __class__ ( items , self . shape , self . ftype )
def clean ( mapping , bind , values ) : """Perform several types of string cleaning for titles etc . ."""
categories = { 'C' : ' ' } for value in values : if isinstance ( value , six . string_types ) : value = normality . normalize ( value , lowercase = False , collapse = True , decompose = False , replace_categories = categories ) yield value
def _get_diff ( environ , label , pop = False ) : """Get previously frozen key - value pairs . : param str label : The name for the frozen environment . : param bool pop : Destroy the freeze after use ; only allow application once . : returns : ` ` dict ` ` of frozen values ."""
if pop : blob = environ . pop ( _variable_name ( label ) , None ) else : blob = environ . get ( _variable_name ( label ) ) return _loads ( blob ) if blob else { }
def tox_get_python_executable ( envconfig ) : """Return a python executable for the given python base name . The first plugin / hook which returns an executable path will determine it . ` ` envconfig ` ` is the testenv configuration which contains per - testenv configuration , notably the ` ` . envname ` ` an...
try : # pylint : disable = no - member pyenv = ( getattr ( py . path . local . sysfind ( 'pyenv' ) , 'strpath' , 'pyenv' ) or 'pyenv' ) cmd = [ pyenv , 'which' , envconfig . basepython ] pipe = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . PIPE , universal_newlines = True ) ...
def _persist ( self ) : """Run the command inside a thread so that we can catch output for each line as it comes in and display it ."""
# run the block / command for command in self . commands : try : process = Popen ( [ command ] , stdout = PIPE , stderr = PIPE , universal_newlines = True , env = self . env , shell = True , ) except Exception as e : retcode = process . poll ( ) msg = "Command '{cmd}' {error} retcode {re...
def export ( self , filename = 'element.zip' ) : """Export this element . Usage : : engine = Engine ( ' myfirewall ' ) extask = engine . export ( filename = ' fooexport . zip ' ) while not extask . done ( ) : extask . wait ( 3) print ( " Finished download task : % s " % extask . message ( ) ) print ( ...
from smc . administration . tasks import Task return Task . download ( self , 'export' , filename )
def filter_requires_grad ( pgroups ) : """Returns parameter groups where parameters that don ' t require a gradient are filtered out . Parameters pgroups : dict Parameter groups to be filtered"""
warnings . warn ( "For filtering gradients, please use skorch.callbacks.Freezer." , DeprecationWarning ) for pgroup in pgroups : output = { k : v for k , v in pgroup . items ( ) if k != 'params' } output [ 'params' ] = ( p for p in pgroup [ 'params' ] if p . requires_grad ) yield output
def _get_column_names_in_altered_table ( self , diff ) : """: param diff : The table diff : type diff : orator . dbal . table _ diff . TableDiff : rtype : dict"""
columns = OrderedDict ( ) for column_name , column in diff . from_table . get_columns ( ) . items ( ) : columns [ column_name . lower ( ) ] = column . get_name ( ) for column_name , column in diff . removed_columns . items ( ) : column_name = column_name . lower ( ) if column_name in columns : del c...
def get_tags_of_delivery_note_per_page ( self , delivery_note_id , per_page = 1000 , page = 1 ) : """Get tags of delivery note per page : param delivery _ note _ id : the delivery note id : param per _ page : How many objects per page . Default : 1000 : param page : Which page . Default : 1 : return : list"...
return self . _get_resource_per_page ( resource = DELIVERY_NOTE_TAGS , per_page = per_page , page = page , params = { 'delivery_note_id' : delivery_note_id } , )
def admm ( X , prox_f , step_f , prox_g = None , step_g = None , L = None , e_rel = 1e-6 , e_abs = 0 , max_iter = 1000 , traceback = None ) : """Alternating Direction Method of Multipliers This method implements the linearized ADMM from Parikh & Boyd ( 2014 ) . Args : X : initial X will be updated prox _ f ...
# use matrix adapter for convenient & fast notation _L = utils . MatrixAdapter ( L ) # get / check compatible step size for g if prox_g is not None and step_g is None : step_g = utils . get_step_g ( step_f , _L . spectral_norm ) # init Z , U = utils . initZU ( X , _L ) it = 0 if traceback is not None : tracebac...
def run ( self ) : '''Runs the de - trending step .'''
try : # Load raw data log . info ( "Loading target data..." ) self . load_tpf ( ) self . mask_planets ( ) self . plot_aperture ( [ self . dvs . top_right ( ) for i in range ( 4 ) ] ) self . init_kernel ( ) M = self . apply_mask ( np . arange ( len ( self . time ) ) ) self . cdppr_arr = self ...
def read_constraints_from_config ( cp , transforms = None , constraint_section = 'constraint' ) : """Loads parameter constraints from a configuration file . Parameters cp : WorkflowConfigParser An open config parser to read from . transforms : list , optional List of transforms to apply to parameters befo...
cons = [ ] for subsection in cp . get_subsections ( constraint_section ) : name = cp . get_opt_tag ( constraint_section , "name" , subsection ) constraint_arg = cp . get_opt_tag ( constraint_section , "constraint_arg" , subsection ) # get any other keyword arguments kwargs = { } section = constraint...
def _set_traffic_eng ( self , v , load = False ) : """Setter method for traffic _ eng , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / mpls _ interface / interface _ dynamic _ bypass / mpls _ interface _ dynamic _ bypass _ sub _ cmds / traffic _ eng ( container ) If this variab...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = traffic_eng . traffic_eng , is_container = 'container' , presence = False , yang_name = "traffic-eng" , rest_name = "traffic-eng" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , registe...
def sim ( sense1 : "wn.Synset" , sense2 : "wn.Synset" , option : str = "path" ) -> float : """Calculates similarity based on user ' s choice . : param sense1 : A synset . : param sense2 : A synset . : param option : String , one of ( ' path ' , ' wup ' , ' lch ' , ' res ' , ' jcn ' , ' lin ' ) . : return : ...
option = option . lower ( ) if option . lower ( ) in [ "path" , "path_similarity" , "wup" , "wupa" , "wu-palmer" , "wu-palmer" , 'lch' , "leacock-chordorow" ] : return similarity_by_path ( sense1 , sense2 , option ) elif option . lower ( ) in [ "res" , "resnik" , "jcn" , "jiang-conrath" , "lin" ] : return simil...
def from_dict ( raw_data ) : """Create WordSet from raw dictionary data ."""
try : set_id = raw_data [ 'id' ] title = raw_data [ 'title' ] terms = [ Term . from_dict ( term ) for term in raw_data [ 'terms' ] ] return WordSet ( set_id , title , terms ) except KeyError : raise ValueError ( 'Unexpected set json structure' )
def alter_database ( self , dbname , db ) : """Parameters : - dbname - db"""
self . send_alter_database ( dbname , db ) self . recv_alter_database ( )
def _make_input_file_list ( binnedfile , num_files ) : """Make the list of input files for a particular energy bin X psf type"""
outdir_base = os . path . abspath ( os . path . dirname ( binnedfile ) ) outbasename = os . path . basename ( binnedfile ) filelist = "" for i in range ( num_files ) : split_key = "%06i" % i output_dir = os . path . join ( outdir_base , split_key ) filepath = os . path . join ( output_dir , outbasename . re...
def _initialize_variogram_model ( X , y , variogram_model , variogram_model_parameters , variogram_function , nlags , weight , coordinates_type ) : """Initializes the variogram model for kriging . If user does not specify parameters , calls automatic variogram estimation routine . Returns lags , semivariance , ...
# distance calculation for rectangular coords now leverages # scipy . spatial . distance ' s pdist function , which gives pairwise distances # in a condensed distance vector ( distance matrix flattened to a vector ) # to calculate semivariances . . . if coordinates_type == 'euclidean' : d = pdist ( X , metric = 'eu...
def compute_membership_strengths ( knn_indices , knn_dists , sigmas , rhos ) : """Construct the membership strength data for the 1 - skeleton of each local fuzzy simplicial set - - this is formed as a sparse matrix where each row is a local fuzzy simplicial set , with a membership strength for the 1 - simplex...
n_samples = knn_indices . shape [ 0 ] n_neighbors = knn_indices . shape [ 1 ] rows = np . zeros ( ( n_samples * n_neighbors ) , dtype = np . int64 ) cols = np . zeros ( ( n_samples * n_neighbors ) , dtype = np . int64 ) vals = np . zeros ( ( n_samples * n_neighbors ) , dtype = np . float64 ) for i in range ( n_samples ...
def internal2external_grad ( xi , bounds ) : """Calculate the internal to external gradiant Calculates the partial of external over internal"""
ge = np . empty_like ( xi ) for i , ( v , bound ) in enumerate ( zip ( xi , bounds ) ) : a = bound [ 0 ] # minimum b = bound [ 1 ] # maximum if a == None and b == None : # No constraints ge [ i ] = 1.0 elif b == None : # only min ge [ i ] = v / np . sqrt ( v ** 2 + 1 ) elif a...
def y_select_cb ( self , w , index ) : """Callback to set Y - axis column ."""
try : self . y_col = self . cols [ index ] except IndexError as e : self . logger . error ( str ( e ) ) else : self . plot_two_columns ( reset_ylimits = True )
def file_logger ( app , level = None ) : """Get file logger Returns configured fire logger ready to be attached to app : param app : application instance : param level : log this level : return : RotatingFileHandler"""
path = os . path . join ( os . getcwd ( ) , 'var' , 'logs' , 'app.log' ) max_bytes = 1024 * 1024 * 2 file_handler = RotatingFileHandler ( filename = path , mode = 'a' , maxBytes = max_bytes , backupCount = 10 ) if level is None : level = logging . INFO file_handler . setLevel ( level ) log_format = '%(asctime)s %(l...
def getSkeletalBoneData ( self , action , eTransformSpace , eMotionRange , unTransformArrayCount ) : """Reads the state of the skeletal bone data associated with this action and copies it into the given buffer ."""
fn = self . function_table . getSkeletalBoneData pTransformArray = VRBoneTransform_t ( ) result = fn ( action , eTransformSpace , eMotionRange , byref ( pTransformArray ) , unTransformArrayCount ) return result , pTransformArray
def with_context ( self , required_by ) : """If required _ by is non - empty , return a version of self that is a ContextualVersionConflict ."""
if not required_by : return self args = self . args + ( required_by , ) return ContextualVersionConflict ( * args )
def add_event ( event_collection , body , timestamp = None ) : """Adds an event . Depending on the persistence strategy of the client , this will either result in the event being uploaded to Keen immediately or will result in saving the event to some local cache . : param event _ collection : the name of th...
_initialize_client_from_environment ( ) _client . add_event ( event_collection , body , timestamp = timestamp )
def parse ( file_contents , file_name ) : '''Takes a list of files which are assumed to be jinja2 templates and tries to parse the contents of the files Args : file _ contents ( str ) : File contents of a jinja file Raises : Exception : An exception is raised if the contents of the file cannot be parsed...
env = Environment ( ) result = "" try : env . parse ( file_contents ) except Exception : _ , exc_value , _ = sys . exc_info ( ) result += "ERROR: Jinja2 Template File: {0}" . format ( file_name ) result += repr ( exc_value ) + '\n' return result
def run ( self ) : """Build extensions in build directory , then copy if - - inplace"""
old_inplace , self . inplace = self . inplace , 0 _build_ext . run ( self ) self . inplace = old_inplace if old_inplace : self . copy_extensions_to_source ( )
def dist_between ( h , seg1 , seg2 ) : """Calculates the distance between two segments . I stole this function from a post by Michael Hines on the NEURON forum ( www . neuron . yale . edu / phpbb / viewtopic . php ? f = 2 & t = 2114)"""
h . distance ( 0 , seg1 . x , sec = seg1 . sec ) return h . distance ( seg2 . x , sec = seg2 . sec )
def _call_pyfftw ( self , x , out , ** kwargs ) : """Implement ` ` self ( x [ , out , * * kwargs ] ) ` ` using pyfftw . Parameters x : ` numpy . ndarray ` Input array to be transformed out : ` numpy . ndarray ` Output array storing the result flags : sequence of strings , optional Flags for the transf...
assert isinstance ( x , np . ndarray ) assert isinstance ( out , np . ndarray ) kwargs . pop ( 'normalise_idft' , None ) # Using ` False ` here kwargs . pop ( 'axes' , None ) kwargs . pop ( 'halfcomplex' , None ) flags = list ( _pyfftw_to_local ( flag ) for flag in kwargs . pop ( 'flags' , ( 'FFTW_MEASURE' , ) ) ) try ...