signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def save_arguments ( module_name , elements ) : """Recursively save arguments name and default value ."""
for elem , signature in elements . items ( ) : if isinstance ( signature , dict ) : # Submodule case save_arguments ( module_name + ( elem , ) , signature ) else : # use introspection to get the Python obj try : themodule = __import__ ( "." . join ( module_name ) ) obj = ...
def get_invoices_per_page ( self , per_page = 1000 , page = 1 , params = None ) : """Get invoices per page : param per _ page : How many objects per page . Default : 1000 : param page : Which page . Default : 1 : param params : Search parameters . Default : { } : return : list"""
return self . _get_resource_per_page ( resource = INVOICES , per_page = per_page , page = page , params = params )
def close ( self ) : """Close socket ( s )"""
if isinstance ( self . c , dict ) : for client in self . c . values ( ) : client . sock . close ( ) return self . c . socket . close ( )
def write_title ( self , title : str , title_color : str = YELLOW , hyphen_line_color : str = WHITE ) : """Prints title with hyphen line underneath it . : param title : The title to print . : param title _ color : The title text color ( default is yellow ) . : param hyphen _ line _ color : The hyphen line col...
self . write_line ( title_color + title ) self . write_line ( hyphen_line_color + '=' * ( len ( title ) + 3 ) )
def get_sequence_rules_for_assessment ( self , assessment_id ) : """Gets a ` ` SequenceRuleList ` ` for an entire assessment . arg : assessment _ id ( osid . id . Id ) : an assessment ` ` Id ` ` return : ( osid . assessment . authoring . SequenceRuleList ) - the returned ` ` SequenceRule ` ` list raise : Nu...
# First , recursively get all the partIds for the assessment def get_all_children_part_ids ( part ) : child_ids = [ ] if part . has_children ( ) : child_ids = list ( part . get_child_assessment_part_ids ( ) ) for child in part . get_child_assessment_parts ( ) : child_ids += get_all_c...
def sign ( self , msg , key ) : """Create a signature over a message as defined in RFC7515 using an Elliptic curve key : param msg : The message : param key : An ec . EllipticCurvePrivateKey instance : return :"""
if not isinstance ( key , ec . EllipticCurvePrivateKey ) : raise TypeError ( "The private key must be an instance of " "ec.EllipticCurvePrivateKey" ) self . _cross_check ( key . public_key ( ) ) num_bits = key . curve . key_size num_bytes = ( num_bits + 7 ) // 8 asn1sig = key . sign ( msg , ec . ECDSA ( self . hash...
def _setup_authentication ( self , username , password ) : '''Create the authentication object with the given credentials .'''
# # BUG WORKAROUND if self . version < 1.1 : # Version 1.0 had a bug when using the key parameter . # Later versions have the opposite bug ( a key in the username doesn ' t function ) if not username : username = self . _key self . _key = None if not username : return if not password : passw...
def _compute_ranks ( X , winsorize = False , truncation = None , verbose = True ) : """Transform each column into ranked data . Tied ranks are averaged . Ranks can optionally be winsorized as described in Liu 2009 otherwise this returns Tsukahara ' s scaled rank based Z - estimator . Parameters X : array - ...
n_samples , n_features = X . shape Xrank = np . zeros ( shape = X . shape ) if winsorize : if truncation is None : truncation = 1 / ( 4 * np . power ( n_samples , 0.25 ) * np . sqrt ( np . pi * np . log ( n_samples ) ) ) elif truncation > 1 : truncation = np . min ( 1.0 , truncation ) for col in...
def _apply_dvs_product_info ( product_info_spec , product_info_dict ) : '''Applies the values of the product _ info _ dict dictionary to a product info spec ( vim . DistributedVirtualSwitchProductSpec )'''
if product_info_dict . get ( 'name' ) : product_info_spec . name = product_info_dict [ 'name' ] if product_info_dict . get ( 'vendor' ) : product_info_spec . vendor = product_info_dict [ 'vendor' ] if product_info_dict . get ( 'version' ) : product_info_spec . version = product_info_dict [ 'version' ]
def rsem ( job , job_vars ) : """Runs RSEM to produce counts job _ vars : tuple Tuple of dictionaries : input _ args and ids"""
input_args , ids = job_vars work_dir = job . fileStore . getLocalTempDir ( ) cpus = input_args [ 'cpu_count' ] sudo = input_args [ 'sudo' ] single_end_reads = input_args [ 'single_end_reads' ] # I / O filtered_bam , rsem_ref = return_input_paths ( job , work_dir , ids , 'filtered.bam' , 'rsem_ref.zip' ) subprocess . ch...
def parse ( self , elt , ps ) : '''processContents - - ' lax ' | ' skip ' | ' strict ' , ' strict ' 1 ) if ' skip ' check namespaces , and return the DOM node . 2 ) if ' lax ' look for declaration , or definition . If not found return DOM node . 3 ) if ' strict ' get declaration , or raise .'''
skip = self . processContents == 'skip' nspname , pname = _get_element_nsuri_name ( elt ) what = GED ( nspname , pname ) if not skip and what is not None : pyobj = what . parse ( elt , ps ) try : pyobj . typecode = what except AttributeError , ex : # Assume this means builtin type . pyobj = ...
def slice ( self , tf_tensor , tensor_shape ) : """" Slice out the corresponding part of tensor given the pnum variable ."""
tensor_layout = self . tensor_layout ( tensor_shape ) if tensor_layout . is_fully_replicated : return self . LaidOutTensor ( [ tf_tensor ] ) else : slice_shape = self . slice_shape ( tensor_shape ) slice_begins = [ self . slice_begin ( tensor_shape , pnum ) for pnum in xrange ( self . size ) ] slice_beg...
def private_ips_absent ( name , network_interface_name = None , network_interface_id = None , private_ip_addresses = None , region = None , key = None , keyid = None , profile = None ) : '''Ensure an ENI does not have secondary private ip addresses associated with it name ( String ) - State definition name ne...
if not salt . utils . data . exactly_one ( ( network_interface_name , network_interface_id ) ) : raise SaltInvocationError ( "Exactly one of 'network_interface_name', " "'network_interface_id' must be provided" ) if not private_ip_addresses : raise SaltInvocationError ( "You must provide the private_ip_addresse...
def get_last_traded_dt ( self , asset , dt , data_frequency ) : """Given an asset and dt , returns the last traded dt from the viewpoint of the given dt . If there is a trade on the dt , the answer is dt provided ."""
return self . _get_pricing_reader ( data_frequency ) . get_last_traded_dt ( asset , dt )
def solve ( self , S , dimK = None ) : """Compute sparse coding and dictionary update for training data ` S ` ."""
# Use dimK specified in _ _ init _ _ as default if dimK is None and self . dimK is not None : dimK = self . dimK # Start solve timer self . timer . start ( [ 'solve' , 'solve_wo_eval' ] ) # Solve CSC problem on S and do dictionary step self . init_vars ( S , dimK ) self . xstep ( S , self . lmbda , dimK ) self . ds...
def local_self_attention_layer ( hparams , prefix ) : """Create self - attention layer based on hyperparameters ."""
return transformer_layers . LocalSelfAttention ( num_heads = hparams . get ( prefix + "num_heads" ) , num_memory_heads = hparams . get ( prefix + "num_memory_heads" ) , radius = hparams . local_attention_radius , key_value_size = hparams . d_kv , shared_kv = hparams . get ( prefix + "shared_kv" , False ) , attention_kw...
def singleton ( cls , session , include = None ) : """Get the a singleton API resource . Some Helium API resources are singletons . The authorized user and organization for a given API key are examples of this . . . code - block : : python authorized _ user = User . singleton ( session ) will retrieve the...
params = build_request_include ( include , None ) url = session . _build_url ( cls . _resource_path ( ) ) process = cls . _mk_one ( session , singleton = True , include = include ) return session . get ( url , CB . json ( 200 , process ) , params = params )
def unnest ( elem ) : """Flatten an arbitrarily nested iterable : param elem : An iterable to flatten : type elem : : class : ` ~ collections . Iterable ` > > > nested _ iterable = ( 1234 , ( 3456 , 4398345 , ( 234234 ) ) , ( 2396 , ( 23895750 , 9283798 , 29384 , ( 289375983275 , 293759 , 2347 , ( 2098 , 7987...
if isinstance ( elem , Iterable ) and not isinstance ( elem , six . string_types ) : elem , target = tee ( elem , 2 ) else : target = elem for el in target : if isinstance ( el , Iterable ) and not isinstance ( el , six . string_types ) : el , el_copy = tee ( el , 2 ) for sub in unnest ( el_...
def _compile_update_from ( self , query ) : """Compile the " from " clause for an update with a join . : param query : A QueryBuilder instance : type query : QueryBuilder : return : The compiled sql : rtype : str"""
if not query . joins : return "" froms = [ ] for join in query . joins : froms . append ( self . wrap_table ( join . table ) ) if len ( froms ) : return " FROM %s" % ", " . join ( froms ) return ""
def rec_sqrt ( x , context = None ) : """Return the reciprocal square root of x . Return + Inf if x is ± 0 , + 0 if x is + Inf , and NaN if x is negative ."""
return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_rec_sqrt , ( BigFloat . _implicit_convert ( x ) , ) , context , )
def parse ( self , title , pageid = None ) : """Returns Mediawiki action = parse query string"""
qry = self . PARSE . substitute ( WIKI = self . uri , ENDPOINT = self . endpoint , PAGE = safequote ( title ) or pageid ) if pageid and not title : qry = qry . replace ( '&page=' , '&pageid=' ) . replace ( '&redirects' , '' ) if self . variant : qry += '&variant=' + self . variant self . set_status ( 'parse' , ...
def timeline ( self ) : """> > > Cluster ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) . timeline > > > Cluster ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , TimelineHistory . from _ node ( 1 , ' [ ] ' ) ) . timeline > > > Cluster ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , TimelineHistory . from _ node ( 1 , ' [ [ " a " ] ] ' ) ) . timeline"""
if self . history : if self . history . lines : try : return int ( self . history . lines [ - 1 ] [ 0 ] ) + 1 except Exception : logger . error ( 'Failed to parse cluster history from DCS: %s' , self . history . lines ) elif self . history . value == '[]' : return...
def create ( self , attributes = None , ** kwargs ) : """Creates a webhook with given attributes ."""
return super ( WebhooksProxy , self ) . create ( resource_id = None , attributes = attributes )
def bounded_from_config ( cls , cp , section , variable_args , bounds_required = False , additional_opts = None ) : """Returns a bounded distribution based on a configuration file . The parameters for the distribution are retrieved from the section titled " [ ` section ` - ` variable _ args ` ] " in the config ...
tag = variable_args variable_args = variable_args . split ( VARARGS_DELIM ) if additional_opts is None : additional_opts = { } # list of args that are used to construct distribution special_args = [ "name" ] + [ 'min-{}' . format ( arg ) for arg in variable_args ] + [ 'max-{}' . format ( arg ) for arg in variable_a...
def p_sens_egde_paren ( self , p ) : 'senslist : AT LPAREN edgesigs RPAREN'
p [ 0 ] = SensList ( p [ 3 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def _rsaes_oaep_decrypt ( self , C , h = None , mgf = None , L = None ) : """Internal method providing RSAES - OAEP - DECRYPT as defined in Sect . 7.1.2 of RFC 3447 . Not intended to be used directly . Please , see encrypt ( ) method for type " OAEP " . Input : C : ciphertext to be decrypted , an octet stri...
# The steps below are the one described in Sect . 7.1.2 of RFC 3447. # 1 ) Length Checking # 1 . a ) is not done if h is None : h = "sha1" if not h in _hashFuncParams : warning ( "Key._rsaes_oaep_decrypt(): unknown hash function %s." , h ) return None hLen = _hashFuncParams [ h ] [ 0 ] hFun = _hashFuncParam...
def _c0 ( self ) : "the logarithm of normalizing constant in pdf"
h_df = self . df / 2 p , S = self . _p , self . S return h_df * ( logdet ( S ) + p * logtwo ) + lpgamma ( p , h_df )
def getHelp ( arg = None ) : """This function provides interactive manuals and tutorials ."""
if arg == None : print ( '--------------------------------------------------------------' ) print ( 'Hello, this is an interactive help system of HITRANonline API.' ) print ( '--------------------------------------------------------------' ) print ( 'Run getHelp(.) with one of the following arguments:' ...
def _getfield ( self , block , name ) : """Return the field with the given ` name ` from ` block ` . If no field with ` name ` exists in any namespace , raises a KeyError . : param block : xblock to retrieve the field from : type block : : class : ` ~ xblock . core . XBlock ` : param name : name of the fiel...
# First , get the field from the class , if defined block_field = getattr ( block . __class__ , name , None ) if block_field is not None and isinstance ( block_field , Field ) : return block_field # Not in the class , so name # really doesn ' t name a field raise KeyError ( name )
def focus0 ( self ) : '''First focus of the ellipse , Point class .'''
f = Point ( self . center ) if self . xAxisIsMajor : f . x -= self . linearEccentricity else : f . y -= self . linearEccentricity return f
def port_add ( self , dpid , port , mac ) : """: returns : old port if learned . ( this may be = port ) None otherwise"""
old_port = self . mac_to_port [ dpid ] . get ( mac , None ) self . mac_to_port [ dpid ] [ mac ] = port if old_port is not None and old_port != port : LOG . debug ( 'port_add: 0x%016x 0x%04x %s' , dpid , port , haddr_to_str ( mac ) ) return old_port
def get ( self , part ) : """Returns a section of the region as a new region Accepts partitioning constants , e . g . Region . NORTH , Region . NORTH _ WEST , etc . Also accepts an int 200-999: * First digit : Raster ( * n * rows by * n * columns ) * Second digit : Row index ( if equal to raster , gets the ...
if part == self . MID_VERTICAL : return Region ( self . x + ( self . w / 4 ) , y , self . w / 2 , self . h ) elif part == self . MID_HORIZONTAL : return Region ( self . x , self . y + ( self . h / 4 ) , self . w , self . h / 2 ) elif part == self . MID_BIG : return Region ( self . x + ( self . w / 4 ) , sel...
def update_handles ( self , key , axis , element , ranges , style ) : """Update the elements of the plot ."""
self . teardown_handles ( ) plot_data , plot_kwargs , axis_kwargs = self . get_data ( element , ranges , style ) with abbreviated_exception ( ) : handles = self . init_artists ( axis , plot_data , plot_kwargs ) self . handles . update ( handles ) return axis_kwargs
def pipe ( self , texts , as_tuples = False , n_threads = - 1 , batch_size = 1000 , disable = [ ] , cleanup = False , component_cfg = None , ) : """Process texts as a stream , and yield ` Doc ` objects in order . texts ( iterator ) : A sequence of texts to process . as _ tuples ( bool ) : If set to True , input...
if n_threads != - 1 : deprecation_warning ( Warnings . W016 ) if as_tuples : text_context1 , text_context2 = itertools . tee ( texts ) texts = ( tc [ 0 ] for tc in text_context1 ) contexts = ( tc [ 1 ] for tc in text_context2 ) docs = self . pipe ( texts , batch_size = batch_size , disable = disable...
def is_linguist_lookup ( self , lookup ) : """Returns true if the given lookup is a valid linguist lookup ."""
field = utils . get_field_name_from_lookup ( lookup ) # To keep default behavior with " FieldError : Cannot resolve keyword " . if ( field not in self . concrete_field_names and field in self . linguist_field_names ) : return True return False
def eigh_robust ( a , b = None , eigvals = None , eigvals_only = False , overwrite_a = False , overwrite_b = False , turbo = True , check_finite = True ) : """Robustly solve the Hermitian generalized eigenvalue problem This function robustly solves the Hermetian generalized eigenvalue problem ` ` A v = lambda B...
kwargs = dict ( eigvals = eigvals , eigvals_only = eigvals_only , turbo = turbo , check_finite = check_finite , overwrite_a = overwrite_a , overwrite_b = overwrite_b ) # Check for easy case first : if b is None : return linalg . eigh ( a , ** kwargs ) # Compute eigendecomposition of b kwargs_b = dict ( turbo = turb...
def hosts_append ( hostsfile = '/etc/hosts' , ip_addr = None , entries = None ) : '''Append a single line to the / etc / hosts file . CLI Example : . . code - block : : bash salt ' * ' dnsutil . hosts _ append / etc / hosts 127.0.0.1 ad1 . yuk . co , ad2 . yuk . co'''
host_list = entries . split ( ',' ) hosts = parse_hosts ( hostsfile = hostsfile ) if ip_addr in hosts : for host in host_list : if host in hosts [ ip_addr ] : host_list . remove ( host ) if not host_list : return 'No additional hosts were added to {0}' . format ( hostsfile ) append_line = '\...
def _add_child ( self , message ) : """Return a new action with C { message } added as a child . Assumes C { message } is not an end message . @ param message : Either a C { WrittenAction } or a C { WrittenMessage } . @ raise WrongTask : If C { message } has a C { task _ uuid } that differs from the action ...
self . _validate_message ( message ) level = message . task_level return self . transform ( ( '_children' , level ) , message )
def remove_sshkey ( host , known_hosts = None ) : '''Remove a host from the known _ hosts file'''
if known_hosts is None : if 'HOME' in os . environ : known_hosts = '{0}/.ssh/known_hosts' . format ( os . environ [ 'HOME' ] ) else : try : known_hosts = '{0}/.ssh/known_hosts' . format ( pwd . getpwuid ( os . getuid ( ) ) . pwd_dir ) except Exception : pass if kn...
def build_payload_from_queued_messages ( self , use_queue , shutdown_event ) : """build _ payload _ from _ queued _ messages Empty the queued messages by building a large ` ` self . log _ payload ` ` : param use _ queue : queue holding the messages : param shutdown _ event : shutdown event"""
not_done = True while not_done : if self . is_shutting_down ( shutdown_event = shutdown_event ) : self . debug_log ( 'build_payload shutting down' ) return True self . debug_log ( 'reading from queue={}' . format ( str ( use_queue ) ) ) try : msg = use_queue . get ( block = True , ti...
def delete_by_query ( self , indices , doc_types , query , ** query_params ) : """Delete documents from one or more indices and one or more types based on a query ."""
path = self . _make_path ( indices , doc_types , '_query' ) body = { "query" : query . serialize ( ) } return self . _send_request ( 'DELETE' , path , body , query_params )
def value ( self ) : """Get the value of the finished async request , if it is available . : raises CloudUnhandledError : When not checking value of ` error ` or ` is _ done ` first : return : the payload value : rtype : str"""
status_code , error_msg , payload = self . check_error ( ) if not self . _status_ok ( status_code ) and not payload : raise CloudUnhandledError ( "Attempted to decode async request which returned an error." , reason = error_msg , status = status_code ) return self . db [ self . async_id ] [ "payload" ]
def _build_request_url ( self , secure , api_method , version ) : """Build a URL for a API method request"""
if secure : proto = ANDROID . PROTOCOL_SECURE else : proto = ANDROID . PROTOCOL_INSECURE req_url = ANDROID . API_URL . format ( protocol = proto , api_method = api_method , version = version ) return req_url
def filter_response_size ( size ) : """Filter : class : ` . Line ` objects by the response size ( in bytes ) . Specially useful when looking for big file downloads . : param size : Minimum amount of bytes a response body weighted . : type size : string : returns : a function that filters by the response siz...
if size . startswith ( '+' ) : size_value = int ( size [ 1 : ] ) else : size_value = int ( size ) def filter_func ( log_line ) : bytes_read = log_line . bytes_read if bytes_read . startswith ( '+' ) : bytes_read = int ( bytes_read [ 1 : ] ) else : bytes_read = int ( bytes_read ) ...
def add_subsegment ( self , subsegment ) : """Add input subsegment as a child subsegment and increment reference counter and total subsegments counter of the parent segment ."""
super ( Subsegment , self ) . add_subsegment ( subsegment ) self . parent_segment . increment ( )
def _unfuse ( self ) : """Unfuses the fused RNN in to a stack of rnn cells ."""
assert not self . _projection_size , "_unfuse does not support projection layer yet!" assert not self . _lstm_state_clip_min and not self . _lstm_state_clip_max , "_unfuse does not support state clipping yet!" get_cell = { 'rnn_relu' : lambda ** kwargs : rnn_cell . RNNCell ( self . _hidden_size , activation = 'relu' , ...
def setpreferredapi ( api ) : """Set the preferred Qt API . Will raise a RuntimeError if a Qt API was already selected . Note that QT _ API environment variable ( if set ) will take precedence ."""
global __PREFERRED_API if __SELECTED_API is not None : raise RuntimeError ( "A Qt api {} was already selected" . format ( __SELECTED_API ) ) if api . lower ( ) not in { "pyqt4" , "pyqt5" , "pyside" , "pyside2" } : raise ValueError ( api ) __PREFERRED_API = api . lower ( )
def validate ( self , protocol_version , values = None ) : """Validate child value types and values against protocol _ version ."""
if values is None : values = self . values return self . get_schema ( protocol_version ) ( values )
def _get_path_for_type ( type_ ) : """Similar to ` _ get _ path _ for ` but for only type names ."""
if type_ . lower ( ) in CORE_TYPES : return Path ( 'index.html#%s' % type_ . lower ( ) ) elif '.' in type_ : namespace , name = type_ . split ( '.' ) return Path ( 'types' , namespace , _get_file_name ( name ) ) else : return Path ( 'types' , _get_file_name ( type_ ) )
def plot_high_levels_data ( self ) : """Complicated function that draws the high level mean plot on canvas4, draws all specimen , sample , or site interpretations according to the UPPER _ LEVEL _ SHOW variable , draws the fisher mean or fisher mean by polarity of all interpretations displayed , draws sample o...
# self . toolbar4 . home ( ) high_level = self . level_box . GetValue ( ) self . UPPER_LEVEL_NAME = self . level_names . GetValue ( ) self . UPPER_LEVEL_MEAN = self . mean_type_box . GetValue ( ) draw_net ( self . high_level_eqarea ) what_is_it = self . level_box . GetValue ( ) + ": " + self . level_names . GetValue ( ...
def process_ogr2ogr ( self , name , layer , input_path ) : """Process a layer using ogr2ogr ."""
output_path = os . path . join ( TEMP_DIRECTORY , '%s.json' % name ) if os . path . exists ( output_path ) : os . remove ( output_path ) ogr2ogr_cmd = [ 'ogr2ogr' , '-f' , 'GeoJSON' , '-clipsrc' , self . config [ 'bbox' ] ] if 'where' in layer : ogr2ogr_cmd . extend ( [ '-where' , '"%s"' % layer [ 'where' ] ] )...
def start_index ( self ) : """Return the 1 - based index of the first item on this page ."""
paginator = self . paginator # Special case , return zero if no items . if paginator . count == 0 : return 0 elif self . number == 1 : return 1 return ( ( self . number - 2 ) * paginator . per_page + paginator . first_page + 1 )
def parse_yaml ( self , y ) : '''Parse a YAML specification of a target execution context into this object .'''
super ( TargetExecutionContext , self ) . parse_yaml ( y ) if 'id' in y : self . id = y [ 'id' ] else : self . id = '' return self
def add_child ( self , child ) : '''Add child node , and copy all options to it'''
super ( RootNode , self ) . add_child ( child ) child . attr_wrapper = self . attr_wrapper
def joint_plot ( x , y , marginalBins = 50 , gridsize = 50 , plotlimits = None , logscale_cmap = False , logscale_marginals = False , alpha_hexbin = 0.75 , alpha_marginals = 0.75 , cmap = "inferno_r" , marginalCol = None , figsize = ( 8 , 8 ) , fontsize = 8 , * args , ** kwargs ) : """Plots some x and y data using ...
with _plt . rc_context ( { 'font.size' : fontsize , } ) : # definitions for the axes hexbin_marginal_seperation = 0.01 left , width = 0.2 , 0.65 - 0.1 # left = left side of hexbin and hist _ x bottom , height = 0.1 , 0.65 - 0.1 # bottom = bottom of hexbin and hist _ y bottom_h = height + bottom ...
def crypto_bloom_filter ( record , # type : Sequence [ Text ] tokenizers , # type : List [ Callable [ [ Text , Optional [ Text ] ] , Iterable [ Text ] ] ] schema , # type : Schema keys # type : Sequence [ Sequence [ bytes ] ] ) : # type : ( . . . ) - > Tuple [ bitarray , Text , int ] """Computes the composite Bloom...
hash_l = schema . l * 2 ** schema . xor_folds bloomfilter = bitarray ( hash_l ) bloomfilter . setall ( False ) for ( entry , tokenize , field , key ) in zip ( record , tokenizers , schema . fields , keys ) : fhp = field . hashing_properties if fhp : ngrams = list ( tokenize ( field . format_value ( entr...
def options ( self , * args , ** kwargs ) : '''Return CORS headers for preflight requests'''
# Allow X - Auth - Token in requests request_headers = self . request . headers . get ( 'Access-Control-Request-Headers' ) allowed_headers = request_headers . split ( ',' ) # Filter allowed header here if needed . # Allow request headers self . set_header ( 'Access-Control-Allow-Headers' , ',' . join ( allowed_headers ...
def _css_helper ( self ) : """Add CSS links for the current page and for the plugins"""
entries = [ entry for entry in self . _plugin_manager . call_hook ( "css" ) if entry is not None ] # Load javascript for the current page entries += self . _get_ctx ( ) [ "css" ] entries = [ "<link href='" + entry + "' rel='stylesheet'>" for entry in entries ] return "\n" . join ( entries )
def _handle_eio_disconnect ( self , sid ) : """Handle Engine . IO disconnect event ."""
self . _handle_disconnect ( sid , '/' ) if sid in self . environ : del self . environ [ sid ]
def nocomment ( astr , com = '!' ) : """just like the comment in python . removes any text after the phrase ' com '"""
alist = astr . splitlines ( ) for i in range ( len ( alist ) ) : element = alist [ i ] pnt = element . find ( com ) if pnt != - 1 : alist [ i ] = element [ : pnt ] return '\n' . join ( alist )
def push ( self , bot , channel_type , ar , user_id ) : """Use this method to push message to user of bot . The message should be packed into ActionResponse object . This allows to push text messages , buttons , images . This also allows to force current state of user . : param bot : bot that will push user...
self . client . push . __getattr__ ( bot . name ) . __call__ ( _method = "POST" , _params = dict ( id = user_id , channel = channel_type ) , _json = ar . to_json ( ) )
def body ( self ) : """Yields the body of the buffered file ."""
for fp , need_close in self . files : try : name = os . path . basename ( fp . name ) except AttributeError : name = '' for chunk in self . gen_chunks ( self . envelope . file_open ( name ) ) : yield chunk for chunk in self . file_chunks ( fp ) : yield chunk for chunk...
def stop ( opts , bot , event ) : """Usage : stop [ - - name = < name > ] [ - - notify = < slack _ username > ] Stop a timer . _ name _ works the same as for ` start ` . If given _ slack _ username _ , reply with an at - mention to the given user ."""
name = opts [ '--name' ] slack_username = opts [ '--notify' ] now = datetime . datetime . now ( ) delta = now - bot . timers . pop ( name ) response = bot . stop_fmt . format ( delta ) if slack_username : mention = '' # The slack api ( provided by https : / / github . com / os / slacker ) is available on all bo...
def precesion_nutation ( date ) : """Precession / nutation joint rotation matrix for the IAU2010 model"""
X , Y , s = _xys ( date ) d = np . arctan ( np . sqrt ( ( X ** 2 + Y ** 2 ) / ( 1 - X ** 2 - Y ** 2 ) ) ) a = 1 / ( 1 + np . cos ( d ) ) return np . array ( [ [ 1 - a * X ** 2 , - a * X * Y , X ] , [ - a * X * Y , 1 - a * Y ** 2 , Y ] , [ - X , - Y , 1 - a * ( X ** 2 + Y ** 2 ) ] ] ) @ rot3 ( s )
def _is_blacklisted_filename ( filepath ) : """Checks if the filename matches filename _ blacklist blacklist is a list of filenames ( str ) and / or file patterns ( dict ) string , specifying an exact filename to ignore [ " . DS _ Store " , " Thumbs . db " ] mapping ( dict ) , where each dict contains : '...
if not cfg . CONF . filename_blacklist : return False filename = os . path . basename ( filepath ) fname = os . path . splitext ( filename ) [ 0 ] blacklisted = False for fblacklist in cfg . CONF . filename_blacklist : if isinstance ( fblacklist , dict ) : to_check = filename if fblacklist . get...
def app_add_developers ( app_name_or_id , alias = None , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / app - xxxx / addDevelopers API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Apps # API - method : - / app - xxxx % 5B / yyyy % 5D ...
fully_qualified_version = app_name_or_id + ( ( '/' + alias ) if alias else '' ) return DXHTTPRequest ( '/%s/addDevelopers' % fully_qualified_version , input_params , always_retry = always_retry , ** kwargs )
def hierarchy_pos ( links , root , width = 1. , vert_gap = 0.2 , vert_loc = 0 , xcenter = 0.5 , pos = None , parent = None , min_dx = 0.03 ) : '''If there is a cycle that is reachable from root , then this will see infinite recursion . G : the graph root : the root node of current branch width : horizontal sp...
if pos is None : pos = { root : ( xcenter , vert_loc ) } else : pos [ root ] = ( xcenter , vert_loc ) neighbors = get_sandbox_neighbours ( links , root ) if len ( neighbors ) != 0 : dx = max ( width / len ( neighbors ) , min_dx ) # nextx = xcenter - width / 2 - dx / 2 nextx = pos [ root ] [ 0 ] - ( ...
def _initialize_parameters ( state_machine , n_features ) : """Helper to create initial parameter vector with the correct shape ."""
return np . zeros ( ( state_machine . n_states + state_machine . n_transitions , n_features ) )
def get_app_model_voice ( self , app_model_item ) : """App Model voice Returns the js menu compatible voice dict if the user can see it , None otherwise"""
if app_model_item . get ( 'name' , None ) is None : raise ImproperlyConfigured ( 'Model menu voices must have a name key' ) # noqa if app_model_item . get ( 'app' , None ) is None : raise ImproperlyConfigured ( 'Model menu voices must have an app key' ) # noqa return self . get_model_voice ( app_model_item . ge...
def simulate ( self , time , feedforwardInputI , feedforwardInputE , v , recurrent = True , dt = None , envelope = False , inputNoise = None , sampleFreq = 1 , startFrom = 0 , save = True ) : """: param time : Amount of time to simulate . Divided into chunks of len dt . : param feedforwardInputI : feedforward i...
# Set up plotting if self . plotting : self . fig = plt . figure ( ) self . ax1 = self . fig . add_subplot ( 311 ) self . ax2 = self . fig . add_subplot ( 312 ) self . ax3 = self . fig . add_subplot ( 313 ) plt . ion ( ) self . ax1 . set_xlabel ( "Excitatory population activity" ) self . ax2...
def getEncodableAttributes ( self , obj , codec = None ) : """Must return a C { dict } of attributes to be encoded , even if its empty . @ param codec : An optional argument that will contain the encoder instance calling this function . @ since : 0.5"""
if not self . _compiled : self . compile ( ) if self . is_dict : return dict ( obj ) if self . shortcut_encode and self . dynamic : return obj . __dict__ . copy ( ) attrs = { } if self . static_attrs : for attr in self . static_attrs : attrs [ attr ] = getattr ( obj , attr , pyamf . Undefined ) ...
def get_pipeline_steps ( pipeline , steps_group ) : """Get the steps attribute of module pipeline . If there is no steps sequence on the pipeline , return None . Guess you could theoretically want to run a pipeline with nothing in it ."""
logger . debug ( "starting" ) assert pipeline assert steps_group logger . debug ( f"retrieving {steps_group} steps from pipeline" ) if steps_group in pipeline : steps = pipeline [ steps_group ] if steps is None : logger . warn ( f"{steps_group}: sequence has no elements. So it won't do " "anything." ) ...
def get_family_notes ( family , data_dir = None ) : '''Return a string representing the notes about a basis set family If the notes are not found , an empty string is returned'''
file_path = _family_notes_path ( family , data_dir ) notes_str = fileio . read_notes_file ( file_path ) if notes_str is None : notes_str = "" ref_data = get_reference_data ( data_dir ) return notes . process_notes ( notes_str , ref_data )
def _create_model ( model , ident , ** params ) : """Create a model by cloning and then setting params"""
with log_errors ( pdb = True ) : model = clone ( model ) . set_params ( ** params ) return model , { "model_id" : ident , "params" : params , "partial_fit_calls" : 0 }
def upload_report ( server , payload , timeout = HQ_DEFAULT_TIMEOUT ) : """Upload a report to the server . : param payload : Dictionary ( JSON serializable ) of crash data . : return : server response"""
try : data = json . dumps ( payload ) r = requests . post ( server + '/reports/upload' , data = data , timeout = timeout ) except Exception as e : logging . error ( e ) return False return r
def apply_on_csv_string ( rules_str , func ) : """Splits a given string by comma , trims whitespace on the resulting strings and applies a given ` ` ` func ` ` ` to each item ."""
splitted = rules_str . split ( "," ) for str in splitted : func ( str . strip ( ) )
def getoptS ( X , Y , M_E , E ) : '''Find Sopt given X , Y'''
n , r = X . shape C = np . dot ( np . dot ( X . T , M_E ) , Y ) C = C . flatten ( ) A = np . zeros ( ( r * r , r * r ) ) for i in range ( r ) : for j in range ( r ) : ind = j * r + i temp = np . dot ( np . dot ( X . T , np . dot ( X [ : , i , None ] , Y [ : , j , None ] . T ) * E ) , Y ) A [...
def recursive_dict_to_dict ( rdict ) : """Convert a recursive dict to a plain ol ' dict ."""
d = { } for ( k , v ) in rdict . items ( ) : if isinstance ( v , defaultdict ) : d [ k ] = recursive_dict_to_dict ( v ) else : d [ k ] = v return d
def build_standard_field ( self , field_name , model_field ) : """Creates a default instance of a basic non - relational field ."""
kwargs = { } if model_field . null or model_field . blank : kwargs [ 'required' ] = False if model_field . null : kwargs [ 'allow_null' ] = True if model_field . blank and ( issubclass ( model_field . __class__ , models . CharField ) or ( issubclass ( model_field . __class__ , models . TextField ) )...
def has_overflow ( self , params ) : """detect inf and nan"""
is_not_finite = 0 for param in params : if param . grad_req != 'null' : grad = param . list_grad ( ) [ 0 ] is_not_finite += mx . nd . contrib . isnan ( grad ) . sum ( ) is_not_finite += mx . nd . contrib . isinf ( grad ) . sum ( ) # NDArray is implicitly converted to bool if is_not_finite ==...
def neighbors ( self , node_id ) : """Find all the nodes where there is an edge from the specified node to that node . Returns a list of node ids ."""
node = self . get_node ( node_id ) return [ self . get_edge ( edge_id ) [ 'vertices' ] [ 1 ] for edge_id in node [ 'edges' ] ]
def collate ( self , merge_type = None , drop = [ ] , drop_constant = False ) : """Collate allows reordering nested containers Collation allows collapsing nested mapping types by merging their dimensions . In simple terms in merges nested containers into a single merged type . In the simple case a HoloMap c...
from . element import Collator merge_type = merge_type if merge_type else self . __class__ return Collator ( self , merge_type = merge_type , drop = drop , drop_constant = drop_constant ) ( )
def bm3_g ( p , v0 , g0 , g0p , k0 , k0p ) : """calculate shear modulus at given pressure . not fully tested with mdaap . : param p : pressure : param v0 : volume at reference condition : param g0 : shear modulus at reference condition : param g0p : pressure derivative of shear modulus at reference condit...
return cal_g_bm3 ( p , [ g0 , g0p ] , [ v0 , k0 , k0p ] )
def _update_failure_type ( self ) : """Updates the failure type of this Note ' s Job . Set the linked Job ' s failure type to that of the most recent JobNote or set to Not Classified if there are no JobNotes . This is called when JobNotes are created ( via . save ( ) ) and deleted ( via . delete ( ) ) and i...
# update the job classification note = JobNote . objects . filter ( job = self . job ) . order_by ( '-created' ) . first ( ) if note : self . job . failure_classification_id = note . failure_classification . id else : self . job . failure_classification_id = FailureClassification . objects . get ( name = 'not c...
def update_stock_codes ( ) : """获取所有股票 ID 到 all _ stock _ code 目录下"""
all_stock_codes_url = "http://www.shdjt.com/js/lib/astock.js" grep_stock_codes = re . compile ( r"~(\d+)`" ) response = requests . get ( all_stock_codes_url ) all_stock_codes = grep_stock_codes . findall ( response . text ) with open ( stock_code_path ( ) , "w" ) as f : f . write ( json . dumps ( dict ( stock = all...
def add ( self , original_index , operation ) : """Add an operation to this Run instance . : Parameters : - ` original _ index ` : The original index of this operation within a larger bulk operation . - ` operation ` : The operation document ."""
self . index_map . append ( original_index ) self . ops . append ( operation )
def spanning_tree_count ( graph : nx . Graph ) -> int : """Return the number of unique spanning trees of a graph , using Kirchhoff ' s matrix tree theorem ."""
laplacian = nx . laplacian_matrix ( graph ) . toarray ( ) comatrix = laplacian [ : - 1 , : - 1 ] det = np . linalg . det ( comatrix ) count = int ( round ( det ) ) return count
def tuple_pairs_to_dict ( input_tuple ) : """This function takes a tuple of elements and uses every two successive elements to generate a dictionary . Each pair of elements becomes a key - value pair in the resulting dictionary . If there is an odd number of elements in the tuple , the last element is ignored ....
result_dict = { input_tuple [ i ] : input_tuple [ i + 1 ] for i in range ( 0 , len ( input_tuple ) - 1 , 2 ) } return result_dict
def pick_event ( self ) : """Extracts an event ( if available ) from the Events queue ."""
logger . debug ( "checking event queue" ) event = snap7 . snap7types . SrvEvent ( ) ready = ctypes . c_int32 ( ) code = self . library . Srv_PickEvent ( self . pointer , ctypes . byref ( event ) , ctypes . byref ( ready ) ) check_error ( code ) if ready : logger . debug ( "one event ready: %s" % event ) return ...
def _host_libc ( self ) : """Use the - - libc - dir option if provided , otherwise invoke a host compiler to find libc dev ."""
libc_dir_option = self . get_options ( ) . libc_dir if libc_dir_option : maybe_libc_crti = os . path . join ( libc_dir_option , self . _LIBC_INIT_OBJECT_FILE ) if os . path . isfile ( maybe_libc_crti ) : return HostLibcDev ( crti_object = maybe_libc_crti , fingerprint = hash_file ( maybe_libc_crti ) ) ...
def send_email ( self , body = None , subject = None , to = list , cc = None , bcc = None , send_as = None , attachments = None ) : """Sends an email in one method , a shortcut for creating an instance of : class : ` Message < pyOutlook . core . message . Message > ` . Args : body ( str ) : The body of the em...
email = Message ( self . access_token , body , subject , to , cc = cc , bcc = bcc , sender = send_as ) if attachments is not None : for attachment in attachments : email . attach ( attachment . get ( 'bytes' ) , attachment . get ( 'name' ) ) email . send ( )
def _parse_ISBN_EAN ( details ) : """Parse ISBN and EAN . Args : details ( obj ) : HTMLElement containing slice of the page with details . Returns : ( ISBN , EAN ) : Tuple with two string or two None ."""
isbn_ean = _get_td_or_none ( details , "ctl00_ContentPlaceHolder1_tblRowIsbnEan" ) if not isbn_ean : return None , None ean = None isbn = None if "/" in isbn_ean : # ISBN and EAN are stored in same string isbn , ean = isbn_ean . split ( "/" ) isbn = isbn . strip ( ) ean = ean . strip ( ) else : isbn...
def parse_simulation ( self , node ) : """Parses < Simulation > @ param node : Node containing the < Simulation > element @ type node : xml . etree . Element"""
self . current_simulation = self . current_component_type . simulation self . process_nested_tags ( node ) self . current_simulation = None
def get_vnetwork_hosts_input_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_vnetwork_hosts = ET . Element ( "get_vnetwork_hosts" ) config = get_vnetwork_hosts input = ET . SubElement ( get_vnetwork_hosts , "input" ) name = ET . SubElement ( input , "name" ) name . text = kwargs . pop ( 'name' ) callback = kwargs . pop ( 'callback' , self . _callback ) ret...
def write_relationships ( self , file_name , flat = True ) : """This module will output the eDNA tags which are used inside each calculation . If flat = True , data will be written flat , like : ADE1CA01 , ADE1PI01 , ADE1PI02 If flat = False , data will be written in the non - flat way , like : ADE1CA01 ,...
with open ( file_name , 'w' ) as writer : if flat : self . _write_relationships_flat ( writer ) else : self . _write_relationships_non_flat ( writer )
def load ( image ) : r"""Loads the ` ` image ` ` and returns a ndarray with the image ' s pixel content as well as a header object . The header can , with restrictions , be used to extract additional meta - information about the image ( e . g . using the methods in ` ~ medpy . io . Header ` ) . Additionally ...
logger = Logger . getInstance ( ) logger . info ( 'Loading image {}...' . format ( image ) ) if not os . path . exists ( image ) : raise ImageLoadingError ( 'The supplied image {} does not exist.' . format ( image ) ) if os . path . isdir ( image ) : # ! TODO : this does not load the meta - data , find a way to loa...
def encode_array ( input_array , codec , param ) : """Encode the array using the method and then add the header to this array . : param input _ array : the array to be encoded : param codec : the integer index of the codec to use : param param : the integer parameter to use in the function : return an array...
return add_header ( codec_dict [ codec ] . encode ( input_array , param ) , codec , len ( input_array ) , param )
def get_syslog_config ( host , username , password , protocol = None , port = None , esxi_hosts = None , credstore = None ) : '''Retrieve the syslog configuration . host The location of the host . username The username used to login to the host , such as ` ` root ` ` . password The password used to logi...
cmd = 'system syslog config get' ret = { } if esxi_hosts : if not isinstance ( esxi_hosts , list ) : raise CommandExecutionError ( '\'esxi_hosts\' must be a list.' ) for esxi_host in esxi_hosts : response = salt . utils . vmware . esxcli ( host , username , password , cmd , protocol = protocol ,...
def set_html5_doctype ( self ) : """Method used to transform a doctype in to a properly html5 doctype"""
doctype = b'<!DOCTYPE html>\n' content = doctype_re . subn ( doctype , self . response . content , 1 ) [ 0 ] self . response . content = content
def CreateServiceProto ( job ) : """Create the Service protobuf . Args : job : Launchdjobdict from servicemanagement framework . Returns : sysinfo _ pb2 . OSXServiceInformation proto"""
service = rdf_client . OSXServiceInformation ( label = job . get ( "Label" ) , program = job . get ( "Program" ) , sessiontype = job . get ( "LimitLoadToSessionType" ) , lastexitstatus = int ( job [ "LastExitStatus" ] ) , timeout = int ( job [ "TimeOut" ] ) , ondemand = bool ( job [ "OnDemand" ] ) ) for arg in job . ge...