signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def zip_dir ( directory ) : """zip a directory tree into a BytesIO object"""
result = io . BytesIO ( ) dlen = len ( directory ) with ZipFile ( result , "w" ) as zf : for root , dirs , files in os . walk ( directory ) : for name in files : full = os . path . join ( root , name ) rel = root [ dlen : ] dest = os . path . join ( rel , name ) ...
def _compress ( self , cmd ) : """Adds the appropriate command to compress the zfs stream"""
compressor = COMPRESSORS . get ( self . compressor ) if compressor is None : return cmd compress_cmd = compressor [ 'compress' ] return "{} | {}" . format ( compress_cmd , cmd )
def _pshell_json ( cmd , cwd = None ) : '''Execute the desired powershell command and ensure that it returns data in JSON format and load that into python'''
if 'convertto-json' not in cmd . lower ( ) : cmd = '{0} | ConvertTo-Json' . format ( cmd ) log . debug ( 'PowerShell: %s' , cmd ) ret = __salt__ [ 'cmd.run_all' ] ( cmd , shell = 'powershell' , cwd = cwd ) if 'pid' in ret : del ret [ 'pid' ] if ret . get ( 'stderr' , '' ) : error = ret [ 'stderr' ] . splitl...
def _process_extensions ( exts ) : """Generate the ` Extensions String ` from an iterable of data forms . : param exts : The data forms to generate the extensions string from . : type exts : : class : ` ~ collections . abc . Iterable ` of : class : ` ~ . forms . xso . Data ` : return : The ` Extensions Stri...
parts = [ _process_form ( form ) for form in exts ] parts . sort ( ) return b"" . join ( parts ) + b"\x1c"
def load_label ( self , idx , label_type = None ) : """Load label image as 1 x height x width integer array of label indices . The leading singleton dimension is required by the loss ."""
if label_type == 'semantic' : label = scipy . io . loadmat ( '{}/SemanticLabels/spatial_envelope_256x256_static_8outdoorcategories/{}.mat' . format ( self . siftflow_dir , idx ) ) [ 'S' ] elif label_type == 'geometric' : label = scipy . io . loadmat ( '{}/GeoLabels/spatial_envelope_256x256_static_8outdoorcatego...
def data_source_and_uncertainty_flags ( self , value = None ) : """Corresponds to IDD Field ` data _ source _ and _ uncertainty _ flags ` Initial day of weather file is checked by EnergyPlus for validity ( as shown below ) Each field is checked for " missing " as shown below . Reasonable values , calculated v...
if value is not None : try : value = str ( value ) except ValueError : raise ValueError ( 'value {} need to be of type str ' 'for field `data_source_and_uncertainty_flags`' . format ( value ) ) if ',' in value : raise ValueError ( 'value should not contain a comma ' 'for field `data_...
def main ( directories ) : '''Perform all checks on the API ' s contained in ` directory ` .'''
msg = 'Checking module "{}" from directory "{}" for coding errors.' api_checker = ApiChecker ( ) resource_checker = ResourceChecker ( ) errors = [ ] modules = [ ] for loader , mname , _ in pkgutil . walk_packages ( directories ) : sys . path . append ( os . path . abspath ( loader . path ) ) log . info ( msg . ...
def extract_operations ( self , migrations ) : """Extract SQL operations from the given migrations"""
operations = [ ] for migration in migrations : for operation in migration . operations : if isinstance ( operation , RunSQL ) : statements = sqlparse . parse ( dedent ( operation . sql ) ) for statement in statements : operation = SqlObjectOperation . parse ( statemen...
def handle_legacy_tloc ( line : str , position : int , tokens : ParseResults ) -> ParseResults : """Handle translocations that lack the ` ` fromLoc ` ` and ` ` toLoc ` ` entries ."""
log . log ( 5 , 'legacy translocation statement: %s [%d]' , line , position ) return tokens
def get_next_step ( self ) : """Find the proper step when user clicks the Next button . : returns : The step to be switched to : rtype : WizardStep"""
if self . parent . get_layer_geometry_key ( ) == layer_geometry_raster [ 'key' ] : return self . parent . step_kw_source layer_purpose = self . parent . step_kw_purpose . selected_purpose ( ) if layer_purpose [ 'key' ] != layer_purpose_aggregation [ 'key' ] : subcategory = self . parent . step_kw_subcategory . ...
def fhs2data_combo ( fhs , cols , index , labels = None , col_sep = ': ' ) : """Collates data from multiple csv files : param fhs : list of paths to csv files : param cols : list of column names to concatenate : param index : name of the column name to be used as the common index of the output pandas table"""
if labels is None : labels = [ basename ( fh ) for fh in fhs ] if len ( fhs ) > 0 : for fhi , fh in enumerate ( fhs ) : label = labels [ fhi ] data = pd . read_csv ( fh ) . set_index ( index ) if fhi == 0 : data_combo = pd . DataFrame ( index = data . index ) for ...
def set_metadata ( self , metadata : MetaData ) -> None : """Sets the metadata for the parent and child tables ."""
self . _parent . set_metadata ( metadata ) self . _child . set_metadata ( metadata )
def find_minmax ( lims , olims ) : """Takes ( a1 , a2 ) and ( b1 , b2 ) as input and returns ( np . nanmin ( a1 , b1 ) , np . nanmax ( a2 , b2 ) ) . Used to calculate min and max values of a number of items ."""
try : limzip = zip ( list ( lims ) , list ( olims ) , [ np . nanmin , np . nanmax ] ) limits = tuple ( [ float ( fn ( [ l , ol ] ) ) for l , ol , fn in limzip ] ) except : limits = ( np . NaN , np . NaN ) return limits
def netmiko_file_transfer ( task : Task , source_file : str , dest_file : str , ** kwargs : Any ) -> Result : """Execute Netmiko file _ transfer method Arguments : source _ file : Source file . dest _ file : Destination file . kwargs : Additional arguments to pass to file _ transfer Returns : Result obj...
net_connect = task . host . get_connection ( "netmiko" , task . nornir . config ) kwargs . setdefault ( "direction" , "put" ) scp_result = file_transfer ( net_connect , source_file = source_file , dest_file = dest_file , ** kwargs ) if kwargs . get ( "disable_md5" ) is True : file_valid = scp_result [ "file_exists"...
def process_exception_message ( exception ) : """Process an exception message . Args : exception : The exception to process . Returns : A filtered string summarizing the exception ."""
exception_message = str ( exception ) for replace_char in [ '\t' , '\n' , '\\n' ] : exception_message = exception_message . replace ( replace_char , '' if replace_char != '\t' else ' ' ) return exception_message . replace ( 'section' , 'alias' )
def zendesk_ticket ( self ) : """| Description : The ID of the Zendesk Support ticket created from this chat . Available only if using version 2 of the Zendesk Chat - Support integration"""
if self . api and self . zendesk_ticket_id : return self . api . _get_zendesk_ticket ( self . zendesk_ticket_id )
def fetch ( db = None , sql = None ) : '''Retrieve data from an sqlite3 db ( returns all rows , be careful ! ) CLI Example : . . code - block : : bash salt ' * ' sqlite3 . fetch / root / test . db ' SELECT * FROM test ; ' '''
cur = _connect ( db ) if not cur : return False cur . execute ( sql ) rows = cur . fetchall ( ) return rows
def get_statements ( self ) : """Convert network edges into Statements . Returns list of Statements Converted INDRA Statements ."""
edges = _get_dict_from_list ( 'edges' , self . cx ) for edge in edges : edge_type = edge . get ( 'i' ) if not edge_type : continue stmt_type = _stmt_map . get ( edge_type ) if stmt_type : id = edge [ '@id' ] source_agent = self . _node_agents . get ( edge [ 's' ] ) target...
def fresh_jwt_required ( fn ) : """A decorator to protect a Flask endpoint . If you decorate an endpoint with this , it will ensure that the requester has a valid and fresh access token before allowing the endpoint to be called . See also : : func : ` ~ flask _ jwt _ extended . jwt _ required `"""
@ wraps ( fn ) def wrapper ( * args , ** kwargs ) : verify_fresh_jwt_in_request ( ) return fn ( * args , ** kwargs ) return wrapper
def _add_remove_user_template ( self , url , template_id , account_id = None , email_address = None ) : '''Add or Remove user from a Template We use this function for two tasks because they have the same API call Args : template _ id ( str ) : The id of the template account _ id ( str ) : ID of the account ...
if not email_address and not account_id : raise HSException ( "No email address or account_id specified" ) data = { } if account_id is not None : data = { "account_id" : account_id } else : data = { "email_address" : email_address } request = self . _get_request ( ) response = request . post ( url + templat...
def run_job ( self , ** kwds ) : """Create a DRMAA job template , populate with specified properties , run the job , and return the external _ job _ id ."""
template = DrmaaSession . session . createJobTemplate ( ) try : for key in kwds : setattr ( template , key , kwds [ key ] ) with DrmaaSession . session_lock : return DrmaaSession . session . runJob ( template ) finally : DrmaaSession . session . deleteJobTemplate ( template )
def build_data ( data_path , size , dataset ) : """Creates the queue and preprocessing operations for the dataset . Args : data _ path : Filename for cifar10 data . size : The number of images in the dataset . dataset : The dataset we are using . Returns : queue : A Tensorflow queue for extracting the i...
image_size = 32 if dataset == "cifar10" : label_bytes = 1 label_offset = 0 elif dataset == "cifar100" : label_bytes = 1 label_offset = 1 depth = 3 image_bytes = image_size * image_size * depth record_bytes = label_bytes + label_offset + image_bytes def load_transform ( value ) : # Convert these examples...
def download_files ( fapi , file_name , conf , use_cache , cache_dir = None ) : """Downloads translated versions of the files"""
retrieval_type = conf . get ( 'retrieval-type' , 'published' ) include_original_strings = 'true' if conf . get ( 'include-original-strings' , False ) else 'false' save_pattern = conf . get ( 'save-pattern' ) if not save_pattern : raise SmarterlingError ( "File %s doesn't have a save-pattern" % file_name ) if cache_...
def _get_video_info ( self ) : """Returns basic information about the video as dictionary ."""
if not hasattr ( self , '_info_cache' ) : encoding_backend = get_backend ( ) try : path = os . path . abspath ( self . path ) except AttributeError : path = os . path . abspath ( self . name ) self . _info_cache = encoding_backend . get_media_info ( path ) return self . _info_cache
def _parse_values ( values , extra = None ) : """Utility function to flatten out args . For internal use only . : param values : list , tuple , or str : param extra : list or None : return : list"""
coerced = list ( values ) if coerced == values : values = coerced else : coerced = tuple ( values ) if coerced == values : values = list ( values ) else : values = [ values ] if extra : values . extend ( extra ) return values
def compare ( self , other ) : """Compare the DigitWord with another DigitWord ( other ) and provided iterated analysis of the matches ( none or loose ) and the occurrence ( one or more ) of each DigitEntry in both DigitWords . The method returns a list of Comparison objects ."""
self . _validate_compare_parameters ( other = other ) return_list = [ ] for idx , digit in enumerate ( other ) : dwa = DigitWordAnalysis ( index = idx , digit = digit , match = ( digit == self . _word [ idx ] ) , in_word = ( self . _word . count ( digit ) > 0 ) , multiple = ( self . _word . count ( digit ) > 1 ) ) ...
def certify_email ( value , required = True ) : """Certifier which verifies that email addresses are well - formed . Does not check that the address exists . : param six . string _ types value : The email address to certify . * * Should be normalized ! * * : param bool required : Whether the value can be ...
certify_required ( value = value , required = required , ) certify_string ( value , min_length = 3 , max_length = 320 ) try : certification_result = email_validator . validate_email ( value , check_deliverability = False , ) except email_validator . EmailNotValidError as ex : six . raise_from ( CertifierValueEr...
def line ( x_fn , y_fn , * , options = { } , ** interact_params ) : """Generates an interactive line chart that allows users to change the parameters of the inputs x _ fn and y _ fn . Args : x _ fn ( Array | ( * args - > Array str | Array int | Array float ) ) : If array , uses array values for x - coordina...
fig = options . get ( '_fig' , False ) or _create_fig ( options = options ) [ line ] = ( _create_marks ( fig = fig , marks = [ bq . Lines ] , options = options ) ) _add_marks ( fig , [ line ] ) def wrapped ( ** interact_params ) : x_data = util . maybe_call ( x_fn , interact_params , prefix = 'x' ) line . x = x...
def _iter_symbols ( code ) : """Iterate all the variable names in the given expression . Example : * ` ` self . foobar ` ` yields ` ` self ` ` * ` ` self [ foobar ] ` ` yields ` self ` ` and ` ` foobar ` `"""
for node in ast . walk ( ast . parse ( code ) ) : if isinstance ( node , ast . Name ) : yield node . id
def bounds_overlap ( bound1 , bound2 ) : '''return true if two bounding boxes overlap'''
( x1 , y1 , w1 , h1 ) = bound1 ( x2 , y2 , w2 , h2 ) = bound2 if x1 + w1 < x2 : return False if x2 + w2 < x1 : return False if y1 + h1 < y2 : return False if y2 + h2 < y1 : return False return True
def init_extension ( self , app ) : """Initialize cache instance ."""
app . config . setdefault ( 'CACHE_VERSION' , '0' ) app . config . setdefault ( 'CACHE_PREFIX' , 'r' ) app . config . setdefault ( 'CACHE_BACKEND' , 'rio.exts.flask_cache.NullBackend' ) app . config . setdefault ( 'CACHE_BACKEND_OPTIONS' , { } )
async def grant_model ( self , username , model_uuid , acl = 'read' ) : """Grant a user access to a model . Note that if the user already has higher permissions than the provided ACL , this will do nothing ( see revoke _ model for a way to remove permissions ) . : param str username : Username : param str...
model_facade = client . ModelManagerFacade . from_connection ( self . connection ( ) ) user = tag . user ( username ) model = tag . model ( model_uuid ) changes = client . ModifyModelAccess ( acl , 'grant' , model , user ) return await model_facade . ModifyModelAccess ( [ changes ] )
def post ( self , path , args , wait = False ) : """POST an HTTP request to a daemon : param path : path to do the request : type path : str : param args : args to add in the request : type args : dict : param wait : True for a long timeout : type wait : bool : return : Content of the HTTP response if...
uri = self . make_uri ( path ) timeout = self . make_timeout ( wait ) for ( key , value ) in list ( args . items ( ) ) : args [ key ] = serialize ( value , True ) try : logger . debug ( "post: %s, timeout: %s, params: %s" , uri , timeout , args ) rsp = self . _requests_con . post ( uri , json = args , timeo...
def _get_next_slot ( self , tag ) : '''get the first unused supval table key , or 0 if the table is empty . useful for filling the supval table sequentially .'''
slot = self . _n . suplast ( tag ) if slot is None or slot == idaapi . BADNODE : return 0 else : return slot + 1
def validate_storage_settings ( storage_class , settings ) : """Given a ` storage _ class ` and a dictionary of ` settings ` to initialize it , this method verifies that all the settings are valid ."""
if not isinstance ( settings , dict ) : raise ImproperlyConfigured ( '{}: storage class settings must be a dict' . format ( storage_class ) ) if not hasattr ( storage_class , 'SETTINGS_VALIDATORS' ) : raise NotImplementedError ( '{}: storage class must define `SETTINGS_VALIDATORS`' . format ( storage_class ) ) ...
def flush_queue ( self ) : """Grab all the current records in the queue and send them ."""
records = [ ] while not self . queue . empty ( ) and len ( records ) < self . batch_size : records . append ( self . queue . get ( ) ) if records : self . send_records ( records ) self . last_flush = time . time ( )
def inline ( self , callback ) : """Set callback for inline queries : Example : > > > @ bot . inline > > > def echo ( iq ) : > > > return iq . answer ( [ > > > { " type " : " text " , " title " : " test " , " id " : " 0 " } > > > @ bot . inline ( r " myinline - ( . + ) " ) > > > def echo ( chat , iq ,...
if callable ( callback ) : self . _default_inline = callback return callback elif isinstance ( callback , str ) : def decorator ( fn ) : self . add_inline ( callback , fn ) return fn return decorator else : raise TypeError ( "str expected {} given" . format ( type ( callback ) ) )
def simulation ( self , data = None ) : """Gets / Sets the simulation data . If no data is passed in , then this method acts as a getter . if data is passed in , then this method acts as a setter . Keyword arguments : data - - the simulation data you wish to set ( default None )"""
if data : return self . _session . put ( self . __v2 ( ) + "/simulation" , data = data ) else : return self . _session . get ( self . __v2 ( ) + "/simulation" ) . json ( )
def get ( self , request ) : """Used to make get calls to mattermost api : param request : : return :"""
headers = { "Authorization" : "Bearer " + self . token } g = requests . get ( self . url + request , headers = headers ) return json . loads ( g . text )
def skip ( self , num_bytes ) : """Jump the ahead the specified bytes in the buffer ."""
if num_bytes is None : self . _offset = len ( self . _data ) else : self . _offset += num_bytes
def registerRti ( self , fullName , fullClassName , extensions = None , pythonPath = '' ) : """Class that maintains the collection of registered inspector classes . Maintains a lit of file extensions that open the RTI by default ."""
check_is_a_sequence ( extensions ) extensions = extensions if extensions is not None else [ ] extensions = [ prepend_point_to_extension ( ext ) for ext in extensions ] regRti = RtiRegItem ( fullName , fullClassName , extensions , pythonPath = pythonPath ) self . registerItem ( regRti )
def modify_subroutine ( subroutine ) : """loops through variables of a subroutine and modifies them"""
# print ( ' \ n - - - - ' , subroutine [ ' name ' ] , ' - - - - ' ) # - - use original function from shtools : subroutine [ 'use' ] = { 'shtools' : { 'map' : { subroutine [ 'name' ] : subroutine [ 'name' ] } , 'only' : 1 } } # - - loop through variables : for varname , varattribs in subroutine [ 'vars' ] . items ( ) : ...
def asset ( self , asset_id , asset_type , action = 'GET' ) : """Gets the asset with the provided id Args : asset _ id : The id of the asset to be retrieved asset _ type : ( str ) Either PHONE , HANDLER , or URL action : Returns :"""
if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) if asset_type == 'PHONE' : return self . tc_requests . adversary_phone_asset ( self . api_type , self . api_sub_type , self . unique_id , asset_id , action = action ) if asset_type == 'HANDLER' : return self . tc_requests ....
def from_xml ( cls , xml ) : """Returns a new Text from the given XML string ."""
s = parse_string ( xml ) return Sentence ( s . split ( "\n" ) [ 0 ] , token = s . tags , language = s . language )
def _visit_pyfiles ( list , dirname , names ) : """Helper for getFilesForName ( ) ."""
# get extension for python source files if not globals ( ) . has_key ( '_py_ext' ) : global _py_ext # _ py _ ext = [ triple [ 0 ] for triple in imp . get _ suffixes ( ) # if triple [ 2 ] = = imp . PY _ SOURCE ] [ 0] _py_ext = [ triple [ 0 ] for triple in imp . get_suffixes ( ) if triple [ 2 ] == imp . P...
def createCluster ( self , hzVersion , xmlconfig ) : """Parameters : - hzVersion - xmlconfig"""
self . send_createCluster ( hzVersion , xmlconfig ) return self . recv_createCluster ( )
def _read_ipx_address ( self ) : """Read IPX address field . Structure of IPX address : Octets Bits Name Description 0 0 ipx . addr . network Network Number 4 32 ipx . addr . node Node Number 10 80 ipx . addr . socket Socket Number"""
# Address Number _byte = self . _read_fileng ( 4 ) _ntwk = ':' . join ( textwrap . wrap ( _byte . hex ( ) , 2 ) ) # Node Number ( MAC ) _byte = self . _read_fileng ( 6 ) _node = ':' . join ( textwrap . wrap ( _byte . hex ( ) , 2 ) ) _maca = '-' . join ( textwrap . wrap ( _byte . hex ( ) , 2 ) ) # Socket Number _sock = ...
def client_secrets ( cls , client_id ) : """Get the client ' s secrets using the client _ id : param client _ id : the client ID , e . g . a service ID : returns : list OAuthSecret instances"""
secrets = yield cls . view . get ( key = client_id , include_docs = True ) raise Return ( [ cls ( ** secret [ 'doc' ] ) for secret in secrets [ 'rows' ] ] )
def globfilter ( filenames , patterns , * , flags = 0 ) : """Filter names using pattern ."""
matches = [ ] flags = _flag_transform ( flags ) unix = _wcparse . is_unix_style ( flags ) obj = _wcparse . compile ( _wcparse . split ( patterns , flags ) , flags ) for filename in filenames : if not unix : filename = util . norm_slash ( filename ) if obj . match ( filename ) : matches . append ...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'fonts' ) and self . fonts is not None : _dict [ 'fonts' ] = [ x . _to_dict ( ) for x in self . fonts ] if hasattr ( self , 'styles' ) and self . styles is not None : _dict [ 'styles' ] = [ x . _to_dict ( ) for x in self . styles ] return _dict
def all_tags_of_type ( self , type_or_types , recurse_into_sprites = True ) : """Generator for all tags of the given type _ or _ types . Generates in breadth - first order , optionally including all sub - containers ."""
for t in self . tags : if isinstance ( t , type_or_types ) : yield t if recurse_into_sprites : for t in self . tags : # recurse into nested sprites if isinstance ( t , SWFTimelineContainer ) : for containedtag in t . all_tags_of_type ( type_or_types ) : yield containe...
def teams ( self , name = None , id = None , is_hidden = False , ** kwargs ) : """Teams of KE - chain . Provide a list of : class : ` Team ` s of KE - chain . You can filter on teamname or id or any other advanced filter . : param name : ( optional ) teamname to filter : type name : basestring or None : par...
request_params = { 'name' : name , 'id' : id , 'is_hidden' : is_hidden } if kwargs : request_params . update ( ** kwargs ) r = self . _request ( 'GET' , self . _build_url ( 'teams' ) , params = request_params ) if r . status_code != requests . codes . ok : # pragma : no cover raise NotFoundError ( "Could not fi...
def _redact_secret ( data : Union [ Dict , List ] , ) -> Union [ Dict , List ] : """Modify ` data ` in - place and replace keys named ` secret ` ."""
if isinstance ( data , dict ) : stack = [ data ] else : stack = [ ] while stack : current = stack . pop ( ) if 'secret' in current : current [ 'secret' ] = '<redacted>' else : stack . extend ( value for value in current . values ( ) if isinstance ( value , dict ) ) return data
def change_screens ( self ) : """Change to the next tool to edit or back to MAIN form"""
if self . settings [ 'next_tool' ] : self . parentApp . change_form ( self . settings [ 'next_tool' ] ) else : self . parentApp . change_form ( 'MAIN' )
def in_reply_to ( self ) -> Optional [ UnstructuredHeader ] : """The ` ` In - Reply - To ` ` header ."""
try : return cast ( UnstructuredHeader , self [ b'in-reply-to' ] [ 0 ] ) except ( KeyError , IndexError ) : return None
def default_distdiff_options ( updates = None ) : """generate an options object with the appropriate default values in place for API usage of distdiff features . overrides is an optional dictionary which will be used to update fields on the options object ."""
parser = create_optparser ( ) options = parser . parse_args ( list ( ) ) if updates : # pylint : disable = W0212 options . _update_careful ( updates ) return options
def make_ioc ( name = None , description = 'Automatically generated IOC' , author = 'IOC_api' , links = None , keywords = None , iocid = None ) : """This generates all parts of an IOC , but without any definition . This is a helper function used by _ _ init _ _ . : param name : string , Name of the ioc : para...
root = ioc_et . make_ioc_root ( iocid ) root . append ( ioc_et . make_metadata_node ( name , description , author , links , keywords ) ) metadata_node = root . find ( 'metadata' ) top_level_indicator = make_indicator_node ( 'OR' ) parameters_node = ( ioc_et . make_parameters_node ( ) ) root . append ( ioc_et . make_cri...
def element ( self , inp = None ) : """Create a new element . For more specific control , use set [ i ] . element ( ) to pick which subset to use ."""
if inp is None : return self . elements [ 0 ] elif inp in self . elements : return inp else : raise ValueError ( 'cannot convert inp {} to element in {}' '' . format ( inp , self ) )
def hypo_list ( nodes ) : """: param nodes : a hypoList node with N hypocenter nodes : returns : a numpy array of shape ( N , 3 ) with strike , dip and weight"""
check_weights ( nodes ) data = [ ] for node in nodes : data . append ( [ node [ 'alongStrike' ] , node [ 'downDip' ] , node [ 'weight' ] ] ) return numpy . array ( data , float )
def Grant ( self ) : """Create the Approval object and notify the Approval Granter ."""
approvals_root_urn = aff4 . ROOT_URN . Add ( "ACL" ) . Add ( self . subject_urn . Path ( ) ) . Add ( self . delegate ) children_urns = list ( aff4 . FACTORY . ListChildren ( approvals_root_urn ) ) if not children_urns : raise access_control . UnauthorizedAccess ( "No approval found for user %s" % utils . SmartStr (...
def get_assessments_taken_by_search ( self , assessment_taken_query , assessment_taken_search ) : """Pass through to provider AssessmentTakenSearchSession . get _ assessments _ taken _ by _ search"""
# Implemented from azosid template for - # osid . resource . ResourceSearchSession . get _ resources _ by _ search _ template if not self . _can ( 'search' ) : raise PermissionDenied ( ) return self . _provider_session . get_assessments_taken_by_search ( assessment_taken_query , assessment_taken_search )
def _generate_provenance ( self ) : """Function to generate provenance at the end of the IF ."""
# noinspection PyTypeChecker exposure = definition ( self . _provenance [ 'exposure_keywords' ] [ 'exposure' ] ) # noinspection PyTypeChecker hazard = definition ( self . _provenance [ 'hazard_keywords' ] [ 'hazard' ] ) # noinspection PyTypeChecker hazard_category = definition ( self . _provenance [ 'hazard_keywords' ]...
def listar_healtchcheck_expect_distinct ( self ) : """Get all expect _ string . : return : Dictionary with the following structure : { ' healthcheck _ expect ' : [ ' expect _ string ' : < expect _ string > , . . . demais healthcheck _ expects . . . ] } : raise InvalidParameterError : Identifier is null an...
url = 'healthcheckexpect/distinct/busca/' code , xml = self . submit ( None , 'GET' , url ) return self . response ( code , xml )
def _viewEntryItem ( self , item = None , * dum ) : """Pops up the viewer dialog for the entry associated with the given item . If ' item ' is None , looks for a selected item in the listview . The dum arguments are for connecting this to QTreeWidget signals such as doubleClicked ( ) ."""
# if item not set , look for selected items in listview . Only 1 must be selected . select = True if item is None : selected = [ item for item in self . etw . iterator ( self . etw . Iterator . Selected ) if item . _ientry is not None ] if len ( selected ) != 1 : return item = selected [ 0 ] sel...
def expect_optional_keyword ( lexer : Lexer , value : str ) -> Optional [ Token ] : """Expect the next token optionally to be a given keyword . If the next token is a given keyword , return that token after advancing the lexer . Otherwise , do not change the parser state and return None ."""
token = lexer . token if token . kind == TokenKind . NAME and token . value == value : lexer . advance ( ) return token return None
def _check_hyperedge_id_consistency ( self ) : """Consistency Check 4 : check for misplaced hyperedge ids : raises : ValueError - - detected inconsistency among dictionaries"""
# Get list of hyperedge _ ids from the hyperedge attributes dict hyperedge_ids_from_attributes = set ( self . _hyperedge_attributes . keys ( ) ) # get hyperedge ids in the forward star forward_star_hyperedge_ids = set ( ) for hyperedge_id_set in self . _forward_star . values ( ) : forward_star_hyperedge_ids . updat...
def get_urls ( self ) : """Returns a list of urls including all NestedSimpleRouter urls"""
ret = super ( SimpleRouter , self ) . get_urls ( ) for router in self . nested_routers : ret . extend ( router . get_urls ( ) ) return ret
def quorum ( name , ** kwargs ) : '''Quorum state This state checks the mon daemons are in quorum . It does not alter the cluster but can be used in formula as a dependency for many cluster operations . Example usage in sls file : . . code - block : : yaml quorum : sesceph . quorum : - require : -...
parameters = _ordereddict2dict ( kwargs ) if parameters is None : return _error ( name , "Invalid parameters:%s" ) if __opts__ [ 'test' ] : return _test ( name , "cluster quorum" ) try : cluster_quorum = __salt__ [ 'ceph.cluster_quorum' ] ( ** parameters ) except ( CommandExecutionError , CommandNotFoundErr...
def add_freeform_sp ( self , x , y , cx , cy ) : """Append a new freeform ` p : sp ` with specified position and size ."""
shape_id = self . _next_shape_id name = 'Freeform %d' % ( shape_id - 1 , ) sp = CT_Shape . new_freeform_sp ( shape_id , name , x , y , cx , cy ) self . insert_element_before ( sp , 'p:extLst' ) return sp
def _load_config_file ( self ) : """Loads config . yaml from filesystem and applies some values which were set via ENV"""
with open ( self . _config_file ) as f : config = yaml . safe_load ( f ) patch_config ( config , self . __environment_configuration ) return config
def indicator ( self ) : """Produce the spinner ."""
while self . run : try : size = self . work_q . qsize ( ) except Exception : note = 'Please wait ' else : note = 'Number of Jobs in Queue = %s ' % size if self . msg : note = '%s %s' % ( note , self . msg ) for item in [ '|' , '/' , '-' , '\\' ] : sys . stdout...
def check_and_format_logs_params ( start , end , tail ) : """Helper to read the params for the logs command"""
def _decode_duration_type ( duration_type ) : durations = { 'm' : 'minutes' , 'h' : 'hours' , 'd' : 'days' , 'w' : 'weeks' } return durations [ duration_type ] if not start : if tail : start_dt = maya . now ( ) . subtract ( seconds = 300 ) . datetime ( naive = True ) else : start_dt = ma...
def temporal_from_resource ( resource ) : '''Parse a temporal coverage from a RDF class / resource ie . either : - a ` dct : PeriodOfTime ` with schema . org ` startDate ` and ` endDate ` properties - an inline gov . uk Time Interval value - an URI reference to a gov . uk Time Interval ontology http : / / r...
if isinstance ( resource . identifier , URIRef ) : # Fetch remote ontology if necessary g = Graph ( ) . parse ( str ( resource . identifier ) ) resource = g . resource ( resource . identifier ) if resource . value ( SCHEMA . startDate ) : return db . DateRange ( start = resource . value ( SCHEMA . startDate...
def update_dimension ( self , key , value , description = None , custom_properties = None , tags = None , ** kwargs ) : """update a dimension Args : key ( string ) : key of the dimension value ( string ) : value of the dimension description ( optional [ string ] ) : a description custom _ properties ( opt...
data = { 'description' : description or '' , 'customProperties' : custom_properties or { } , 'tags' : tags or [ ] , 'key' : key , 'value' : value } resp = self . _put ( self . _u ( self . _DIMENSION_ENDPOINT_SUFFIX , key , value ) , data = data , ** kwargs ) resp . raise_for_status ( ) return resp . json ( )
def parameter_type ( self , parameter_type ) : """Sets the parameter _ type of this DashboardParameterValue . : param parameter _ type : The parameter _ type of this DashboardParameterValue . # noqa : E501 : type : str"""
allowed_values = [ "SIMPLE" , "LIST" , "DYNAMIC" ] # noqa : E501 if parameter_type not in allowed_values : raise ValueError ( "Invalid value for `parameter_type` ({0}), must be one of {1}" # noqa : E501 . format ( parameter_type , allowed_values ) ) self . _parameter_type = parameter_type
def pretty ( price , currency , * , abbrev = True , trim = True ) : """return format price with symbol . Example format ( 100 , ' USD ' ) return ' $ 100' pretty ( price , currency , abbrev = True , trim = False ) abbrev : True : print value + symbol . Symbol can either be placed before or after value False ...
currency = validate_currency ( currency ) price = validate_price ( price ) space = '' if nospace ( currency ) else ' ' fmtstr = '' if trim : fmtstr = '{:0,.{x}f}' . format ( price , x = decimals ( currency ) ) . rstrip ( '0' ) . rstrip ( '.' ) else : fmtstr = '{:0,}' . format ( price ) . rstrip ( '0' ) . rstrip...
def amazon_s3_url ( self , sat , band ) : """Return an amazon s3 url the contains the scene and band provided . : param sat : Expects an object created by scene _ interpreter method : type sat : dict : param filename : The filename that has to be downloaded from Amazon : type filename : String : r...
if band != 'MTL' : filename = '%s_B%s.TIF' % ( sat [ 'scene' ] , band ) else : filename = '%s_%s.txt' % ( sat [ 'scene' ] , band ) return url_builder ( [ self . s3 , sat [ 'sat' ] , sat [ 'path' ] , sat [ 'row' ] , sat [ 'scene' ] , filename ] )
def add_done_callback ( self , fn ) : """Attach the provided callable to the future . The provided function is called , with this future as its only argument , when the future finishes running ."""
if self . done ( ) : return fn ( self ) self . _callbacks . append ( fn )
def login_or_register ( client : GMatrixClient , signer : Signer , prev_user_id : str = None , prev_access_token : str = None , ) -> User : """Login to a Raiden matrix server with password and displayname proof - of - keys - Username is in the format : 0x < eth _ address > ( . < suffix > ) ? , where the suffix is...
server_url = client . api . base_url server_name = urlparse ( server_url ) . netloc base_username = to_normalized_address ( signer . address ) _match_user = re . match ( f'^@{re.escape(base_username)}.*:{re.escape(server_name)}$' , prev_user_id or '' , ) if _match_user : # same user as before log . debug ( 'Trying ...
def loop_forever ( self , timeout = 1.0 , max_packets = 1 , retry_first_connection = False ) : """This function call loop ( ) for you in an infinite blocking loop . It is useful for the case where you only want to run the MQTT client loop in your program . loop _ forever ( ) will handle reconnecting for you ....
run = True while run : if self . _state == mqtt_cs_connect_async : try : self . reconnect ( ) except socket . error : if not retry_first_connection : raise self . _easy_log ( MQTT_LOG_DEBUG , "Connection failed, retrying" ) self . _back...
def mavlink_packet ( self , m ) : '''handle incoming mavlink packet'''
type = m . get_type ( ) if type in [ 'COMMAND_ACK' ] : if m . command == mavutil . mavlink . MAV_CMD_DO_GO_AROUND : if ( m . result == 0 and self . abort_ack_received == False ) : self . say ( "Landing Abort Command Successfully Sent." ) self . abort_ack_received = True elif ...
def in_chain ( cls , client , chain_id , expiration_dates = [ ] ) : """fetch all option instruments in an options chain - expiration _ dates = optionally scope"""
request_url = "https://api.robinhood.com/options/instruments/" params = { "chain_id" : chain_id , "expiration_dates" : "," . join ( expiration_dates ) } data = client . get ( request_url , params = params ) results = data [ 'results' ] while data [ 'next' ] : data = client . get ( data [ 'next' ] ) results . ex...
def make_country_nationality_list ( cts , ct_file ) : """Combine list of countries and list of nationalities"""
countries = pd . read_csv ( ct_file ) nationality = dict ( zip ( countries . nationality , countries . alpha_3_code ) ) both_codes = { ** nationality , ** cts } return both_codes
def _fuse_last ( working_list , homology , tm ) : '''With one sequence left , attempt to fuse it to itself . : param homology : length of terminal homology in bp . : type homology : int : raises : AmbiguousGibsonError if either of the termini are palindromic ( would bind self - self ) . ValueError if the ...
# 1 . Construct graph on self - self # ( destination , size , strand1 , strand2) pattern = working_list [ 0 ] def graph_strands ( strand1 , strand2 ) : matchlen = homology_report ( pattern , pattern , strand1 , strand2 , cutoff = homology , min_tm = tm , top_two = True ) if matchlen : # Ignore full - sequence m...
def delete_resource_view ( self , resource_view ) : # type : ( Union [ ResourceView , Dict , str ] ) - > None """Delete a resource view from the resource and HDX Args : resource _ view ( Union [ ResourceView , Dict , str ] ) : Either a resource view id or resource view metadata either from a ResourceView object...
if isinstance ( resource_view , str ) : if is_valid_uuid ( resource_view ) is False : raise HDXError ( '%s is not a valid resource view id!' % resource_view ) resource_view = ResourceView ( { 'id' : resource_view } , configuration = self . configuration ) else : resource_view = self . _get_resource_...
def setVisible ( self , state ) : """Sets whether or not this connection ' s local visibility should be on . : param state | , bool >"""
self . _visible = state super ( XNodeConnection , self ) . setVisible ( self . isVisible ( ) )
def shutdown_all ( self ) : """For testing use , arrange for all connections to be shut down ."""
self . _lock . acquire ( ) try : for context in list ( self . _key_by_context ) : self . _shutdown_unlocked ( context ) finally : self . _lock . release ( )
def remove ( self , val ) : """Remove first occurrence of * val * . Raises ValueError if * val * is not present ."""
_maxes = self . _maxes if not _maxes : raise ValueError ( '{0} not in list' . format ( repr ( val ) ) ) key = self . _key ( val ) pos = bisect_left ( _maxes , key ) if pos == len ( _maxes ) : raise ValueError ( '{0} not in list' . format ( repr ( val ) ) ) _keys = self . _keys _lists = self . _lists idx = bisec...
def before_update ( mapper , conn , target ) : """Set the column id number based on the table number and the sequence id for the column ."""
assert target . datatype or target . valuetype target . name = Column . mangle_name ( target . name ) Column . update_number ( target )
def get ( self , key , value ) : """Gets an element from an index under a given key - value pair @ params key : Index key string @ params value : Index value string @ returns A generator of Vertex or Edge objects"""
for element in self . neoindex [ key ] [ value ] : if self . indexClass == "vertex" : yield Vertex ( element ) elif self . indexClass == "edge" : yield Edge ( element ) else : raise TypeError ( self . indexClass )
def _delete ( self , bits , pos ) : """Delete bits at pos ."""
assert 0 <= pos <= self . len assert pos + bits <= self . len if not pos : # Cutting bits off at the start . self . _truncatestart ( bits ) return if pos + bits == self . len : # Cutting bits off at the end . self . _truncateend ( bits ) return if pos > self . len - pos - bits : # More bits before cut p...
def load ( self ) : """Load metafile into client ."""
if not self . ns . info_hash and not self . parse ( ) : return self . addinfo ( ) # TODO : dry _ run try : # TODO : Scrub metafile if requested # Determine target state start_it = self . job . config . load_mode . lower ( ) in ( "start" , "started" ) queue_it = self . job . config . queued if "start" in...
def __edit_line ( line , code , code_obj ) : # pylint : disable = R0201 """Edit a line with one code object built in the ctor ."""
try : # pylint : disable = eval - used result = eval ( code_obj , globals ( ) , locals ( ) ) except TypeError as ex : log . error ( "failed to execute %s: %s" , code , ex ) raise if result is None : log . error ( "cannot process line '%s' with %s" , line , code ) raise RuntimeError ( 'failed to proc...
def start ( self , target = None , args = None , kwargs = None , advices = None , exec_ctx = None , ctx = None ) : """Start to proceed this Joinpoint in initializing target , its arguments and advices . Call self . proceed at the end . : param callable target : new target to use in proceeding . self . target by...
# init target and _ interception if not None as set _ target method do if target is not None : self . set_target ( target = target , ctx = ctx ) # init args if not None if args is not None : self . args = args # init kwargs if not None if kwargs is not None : self . kwargs = kwargs # get advices to process ...
def _expectation ( p , lin_kern , feat1 , rbf_kern , feat2 , nghp = None ) : """Compute the expectation : expectation [ n ] = < Ka _ { Z1 , x _ n } Kb _ { x _ n , Z2 } > _ p ( x _ n ) - K _ lin _ { . , . } : : Linear kernel - K _ rbf _ { . , . } : : RBF kernel Different Z1 and Z2 are handled if p is diagona...
return tf . matrix_transpose ( expectation ( p , ( rbf_kern , feat2 ) , ( lin_kern , feat1 ) ) )
def download ( sc , age = 0 , path = 'reports' , ** args ) : '''Report Downloader The report downloader will pull reports down from SecurityCenter based on the conditions provided to the path provided . sc = SecurityCenter5 object age = number of days old the report may be to be included in the search . ...
# if the download path doesn ' t exist , we need to create it . if not os . path . exists ( path ) : logger . debug ( 'report path didn\'t exist. creating it.' ) os . makedirs ( path ) # Now we will need to comuter the timestamp for the date that the age has # apecified . The API expects this in a unix timestam...
def get_time ( self ) : '''get time , using ATTITUDE . time _ boot _ ms if in SITL with SIM _ SPEEDUP ! = 1'''
systime = time . time ( ) - self . mpstate . start_time_s if not self . mpstate . is_sitl : return systime try : speedup = int ( self . get_mav_param ( 'SIM_SPEEDUP' , 1 ) ) except Exception : return systime if speedup != 1 : return self . mpstate . attitude_time_s return systime
def verifies ( self , hash , signature ) : """Verify that signature is a valid signature of hash . Return True if the signature is valid ."""
# From X9.62 J . 3.1. G = self . generator n = G . order ( ) r = signature . r s = signature . s if r < 1 or r > n - 1 : return False if s < 1 or s > n - 1 : return False c = numbertheory . inverse_mod ( s , n ) u1 = ( hash * c ) % n u2 = ( r * c ) % n xy = u1 * G + u2 * self . point v = xy . x ( ) % n return v...
def _write_header ( name , header , required , stream , encoder , strict = False ) : """Write AMF message header . @ param name : Name of the header . @ param header : Header value . @ param required : Whether understanding this header is required ( ? ) . @ param stream : L { BufferedByteStream < pyamf . ut...
stream . write_ushort ( len ( name ) ) stream . write_utf8_string ( name ) stream . write_uchar ( required ) write_pos = stream . tell ( ) stream . write_ulong ( 0 ) old_pos = stream . tell ( ) encoder . writeElement ( header ) new_pos = stream . tell ( ) if strict : stream . seek ( write_pos ) stream . write_u...
def memory_usage ( self , string = False ) : """Get the memory usage estimate of the container . Args : string ( bool ) : Human readable string ( default false ) See Also : : func : ` ~ exa . core . container . Container . info `"""
if string : n = getsizeof ( self ) return ' ' . join ( ( str ( s ) for s in convert_bytes ( n ) ) ) return self . info ( ) [ 'size' ]