signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_assessment_part_query_session_for_bank ( self , bank_id , proxy ) : """Gets the ` ` OsidSession ` ` associated with the assessment part query service for the given bank . arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Bank ` ` arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( o...
if not self . supports_assessment_part_query ( ) : raise errors . Unimplemented ( ) # Also include check to see if the catalog Id is found otherwise raise errors . NotFound # pylint : disable = no - member return sessions . AssessmentPartQuerySession ( bank_id , proxy , self . _runtime )
def project_closed ( self , project ) : """Called when a project is closed . : param project : Project instance"""
yield from super ( ) . project_closed ( project ) # delete useless Dynamips files project_dir = project . module_working_path ( self . module_name . lower ( ) ) files = glob . glob ( os . path . join ( glob . escape ( project_dir ) , "*.ghost" ) ) files += glob . glob ( os . path . join ( glob . escape ( project_dir ) ...
def declaration_path ( decl ) : """Returns a list of parent declarations names . Args : decl ( declaration _ t ) : declaration for which declaration path should be calculated . Returns : list [ ( str | basestring ) ] : list of names , where first item is the top parent name and last item the inputted ...
if not decl : return [ ] if not decl . cache . declaration_path : result = [ decl . name ] parent = decl . parent while parent : if parent . cache . declaration_path : result . reverse ( ) decl . cache . declaration_path = parent . cache . declaration_path + result ...
def parse ( cls , requester , entries ) : """Parse a JSON array into a list of model instances ."""
result_entries = SearchableList ( ) for entry in entries : result_entries . append ( cls . instance . parse ( requester , entry ) ) return result_entries
def decrypt ( self , value ) : """Decrypt session data ."""
try : value , timestamp , signature = value . split ( "|" ) except ValueError : return None if check_signature ( signature , self . secret , value + timestamp , encoding = self . encoding ) : return base64 . b64decode ( value ) . decode ( self . encoding )
def floating_ip_associate ( name , kwargs , call = None ) : '''Associate a floating IP address to a server . . versionadded : : 2016.3.0'''
if call != 'action' : raise SaltCloudSystemExit ( 'The floating_ip_associate action must be called with -a of --action.' ) if 'floating_ip' not in kwargs : log . error ( 'floating_ip is required' ) return False conn = get_conn ( ) conn . floating_ip_associate ( name , kwargs [ 'floating_ip' ] ) return list_...
def _ReadTable ( self , tables , file_object , table_offset ) : """Reads the table . Args : tables ( dict [ int , KeychainDatabaseTable ] ) : tables per identifier . file _ object ( file ) : file - like object . table _ offset ( int ) : offset of the table relative to the start of the file . Raises : ...
table_header = self . _ReadTableHeader ( file_object , table_offset ) for record_offset in table_header . record_offsets : if record_offset == 0 : continue record_offset += table_offset if table_header . record_type == self . _RECORD_TYPE_CSSM_DL_DB_SCHEMA_INFO : self . _ReadRecordSchemaInfo...
def has_assessment_section_begun ( self , assessment_section_id ) : """Tests if this assessment section has started . A section begins from the designated start time if a start time is defined . If no start time is defined the section may begin at any time . Assessment items cannot be accessed or submitted if...
return get_section_util ( assessment_section_id , runtime = self . _runtime ) . _assessment_taken . has_started ( )
def home ( request , chat_channel_name = None ) : """if we have a chat _ channel _ name kwarg , have the response include that channel name so the javascript knows to subscribe to that channel . . ."""
if not chat_channel_name : chat_channel_name = 'homepage' context = { 'address' : chat_channel_name , 'history' : [ ] , } if ChatMessage . objects . filter ( channel = chat_channel_name ) . exists ( ) : context [ 'history' ] = ChatMessage . objects . filter ( channel = chat_channel_name ) # TODO add https webso...
def single_device_data_message ( self , registration_id = None , condition = None , collapse_key = None , delay_while_idle = False , time_to_live = None , restricted_package_name = None , low_priority = False , dry_run = False , data_message = None , content_available = None , android_channel_id = None , timeout = 5 , ...
if registration_id is None : raise InvalidDataError ( 'Invalid registration ID' ) # [ registration _ id ] cos we ' re sending to a single device payload = self . parse_payload ( registration_ids = [ registration_id ] , condition = condition , collapse_key = collapse_key , delay_while_idle = delay_while_idle , time_...
def handle ( self , * args , ** options ) : """Compares current database with a migrations . Creates a temporary database , applies all the migrations to it , and then dumps the schema from both current and temporary , diffs them , then report the diffs to the user ."""
self . db = options . get ( "database" , DEFAULT_DB_ALIAS ) self . current_name = connections [ self . db ] . settings_dict [ "NAME" ] self . compare_name = options . get ( "db_name" ) self . lines = options . get ( "lines" ) self . ignore = int ( options . get ( 'ignore' ) ) if not self . compare_name : self . com...
def l2traceroute_input_dest_mac ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) l2traceroute = ET . Element ( "l2traceroute" ) config = l2traceroute input = ET . SubElement ( l2traceroute , "input" ) dest_mac = ET . SubElement ( input , "dest-mac" ) dest_mac . text = kwargs . pop ( 'dest_mac' ) callback = kwargs . pop ( 'callback' , self . _callback ) return call...
def _get_format_callable ( term , color , back_color ) : """Get string - coloring callable Get callable for string output using ` ` color ` ` on ` ` back _ color ` ` on ` ` term ` ` : param term : blessings . Terminal instance : param color : Color that callable will color the string it ' s passed : param...
if isinstance ( color , str ) : ensure ( any ( isinstance ( back_color , t ) for t in [ str , type ( None ) ] ) , TypeError , "back_color must be a str or NoneType" ) if back_color : return getattr ( term , "_" . join ( [ color , "on" , back_color ] ) ) elif back_color is None : return getat...
def _set_fast_flood ( self , v , load = False ) : """Setter method for fast _ flood , mapped from YANG variable / routing _ system / router / isis / router _ isis _ cmds _ holder / router _ isis _ attributes / fast _ flood ( container ) If this variable is read - only ( config : false ) in the source YANG file ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = fast_flood . fast_flood , is_container = 'container' , presence = True , yang_name = "fast-flood" , rest_name = "fast-flood" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_pat...
def field_dict_from_row ( row , model , field_names = None , ignore_fields = ( 'id' , 'pk' ) , strip = True , blank_none = True , ignore_related = True , ignore_values = ( None , ) , ignore_errors = True , verbosity = 0 ) : """Construct a Mapping ( dict ) from field names to values from a row of data Args : row...
errors = collections . Counter ( ) if not field_names : field_classes = [ f for f in model . _meta . _fields ( ) if ( not ignore_fields or ( f . name not in ignore_fields ) ) ] field_names = [ f . name for f in field_classes ] else : field_classes = [ f for f in model . _meta . _fields ( ) if ( f . name in ...
def cache_url_config ( cls , url , backend = None ) : """Pulled from DJ - Cache - URL , parse an arbitrary Cache URL . : param url : : param backend : : return :"""
url = urlparse ( url ) if not isinstance ( url , cls . URL_CLASS ) else url location = url . netloc . split ( ',' ) if len ( location ) == 1 : location = location [ 0 ] config = { 'BACKEND' : cls . CACHE_SCHEMES [ url . scheme ] , 'LOCATION' : location , } # Add the drive to LOCATION if url . scheme == 'filecache' ...
def copy_file ( old , new ) : """Copy the old file to the location of the new file : param old : The file to copy : type old : : class : ` JB _ File ` : param new : The JB _ File for the new location : type new : : class : ` JB _ File ` : returns : None : rtype : None : raises : None"""
oldp = old . get_fullpath ( ) newp = new . get_fullpath ( ) log . info ( "Copying %s to %s" , oldp , newp ) new . create_directory ( ) shutil . copy ( oldp , newp )
def print_version_of_tools ( ) : """print versions of used tools to logger"""
logger . info ( "Using these tools:" ) for tool in get_version_of_tools ( ) : logger . info ( "%s-%s at %s" , tool [ "name" ] , tool [ "version" ] , tool [ "path" ] )
def value ( self , new_value ) : """Set a value . Value is a tuple : ( < timestamp > , < new _ value > )"""
self . _value = ( datetime . now ( ) , new_value ) self . history_add ( self . _value )
def send_email_confirmation_instructions ( self , user ) : """Sends the confirmation instructions email for the specified user . Sends signal ` confirm _ instructions _ sent ` . : param user : The user to send the instructions to ."""
token = self . security_utils_service . generate_confirmation_token ( user ) confirmation_link = url_for ( 'security_controller.confirm_email' , token = token , _external = True ) self . send_mail ( _ ( 'flask_unchained.bundles.security:email_subject.email_confirmation_instructions' ) , to = user . email , template = '...
def dominant_flat_five ( note ) : """Build a dominant flat five chord on note . Example : > > > dominant _ flat _ five ( ' C ' ) [ ' C ' , ' E ' , ' Gb ' , ' Bb ' ]"""
res = dominant_seventh ( note ) res [ 2 ] = notes . diminish ( res [ 2 ] ) return res
def get_title ( self ) : """The title to be displayed in the titlebar of the terminal ."""
w = self . arrangement . get_active_window ( ) if w and w . active_process : title = w . active_process . screen . title else : title = '' if title : return '%s - Pymux' % ( title , ) else : return 'Pymux'
def search_filter ( entities , filters ) : """Read all ` ` entities ` ` and locally filter them . This method can be used like so : : entities = EntitySearchMixin ( entities , { ' name ' : ' foo ' } ) In this example , only entities where ` ` entity . name = = ' foo ' ` ` holds true are returned . An arbitr...
# Check to make sure all arguments are sane . if len ( entities ) == 0 : return entities fields = entities [ 0 ] . get_fields ( ) # assume all entities are identical if not set ( filters ) . issubset ( fields ) : raise NoSuchFieldError ( 'Valid filters are {0}, but received {1} instead.' . format ( fields . key...
def _is_logged_in ( self ) : """Check whether or not the user is logged in ."""
# if the user has not logged in in 24 hours , relogin if not self . _http . _has_session ( ) or datetime . utcnow ( ) >= self . _lastlogin + timedelta ( hours = 24 ) : return self . _login ( ) else : return { }
async def get_search_page ( self , term : str ) : """Get search page . This function will get the first link from the search term we do on term and then it will return the link we want to parse from . : param term : Light Novel to Search For"""
# Uses the BASEURL and also builds link for the page we want using the term given params = { 's' : term , 'post_type' : 'seriesplan' } async with self . session . get ( self . BASEURL , params = params ) as response : # If the response is 200 OK if response . status == 200 : search = BeautifulSoup ( await r...
def DedupVcardFilenames ( vcard_dict ) : """Make sure every vCard in the dictionary has a unique filename ."""
remove_keys = [ ] add_pairs = [ ] for k , v in vcard_dict . items ( ) : if not len ( v ) > 1 : continue for idx , vcard in enumerate ( v ) : fname , ext = os . path . splitext ( k ) fname = '{}-{}' . format ( fname , idx + 1 ) fname = fname + ext assert fname not in vcard...
def compat_get_paginated_response ( view , page ) : """get _ paginated _ response is unknown to DRF 3.0"""
if DRFVLIST [ 0 ] == 3 and DRFVLIST [ 1 ] >= 1 : from rest_messaging . serializers import ComplexMessageSerializer # circular import serializer = ComplexMessageSerializer ( page , many = True ) return view . get_paginated_response ( serializer . data ) else : serializer = view . get_pagination_seria...
def get_json ( filename ) : """Return a json value of the exif Get a filename and return a JSON object Arguments : filename { string } - - your filename Returns : [ JSON ] - - Return a JSON object"""
check_if_this_file_exist ( filename ) # Process this function filename = os . path . abspath ( filename ) s = command_line ( [ 'exiftool' , '-G' , '-j' , '-sort' , filename ] ) if s : # convert bytes to string s = s . decode ( 'utf-8' ) . rstrip ( '\r\n' ) return json . loads ( s ) else : return s
def icohplist ( self ) : """Returns : icohplist compatible with older version of this class"""
icohplist_new = { } for key , value in self . _icohpcollection . _icohplist . items ( ) : icohplist_new [ key ] = { "length" : value . _length , "number_of_bonds" : value . _num , "icohp" : value . _icohp , "translation" : value . _translation } return icohplist_new
def stream ( self , date_created_after = values . unset , date_created_before = values . unset , track = values . unset , publisher = values . unset , kind = values . unset , limit = None , page_size = None ) : """Streams SubscribedTrackInstance records from the API as a generator stream . This operation lazily l...
limits = self . _version . read_limits ( limit , page_size ) page = self . page ( date_created_after = date_created_after , date_created_before = date_created_before , track = track , publisher = publisher , kind = kind , page_size = limits [ 'page_size' ] , ) return self . _version . stream ( page , limits [ 'limit' ]...
def EnableJob ( self , job_id , token = None ) : """Enable cron job with the given URN ."""
job_urn = self . CRON_JOBS_PATH . Add ( job_id ) cron_job = aff4 . FACTORY . Open ( job_urn , mode = "rw" , aff4_type = CronJob , token = token ) cron_job . Set ( cron_job . Schema . DISABLED ( 0 ) ) cron_job . Close ( )
def metadata ( self , file_path , params = None ) : """: params : title : string keywords : array extra _ metadata : array temporal _ coverage : coverage object spatial _ coverage : coverage object : return : file metadata object ( 200 status code )"""
url_base = self . hs . url_base url = "{url_base}/resource/{pid}/files/metadata/{file_path}/" . format ( url_base = url_base , pid = self . pid , file_path = file_path ) if params is None : r = self . hs . _request ( 'GET' , url ) else : headers = { } headers [ "Content-Type" ] = "application/json" r = ...
def _complete_word ( self , symbol , attribute ) : """Suggests context completions based exclusively on the word preceding the cursor ."""
# The cursor is after a % ( , \ s and the user is looking for a list # of possibilities that is a bit smarter that regular AC . if self . context . el_call in [ "sub" , "fun" , "assign" , "arith" ] : if symbol == "" : # The only possibilities are local vars , global vars or functions # presented in that order o...
def get_auth_token ( self , user ) : """Returns the user ' s authentication token ."""
data = [ str ( user . id ) , self . security . hashing_context . hash ( encode_string ( user . _password ) ) ] return self . security . remember_token_serializer . dumps ( data )
def not26 ( func ) : """Function decorator for methods not implemented in Python 2.6."""
@ wraps ( func ) def errfunc ( * args , ** kwargs ) : raise NotImplementedError if hexversion < 0x02070000 : return errfunc else : return func
def set_location ( self , location , values , missing_to_none = False ) : """Sets the column values , as given by the keys of the values dict , for the row at location to the values of the values dict . If missing _ to _ none is False then columns not in the values dict will be left unchanged , if it is True th...
if missing_to_none : # populate the dict with None in any column missing for column in self . _columns : if column not in values : values [ column ] = None for column in values : i = self . _columns . index ( column ) self . _data [ i ] [ location ] = values [ column ]
def average_value ( num_list ) : """This function calculates the average of all numbers in a given list . Examples : average _ value ( [ 8 , 2 , 3 , 0 , 7 ] ) - > 4.0 average _ value ( [ - 10 , - 20 , - 30 ] ) - > - 20.0 average _ value ( [ 19 , 15 , 18 ] ) - > 17.333332 : param num _ list : A list of num...
sum_of_numbers = sum ( num_list ) quantity_of_numbers = len ( num_list ) return ( sum_of_numbers / quantity_of_numbers )
def concretize_read_addr ( self , addr , strategies = None ) : """Concretizes an address meant for reading . : param addr : An expression for the address . : param strategies : A list of concretization strategies ( to override the default ) . : returns : A list of concrete addresses ."""
if isinstance ( addr , int ) : return [ addr ] elif not self . state . solver . symbolic ( addr ) : return [ self . state . solver . eval ( addr ) ] strategies = self . read_strategies if strategies is None else strategies return self . _apply_concretization_strategies ( addr , strategies , 'load' )
def __recognize_list ( self , node : yaml . Node , expected_type : Type ) -> RecResult : """Recognize a node that we expect to be a list of some kind . Args : node : The node to recognize . expected _ type : List [ . . . something . . . ] Returns expected _ type and the empty string if it was recognized ,...
logger . debug ( 'Recognizing as a list' ) if not isinstance ( node , yaml . SequenceNode ) : message = '{}{}Expected a list here.' . format ( node . start_mark , os . linesep ) return [ ] , message item_type = generic_type_args ( expected_type ) [ 0 ] for item in node . value : recognized_types , message =...
def find_existing_configs ( self , default ) : '''Find configuration files on the system . : return :'''
configs = [ ] for cfg in [ default , self . _config_filename_ , 'minion' , 'proxy' , 'cloud' , 'spm' ] : if not cfg : continue config_path = self . get_config_file_path ( cfg ) if os . path . exists ( config_path ) : configs . append ( cfg ) if default and default not in configs : raise ...
def z2r ( z ) : """Function that calculates the inverse Fisher z - transformation Parameters z : int or ndarray Fishers z transformed correlation value Returns result : int or ndarray Correlation value"""
with np . errstate ( invalid = 'ignore' , divide = 'ignore' ) : return ( np . exp ( 2 * z ) - 1 ) / ( np . exp ( 2 * z ) + 1 )
def data ( self , data : numpy . ndarray ) -> None : """Set the data . : param data : A numpy ndarray . . . versionadded : : 1.0 Scriptable : Yes"""
self . __data_item . set_data ( numpy . copy ( data ) )
def complete_acquaintance_strategy ( qubit_order : Sequence [ ops . Qid ] , acquaintance_size : int = 0 , ) -> circuits . Circuit : """Returns an acquaintance strategy capable of executing a gate corresponding to any set of at most acquaintance _ size qubits . Args : qubit _ order : The qubits on which the st...
if acquaintance_size < 0 : raise ValueError ( 'acquaintance_size must be non-negative.' ) elif acquaintance_size == 0 : return circuits . Circuit ( device = UnconstrainedAcquaintanceDevice ) if acquaintance_size > len ( qubit_order ) : return circuits . Circuit ( device = UnconstrainedAcquaintanceDevice ) i...
def greyInput ( self ) : """Adjust ` ` self . d ` ` dictionary for greyscale input device . ` ` profileclass ` ` is ' scnr ' , ` ` colourspace ` ` is ' GRAY ' , ` ` pcs ` ` is ' XYZ ' ."""
self . d . update ( dict ( profileclass = 'scnr' , colourspace = 'GRAY' , pcs = 'XYZ ' ) ) return self
def clean_by_request ( self , request ) : '''Remove all futures that were waiting for request ` request ` since it is done waiting'''
if request not in self . request_map : return for tag , matcher , future in self . request_map [ request ] : # timeout the future self . _timeout_future ( tag , matcher , future ) # remove the timeout if future in self . timeout_map : tornado . ioloop . IOLoop . current ( ) . remove_timeout ( se...
def row_includes_spans ( table , row , spans ) : """Determine if there are spans within a row Parameters table : list of lists of str row : int spans : list of lists of lists of int Returns bool Whether or not a table ' s row includes spans"""
for column in range ( len ( table [ row ] ) ) : for span in spans : if [ row , column ] in span : return True return False
def surfacemass ( self , R , log = False ) : """NAME : surfacemass PURPOSE : return the surface density profile at this R INPUT : R - Galactocentric radius ( / ro ) log - if True , return the log ( default : False ) OUTPUT : Sigma ( R ) HISTORY : 2010-03-26 - Written - Bovy ( NYU )"""
if log : return - R / self . _params [ 0 ] else : return sc . exp ( - R / self . _params [ 0 ] )
def _precompile_regexp ( self , trigger ) : """Precompile the regex for most triggers . If the trigger is non - atomic , and doesn ' t include dynamic tags like ` ` < bot > ` ` , ` ` < get > ` ` , ` ` < input > / < reply > ` ` or arrays , it can be precompiled and save time when matching . : param str trigg...
if utils . is_atomic ( trigger ) : return # Don ' t need a regexp for atomic triggers . # Check for dynamic tags . for tag in [ "@" , "<bot" , "<get" , "<input" , "<reply" ] : if tag in trigger : return # Can ' t precompile this trigger . self . _regexc [ "trigger" ] [ trigger ] = self . _brain . reply_...
def ls ( ctx , name ) : """List EMR instances"""
session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) client = session . client ( 'emr' ) results = client . list_clusters ( ClusterStates = [ 'RUNNING' , 'STARTING' , 'BOOTSTRAPPING' , 'WAITING' ] ) for cluster in results [ 'Clusters' ] : click . echo ( "{0}\t{1}\t{2}" . format ( cluster [ 'Id' ] , cluster...
def is_of_genus_type ( self , genus_type = None ) : """Tests if this object is of the given genus Type . The given genus type may be supported by the object through the type hierarchy . | arg : ` ` genus _ type ` ` ( ` ` osid . type . Type ` ` ) : a genus type | return : ( ` ` boolean ` ` ) - true if this o...
if genus_type is None : raise NullArgument ( ) else : my_genus_type = self . get_genus_type ( ) return ( genus_type . get_authority ( ) == my_genus_type . get_authority ( ) and genus_type . get_identifier_namespace ( ) == my_genus_type . get_identifier_namespace ( ) and genus_type . get_identifier ( ) == my...
def require_subsystem ( self , subsystem , log_method = logging . warning ) : """Check whether the given subsystem is enabled and is writable ( i . e . , new cgroups can be created for it ) . Produces a log message for the user if one of the conditions is not fulfilled . If the subsystem is enabled but not wr...
if not subsystem in self : log_method ( 'Cgroup subsystem %s is not enabled. ' 'Please enable it with "sudo mount -t cgroup none /sys/fs/cgroup".' , subsystem ) return False try : test_cgroup = self . create_fresh_child_cgroup ( subsystem ) test_cgroup . remove ( ) except OSError as e : self . paths...
def setProp ( self , name , value ) : """Set ( or reset ) an attribute carried by a node . If @ name has a prefix , then the corresponding namespace - binding will be used , if in scope ; it is an error it there ' s no such ns - binding for the prefix in scope ."""
ret = libxml2mod . xmlSetProp ( self . _o , name , value ) if ret is None : raise treeError ( 'xmlSetProp() failed' ) __tmp = xmlAttr ( _obj = ret ) return __tmp
def nucleotide_range ( self ) : '''Returns the nucleotide ( start , end ) positions inclusive of this variant . start = = end if it ' s an amino acid variant , otherwise start + 2 = = end'''
if self . variant_type == 'p' : return 3 * self . position , 3 * self . position + 2 else : return self . position , self . position
def to_file ( self , filename , binary = False , ** kwargs ) : """Save gridded data to a file . Usage x . to _ file ( filename , [ binary , * * kwargs ] ) Parameters filename : str Name of output file . For text files ( default ) , the file will be saved automatically in gzip compressed format if the fi...
if binary is False : _np . savetxt ( filename , self . data , ** kwargs ) elif binary is True : _np . save ( filename , self . data , ** kwargs ) else : raise ValueError ( 'binary must be True or False. ' 'Input value is {:s}' . format ( binary ) )
def makeBasicSolution ( self , EndOfPrdvP , aLvl , interpolator ) : '''Given end of period assets and end of period marginal value , construct the basic solution for this period . Parameters EndOfPrdvP : np . array Array of end - of - period marginal values . aLvl : np . array Array of end - of - period...
xLvl , mLvl , pLvl = self . getPointsForInterpolation ( EndOfPrdvP , aLvl ) MedShk_temp = np . tile ( np . reshape ( self . MedShkVals , ( self . MedShkVals . size , 1 , 1 ) ) , ( 1 , mLvl . shape [ 1 ] , mLvl . shape [ 2 ] ) ) solution_now = self . usePointsForInterpolation ( xLvl , mLvl , pLvl , MedShk_temp , interpo...
def name_parts ( self ) : """Works with PartialNameMixin . clear _ dict to set NONE and ANY values ."""
default = PartialMixin . ANY np = ( [ ( k , default , True ) for k , _ , _ in super ( NameQuery , self ) . name_parts ] + [ ( k , default , True ) for k , _ , _ in Name . _generated_names ] ) return np
def transaction ( self , collections , action , waitForSync = False , lockTimeout = None , params = None ) : """Execute a server - side transaction"""
payload = { "collections" : collections , "action" : action , "waitForSync" : waitForSync } if lockTimeout is not None : payload [ "lockTimeout" ] = lockTimeout if params is not None : payload [ "params" ] = params self . connection . reportStart ( action ) r = self . connection . session . post ( self . transa...
def get_paths_to_simplify ( G , strict = True ) : """Create a list of all the paths to be simplified between endpoint nodes . The path is ordered from the first endpoint , through the interstitial nodes , to the second endpoint . If your street network is in a rural area with many interstitial nodes between t...
# first identify all the nodes that are endpoints start_time = time . time ( ) endpoints = set ( [ node for node in G . nodes ( ) if is_endpoint ( G , node , strict = strict ) ] ) log ( 'Identified {:,} edge endpoints in {:,.2f} seconds' . format ( len ( endpoints ) , time . time ( ) - start_time ) ) start_time = time ...
def _tag_cmds ( self , * cmds ) : """Yields tagged commands ."""
for ( method , args ) in cmds : tagged_cmd = [ method , args , self . _tag ] self . _tag = self . _tag + 1 yield tagged_cmd
def _find ( self , name , domain = None , path = None ) : """Requests uses this method internally to get cookie values . If there are conflicting cookies , _ find arbitrarily chooses one . See _ find _ no _ duplicates if you want an exception thrown if there are conflicting cookies . : param name : a string...
for cookie in iter ( self ) : if cookie . name == name : if domain is None or cookie . domain == domain : if path is None or cookie . path == path : return cookie . value raise KeyError ( 'name=%r, domain=%r, path=%r' % ( name , domain , path ) )
def delete_server_cert ( cert_name , region = None , key = None , keyid = None , profile = None ) : '''Deletes a certificate from Amazon . . . versionadded : : 2015.8.0 CLI Example : . . code - block : : bash salt myminion boto _ iam . delete _ server _ cert mycert _ name'''
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) try : return conn . delete_server_cert ( cert_name ) except boto . exception . BotoServerError as e : log . debug ( e ) log . error ( 'Failed to delete certificate %s.' , cert_name ) return False
def sents ( self , fileids = None ) -> Generator [ str , str , None ] : """: param fileids : : return : A generator of sentences"""
for para in self . paras ( fileids ) : sentences = self . _sent_tokenizer . tokenize ( para ) for sentence in sentences : yield sentence
def get_possible_splits ( n ) : """Parameters n : int n strokes were make"""
get_bin = lambda x , n : x >= 0 and str ( bin ( x ) ) [ 2 : ] . zfill ( n ) or "-" + str ( bin ( x ) ) [ 3 : ] . zfill ( n ) possible_splits = [ ] for i in range ( 2 ** ( n - 1 ) ) : possible_splits . append ( get_bin ( i , n - 1 ) ) return possible_splits
def iteration ( self , node_status = True ) : """Execute a single model iteration : return : Iteration _ id , Incremental node status ( dictionary node - > status )"""
self . clean_initial_status ( self . available_statuses . values ( ) ) actual_status = { node : nstatus for node , nstatus in future . utils . iteritems ( self . status ) } if self . actual_iteration == 0 : self . actual_iteration += 1 delta , node_count , status_delta = self . status_delta ( actual_status ) ...
def unique_lorem ( anon , obj , field , val ) : """Generates a unique paragraph of lorem ipsum text"""
return anon . faker . unique_lorem ( field = field )
def setCurrentLayer ( self , layer ) : """Sets the current layer for this scene to the inputed layer . : param layer | < XNodeLayer > | | None"""
if self . _currentLayer == layer : return False old = self . _currentLayer self . _currentLayer = layer if old is not None : old . sync ( ) if layer is not None : layer . sync ( ) self . selectionFinished . emit ( ) self . invalidate ( ) return True
def edges ( self , data = False , native = True ) : """Returns a list of all edges in the : class : ` . GraphCollection ` \ . Parameters data : bool ( default : False ) If True , returns a list of 3 - tuples containing source and target node labels , and attributes . Returns edges : list"""
edges = self . master_graph . edges ( data = data ) if native : if data : edges = [ ( self . node_index [ s ] , self . node_index [ t ] , attrs ) for s , t , attrs in edges ] else : edges = [ ( self . node_index [ s ] , self . node_index [ t ] ) for s , t in edges ] return edges
def get_stanza ( self , peer_jid ) : """Return the last presence recieved for the given bare or full ` peer _ jid ` . If the last presence was unavailable , the return value is : data : ` None ` , as if no presence was ever received . If no presence was ever received for the given bare JID , : data : ` None `...
try : return self . _presences [ peer_jid . bare ( ) ] [ peer_jid . resource ] except KeyError : pass try : return self . _presences [ peer_jid . bare ( ) ] [ None ] except KeyError : pass
def readDivPressure ( fileName ) : """Reads in diversifying pressures from some file . Scale diversifying pressure values so absolute value of the max value is 1, unless all values are zero . Args : ` fileName ` ( string or readable file - like object ) File holding diversifying pressure values . Can be ...
try : df = pandas . read_csv ( fileName , sep = None , engine = 'python' ) pandasformat = True except ValueError : pandasformat = False df . columns = [ 'site' , 'divPressureValue' ] scaleFactor = max ( df [ "divPressureValue" ] . abs ( ) ) if scaleFactor > 0 : df [ "divPressureValue" ] = [ x / scaleFac...
def _getFromTime ( self , atDate = None ) : """Time that the event starts ( in the local time zone ) ."""
return getLocalTime ( self . date_from , self . time_from , self . tz )
def _flatterm_iter ( cls , expression : Expression ) -> Iterator [ TermAtom ] : """Generator that yields the atoms of the expressions in prefix notation with operation end markers ."""
if isinstance ( expression , Operation ) : yield type ( expression ) for operand in op_iter ( expression ) : yield from cls . _flatterm_iter ( operand ) yield OPERATION_END elif isinstance ( expression , SymbolWildcard ) : yield expression . symbol_type elif isinstance ( expression , ( Symbol , ...
def only_for ( theme , redirect_to = '/' , raise_error = None ) : """Decorator for restrict access to views according by list of themes . Params : * ` ` theme ` ` - string or list of themes where decorated view must be * ` ` redirect _ to ` ` - url or name of url pattern for redirect if CURRENT _ THEME not ...
def check_theme ( * args , ** kwargs ) : if isinstance ( theme , six . string_types ) : themes = ( theme , ) else : themes = theme if settings . CURRENT_THEME is None : return True result = settings . CURRENT_THEME in themes if not result and raise_error is not None : ...
def send_response ( self , code , message = None ) : """Send the response header and log the response code ."""
self . log_request ( code ) if message is None : message = code in self . responses and self . responses [ code ] [ 0 ] or "" if self . request_version != "HTTP/0.9" : hdr = "%s %d %s\r\n" % ( self . protocol_version , code , message ) self . wfile . write ( hdr . encode ( "ascii" ) )
def quitter ( ) : """Mark quitter as such ."""
unique_id = request . form [ 'uniqueId' ] if unique_id [ : 5 ] == "debug" : debug_mode = True else : debug_mode = False if debug_mode : resp = { "status" : "didn't mark as quitter since this is debugging" } return jsonify ( ** resp ) else : try : unique_id = request . form [ 'uniqueId' ] ...
def generate_fetch_ivy ( cls , jars , ivyxml , confs , resolve_hash_name ) : """Generates an ivy xml with all jars marked as intransitive using the all conflict manager ."""
org = IvyUtils . INTERNAL_ORG_NAME name = resolve_hash_name extra_configurations = [ conf for conf in confs if conf and conf != 'default' ] # Use org name _ and _ rev so that we can have dependencies with different versions . This will # allow for batching fetching if we want to do that . jars_by_key = OrderedDict ( ) ...
def ibm_to_ieee ( ibm ) : '''Translate IBM - format floating point numbers ( as bytes ) to IEEE 754 64 - bit floating point format ( as Python float ) .'''
# IBM mainframe : sign * 0 . mantissa * 16 * * ( exponent - 64) # Python uses IEEE : sign * 1 . mantissa * 2 * * ( exponent - 1023) # Pad - out to 8 bytes if necessary . We expect 2 to 8 bytes , but # there ' s no need to check ; bizarre sizes will cause a struct # module unpack error . ibm = ibm . ljust ( 8 , b'\x00' ...
def verify ( self , smessage , signature = None , encoder = encoding . RawEncoder ) : """Verifies the signature of a signed message , returning the message if it has not been tampered with else raising : class : ` ~ nacl . signing . BadSignatureError ` . : param smessage : [ : class : ` bytes ` ] Either the o...
if signature is not None : # If we were given the message and signature separately , combine # them . smessage = signature + encoder . decode ( smessage ) else : # Decode the signed message smessage = encoder . decode ( smessage ) return nacl . bindings . crypto_sign_open ( smessage , self . _key )
def get_multiple_layers ( self , layer_name ) : """Returns a list of all the layers in the packet that are of the layer type ( an incase - sensitive string ) . This is in order to retrieve layers which appear multiple times in the same packet ( i . e . double VLAN ) which cannot be retrieved by easier means .""...
return [ layer for layer in self . layers if layer . layer_name . lower ( ) == layer_name . lower ( ) ]
def encrpyt_file ( self , filename ) : '''Encrypt File Args : filename : Pass the filename to encrypt . Returns : No return .'''
if not os . path . exists ( filename ) : print "Invalid filename %s. Does not exist" % filename return if self . vault_password is None : print "ENV Variable PYANSI_VAULT_PASSWORD not set" return if self . is_file_encrypted ( filename ) : # No need to do anything . return cipher = 'AES256' vaultedit...
def retry_shipper_tasks ( self , project_name , logstore_name , shipper_name , task_list ) : """retry failed tasks , only the failed task can be retried Unsuccessful opertaion will cause an LogException . : type project _ name : string : param project _ name : the Project name : type logstore _ name : strin...
headers = { } params = { } body = six . b ( json . dumps ( task_list ) ) headers [ 'Content-Type' ] = 'application/json' headers [ 'x-log-bodyrawsize' ] = str ( len ( body ) ) resource = "/logstores/" + logstore_name + "/shipper/" + shipper_name + "/tasks" ( resp , header ) = self . _send ( "PUT" , project_name , body ...
def make_app ( global_conf , full_stack = True , static_files = True , ** app_conf ) : """Create a Pylons WSGI application and return it ` ` global _ conf ` ` The inherited configuration for this application . Normally from the [ DEFAULT ] section of the Paste ini file . ` ` full _ stack ` ` Whether this ...
# Configure the Pylons environment config = load_environment ( global_conf , app_conf ) # The Pylons WSGI app app = PylonsApp ( config = config ) # Routing / Session Middleware app = RoutesMiddleware ( app , config [ 'routes.map' ] , singleton = False ) app = SessionMiddleware ( app , config ) # CUSTOM MIDDLEWARE HERE ...
def save ( self , dst , buffer_size = 16384 ) : """Save the file to a destination path or file object . If the destination is a file object you have to close it yourself after the call . The buffer size is the number of bytes held in memory during the copy process . It defaults to 16KB . For secure file sav...
from shutil import copyfileobj close_dst = False if isinstance ( dst , string_types ) : dst = open ( dst , "wb" ) close_dst = True try : copyfileobj ( self . stream , dst , buffer_size ) finally : if close_dst : dst . close ( )
def is_dark_font_color ( color_scheme ) : """Check if the font color used in the color scheme is dark ."""
color_scheme = get_color_scheme ( color_scheme ) font_color , fon_fw , fon_fs = color_scheme [ 'normal' ] return dark_color ( font_color )
def __buttonEvent ( event ) : """Handle an event that is generated by a person clicking a button ."""
global boxRoot , __widgetTexts , __replyButtonText __replyButtonText = __widgetTexts [ event . widget ] boxRoot . quit ( )
def isCode ( self , blockOrBlockNumber , column ) : """Check if text at given position is a code . If language is not known , or text is not parsed yet , ` ` True ` ` is returned"""
if isinstance ( blockOrBlockNumber , QTextBlock ) : block = blockOrBlockNumber else : block = self . document ( ) . findBlockByNumber ( blockOrBlockNumber ) return self . _highlighter is None or self . _highlighter . isCode ( block , column )
def strongly_connected_components ( self ) : """Return list of strongly connected components of this graph . Returns a list of subgraphs . Algorithm is based on that described in " Path - based depth - first search for strong and biconnected components " by Harold N . Gabow , Inf . Process . Lett . 74 ( 200...
raw_sccs = self . _component_graph ( ) sccs = [ ] for raw_scc in raw_sccs : sccs . append ( [ v for vtype , v in raw_scc if vtype == 'VERTEX' ] ) return [ self . full_subgraph ( scc ) for scc in sccs ]
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : """Create a JobTemplate object before calling read ( ) ignore ' advanced '"""
if entity is None : entity = TemplateInput ( self . _server_config , template = self . template ) if ignore is None : ignore = set ( ) ignore . add ( 'advanced' ) return super ( TemplateInput , self ) . read ( entity = entity , attrs = attrs , ignore = ignore , params = params )
def render_string ( self , template_name , ** kwargs ) : """添加注入模板的自定义参数等信息"""
if hasattr ( self , "session" ) : kwargs [ "session" ] = self . session return super ( BaseHandler , self ) . render_string ( template_name , ** kwargs )
def normalize_body ( self , b ) : """return the body as a string , formatted to the appropriate content type : param b : mixed , the current raw body : returns : unicode string"""
if b is None : return '' if self . is_json ( ) : # TODO ? ? ? # I don ' t like this , if we have a content type but it isn ' t one # of the supported ones we were returning the exception , which threw # Jarid off , but now it just returns a string , which is not best either # my thought is we could have a body _ ty...
def _collect ( self , section = None ) : """Collect HAProxy Stats"""
if self . config [ 'method' ] == 'http' : csv_data = self . http_get_csv_data ( section ) elif self . config [ 'method' ] == 'unix' : csv_data = self . unix_get_csv_data ( ) else : self . log . error ( "Unknown collection method: %s" , self . config [ 'method' ] ) csv_data = [ ] data = list ( csv . read...
def _read ( self , size ) : """Return size bytes from the stream ."""
if self . comptype == "tar" : return self . __read ( size ) c = len ( self . dbuf ) while c < size : buf = self . __read ( self . bufsize ) if not buf : break try : buf = self . cmp . decompress ( buf ) except IOError : raise ReadError ( "invalid compressed data" ) self ....
def _kwargs_checks_gen ( self , decorated_function , function_spec , arg_specs ) : """Generate checks for keyword argument testing : param decorated _ function : function decorator : param function _ spec : function inspect information : param arg _ specs : argument specification ( same as arg _ specs in : me...
args_names = [ ] args_names . extend ( function_spec . args ) if function_spec . varargs is not None : args_names . append ( function_spec . args ) args_check = { } for arg_name in arg_specs . keys ( ) : if arg_name not in args_names : args_check [ arg_name ] = self . check ( arg_specs [ arg_name ] , ar...
def translate ( patterns , * , flags = 0 ) : """Translate ` fnmatch ` pattern ."""
flags = _flag_transform ( flags ) return _wcparse . translate ( _wcparse . split ( patterns , flags ) , flags )
def get_all_results_for_query_batch ( self , batch_id , job_id = None , chunk_size = 2048 ) : """Gets result ids and generates each result set from the batch and returns it as an generator fetching the next result set when needed Args : batch _ id : id of batch job _ id : id of job , if not provided , it wi...
result_ids = self . get_query_batch_result_ids ( batch_id , job_id = job_id ) if not result_ids : raise RuntimeError ( 'Batch is not complete' ) for result_id in result_ids : yield self . get_query_batch_results ( batch_id , result_id , job_id = job_id , chunk_size = chunk_size )
def kwargs_from_keyword ( from_kwargs , to_kwargs , keyword , clean_origin = True ) : """Looks for keys of the format keyword _ value . And return a dictionary with { keyword : value } format Parameters : from _ kwargs : dict Original dictionary to _ kwargs : dict Dictionary where the items will be appe...
for k in list ( from_kwargs . keys ( ) ) : if '{0}_' . format ( keyword ) in k : to_kwargs [ k . replace ( '{0}_' . format ( keyword ) , '' ) ] = from_kwargs [ k ] if clean_origin : del from_kwargs [ k ] return to_kwargs
def add ( self , registry ) : """Add works like replace , but only previously pushed metrics with the same name ( and the same job and instance ) will be replaced . ( It uses HTTP method ' POST ' to push to the Pushgateway . )"""
# POST payload = self . formatter . marshall ( registry ) r = requests . post ( self . path , data = payload , headers = self . headers )
def _get_model_fields ( self , model , prefix = _field_prefix ) : """Find all fields of given model that are not default models ."""
fields = list ( ) for field_name , field in model ( ) . _ordered_fields : # Filter the default fields if field_name not in getattr ( model , '_DEFAULT_BASE_FIELDS' , [ ] ) : type_name = utils . to_camel ( field . solr_type ) required = self . _marker_true if field . required is True else self . _mar...
def command_list ( self , sources , _opt = False ) : '''command line as list'''
def abspath ( x ) : x = Path ( x ) . abspath ( ) if not x . exists ( ) : raise ValueError ( 'file not found! ' + x ) return x self . f_cpu = int ( self . f_cpu ) self . mcu = str ( self . mcu ) # if not self . mcu in self . targets : # raise ValueError ( ' invalid mcu : ' + self . mcu ) if not _opt ...
def vote ( cls ) : """Cast a public vote for this comic ."""
url = configuration . VoteUrl + 'count/' uid = get_system_uid ( ) data = { "name" : cls . getName ( ) . replace ( '/' , '_' ) , "uid" : uid } page = urlopen ( url , cls . session , data = data ) return page . text
def set_parameter_values ( self , values ) : """Sets the value of multiple parameters . : param dict values : Values keyed by parameter name . This name can be either a fully - qualified XTCE name or an alias in the format ` ` NAMESPACE / NAME ` ` ."""
req = rest_pb2 . BulkSetParameterValueRequest ( ) for key in values : item = req . request . add ( ) item . id . MergeFrom ( _build_named_object_id ( key ) ) item . value . MergeFrom ( _build_value_proto ( values [ key ] ) ) url = '/processors/{}/{}/parameters/mset' . format ( self . _instance , self . _pro...