signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def p_scope ( p ) :
"""scope : ' , ' SCOPE ' ( ' metaElementList ' ) '""" | slist = p [ 4 ]
scopes = OrderedDict ( )
for i in ( 'CLASS' , 'ASSOCIATION' , 'INDICATION' , 'PROPERTY' , 'REFERENCE' , 'METHOD' , 'PARAMETER' , 'ANY' ) :
scopes [ i ] = i in slist
p [ 0 ] = scopes |
def ecdh_derive_key ( key , epk , apu , apv , alg , dk_len ) :
"""ECDH key derivation , as defined by JWA
: param key : Elliptic curve private key
: param epk : Elliptic curve public key
: param apu : PartyUInfo
: param apv : PartyVInfo
: param alg : Algorithm identifier
: param dk _ len : Length of key... | # Compute shared secret
shared_key = key . exchange ( ec . ECDH ( ) , epk )
# Derive the key
# AlgorithmID | | PartyUInfo | | PartyVInfo | | SuppPubInfo
otherInfo = bytes ( alg ) + struct . pack ( "!I" , len ( apu ) ) + apu + struct . pack ( "!I" , len ( apv ) ) + apv + struct . pack ( "!I" , dk_len )
return concat_sha... |
def get_inner_data ( dictionary ) :
"""Gets 2nd - level data into 1st - level dictionary
: param dictionary : dict
: return : with 2nd - level data""" | out = { }
for key in dictionary . keys ( ) :
inner_keys = dictionary [ key ] . keys ( )
for inner_key in inner_keys :
new_key = key + " " + inner_key
# concatenate
out [ new_key ] = dictionary [ key ] [ inner_key ]
return out |
def calculate_hex ( hex_string ) :
"""Credit for conversion to itsnotlupus / vesync _ wsproxy""" | hex_conv = hex_string . split ( ':' )
converted_hex = ( int ( hex_conv [ 0 ] , 16 ) + int ( hex_conv [ 1 ] , 16 ) ) / 8192
return converted_hex |
def parse_property_array ( parser , event , node ) : # pylint : disable = unused - argument
"""Parse CIM / XML PROPERTY . ARRAY element and return CIMProperty""" | name = _get_required_attribute ( node , 'NAME' )
cim_type = _get_required_attribute ( node , 'TYPE' )
# TODO 2/16 KS : array _ size here is unused . It is valid attribute .
array_size = _get_attribute ( node , 'ARRAYSIZE' )
class_origin = _get_attribute ( node , 'CLASSORIGIN' )
propagated = _get_attribute ( node , 'PRO... |
def datasets ( self , libref : str = '' ) -> str :
"""This method is used to query a libref . The results show information about the libref including members .
: param libref : the libref to query
: return :""" | code = "proc datasets"
if libref :
code += " dd=" + libref
code += "; quit;"
if self . nosub :
print ( code )
else :
if self . results . lower ( ) == 'html' :
ll = self . _io . submit ( code , "html" )
if not self . batch :
self . DISPLAY ( self . HTML ( ll [ 'LST' ] ) )
... |
def summary_table ( pairs , key_header , descr_header = "Description" , width = 78 ) :
"""List of one - liner strings containing a reStructuredText summary table
for the given pairs ` ` ( name , object ) ` ` .""" | from . lazy_text import rst_table , small_doc
max_width = width - max ( len ( k ) for k , v in pairs )
table = [ ( k , small_doc ( v , max_width = max_width ) ) for k , v in pairs ]
return rst_table ( table , ( key_header , descr_header ) ) |
def add_environment ( self , environment , sync = True ) :
"""add an environment to this OS instance .
: param environment : the environment to add on this OS instance
: param sync : If sync = True ( default ) synchronize with Ariane server . If sync = False ,
add the environment object on list to be added on... | LOGGER . debug ( "OSInstance.add_environment" )
if not sync :
self . environment_2_add . append ( environment )
else :
if environment . id is None :
environment . save ( )
if self . id is not None and environment . id is not None :
params = { 'id' : self . id , 'environmentID' : environment ... |
async def set_utc ( pyvlx ) :
"""Enable house status monitor .""" | setutc = SetUTC ( pyvlx = pyvlx )
await setutc . do_api_call ( )
if not setutc . success :
raise PyVLXException ( "Unable to set utc." ) |
def iter_doc_filepaths ( self , ** kwargs ) :
"""Generator that iterates over all detected documents .
and returns the filesystem path to each doc .
Order is by shard , but arbitrary within shards .
@ TEMP not locked to prevent doc creation / deletion""" | for shard in self . _shards :
for doc_id , blob in shard . iter_doc_filepaths ( ** kwargs ) :
yield doc_id , blob |
def add_pyspark_path ( ) :
"""Add PySpark to the library path based on the value of SPARK _ HOME .""" | try :
spark_home = os . environ [ 'SPARK_HOME' ]
sys . path . append ( os . path . join ( spark_home , 'python' ) )
py4j_src_zip = glob ( os . path . join ( spark_home , 'python' , 'lib' , 'py4j-*-src.zip' ) )
if len ( py4j_src_zip ) == 0 :
raise ValueError ( 'py4j source archive not found in %s... |
def connect ( self , driver ) :
"""Connect using the Telnet protocol specific FSM .""" | # 0 1 2 3
events = [ ESCAPE_CHAR , driver . press_return_re , driver . standby_re , driver . username_re , # 4 5 6 7
driver . password_re , driver . more_re , self . device . prompt_re , driver . rommon_re , # 8 9 10 11 12
driver . unable_to_connect_re , driver . timeout_re , pexpect . TIMEOUT , PASSWORD_OK , driver . ... |
def get_caller ( stack_index = 2 , root_dir = None ) :
'''Returns file . py : lineno of your caller . A stack _ index of 2 will provide
the caller of the function calling this function . Notice that stack _ index
of 2 or more will fail if called from global scope .''' | caller = inspect . getframeinfo ( inspect . stack ( ) [ stack_index ] [ 0 ] )
# Trim the filenames for readability .
filename = caller . filename
if root_dir is not None :
filename = re . sub ( "^" + root_dir + "/" , "" , filename )
return "%s:%d" % ( filename , caller . lineno ) |
def set_config ( self , key , value ) :
'''set { key : value } paris to self . config''' | self . config = self . read_file ( )
self . config [ key ] = value
self . write_file ( ) |
def get_historical_minute_data ( self , ticker : str ) :
"""Request historical 5 minute data from DTN .""" | start = self . _start
stop = self . _stop
if len ( stop ) > 4 :
stop = stop [ : 4 ]
if len ( start ) > 4 :
start = start [ : 4 ]
for year in range ( int ( start ) , int ( stop ) + 1 ) :
beg_time = ( '%s0101000000' % year )
end_time = ( '%s1231235959' % year )
msg = "HIT,%s,60,%s,%s,,,,1,,,s\r\n" % (... |
def get_var_name ( self , i ) :
"""Return variable name""" | method = "get_var_name"
A = None
metadata = { method : i }
send_array ( self . socket , A , metadata )
A , metadata = recv_array ( self . socket , poll = self . poll , poll_timeout = self . poll_timeout , flags = self . zmq_flags )
return metadata [ method ] |
def _set_dxproject_id ( self , latest_project = False ) :
"""Searches for the project in DNAnexus based on the input arguments when instantiating the class .
If multiple projects are found based on the search criteria , an exception will be raised . A
few various search strategies are employed , based on the in... | dx_project_props = { }
if self . library_name :
dx_project_props [ "library_name" ] = self . library_name
if self . uhts_run_name :
dx_project_props [ "seq_run_name" ] = self . uhts_run_name
if self . sequencing_lane :
dx_project_props [ "seq_lane_index" ] = str ( self . sequencing_lane )
dx_proj = ""
if se... |
def groupfinder ( userid , request ) :
"""Default groupfinder implementaion for pyramid applications
: param userid :
: param request :
: return :""" | if userid and hasattr ( request , "user" ) and request . user :
groups = [ "group:%s" % g . id for g in request . user . groups ]
return groups
return [ ] |
def policy_assignment_create ( name , scope , definition_name , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Create a policy assignment .
: param name : The name of the policy assignment to create .
: param scope : The scope of the policy assignment .
: param definition _ name : The name of the policy def... | polconn = __utils__ [ 'azurearm.get_client' ] ( 'policy' , ** kwargs )
# " get " doesn ' t work for built - in policies per https : / / github . com / Azure / azure - cli / issues / 692
# Uncomment this section when the ticket above is resolved .
# BEGIN
# definition = policy _ definition _ get (
# name = definition _ ... |
def _parse_boolean ( value ) :
"""Coerce value into an bool .
: param str value : Value to parse .
: returns : bool or None if the value is not a boolean string .""" | value = value . lower ( )
if value in _true_strings :
return True
elif value in _false_strings :
return False
else :
return None |
def get_authenticate_header ( self , request ) :
"""If a request is unauthenticated , determine the WWW - Authenticate
header to use for 401 responses , if any .""" | authenticators = self . get_authenticators ( )
if authenticators :
return authenticators [ 0 ] . authenticate_header ( request ) |
def from_statement ( cls , statement ) :
"""Create a selection function from a statement""" | if statement [ 0 ] in [ "TS" , "TIMESTAMP" , "UTCTIMESTAMP" , "UTCTS" ] :
return TimestampFunction . from_statement ( statement )
elif statement [ 0 ] in [ "NOW" , "UTCNOW" ] :
return NowFunction . from_statement ( statement )
else :
raise SyntaxError ( "Unknown function %r" % statement [ 0 ] ) |
def _find_highest_supported_command ( self , * segment_classes , ** kwargs ) :
"""Search the BPD for the highest supported version of a segment .""" | return_parameter_segment = kwargs . get ( "return_parameter_segment" , False )
parameter_segment_name = "{}I{}S" . format ( segment_classes [ 0 ] . TYPE [ 0 ] , segment_classes [ 0 ] . TYPE [ 2 : ] )
version_map = dict ( ( clazz . VERSION , clazz ) for clazz in segment_classes )
max_version = self . bpd . find_segment_... |
def getContainers ( self ) :
"""Return a list of all containers of this type""" | _containers = [ ]
for container in self . bika_setup . bika_containers . objectValues ( ) :
containertype = container . getContainerType ( )
if containertype and containertype . UID ( ) == self . UID ( ) :
_containers . append ( container )
return _containers |
def has ( prop , object_or_dct ) :
"""Implementation of ramda has
: param prop :
: param object _ or _ dct :
: return :""" | return prop in object_or_dct if isinstance ( dict , object_or_dct ) else hasattr ( object_or_dct , prop ) |
def _add_consequences ( self , variant_obj , raw_variant_line ) :
"""Add the consequences found for a variant
Args :
variant _ obj ( puzzle . models . Variant )
raw _ variant _ line ( str ) : A raw vcf variant line""" | consequences = [ ]
for consequence in SO_TERMS :
if consequence in raw_variant_line :
consequences . append ( consequence )
variant_obj . consequences = consequences |
def pin_command ( self ) :
"""Compose pip - compile shell command""" | parts = [ 'pip-compile' , '--no-header' , '--verbose' , '--rebuild' , '--no-index' , '--output-file' , self . outfile , self . infile , ]
if OPTIONS [ 'upgrade' ] :
parts . insert ( 3 , '--upgrade' )
if self . add_hashes :
parts . insert ( 1 , '--generate-hashes' )
return parts |
def is_marginable ( self ) :
"""True if adding counts across this dimension axis is meaningful .""" | return self . dimension_type not in { DT . CA , DT . MR , DT . MR_CAT , DT . LOGICAL } |
def dst ( self , dt , is_dst = None ) :
'''See datetime . tzinfo . dst
The is _ dst parameter may be used to remove ambiguity during DST
transitions .
> > > from pytz import timezone
> > > tz = timezone ( ' America / St _ Johns ' )
> > > normal = datetime ( 2009 , 9 , 1)
> > > tz . dst ( normal )
date... | if dt is None :
return None
elif dt . tzinfo is not self :
dt = self . localize ( dt , is_dst )
return dt . tzinfo . _dst
else :
return self . _dst |
def _hook_mem_unmapped ( self , uc , access , address , size , value , user_data , size_extension = True ) : # pylint : disable = unused - argument
"""This callback is called when unicorn needs to access data that ' s not yet present in memory .""" | # FIXME check angr hooks at ` address `
if size_extension :
start = address & ( 0xfffffffffffff0000 )
length = ( ( address + size + 0xffff ) & ( 0xfffffffffffff0000 ) ) - start
else :
start = address & ( 0xffffffffffffff000 )
length = ( ( address + size + 0xfff ) & ( 0xffffffffffffff000 ) ) - start
if (... |
def _parseSections ( self , data ) :
"""Parse data and separate sections . Returns dictionary that maps
section name to section data .
@ param data : Multiline data .
@ return : Dictionary that maps section names to section data .""" | section_dict = { }
lines = data . splitlines ( )
idx = 0
numlines = len ( lines )
section = None
while idx < numlines :
line = lines [ idx ]
idx += 1
mobj = re . match ( '^(\w[\w\s\(\)]+[\w\)])\s*:$' , line )
if mobj :
section = mobj . group ( 1 )
section_dict [ section ] = [ ]
else ... |
def emulate_network ( network_constraints , roles = None , inventory_path = None , extra_vars = None ) :
"""Emulate network links .
Read ` ` network _ constraints ` ` and apply ` ` tc ` ` rules on all the nodes .
Constraints are applied between groups of machines . Theses groups are
described in the ` ` netwo... | # 1 ) Retrieve the list of ips for all nodes ( Ansible )
# 2 ) Build all the constraints ( Python )
# { source : src , target : ip _ dest , device : if , rate : x , delay : y }
# 3 ) Enforce those constraints ( Ansible )
if not network_constraints :
return
if roles is None and inventory is None :
raise ValueErr... |
def rmon_alarm_entry_alarm_owner ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
rmon = ET . SubElement ( config , "rmon" , xmlns = "urn:brocade.com:mgmt:brocade-rmon" )
alarm_entry = ET . SubElement ( rmon , "alarm-entry" )
alarm_index_key = ET . SubElement ( alarm_entry , "alarm-index" )
alarm_index_key . text = kwargs . pop ( 'alarm_index' )
alarm_owner = ET . ... |
def from_tgt ( ksoc , tgt , key ) :
"""Sets up the kerberos object from tgt and the session key .
Use this function when pulling the TGT from ccache file .""" | kc = KerbrosComm ( None , ksoc )
kc . kerberos_TGT = tgt
kc . kerberos_cipher_type = key [ 'keytype' ]
kc . kerberos_session_key = Key ( kc . kerberos_cipher_type , key [ 'keyvalue' ] )
kc . kerberos_cipher = _enctype_table [ kc . kerberos_cipher_type ]
return kc |
def eigenvalues_ ( self ) :
"""The eigenvalues associated with each principal component .""" | utils . validation . check_is_fitted ( self , 's_' )
return np . square ( self . s_ ) . tolist ( ) |
def describe_resource ( self , resource_path ) :
"""Describes a resource based on its resource path ( the URL path modulo host part ) .
: Parameters :
- ` resource _ path ` : The path of the resource to describe , for example , ` / api / v1 / namespaces / default / replicationcontrollers / webserver - rc `""" | res = self . execute_operation ( method = "GET" , ops_path = resource_path )
return res |
def do_mute ( self , sender , body , args ) :
"""Temporarily mutes chatroom for a user""" | if sender . get ( 'MUTED' ) :
self . send_message ( 'you are already muted' , sender )
else :
self . broadcast ( '%s has muted this chatroom' % ( sender [ 'NICK' ] , ) )
sender [ 'QUEUED_MESSAGES' ] = [ ]
sender [ 'MUTED' ] = True |
def get_connected_components_as_subgraphs ( graph ) :
"""Finds all connected components of the graph .
Returns a list of graph objects , each representing a connected component .
Returns an empty list for an empty graph .""" | components = get_connected_components ( graph )
list_of_graphs = [ ]
for c in components :
edge_ids = set ( )
nodes = [ graph . get_node ( node ) for node in c ]
for n in nodes : # - - Loop through the edges in each node , to determine if it should be included
for e in n [ 'edges' ] : # - - Only add... |
def PartialDynamicSystem ( self , ieq , variable ) :
"""returns dynamical system blocks associated to output variable""" | if ieq == 0 : # w2 = Rw1
if variable == self . physical_nodes [ 0 ] . variable : # w1 = w2 / R
return [ Gain ( self . physical_nodes [ 1 ] . variable , variable , 1 / self . ratio ) ]
elif variable == self . physical_nodes [ 1 ] . variable : # w2 = Rw1
return [ Gain ( self . physical_nodes [ 0 ]... |
def load ( self , context ) :
"""Returns the plugin , if possible .
Args :
context : The TBContext flags .
Returns :
A InteractiveInferencePlugin instance or None if it couldn ' t be loaded .""" | try : # pylint : disable = g - import - not - at - top , unused - import
import tensorflow
except ImportError :
return
# pylint : disable = line - too - long , g - import - not - at - top
from tensorboard . plugins . interactive_inference . interactive_inference_plugin import InteractiveInferencePlugin
return I... |
def _is_compatible_with ( self , other ) :
"""Return True if names are not incompatible .
This checks that the gender of titles and compatibility of suffixes""" | title = self . _compare_title ( other )
suffix = self . _compare_suffix ( other )
return title and suffix |
def imulti_stats ( self , start = 0 , end = - 1 , series = None , fields = None , stats = None ) :
'''Perform cross multivariate statistics calculation of
this : class : ` ColumnTS ` and other optional * series * from * start *
to * end * .
: parameter start : the start rank .
: parameter start : the end ra... | stats = stats or self . default_multi_stats
backend = self . read_backend
return backend . execute ( backend . structure ( self ) . imulti_stats ( start , end , fields , series , stats ) , self . _stats ) |
def create_parsing_plan ( self , desired_type : Type [ T ] , filesystem_object : PersistedObject , logger : Logger , _main_call : bool = True ) :
"""Implements the abstract parent method by using the recursive parsing plan impl . Subclasses wishing to produce
their own parsing plans should rather override _ creat... | in_root_call = False
# - - log msg only for the root call , not for the children that will be created by the code below
if _main_call and ( not hasattr ( AnyParser . thrd_locals , 'flag_init' ) or AnyParser . thrd_locals . flag_init == 0 ) : # print ( ' Building a parsing plan to parse ' + str ( filesystem _ object ) +... |
def _load ( self , file_parser , section_name ) :
"""The current element is loaded from the configuration file ,
all constraints and requirements are checked .""" | # pylint : disable - msg = W0621
log = logging . getLogger ( 'argtoolbox' )
try :
log . debug ( "looking for field (section=" + section_name + ") : " + self . _name )
data = None
try :
if self . e_type == int :
data = file_parser . getint ( section_name , self . _name )
elif self... |
def handle_method ( signature_node , module , object_name , cache ) :
"""Styles ` ` automethod ` ` entries .
Adds ` ` abstract ` ` prefix to abstract methods .
Adds link to originating class for inherited methods .""" | * class_names , attr_name = object_name . split ( "." )
# Handle nested classes
class_ = module
for class_name in class_names :
class_ = getattr ( class_ , class_name , None )
if class_ is None :
return
attr = getattr ( class_ , attr_name )
try :
inspected_attr = cache [ class_ ] [ attr_name ]
d... |
def parse_v2_signing_block ( self ) :
"""Parse the V2 signing block and extract all features""" | self . _v2_signing_data = [ ]
# calling is _ signed _ v2 should also load the signature
if not self . is_signed_v2 ( ) :
return
block_bytes = self . _v2_blocks [ self . _APK_SIG_KEY_V2_SIGNATURE ]
block = io . BytesIO ( block_bytes )
view = block . getvalue ( )
# V2 signature Block data format :
# * signer :
# * si... |
def options ( cls ) :
"""Provide a sorted list of options .""" | return sorted ( ( value , name ) for ( name , value ) in cls . __dict__ . items ( ) if not name . startswith ( '__' ) ) |
def webui ( cmd , hostport = '127.0.0.1:8800' , skip_browser = False ) :
"""start the webui server in foreground or perform other operation on the
django application""" | dbpath = os . path . realpath ( os . path . expanduser ( config . dbserver . file ) )
if os . path . isfile ( dbpath ) and not os . access ( dbpath , os . W_OK ) :
sys . exit ( 'This command must be run by the proper user: ' 'see the documentation for details' )
if cmd == 'start' :
dbserver . ensure_on ( )
... |
def cli ( ctx , location , runtime , dependency_manager , output_dir , name , no_input ) :
"""Initialize a serverless application with a SAM template , folder
structure for your Lambda functions , connected to an event source such as APIs ,
S3 Buckets or DynamoDB Tables . This application includes everything yo... | # All logic must be implemented in the ` do _ cli ` method . This helps ease unit tests
do_cli ( ctx , location , runtime , dependency_manager , output_dir , name , no_input ) |
def _retrieve_remote ( fnames ) :
"""Retrieve remote inputs found in the same bucket as the template or metadata files .""" | for fname in fnames :
if objectstore . is_remote ( fname ) :
inputs = [ ]
regions = [ ]
remote_base = os . path . dirname ( fname )
for rfname in objectstore . list ( remote_base ) :
if rfname . endswith ( tuple ( KNOWN_EXTS . keys ( ) ) ) :
inputs . appen... |
def eject_media ( self ) :
"""Ejects Virtual Media .
: raises : SushyError , on an error from iLO .""" | try :
super ( VirtualMedia , self ) . eject_media ( )
except sushy_exceptions . SushyError :
target_uri = self . _get_action_element ( 'eject' ) . target_uri
self . _conn . post ( target_uri , data = { } ) |
def get_reachable_volume_templates ( self , start = 0 , count = - 1 , filter = '' , query = '' , sort = '' , networks = None , scope_uris = '' , private_allowed_only = False ) :
"""Gets the storage templates that are connected on the specified networks based on the storage system
port ' s expected network connect... | uri = self . URI + "/reachable-volume-templates"
uri += "?networks={}&privateAllowedOnly={}" . format ( networks , private_allowed_only )
get_uri = self . _client . build_query_uri ( start = start , count = count , filter = filter , query = query , sort = sort , uri = uri , scope_uris = scope_uris )
return self . _clie... |
def Ergun ( dp , voidage , vs , rho , mu , L = 1 ) :
r'''Calculates pressure drop across a packed bed of spheres using a
correlation developed in [ 1 ] _ , as shown in [ 2 ] _ and [ 3 ] _ . Eighteenth most
accurate correlation overall in the review of [ 2 ] _ .
Most often presented in the following form :
.... | Re = dp * rho * vs / mu
fp = ( 150 + 1.75 * ( Re / ( 1 - voidage ) ) ) * ( 1 - voidage ) ** 2 / ( voidage ** 3 * Re )
return fp * rho * vs ** 2 * L / dp |
def _init_browser ( self ) :
"""Update this everytime the CERN SSO login form is refactored .""" | self . browser = splinter . Browser ( 'phantomjs' )
self . browser . visit ( self . server_url )
self . browser . find_link_by_partial_text ( "Sign in" ) . click ( )
self . browser . fill ( 'ctl00$ctl00$NICEMasterPageBodyContent$SiteContentPlaceholder$' 'txtFormsLogin' , self . user )
self . browser . fill ( 'ctl00$ctl... |
def get_valid_managers ( cls , location ) :
"""Get the valid RepoManagers for this location .""" | def by_priority_attr ( c ) :
return getattr ( c , 'priority' , 0 )
classes = sorted ( iter_subclasses ( cls ) , key = by_priority_attr , reverse = True )
all_managers = ( c ( location ) for c in classes )
return ( mgr for mgr in all_managers if mgr . is_valid ( ) ) |
def namePop ( ctxt ) :
"""Pops the top element name from the name stack""" | if ctxt is None :
ctxt__o = None
else :
ctxt__o = ctxt . _o
ret = libxml2mod . namePop ( ctxt__o )
return ret |
def upsert ( self , doc , namespace , timestamp , update_spec = None ) :
"""Insert a document into Elasticsearch .""" | index , doc_type = self . _index_and_mapping ( namespace )
# No need to duplicate ' _ id ' in source document
doc_id = u ( doc . pop ( "_id" ) )
metadata = { 'ns' : namespace , '_ts' : timestamp }
# Index the source document , using lowercase namespace as index name .
action = { '_op_type' : 'index' , '_index' : index ... |
def save ( self ) :
"""Method that saves configuration parameter changes from instance of SHConfig class to global config class and
to ` config . json ` file .
Example of use case
` ` my _ config = SHConfig ( ) ` ` \n
` ` my _ config . instance _ id = ' < new instance id > ' ` ` \n
` ` my _ config . save ... | is_changed = False
for prop in self . _instance . CONFIG_PARAMS :
if getattr ( self , prop ) != getattr ( self . _instance , prop ) :
is_changed = True
setattr ( self . _instance , prop , getattr ( self , prop ) )
if is_changed :
self . _instance . save_configuration ( ) |
def parse_args ( ) :
"""parse main ( ) args""" | description = ( "Get Wikipedia article info and Wikidata via MediaWiki APIs.\n\n" "Gets a random English Wikipedia article by default, or in the\n" "language -lang, or from the wikisite -wiki, or by specific\n" "title -title. The output is a plain text extract unless -HTML." )
epilog = ( "Powered by https://github.com/... |
def laplace_crossover ( random , mom , dad , args ) :
"""Return the offspring of Laplace crossover on the candidates .
This function performs Laplace crosssover ( LX ) , following the
implementation specified in ( Deep and Thakur , " A new crossover
operator for real coded genetic algorithms , " Applied Mathe... | crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 )
if random . random ( ) < crossover_rate :
bounder = args [ '_ec' ] . bounder
a = args . setdefault ( 'lx_location' , 0 )
b = args . setdefault ( 'lx_scale' , 0.5 )
bro = copy . copy ( dad )
sis = copy . copy ( mom )
for i , ( m , d ) ... |
def _get_split_rhat ( values , round_to = 2 ) :
"""Compute the split - rhat for a 2d array .""" | shape = values . shape
if len ( shape ) != 2 :
raise TypeError ( "Effective sample size calculation requires 2 dimensional arrays." )
_ , num_samples = shape
num_split = num_samples // 2
# Calculate split chain mean
split_chain_mean1 = np . mean ( values [ : , : num_split ] , axis = 1 )
split_chain_mean2 = np . mea... |
def run_baton_query ( self , baton_binary : BatonBinary , program_arguments : List [ str ] = None , input_data : Any = None ) -> List [ Dict ] :
"""Runs a baton query .
: param baton _ binary : the baton binary to use
: param program _ arguments : arguments to give to the baton binary
: param input _ data : i... | if program_arguments is None :
program_arguments = [ ]
baton_binary_location = os . path . join ( self . _baton_binaries_directory , baton_binary . value )
program_arguments = [ baton_binary_location ] + program_arguments
_logger . info ( "Running baton command: '%s' with data '%s'" % ( program_arguments , input_da... |
def sort_js_files ( js_files ) :
"""Sorts JavaScript files in ` js _ files ` .
It sorts JavaScript files in a given ` js _ files `
into source files , mock files and spec files based on file extension .
Output :
* sources : source files for production . The order of source files
is significant and should ... | modules = [ f for f in js_files if f . endswith ( MODULE_EXT ) ]
mocks = [ f for f in js_files if f . endswith ( MOCK_EXT ) ]
specs = [ f for f in js_files if f . endswith ( SPEC_EXT ) ]
other_sources = [ f for f in js_files if ( not f . endswith ( MODULE_EXT ) and not f . endswith ( MOCK_EXT ) and not f . endswith ( S... |
def call ( self , method , params , callback = None ) :
"""Call a remote method
Arguments :
method - remote method name
params - remote method parameters
Keyword Arguments :
callback - callback function containing return data""" | self . _wait_for_connect ( )
self . ddp_client . call ( method , params , callback = callback ) |
def get_key_auth_cb ( key_filepath ) :
"""This is just a convenience function for key - based login .""" | def auth_cb ( ssh ) :
key = ssh_pki_import_privkey_file ( key_filepath )
ssh . userauth_publickey ( key )
return auth_cb |
def stringify_summary ( summary ) :
"""stringify summary , in order to dump json file and generate html report .""" | for index , suite_summary in enumerate ( summary [ "details" ] ) :
if not suite_summary . get ( "name" ) :
suite_summary [ "name" ] = "testcase {}" . format ( index )
for record in suite_summary . get ( "records" ) :
meta_datas = record [ 'meta_datas' ]
__stringify_meta_datas ( meta_data... |
def convert ( self ) :
"""Convert file ( s ) from ` ` mwTab ` ` format to ` ` JSON ` ` format or from ` ` JSON ` ` format to ` ` mwTab ` ` format .
: return : None
: rtype : : py : obj : ` None `""" | if not os . path . exists ( os . path . dirname ( self . file_generator . to_path ) ) :
dirname = os . path . dirname ( self . file_generator . to_path )
if dirname :
os . makedirs ( dirname )
if os . path . isdir ( self . file_generator . from_path ) :
self . _many_to_many ( )
elif os . path . isfi... |
def choice ( self , other ) :
'''( | ) This combinator implements choice . The parser p | q first applies p .
If it succeeds , the value of p is returned .
If p fails * * without consuming any input * * , parser q is tried .
NOTICE : without backtrack .''' | @ Parser
def choice_parser ( text , index ) :
res = self ( text , index )
return res if res . status or res . index != index else other ( text , index )
return choice_parser |
def of_operator ( context , x , y ) :
"""' of ' operator of permission if
This operator is used to specify the target object of permission""" | return x . eval ( context ) , y . eval ( context ) |
def _cull_redundant_about ( obj ) :
"""Removes the @ about key from the ` obj ` dict if that value refers to the
dict ' s ' @ id '""" | about_val = obj . get ( '@about' )
if about_val :
id_val = obj . get ( '@id' )
if id_val and ( ( '#' + id_val ) == about_val ) :
del obj [ '@about' ] |
def _complete_transaction ( cleanup_only , recursive , max_attempts , run_count , cmd_ret_list ) :
'''. . versionadded : : Fluorine
Called from ` ` complete _ transaction ` ` to protect the arguments
used for tail recursion , ` ` run _ count ` ` and ` ` cmd _ ret _ list ` ` .''' | cmd = [ 'yum-complete-transaction' ]
if cleanup_only :
cmd . append ( '--cleanup-only' )
cmd_ret_list . append ( __salt__ [ 'cmd.run_all' ] ( cmd , output_loglevel = 'trace' , python_shell = False ) )
if ( cmd_ret_list [ - 1 ] [ 'retcode' ] == salt . defaults . exitcodes . EX_OK and recursive and 'No unfinished tra... |
def get_all ( kind = '2' ) :
'''Get All the records .''' | return TabPost . select ( ) . where ( ( TabPost . kind == kind ) & ( TabPost . valid == 1 ) ) . order_by ( TabPost . time_update . desc ( ) ) |
def _get_registerd_func ( name_or_func ) :
"""get a xcorr function from a str or callable .""" | # get the function or register callable
if callable ( name_or_func ) :
func = register_array_xcorr ( name_or_func )
else :
func = XCOR_FUNCS [ name_or_func or 'default' ]
assert callable ( func ) , 'func is not callable'
# ensure func has the added methods
if not hasattr ( func , 'registered' ) :
func = reg... |
def _extract_programming_immediate_instructions_text ( self , element_id ) :
"""Extract assignment text ( instructions ) .
@ param element _ id : Element id to extract assignment instructions from .
@ type element _ id : str
@ return : List of assignment text ( instructions ) .
@ rtype : [ str ]""" | dom = get_page ( self . _session , OPENCOURSE_PROGRAMMING_IMMEDIATE_INSTRUCTIOINS_URL , json = True , course_id = self . _course_id , element_id = element_id )
return [ element [ 'assignmentInstructions' ] [ 'definition' ] [ 'value' ] for element in dom [ 'elements' ] ] |
def _inclusiveNamespacePrefixes ( node , context , unsuppressedPrefixes ) :
'''http : / / www . w3 . org / TR / xml - exc - c14n /
InclusiveNamespaces PrefixList parameter , which lists namespace prefixes that
are handled in the manner described by the Canonical XML Recommendation''' | inclusive = [ ]
if node . prefix :
usedPrefixes = [ 'xmlns:%s' % node . prefix ]
else :
usedPrefixes = [ 'xmlns' ]
for a in _attrs ( node ) :
if a . nodeName . startswith ( 'xmlns' ) or not a . prefix :
continue
usedPrefixes . append ( 'xmlns:%s' % a . prefix )
unused_namespace_dict = { }
for at... |
def load_profile ( ctx , variant_file , update , stats , profile_threshold ) :
"""Command for profiling of samples . User may upload variants used in profiling
from a vcf , update the profiles for all samples , and get some stats
from the profiles in the database .
Profiling is used to monitor duplicates in t... | adapter = ctx . obj [ 'adapter' ]
if variant_file :
load_profile_variants ( adapter , variant_file )
if update :
update_profiles ( adapter )
if stats :
distance_dict = profile_stats ( adapter , threshold = profile_threshold )
click . echo ( table_from_dict ( distance_dict ) ) |
def serve_once ( self ) :
"""Listen and handle 1 request .""" | # 256 is the maximum size of a Modbus RTU frame .
request_adu = self . serial_port . read ( 256 )
log . debug ( '<-- {0}' . format ( hexlify ( request_adu ) ) )
if len ( request_adu ) == 0 :
raise ValueError
response_adu = self . process ( request_adu )
self . respond ( response_adu ) |
def p_expr_GT_expr ( p ) :
"""expr : expr GT expr""" | p [ 0 ] = make_binary ( p . lineno ( 2 ) , 'GT' , p [ 1 ] , p [ 3 ] , lambda x , y : x > y ) |
def _set_type ( self , v , load = False ) :
"""Setter method for type , mapped from YANG variable / overlay / access _ list / type ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ type is considered as a private
method . Backends looking to populate this ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = type . type , is_container = 'container' , presence = False , yang_name = "type" , rest_name = "type" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions ... |
def sort_dict ( unsorted_dict ) :
"""Return a OrderedDict ordered by key names from the : unsorted _ dict :""" | sorted_dict = OrderedDict ( )
# sort items before inserting them into a dict
for key , value in sorted ( unsorted_dict . items ( ) , key = itemgetter ( 0 ) ) :
sorted_dict [ key ] = value
return sorted_dict |
def nmb_neurons ( self ) -> Tuple [ int , ... ] :
"""Number of neurons of the hidden layers .
> > > from hydpy import ANN
> > > ann = ANN ( None )
> > > ann ( nmb _ inputs = 2 , nmb _ neurons = ( 2 , 1 ) , nmb _ outputs = 3)
> > > ann . nmb _ neurons
(2 , 1)
> > > ann . nmb _ neurons = ( 3 , )
> > > a... | return tuple ( numpy . asarray ( self . _cann . nmb_neurons ) ) |
def process_result_value ( self , value , dialect ) :
"""convert value from json to a python object""" | if value is not None :
value = simplejson . loads ( value )
return value |
def find_longest_increasing_subsequence ( sequence ) :
"""This function calculates the length of the longest monotonically increasing subsequence in the input list .
Args :
sequence : A list of numeric values .
Returns :
An integer value that represents the length of the longest monotonically increasing sub... | sequence_len = len ( sequence )
subsequence_lengths = [ 1 ] * sequence_len
for idx1 in range ( 1 , sequence_len ) :
for idx2 in range ( 0 , idx1 ) :
if sequence [ idx1 ] > sequence [ idx2 ] and subsequence_lengths [ idx1 ] < subsequence_lengths [ idx2 ] + 1 :
subsequence_lengths [ idx1 ] = subse... |
def reciprocal_rank ( truth , recommend ) :
"""Reciprocal Rank ( RR ) .
Args :
truth ( numpy 1d array ) : Set of truth samples .
recommend ( numpy 1d array ) : Ordered set of recommended samples .
Returns :
float : RR .""" | for n in range ( recommend . size ) :
if recommend [ n ] in truth :
return 1. / ( n + 1 )
return 0. |
def prox_max_entropy ( X , step , gamma = 1 ) :
"""Proximal operator for maximum entropy regularization .
g ( x ) = gamma \ sum _ i x _ i ln ( x _ i )
has the analytical solution of gamma W ( 1 / gamma exp ( ( X - gamma ) / gamma ) ) , where
W is the Lambert W function .""" | from scipy . special import lambertw
gamma_ = _step_gamma ( step , gamma )
# minimize entropy : return gamma _ * np . real ( lambertw ( np . exp ( ( X - gamma _ ) / gamma _ ) / gamma _ ) )
above = X > 0
X [ above ] = gamma_ * np . real ( lambertw ( np . exp ( X [ above ] / gamma_ - 1 ) / gamma_ ) )
return X |
def pixdump ( source , start = None , end = None , length = None , width = 64 , height = None , palette = None ) :
"""Print the contents of a byte string as a 256 colour image .
source
The byte string to print .
start
Start offset to read from ( default : start )
end
End offset to stop reading at ( defa... | for line in pixdump_iter ( source , start , end , length , width , height , palette ) :
print ( line ) |
def sendto ( self , transport , addr ) :
"""Send request to a given address via given transport .
Args :
transport ( asyncio . DatagramTransport ) :
Write transport to send the message on .
addr ( Tuple [ str , int ] ) :
IP address and port pair to send the message to .""" | msg = bytes ( self ) + b'\r\n'
logger . debug ( "%s:%s < %s" , * ( addr + ( self , ) ) )
transport . sendto ( msg , addr ) |
async def parseResults ( self , api_data ) :
"""See CoverSource . parseResults .""" | results = [ ]
# parse page
parser = lxml . etree . HTMLParser ( )
html = lxml . etree . XML ( api_data . decode ( "utf-8" ) , parser )
for page_struct_version , result_selector in enumerate ( __class__ . RESULTS_SELECTORS ) :
result_nodes = result_selector ( html )
if result_nodes :
break
for rank , res... |
def obfuscate_builtins ( module , tokens , name_generator , table = None ) :
"""Inserts an assignment , ' < obfuscated identifier > = < builtin function > ' at
the beginning of * tokens * ( after the shebang and encoding if present ) for
every Python built - in function that is used inside * tokens * . Also , r... | used_builtins = analyze . enumerate_builtins ( tokens )
obfuscated_assignments = remap_name ( name_generator , used_builtins , table )
replacements = [ ]
for assignment in obfuscated_assignments . split ( '\n' ) :
replacements . append ( assignment . split ( '=' ) [ 0 ] )
replacement_dict = dict ( zip ( used_builti... |
def _handle_tag_definetext2 ( self ) :
"""Handle the DefineText2 tag .""" | obj = _make_object ( "DefineText2" )
self . _generic_definetext_parser ( obj , self . _get_struct_rgba )
return obj |
def calculate_report_size ( self , current_type , report_header ) :
"""Determine the size of a report given its type and header""" | fmt = self . known_formats [ current_type ]
return fmt . ReportLength ( report_header ) |
def register ( self , * args , ** kwargs ) :
'''调用方可根据主键字段进行爬虫的创建或更新操作
: return : 返回符合接口定义的字典数据
: rtype : dict''' | return { 'name' : zhihu . name , 'display_name' : zhihu . display_name , 'author' : zhihu . author , 'email' : zhihu . email , 'description' : zhihu . description , 'meta' : { # 爬取计划 , 参考 crontab 配置方法
'crawl_schedule' : '0 23 * * *' , # 执行爬取的随机延时 , 单位秒 , 用于避免被 Ban
'crawl_random_delay' : str ( 60 * 60 ) , 'package_modul... |
def tables ( self ) :
"""Return the list of table names in the database""" | tables = [ ]
self . cursor . execute ( "SELECT name FROM sqlite_master WHERE type='table'" )
for table_info in self . cursor . fetchall ( ) :
if table_info [ 0 ] != 'sqlite_sequence' :
tables . append ( table_info [ 0 ] )
return tables |
def check_path_matches_patterns ( path , patterns ) :
'''Check if the path matches at least one of the provided patterns .''' | path = os . path . abspath ( path )
for patt in patterns :
if isinstance ( patt , six . string_types ) :
if path == patt :
return True
elif patt . search ( path ) :
return True
return False |
def textrank ( self , sentence , topK = 20 , withWeight = False , allowPOS = ( 'ns' , 'n' , 'vn' , 'v' ) , withFlag = False ) :
"""Extract keywords from sentence using TextRank algorithm .
Parameter :
- topK : return how many top keywords . ` None ` for all possible words .
- withWeight : if True , return a l... | self . pos_filt = frozenset ( allowPOS )
g = UndirectWeightedGraph ( )
cm = defaultdict ( int )
words = tuple ( self . tokenizer . cut ( sentence ) )
for i , wp in enumerate ( words ) :
if self . pairfilter ( wp ) :
for j in xrange ( i + 1 , i + self . span ) :
if j >= len ( words ) :
... |
def isograph ( self , min_weight = None ) :
'''Remove short - circuit edges using the Isograph algorithm .
min _ weight : float , optional
Minimum weight of edges to consider removing . Defaults to max ( MST ) .
From " Isograph : Neighbourhood Graph Construction Based On Geodesic Distance
For Semi - Supervi... | W = self . matrix ( 'dense' )
# get candidate edges : all edges - MST edges
tree = self . minimum_spanning_subtree ( )
candidates = np . argwhere ( ( W - tree . matrix ( 'dense' ) ) > 0 )
cand_weights = W [ candidates [ : , 0 ] , candidates [ : , 1 ] ]
# order by increasing edge weight
order = np . argsort ( cand_weigh... |
def get_range ( self , start = None , stop = None ) :
"""Return a RangeMap for the range start to stop .
Returns :
A RangeMap""" | return self . from_iterable ( self . ranges ( start , stop ) ) |
def terminate ( self ) :
"""Terminate the Service execution .
. . versionadded : : 1.13
: return : None if the termination request was successful
: raises APIError : When the service execution could not be terminated .""" | url = self . _client . _build_url ( 'service_execution_terminate' , service_execution_id = self . id )
response = self . _client . _request ( 'GET' , url , params = dict ( format = 'json' ) )
if response . status_code != requests . codes . accepted : # pragma : no cover
raise APIError ( "Could not execute service '... |
def fit ( self , X , y , cost_mat , check_input = False ) :
"""Build a example - dependent cost - sensitive decision tree from the training set ( X , y , cost _ mat )
Parameters
y _ true : array indicator matrix
Ground truth ( correct ) labels .
X : array - like of shape = [ n _ samples , n _ features ]
T... | # TODO : Check input
# TODO : Add random state
n_samples , self . n_features_ = X . shape
self . tree_ = self . _tree_class ( )
# Maximum number of features to be taken into account per split
if isinstance ( self . max_features , six . string_types ) :
if self . max_features == "auto" :
max_features = max (... |
def datasource_process ( self , datasource_id ) :
"""deprecated
Запускает настроенные обработки в фиде
: param datasource _ id : uuid""" | # TODO Выпилить потом класс используется для другого
# TODO без applicationId не выбираются поля сущностей . Подумать на сколько это НЕ нормально
response = self . __app . native_api_call ( 'feed' , 'datasource/' + datasource_id + '/process?applicationId=1' , { } , self . __options , False , None , False , http_method... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.