signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def rapidfire ( self , check_status = True , max_nlaunch = - 1 , max_loops = 1 , sleep_time = 5 , ** kwargs ) : """Use : class : ` PyLauncher ` to submits tasks in rapidfire mode . kwargs contains the options passed to the launcher . Args : check _ status : max _ nlaunch : Maximum number of launches . defau...
self . check_pid_file ( ) self . set_spectator_mode ( False ) if check_status : self . check_status ( ) from . launcher import PyLauncher return PyLauncher ( self , ** kwargs ) . rapidfire ( max_nlaunch = max_nlaunch , max_loops = max_loops , sleep_time = sleep_time )
def obfn_g1 ( self , Y1 ) : r"""Compute : math : ` g _ 1 ( \ mathbf { y _ 1 } ) ` component of ADMM objective function ."""
return np . linalg . norm ( ( self . Pcn ( Y1 ) - Y1 ) )
def _parse_summaryRecordSysNumber ( summaryRecordSysNumber ) : """Try to parse vague , not likely machine - readable description and return first token , which contains enough numbers in it ."""
def number_of_digits ( token ) : digits = filter ( lambda x : x . isdigit ( ) , token ) return len ( digits ) tokens = map ( lambda x : remove_hairs ( x , r" .,:;<>(){}[]\/" ) , summaryRecordSysNumber . split ( ) ) # pick only tokens that contains 3 digits contains_digits = filter ( lambda x : number_of_digits ...
def has_edit_permission ( self , request , obj = None , version = None ) : """Returns a boolean if the user in the request has edit permission for the object . Can also be passed a version object to check if the user has permission to edit a version of the object ( if they own it ) ."""
# Has the edit permission for this object type permission_name = '{}.edit_{}' . format ( self . opts . app_label , self . opts . model_name ) has_permission = request . user . has_perm ( permission_name ) if obj is not None and has_permission is False : has_permission = request . user . has_perm ( permission_name ,...
def health_check ( self ) : """Checks to make sure the file is there ."""
logger . debug ( 'Health Check on file for: {namespace}' . format ( namespace = self . namespace ) ) return os . path . isfile ( self . data_file )
def iqr ( data , channels = None ) : """Calculate the Interquartile Range of the events in an FCSData object . Parameters data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters ( aka channels ) . channels : int or str or list of int or list ...
# Slice data to take statistics from if channels is None : data_stats = data else : data_stats = data [ : , channels ] # Calculate and return statistic q75 , q25 = np . percentile ( data_stats , [ 75 , 25 ] , axis = 0 ) return q75 - q25
def configure ( self , statistics = "max" , max_ticks = 5 , plot_hists = True , flip = True , serif = True , sigma2d = False , sigmas = None , summary = None , bins = None , rainbow = None , colors = None , linestyles = None , linewidths = None , kde = False , smooth = None , cloud = None , shade = None , shade_alpha =...
# Dirty way of ensuring overrides happen when requested l = locals ( ) explicit = [ ] for k in l . keys ( ) : if l [ k ] is not None : explicit . append ( k ) if k . endswith ( "s" ) : explicit . append ( k [ : - 1 ] ) self . _init_params ( ) num_chains = len ( self . chains ) assert rai...
def get_quantiles ( acquisition_par , fmin , m , s ) : '''Quantiles of the Gaussian distribution useful to determine the acquisition function values : param acquisition _ par : parameter of the acquisition function : param fmin : current minimum . : param m : vector of means . : param s : vector of standard...
if isinstance ( s , np . ndarray ) : s [ s < 1e-10 ] = 1e-10 elif s < 1e-10 : s = 1e-10 u = ( fmin - m - acquisition_par ) / s phi = np . exp ( - 0.5 * u ** 2 ) / np . sqrt ( 2 * np . pi ) Phi = 0.5 * erfc ( - u / np . sqrt ( 2 ) ) return ( phi , Phi , u )
def pip_get_installed ( ) : """Code extracted from the middle of the pip freeze command . FIXME : does not list anything installed via - e"""
from pip . _internal . utils . misc import dist_is_local return tuple ( dist_to_req ( dist ) for dist in fresh_working_set ( ) if dist_is_local ( dist ) if dist . key != 'python' # See # 220 )
async def disable_digital_reporting ( self , command ) : """Disable Firmata reporting for a digital pin . : param command : { " method " : " disable _ digital _ reporting " , " params " : [ PIN ] } : returns : No return message ."""
pin = int ( command [ 0 ] ) await self . core . disable_digital_reporting ( pin )
def from_app_role ( cls , url , path , role_id , secret_id ) : """Constructor : use AppRole authentication to read secrets from a Vault path See https : / / www . vaultproject . io / docs / auth / approle . html Args : url : Vault url path : Vault path where secrets are stored role _ id : Vault RoleID s...
token = cls . _fetch_app_role_token ( url , role_id , secret_id ) source_dict = cls . _fetch_secrets ( url , path , token ) return cls ( source_dict , url , path , token )
def shell_command ( class_path ) : """Drop into a debugging shell ."""
loader = ClassLoader ( * class_path ) shell . start_shell ( local_ns = { 'ClassFile' : ClassFile , 'loader' : loader , 'constants' : importlib . import_module ( 'jawa.constants' ) , } )
def query ( self , * args , ** kwargs ) : """Generic query method . In reality , your storage class would have its own query methods , Performs a Mongo find on the Marketdata index metadata collection . See : http : / / api . mongodb . org / python / current / api / pymongo / collection . html"""
for x in self . _collection . find ( * args , ** kwargs ) : x [ 'stuff' ] = cPickle . loads ( x [ 'stuff' ] ) del x [ '_id' ] # Remove default unique ' _ id ' field from doc yield Stuff ( ** x )
def _inject_closure_values_fix_closures ( c , injected , ** kwargs ) : """Recursively fix closures Python bytecode for a closure looks like : : LOAD _ CLOSURE var1 BUILD _ TUPLE < n _ of _ vars _ closed _ over > LOAD _ CONST < code _ object _ containing _ closure > MAKE _ CLOSURE or this in 3.6 ( MAKE _...
code = c . code orig_len = len ( code ) for iback , ( opcode , value ) in enumerate ( reversed ( code ) ) : i = orig_len - iback - 1 if opcode != MAKE_CLOSURE : continue codeobj = code [ i - 1 - OPCODE_OFFSET ] assert codeobj [ 0 ] == byteplay . LOAD_CONST build_tuple = code [ i - 2 - OPCODE...
def update_created_pools ( self ) : """When the set of live nodes change , the loadbalancer will change its mind on host distances . It might change it on the node that came / left but also on other nodes ( for instance , if a node dies , another previously ignored node may be now considered ) . This method...
futures = set ( ) for host in self . cluster . metadata . all_hosts ( ) : distance = self . _profile_manager . distance ( host ) pool = self . _pools . get ( host ) future = None if not pool or pool . is_shutdown : # we don ' t eagerly set is _ up on previously ignored hosts . None is included here ...
def p_common_scalar_magic_line ( p ) : 'common _ scalar : LINE'
p [ 0 ] = ast . MagicConstant ( p [ 1 ] . upper ( ) , p . lineno ( 1 ) , lineno = p . lineno ( 1 ) )
def get_chat_administrators ( self , chat_id ) : """Use this method to get a list of administrators in a chat . On success , returns an Array of ChatMember objects that contains information about all chat administrators except other bots . : param chat _ id : : return :"""
result = apihelper . get_chat_administrators ( self . token , chat_id ) ret = [ ] for r in result : ret . append ( types . ChatMember . de_json ( r ) ) return ret
def get_mouse_location2 ( self ) : """Get all mouse location - related data . : return : a namedtuple with ` ` x ` ` , ` ` y ` ` , ` ` screen _ num ` ` and ` ` window ` ` fields"""
x = ctypes . c_int ( 0 ) y = ctypes . c_int ( 0 ) screen_num_ret = ctypes . c_ulong ( 0 ) window_ret = ctypes . c_ulong ( 0 ) _libxdo . xdo_get_mouse_location2 ( self . _xdo , ctypes . byref ( x ) , ctypes . byref ( y ) , ctypes . byref ( screen_num_ret ) , ctypes . byref ( window_ret ) ) return mouse_location2 ( x . v...
def parse_args ( bels : list , char_locs : CharLocs , parsed : Parsed , errors : Errors ) -> Tuple [ Parsed , Errors ] : """Parse arguments from functions Args : bels : BEL string as list of chars char _ locs : char locations for parens , commas and quotes parsed : function locations errors : error messag...
commas = char_locs [ "commas" ] # Process each span key in parsed from beginning for span in parsed : if parsed [ span ] [ "type" ] != "Function" or "parens_span" not in parsed [ span ] : continue # Skip if not argument - less sp , ep = parsed [ span ] [ "parens_span" ] # calculate args _ en...
def _parse_postmeta ( element ) : import phpserialize """Retrive post metadata as a dictionary"""
metadata = { } fields = element . findall ( "./{%s}postmeta" % WP_NAMESPACE ) for field in fields : key = field . find ( "./{%s}meta_key" % WP_NAMESPACE ) . text value = field . find ( "./{%s}meta_value" % WP_NAMESPACE ) . text if key == "_wp_attachment_metadata" : stream = StringIO ( value . encode...
def after_init_apps ( sender ) : """Check redis version"""
from uliweb import settings from uliweb . utils . common import log check = settings . get_var ( 'REDIS/check_version' ) if check : client = get_redis ( ) try : info = client . info ( ) except Exception as e : log . exception ( e ) log . error ( 'Redis is not started!' ) retu...
def get_param ( self , param , default = None ) : """Get a parameter in config ( handle default value ) : param param : name of the parameter to recover : type param : string : param default : the default value , raises an exception if param is not in configuration and default is None ( which is the defau...
if param in self . config : return self . config [ param ] elif default is not None : return default else : raise MissingParameter ( 'ppolicy' , param )
def run_field_scan ( ModelClass , model_kwargs , t_output_every , t_upto , field , vals , force_resume = True , parallel = False ) : """Run many models with a range of parameter sets . Parameters ModelClass : callable A class or factory function that returns a model object by calling ` ModelClass ( model _ ...
model_kwarg_sets = [ dict ( model_kwargs , field = val ) for val in vals ] run_kwarg_scan ( ModelClass , model_kwarg_sets , t_output_every , t_upto , force_resume , parallel )
def wcs ( self ) : """World coordinate system ( ` ~ astropy . wcs . WCS ` ) ."""
wcs = WCS ( naxis = 2 ) wcs . wcs . crval = self . config [ 'crval' ] wcs . wcs . crpix = self . config [ 'crpix' ] wcs . wcs . cdelt = self . config [ 'cdelt' ] wcs . wcs . ctype = self . config [ 'ctype' ] return wcs
def evaluate_extracted_tokens ( gold_content , extr_content ) : """Evaluate the similarity between gold - standard and extracted content , typically for a single HTML document , as another way of evaluating the performance of an extractor model . Args : gold _ content ( str or Sequence [ str ] ) : Gold - st...
if isinstance ( gold_content , string_ ) : gold_content = simple_tokenizer ( gold_content ) if isinstance ( extr_content , string_ ) : extr_content = simple_tokenizer ( extr_content ) gold_set = set ( gold_content ) extr_set = set ( extr_content ) jaccard = len ( gold_set & extr_set ) / len ( gold_set | extr_se...
def update_line ( self , t , x , y , ** kw ) : """overwrite data for trace t"""
self . panel . update_line ( t , x , y , ** kw )
def absent ( name , auth = None ) : '''Ensure service does not exist name Name of the service'''
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } __salt__ [ 'keystoneng.setup_clouds' ] ( auth ) service = __salt__ [ 'keystoneng.service_get' ] ( name = name ) if service : if __opts__ [ 'test' ] is True : ret [ 'result' ] = None ret [ 'changes' ] = { 'id' : service . id...
def remove_trailing_stars ( self , new_path = None , in_place = True , check = False ) : """Remove the bad character that can be inserted by some programs at the end of sequences ."""
# Optional check # if check and int ( sh . grep ( '-c' , '\*' , self . path , _ok_code = [ 0 , 1 ] ) ) == 0 : return self # Faster with bash utilities # if in_place is True : sh . sed ( '-i' , 's/\*$//g' , self . path ) return self # Standard way # if new_path is None : new_fasta = self . __class__ ( ne...
def subset_sum ( x , R ) : """Subsetsum by splitting : param x : table of values : param R : target value : returns bool : if there is a subsequence of x with total sum R : complexity : : math : ` O ( n ^ { \\ lceil n / 2 \\ rceil } ) `"""
k = len ( x ) // 2 # divide input Y = [ v for v in part_sum ( x [ : k ] ) ] Z = [ R - v for v in part_sum ( x [ k : ] ) ] Y . sort ( ) # test of intersection between Y and Z Z . sort ( ) i = 0 j = 0 while i < len ( Y ) and j < len ( Z ) : if Y [ i ] == Z [ j ] : return True elif Y [ i ] < Z [ j ] : # in...
def id_pools_vmac_ranges ( self ) : """Gets the IdPoolsRanges API Client for VMAC Ranges . Returns : IdPoolsRanges :"""
if not self . __id_pools_vmac_ranges : self . __id_pools_vmac_ranges = IdPoolsRanges ( 'vmac' , self . __connection ) return self . __id_pools_vmac_ranges
def files ( self ) : '''Listing files related to workflows related to current directory'''
try : cur = self . conn . cursor ( ) cur . execute ( 'SELECT id, item FROM workflows WHERE entry_type = "tracked_files"' ) return [ ( x [ 0 ] , eval ( x [ 1 ] ) ) for x in cur . fetchall ( ) ] except sqlite3 . DatabaseError as e : env . logger . warning ( f'Failed to get files from signature database: {...
def crosslisting_feature ( catalog , soup ) : """Parses all the crosslistings . These refer to the similar CRNs , such as a grad & undergrad level course ."""
listing = { } for elem in soup . coursedb . findAll ( 'crosslisting' ) : seats = int ( elem [ 'seats' ] ) crns = [ safeInt ( crn . string ) for crn in elem . findAll ( 'crn' ) ] # we want to refer to the same object to save space cl = CrossListing ( crns , seats ) for crn in crns : listing [...
def operations ( nsteps ) : '''Returns the number of operations needed for nsteps of GMRES'''
return { 'A' : 1 + nsteps , 'M' : 2 + nsteps , 'Ml' : 2 + nsteps , 'Mr' : 1 + nsteps , 'ip_B' : 2 + nsteps + nsteps * ( nsteps + 1 ) / 2 , 'axpy' : 4 + 2 * nsteps + nsteps * ( nsteps + 1 ) / 2 }
def seek ( self , offset , whence = 0 ) : """Move to a new offset either relative or absolute . whence = 0 is absolute , whence = 1 is relative , whence = 2 is relative to the end . Any relative or absolute seek operation which would result in a negative position is undefined and that case can be ignored in...
if self . closed : raise ValueError ( "I/O operation on closed file" ) if whence == 0 : if offset < 0 : raise IOError ( 'seek would move position outside the file' ) self . pos = offset elif whence == 1 : if self . pos + offset < 0 : raise IOError ( 'seek would move position outside the ...
def locate_numbers ( input_string : str ) -> int : """This function will find the numbers in a string and return their starting position . Args : input _ string : An input string that may contain numbers . Returns : The starting position of the numbers in the input string . Examples : > > > locate _ num...
import re for match in re . finditer ( '\d+' , input_string ) : return match . start ( )
def join ( * args , trailing_slash = False ) : """Return a url path joined from the arguments . It correctly handles blank / None arguments , and removes back - to - back slashes , eg : : assert join ( ' / ' , ' foo ' , None , ' bar ' , ' ' , ' baz ' ) = = ' / foo / bar / baz ' assert join ( ' / ' , ' / foo '...
dirty_path = '/' . join ( map ( lambda x : x and x or '' , args ) ) path = re . sub ( r'/+' , '/' , dirty_path ) if path in { '' , '/' } : return '/' path = path . rstrip ( '/' ) return path if not trailing_slash else path + '/'
def find_family ( self , pattern = r".*" , flags = 0 , node = None ) : """Returns the Nodes from given family . : param pattern : Matching pattern . : type pattern : unicode : param flags : Matching regex flags . : type flags : int : param node : Node to start walking from . : type node : AbstractNode o...
return self . __root_node . find_family ( pattern , flags , node or self . __root_node )
def noun_phrases ( self ) : """Returns a list of noun phrases for this blob ."""
return WordList ( [ phrase . strip ( ) for phrase in self . np_extractor . extract ( self . raw ) if len ( phrase . split ( ) ) > 1 ] )
def resolve_ssl_version ( candidate ) : """like resolve _ cert _ reqs"""
if candidate is None : return PROTOCOL_SSLv23 if isinstance ( candidate , str ) : res = getattr ( ssl , candidate , None ) if res is None : res = getattr ( ssl , 'PROTOCOL_' + candidate ) return res return candidate
def AppMoVCopeland ( profile , alpha = 0.5 ) : """Returns an integer that is equal to the margin of victory of the election profile , that is , the smallest number k such that changing k votes can change the winners . : ivar Profile profile : A Profile object that represents an election profile ."""
# Currently , we expect the profile to contain complete ordering over candidates . elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" : print ( "ERROR: unsupported profile type" ) exit ( ) # Initialization n = profile . numVoters m = profile . numCands # Compute the original winner ...
def create_pipeline_run ( pipeline , context_by_op ) : """Create a pipeline run / instance ."""
pipeline_run = PipelineRun . objects . create ( pipeline = pipeline ) dag , ops = pipeline . dag # Go trough the operation and create operation runs and the upstreams op_runs = { } runs_by_ops = { } for op_id in dag . keys ( ) : op_run = OperationRun . objects . create ( pipeline_run = pipeline_run , operation_id =...
def is_ssl_error ( error = None ) : """Checks if the given error ( or the current one ) is an SSL error ."""
exc_types = ( ssl . SSLError , ) try : from OpenSSL . SSL import Error exc_types += ( Error , ) except ImportError : pass if error is None : error = sys . exc_info ( ) [ 1 ] return isinstance ( error , exc_types )
def _detect_database_platform ( self ) : """Detects and sets the database platform . Evaluates custom platform class and version in order to set the correct platform . : raises InvalidPlatformSpecified : if an invalid platform was specified for this connection ."""
version = self . _get_database_platform_version ( ) if version is not None : self . _platform = self . _create_database_platform_for_version ( version ) else : self . _platform = self . get_dbal_platform ( )
def draw_plot ( self ) : """Redraws the plot"""
import numpy , pylab state = self . state if len ( self . data [ 0 ] ) == 0 : print ( "no data to plot" ) return vhigh = max ( self . data [ 0 ] ) vlow = min ( self . data [ 0 ] ) for i in range ( 1 , len ( self . plot_data ) ) : vhigh = max ( vhigh , max ( self . data [ i ] ) ) vlow = min ( vlow , min ...
async def answer_callback_query ( self , callback_query_id : base . String , text : typing . Union [ base . String , None ] = None , show_alert : typing . Union [ base . Boolean , None ] = None , url : typing . Union [ base . String , None ] = None , cache_time : typing . Union [ base . Integer , None ] = None ) -> bas...
payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . ANSWER_CALLBACK_QUERY , payload ) return result
def unregister_plotter ( identifier , sorter = True , plot_func = True ) : """Unregister a : class : ` psyplot . plotter . Plotter ` for the projects Parameters identifier : str Name of the attribute that is used to filter for the instances belonging to this plotter or to create plots with this plotter so...
d = registered_plotters . get ( identifier , { } ) if sorter and hasattr ( Project , identifier ) : delattr ( Project , identifier ) d [ 'sorter' ] = False if plot_func and hasattr ( ProjectPlotter , identifier ) : for cls in [ ProjectPlotter , DatasetPlotter , DataArrayPlotter ] : delattr ( cls , i...
def get_configure ( self , repo = None , name = None , groups = None , main_cfg = False ) : """Get the vent . template settings for a given tool by looking at the plugin _ manifest"""
constraints = locals ( ) del constraints [ 'main_cfg' ] status = ( True , None ) template_dict = { } return_str = '' if main_cfg : vent_cfg = Template ( self . vent_config ) for section in vent_cfg . sections ( ) [ 1 ] : template_dict [ section ] = { } for vals in vent_cfg . section ( section ) ...
def can_create_asset_content_with_record_types ( self , asset_id = None , asset_content_record_types = None ) : """Tests if this user can create an ` ` AssetContent ` ` using the desired record types . While ` ` RepositoryManager . getAssetContentRecordTypes ( ) ` ` can be used to test which records are support...
url_path = construct_url ( 'authorization' , bank_id = self . _catalog_idstr ) return self . _get_request ( url_path ) [ 'assetHints' ] [ 'canCreate' ]
def _find_unused_static_warnings ( filename , lines , ast_list ) : """Warn about unused static variables ."""
static_declarations = dict ( _get_static_declarations ( ast_list ) ) def find_variables_use ( body ) : for child in body : if child . name in static_declarations : static_use_counts [ child . name ] += 1 static_use_counts = collections . Counter ( ) for node in ast_list : if isinstance ( nod...
def print_row ( * argv ) : """Print one row of data"""
# for i in range ( 0 , len ( argv ) ) : # row + = f " { argv [ i ] } " # columns row = "" # id row += f"{argv[0]:<3}" # name row += f" {argv[1]:<13}" # allocation row += f" {argv[2]:>5}" # level # row + = f " { argv [ 3 ] } " print ( row )
def main ( ) : """Shows basic usage of the Google Calendar API . Creates a Google Calendar API service object and outputs a list of the next 10 events on the user ' s calendar ."""
credentials = get_credentials ( ) http = credentials . authorize ( httplib2 . Http ( ) ) service = discovery . build ( 'calendar' , 'v3' , http = http ) now = datetime . datetime . utcnow ( ) . isoformat ( ) + 'Z' # ' Z ' indicates UTC time print ( 'Getting the upcoming 10 events' ) eventsResult = service . events ( ) ...
def _is_duplicate_record ( self , rtype , name , content ) : """Check if DNS entry already exists ."""
records = self . _list_records ( rtype , name , content ) is_duplicate = len ( records ) >= 1 if is_duplicate : LOGGER . info ( 'Duplicate record %s %s %s, NOOP' , rtype , name , content ) return is_duplicate
def generate_menu ( self , ass , text , path = None , level = 0 ) : """Function generates menu from based on ass parameter"""
menu = self . create_menu ( ) for index , sub in enumerate ( sorted ( ass [ 1 ] , key = lambda y : y [ 0 ] . fullname . lower ( ) ) ) : if index != 0 : text += "|" text += "- " + sub [ 0 ] . fullname new_path = list ( path ) if level == 0 : new_path . append ( ass [ 0 ] . name ) new_...
def match_column_labels ( self , match_value_or_fct , levels = None , max_matches = 0 , empty_res = 1 ) : """Check the original DataFrame ' s column labels to find a subset of the current region : param match _ value _ or _ fct : value or function ( hdr _ value ) which returns True for match : param levels : [ ...
allmatches = self . parent . _find_column_label_positions ( match_value_or_fct , levels ) # only keep matches which are within this region matches = [ m for m in allmatches if m in self . col_ilocs ] if max_matches and len ( matches ) > max_matches : matches = matches [ : max_matches ] if matches : return Regio...
def interval_overlap ( a , b , x , y ) : """Returns by how much two intervals overlap assumed that a < = b and x < = y"""
if b <= x or a >= y : return 0 elif x <= a <= y : return min ( b , y ) - a elif x <= b <= y : return b - max ( a , x ) elif a >= x and b <= y : return b - a else : assert False
def assert_greater ( first , second , msg_fmt = "{msg}" ) : """Fail if first is not greater than second . > > > assert _ greater ( ' foo ' , ' bar ' ) > > > assert _ greater ( 5 , 5) Traceback ( most recent call last ) : AssertionError : 5 is not greater than 5 The following msg _ fmt arguments are suppor...
if not first > second : msg = "{!r} is not greater than {!r}" . format ( first , second ) fail ( msg_fmt . format ( msg = msg , first = first , second = second ) )
def log ( self , lvl , msg , * args , ** kwargs ) : """Both prints to stdout / stderr and the django . currencies logger"""
logger . log ( lvl , msg , * args , ** kwargs ) if lvl >= self . verbosity : if args : fmsg = msg % args else : fmsg = msg % kwargs if lvl >= logging . WARNING : self . stderr . write ( fmsg ) else : self . stdout . write ( fmsg )
def set_bucket_props ( self , transport , bucket , props ) : """set _ bucket _ props ( bucket , props ) Sets bucket properties for the given bucket . . . note : : This request is automatically retried : attr : ` retries ` times if it fails due to network error . : param bucket : the bucket whose properties ...
_validate_bucket_props ( props ) return transport . set_bucket_props ( bucket , props )
def close ( self ) : """Closes associated resources of this request object . This closes all file handles explicitly . You can also use the request object in a with statement with will automatically close it . . . versionadded : : 0.9"""
files = self . __dict__ . get ( 'files' ) for key , value in iter_multi_items ( files or ( ) ) : value . close ( )
def summary ( self ) : """Summary by packages and dependencies"""
print ( "\nStatus summary" ) print ( "=" * 79 ) print ( "{0}found {1} dependencies in {2} packages.{3}\n" . format ( self . grey , self . count_dep , self . count_pkg , self . endc ) )
def nodes ( self ) : """Return the list of nodes ."""
getnode = self . _nodes . __getitem__ return [ getnode ( nid ) for nid in self . _nodeids ]
def last_day ( self ) : """Return the last day of Yom Tov or Shabbat . This is useful for three - day holidays , for example : it will return the last in a string of Yom Tov + Shabbat . If this HDate is Shabbat followed by no Yom Tov , returns the Saturday . If this HDate is neither Yom Tov , nor Shabbat , ...
day_iter = self while day_iter . next_day . is_yom_tov or day_iter . next_day . is_shabbat : day_iter = day_iter . next_day return day_iter
def parse_data_type ( self , index , ** kwargs ) : """Parse a type to an other type"""
if not index . isValid ( ) : return False try : if kwargs [ 'atype' ] == "date" : self . _data [ index . row ( ) ] [ index . column ( ) ] = datestr_to_datetime ( self . _data [ index . row ( ) ] [ index . column ( ) ] , kwargs [ 'dayfirst' ] ) . date ( ) elif kwargs [ 'atype' ] == "perc" : _...
def unzip ( iterable ) : """The inverse of : func : ` zip ` , this function disaggregates the elements of the zipped * iterable * . The ` ` i ` ` - th iterable contains the ` ` i ` ` - th element from each element of the zipped iterable . The first element is used to to determine the length of the remaining...
head , iterable = spy ( iter ( iterable ) ) if not head : # empty iterable , e . g . zip ( [ ] , [ ] , [ ] ) return ( ) # spy returns a one - length iterable as head head = head [ 0 ] iterables = tee ( iterable , len ( head ) ) def itemgetter ( i ) : def getter ( obj ) : try : return obj [ i...
def _calc_damping ( mod_reducs , x_2 , x_2_mean , x_3 , x_3_mean ) : """Compute the damping ratio using Equation ( 16 ) ."""
# Mean values of the predictors x_1_mean = - 1.0 x_1 = np . log ( np . log ( 1 / mod_reducs ) + 0.103 ) ones = np . ones_like ( mod_reducs ) x = np . c_ [ ones , x_1 , x_2 , x_3 , ( x_1 - x_1_mean ) * ( x_2 - x_2_mean ) , ( x_2 - x_2_mean ) * ( x_3 - x_3_mean ) ] c = np . c_ [ 2.86 , 0.571 , - 0.103 , - 0.141 , 0.0419 ...
def crypto_hash_sha512 ( message ) : """Hashes and returns the message ` ` message ` ` . : param message : bytes : rtype : bytes"""
digest = ffi . new ( "unsigned char[]" , crypto_hash_sha512_BYTES ) rc = lib . crypto_hash_sha512 ( digest , message , len ( message ) ) ensure ( rc == 0 , 'Unexpected library error' , raising = exc . RuntimeError ) return ffi . buffer ( digest , crypto_hash_sha512_BYTES ) [ : ]
def rmv_normal_cov ( mu , C , size = 1 ) : """Random multivariate normal variates ."""
mu_size = np . shape ( mu ) if size == 1 : return np . random . multivariate_normal ( mu , C , size ) . reshape ( mu_size ) else : return np . random . multivariate_normal ( mu , C , size ) . reshape ( ( size , ) + mu_size )
def connect ( self , autospawn = False , wait = False ) : '''Connect to pulseaudio server . " autospawn " option will start new pulse daemon , if necessary . Specifying " wait " option will make function block until pulseaudio server appears .'''
if self . _loop_closed : raise PulseError ( 'Eventloop object was already' ' destroyed and cannot be reused from this instance.' ) if self . connected is not None : self . _ctx_init ( ) flags , self . connected = 0 , None if not autospawn : flags |= c . PA_CONTEXT_NOAUTOSPAWN if wait : flags |= c . PA_C...
def dumpcache ( self ) : '''Usage : dumpcache - display file hash cache'''
if cached . cacheloaded : # pprint . pprint ( cached . cache ) MyPrettyPrinter ( ) . pprint ( cached . cache ) return const . ENoError else : perr ( "Cache not loaded." ) return const . ECacheNotLoaded
def avail_sizes ( call = None ) : '''Return a dict of all available VM sizes on the cloud provider with relevant data . This data is provided in three dicts .'''
if call == 'action' : raise SaltCloudSystemExit ( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) ret = { 'block devices' : { } , 'memory' : { } , 'processors' : { } , } conn = get_conn ( ) response = conn . getCreateObjectOptions ( ) for device in response [ 'b...
def _set_widths ( self , row , proc_group ) : """Update auto - width Fields based on ` row ` . Parameters row : dict proc _ group : { ' default ' , ' override ' } Whether to consider ' default ' or ' override ' key for pre - and post - format processors . Returns True if any widths required adjustment...
width_free = self . style [ "width_" ] - sum ( [ sum ( self . fields [ c ] . width for c in self . columns ) , self . width_separtor ] ) if width_free < 0 : width_fixed = sum ( [ sum ( self . fields [ c ] . width for c in self . columns if c not in self . autowidth_columns ) , self . width_separtor ] ) assert w...
def getScale ( self , zoom ) : """Returns the scale at a given zoom level"""
if self . unit == 'degrees' : resolution = self . getResolution ( zoom ) * EPSG4326_METERS_PER_UNIT else : resolution = self . getResolution ( zoom ) return resolution / STANDARD_PIXEL_SIZE
def set_model ( self , model ) : """Set all levels \' model to the given one : param m : the model that the levels should use : type m : QtCore . QAbstractItemModel : returns : None : rtype : None : raises : None"""
# do the set model in reverse ! # set model might trigger an update for the lower levels # but the lower ones have a different model , so it will fail anyways # this way the initial state after set _ model is correct . self . model = model self . _levels [ 0 ] . set_model ( model )
def sum ( self ) : """Summary Returns : TYPE : Description"""
return NumpyArrayWeld ( numpy_weld_impl . aggr ( self . expr , "+" , 0 , self . weld_type ) , self . weld_type , 0 )
def to_date ( value , default = None ) : """Tries to convert the passed in value to Zope ' s DateTime : param value : The value to be converted to a valid DateTime : type value : str , DateTime or datetime : return : The DateTime representation of the value passed in or default"""
if isinstance ( value , DateTime ) : return value if not value : if default is None : return None return to_date ( default ) try : if isinstance ( value , str ) and '.' in value : # https : / / docs . plone . org / develop / plone / misc / datetime . html # datetime - problems - and - pitfalls ...
def physicalMemory ( ) : """> > > n = physicalMemory ( ) > > > n > 0 True > > > n = = physicalMemory ( ) True"""
try : return os . sysconf ( 'SC_PAGE_SIZE' ) * os . sysconf ( 'SC_PHYS_PAGES' ) except ValueError : return int ( subprocess . check_output ( [ 'sysctl' , '-n' , 'hw.memsize' ] ) . decode ( 'utf-8' ) . strip ( ) )
def edit_message_reply_markup ( self , * args , ** kwargs ) : """See : func : ` edit _ message _ reply _ markup `"""
return edit_message_reply_markup ( * args , ** self . _merge_overrides ( ** kwargs ) ) . run ( )
def _gen_4spec ( op , path , value , create_path = False , xattr = False , _expand_macros = False ) : """Like ` _ gen _ 3spec ` , but also accepts a mandatory value as its third argument : param bool _ expand _ macros : Whether macros in the value should be expanded . The macros themselves are defined at the se...
flags = 0 if create_path : flags |= _P . SDSPEC_F_MKDIR_P if xattr : flags |= _P . SDSPEC_F_XATTR if _expand_macros : flags |= _P . SDSPEC_F_EXPANDMACROS return Spec ( op , path , flags , value )
def distinct ( self , numPartitions = None ) : """Return a new RDD containing the distinct elements in this RDD . > > > sorted ( sc . parallelize ( [ 1 , 1 , 2 , 3 ] ) . distinct ( ) . collect ( ) ) [1 , 2 , 3]"""
return self . map ( lambda x : ( x , None ) ) . reduceByKey ( lambda x , _ : x , numPartitions ) . map ( lambda x : x [ 0 ] )
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : """See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec of input and result values . Implements equation 14 of Hong & Goda ( 2007)"""
C = self . COEFFS [ imt ] C_PGA = self . COEFFS [ PGA ( ) ] C_AMP = self . AMP_COEFFS [ imt ] # Gets the PGA on rock - need to convert from g to cm / s / s pga_rock = self . _compute_pga_rock ( C_PGA , rup . mag , dists . rjb ) * 980.665 # Get the mean ground motion value mean = ( self . _compute_nonlinear_magnitude_te...
def _manage_used_ips ( self , current_ip ) : """Handle registering and releasing used Tor IPs . : argument current _ ip : current Tor IP : type current _ ip : str"""
# Register current IP . self . used_ips . append ( current_ip ) # Release the oldest registred IP . if self . reuse_threshold : if len ( self . used_ips ) > self . reuse_threshold : del self . used_ips [ 0 ]
def query ( self , sql : str , args : tuple = None ) : """Execute a SQL query with a return value ."""
with self . _cursor ( ) as cursor : log . debug ( 'Running SQL: ' + str ( ( sql , args ) ) ) cursor . execute ( sql , args ) return cursor . fetchall ( )
def _matrix_grad ( q , h , h_dx , t , t_prime ) : '''Returns the gradient with respect to a single variable'''
N = len ( q ) W = np . zeros ( [ N , N ] ) Wprime = np . zeros ( [ N , N ] ) for i in range ( N ) : W [ i , i ] = 0.5 * ( h [ min ( i + 1 , N - 1 ) ] - h [ max ( i - 1 , 0 ) ] ) Wprime [ i , i ] = 0.5 * ( h_dx [ min ( i + 1 , N - 1 ) ] - h_dx [ max ( i - 1 , 0 ) ] ) tgrad = np . array ( [ t_prime [ i ] * h_dx [...
def process_status ( self , helper , session , check ) : """" process a single status"""
snmp_result_status = helper . get_snmp_value ( session , helper , DEVICE_GLOBAL_OIDS [ 'oid_' + check ] ) if check == "system_lcd" : helper . update_status ( helper , normal_check ( "global" , snmp_result_status , "LCD status" ) ) elif check == "global_storage" : helper . update_status ( helper , normal_check (...
def get_sensor_reading ( self , sensorname ) : """Get a sensor reading by name Returns a single decoded sensor reading per the name passed in : param sensorname : Name of the desired sensor : returns : sdr . SensorReading object"""
self . init_sdr ( ) for sensor in self . _sdr . get_sensor_numbers ( ) : if self . _sdr . sensors [ sensor ] . name == sensorname : rsp = self . raw_command ( command = 0x2d , netfn = 4 , data = ( sensor , ) ) if 'error' in rsp : raise exc . IpmiException ( rsp [ 'error' ] , rsp [ 'code'...
def noisy_layer ( self , prefix , action_in , out_size , sigma0 , non_linear = True ) : """a common dense layer : y = w ^ { T } x + b a noisy layer : y = ( w + \ epsilon _ w * \ sigma _ w ) ^ { T } x + ( b + \ epsilon _ b * \ sigma _ b ) where \ epsilon are random variables sampled from factorized normal di...
in_size = int ( action_in . shape [ 1 ] ) epsilon_in = tf . random_normal ( shape = [ in_size ] ) epsilon_out = tf . random_normal ( shape = [ out_size ] ) epsilon_in = self . f_epsilon ( epsilon_in ) epsilon_out = self . f_epsilon ( epsilon_out ) epsilon_w = tf . matmul ( a = tf . expand_dims ( epsilon_in , - 1 ) , b ...
def render_tree ( tree , list_all = True , show_only = None , frozen = False , exclude = None ) : """Convert tree to string representation : param dict tree : the package tree : param bool list _ all : whether to list all the pgks at the root level or only those that are the sub - dependencies : param set...
tree = sorted_tree ( tree ) branch_keys = set ( r . key for r in flatten ( tree . values ( ) ) ) nodes = tree . keys ( ) use_bullets = not frozen key_tree = dict ( ( k . key , v ) for k , v in tree . items ( ) ) get_children = lambda n : key_tree . get ( n . key , [ ] ) if show_only : nodes = [ p for p in nodes if ...
def inset_sizes ( cls , original_width , original_height , target_width , target_height ) : """Calculate new image sizes for inset mode : param original _ width : int : param original _ height : int : param target _ width : int : param target _ height : int : return : tuple ( int , int )"""
if target_width >= original_width and target_height >= original_height : target_width = float ( original_width ) target_height = original_height elif target_width <= original_width and target_height >= original_height : k = original_width / float ( target_width ) target_height = int ( original_height / ...
def _jmomentsurfaceIntegrand ( vz , vR , vT , R , z , df , sigmaR1 , gamma , sigmaz1 , n , m , o ) : # pragma : no cover because this is too slow ; a warning is shown """Internal function that is the integrand for the vmomentsurface mass integration"""
return df ( R , vR * sigmaR1 , vT * sigmaR1 * gamma , z , vz * sigmaz1 , use_physical = False , func = ( lambda x , y , z : x ** n * y ** m * z ** o ) )
def _bits_to_geohash ( value ) : """Convert a list of GeoHash bits to a GeoHash ."""
ret = [ ] # Get 5 bits at a time for i in ( value [ i : i + 5 ] for i in xrange ( 0 , len ( value ) , 5 ) ) : # Convert binary to integer # Note : reverse here , the slice above doesn ' t work quite right in reverse . total = sum ( [ ( bit * 2 ** count ) for count , bit in enumerate ( i [ : : - 1 ] ) ] ) ret . ...
def _encode_params ( data ) : """Encode parameters in a piece of data . If the data supplied is a dictionary , encodes each parameter in it , and returns a list of tuples containing the encoded parameters , and a urlencoded version of that . Otherwise , assumes the data is already encoded appropriately , an...
if hasattr ( data , '__iter__' ) : data = dict ( data ) if hasattr ( data , 'items' ) : result = [ ] for k , vs in data . items ( ) : for v in isinstance ( vs , list ) and vs or [ vs ] : result . append ( ( k . encode ( 'utf-8' ) if isinstance ( k , unicode ) else k , v . encode ( 'utf-8...
def add_command ( self , command , * args , ** kwargs ) : """add a command . This is basically a wrapper for add _ parser ( )"""
cmd = self . add_parser ( command , * args , ** kwargs )
def showBindingsForActionSet ( self , unSizeOfVRSelectedActionSet_t , unSetCount , originToHighlight ) : """Shows the current binding all the actions in the specified action sets"""
fn = self . function_table . showBindingsForActionSet pSets = VRActiveActionSet_t ( ) result = fn ( byref ( pSets ) , unSizeOfVRSelectedActionSet_t , unSetCount , originToHighlight ) return result , pSets
def default_setup ( ) : """The default API setup for lxc4u This is the API that you access globally from lxc4u ."""
service = LXCService lxc_types = dict ( LXC = LXC , LXCWithOverlays = LXCWithOverlays , __default__ = UnmanagedLXC ) loader = LXCLoader ( lxc_types , service ) manager = LXCManager ( loader , service ) return LXCAPI ( manager = manager , service = service )
def __get_charset ( self ) : '''Return the character encoding ( charset ) used internally by MeCab . Charset is that of the system dictionary used by MeCab . Will defer to the user - specified MECAB _ CHARSET environment variable , if set . Defaults to shift - jis on Windows . Defaults to utf - 8 on Mac OS ...
cset = os . getenv ( self . MECAB_CHARSET ) if cset : logger . debug ( self . _DEBUG_CSET_DEFAULT . format ( cset ) ) return cset else : try : res = Popen ( [ 'mecab' , '-D' ] , stdout = PIPE ) . communicate ( ) lines = res [ 0 ] . decode ( ) if not lines . startswith ( 'unrecognized...
def popall ( self , key ) : """Remove specified key and return all corresponding values . If they key is not found , an empty list is return . > > > m = MutableMultiMap ( [ ( ' a ' , 1 ) , ( ' b ' , 2 ) , ( ' b ' , 3 ) , ( ' c ' , 4 ) ] ) > > > m . popall ( ' a ' ) > > > m . popall ( ' b ' ) [2 , 3] > >...
values = self . getall ( key ) try : del self [ key ] except KeyError : pass return values
def load_plugins ( self , plugin_class_name ) : """load all available plugins : param plugin _ class _ name : str , name of plugin class ( e . g . ' PreBuildPlugin ' ) : return : dict , bindings for plugins of the plugin _ class _ name class"""
# imp . findmodule ( ' atomic _ reactor ' ) doesn ' t work plugins_dir = os . path . join ( os . path . dirname ( __file__ ) , 'plugins' ) logger . debug ( "loading plugins from dir '%s'" , plugins_dir ) files = [ os . path . join ( plugins_dir , f ) for f in os . listdir ( plugins_dir ) if f . endswith ( ".py" ) ] if ...
def _finalize_upload ( self , ud ) : # type : ( Uploader , blobxfer . models . upload . Descriptor ) - > None """Finalize file upload : param Uploader self : this : param blobxfer . models . upload . Descriptor ud : upload descriptor"""
metadata = ud . generate_metadata ( ) if ud . requires_put_block_list : # put block list for non one - shot block blobs self . _finalize_block_blob ( ud , metadata ) elif ud . remote_is_page_blob or ud . remote_is_append_blob : # append and page blob finalization self . _finalize_nonblock_blob ( ud , metadata )...
def download_package ( self , feed_id , group_id , artifact_id , version , file_name ) : """DownloadPackage . [ Preview API ] Fulfills maven package file download requests by returning the url of the package file requested . : param str feed _ id : Name or ID of the feed . : param str group _ id : GroupId of ...
route_values = { } if feed_id is not None : route_values [ 'feedId' ] = self . _serialize . url ( 'feed_id' , feed_id , 'str' ) if group_id is not None : route_values [ 'groupId' ] = self . _serialize . url ( 'group_id' , group_id , 'str' ) if artifact_id is not None : route_values [ 'artifactId' ] = self ....
def find_identifier ( self ) : """Find a unique identifier for each feature , create it if needed ."""
features = self . data [ 'features' ] n = len ( features ) feature = features [ 0 ] if 'id' in feature and len ( set ( feat [ 'id' ] for feat in features ) ) == n : return 'feature.id' for key in feature . get ( 'properties' , [ ] ) : if len ( set ( feat [ 'properties' ] [ key ] for feat in features ) ) == n : ...