signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_request_kwargs ( self ) : """Construct keyword parameters for Session . request ( ) and Session . resolve _ redirects ( ) ."""
kwargs = dict ( stream = True , timeout = self . aggregate . config [ "timeout" ] ) if self . proxy : kwargs [ "proxies" ] = { self . proxytype : self . proxy } if self . scheme == u"https" and self . aggregate . config [ "sslverify" ] : kwargs [ 'verify' ] = self . aggregate . config [ "sslverify" ] else : ...
def _check_available_disk_space ( self , project ) : """Sends a warning notification if disk space is getting low . : param project : project instance"""
try : used_disk_space = psutil . disk_usage ( project . path ) . percent except FileNotFoundError : log . warning ( 'Could not find "{}" when checking for used disk space' . format ( project . path ) ) return # send a warning if used disk space is > = 90% if used_disk_space >= 90 : message = 'Only {}% o...
def build_skos_concepts ( self ) : """2015-08-19 : first draft"""
self . all_skos_concepts = [ ] # @ todo : keep adding ? qres = self . sparqlHelper . getSKOSInstances ( ) # print ( " rdflib query done " ) for candidate in qres : test_existing_cl = self . get_skos ( uri = candidate [ 0 ] ) if not test_existing_cl : # create it self . all_skos_concepts += [ OntoSKOSCon...
def dump ( d , fp , indent = 4 , spacer = " " , quote = '"' , newlinechar = "\n" , end_comment = False ) : """Write d ( the Mapfile dictionary ) as a formatted stream to fp Parameters d : dict A Python dictionary based on the the mappyfile schema fp : file A file - like object indent : int The number ...
map_string = _pprint ( d , indent , spacer , quote , newlinechar , end_comment ) fp . write ( map_string )
def _set_ldp_sync_info ( self , v , load = False ) : """Setter method for ldp _ sync _ info , mapped from YANG variable / isis _ state / interface _ detail / isis _ intf / ldp _ sync _ info ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ ldp _ sync _ info ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = ldp_sync_info . ldp_sync_info , is_container = 'container' , presence = False , yang_name = "ldp-sync-info" , rest_name = "ldp-sync-info" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods ,...
def openorders ( ctx , account ) : """List open orders of an account"""
account = Account ( account or config [ "default_account" ] , bitshares_instance = ctx . bitshares ) t = [ [ "Price" , "Quote" , "Base" , "ID" ] ] for o in account . openorders : t . append ( [ "{:f} {}/{}" . format ( o [ "price" ] , o [ "base" ] [ "asset" ] [ "symbol" ] , o [ "quote" ] [ "asset" ] [ "symbol" ] , )...
def check_type ( self ) : """Make sure each stochastic has a correct type , and identify discrete stochastics ."""
self . isdiscrete = { } for stochastic in self . stochastics : if stochastic . dtype in integer_dtypes : self . isdiscrete [ stochastic ] = True elif stochastic . dtype in bool_dtypes : raise ValueError ( 'Binary stochastics not supported by AdaptativeMetropolis.' ) else : self . isd...
def safe_dump ( data , abspath , indent_format = False , float_precision = None , ensure_ascii = True , enable_verbose = True ) : """A stable version of : func : ` dump ` , this method will silently overwrite existing file . There ' s a issue with : func : ` dump ` : If your program is interrupted while writi...
abspath = lower_ext ( str ( abspath ) ) abspath_temp = "%s.tmp" % abspath dump ( data , abspath_temp , indent_format = indent_format , float_precision = float_precision , ensure_ascii = ensure_ascii , overwrite = True , enable_verbose = enable_verbose ) shutil . move ( abspath_temp , abspath )
def get_spider_list ( self , project_name , version = None ) : """Get the list of spiders available in the last ( unless overridden ) version of some project . : param project _ name : the project name : param version : the version of the project to examine : return : a dictionary that spider name list exam...
url , method = self . command_set [ 'listspiders' ] [ 0 ] , self . command_set [ 'listspiders' ] [ 1 ] data = { } data [ 'project' ] = project_name if version is not None : data [ '_version' ] = version response = http_utils . request ( url , method_type = method , data = data , return_type = http_utils . RETURN_JS...
def query ( self ) : """Returns the query that is defined by this current panel . : return < orb . Query >"""
joiner = self . currentJoiner ( ) query = Query ( ) for entry in self . entries ( ) : if joiner == QueryCompound . Op . And : query &= entry . query ( ) else : query |= entry . query ( ) query . setName ( self . uiNameTXT . text ( ) ) return query
def to_db ( catchment , session , method = 'create' , autocommit = False ) : """Load catchment object into the database . A catchment / station number ( : attr : ` catchment . id ` ) must be provided . If : attr : ` method ` is set to ` update ` , any existing catchment in the database with the same catchment n...
if not catchment . id : raise ValueError ( "Catchment/station number (`catchment.id`) must be set." ) if method == 'create' : session . add ( catchment ) elif method == 'update' : session . merge ( catchment ) else : raise ValueError ( "Method `{}` invalid. Use either `create` or `update`." ) if autocom...
def get_worksheets_section ( self ) : """Returns the section dictionary related with Worksheets , that contains some informative panels ( like WS to be verified , WS with results pending , etc . )"""
out = [ ] bc = getToolByName ( self . context , CATALOG_WORKSHEET_LISTING ) query = { 'portal_type' : "Worksheet" , } # Check if dashboard _ cookie contains any values to query # elements by query = self . _update_criteria_with_filters ( query , 'worksheets' ) # Active Worksheets ( all ) total = self . search_count ( q...
def from_array ( array ) : """Deserialize a new Sticker from a given dictionary . : return : new Sticker instance . : rtype : Sticker"""
if array is None or not array : return None # end if assert_type_or_raise ( array , dict , parameter_name = "array" ) from . stickers import MaskPosition data = { } data [ 'file_id' ] = u ( array . get ( 'file_id' ) ) data [ 'width' ] = int ( array . get ( 'width' ) ) data [ 'height' ] = int ( array . get ( 'height...
def incrby ( self , key , increment ) : """Increment the integer value of a key by the given amount . : raises TypeError : if increment is not int"""
if not isinstance ( increment , int ) : raise TypeError ( "increment must be of type int" ) return self . execute ( b'INCRBY' , key , increment )
def _load_json_result ( self , conf , compile_classpath , coursier_cache_path , invalidation_check , pants_jar_path_base , result , override_classifiers = None ) : """Given a coursier run result , load it into compile _ classpath by target . : param compile _ classpath : ` ClasspathProducts ` that will be modifie...
# Parse the coursier result flattened_resolution = self . _extract_dependencies_by_root ( result ) coord_to_resolved_jars = self . _map_coord_to_resolved_jars ( result , coursier_cache_path , pants_jar_path_base ) # Construct a map from org : name to the reconciled org : name : version coordinate # This is used when th...
def tokenize ( self , value ) : """Split the incoming value into tokens and process each token , optionally stemming or running metaphone . : returns : A ` ` dict ` ` mapping token to score . The score is based on the relative frequency of the word in the document ."""
words = self . split_phrase ( decode ( value ) . lower ( ) ) if self . _stopwords : words = [ w for w in words if w not in self . _stopwords ] if self . _min_word_length : words = [ w for w in words if len ( w ) >= self . _min_word_length ] fraction = 1. / ( len ( words ) + 1 ) # Prevent division by zero . # Ap...
def get_reddit ( ) : """Returns the reddit dataset , downloading locally if necessary . This dataset was released here : https : / / www . reddit . com / r / redditdev / comments / dtg4j / want _ to _ help _ reddit _ build _ a _ recommender _ a _ public / and contains 23M up / down votes from 44K users on 3.4...
filename = os . path . join ( _download . LOCAL_CACHE_DIR , "reddit.hdf5" ) if not os . path . isfile ( filename ) : log . info ( "Downloading dataset to '%s'" , filename ) _download . download_file ( URL , filename ) else : log . info ( "Using cached dataset at '%s'" , filename ) with h5py . File ( filenam...
def canon_did ( uri : str ) -> str : """Convert a URI into a DID if need be , left - stripping ' did : sov : ' if present . Return input if already a DID . Raise BadIdentifier for invalid input . : param uri : input URI or DID : return : corresponding DID"""
if ok_did ( uri ) : return uri if uri . startswith ( 'did:sov:' ) : rv = uri [ 8 : ] if ok_did ( rv ) : return rv raise BadIdentifier ( 'Bad specification {} does not correspond to a sovrin DID' . format ( uri ) )
def get_hash_for_filename ( filename , hashfile_path ) : """Return hash for filename in the hashfile ."""
filehash = '' with open ( hashfile_path , 'r' ) as stream : for _cnt , line in enumerate ( stream ) : if line . rstrip ( ) . endswith ( filename ) : filehash = re . match ( r'^[A-Za-z0-9]*' , line ) . group ( 0 ) break if filehash : return filehash raise AttributeError ( "Filenam...
def get_name_DID_info ( self , name ) : """Get a name ' s DID info Returns None if not found"""
db = get_db_state ( self . working_dir ) did_info = db . get_name_DID_info ( name ) if did_info is None : return { 'error' : 'No such name' , 'http_status' : 404 } return did_info
def list_cidr_ips_ipv6 ( cidr ) : '''Get a list of IPv6 addresses from a CIDR . CLI example : : salt myminion netaddress . list _ cidr _ ips _ ipv6 192.168.0.0/20'''
ips = netaddr . IPNetwork ( cidr ) return [ six . text_type ( ip . ipv6 ( ) ) for ip in list ( ips ) ]
def add_env ( url , saltenv ) : '''append ` saltenv ` to ` url ` as a query parameter to a ' salt : / / ' url'''
if not url . startswith ( 'salt://' ) : return url path , senv = parse ( url ) return create ( path , saltenv )
def human_and_00 ( X , y , model_generator , method_name ) : """AND ( false / false ) This tests how well a feature attribution method agrees with human intuition for an AND operation combined with linear effects . This metric deals specifically with the question of credit allocation for the following functio...
return _human_and ( X , model_generator , method_name , False , False )
def add_asn ( self , auth , attr ) : """Add AS number to NIPAP . * ` auth ` [ BaseAuth ] AAA options . * ` attr ` [ asn _ attr ] ASN attributes . Returns a dict describing the ASN which was added . This is the documentation of the internal backend function . It ' s exposed over XML - RPC , please also...
self . _logger . debug ( "add_asn called; attr: %s" % unicode ( attr ) ) # sanity check - do we have all attributes ? req_attr = [ 'asn' , ] allowed_attr = [ 'asn' , 'name' ] self . _check_attr ( attr , req_attr , allowed_attr ) insert , params = self . _sql_expand_insert ( attr ) sql = "INSERT INTO ip_net_asn " + inse...
def _validate_completeness ( self ) : """Verify that the actual file manifests match the files in the data directory"""
errors = list ( ) # First we ' ll make sure there ' s no mismatch between the filesystem # and the list of files in the manifest ( s ) only_in_manifests , only_on_fs , only_in_fetch = self . compare_manifests_with_fs_and_fetch ( ) for path in only_in_manifests : e = FileMissing ( path ) LOGGER . warning ( force...
def revoke_auth ( preserve_minion_cache = False ) : '''The minion sends a request to the master to revoke its own key . Note that the minion session will be revoked and the minion may not be able to return the result of this command back to the master . If the ' preserve _ minion _ cache ' flag is set to True...
masters = list ( ) ret = True if 'master_uri_list' in __opts__ : for master_uri in __opts__ [ 'master_uri_list' ] : masters . append ( master_uri ) else : masters . append ( __opts__ [ 'master_uri' ] ) for master in masters : channel = salt . transport . client . ReqChannel . factory ( __opts__ , ma...
def cprint ( text , fg = Color . normal , bg = Color . normal , fg_dark = False , bg_dark = False , underlined = False , parse = False , ) : """Print string in to stdout using colored font . See L { set _ color } for more details about colors . Args : text ( str ) : Text that needs to be printed ."""
if parse : color_re = Color . color_re ( ) lines = text . splitlines ( ) count = len ( lines ) for i , line in enumerate ( lines ) : previous = 0 end = len ( line ) for match in color_re . finditer ( line ) : sys . stdout . write ( line [ previous : match . start ( ) ...
def hacking_has_license ( physical_line , filename , lines , line_number ) : """Check for Apache 2.0 license . H102 license header not found"""
# don ' t work about init files for now # TODO ( sdague ) : enforce license in init file if it ' s not empty of content license_found = False # skip files that are < 10 lines , which isn ' t enough for a license to fit # this allows us to handle empty files , as well as not fail on the Okay # doctests . if line_number ...
def before_all ( context ) : """Setup before all tests . Initialize the logger framework . : param context : test context ."""
lf = LoggerFactory ( config_file = '../features/resources/test_config.yaml' ) lf . initialize ( ) ll = lf . get_instance ( 'environment' ) ll . info ( 'Logger initialized: {}' . format ( lf . config ) ) ll . info ( 'Initial test context: {}' . format ( context ) )
def as_list ( self , decode = False ) : """Return a list of items in the array ."""
return [ _decode ( i ) for i in self ] if decode else list ( self )
def _hid_enumerate ( vendor_id = 0 , product_id = 0 ) : """Enumerates all the hid devices for VID : PID . Returns a list of ` HIDDevice ` objects . If vid is 0 , then match any vendor id . Similarly , if pid is 0, match any product id . If both are zero , enumerate all HID devices ."""
start = hidapi . hid_enumerate ( vendor_id , product_id ) result = [ ] cur = ffi . new ( "struct hid_device_info*" ) ; cur = start # Copy everything into python list while cur != ffi . NULL : result . append ( HIDDevice ( cur ) ) cur = cur . next # Free the C memory hidapi . hid_free_enumeration ( start ) retur...
def get_sanitized_endpoint ( url ) : """Sanitize an endpoint , as removing unneeded parameters"""
# sanitize esri sanitized_url = url . rstrip ( ) esri_string = '/rest/services' if esri_string in url : match = re . search ( esri_string , sanitized_url ) sanitized_url = url [ 0 : ( match . start ( 0 ) + len ( esri_string ) ) ] return sanitized_url
def _update_options ( model , connection = None ) : """Updates the table options for the given model if necessary . : param model : The model to update . : param connection : Name of the connection to use : return : ` True ` , if the options were modified in Cassandra , ` False ` otherwise . : rtype : boo...
ks_name = model . _get_keyspace ( ) msg = format_log_context ( "Checking %s for option differences" , keyspace = ks_name , connection = connection ) log . debug ( msg , model ) model_options = model . __options__ or { } table_meta = _get_table_metadata ( model , connection = connection ) # go to CQL string first to nor...
def update_shortcut_settings ( self ) : """Creates the list store for the shortcuts"""
self . shortcut_list_store . clear ( ) shortcuts = self . gui_config_model . get_current_config_value ( "SHORTCUTS" , use_preliminary = True , default = { } ) actions = sorted ( shortcuts . keys ( ) ) for action in actions : keys = shortcuts [ action ] self . shortcut_list_store . append ( ( str ( action ) , st...
def check_overlap ( a , b ) : """Check for wavelength overlap between two spectra . . . note : : Generalized from : meth : ` pysynphot . spectrum . SpectralElement . check _ overlap ` . Parameters a , b : ` ~ pysynphot . spectrum . SourceSpectrum ` or ` ~ pysynphot . spectrum . SpectralElement ` Typical...
if a . isAnalytic or b . isAnalytic : # then it ' s defined everywhere result = 'full' else : # get the wavelength arrays waves = list ( ) for x in ( a , b ) : if hasattr ( x , 'throughput' ) : wv = x . wave [ np . where ( x . throughput != 0 ) ] elif hasattr ( x , 'flux' ) : ...
def __update_info ( self ) : """Updates " visualization options " and " file info " areas ."""
from f311 import explorer as ex import f311 t = self . tableWidget z = self . listWidgetVis z . clear ( ) classes = self . __vis_classes = [ ] propss = self . __lock_get_current_propss ( ) npp = len ( propss ) s0 , s1 = "" , "" if npp == 1 : p = propss [ 0 ] # Visualization options if p . flag_scanned : ...
def vertex_array ( self , program , content , index_buffer = None , index_element_size = 4 , * , skip_errors = False ) -> 'VertexArray' : '''Create a : py : class : ` VertexArray ` object . Args : program ( Program ) : The program used when rendering . content ( list ) : A list of ( buffer , format , attribut...
members = program . _members index_buffer_mglo = None if index_buffer is None else index_buffer . mglo content = tuple ( ( a . mglo , b ) + tuple ( getattr ( members . get ( x ) , 'mglo' , None ) for x in c ) for a , b , * c in content ) res = VertexArray . __new__ ( VertexArray ) res . mglo , res . _glo = self . mglo ...
def predictions ( self ) : """Generator that yields prediction objects from an API response ."""
for prediction in self . api . predictions ( vid = self . vid ) [ 'prd' ] : pobj = Prediction . fromapi ( self . api , prediction ) pobj . _busobj = self yield pobj
def ic ( ctext ) : '''takes ciphertext , calculates index of coincidence .'''
counts = ngram_count ( ctext , N = 1 ) icval = 0 for k in counts . keys ( ) : icval += counts [ k ] * ( counts [ k ] - 1 ) icval /= ( len ( ctext ) * ( len ( ctext ) - 1 ) ) return icval
def connect_post_namespaced_pod_portforward ( self , name , namespace , ** kwargs ) : """connect POST requests to portforward of Pod This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . connect _ post _ namespaced ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . connect_post_namespaced_pod_portforward_with_http_info ( name , namespace , ** kwargs ) else : ( data ) = self . connect_post_namespaced_pod_portforward_with_http_info ( name , namespace , ** kwargs ) return data
def message ( self ) : """Read mail , parse it and return a Message instance ."""
logger . debug ( "Parsing mail at {} ..." . format ( self . path ) ) with open ( self . path , 'rb' ) as mail_file : if PY2 : message = email . message_from_file ( mail_file ) else : message = email . message_from_binary_file ( mail_file ) return message
def random_split ( dataset , prob = .5 ) : """Utility for performing a random split for text data that is already in bag - of - words format . For each ( word , count ) pair in a particular element , the counts are uniformly partitioned in either a training set or a test set . Parameters dataset : SArray ...
def grab_values ( x , train = True ) : if train : ix = 0 else : ix = 1 return dict ( [ ( key , value [ ix ] ) for key , value in six . iteritems ( x ) if value [ ix ] != 0 ] ) def word_count_split ( n , p ) : num_in_test = 0 for i in range ( n ) : if random . random ( ) < p :...
def association ( self , group_xid ) : """Add association using xid value . Args : group _ xid ( str ) : The external id of the Group to associate ."""
association = { 'groupXid' : group_xid } self . _indicator_data . setdefault ( 'associatedGroups' , [ ] ) . append ( association )
def query_trial ( request ) : """Rest API to query the trial info , with the given trial _ id . The url pattern should be like this : curl http : / / < server > : < port > / query _ trial ? trial _ id = < trial _ id > The response may be : " app _ url " : " None " , " trial _ status " : " TERMINATED " , ...
trial_id = request . GET . get ( "trial_id" ) trials = TrialRecord . objects . filter ( trial_id = trial_id ) . order_by ( "-start_time" ) if len ( trials ) == 0 : resp = "Unkonwn trial id %s.\n" % trials else : trial = trials [ 0 ] result = { "trial_id" : trial . trial_id , "job_id" : trial . job_id , "tri...
def get_parent_plate_value ( tree , node , value = None ) : """Recurse up the tree getting parent plate values : param tree : The tree : param node : The current node : param value : The initial plate value : return : The plate value as a list of tuples"""
if value is None : value = [ ] parent = tree . parent ( node . identifier ) if parent . is_root ( ) : # value . append ( ( parent . tag , parent . identifier ) ) return value value = PlateManager . get_parent_plate_value ( tree , parent , value ) if "." in parent . identifier : pass value . append ( ( paren...
def bounds ( self ) : """: return : List of tuples of all bounds on parameters ."""
bounds = [ ] for p in self . params : if p . fixed : if p . value >= 0.0 : bounds . append ( [ np . nextafter ( p . value , 0 ) , p . value ] ) else : bounds . append ( [ p . value , np . nextafter ( p . value , 0 ) ] ) else : bounds . append ( [ p . min , p . max...
def splitter ( lines , sep = "-=" , keep_idx = False ) : """Splits underlined blocks without indentation ( reStructuredText pattern ) . Parameters lines : A list of strings sep : Underline symbols . A line with only such symbols will be seen as a underlined one . keep _ idx : If False ( default ) , ...
separators = audiolazy . Stream ( idx - 1 for idx , el in enumerate ( lines ) if all ( char in sep for char in el ) and len ( el ) > 0 ) . append ( [ len ( lines ) ] ) first_idx = separators . copy ( ) . take ( ) blk_data = OrderedDict ( ) empty_count = iter ( audiolazy . count ( 1 ) ) next_empty = lambda : "--Empty--{...
def write ( self , title , data , output = None ) : '''Add a data to the current opened section . : return :'''
if not isinstance ( data , ( dict , list , tuple ) ) : data = { 'raw-content' : str ( data ) } output = output or self . __default_outputter if output != 'null' : try : if isinstance ( data , dict ) and 'return' in data : data = data [ 'return' ] content = self . _printout ( data , o...
def x10_command_type ( command ) : """Return the X10 command type from an X10 command ."""
command_type = X10CommandType . DIRECT if command in [ X10_COMMAND_ALL_UNITS_OFF , X10_COMMAND_ALL_LIGHTS_ON , X10_COMMAND_ALL_LIGHTS_OFF ] : command_type = X10CommandType . BROADCAST return command_type
def on_batch_end ( self , train , ** kwargs ) : "Take the stored results and puts it in ` self . stats `"
if train : self . stats . append ( self . hooks . stored )
def set_list_predicates ( self ) : """Reads through the rml mappings and determines all fields that should map to a list / array with a json output"""
results = self . rml . query ( """ SELECT DISTINCT ?subj_class ?list_field { ?bn rr:datatype rdf:List . ?bn rr:predicate ?list_field . ?s ?p ?bn . ?s rr:subjectMap ?sm_bn . ?sm_bn rr:class...
def launch ( self ) : """Make the script file and return the newly created job id"""
# Make script file # self . make_script ( ) # Do it # sbatch_out = sh . sbatch ( self . script_path ) jobs . expire ( ) # Message # print Color . i_blu + "SLURM:" + Color . end + " " + str ( sbatch_out ) , # Return id # self . id = int ( re . findall ( "Submitted batch job ([0-9]+)" , str ( sbatch_out ) ) [ 0 ] ) retur...
def setPrefix ( self , p , u = None ) : """Set the element namespace prefix . @ param p : A new prefix for the element . @ type p : basestring @ param u : A namespace URI to be mapped to the prefix . @ type u : basestring @ return : self @ rtype : L { Element }"""
self . prefix = p if p is not None and u is not None : self . addPrefix ( p , u ) return self
def on_close ( self ) : '''Called when client closes this connection . Cleanup is done here .'''
if self . id in self . funcserver . websocks : self . funcserver . websocks [ self . id ] = None ioloop = tornado . ioloop . IOLoop . instance ( ) ioloop . add_callback ( lambda : self . funcserver . websocks . pop ( self . id , None ) ) psession = self . funcserver . pysessions . get ( self . pysession_id ...
def arabic_digit_to_thai_digit ( text : str ) -> str : """: param str text : Text with Arabic digits such as ' 1 ' , ' 2 ' , ' 3' : return : Text with Arabic digits being converted to Thai digits such as ' ๑ ' , ' ๒ ' , ' ๓'"""
if not text or not isinstance ( text , str ) : return "" newtext = [ ] for ch in text : if ch in _arabic_thai : newtext . append ( _arabic_thai [ ch ] ) else : newtext . append ( ch ) return "" . join ( newtext )
def _get_keyid_by_gpg_key ( key_material ) : """Get a GPG key fingerprint by GPG key material . Gets a GPG key fingerprint ( 40 - digit , 160 - bit ) by the ASCII armor - encoded or binary GPG key material . Can be used , for example , to generate file names for keys passed via charm options . : param key _...
# Use the same gpg command for both Xenial and Bionic cmd = 'gpg --with-colons --with-fingerprint' ps = subprocess . Popen ( cmd . split ( ) , stdout = subprocess . PIPE , stderr = subprocess . PIPE , stdin = subprocess . PIPE ) out , err = ps . communicate ( input = key_material ) if six . PY3 : out = out . decode...
def check_lazy_load_subadres ( f ) : '''Decorator function to lazy load a : class : ` Subadres ` .'''
def wrapper ( * args ) : subadres = args [ 0 ] if ( subadres . _metadata is None or subadres . aard_id is None or subadres . huisnummer_id is None ) : log . debug ( 'Lazy loading Subadres %d' , subadres . id ) subadres . check_gateway ( ) s = subadres . gateway . get_subadres_by_id ( sub...
def get_sent ( self , * args , ** kwargs ) : """Return a get _ content generator for sent messages . The additional parameters are passed directly into : meth : ` . get _ content ` . Note : the ` url ` parameter cannot be altered ."""
return self . get_content ( self . config [ 'sent' ] , * args , ** kwargs )
def drum_status ( self , filter_supported : bool = True ) -> Dict [ str , Any ] : """Return the state of all drums ."""
drum_status = { } for color in self . COLOR_NAMES : try : drum_stat = self . data . get ( '{}_{}' . format ( SyncThru . DRUM , color ) , { } ) if filter_supported and drum_stat . get ( 'opt' , 0 ) == 0 : continue else : drum_status [ color ] = drum_stat except ( K...
def reset ( self ) : """Reset the connection"""
self . _request = None self . _response = None self . _transaction_id = uuid . uuid4 ( ) . hex
def import_from_path ( path ) : """Imports a package , module or attribute from path Thanks http : / / stackoverflow . com / a / 14050282/1267398 > > > import _ from _ path ( ' os . path ' ) < module ' posixpath ' . . . > > > import _ from _ path ( ' os . path . basename ' ) < function basename at . . . ...
try : return importlib . import_module ( path ) except ImportError : if '.' not in path : raise module_name , attr_name = path . rsplit ( '.' , 1 ) if not does_module_exist ( module_name ) : raise ImportError ( "No object found at '{}'" . format ( path ) ) mod = importlib . import_mo...
def update_table ( self , table_name , provisioned_throughput ) : """Updates the provisioned throughput for a given table . : type table _ name : str : param table _ name : The name of the table to update . : type provisioned _ throughput : dict : param provisioned _ throughput : A Python version of the P...
data = { 'TableName' : table_name , 'ProvisionedThroughput' : provisioned_throughput } json_input = json . dumps ( data ) return self . make_request ( 'UpdateTable' , json_input )
def set_end ( self , t ) : """Override the GPS end time ( and set the duration ) of this ScienceSegment . @ param t : new GPS end time ."""
self . __dur -= self . __end - t self . __end = t
def _get_save_wall_photo ( session , photo , server , hash , user_id = None , group_id = None ) : """https : / / vk . com / dev / photos . saveWallPhoto"""
if group_id < 0 : group_id = abs ( group_id ) response = session . fetch ( "photos.saveWallPhoto" , photo = photo , server = server , hash = hash , user_id = user_id , group_id = group_id ) [ 0 ] return response [ 'id' ] , response [ 'owner_id' ]
def get_all_breakpoints ( self ) : """Returns all breakpoint objects as a list of tuples . Each tuple contains : - Process global ID to which the breakpoint applies . - Thread global ID to which the breakpoint applies , or C { None } . - The L { Breakpoint } object itself . @ note : If you ' re only inter...
bplist = list ( ) # Get the code breakpoints . for ( pid , bp ) in self . get_all_code_breakpoints ( ) : bplist . append ( ( pid , None , bp ) ) # Get the page breakpoints . for ( pid , bp ) in self . get_all_page_breakpoints ( ) : bplist . append ( ( pid , None , bp ) ) # Get the hardware breakpoints . for ( t...
def open ( self ) : """Implementation of NAPALM method open ."""
try : connection = self . transport_class ( host = self . hostname , username = self . username , password = self . password , timeout = self . timeout , ** self . eapi_kwargs ) if self . device is None : self . device = pyeapi . client . Node ( connection , enablepwd = self . enablepwd ) # does not...
def parse_array ( array_string ) : """Parse an array string as returned by clickhouse . For example : " [ ' hello ' , ' world ' ] " = = > [ " hello " , " world " ] " [ 1,2,3 ] " = = > [ 1 , 2 , 3]"""
# Sanity check if len ( array_string ) < 2 or array_string [ 0 ] != '[' or array_string [ - 1 ] != ']' : raise ValueError ( 'Invalid array string: "%s"' % array_string ) # Drop opening brace array_string = array_string [ 1 : ] # Go over the string , lopping off each value at the beginning until nothing is left valu...
def get_task_config_fields ( config_class ) : """Get all configuration Fields from a Config class . Parameters config _ class : ` ` lsst . pipe . base . Config ` ` - type The configuration class ( not an instance ) corresponding to a Task . Returns config _ fields : ` dict ` Mapping where keys are the c...
from lsst . pex . config import Field def is_config_field ( obj ) : return isinstance ( obj , Field ) return _get_alphabetical_members ( config_class , is_config_field )
def _updateInferenceStats ( self , statistics , objectName = None ) : """Updates the inference statistics . Parameters : @ param statistics ( dict ) Dictionary in which to write the statistics @ param objectName ( str ) Name of the inferred object , if known . Otherwise , set to None ."""
L4Representations = self . getL4Representations ( ) L4PredictedCells = self . getL4PredictedCells ( ) L4PredictedActiveCells = self . getL4PredictedActiveCells ( ) L2Representation = self . getL2Representations ( ) for i in xrange ( self . numColumns ) : statistics [ "L4 Representation C" + str ( i ) ] . append ( l...
def on ( self , event , handler ) : """Attaches the handler to the specified event . @ param event : event to attach the handler to . Any object can be passed as event , but string is preferable . If qcore . EnumBase instance is passed , its name is used as event key . @ param handler : event handler . @ ...
event_hook = self . get_or_create ( event ) event_hook . subscribe ( handler ) return self
def make_pre_authed_request ( self , env , method = None , path = None , body = None , headers = None ) : """Nearly the same as swift . common . wsgi . make _ pre _ authed _ request except that this also always sets the ' swift . source ' and user agent . Newer Swift code will support swift _ source as a kwar...
if self . default_storage_policy : sp = self . default_storage_policy if headers : headers . update ( { 'X-Storage-Policy' : sp } ) else : headers = { 'X-Storage-Policy' : sp } subreq = swift . common . wsgi . make_pre_authed_request ( env , method = method , path = path , body = body , head...
def fill_edge_matrix ( nsrcs , match_dict ) : """Create and fill a matrix with the graph ' edges ' between sources . Parameters nsrcs : int number of sources ( used to allocate the size of the matrix ) match _ dict : dict ( ( int , int ) : float ) Each entry gives a pair of source indices , and the corr...
e_matrix = np . zeros ( ( nsrcs , nsrcs ) ) for k , v in match_dict . items ( ) : e_matrix [ k [ 0 ] , k [ 1 ] ] = v return e_matrix
def CheckFile ( self , filename ) : """Validates the artifacts definition in a specific file . Args : filename ( str ) : name of the artifacts definition file . Returns : bool : True if the file contains valid artifacts definitions ."""
result = True artifact_reader = reader . YamlArtifactsReader ( ) try : for artifact_definition in artifact_reader . ReadFile ( filename ) : try : self . _artifact_registry . RegisterDefinition ( artifact_definition ) except KeyError : logging . warning ( 'Duplicate artifact d...
def from_list ( commands ) : """Given a list of tuples of form ( depth , text ) that represents a DFS traversal of a command tree , returns a dictionary representing command tree ."""
def subtrees ( commands , level ) : if not commands : return acc = [ ] parent , * commands = commands for command in commands : if command [ 'level' ] > level : acc . append ( command ) else : yield ( parent , acc ) parent = command ...
def create_widget ( self ) : """Create the underlying widget . A toast is not a subclass of view , hence we don ' t set name as widget or children will try to use it as their parent ( which crashes ) ."""
d = self . declaration Snackbar . make ( self . parent_widget ( ) , d . text , 0 if d . duration else - 2 ) . then ( self . on_widget_created )
def view_links ( obj ) : '''Link to performance data and duplicate overview .'''
result = format_html ( '' ) result += format_html ( '<a href="%s" style="white-space: nowrap">Show duplicates</a><br/>' % reverse ( 'duplicates' , args = ( obj . pk , ) ) ) result += format_html ( '<a href="%s" style="white-space: nowrap">Show submissions</a><br/>' % obj . grading_url ( ) ) result += format_html ( '<a ...
def tournament ( self , negative = False ) : """Tournament selection and when negative is True it performs negative tournament selection"""
if self . generation <= self . _random_generations and not negative : return self . random_selection ( ) if not self . _negative_selection and negative : return self . random_selection ( negative = negative ) vars = self . random ( ) fit = [ ( k , self . population [ x ] . fitness ) for k , x in enumerate ( var...
def root ( ) : """Placeholder root url for the PCI . Ideally this should never be called !"""
response = { "links" : { "message" : "Welcome to the SIP Processing Controller Interface" , "items" : [ { "href" : "{}health" . format ( request . url ) } , { "href" : "{}subarrays" . format ( request . url ) } , { "href" : "{}scheduling_blocks" . format ( request . url ) } , { "href" : "{}processing_blocks" . format (...
def int_global_to_local_stop ( self , index , axis = 0 ) : """Calculate local index from global index from stop _ index : param index : global index as integer : param axis : current axis to process : return :"""
if index < self . __mask [ axis ] . start + self . __halos [ 0 ] [ axis ] : return None if index > self . __mask [ axis ] . stop : return self . __mask [ axis ] . stop - self . __mask [ axis ] . start return index - self . __mask [ axis ] . start
def _bucket_key ( self ) : """Returns hash bucket key for the redis key"""
return "{}.size.{}" . format ( self . prefix , ( self . _hashed_key // 1000 ) if self . _hashed_key > 1000 else self . _hashed_key )
def load ( fnames , tag = '' , sat_id = None ) : """Load the SuperMAG files Parameters fnames : ( list ) List of filenames tag : ( str or NoneType ) Denotes type of file to load . Accepted types are ' indices ' , ' all ' , ' stations ' , and ' ' ( for just magnetometer measurements ) . ( default = ' ' )...
# Ensure that there are files to load if len ( fnames ) <= 0 : return pysat . DataFrame ( None ) , pysat . Meta ( None ) # Ensure that the files are in a list if isinstance ( fnames , str ) : fnames = [ fnames ] # Initialise the output data data = pds . DataFrame ( ) baseline = list ( ) # Cycle through the file...
def as_xml ( self ) : """XML representation of the error to be used in HTTP response . This XML format follows the IIIF Image API v1.0 specification , see < http : / / iiif . io / api / image / 1.0 / # error >"""
# Build tree spacing = ( "\n" if ( self . pretty_xml ) else "" ) root = Element ( 'error' , { 'xmlns' : I3F_NS } ) root . text = spacing e_parameter = Element ( 'parameter' , { } ) e_parameter . text = self . parameter e_parameter . tail = spacing root . append ( e_parameter ) if ( self . text ) : e_text = Element ...
def element_count ( self ) : """Retrieve the number of elements in this type . Returns an int . If the Type is not an array or vector , this raises ."""
result = conf . lib . clang_getNumElements ( self ) if result < 0 : raise Exception ( 'Type does not have elements.' ) return result
def save ( self ) : """Updates the list with changes ."""
# Based on the documentation at # http : / / msdn . microsoft . com / en - us / library / lists . lists . updatelistitems % 28v = office . 12%29 . aspx # Note , this ends up un - namespaced . SharePoint doesn ' t care about # namespaces on this XML node , and will bork if any of these elements # have a namespace prefix...
def reverse ( self ) : """NAME : reverse PURPOSE : reverse an already integrated orbit ( that is , make it go from end to beginning in t = 0 to tend ) INPUT : ( none ) OUTPUT : ( none ) HISTORY : 2011-04-13 - Written - Bovy ( NYU )"""
if hasattr ( self , '_orbInterp' ) : delattr ( self , '_orbInterp' ) if hasattr ( self , 'rs' ) : delattr ( self , 'rs' ) sortindx = list ( range ( len ( self . _orb . t ) ) ) sortindx . sort ( key = lambda x : self . _orb . t [ x ] , reverse = True ) for ii in range ( self . _orb . orbit . shape [ 1 ] ) : ...
def vectorize ( function ) : """Allow a method that only accepts scalars to accept vectors too . This decorator has two different behaviors depending on the dimensionality of the array passed as an argument : * * 1 - d array * * It will work under the assumption that the ` function ` argument is a callable ...
def decorated ( self , X , * args , ** kwargs ) : if not isinstance ( X , np . ndarray ) : return function ( self , X , * args , ** kwargs ) if len ( X . shape ) == 1 : X = X . reshape ( [ - 1 , 1 ] ) if len ( X . shape ) == 2 : return np . fromiter ( ( function ( self , * x , * args...
def save ( self , folder_path = '' , configuration_type = 'running' , vrf_management_name = None , return_artifact = False ) : """Backup ' startup - config ' or ' running - config ' from device to provided file _ system [ ftp | tftp ] Also possible to backup config to localhost : param folder _ path : tftp / ft...
if hasattr ( self . resource_config , "vrf_management_name" ) : vrf_management_name = vrf_management_name or self . resource_config . vrf_management_name self . _validate_configuration_type ( configuration_type ) folder_path = self . get_path ( folder_path ) system_name = re . sub ( '\s+' , '_' , self . resource_co...
def remove ( name , ** kwargs ) : '''Remove system rc configuration variables CLI Example : . . code - block : : bash salt ' * ' sysrc . remove name = sshd _ enable'''
cmd = 'sysrc -v' if 'file' in kwargs : cmd += ' -f ' + kwargs [ 'file' ] if 'jail' in kwargs : cmd += ' -j ' + kwargs [ 'jail' ] cmd += ' -x ' + name sysrcs = __salt__ [ 'cmd.run' ] ( cmd ) if "sysrc: unknown variable" in sysrcs : raise CommandExecutionError ( sysrcs ) else : return name + " removed"
def reshape ( self , * shape , ** kwargs ) : """Returns a * * view * * of this array with a new shape without altering any data . Parameters shape : tuple of int , or n ints The new shape should not change the array size , namely ` ` np . prod ( new _ shape ) ` ` should be equal to ` ` np . prod ( self . sh...
if len ( shape ) == 1 and isinstance ( shape [ 0 ] , ( list , tuple ) ) : shape = shape [ 0 ] elif not shape : shape = kwargs . get ( 'shape' ) assert shape , "Shape must be provided." if not all ( k in [ 'shape' , 'reverse' ] for k in kwargs ) : raise TypeError ( "Got unknown keywords in reshape: {}. "...
def __set_checksum ( self ) : """Sets the checksum on the last byte of buffer , based on values in the buffer : return : None"""
checksum = self . __get_checksum ( self . __out_buffer . raw ) self . STRUCT_CHECKSUM . pack_into ( self . __out_buffer , self . OFFSET_CHECKSUM , checksum )
def _check_reads_hit ( self , alignment_io , min_aligned_fraction ) : '''Given an alignment return a list of sequence names that are less than the min _ aligned _ fraction'''
to_return = [ ] alignment_length = None for s in SeqIO . parse ( alignment_io , "fasta" ) : if not alignment_length : alignment_length = len ( s . seq ) min_length = int ( min_aligned_fraction * alignment_length ) logging . debug ( "Determined min number of aligned bases to be %s" % min_leng...
def plotprofMulti ( self , ini , end , delta , what_specie , xlim1 , xlim2 , ylim1 , ylim2 , symbol = None ) : '''create a movie with mass fractions vs mass coordinate between xlim1 and xlim2 , ylim1 and ylim2 . Only works with instances of se . Parameters ini : integer Initial model i . e . cycle . end...
plotType = self . _classTest ( ) if plotType == 'se' : for i in range ( ini , end + 1 , delta ) : step = int ( i ) # print step if symbol == None : symbol_dummy = '-' for j in range ( len ( what_specie ) ) : self . plot_prof_1 ( step , what_specie [ j ...
def report_events ( self , start_date , end_date , type = "system" ) : """Create a report for all client events or all system events . Uses GET to / reports / events / { clients , system } interface : Args : * * start _ date * : ( datetime ) Start time for report generation * * end _ date * : ( datetime ) E...
start_str , end_str = self . _format_input_dates ( start_date , end_date ) params = { "start_date" : start_str , "end_date" : end_str } endpoint = url . reports_events_clients if type == "clients" else url . reports_events_system response = self . _get ( endpoint , params = params ) self . _check_response ( response , ...
def validateMasterOption ( master ) : """Validate master ( - m , - - master ) command line option . Checks that option is a string of the ' hostname : port ' form , otherwise raises an UsageError exception . @ type master : string @ param master : master option @ raise usage . UsageError : on invalid mast...
try : hostname , port = master . split ( ":" ) port = int ( port ) except ( TypeError , ValueError ) : raise usage . UsageError ( "master must have the form 'hostname:port'" )
def post ( self , uri , data , ** kwargs ) : """POST the provided data to the specified path See : meth : ` request ` for additional details . The ` data ` parameter here is expected to be a string type ."""
return self . request ( "POST" , uri , data = data , ** kwargs )
def output ( self , result ) : """Adapts the result of a function based on the returns definition ."""
if self . returns : errors = None try : return self . _adapt_result ( result ) except AdaptErrors as e : errors = e . errors except AdaptError as e : errors = [ e ] raise AnticipateErrors ( message = 'Return value %r does not match anticipated type %r' % ( type ( result ) , s...
def relative_bias ( fm , scale_factor = 1 , estimator = None ) : """Computes the relative bias , i . e . the distribution of saccade angles and amplitudes . Parameters : fm : DataMat The fixation data to use scale _ factor : double Returns : 2D probability distribution of saccade angles and amplitudes...
assert 'fix' in fm . fieldnames ( ) , "Can not work without fixation numbers" excl = fm . fix - np . roll ( fm . fix , 1 ) != 1 # Now calculate the direction where the NEXT fixation goes to diff_x = ( np . roll ( fm . x , 1 ) - fm . x ) [ ~ excl ] diff_y = ( np . roll ( fm . y , 1 ) - fm . y ) [ ~ excl ] # Make a hist...
def set_cellpydata ( self , cellpydata , cycle ) : """Performing fit of the OCV steps in the cycles set by set _ cycles ( ) from the data set by set _ data ( ) r is found by calculating v0 / i _ start - - > err ( r ) = err ( v0 ) + err ( i _ start ) . c is found from using tau / r - - > err ( c ) = err ( r ) ...
self . data = cellpydata self . step_table = self . data . dataset # hope it works . . . time_voltage = self . data . get_ocv ( direction = 'up' , cycles = cycle ) time = time_voltage . Step_Time voltage = time_voltage . Voltage self . time = np . array ( time ) self . voltage = np . array ( voltage )
def points ( self ) : """The center of each filled cell as a list of points . Returns points : ( self . filled , 3 ) float , list of points"""
points = matrix_to_points ( matrix = self . matrix , pitch = self . pitch , origin = self . origin ) return points
def notify_command ( command_format , mounter ) : """Command notification tool . This works similar to Notify , but will issue command instead of showing the notifications on the desktop . This can then be used to react to events from shell scripts . The command can contain modern pythonic format placeholde...
udisks = mounter . udisks for event in [ 'device_mounted' , 'device_unmounted' , 'device_locked' , 'device_unlocked' , 'device_added' , 'device_removed' , 'job_failed' ] : udisks . connect ( event , run_bg ( DeviceCommand ( command_format , event = event ) ) )