signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def bygroups ( * args ) : """Callback that yields multiple actions for each group in the match ."""
def callback ( lexer , match , ctx = None ) : for i , action in enumerate ( args ) : if action is None : continue elif type ( action ) is _TokenType : data = match . group ( i + 1 ) if data : yield match . start ( i + 1 ) , action , data el...
def _clean_kwargs ( keep_name = False , ** kwargs ) : '''Sanatize the the arguments for use with shade'''
if 'name' in kwargs and not keep_name : kwargs [ 'name_or_id' ] = kwargs . pop ( 'name' ) return __utils__ [ 'args.clean_kwargs' ] ( ** kwargs )
def dockerize_package ( ctx , os , host ) : """Creates a Docker build file pre - configured with Plume ."""
from canari . commands . dockerize_package import dockerize_package dockerize_package ( ctx . project , os , host )
def update_script_from_item ( self , item ) : """updates the script based on the information provided in item Args : script : script to be updated item : B26QTreeItem that contains the new settings of the script"""
script , path_to_script , script_item = item . get_script ( ) # build dictionary # get full information from script dictator = list ( script_item . to_dict ( ) . values ( ) ) [ 0 ] # there is only one item in the dictionary for instrument in list ( script . instruments . keys ( ) ) : # update instrument script . in...
def get_events ( self ) : """Get event list from satellite : return : A copy of the events list : rtype : list"""
res = copy . copy ( self . events ) del self . events [ : ] return res
def load ( self , schema_file : Union [ str , TextIO ] , schema_location : Optional [ str ] = None ) -> ShExJ . Schema : """Load a ShEx Schema from schema _ location : param schema _ file : name or file - like object to deserialize : param schema _ location : URL or file name of schema . Used to create the base...
if isinstance ( schema_file , str ) : schema_file = self . location_rewrite ( schema_file ) self . schema_text = load_shex_file ( schema_file ) else : self . schema_text = schema_file . read ( ) if self . base_location : self . root_location = self . base_location elif schema_location : self . root_...
def as_issue ( self ) : """: calls : ` GET / repos / : owner / : repo / issues / : number < http : / / developer . github . com / v3 / issues > ` _ : rtype : : class : ` github . Issue . Issue `"""
headers , data = self . _requester . requestJsonAndCheck ( "GET" , self . issue_url ) return github . Issue . Issue ( self . _requester , headers , data , completed = True )
def description_record ( self ) : """Return dict describing : class : ` condoor . Connection ` object . Example : : { ' connections ' : [ { ' chain ' : [ { ' driver _ name ' : ' eXR ' , ' family ' : ' ASR9K ' , ' hostname ' : ' vkg3 ' , ' is _ console ' : True , ' is _ target ' : True , ' mode ' : ' g...
if self . connection_chains : return { 'connections' : [ { 'chain' : [ device . device_info for device in chain . devices ] } for chain in self . connection_chains ] , 'last_chain' : self . _last_chain_index , } else : raise ConnectionError ( "Device not connected" )
def sanity_check_subsections ( self ) : """This function goes through the ConfigParset and checks that any options given in the [ SECTION _ NAME ] section are not also given in any [ SECTION _ NAME - SUBSECTION ] sections ."""
# Loop over the sections in the ini file for section in self . sections ( ) : # [ pegasus _ profile ] specially is allowed to be overriden by # sub - sections if section == 'pegasus_profile' : continue # Loop over the sections again for section2 in self . sections ( ) : # Check if any are subsection...
def plot_total ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = '$|B|$, nT' , ax = None , show = True , fname = None , ** kwargs ) : """Plot the total magnetic intensity . Usage x . plot _ total ( [ tick _ interval , xlabel , ylabel , ax , colorbar , cb _ orientation , cb _ label , show , f...
if ax is None : fig , axes = self . total . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . total . plot ( colorbar ...
def import_from_xls ( filename_or_fobj , sheet_name = None , sheet_index = 0 , start_row = None , start_column = None , end_row = None , end_column = None , * args , ** kwargs ) : """Return a rows . Table created from imported XLS file ."""
source = Source . from_file ( filename_or_fobj , mode = "rb" , plugin_name = "xls" ) source . fobj . close ( ) book = xlrd . open_workbook ( source . uri , formatting_info = True , logfile = open ( os . devnull , mode = "w" ) ) if sheet_name is not None : sheet = book . sheet_by_name ( sheet_name ) else : sheet...
def generate ( cls , country_code , bank_code , account_code ) : """Generate an IBAN from it ' s components . If the bank - code and / or account - number have less digits than required by their country specific representation , the respective component is padded with zeros . Examples : To generate an IBAN ...
spec = _get_iban_spec ( country_code ) bank_code_length = code_length ( spec , 'bank_code' ) branch_code_length = code_length ( spec , 'branch_code' ) bank_and_branch_code_length = bank_code_length + branch_code_length account_code_length = code_length ( spec , 'account_code' ) if len ( bank_code ) > bank_and_branch_co...
def _stmt_inside_loop ( self , stmt_idx ) : """Test whether a statement is inside the loop body or not . : param stmt _ idx : : return :"""
# TODO : This is slow . Fix the performance issue for node in self . loop . body_nodes : if node . addr . stmt_idx <= stmt_idx < node . addr . stmt_idx + node . size : return True return False
def close ( self , child ) : """Close a child position - alias for rebalance ( 0 , child ) . This will also flatten ( close out all ) the child ' s children . Args : * child ( str ) : Child , specified by name ."""
c = self . children [ child ] # flatten if children not None if c . children is not None and len ( c . children ) != 0 : c . flatten ( ) if c . value != 0. and not np . isnan ( c . value ) : c . allocate ( - c . value )
def sample ( self , label ) : """generate random cropping boxes according to parameters if satifactory crops generated , apply to ground - truth as well Parameters : label : numpy . array ( n x 5 matrix ) ground - truths Returns : list of ( crop _ box , label ) tuples , if failed , return empty list [ ]...
samples = [ ] count = 0 for trial in range ( self . max_trials ) : if count >= self . max_sample : return samples scale = np . random . uniform ( self . min_scale , self . max_scale ) min_ratio = max ( self . min_aspect_ratio , scale * scale ) max_ratio = min ( self . max_aspect_ratio , 1. / sca...
def install_builtin ( translator , do_unicode ) : """Install _ ( ) and _ n ( ) gettext methods into default namespace ."""
try : import __builtin__ as builtins except ImportError : # Python 3 import builtins # Python 3 has no ugettext has_unicode = hasattr ( translator , 'ugettext' ) if do_unicode and has_unicode : builtins . __dict__ [ '_' ] = translator . ugettext # also install ngettext builtins . __dict__ [ '_n' ] =...
def perform_batch_reply ( self , * , callback : Callable [ ... , str ] = None , target_handles : Dict [ str , str ] = None , lookback_limit : int = 20 , per_service_lookback_limit : Dict [ str , int ] = None , ) -> IterationRecord : """Performs batch reply on target accounts . Looks up the recent messages of the ...
if callback is None : raise BotSkeletonException ( "Callback must be provided." "" ) if target_handles is None : raise BotSkeletonException ( "Targets must be provided." "" ) if lookback_limit > self . lookback_limit : raise BotSkeletonException ( f"Lookback_limit cannot exceed {self.lookback_limit}, " + f"...
def postman ( filename , pretty , urlvars , swagger ) : '''Dump the API as a Postman collection'''
data = api . as_postman ( urlvars = urlvars , swagger = swagger ) json_to_file ( data , filename , pretty )
def get_collection ( self , uri = None , filter = '' , path = '' ) : """Retrieves a collection of resources . Use this function when the ' start ' and ' count ' parameters are not allowed in the GET call . Otherwise , use get _ all instead . Optional filtering criteria may be specified . Args : filter ( l...
if not uri : uri = self . _base_uri if filter : filter = self . make_query_filter ( filter ) filter = "?" + filter [ 1 : ] uri = "{uri}{path}{filter}" . format ( uri = uri , path = path , filter = filter ) logger . debug ( 'Get resource collection (uri = %s)' % uri ) response = self . _connection . get ( ur...
def open ( self , options ) : """Open and include the refrenced schema . @ param options : An options dictionary . @ type options : L { options . Options } @ return : The referenced schema . @ rtype : L { Schema }"""
if self . opened : return self . opened = True log . debug ( '%s, including location="%s"' , self . id , self . location ) result = self . download ( options ) log . debug ( 'included:\n%s' , result ) return result
def write_metadata_to_filestream ( filedir , filestream , max_bytes = MAX_FILE_DEFAULT ) : """Make metadata file for all files in a directory ( helper function ) : param filedir : This field is the filepath of the directory whose csv has to be made . : param filestream : This field is a stream for writing to ...
csv_out = csv . writer ( filestream ) subdirs = [ os . path . join ( filedir , i ) for i in os . listdir ( filedir ) if os . path . isdir ( os . path . join ( filedir , i ) ) ] if subdirs : logging . info ( 'Making metadata for subdirs of {}' . format ( filedir ) ) if not all ( [ re . match ( '^[0-9]{8}$' , os ...
def tarbell_install ( command , args ) : """Install a project ."""
with ensure_settings ( command , args ) as settings : project_url = args . get ( 0 ) puts ( "\n- Getting project information for {0}" . format ( project_url ) ) project_name = project_url . split ( "/" ) . pop ( ) error = None # Create a tempdir and clone tempdir = tempfile . mkdtemp ( ) try...
def read_json_document ( title ) : """Reads in a json document and returns a native python datastructure ."""
if not title . endswith ( '.json' ) : juicer . utils . Log . log_warn ( "File name (%s) does not end with '.json', appending it automatically." % title ) title += '.json' if not os . path . exists ( title ) : raise IOError ( "Could not find file: '%s'" % title ) f = open ( title , 'r' ) doc = f . read ( ) f...
def create_default_units_and_dimensions ( ) : """Adds the units and the dimensions reading a json file . It adds only dimensions and units that are not inside the db It is possible adding new dimensions and units to the DB just modifiyin the json file"""
default_units_file_location = os . path . realpath ( os . path . join ( os . path . dirname ( os . path . realpath ( __file__ ) ) , '../' , 'static' , 'default_units_and_dimensions.json' ) ) d = None with open ( default_units_file_location ) as json_data : d = json . load ( json_data ) json_data . close ( ) for...
def movies_opening ( self , ** kwargs ) : """Gets the current opening movies from the API . Args : limit ( optional ) : limits the number of movies returned , default = 10 country ( optional ) : localized data for selected country , default = " us " Returns : A dict respresentation of the JSON returned fr...
path = self . _get_path ( 'movies_opening' ) response = self . _GET ( path , kwargs ) self . _set_attrs_to_values ( response ) return response
def start_sctp_client ( self , ip = None , port = None , name = None , timeout = None , protocol = None , family = 'ipv4' ) : """Starts a new SCTP client . Client can be optionally given ` ip ` and ` port ` to bind to , as well as ` name ` , default ` timeout ` and a ` protocol ` . ` family ` can be either ip...
self . _start_client ( SCTPClient , ip , port , name , timeout , protocol , family )
def get_owner_and_repo ( repourl ) : """Takes a git repository URL from Bitbucket and tries to determine the owner and repository name : param repourl : Bitbucket git repo in the form of git @ bitbucket . com : OWNER / REPONAME . git https : / / bitbucket . com / OWNER / REPONAME . git ssh : / / git @ bitbu...
parsed = urlparse ( repourl ) if parsed . scheme : path = parsed . path [ 1 : ] else : # we assume git @ host : owner / repo . git here path = parsed . path . split ( ':' , 1 ) [ - 1 ] if path . endswith ( '.git' ) : path = path [ : - 4 ] while path . endswith ( '/' ) : path = path [ : - 1 ] parts = pat...
def on_shutdown ( self , broker ) : """Shut down the write end of the logging socket ."""
_v and LOG . debug ( '%r.on_shutdown()' , self ) if not IS_WSL : # #333 : WSL generates invalid readiness indication on shutdown ( ) self . _wsock . shutdown ( socket . SHUT_WR ) self . _wsock . close ( ) self . transmit_side . close ( )
def _parse_meta_info ( self , line ) : """Parse and extract all meta data by looping through the dictionary of meta _ info regexs updates self . meta _ info Args : line ( str ) : line of the msp file"""
if self . mslevel : self . meta_info [ 'ms_level' ] = self . mslevel if self . polarity : self . meta_info [ 'polarity' ] = self . polarity for k , regexes in six . iteritems ( self . meta_regex ) : for reg in regexes : m = re . search ( reg , line , re . IGNORECASE ) if m : self...
def breadth_first_vertex_order ( vertices_resources , nets ) : """A generator which iterates over a set of vertices in a breadth - first order in terms of connectivity . For use as a vertex ordering for the sequential placer ."""
# Special case : no vertices , just stop immediately if len ( vertices_resources ) == 0 : return # Enumerate the set of nets attached to each vertex vertex_neighbours = defaultdict ( set ) for net in nets : # Note : Iterating over a Net object produces the set of vertices # involved in the net . vertex_neighbou...
def _timedeltaToSignHrMin ( offset ) : """Return a ( sign , hour , minute ) triple for the offset described by timedelta . sign is a string , either " + " or " - " . In the case of 0 offset , sign is " + " ."""
minutes = round ( ( offset . days * 3600000000 * 24 + offset . seconds * 1000000 + offset . microseconds ) / 60000000.0 ) if minutes < 0 : sign = '-' minutes = - minutes else : sign = '+' return ( sign , minutes // 60 , minutes % 60 )
def mktns ( self ) : """Make the schema ' s target namespace . @ return : namespace representation of the schema ' s targetNamespace value . @ rtype : ( prefix , URI )"""
tns = self . root . get ( "targetNamespace" ) tns_prefix = None if tns is not None : tns_prefix = self . root . findPrefix ( tns ) return tns_prefix , tns
def default ( self , name , action , seqno ) : """Defaults the routemap on the node Note : This method will attempt to default the routemap from the nodes operational config . Since routemaps do not exist by default , the default action is essentially a negation and the result will be the removal of the r...
return self . configure ( 'default route-map %s %s %s' % ( name , action , seqno ) )
def _get_bokeh_chart ( self , x_field , y_field , chart_type , label , opts , style , options = { } , ** kwargs ) : """Get a Bokeh chart object"""
if isinstance ( x_field , list ) : kdims = x_field else : kdims = [ x_field ] if isinstance ( y_field , list ) : vdims = y_field else : vdims = [ y_field ] args = kwargs args [ "data" ] = self . df args [ "kdims" ] = kdims args [ "vdims" ] = vdims if label is not None : args [ "label" ] = label else...
def check_plate_compatibility ( tool , source_plate , sink_plate ) : """Checks whether the source and sink plate are compatible given the tool : param tool : The tool : param source _ plate : The source plate : param sink _ plate : The sink plate : return : Either an error , or None : type tool : Tool :...
if sink_plate == source_plate . parent : return None # could be that they have the same meta data , but the sink plate is a simplification of the source # plate ( e . g . when using IndexOf tool ) if sink_plate . meta_data_id == source_plate . meta_data_id : if sink_plate . is_sub_plate ( source_plate ) : ...
def _update_proxy ( self , change ) : """An observer which sends state change to the proxy ."""
if change [ 'name' ] in [ 'row' , 'column' ] : super ( AbstractWidgetItem , self ) . _update_proxy ( change ) else : self . proxy . data_changed ( change )
def _get_audio_sample_bit ( self , audio_abs_path ) : """Parameters audio _ abs _ path : str Returns sample _ bit : int"""
sample_bit = int ( subprocess . check_output ( ( """sox --i {} | grep "{}" | awk -F " : " '{{print $2}}' | """ """grep -oh "^[^-]*" """ ) . format ( audio_abs_path , "Precision" ) , shell = True , universal_newlines = True ) . rstrip ( ) ) return sample_bit
def isOriginalLocation ( attr ) : """Attempt to discover if this appearance of a PythonAttribute representing a class refers to the module where that class was defined ."""
sourceModule = inspect . getmodule ( attr . load ( ) ) if sourceModule is None : return False currentModule = attr while not isinstance ( currentModule , PythonModule ) : currentModule = currentModule . onObject return currentModule . name == sourceModule . __name__
def stringPropertyNames ( self ) : r"""Returns a ` set ` of all keys in the ` Properties ` object and its ` defaults ` ( and its ` defaults ` \ ’ s ` defaults ` , etc . ) : rtype : ` set ` of text strings"""
names = set ( self . data ) if self . defaults is not None : names . update ( self . defaults . stringPropertyNames ( ) ) return names
def get_sdk_version ( self ) -> str : '''Show Android SDK version .'''
output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'getprop' , 'ro.build.version.sdk' ) return output . strip ( )
def path_from_pythonpath ( pythonpath ) : """Create an fs . Path object from a pythonpath string ."""
path = fs . Path ( ) for p in pythonpath . split ( os . pathsep ) : path . add_path ( utils . expand_path ( p ) , 'os' ) return path
def overlay_images ( self , canvas , data , whence = 0.0 ) : """Overlay data from any canvas image objects . Parameters canvas : ` ~ ginga . canvas . types . layer . DrawingCanvas ` Canvas containing possible images to overlay . data : ndarray Output array on which to overlay image data . whence See :...
# if not canvas . is _ compound ( ) : if not hasattr ( canvas , 'objects' ) : return for obj in canvas . get_objects ( ) : if hasattr ( obj , 'draw_image' ) : obj . draw_image ( self , data , whence = whence ) elif obj . is_compound ( ) and ( obj != canvas ) : self . overlay_images ( obj , d...
def appendInnerHTML ( self , html ) : '''appendInnerHTML - Appends nodes from arbitrary HTML as if doing element . innerHTML + = ' someHTML ' in javascript . @ param html < str > - Some HTML NOTE : If associated with a document ( AdvancedHTMLParser ) , the html will use the encoding associated with that docum...
# Late - binding to prevent circular import from . Parser import AdvancedHTMLParser # Inherit encoding from the associated document , if any . encoding = None if self . ownerDocument : encoding = self . ownerDocument . encoding # Generate blocks ( text nodes and AdvancedTag ' s ) from HTML blocks = AdvancedHTMLPars...
def create_rflink_connection ( port = None , host = None , baud = 57600 , protocol = RflinkProtocol , packet_callback = None , event_callback = None , disconnect_callback = None , ignore = None , loop = None ) : """Create Rflink manager class , returns transport coroutine ."""
# use default protocol if not specified protocol = partial ( protocol , loop = loop if loop else asyncio . get_event_loop ( ) , packet_callback = packet_callback , event_callback = event_callback , disconnect_callback = disconnect_callback , ignore = ignore if ignore else [ ] , ) # setup serial connection if no transpo...
def preprocess_input ( userinput ) : """< Purpose > Preprocess the raw command line input string . < Arguments > The raw command line input string . We assume it is pre - stripped . < Side Effects > The string will be processed by each module that has a defined preprocessor . < Exceptions > None < R...
for module in get_enabled_modules ( ) : # Not every module has a preprocessor . . . if 'input_preprocessor' in module_data [ module ] : userinput = module_data [ module ] [ 'input_preprocessor' ] ( userinput ) return userinput
def parse ( cls , msg ) : """Parse message string to response object ."""
lines = msg . splitlines ( ) version , status_code , reason = lines [ 0 ] . split ( ) headers = cls . parse_headers ( '\r\n' . join ( lines [ 1 : ] ) ) return cls ( version = version , status_code = status_code , reason = reason , headers = headers )
def isin ( comps , values ) : """Compute the isin boolean array Parameters comps : array - like values : array - like Returns boolean array same length as comps"""
if not is_list_like ( comps ) : raise TypeError ( "only list-like objects are allowed to be passed" " to isin(), you passed a [{comps_type}]" . format ( comps_type = type ( comps ) . __name__ ) ) if not is_list_like ( values ) : raise TypeError ( "only list-like objects are allowed to be passed" " to isin(), yo...
def IsExecutionWhitelisted ( cmd , args ) : """Check if a binary and args is whitelisted . Args : cmd : Canonical path to the binary . args : List of arguments to be passed to the binary . Returns : Bool , True if it is whitelisted . These whitelists could also go in the platform specific client files ...
if platform . system ( ) == "Windows" : whitelist = [ ( "arp.exe" , [ "-a" ] ) , ( "driverquery.exe" , [ "/v" ] ) , ( "ipconfig.exe" , [ "/all" ] ) , ( "netsh.exe" , [ "advfirewall" , "firewall" , "show" , "rule" , "name=all" ] ) , ( "netsh.exe" , [ "advfirewall" , "monitor" , "show" , "firewall" , "rule" , "name=a...
def profileFromPNG ( inp ) : """Extract profile from PNG file . Return ( * profile * , * name * ) pair ."""
r = png . Reader ( file = inp ) _ , chunk = r . chunk ( 'iCCP' ) i = chunk . index ( b'\x00' ) name = chunk [ : i ] compression = chunk [ i + 1 ] assert compression == 0 profile = zlib . decompress ( chunk [ i + 2 : ] ) return profile , name
def _search_dirs ( self , dirs , basename , extension = "" ) : """Search a list of directories for a given filename or directory name . Iterator over the supplied directories , returning the first file found with the supplied name and extension . : param dirs : a list of directories : param basename : the f...
for d in dirs : path = os . path . join ( d , '%s%s' % ( basename , extension ) ) if os . path . exists ( path ) : return path return None
def save ( self , filepath ) : """Save current configuration to file . : param str filepath : Path to file where settings will be saved . : raises : ValueError if supplied filepath cannot be written to ."""
self . _config . add_section ( "RetryPolicy" ) self . _config . set ( "RetryPolicy" , "retries" , str ( self . retry_policy . retries ) ) self . _config . set ( "RetryPolicy" , "backoff_factor" , str ( self . retry_policy . backoff_factor ) ) self . _config . set ( "RetryPolicy" , "max_backoff" , str ( self . retry_pol...
def wait_new_conf ( self ) : """Send a HTTP request to the satellite ( GET / wait _ new _ conf ) : return : True if wait new conf , otherwise False : rtype : bool"""
logger . debug ( "Wait new configuration for %s, %s %s" , self . name , self . alive , self . reachable ) return self . con . get ( '_wait_new_conf' )
def load_data ( self ) : """Loads image and label data from specified directory path . : return : Dataset object containing image and label data ."""
images = list ( ) labels = list ( ) emotion_index_map = dict ( ) label_directories = [ dir for dir in os . listdir ( self . datapath ) if not dir . startswith ( '.' ) ] for label_directory in label_directories : if self . target_emotion_map : if label_directory not in self . target_emotion_map . keys ( ) : ...
def wait ( fs , timeout = - 1 , return_when = ALL_COMPLETED ) : """Wait for the futures in the given sequence to complete . Using this function may prevent a worker from executing . : param fs : The sequence of Futures to wait upon . : param timeout : The maximum number of seconds to wait . If negative or not...
DoneAndNotDoneFutures = namedtuple ( 'DoneAndNotDoneFutures' , 'done not_done' ) if timeout < 0 : # Negative timeout means blocking . if return_when == FIRST_COMPLETED : next ( _waitAny ( * fs ) ) elif return_when in [ ALL_COMPLETED , FIRST_EXCEPTION ] : for _ in _waitAll ( * fs ) : ...
def outer_definition_name ( cls ) : """Helper method for creating outer definition name . Returns : If definition is nested , will return the outer definitions name , else the package name ."""
outer_definition = cls . message_definition ( ) if not outer_definition : return util . get_package_for_module ( cls . __module__ ) return outer_definition . definition_name ( )
def set_state ( self , value , labels = None ) : """: param value : Any number : param labels : A list of two Strings sending None won ' t change the current values . : return :"""
values = { "value" : value } json_labels = [ ] if labels : for label in labels : json_labels . append ( str ( label ) . upper ( ) ) values [ "labels" ] = json_labels self . _update_state_from_response ( self . parent . set_dial ( values , self . index ( ) ) )
def validateFilepath ( value , blank = False , strip = None , allowlistRegexes = None , blocklistRegexes = None , excMsg = None , mustExist = False ) : r"""Raises ValidationException if value is not a valid filename . Filenames can ' t contain \ \ / : * ? " < > | Returns the value argument . * value ( str ) :...
returnNow , value = _prevalidationCheck ( value , blank , strip , allowlistRegexes , blocklistRegexes , excMsg ) if returnNow : return value if ( value != value . strip ( ) ) or ( any ( c in value for c in '*?"<>|' ) ) : # Same as validateFilename , except we allow \ and / and : if ':' in value : if val...
def add_subrule ( self , subrule , weight ) : """Add subrule to the rule . : param subrule : Subrule to add to this rule , an instance of : class : ` Rule ` or : class : ` RuleLeaf ` . : param float weight : Weight of the subrule"""
if not issubclass ( subrule . __class__ , ( Rule , RuleLeaf ) ) : raise TypeError ( "Rule's class must be (subclass of) {} or {}, got " "{}." . format ( Rule , RuleLeaf , subrule . __class__ ) ) self . __domains = set . union ( self . __domains , subrule . domains ) self . R . append ( subrule ) self . W . append (...
def _validate_currency ( self , currency ) : """Check if the given order book is valid . : param currency : Major currency name in lowercase . : type currency : str | unicode : raise InvalidCurrencyError : If an invalid major currency is given ."""
if currency not in self . major_currencies : raise InvalidCurrencyError ( 'Invalid major currency \'{}\'. Choose from {}.' . format ( currency , tuple ( self . major_currencies ) ) )
def inform_version_connect ( self , msg ) : """Process a # version - connect message ."""
if len ( msg . arguments ) < 2 : return # Store version information . name = msg . arguments [ 0 ] self . versions [ name ] = tuple ( msg . arguments [ 1 : ] ) if msg . arguments [ 0 ] == "katcp-protocol" : protocol_flags = ProtocolFlags . parse_version ( msg . arguments [ 1 ] ) self . _set_protocol_from_in...
def symmetry ( self ) : """Check whether a mesh has rotational symmetry . Returns symmetry : None No rotational symmetry ' radial ' Symmetric around an axis ' spherical ' Symmetric around a point"""
symmetry , axis , section = inertia . radial_symmetry ( self ) self . _cache [ 'symmetry_axis' ] = axis self . _cache [ 'symmetry_section' ] = section return symmetry
def write ( s = '' ) : """Automates the process of typing by converting a string into a set of press ( ) and hold ( ) calls : param s : string to be written : return : None"""
for char in s : if char . isupper ( ) : # Handles uppercase hold ( 'shift' , char . lower ( ) ) elif char == " " : # Handles spaces press ( 'spacebar' ) elif char == "\n" : # Handles newline press ( 'enter' ) elif char in ( ')' , '!' , '@' , '#' , '$' , '%' , '^' , '&' , '*' , '(...
def get_lattice_quanta ( self , convert_to_muC_per_cm2 = True , all_in_polar = True ) : """Returns the dipole / polarization quanta along a , b , and c for all structures ."""
lattices = [ s . lattice for s in self . structures ] volumes = np . array ( [ s . lattice . volume for s in self . structures ] ) L = len ( self . structures ) e_to_muC = - 1.6021766e-13 cm2_to_A2 = 1e16 units = 1.0 / np . array ( volumes ) units *= e_to_muC * cm2_to_A2 # convert polarizations and lattice lengths prio...
def events ( self ) -> Iterable [ Tuple [ Optional [ float ] , Callable , Sequence [ Any ] , Mapping [ str , Any ] ] ] : """Iterates over scheduled events . Each event is a 4 - tuple composed of the moment ( on the simulated clock ) the event should execute , the function corresponding to the event , its position...
return ( ( event . timestamp , event . fn , event . args , event . kwargs ) for event in self . _events if not event . is_cancelled )
def ParseOptions ( cls , options , config_object , category = None , names = None ) : """Parses and validates arguments using the appropriate helpers . Args : options ( argparse . Namespace ) : parser options . config _ object ( object ) : object to be configured by an argument helper . category ( Optional ...
for helper_name , helper_class in cls . _helper_classes . items ( ) : if ( ( category and helper_class . CATEGORY != category ) or ( names and helper_name not in names ) ) : continue try : helper_class . ParseOptions ( options , config_object ) except errors . BadConfigObject : pass
def sem ( self , ddof = 1 ) : """Compute standard error of the mean of groups , excluding missing values . For multiple groupings , the result index will be a MultiIndex . Parameters ddof : integer , default 1 degrees of freedom"""
return self . std ( ddof = ddof ) / np . sqrt ( self . count ( ) )
def uninstall ( self , pkgname , * args , ** kwargs ) : """A context manager which allows uninstallation of packages from the environment : param str pkgname : The name of a package to uninstall > > > env = Environment ( " / path / to / env / root " ) > > > with env . uninstall ( " pytz " , auto _ confirm = T...
auto_confirm = kwargs . pop ( "auto_confirm" , True ) verbose = kwargs . pop ( "verbose" , False ) with self . activated ( ) : monkey_patch = next ( iter ( dist for dist in self . base_working_set if dist . project_name == "recursive-monkey-patch" ) , None ) if monkey_patch : monkey_patch . activate ( )...
def get_shapes_pymunk_space ( df_convex_shapes , shape_i_columns ) : '''Return two - ple containing : - A ` pymunk . Space ` instance . - A ` pandas . Series ` mapping each ` pymunk . Body ` object in the ` Space ` to a shape index . The ` Body ` to shape index mapping makes it possible to , for example , l...
if isinstance ( shape_i_columns , bytes ) : shape_i_columns = [ shape_i_columns ] space = pm . Space ( ) bodies = [ ] convex_groups = df_convex_shapes . groupby ( shape_i_columns ) for shape_i , df_i in convex_groups : if not isinstance ( shape_i , ( list , tuple ) ) : shape_i = [ shape_i ] if hasat...
def _uncythonized_model ( self , beta ) : """Creates the structure of the model Parameters beta : np . array Contains untransformed starting values for latent variables Returns theta : np . array Contains the predicted values for the time series Y : np . array Contains the length - adjusted time ser...
parm = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( beta . shape [ 0 ] ) ] ) coefficients = np . zeros ( ( self . X . shape [ 1 ] , self . model_Y . shape [ 0 ] + 1 ) ) coefficients [ : , 0 ] = self . initial_values theta = np . zeros ( self . model_Y . shape...
def getResourceMapPid ( self ) : """Returns : str : PID of the Resource Map itself ."""
ore = [ o for o in self . subjects ( predicate = rdflib . RDF . type , object = ORE . ResourceMap ) ] [ 0 ] pid = [ str ( o ) for o in self . objects ( predicate = DCTERMS . identifier , subject = ore ) ] [ 0 ] return pid
def _summarize_coefficients ( top_coefs , bottom_coefs ) : """Return a tuple of sections and section titles . Sections are pretty print of model coefficients Parameters top _ coefs : SFrame of top k coefficients bottom _ coefs : SFrame of bottom k coefficients Returns ( sections , section _ titles ) : t...
def get_row_name ( row ) : if row [ 'index' ] is None : return row [ 'name' ] else : return "%s[%s]" % ( row [ 'name' ] , row [ 'index' ] ) if len ( top_coefs ) == 0 : top_coefs_list = [ ( 'No Positive Coefficients' , _precomputed_field ( '' ) ) ] else : top_coefs_list = [ ( get_row_name...
def satosa_logging ( logger , level , message , state , ** kwargs ) : """Adds a session ID to the message . : type logger : logging : type level : int : type message : str : type state : satosa . state . State : param logger : Logger to use : param level : Logger level ( ex : logging . DEBUG / logging ....
if state is None : session_id = "UNKNOWN" else : try : session_id = state [ LOGGER_STATE_KEY ] except KeyError : session_id = uuid4 ( ) . urn state [ LOGGER_STATE_KEY ] = session_id logger . log ( level , "[{id}] {msg}" . format ( id = session_id , msg = message ) , ** kwargs )
def make_seg_table ( workflow , seg_files , seg_names , out_dir , tags = None , title_text = None , description = None ) : """Creates a node in the workflow for writing the segment summary table . Returns a File instances for the output file ."""
seg_files = list ( seg_files ) seg_names = list ( seg_names ) if tags is None : tags = [ ] makedir ( out_dir ) node = PlotExecutable ( workflow . cp , 'page_segtable' , ifos = workflow . ifos , out_dir = out_dir , tags = tags ) . create_node ( ) node . add_input_list_opt ( '--segment-files' , seg_files ) quoted_seg...
def set_max_string_length ( self , length = None ) : """stub"""
if self . get_max_string_length_metadata ( ) . is_read_only ( ) : raise NoAccess ( ) if not self . my_osid_object_form . _is_valid_cardinal ( length , self . get_max_string_length_metadata ( ) ) : raise InvalidArgument ( ) if self . my_osid_object_form . min_string_length is not None and length < self . my_osid...
def ip_registrant_monitor ( self , query , days_back = 0 , search_type = "all" , server = None , country = None , org = None , page = 1 , include_total_count = False , ** kwargs ) : """Query based on free text query terms"""
return self . _results ( 'ip-registrant-monitor' , '/v1/ip-registrant-monitor' , query = query , days_back = days_back , search_type = search_type , server = server , country = country , org = org , page = page , include_total_count = include_total_count , ** kwargs )
def optimize_delta_bisection ( self , data , skipstep = 1 , verbose = None ) : """Find optimal ridge penalty with bisection search . Parameters data : array , shape ( n _ trials , n _ channels , n _ samples ) Epoched data set . At least two trials are required . skipstep : int , optional Speed up calculat...
data = atleast_3d ( data ) if data . shape [ 0 ] < 2 : raise ValueError ( "At least two trials are required." ) if verbose is None : verbose = config . getboolean ( 'scot' , 'verbose' ) maxsteps = 10 maxdelta = 1e50 a = - 10 b = 10 trform = lambda x : np . sqrt ( np . exp ( x ) ) msge = _get_msge_with_gradient_...
def str_with_sizes ( self , max_name , max_remote_id , max_size ) : """Create string for report based on internal properties using sizes to line up columns . : param max _ name : int width of the name column : param max _ remote _ id : int width of the remote _ id column : return : str info from this report i...
name_str = self . name . ljust ( max_name ) remote_id_str = self . remote_id . ljust ( max_remote_id ) size_str = self . size . ljust ( max_size ) return u'{} {} {} {}' . format ( name_str , remote_id_str , size_str , self . file_hash )
def field_specific_errors ( self ) : """Returns a dictionary of field - specific validation errors for this row ."""
return { key : value for key , value in self . error_dict . items ( ) if key != NON_FIELD_ERRORS }
def delete_table ( self , table , retry = DEFAULT_RETRY , not_found_ok = False ) : """Delete a table See https : / / cloud . google . com / bigquery / docs / reference / rest / v2 / tables / delete Args : table ( Union [ : class : ` ~ google . cloud . bigquery . table . Table ` , : class : ` ~ google . clou...
table = _table_arg_to_table_ref ( table , default_project = self . project ) if not isinstance ( table , TableReference ) : raise TypeError ( "Unable to get TableReference for table '{}'" . format ( table ) ) try : self . _call_api ( retry , method = "DELETE" , path = table . path ) except google . api_core . e...
def _ConvertRowToUnicode ( self , parser_mediator , row ) : """Converts all strings in a DSV row dict to Unicode . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . row ( dict [ str , bytes ] ) : a row from a DSV file , whe...
for key , value in iter ( row . items ( ) ) : if isinstance ( value , py2to3 . UNICODE_TYPE ) : continue try : row [ key ] = value . decode ( self . _encoding ) except UnicodeDecodeError : replaced_value = value . decode ( self . _encoding , errors = 'replace' ) parser_mediat...
def is_active_feature ( feature , redirect_to = None , redirect = None ) : """Decorator for Flask views . If a feature is off , it can either return a 404 or redirect to a URL if you ' d rather ."""
def _is_active_feature ( func ) : @ wraps ( func ) def wrapped ( * args , ** kwargs ) : if not is_active ( feature ) : url = redirect_to if redirect : url = url_for ( redirect ) if url : log . debug ( u'Feature {feature} is off, redirec...
def from_tibiadata ( cls , content ) : """Parses the content of the World Overview section from TibiaData . com into an object of this class . Notes Due to TibiaData limitations , : py : attr : ` record _ count ` and : py : attr : ` record _ date ` are unavailable object . Additionally , the listed worlds i...
json_data = parse_json ( content ) try : worlds_json = json_data [ "worlds" ] [ "allworlds" ] world_overview = cls ( ) for world_json in worlds_json : world = ListedWorld ( world_json [ "name" ] , world_json [ "location" ] , world_json [ "worldtype" ] ) world . _parse_additional_info ( world...
def saveCustomParams ( self , data ) : """Send custom dictionary to Polyglot to save and be retrieved on startup . : param data : Dictionary of key value pairs to store in Polyglot database ."""
LOGGER . info ( 'Sending customParams to Polyglot.' ) message = { 'customparams' : data } self . send ( message )
def _generate_custom_type ( self , resource_type ) : """Dynamically allocates a new CustomResource class definition using the specified Custom : : SomeCustomName resource type . This special resource type is equivalent to the AWS : : CloudFormation : : CustomResource ."""
if not resource_type . startswith ( "Custom::" ) : raise TypeError ( "Custom types must start with Custom::" ) custom_type = type ( str ( resource_type . replace ( "::" , "" ) ) , ( self . inspect_resources [ 'AWS::CloudFormation::CustomResource' ] , ) , { 'resource_type' : resource_type } ) self . inspect_members ...
def ep ( self , exc : Exception ) -> bool : """Return False if the exception had not been handled gracefully"""
if not isinstance ( exc , ConnectionAbortedError ) : return False if len ( exc . args ) != 2 : return False origin , reason = exc . args logging . getLogger ( __name__ ) . warning ( 'Exited' ) return True
def unassign_log_entry_from_log ( self , log_entry_id , log_id ) : """Removes a ` ` LogEntry ` ` from a ` ` Log ` ` . arg : log _ entry _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` LogEntry ` ` arg : log _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Log ` ` raise : NotFound - ` ` log _ entry _ ...
# Implemented from template for # osid . resource . ResourceBinAssignmentSession . unassign _ resource _ from _ bin mgr = self . _get_provider_manager ( 'LOGGING' , local = True ) lookup_session = mgr . get_log_lookup_session ( proxy = self . _proxy ) lookup_session . get_log ( log_id ) # to raise NotFound self . _unas...
def send_request ( self , service_name , actions , switches = None , correlation_id = None , continue_on_error = False , context = None , control_extra = None , message_expiry_in_seconds = None , suppress_response = False , ) : """Build and send a JobRequest , and return a request ID . The context and control _ e...
control_extra = control_extra . copy ( ) if control_extra else { } if message_expiry_in_seconds and 'timeout' not in control_extra : control_extra [ 'timeout' ] = message_expiry_in_seconds handler = self . _get_handler ( service_name ) control = self . _make_control_header ( continue_on_error = continue_on_error , ...
def render_activity ( activity , grouped_activity = None , * args , ** kwargs ) : """Given an activity , will attempt to render the matching template snippet for that activity ' s content object or will return a simple representation of the activity . Also takes an optional ' grouped _ activity ' argument tha...
template_name = 'activity_monitor/includes/models/{0.app_label}_{0.model}.html' . format ( activity . content_type ) try : tmpl = loader . get_template ( template_name ) except template . TemplateDoesNotExist : return None # we know we have a template , so render it content_object = activity . content_object re...
async def release ( self , * , comment : str = None , erase : bool = None , secure_erase : bool = None , quick_erase : bool = None , wait : bool = False , wait_interval : int = 5 ) : """Release the machine . : param comment : Reason machine was released . : type comment : ` str ` : param erase : Erase the dis...
params = remove_None ( { "system_id" : self . system_id , "comment" : comment , "erase" : erase , "secure_erase" : secure_erase , "quick_erase" : quick_erase , } ) self . _data = await self . _handler . release ( ** params ) if not wait : return self else : # Wait for machine to be released while self . status ...
def add ( self , name , graph ) : """Index and add a : ref : ` networkx . Graph < networkx : graph > ` to the : class : ` . GraphCollection ` . Parameters name : hashable Unique name used to identify the ` graph ` . graph : : ref : ` networkx . Graph < networkx : graph > ` Raises ValueError If ` nam...
if name in self : raise ValueError ( "{0} exists in this GraphCollection" . format ( name ) ) elif hasattr ( self , unicode ( name ) ) : raise ValueError ( "Name conflicts with an existing attribute" ) indexed_graph = self . index ( name , graph ) # Add all edges to the ` master _ graph ` . for s , t , attrs in...
def save ( self ) : """Saves the snapshot based on the current region ."""
# close down the snapshot widget if self . hideWindow ( ) : self . hideWindow ( ) . hide ( ) self . hide ( ) QApplication . processEvents ( ) time . sleep ( 1 ) # create the pixmap to save wid = QApplication . desktop ( ) . winId ( ) if not self . _region . isNull ( ) : x = self . _region . x ( ) y = self ....
def _get_total_available_slots ( self , context , template_id , capacity ) : """Returns available slots in idle devices based on < template _ id > . Only slots in tenant unbound hosting devices are counted to ensure there is always hosting device slots available regardless of tenant ."""
query = context . session . query ( hd_models . HostingDevice . id ) query = query . outerjoin ( hd_models . SlotAllocation , hd_models . HostingDevice . id == hd_models . SlotAllocation . hosting_device_id ) query = query . filter ( hd_models . HostingDevice . template_id == template_id , hd_models . HostingDevice . a...
def user_login ( self , email = None , password = None ) : """Login with email , password and get back a session cookie : type email : str : param email : The email used for authentication : type password : str : param password : The password used for authentication"""
email = six . moves . input ( "Email: " ) if email is None else email password = getpass . getpass ( ) if password is None else password login_data = { "method" : "user.login" , "params" : { "email" : email , "pass" : password } } # If the user / password match , the server respond will contain a # session cookie that ...
def return_dat ( self , chan , begsam , endsam ) : """Return the data as 2D numpy . ndarray . Parameters chan : int or list index ( indices ) of the channels to read begsam : int index of the first sample endsam : int index of the last sample Returns numpy . ndarray A 2d matrix , with dimension ...
dat = _read_memmap ( self . eeg_file , self . dshape , begsam , endsam , self . data_type , self . data_order ) return dat [ chan , : ] * self . gain [ chan , None ]
def get_card_transfer ( provider : Provider , deck : Deck , txid : str , debug : bool = False ) -> Iterator : '''get a single card transfer by it ' s id'''
rawtx = provider . getrawtransaction ( txid , 1 ) bundle = card_bundler ( provider , deck , rawtx ) return card_bundle_parser ( bundle , debug )
def _instance_callable ( obj ) : """Given an object , return True if the object is callable . For classes , return True if instances would be callable ."""
if not isinstance ( obj , ClassTypes ) : # already an instance return getattr ( obj , '__call__' , None ) is not None klass = obj # uses _ _ bases _ _ instead of _ _ mro _ _ so that we work with old style classes if klass . __dict__ . get ( '__call__' ) is not None : return True for base in klass . __bases__ : ...
def sens_atmos_send ( self , TempAmbient , Humidity , force_mavlink1 = False ) : '''Atmospheric sensors ( temperature , humidity , . . . ) TempAmbient : Ambient temperature [ degrees Celsius ] ( float ) Humidity : Relative humidity [ % ] ( float )'''
return self . send ( self . sens_atmos_encode ( TempAmbient , Humidity ) , force_mavlink1 = force_mavlink1 )
def variables ( self ) -> list : """Variables ."""
try : assert self . _variables is not None except ( AssertionError , AttributeError ) : pattern = "|" . join ( map ( re . escape , operators ) ) keys = re . split ( pattern , self . expression ) indices = [ ] for key in keys : if key in self . parent . variable_names : indices . ...
def batch_augment ( x , func , device = '/CPU:0' ) : """Apply dataset augmentation to a batch of exmaples . : param x : Tensor representing a batch of examples . : param func : Callable implementing dataset augmentation , operating on a single image . : param device : String specifying which device to use ....
with tf . device ( device ) : return tf . map_fn ( func , x )
def eval ( self , expression , args = None , * , timeout = - 1.0 , push_subscribe = False ) -> _MethodRet : """Eval request coroutine . Examples : . . code - block : : pycon > > > await conn . eval ( ' return 42 ' ) < Response sync = 3 rowcount = 1 data = [ 42 ] > > > > await conn . eval ( ' return box . ...
return self . _db . eval ( expression , args , timeout = timeout , push_subscribe = push_subscribe )