signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _get_parameter_dictionary ( self , base_name , dictionary , sorted_keys , parameter ) : """Recursively loops over the parameter ' s children , adding keys ( starting with base _ name ) and values to the supplied dictionary ( provided they do not have a value of None ) ."""
# assemble the key for this parameter k = base_name + "/" + parameter . name ( ) # first add this parameter ( if it has a value ) if not parameter . value ( ) == None : sorted_keys . append ( k [ 1 : ] ) dictionary [ sorted_keys [ - 1 ] ] = parameter . value ( ) # now loop over the children for p in parameter ....
def phone_number ( random = random , * args , ** kwargs ) : """Return a phone number > > > mock _ random . seed ( 0) > > > phone _ number ( random = mock _ random ) '555-0000' > > > phone _ number ( random = mock _ random ) '1-604-555-0000' > > > phone _ number ( random = mock _ random ) '864-70-555-0...
return random . choice ( [ '555-{number}{other_number}{number}{other_number}' , '1-604-555-{number}{other_number}{number}{other_number}' , '864-70-555-{number}{other_number}{number}{other_number}' , '867-5309' ] ) . format ( number = number ( random = random ) , other_number = number ( random = random ) )
def analysis_error ( sender , exception , message ) : """A helper to spawn an error and halt processing . An exception will be logged , busy status removed and a message displayed . . . versionadded : : 3.3 : param sender : The sender . : type sender : object : param message : an ErrorMessage to display...
LOGGER . exception ( message ) message = get_error_message ( exception , context = message ) send_error_message ( sender , message )
def get_git_isolation ( ) : """Get Git isolation from the current context ."""
ctx = click . get_current_context ( silent = True ) if ctx and GIT_ISOLATION in ctx . meta : return ctx . meta [ GIT_ISOLATION ]
def get_token ( user = None , password = None , url = 'https://localhost:8089' , verify = False , ssl_options = None , version = "7.0.3" , debug = False ) : """get _ token This will get a user token and throw for any errors : param user : username - defaults to env var : SPLUNK _ ADMIN _ USER : param passwo...
use_user = os . getenv ( "SPLUNK_ADMIN_USER" , user ) use_password = os . getenv ( "SPLUNK_ADMIN_PASSWORD" , password ) if not use_user : use_user = "admin" if not use_password : use_password = "changeme" full_url = ( '{}/servicesNS/admin/splunk_httpinput/data/inputs/http' ) . format ( url ) if debug : prin...
def to_email ( email_class , email , language = None , ** data ) : """Send email to specified email address"""
if language : email_class ( ) . send ( [ email ] , language = language , ** data ) else : email_class ( ) . send ( [ email ] , translation . get_language ( ) , ** data )
def body ( self ) : """Response body . : raises : : class : ` ContentLimitExceeded ` , : class : ` ContentDecodingError `"""
content = [ ] length = 0 for chunk in self : content . append ( chunk ) length += len ( chunk ) if self . length_limit and length > self . length_limit : self . close ( ) raise ContentLimitExceeded ( "Content length is more than %d " "bytes" % self . length_limit ) return b ( "" ) . join ( c...
def _fat_mounts ( self ) : """! Lists mounted devices with vfat file system ( potential mbeds ) @ result Returns list of all mounted vfat devices @ details Uses Linux shell command : ' mount '"""
_stdout , _ , retval = self . _run_cli_process ( "mount" ) if not retval : for line in _stdout . splitlines ( ) : if b"vfat" in line : match = self . mmp . search ( line . decode ( "utf-8" ) ) if match : yield match . group ( "dev" ) , match . group ( "dir" )
def satisfy_custom_matcher ( self , args , kwargs ) : """Returns a boolean indicating whether or not the mock will accept the provided arguments . : param tuple args : A tuple of position args : param dict kwargs : A dictionary of keyword args : return : Whether or not the mock accepts the provided arguments ...
is_match = super ( Expectation , self ) . satisfy_custom_matcher ( args , kwargs ) if is_match : self . _satisfy ( ) return is_match
def EncodeMessages ( self , message_list , result , destination = None , timestamp = None , api_version = 3 ) : """Accepts a list of messages and encodes for transmission . This function signs and then encrypts the payload . Args : message _ list : A MessageList rdfvalue containing a list of GrrMessages . r...
if api_version not in [ 3 ] : raise RuntimeError ( "Unsupported api version: %s, expected 3." % api_version ) # TODO ( amoser ) : This is actually not great , we have two # communicator classes already , one for the client , one for the # server . This should be different methods , not a single one that # gets pass...
def user_role_list ( user_id = None , tenant_id = None , user_name = None , tenant_name = None , profile = None , project_id = None , project_name = None , ** connection_args ) : '''Return a list of available user _ roles ( keystone user - roles - list ) CLI Examples : . . code - block : : bash salt ' * ' key...
kstone = auth ( profile , ** connection_args ) ret = { } if project_id and not tenant_id : tenant_id = project_id elif project_name and not tenant_name : tenant_name = project_name if user_name : for user in kstone . users . list ( ) : if user . name == user_name : user_id = user . id ...
def get_features_all ( self ) : """Return all features with its names . Regardless of being used for train and prediction . Sorted by the names . Returns all _ features : OrderedDict Features dictionary ."""
features = { } # Get all the names of features . all_vars = vars ( self ) for name in all_vars . keys ( ) : if name in feature_names_list_all : features [ name ] = all_vars [ name ] # Sort by the keys ( i . e . feature names ) . features = OrderedDict ( sorted ( features . items ( ) , key = lambda t : t [ 0...
def fetch_attr_type ( self , table_name ) : """: return : Dictionary of attribute names and attribute types in the table . : rtype : dict : raises simplesqlite . NullDatabaseConnectionError : | raises _ check _ connection | : raises simplesqlite . TableNotFoundError : | raises _ verify _ table _ existen...
self . verify_table_existence ( table_name ) result = self . execute_query ( "SELECT sql FROM sqlite_master WHERE type='table' and name={:s}" . format ( Value ( table_name ) ) ) query = result . fetchone ( ) [ 0 ] match = re . search ( "[(].*[)]" , query ) def get_entry ( items ) : key = " " . join ( items [ : - 1 ...
def get_service_package_quota ( self , ** kwargs ) : # noqa : E501 """Service package quota . # noqa : E501 Get the available firmware update quota for the currently authenticated commercial account . * * Example usage : * * curl - X GET https : / / api . us - east - 1 . mbedcloud . com / v3 / service - packages ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . get_service_package_quota_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . get_service_package_quota_with_http_info ( ** kwargs ) # noqa : E501 return data
def check ( self , value , major ) : """Check that each item in the value list is in the allowed set ."""
for v in value : super ( DiscreteMulti , self ) . check ( v , major )
def powerUp ( self , powerup , interface = None , priority = 0 ) : """Installs a powerup ( e . g . plugin ) on an item or store . Powerups will be returned in an iterator when queried for using the ' powerupsFor ' method . Normally they will be returned in order of installation [ this may change in future ver...
if interface is None : for iface , priority in powerup . _getPowerupInterfaces ( ) : self . powerUp ( powerup , iface , priority ) elif interface is IPowerupIndirector : raise TypeError ( "You cannot install a powerup for IPowerupIndirector: " + powerup ) else : forc = self . store . findOrCreate ( ...
def jstemplate ( parser , token ) : """Templatetag to handle any of the Mustache - based templates . Replaces ` ` [ [ [ ` ` and ` ` ] ] ] ` ` with ` ` { { { ` ` and ` ` } } } ` ` , ` ` [ [ ` ` and ` ` ] ] ` ` with ` ` { { ` ` and ` ` } } ` ` and ` ` [ % ` ` and ` ` % ] ` ` with ` ` { % ` ` and ` ` % } ` ` to ...
nodelist = parser . parse ( ( 'endjstemplate' , ) ) parser . delete_first_token ( ) return JSTemplateNode ( nodelist )
def get_img_hash ( image , hash_size = 8 ) : """Grayscale and shrink the image in one step"""
image = image . resize ( ( hash_size + 1 , hash_size ) , Image . ANTIALIAS , ) pixels = list ( image . getdata ( ) ) # print ( ' get _ img _ hash : pixels = ' , pixels ) # Compare adjacent pixels . difference = [ ] for row in range ( hash_size ) : for col in range ( hash_size ) : pixel_left = image . getpix...
def __doc_cmp ( self , other ) : """Comparison function . Can be used to sort docs alphabetically ."""
if other is None : return - 1 if self . is_new and other . is_new : return 0 if self . __docid < other . __docid : return - 1 elif self . __docid == other . __docid : return 0 else : return 1
def _table_filename ( tbl_filename ) : """Determine if the table path should end in . gz or not and return it . A . gz path is preferred only if it exists and is newer than any regular text file path . Raises : : class : ` delphin . exceptions . ItsdbError ` : when neither the . gz nor text file exist .""...
tbl_filename = str ( tbl_filename ) # convert any Path objects txfn = _normalize_table_path ( tbl_filename ) gzfn = txfn + '.gz' if os . path . exists ( txfn ) : if ( os . path . exists ( gzfn ) and os . stat ( gzfn ) . st_mtime > os . stat ( txfn ) . st_mtime ) : tbl_filename = gzfn else : tbl_...
def plot_date ( datasets , ** kwargs ) : """Plot points with dates . datasets can be Dataset object or list of Dataset ."""
defaults = { 'grid' : True , 'xlabel' : '' , 'ylabel' : '' , 'title' : '' , 'output' : None , 'figsize' : ( 8 , 6 ) , } plot_params = { 'color' : 'b' , 'ls' : '' , 'alpha' : 0.75 , } _update_params ( defaults , plot_params , kwargs ) if isinstance ( datasets , Dataset ) : datasets = [ datasets ] colors = [ 'b' , 'g...
def register ( name , klass ) : """Add a plugin to the plugin catalog ."""
if rapport . config . get_int ( "rapport" , "verbosity" ) >= 1 : print ( "Registered plugin: {0}" . format ( name ) ) _PLUGIN_CATALOG [ name ] = klass
def weight ( self , arr : Collection , is_item : bool = True ) : "Bias for item or user ( based on ` is _ item ` ) for all in ` arr ` . ( Set model to ` cpu ` and no grad . )"
idx = self . get_idx ( arr , is_item ) m = self . model layer = m . i_weight if is_item else m . u_weight return layer ( idx )
def _get_boxscore_uri ( self , url ) : """Find the boxscore URI . Given the boxscore tag for a game , parse the embedded URI for the boxscore . Parameters url : PyQuery object A PyQuery object containing the game ' s boxscore tag which has the boxscore URI embedded within it . Returns string Retur...
uri = re . sub ( r'.*/boxes/' , '' , str ( url ) ) uri = re . sub ( r'\.shtml.*' , '' , uri ) . strip ( ) return uri
def uninstall ( self , bug : Bug ) -> bool : """Uninstalls the Docker image associated with a given bug ."""
r = self . __api . post ( 'bugs/{}/uninstall' . format ( bug . name ) ) raise NotImplementedError
def parse_scg_ink_file ( filename ) : """Parse a SCG INK file . Parameters filename : string The path to a SCG INK file . Returns HandwrittenData The recording as a HandwrittenData object ."""
stroke_count = 0 stroke_point_count = - 1 recording = [ ] current_stroke = [ ] time = 0 got_annotations = False annotations = [ ] formula_in_latex = get_latex ( filename ) with open ( filename ) as f : contents = f . read ( ) . strip ( ) lines = contents . split ( "\n" ) for i , line in enumerate ( lines ) : li...
def list_upcoming ( cls ) : """Returns a collection of upcoming tasks ( tasks that have not yet been completed , regardless of whether they ’ re overdue ) for the authenticated user : return : : rtype : list"""
return fields . ListField ( name = cls . ENDPOINT , init_class = cls ) . decode ( cls . element_from_string ( cls . _get_request ( endpoint = cls . ENDPOINT + '/upcoming' ) . text ) )
def getSignalParameters ( fitParams , n_std = 3 ) : '''return minimum , average , maximum of the signal peak'''
signal = getSignalPeak ( fitParams ) mx = signal [ 1 ] + n_std * signal [ 2 ] mn = signal [ 1 ] - n_std * signal [ 2 ] if mn < fitParams [ 0 ] [ 1 ] : mn = fitParams [ 0 ] [ 1 ] # set to bg return mn , signal [ 1 ] , mx
def remove_file ( fpath , verbose = None , ignore_errors = True , dryrun = False , quiet = QUIET ) : """Removes a file"""
if verbose is None : verbose = not quiet if dryrun : if verbose : print ( '[util_path] Dryrem %r' % fpath ) return else : try : os . remove ( fpath ) if verbose : print ( '[util_path] Removed %r' % fpath ) except OSError : print ( '[util_path.remove_file] ...
def sleuthify_sailfish ( sailfish_dir ) : """if installed , use wasabi to create abundance . h5 output for use with sleuth"""
if not R_package_path ( "wasabi" ) : return None else : rscript = Rscript_cmd ( ) cmd = """{rscript} --no-environ -e 'library("wasabi"); prepare_fish_for_sleuth(c("{sailfish_dir}"))'""" do . run ( cmd . format ( ** locals ( ) ) , "Converting Sailfish to Sleuth format." ) return os . path . join ( sailfi...
def token_load ( self , line_number , tokens ) : self . line_number = line_number assert tokens [ - 1 ] == 0x00 , "line code %s doesn't ends with \\x00: %s" % ( repr ( tokens ) , repr ( tokens [ - 1 ] ) ) """NOTE : The BASIC interpreter changed REM shortcut and ELSE internaly : " ELSE " < - > " : ELSE "...
for src , dst in self . tokens_replace_rules : log . info ( "Relace tokens %s with $%02x" , pformat_byte_hex_list ( src ) , dst ) log . debug ( "Before..: %s" , pformat_byte_hex_list ( tokens ) ) tokens = list_replace ( tokens , src , dst ) log . debug ( "After...: %s" , pformat_byte_hex_list ( tokens )...
def arrange_hybrid_list ( hybrid_list ) : """Create a function to sort a provided mixed list of strings and integers . > > > arrange _ hybrid _ list ( [ 19 , ' red ' , 12 , ' green ' , ' blue ' , 10 , ' white ' , ' green ' , 1 ] ) [1 , 10 , 12 , 19 , ' blue ' , ' green ' , ' green ' , ' red ' , ' white ' ] Ex...
number_elements = sorted ( [ item for item in hybrid_list if isinstance ( item , int ) ] ) string_elements = sorted ( [ item for item in hybrid_list if isinstance ( item , str ) ] ) return ( number_elements + string_elements )
def print_callback ( val ) : """Internal function . This function is called via a call back returning from IPC to Cython to Python . It tries to perform incremental printing to IPython Notebook or Jupyter Notebook and when all else fails , just prints locally ."""
success = False try : # for reasons I cannot fathom , regular printing , even directly # to io . stdout does not work . # I have to intrude rather deep into IPython to make it behave if have_ipython : if InteractiveShell . initialized ( ) : IPython . display . publish_display_data ( { 'text/plai...
def send_community_request_email ( increq ) : """Signal for sending emails after community inclusion request ."""
from flask_mail import Message from invenio_mail . tasks import send_email msg_body = format_request_email_body ( increq ) msg_title = format_request_email_title ( increq ) sender = current_app . config [ 'COMMUNITIES_REQUEST_EMAIL_SENDER' ] msg = Message ( msg_title , sender = sender , recipients = [ increq . communit...
def setData ( self , wordBeforeCursor , wholeWord ) : """Set model information"""
self . _typedText = wordBeforeCursor self . words = self . _makeListOfCompletions ( wordBeforeCursor , wholeWord ) commonStart = self . _commonWordStart ( self . words ) self . canCompleteText = commonStart [ len ( wordBeforeCursor ) : ] self . layoutChanged . emit ( )
def copy ( self ) : """Properly creates a new PauliTerm , with a completely new dictionary of operators"""
new_term = PauliTerm ( "I" , 0 , 1.0 ) # create new object # manually copy all attributes over for key in self . __dict__ . keys ( ) : val = self . __dict__ [ key ] if isinstance ( val , ( dict , list , set ) ) : # mutable types new_term . __dict__ [ key ] = copy . copy ( val ) else : # immutable ty...
def tunnel_bindings ( self ) : """Return a dictionary containing the active local < > remote tunnel _ bindings"""
return dict ( ( _server . remote_address , _server . local_address ) for _server in self . _server_list if self . tunnel_is_up [ _server . local_address ] )
def get_variant_by_id ( cls , variant_id , ** kwargs ) : """Find Variant Return single instance of Variant by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . get _ variant _ by _ id ( variant _ id , async...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _get_variant_by_id_with_http_info ( variant_id , ** kwargs ) else : ( data ) = cls . _get_variant_by_id_with_http_info ( variant_id , ** kwargs ) return data
def on_disconnect ( self ) : "Called when the stream disconnects"
if self . _stream is not None : self . _stream = None if self . _buffer is not None : self . _buffer . close ( ) self . _buffer = None self . encoding = None
def acquisition_time ( self ) : """Acquisition time , in seconds . The acquisition time is calculated using the ' time ' channel by default ( channel name is case independent ) . If the ' time ' channel is not available , the acquisition _ start _ time and acquisition _ end _ time , extracted from the $ BTI...
# Get time channels indices time_channel_idx = [ idx for idx , channel in enumerate ( self . channels ) if channel . lower ( ) == 'time' ] if len ( time_channel_idx ) > 1 : raise KeyError ( "more than one time channel in data" ) # Check if the time channel is available elif len ( time_channel_idx ) == 1 : # Use the...
def render_to_mail ( template , context , ** kwargs ) : """Renders a mail and returns the resulting ` ` EmailMultiAlternatives ` ` instance * ` ` template ` ` : The base name of the text and HTML ( optional ) version of the mail . * ` ` context ` ` : The context used to render the mail . This context instan...
lines = iter ( line . rstrip ( ) for line in render_to_string ( "%s.txt" % template , context ) . splitlines ( ) ) subject = "" try : while True : line = next ( lines ) if line : subject = line break except StopIteration : # if lines is empty pass body = "\n" . join ( lin...
def extract_path_arguments ( path ) : """Extracts a swagger path arguments from the given flask path . This / path / < parameter > extracts [ { name : ' parameter ' } ] And this / < string ( length = 2 ) : lang _ code > / < string : id > / < float : probability > extracts : [ { name : ' lang _ code ' , data...
# Remove all paranteses path = re . sub ( '\([^\)]*\)' , '' , path ) args = re . findall ( '<([^>]+)>' , path ) def split_arg ( arg ) : spl = arg . split ( ':' ) if len ( spl ) == 1 : return { 'name' : spl [ 0 ] , 'dataType' : 'string' , 'paramType' : 'path' } else : return { 'name' : spl [ ...
def _maintain ( self , node ) : """maintains the invariant for the given node : promize : the lazy values are None / 0 for this node"""
# requires node and its direct descends to be clean l = 2 * node r = 2 * node + 1 assert self . lazyset [ node ] is None assert self . lazyadd [ node ] == 0 assert self . lazyset [ l ] is None assert self . lazyadd [ l ] == 0 assert self . lazyset [ r ] is None assert self . lazyadd [ r ] == 0 self . maxval [ node ] = ...
def _set_rp_cand_interface ( self , v , load = False ) : """Setter method for rp _ cand _ interface , mapped from YANG variable / rbridge _ id / router / hide _ pim _ holder / pim / rp _ candidate / rp _ cand _ interface ( list ) If this variable is read - only ( config : false ) in the source YANG file , then ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "rp_cand_intf_type rp_cand_intf_id" , rp_cand_interface . rp_cand_interface , yang_name = "rp-cand-interface" , rest_name = "interface" , parent = self , is_container = 'list' , user_ordered = False , path_help...
def intervalTrees ( reffh , scoreType = int , verbose = False ) : """Build a dictionary of interval trees indexed by chrom from a BED stream or file : param reffh : This can be either a string , or a stream - like object . In the former case , it is treated as a filename . The format of the file / stream mu...
if type ( reffh ) . __name__ == "str" : fh = open ( reffh ) else : fh = reffh # load all the regions and split them into lists for each chrom elements = { } if verbose and fh != sys . stdin : totalLines = linesInFile ( fh . name ) pind = ProgressIndicator ( totalToDo = totalLines , messagePrefix = "comp...
def _get_rest_doc ( self , request , start_response ) : """Sends back HTTP response with API directory . This calls start _ response and returns the response body . It will return the discovery doc for the requested api / version . Args : request : An ApiRequest , the transformed request sent to the Discove...
api = request . body_json [ 'api' ] version = request . body_json [ 'version' ] generator = discovery_generator . DiscoveryGenerator ( request = request ) services = [ s for s in self . _backend . api_services if s . api_info . name == api and s . api_info . api_version == version ] doc = generator . pretty_print_confi...
def generate ( self , verified , keygen ) : """: param verified : телефон или email ( verified _ entity ) : param keygen : функция генерации ключа : return :"""
return Verification ( verified_entity = verified , key = keygen ( ) , verified = False )
def __recognize_scalar ( self , node : yaml . Node , expected_type : Type ) -> RecResult : """Recognize a node that we expect to be a scalar . Args : node : The node to recognize . expected _ type : The type it is expected to be . Returns : A list of recognized types and an error message"""
logger . debug ( 'Recognizing as a scalar' ) if ( isinstance ( node , yaml . ScalarNode ) and node . tag == scalar_type_to_tag [ expected_type ] ) : return [ expected_type ] , '' message = 'Failed to recognize a {}\n{}\n' . format ( type_to_desc ( expected_type ) , node . start_mark ) return [ ] , message
def divide ( self , other , out = None ) : """Return ` ` out = self / other ` ` . If ` ` out ` ` is provided , the result is written to it . See Also LinearSpace . divide"""
return self . space . divide ( self , other , out = out )
def show_tree ( self , has_tree = False , force_update = False ) : """show tree list : param has _ tree : tree exist or not , False by default , if True , tree should be cleared first : param force _ update : force update flag , if True , update neglect other flags . : return : has _ tree , True successful , ...
if has_tree : self . has_tree = self . clear_tree ( ) if force_update : self . data_refresh_flag = True try : if self . data_refresh_flag : fn = self . open_filename if self . get_filetype ( fn ) . lower ( ) == 'json' : data_dict = self . read_json ( fn ) elif self . get_...
def main ( argString = None ) : """The main function of the module . : param argString : the options . : type argString : list These are the steps : 1 . Prints the options . 2 . Runs Plink with the ` ` geno ` ` option ( : py : func : ` runPlink ` ) . 3 . Compares the two ` ` bim ` ` files ( before and a...
# Getting and checking the options args = parseArgs ( argString ) checkArgs ( args ) logger . info ( "Options used:" ) for key , value in vars ( args ) . iteritems ( ) : logger . info ( " --{} {}" . format ( key . replace ( "_" , "-" ) , value ) ) # Run plink logger . info ( "Running Plink" ) runPlink ( args ) # C...
def is_powered_on ( self ) : """Get power status of device . The set - top box can ' t explicitly powered on or powered off the device . The power can only be toggled . To find out the power status of the device a little trick is used . When the set - top box is powered a web server is running on port 62137...
host = '{0}:62137' . format ( self . ip ) try : HTTPConnection ( host , timeout = 2 ) . request ( 'GET' , '/DeviceDescription.xml' ) except ( ConnectionRefusedError , socket . timeout ) : log . debug ( 'Set-top box at %s:%s is powered off.' , self . ip , self . port ) return False log . debug ( 'Set-top box...
def read_body ( response , max_bytes = None ) : """Return a ` Deferred ` yielding at most * max _ bytes * bytes from the body of a Twisted Web * response * , or the whole body if * max _ bytes * is ` None ` ."""
finished = Deferred ( ) response . deliverBody ( TruncatingReadBodyProtocol ( response . code , response . phrase , finished , max_bytes ) ) return finished
def autodiscover ( site = None ) : """Auto - discover INSTALLED _ APPS nexus . py modules and fail silently when not present . This forces an import on them to register any api bits they may want . Specifying ` ` site ` ` will register all auto discovered modules with the new site ."""
# Bail out if autodiscover didn ' t finish loading from a previous call so # that we avoid running autodiscover again when the URLconf is loaded by # the exception handler to resolve the handler500 view . This prevents an # admin . py module with errors from re - registering models and raising a # spurious AlreadyRegis...
def read_virtual_memory ( self , cpu_id , address , size ) : """Reads guest virtual memory , no side effects ( MMIO + + ) . This feature is not implemented in the 4.0.0 release but may show up in a dot release . in cpu _ id of type int The identifier of the Virtual CPU . in address of type int The guest...
if not isinstance ( cpu_id , baseinteger ) : raise TypeError ( "cpu_id can only be an instance of type baseinteger" ) if not isinstance ( address , baseinteger ) : raise TypeError ( "address can only be an instance of type baseinteger" ) if not isinstance ( size , baseinteger ) : raise TypeError ( "size can...
def generate ( self , descriptors ) : """Generate new architecture . Args : descriptors : All the searched neural architectures . Returns : graph : An instance of Graph . A morphed neural network with weights . father _ id : The father node ID in the search tree ."""
model_ids = self . search_tree . adj_list . keys ( ) target_graph = None father_id = None descriptors = deepcopy ( descriptors ) elem_class = Elem if self . optimizemode is OptimizeMode . Maximize : elem_class = ReverseElem # Initialize the priority queue . pq = PriorityQueue ( ) temp_list = [ ] for model_id in mod...
def str_lexer ( mode ) : """generate token strings ' cache"""
cast_to_const = ConstStrPool . cast_to_const def f_raw ( inp_str , pos ) : return cast_to_const ( mode ) if inp_str . startswith ( mode , pos ) else None def f_collection ( inp_str , pos ) : for each in mode : if inp_str . startswith ( each , pos ) : return cast_to_const ( each ) return ...
def build_attachment2 ( ) : """Build attachment mock ."""
attachment = Attachment ( ) attachment . content = "BwdW" attachment . type = "image/png" attachment . filename = "banner.png" attachment . disposition = "inline" attachment . content_id = "Banner" return attachment
def is_short ( self , word ) : """Determine if the word is short . Short words are ones that end in a short syllable and have an empty R1 region ."""
short = False length = len ( word ) if self . r1 >= length : if length > 2 : ending = word [ length - 3 : ] if re . match ( "[^aeiouy][aeiouy][^aeiouwxY]" , ending ) : short = True else : if re . match ( "[aeiouy][^aeiouy]" , word ) : short = True return short
def grant_permission ( username , resource = None , resource_type = 'keyspace' , permission = None , contact_points = None , port = None , cql_user = None , cql_pass = None ) : '''Grant permissions to a user . : param username : The name of the user to grant permissions to . : type username : str : param reso...
permission_cql = "grant {0}" . format ( permission ) if permission else "grant all permissions" resource_cql = "on {0} {1}" . format ( resource_type , resource ) if resource else "on all keyspaces" query = "{0} {1} to {2}" . format ( permission_cql , resource_cql , username ) log . debug ( "Attempting to grant permissi...
def authenticate ( self , bound_route , actual_params ) -> bool : """Runs the pre - defined authenticaton service : param bound _ route str route matched : param actual _ params dict actual url parameters : rtype : bool"""
if self . __auth_service is not None : auth_route = "{0}_{1}{2}" . format ( self . __method , self . __route , bound_route ) auth_data = self . __auth_service . authenticate ( self . __request , auth_route , actual_params ) if auth_data is True : self . app . auth_data = self . __auth_service . auth...
def cache_property ( key , empty , type ) : """Return a new property object for a cache header . Useful if you want to add support for a cache extension in a subclass ."""
return property ( lambda x : x . _get_cache_value ( key , empty , type ) , lambda x , v : x . _set_cache_value ( key , v , type ) , lambda x : x . _del_cache_value ( key ) , 'accessor for %r' % key )
def add_log_callback ( callback ) : """Adds a log callback ."""
global _log_callbacks if not callable ( callback ) : raise ValueError ( "Callback must be callable" ) _log_callbacks . add ( callback ) return callback
def update_topology ( ) : """updates all the topology sends logs to the " nodeshot . networking " logger"""
for topology in Topology . objects . all ( ) : try : topology . update ( ) except Exception as e : msg = 'Failed to update {}' . format ( topology . __repr__ ( ) ) logger . exception ( msg ) print ( '{0}: {1}\n' 'see networking.log for more information\n' . format ( msg , e . __c...
def define_empty_source_parallel_buckets ( max_seq_len_target : int , bucket_width : int = 10 ) -> List [ Tuple [ int , int ] ] : """Returns ( source , target ) buckets up to ( None , max _ seq _ len _ target ) . The source is empty since it is supposed to not contain data that can be bucketized . The target is...
target_step_size = max ( 1 , bucket_width ) target_buckets = define_buckets ( max_seq_len_target , step = target_step_size ) # source buckets are always 0 since there is no text source_buckets = [ 0 for b in target_buckets ] target_buckets = [ max ( 2 , b ) for b in target_buckets ] parallel_buckets = list ( zip ( sour...
def calculate_gradient ( self , batch_info , device , model , rollout ) : """Calculate loss of the supplied rollout"""
evaluator = model . evaluate ( rollout ) batch_size = rollout . frames ( ) dones_tensor = evaluator . get ( 'rollout:dones' ) rewards_tensor = evaluator . get ( 'rollout:rewards' ) assert dones_tensor . dtype == torch . float32 with torch . no_grad ( ) : target_evaluator = self . target_model . evaluate ( rollout )...
def validate_member_id_params_for_group_type ( group_type , params , member_group_ids , member_entity_ids ) : """Determine whether member ID parameters can be sent with a group create / update request . These parameters are only allowed for the internal group type . If they ' re set for an external group type , V...
if group_type == 'external' : if member_entity_ids is not None : logger . warning ( "InvalidRequest: member entities can't be set manually for external groupsl ignoring member_entity_ids argument." ) else : params [ 'member_entity_ids' ] = member_entity_ids if group_type == 'external' : if member_gr...
def default_logging_dict ( * loggers : str , ** kwargs : Any ) -> DictStrAny : r"""Prepare logging dict suitable with ` ` logging . config . dictConfig ` ` . * * Usage * * : : from logging . config import dictConfig dictConfig ( default _ logging _ dict ( ' yourlogger ' ) ) : param \ * loggers : Enable logg...
kwargs . setdefault ( 'level' , 'INFO' ) return { 'version' : 1 , 'disable_existing_loggers' : True , 'filters' : { 'ignore_errors' : { '()' : IgnoreErrorsFilter , } , } , 'formatters' : { 'default' : { 'format' : '%(asctime)s [%(levelname)s:%(name)s] %(message)s' , } , 'naked' : { 'format' : u'%(message)s' , } , } , '...
def _alter ( self , tree ) : """Run an ALTER statement"""
if tree . throughput : [ read , write ] = tree . throughput index = None if tree . index : index = tree . index self . _update_throughput ( tree . table , read , write , index ) elif tree . drop_index : updates = [ IndexUpdate . delete ( tree . drop_index [ 0 ] ) ] try : self . c...
def perform_bandfill_corr ( self , eigenvalues , kpoint_weights , potalign , vbm , cbm ) : """This calculates the band filling correction based on excess of electrons / holes in CB / VB . . . Note that the total free holes and electrons may also be used for a " shallow donor / acceptor " correction with specifi...
bf_corr = 0. self . metadata [ "potalign" ] = potalign self . metadata [ "num_hole_vbm" ] = 0. self . metadata [ "num_elec_cbm" ] = 0. if len ( eigenvalues . keys ( ) ) == 1 : # needed because occupation of non - spin calcs is still 1 . . . should be 2 spinfctr = 2. elif len ( eigenvalues . keys ( ) ) == 2 : sp...
def set_extent_size ( self , length , units ) : """Sets the volume group extent size in the given units : : from lvm2py import * lvm = LVM ( ) vg = lvm . get _ vg ( " myvg " , " w " ) vg . set _ extent _ size ( 2 , " MiB " ) * Args : * * length ( int ) : The desired length size . * units ( str ) : The...
size = length * size_units [ units ] self . open ( ) ext = lvm_vg_set_extent_size ( self . handle , c_ulong ( size ) ) self . _commit ( ) self . close ( ) if ext != 0 : raise CommitError ( "Failed to set extent size." )
def plot_raster ( self , cell_dimension = 'N' , time_dimension = 0 , resolution = 1.0 , units = None , min_t = None , max_t = None , weight_function = None , normalize_time = True , normalize_n = True , start_units_with_0 = True , ** kwargs ) : """Plots a raster plot with ` cell _ dimension ` as y and ` time _ dime...
if bool ( self ) : import matplotlib . pylab as plt plt . plot ( self [ time_dimension ] , self [ cell_dimension ] , '.' , ** kwargs ) plt . xlim ( min_t , max_t )
def qos ( self , prefetch_count = 0 , prefetch_size = 0 , global_ = False ) : """Specify quality of service . : param int prefetch _ count : Prefetch window in messages : param int / long prefetch _ size : Prefetch window in octets : param bool global _ : Apply to entire connection : raises AMQPInvalidArgum...
if not compatibility . is_integer ( prefetch_count ) : raise AMQPInvalidArgument ( 'prefetch_count should be an integer' ) elif not compatibility . is_integer ( prefetch_size ) : raise AMQPInvalidArgument ( 'prefetch_size should be an integer' ) elif not isinstance ( global_ , bool ) : raise AMQPInvalidArgu...
def can_import ( self , file_uris , current_doc = None ) : """Check that the specified file looks like a directory containing many pdf files"""
if len ( file_uris ) <= 0 : return False try : for file_uri in file_uris : file_uri = self . fs . safe ( file_uri ) for child in self . fs . recurse ( file_uri ) : if self . check_file_type ( child ) : return True except GLib . GError : pass return False
def progression_sinusoidal ( week , start_weight , final_weight , start_week , end_week , periods = 2 , scale = 0.025 , offset = 0 ) : """A sinusoidal progression function going through the points ( ' start _ week ' , ' start _ weight ' ) and ( ' end _ week ' , ' final _ weight ' ) , evaluated in ' week ' . Thi...
# Get the linear model linear = progression_linear ( week , start_weight , final_weight , start_week , end_week ) # Calculate the time period and the argument to the sine function time_period = end_week - start_week sine_argument = ( ( week - offset - start_week ) * ( math . pi * 2 ) / ( time_period / periods ) ) linea...
def open_streaming_interface ( self ) : """Called when someone opens a streaming interface to the device . This method will automatically notify sensor _ graph that there is a streaming interface opened . Returns : list : A list of IOTileReport objects that should be sent out the streaming interface ."""
super ( ReferenceDevice , self ) . open_streaming_interface ( ) self . rpc ( 8 , rpcs . SG_GRAPH_INPUT , 8 , streams . COMM_TILE_OPEN ) return [ ]
def predict_input ( itos_filename , trained_classifier_filename , num_classes = 2 ) : """Loads a model and produces predictions on arbitrary input . : param itos _ filename : the path to the id - to - string mapping file : param trained _ classifier _ filename : the filename of the trained classifier ; typica...
# Check the itos file exists if not os . path . exists ( itos_filename ) : print ( "Could not find " + itos_filename ) exit ( - 1 ) # Check the classifier file exists if not os . path . exists ( trained_classifier_filename ) : print ( "Could not find " + trained_classifier_filename ) exit ( - 1 ) stoi ,...
def keys_to_snake_case ( camel_case_dict ) : """Make a copy of a dictionary with all keys converted to snake case . This is just calls to _ snake _ case on each of the keys in the dictionary and returns a new dictionary . : param camel _ case _ dict : Dictionary with the keys to convert . : type camel _ case ...
return dict ( ( to_snake_case ( key ) , value ) for ( key , value ) in camel_case_dict . items ( ) )
def guess_message_type ( message ) : """Guess the message type based on the class of message : param message : Message to guess the type for : type message : APPMessage : return : The corresponding message type ( MsgType ) or None if not found : rtype : None | int"""
if isinstance ( message , APPConfigMessage ) : return MsgType . CONFIG elif isinstance ( message , APPJoinMessage ) : return MsgType . JOIN elif isinstance ( message , APPDataMessage ) : # All inheriting from this first ! ! return MsgType . DATA elif isinstance ( message , APPUpdateMessage ) : return Ms...
def get_function_doc ( function , config = default_config ) : """Return doc for a function ."""
if config . exclude_function : for ex in config . exclude_function : if ex . match ( function . __name__ ) : return None return _doc_object ( function , 'function' , config = config )
def get_build_log_zip ( self , project , build_id , log_id , start_line = None , end_line = None , ** kwargs ) : """GetBuildLogZip . Gets an individual log file for a build . : param str project : Project ID or project name : param int build _ id : The ID of the build . : param int log _ id : The ID of the ...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if build_id is not None : route_values [ 'buildId' ] = self . _serialize . url ( 'build_id' , build_id , 'int' ) if log_id is not None : route_values [ 'logId' ] = self . _seriali...
def _publish ( tgt , fun , arg = None , tgt_type = 'glob' , returner = '' , timeout = None , form = 'clean' , roster = None ) : '''Publish a command " from the minion out to other minions " . In reality , the minion does not execute this function , it is executed by the master . Thus , no access control is enab...
if fun . startswith ( 'publish.' ) : log . info ( 'Cannot publish publish calls. Returning {}' ) return { } # TODO : implement returners ? Do they make sense for salt - ssh calls ? if returner : log . warning ( 'Returners currently not supported in salt-ssh publish' ) # Make sure args have been processed if...
def pattern_error ( self , original , loc , value_var , check_var ) : """Construct a pattern - matching error message ."""
base_line = clean ( self . reformat ( getline ( loc , original ) ) ) line_wrap = self . wrap_str_of ( base_line ) repr_wrap = self . wrap_str_of ( ascii ( base_line ) ) return ( "if not " + check_var + ":\n" + openindent + match_err_var + ' = _coconut_MatchError("pattern-matching failed for " ' + repr_wrap + ' " in " +...
def alignICP ( source , target , iters = 100 , rigid = False ) : """Return a copy of source actor which is aligned to target actor through the ` Iterative Closest Point ` algorithm . The core of the algorithm is to match each vertex in one surface with the closest surface point on the other , then apply the t...
if isinstance ( source , Actor ) : source = source . polydata ( ) if isinstance ( target , Actor ) : target = target . polydata ( ) icp = vtk . vtkIterativeClosestPointTransform ( ) icp . SetSource ( source ) icp . SetTarget ( target ) icp . SetMaximumNumberOfIterations ( iters ) if rigid : icp . GetLandmar...
def user_admin_urlname ( action ) : """Return the admin URLs for the user app used ."""
user = get_user_model ( ) return 'admin:%s_%s_%s' % ( user . _meta . app_label , user . _meta . model_name , action )
def populate_class_members ( self , element_cls , prop_name ) : """Add the appropriate methods to * element _ cls * ."""
super ( OneOrMore , self ) . populate_class_members ( element_cls , prop_name ) self . _add_list_getter ( ) self . _add_creator ( ) self . _add_inserter ( ) self . _add_adder ( ) self . _add_public_adder ( ) delattr ( element_cls , prop_name )
def _has_no_pendings ( self , statuses ) : """Returns True if a statuses dict has no PENDING statuses ."""
return all ( s != ClientBatchStatus . PENDING for s in statuses . values ( ) )
def symmetric_difference_update ( self , other ) : """Throws out all intervals except those only in self or other , not both ."""
other = set ( other ) ivs = list ( self ) for iv in ivs : if iv in other : self . remove ( iv ) other . remove ( iv ) self . update ( other )
def replace_variables ( self , source : str , variables : dict ) -> str : """Replace { { variable - name } } with stored value ."""
try : replaced = re . sub ( "{{(.*?)}}" , lambda m : variables . get ( m . group ( 1 ) , "" ) , source ) except TypeError : replaced = source return replaced
def add_worksheet ( self ) : """Add a worksheet to the workbook ."""
wsh = self . workbook . add_worksheet ( ) if self . vars . fld2col_widths is not None : self . set_xlsx_colwidths ( wsh , self . vars . fld2col_widths , self . wbfmtobj . get_prt_flds ( ) ) return wsh
def pseudo_inv ( self , maxsing = None , eigthresh = 1.0e-5 ) : """The pseudo inverse of self . Formed using truncated singular value decomposition and Matrix . pseudo _ inv _ components Parameters maxsing : int the number of singular components to use . If None , maxsing is calculated using Matrix . get ...
if maxsing is None : maxsing = self . get_maxsing ( eigthresh = eigthresh ) full_s = self . full_s . T for i in range ( self . s . shape [ 0 ] ) : if i <= maxsing : full_s . x [ i , i ] = 1.0 / full_s . x [ i , i ] else : full_s . x [ i , i ] = 0.0 return self . v * full_s * self . u . T
def _update_version ( self ) : """Ask for and store a new dev version string ."""
# current = self . vcs . version current = self . data [ 'new_version' ] # Clean it up to a non - development version . current = utils . cleanup_version ( current ) # Try to make sure that the suggestion for next version after # 1.1.19 is not 1.1.110 , but 1.1.20. current_split = current . split ( '.' ) major = '.' . ...
def pre_attention ( self , segment_number , query_antecedent , memory_antecedent , bias ) : """Called prior to self - attention , to incorporate memory items . Args : segment _ number : an integer Tensor with shape [ batch ] query _ antecedent : a Tensor with shape [ batch , length _ q , channels ] memory _...
with tf . variable_scope ( self . name + "/pre_attention" , reuse = tf . AUTO_REUSE ) : assert memory_antecedent is None , "We only support language modeling" with tf . control_dependencies ( [ tf . assert_greater_equal ( self . batch_size , tf . size ( segment_number ) ) ] ) : difference = self . batch...
def is_socket ( self ) : """Whether this path is a socket ."""
try : return S_ISSOCK ( self . stat ( ) . st_mode ) except OSError as e : if e . errno not in ( ENOENT , ENOTDIR ) : raise # Path doesn ' t exist or is a broken symlink # ( see https : / / bitbucket . org / pitrou / pathlib / issue / 12 / ) return False
def targets ( tgt , tgt_type = 'range' , ** kwargs ) : '''Return the targets from a range query'''
r = seco . range . Range ( __opts__ [ 'range_server' ] ) log . debug ( 'Range connection to \'%s\' established' , __opts__ [ 'range_server' ] ) hosts = [ ] try : log . debug ( 'Querying range for \'%s\'' , tgt ) hosts = r . expand ( tgt ) except seco . range . RangeException as err : log . error ( 'Range se...
def add_ip ( self , family = 'IPv4' ) : """Allocate a new ( random ) IP - address to the Server ."""
IP = self . cloud_manager . attach_ip ( self . uuid , family ) self . ip_addresses . append ( IP ) return IP
def func ( data_row , wait ) : '''A sample function It takes ' wait ' seconds to calculate the sum of each row'''
time . sleep ( wait ) data_row [ 'sum' ] = data_row [ 'col_1' ] + data_row [ 'col_2' ] return data_row
def read ( url , ** args ) : """Loads an object from a data URI ."""
info , data = url . path . split ( ',' ) info = data_re . search ( info ) . groupdict ( ) mediatype = info . setdefault ( 'mediatype' , 'text/plain;charset=US-ASCII' ) if ';' in mediatype : mimetype , params = mediatype . split ( ';' , 1 ) params = [ p . split ( '=' ) for p in params . split ( ';' ) ] param...
def writeQuotes ( self , quotes ) : '''write quotes'''
tName = self . tableName ( HBaseDAM . QUOTE ) if tName not in self . __hbase . getTableNames ( ) : self . __hbase . createTable ( tName , [ ColumnDescriptor ( name = HBaseDAM . QUOTE , maxVersions = 5 ) ] ) for quote in quotes : self . __hbase . updateRow ( self . tableName ( HBaseDAM . QUOTE ) , quote . time ,...
def _call ( self , x , out = None , ** kwargs ) : """Raw evaluation method ."""
if out is None : return self . _call_out_of_place ( x , ** kwargs ) else : self . _call_in_place ( x , out = out , ** kwargs )