signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_visible_toolbars ( self ) : """Collects the visible toolbars ."""
toolbars = [ ] for toolbar in self . toolbarslist : if toolbar . toggleViewAction ( ) . isChecked ( ) : toolbars . append ( toolbar ) self . visible_toolbars = toolbars
def make_eventrule ( date_rule , time_rule , cal , half_days = True ) : """Constructs an event rule from the factory api ."""
_check_if_not_called ( date_rule ) _check_if_not_called ( time_rule ) if half_days : inner_rule = date_rule & time_rule else : inner_rule = date_rule & time_rule & NotHalfDay ( ) opd = OncePerDay ( rule = inner_rule ) # This is where a scheduled function ' s rule is associated with a calendar . opd . cal = cal ...
def pressAndHold ( * args ) : '''press and hold . Do NOT release . accepts as many arguments as you want . e . g . pressAndHold ( ' left _ arrow ' , ' a ' , ' b ' ) .'''
for i in args : win32api . keybd_event ( VK_CODE [ i ] , 0 , 0 , 0 ) time . sleep ( .05 )
def read_ligolw ( source , contenthandler = LIGOLWContentHandler , ** kwargs ) : """Read one or more LIGO _ LW format files Parameters source : ` str ` , ` file ` the open file or file path to read contenthandler : ` ~ xml . sax . handler . ContentHandler ` , optional content handler used to parse documen...
from ligo . lw . ligolw import Document from ligo . lw import types from ligo . lw . lsctables import use_in from ligo . lw . utils import ( load_url , ligolw_add ) # mock ToPyType to link to numpy dtypes topytype = types . ToPyType . copy ( ) for key in types . ToPyType : if key in types . ToNumPyType : ty...
def _get_error_message ( self , response ) : """Parse and return the first error message"""
error_message = 'An error occurred processing your request.' try : content = response . json ( ) # { " errors " : [ { " code " : 34 , " message " : " Sorry , # that page does not exist " } ] } error_message = content [ 'errors' ] [ 0 ] [ 'message' ] except TypeError : error_message = content [ 'erro...
def vorticity ( u , v , dx , dy ) : r"""Calculate the vertical vorticity of the horizontal wind . Parameters u : ( M , N ) ndarray x component of the wind v : ( M , N ) ndarray y component of the wind dx : float or ndarray The grid spacing ( s ) in the x - direction . If an array , there should be one...
dudy = first_derivative ( u , delta = dy , axis = - 2 ) dvdx = first_derivative ( v , delta = dx , axis = - 1 ) return dvdx - dudy
def generate_hashes ( filepath , blocksize = 65536 ) : '''Generate several hashes ( md5 and sha1 ) in a single sweep of the file . Using two hashes lowers the probability of collision and false negative ( file modified but the hash is the same ) . Supports big files by streaming blocks by blocks to the hasher autom...
# Init hashers hasher_md5 = hashlib . md5 ( ) hasher_sha1 = hashlib . sha1 ( ) # Read the file blocks by blocks with open ( filepath , 'rb' ) as afile : buf = afile . read ( blocksize ) while len ( buf ) > 0 : # Compute both hashes at the same time hasher_md5 . update ( buf ) hasher_sha1 . updat...
def reduce_stock ( self , product_id , sku_info , quantity ) : """减少库存 : param product _ id : 商品ID : param sku _ info : sku信息 , 格式 " id1 : vid1 ; id2 : vid2 " , 如商品为统一规格 , 则此处赋值为空字符串即可 : param quantity : 减少的库存数量 : return : 返回的 JSON 数据包"""
return self . _post ( 'merchant/stock/reduce' , data = { "product_id" : product_id , "sku_info" : sku_info , "quantity" : quantity } )
def insert ( self , seq ) : """Populates the DB from a sequence of strings , ERASING PREVIOUS STATE . : param seq : an iterable"""
# erase previous elements and make defaultdict for easier insertion . self . _els_idxed = defaultdict ( lambda : defaultdict ( set ) ) if type ( seq ) is str : raise ValueError ( 'Provided argument should be a sequence of strings' ', but not a string itself.' ) for el in seq : if type ( el ) is not str : ...
def to_dict ( self ) : """Convert the object into a json serializable dictionary . Note : It uses the private method _ save _ to _ input _ dict of the parent . : return dict : json serializable dictionary containing the needed information to instantiate the object"""
input_dict = super ( Add , self ) . _save_to_input_dict ( ) input_dict [ "class" ] = str ( "GPy.kern.Add" ) return input_dict
def analyse ( self , demand_item , demand_item_code ) : """Run the analyis of the model Doesn ' t return anything , but creates a new item ` ` LcoptModel . result _ set ` ` containing the results"""
my_analysis = Bw2Analysis ( self ) self . result_set = my_analysis . run_analyses ( demand_item , demand_item_code , ** self . analysis_settings ) return True
def get ( number , locale ) : """Returns the plural position to use for the given locale and number . @ type number : int @ param number : The number @ type locale : str @ param locale : The locale @ rtype : int @ return : The plural position"""
if locale == 'pt_BR' : # temporary set a locale for brazilian locale = 'xbr' if len ( locale ) > 3 : locale = locale . split ( "_" ) [ 0 ] rule = PluralizationRules . _rules . get ( locale , lambda _ : 0 ) _return = rule ( number ) if not isinstance ( _return , int ) or _return < 0 : return 0 return _return
def in_resource ( self , field , resource ) : """Return True if resource contains a valid value for the field ( not an empty or None value )"""
resource_field = resource . get ( field , None ) return resource_field is not None and resource_field != ''
def refresh ( self , reload = False ) : """: param reload : Make the request to return a new profile tree . This will result in the caching of the profile _ tree attribute . The new profile _ tree will be returned ."""
util . cached_property . bust_caches ( self , excludes = ( 'authcode' ) ) self . questions = self . question_fetchable ( ) if reload : return self . profile_tree
def definitions_help ( ) : """Help message for Definitions . . . versionadded : : 4.0.0 : returns : A message object containing helpful information . : rtype : messaging . message . Message"""
message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message
def prepare_blacklist ( src , dst , duration = 3600 , src_port1 = None , src_port2 = None , src_proto = 'predefined_tcp' , dst_port1 = None , dst_port2 = None , dst_proto = 'predefined_tcp' ) : """Create a blacklist entry . A blacklist can be added directly from the engine node , or from the system context . If...
json = { } directions = { src : 'end_point1' , dst : 'end_point2' } for direction , key in directions . items ( ) : json [ key ] = { 'address_mode' : 'any' } if 'any' in direction . lower ( ) else { 'address_mode' : 'address' , 'ip_network' : direction } if src_port1 : json . setdefault ( 'end_point1' ) . updat...
def handle_lines ( self ) : """Assemble incoming data into per - line packets ."""
while "\r\n" in self . buffer : line , self . buffer = self . buffer . split ( "\r\n" , 1 ) if valid_packet ( line ) : self . handle_raw_packet ( line ) else : log . warning ( 'dropping invalid data: %s' , line )
def field ( self , name ) : """Returns the field on this struct with the given name . Will try to find this name on all ancestors if this struct extends another . If found , returns a dict with keys : ' name ' , ' comment ' , ' type ' , ' is _ array ' If not found , returns None : Parameters : name stri...
if self . fields . has_key ( name ) : return self . fields [ name ] elif self . extends : if not self . parent : self . parent = self . contract . struct ( self . extends ) return self . parent . field ( name ) else : return None
def _read_header ( self ) : """Get the needed header information to initialize dataset ."""
self . _header = self . cdmrf . fetch_header ( ) self . load_from_stream ( self . _header )
def _arithmetic_helper ( a : "BitVecFunc" , b : Union [ BitVec , int ] , operation : Callable ) -> "BitVecFunc" : """Helper function for arithmetic operations on BitVecFuncs . : param a : The BitVecFunc to perform the operation on . : param b : A BitVec or int to perform the operation on . : param operation :...
if isinstance ( b , int ) : b = BitVec ( z3 . BitVecVal ( b , a . size ( ) ) ) raw = operation ( a . raw , b . raw ) union = a . annotations + b . annotations if isinstance ( b , BitVecFunc ) : # TODO : Find better value to set input and name to in this case ? return BitVecFunc ( raw = raw , func_name = None , ...
def set_major ( self ) : """Increment the major number of project"""
old_version = self . get_version ( ) new_version = str ( int ( old_version . split ( '.' , 5 ) [ 0 ] ) + 1 ) + '.0.0' self . set_version ( old_version , new_version )
def rotatePolygon ( polygon , theta , origin = None ) : """Rotates the given polygon around the origin or if not given it ' s center of mass polygon : np . array ( ( x1 , y1 ) , ( . . . ) ) theta : rotation clockwise in RADIAN origin = [ x , y ] - if not given set to center of gravity returns : None"""
if origin is None : origin = np . mean ( polygon , axis = 0 , dtype = polygon . dtype ) # polygon = polygon . copy ( ) polygon -= origin for n , corner in enumerate ( polygon ) : polygon [ n ] = corner [ 0 ] * np . cos ( theta ) - corner [ 1 ] * np . sin ( theta ) , corner [ 0 ] * np . sin ( theta ) + corner [ ...
def device_connect ( device_id ) : """Force a connection attempt via HTTP GET ."""
success = False if device_id in devices : devices [ device_id ] . connect ( ) success = True return jsonify ( success = success )
def hide_routemap_holder_route_map_content_set_origin_origin_igp ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) hide_routemap_holder = ET . SubElement ( config , "hide-routemap-holder" , xmlns = "urn:brocade.com:mgmt:brocade-ip-policy" ) route_map = ET . SubElement ( hide_routemap_holder , "route-map" ) name_key = ET . SubElement ( route_map , "name" ) name_key . text = kwargs . pop ( 'name' ) ...
def fasta_from_biom ( table , fasta_file_name ) : '''Save sequences from a biom table to a fasta file Parameters table : biom . Table The biom table containing the sequences fasta _ file _ name : str Name of the fasta output file'''
logger = logging . getLogger ( __name__ ) logger . debug ( 'saving biom table sequences to fasta file %s' % fasta_file_name ) with open ( fasta_file_name , 'w' ) as f : for cseq in table . ids ( axis = 'observation' ) : f . write ( '>%s\n%s\n' % ( cseq , cseq ) ) logger . info ( 'saved biom table sequences ...
def rev_after ( self , rev : int ) -> int : """Return the earliest future rev on which the value will change ."""
self . seek ( rev ) if self . _future : return self . _future [ - 1 ] [ 0 ]
def add_to_loader_class ( cls , loader_class = None , tag = None , ** kwargs ) : # type : ( type ( yaml . Loader ) , str , * * str ) - > YamlIncludeConstructor """Create an instance of the constructor , and add it to the YAML ` Loader ` class : param loader _ class : The ` Loader ` class add constructor to . . ...
if tag is None : tag = '' tag = tag . strip ( ) if not tag : tag = cls . DEFAULT_TAG_NAME if not tag . startswith ( '!' ) : raise ValueError ( '`tag` argument should start with character "!"' ) instance = cls ( ** kwargs ) if loader_class is None : if FullLoader : yaml . add_constructor ( tag , ...
def setDragQuery ( self , query ) : """Sets the query that should be used when this record is dragged . This value will be set into the application / x - query format for mime data . : param query | < orb . Query > | | None"""
if query is not None : self . setDragData ( 'application/x-orb-query' , query . toXmlString ( ) ) else : self . setDragData ( 'application/x-orb-query' , None )
def get_backend_init_list ( backend_vals ) : """Turn backend config dict into command line items ."""
cmd_list = [ ] for ( key , val ) in backend_vals . items ( ) : cmd_list . append ( '-backend-config' ) cmd_list . append ( key + '=' + val ) return cmd_list
def allow_ast_comparison ( ) : """This ugly little monkey - patcher adds in a helper class to all the AST node types . This helper class allows eq / ne comparisons to work , so that entire trees can be easily compared by Python ' s comparison machinery . Used by the anti8 functions to compare old and new AS...
class CompareHelper ( object ) : def __eq__ ( self , other ) : return type ( self ) == type ( other ) and vars ( self ) == vars ( other ) def __ne__ ( self , other ) : return type ( self ) != type ( other ) or vars ( self ) != vars ( other ) for item in vars ( ast ) . values ( ) : if type ( ...
def _run_includemes ( configurator , includemes ) : """Automatically include packages defined in * * include * * configuration key . : param pyramid . config . Configurator configurator : pyramid ' s app configurator : param dict includemes : include , a list of includes or dictionary"""
for include in includemes : if includemes [ include ] : try : configurator . include ( include , includemes [ include ] ) except AttributeError : configurator . include ( include )
def exchange_code_for_token ( self , authorization_code ) : # type : ( str ) - > se _ leg _ op . access _ token . AccessToken """Exchanges an authorization code for an access token ."""
if authorization_code not in self . authorization_codes : raise InvalidAuthorizationCode ( '{} unknown' . format ( authorization_code ) ) authz_info = self . authorization_codes [ authorization_code ] if authz_info [ 'used' ] : logger . debug ( 'detected already used authz_code=%s' , authorization_code ) ra...
def find_distinct ( self , collection , key ) : """Search a collection for the distinct key values provided . Args : collection : The db collection . See main class documentation . key : The name of the key to find distinct values . For example with the indicators collection , the key could be " type " . ...
obj = getattr ( self . db , collection ) result = obj . distinct ( key ) return result
def resize ( self , newWidth = 0 , newHeight = 0 ) : """\~english Resize width and height of rectangles @ param newWidth : new width value @ param newHeight : new height value \~chinese 重新设定矩形高宽 @ param newWidth : 新宽度 @ param newHeight : 新高度"""
self . height = newHeight self . width = newWidth
def chunks ( iterable , n ) : """A python generator that yields 100 - length sub - list chunks . Input : - full _ list : The input list that is to be separated in chunks of 100. - chunk _ size : Should be set to 100 , unless the Twitter API changes . Yields : - sub _ list : List chunks of length 100."""
for i in np . arange ( 0 , len ( iterable ) , n ) : yield iterable [ i : i + n ]
def _map_arguments ( self , args ) : """Map from the top - level arguments to the arguments provided to the indiviudal links"""
comp_file = args . get ( 'comp' , None ) datafile = args . get ( 'data' , None ) if is_null ( comp_file ) : return if is_null ( datafile ) : return NAME_FACTORY . update_base_dict ( datafile ) outdir = args . get ( 'outdir' , None ) outkey = args . get ( 'outkey' , None ) ft1file = args [ 'ft1file' ] if is_null...
def start ( self ) : """Start the instance ."""
rs = self . connection . start_instances ( [ self . id ] ) if len ( rs ) > 0 : self . _update ( rs [ 0 ] )
def _GetCh ( self ) : """Read a single character from the user . Returns : A string , the character read ."""
fd = self . _tty . fileno ( ) old = termios . tcgetattr ( fd ) try : tty . setraw ( fd ) ch = self . _tty . read ( 1 ) # Also support arrow key shortcuts ( escape + 2 chars ) if ord ( ch ) == 27 : ch += self . _tty . read ( 2 ) finally : termios . tcsetattr ( fd , termios . TCSADRAIN , old )...
def _start_services ( self , console_env ) : """Overrides superclass ."""
self . _ad . load_snippet ( name = 'snippet' , package = self . _package ) console_env [ 'snippet' ] = self . _ad . snippet console_env [ 's' ] = self . _ad . snippet
def get_product_historic_rates ( self , product_id , start = None , end = None , granularity = None ) : """Historic rates for a product . Rates are returned in grouped buckets based on requested ` granularity ` . If start , end , and granularity aren ' t provided , the exchange will assume some ( currently un...
params = { } if start is not None : params [ 'start' ] = start if end is not None : params [ 'end' ] = end if granularity is not None : acceptedGrans = [ 60 , 300 , 900 , 3600 , 21600 , 86400 ] if granularity not in acceptedGrans : raise ValueError ( 'Specified granularity is {}, must be in appr...
def cmd ( * args , ** kwargs ) : """Decorate a callable to replace it with a manufactured command class . Extends the interface of ` ` CommandDecorator ` ` , allowing the same ` ` cmd ` ` to be used as a decorator or as a decorator factory : : @ cmd ( root = True ) def build ( ) : @ build . register @...
try : ( first , * remainder ) = args except ValueError : pass else : if callable ( first ) : return CommandDecorator ( * remainder , ** kwargs ) ( first ) return CommandDecorator ( * args , ** kwargs )
def make_data_classif ( dataset , n , nz = .5 , theta = 0 , random_state = None , ** kwargs ) : """dataset generation for classification problems Parameters dataset : str type of classification problem ( see code ) n : int number of training samples nz : float noise level ( > 0) random _ state : int...
generator = check_random_state ( random_state ) if dataset . lower ( ) == '3gauss' : y = np . floor ( ( np . arange ( n ) * 1.0 / n * 3 ) ) + 1 x = np . zeros ( ( n , 2 ) ) # class 1 x [ y == 1 , 0 ] = - 1. x [ y == 1 , 1 ] = - 1. x [ y == 2 , 0 ] = - 1. x [ y == 2 , 1 ] = 1. x [ y == 3 ...
def get_automated_runs ( ) : """Return all automated runs"""
path = functions . get_path_from_query_string ( request ) if request . method == 'GET' : with functions . DBContextManager ( path ) as session : automated_runs = session . query ( models . AutomatedRun ) . all ( ) return jsonify ( list ( map ( lambda x : x . serialize , automated_runs ) ) ) if reque...
def general_acquisition_info ( metadata ) : """General sentence on data acquisition . Should be first sentence in MRI data acquisition section . Parameters metadata : : obj : ` dict ` The metadata for the dataset . Returns out _ str : : obj : ` str ` Output string with scanner information ."""
out_str = ( 'MR data were acquired using a {tesla}-Tesla {manu} {model} ' 'MRI scanner.' ) out_str = out_str . format ( tesla = metadata . get ( 'MagneticFieldStrength' , 'UNKNOWN' ) , manu = metadata . get ( 'Manufacturer' , 'MANUFACTURER' ) , model = metadata . get ( 'ManufacturersModelName' , 'MODEL' ) ) return out_...
def _parse ( self ) : """Parses raw data"""
for i in range ( len ( self . data ) ) : self . _parse_row ( i )
def evaluate_cartesian_multi ( self , param_vals , _verify = True ) : r"""Compute multiple points on the surface . Assumes ` ` param _ vals ` ` has two columns of Cartesian coordinates . See : meth : ` evaluate _ cartesian ` for more details on how each row of parameter values is evaluated . . . image : : ....
if _verify : if param_vals . ndim != 2 : raise ValueError ( "Parameter values must be 2D array" ) for s , t in param_vals : self . _verify_cartesian ( s , t ) return _surface_helpers . evaluate_cartesian_multi ( self . _nodes , self . _degree , param_vals , self . _dimension )
def request_timeout_hint ( timeout_hint ) : """Decorator ; add recommended client timeout hint to a request for request Useful for requests that take longer than average to reply . Hint is provided to clients via ? request - timeout - hint . Note this is only exposed if the device server sets the protocol ver...
if timeout_hint is not None : timeout_hint = float ( timeout_hint ) def decorator ( handler ) : handler . request_timeout_hint = timeout_hint return handler return decorator
def find_xenon_grpc_jar ( ) : """Find the Xenon - GRPC jar - file , windows version ."""
prefix = Path ( sys . prefix ) locations = [ prefix / 'lib' , prefix / 'local' / 'lib' ] for location in locations : jar_file = location / 'xenon-grpc-{}-all.jar' . format ( xenon_grpc_version ) if not jar_file . exists ( ) : continue else : return str ( jar_file ) return None
def put ( self , key , value , minutes ) : """Store an item in the cache for a given number of minutes . : param key : The cache key : type key : str : param value : The cache value : type value : mixed : param minutes : The lifetime in minutes of the cached value : type minutes : int"""
self . _memcache . set ( self . _prefix + key , value , minutes * 60 )
def plot_ts ( ax , agemin , agemax , timescale = 'gts12' , ylabel = "Age (Ma)" ) : """Make a time scale plot between specified ages . Parameters : ax : figure object agemin : Minimum age for timescale agemax : Maximum age for timescale timescale : Time Scale [ default is Gradstein et al . , ( 2012 ) ] f...
ax . set_title ( timescale . upper ( ) ) ax . axis ( [ - .25 , 1.5 , agemax , agemin ] ) ax . axes . get_xaxis ( ) . set_visible ( False ) # get dates and chron names for timescale TS , Chrons = pmag . get_ts ( timescale ) X , Y , Y2 = [ 0 , 1 ] , [ ] , [ ] cnt = 0 if agemin < TS [ 1 ] : # in the Brunhes Y = [ agem...
def task_transaction ( channel ) : """Ensures a task is fetched and acknowledged atomically ."""
with channel . lock : if channel . poll ( 0 ) : task = channel . recv ( ) channel . send ( Acknowledgement ( os . getpid ( ) , task . id ) ) else : raise RuntimeError ( "Race condition between workers" ) return task
def nginx_access ( line ) : '''> > > import pprint > > > input _ line1 = ' { " remote _ addr " : " 127.0.0.1 " , " remote _ user " : " - " , " timestamp " : " 1515144699.201 " , " request " : " GET / HTTP / 1.1 " , " status " : " 200 " , " request _ time " : " 0.000 " , " body _ bytes _ sent " : " 396 " , " http ...
# TODO Handle nginx error logs log = json . loads ( line ) timestamp_iso = datetime . datetime . utcfromtimestamp ( float ( log [ 'timestamp' ] ) ) . isoformat ( ) log . update ( { 'timestamp' : timestamp_iso } ) if '-' in log . get ( 'upstream_response_time' ) : log [ 'upstream_response_time' ] = 0.0 log [ 'body_b...
def get_filter_qobj ( self , keys = None ) : """Return a copy of this Query object with additional where clauses for the keys in the argument"""
# only care about columns in aggregates right ? cols = set ( ) for agg in self . select . aggregates : cols . update ( agg . cols ) sels = [ SelectExpr ( col , [ col ] , col , None ) for col in cols ] select = Select ( sels ) where = list ( self . where ) if keys : keys = list ( keys ) keys = map ( sqlize ,...
def _visible_width ( s ) : """Visible width of a printed string . ANSI color codes are removed . > > > _ visible _ width ( ' \x1b [31mhello \x1b [0m ' ) , _ visible _ width ( " world " ) (5 , 5)"""
if isinstance ( s , _text_type ) or isinstance ( s , _binary_type ) : return len ( _strip_invisible ( s ) ) else : return len ( _text_type ( s ) )
def acor ( self , k = 5 ) : """Autocorrelation time of the chain return the autocorrelation time for each parameters Inputs : parameter in self - consistent window Outputs : autocorrelation time of the chain"""
try : import acor except ImportError : print ( "Can't import acor, please download it." ) return 0 n = np . shape ( self . _chain ) [ 1 ] t = np . zeros ( n ) for i in xrange ( n ) : t [ i ] = acor . acor ( self . _chain [ : , i ] , k ) [ 0 ] return t
def lon_to_deg ( lon ) : """Convert longitude to degrees ."""
if isinstance ( lon , str ) and ( ':' in lon ) : # TODO : handle other coordinate systems lon_deg = hmsStrToDeg ( lon ) else : lon_deg = float ( lon ) return lon_deg
def VAR_DECL ( self , cursor ) : """Handles Variable declaration ."""
# get the name name = self . get_unique_name ( cursor ) log . debug ( 'VAR_DECL: name: %s' , name ) # Check for a previous declaration in the register if self . is_registered ( name ) : return self . get_registered ( name ) # get the typedesc object _type = self . _VAR_DECL_type ( cursor ) # transform the ctypes va...
def mirtrace_rna_categories ( self ) : """Generate the miRTrace RNA Categories"""
# Specify the order of the different possible categories keys = OrderedDict ( ) keys [ 'reads_mirna' ] = { 'color' : '#33a02c' , 'name' : 'miRNA' } keys [ 'reads_rrna' ] = { 'color' : '#ff7f00' , 'name' : 'rRNA' } keys [ 'reads_trna' ] = { 'color' : '#1f78b4' , 'name' : 'tRNA' } keys [ 'reads_artifact' ] = { 'color' : ...
def snpsift ( self ) : """SnpSift"""
tstart = datetime . now ( ) # command = ' python % s / snpsift . py - i sanity _ check / checked . vcf 2 > log / snpsift . log ' % ( scripts _ dir ) # self . shell ( command ) ss = snpsift . SnpSift ( self . vcf_file ) ss . run ( ) tend = datetime . now ( ) execution_time = tend - tstart
def delete_service ( self , service_id ) : """Delete a service ."""
content = self . _fetch ( "/service/%s" % service_id , method = "DELETE" ) return self . _status ( content )
def read ( self , url ) : """Read storage at a given url"""
params = self . _split_url ( url ) output_stream = io . BytesIO ( ) block_blob_service = self . _block_blob_service ( account_name = params [ "account" ] , sas_token = params [ "sas_token" ] ) block_blob_service . get_blob_to_stream ( container_name = params [ "container" ] , blob_name = params [ "blob" ] , stream = ou...
def v1_tag_associate ( request , tags , tag ) : '''Associate an HTML element with a tag . The association should be a JSON serialized object on the request body . Here is an example association that should make the object ' s structure clear : . . code - block : : python " url " : " http : / / example . c...
tag = tag . decode ( 'utf-8' ) . strip ( ) assoc = dict ( json . loads ( request . body . read ( ) ) , ** { 'tag' : tag } ) tags . add ( assoc )
def plot_series ( filename , plot_kwargs = None ) : '''Plot series data from MonitorSeries output text file . Args : filename ( str ) : Path to * . series . txt file produced by : obj : ` ~ nnabla . MonitorSeries ` class . plot _ kwags ( dict , optional ) : Keyward arguments passed to : function : ` matplot...
import matplotlib . pyplot as plt if plot_kwargs is None : plot_kwargs = { } data = np . genfromtxt ( filename , dtype = 'i8,f4' , names = [ 'k' , 'v' ] ) index = data [ 'k' ] values = data [ 'v' ] plt . plot ( index , values , ** plot_kwargs )
def tag_release ( message ) : # type : ( str , bool ) - > None """Tag the current commit with as the current version release . This should be the same commit as the one that ' s uploaded as the release ( to pypi for example ) . * * Example Config * * : : version _ file : ' src / mypkg / _ _ init _ _ . py ' ...
from peltak . extra . gitflow import logic logic . release . tag ( message )
def remove_tab ( self , index ) : """Overrides removeTab to emit tab _ closed and last _ tab _ closed signals . : param index : index of the tab to remove ."""
widget = self . widget ( index ) try : document = widget . document ( ) except AttributeError : document = None # not a QPlainTextEdit clones = self . _close_widget ( widget ) self . tab_closed . emit ( widget ) self . removeTab ( index ) self . _restore_original ( clones ) widget . _original_tab_widget . _...
def publish_model ( args : argparse . Namespace , backend : StorageBackend , log : logging . Logger ) : """Push the model to Google Cloud Storage and updates the index file . : param args : : class : ` argparse . Namespace ` with " model " , " backend " , " args " , " force " , " meta " " update _ default " , " u...
path = os . path . abspath ( args . model ) try : model = GenericModel ( source = path , dummy = True ) except ValueError as e : log . critical ( '"model" must be a path: %s' , e ) return 1 except Exception as e : log . critical ( "Failed to load the model: %s: %s" % ( type ( e ) . __name__ , e ) ) ...
def concordance_index ( event_times , predicted_scores , event_observed = None ) : """Calculates the concordance index ( C - index ) between two series of event times . The first is the real survival times from the experimental data , and the other is the predicted survival times from a model of some kind . ...
event_times = np . asarray ( event_times , dtype = float ) predicted_scores = np . asarray ( predicted_scores , dtype = float ) # Allow for ( n , 1 ) or ( 1 , n ) arrays if event_times . ndim == 2 and ( event_times . shape [ 0 ] == 1 or event_times . shape [ 1 ] == 1 ) : # Flatten array event_times = event_times . ...
def solution ( self , b ) : """Checks whether an integer is solution of the current strided Interval : param b : integer to check : return : True if b belongs to the current Strided Interval , False otherwhise"""
if isinstance ( b , numbers . Number ) : b = StridedInterval ( lower_bound = b , upper_bound = b , stride = 0 , bits = self . bits ) else : raise ClaripyOperationError ( 'Oops, Strided intervals cannot be passed as "' 'parameter to function solution. To implement' ) if self . intersection ( b ) . is_empty : ...
def __generate_string ( length ) : # pragma : no cover """Generate a string for password creation ."""
return '' . join ( SystemRandom ( ) . choice ( string . ascii_letters + string . digits ) for x in range ( length ) ) . encode ( )
def create_namespaced_replica_set ( self , namespace , body , ** kwargs ) : # noqa : E501 """create _ namespaced _ replica _ set # noqa : E501 create a ReplicaSet # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > >...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . create_namespaced_replica_set_with_http_info ( namespace , body , ** kwargs ) # noqa : E501 else : ( data ) = self . create_namespaced_replica_set_with_http_info ( namespace , body , ** kwargs ) # noqa : E501 ...
def splitext ( p ) : r"""Like the normal splitext ( in posixpath ) , but doesn ' t treat dotfiles ( e . g . . emacs ) as extensions . Also uses os . sep instead of ' / ' ."""
root , ext = os . path . splitext ( p ) # check for dotfiles if ( not root or root [ - 1 ] == os . sep ) : # XXX : use ' / ' or os . sep here ? ? ? return ( root + ext , "" ) else : return root , ext
def syncLayerData ( self , layerData = None ) : """Syncs the layer information for this item from the given layer data . : param layerData | < dict > | | None"""
if not self . _layer : return if not layerData : layerData = self . _layer . layerData ( ) self . setVisible ( layerData . get ( 'visible' , True ) ) if layerData . get ( 'current' ) : # set the default parameters flags = self . ItemIsMovable flags |= self . ItemIsSelectable flags |= self . ItemIsFo...
def isemhash_unbottleneck ( x , hidden_size , isemhash_filter_size_multiplier = 1.0 ) : """Improved semantic hashing un - bottleneck ."""
filter_size = int ( hidden_size * isemhash_filter_size_multiplier ) x = 0.5 * ( x - 1.0 ) # Move from [ - 1 , 1 ] to [ 0 , 1 ] . with tf . variable_scope ( "isemhash_unbottleneck" ) : h1a = tf . layers . dense ( x , filter_size , name = "hidden1a" ) h1b = tf . layers . dense ( 1.0 - x , filter_size , name = "hi...
def get_locales ( self , package_name ) : """Retrieve a list of all available locales in a given packagename . : param package _ name : the package name to get locales of"""
self . _analyse ( ) return list ( self . values [ package_name ] . keys ( ) )
def lifted_gate ( gate : Gate , n_qubits : int ) : """Lift a pyquil : py : class : ` Gate ` in a full ` ` n _ qubits ` ` - qubit Hilbert space . This function looks up the matrix form of the gate and then dispatches to : py : func : ` lifted _ gate _ matrix ` with the target qubits . : param gate : A gate :...
if len ( gate . params ) > 0 : matrix = QUANTUM_GATES [ gate . name ] ( * gate . params ) else : matrix = QUANTUM_GATES [ gate . name ] return lifted_gate_matrix ( matrix = matrix , qubit_inds = [ q . index for q in gate . qubits ] , n_qubits = n_qubits )
def set_value ( self , value : datetime ) : """Sets the current value"""
assert isinstance ( value , datetime ) self . value = value
def user_remove_prj ( self , * args , ** kwargs ) : """Remove the selected project from the user : returns : None : rtype : None : raises : None"""
if not self . cur_user : return i = self . user_prj_tablev . currentIndex ( ) item = i . internalPointer ( ) if item : prj = item . internal_data ( ) prj . users . remove ( self . cur_user ) item . set_parent ( None )
def before_content ( self ) : """Called before parsing content . Push the class name onto the class name stack . Used to construct the full name for members ."""
ChapelObject . before_content ( self ) if self . names : self . env . temp_data [ 'chpl:class' ] = self . names [ 0 ] [ 0 ] self . clsname_set = True
def items ( self , raw = False ) : """Like ` items ` for dicts but with a ` raw ` option # Parameters _ raw _ : ` optional [ bool ] ` > Default ` False ` , if ` True ` the ` KeysView ` contains the raw values as the values # Returns ` KeysView ` > The key - value pairs of the record"""
if raw : return self . _fieldDict . items ( ) else : return collections . abc . Mapping . items ( self )
def append ( self , item ) : """Adds a new item to the end of the collection ."""
if len ( self ) == 0 : # Special case , we make this the current item self . index = 0 self . items . append ( item )
def _from_dict ( cls , _dict ) : """Initialize a Features object from a json dictionary ."""
args = { } if 'concepts' in _dict : args [ 'concepts' ] = ConceptsOptions . _from_dict ( _dict . get ( 'concepts' ) ) if 'emotion' in _dict : args [ 'emotion' ] = EmotionOptions . _from_dict ( _dict . get ( 'emotion' ) ) if 'entities' in _dict : args [ 'entities' ] = EntitiesOptions . _from_dict ( _dict . g...
def _set_counter ( self , v , load = False ) : """Setter method for counter , mapped from YANG variable / rbridge _ id / ag / counter ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ counter is considered as a private method . Backends looking to populate...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = counter . counter , is_container = 'container' , presence = False , yang_name = "counter" , rest_name = "counter" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True ,...
def p_type ( self , p ) : '''type : term | array _ type opt _ order | pointer _ type | type LIST | type SET | type LPAREN opt _ types RPAREN | type COLUMN type DICT | LPAREN types RPAREN | LARRAY type RARRAY | type OR type'''
if len ( p ) == 2 : p [ 0 ] = p [ 1 ] , elif len ( p ) == 3 and p [ 2 ] == 'list' : p [ 0 ] = tuple ( List [ t ] for t in p [ 1 ] ) elif len ( p ) == 3 and p [ 2 ] == 'set' : p [ 0 ] = tuple ( Set [ t ] for t in p [ 1 ] ) elif len ( p ) == 3 : if p [ 2 ] is None : expanded = [ ] for nd i...
def get_section ( self , * key ) : """The recommended way of retrieving a section by key when extending configmanager ' s behaviour ."""
section = self . _get_item_or_section ( key ) if not section . is_section : raise RuntimeError ( '{} is an item, not a section' . format ( key ) ) return section
def autocomplete ( self , name , context_name = None , include_dubious = False ) : """Takes a name and optional context _ name returns a list of matches . Each match is a dict with : ' higher ' boolean DEF ? ? ? ' exact ' boolean for exact match ' ottId ' int ' name ' name ( or uniqname ? ? ? ) for the ta...
if context_name and context_name not in self . valid_contexts : raise ValueError ( '"{}" is not a valid context name' . format ( context_name ) ) if self . use_v1 : uri = '{p}/autocompleteBoxQuery' . format ( p = self . prefix ) data = { 'queryString' : name } if context_name : data [ 'contextNa...
def gauss_fit ( X , Y ) : """Fit the function to a gaussian . Parameters X : 1d array X values Y : 1d array Y values Returns ( The return from scipy . optimize . curve _ fit ) popt : array Optimal values for the parameters pcov : 2d array The estimated covariance of popt . Notes / ! \ This...
X = np . asarray ( X ) Y = np . asarray ( Y ) # Can not have negative values Y [ Y < 0 ] = 0 # define gauss function def gauss ( x , a , x0 , sigma ) : return a * np . exp ( - ( x - x0 ) ** 2 / ( 2 * sigma ** 2 ) ) # get first estimation for parameter mean = ( X * Y ) . sum ( ) / Y . sum ( ) sigma = np . sqrt ( ( Y...
def calculate_total_amt ( self , items = { } ) : """Returns the total amount / cost of items in the current invoice"""
_items = items . items ( ) or self . items . items ( ) return sum ( float ( x [ 1 ] . total_price ) for x in _items )
def is_iterable ( value , include_maps = False , include_sets = True ) : """Returns whether value is iterable . ` ` include _ maps ` ` Maps are technically iterable , defaulting to their keys , but you commonly want to find if it is a list - like type and leave maps alone , so this is False by default . `...
if hasattr ( value , '__iter__' ) : if not include_maps and hasattr ( value , 'keys' ) : return False if not include_sets and hasattr ( value , 'isdisjoint' ) : return False return True else : return False
def filter ( self , obj , * args , ** kwargs ) : """Filter the given object through the filter chain . : param obj : The object to filter : param args : Additional arguments to pass to each filter function . : param kwargs : Additional keyword arguments to pass to each filter function . : return : The fil...
for _ , _ , func in self . _filter_order : obj = func ( obj , * args , ** kwargs ) if obj is None : return None return obj
def _check_time_range ( time_range , now ) : '''Check time range'''
if _TIME_SUPPORTED : _start = dateutil_parser . parse ( time_range [ 'start' ] ) _end = dateutil_parser . parse ( time_range [ 'end' ] ) return bool ( _start <= now <= _end ) else : log . error ( 'Dateutil is required.' ) return False
def ensure_scheme ( url , default_scheme = 'http' ) : """Adds a scheme to a url if not present . Args : url ( string ) : a url , assumed to start with netloc default _ scheme ( string ) : a scheme to be added Returns : string : URL with a scheme"""
parsed = urlsplit ( url , scheme = default_scheme ) if not parsed . netloc : parsed = SplitResult ( scheme = parsed . scheme , netloc = parsed . path , path = '' , query = parsed . query , fragment = parsed . fragment ) return urlunsplit ( parsed )
def get ( method , hmc , uri , uri_parms , logon_required ) : """Operation : List LDAP Server Definitions ."""
query_str = uri_parms [ 0 ] try : console = hmc . consoles . lookup_by_oid ( None ) except KeyError : raise InvalidResourceError ( method , uri ) result_ldap_srv_defs = [ ] filter_args = parse_query_parms ( method , uri , query_str ) for ldap_srv_def in console . ldap_server_definitions . list ( filter_args ) :...
def cache_invalidate_by_tags ( tags , cache = None ) : """Clear cache by tags ."""
if isinstance ( tags , basestring ) : tags = [ tags ] tag_keys = [ CACHE_TAG_KEY % tag for tag in tags if tag ] if not tag_keys : raise ValueError ( 'Attr tags invalid' ) if cache is None : cache = default_cache tag_keys_for_delete = [ ] if cache . __class__ . __name__ == 'RedisCache' : from django_redi...
async def serve ( http_handler : HTTP_WRAPPER_TYPE , websocket_handler = None , address : str = '127.0.0.1' , port : int = 8000 ) : """start server"""
return await asyncio . start_server ( SocketWrapper ( http_handler , websocket_handler ) , address , port )
def interpolations_to_summary ( sample_ind , interpolations , first_frame , last_frame , hparams , decode_hp ) : """Converts interpolated frames into tf summaries . The summaries consists of : 1 . Image summary corresponding to the first frame . 2 . Image summary corresponding to the last frame . 3 . The in...
parent_tag = "sample_%d" % sample_ind frame_shape = hparams . problem . frame_shape interp_shape = [ hparams . batch_size , decode_hp . num_interp ] + frame_shape interpolations = np . reshape ( interpolations , interp_shape ) interp_tag = "%s/interp/%s" % ( parent_tag , decode_hp . channel_interp ) if decode_hp . chan...
def get_handler_classes ( self ) : """Return the list of handlers to use when receiving RPC requests ."""
handler_classes = [ import_string ( handler_cls ) for handler_cls in settings . MODERNRPC_HANDLERS ] if self . protocol == ALL : return handler_classes else : return [ cls for cls in handler_classes if cls . protocol in ensure_sequence ( self . protocol ) ]
def __search ( self ) : """Performs the search ."""
self . __search_results = [ ] editorsFiles = self . __container . default_target in self . __location . targets and [ editor . file for editor in self . __container . script_editor . list_editors ( ) ] or [ ] self . __search_editors_files ( editorsFiles ) self . __search_files ( self . __location . files ) for director...
def get_workflows ( self ) : """Scans and loads all wf found under WORKFLOW _ PACKAGES _ PATHS Yields : XML content of diagram file"""
for pth in settings . WORKFLOW_PACKAGES_PATHS : for f in glob . glob ( "%s/*.bpmn" % pth ) : with open ( f ) as fp : yield os . path . basename ( os . path . splitext ( f ) [ 0 ] ) , fp . read ( )
def export_aggregate_by_csv ( ekey , dstore ) : """: param ekey : export key , i . e . a pair ( datastore key , fmt ) : param dstore : datastore object"""
token , what = ekey [ 0 ] . split ( '/' , 1 ) aw = extract ( dstore , 'aggregate/' + what ) fnames = [ ] writer = writers . CsvWriter ( fmt = writers . FIVEDIGITS ) path = '%s.%s' % ( sanitize ( ekey [ 0 ] ) , ekey [ 1 ] ) fname = dstore . export_path ( path ) writer . save ( aw . to_table ( ) , fname ) fnames . append...
def generate_id_token ( self , name , audience , delegates = None , include_email = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Generates an OpenID Connect ID token for a service account . Example : > > > f...
# Wrap the transport method to add retry and timeout logic . if "generate_id_token" not in self . _inner_api_calls : self . _inner_api_calls [ "generate_id_token" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . generate_id_token , default_retry = self . _method_configs [ "GenerateIdToke...