signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def main ( ) : """Main method of the script"""
parser = __build_option_parser ( ) args = parser . parse_args ( ) analyze_ws = AnalyzeWS ( args ) try : analyze_ws . set_file ( args . file_ [ 0 ] ) except IOError : print 'IOError raised while reading file. Exiting!' sys . exit ( 3 ) # Start the chosen mode if args . to_file or args . to_browser : anal...
def tables ( self ) : """A list containing the tables in this container , in document order . Read - only ."""
from . table import Table return [ Table ( tbl , self ) for tbl in self . _element . tbl_lst ]
def get_agents ( self ) : """Gets all ` ` Agents ` ` . In plenary mode , the returned list contains all known agents or an error results . Otherwise , the returned list may contain only those agents that are accessible through this session . return : ( osid . authentication . AgentList ) - a list of ` ` Age...
# Implemented from template for # osid . resource . ResourceLookupSession . get _ resources # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'authentication' , collection = 'Agent' , runtime = self . _runtime ) result = collection . find ( self . _view_filter ( ) ) . sort (...
def raw ( self ) : """An eager version of Trace Returns raw : RawTrace"""
return RawTrace ( self . filehandle , self . dtype , len ( self ) , self . shape , self . readonly , )
def _split_overlays ( self ) : """Splits a DynamicMap into its components . Only well defined for DynamicMap with consistent number and order of layers ."""
if not len ( self ) : raise ValueError ( 'Cannot split DynamicMap before it has been initialized' ) elif not issubclass ( self . type , CompositeOverlay ) : return None , self from . . util import Dynamic keys = list ( self . last . data . keys ( ) ) dmaps = [ ] for key in keys : el = self . last . data [ k...
def _urlnorm ( cls , uri ) : """Normalize the URL to create a safe key for the cache"""
( scheme , authority , path , query , fragment ) = parse_uri ( uri ) if not scheme or not authority : raise Exception ( "Only absolute URIs are allowed. uri = %s" % uri ) scheme = scheme . lower ( ) authority = authority . lower ( ) if not path : path = "/" # Could do syntax based normalization of the URI befor...
def GetDirections ( self , origin , destination , sensor = False , mode = None , waypoints = None , alternatives = None , avoid = None , language = None , units = None , region = None , departure_time = None , arrival_time = None ) : '''Get Directions Service Pls refer to the Google Maps Web API for the details o...
params = { 'origin' : origin , 'destination' : destination , 'sensor' : str ( sensor ) . lower ( ) } if mode : params [ 'mode' ] = mode if waypoints : params [ 'waypoints' ] = waypoints if alternatives : params [ 'alternatives' ] = alternatives if avoid : params [ 'avoid' ] = avoid if language : par...
def create_authn_query_response ( self , subject , session_index = None , requested_context = None , in_response_to = None , issuer = None , sign_response = False , status = None , sign_alg = None , digest_alg = None , ** kwargs ) : """A successful < Response > will contain one or more assertions containing authe...
margs = self . message_args ( ) asserts = [ ] for statement in self . session_db . get_authn_statements ( subject . name_id , session_index , requested_context ) : asserts . append ( saml . Assertion ( authn_statement = statement , subject = subject , ** margs ) ) if asserts : args = { "assertion" : asserts } e...
def set_alias ( cls , domain , login , aliases ) : """Update aliases on a mailbox ."""
return cls . call ( 'domain.mailbox.alias.set' , domain , login , aliases )
def authenticate ( self ) : """Determine the current domain and zone IDs for the domain ."""
try : payload = self . _api . domain . info ( self . _api_key , self . _domain ) self . _zone_id = payload [ 'zone_id' ] return payload [ 'id' ] except xmlrpclib . Fault as err : raise Exception ( "Failed to authenticate: '{0}'" . format ( err ) )
def validate ( self ) : """validate : Makes sure input question is valid Args : None Returns : boolean indicating if input question is valid"""
try : assert self . question_type == exercises . INPUT_QUESTION , "Assumption Failed: Question should be input answer type" assert len ( self . answers ) > 0 , "Assumption Failed: Multiple selection question should have answers" for a in self . answers : assert 'answer' in a , "Assumption Failed: An...
def setup ( self , config_file ) : """Setup settings from a JSON config file"""
def get_config_and_warn ( key , default , abort = False ) : value = config . get ( key , None ) if not value : print ( f"Cannot find {key} in settings, using default value: {default}" ) value = default if abort : sys . exit ( - 1 ) return value if not self . DATA_DIR_PATH...
def divide_url ( self , url ) : """divide url into host and path two parts"""
if 'https://' in url : host = url [ 8 : ] . split ( '/' ) [ 0 ] path = url [ 8 + len ( host ) : ] elif 'http://' in url : host = url [ 7 : ] . split ( '/' ) [ 0 ] path = url [ 7 + len ( host ) : ] else : host = url . split ( '/' ) [ 0 ] path = url [ len ( host ) : ] return host , path
def update ( self , * args , ** kwargs ) : """Update the IP on the remote service ."""
# first find the update _ url for the provided account + hostname : update_url = next ( ( r . update_url for r in records ( self . _credentials , self . _url ) if r . hostname == self . hostname ) , None ) if update_url is None : LOG . warning ( "Could not find hostname '%s' at '%s'" , self . hostname , self . _url...
def mask ( args ) : """% prog mask fastafile Mask the contaminants . By default , this will compare against UniVec _ Core and Ecoli . fasta . Merge the contaminant results , and use ` maskFastaFromBed ` . Can perform FASTA tidy if requested ."""
p = OptionParser ( mask . __doc__ ) p . add_option ( "--db" , help = "Contaminant db other than Ecoli K12 [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args assert op . exists ( fastafile ) outfastafile = fastafile . rsplit ( ...
def get_microversion_for_features ( service , features , wrapper_class , min_ver , max_ver ) : """Retrieves that highest known functional microversion for features"""
feature_versions = get_requested_versions ( service , features ) if not feature_versions : return None for version in feature_versions : microversion = wrapper_class ( version ) if microversion . matches ( min_ver , max_ver ) : return microversion return None
def orderExecuted ( self , orderId ) : '''call back for executed order'''
if orderId == self . __stopOrderId : LOG . debug ( "smaStrategy stop order canceled %s" % orderId ) # stop order executed self . __clearStopOrder ( )
def parse_response ( self , resp ) : """Parse the xmlrpc response ."""
p , u = self . getparser ( ) p . feed ( resp . content ) p . close ( ) return u . close ( )
def direct_command_short ( self , command ) : """Wrapper for short - form commands ( doesn ' t need device id or flags byte )"""
self . logger . info ( "direct_command_short: Command %s" , command ) command_url = ( self . hub_url + '/3?' + command + "=I=0" ) return self . post_direct_command ( command_url )
def print_all ( msg ) : """Print all objects . Print a table of all active libvips objects . Handy for debugging ."""
gc . collect ( ) logger . debug ( msg ) vips_lib . vips_object_print_all ( ) logger . debug ( )
def get_submission ( self , url = None , submission_id = None , comment_limit = 0 , comment_sort = None , params = None ) : """Return a Submission object for the given url or submission _ id . : param comment _ limit : The desired number of comments to fetch . If < = 0 fetch the default number for the session '...
if bool ( url ) == bool ( submission_id ) : raise TypeError ( 'One (and only one) of id or url is required!' ) if submission_id : url = urljoin ( self . config [ 'comments' ] , submission_id ) return objects . Submission . from_url ( self , url , comment_limit = comment_limit , comment_sort = comment_sort , par...
def add_title ( self , title , subtitle = None , source = None ) : """Add title . : param title : title for the current document : type title : string : param subtitle : subtitle for the current document : type subtitle : string : param source : source for the given title : type source : string"""
title_entry = self . _sourced_dict ( source , title = title , ) if subtitle is not None : title_entry [ 'subtitle' ] = subtitle self . _append_to ( 'titles' , title_entry )
def mk_terminal_context_menu ( terminal , window , settings , callback_object ) : """Create the context menu for a terminal ."""
# Store the menu in a temp variable in terminal so that popup ( ) is happy . See : # https : / / stackoverflow . com / questions / 28465956/ terminal . context_menu = Gtk . Menu ( ) menu = terminal . context_menu mi = Gtk . MenuItem ( _ ( "Copy" ) ) mi . connect ( "activate" , callback_object . on_copy_clipboard ) menu...
def _build_requested_prefetches ( self , prefetches , requirements , model , fields , filters ) : """Build a prefetch dictionary based on request requirements ."""
for name , field in six . iteritems ( fields ) : original_field = field if isinstance ( field , DynamicRelationField ) : field = field . serializer if isinstance ( field , serializers . ListSerializer ) : field = field . child if not isinstance ( field , serializers . ModelSerializer ) :...
def parts ( self , * args , ** kwargs ) : """Retrieve parts belonging to this activity . Without any arguments it retrieves the Instances related to this task only . This call only returns the configured properties in an activity . So properties that are not configured are not in the returned parts . See : ...
return self . _client . parts ( * args , activity = self . id , ** kwargs )
def _addPub ( self , stem , source ) : """Enters stem as value for source ."""
key = re . sub ( "[^A-Za-z0-9&]+" , " " , source ) . strip ( ) . upper ( ) self . sourceDict [ key ] = stem self . bibstemWords . setdefault ( stem , set ( ) ) . update ( key . lower ( ) . split ( ) )
def _delete_from_search_index ( * , instance , index ) : """Remove a document from a search index ."""
pre_delete . send ( sender = instance . __class__ , instance = instance , index = index ) if settings . auto_sync ( instance ) : instance . delete_search_document ( index = index )
def change_time ( self ) : """dfdatetime . DateTimeValues : change time or None if not available ."""
timestamp = self . _fsapfs_file_entry . get_inode_change_time_as_integer ( ) return dfdatetime_apfs_time . APFSTime ( timestamp = timestamp )
def get_group_category ( self , category ) : """Get a single group category . : calls : ` GET / api / v1 / group _ categories / : group _ category _ id < https : / / canvas . instructure . com / doc / api / group _ categories . html # method . group _ categories . show > ` _ : param category : The object or ID ...
category_id = obj_or_id ( category , "category" , ( GroupCategory , ) ) response = self . __requester . request ( 'GET' , 'group_categories/{}' . format ( category_id ) ) return GroupCategory ( self . __requester , response . json ( ) )
def _DrawStations ( self , color = "#aaa" ) : """Generates svg with a horizontal line for each station / stop . Args : # Class Stop is defined in transitfeed . py stations : [ Stop , Stop , . . . ] Returns : # A string containing a polyline tag for each stop " < polyline class = " Station " stroke = " #...
stations = self . _stations tmpstrs = [ ] for y in stations : tmpstrs . append ( ' <polyline class="Station" stroke="%s" \ points="%s,%s, %s,%s" />' % ( color , 20 , 20 + y + .5 , self . _gwidth + 20 , 20 + y + .5 ) ) return "" . join ( tmpstrs )
def get_obj_attrs ( obj ) : """Return a dictionary built from the attributes of the given object ."""
pr = { } if obj is not None : if isinstance ( obj , numpy . core . records . record ) : for name in obj . dtype . names : pr [ name ] = getattr ( obj , name ) elif hasattr ( obj , '__dict__' ) and obj . __dict__ : pr = obj . __dict__ elif hasattr ( obj , '__slots__' ) : f...
def set ( self , value ) : """Sets the value of the object : param value : True , False or another value that works with bool ( )"""
self . _native = bool ( value ) self . contents = b'\x00' if not value else b'\xff' self . _header = None if self . _trailer != b'' : self . _trailer = b''
def word_wrap_tree ( parented_tree , width = 0 ) : """line - wrap an NLTK ParentedTree for pretty - printing"""
if width != 0 : for i , leaf_text in enumerate ( parented_tree . leaves ( ) ) : dedented_text = textwrap . dedent ( leaf_text ) . strip ( ) parented_tree [ parented_tree . leaf_treeposition ( i ) ] = textwrap . fill ( dedented_text , width = width ) return parented_tree
def verify ( pwfile , user , password , opts = '' , runas = None ) : '''Return True if the htpasswd file exists , the user has an entry , and their password matches . pwfile Fully qualified path to htpasswd file user User name password User password opts Valid options that can be passed are : - ...
if not os . path . exists ( pwfile ) : return False cmd = [ 'htpasswd' , '-bv{0}' . format ( opts ) , pwfile , user , password ] ret = __salt__ [ 'cmd.run_all' ] ( cmd , runas = runas , python_shell = False ) log . debug ( 'Result of verifying htpasswd for user %s: %s' , user , ret ) return ret [ 'retcode' ] == 0
def delta ( self ) : """returns the time ( in seconds ) that the batch took , if complete"""
completed_date = parse_api_datetime ( self . batch [ "CompletedDate" ] ) created_date = parse_api_datetime ( self . batch [ "CreatedDate" ] ) td = completed_date - created_date return td . total_seconds ( )
def trigger ( self , * args , ** kwargs ) : """Execute the handlers with a message , if any ."""
for h in self . handlers : h ( * args , ** kwargs )
def createKMZ ( self , kmz_as_json ) : """Creates a KMZ file from json . See http : / / resources . arcgis . com / en / help / arcgis - rest - api / index . html # / Create _ Kmz / 02r3000001tm00000/ for more information ."""
kmlURL = self . _url + "/createKmz" params = { "f" : "json" , "kml" : kmz_as_json } return self . _post ( url = kmlURL , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port )
def _determine_profiles ( self ) : """Determine the WBEM management profiles advertised by the WBEM server , by communicating with it and enumerating the instances of ` CIM _ RegisteredProfile ` . If the profiles could be determined , this method sets the : attr : ` profiles ` property of this object to the...
mp_insts = self . _conn . EnumerateInstances ( "CIM_RegisteredProfile" , namespace = self . interop_ns ) self . _profiles = mp_insts
def run_multiple_processes ( args_list : List [ List [ str ] ] , die_on_failure : bool = True ) -> None : """Fire up multiple processes , and wait for them to finihs . Args : args _ list : command arguments for each process die _ on _ failure : see : func : ` wait _ for _ processes `"""
for procargs in args_list : start_process ( procargs ) # Wait for them all to finish wait_for_processes ( die_on_failure = die_on_failure )
def get_time_slide_id ( self , offsetdict , create_new = None , superset_ok = False , nonunique_ok = False ) : """Return the time _ slide _ id corresponding to the offset vector described by offsetdict , a dictionary of instrument / offset pairs . If the optional create _ new argument is None ( the default ) ...
# look for matching offset vectors if superset_ok : ids = [ id for id , slide in self . as_dict ( ) . items ( ) if offsetdict == dict ( ( instrument , offset ) for instrument , offset in slide . items ( ) if instrument in offsetdict ) ] else : ids = [ id for id , slide in self . as_dict ( ) . items ( ) if offse...
def accept ( self , logevent ) : """Process line . Overwrite BaseFilter . accept ( ) and return True if the provided logevent should be accepted ( causing output ) , or False if not ."""
for word in self . words : if re . search ( word , logevent . line_str ) : return True return False
def __get_first_available_id ( self ) : """Private method to get the first available id . The id can only be an integer greater than 0. Returns : int : The first available id"""
traps = self . get_all ( ) if traps : used_ids = [ 0 ] for trap in traps : used_uris = trap . get ( 'uri' ) used_ids . append ( int ( used_uris . split ( '/' ) [ - 1 ] ) ) used_ids . sort ( ) return self . __findFirstMissing ( used_ids , 0 , len ( used_ids ) - 1 ) else : return 1
def warning ( self , msg , pos = None ) : """Logs a warning message pertaining to the given SeqAtom ."""
self . log ( msg , 'warning: ' + self . location ( pos ) )
def renameTable ( self , login , oldTableName , newTableName ) : """Parameters : - login - oldTableName - newTableName"""
self . send_renameTable ( login , oldTableName , newTableName ) self . recv_renameTable ( )
def lex ( self , text ) : """Iterator that tokenizes ` text ` and yields up tokens as they are found"""
for match in self . regex . finditer ( text ) : name = match . lastgroup yield ( name , match . group ( name ) )
def _legacy_symbol_table ( build_file_aliases ) : """Construct a SymbolTable for the given BuildFileAliases . : param build _ file _ aliases : BuildFileAliases to register . : type build _ file _ aliases : : class : ` pants . build _ graph . build _ file _ aliases . BuildFileAliases ` : returns : A SymbolTabl...
table = { alias : _make_target_adaptor ( TargetAdaptor , target_type ) for alias , target_type in build_file_aliases . target_types . items ( ) } for alias , factory in build_file_aliases . target_macro_factories . items ( ) : # TargetMacro . Factory with more than one target type is deprecated . # For default sources ...
def set_custom_colorset ( self ) : """Defines a colorset with matching colors . Provided by Joachim ."""
cmd . set_color ( 'myorange' , '[253, 174, 97]' ) cmd . set_color ( 'mygreen' , '[171, 221, 164]' ) cmd . set_color ( 'myred' , '[215, 25, 28]' ) cmd . set_color ( 'myblue' , '[43, 131, 186]' ) cmd . set_color ( 'mylightblue' , '[158, 202, 225]' ) cmd . set_color ( 'mylightgreen' , '[229, 245, 224]' )
def copy_cwl_files ( from_dir = CWL_PATH , to_dir = None ) : """Copy cwl files to a directory where the cwl - runner can find them . Args : from _ dir ( str ) : Path to directory where to copy files from ( default : the cwl directory of nlppln ) . to _ dir ( str ) : Path to directory where the files should ...
cwl_files = glob . glob ( '{}{}*.cwl' . format ( from_dir , os . sep ) ) # if no files are found , the output directory should not be created if len ( cwl_files ) > 0 : create_dirs ( to_dir ) for fi in cwl_files : fo = os . path . join ( to_dir , os . path . basename ( fi ) ) shutil . copy2 ( fi , fo ) retu...
def create_composite_loss ( self , losses , regularize = True , include_marked = True , name = 'cost' ) : """Creates a loss that is the sum of all specified losses . Args : losses : A sequence of losses to include . regularize : Whether or not to include regularization losses . include _ marked : Whether or...
all_losses = [ ] if losses : all_losses . extend ( losses ) if include_marked : all_losses . extend ( self . marked_losses ) if not all_losses : raise ValueError ( 'No losses specified!' ) if regularize : all_losses . extend ( self . regularization_losses ) with self . _g . as_default ( ) : result =...
def start_service ( addr , n ) : """Start a service"""
s = Subscriber ( addr ) s . socket . set_string_option ( nanomsg . SUB , nanomsg . SUB_SUBSCRIBE , 'test' ) started = time . time ( ) for _ in range ( n ) : msg = s . socket . recv ( ) s . socket . close ( ) duration = time . time ( ) - started print ( 'Raw SUB service stats:' ) util . print_stats ( n , duration ) ...
def add_recording_behavior ( self , component , runnable ) : """Adds recording - related dynamics to a runnable component based on the dynamics specifications in the component model . @ param component : Component model containing dynamics specifications . @ type component : lems . model . component . FatComp...
simulation = component . simulation for rec in simulation . records : rec . id = runnable . id self . current_record_target . add_variable_recorder ( self . current_data_output , rec )
def stripboxplot ( x , y , data , ax = None , significant = None , ** kwargs ) : """Overlay a stripplot on top of a boxplot ."""
ax = sb . boxplot ( x = x , y = y , data = data , ax = ax , fliersize = 0 , ** kwargs ) plot = sb . stripplot ( x = x , y = y , data = data , ax = ax , jitter = kwargs . pop ( "jitter" , 0.05 ) , color = kwargs . pop ( "color" , "0.3" ) , ** kwargs ) if data [ y ] . min ( ) >= 0 : hide_negative_y_ticks ( plot ) if ...
def get_font ( self , font ) : """Return the escpos index for ` font ` . Makes sure that the requested ` font ` is valid ."""
font = { 'a' : 0 , 'b' : 1 } . get ( font , font ) if not six . text_type ( font ) in self . fonts : raise NotSupported ( '"{}" is not a valid font in the current profile' . format ( font ) ) return font
def guard_reinstate ( analysis_request ) : """Returns whether ' reinstate " transition can be performed or not . Returns True only if this is not a partition or the parent analysis request can be reinstated or is not in a cancelled state"""
parent = analysis_request . getParentAnalysisRequest ( ) if not parent : return True if api . get_workflow_status_of ( parent ) != "cancelled" : return True return isTransitionAllowed ( parent , "reinstate" )
def run ( self , dat = None ) : """发布消息 - 样例 : . . code : : python ' hostname ' : ' 192.168.1.2 ' , ' port ' : 1883, ' username ' : ' admin ' , ' password ' : ' admin ' , Publisher ( t ) . run ( { ' payload ' : json . dumps ( t ) } ) if pub else TopicConsumer ( t ) . run ( ) : param dat : : type d...
conf = self . conf dat = dat if dat else { } publish . single ( topic = dat . get ( 'topic' , 'test_topic' ) , payload = dat . get ( 'payload' , 'just a test topic payload' ) , qos = dat . get ( 'qos' , 0 ) , retain = dat . get ( 'retain' , False ) , hostname = conf [ 'hostname' ] , port = conf [ 'port' ] , auth = conf...
def update ( self , records , context ) : """Updates the modified data in the database for the inputted record . If the dryRun flag is specified then the command will be logged but not executed . : param record | < orb . Table > lookup | < orb . LookupOptions > options | < orb . Context > : return < dic...
UPDATE = self . statement ( 'UPDATE' ) sql , data = UPDATE ( records ) if context . dryRun : print sql , data return [ ] , 0 else : return self . execute ( sql , data , writeAccess = True )
def add_gauge ( self , gauge ) : """Add ` gauge ` to the registry . Raises a ` ValueError ` if another gauge with the same name already exists in the registry . : type gauge : class : ` LongGauge ` , class : ` DoubleGauge ` , : class : ` opencensus . metrics . export . cumulative . LongCumulative ` , : cl...
if gauge is None : raise ValueError name = gauge . descriptor . name with self . _gauges_lock : if name in self . gauges : raise ValueError ( 'Another gauge named "{}" is already registered' . format ( name ) ) self . gauges [ name ] = gauge
def calculate_loss ( original_price , selling_price ) : """This function calculates the loss incurred if a product is sold at a price lower than its original price . If the selling price is higher than or equal to the original price , it returns None . Args : original _ price : Original cost of the product ...
if selling_price > original_price : loss = selling_price - original_price return loss else : return None
def _split_raw_signature ( sig ) : """Split raw signature into components : param sig : The signature : return : A 2 - tuple"""
c_length = len ( sig ) // 2 r = int_from_bytes ( sig [ : c_length ] , byteorder = 'big' ) s = int_from_bytes ( sig [ c_length : ] , byteorder = 'big' ) return r , s
def write_file ( response , destination_folder , file_name ) : """Write the response content in a file in the destination folder . : param response : Response : param destination _ folder : Destination folder , string : param file _ name : File name , string : return : bool"""
if response . status_code == 200 : with open ( os . path . join ( destination_folder , file_name ) , 'wb' ) as f : for chunk in response . iter_content ( chunk_size = None ) : f . write ( chunk ) logger . info ( f'Saved downloaded file in {f.name}' ) else : logger . warning ( f'consume f...
def get_query_param ( self , key , default = None ) : """Get query parameter uniformly for GET and POST requests ."""
value = self . request . query_params . get ( key , None ) if value is None : value = self . request . data . get ( key , None ) if value is None : value = default return value
def buildMask ( self , chip , bits = 0 , write = False ) : """Build masks as specified in the user parameters found in the configObj object ."""
sci_chip = self . _image [ self . scienceExt , chip ] # # # For WFPC2 Data , build mask files using : maskname = sci_chip . dqrootname + '_dqmask.fits' dqmask_name = buildmask . buildShadowMaskImage ( sci_chip . dqfile , sci_chip . detnum , sci_chip . extnum , maskname , bitvalue = bits , binned = sci_chip . binned ) s...
def order_book ( self , selling_asset_code , buying_asset_code , selling_asset_issuer = None , buying_asset_issuer = None , limit = 10 ) : """Return , for each orderbook , a summary of the orderbook and the bids and asks associated with that orderbook . See the external docs below for information on the argumen...
selling_asset = Asset ( selling_asset_code , selling_asset_issuer ) buying_asset = Asset ( buying_asset_code , buying_asset_issuer ) asset_params = { 'selling_asset_type' : selling_asset . type , 'selling_asset_code' : None if selling_asset . is_native ( ) else selling_asset . code , 'selling_asset_issuer' : selling_as...
def apply ( self , q , bindings , ordering , distinct = None ) : """Sort on a set of field specifications of the type ( ref , direction ) in order of the submitted list ."""
info = [ ] for ( ref , direction ) in self . parse ( ordering ) : info . append ( ( ref , direction ) ) table , column = self . cube . model [ ref ] . bind ( self . cube ) if distinct is not None and distinct != ref : column = asc ( ref ) if direction == 'asc' else desc ( ref ) else : co...
def __parse_affiliations_yml ( self , affiliations ) : """Parse identity ' s affiliations from a yaml dict ."""
enrollments = [ ] for aff in affiliations : name = self . __encode ( aff [ 'organization' ] ) if not name : error = "Empty organization name" msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg ) elif name . lower ( ) == 'unknown' : ...
def GitHub_raise_for_status ( r ) : """Call instead of r . raise _ for _ status ( ) for GitHub requests Checks for common GitHub response issues and prints messages for them ."""
# This will happen if the doctr session has been running too long and the # OTP code gathered from GitHub _ login has expired . # TODO : Refactor the code to re - request the OTP without exiting . if r . status_code == 401 and r . headers . get ( 'X-GitHub-OTP' ) : raise GitHubError ( "The two-factor authentication...
def delete_row ( dbconn , table_name , field , value ) : """Delete a row from a table in a database . : param dbconn : data base connection : param table _ name : name of the table : param field : field of the table to target : param value : value of the field in the table to delete"""
cur = dbconn . cursor ( ) cur . execute ( "DELETE FROM '{name}' WHERE {field}='{value}'" . format ( name = table_name , field = field , value = value ) ) dbconn . commit ( )
def enable_root_user ( self ) : """Enables login from any host for the root user and provides the user with a generated root password ."""
uri = "/instances/%s/root" % self . id resp , body = self . manager . api . method_post ( uri ) return body [ "user" ] [ "password" ]
def stages ( self , from_directory = None , check_dag = True ) : """Walks down the root directory looking for Dvcfiles , skipping the directories that are related with any SCM ( e . g . ` . git ` ) , DVC itself ( ` . dvc ` ) , or directories tracked by DVC ( e . g . ` dvc add data ` would skip ` data / ` ) ...
from dvc . stage import Stage if not from_directory : from_directory = self . root_dir elif not os . path . isdir ( from_directory ) : raise TargetNotDirectoryError ( from_directory ) stages = [ ] outs = [ ] ignore_file_handler = DvcIgnoreFileHandler ( self . tree ) for root , dirs , files in self . tree . walk...
def delete_source ( self , name , save_template = True , delete_source_map = False , build_fixed_wts = True , ** kwargs ) : """Delete a source from the ROI model . Parameters name : str Source name . save _ template : bool Keep the SpatialMap FITS template associated with this source . delete _ source...
if not self . roi . has_source ( name ) : self . logger . error ( 'No source with name: %s' , name ) return loglevel = kwargs . pop ( 'loglevel' , self . loglevel ) self . logger . log ( loglevel , 'Deleting source %s' , name ) # STs require a source to be freed before deletion if self . like is not None : ...
def _rebuild_entries ( self ) : """Recreates the entries master list based on the groups hierarchy ( order matters here , since the parser uses order to determine lineage ) ."""
self . entries = [ ] def collapse_entries ( group ) : for entry in group . entries : self . entries . append ( entry ) for subgroup in group . children : collapse_entries ( subgroup ) collapse_entries ( self . root )
def _pypsa_generator_timeseries_aggregated_at_lv_station ( network , timesteps ) : """Aggregates generator time series per generator subtype and LV grid . Parameters network : Network The eDisGo grid topology model overall container timesteps : array _ like Timesteps is an array - like object with entries...
generation_p = [ ] generation_q = [ ] for lv_grid in network . mv_grid . lv_grids : # Determine aggregated generation at LV stations generation = { } for gen in lv_grid . generators : # for type in gen . type : # for subtype in gen . subtype : gen_name = '_' . join ( [ gen . type , gen . subtype , '...
def parse_commit_log ( commit_log : dict ) -> str : """: commit _ log : chronos . helpers . git _ commits _ since _ last _ tag ( ) output . Parse Git log and return either ' maj ' , ' min ' , or ' pat ' ."""
rv = 'pat' cc_patterns = patterns ( ) for value in commit_log . values ( ) : if re . search ( cc_patterns [ 'feat' ] , value ) : rv = 'min' if re . search ( cc_patterns [ 'BREAKING CHANGE' ] , value ) : rv = 'maj' return rv
def _pull_content_revision_parent ( self ) : """combine the pulling of these three properties"""
if self . _revision_id is None : query_params = { "prop" : "extracts|revisions" , "explaintext" : "" , "rvprop" : "ids" , } query_params . update ( self . __title_query_param ( ) ) request = self . mediawiki . wiki_request ( query_params ) page_info = request [ "query" ] [ "pages" ] [ self . pageid ] ...
def bind ( self , args , kwargs ) : """Bind arguments and keyword arguments to the encapsulated function . Returns a dictionary of parameters ( named according to function parameters ) with the values that were bound to each name ."""
spec = self . _spec resolution = self . resolve ( args , kwargs ) params = dict ( zip ( spec . args , resolution . slots ) ) if spec . varargs : params [ spec . varargs ] = resolution . varargs if spec . varkw : params [ spec . varkw ] = resolution . varkw if spec . kwonlyargs : params . update ( resolution...
def construct_request_uri ( local_dir , base_path , ** kwargs ) : """Constructs a special redirect _ uri to be used when communicating with one OP . Each OP should get their own redirect _ uris . : param local _ dir : Local directory in which to place the file : param base _ path : Base URL to start with : ...
_filedir = local_dir if not os . path . isdir ( _filedir ) : os . makedirs ( _filedir ) _webpath = base_path _name = rndstr ( 10 ) + ".jwt" filename = os . path . join ( _filedir , _name ) while os . path . exists ( filename ) : _name = rndstr ( 10 ) filename = os . path . join ( _filedir , _name ) _webname...
def _partialParseTimeStd ( self , s , sourceTime ) : """test if giving C { s } matched CRE _ TIMEHMS , used by L { parse ( ) } @ type s : string @ param s : date / time text to evaluate @ type sourceTime : struct _ time @ param sourceTime : C { struct _ time } value to use as the base @ rtype : tuple @ ...
parseStr = None chunk1 = chunk2 = '' # HH : MM ( : SS ) time strings m = self . ptc . CRE_TIMEHMS . search ( s ) if m is not None : if m . group ( 'seconds' ) is not None : parseStr = '%s:%s:%s' % ( m . group ( 'hours' ) , m . group ( 'minutes' ) , m . group ( 'seconds' ) ) chunk1 = s [ : m . start ...
def next ( self ) : """Returns a ` . Future ` that will yield the next available result . Note that this ` . Future ` will not be the same object as any of the inputs ."""
self . _running_future = TracebackFuture ( ) if self . _finished : self . _return_result ( self . _finished . popleft ( ) ) return self . _running_future
def isWon ( state , who ) : """Test if a tic - tac - toe game has been won . Assumes that the board is in a legal state . Will test if the value 1 is in any winning combination ."""
for w in WINS : S = sum ( 1 if ( w [ k ] == 1 and state [ k ] == who ) else 0 for k in range ( ACTIONS ) ) if S == 3 : # We have a win return True # There were no wins so return False return False
def feat ( self , k , v ) : """Store value ' v ' as a feature name ' k ' for this object . Features are stored in the dictionary self . feats . [ IMPORTANT NOTE : ] If the feature ' k ' is not yet defined , then : self . feats [ k ] = v OTHERWISE : self . feats [ k ] becomes a list ( if not already ) ...
if ( not hasattr ( self , 'feats' ) ) : self . feats = { } if ( not hasattr ( self , 'featpaths' ) ) : self . featpaths = { } if ( not k in self . feats ) : self . feats [ k ] = v else : if type ( self . feats [ k ] ) == type ( [ ] ) : self . feats [ k ] . append ( v ) else : ...
def run_container ( docker_client , backup_data ) : """Pull the Docker image and creates a container with a ' / backup ' volume . This volume will be mounted on the temporary workdir previously created . It will then start the container and return the container object ."""
docker_client . pull ( backup_data [ 'image' ] ) container = docker_client . create_container ( image = backup_data [ 'image' ] , volumes = [ '/backup' ] , command = backup_data [ 'command' ] ) docker_client . start ( container . get ( 'Id' ) , binds = { backup_data [ 'workdir' ] : { 'bind' : '/backup' , 'ro' : False }...
def get_offset_topic_partition_count ( kafka_config ) : """Given a kafka cluster configuration , return the number of partitions in the offset topic . It will raise an UnknownTopic exception if the topic cannot be found ."""
metadata = get_topic_partition_metadata ( kafka_config . broker_list ) if CONSUMER_OFFSET_TOPIC not in metadata : raise UnknownTopic ( "Consumer offset topic is missing." ) return len ( metadata [ CONSUMER_OFFSET_TOPIC ] )
def iter_transport_opts ( opts ) : '''Yield transport , opts for all master configured transports'''
transports = set ( ) for transport , opts_overrides in six . iteritems ( opts . get ( 'transport_opts' , { } ) ) : t_opts = dict ( opts ) t_opts . update ( opts_overrides ) t_opts [ 'transport' ] = transport transports . add ( transport ) yield transport , t_opts if opts [ 'transport' ] not in trans...
def create_remote_subnet ( self , account_id , identifier , cidr ) : """Creates a remote subnet on the given account . : param string account _ id : The account identifier . : param string identifier : The network identifier of the remote subnet . : param string cidr : The CIDR value of the remote subnet . ...
return self . remote_subnet . createObject ( { 'accountId' : account_id , 'cidr' : cidr , 'networkIdentifier' : identifier } )
def _add_dimensions ( self , item , dims , constant_keys ) : """Recursively descend through an Layout and NdMapping objects in order to add the supplied dimension values to all contained HoloMaps ."""
if isinstance ( item , Layout ) : item . fixed = False dim_vals = [ ( dim , val ) for dim , val in dims [ : : - 1 ] if dim not in self . drop ] if isinstance ( item , self . merge_type ) : new_item = item . clone ( cdims = constant_keys ) for dim , val in dim_vals : dim = asdim ( dim ) if di...
def make ( id , client , cls , parent_id = None , json = None ) : """Makes an api object based on an id and class . : param id : The id of the object to create : param client : The LinodeClient to give the new object : param cls : The class type to instantiate : param parent _ id : The parent id for derived...
from . dbase import DerivedBase if issubclass ( cls , DerivedBase ) : return cls ( client , id , parent_id , json ) else : return cls ( client , id , json )
def get_status ( self , hosts , services ) : """Get the status of this host : return : " OK " , " WARNING " , " CRITICAL " , " UNKNOWN " or " n / a " based on service state _ id or business _ rule state : rtype : str"""
if self . got_business_rule : mapping = { 0 : u'OK' , 1 : u'WARNING' , 2 : u'CRITICAL' , 3 : u'UNKNOWN' , 4 : u'UNREACHABLE' , } return mapping . get ( self . business_rule . get_state ( hosts , services ) , "n/a" ) return self . state
def graphql_request_create ( self , data , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / chat / conversations - api # api - path"
api_path = "/graphql/request" return self . call ( api_path , method = "POST" , data = data , ** kwargs )
def shareproject ( self , project_id , group_id , group_access ) : """Allow to share project with group . : param project _ id : The ID of a project : param group _ id : The ID of a group : param group _ access : Level of permissions for sharing : return : True is success"""
data = { 'id' : project_id , 'group_id' : group_id , 'group_access' : group_access } request = requests . post ( '{0}/{1}/share' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl ) return request . status_code == 201
def generate_cot_body ( context ) : """Generate the chain of trust dictionary . This is the unsigned and unformatted chain of trust artifact contents . Args : context ( scriptworker . context . Context ) : the scriptworker context . Returns : dict : the unsignd and unformatted chain of trust artifact cont...
try : cot = { 'artifacts' : get_cot_artifacts ( context ) , 'chainOfTrustVersion' : 1 , 'runId' : context . claim_task [ 'runId' ] , 'task' : context . task , 'taskId' : context . claim_task [ 'status' ] [ 'taskId' ] , 'workerGroup' : context . claim_task [ 'workerGroup' ] , 'workerId' : context . config [ 'worker_...
def check_db_connection ( ) : '''from : https : / / stackoverflow . com / questions / 7835272 / django - operationalerror - 2006 - mysql - server - has - gone - away'''
# mysql is lazily connected to in django . # connection . connection is None means # you have not connected to mysql before if connection . connection and not connection . is_usable ( ) : # destroy the default mysql connection # after this line , when you use ORM methods # django will reconnect to the default mysql ...
def _count_fastq_reads ( in_fastq , min_reads ) : """Count the number of fastq reads in a file , stopping after reaching min _ reads ."""
with open ( in_fastq ) as in_handle : items = list ( itertools . takewhile ( lambda i : i <= min_reads , ( i for i , _ in enumerate ( FastqGeneralIterator ( in_handle ) ) ) ) ) return len ( items )
def dbStore ( self , typ , py_value , context = None ) : """Prepares to store this column for the a particular backend database . : param backend : < orb . Database > : param py _ value : < variant > : param context : < orb . Context > : return : < variant >"""
if py_value is None : return None return self . valueToString ( py_value , context = context )
def __extract_info ( self , lines ) : """Extracts the following info from the source of the module with the class that acts like a namespace for constants : * Start line with constants * Last line with constants * Indent for constants : param list [ str ] lines : The source of the module with the class th...
ret = { 'start_line' : 0 , 'last_line' : 0 , 'indent' : '' } mode = 1 count = 0 for line in lines : if mode == 1 : if line . strip ( ) == self . __annotation : ret [ 'start_line' ] = count + 1 ret [ 'last_line' ] = count + 1 parts = re . match ( r'^(\s+)' , line ) ...
def evaluate_strings ( self , string , temp = False ) : """Evaluate strings ."""
value = '' if self . strings : if self . decode_escapes : value = RE_SURROGATES . sub ( self . replace_surrogates , ( RE_TEMP_ESC if temp else RE_ESC ) . sub ( self . replace_escapes , string ) ) else : value = string if not temp : self . quoted_strings . append ( [ value , self . li...
def prim ( G , start , weight = 'weight' ) : """Algorithm for finding a minimum spanning tree for a weighted undirected graph ."""
if len ( connected_components ( G ) ) != 1 : raise GraphInsertError ( "Prim algorithm work with connected graph only" ) if start not in G . vertices : raise GraphInsertError ( "Vertex %s doesn't exist." % ( start , ) ) pred = { } key = { } pqueue = { } lowest = 0 for edge in G . edges : if G . edges [ edge ...
def KepMag ( EPIC , campaign = None ) : '''Returns the * Kepler * magnitude for a given EPIC target .'''
if campaign is None : campaign = Campaign ( EPIC ) if hasattr ( campaign , '__len__' ) : raise AttributeError ( "Please choose a campaign/season for this target: %s." % campaign ) stars = GetK2Stars ( ) [ campaign ] i = np . argmax ( [ s [ 0 ] == EPIC for s in stars ] ) return stars [ i ] [ 1 ]
def default_ms_subtable ( subtable , name = None , tabdesc = None , dminfo = None ) : """Creates a default Measurement Set subtable . Any Table Description elements in tabdesc will overwrite the corresponding element in a default Measurement Set Table Description ( columns , hypercolumns and keywords ) . if n...
if name is None : name = subtable # Default to empty dictionaries if tabdesc is None : tabdesc = { } if dminfo is None : dminfo = { } # Wrap the Table object return table ( _default_ms_subtable ( subtable , name , tabdesc , dminfo ) , _oper = 3 )
def chunks ( lista , size ) : """Yield successive n - sized chunks from l ."""
if not isinstance ( lista , list ) : logger . error ( 'Erron in chunks, arg introduced is not a list.' , lista = lista ) return lista for i in range ( 0 , len ( lista ) , size ) : yield lista [ i : i + size ]
def insert_one ( self , * args , ** kwargs ) : """Run the pymongo insert _ one command against the default database and collection and returne the inserted ID ."""
# print ( f " database . collection : ' { self . database . name } . { self . collection . name } ' " ) result = self . collection . insert_one ( * args , ** kwargs ) return result . inserted_id