signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def addGeneTargetingReagent ( self , reagent_id , reagent_label , reagent_type , gene_id , description = None ) : """Here , a gene - targeting reagent is added . The actual targets of this reagent should be added separately . : param reagent _ id : : param reagent _ label : : param reagent _ type : : retu...
# TODO add default type to reagent _ type self . model . addIndividualToGraph ( reagent_id , reagent_label , reagent_type , description ) self . graph . addTriple ( reagent_id , self . globaltt [ 'targets_gene' ] , gene_id ) return
def assemble_transition_model_from_gradable_adjectives ( self ) : """Add probability distribution functions constructed from gradable adjective data to the edges of the analysis graph data structure . Args : adjective _ data res"""
df = pd . read_sql_table ( "gradableAdjectiveData" , con = engine ) gb = df . groupby ( "adjective" ) rs = gaussian_kde ( flatMap ( lambda g : gaussian_kde ( get_respdevs ( g [ 1 ] ) ) . resample ( self . res ) [ 0 ] . tolist ( ) , gb , ) ) . resample ( self . res ) [ 0 ] for edge in self . edges ( data = True ) : ...
def load ( target , source_module = None ) : """Get the actual implementation of the target ."""
module , klass , function = _get_module ( target ) if not module and source_module : module = source_module if not module : raise MissingModule ( "No module name supplied or source_module provided." ) actual_module = sys . modules [ module ] if not klass : return getattr ( actual_module , function ) class_o...
def _update_return_dict ( ret , success , data , errors = None , warnings = None ) : '''PRIVATE METHOD Updates the return dictionary and returns it . ret : dict < str , obj > The original return dict to update . The ret param should have been created from _ get _ return _ dict ( ) success : boolean ( True...
errors = [ ] if errors is None else errors warnings = [ ] if warnings is None else warnings ret [ 'success' ] = success ret [ 'data' ] . update ( data ) ret [ 'errors' ] = ret [ 'errors' ] + errors ret [ 'warnings' ] = ret [ 'warnings' ] + warnings return ret
def path_file_to_list ( path_file ) : """: return : A list with the paths which are stored in a text file in a line - by - line format . Validate each path using is _ valid _ path"""
paths = [ ] path_file_fd = file ( path_file ) for line_no , line in enumerate ( path_file_fd . readlines ( ) , start = 1 ) : line = line . strip ( ) if not line : # Blank line support continue if line . startswith ( '#' ) : # Comment support continue try : is_valid_path ( line ) ...
def replace_variable ( self , variable ) : """Substitute variables with numeric values"""
if variable == 'x' : return self . value if variable == 't' : return self . timedelta raise ValueError ( "Invalid variable %s" , variable )
def f_extend_old ( map , s ) : """Extend map of function to cover sphere " twice " up to theta = 2pi This introduces new points when Nphi is odd , and duplicates values when Nphi is even , making it easier to perform certain transformation operations . This is mostly an internal function , included here for b...
import numpy as np map = np . ascontiguousarray ( map , dtype = np . complex128 ) extended_map = np . empty ( ( 2 * ( map . shape [ 0 ] - 1 ) , map . shape [ 1 ] , ) , dtype = np . complex128 ) _f_extend_old ( map , extended_map , s ) return extended_map
def fixpointmethod ( self , cfg_node ) : """The most important part of PyT , where we perform the variant of reaching definitions to find where sources reach ."""
JOIN = self . join ( cfg_node ) # Assignment check if isinstance ( cfg_node , AssignmentNode ) : arrow_result = JOIN # Reassignment check if cfg_node . left_hand_side not in cfg_node . right_hand_side_variables : # Get previous assignments of cfg _ node . left _ hand _ side and remove them from JOIN ...
def visit_unaryop ( self , node , parent ) : """visit a UnaryOp node by returning a fresh instance of it"""
newnode = nodes . UnaryOp ( self . _unary_op_classes [ node . op . __class__ ] , node . lineno , node . col_offset , parent , ) newnode . postinit ( self . visit ( node . operand , newnode ) ) return newnode
def addGaussNoise ( self , sigma ) : """Add gaussian noise . : param float sigma : sigma is expressed in percent of the diagonal size of actor . : Example : . . code - block : : python from vtkplotter import Sphere Sphere ( ) . addGaussNoise ( 1.0 ) . show ( )"""
sz = self . diagonalSize ( ) pts = self . coordinates ( ) n = len ( pts ) ns = np . random . randn ( n , 3 ) * sigma * sz / 100 vpts = vtk . vtkPoints ( ) vpts . SetNumberOfPoints ( n ) vpts . SetData ( numpy_to_vtk ( pts + ns , deep = True ) ) self . poly . SetPoints ( vpts ) self . poly . GetPoints ( ) . Modified ( )...
def cloud_init_interface ( name , vm_ = None , ** kwargs ) : '''Interface between salt . cloud . lxc driver and lxc . init ` ` vm _ ` ` is a mapping of vm opts in the salt . cloud format as documented for the lxc driver . This can be used either : - from the salt cloud driver - because you find the argume...
if vm_ is None : vm_ = { } vm_ = copy . deepcopy ( vm_ ) vm_ = salt . utils . dictupdate . update ( vm_ , kwargs ) profile_data = copy . deepcopy ( vm_ . get ( 'lxc_profile' , vm_ . get ( 'profile' , { } ) ) ) if not isinstance ( profile_data , ( dict , six . string_types ) ) : profile_data = { } profile = get_...
def dropout_no_scaling ( x , keep_prob ) : """Like tf . nn . dropout , but does not scale up . Works on integers also . Args : x : a Tensor keep _ prob : a floating point number Returns : Tensor of the same shape as x ."""
if keep_prob == 1.0 : return x mask = tf . less ( tf . random_uniform ( tf . shape ( x ) ) , keep_prob ) return x * cast_like ( mask , x )
def local ( reload , port ) : """run local app server , assumes into the account"""
import logging from bottle import run from app import controller , app from c7n . resources import load_resources load_resources ( ) print ( "Loaded resources definitions" ) logging . basicConfig ( level = logging . DEBUG ) logging . getLogger ( 'botocore' ) . setLevel ( logging . WARNING ) if controller . db . provisi...
def space_clone ( args ) : """Replicate a workspace"""
# FIXME : add - - deep copy option ( shallow by default ) # add aliasing capability , then make space _ copy alias if not args . to_workspace : args . to_workspace = args . workspace if not args . to_project : args . to_project = args . project if ( args . project == args . to_project and args . workspace == ar...
def on_down ( self , host ) : """Called by the parent Cluster instance when a node is marked down . Only intended for internal use ."""
future = self . remove_pool ( host ) if future : future . add_done_callback ( lambda f : self . update_created_pools ( ) )
def render_workflow_html_template ( filename , subtemplate , filelists , ** kwargs ) : """Writes a template given inputs from the workflow generator . Takes a list of tuples . Each tuple is a pycbc File object . Also the name of the subtemplate to render and the filename of the output ."""
dirnam = os . path . dirname ( filename ) makedir ( dirnam ) try : filenames = [ f . name for filelist in filelists for f in filelist if f is not None ] except TypeError : filenames = [ ] # render subtemplate subtemplate_dir = pycbc . results . __path__ [ 0 ] + '/templates/wells' env = Environment ( loader = Fi...
def _next_sample_index ( self ) : """Rotates through each active sampler by incrementing the index"""
# Return the next streamer index where the streamer is not None , # wrapping around . idx = self . active_index_ self . active_index_ += 1 if self . active_index_ >= len ( self . streams_ ) : self . active_index_ = 0 # Continue to increment if this streamer is exhausted ( None ) # This should never be infinite loop...
def reverse_readline ( m_file , blk_size = 4096 , max_mem = 4000000 ) : """Generator method to read a file line - by - line , but backwards . This allows one to efficiently get data at the end of a file . Based on code by Peter Astrand < astrand @ cendio . se > , using modifications by Raymond Hettinger and K...
# Check if the file stream is a bit stream or not is_text = isinstance ( m_file , io . TextIOWrapper ) try : file_size = os . path . getsize ( m_file . name ) except AttributeError : # Bz2 files do not have name attribute . Just set file _ size to above # max _ mem for now . file_size = max_mem + 1 # If the fil...
def parse_wordnet ( self , debug = False ) : '''Parses wordnet from < self . file >'''
synList = [ ] self . milestone = 0 # to start from beginning of file while self . milestone < os . path . getsize ( self . fileName ) - 5 : if debug : print ( 'self.milestone' , self . milestone ) a = self . parse_synset ( offset = self . milestone ) synList . append ( a ) self . milestone = sel...
def get_all_mfa_devices ( user_name , region = None , key = None , keyid = None , profile = None ) : '''Get all MFA devices associated with an IAM user . . . versionadded : : 2016.3.0 CLI Example : . . code - block : : bash salt myminion boto _ iam . get _ all _ mfa _ devices user _ name'''
user = get_user ( user_name , region , key , keyid , profile ) if not user : log . error ( 'IAM user %s does not exist' , user_name ) return False conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) try : result = conn . get_all_mfa_devices ( user_name ) devices = result...
def interpret_script ( shell_script ) : """Make it appear as if commands are typed into the terminal ."""
with CaptureOutput ( ) as capturer : shell = subprocess . Popen ( [ 'bash' , '-' ] , stdin = subprocess . PIPE ) with open ( shell_script ) as handle : for line in handle : sys . stdout . write ( ansi_wrap ( '$' , color = 'green' ) + ' ' + line ) sys . stdout . flush ( ) ...
def Bradford ( q , low = 0 , high = 1 , tag = None ) : """A Bradford random variate Parameters q : scalar The shape parameter low : scalar The lower bound of the distribution ( default = 0) high : scalar The upper bound of the distribution ( default = 1)"""
assert q > 0 , 'Bradford "q" parameter must be greater than zero' assert low < high , 'Bradford "low" parameter must be less than "high"' return uv ( ss . bradford ( q , loc = low , scale = high - low ) , tag = tag )
def create ( cls , monetary_account_paying_id , request_id , maximum_amount_per_month , custom_headers = None ) : """Create a new SDD whitelist entry . : type user _ id : int : param monetary _ account _ paying _ id : ID of the monetary account of which you want to pay from . : type monetary _ account _ pay...
if custom_headers is None : custom_headers = { } request_map = { cls . FIELD_MONETARY_ACCOUNT_PAYING_ID : monetary_account_paying_id , cls . FIELD_REQUEST_ID : request_id , cls . FIELD_MAXIMUM_AMOUNT_PER_MONTH : maximum_amount_per_month } request_map_string = converter . class_to_json ( request_map ) request_map_st...
def attempt ( self , * kinds ) : """Try to get the next token if it matches one of the kinds given , otherwise returning None . If no kinds are given , any kind is accepted ."""
if self . _error : raise self . _error token = self . next_token if not token : return None if kinds and token . kind not in kinds : return None self . _advance ( ) return token
def maybe_infer_tz ( tz , inferred_tz ) : """If a timezone is inferred from data , check that it is compatible with the user - provided timezone , if any . Parameters tz : tzinfo or None inferred _ tz : tzinfo or None Returns tz : tzinfo or None Raises TypeError : if both timezones are present but d...
if tz is None : tz = inferred_tz elif inferred_tz is None : pass elif not timezones . tz_compare ( tz , inferred_tz ) : raise TypeError ( 'data is already tz-aware {inferred_tz}, unable to ' 'set specified tz: {tz}' . format ( inferred_tz = inferred_tz , tz = tz ) ) return tz
def _handle_problem_status ( self , message , future ) : """Handle the results of a problem submission or results request . This method checks the status of the problem and puts it in the correct queue . Args : message ( dict ) : Update message from the SAPI server wrt . this problem . future ` Future ` : f...
try : _LOGGER . trace ( "Handling response: %r" , message ) _LOGGER . debug ( "Handling response for %s with status %s" , message . get ( 'id' ) , message . get ( 'status' ) ) # Handle errors in batch mode if 'error_code' in message and 'error_msg' in message : raise SolverFailureError ( message...
def extract_data_from_response ( self , response , data_key = None ) : """Given a response and an optional data _ key should return a dictionary of data returned as part of the response ."""
response_json_data = response . json ( ) # Seems to be two types of response , a dict with keys and then lists of data or a flat list data with no key . if type ( response_json_data ) == list : # Return the data return response_json_data elif type ( response_json_data ) == dict : if data_key is None : r...
def piGenGosper ( ) : """A generator function that yields the digits of Pi"""
z = ( ( 1 , 0 , 0 , 1 ) , 1 ) while True : lft = __lfts ( z [ 1 ] ) n = int ( __next ( z ) ) if __safe ( z , n ) : z = __prod ( z , n ) yield n else : z = __cons ( z , lft )
def read ( self , searched_resource , uri_parameters = None , request_body_dict = None , query_parameters_dict = None , additional_headers = None ) : """This method is used to read a resource using the GET HTTP Method : param searched _ resource : A valid display name in the RAML file matching the resource : pa...
return self . _request ( searched_resource , 'get' , uri_parameters , request_body_dict , query_parameters_dict , additional_headers )
def _setup ( self ) : """Performs the RFXtrx initialisation protocol in a Future . Currently this is the rough workflow of the interactions with the RFXtrx . We also do a few extra things - flush the buffer , and attach readers / writers to the asyncio loop . 1 . Write a RESET packet ( write all zeros ) 2...
self . log . info ( "Adding reader to prepare to receive." ) self . loop . add_reader ( self . dev . fd , self . read ) self . log . info ( "Flushing the RFXtrx buffer." ) self . flushSerialInput ( ) self . log . info ( "Writing the reset packet to the RFXtrx. (blocking)" ) yield from self . sendRESET ( ) self . log . ...
def _apply_line_rules ( self , markdown_string ) : """Iterates over the lines in a given markdown string and applies all the enabled line rules to each line"""
all_violations = [ ] lines = markdown_string . split ( "\n" ) line_rules = self . line_rules line_nr = 1 ignoring = False for line in lines : if ignoring : if line . strip ( ) == '<!-- markdownlint:enable -->' : ignoring = False else : if line . strip ( ) == '<!-- markdownlint:disabl...
def parse_deps ( orig_doc , options = { } ) : """Generate dependency parse in { ' words ' : [ ] , ' arcs ' : [ ] } format . doc ( Doc ) : Document do parse . RETURNS ( dict ) : Generated dependency parse keyed by words and arcs ."""
doc = Doc ( orig_doc . vocab ) . from_bytes ( orig_doc . to_bytes ( ) ) if not doc . is_parsed : user_warning ( Warnings . W005 ) if options . get ( "collapse_phrases" , False ) : with doc . retokenize ( ) as retokenizer : for np in list ( doc . noun_chunks ) : attrs = { "tag" : np . root . ...
def contraction_string ( element ) : """Forms a string specifying the contractions for an element ie , ( 16s , 10p ) - > [ 4s , 3p ]"""
# Does not have electron shells ( ECP only ? ) if 'electron_shells' not in element : return "" cont_map = dict ( ) for sh in element [ 'electron_shells' ] : nprim = len ( sh [ 'exponents' ] ) ngeneral = len ( sh [ 'coefficients' ] ) # is a combined general contraction ( sp , spd , etc ) is_spdf = le...
def eucdist_task ( newick_string_a , newick_string_b , normalise , min_overlap = 4 , overlap_fail_value = 0 ) : """Distributed version of tree _ distance . eucdist Parameters : two valid newick strings and a boolean"""
tree_a = Tree ( newick_string_a ) tree_b = Tree ( newick_string_b ) return treedist . eucdist ( tree_a , tree_b , normalise , min_overlap , overlap_fail_value )
def weld_str_find ( array , sub , start , end ) : """Return index of sub in elements if found , else - 1. Parameters array : numpy . ndarray or WeldObject Input data . sub : str To check for . start : int Start index for searching . end : int or None Stop index for searching . Returns WeldObje...
obj_id , weld_obj = create_weld_object ( array ) sub_id = get_weld_obj_id ( weld_obj , sub ) if end is None : end = 'len(e)' else : end = to_weld_literal ( end , WeldLong ( ) ) start = to_weld_literal ( start , WeldLong ( ) ) # TODO : maybe be more friendly and fix end > = len ( e ) to be len ( e ) - 1? weld_te...
def make_dataset ( self , dataset , raise_if_exists = False , body = None ) : """Creates a new dataset with the default permissions . : param dataset : : type dataset : BQDataset : param raise _ if _ exists : whether to raise an exception if the dataset already exists . : raises luigi . target . FileAlready...
if body is None : body = { } try : # Construct a message body in the format required by # https : / / developers . google . com / resources / api - libraries / documentation / bigquery / v2 / python / latest / bigquery _ v2 . datasets . html # insert body [ 'datasetReference' ] = { 'projectId' : dataset . proje...
def next ( self ) : """Move to the next valid locus . Will only return valid loci or exit via StopIteration exception"""
while True : self . cur_idx += 1 if self . __datasource . populate_iteration ( self ) : return self raise StopIteration
def get_header_items ( self ) : """Get an iterable list of key / value pairs representing headers . This function provides Python 2/3 compatibility as related to the parsing of request headers . Python 2.7 is not compliant with RFC 3875 Section 4.1.18 which requires multiple values for headers to be provide...
if PY2 : # For Python 2 , process the headers manually according to # W3C RFC 2616 Section 4.2. items = [ ] for header in self . headers . headers : # Remove " \ n \ r " from the header and split on " : " to get # the field name and value . key , value = header [ 0 : - 2 ] . split ( ":" , 1 ) ...
def substitute_placeholders ( inputstring , placeholders ) : """Take a string with placeholders , and return the strings with substitutions ."""
newst = inputstring . format ( link = placeholders . link , filename = placeholders . filename , directory = placeholders . directory , fullpath = placeholders . fullpath , title = placeholders . title , filename_title = placeholders . filename_title , date = placeholders . date_string ( ) , podcasttitle = placeholders...
def set ( self , obj , build_kwargs ) : """Set cached value ."""
if build_kwargs is None : build_kwargs = { } cached = { } if 'queryset' in build_kwargs : cached = { 'model' : build_kwargs [ 'queryset' ] . model , 'pks' : list ( build_kwargs [ 'queryset' ] . values_list ( 'pk' , flat = True ) ) , } elif 'obj' in build_kwargs : cached = { 'obj' : build_kwargs [ 'obj' ] , ...
def read_from_file ( cls , filename : str , question : List [ Token ] ) -> 'TableQuestionKnowledgeGraph' : """We read tables formatted as TSV files here . We assume the first line in the file is a tab separated list of column headers , and all subsequent lines are content rows . For example if the TSV file is :...
return cls . read_from_lines ( open ( filename ) . readlines ( ) , question )
def StopHunt ( hunt_id , reason = None ) : """Stops a hunt with a given id ."""
hunt_obj = data_store . REL_DB . ReadHuntObject ( hunt_id ) if hunt_obj . hunt_state not in [ hunt_obj . HuntState . STARTED , hunt_obj . HuntState . PAUSED ] : raise OnlyStartedOrPausedHuntCanBeStoppedError ( hunt_obj ) data_store . REL_DB . UpdateHuntObject ( hunt_id , hunt_state = hunt_obj . HuntState . STOPPED ...
def get_projects ( osa_repo_dir , commit ) : """Get all projects from multiple YAML files ."""
# Check out the correct commit SHA from the repository repo = Repo ( osa_repo_dir ) checkout ( repo , commit ) yaml_files = glob . glob ( '{0}/playbooks/defaults/repo_packages/*.yml' . format ( osa_repo_dir ) ) yaml_parsed = [ ] for yaml_file in yaml_files : with open ( yaml_file , 'r' ) as f : yaml_parsed ...
def remove ( self , slide_layout ) : """Remove * slide _ layout * from the collection . Raises ValueError when * slide _ layout * is in use ; a slide layout which is the basis for one or more slides cannot be removed ."""
# - - - raise if layout is in use - - - if slide_layout . used_by_slides : raise ValueError ( 'cannot remove slide-layout in use by one or more slides' ) # - - - target layout is identified by its index in this collection - - - target_idx = self . index ( slide_layout ) # - - remove layout from p : sldLayoutIds of ...
def setSubgraphVal ( self , parent_name , graph_name , field_name , val ) : """Set Value for Field in Subgraph . The private method is for use in retrieveVals ( ) method of child classes . @ param parent _ name : Root Graph Name @ param graph _ name : Subgraph Name @ param field _ name : Field Name . @ ...
subgraph = self . _getSubGraph ( parent_name , graph_name , True ) if subgraph . hasField ( field_name ) : subgraph . setVal ( field_name , val ) else : raise AttributeError ( "Invalid field name %s for subgraph %s " "of parent graph %s." % ( field_name , graph_name , parent_name ) )
def invalid_code ( self , code , card_id = None ) : """设置卡券失效"""
card_data = { 'code' : code } if card_id : card_data [ 'card_id' ] = card_id return self . _post ( 'card/code/unavailable' , data = card_data )
def execute ( cls , stage , state , data , next_allowed_exec_time = None ) : """Execute the operation , rate limiting allowing ."""
try : context = Context . from_state ( state , stage ) now = datetime . utcnow ( ) if next_allowed_exec_time and now < next_allowed_exec_time : # task not allowed to run yet ; put it back in the queue Queue . queue ( stage , state , data , delay = next_allowed_exec_time ) elif context . crawler ...
def update_external_account ( resource_root , account ) : """Update an external account @ param resource _ root : The root Resource object . @ param account : Account to update , account name must be specified . @ return : An ApiExternalAccount object , representing the updated external account"""
return call ( resource_root . put , EXTERNAL_ACCOUNT_PATH % ( "update" , ) , ApiExternalAccount , False , data = account )
def name ( self ) : """Return the String assosciated with the tag name"""
if self . m_name == - 1 or ( self . m_event != const . START_TAG and self . m_event != const . END_TAG ) : return u'' return self . sb [ self . m_name ]
def _undo_save ( self , datastreams , logMessage = None ) : """Takes a list of datastreams and a datetime , run undo save on all of them , and returns a list of the datastreams where the undo succeeded . : param datastreams : list of datastream ids ( should be in self . dscache ) : param logMessage : optional...
return [ ds for ds in datastreams if self . dscache [ ds ] . undo_last_save ( logMessage ) ]
def _update_indicator ( self , K , L ) : """update the indicator"""
_update = { 'term' : self . n_terms * np . ones ( ( K , L ) ) . T . ravel ( ) , 'row' : np . kron ( np . arange ( K ) [ : , np . newaxis ] , np . ones ( ( 1 , L ) ) ) . T . ravel ( ) , 'col' : np . kron ( np . ones ( ( K , 1 ) ) , np . arange ( L ) [ np . newaxis , : ] ) . T . ravel ( ) } for key in list ( _update . ke...
def add_vector ( self , vector ) : """Writes the provided vector to the matrix . ` vector ` An iterable of ` ` ( word - id , word - frequency ) ` ` tuples"""
self . _num_docs += 1 max_id , veclen = self . _mmw . write_vector ( self . _num_docs , vector ) self . _num_terms = max ( self . _num_terms , 1 + max_id ) self . _num_nnz += veclen
def set_equation_from_string ( self , equation_str , fail_silently = False , check_equation = True ) : """Set equation attribute from a string . Checks to see that the string is well - formed , and then uses sympy . sympify to evaluate . Args : equation _ str ( str ) : A string representation ( in valid Pyt...
if check_equation : regex_check ( equation_str ) # Create Queue to allow for timeout q = multiprocessing . Queue ( ) def prep ( conn ) : equation , error = None , False try : equation = sympy . sympify ( equation_str ) except sympy . SympifyError : error = True q . put ( ( equation ,...
def macro_list ( self , args : argparse . Namespace ) -> None : """List some or all macros"""
if args . name : for cur_name in utils . remove_duplicates ( args . name ) : if cur_name in self . macros : self . poutput ( "macro create {} {}" . format ( cur_name , self . macros [ cur_name ] . value ) ) else : self . perror ( "Macro '{}' not found" . format ( cur_name ) ,...
def make ( self , cwl ) : """Instantiate a CWL object from a CWl document ."""
load = load_tool . load_tool ( cwl , self . loading_context ) if isinstance ( load , int ) : raise Exception ( "Error loading tool" ) return Callable ( load , self )
def register ( self , ptype ) : """register ptype as a local typedef"""
# Too many of them leads to memory burst if len ( self . typedefs ) < cfg . getint ( 'typing' , 'max_combiner' ) : self . typedefs . append ( ptype ) return True return False
def RecordHistory ( self ) : """Add the given node to the history - set"""
if not self . restoringHistory : record = self . activated_node if self . historyIndex < - 1 : try : del self . history [ self . historyIndex + 1 : ] except AttributeError , err : pass if ( not self . history ) or record != self . history [ - 1 ] : self . hist...
def upload ( self , version = None , tags = None , ext = None , source_fpath = None , overwrite = False , ** kwargs ) : """Uploads the given instance of this dataset to dataset store . Parameters version : str , optional The version of the instance of this dataset . tags : list of str , optional The tags ...
if source_fpath : ext = self . add_local ( source_fpath = source_fpath , version = version , tags = tags ) if ext is None : ext = self . _find_extension ( version = version , tags = tags ) if ext is None : attribs = "{}{}" . format ( "version={} and " . format ( version ) if version else "" , "tags={}" . fo...
def check_token_type ( token_type ) : """Verify that a token type is well - formed > > > check _ token _ type ( ' STACKS ' ) True > > > check _ token _ type ( ' BTC ' ) False > > > check _ token _ type ( ' abcdabcdabcd ' ) True > > > check _ token _ type ( ' abcdabcdabcdabcdabcd ' ) False"""
return check_string ( token_type , min_length = 1 , max_length = LENGTHS [ 'namespace_id' ] , pattern = '^{}$|{}' . format ( TOKEN_TYPE_STACKS , OP_NAMESPACE_PATTERN ) )
def _py2_crc16 ( value ) : """Calculate the CRC for the value in Python 2 : param str value : The value to return for the CRC Checksum : rtype : int"""
crc = 0 for byte in value : crc = ( ( crc << 8 ) & 0xffff ) ^ _CRC16_LOOKUP [ ( ( crc >> 8 ) ^ ord ( byte ) ) & 0xff ] return crc
def encodedFileID ( self , jobStoreFileID ) : """Uses a url safe base64 encoding to encode the jobStoreFileID into a unique identifier to use as filename within the cache folder . jobstore IDs are essentially urls / paths to files and thus cannot be used as is . Base64 encoding is used since it is reversible . ...
base64Text = base64 . urlsafe_b64encode ( jobStoreFileID . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) outCachedFile = os . path . join ( self . localCacheDir , base64Text ) return outCachedFile
def match ( self , version ) : """Match ` ` version ` ` with this collection of constraints . : param version : Version to match against the constraint . : type version : : ref : ` version expression < version - expressions > ` or : class : ` . Version ` : rtype : ` ` True ` ` if ` ` version ` ` satisfies the...
return all ( constraint . match ( version ) for constraint in self . constraints )
def CreateAFF4Object ( stat_response , client_id_urn , mutation_pool , token = None ) : """This creates a File or a Directory from a stat response ."""
urn = stat_response . pathspec . AFF4Path ( client_id_urn ) if stat . S_ISDIR ( stat_response . st_mode ) : ftype = standard . VFSDirectory else : ftype = aff4_grr . VFSFile with aff4 . FACTORY . Create ( urn , ftype , mode = "w" , mutation_pool = mutation_pool , token = token ) as fd : fd . Set ( fd . Sche...
def nick ( self ) : """return nick name : . . code - block : : py > > > print ( IrcString ( ' foo ' ) . nick ) foo > > > print ( IrcString ( ' foo ! user @ host ' ) . nick ) foo > > > IrcString ( ' # foo ' ) . nick is None True > > > IrcString ( ' irc . freenode . net ' ) . nick is None True"""
if '!' in self : return self . split ( '!' , 1 ) [ 0 ] if not self . is_channel and not self . is_server : return self
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'document_label' ) and self . document_label is not None : _dict [ 'document_label' ] = self . document_label if hasattr ( self , 'location' ) and self . location is not None : _dict [ 'location' ] = self . location . _to_dict ( ) if hasattr ( self , 'text' ) and self . text is n...
def declarative_fields ( cls_filter , meta_base = type , extra_attr_name = 'base_fields' ) : """Metaclass that converts Field attributes to a dictionary called ' base _ fields ' , taking into account parent class ' cls _ filter ' ."""
def __new__ ( cls , name , bases , attrs ) : attrs [ extra_attr_name ] = fields = get_declared_fields ( bases , attrs , cls_filter , extra_attr_name = extra_attr_name ) attrs [ extra_attr_name + '_names' ] = set ( fields . keys ( ) ) new_class = meta_base . __new__ ( cls , name , bases , attrs ) return ...
def calculate_retry_delay ( attempt , max_delay = 300 ) : """Calculates an exponential backoff for retry attempts with a small amount of jitter ."""
delay = int ( random . uniform ( 2 , 4 ) ** attempt ) if delay > max_delay : # After reaching the max delay , stop using expontential growth # and keep the delay nearby the max . delay = int ( random . uniform ( max_delay - 20 , max_delay + 20 ) ) return delay
def _drain ( self , cycles = None ) : """Activate the pump and let the flow go . This will call the process ( ) method on each attached module until a StopIteration is raised , usually by a pump when it reached the EOF . A StopIteration is also raised when self . cycles was set and the number of cycles has ...
log . info ( "Now draining..." ) if not cycles : log . info ( "No cycle count, the pipeline may be drained forever." ) if self . calibration : log . info ( "Setting up the detector calibration." ) for module in self . modules : module . detector = self . calibration . get_detector ( ) try : whil...
def discard_events ( library , session , event_type , mechanism ) : """Discards event occurrences for specified event types and mechanisms in a session . Corresponds to viDiscardEvents function of the VISA library . : param library : the visa library wrapped by ctypes . : param session : Unique logical identi...
return library . viDiscardEvents ( session , event_type , mechanism )
def start ( self ) : """Run the commands"""
self . check_dependencies ( ) self . args = self . parser . parse_args ( ) # Python 3 doesn ' t set the cmd if no args are given if not hasattr ( self . args , 'cmd' ) : self . parser . print_help ( ) return cmd = self . args . cmd try : if cmd . app_dir_required and not self . in_app_directory : ra...
def sub_escapes ( sval ) : '''Process escaped characters in ` ` sval ` ` . Arguments : - ` sval ` :'''
sval = sval . replace ( '\\a' , '\a' ) sval = sval . replace ( '\\b' , '\x00' ) sval = sval . replace ( '\\f' , '\f' ) sval = sval . replace ( '\\n' , '\n' ) sval = sval . replace ( '\\r' , '\r' ) sval = sval . replace ( '\\t' , '\t' ) sval = sval . replace ( '\\v' , '\v' ) sval = sval . replace ( '\\\\' , '\\' ) retur...
def stat_mode_to_index_mode ( mode ) : """Convert the given mode from a stat call to the corresponding index mode and return it"""
if S_ISLNK ( mode ) : # symlinks return S_IFLNK if S_ISDIR ( mode ) or S_IFMT ( mode ) == S_IFGITLINK : # submodules return S_IFGITLINK return S_IFREG | 0o644 | ( mode & 0o111 )
def gather_positions ( tree ) : """Makes a list of positions and position commands from the tree"""
pos = { 'data-x' : 'r0' , 'data-y' : 'r0' , 'data-z' : 'r0' , 'data-rotate-x' : 'r0' , 'data-rotate-y' : 'r0' , 'data-rotate-z' : 'r0' , 'data-scale' : 'r0' , 'is_path' : False } steps = 0 default_movement = True for step in tree . findall ( 'step' ) : steps += 1 for key in POSITION_ATTRIBS : value = st...
def load_mayaplugins ( ) : """Loads the maya plugins ( not jukebox plugins ) of the pipeline : returns : None : rtype : None : raises : None"""
mpp = os . environ . get ( 'MAYA_PLUG_IN_PATH' ) if mpp is not None : ';' . join ( [ mpp , MAYA_PLUGIN_PATH ] ) else : mpp = MAYA_PLUGIN_PATH # to simply load all plugins inside our plugin path , we override pluginpath temporarly os . environ [ 'MAYA_PLUG_IN_PATH' ] = MAYA_PLUGIN_PATH cmds . loadPlugin ( allPlu...
def _restore_output ( self , statement : Statement , saved_state : utils . RedirectionSavedState ) -> None : """Handles restoring state after output redirection as well as the actual pipe operation if present . : param statement : Statement object which contains the parsed input from the user : param saved _ ...
if saved_state . redirecting : # If we redirected output to the clipboard if statement . output and not statement . output_to : self . stdout . seek ( 0 ) write_to_paste_buffer ( self . stdout . read ( ) ) try : # Close the file or pipe that stdout was redirected to self . stdout . close...
def GenerateConfigFile ( load_hook , dump_hook , ** kwargs ) -> ConfigFile : """Generates a ConfigFile object using the specified hooks . These hooks should be functions , and have one argument . When a hook is called , the ConfigFile object is passed to it . Use this to load your data from the fd object , or r...
def ConfigFileGenerator ( filename , safe_load : bool = True ) : cfg = ConfigFile ( fd = filename , load_hook = load_hook , dump_hook = dump_hook , safe_load = safe_load , ** kwargs ) return cfg return ConfigFileGenerator
def _retry_get ( self , uri ) : """Handles GET calls to the Cloud DNS API in order to retry on empty body responses ."""
for i in six . moves . range ( DEFAULT_RETRY ) : resp , body = self . api . method_get ( uri ) if body : return resp , body # Tried too many times raise exc . ServiceResponseFailure ( "The Cloud DNS service failed to " "respond to the request." )
def addpackage ( sys_sitedir , pthfile , known_dirs ) : """Wrapper for site . addpackage Try and work out which directories are added by the . pth and add them to the known _ dirs set : param sys _ sitedir : system site - packages directory : param pthfile : path file to add : param known _ dirs : set of ...
with open ( join ( sys_sitedir , pthfile ) ) as f : for n , line in enumerate ( f ) : if line . startswith ( "#" ) : continue line = line . rstrip ( ) if line : if line . startswith ( ( "import " , "import\t" ) ) : exec ( line , globals ( ) , locals ( ...
def stats ( self , alpha = 0.05 , start = 0 , batches = 100 , chain = None , quantiles = ( 2.5 , 25 , 50 , 75 , 97.5 ) ) : """Generate posterior statistics for node . : Parameters : name : string The name of the tallyable object . alpha : float The alpha level for generating posterior intervals . Defaults...
try : trace = np . squeeze ( np . array ( self . db . trace ( self . name ) ( chain = chain ) , float ) ) [ start : ] n = len ( trace ) if not n : print_ ( 'Cannot generate statistics for zero-length trace in' , self . __name__ ) return return { 'n' : n , 'standard deviation' : trace . s...
def _format_monitor_parameter ( param ) : """This is a workaround for a known issue ID645289 , which affects all versions of TMOS at this time ."""
if '{' in param and '}' : tmp = param . strip ( '}' ) . split ( '{' ) monitor = '' . join ( tmp ) . rstrip ( ) return monitor else : return param
def convert_to_json_with_mac ( self , md5digest , hmacdigest ) : # type : ( EncryptionMetadata , str , str ) - > dict """Constructs metadata for encryption : param EncryptionMetadata self : this : param str md5digest : md5 digest : param str hmacdigest : hmac - sha256 digest ( data ) : rtype : dict : retu...
# encrypt keys enc_content_key = blobxfer . operations . crypto . rsa_encrypt_key_base64_encoded ( None , self . _rsa_public_key , self . symmetric_key ) enc_sign_key = blobxfer . operations . crypto . rsa_encrypt_key_base64_encoded ( None , self . _rsa_public_key , self . signing_key ) # generate json encjson = { Encr...
def delete_lbaas_member ( self , lbaas_member , lbaas_pool ) : """Deletes the specified lbaas _ member ."""
return self . delete ( self . lbaas_member_path % ( lbaas_pool , lbaas_member ) )
def engineer_info ( self , action ) : """Returns : dict : engineer command information - arguments ( list < dict > ) : command arguments - args ( list ) : args to pass through to click . argument - kwargs ( dict ) : keyword arguments to pass through to click . argument - options ( list < dict > ) : comman...
fn = getattr ( self , action , None ) if not fn : raise AttributeError ( "Engineer action not found: %s" % action ) if not hasattr ( fn , "engineer" ) : raise AttributeError ( "Engineer action not exposed: %s" % action ) return fn . engineer
def mean_fill ( adf ) : """Looks at each row , and calculates the mean . Honours the Trump override / failsafe logic ."""
ordpt = adf . values [ 0 ] if not pd . isnull ( ordpt ) : return ordpt fdmn = adf . iloc [ 1 : - 1 ] . mean ( ) if not pd . isnull ( fdmn ) : return fdmn flspt = adf . values [ - 1 ] if not pd . isnull ( flspt ) : return flspt return nan
def _calculate_type_bound_at_step ( match_step ) : """Return the GraphQL type bound at the given step , or None if no bound is given ."""
current_type_bounds = [ ] if isinstance ( match_step . root_block , QueryRoot ) : # The QueryRoot start class is a type bound . current_type_bounds . extend ( match_step . root_block . start_class ) if match_step . coerce_type_block is not None : # The CoerceType target class is also a type bound . current_type...
def bogoliubov_trans ( p , q , theta ) : r"""The 2 - mode Bogoliubov transformation is mapped to two - qubit operations . We use the identity X S ^ \ dag X S X = Y X S ^ \ dag Y S X = X to transform the Hamiltonian XY + YX to XX + YY type . The time evolution of the XX + YY Hamiltonian can be expressed as a p...
# The iSWAP gate corresponds to evolve under the Hamiltonian XX + YY for # time - pi / 4. expo = - 4 * theta / np . pi yield cirq . X ( p ) yield cirq . S ( p ) yield cirq . ISWAP ( p , q ) ** expo yield cirq . S ( p ) ** 1.5 yield cirq . X ( p )
def cache ( handle = lambda * args , ** kwargs : None , args = UNDEFINED , kwargs = UNDEFINED , ignore = UNDEFINED , call_stack = UNDEFINED , callback = UNDEFINED , subsequent_rvalue = UNDEFINED ) : """Store a call descriptor : param lambda handle : Any callable will work here . The method to cache . : param tu...
if args == UNDEFINED : args = tuple ( ) if kwargs == UNDEFINED : kwargs = { } if not USE_CALIENDO : return handle ( * args , ** kwargs ) filtered_args = ignore . filter_args ( args ) if ignore is not UNDEFINED else args filtered_kwargs = ignore . filter_kwargs ( kwargs ) if ignore is not UNDEFINED else args...
def check_keypoint ( kp , rows , cols ) : """Check if keypoint coordinates are in range [ 0 , 1)"""
for name , value , size in zip ( [ 'x' , 'y' ] , kp [ : 2 ] , [ cols , rows ] ) : if not 0 <= value < size : raise ValueError ( 'Expected {name} for keypoint {kp} ' 'to be in the range [0.0, {size}], got {value}.' . format ( kp = kp , name = name , value = value , size = size ) )
def _extract_metrics ( self , wmi_sampler , tag_by , tag_queries , constant_tags ) : """Extract and tag metrics from the WMISampler . Raise when multiple WMIObject were returned by the sampler with no ` tag _ by ` specified . Returns : List of WMIMetric WMIMetric ( " freemegabytes " , 19742 , [ " name : _ tot...
if len ( wmi_sampler ) > 1 and not tag_by : raise MissingTagBy ( u"WMI query returned multiple rows but no `tag_by` value was given." " class={wmi_class} - properties={wmi_properties} - filters={filters}" . format ( wmi_class = wmi_sampler . class_name , wmi_properties = wmi_sampler . property_names , filters = wmi...
def verify_arguments ( self , args = None , kwargs = None ) : """Ensures that the arguments specified match the signature of the real method . : raise : ` ` VerifyingDoubleError ` ` if the arguments do not match ."""
args = self . args if args is None else args kwargs = self . kwargs if kwargs is None else kwargs try : verify_arguments ( self . _target , self . _method_name , args , kwargs ) except VerifyingBuiltinDoubleArgumentError : if doubles . lifecycle . ignore_builtin_verification ( ) : raise
def QA_fetch_get_stock_day ( code , start_date , end_date , if_fq = '00' , frequence = 'day' , ip = None , port = None ) : """获取日线及以上级别的数据 Arguments : code { str : 6 } - - code 是一个单独的code 6位长度的str start _ date { str : 10 } - - 10位长度的日期 比如 ' 2017-01-01' end _ date { str : 10 } - - 10位长度的日期 比如 ' 2018-01-01' ...
ip , port = get_mainmarket_ip ( ip , port ) api = TdxHq_API ( ) try : with api . connect ( ip , port , time_out = 0.7 ) : if frequence in [ 'day' , 'd' , 'D' , 'DAY' , 'Day' ] : frequence = 9 elif frequence in [ 'w' , 'W' , 'Week' , 'week' ] : frequence = 5 elif frequ...
def top_priority_effect_per_variant ( self ) : """Highest priority effect for each unique variant"""
return OrderedDict ( ( variant , top_priority_effect ( variant_effects ) ) for ( variant , variant_effects ) in self . groupby_variant ( ) . items ( ) )
def update_repository ( self , new_repository_info , repository_id , project = None ) : """UpdateRepository . [ Preview API ] Updates the Git repository with either a new repo name or a new default branch . : param : class : ` < GitRepository > < azure . devops . v5_1 . git . models . GitRepository > ` new _ re...
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' ) content = self . _serialize . body ( new_repositor...
def get_pwm_list ( motif_name_list , pseudocountProb = 0.0001 ) : """Get a list of ENCODE PWM ' s . # Arguments pwm _ id _ list : List of id ' s from the ` PWM _ id ` column in ` get _ metadata ( ) ` table pseudocountProb : Added pseudocount probabilities to the PWM # Returns List of ` concise . utils . p...
l = _load_motifs ( ) l = { k . split ( ) [ 0 ] : v for k , v in l . items ( ) } pwm_list = [ PWM ( l [ m ] + pseudocountProb , name = m ) for m in motif_name_list ] return pwm_list
def _conf ( cls , opts ) : """Setup logging via ini - file from logging _ conf _ file option ."""
logging_conf = cls . config . get ( 'core' , 'logging_conf_file' , None ) if logging_conf is None : return False if not os . path . exists ( logging_conf ) : # FileNotFoundError added only in Python 3.3 # https : / / docs . python . org / 3 / whatsnew / 3.3 . html # pep - 3151 - reworking - the - os - and - io - ex...
def updatewhere ( clas , pool_or_cursor , where_keys , ** update_keys ) : "this doesn ' t allow raw _ keys for now"
# if clas . JSONFIELDS : raise NotImplementedError # todo ( awinter ) : do I need to make the same change for SpecialField ? if not where_keys or not update_keys : raise ValueError setclause = ',' . join ( k + '=%s' for k in update_keys ) whereclause = ' and ' . join ( eqexpr ( k , v ) for k , v in where_keys . ite...
def logToMaster ( self , text , level = logging . INFO ) : """Send a logging message to the leader . The message will also be logged by the worker at the same level . : param text : The string to log . : param int level : The logging level ."""
logger . log ( level = level , msg = ( "LOG-TO-MASTER: " + text ) ) self . loggingMessages . append ( dict ( text = text , level = level ) )
def formfield ( self , ** kwargs ) : """Gets the form field associated with this field ."""
defaults = dict ( form_class = LocalizedFieldForm , required = False if self . blank else self . required ) defaults . update ( kwargs ) return super ( ) . formfield ( ** defaults )
def closing_plugin ( self , cancelable = False ) : """Perform actions before parent main window is closed"""
self . dialog_manager . close_all ( ) self . shell . exit_interpreter ( ) return True
def stage ( draft , discard , repo_directory , release_name , release_description ) : """Stages a release"""
with work_in ( repo_directory ) : if discard : stage_command . discard ( release_name , release_description ) else : stage_command . stage ( draft , release_name , release_description )