signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def download ( self , output_dir , url , overwrite ) : """Dowload file to / tmp"""
tmp = self . url2tmp ( output_dir , url ) if os . path . isfile ( tmp ) and not overwrite : logging . info ( "File {0} already exists. Skipping download." . format ( tmp ) ) return tmp f = open ( tmp , 'wb' ) logging . info ( "Downloading {0}" . format ( url ) ) res = requests . get ( url , stream = True ) if r...
def visit_UnaryOp ( self , node : AST , dfltChaining : bool = True ) -> str : """Return representation of ` node ` s operator and operand ."""
op = node . op with self . op_man ( op ) : return self . visit ( op ) + self . visit ( node . operand )
def update_hash ( src_file ) : """Update the hash for the given file . Args : src : The file name . root : The path of the given file ."""
hash_file = local . path ( src_file ) + ".hash" new_hash = 0 with open ( hash_file , 'w' ) as h_file : new_hash = get_hash_of_dirs ( src_file ) h_file . write ( str ( new_hash ) ) return new_hash
def reset_clipboard ( self ) : """Resets the clipboard , so that old elements do not pollute the new selection that is copied into the clipboard . : return :"""
# reset selections for state_element_attr in ContainerState . state_element_attrs : self . model_copies [ state_element_attr ] = [ ] # reset parent state _ id the copied elements are taken from self . copy_parent_state_id = None self . reset_clipboard_mapping_dicts ( )
def _deep_merge_dict ( a , b ) : """Additively merge right side dict into left side dict ."""
for k , v in b . items ( ) : if k in a and isinstance ( a [ k ] , dict ) and isinstance ( v , dict ) : _deep_merge_dict ( a [ k ] , v ) else : a [ k ] = v
def build ( cls , node ) : """Construct a namer object for a given function scope ."""
if not isinstance ( node , gast . FunctionDef ) : raise ValueError namer = cls ( ) namer . names . update ( get_names ( node ) ) return namer
def cast_to_report ( self , value ) : """Report format uses only the value ' s id"""
value = super ( ValuesListField , self ) . cast_to_report ( value ) if value : return value [ 'id' ]
def flush ( self , include_footers : bool = False ) -> "Future[None]" : """Flushes the current output buffer to the network . The ` ` callback ` ` argument , if given , can be used for flow control : it will be run when all flushed data has been written to the socket . Note that only one flush callback can be...
assert self . request . connection is not None chunk = b"" . join ( self . _write_buffer ) self . _write_buffer = [ ] if not self . _headers_written : self . _headers_written = True for transform in self . _transforms : assert chunk is not None self . _status_code , self . _headers , chunk = tra...
def unpack_ip_addr ( addr ) : """Given a six - octet BACnet address , return an IP address tuple ."""
if isinstance ( addr , bytearray ) : addr = bytes ( addr ) return ( socket . inet_ntoa ( addr [ 0 : 4 ] ) , struct . unpack ( '!H' , addr [ 4 : 6 ] ) [ 0 ] )
def ip_rtm_config_route_static_route_oif_static_route_oif_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ip = ET . SubElement ( config , "ip" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" ) rtm_config = ET . SubElement ( ip , "rtm-config" , xmlns = "urn:brocade.com:mgmt:brocade-rtm" ) route = ET . SubElement ( rtm_config , "route" ) static_route_oif = ET . SubElement ( route , "sta...
def get_client_by_appid ( self , authorizer_appid ) : """通过 authorizer _ appid 获取 Client 对象 : params authorizer _ appid : 授权公众号appid"""
access_token_key = '{0}_access_token' . format ( authorizer_appid ) refresh_token_key = '{0}_refresh_token' . format ( authorizer_appid ) access_token = self . session . get ( access_token_key ) refresh_token = self . session . get ( refresh_token_key ) assert refresh_token if not access_token : ret = self . refres...
async def get_key_metadata ( wallet_handle : int , verkey : str ) -> str : """Retrieves the meta information for the giving key in the wallet . : param wallet _ handle : Wallet handle ( created by open _ wallet ) . : param verkey : The key ( verkey , key id ) to retrieve metadata . : return : metadata : The m...
logger = logging . getLogger ( __name__ ) logger . debug ( "get_key_metadata: >>> wallet_handle: %r, verkey: %r" , wallet_handle , verkey ) if not hasattr ( get_key_metadata , "cb" ) : logger . debug ( "get_key_metadata: Creating callback" ) get_key_metadata . cb = create_cb ( CFUNCTYPE ( None , c_int32 , c_int...
def parse_variable ( self , variable ) : """Method to parse an input or output variable . * * Example Variable * * : : # App : 1234 : output ! String Args : variable ( string ) : The variable name to parse . Returns : ( dictionary ) : Result of parsed string ."""
data = None if variable is not None : variable = variable . strip ( ) if re . match ( self . _variable_match , variable ) : var = re . search ( self . _variable_parse , variable ) data = { 'root' : var . group ( 0 ) , 'job_id' : var . group ( 2 ) , 'name' : var . group ( 3 ) , 'type' : var . gro...
def __convert_booleans ( self , eitem ) : """Convert True / False to 1/0 for better kibana processing"""
for field in eitem . keys ( ) : if isinstance ( eitem [ field ] , bool ) : if eitem [ field ] : eitem [ field ] = 1 else : eitem [ field ] = 0 return eitem
def run_final_eval ( train_session , module_spec , class_count , image_lists , jpeg_data_tensor , decoded_image_tensor , resized_image_tensor , bottleneck_tensor ) : """Runs a final evaluation on an eval graph using the test data set . Args : train _ session : Session for the train graph with the tensors below ...
test_bottlenecks , test_ground_truth , test_filenames = ( get_random_cached_bottlenecks ( train_session , image_lists , FLAGS . test_batch_size , 'testing' , FLAGS . bottleneck_dir , FLAGS . image_dir , jpeg_data_tensor , decoded_image_tensor , resized_image_tensor , bottleneck_tensor , FLAGS . tfhub_module ) ) ( eval_...
def wald_wolfowitz ( sequence ) : """implements the wald - wolfowitz runs test : http : / / en . wikipedia . org / wiki / Wald - Wolfowitz _ runs _ test http : / / support . sas . com / kb / 33/092 . html : param sequence : any iterable with at most 2 values . e . g . '1001001' [1 , 0 , 1 , 0 , 1] ' aba...
R = n_runs = sum ( 1 for s in groupby ( sequence , lambda a : a ) ) n = float ( sum ( 1 for s in sequence if s == sequence [ 0 ] ) ) m = float ( sum ( 1 for s in sequence if s != sequence [ 0 ] ) ) # expected mean runs ER = ( ( 2 * n * m ) / ( n + m ) ) + 1 # expected variance runs VR = ( 2 * n * m * ( 2 * n * m - n - ...
async def wait ( self ) : """EventSourceResponse object is used for streaming data to the client , this method returns future , so we can wain until connection will be closed or other task explicitly call ` ` stop _ streaming ` ` method ."""
if self . _ping_task is None : raise RuntimeError ( 'Response is not started' ) with contextlib . suppress ( asyncio . CancelledError ) : await self . _ping_task
def copy_to_region ( self , region ) : """Create a new key pair of the same new in another region . Note that the new key pair will use a different ssh cert than the this key pair . After doing the copy , you will need to save the material associated with the new key pair ( use the save method ) to a local ...
if region . name == self . region : raise BotoClientError ( 'Unable to copy to the same Region' ) conn_params = self . connection . get_params ( ) rconn = region . connect ( ** conn_params ) kp = rconn . create_key_pair ( self . name ) return kp
def path_regex ( self ) : """Return the regex for the path to the build folder ."""
regex = r'releases/%(VERSION)s/%(PLATFORM)s/%(LOCALE)s/' return regex % { 'LOCALE' : self . locale , 'PLATFORM' : self . platform_regex , 'VERSION' : self . version }
def showLayer ( self , title = '' , debugText = '' ) : """Shows the single layer . : param title : A string with the title of the window where to render the image . : param debugText : A string with some text to render over the image . : rtype : Nothing ."""
img = PIL . Image . fromarray ( self . data , 'RGBA' ) if debugText != '' : draw = PIL . ImageDraw . Draw ( img ) font = PIL . ImageFont . truetype ( "DejaVuSansMono.ttf" , 24 ) draw . text ( ( 0 , 0 ) , debugText , ( 255 , 255 , 255 ) , font = font ) img . show ( title = title )
def generate_evenly_distributed_data_sparse ( dim = 2000 , num_active = 40 , num_samples = 1000 ) : """Generates a set of data drawn from a uniform distribution . The binning structure from Poirazi & Mel is ignored , and all ( dim choose num _ active ) arrangements are possible ."""
indices = [ numpy . random . choice ( dim , size = num_active , replace = False ) for _ in range ( num_samples ) ] data = SM32 ( ) data . reshape ( 0 , dim ) for row in indices : data . addRowNZ ( row , [ 1 ] * num_active ) # data . reshape ( num _ samples , dim ) # for sample , datapoint in enumerate ( indices ) :...
def get ( self , sid ) : """Constructs a ReservationContext : param sid : The sid : returns : twilio . rest . taskrouter . v1 . workspace . task . reservation . ReservationContext : rtype : twilio . rest . taskrouter . v1 . workspace . task . reservation . ReservationContext"""
return ReservationContext ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , task_sid = self . _solution [ 'task_sid' ] , sid = sid , )
def append_transformed_structures ( self , tstructs_or_transmuter ) : """Method is overloaded to accept either a list of transformed structures or transmuter , it which case it appends the second transmuter " s structures . Args : tstructs _ or _ transmuter : A list of transformed structures or a transmut...
if isinstance ( tstructs_or_transmuter , self . __class__ ) : self . transformed_structures . extend ( tstructs_or_transmuter . transformed_structures ) else : for ts in tstructs_or_transmuter : assert isinstance ( ts , TransformedStructure ) self . transformed_structures . extend ( tstructs_or_tran...
def commit ( self ) : """Commit recorded changes , turn off recording , return changes ."""
assert self . record result = self . files_written , self . dirs_created self . _init_record ( ) return result
def validate_input ( function ) : """Decorator that validates the kwargs of the function passed to it ."""
@ wraps ( function ) def wrapper ( * args , ** kwargs ) : try : name = function . __name__ + '_validator' # find validator name globals ( ) [ name ] ( kwargs ) # call validation function return function ( * args , ** kwargs ) except KeyError : raise Exception ( "C...
def _src_media_url_for_video ( self , video ) : '''Get the url for the video media that we can send to Clarify'''
src_url = None best_height = 0 best_source = None # TODO : This assumes we have ingested videos . For remote videos , check if the remote flag is True # and if so , use the src url from the Asset endpoint . video_sources = self . bc_client . get_video_sources ( video [ 'id' ] ) # Look for codec H264 with good resolutio...
def getinfo ( self , disk , part = '' ) : """Get more info about a disk or a disk partition : param disk : ( / dev / sda , / dev / sdb , etc . . ) : param part : ( / dev / sda1 , / dev / sdb2 , etc . . . ) : return : a dict with { " blocksize " , " start " , " size " , and " free " sections }"""
args = { "disk" : disk , "part" : part , } self . _getpart_chk . check ( args ) response = self . _client . raw ( 'disk.getinfo' , args ) result = response . get ( ) if result . state != 'SUCCESS' : raise RuntimeError ( 'failed to get info: %s' % result . data ) if result . level != 20 : # 20 is JSON output . r...
def save_object ( self , obj , expected_value = None ) : """Marshal the object and do a PUT"""
doc = self . marshal_object ( obj ) if obj . id : url = "/%s/%s" % ( self . db_name , obj . id ) else : url = "/%s" % ( self . db_name ) resp = self . _make_request ( "PUT" , url , body = doc . toxml ( ) ) new_obj = self . get_object_from_doc ( obj . __class__ , None , parse ( resp ) ) obj . id = new_obj . id f...
def _get_referenced_type_equivalences ( graphql_types , type_equivalence_hints ) : """Filter union types with no edges from the type equivalence hints dict ."""
referenced_types = set ( ) for graphql_type in graphql_types . values ( ) : if isinstance ( graphql_type , ( GraphQLObjectType , GraphQLInterfaceType ) ) : for _ , field in graphql_type . fields . items ( ) : if isinstance ( field . type , GraphQLList ) : referenced_types . add (...
def permute ( self , ordering : np . ndarray , axis : int ) -> None : """Permute the dataset along the indicated axis . Args : ordering ( list of int ) : The desired order along the axis axis ( int ) : The axis along which to permute Returns : Nothing ."""
if self . _file . __contains__ ( "tiles" ) : del self . _file [ 'tiles' ] ordering = list ( np . array ( ordering ) . flatten ( ) ) # Flatten the ordering , in case we got a column vector self . layers . _permute ( ordering , axis = axis ) if axis == 0 : self . row_attrs . _permute ( ordering ) self . row_g...
def create_key ( key_type = 'RSA' , key_length = 1024 , name_real = 'Autogenerated Key' , name_comment = 'Generated by SaltStack' , name_email = None , subkey_type = None , subkey_length = None , expire_date = None , use_passphrase = False , user = None , gnupghome = None ) : '''Create a key in the GPG keychain ....
ret = { 'res' : True , 'fingerprint' : '' , 'message' : '' } create_params = { 'key_type' : key_type , 'key_length' : key_length , 'name_real' : name_real , 'name_comment' : name_comment , } gpg = _create_gpg ( user , gnupghome ) if name_email : create_params [ 'name_email' ] = name_email if subkey_type : creat...
def design ( npos ) : """make a design matrix for an anisotropy experiment"""
if npos == 15 : # rotatable design of Jelinek for kappabridge ( see Tauxe , 1998) A = np . array ( [ [ .5 , .5 , 0 , - 1. , 0 , 0 ] , [ .5 , .5 , 0 , 1. , 0 , 0 ] , [ 1 , .0 , 0 , 0 , 0 , 0 ] , [ .5 , .5 , 0 , - 1. , 0 , 0 ] , [ .5 , .5 , 0 , 1. , 0 , 0 ] , [ 0 , .5 , .5 , 0 , - 1. , 0 ] , [ 0 , .5 , .5 , 0 , 1. , ...
def _policyFileReplaceOrAppend ( this_string , policy_data , append_only = False ) : '''helper function to take a ADMX policy string for registry . pol file data and update existing string or append the string to the data'''
# we are going to clean off the special pre - fixes , so we get only the valuename if not policy_data : policy_data = b'' specialValueRegex = salt . utils . stringutils . to_bytes ( r'(\*\*Del\.|\*\*DelVals\.){0,1}' ) item_key = None item_value_name = None data_to_replace = None if not append_only : item_key = ...
def installed_add_ons ( self ) : """: rtype : twilio . rest . preview . marketplace . installed _ add _ on . InstalledAddOnList"""
if self . _installed_add_ons is None : self . _installed_add_ons = InstalledAddOnList ( self ) return self . _installed_add_ons
def load ( cls , filename ) : """Loads the experiment from disk . : param filename : the filename of the experiment to load : type filename : str : return : the experiment : rtype : Experiment"""
jobject = javabridge . static_call ( "weka/experiment/Experiment" , "read" , "(Ljava/lang/String;)Lweka/experiment/Experiment;" , filename ) return Experiment ( jobject = jobject )
def obtain_credentials ( credentials ) : """Prompt for credentials if possible . If the credentials are " - " then read from stdin without interactive prompting ."""
if credentials == "-" : credentials = sys . stdin . readline ( ) . strip ( ) elif credentials is None : credentials = try_getpass ( "API key (leave empty for anonymous access): " ) # Ensure that the credentials have a valid form . if credentials and not credentials . isspace ( ) : return Credentials . parse...
def list_users ( self , limit = None , marker = None ) : """Returns a list of the names of all users for this instance ."""
return self . _user_manager . list ( limit = limit , marker = marker )
def fill_default_satellites ( self , alignak_launched = False ) : # pylint : disable = too - many - branches , too - many - locals , too - many - statements """If a required satellite is missing in the configuration , we create a new satellite on localhost with some default values : param alignak _ launched : c...
# Log all satellites list logger . debug ( "Alignak configured daemons list:" ) self . log_daemons_list ( ) # We must create relations betweens the realms first . This is necessary to have # an accurate map of the situation ! self . realms . linkify ( ) self . realms . get_default ( check = True ) # Get list of known r...
def mkstemp ( suffix = "" , prefix = template , dir = None , text = False ) : """User - callable function to create and return a unique temporary file . The return value is a pair ( fd , name ) where fd is the file descriptor returned by os . open , and name is the filename . If ' suffix ' is specified , the ...
if dir is None : dir = gettempdir ( ) if text : flags = _text_openflags else : flags = _bin_openflags return _mkstemp_inner ( dir , prefix , suffix , flags )
def check_if_this_file_exist ( filename ) : """Check if this file exist and if it ' s a directory This function will check if the given filename actually exists and if it ' s not a Directory Arguments : filename { string } - - filename Return : True : if it ' s not a directory and if this file exist F...
# get the absolute path filename = os . path . abspath ( filename ) # Boolean this_file_exist = os . path . exists ( filename ) a_directory = os . path . isdir ( filename ) result = this_file_exist and not a_directory if result == False : raise ValueError ( 'The filename given was either non existent or was a direc...
def onMessageUnsent ( self , mid = None , author_id = None , thread_id = None , thread_type = None , ts = None , msg = None , ) : """Called when the client is listening , and someone unsends ( deletes for everyone ) a message : param mid : ID of the unsent message : param author _ id : The ID of the person who ...
log . info ( "{} unsent the message {} in {} ({}) at {}s" . format ( author_id , repr ( mid ) , thread_id , thread_type . name , ts / 1000 ) )
def switch_off ( self , * args ) : """Sets the state of the switch to False if off _ check ( ) returns True , given the arguments provided in kwargs . : param kwargs : variable length dictionary of key - pair arguments : return : Boolean . Returns True if the operation is successful"""
if self . off_check ( * args ) : return self . _switch . switch ( False ) else : return False
def check_header_validity ( header ) : """Verifies that header value is a string which doesn ' t contain leading whitespace or return characters . This prevents unintended header injection . : param header : tuple , in the format ( name , value ) ."""
name , value = header if isinstance ( value , bytes ) : pat = _CLEAN_HEADER_REGEX_BYTE else : pat = _CLEAN_HEADER_REGEX_STR try : if not pat . match ( value ) : raise InvalidHeader ( "Invalid return character or leading space in header: %s" % name ) except TypeError : raise InvalidHeader ( "Valu...
def joined ( name , host , user = 'rabbit' , ram_node = None , runas = 'root' ) : '''Ensure the current node joined to a cluster with node user @ host name Irrelevant , not used ( recommended : user @ host ) user The user of node to join to ( default : rabbit ) host The host of node to join to ram _ n...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } status = __salt__ [ 'rabbitmq.cluster_status' ] ( ) if '{0}@{1}' . format ( user , host ) in status : ret [ 'comment' ] = 'Already in cluster' return ret if not __opts__ [ 'test' ] : result = __salt__ [ 'rabbitmq.join_cluster' ] ( ...
def Import ( context , request ) : """Read analysis results from an XML string"""
errors = [ ] logs = [ ] # Do import stuff here logs . append ( "Generic XML Import is not available" ) results = { 'errors' : errors , 'log' : logs } return json . dumps ( results )
def _get_package_manager ( self ) : '''Get package manager . : return :'''
ret = None if self . __grains__ . get ( 'os_family' ) in ( 'Kali' , 'Debian' ) : ret = 'apt-get' elif self . __grains__ . get ( 'os_family' , '' ) == 'Suse' : ret = 'zypper' elif self . __grains__ . get ( 'os_family' , '' ) == 'redhat' : ret = 'yum' if ret is None : raise InspectorKiwiProcessorException...
def mangle_package_path ( self , files ) : """Mangle paths for post - UsrMove systems . If the system implements UsrMove , all files will be in ' / usr / [ s ] bin ' . This method substitutes all the / [ s ] bin references in the ' files ' list with ' / usr / [ s ] bin ' . : param files : the list of packag...
paths = [ ] def transform_path ( path ) : # Some packages actually own paths in / bin : in this case , # duplicate the path as both the / and / usr version . skip_paths = [ "/bin/rpm" , "/bin/mailx" ] if path in skip_paths : return ( path , os . path . join ( "/usr" , path [ 1 : ] ) ) return ( re . ...
def bddvar ( name , index = None ) : r"""Return a unique BDD variable . A Boolean * variable * is an abstract numerical quantity that may assume any value in the set : math : ` B = \ { 0 , 1 \ } ` . The ` ` bddvar ` ` function returns a unique Boolean variable instance represented by a binary decision diagr...
bvar = boolfunc . var ( name , index ) try : var = _VARS [ bvar . uniqid ] except KeyError : var = _VARS [ bvar . uniqid ] = BDDVariable ( bvar ) _BDDS [ var . node ] = var return var
def reverseGeocode ( self , location ) : """The reverseGeocode operation determines the address at a particular x / y location . You pass the coordinates of a point location to the geocoding service , and the service returns the address that is closest to the location . Input : location - either an Point ...
params = { "f" : "json" } url = self . _url + "/reverseGeocode" if isinstance ( location , Point ) : params [ 'location' ] = location . asDictionary elif isinstance ( location , list ) : params [ 'location' ] = "%s,%s" % ( location [ 0 ] , location [ 1 ] ) else : raise Exception ( "Invalid location" ) retur...
def add_clink ( self , my_clink ) : """Adds a clink to the causalRelations layer @ type my _ clink : L { Cclink } @ param my _ clink : clink object"""
if self . causalRelations_layer is None : self . causalRelations_layer = CcausalRelations ( ) self . root . append ( self . causalRelations_layer . get_node ( ) ) self . causalRelations_layer . add_clink ( my_clink )
def modify_process_property ( self , key , value , pid = None ) : '''modify _ process _ property ( self , key , value , pid = None ) Modify process output property . Please note that the process property key provided must be declared as an output property in the relevant service specification . : Parameters :...
pid = self . _get_pid ( pid ) request_data = { "key" : key , "value" : value } return self . _call_rest_api ( 'post' , '/processes/' + pid + '/output' , data = request_data , error = 'Failed to modify output property [%s]' % key )
def FromManagedObject ( self ) : """Method creates and returns an object of _ GenericMO class using the classId and other information from the managed object ."""
import os if ( isinstance ( self . mo , ManagedObject ) == True ) : self . classId = self . mo . classId if self . mo . getattr ( 'Dn' ) : self . dn = self . mo . getattr ( 'Dn' ) if self . mo . getattr ( 'Rn' ) : self . rn = self . mo . getattr ( 'Rn' ) elif self . dn : self . r...
def weave_layers ( infiles , output_file , log , context ) : """Apply text layer and / or image layer changes to baseline file This is where the magic happens . infiles will be the main PDF to modify , and optional . text . pdf and . image - layer . pdf files , organized however ruffus organizes them . From...
def input_sorter ( key ) : try : return page_number ( key ) except ValueError : return - 1 flat_inputs = sorted ( flatten_groups ( infiles ) , key = input_sorter ) groups = groupby ( flat_inputs , key = input_sorter ) # Extract first item _ , basegroup = next ( groups ) base = list ( basegroup )...
def get_coiledcoil_region ( self , cc_number = 0 , cutoff = 7.0 , min_kihs = 2 ) : """Assembly containing only assigned regions ( i . e . regions with contiguous KnobsIntoHoles ."""
g = self . filter_graph ( self . graph , cutoff = cutoff , min_kihs = min_kihs ) ccs = sorted ( networkx . connected_component_subgraphs ( g , copy = True ) , key = lambda x : len ( x . nodes ( ) ) , reverse = True ) cc = ccs [ cc_number ] helices = [ x for x in g . nodes ( ) if x . number in cc . nodes ( ) ] assigned_...
def create_alias ( FunctionName , Name , FunctionVersion , Description = "" , region = None , key = None , keyid = None , profile = None ) : '''Given a valid config , create an alias to a function . Returns { created : true } if the alias was created and returns { created : False } if the alias was not created ...
try : conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) alias = conn . create_alias ( FunctionName = FunctionName , Name = Name , FunctionVersion = FunctionVersion , Description = Description ) if alias : log . info ( 'The newly created alias name is %s' , alias [ ...
def extend_columns ( self , column_data , kind ) : """Extend column metadata : param column _ data : list of ( rel _ name , column _ name ) tuples : param kind : either ' tables ' or ' views ' : return :"""
# ' column _ data ' is a generator object . It can throw an exception while # being consumed . This could happen if the user has launched the app # without specifying a database name . This exception must be handled to # prevent crashing . try : column_data = [ self . escaped_names ( d , '"' ) for d in column_data ...
def reshape ( self , shape : tf . TensorShape ) -> 'TensorFluent' : '''Returns a TensorFluent for the reshape operation with given ` shape ` . Args : shape : The output ' s shape . Returns : A TensorFluent wrapping the reshape operation .'''
t = tf . reshape ( self . tensor , shape ) scope = self . scope . as_list ( ) batch = self . batch return TensorFluent ( t , scope , batch = batch )
def step_worker ( step , pipe , max_entities ) : """All messages follow the form : < message > , < data > Valid messages run , < input _ data > finalise , None next , None stop , None"""
state = None while True : message , input = pipe . recv ( ) if message == 'run' : state = step . run ( input , max_entities ) elif message == 'finalise' : state = step . finalise ( max_entities ) elif message == 'next' : try : data = state . next ( ) sys ....
def revnet_step ( name , x , hparams , reverse = True ) : """One step of glow generative flow . Actnorm + invertible 1X1 conv + affine _ coupling . Args : name : used for variable scope . x : input hparams : coupling _ width is the only hparam that is being used in this function . reverse : forward or...
with tf . variable_scope ( name , reuse = tf . AUTO_REUSE ) : if hparams . coupling == "additive" : coupling_layer = functools . partial ( additive_coupling , name = "additive" , reverse = reverse , mid_channels = hparams . coupling_width , activation = hparams . activation , dropout = hparams . coupling_dr...
def new_message_email ( sender , instance , signal , subject_prefix = _ ( u'New Message: %(subject)s' ) , template_name = "django_messages/new_message.html" , default_protocol = None , * args , ** kwargs ) : """This function sends an email and is called via Django ' s signal framework . Optional arguments : ` `...
if default_protocol is None : default_protocol = getattr ( settings , 'DEFAULT_HTTP_PROTOCOL' , 'http' ) if 'created' in kwargs and kwargs [ 'created' ] : try : current_domain = Site . objects . get_current ( ) . domain subject = subject_prefix % { 'subject' : instance . subject } messag...
def strictjoin ( L , keycols , nullvals = None , renaming = None , Names = None ) : """Combine two or more numpy ndarray with structured dtypes on common key column ( s ) . Merge a list ( or dictionary ) of numpy arrays , given by ` L ` , on key columns listed in ` keycols ` . The ` ` strictjoin ` ` assumes...
if isinstance ( L , dict ) : Names = L . keys ( ) LL = L . values ( ) else : if Names == None : Names = range ( len ( L ) ) else : assert len ( Names ) == len ( L ) LL = L if isinstance ( keycols , str ) : keycols = [ l . strip ( ) for l in keycols . split ( ',' ) ] assert all ( ...
def from_fault_data ( cls , edges , mesh_spacing ) : """Create and return a fault surface using fault source data . : param edges : A list of at least two horizontal edges of the surface as instances of : class : ` openquake . hazardlib . geo . line . Line ` . The list should be in top - to - bottom order (...
cls . check_fault_data ( edges , mesh_spacing ) surface_nodes = [ complex_fault_node ( edges ) ] mean_length = numpy . mean ( [ edge . get_length ( ) for edge in edges ] ) num_hor_points = int ( round ( mean_length / mesh_spacing ) ) + 1 if num_hor_points <= 1 : raise ValueError ( 'mesh spacing %.1f km is too big f...
def poissonSpikeGenerator ( firingRate , nBins , nTrials ) : """Generates a Poisson spike train . @ param firingRate ( int ) firing rate of sample of Poisson spike trains to be generated @ param nBins ( int ) number of bins or timesteps for the Poisson spike train @ param nTrials ( int ) number of trials ( or...
dt = 0.001 # we are simulating a ms as a single bin in a vector , ie 1sec = 1000bins poissonSpikeTrain = np . zeros ( ( nTrials , nBins ) , dtype = "uint32" ) for i in range ( nTrials ) : for j in range ( int ( nBins ) ) : if random . random ( ) < firingRate * dt : poissonSpikeTrain [ i , j ] = ...
def check_for_duplicate_comment ( self , new ) : """Check that a submitted comment isn ' t a duplicate . This might be caused by someone posting a comment twice . If it is a dup , silently return the * previous * comment ."""
possible_duplicates = self . get_comment_model ( ) . _default_manager . using ( self . target_object . _state . db ) . filter ( content_type = new . content_type , object_pk = new . object_pk ) for old in possible_duplicates : if old . post_date . date ( ) == new . post_date . date ( ) and old . text == new . text ...
def setInputFormatText ( self , text ) : """Sets the input format text for this widget to the given value . : param text | < str >"""
try : self . _inputFormat = XLineEdit . InputFormat [ nativestring ( text ) ] except KeyError : pass
def add_lfn ( self , lfn ) : """Add an LFN table to a parsed LIGO _ LW XML document . lfn = lfn to be added"""
if len ( self . table [ 'process' ] [ 'stream' ] ) > 1 : msg = "cannot add lfn to table with more than one process" raise LIGOLwParseError , msg # get the process _ id from the process table pid_col = self . table [ 'process' ] [ 'orderedcol' ] . index ( 'process_id' ) pid = self . table [ 'process' ] [ 'stream...
def get_task_fs ( self , courseid , taskid ) : """: param courseid : the course id of the course : param taskid : the task id of the task : raise InvalidNameException : return : A FileSystemProvider to the folder containing the task files"""
if not id_checker ( courseid ) : raise InvalidNameException ( "Course with invalid name: " + courseid ) if not id_checker ( taskid ) : raise InvalidNameException ( "Task with invalid name: " + taskid ) return self . _filesystem . from_subfolder ( courseid ) . from_subfolder ( taskid )
def avail_images ( call = None ) : '''Return a list of the images that are on the provider'''
if call == 'action' : raise SaltCloudSystemExit ( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) items = query ( action = 'template' ) ret = { } for item in items : ret [ item . attrib [ 'name' ] ] = item . attrib return ret
def getVersionFromArchiveId ( git_archive_id = '$Format:%ct %d$' ) : """Extract the tag if a source is from git archive . When source is exported via ` git archive ` , the git _ archive _ id init value is modified and placeholders are expanded to the " archived " revision : % ct : committer date , UNIX timest...
# mangle the magic string to make sure it is not replaced by git archive if not git_archive_id . startswith ( '$For' 'mat:' ) : # source was modified by git archive , try to parse the version from # the value of git _ archive _ id match = re . search ( r'tag:\s*v([^,)]+)' , git_archive_id ) if match : # archive...
def objectprep ( self ) : """Creates fastq files from an in - progress Illumina MiSeq run or create an object and moves files appropriately"""
# Create . fastq files if necessary . Otherwise create the metadata object if self . bcltofastq : if self . customsamplesheet : assert os . path . isfile ( self . customsamplesheet ) , 'Cannot find custom sample sheet as specified {}' . format ( self . customsamplesheet ) # Create the FASTQ files se...
def parse_tokens ( tokens ) : '''Read tokens strings into ( is _ flag , value ) tuples : For this value of ` tokens ` : [ ' - f ' , ' pets . txt ' , ' - v ' , ' cut ' , ' - cz ' , ' - - lost ' , ' - - delete = sam ' , ' - - ' , ' lester ' , ' jack ' ] ` flatten ( tokens ) ` yields an iterable : ( True , ' f...
# one pass max tokens = iter ( tokens ) for token in tokens : if token == '--' : # bleed out tokens without breaking , since tokens is an iterator for token in tokens : yield False , token elif token . startswith ( '-' ) : # this handles both - - last = man . txt and - czf = file . tgz #...
def bait ( self , maskmiddle = 'f' , k = '19' ) : """Use bbduk to perform baiting : param maskmiddle : boolean argument treat the middle base of a kmer as a wildcard ; increases sensitivity in the presence of errors . : param k : keyword argument for length of kmers to use in the analyses"""
logging . info ( 'Performing kmer baiting of fastq files with {at} targets' . format ( at = self . analysistype ) ) # There seems to be some sort of issue with java incorrectly calculating the total system memory on certain # computers . For now , calculate the memory , and feed it into the bbduk call if self . kmer_si...
def update_delisting ( self , num_iid , session ) : '''taobao . item . update . delisting 商品下架 单个商品下架 输入的num _ iid必须属于当前会话用户'''
request = TOPRequest ( 'taobao.item.update.delisting' ) request [ 'num_iid' ] = num_iid self . create ( self . execute ( request , session ) [ 'item' ] ) return self
def load_L3G_arduino ( filename , remove_begin_spurious = False , return_parser = False ) : "Load gyro data collected by the arduino version of the L3G logging platform , and return the data ( in rad / s ) , a time vector , and the sample rate ( seconds )"
file_data = open ( filename , 'rb' ) . read ( ) parser = L3GArduinoParser ( ) parser . parse ( file_data [ 7 : ] ) # Skip first " GYROLOG " header in file data = parser . data if parser . actual_data_rate : T = 1. / parser . actual_data_rate print ( "Found measured data rate %.3f ms (%.3f Hz)" % ( 1000 * T , 1....
def _byte_encode ( self , token ) : """Encode a single token byte - wise into integer ids ."""
# Vocab ids for all bytes follow ids for the subwords offset = len ( self . _subwords ) if token == "_" : return [ len ( self . _subwords ) + ord ( " " ) ] return [ i + offset for i in list ( bytearray ( tf . compat . as_bytes ( token ) ) ) ]
def autobuild_doxygen ( tile ) : """Generate documentation for firmware in this module using doxygen"""
iotile = IOTile ( '.' ) doxydir = os . path . join ( 'build' , 'doc' ) doxyfile = os . path . join ( doxydir , 'doxygen.txt' ) outfile = os . path . join ( doxydir , '%s.timestamp' % tile . unique_id ) env = Environment ( ENV = os . environ , tools = [ ] ) env [ 'IOTILE' ] = iotile # There is no / dev / null on Windows...
def _mmInit ( self ) : """Create the minimum match dictionary of keys"""
# cache references to speed up loop a bit mmkeys = { } mmkeysGet = mmkeys . setdefault minkeylength = self . minkeylength for key in self . data . keys ( ) : # add abbreviations as short as minkeylength # always add at least one entry ( even for key = " " ) lenkey = len ( key ) start = min ( minkeylength , lenk...
def clip_upper ( self , threshold , axis = None , inplace = False ) : """Trim values above a given threshold . . . deprecated : : 0.24.0 Use clip ( upper = threshold ) instead . Elements above the ` threshold ` will be changed to match the ` threshold ` value ( s ) . Threshold can be a single value or an ar...
warnings . warn ( 'clip_upper(threshold) is deprecated, ' 'use clip(upper=threshold) instead' , FutureWarning , stacklevel = 2 ) return self . _clip_with_one_bound ( threshold , method = self . le , axis = axis , inplace = inplace )
def merge_dicts ( dict1 , dict2 , deep_merge = True ) : """Merge dict2 into dict1."""
if deep_merge : if isinstance ( dict1 , list ) and isinstance ( dict2 , list ) : return dict1 + dict2 if not isinstance ( dict1 , dict ) or not isinstance ( dict2 , dict ) : return dict2 for key in dict2 : dict1 [ key ] = merge_dicts ( dict1 [ key ] , dict2 [ key ] ) if key in dict1 ...
def compute_volume ( sizes , centers , normals ) : """Compute the numerical volume of a convex mesh : parameter array sizes : array of sizes of triangles : parameter array centers : array of centers of triangles ( x , y , z ) : parameter array normals : array of normals of triangles ( will normalize if not al...
# the volume of a slanted triangular cone is A _ triangle * ( r _ vec dot norm _ vec ) / 3. # TODO : implement normalizing normals into meshing routines ( or at least have them supply normal _ mags to the mesh ) # TODO : remove this function - should now be returned by the meshing algorithm itself # although wd method ...
def is_unit_or_unitstring ( value ) : """must be an astropy . unit"""
if is_unit ( value ) [ 0 ] : return True , value try : unit = units . Unit ( value ) except : return False , value else : return True , unit
def all ( self , ** kwargs ) : """List all the members , included inherited ones . Args : all ( bool ) : If True , return all the items , without pagination per _ page ( int ) : Number of items to retrieve per request page ( int ) : ID of the page to return ( starts with page 1) as _ list ( bool ) : If se...
path = '%s/all' % self . path obj = self . gitlab . http_list ( path , ** kwargs ) return [ self . _obj_cls ( self , item ) for item in obj ]
def setCurrentNode ( self , node ) : """Sets the currently selected node in the scene . If multiple nodes are selected , then the last one selected \ will be considered the current one . : param node | < XNode > | | None"""
self . blockSignals ( True ) self . clearSelection ( ) if node : node . setSelected ( True ) self . blockSignals ( False )
def get_binaries ( ) : """Download and return paths of all platform - specific binaries"""
paths = [ ] for arp in [ False , True ] : paths . append ( get_binary ( arp = arp ) ) return paths
def display_all ( self ) : """Print detailed information ."""
print ( ( "total elapse %0.6f seconds, last elapse %0.6f seconds, " "took %s times measurement" ) % ( self . total_elapse , self . elapse , len ( self . records ) ) )
def uri_with ( uri , scheme = None , netloc = None , path = None , params = None , query = None , fragment = None ) : """Return a URI with the given part ( s ) replaced . Parts are decoded / encoded ."""
old_scheme , old_netloc , old_path , old_params , old_query , old_fragment = urlparse ( uri ) path , _netloc = _normalize_win_path ( path ) return urlunparse ( ( scheme or old_scheme , netloc or old_netloc , path or old_path , params or old_params , query or old_query , fragment or old_fragment ) )
def create_pull_request ( self , git_pull_request_to_create , repository_id , project = None , supports_iterations = None ) : """CreatePullRequest . [ Preview API ] Create a pull request . : param : class : ` < GitPullRequest > < azure . devops . v5_1 . git . models . GitPullRequest > ` git _ pull _ request _ t...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if repository_id is not None : route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' ) query_parameters = { } if supports_iterations is n...
def add_formatter ( self , sqla_col_type , formatter , key_specific = None ) : """Add a formatter to the registry if key _ specific is provided , this formatter will only be used for some specific exports"""
self . add_item ( sqla_col_type , formatter , key_specific )
def _list_tenants ( self , admin ) : """Returns either a list of all tenants ( admin = True ) , or the tenant for the currently - authenticated user ( admin = False ) ."""
resp , resp_body = self . method_get ( "tenants" , admin = admin ) if 200 <= resp . status_code < 300 : tenants = resp_body . get ( "tenants" , [ ] ) return [ Tenant ( self , tenant ) for tenant in tenants ] elif resp . status_code in ( 401 , 403 ) : raise exc . AuthorizationFailure ( "You are not authorize...
def on_source_directory_chooser_clicked ( self ) : """Autoconnect slot activated when tbSourceDir is clicked ."""
title = self . tr ( 'Set the source directory for script and scenario' ) self . choose_directory ( self . source_directory , title )
def copy ( self , memo = None , which = None ) : """Returns a ( deep ) copy of the current parameter handle . All connections to parents of the copy will be cut . : param dict memo : memo for deepcopy : param Parameterized which : parameterized object which started the copy process [ default : self ]"""
# raise NotImplementedError , " Copy is not yet implemented , TODO : Observable hierarchy " if memo is None : memo = { } import copy # the next part makes sure that we do not include parents in any form : parents = [ ] if which is None : which = self which . traverse_parents ( parents . append ) # collect paren...
def warning ( self , msg , * args , ** kwargs ) -> Task : # type : ignore """Log msg with severity ' WARNING ' . To pass exception information , use the keyword argument exc _ info with a true value , e . g . await logger . warning ( " Houston , we have a bit of a problem " , exc _ info = 1)"""
return self . _make_log_task ( logging . WARNING , msg , args , ** kwargs )
def _redirect ( self , args ) : """asks the client to use a different server This method redirects the client to another server , based on the requested virtual host and / or capabilities . RULE : When getting the Connection . Redirect method , the client SHOULD reconnect to the host specified , and if th...
host = args . read_shortstr ( ) self . known_hosts = args . read_shortstr ( ) AMQP_LOGGER . debug ( 'Redirected to [%s], known_hosts [%s]' % ( host , self . known_hosts ) ) return host
def do_add_x10_device ( self , args ) : """Add an X10 device to the IM . Usage : add _ x10 _ device housecode unitcode type Arguments : housecode : Device housecode ( A - P ) unitcode : Device unitcode ( 1 - 16) type : Device type Current device types are : - OnOff - Dimmable - Sensor Example ...
params = args . split ( ) housecode = None unitcode = None dev_type = None try : housecode = params [ 0 ] unitcode = int ( params [ 1 ] ) if unitcode not in range ( 1 , 17 ) : raise ValueError dev_type = params [ 2 ] except IndexError : pass except ValueError : _LOGGING . error ( 'X10 un...
def init ( self , with_soft = True ) : """The method for the SAT oracle initialization . Since the oracle is is used non - incrementally , it is reinitialized at every iteration of the MaxSAT algorithm ( see : func : ` reinit ` ) . An input parameter ` ` with _ soft ` ` ( ` ` False ` ` by default ) regulates ...
self . oracle = Solver ( name = self . solver , bootstrap_with = self . hard , use_timer = True ) # self . atm1 is not empty only in case of minicard for am in self . atm1 : self . oracle . add_atmost ( * am ) if with_soft : for cl , cpy in zip ( self . soft , self . scpy ) : if cpy : self ....
def get_current_user ( self ) : """Override get _ current _ user for Google AppEngine Checks for oauth capable request first , if this fails fall back to standard users API"""
from google . appengine . api import users if _IS_DEVELOPMENT_SERVER : return users . get_current_user ( ) else : from google . appengine . api import oauth try : user = oauth . get_current_user ( ) except oauth . OAuthRequestError : user = users . get_current_user ( ) return user
def _nest_variable ( v , check_records = False ) : """Nest a variable when moving from scattered back to consolidated . check _ records - - avoid re - nesting a record input if it comes from a previous step and is already nested , don ' t need to re - array ."""
if ( check_records and is_cwl_record ( v ) and len ( v [ "id" ] . split ( "/" ) ) > 1 and v . get ( "type" , { } ) . get ( "type" ) == "array" ) : return v else : v = copy . deepcopy ( v ) v [ "type" ] = { "type" : "array" , "items" : v [ "type" ] } return v
def copy ( self ) : """Copy this object into a new object of the same type . The returned object will not have a parent object ."""
copyClass = self . copyClass if copyClass is None : copyClass = self . __class__ copied = copyClass ( ) copied . copyData ( self ) return copied
def _set_splits ( self , split_dict ) : """Split setter ( private method ) ."""
# Update the dictionary representation . # Use from / to proto for a clean copy self . _splits = split_dict . copy ( ) # Update the proto del self . as_proto . splits [ : ] # Clear previous for split_info in split_dict . to_proto ( ) : self . as_proto . splits . add ( ) . CopyFrom ( split_info )
def conf_budget ( self , budget ) : """Set limit on the number of conflicts ."""
if self . minisat : pysolvers . minisatgh_cbudget ( self . minisat , budget )