signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def match_score ( self , supported : 'Language' ) -> int : """Suppose that ` self ` is the language that the user desires , and ` supported ` is a language that is actually supported . This method returns a number from 0 to 100 indicating how similar the supported language is ( higher numbers are better ) . T...
if supported == self : return 100 desired_complete = self . prefer_macrolanguage ( ) . maximize ( ) supported_complete = supported . prefer_macrolanguage ( ) . maximize ( ) desired_triple = ( desired_complete . language , desired_complete . script , desired_complete . region ) supported_triple = ( supported_complet...
def update ( self , project , params = { } , ** options ) : """A specific , existing project can be updated by making a PUT request on the URL for that project . Only the fields provided in the ` data ` block will be updated ; any unspecified fields will remain unchanged . When using this method , it is best ...
path = "/projects/%s" % ( project ) return self . client . put ( path , params , ** options )
def print_error ( msg , color = True ) : """Print an error message . : param string msg : the message : param bool color : if ` ` True ` ` , print with POSIX color"""
if color and is_posix ( ) : safe_print ( u"%s[ERRO] %s%s" % ( ANSI_ERROR , msg , ANSI_END ) ) else : safe_print ( u"[ERRO] %s" % ( msg ) )
def gates_by_name ( self , name ) : """Return all defined noisy gates of a particular gate name . : param str name : The gate name . : return : A list of noise models representing that gate . : rtype : Sequence [ KrausModel ]"""
return [ g for g in self . gates if g . gate == name ]
def supervise ( args ) : '''Run legacy , Firehose - style workflow of workflows'''
project = args . project workspace = args . workspace namespace = args . namespace workflow = args . workflow sample_sets = args . sample_sets recovery_file = args . json_checkpoint # If no sample sets are provided , run on all sample sets if not sample_sets : r = fapi . get_entities ( args . project , args . works...
def pivot_hist ( self , pivot_column_label , value_column_label , overlay = True , width = 6 , height = 4 , ** vargs ) : """Draw histograms of each category in a column ."""
warnings . warn ( "pivot_hist is deprecated; use " "hist(value_column_label, group=pivot_column_label), or " "with side_by_side=True if you really want side-by-side " "bars." ) pvt_labels = np . unique ( self [ pivot_column_label ] ) pvt_columns = [ self [ value_column_label ] [ np . where ( self [ pivot_column_label ]...
def get_template_parameters_s3 ( template_key , s3_resource ) : """Checks for existance of parameters object in S3 against supported suffixes and returns parameters file key if found Args : template _ key : S3 key for template file . omit bucket . s3 _ resource : a boto3 s3 resource Returns : filename of ...
for suffix in EFConfig . PARAMETER_FILE_SUFFIXES : parameters_key = template_key . replace ( "/templates" , "/parameters" ) + suffix try : obj = s3_resource . Object ( EFConfig . S3_CONFIG_BUCKET , parameters_key ) obj . get ( ) return parameters_key except ClientError : cont...
def _compute_variables_indices ( self ) : """Computes and saves the index location of each variable ( as a list ) in the objectives space and in the model space . If no categorical variables are available , these two are equivalent ."""
counter_objective = 0 counter_model = 0 for variable in self . space_expanded : variable . set_index_in_objective ( [ counter_objective ] ) counter_objective += 1 if variable . type is not 'categorical' : variable . set_index_in_model ( [ counter_model ] ) counter_model += 1 else : ...
def run_and_measure ( self , quil_program : Program , qubits : List [ int ] = None , trials : int = 1 , memory_map : Any = None ) -> np . ndarray : """Run a Quil program once to determine the final wavefunction , and measure multiple times . Alternatively , consider using ` ` wavefunction ` ` and calling ` ` samp...
if qubits is None : qubits = sorted ( quil_program . get_qubits ( indices = True ) ) if memory_map is not None : quil_program = self . augment_program_with_memory_values ( quil_program , memory_map ) return self . connection . _run_and_measure ( quil_program = quil_program , qubits = qubits , trials = trials , ...
def _evaluatelinearPotentials ( Pot , x , t = 0. ) : """Raw , undecorated function for internal use"""
if isinstance ( Pot , list ) : sum = 0. for pot in Pot : sum += pot . _call_nodecorator ( x , t = t ) return sum elif isinstance ( Pot , linearPotential ) : return Pot . _call_nodecorator ( x , t = t ) else : # pragma : no cover raise PotentialError ( "Input to 'evaluatelinearPotentials' is ...
def is_file ( self , follow_symlinks = True ) : """Return True if this entry is a file or a symbolic link pointing to a file ; return False if the entry is or points to a directory or other non - file entry , or if it doesn ’ t exist anymore . The result is cached on the os . DirEntry object . Args : foll...
return self . _system . isfile ( path = self . _path , client_kwargs = self . _client_kwargs )
def reply_with_message ( self , rep_msg ) : """Send a pre - created reply message to the client connection . Will check that rep _ msg . name matches the bound request ."""
self . _post_reply ( ) return self . client_connection . reply ( rep_msg , self . msg )
def quadrect ( f , n , a , b , kind = 'lege' , * args , ** kwargs ) : """Integrate the d - dimensional function f on a rectangle with lower and upper bound for dimension i defined by a [ i ] and b [ i ] , respectively ; using n [ i ] points . Parameters f : function The function to integrate over . This s...
if kind . lower ( ) == "lege" : nodes , weights = qnwlege ( n , a , b ) elif kind . lower ( ) == "cheb" : nodes , weights = qnwcheb ( n , a , b ) elif kind . lower ( ) == "trap" : nodes , weights = qnwtrap ( n , a , b ) elif kind . lower ( ) == "simp" : nodes , weights = qnwsimp ( n , a , b ) else : ...
def get_namespace ( self , key ) : """Returns a : class : ` ~ bang . util . SharedNamespace ` for the given : attr : ` key ` . These are used by : class : ` ~ bang . deployers . deployer . Deployer ` objects of the same ` ` deployer _ class ` ` to coordinate control over multiple deployed instances of like ...
namespace = self . shared_namespaces . get ( key ) if namespace : return namespace ns = SharedNamespace ( self . manager ) self . shared_namespaces [ key ] = ns return ns
def addLookupReference ( feature , lookup , script = None , languages = None , exclude_dflt = False ) : """Shortcut for addLookupReferences , but for a single lookup ."""
return addLookupReferences ( feature , ( lookup , ) , script = script , languages = languages , exclude_dflt = exclude_dflt , )
def list_queues ( self , prefix = None , num_results = None , include_metadata = False , marker = None , timeout = None ) : '''Returns a generator to list the queues . The generator will lazily follow the continuation tokens returned by the service and stop when all queues have been returned or num _ results is...
include = 'metadata' if include_metadata else None operation_context = _OperationContext ( location_lock = True ) kwargs = { 'prefix' : prefix , 'max_results' : num_results , 'include' : include , 'marker' : marker , 'timeout' : timeout , '_context' : operation_context } resp = self . _list_queues ( ** kwargs ) return ...
def host ( self , value ) : """A string that will be automatically included at the beginning of the url generated for doing each http request . : param value : The host to be connected with , e . g . ( http : / / hostname ) or ( https : / / X . X . X . X : port )"""
scheme , host , port = get_hostname_parameters_from_url ( value ) self . _host = "%s://%s:%s" % ( scheme , host , port )
def auth_user_ldap ( self , username , password ) : """Method for authenticating user , auth LDAP style . depends on ldap module that is not mandatory requirement for F . A . B . : param username : The username : param password : The password"""
if username is None or username == "" : return None user = self . find_user ( username = username ) if user is not None and ( not user . is_active ) : return None else : try : import ldap except Exception : raise Exception ( "No ldap library for python." ) try : if self . aut...
def reply_code_tuple ( code : int ) -> Tuple [ int , int , int ] : '''Return the reply code as a tuple . Args : code : The reply code . Returns : Each item in the tuple is the digit .'''
return code // 100 , code // 10 % 10 , code % 10
def log_request ( request : str , trim_log_values : bool = False , ** kwargs : Any ) -> None : """Log a request"""
return log_ ( request , request_logger , logging . INFO , trim = trim_log_values , ** kwargs )
def setStyle ( self , stylename ) : """Adjusts the output format of messages based on the style name provided Styles are loaded like python modules , so you can import styles from your own modules or use the ones in fastlog . styles Available styles can be found under / fastlog / styles / The default style is...
self . style = importlib . import_module ( stylename ) newHandler = Handler ( ) newHandler . setFormatter ( Formatter ( self . style ) ) self . addHandler ( newHandler )
def get_cache_stats ( ) : """Returns a list of dictionaries of all cache servers and their stats , if they provide stats ."""
cache_stats = [ ] for name , _ in six . iteritems ( settings . CACHES ) : cache_backend = caches [ name ] try : cache_backend_stats = cache_backend . _cache . get_stats ( ) except AttributeError : # this backend doesn ' t provide stats logger . info ( 'The memcached backend "{0}" does not su...
def to_ipa ( s ) : """Convert * s * to IPA ."""
identity = identify ( s ) if identity == IPA : return s elif identity == PINYIN : return pinyin_to_ipa ( s ) elif identity == ZHUYIN : return zhuyin_to_ipa ( s ) else : raise ValueError ( "String is not a valid Chinese transcription." )
def status ( self ) : """Gets the status for the column based on the cell ' s data ."""
# Deal with status column mechanics based in this cell ' s data if hasattr ( self , '_status' ) : # pylint : disable = access - member - before - definition return self . _status if self . column . status or self . column . name in self . column . table . _meta . status_columns : # returns the first matching status...
def _file_stat ( self , mode , infostr , stat ) : """update stat regarding to file operation , e . g . open , save , saveas , etc ."""
action_str = mode . upper ( ) info_str = infostr if stat == 'OK' : self . action_st_panel . SetBackgroundColour ( '#00FF00' ) else : # ERR self . action_st_panel . SetBackgroundColour ( '#FF0000' ) self . action_st . SetLabel ( action_str ) if info_str is None : info_str = 'Undefined File' self . info_st . ...
def is_file_url ( url ) : """Returns true if the given url is a file url"""
from . misc import to_text if not url : return False if not isinstance ( url , six . string_types ) : try : url = getattr ( url , "url" ) except AttributeError : raise ValueError ( "Cannot parse url from unknown type: {0!r}" . format ( url ) ) url = to_text ( url , encoding = "utf-8" ) retur...
def insert ( self , data ) : """Inserts item into this collection . An _ id field will be generated if not assigned in the data . : param data : Document to insert : type data : ` ` string ` ` : return : _ id of inserted object : rtype : ` ` dict ` `"""
return json . loads ( self . _post ( '' , headers = KVStoreCollectionData . JSON_HEADER , body = data ) . body . read ( ) . decode ( 'utf-8' ) )
def delete_edge ( self , ind_node , dep_node ) : """Delete an edge from the graph . Args : ind _ node ( str ) : The independent node to delete an edge from . dep _ node ( str ) : The dependent node that has a dependency on the ind _ node . Raises : KeyError : Raised when the edge doesn ' t already exist...
graph = self . graph if dep_node not in graph . get ( ind_node , [ ] ) : raise KeyError ( "No edge exists between %s and %s." % ( ind_node , dep_node ) ) graph [ ind_node ] . remove ( dep_node )
def _get_data ( self , read_size ) : """Get data from the character device ."""
if NIX : return super ( Keyboard , self ) . _get_data ( read_size ) return self . _pipe . recv_bytes ( )
def ping ( ) : '''Is the marathon api responding ?'''
try : response = salt . utils . http . query ( "{0}/ping" . format ( CONFIG [ CONFIG_BASE_URL ] ) , decode_type = 'plain' , decode = True , ) log . debug ( 'marathon.info returned successfully: %s' , response , ) if 'text' in response and response [ 'text' ] . strip ( ) == 'pong' : return True excep...
def find_sanitizer ( self , name ) : """Searches for a sanitizer function with given name . The name should contain two parts separated from each other with a dot , the first part being the module name while the second being name of the function contained in the module , when it ' s being prefixed with " sani...
# Split the sanitizer name into two parts , one containing the Python # module name , while second containing portion of the function name # we are looking for . name_parts = name . split ( "." ) if len ( name_parts ) < 2 : raise ConfigurationError ( "Unable to separate module name from function name in '%s'" % ( n...
def powerset ( l ) : """Generates all subsets of list ` l ` ( as tuples ) . Example > > > from pgmpy . utils . mathext import powerset > > > list ( powerset ( [ 1,2,3 ] ) ) [ ( ) , ( 1 , ) , ( 2 , ) , ( 3 , ) , ( 1,2 ) , ( 1,3 ) , ( 2,3 ) , ( 1,2,3 ) ]"""
return chain . from_iterable ( combinations ( l , r ) for r in range ( len ( l ) + 1 ) )
def modify_network_interface_attribute ( name = None , network_interface_id = None , attr = None , value = None , region = None , key = None , keyid = None , profile = None ) : '''Modify an attribute of an Elastic Network Interface . . . versionadded : : 2016.3.0 CLI Example : . . code - block : : bash salt...
if not ( name or network_interface_id ) : raise SaltInvocationError ( 'Either name or network_interface_id must be provided.' ) if attr is None and value is None : raise SaltInvocationError ( 'attr and value must be provided.' ) r = { } conn = _get_conn ( region = region , key = key , keyid = keyid , profile = ...
def minibatch_by_words ( items , size , tuples = True , count_words = len ) : """Create minibatches of a given number of words ."""
if isinstance ( size , int ) : size_ = itertools . repeat ( size ) else : size_ = size items = iter ( items ) while True : batch_size = next ( size_ ) batch = [ ] while batch_size >= 0 : try : if tuples : doc , gold = next ( items ) else : ...
def add ( self , * args ) : """This function adds strings to the keyboard , while not exceeding row _ width . E . g . ReplyKeyboardMarkup # add ( " A " , " B " , " C " ) yields the json result { keyboard : [ [ " A " ] , [ " B " ] , [ " C " ] ] } when row _ width is set to 1. When row _ width is set to 2 , the...
i = 1 row = [ ] for button in args : row . append ( button . to_dic ( ) ) if i % self . row_width == 0 : self . keyboard . append ( row ) row = [ ] i += 1 if len ( row ) > 0 : self . keyboard . append ( row )
def _get_repo_details ( saltenv ) : '''Return repo details for the specified saltenv as a namedtuple'''
contextkey = 'winrepo._get_repo_details.{0}' . format ( saltenv ) if contextkey in __context__ : ( winrepo_source_dir , local_dest , winrepo_file ) = __context__ [ contextkey ] else : winrepo_source_dir = __opts__ [ 'winrepo_source_dir' ] dirs = [ __opts__ [ 'cachedir' ] , 'files' , saltenv ] url_parts ...
def handle ( self , dict ) : '''Processes a vaild crawl request @ param dict : a valid dictionary object'''
# format key ex_res = self . extract ( dict [ 'url' ] ) key = "{sid}:{dom}.{suf}:queue" . format ( sid = dict [ 'spiderid' ] , dom = ex_res . domain , suf = ex_res . suffix ) val = ujson . dumps ( dict ) # shortcut to shove stuff into the priority queue self . redis_conn . zadd ( key , val , - dict [ 'priority' ] ) # i...
def set_user_info ( self , nick , user = '*' , real = '*' ) : """Sets user info for this server , to be used before connection . Args : nick ( str ) : Nickname to use . user ( str ) : Username to use . real ( str ) : Realname to use ."""
if self . connected : raise Exception ( "Can't set user info now, we're already connected!" ) # server will pickup list when they exist if not self . connected : self . nick = nick self . connect_info [ 'user' ] = { 'nick' : nick , 'user' : user , 'real' : real , }
def __callback ( self , event , * args , ** kwargs ) : # type : ( str , * Any , * * Any ) - > Any """Calls the registered method in the component for the given event : param event : An event ( IPOPO _ CALLBACK _ VALIDATE , . . . ) : return : The callback result , or None : raise Exception : Something went wro...
comp_callback = self . context . get_callback ( event ) if not comp_callback : # No registered callback return True # Call it result = comp_callback ( self . instance , * args , ** kwargs ) if result is None : # Special case , if the call back returns nothing return True return result
def get_aggregation ( self , name ) : '''Fetch an aggregation result given its name As there is no way at this point know the aggregation type ( ie . bucket , pipeline or metric ) we guess it from the response attributes . Only bucket and metric types are handled'''
agg = self . aggregations [ name ] if 'buckets' in agg : return agg [ 'buckets' ] else : return agg
def move_file ( source , dest ) : """Move file from * source * to * dest * If file is a Python script , also rename . pyc and . pyo files if any"""
import shutil shutil . copy ( source , dest ) remove_file ( source )
def resources_dynamic ( self ) : """Returns all resources directly owned by group , can be used to assign ownership of new resources : : user . resources . append ( resource )"""
return sa . orm . relationship ( "Resource" , cascade = "all" , passive_deletes = True , passive_updates = True , lazy = "dynamic" , )
def saturation ( self , saturation ) : """Set the group saturation . : param saturation : Saturation in decimal percent ( 0.0-1.0 ) ."""
if saturation < 0 or saturation > 1 : raise ValueError ( "Saturation must be a percentage " "represented as decimal 0-1.0" ) self . _saturation = saturation self . _update_color ( ) if saturation == 0 : self . white ( ) else : cmd = self . command_set . saturation ( saturation ) self . send ( cmd )
def update_link_rel_based ( self , old_rel , new_rel = None , new_text = None , single_link = False ) : """Update link nodes , based on the existing link / @ rel values . This requires specifying a link / @ rel value to update , and either a new link / @ rel value , or a new link / text ( ) value for all links ...
links = self . metadata . xpath ( './links/link[@rel="{}"]' . format ( old_rel ) ) if len ( links ) < 1 : log . warning ( 'No links with link/[@rel="{}"]' . format ( str ( old_rel ) ) ) return False if new_rel and not new_text : # update link / @ rel value for link in links : link . attrib [ 'rel' ]...
def evaluate ( self , verbose = True , passes = None ) : """Summary Returns : TYPE : Description"""
i = 0 exprs = [ ] for column_name in self . column_names : if len ( self . column_names ) > 1 : index = "1.$%d" % i else : index = "1" expr = self . get_column ( column_name , self . column_types [ i ] , index , verbose = verbose ) i += 1 exprs . append ( expr ) i = 0 for column_name...
def get_ports_alert ( self , port , header = "" , log = False ) : """Return the alert status relative to the port scan return value ."""
ret = 'OK' if port [ 'status' ] is None : ret = 'CAREFUL' elif port [ 'status' ] == 0 : ret = 'CRITICAL' elif ( isinstance ( port [ 'status' ] , ( float , int ) ) and port [ 'rtt_warning' ] is not None and port [ 'status' ] > port [ 'rtt_warning' ] ) : ret = 'WARNING' # Get stat name stat_name = self . get_...
def get ( self , spike_ids , channels = None ) : """Load the waveforms of the specified spikes ."""
if isinstance ( spike_ids , slice ) : spike_ids = _range_from_slice ( spike_ids , start = 0 , stop = self . n_spikes , ) if not hasattr ( spike_ids , '__len__' ) : spike_ids = [ spike_ids ] if channels is None : channels = slice ( None , None , None ) nc = self . n_channels else : channels = np . as...
def set_code_exprs ( self , codes ) : """Convenience : sets all the code expressions at once ."""
self . code_objs = dict ( ) self . _codes = [ ] for code in codes : self . append_code_expr ( code )
def frameify ( self , state , data ) : """Split data into a sequence of frames ."""
# Pull in any partially - processed data data = state . recv_buf + data # Loop over the data while data : if state . frame_len is None : # Try to grab a frame length from the data if len ( data ) < self . fmt . size : # Not enough data ; try back later break # Extract the length ...
def wrapper__ignore ( self , type_ ) : """Selectively ignore certain types when wrapping attributes . : param class type : The class / type definition to ignore . : rtype list ( type ) : The current list of ignored types"""
if type_ not in self . __exclusion_list : self . __exclusion_list . append ( type_ ) return self . __exclusion_list
def dist_docs ( ) : "create a documentation bundle"
dist_dir = path ( "dist" ) html_dir = path ( "docs/_build/html" ) docs_package = path ( "%s/%s-%s-docs.zip" % ( dist_dir . abspath ( ) , options . setup . name , options . setup . version ) ) if not html_dir . exists ( ) : error ( "\n*** ERROR: Please build the HTML docs!" ) sys . exit ( 1 ) dist_dir . exists (...
def distortion_score ( X , labels , metric = 'euclidean' ) : """Compute the mean distortion of all samples . The distortion is computed as the the sum of the squared distances between each observation and its closest centroid . Logically , this is the metric that K - Means attempts to minimize as it is fittin...
# Encode labels to get unique centers and groups le = LabelEncoder ( ) labels = le . fit_transform ( labels ) unique_labels = le . classes_ # Sum of the distortions distortion = 0 # Loop through each label ( center ) to compute the centroid for current_label in unique_labels : # Mask the instances that belong to the cu...
def train_local ( self , closest_point , label_vector_description = None , N = None , pivot = True , ** kwargs ) : """Train the model in a Cannon - like fashion using the grid points as labels and the intensities as normalsied rest - frame fluxes within some local regime ."""
lv = self . _cannon_label_vector if label_vector_description is None else self . _interpret_label_vector ( label_vector_description ) # By default we will train to the nearest 10 % of the grid . # If grid subset is a fraction , scale it to real numbers . if N is None : N = self . _configuration . get ( "settings" ,...
def __reset_crosshair ( self ) : """redraw the cross - hair on the horizontal slice plot Parameters x : int the x image coordinate y : int the y image coordinate Returns"""
self . lhor . set_ydata ( self . y_coord ) self . lver . set_xdata ( self . x_coord )
def df ( self , keys = None , basis = None , uwi = False ) : """Return current curve data as a ` ` pandas . DataFrame ` ` object . Everything has to have the same basis , because the depth is going to become the index of the DataFrame . If you don ' t provide one , ` ` welly ` ` will make one using ` ` survey...
try : import pandas as pd except : m = "You must install pandas to use dataframes." raise WellError ( m ) from pandas . api . types import is_object_dtype if keys is None : keys = [ k for k , v in self . data . items ( ) if isinstance ( v , Curve ) ] else : keys = utils . flatten_list ( keys ) if ba...
def is_format_supported ( self , format_p ) : """Checks if a specific drag ' n drop MIME / Content - type format is supported . in format _ p of type str Format to check for . return supported of type bool Returns @ c true if the specified format is supported , @ c false if not ."""
if not isinstance ( format_p , basestring ) : raise TypeError ( "format_p can only be an instance of type basestring" ) supported = self . _call ( "isFormatSupported" , in_p = [ format_p ] ) return supported
def update ( self , instance , oldValue , newValue ) : """Updates the aggregate based on a change in the child value ."""
histogram = self . __get__ ( instance , None ) if oldValue : histogram [ oldValue ] -= 1 if self . autoDelete and histogram [ oldValue ] == 0 : del histogram [ oldValue ] if newValue : histogram [ newValue ] += 1
def build_prev_op ( self ) : """Compose ' list - map ' which allows to jump to previous op , given offset of current op as index ."""
code = self . code codelen = len ( code ) # 2 . x uses prev 3 . x uses prev _ op . Sigh # Until we get this sorted out . self . prev = self . prev_op = [ 0 ] for offset in self . op_range ( 0 , codelen ) : op = code [ offset ] for _ in range ( instruction_size ( op , self . opc ) ) : self . prev_op . ap...
def __edges_between_two_vertices ( self , vertex1 , vertex2 , keys = False ) : """Iterates over edges between two supplied vertices in current : class : ` BreakpointGraph ` Checks that both supplied vertices are present in current breakpoint graph and then yield all edges that are located between two supplied ver...
for vertex in vertex1 , vertex2 : if vertex not in self . bg : raise ValueError ( "Supplied vertex ({vertex_name}) is not present in current BreakpointGraph" "" . format ( vertex_name = str ( vertex . name ) ) ) for bgedge , key in self . __get_edges_by_vertex ( vertex = vertex1 , keys = True ) : if bge...
def _get_api_url ( self , secure = None , ** formatters ) : '''Constructs Postmark API url : param secure : Use the https Postmark API . : param \ * \ * formatters : : func : ` string . format ` keyword arguments to format the url with . : rtype : Postmark API url'''
if self . endpoint is None : raise NotImplementedError ( 'endpoint must be defined on a subclass' ) if secure is None : secure = self . secure if secure : api_url = POSTMARK_API_URL_SECURE else : api_url = POSTMARK_API_URL url = urljoin ( api_url , self . endpoint ) if formatters : url = url . forma...
def savefig ( self , output_path , ** kwargs ) : """Save figure during generation . This method is used to save a completed figure during the main function run . It represents a call to ` ` matplotlib . pyplot . fig . savefig ` ` . # TODO : Switch to kwargs for matplotlib . pyplot . savefig Args : output ...
self . figure . save_figure = True self . figure . output_path = output_path self . figure . savefig_kwargs = kwargs return
def from_shapely ( sgeom , srid = None ) : """Create a Geometry from a Shapely geometry and the specified SRID . The Shapely geometry will not be modified ."""
if SHAPELY : WKBWriter . defaults [ "include_srid" ] = True if srid : lgeos . GEOSSetSRID ( sgeom . _geom , srid ) return Geometry ( sgeom . wkb_hex ) else : raise DependencyError ( "Shapely" )
def get_client ( provider , token = '' ) : "Return the API client for the given provider ."
cls = OAuth2Client if provider . request_token_url : cls = OAuthClient return cls ( provider , token )
def returner ( ret ) : '''Return data to a Pg server'''
try : with _get_serv ( ret , commit = True ) as cur : sql = '''INSERT INTO salt_returns (fun, jid, return, id, success, full_ret, alter_time) VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))''' cur . execute ( sql , ( ret [ 'fun' ] , ret [ 'jid' ] , psycopg2 ...
def run_through_shell ( command , enable_shell = False ) : """Retrieve output of a command . Returns a named tuple with three elements : * ` ` rc ` ` ( integer ) Return code of command . * ` ` out ` ` ( string ) Everything that was printed to stdout . * ` ` err ` ` ( string ) Everything that was printed to ...
if not enable_shell and isinstance ( command , str ) : command = shlex . split ( command ) returncode = None stderr = None try : proc = subprocess . Popen ( command , stderr = subprocess . PIPE , stdout = subprocess . PIPE , shell = enable_shell ) out , stderr = proc . communicate ( ) out = out . decode...
def collapse_equal_values ( values , counts ) : """Take a tuple ( values , counts ) , remove consecutive values and increment their count instead ."""
assert len ( values ) == len ( counts ) previousValue = values [ 0 ] previousCount = 0 for value , count in zip ( values , counts ) : if value != previousValue : yield ( previousValue , previousCount ) previousCount = 0 previousValue = value previousCount += count yield ( previousValue ,...
def create_upload_url ( self , upload_id , number , size , hash_value , hash_alg ) : """Given an upload created by create _ upload retrieve a url where we can upload a chunk . : param upload _ id : uuid of the upload : param number : int incrementing number of the upload ( 1 - based index ) : param size : int...
if number < 1 : raise ValueError ( "Chunk number must be > 0" ) data = { "number" : number , "size" : size , "hash" : { "value" : hash_value , "algorithm" : hash_alg } } return self . _put ( "/uploads/" + upload_id + "/chunks" , data )
def _cache_get ( self , date ) : """Return cache data for the specified day ; cache locally in this class . : param date : date to get data for : type date : datetime . datetime : return : cache data for date : rtype : dict"""
if date in self . cache_data : logger . debug ( 'Using class-cached data for date %s' , date . strftime ( '%Y-%m-%d' ) ) return self . cache_data [ date ] logger . debug ( 'Getting data from cache for date %s' , date . strftime ( '%Y-%m-%d' ) ) data = self . cache . get ( self . project_name , date ) self . cac...
def pointerEvent ( self , x , y , buttonmask = 0 ) : """Indicates either pointer movement or a pointer button press or release . The pointer is now at ( x - position , y - position ) , and the current state of buttons 1 to 8 are represented by bits 0 to 7 of button - mask respectively , 0 meaning up , 1 meaning...
self . transport . write ( pack ( "!BBHH" , 5 , buttonmask , x , y ) )
def save_features ( paths : List [ str ] , datas : List [ np . ndarray ] , compressed : bool = False ) -> List : """Save features specified with absolute paths . : param paths : List of files specified with paths . : param datas : List of numpy ndarrays to save into the respective files : param compressed : U...
fnames = [ ] # type : List [ str ] for path , data in zip ( paths , datas ) : fnames . append ( save_feature ( path , data , compressed ) ) return fnames
def deriv2 ( self , p ) : """Second derivative of the link function g ' ' ( p ) implemented through numerical differentiation"""
from statsmodels . tools . numdiff import approx_fprime_cs # TODO : workaround proplem with numdiff for 1d return np . diag ( approx_fprime_cs ( p , self . deriv ) )
def hostname_is_compatible ( conn , logger , provided_hostname ) : """Make sure that the host that we are connecting to has the same value as the ` hostname ` in the remote host , otherwise mons can fail not reaching quorum ."""
logger . debug ( 'determining if provided host has same hostname in remote' ) remote_hostname = conn . remote_module . shortname ( ) if remote_hostname == provided_hostname : return logger . warning ( '*' * 80 ) logger . warning ( 'provided hostname must match remote hostname' ) logger . warning ( 'provided hostnam...
def roulette ( weights , n ) : """Choose randomly the given number of items . The probability the item is chosen is proportionate to its weight . . . testsetup : : import random from proso . rand import roulette random . seed ( 1) . . testcode : : print ( roulette ( { ' cat ' : 2 , ' dog ' : 1000 } , ...
if n > len ( weights ) : raise Exception ( "Can't choose {} samples from {} items" . format ( n , len ( weights ) ) ) if any ( map ( lambda w : w <= 0 , weights . values ( ) ) ) : raise Exception ( "The weight can't be a non-positive number." ) items = weights . items ( ) chosen = set ( ) for i in range ( n ) :...
def msg ( message , * args , ** kwargs ) : """Prints a message from the server to the log file ."""
global log_file if log_file is None : log_file = sys . stderr if long_msg : file_name , line = caller_trace ( ) file_name , file_type = os . path . splitext ( file_name ) if file_name . endswith ( '/__init__' ) : file_name = os . path . basename ( os . path . dirname ( file_name ) ) elif fil...
def load_settings ( file_path , module_name = '' , secret_key = '' ) : '''a method to load data from json valid files : param file _ path : string with path to settings file : param module _ name : [ optional ] string with name of module containing file path : param secret _ key : [ optional ] string with key...
# validate inputs title = 'load_settings' try : _path_arg = '%s(file_path=%s)' % ( title , str ( file_path ) ) except : raise ValueError ( '%s(file_path=...) must be a string.' % title ) # find relative path from module from os import path if module_name : try : _path_arg = _path_arg . replace ( ')'...
def delete_eventtype ( self , test_type_str = None ) : """Action : create dialog to delete event type ."""
if test_type_str : answer = test_type_str , True else : answer = QInputDialog . getText ( self , 'Delete Event Type' , 'Enter event\'s name to delete' ) if answer [ 1 ] : self . annot . remove_event_type ( answer [ 0 ] ) self . display_eventtype ( ) self . update_annotations ( )
def generate_mapping ( order ) : """This function will take an order string and return a mapping between components in the metric and the various Lambda components . This must be used ( and consistently used ) when generating the metric * and * when transforming to / from the xi _ i coordinates to the lambda ...
mapping = { } mapping [ 'Lambda0' ] = 0 if order == 'zeroPN' : return mapping mapping [ 'Lambda2' ] = 1 if order == 'onePN' : return mapping mapping [ 'Lambda3' ] = 2 if order == 'onePointFivePN' : return mapping mapping [ 'Lambda4' ] = 3 if order == 'twoPN' : return mapping mapping [ 'LogLambda5' ] = 4...
def raise_error ( error_type : str ) -> None : """Raise the appropriate error based on error message ."""
try : error = next ( ( v for k , v in ERROR_CODES . items ( ) if k in error_type ) ) except StopIteration : error = AirVisualError raise error ( error_type )
def systemInformationType9 ( ) : """SYSTEM INFORMATION TYPE 9 Section 9.1.43"""
a = L2PseudoLength ( l2pLength = 0x01 ) b = TpPd ( pd = 0x6 ) c = MessageType ( mesType = 0x4 ) # 00000100 d = Si9RestOctets ( ) packet = a / b / c / d return packet
def getBoolTrackedDeviceProperty ( self , unDeviceIndex , prop ) : """Returns a bool property . If the device index is not valid or the property is not a bool type this function will return false ."""
fn = self . function_table . getBoolTrackedDeviceProperty pError = ETrackedPropertyError ( ) result = fn ( unDeviceIndex , prop , byref ( pError ) ) return result , pError
def insert ( self , context ) : """Build the image . : param resort . engine . execution . Context context : Current execution context ."""
try : current_dir = os . getcwd ( ) os . chdir ( os . path . join ( context . profile_dir ( ) , self . __base_dir ) ) args = [ "packer" , "build" , self . __template_path ] subprocess . call ( args ) finally : shutil . rmtree ( "output-*" , ignore_errors = True ) os . chdir ( current_dir )
def _get_yum_config ( ) : '''Returns a dict representing the yum config options and values . We try to pull all of the yum config options into a standard dict object . This is currently only used to get the reposdir settings , but could be used for other things if needed . If the yum python library is avail...
# in case of any non - fatal failures , these defaults will be used conf = { 'reposdir' : [ '/etc/yum/repos.d' , '/etc/yum.repos.d' ] , } if HAS_YUM : try : yb = yum . YumBase ( ) yb . preconf . init_plugins = False for name , value in six . iteritems ( yb . conf ) : conf [ name ...
def get_value ( obj , name , fallback = None ) : """Calls through to has _ value . If has _ value [ 0 ] is True , return has _ value [ 1 ] otherwise returns fallback ( ) if fallback is callable , else just fallback . : obj : the object to pull values from : name : the name to use when getting the value : fa...
present , value = has_value ( obj , name ) if present : return value else : if callable ( fallback ) : return fallback ( ) else : return fallback
def _cleanup ( self , status , expires_multiplier = 1 ) : u"""Clean up expired records . Will remove all entries for any ChordData whose callback result is in state < status > that was marked completed more than ( self . expires * < expires _ multipler > ) ago ."""
# self . expires is inherited , and defaults to 1 day ( or setting CELERY _ TASK _ RESULT _ EXPIRES ) expires = self . expires if isinstance ( self . expires , timedelta ) else timedelta ( seconds = self . expires ) expires = expires * expires_multiplier chords_to_delete = ChordData . objects . filter ( callback_result...
def hil_state_encode ( self , time_usec , roll , pitch , yaw , rollspeed , pitchspeed , yawspeed , lat , lon , alt , vx , vy , vz , xacc , yacc , zacc ) : '''DEPRECATED PACKET ! Suffers from missing airspeed fields and singularities due to Euler angles . Please use HIL _ STATE _ QUATERNION instead . Sent from s...
return MAVLink_hil_state_message ( time_usec , roll , pitch , yaw , rollspeed , pitchspeed , yawspeed , lat , lon , alt , vx , vy , vz , xacc , yacc , zacc )
def update_intervals ( self , back = None ) : '''Return the update intervals for all of the enabled fileserver backends which support variable update intervals .'''
back = self . backends ( back ) ret = { } for fsb in back : fstr = '{0}.update_intervals' . format ( fsb ) if fstr in self . servers : ret [ fsb ] = self . servers [ fstr ] ( ) return ret
def yAxisIsMinor ( self ) : '''Returns True if the minor axis is parallel to the Y axis , boolean .'''
return min ( self . radius . x , self . radius . y ) == self . radius . y
def dump_yaml ( data , Dumper = _Dumper , default_flow_style = False ) : """Returns data as yaml - formatted string ."""
content = yaml . dump ( data , default_flow_style = default_flow_style , Dumper = Dumper ) return content . strip ( )
def returnData ( self , dsptr ) : """" get ip data from db file by data start ptr " param : dsptr"""
dataPtr = dsptr & 0x00FFFFFFL dataLen = ( dsptr >> 24 ) & 0xFF self . __f . seek ( dataPtr ) data = self . __f . read ( dataLen ) result = data [ 4 : ] . split ( '|' ) location = Location ( self . getLong ( data , 0 ) , result [ 0 ] , result [ 1 ] , result [ 2 ] , result [ 3 ] , result [ 4 ] ) return location
def list_icmp_block ( zone , permanent = True ) : '''List ICMP blocks on a zone . . versionadded : : 2015.8.0 CLI Example : . . code - block : : bash salt ' * ' firewlld . list _ icmp _ block zone'''
cmd = '--zone={0} --list-icmp-blocks' . format ( zone ) if permanent : cmd += ' --permanent' return __firewall_cmd ( cmd ) . split ( )
def alter ( self , function ) : """Alters the currently stored reference by applying a function on it . : param function : ( Function ) , A stateful serializable object which represents the Function defined on server side . This object must have a serializable Function counter part registered on server side w...
check_not_none ( function , "function can't be None" ) return self . _encode_invoke ( atomic_reference_alter_codec , function = self . _to_data ( function ) )
def add_tokens_for_group ( self , with_pass = False ) : """Add the tokens for the group signature"""
kls = self . groups . super_kls name = self . groups . kls_name # Reset indentation to beginning and add signature self . reset_indentation ( '' ) self . result . extend ( self . tokens . make_describe ( kls , name ) ) # Add pass if necessary if with_pass : self . add_tokens_for_pass ( ) self . groups . finish_sign...
def post_mockdata_url ( service_name , implementation_name , url , headers , body , dir_base = dirname ( __file__ ) ) : """: param service _ name : possible " sws " , " pws " , " book " , " hfs " , etc . : param implementation _ name : possible values : " file " , etc ."""
# Currently this post method does not return a response body response = MockHTTP ( ) if body is not None : if "dispatch" in url : response . status = 200 else : response . status = 201 response . headers = { "X-Data-Source" : service_name + " file mock data" , "Content-Type" : headers [ 'Con...
def get_labels ( self , request_data , project = None , top = None , skip = None ) : """GetLabels . Get a collection of shallow label references . : param : class : ` < TfvcLabelRequestData > < azure . devops . v5_0 . tfvc . models . TfvcLabelRequestData > ` request _ data : labelScope , name , owner , and item...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) query_parameters = { } if request_data is not None : if request_data . label_scope is not None : query_parameters [ 'requestData.labelScope' ] = request_data . label_scope ...
def record_environment ( self ) : '''collect a limited set of environment variables based on the list under record _ envirionment in the configuration file .'''
# whitelist is a newline separated list under record _ environment envars = self . _get_setting ( name = 'whitelist' , section = 'record_environment' , user = False ) if envars is not None : # User uppercase envars = [ x . upper ( ) for x in envars . split ( '\n' ) ] # Make transparent for the user bot . cu...
def set_defaults ( self , * args , ** kwargs ) : '''node . set _ defaults ( a = b . . . ) yields a new calculation node identical to the given node except with the default values matching the given key - value pairs . Arguments are collapsed left - to right with later arguments overwriting earlier arguments .''...
args = merge ( self . defaults , args , kwargs ) new_cnode = copy . copy ( self ) object . __setattr__ ( new_cnode , 'defaults' , ps . pmap ( args ) ) return new_cnode
def parse_s2bs ( s2bs ) : """convert s2b files to dictionary"""
s2b = { } for s in s2bs : for line in open ( s ) : line = line . strip ( ) . split ( '\t' ) s , b = line [ 0 ] , line [ 1 ] s2b [ s ] = b return s2b
def save_modules ( ) : """Context in which imported modules are saved . Translates exceptions internal to the context into the equivalent exception outside the context ."""
saved = sys . modules . copy ( ) with ExceptionSaver ( ) as saved_exc : yield saved sys . modules . update ( saved ) # remove any modules imported since del_modules = ( mod_name for mod_name in sys . modules if mod_name not in saved # exclude any encodings modules . See # 285 and not mod_name . startswith ( 'encodi...
def register_dde_task ( self , * args , ** kwargs ) : """Register a Dde task ."""
kwargs [ "task_class" ] = DdeTask return self . register_task ( * args , ** kwargs )
def debugging ( ) : """This one I use for debugging . . ."""
print ( "In debugging" ) json_file = r"C:\Scripting\Processing\Cell" r"data\outdata\SiBEC\cellpy_batch_bec_exp02.json" b = init ( default_log_level = "DEBUG" ) b . load_info_df ( json_file ) print ( b . info_df . head ( ) ) # setting some variables b . export_raw = False b . export_cycles = False b . export_ica = False...