signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _load_chains ( f ) : '''Loads all LiftOverChain objects from a file into an array . Returns the result .'''
chains = [ ] while True : line = f . readline ( ) if not line : break if line . startswith ( b'#' ) or line . startswith ( b'\n' ) or line . startswith ( b'\r' ) : continue if line . startswith ( b'chain' ) : # Read chain chains . append ( LiftOverChain ( line , f ) ) con...
def evaluate ( self , genomes , config ) : """Evaluates the genomes . This method raises a ModeError if the DistributedEvaluator is not in primary mode ."""
if self . mode != MODE_PRIMARY : raise ModeError ( "Not in primary mode!" ) tasks = [ ( genome_id , genome , config ) for genome_id , genome in genomes ] id2genome = { genome_id : genome for genome_id , genome in genomes } tasks = chunked ( tasks , self . secondary_chunksize ) n_tasks = len ( tasks ) for task in ta...
def user_create ( self , data , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / users # create - user"
api_path = "/api/v2/users.json" return self . call ( api_path , method = "POST" , data = data , ** kwargs )
def BuscarCTG ( self , tipo_certificado = "P" , cuit_depositante = None , nro_planta = None , cod_grano = 2 , campania = 1314 , nro_ctg = None , tipo_ctg = None , nro_carta_porte = None , fecha_confirmacion_ctg_des = None , fecha_confirmacion_ctg_has = None , ) : "Devuelve los CTG / Carta de porte que se puede incl...
ret = self . client . cgBuscarCtg ( auth = { 'token' : self . Token , 'sign' : self . Sign , 'cuit' : self . Cuit , } , tipoCertificado = tipo_certificado , cuitDepositante = cuit_depositante or self . Cuit , nroPlanta = nro_planta , codGrano = cod_grano , campania = campania , nroCtg = nro_ctg , tipoCtg = tipo_ctg , n...
def get_turicreate_object_type ( url ) : '''Given url where a Turi Create object is persisted , return the Turi Create object type : ' model ' , ' graph ' , ' sframe ' , or ' sarray ' '''
from . . _connect import main as _glconnect ret = _glconnect . get_unity ( ) . get_turicreate_object_type ( _make_internal_url ( url ) ) # to be consistent , we use sgraph instead of graph here if ret == 'graph' : ret = 'sgraph' return ret
def to_python ( self , value ) : """Convert the input JSON value into python structures , raises django . core . exceptions . ValidationError if the data can ' t be converted ."""
if isinstance ( value , dict ) : return value if self . blank and not value : return None if isinstance ( value , string_types ) : try : return json . loads ( value ) except Exception as e : raise ValidationError ( str ( e ) ) return value
def language ( self , value = None ) : """No arguments : Get the document ' s language ( ISO - 639-3 ) from metadata Argument : Set the document ' s language ( ISO - 639-3 ) in metadata"""
if not ( value is None ) : if ( self . metadatatype == "native" ) : self . metadata [ 'language' ] = value else : self . _language = value if self . metadatatype == "native" : if 'language' in self . metadata : return self . metadata [ 'language' ] else : return None else...
def do_OP_EQUAL ( vm ) : """> > > s = [ b ' string1 ' , b ' string1 ' ] > > > do _ OP _ EQUAL ( s ) > > > print ( s = = [ b ' \1 ' ] ) True > > > s = [ b ' string1 ' , b ' string2 ' ] > > > do _ OP _ EQUAL ( s ) > > > print ( s = = [ b ' ' ] ) True"""
v1 , v2 = [ vm . pop ( ) for i in range ( 2 ) ] vm . append ( vm . bool_to_script_bytes ( v1 == v2 ) )
def get_reposts ( self ) : """https : / / vk . com / dev / wall . getReposts"""
return self . _session . fetch_items ( 'wall.getReposts' , self . from_json , count = 1000 , owner_id = self . from_id , post_id = self . id )
def ParseFileTransfer ( self , parser_mediator , query , row , cache = None , database = None , ** unused_kwargs ) : """Parses a file transfer . There is no direct relationship between who sends the file and who accepts the file . Args : parser _ mediator ( ParserMediator ) : mediates interactions between p...
query_hash = hash ( query ) source_dict = cache . GetResults ( 'source' ) if not source_dict : results = database . Query ( self . QUERY_SOURCE_FROM_TRANSFER ) cache . CacheQueryResults ( results , 'source' , 'pk_id' , ( 'skypeid' , 'skypename' ) ) source_dict = cache . GetResults ( 'source' ) dest_dict = c...
def _print_message ( self , flag_message = None , color = None , padding = None , reverse = False ) : """Outputs the message to the terminal"""
if flag_message : flag_message = stdout_encode ( flag ( flag_message , color = color if self . pretty else None , show = False ) ) if not reverse : print ( padd ( flag_message , padding ) , self . format_messages ( self . message ) ) else : print ( self . format_messages ( self . message ) ,...
def count_matrix_coo2_mult ( dtrajs , lag , sliding = True , sparse = True , nstates = None ) : r"""Generate a count matrix from a given list discrete trajectories . The generated count matrix is a sparse matrix in compressed sparse row ( CSR ) or numpy ndarray format . Parameters dtraj : list of ndarrays ...
# Determine number of states if nstates is None : from msmtools . dtraj import number_of_states nstates = number_of_states ( dtrajs ) rows = [ ] cols = [ ] # collect transition index pairs for dtraj in dtrajs : if dtraj . size > lag : if ( sliding ) : rows . append ( dtraj [ 0 : - lag ] ...
def ticker ( self , base = "btc" , quote = "usd" ) : """Returns dictionary ."""
url = self . _construct_url ( "ticker/" , base , quote ) return self . _get ( url , return_json = True , version = 2 )
def bind_keys ( self , objects ) : """Configure name map : My goal here is to associate a named object with a specific function"""
for object in objects : if object . keys != None : for key in object . keys : if key != None : self . bind_key_name ( key , object . name )
def on_sigprof ( self , _unused_signum , _unused_frame ) : """Called when SIGPROF is sent to the process , will dump the stats , in future versions , queue them for the master process to get data . : param int _ unused _ signum : The signal number : param frame _ unused _ frame : The python frame the signal w...
self . stats_queue . put ( self . report_stats ( ) , True ) self . last_stats_time = time . time ( ) signal . siginterrupt ( signal . SIGPROF , False )
def provides_distribution ( self , name , version = None ) : """Iterates over all distributions to find which distributions provide * name * . If a * version * is provided , it will be used to filter the results . This function only returns the first result found , since no more than one values are expected ....
matcher = None if version is not None : try : matcher = self . _scheme . matcher ( '%s (%s)' % ( name , version ) ) except ValueError : raise DistlibException ( 'invalid name or version: %r, %r' % ( name , version ) ) for dist in self . get_distributions ( ) : # We hit a problem on Travis where ...
def norm_2l2 ( x , axis = None ) : r"""Compute the squared : math : ` \ ell _ 2 ` norm . . math : : \ | \ mathbf { x } \ | _ 2 ^ 2 = \ sum _ i x _ i ^ 2 where : math : ` x _ i ` is element : math : ` i ` of vector : math : ` \ mathbf { x } ` . Parameters x : array _ like Input array : math : ` \ mathbf ...
nl2 = np . sum ( x ** 2 , axis = axis , keepdims = True ) # If the result has a single element , convert it to a scalar if nl2 . size == 1 : nl2 = nl2 . ravel ( ) [ 0 ] return nl2
def exec_file ( path , name ) : """Extract a constant from a python file by looking for a line defining the constant and executing it ."""
result = { } code = read_file ( path ) lines = [ line for line in code . split ( '\n' ) if line . startswith ( name ) ] exec ( "\n" . join ( lines ) , result ) return result [ name ]
def calculate_hashes ( self ) : """Return hashes of the contents of this MAR file . The hashes depend on the algorithms defined in the MAR file ' s signature block . Returns : A list of ( algorithm _ id , hash ) tuples"""
hashers = [ ] if not self . mardata . signatures : return [ ] for s in self . mardata . signatures . sigs : h = make_hasher ( s . algorithm_id ) hashers . append ( ( s . algorithm_id , h ) ) for block in get_signature_data ( self . fileobj , self . mardata . signatures . filesize ) : [ h . update ( bloc...
def currentMode ( self ) : """Returns the current mode for this widget . : return < XOrbBrowserWidget . Mode >"""
if ( self . uiCardACT . isChecked ( ) ) : return XOrbBrowserWidget . Mode . Card elif ( self . uiDetailsACT . isChecked ( ) ) : return XOrbBrowserWidget . Mode . Detail else : return XOrbBrowserWidget . Mode . Thumbnail
def count_numerics ( input_str ) : """This function counts the number of numeric characters in a provided string . Examples : count _ numerics ( ' program2bedone ' ) - > 1 count _ numerics ( ' 3wonders ' ) - > 1 count _ numerics ( ' 123 ' ) - > 3 : param input _ str : A string possibly containing numeric ...
numeric_count = sum ( char . isdigit ( ) for char in input_str ) return numeric_count
def yank_fields_from_attrs ( attrs , _as = None , sort = True ) : """Extract all the fields in given attributes ( dict ) and return them ordered"""
fields_with_names = [ ] for attname , value in list ( attrs . items ( ) ) : field = get_field_as ( value , _as ) if not field : continue fields_with_names . append ( ( attname , field ) ) if sort : fields_with_names = sorted ( fields_with_names , key = lambda f : f [ 1 ] ) return OrderedDict ( f...
async def read ( self ) : """| coro | Retrieves the content of this asset as a : class : ` bytes ` object . . . warning : : : class : ` PartialEmoji ` won ' t have a connection state if user created , and a URL won ' t be present if a custom image isn ' t associated with the asset , e . g . a guild with n...
if not self . _url : raise DiscordException ( 'Invalid asset (no URL provided)' ) if self . _state is None : raise DiscordException ( 'Invalid state (no ConnectionState provided)' ) return await self . _state . http . get_from_cdn ( self . _url )
def get_workflows ( ) : """Returns a mapping of id - > workflow"""
wftool = api . get_tool ( "portal_workflow" ) wfs = { } for wfid in wftool . objectIds ( ) : wf = wftool . getWorkflowById ( wfid ) if hasattr ( aq_base ( wf ) , "updateRoleMappingsFor" ) : wfs [ wfid ] = wf return wfs
def _fake_invokemethod ( self , methodname , objectname , Params , ** params ) : # pylint : disable = invalid - name """Implements a mock WBEM server responder for : meth : ` ~ pywbem . WBEMConnection . InvokeMethod ` This responder calls a function defined by an entry in the methods repository . The return f...
if isinstance ( objectname , ( CIMInstanceName , CIMClassName ) ) : localobject = deepcopy ( objectname ) if localobject . namespace is None : localobject . namespace = self . default_namespace localobject . host = None elif isinstance ( objectname , six . string_types ) : # a string is always i...
def plan_scripts ( self ) : """Gets the Plan Scripts API client . Returns : PlanScripts :"""
if not self . __plan_scripts : self . __plan_scripts = PlanScripts ( self . __connection ) return self . __plan_scripts
def get_significant_digits ( numeric_value ) : """Returns the precision for a given floatable value . If value is None or not floatable , returns None . Will return positive values if the result is below 1 and will return 0 values if the result is above or equal to 1. : param numeric _ value : the value to ...
try : numeric_value = float ( numeric_value ) except ( TypeError , ValueError ) : return None if numeric_value == 0 : return 0 significant_digit = int ( math . floor ( math . log10 ( abs ( numeric_value ) ) ) ) return 0 if significant_digit > 0 else abs ( significant_digit )
def _conn_key ( self , instance , db_key , db_name = None ) : '''Return a key to use for the connection cache'''
dsn , host , username , password , database , driver = self . _get_access_info ( instance , db_key , db_name ) return '{}:{}:{}:{}:{}:{}' . format ( dsn , host , username , password , database , driver )
def _get_weekly_date_range ( self , metric_date , delta ) : """Gets the range of years that we need to use as keys to get metrics from redis ."""
dates = [ metric_date ] end_date = metric_date + delta # Figure out how many years our metric range spans spanning_years = end_date . year - metric_date . year for i in range ( spanning_years ) : # for the weekly keys , we only care about the year dates . append ( datetime . date ( year = metric_date . year + ( i +...
def first_from_generator ( generator ) : """Pull the first value from a generator and return it , closing the generator : param generator : A generator , this will be mapped onto a list and the first item extracted . : return : None if there are no items , or the first item otherwise . : internal :"""
try : result = next ( generator ) except StopIteration : result = None finally : generator . close ( ) return result
def subscribe ( obj , event , callback , event_state = None ) : """Subscribe an event from an class . Subclasses of the class / object will also fire events for this class , unless a more specific event exists ."""
if inspect . isclass ( obj ) : cls = obj . __name__ else : cls = obj . __class__ . __name__ if event_state is None : event_state = states . ANY event_key = '.' . join ( [ cls , event , event_state ] ) if event_key not in EVENT_HANDLERS : EVENT_HANDLERS [ event_key ] = [ ] EVENT_HANDLERS [ event_key ] . ...
def put_data ( up_token , key , data , params = None , mime_type = 'application/octet-stream' , check_crc = False , progress_handler = None , fname = None ) : """上传二进制流到七牛 Args : up _ token : 上传凭证 key : 上传文件名 data : 上传二进制流 params : 自定义变量 , 规格参考 http : / / developer . qiniu . com / docs / v6 / api / overvi...
final_data = '' if hasattr ( data , 'read' ) : while True : tmp_data = data . read ( config . _BLOCK_SIZE ) if len ( tmp_data ) == 0 : break else : final_data += tmp_data else : final_data = data crc = crc32 ( final_data ) return _form_put ( up_token , key , final...
def get_command_header ( parser , usage_message = "" , usage = False ) : """Return the command line header : param parser : : param usage _ message : : param usage : : return : The command header"""
loader = template . Loader ( os . path . join ( firenado . conf . ROOT , 'management' , 'templates' , 'help' ) ) return loader . load ( "header.txt" ) . generate ( parser = parser , usage_message = usage_message , usage = usage , firenado_version = "." . join ( map ( str , firenado . __version__ ) ) ) . decode ( sys . ...
def down_ec2 ( instance_id , region , access_key_id , secret_access_key ) : """shutdown of an existing EC2 instance"""
conn = connect_to_ec2 ( region , access_key_id , secret_access_key ) # get the instance _ id from the state file , and stop the instance instance = conn . stop_instances ( instance_ids = instance_id ) [ 0 ] while instance . state != "stopped" : log_yellow ( "Instance state: %s" % instance . state ) sleep ( 10 )...
def randomize_graph_partial_und ( A , B , maxswap , seed = None ) : '''A = RANDOMIZE _ GRAPH _ PARTIAL _ UND ( A , B , MAXSWAP ) takes adjacency matrices A and B and attempts to randomize matrix A by performing MAXSWAP rewirings . The rewirings will avoid any spots where matrix B is nonzero . Parameters A...
rng = get_rng ( seed ) A = A . copy ( ) i , j = np . where ( np . triu ( A , 1 ) ) i . setflags ( write = True ) j . setflags ( write = True ) m = len ( i ) nswap = 0 while nswap < maxswap : while True : e1 , e2 = rng . randint ( m , size = ( 2 , ) ) while e1 == e2 : e2 = rng . randint (...
def on_done ( self ) : """Reimplemented from : meth : ` ~ AsyncViewBase . on _ done `"""
if self . _d : self . _d . callback ( self ) self . _d = None
def get_related ( self ) : '''get ore : aggregates for this resource , optionally retrieving resource payload Args : retrieve ( bool ) : if True , issue . refresh ( ) on resource thereby confirming existence and retrieving payload'''
if self . exists and hasattr ( self . rdf . triples , 'ore' ) and hasattr ( self . rdf . triples . ore , 'aggregates' ) : related = [ self . repo . parse_uri ( uri ) for uri in self . rdf . triples . ore . aggregates ] # return return related else : return [ ]
def for_branch ( self , branch ) : """Return a new CourseLocator for another branch of the same library ( also version agnostic )"""
if self . org is None and branch is not None : raise InvalidKeyError ( self . __class__ , "Branches must have full library ids not just versions" ) return self . replace ( branch = branch , version_guid = None )
def refreshRecords ( self ) : """Refreshes the records being loaded by this browser ."""
table_type = self . tableType ( ) if ( not table_type ) : self . _records = RecordSet ( ) return False search = nativestring ( self . uiSearchTXT . text ( ) ) query = self . query ( ) . copy ( ) terms , search_query = Q . fromSearch ( search ) if ( search_query ) : query &= search_query self . _records = ta...
def _update_transform_subject ( Xi , Si , R ) : """Updates the mappings ` W _ i ` for one subject . Parameters Xi : array , shape = [ voxels , timepoints ] The fMRI data : math : ` X _ i ` for aligning the subject . Si : array , shape = [ voxels , timepoints ] The individual component : math : ` S _ i ` f...
A = Xi . dot ( R . T ) A -= Si . dot ( R . T ) # Solve the Procrustes problem U , _ , V = np . linalg . svd ( A , full_matrices = False ) return U . dot ( V )
def dispatch ( self , * args , ** kwargs ) : """This decorator sets this view to have restricted permissions ."""
return super ( BreedingUpdate , self ) . dispatch ( * args , ** kwargs )
def web_error_and_result ( f ) : """Same as error _ and _ result decorator , except : If no exception was raised during task execution , ONLY IN CASE OF WEB REQUEST formats task result into json dictionary { ' data ' : task return value }"""
@ wraps ( f ) def web_error_and_result_decorator ( * args , ** kwargs ) : return error_and_result_decorator_inner_fn ( f , True , * args , ** kwargs ) return web_error_and_result_decorator
def tickets_list ( self , external_id = None , include = None , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / tickets # json - format"
api_path = "/api/v2/tickets.json" api_query = { } if "query" in kwargs . keys ( ) : api_query . update ( kwargs [ "query" ] ) del kwargs [ "query" ] if external_id : api_query . update ( { "external_id" : external_id , } ) if include : api_query . update ( { "include" : include , } ) return self . call ...
def update_params_for_auth ( self , headers , querys , auth_settings ) : """Updates header and query params based on authentication setting . : param headers : Header parameters dict to be updated . : param querys : Query parameters tuple list to be updated . : param auth _ settings : Authentication setting i...
if not auth_settings : return for auth in auth_settings : auth_setting = self . configuration . auth_settings ( ) . get ( auth ) if auth_setting : if not auth_setting [ 'value' ] : continue elif auth_setting [ 'in' ] == 'header' : headers [ auth_setting [ 'key' ] ] = ...
def _iplot ( self , kind = 'scatter' , data = None , layout = None , filename = '' , sharing = None , title = '' , xTitle = '' , yTitle = '' , zTitle = '' , theme = None , colors = None , colorscale = None , fill = False , width = None , dash = 'solid' , mode = '' , interpolation = 'linear' , symbol = 'circle' , size =...
# Valid Kwargs valid_kwargs = [ 'color' , 'opacity' , 'column' , 'columns' , 'labels' , 'text' , 'world_readable' , 'colorbar' ] BUBBLE_KWARGS = [ 'abs_size' ] TRACE_KWARGS = [ 'hoverinfo' , 'connectgaps' ] HEATMAP_SURFACE_KWARGS = [ 'center_scale' , 'zmin' , 'zmax' ] PIE_KWARGS = [ 'sort' , 'pull' , 'hole' , 'textposi...
def set_html ( self , html , url = None ) : """Sets custom HTML in our Webkit session and allows to specify a fake URL . Scripts and CSS is dynamically fetched as if the HTML had been loaded from the given URL ."""
if url : self . conn . issue_command ( 'SetHtml' , html , url ) else : self . conn . issue_command ( 'SetHtml' , html )
def node_from_nid ( self , nid ) : """Return the node in the ` Flow ` with the given ` nid ` identifier"""
for node in self . iflat_nodes ( ) : if node . node_id == nid : return node raise ValueError ( "Cannot find node with node id: %s" % nid )
def validate ( cls ) : """Make sure , that conspect element is properly selected . If not , show error ."""
if cls . get_dict ( ) : cls . show_error ( False ) return True cls . show_error ( True ) return False
def image_similarity ( fixed_image , moving_image , metric_type = 'MeanSquares' , fixed_mask = None , moving_mask = None , sampling_strategy = 'regular' , sampling_percentage = 1. ) : """Measure similarity between two images ANTsR function : ` imageSimilarity ` Arguments fixed : ANTsImage the fixed image ...
metric = mio2 . create_ants_metric ( fixed_image , moving_image , metric_type , fixed_mask , moving_mask , sampling_strategy , sampling_percentage ) return metric . get_value ( )
def start_active_span ( self , operation_name , child_of = None , references = None , tags = None , start_time = None , ignore_active_span = False , finish_on_close = True ) : """Returns a newly started and activated : class : ` Scope ` . The returned : class : ` Scope ` supports with - statement contexts . For ...
return self . _noop_scope
def find_one ( self , cls , id ) : """Find single keyed row - as per the gludb spec ."""
found = self . find_by_index ( cls , 'id' , id ) return found [ 0 ] if found else None
def run_lldptool ( self , args ) : """Function for invoking the lldptool utility ."""
full_args = [ 'lldptool' ] + args try : utils . execute ( full_args , root_helper = self . root_helper ) except Exception as e : LOG . error ( "Unable to execute %(cmd)s. " "Exception: %(exception)s" , { 'cmd' : full_args , 'exception' : e } )
def _read_plain_json ( file_path , check_bse ) : """Reads a JSON file A simple wrapper around json . load that only takes the file name If the file does not exist , an exception is thrown . If the file does exist , but there is a problem with the JSON formatting , the filename is added to the exception info...
if not os . path . isfile ( file_path ) : raise FileNotFoundError ( 'JSON file \'{}\' does not exist, is not ' 'readable, or is not a file' . format ( file_path ) ) try : if file_path . endswith ( '.bz2' ) : with bz2 . open ( file_path , 'rt' , encoding = _default_encoding ) as f : js = json...
def _write_bin ( self , data , stream , byte_order ) : '''Write data to a binary stream .'''
_write_array ( stream , _np . dtype ( self . dtype ( byte_order ) ) . type ( data ) )
def edit_service ( self , loadbal_id , service_id , ip_address_id = None , port = None , enabled = None , hc_type = None , weight = None ) : """Edits an existing service properties . : param int loadbal _ id : The id of the loadbal where the service resides : param int service _ id : The id of the service to ed...
_filter = { 'virtualServers' : { 'serviceGroups' : { 'services' : { 'id' : utils . query_filter ( service_id ) } } } } mask = 'serviceGroups[services[groupReferences,healthChecks]]' virtual_servers = self . lb_svc . getVirtualServers ( id = loadbal_id , filter = _filter , mask = mask ) for service in virtual_servers [ ...
def get_treasury_yield ( start = None , end = None , period = '3MO' ) : """Load treasury yields from FRED . Parameters start : date , optional Earliest date to fetch data for . Defaults to earliest date available . end : date , optional Latest date to fetch data for . Defaults to latest date available...
if start is None : start = '1/1/1970' if end is None : end = _1_bday_ago ( ) treasury = web . DataReader ( "DGS3{}" . format ( period ) , "fred" , start , end ) treasury = treasury . ffill ( ) return treasury
def _urls_for_js ( urls = None ) : """Return templated URLs prepared for javascript ."""
if urls is None : # prevent circular import from . urls import urlpatterns urls = [ url . name for url in urlpatterns if getattr ( url , 'name' , None ) ] urls = dict ( zip ( urls , [ get_uri_template ( url ) for url in urls ] ) ) urls . update ( getattr ( settings , 'LEAFLET_STORAGE_EXTRA_URLS' , { } ) ) retur...
def parse ( self , data , length , version = 1 ) : """Parses this tag"""
self . characterId = data . readUI16 ( ) self . depth = data . readUI16 ( )
def touch ( args ) : """% prog touch timestamp . info Recover timestamps for files in the current folder . CAUTION : you must execute this in the same directory as timestamp ( ) ."""
from time import ctime p = OptionParser ( touch . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) info , = args fp = open ( info ) for row in fp : path , atime , mtime = row . split ( ) atime = float ( atime ) mtime = float ( mtime ) curre...
def get_api_publisher ( self , social_user ) : """and other https : / / vk . com / dev . php ? method = wall . post"""
def _post ( ** kwargs ) : api = self . get_api ( social_user ) from pudb import set_trace ; set_trace ( ) # api . group . getInfo ( ' uids ' = ' your _ group _ id ' , ' fields ' = ' members _ count ' ) # response = api . wall . post ( * * kwargs ) return response return _post
def listGetRawString ( self , doc , inLine ) : """Builds the string equivalent to the text contained in the Node list made of TEXTs and ENTITY _ REFs , contrary to xmlNodeListGetString ( ) this function doesn ' t do any character encoding handling ."""
if doc is None : doc__o = None else : doc__o = doc . _o ret = libxml2mod . xmlNodeListGetRawString ( doc__o , self . _o , inLine ) return ret
def track ( self , thread_id , frame , frame_id_to_lineno , frame_custom_thread_id = None ) : ''': param thread _ id : The thread id to be used for this frame . : param frame : The topmost frame which is suspended at the given thread . : param frame _ id _ to _ lineno : If available , the line number for ...
with self . _lock : coroutine_or_main_thread_id = frame_custom_thread_id or thread_id if coroutine_or_main_thread_id in self . _suspended_frames_manager . _thread_id_to_tracker : sys . stderr . write ( 'pydevd: Something is wrong. Tracker being added twice to the same thread id.\n' ) self . _suspend...
def set_basic_selection ( self , selection , value , fields = None ) : """Modify data for an item or region of the array . Parameters selection : tuple An integer index or slice or tuple of int / slice specifying the requested region for each dimension of the array . value : scalar or array - like Value...
# guard conditions if self . _read_only : err_read_only ( ) # refresh metadata if not self . _cache_metadata : self . _load_metadata_nosync ( ) # handle zero - dimensional arrays if self . _shape == ( ) : return self . _set_basic_selection_zd ( selection , value , fields = fields ) else : return self . ...
def rdpcap ( filename , count = - 1 ) : """Read a pcap file and return a packet list count : read only < count > packets"""
with PcapReader ( filename ) as pcap : return pcap . read_all ( count = count )
def verify ( self , chksum ) : """verify : 1 byte - > boolean verify checksums the frame , adds the expected checksum , and determines whether the result is correct . The result should be 0xFF ."""
total = 0 # Add together all bytes for byte in self . data : total += byteToInt ( byte ) # Add checksum too total += byteToInt ( chksum ) # Only keep low bits total &= 0xFF # Check result return total == 0xFF
def deviance ( self , endog , mu , freq_weights = 1 , scale = 1. , axis = None ) : r'''Deviance function for either Bernoulli or Binomial data . Parameters endog : array - like Endogenous response variable ( already transformed to a probability if appropriate ) . mu : array Fitted mean response variable...
if np . shape ( self . n ) == ( ) and self . n == 1 : one = np . equal ( endog , 1 ) return - 2 * np . sum ( ( one * np . log ( mu + 1e-200 ) + ( 1 - one ) * np . log ( 1 - mu + 1e-200 ) ) * freq_weights , axis = axis ) else : return 2 * np . sum ( self . n * freq_weights * ( endog * np . log ( endog / mu +...
def _setupDefaultParamList ( self ) : """This creates self . defaultParamList . It also does some checks on the paramList , sets its order if needed , and deletes any extra or unknown pars if found . We assume the order of self . defaultParamList is the correct order ."""
# Obtain the default parameter list self . defaultParamList = self . _taskParsObj . getDefaultParList ( ) theParamList = self . _taskParsObj . getParList ( ) # Lengths are probably equal but this isn ' t necessarily an error # here , so we check for differences below . if len ( self . defaultParamList ) != len ( thePar...
def calculate ( self , film , substrate , elasticity_tensor = None , film_millers = None , substrate_millers = None , ground_state_energy = 0 , lowest = False ) : """Finds all topological matches for the substrate and calculates elastic strain energy and total energy for the film if elasticity tensor and ground...
self . film = film self . substrate = substrate # Generate miller indicies if none specified for film if film_millers is None : film_millers = sorted ( get_symmetrically_distinct_miller_indices ( self . film , self . film_max_miller ) ) # Generate miller indicies if none specified for substrate if substrate_millers...
def load_k40_coincidences_from_rootfile ( filename , dom_id ) : """Load k40 coincidences from JMonitorK40 ROOT file Parameters filename : root file produced by JMonitorK40 dom _ id : DOM ID Returns data : numpy array of coincidences dom _ weight : weight to apply to coincidences to get rate in Hz"""
from ROOT import TFile root_file_monitor = TFile ( filename , "READ" ) dom_name = str ( dom_id ) + ".2S" histo_2d_monitor = root_file_monitor . Get ( dom_name ) data = [ ] for c in range ( 1 , histo_2d_monitor . GetNbinsX ( ) + 1 ) : combination = [ ] for b in range ( 1 , histo_2d_monitor . GetNbinsY ( ) + 1 ) ...
def eval ( self , data , data_store , * , exclude = None ) : """Return a new object in which callable parameters have been evaluated . Native types are not touched and simply returned , while callable methods are executed and their return value is returned . Args : data ( MultiTaskData ) : The data object t...
exclude = [ ] if exclude is None else exclude result = { } for key , value in self . items ( ) : if key in exclude : continue if value is not None and callable ( value ) : result [ key ] = value ( data , data_store ) else : result [ key ] = value return TaskParameters ( result )
def parse_string ( self ) : """Parse a regular unquoted string from the token stream ."""
aliased_value = LITERAL_ALIASES . get ( self . current_token . value . lower ( ) ) if aliased_value is not None : return aliased_value return String ( self . current_token . value )
def ip_dns_dom_name_domain_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ip = ET . SubElement ( config , "ip" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" ) dns = ET . SubElement ( ip , "dns" , xmlns = "urn:brocade.com:mgmt:brocade-ip-administration" ) dom_name = ET . SubElement ( dns , "dom-name" ) domain_name = ET . SubElement ( dom_name , "domain...
def _clear_policy ( self , lambda_name ) : """Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates ."""
try : policy_response = self . lambda_client . get_policy ( FunctionName = lambda_name ) if policy_response [ 'ResponseMetadata' ] [ 'HTTPStatusCode' ] == 200 : statement = json . loads ( policy_response [ 'Policy' ] ) [ 'Statement' ] for s in statement : delete_response = self . lam...
def prepare_gold ( ctx , annotations , gout ) : """Prepare bc - evaluate gold file from annotations supplied by CHEMDNER ."""
click . echo ( 'chemdataextractor.chemdner.prepare_gold' ) for line in annotations : pmid , ta , start , end , text , category = line . strip ( ) . split ( '\t' ) gout . write ( '%s\t%s:%s:%s\n' % ( pmid , ta , start , end ) )
def settle_order ( self ) : """交易前置结算 1 . 回测 : 交易队列清空 , 待交易队列标记SETTLE 2 . 账户每日结算 3 . broker结算更新"""
if self . if_start_orderthreading : self . order_handler . run ( QA_Event ( event_type = BROKER_EVENT . SETTLE , event_queue = self . trade_engine . kernels_dict [ 'ORDER' ] . queue ) )
def load_training_roidbs ( self , names ) : """Args : names ( list [ str ] ) : name of the training datasets , e . g . [ ' train2014 ' , ' valminusminival2014 ' ] Returns : roidbs ( list [ dict ] ) : Produce " roidbs " as a list of dict , each dict corresponds to one image with k > = 0 instances . and the...
return COCODetection . load_many ( cfg . DATA . BASEDIR , names , add_gt = True , add_mask = cfg . MODE_MASK )
def generate_to ( self , worksheet , row ) : '''Generate row report . Generates a row report of the item represented by this instance and inserts it into a given worksheet at a specified row number . : param worksheet : Reference to a worksheet in which to insert row report . : param row : Row number .'''
super ( ItemImage , self ) . generate_to ( worksheet , row ) embedded = False fmt = self . generator . formats worksheet . write ( row , 3 , "image" , fmt [ 'type_image' ] ) worksheet . write_url ( row , 5 , self . data [ 0 ] , fmt [ 'link' ] ) try : if self . data : image = self . resize_image ( StringIO (...
def assign_assessment_offered_to_bank ( self , assessment_offered_id , bank_id ) : """Adds an existing ` ` AssessmentOffered ` ` to a ` ` Bank ` ` . arg : assessment _ offered _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` AssessmentOffered ` ` arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the `...
# Implemented from template for # osid . resource . ResourceBinAssignmentSession . assign _ resource _ to _ bin mgr = self . _get_provider_manager ( 'ASSESSMENT' , local = True ) lookup_session = mgr . get_bank_lookup_session ( proxy = self . _proxy ) lookup_session . get_bank ( bank_id ) # to raise NotFound self . _as...
def _format_url ( handler , host = None , core_name = None , extra = None ) : '''PRIVATE METHOD Formats the URL based on parameters , and if cores are used or not handler : str The request handler to hit . host : str ( None ) The solr host to query . _ _ opts _ _ [ ' host ' ] is default core _ name : st...
extra = [ ] if extra is None else extra if _get_none_or_value ( host ) is None or host == 'None' : host = __salt__ [ 'config.option' ] ( 'solr.host' ) port = __salt__ [ 'config.option' ] ( 'solr.port' ) baseurl = __salt__ [ 'config.option' ] ( 'solr.baseurl' ) if _get_none_or_value ( core_name ) is None : if no...
def json_2_injector_component ( json_obj ) : """transform the JSON return by Ariane server to local object : param json _ obj : the JSON returned by Ariane server : return : a new InjectorCachedComponent"""
LOGGER . debug ( "InjectorCachedComponent.json_2_injector_component" ) return InjectorCachedComponent ( component_id = json_obj [ 'componentId' ] , component_name = json_obj [ 'componentName' ] , component_type = json_obj [ 'componentType' ] , component_admin_queue = json_obj [ 'componentAdminQueue' ] , refreshing = js...
def items ( self ) : """Schema or a list of schemas describing particular elements of the object . A single schema applies to all the elements . Each element of the object must match that schema . A list of schemas describes particular elements of the object ."""
value = self . _schema . get ( "items" , { } ) if not isinstance ( value , ( list , dict ) ) : raise SchemaError ( "items value {0!r} is neither a list nor an object" . format ( value ) ) return value
def record ( self ) : # type : ( ) - > bytes '''Generate a string representing the Rock Ridge Rock Ridge record . Parameters : None . Returns : String containing the Rock Ridge record .'''
if not self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'RR record not yet initialized!' ) return b'RR' + struct . pack ( '=BBB' , RRRRRecord . length ( ) , SU_ENTRY_VERSION , self . rr_flags )
def _readClusterSettings ( self ) : """Read the current instance ' s meta - data to get the cluster settings ."""
# get the leader metadata mdUrl = "http://169.254.169.254/metadata/instance?api-version=2017-08-01" header = { 'Metadata' : 'True' } request = urllib . request . Request ( url = mdUrl , headers = header ) response = urllib . request . urlopen ( request ) data = response . read ( ) dataStr = data . decode ( "utf-8" ) me...
def GetShowDetails ( self ) : """Extract show name , season number and episode number from file name . Supports formats S < NUM > E < NUM > or < NUM > x < NUM > for season and episode numbers where letters are case insensitive and number can be one or more digits . It expects season number to be unique howeve...
fileName = os . path . splitext ( os . path . basename ( self . fileInfo . origPath ) ) [ 0 ] # Episode Number episodeNumSubstring = set ( re . findall ( "(?<=[0-9])[xXeE][0-9]+(?:[xXeE_.-][0-9]+)*" , fileName ) ) if len ( episodeNumSubstring ) != 1 : goodlogging . Log . Info ( "TVFILE" , "Incompatible filename no ...
def south_field_triple ( self ) : "Returns a suitable description of this field for South ."
from south . modelsinspector import introspector field_class = "django.db.models.fields.CharField" args , kwargs = introspector ( self ) return ( field_class , args , kwargs )
def list ( self , params = None , headers = None ) : """List creditor bank accounts . Returns a [ cursor - paginated ] ( # api - usage - cursor - pagination ) list of your creditor bank accounts . Args : params ( dict , optional ) : Query string parameters . Returns : CreditorBankAccount"""
path = '/creditor_bank_accounts' response = self . _perform_request ( 'GET' , path , params , headers , retry_failures = True ) return self . _resource_for ( response )
def delta_decode ( in_array ) : """A function to delta decode an int array . : param in _ array : the input array of integers : return the decoded array"""
if len ( in_array ) == 0 : return [ ] this_ans = in_array [ 0 ] out_array = [ this_ans ] for i in range ( 1 , len ( in_array ) ) : this_ans += in_array [ i ] out_array . append ( this_ans ) return out_array
def get_by ( self , field , value ) : """Gets all drive enclosures that match the filter . The search is case - insensitive . Args : Field : field name to filter . Value : value to filter . Returns : list : A list of drive enclosures ."""
return self . _client . get_by ( field = field , value = value )
def _insert_post_complete_tasks ( context ) : """Insert the event ' s asyncs and cleanup tasks ."""
logging . debug ( "Context %s is complete." , context . id ) # Async event handlers context . exec_event_handler ( 'complete' , transactional = True ) # Insert cleanup tasks try : # TODO : If tracking results we may not want to auto cleanup and instead # wait until the results have been accessed . from furious . as...
def post_process ( self , settings ) : """Perform post processing methods on settings according to their definition in manifest . Post process methods are implemented in their own method that have the same signature : * Get arguments : Current settings , item name and item value ; * Return item value poss...
for k in settings : # Search for post process rules for setting in manifest if k in self . settings_manifesto and self . settings_manifesto [ k ] . get ( 'postprocess' , None ) is not None : rules = self . settings_manifesto [ k ] [ 'postprocess' ] # Chain post process rules from each setting ...
def GetRowMatch ( self , attributes ) : """Returns the row number that matches the supplied attributes ."""
for row in self . compiled : try : for key in attributes : # Silently skip attributes not present in the index file . # pylint : disable = E1103 if ( key in row . header and row [ key ] and not row [ key ] . match ( attributes [ key ] ) ) : # This line does not match , so break and try n...
def list_of_list ( self ) : """This will convert the data from a list of dict to a list of list : return : list of dict"""
ret = [ [ row . get ( key , '' ) for key in self . _col_names ] for row in self ] return ReprListList ( ret , col_names = self . _col_names , col_types = self . _col_types , width_limit = self . _width_limit , digits = self . _digits , convert_unicode = self . _convert_unicode )
def query_pager_by_kind ( kind , current_page_num = 1 ) : '''Query pager'''
return TabWiki . select ( ) . where ( TabWiki . kind == kind ) . order_by ( TabWiki . time_create . desc ( ) ) . paginate ( current_page_num , CMS_CFG [ 'list_num' ] )
def take_control ( self ) : """This function is a better documented and touched up version of the posix _ shell function found in the interactive . py demo script that ships with Paramiko ."""
if has_termios : # Get attributes of the shell you were in before going to the # new one original_tty = termios . tcgetattr ( sys . stdin ) try : tty . setraw ( sys . stdin . fileno ( ) ) tty . setcbreak ( sys . stdin . fileno ( ) ) # We must set the timeout to 0 so that we can bypass ti...
def record_variant_id ( record ) : """Get variant ID from pyvcf . model . _ Record"""
if record . ID : return record . ID else : return record . CHROM + ':' + str ( record . POS )
def nm2lt7 ( short_nm : float , long_nm : float , step_cminv : float = 20 ) -> Tuple [ float , float , float ] : """converts wavelength in nm to cm ^ - 1 minimum meaningful step is 20 , but 5 is minimum before crashing lowtran short : shortest wavelength e . g . 200 nm long : longest wavelength e . g . 30000 ...
short = 1e7 / short_nm long = 1e7 / long_nm N = int ( np . ceil ( ( short - long ) / step_cminv ) ) + 1 # yes , ceil return short , long , N
def user_parse ( data ) : """Parse information from the provider ."""
yield 'id' , data . get ( 'id' ) yield 'username' , data . get ( 'username' ) yield 'discriminator' , data . get ( 'discriminator' ) yield 'picture' , "https://cdn.discordapp.com/avatars/{}/{}.png" . format ( data . get ( 'id' ) , data . get ( 'avatar' ) )
def track ( context , file_names ) : """Keep track of each file in list file _ names . Tracking does not create or delete the actual file , it only tells the version control system whether to maintain versions ( to keep track ) of the file ."""
context . obj . find_repo_type ( ) for fn in file_names : context . obj . call ( [ context . obj . vc_name , 'add' , fn ] )
def set_env_or_defaults ( self ) : """Read some environment variables and set them on the config . If no environment variable is found and the config section / key is empty , then set some default values ."""
option = namedtuple ( 'Option' , [ 'section' , 'name' , 'env_var' , 'default_value' ] ) options = [ option ( 'auth' , 'user' , 'NAPPS_USER' , None ) , option ( 'auth' , 'token' , 'NAPPS_TOKEN' , None ) , option ( 'napps' , 'api' , 'NAPPS_API_URI' , 'https://napps.kytos.io/api/' ) , option ( 'napps' , 'repo' , 'NAPPS_RE...
def decode ( model , tokens , start_token , end_token , pad_token , max_len = 10000 , max_repeat = 10 , max_repeat_block = 10 ) : """Decode with the given model and input tokens . : param model : The trained model . : param tokens : The input tokens of encoder . : param start _ token : The token that represen...
is_single = not isinstance ( tokens [ 0 ] , list ) if is_single : tokens = [ tokens ] batch_size = len ( tokens ) decoder_inputs = [ [ start_token ] for _ in range ( batch_size ) ] outputs = [ None for _ in range ( batch_size ) ] output_len = 1 while len ( list ( filter ( lambda x : x is None , outputs ) ) ) > 0 : ...