signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def sync ( infile , outfile ) :
"""Sync ( download ) latest policies from the Anchore . io service .""" | ecode = 0
try :
rc , ret = anchore_policy . sync_policymeta ( bundlefile = infile , outfile = outfile )
if not rc :
anchore_print_err ( ret [ 'text' ] )
ecode = 1
elif outfile and outfile == '-' :
anchore_print ( ret [ 'text' ] )
except Exception as err :
anchore_print_err ( 'ope... |
def register_blueprint ( self , blueprint ) :
'''Register given blueprint on curren app .
This method is provided for using inside plugin ' s module - level
: func : ` register _ plugin ` functions .
: param blueprint : blueprint object with plugin endpoints
: type blueprint : flask . Blueprint''' | if blueprint not in self . _blueprint_known :
self . app . register_blueprint ( blueprint )
self . _blueprint_known . add ( blueprint ) |
def store_fw_db_router ( self , tenant_id , net_id , subnet_id , router_id , os_status ) :
"""Store the result of FW router operation in DB .
Calls the service object routine to commit the result of router
operation in to DB , after updating the local cache .""" | serv_obj = self . get_service_obj ( tenant_id )
serv_obj . update_fw_local_router ( net_id , subnet_id , router_id , os_status )
serv_obj . commit_fw_db ( )
serv_obj . commit_fw_db_result ( ) |
def end ( self ) :
"""Finalise lz4 frame , outputting any remaining as return from this function or by writing to fp )""" | with self . __lock :
if self . __write :
self . __write ( compress_end ( self . __ctx ) )
else :
return compress_end ( self . __ctx ) |
def can_fetch ( self , useragent , url ) :
"""Using the parsed robots . txt decide if useragent can fetch url .
@ return : True if agent can fetch url , else False
@ rtype : bool""" | log . debug ( LOG_CHECK , "%r check allowance for:\n user agent: %r\n url: %r ..." , self . url , useragent , url )
if not isinstance ( useragent , str ) :
useragent = useragent . encode ( "ascii" , "ignore" )
if not isinstance ( url , str ) :
url = url . encode ( "ascii" , "ignore" )
if self . disallow_all :... |
def rebin_scale ( a , scale = 1 ) :
"""Scale an array to a new shape .""" | newshape = tuple ( ( side * scale ) for side in a . shape )
return rebin ( a , newshape ) |
def _aha_request ( self , cmd , ain = None , param = None , rf = str ) :
"""Send an AHA request .""" | url = 'http://' + self . _host + '/webservices/homeautoswitch.lua'
params = { 'switchcmd' : cmd , 'sid' : self . _sid }
if param :
params [ 'param' ] = param
if ain :
params [ 'ain' ] = ain
plain = self . _request ( url , params )
if plain == 'inval' :
raise InvalidError
if rf == bool :
return bool ( in... |
def create ( cls , data , path = None , defaults = None , overwrite = False , random_id = False , ** kwargs ) :
"""Creates a new database object and stores it in the database
NOTE : The path and defaults parameters to this function are to allow
use of the DatabaseObject class directly . However , this class is ... | self = cls ( path = path , defaults = defaults , _new_object = data )
for key , value in self . items ( ) :
if key == ID_KEY :
continue
if self . DEFAULTS and key not in self . DEFAULTS :
self . _handle_non_default_key ( key , value )
self . _check_type ( key , value )
if random_id and ID_KE... |
def process_insert_get_id ( self , query , sql , values , sequence = None ) :
"""Process an " insert get ID " query .
: param query : A QueryBuilder instance
: type query : QueryBuilder
: param sql : The sql query to execute
: type sql : str
: param values : The value bindings
: type values : list
: p... | result = query . get_connection ( ) . select_from_write_connection ( sql , values )
id = result [ 0 ] [ 0 ]
if isinstance ( id , int ) :
return id
if str ( id ) . isdigit ( ) :
return int ( id )
return id |
def identity ( self ) :
"""A unique identifier for the current visitor .""" | if hasattr ( self . _identity , 'get_identity' ) :
return self . _identity . get_identity ( self . _environ )
return self . _identity ( self . _environ ) |
def find_geo_coords ( s ) :
"""Returns a list of lat / lons found by scanning the given text""" | coords = [ ]
LOG . debug ( "Matching in text size %s" , len ( s ) )
for c in INFO_BOX_LAT_LON . findall ( s ) :
try :
coord = ( float ( c [ 1 ] ) , float ( c [ 2 ] ) )
# , c [ 0 ] )
coords . append ( coord )
LOG . debug ( "Found info box lat/lon: %s" , coord )
except Exception as... |
def _check_pip_installed ( ) :
"""Invoke ` pip - - version ` and make sure it doesn ' t error .
Use check _ output to capture stdout and stderr
Invokes pip by the same manner that we plan to in _ call _ pip ( )
Don ' t bother trying to reuse _ call _ pip to do this . . . Finnicky and not worth
the effort ."... | try :
subprocess . check_output ( [ sys . executable , "-m" , "pip" , "--version" ] , stderr = subprocess . STDOUT )
return True
except subprocess . CalledProcessError :
return False |
def evaluate_cut ( uncut_subsystem , cut , unpartitioned_ces ) :
"""Compute the system irreducibility for a given cut .
Args :
uncut _ subsystem ( Subsystem ) : The subsystem without the cut applied .
cut ( Cut ) : The cut to evaluate .
unpartitioned _ ces ( CauseEffectStructure ) : The cause - effect struc... | log . debug ( 'Evaluating %s...' , cut )
cut_subsystem = uncut_subsystem . apply_cut ( cut )
if config . ASSUME_CUTS_CANNOT_CREATE_NEW_CONCEPTS :
mechanisms = unpartitioned_ces . mechanisms
else : # Mechanisms can only produce concepts if they were concepts in the
# original system , or the cut divides the mechanis... |
def render ( self , form = None , ** kwargs ) :
"""Returns the ` ` HttpResponse ` ` with the context data""" | context = self . get_context ( ** kwargs )
return self . render_to_response ( context ) |
def new ( self , bootstrap_with = None , use_timer = False , with_proof = False ) :
"""Actual constructor of the solver .""" | if not self . maplesat :
self . maplesat = pysolvers . maplechrono_new ( )
if bootstrap_with :
for clause in bootstrap_with :
self . add_clause ( clause )
self . use_timer = use_timer
self . call_time = 0.0
# time spent for the last call to oracle
self . accu_time = 0.0
#... |
def _serve_file ( self , path ) :
"""Call Paste ' s FileApp ( a WSGI application ) to serve the file
at the specified path""" | request = self . _py_object . request
request . environ [ 'PATH_INFO' ] = '/%s' % path
return PkgResourcesParser ( 'pylons' , 'pylons' ) ( request . environ , self . start_response ) |
def execute ( self , conn , file_id_list , transaction = False ) :
"""file _ id _ list : file _ id _ list""" | sql = self . sql
binds = { }
if file_id_list :
count = 0
for an_id in file_id_list :
if count > 0 :
sql += ", "
sql += ":file_id_%s" % count
binds . update ( { "file_id_%s" % count : an_id } )
count += 1
sql += ")"
else :
dbsExceptionHandler ( 'dbsException-in... |
def parse ( input , server = default_erg_server , params = None , headers = None ) :
"""Request a parse of * input * on * server * and return the response .
Args :
input ( str ) : sentence to be parsed
server ( str ) : the url for the server ( the default LOGON server
is used by default )
params ( dict ) ... | return next ( parse_from_iterable ( [ input ] , server , params , headers ) , None ) |
def save ( self , directory = None ) :
"""Dump the entire contents of the database into the tabledata directory as ascii files""" | from subprocess import call
# If user did not supply a new directory , use the one loaded ( default : tabledata )
if isinstance ( directory , type ( None ) ) :
directory = self . directory
# Create the . sql file is it doesn ' t exist , i . e . if the Database class called a . db file initially
if not os . path . i... |
def _pos ( self , k ) :
"""Description :
Position k breaking
Parameters :
k : position k is used for the breaking""" | if k < 2 :
raise ValueError ( "k smaller than 2" )
G = np . zeros ( ( self . m , self . m ) )
for i in range ( self . m ) :
for j in range ( self . m ) :
if i == j :
continue
if i < k or j < k :
continue
if i == k or j == k :
G [ i ] [ j ] = 1
return G |
def psf_convolution ( self , grid , grid_scale , psf_subgrid = False , subgrid_res = 1 ) :
"""convolves a given pixel grid with a PSF""" | psf_type = self . psf_type
if psf_type == 'NONE' :
return grid
elif psf_type == 'GAUSSIAN' :
sigma = self . _sigma_gaussian / grid_scale
img_conv = ndimage . filters . gaussian_filter ( grid , sigma , mode = 'nearest' , truncate = self . _truncation )
return img_conv
elif psf_type == 'PIXEL' :
if ps... |
def ip_addrs6 ( interface = None , include_loopback = False , cidr = None ) :
'''Returns a list of IPv6 addresses assigned to the host .
interface
Only IP addresses from that interface will be returned .
include _ loopback : False
Include loopback : : 1 IPv6 address .
cidr
Describes subnet using CIDR no... | addrs = salt . utils . network . ip_addrs6 ( interface = interface , include_loopback = include_loopback )
if cidr :
return [ i for i in addrs if salt . utils . network . in_subnet ( cidr , [ i ] ) ]
else :
return addrs |
def _create_fulltext_query ( self ) :
"""Support the json - server fulltext search with a broad LIKE filter .""" | filter_by = [ ]
if 'q' in request . args :
columns = flat_model ( model_tree ( self . __class__ . __name__ , self . model_cls ) )
for q in request . args . getlist ( 'q' ) :
filter_by += [ '{col}::like::%{q}%' . format ( col = col , q = q ) for col in columns ]
return filter_by |
def counter ( self , counter_name , default = 0 ) :
"""Get the current counter value .
Args :
counter _ name : name of the counter in string .
default : default value in int if one doesn ' t exist .
Returns :
Current value of the counter .""" | return self . _state . counters_map . get ( counter_name , default ) |
def _init_id2gos ( assoc_fn ) : # # , no _ top = False ) :
"""Reads a gene id go term association file . The format of the file
is as follows :
AAR1GO : 0005575 ; GO : 0003674 ; GO : 0006970 ; GO : 0006970 ; GO : 0040029
AAR2GO : 0005575 ; GO : 0003674 ; GO : 0040029 ; GO : 0009845
ACD5GO : 0005575 ; GO : 0... | assoc = cx . defaultdict ( set )
# # top _ terms = set ( [ ' GO : 0008150 ' , ' GO : 0003674 ' , ' GO : 0005575 ' ] ) # BP , MF , CC
for row in open ( assoc_fn , 'r' ) :
atoms = row . split ( )
if len ( atoms ) == 2 :
gene_id , go_terms = atoms
elif len ( atoms ) > 2 and row . count ( '\t' ) == 1 :
... |
def path_expand ( text ) :
"""returns a string with expanded variable .
: param text : the path to be expanded , which can include ~ and environment $ variables
: param text : string""" | result = os . path . expandvars ( os . path . expanduser ( text ) )
# template = Template ( text )
# result = template . substitute ( os . environ )
if result . startswith ( "." ) :
result = result . replace ( "." , os . getcwd ( ) , 1 )
return result |
def dict_merge ( dct , merge_dct ) :
"""Recursive dict merge . Inspired by : meth : ` ` dict . update ( ) ` ` , instead of
updating only top - level keys , dict _ merge recurses down into dicts nested
to an arbitrary depth , updating keys . The ` ` merge _ dct ` ` is merged into
` ` dct ` ` .
: param dct : ... | for k , v in merge_dct . items ( ) :
if ( k in dct and isinstance ( dct [ k ] , dict ) and isinstance ( v , dict ) ) :
dict_merge ( dct [ k ] , v )
else :
dct [ k ] = v |
def is_tango_object ( arg ) :
"""Return tango data if the argument is a tango object ,
False otherwise .""" | classes = attribute , device_property
if isinstance ( arg , classes ) :
return arg
try :
return arg . __tango_command__
except AttributeError :
return False |
def import_process_template ( self , upload_stream , ignore_warnings = None , ** kwargs ) :
"""ImportProcessTemplate .
[ Preview API ] Imports a process from zip file .
: param object upload _ stream : Stream to upload
: param bool ignore _ warnings : Default value is false
: rtype : : class : ` < ProcessIm... | route_values = { }
route_values [ 'action' ] = 'Import'
query_parameters = { }
if ignore_warnings is not None :
query_parameters [ 'ignoreWarnings' ] = self . _serialize . query ( 'ignore_warnings' , ignore_warnings , 'bool' )
if "callback" in kwargs :
callback = kwargs [ "callback" ]
else :
callback = None... |
def _parse_args ( args : List [ str ] ) -> _SetArgumentsRunConfig :
"""Parses the given CLI arguments to get a run configuration .
: param args : CLI arguments
: return : run configuration derived from the given CLI arguments""" | parser = argparse . ArgumentParser ( prog = "gitlab-set-variables" , description = "Tool for setting a GitLab project's build variables" )
add_common_arguments ( parser , project = True )
parser . add_argument ( "source" , nargs = "+" , type = str , help = "File to source build variables from. Can be a ini file, JSON f... |
def clone ( self , ** keywd ) :
"""constructs new argument _ t instance
return argument _ t (
name = keywd . get ( ' name ' , self . name ) ,
decl _ type = keywd . get ( ' decl _ type ' , self . decl _ type ) ,
default _ value = keywd . get ( ' default _ value ' , self . default _ value ) ,
attributes = k... | return argument_t ( name = keywd . get ( 'name' , self . name ) , decl_type = keywd . get ( 'decl_type' , self . decl_type ) , default_value = keywd . get ( 'default_value' , self . default_value ) , attributes = keywd . get ( 'attributes' , self . attributes ) ) |
def grab ( self , * keys : typing . List [ str ] , default_value = None ) -> typing . Tuple :
"""Returns a tuple containing multiple values from the cache specified by
the keys arguments
: param keys :
One or more variable names stored in the cache that should be
returned by the grab function . The order of... | return tuple ( [ self . fetch ( k , default_value ) for k in keys ] ) |
def standardize_back ( xs , offset , scale ) :
"""This is function for de - standarization of input series .
* * Args : * *
* ` xs ` : standardized input ( 1 dimensional array )
* ` offset ` : offset to add ( float ) .
* ` scale ` : scale ( float ) .
* * Returns : * *
* ` x ` : original ( destandardised... | try :
offset = float ( offset )
except :
raise ValueError ( 'The argument offset is not None or float.' )
try :
scale = float ( scale )
except :
raise ValueError ( 'The argument scale is not None or float.' )
try :
xs = np . array ( xs , dtype = "float64" )
except :
raise ValueError ( 'The argum... |
def getControls ( self ) :
'''Calculates consumption for each consumer of this type using the consumption functions .
Parameters
None
Returns
None''' | cNrmNow = np . zeros ( self . AgentCount ) + np . nan
for t in range ( self . T_cycle ) :
these = t == self . t_cycle
cNrmNow [ these ] = self . solution [ t ] . cFunc ( self . mNrmNow [ these ] , self . PrefShkNow [ these ] )
self . cNrmNow = cNrmNow
return None |
def qstat ( self , queue_name , return_dict = False ) :
"""Return the status of the queue ( currently unimplemented ) .
Future support / testing of QSTAT support in Disque
QSTAT < qname >
Return produced . . . consumed . . . idle . . . sources [ . . . ] ctime . . .""" | rtn = self . execute_command ( 'QSTAT' , queue_name )
if return_dict :
grouped = self . _grouper ( rtn , 2 )
rtn = dict ( ( a , b ) for a , b in grouped )
return rtn |
def add_external_parameter ( self , parameter ) :
"""Add a parameter that comes from something other than a function , to the model .
: param parameter : a Parameter instance
: return : none""" | assert isinstance ( parameter , Parameter ) , "Variable must be an instance of IndependentVariable"
if self . _has_child ( parameter . name ) : # Remove it from the children only if it is a Parameter instance , otherwise don ' t , which will
# make the _ add _ child call fail ( which is the expected behaviour ! You sho... |
def get_variants ( self , chromosome = None , start = None , end = None ) :
"""Return all variants in the database
If no region is specified all variants will be returned .
Args :
chromosome ( str )
start ( int )
end ( int )
Returns :
variants ( Iterable ( Variant ) )""" | query = { }
if chromosome :
query [ 'chrom' ] = chromosome
if start :
query [ 'start' ] = { '$lte' : end }
query [ 'end' ] = { '$gte' : start }
LOG . info ( "Find all variants {}" . format ( query ) )
return self . db . variant . find ( query ) . sort ( [ ( 'start' , ASCENDING ) ] ) |
def volume_attach ( provider , names , ** kwargs ) :
'''Attach volume to a server
CLI Example :
. . code - block : : bash
salt minionname cloud . volume _ attach my - nova myblock server _ name = myserver device = ' / dev / xvdf ' ''' | client = _get_client ( )
info = client . extra_action ( provider = provider , names = names , action = 'volume_attach' , ** kwargs )
return info |
def updateMesh ( self , polydata ) :
"""Overwrite the polygonal mesh of the actor with a new one .""" | self . poly = polydata
self . mapper . SetInputData ( polydata )
self . mapper . Modified ( )
return self |
async def on_isupport_invex ( self , value ) :
"""Server allows invite exceptions .""" | if not value :
value = INVITE_EXCEPT_MODE
self . _channel_modes . add ( value )
self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_LIST ] . add ( value ) |
def is_writable_attr ( ext ) :
"""Check if an extension attribute is writable .
ext ( tuple ) : The ( default , getter , setter , method ) tuple available via
{ Doc , Span , Token } . get _ extension .
RETURNS ( bool ) : Whether the attribute is writable .""" | default , method , getter , setter = ext
# Extension is writable if it has a setter ( getter + setter ) , if it has a
# default value ( or , if its default value is none , none of the other values
# should be set ) .
if setter is not None or default is not None or all ( e is None for e in ext ) :
return True
return... |
def project_activity ( index , start , end ) :
"""Compute the metrics for the project activity section of the enriched
github issues index .
Returns a dictionary containing a " metric " key . This key contains the
metrics for this section .
: param index : index object
: param start : start date to get th... | results = { "metrics" : [ OpenedIssues ( index , start , end ) , ClosedIssues ( index , start , end ) ] }
return results |
def lines_touch_2D ( ab , cd ) :
'''lines _ touch _ 2D ( ( a , b ) , ( c , d ) ) is equivalent to lines _ colinear ( ( a , b ) , ( c , d ) ) |
numpy . isfinite ( line _ intersection _ 2D ( ( a , b ) , ( c , d ) ) [ 0 ] )''' | return lines_colinear ( ab , cd ) | np . isfinite ( line_intersection_2D ( ab , cd ) [ 0 ] ) |
def load ( self , rel_path = None ) :
"""Add sim _ src to layer .""" | for k , v in self . layer . iteritems ( ) :
self . add ( k , v [ 'module' ] , v . get ( 'package' ) )
filename = v . get ( 'filename' )
path = v . get ( 'path' )
if filename :
warnings . warn ( DeprecationWarning ( SIMFILE_LOAD_WARNING ) )
# default path for data is in . . / simulations
... |
def make_list ( self , end_token = "]" ) :
"""We are in a list so get values until the end token . This can also
used to get tuples .""" | out = [ ]
while True :
try :
value = self . value_assign ( end_token = end_token )
out . append ( value )
self . separator ( end_token = end_token )
except self . ParseEnd :
return out |
def main ( ) :
"""Main entry point""" | parser = OptionParser ( )
parser . add_option ( '-a' , '--hostname' , help = 'ClamAV source server hostname' , dest = 'hostname' , type = 'str' , default = 'db.de.clamav.net' )
parser . add_option ( '-r' , '--text-record' , help = 'ClamAV Updates TXT record' , dest = 'txtrecord' , type = 'str' , default = 'current.cvd.... |
def makeInstance ( self , instanceDescriptor , doRules = False , glyphNames = None , pairs = None , bend = False ) :
"""Generate a font object for this instance""" | font = self . _instantiateFont ( None )
# make fonty things here
loc = Location ( instanceDescriptor . location )
anisotropic = False
locHorizontal = locVertical = loc
if self . isAnisotropic ( loc ) :
anisotropic = True
locHorizontal , locVertical = self . splitAnisotropic ( loc )
# groups
renameMap = getattr ... |
def evaluate_errors ( json_response ) :
"""Evaluate rest errors .""" | if 'errors' not in json_response or not isinstance ( json_response [ 'errors' ] , list ) or not json_response [ 'errors' ] or not isinstance ( json_response [ 'errors' ] [ 0 ] , int ) :
raise PyVLXException ( 'Could not evaluate errors {0}' . format ( json . dumps ( json_response ) ) )
# unclear if response may con... |
def run ( self , name , replace = None , actions = None ) :
"""Do an action .
If ` replace ` is provided as a dictionary , do a search / replace using
% { } templates on content of action ( unique to action type )""" | self . actions = actions
# incase we use group
action = actions . get ( name )
if not action :
self . die ( "Action not found: {}" , name )
action [ 'name' ] = name
action_type = action . get ( 'type' , "none" )
try :
func = getattr ( self , '_run__' + action_type )
except AttributeError :
self . die ( "Uns... |
def binned_entropy ( x , max_bins ) :
"""First bins the values of x into max _ bins equidistant bins .
Then calculates the value of
. . math : :
- \\ sum _ { k = 0 } ^ { min ( max \\ _ bins , len ( x ) ) } p _ k log ( p _ k ) \\ cdot \\ mathbf { 1 } _ { ( p _ k > 0 ) }
where : math : ` p _ k ` is the percen... | if not isinstance ( x , ( np . ndarray , pd . Series ) ) :
x = np . asarray ( x )
hist , bin_edges = np . histogram ( x , bins = max_bins )
probs = hist / x . size
return - np . sum ( p * np . math . log ( p ) for p in probs if p != 0 ) |
def add_options ( self ) :
"""Add program options .""" | super ( ThemeSwitcher , self ) . add_options ( )
self . add_bool_option ( "-l" , "--list" , help = "list available themes" )
self . add_bool_option ( "-c" , "--current" , help = "print path to currently selected theme" )
self . add_bool_option ( "-n" , "--next" , help = "rotate through selected themes, and print new pa... |
def set_block ( arr , arr_block ) :
"""Sets the diagonal blocks of an array to an given array
Parameters
arr : numpy ndarray
the original array
block _ arr : numpy ndarray
the block array for the new diagonal
Returns
numpy ndarray ( the modified array )""" | nr_col = arr . shape [ 1 ]
nr_row = arr . shape [ 0 ]
nr_col_block = arr_block . shape [ 1 ]
nr_row_block = arr_block . shape [ 0 ]
if np . mod ( nr_row , nr_row_block ) or np . mod ( nr_col , nr_col_block ) :
raise ValueError ( 'Number of rows/columns of the input array ' 'must be a multiple of block shape' )
if n... |
def dP_demister_dry_Setekleiv_Svendsen ( S , voidage , vs , rho , mu , L = 1 ) :
r'''Calculates dry pressure drop across a demister , using the
correlation in [ 1 ] _ . This model is for dry demisters with no holdup only .
. . math : :
\ frac { \ Delta P \ epsilon ^ 2 } { \ rho _ f v ^ 2 } = 10.29 - \ frac { ... | term = 10.29 - 565. / ( 69.6 * S * L - ( S * L ) ** 2 - 779 ) - 74.9 / ( 160.9 - 4.85 * S * L )
right = term + 45.33 * ( mu * voidage * S ** 2 * L / rho / vs ) ** 0.75
return right * rho * vs ** 2 / voidage ** 2 |
def scan ( client , query = None , scroll = "5m" , raise_on_error = True , preserve_order = False , size = 1000 , request_timeout = None , clear_scroll = True , scroll_kwargs = None , ** kwargs ) :
"""Simple abstraction on top of the
: meth : ` ~ elasticsearch . Elasticsearch . scroll ` api - a simple iterator th... | scroll_kwargs = scroll_kwargs or { }
if not preserve_order :
query = query . copy ( ) if query else { }
query [ "sort" ] = "_doc"
# initial search
resp = client . search ( body = query , scroll = scroll , size = size , request_timeout = request_timeout , ** kwargs )
scroll_id = resp . get ( "_scroll_id" )
try :... |
def _user_settings ( self ) :
"""Resolve settings dict from django settings module .
Validate that all the required keys are present and also that none of
the removed keys do .
Result is cached .""" | user_settings = getattr ( settings , self . _name , { } )
if not user_settings and self . _required :
raise ImproperlyConfigured ( "Settings file is missing dict options with name {}" . format ( self . _name ) )
keys = frozenset ( user_settings . keys ( ) )
required = self . _required - keys
if required :
raise... |
def bytes2guid ( s ) :
"""Converts a serialized GUID to a text GUID""" | assert isinstance ( s , bytes )
u = struct . unpack
v = [ ]
v . extend ( u ( "<IHH" , s [ : 8 ] ) )
v . extend ( u ( ">HQ" , s [ 8 : 10 ] + b"\x00\x00" + s [ 10 : ] ) )
return "%08X-%04X-%04X-%04X-%012X" % tuple ( v ) |
def trim_trailing_silence ( obj ) :
"""Return a copy of the object with trimmed trailing silence of the
piano - roll ( s ) .""" | _check_supported ( obj )
copied = deepcopy ( obj )
length = copied . get_active_length ( )
copied . pianoroll = copied . pianoroll [ : length ]
return copied |
def insert_graph ( self , graph : BELGraph , store_parts : bool = True , use_tqdm : bool = False ) -> Network :
"""Insert a graph in the database and returns the corresponding Network model .
: raises : pybel . resources . exc . ResourceError""" | if not graph . name :
raise ValueError ( 'Can not upload a graph without a name' )
if not graph . version :
raise ValueError ( 'Can not upload a graph without a version' )
log . debug ( 'inserting %s v%s' , graph . name , graph . version )
t = time . time ( )
self . ensure_default_namespace ( )
namespace_urls =... |
def make ( cls , ** kwargs ) :
"""Create a container .
Reports extra keys as well as missing ones .
Thanks to habnabit for the idea !""" | cls_attrs = { f . name : f for f in attr . fields ( cls ) }
unknown = { k : v for k , v in kwargs . items ( ) if k not in cls_attrs }
if len ( unknown ) > 0 :
_LOGGER . warning ( "Got unknowns for %s: %s - please create an issue!" , cls . __name__ , unknown )
missing = [ k for k in cls_attrs if k not in kwargs ]
da... |
def is_c_extension ( module : ModuleType ) -> bool :
"""Modified from
https : / / stackoverflow . com / questions / 20339053 / in - python - how - can - one - tell - if - a - module - comes - from - a - c - extension .
` ` True ` ` only if the passed module is a C extension implemented as a
dynamically linked... | # noqa
assert inspect . ismodule ( module ) , '"{}" not a module.' . format ( module )
# If this module was loaded by a PEP 302 - compliant CPython - specific loader
# loading only C extensions , this module is a C extension .
if isinstance ( getattr ( module , '__loader__' , None ) , ExtensionFileLoader ) :
return... |
def complexity_fd_higushi ( signal , k_max ) :
"""Computes Higuchi Fractal Dimension of a signal . Based on the ` pyrem < https : / / github . com / gilestrolab / pyrem > ` _ repo by Quentin Geissmann .
Parameters
signal : list or array
List or array of values .
k _ max : int
The maximal value of k . The ... | signal = np . array ( signal )
L = [ ]
x = [ ]
N = signal . size
km_idxs = np . triu_indices ( k_max - 1 )
km_idxs = k_max - np . flipud ( np . column_stack ( km_idxs ) ) - 1
km_idxs [ : , 1 ] -= 1
for k in range ( 1 , k_max ) :
Lk = 0
for m in range ( 0 , k ) : # we pregenerate all idxs
idxs = np . ara... |
def source_to_unicode ( txt , errors = 'replace' , skip_encoding_cookie = True ) :
"""Converts a bytes string with python source code to unicode .
Unicode strings are passed through unchanged . Byte strings are checked
for the python source file encoding cookie to determine encoding .
txt can be either a byte... | if isinstance ( txt , six . text_type ) :
return txt
if isinstance ( txt , six . binary_type ) :
buffer = io . BytesIO ( txt )
else :
buffer = txt
try :
encoding , _ = detect_encoding ( buffer . readline )
except SyntaxError :
encoding = "ascii"
buffer . seek ( 0 )
newline_decoder = io . Incremental... |
def _assign_value_by_type ( self , pbuf_obj , value , _bool = True , _float = True , _integer = True , _string = True , error_prefix = '' ) :
"""Assigns the supplied value to the appropriate protobuf value type""" | # bool inherits int , so bool instance check must be executed prior to
# checking for integer types
if isinstance ( value , bool ) and _bool is True :
pbuf_obj . value . boolValue = value
elif isinstance ( value , six . integer_types ) and not isinstance ( value , bool ) and _integer is True :
if value < INTEGE... |
def terminate ( self , wait = False ) :
"""Terminate the process .""" | if self . proc is not None :
self . proc . stdout . close ( )
try :
self . proc . terminate ( )
except ProcessLookupError :
pass
if wait :
self . proc . wait ( ) |
def list_subnets ( self , retrieve_all = True , ** _params ) :
"""Fetches a list of all subnets for a project .""" | return self . list ( 'subnets' , self . subnets_path , retrieve_all , ** _params ) |
def send ( self , auto_complete = True , callback = None ) :
"""Begin uploading file ( s ) and sending email ( s ) .
If ` auto _ complete ` is set to ` ` False ` ` you will have to call the
: func : ` Transfer . complete ` function at a later stage .
: param auto _ complete : Whether or not to mark transfer a... | tot = len ( self . files )
url = self . transfer_info [ 'transferurl' ]
for index , fmfile in enumerate ( self . files ) :
msg = 'Uploading: "{filename}" ({cur}/{tot})'
logger . debug ( msg . format ( filename = fmfile [ 'thefilename' ] , cur = index + 1 , tot = tot ) )
with open ( fmfile [ 'filepath' ] , '... |
def _check_refer_redirect ( self , environ ) :
"""Returns a WbResponse for a HTTP 307 redirection if the HTTP referer header is the same as the HTTP host header
: param dict environ : The WSGI environment dictionary for the request
: return : WbResponse HTTP 307 redirection
: rtype : WbResponse""" | referer = environ . get ( 'HTTP_REFERER' )
if not referer :
return
host = environ . get ( 'HTTP_HOST' )
if host not in referer :
return
inx = referer [ 1 : ] . find ( 'http' )
if not inx :
inx = referer [ 1 : ] . find ( '///' )
if inx > 0 :
inx + 1
if inx < 0 :
return
url = referer [ inx + 1... |
def removeID ( self , attr ) :
"""Remove the given attribute from the ID table maintained
internally .""" | if attr is None :
attr__o = None
else :
attr__o = attr . _o
ret = libxml2mod . xmlRemoveID ( self . _o , attr__o )
return ret |
def __StripName ( self , name ) :
"""Strip strip _ prefix entries from name .""" | if not name :
return name
for prefix in self . __strip_prefixes :
if name . startswith ( prefix ) :
return name [ len ( prefix ) : ]
return name |
def _find_base_type ( data_type ) :
"""Find the Nani ' s base type for a given data type .
This is useful when Nani ' s data types were subclassed and the original type
is required .""" | bases = type ( data_type ) . __mro__
for base in bases :
if base in _ALL :
return base
return None |
def filter_factory ( global_conf , ** local_conf ) :
"""Returns a WSGI filter app for use with paste . deploy .""" | conf = global_conf . copy ( )
conf . update ( local_conf )
def blacklist ( app ) :
return BlacklistFilter ( app , conf )
return blacklist |
def _read_join_syn ( self , bits , size , kind ) :
"""Read Join Connection option for Initial SYN .
Positional arguments :
* bits - str , 4 - bit data
* size - int , length of option
* kind - int , 30 ( Multipath TCP )
Returns :
* dict - - extracted Join Connection ( MP _ JOIN - SYN ) option for Initial... | adid = self . _read_unpack ( 1 )
rtkn = self . _read_fileng ( 4 )
srno = self . _read_unpack ( 4 )
data = dict ( kind = kind , length = size + 1 , subtype = 'MP_JOIN-SYN' , join = dict ( syn = dict ( backup = True if int ( bits [ 3 ] ) else False , addrid = adid , token = rtkn , randnum = srno , ) , ) , )
return data |
def setup_prj_page ( self , ) :
"""Create and set the model on the project page
: returns : None
: rtype : None
: raises : None""" | self . prj_seq_tablev . horizontalHeader ( ) . setResizeMode ( QtGui . QHeaderView . ResizeToContents )
self . prj_atype_tablev . horizontalHeader ( ) . setResizeMode ( QtGui . QHeaderView . ResizeToContents )
self . prj_dep_tablev . horizontalHeader ( ) . setResizeMode ( QtGui . QHeaderView . ResizeToContents )
self .... |
def get_user_info ( tokens , uk ) :
'''获取用户的部分信息 .
比如头像 , 用户名 , 自我介绍 , 粉丝数等 .
这个接口可用于查询任何用户的信息 , 只要知道他 / 她的uk .''' | url = '' . join ( [ const . PAN_URL , 'pcloud/user/getinfo?channel=chunlei&clienttype=0&web=1' , '&bdstoken=' , tokens [ 'bdstoken' ] , '&query_uk=' , uk , '&t=' , util . timestamp ( ) , ] )
req = net . urlopen ( url )
if req :
info = json . loads ( req . data . decode ( ) )
if info and info [ 'errno' ] == 0 :
... |
def fixcode ( ** kwargs ) :
"""auto pep8 format all python file in ` ` source code ` ` and ` ` tests ` ` dir .""" | # repository direcotry
repo_dir = Path ( __file__ ) . parent . absolute ( )
# source code directory
source_dir = Path ( repo_dir , package . __name__ )
if source_dir . exists ( ) :
print ( "Source code locate at: '%s'." % source_dir )
print ( "Auto pep8 all python file ..." )
source_dir . autopep8 ( ** kwar... |
def listChoices ( self , category , libtype = None , ** kwargs ) :
"""Returns a list of : class : ` ~ plexapi . library . FilterChoice ` objects for the
specified category and libtype . kwargs can be any of the same kwargs in
: func : ` plexapi . library . LibraySection . search ( ) ` to help narrow down the ch... | # TODO : Should this be moved to base ?
if category in kwargs :
raise BadRequest ( 'Cannot include kwarg equal to specified category: %s' % category )
args = { }
for subcategory , value in kwargs . items ( ) :
args [ category ] = self . _cleanSearchFilter ( subcategory , value )
if libtype is not None :
arg... |
def find_lexer_for_filename ( filename ) :
"""Get a Pygments Lexer given a filename .""" | filename = filename or ''
root , ext = os . path . splitext ( filename )
if ext in custom_extension_lexer_mapping :
lexer = get_lexer_by_name ( custom_extension_lexer_mapping [ ext ] )
else :
try :
lexer = get_lexer_for_filename ( filename )
except Exception :
return TextLexer ( )
return lex... |
def load_level ( self ) :
"""| coro |
Load the players XP and level""" | data = yield from self . auth . get ( "https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/r6playerprofile/playerprofile/progressions?profile_ids=%s" % ( self . spaceid , self . platform_url , self . id ) )
if "player_profiles" in data and len ( data [ "player_profiles" ] ) > 0 :
self . xp = data [ "player... |
def merge_split_adjustments_with_overwrites ( self , pre , post , overwrites , requested_split_adjusted_columns ) :
"""Merge split adjustments with the dict containing overwrites .
Parameters
pre : dict [ str - > dict [ int - > list ] ]
The adjustments that occur before the split - adjusted - asof - date .
... | for column_name in requested_split_adjusted_columns : # We can do a merge here because the timestamps in ' pre ' and
# ' post ' are guaranteed to not overlap .
if pre : # Either empty or contains all columns .
for ts in pre [ column_name ] :
add_new_adjustments ( overwrites , pre [ column_name ]... |
def linear ( m = 1 , b = 0 ) :
'''Return a driver function that can advance a sequence of linear values .
. . code - block : : none
value = m * i + b
Args :
m ( float ) : a slope for the linear driver
x ( float ) : an offset for the linear driver''' | def f ( i ) :
return m * i + b
return partial ( force , sequence = _advance ( f ) ) |
def _objectify ( items , container_name ) :
"""Splits a listing of objects into their appropriate wrapper classes .""" | objects = [ ]
# Deal with objects and object pseudo - folders first , save subdirs for later
for item in items :
if item . get ( "subdir" , None ) is not None :
object_cls = PseudoFolder
else :
object_cls = StorageObject
objects . append ( object_cls ( item , container_name ) )
return object... |
def format_configurablefield_nodes ( field_name , field , field_id , state , lineno ) :
"""Create a section node that documents a ConfigurableField config field .
Parameters
field _ name : ` str `
Name of the configuration field ( the attribute name of on the config
class ) .
field : ` ` lsst . pex . conf... | # Custom default target definition list that links to Task topics
default_item = nodes . definition_list_item ( )
default_item . append ( nodes . term ( text = "Default" ) )
default_item_content = nodes . definition ( )
para = nodes . paragraph ( )
name = '.' . join ( ( field . target . __module__ , field . target . __... |
def info ( device ) :
'''Get filesystem geometry information .
CLI Example :
. . code - block : : bash
salt ' * ' xfs . info / dev / sda1''' | out = __salt__ [ 'cmd.run_all' ] ( "xfs_info {0}" . format ( device ) )
if out . get ( 'stderr' ) :
raise CommandExecutionError ( out [ 'stderr' ] . replace ( "xfs_info:" , "" ) . strip ( ) )
return _parse_xfs_info ( out [ 'stdout' ] ) |
def exec_command ( cmd , in_data = '' , chdir = None , shell = None , emulate_tty = False ) :
"""Run a command in a subprocess , emulating the argument handling behaviour of
SSH .
: param bytes cmd :
String command line , passed to user ' s shell .
: param bytes in _ data :
Optional standard input for the... | assert isinstance ( cmd , mitogen . core . UnicodeType )
return exec_args ( args = [ get_user_shell ( ) , '-c' , cmd ] , in_data = in_data , chdir = chdir , shell = shell , emulate_tty = emulate_tty , ) |
def next_bday ( self ) :
"""Used for moving to next business day .""" | if self . n >= 0 :
nb_offset = 1
else :
nb_offset = - 1
if self . _prefix . startswith ( 'C' ) : # CustomBusinessHour
return CustomBusinessDay ( n = nb_offset , weekmask = self . weekmask , holidays = self . holidays , calendar = self . calendar )
else :
return BusinessDay ( n = nb_offset ) |
def play_note ( note ) :
"""play _ note determines the coordinates of a note on the keyboard image
and sends a request to play the note to the fluidsynth server""" | global text
octave_offset = ( note . octave - LOWEST ) * width
if note . name in WHITE_KEYS : # Getting the x coordinate of a white key can be done automatically
w = WHITE_KEYS . index ( note . name ) * white_key_width
w = w + octave_offset
# Add a list containing the x coordinate , the tick at the current ... |
def down_the_wabbit_hole ( session , class_name ) :
"""Authenticate on class . coursera . org""" | auth_redirector_url = AUTH_REDIRECT_URL . format ( class_name = class_name )
r = session . get ( auth_redirector_url )
logging . debug ( 'Following %s to authenticate on class.coursera.org.' , auth_redirector_url )
try :
r . raise_for_status ( )
except requests . exceptions . HTTPError as e :
raise Authenticati... |
def unobserve_property ( self , name , handler ) :
"""Unregister a property observer . This requires both the observed property ' s name and the handler function that
was originally registered as one handler could be registered for several properties . To unregister a handler
from * all * observed properties se... | self . _property_handlers [ name ] . remove ( handler )
if not self . _property_handlers [ name ] :
_mpv_unobserve_property ( self . _event_handle , hash ( name ) & 0xffffffffffffffff ) |
def check_for_flexible_downtime ( self , timeperiods , hosts , services ) :
"""Enter in a downtime if necessary and raise start notification
When a non Ok state occurs we try to raise a flexible downtime .
: param timeperiods : Timeperiods objects , used for downtime period
: type timeperiods : alignak . obje... | status_updated = False
for downtime_id in self . downtimes :
downtime = self . downtimes [ downtime_id ]
# Activate flexible downtimes ( do not activate triggered downtimes )
# Note : only activate if we are between downtime start and end time !
if downtime . fixed or downtime . is_in_effect :
c... |
def extra ( method , profile , ** libcloud_kwargs ) :
'''Call an extended method on the driver
: param method : Driver ' s method name
: type method : ` ` str ` `
: param profile : The profile key
: type profile : ` ` str ` `
: param libcloud _ kwargs : Extra arguments for the driver ' s method
: type l... | libcloud_kwargs = salt . utils . args . clean_kwargs ( ** libcloud_kwargs )
conn = _get_driver ( profile = profile )
connection_method = getattr ( conn , method )
return connection_method ( ** libcloud_kwargs ) |
def assert_inequivalent ( o1 , o2 ) :
'''Asserts that o1 and o2 are distinct and inequivalent objects''' | if not ( isinstance ( o1 , type ) and isinstance ( o2 , type ) ) :
assert o1 is not o2
assert not o1 == o2 and o1 != o2
assert not o2 == o1 and o2 != o1 |
def get_jids ( ) :
'''Return a dict mapping all job ids to job information''' | ret = { }
for jid , job , _ , _ in _walk_through ( _job_dir ( ) ) :
ret [ jid ] = salt . utils . jid . format_jid_instance ( jid , job )
if __opts__ . get ( 'job_cache_store_endtime' ) :
endtime = get_endtime ( jid )
if endtime :
ret [ jid ] [ 'EndTime' ] = endtime
return ret |
def update_nanopubstore_start_dt ( url : str , start_dt : str ) :
"""Add nanopubstore start _ dt to belapi . state _ mgmt collection
Args :
url : url of nanopubstore
start _ dt : datetime of last query against nanopubstore for new ID ' s""" | hostname = urllib . parse . urlsplit ( url ) [ 1 ]
start_dates_doc = state_mgmt . get ( start_dates_doc_key )
if not start_dates_doc :
start_dates_doc = { "_key" : start_dates_doc_key , "start_dates" : [ { "nanopubstore" : hostname , "start_dt" : start_dt } ] , }
state_mgmt . insert ( start_dates_doc )
else :
... |
def _mapFuture ( callable_ , * iterables ) :
"""Similar to the built - in map function , but each of its
iteration will spawn a separate independent parallel Future that will run
either locally or remotely as ` callable ( * args ) ` .
: param callable : Any callable object ( function or class object with * _ ... | childrenList = [ ]
for args in zip ( * iterables ) :
childrenList . append ( submit ( callable_ , * args ) )
return childrenList |
def _py_code_clean ( lines , tab , executable ) :
"""Appends all the code lines needed to create the result class instance and populate
its keys with all output variables .""" | count = 0
allparams = executable . ordered_parameters
if type ( executable ) . __name__ == "Function" :
allparams = allparams + [ executable ]
for p in allparams :
value = _py_clean ( p , tab )
if value is not None :
count += 1
lines . append ( value )
return count |
def copy_logstore ( from_client , from_project , from_logstore , to_logstore , to_project = None , to_client = None ) :
"""copy logstore , index , logtail config to target logstore , machine group are not included yet .
the target logstore will be crated if not existing
: type from _ client : LogClient
: para... | # check client
if to_project is not None : # copy to a different project in different client
to_client = to_client or from_client
# check if target project exists or not
ret = from_client . get_project ( from_project )
try :
ret = to_client . create_project ( to_project , ret . get_description (... |
def ads_use_dev_spaces ( cluster_name , resource_group_name , update = False , space_name = None , do_not_prompt = False ) :
"""Use Azure Dev Spaces with a managed Kubernetes cluster .
: param cluster _ name : Name of the managed cluster .
: type cluster _ name : String
: param resource _ group _ name : Name ... | azds_cli = _install_dev_spaces_cli ( update )
use_command_arguments = [ azds_cli , 'use' , '--name' , cluster_name , '--resource-group' , resource_group_name ]
if space_name is not None :
use_command_arguments . append ( '--space' )
use_command_arguments . append ( space_name )
if do_not_prompt :
use_comman... |
def get_league ( self , slug ) :
"""Returns a Pokemon League object containing the details about the
league .""" | endpoint = '/league/' + slug
return self . make_request ( self . BASE_URL + endpoint ) |
def catches ( catch = None , handler = None , exit = True , handle_all = False ) :
"""Very simple decorator that tries any of the exception ( s ) passed in as
a single exception class or tuple ( containing multiple ones ) returning the
exception message and optionally handling the problem if it raises with the ... | catch = catch or Exception
logger = logging . getLogger ( 'ceph_deploy' )
def decorate ( f ) :
@ wraps ( f )
def newfunc ( * a , ** kw ) :
exit_from_catch = False
try :
return f ( * a , ** kw )
except catch as e :
if handler :
return handler ( e )
... |
def is_coincident ( self , other , keys = None ) :
"""Return True if any segment in any list in self intersects
any segment in any list in other . If the optional keys
argument is not None , then it should be an iterable of keys
and only segment lists for those keys will be considered in
the test ( instead ... | if keys is not None :
keys = set ( keys )
self = tuple ( self [ key ] for key in set ( self ) & keys )
other = tuple ( other [ key ] for key in set ( other ) & keys )
else :
self = tuple ( self . values ( ) )
other = tuple ( other . values ( ) )
# make sure inner loop is smallest
if len ( self ) < l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.