signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def synthesizeMember ( memberName , default = None , contract = None , readOnly = False , getterName = None , setterName = None , privateMemberName = None ) : """When applied to a class , this decorator adds getter / setter methods to it and overrides the constructor in order to set the default value of the member ...
accessorDelegate = AccessorDelegate ( namingConvention = NamingConventionCamelCase ( ) , getterName = getterName , setterName = setterName ) return SyntheticDecoratorFactory ( ) . syntheticMemberDecorator ( memberName = memberName , defaultValue = default , contract = contract , readOnly = readOnly , privateMemberName ...
def encrypt_with_caching ( kms_cmk_arn , max_age_in_cache , cache_capacity ) : """Encrypts a string using an AWS KMS customer master key ( CMK ) and data key caching . : param str kms _ cmk _ arn : Amazon Resource Name ( ARN ) of the KMS customer master key : param float max _ age _ in _ cache : Maximum time in...
# Data to be encrypted my_data = "My plaintext data" # Security thresholds # Max messages ( or max bytes per ) data key are optional MAX_ENTRY_MESSAGES = 100 # Create an encryption context encryption_context = { "purpose" : "test" } # Create a master key provider for the KMS customer master key ( CMK ) key_provider = a...
def OnSquareSelected ( self , event ) : """Update all views to show selection children / parents"""
self . selected_node = event . node self . calleeListControl . integrateRecords ( self . adapter . children ( event . node ) ) self . callerListControl . integrateRecords ( self . adapter . parents ( event . node ) )
def _validate_desc ( self , desc ) : """Validate the predicate description ."""
if desc is None : return desc if not isinstance ( desc , STRING_TYPES ) : raise TypeError ( "predicate description for Matching must be a string, " "got %r" % ( type ( desc ) , ) ) # Python 2 mandates _ _ repr _ _ to be an ASCII string , # so if Unicode is passed ( usually due to unicode _ literals ) , # it sho...
def p_argument_list ( self , p ) : """argument _ list : assignment _ expr | argument _ list COMMA assignment _ expr"""
if len ( p ) == 2 : p [ 0 ] = [ p [ 1 ] ] else : p [ 1 ] . append ( p [ 3 ] ) p [ 0 ] = p [ 1 ]
def write_incron_file ( user , path ) : '''Writes the contents of a file to a user ' s incrontab CLI Example : . . code - block : : bash salt ' * ' incron . write _ incron _ file root / tmp / new _ incron'''
return __salt__ [ 'cmd.retcode' ] ( _get_incron_cmdstr ( path ) , runas = user , python_shell = False ) == 0
def wait_actions ( self , actions , wait_interval = None , wait_time = None ) : r"""Poll the server periodically until all actions in ` ` actions ` ` have either completed or errored out , yielding each ` Action ` ' s final value as it ends . If ` ` wait _ time ` ` is exceeded , a ` WaitTimeoutError ` ( conta...
return self . _wait ( map ( self . _action , actions ) , "done" , True , wait_interval , wait_time )
def make_safe_filename_from_url ( self , url ) : '''return a version of url safe for use as a filename'''
r = re . compile ( "([^a-zA-Z0-9_.-])" ) filename = r . sub ( lambda m : "%" + str ( hex ( ord ( str ( m . group ( 1 ) ) ) ) ) . upper ( ) , url ) return filename
def examples ( self ) : """Return examples from all sub - spaces ."""
for examples in product ( * [ spc . examples for spc in self . spaces ] ) : name = ', ' . join ( name for name , _ in examples ) element = self . element ( [ elem for _ , elem in examples ] ) yield ( name , element )
def set_memory ( self , total = None , static = None ) : """Set the maxium allowed memory . Args : total : The total memory . Integer . Unit : MBytes . If set to None , this parameter will be neglected . static : The static memory . Integer . Unit MBytes . If set to None , this parameterwill be neglected ...
if total : self . params [ "rem" ] [ "mem_total" ] = total if static : self . params [ "rem" ] [ "mem_static" ] = static
def number_to_bytes ( n , endian = 'big' ) : """Convert an integer to a corresponding string of bytes . . : param n : Integer to convert . : param endian : Byte order to convert into ( ' big ' or ' little ' endian - ness , default ' big ' ) Assumes bytes are 8 bits . This is a special - case version o...
res = [ ] while n : n , ch = divmod ( n , 256 ) if PY3 : res . append ( ch ) else : res . append ( chr ( ch ) ) if endian == 'big' : res . reverse ( ) if PY3 : return bytes ( res ) else : return '' . join ( res )
def fromxml ( node ) : """Static method returning a ParameterCondition instance from the given XML description . Node can be a string or an etree . _ Element ."""
if not isinstance ( node , ElementTree . _Element ) : # pylint : disable = protected - access node = parsexmlstring ( node ) assert node . tag . lower ( ) == 'parametercondition' kwargs = { } found = False for node in node : if node . tag == 'if' : # interpret conditions : for subnode in node : ...
def minimum_katcp_version ( major , minor = 0 ) : """Decorator ; exclude handler if server ' s protocol version is too low Useful for including default handler implementations for KATCP features that are only present in certain KATCP protocol versions Examples > > > class MyDevice ( DeviceServer ) : . . ....
version_tuple = ( major , minor ) def decorator ( handler ) : handler . _minimum_katcp_version = version_tuple return handler return decorator
def create_directory ( self ) : """Creates a directory under the selected directory ( if the selected item is a file , the parent directory is used ) ."""
src = self . get_current_path ( ) name , status = QtWidgets . QInputDialog . getText ( self . tree_view , _ ( 'Create directory' ) , _ ( 'Name:' ) , QtWidgets . QLineEdit . Normal , '' ) if status : fatal_names = [ '.' , '..' ] for i in fatal_names : if i == name : QtWidgets . QMessageBox . ...
def get_option_parser ( defaults ) : """Create and return an OptionParser with the given defaults ."""
# based on recipe from : # http : / / stackoverflow . com / questions / 1880404 / using - a - file - to - store - optparse - arguments # process command line parameters # e . g . skosify yso . owl - o yso - skos . rdf usage = "Usage: %prog [options] voc1 [voc2 ...]" parser = optparse . OptionParser ( usage = usage ) pa...
def perform_extended_selection ( self , event = None ) : """Performs extended word selection . : param event : QMouseEvent"""
TextHelper ( self . editor ) . select_extended_word ( continuation_chars = self . continuation_characters ) if event : event . accept ( )
def execute_process_synchronously_without_raising ( self , execute_process_request , name , labels = None ) : """Executes a process ( possibly remotely ) , and returns information about its output . : param execute _ process _ request : The ExecuteProcessRequest to run . : param name : A descriptive name repres...
with self . new_workunit ( name = name , labels = labels , cmd = ' ' . join ( execute_process_request . argv ) , ) as workunit : result = self . _scheduler . product_request ( FallibleExecuteProcessResult , [ execute_process_request ] ) [ 0 ] workunit . output ( "stdout" ) . write ( result . stdout ) workun...
def merge_elisions ( elided : List [ str ] ) -> str : """Given a list of strings with different space swapping elisions applied , merge the elisions , taking the most without compounding the omissions . : param elided : : return : > > > merge _ elisions ( [ . . . " ignavae agua multum hiatus " , " ignav a...
results = list ( elided [ 0 ] ) for line in elided : for idx , car in enumerate ( line ) : if car == " " : results [ idx ] = " " return "" . join ( results )
def visit_Compare ( self , node : ast . Compare ) -> Any : """Recursively visit the comparators and apply the operations on them ."""
# pylint : disable = too - many - branches left = self . visit ( node = node . left ) comparators = [ self . visit ( node = comparator ) for comparator in node . comparators ] result = None # type : Optional [ Any ] for comparator , op in zip ( comparators , node . ops ) : if isinstance ( op , ast . Eq ) : ...
def device_event_list ( self , ** kwargs ) : # noqa : E501 """List all device events . # noqa : E501 List all device events for an account . # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass asynchronous = True > > > thread = api . dev...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . device_event_list_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . device_event_list_with_http_info ( ** kwargs ) # noqa : E501 return data
def create_subnet_group ( name , description , subnet_ids , tags = None , region = None , key = None , keyid = None , profile = None ) : '''Create an RDS subnet group CLI example to create an RDS subnet group : : salt myminion boto _ rds . create _ subnet _ group my - subnet - group " group description " ' [ su...
res = __salt__ [ 'boto_rds.subnet_group_exists' ] ( name , tags , region , key , keyid , profile ) if res . get ( 'exists' ) : return { 'exists' : bool ( res ) } try : conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) if not conn : return { 'results' : bool ( conn ...
def create_regular_expression ( self , regexp ) : """Create a regular expression for this inspection situation context . The inspection situation must be using an inspection context that supports regex . : param str regexp : regular expression string : raises CreateElementFailed : failed to modify the situa...
for parameter in self . situation_context . situation_parameters : if parameter . type == 'regexp' : return self . add_parameter_value ( 'reg_exp_situation_parameter_values' , ** { 'parameter_ref' : parameter . href , 'reg_exp' : regexp } ) # Treat as raw string raise CreateElementFailed ( 'The situation do...
def find_prototypes ( code ) : """Return a list of signatures for each function prototype declared in * code * . Format is [ ( name , [ args ] , rtype ) , . . . ] ."""
prots = [ ] lines = code . split ( '\n' ) for line in lines : m = re . match ( "\s*" + re_func_prot , line ) if m is not None : rtype , name , args = m . groups ( ) [ : 3 ] if args == 'void' or args . strip ( ) == '' : args = [ ] else : args = [ tuple ( arg . stri...
def window_handles ( self ) : """Returns the handles of all windows within the current session . : Usage : driver . window _ handles"""
if self . w3c : return self . execute ( Command . W3C_GET_WINDOW_HANDLES ) [ 'value' ] else : return self . execute ( Command . GET_WINDOW_HANDLES ) [ 'value' ]
def run_lint_command ( ) : """Run lint command in the shell and save results to lint - result . xml"""
lint , app_dir , lint_result , ignore_layouts = parse_args ( ) if not lint_result : if not distutils . spawn . find_executable ( lint ) : raise Exception ( '`%s` executable could not be found and path to lint result not specified. See --help' % lint ) lint_result = os . path . join ( app_dir , 'lint-res...
def thresholds ( self ) : """Threshold values of the response functions ."""
return numpy . array ( sorted ( self . _key2float ( key ) for key in self . _coefs ) , dtype = float )
def run_cron_with_cache_check ( cron_class , force = False , silent = False ) : """Checks the cache and runs the cron or not . @ cron _ class - cron class to run . @ force - run job even if not scheduled @ silent - suppress notifications"""
with CronJobManager ( cron_class , silent ) as manager : manager . run ( force )
def run ( self , instance ) : """Run the recorded chain of methods on ` instance ` . Args : instance : an object ."""
last = instance for item in self . stack : if isinstance ( item , str ) : last = getattr ( last , item ) else : last = last ( * item [ 0 ] , ** item [ 1 ] ) self . stack = [ ] return last
def lookup_token ( self , line , col ) : """Given a minified location , this tries to locate the closest token that is a match . Returns ` None ` if no match can be found ."""
# Silently ignore underflows if line < 0 or col < 0 : return None tok_out = _ffi . new ( 'lsm_token_t *' ) if rustcall ( _lib . lsm_view_lookup_token , self . _get_ptr ( ) , line , col , tok_out ) : return convert_token ( tok_out [ 0 ] )
def add_labels ( self , * args ) : """Add labels to this issue . : param str args : ( required ) , names of the labels you wish to add : returns : list of : class : ` Label ` \ s"""
url = self . _build_url ( 'labels' , base_url = self . _api ) json = self . _json ( self . _post ( url , data = args ) , 200 ) return [ Label ( l , self ) for l in json ] if json else [ ]
def get_all_contacts_of_client ( self , client_id ) : """Get all contacts of client This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing : param client _ id : The id of the client : return : list"""
return self . _iterate_through_pages ( get_function = self . get_contacts_of_client_per_page , resource = CONTACTS , ** { 'client_id' : client_id } )
def find_lines ( self , linespec ) : """Find lines that match the linespec regex ."""
res = [ ] linespec += ".*" for line in self . cfg : match = re . search ( linespec , line ) if match : res . append ( match . group ( 0 ) ) return res
def physical ( self ) : """get the physical samples values Returns phys : Signal new * Signal * with physical values"""
if not self . raw or self . conversion is None : samples = self . samples . copy ( ) else : samples = self . conversion . convert ( self . samples ) return Signal ( samples , self . timestamps . copy ( ) , unit = self . unit , name = self . name , conversion = self . conversion , raw = False , master_metadata =...
def create_parser ( ) : """Returns argument parser"""
parser = argparse . ArgumentParser ( description = 'Extract structured data from PDF files and save to CSV or JSON.' ) parser . add_argument ( '--input-reader' , choices = input_mapping . keys ( ) , default = 'pdftotext' , help = 'Choose text extraction function. Default: pdftotext' , ) parser . add_argument ( '--outpu...
def heatmap_mpl ( dfr , outfilename = None , title = None , params = None ) : """Returns matplotlib heatmap with cluster dendrograms . - dfr - pandas DataFrame with relevant data - outfilename - path to output file ( indicates output format ) - params - a list of parameters for plotting : [ colormap , vmin , ...
# Layout figure grid and add title # Set figure size by the number of rows in the dataframe figsize = max ( 8 , dfr . shape [ 0 ] * 0.175 ) fig = plt . figure ( figsize = ( figsize , figsize ) ) # if title : # fig . suptitle ( title ) heatmap_gs = gridspec . GridSpec ( 2 , 2 , wspace = 0.0 , hspace = 0.0 , width_ratios...
def spa_c ( time , latitude , longitude , pressure = 101325 , altitude = 0 , temperature = 12 , delta_t = 67.0 , raw_spa_output = False ) : """Calculate the solar position using the C implementation of the NREL SPA code . The source files for this code are located in ' . / spa _ c _ files / ' , along with a R...
# Added by Rob Andrews ( @ Calama - Consulting ) , Calama Consulting , 2014 # Edited by Will Holmgren ( @ wholmgren ) , University of Arizona , 2014 # Edited by Tony Lorenzo ( @ alorenzo175 ) , University of Arizona , 2015 try : from pvlib . spa_c_files . spa_py import spa_calc except ImportError : raise Import...
def calculate_gradient ( self , batch_info , device , model , rollout ) : """Calculate loss of the supplied rollout"""
assert isinstance ( rollout , Trajectories ) , "ACER algorithm requires trajectory input" local_epsilon = 1e-6 evaluator = model . evaluate ( rollout ) actions = evaluator . get ( 'rollout:actions' ) rollout_probabilities = torch . exp ( evaluator . get ( 'rollout:logprobs' ) ) # We calculate the trust - region update ...
def get_relation_kwargs ( field_name , relation_info ) : """Creating a default instance of a flat relational field ."""
model_field , related_model = relation_info kwargs = { } if related_model and not issubclass ( related_model , EmbeddedDocument ) : kwargs [ 'queryset' ] = related_model . objects if model_field : if hasattr ( model_field , 'verbose_name' ) and needs_label ( model_field , field_name ) : kwargs [ 'label'...
def get_valid_filename ( s ) : """like the regular get _ valid _ filename , but also slugifies away umlauts and stuff ."""
s = get_valid_filename_django ( s ) filename , ext = os . path . splitext ( s ) filename = slugify ( filename ) ext = slugify ( ext ) if ext : return "%s.%s" % ( filename , ext ) else : return "%s" % ( filename , )
def SetLines ( self , lines ) : """Set number of screen lines . Args : lines : An int , number of lines . If None , use terminal dimensions . Raises : ValueError , TypeError : Not a valid integer representation ."""
( self . _cli_lines , self . _cli_cols ) = TerminalSize ( ) if lines : self . _cli_lines = int ( lines )
def dereference ( self , session , ref , allow_none = False ) : """Dereference an ObjectID to this field ' s underlying type"""
ref = DBRef ( id = ref , collection = self . type . type . get_collection_name ( ) , database = self . db ) ref . type = self . type . type return session . dereference ( ref , allow_none = allow_none )
def convert_enum ( func ) : """Decorator to use Enum value on type casts ."""
@ wraps ( func ) def inner ( self , value ) : try : if self . check_value ( value . value ) : return value . value return func ( self , value . value ) except AttributeError : pass return func ( self , value ) return inner
def to_bytes ( obj ) : """Ensures that the obj is of byte - type ."""
if PY3 : if isinstance ( obj , str ) : return obj . encode ( settings . DEFAULT_ENCODING ) else : return obj if isinstance ( obj , bytes ) else b'' else : if isinstance ( obj , str ) : return obj else : return obj . encode ( settings . DEFAULT_ENCODING ) if isinstance ( o...
def transform ( data , target_wd , target_ht , is_train , box ) : """Crop and normnalize an image nd array ."""
if box is not None : x , y , w , h = box data = data [ y : min ( y + h , data . shape [ 0 ] ) , x : min ( x + w , data . shape [ 1 ] ) ] # Resize to target _ wd * target _ ht . data = mx . image . imresize ( data , target_wd , target_ht ) # Normalize in the same way as the pre - trained model . data = data . as...
def run ( self ) : """Train the model on randomly generated batches"""
_ , test_data = self . data . load ( train = False , test = True ) try : self . model . fit_generator ( self . samples_to_batches ( self . generate_samples ( ) , self . args . batch_size ) , steps_per_epoch = self . args . steps_per_epoch , epochs = self . epoch + self . args . epochs , validation_data = test_data ...
def create_jar ( jar_file , entries ) : """Create JAR from given entries . : param jar _ file : filename of the created JAR : type jar _ file : str : param entries : files to put into the JAR : type entries : list [ str ] : return : None"""
# ' jar ' adds separate entries for directories , also for empty ones . with ZipFile ( jar_file , "w" ) as jar : jar . writestr ( "META-INF/" , "" ) jar . writestr ( "META-INF/MANIFEST.MF" , Manifest ( ) . get_data ( ) ) for entry in entries : jar . write ( entry ) if os . path . isdir ( ent...
def append_delta_index ( self , ts_data = None , data_delta = None , key = KEY_DATA ) : """Append columns with ∆ T between rows to data ."""
reasign = False if data_delta is None : if self . data is not None : data_delta = self . data [ key ] else : self . printif ( 'NO HAY DATOS PARA AÑADIR DELTA' , 'error' ) return None reasign = True data_delta [ 'delta' ] = data_delta . index . tz_convert ( 'UTC' ) if ts_data is not N...
def set_score_system ( self , grade_system_id ) : """Sets the scoring system . arg : grade _ system _ id ( osid . id . Id ) : the grade system raise : InvalidArgument - ` ` grade _ system _ id ` ` is invalid raise : NoAccess - ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` ` * compliance : mandatory - - Th...
# Implemented from template for osid . resource . ResourceForm . set _ avatar _ template if self . get_score_system_metadata ( ) . is_read_only ( ) : raise errors . NoAccess ( ) if not self . _is_valid_id ( grade_system_id ) : raise errors . InvalidArgument ( ) self . _my_map [ 'scoreSystemId' ] = str ( grade_s...
async def get_headline ( self , name ) : """Get stored messages for a service . Args : name ( string ) : The name of the service to get messages from . Returns : ServiceMessage : the headline or None if no headline has been set"""
resp = await self . send_command ( OPERATIONS . CMD_QUERY_HEADLINE , { 'name' : name } , MESSAGES . QueryHeadlineResponse , timeout = 5.0 ) if resp is not None : resp = states . ServiceMessage . FromDictionary ( resp ) return resp
def north_arrow ( self , north_arrow_path ) : """Set image that will be used as north arrow in reports . : param north _ arrow _ path : Path to the north arrow image . : type north _ arrow _ path : str"""
if isinstance ( north_arrow_path , str ) and os . path . exists ( north_arrow_path ) : self . _north_arrow = north_arrow_path else : self . _north_arrow = default_north_arrow_path ( )
def read ( self , vals ) : """Read values . Args : vals ( list ) : list of strings representing values"""
i = 0 count = int ( vals [ i ] ) i += 1 for _ in range ( count ) : obj = TypicalOrExtremePeriod ( ) obj . read ( vals [ i : i + obj . field_count ] ) self . add_typical_or_extreme_period ( obj ) i += obj . field_count
def get_path ( filename ) : """Get absolute path for filename . : param filename : file : return : path"""
path = abspath ( filename ) if os . path . isdir ( filename ) else dirname ( abspath ( filename ) ) return path
def get_historical_standings ( date ) : """Return the historical standings file for specified date ."""
try : url = STANDINGS_HISTORICAL_URL . format ( date . year , date . strftime ( '%Y/%m/%d' ) ) return urlopen ( url ) except HTTPError : ValueError ( 'Could not find standings for that date.' )
def copy_labels ( src , dst ) : """Copies all labels of one object to another object . : type src : object : param src : The object to check read the labels from . : type dst : object : param dst : The object into which the labels are copied ."""
labels = src . __dict__ . get ( '_labels' ) if labels is None : return dst . __dict__ [ '_labels' ] = labels . copy ( )
def path ( self , path ) : """Creates a path based on the location attribute of the backend and the path argument of the function . If the path argument is an absolute path the path is returned . : param path : The path that should be joined with the backends location ."""
if os . path . isabs ( path ) : return path return os . path . join ( self . location , path )
def score ( self , sequences , y = None ) : """Score the model on new data using the generalized matrix Rayleigh quotient Parameters sequences : list of array - like List of sequences , or a single sequence . Each sequence should be a 1D iterable of state labels . Labels can be integers , strings , or o...
# eigenvectors from the model we ' re scoring , ` self ` V = self . right_eigenvectors_ m2 = self . __class__ ( ** self . get_params ( ) ) m2 . fit ( sequences ) if self . mapping_ != m2 . mapping_ : V = self . _map_eigenvectors ( V , m2 . mapping_ ) S = np . diag ( m2 . populations_ ) C = S . dot ( m2 . transmat_ ...
def get_relationship_admin_session_for_family ( self , family_id ) : """Gets the ` ` OsidSession ` ` associated with the relationship administration service for the given family . arg : family _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Family ` ` return : ( osid . relationship . RelationshipAdminSessio...
if not self . supports_relationship_admin ( ) : raise errors . Unimplemented ( ) # Also include check to see if the catalog Id is found otherwise raise errors . NotFound # pylint : disable = no - member return sessions . RelationshipAdminSession ( family_id , runtime = self . _runtime )
def postprocess_key_for_export ( self , key , client_random , server_random , con_end , read_or_write , req_len ) : """Postprocess cipher key for EXPORT ciphersuite , i . e . weakens it . An export key generation example is given in section 6.3.1 of RFC 2246. See also page 86 of EKR ' s book ."""
s = con_end + read_or_write s = ( s == "clientwrite" or s == "serverread" ) if self . tls_version < 0x0300 : return None elif self . tls_version == 0x0300 : if s : tbh = key + client_random + server_random else : tbh = key + server_random + client_random export_key = _tls_hash_algs [ "MD...
def add_users ( self , users = None ) : """Add users ( specified by email address ) to this user group . In case of ambiguity ( two users with same email address ) , the non - AdobeID user is preferred . : param users : list of emails for users to add to the group . : return : the Group , so you can do Group ...
if not users : raise ArgumentError ( "You must specify emails for users to add to the user group" ) ulist = { "user" : [ user for user in users ] } return self . append ( add = ulist )
def __up ( self , onlyrecord = False ) : """Return to the current command ' s parent This method should be called each time a command is complete . In case of a top level command ( no parent ) , it is recorded into a specific list for further usage . : param onlyrecord : tell to only record the new command ...
if self . __curcommand . must_follow is not None : if not self . __curcommand . parent : prevcmd = self . result [ - 1 ] if len ( self . result ) else None else : prevcmd = self . __curcommand . parent . children [ - 2 ] if len ( self . __curcommand . parent . children ) >= 2 else None if pr...
def createPedChr24UsingPlink ( options ) : """Run plink to create a ped format . : param options : the options . : type options : argparse . Namespace Uses Plink to create a ` ` ped ` ` file of markers on the chromosome ` ` 24 ` ` . It uses the ` ` recodeA ` ` options to use additive coding . It also subset...
plinkCommand = [ "plink" , "--noweb" , "--bfile" , options . bfile , "--chr" , "24" , "--recodeA" , "--keep" , options . out + ".list_problem_sex_ids" , "--out" , options . out + ".chr24_recodeA" ] runCommand ( plinkCommand )
def __cal_continue ( cls , list_data ) : """計算持續天數 : rtype : int : returns : 向量數值 : 正數向上 、 負數向下 。"""
diff_data = [ ] for i in range ( 1 , len ( list_data ) ) : if list_data [ - i ] > list_data [ - i - 1 ] : diff_data . append ( 1 ) else : diff_data . append ( - 1 ) cont = 0 for value in diff_data : if value == diff_data [ 0 ] : cont += 1 else : break return cont * diff_d...
def upscale ( file_name , scale = 1.5 , margin_x = 0 , margin_y = 0 , suffix = 'scaled' , tempdir = None ) : """Upscale a PDF to a large size ."""
def adjust ( page ) : info = PageMerge ( ) . add ( page ) x1 , y1 , x2 , y2 = info . xobj_box viewrect = ( margin_x , margin_y , x2 - x1 - 2 * margin_x , y2 - y1 - 2 * margin_y ) page = PageMerge ( ) . add ( page , viewrect = viewrect ) page [ 0 ] . scale ( scale ) return page . render ( ) # Set...
def read_excel_file ( inputfile , sheet_name ) : """Return a matrix containing all the information present in the excel sheet of the specified excel document . : arg inputfile : excel document to read : arg sheetname : the name of the excel sheet to return"""
workbook = xlrd . open_workbook ( inputfile ) output = [ ] found = False for sheet in workbook . sheets ( ) : if sheet . name == sheet_name : found = True for row in range ( sheet . nrows ) : values = [ ] for col in range ( sheet . ncols ) : values . append ( ...
def update ( self , url , cache_info = None ) : """Update cache information for url : param url : Update for this url : type url : str | unicode : param cache _ info : Cache info : type cache _ info : floscraper . models . CacheInfo : rtype : None"""
key = hashlib . md5 ( url ) . hexdigest ( ) access_time = None if not cache_info : cache_info = CacheInfo ( ) if not access_time : cache_info . access_time = now_utc ( ) self . _cache_meta_set ( key , cache_info . to_dict ( ) )
def set_channel ( self , channel ) : """set _ channel : records progress from constructed channel Args : channel ( Channel ) : channel Ricecooker is creating Returns : None"""
self . channel = channel self . __record_progress ( Status . CREATE_TREE )
def reduce_by_key_impl ( func , sequence ) : """Implementation for reduce _ by _ key _ t : param func : reduce function : param sequence : sequence to reduce : return : reduced sequence"""
result = { } for key , value in sequence : if key in result : result [ key ] = func ( result [ key ] , value ) else : result [ key ] = value return six . viewitems ( result )
def get_crimes_point ( self , lat , lng , date = None , category = None ) : """Get crimes within a 1 - mile radius of a location . Uses the crime - street _ API call . . . _ crime - street : https / / data . police . uk / docs / method / crime - street / : rtype : list : param lat : The latitude of the loca...
if isinstance ( category , CrimeCategory ) : category = category . id method = 'crimes-street/%s' % ( category or 'all-crime' ) kwargs = { 'lat' : lat , 'lng' : lng , } crimes = [ ] if date is not None : kwargs [ 'date' ] = date for c in self . service . request ( 'GET' , method , ** kwargs ) : crimes . app...
def format ( self , record ) : """Override default format method ."""
if record . levelno == logging . DEBUG : string = Back . WHITE + Fore . BLACK + ' debug ' elif record . levelno == logging . INFO : string = Back . BLUE + Fore . WHITE + ' info ' elif record . levelno == logging . WARNING : string = Back . YELLOW + Fore . BLACK + ' warning ' elif record . levelno == logging...
def epifreq ( self , R ) : """NAME : epifreq PURPOSE : calculate the epicycle frequency at R in this potential INPUT : R - Galactocentric radius ( can be Quantity ) OUTPUT : epicycle frequency HISTORY : 2011-10-09 - Written - Bovy ( IAS )"""
return nu . sqrt ( self . R2deriv ( R , 0. , use_physical = False ) - 3. / R * self . Rforce ( R , 0. , use_physical = False ) )
def dataflag ( d , data_read ) : """Flagging data in single process"""
for flag in d [ 'flaglist' ] : mode , sig , conv = flag # resultlist = [ ] # with closing ( mp . Pool ( 4 , initializer = initreadonly , initargs = ( data _ read _ mem , ) ) ) as flagpool : for ss in d [ 'spw' ] : chans = n . arange ( d [ 'spw_chanr_select' ] [ ss ] [ 0 ] , d [ 'spw_chanr_select...
def parse_block_scalar_empty_line ( indent_token_class , content_token_class ) : """Process an empty line in a block scalar ."""
def callback ( lexer , match , context ) : text = match . group ( ) if ( context . block_scalar_indent is None or len ( text ) <= context . block_scalar_indent ) : if text : yield match . start ( ) , indent_token_class , text else : indentation = text [ : context . block_scalar_i...
def console_map_ascii_code_to_font ( asciiCode : int , fontCharX : int , fontCharY : int ) -> None : """Set a character code to new coordinates on the tile - set . ` asciiCode ` must be within the bounds created during the initialization of the loaded tile - set . For example , you can ' t use 255 here unless y...
lib . TCOD_console_map_ascii_code_to_font ( _int ( asciiCode ) , fontCharX , fontCharY )
def get_matrix ( self ) : """Return a copy of the current transformation matrix ( CTM ) ."""
matrix = Matrix ( ) cairo . cairo_get_matrix ( self . _pointer , matrix . _pointer ) self . _check_status ( ) return matrix
def s_data ( nrows_fdata , Nmax , Q ) : """I am going to assume we will always have even data . This is pretty safe because it means that we have measured both poles of the sphere and have data that has been continued . nrows _ fdata : Number of rows in fdata . Nmax : The largest number of n values desired ...
if np . mod ( nrows_fdata , 2 ) == 1 : raise Exception ( "nrows_fdata must be even." ) L1 = nrows_fdata s = np . zeros ( Q , dtype = np . complex128 ) MM = int ( L1 / 2 ) for nu in xrange ( - MM , MM + Nmax + 1 ) : if np . mod ( nu , 2 ) == 1 : s [ nu - MM ] = - 1j / nu return s
def _find_Generic_super_origin ( subclass , superclass_origin ) : """Helper for _ issubclass _ Generic ."""
stack = [ subclass ] param_map = { } while len ( stack ) > 0 : bs = stack . pop ( ) if is_Generic ( bs ) : if not bs . __origin__ is None and len ( bs . __origin__ . __parameters__ ) > 0 : for i in range ( len ( bs . __args__ ) ) : ors = bs . __origin__ . __parameters__ [ i ]...
def get_geometry_from_name ( self , name ) : """Returns the coordination geometry of the given name . : param name : The name of the coordination geometry ."""
for gg in self . cg_list : if gg . name == name or name in gg . alternative_names : return gg raise LookupError ( 'No coordination geometry found with name "{name}"' . format ( name = name ) )
def get_token ( url_base , tenant_id , user , password ) : """It obtains a valid token . : param url _ base : keystone url : param tenand _ id : the id of the tenant : param user : the user : param paassword : the password"""
url = 'http://' + url_base + '/v2.0/tokens' headers = { 'Content-Type' : 'application/json' } payload = '{"auth":{"tenantId":"' + tenant_id + '","passwordCredentials":{"username":"' + user + '","password":"' + password + '"}}}' response = requests . post ( url , headers = headers , data = payload ) if response . status...
def getOutEdges ( self , label = None ) : """Gets all the outgoing edges of the node . If label parameter is provided , it only returns the edges of the given label @ params label : Optional parameter to filter the edges @ returns A generator function with the outgoing edges"""
if label : for edge in self . neoelement . relationships . outgoing ( types = [ label ] ) : yield Edge ( edge ) else : for edge in self . neoelement . relationships . outgoing ( ) : yield Edge ( edge )
def asint ( vari ) : """Convert dtype of polynomial coefficients to float . Example : > > > poly = 1.5 * cp . variable ( ) + 2.25 > > > print ( poly ) 1.5q0 + 2.25 > > > print ( cp . asint ( poly ) ) q0 + 2"""
if isinstance ( vari , Poly ) : core = vari . A . copy ( ) for key in vari . keys : core [ key ] = numpy . asarray ( core [ key ] , dtype = int ) return Poly ( core , vari . dim , vari . shape , int ) return numpy . asarray ( vari , dtype = int )
def to_matrix ( self , index_regs = None , index_meta = None , columns_regs = None , columns_meta = None , values_regs = None , values_meta = None , ** kwargs ) : """Transforms the GDataframe to a pivot matrix having as index and columns the ones specified . This function is a wrapper around the pivot _ table fun...
index_regs = index_regs if index_regs is not None else [ ] index_meta = index_meta if index_meta is not None else [ ] columns_regs = columns_regs if columns_regs is not None else [ ] columns_meta = columns_meta if columns_meta is not None else [ ] values_regs = values_regs if values_regs is not None else [ ] values_met...
def set_sectPr ( self , sectPr ) : """Unconditionally replace or add * sectPr * as a grandchild in the correct sequence ."""
pPr = self . get_or_add_pPr ( ) pPr . _remove_sectPr ( ) pPr . _insert_sectPr ( sectPr )
def convert ( self , request , response , data ) : """Performs the desired Conversion . : param request : The webob Request object describing the request . : param response : The webob Response object describing the response . : param data : The data dictionary returned by the prepare ( ) method . : r...
if self . modifier . param in ( None , 'canonical' , 'local' ) : return str ( request . environ [ 'SERVER_PORT' ] ) elif self . modifier . param == 'remote' : return str ( request . environ . get ( 'REMOTE_PORT' , '-' ) ) return "-"
def read ( self , size = None ) : # pylint : disable = invalid - name """Reads from the buffer ."""
if size is None or size < 0 : raise exceptions . NotYetImplementedError ( 'Illegal read of size %s requested on BufferedStream. ' 'Wrapped stream %s is at position %s-%s, ' '%s bytes remaining.' % ( size , self . __stream , self . __start_pos , self . __end_pos , self . _bytes_remaining ) ) data = '' if self . _byt...
def get_builtin_type ( self , model ) : """Return built - in type representation of Collection . : param DomainModel model : : rtype list :"""
return [ item . get_data ( ) if isinstance ( item , self . related_model_cls ) else item for item in self . get_value ( model ) ]
def which ( name ) : """Returns the full path to executable in path matching provided name . ` name ` String value . Returns string or ` ` None ` ` ."""
# we were given a filename , return it if it ' s executable if os . path . dirname ( name ) != '' : if not os . path . isdir ( name ) and os . access ( name , os . X_OK ) : return name else : return None # fetch PATH env var and split path_val = os . environ . get ( 'PATH' , None ) or os . defpa...
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : AssetContext for this AssetInstance : rtype : twilio . rest . serverless . v1 . service . asset . AssetContext"""
if self . _context is None : self . _context = AssetContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def get_params ( self , * keys ) : """Returns the specified parameters for the current preprocessor . Parameters : keys : variable sized list , containing the names of the requested parameters Returns : values : list or dictionary , if any ` keys ` are specified those named parameters ' values are returne...
if len ( keys ) == 0 : return vars ( self ) else : return [ vars ( self ) [ k ] for k in keys ]
def merge ( self , other_rel ) : """Ingest another DistributedReliability and add its contents to the current object . Args : other _ rel : a Distributed reliability object ."""
if other_rel . thresholds . size == self . thresholds . size and np . all ( other_rel . thresholds == self . thresholds ) : self . frequencies += other_rel . frequencies else : print ( "Input table thresholds do not match." )
def _wrap_tracebackexception_format ( redact : Callable [ [ str ] , str ] ) : """Monkey - patch TracebackException . format to redact printed lines . Only the last call will be effective . Consecutive calls will overwrite the previous monkey patches ."""
original_format = getattr ( TracebackException , '_original' , None ) if original_format is None : original_format = TracebackException . format setattr ( TracebackException , '_original' , original_format ) @ wraps ( original_format ) def tracebackexception_format ( self , * , chain = True ) : for line in ...
def store_broadcast_message ( self , message , sender_wif , wifs , change_address = None , txouts = None , fee = 10000 , lock_time = 0 , dust_limit = common . DUST_LIMIT ) : """TODO add docstring"""
rawtx = self . create_tx ( txouts = txouts , lock_time = lock_time ) rawtx = self . add_broadcast_message ( rawtx , message , sender_wif , dust_limit = dust_limit ) rawtx = self . add_inputs ( rawtx , wifs , change_address = change_address , fee = fee ) return self . publish ( rawtx )
def refs_to ( cls , sha1 , repo ) : """Returns all refs pointing to the given SHA1."""
matching = [ ] for refname in repo . listall_references ( ) : symref = repo . lookup_reference ( refname ) dref = symref . resolve ( ) oid = dref . target commit = repo . get ( oid ) if commit . hex == sha1 : matching . append ( symref . shorthand ) return matching
def present ( name , value , delimiter = DEFAULT_TARGET_DELIM , force = False ) : '''Ensure that a grain is set . . versionchanged : : v2015.8.2 name The grain name value The value to set on the grain force If force is True , the existing grain will be overwritten regardless of its existing or provi...
name = re . sub ( delimiter , DEFAULT_TARGET_DELIM , name ) ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } _non_existent = object ( ) existing = __salt__ [ 'grains.get' ] ( name , _non_existent ) if existing == value : ret [ 'comment' ] = 'Grain is already set' return ret if __opts...
def gen_keys ( keydir , keyname , keysize , user = None , passphrase = None ) : '''Generate a RSA public keypair for use with salt : param str keydir : The directory to write the keypair to : param str keyname : The type of salt server for whom this key should be written . ( i . e . ' master ' or ' minion ' ) ...
base = os . path . join ( keydir , keyname ) priv = '{0}.pem' . format ( base ) pub = '{0}.pub' . format ( base ) if HAS_M2 : gen = RSA . gen_key ( keysize , 65537 , lambda : None ) else : salt . utils . crypt . reinit_crypto ( ) gen = RSA . generate ( bits = keysize , e = 65537 ) if os . path . isfile ( pr...
def disable ( self ) : """Relieve all state machines that have no active execution and hide the widget"""
self . ticker_text_label . hide ( ) if self . current_observed_sm_m : self . stop_sm_m_observation ( self . current_observed_sm_m )
def set ( self , name , value = True ) : "set a feature value"
setattr ( self , name . lower ( ) , value )
def discover_indexes ( self ) : """Save list of index builders into ` ` _ index _ builders ` ` ."""
self . indexes = [ ] for app_config in apps . get_app_configs ( ) : indexes_path = '{}.elastic_indexes' . format ( app_config . name ) try : indexes_module = import_module ( indexes_path ) for attr_name in dir ( indexes_module ) : attr = getattr ( indexes_module , attr_name ) ...
def get_family_search_session ( self , proxy = None ) : """Gets the ` ` OsidSession ` ` associated with the family search service . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . relationship . FamilySearchSession ) - a ` ` FamilySearchSession ` ` raise : NullArgument - ` ` proxy ` ` is ` ...
if not self . supports_family_search ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( ) proxy = self . _convert_proxy ( proxy ) try : session = sessions . FamilySearchSession ( proxy = proxy , runtime = self . _runtime ) except AttributeError : ...
def sum_of_nested_tuples ( tup1 , tup2 ) : """This function performs element - wise addition of two nested tuples . It pairs the corresponding elements of each tuple and then adds them together . Args : tup1 , tup2 : Nested tuples with equal dimensions Returns : A nested tuple with each element being the ...
result = tuple ( ( tuple ( ( ( element1 + element2 ) for ( element1 , element2 ) in zip ( tuple1 , tuple2 ) ) ) for ( tuple1 , tuple2 ) in zip ( tup1 , tup2 ) ) ) return result
def yVal ( self ) : """Return the ` ` < c : yVal > ` ` element for this series as an oxml element . This element contains the Y values for this series ."""
xml = self . _yVal_tmpl . format ( ** { 'nsdecls' : ' %s' % nsdecls ( 'c' ) , 'numRef_xml' : self . numRef_xml ( self . _series . y_values_ref , self . _series . number_format , self . _series . y_values ) , } ) return parse_xml ( xml )