idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
19,300
def run_with_output ( self , * args , ** kwargs ) : for job in self . jobs : job . run_with_output ( * args , ** kwargs )
Runs command on every first job in the run returns stdout .
19,301
def _run_raw ( self , * args , ** kwargs ) : for job in self . jobs : job . _run_raw ( * args , ** kwargs )
_run_raw on every job in the run .
19,302
def keypair_setup ( ) : os . system ( 'mkdir -p ' + u . PRIVATE_KEY_LOCATION ) keypair_name = u . get_keypair_name ( ) keypair = u . get_keypair_dict ( ) . get ( keypair_name , None ) keypair_fn = u . get_keypair_fn ( ) if keypair : print ( "Reusing keypair " + keypair_name ) assert os . path . exists ( keypair_fn ) , ...
Creates keypair if necessary saves private key locally returns contents of private key file .
19,303
def placement_group_setup ( group_name ) : existing_placement_groups = u . get_placement_group_dict ( ) group = existing_placement_groups . get ( group_name , None ) if group : assert group . state == 'available' assert group . strategy == 'cluster' print ( "Reusing group " , group . name ) return group print ( "Creati...
Creates placement_group group if necessary . Returns True if new placement_group group was created False otherwise .
19,304
def upload ( self , local_fn : str , remote_fn : str = '' , dont_overwrite : bool = False ) : raise NotImplementedError ( )
Uploads given file to the task . If remote_fn is not specified dumps it into task current directory with the same name .
19,305
def _non_blocking_wrapper ( self , method , * args , ** kwargs ) : exceptions = [ ] def task_run ( task ) : try : getattr ( task , method ) ( * args , ** kwargs ) except Exception as e : exceptions . append ( e ) threads = [ threading . Thread ( name = f'task_{method}_{i}' , target = task_run , args = [ t ] ) for i , t...
Runs given method on every task in the job . Blocks until all tasks finish . Propagates exception from first failed task .
19,306
def get_default_vpc ( ) : ec2 = get_ec2_resource ( ) for vpc in ec2 . vpcs . all ( ) : if vpc . is_default : return vpc
Return default VPC or none if not present
19,307
def get_subnet_dict ( ) : subnet_dict = { } vpc = get_vpc ( ) for subnet in vpc . subnets . all ( ) : zone = subnet . availability_zone assert zone not in subnet_dict , "More than one subnet in %s, why?" % ( zone , ) subnet_dict [ zone ] = subnet return subnet_dict
Returns dictionary of availability zone - > subnet for current VPC .
19,308
def get_keypair_name ( ) : username = get_username ( ) assert '-' not in username , "username must not contain -, change $USER" validate_aws_name ( username ) assert len ( username ) < 30 return get_prefix ( ) + '-' + username
Returns current keypair name .
19,309
def get_keypair_fn ( ) : keypair_name = get_keypair_name ( ) account = get_account_number ( ) region = get_region ( ) fn = f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem' return fn
Location of . pem file for current keypair
19,310
def lookup_instance ( name : str , instance_type : str = '' , image_name : str = '' , states : tuple = ( 'running' , 'stopped' , 'initializing' ) ) : ec2 = get_ec2_resource ( ) instances = ec2 . instances . filter ( Filters = [ { 'Name' : 'instance-state-name' , 'Values' : states } ] ) prefix = get_prefix ( ) username ...
Looks up AWS instance for given instance name like simple . worker . If no instance found in current AWS environment returns None .
19,311
def ssh_to_task ( task ) -> paramiko . SSHClient : username = task . ssh_username hostname = task . public_ip ssh_key_fn = get_keypair_fn ( ) print ( f"ssh -i {ssh_key_fn} {username}@{hostname}" ) pkey = paramiko . RSAKey . from_private_key_file ( ssh_key_fn ) ssh_client = paramiko . SSHClient ( ) ssh_client . set_miss...
Create ssh connection to task s machine
19,312
def delete_efs_by_id ( efs_id ) : start_time = time . time ( ) efs_client = get_efs_client ( ) sys . stdout . write ( "deleting %s ... " % ( efs_id , ) ) while True : try : response = efs_client . delete_file_system ( FileSystemId = efs_id ) if is_good_response ( response ) : print ( "succeeded" ) break time . sleep ( ...
Deletion sometimes fails try several times .
19,313
def extract_attr_for_match ( items , ** kwargs ) : query_arg = None for arg , value in kwargs . items ( ) : if value == - 1 : assert query_arg is None , "Only single query arg (-1 valued) is allowed" query_arg = arg result = [ ] filterset = set ( kwargs . keys ( ) ) for item in items : match = True assert filterset . i...
Helper method to get attribute value for an item matching some criterion . Specify target criteria value as dict with target attribute having value - 1
19,314
def get_instance_property ( instance , property_name ) : name = get_name ( instance ) while True : try : value = getattr ( instance , property_name ) if value is not None : break print ( f"retrieving {property_name} on {name} produced None, retrying" ) time . sleep ( RETRY_INTERVAL_SEC ) instance . reload ( ) continue ...
Retrieves property of an instance keeps retrying until getting a non - None
19,315
def wait_until_available ( resource ) : while True : resource . load ( ) if resource . state == 'available' : break time . sleep ( RETRY_INTERVAL_SEC )
Waits until interval state becomes available
19,316
def maybe_create_placement_group ( name = '' , max_retries = 10 ) : if not name : return client = get_ec2_client ( ) while True : try : client . describe_placement_groups ( GroupNames = [ name ] ) print ( "Reusing placement_group group: " + name ) break except Exception : print ( "Creating placement_group group: " + na...
Creates placement_group group or reuses existing one . Crash if unable to create placement_group group . If name is empty ignores request .
19,317
def is_chief ( task : backend . Task , run_name : str ) : global run_task_dict if run_name not in run_task_dict : return True task_list = run_task_dict [ run_name ] assert task in task_list , f"Task {task.name} doesn't belong to run {run_name}" return task_list [ 0 ] == task
Returns True if task is chief task in the corresponding run
19,318
def ossystem ( cmd ) : p = subprocess . Popen ( cmd , shell = True , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) ( stdout , stderr ) = p . communicate ( ) return stdout . decode ( 'ascii' )
Like os . system but returns output of command as string .
19,319
def _maybe_create_resources ( logging_task : Task = None ) : def log ( * args ) : if logging_task : logging_task . log ( * args ) else : util . log ( * args ) def should_create_resources ( ) : prefix = u . get_prefix ( ) if u . get_keypair_name ( ) not in u . get_keypair_dict ( ) : log ( f"Missing {u.get_keypair_name()...
Use heuristics to decide to possibly create resources
19,320
def _set_aws_environment ( task : Task = None ) : current_zone = os . environ . get ( 'NCLUSTER_ZONE' , '' ) current_region = os . environ . get ( 'AWS_DEFAULT_REGION' , '' ) def log ( * args ) : if task : task . log ( * args ) else : util . log ( * args ) if current_region and current_zone : assert current_zone . star...
Sets up AWS environment from NCLUSTER environment variables
19,321
def join ( self , ignore_errors = False ) : assert self . _status_fn , "Asked to join a task which hasn't had any commands executed on it" check_interval = 0.2 status_fn = self . _status_fn if not self . wait_for_file ( status_fn , max_wait_sec = 30 ) : self . log ( f"Retrying waiting for {status_fn}" ) while not self ...
Waits until last executed command completed .
19,322
def _run_with_output_on_failure ( self , cmd , non_blocking = False , ignore_errors = False , max_wait_sec = 365 * 24 * 3600 , check_interval = 0.2 ) -> str : if not self . _can_run : assert False , "Using .run before initialization finished" if '\n' in cmd : assert False , "Don't support multi-line for run2" cmd = cmd...
Experimental version of run propagates error messages to client . This command will be default run eventually
19,323
def upload ( self , local_fn : str , remote_fn : str = '' , dont_overwrite : bool = False ) -> None : if '*' in local_fn : for local_subfn in glob . glob ( local_fn ) : self . upload ( local_subfn ) return if '#' in local_fn : self . log ( "skipping backup file {local_fn}" ) return if not self . sftp : self . sftp = u ...
Uploads file to remote instance . If location not specified dumps it into default directory . If remote location has files or directories with the same name behavior is undefined .
19,324
def _replace_lines ( fn , startswith , new_line ) : new_lines = [ ] for line in open ( fn ) : if line . startswith ( startswith ) : new_lines . append ( new_line ) else : new_lines . append ( line ) with open ( fn , 'w' ) as f : f . write ( '\n' . join ( new_lines ) )
Replace lines starting with starts_with in fn with new_line .
19,325
def now_micros ( absolute = False ) -> int : micros = int ( time . time ( ) * 1e6 ) if absolute : return micros return micros - EPOCH_MICROS
Return current micros since epoch as integer .
19,326
def now_millis ( absolute = False ) -> int : millis = int ( time . time ( ) * 1e3 ) if absolute : return millis return millis - EPOCH_MICROS // 1000
Return current millis since epoch as integer .
19,327
def install_pdb_handler ( ) : import signal import pdb def handler ( _signum , _frame ) : pdb . set_trace ( ) signal . signal ( signal . SIGQUIT , handler )
Make CTRL + \ break into gdb .
19,328
def shell_add_echo ( script ) : new_script = "" for cmd in script . split ( '\n' ) : cmd = cmd . strip ( ) if not cmd : continue new_script += "echo \\* " + shlex . quote ( cmd ) + "\n" new_script += cmd + "\n" return new_script
Goes over each line script adds echo cmd in front of each cmd .
19,329
def random_id ( k = 5 ) : return '' . join ( random . choices ( string . ascii_lowercase + string . digits , k = k ) )
Random id to use for AWS identifiers .
19,330
def alphanumeric_hash ( s : str , size = 5 ) : import hashlib import base64 hash_object = hashlib . md5 ( s . encode ( 'ascii' ) ) s = base64 . b32encode ( hash_object . digest ( ) ) result = s [ : size ] . decode ( 'ascii' ) . lower ( ) return result
Short alphanumeric string derived from hash of given string
19,331
def is_bash_builtin ( cmd ) : bash_builtins = [ 'alias' , 'bg' , 'bind' , 'alias' , 'bg' , 'bind' , 'break' , 'builtin' , 'caller' , 'cd' , 'command' , 'compgen' , 'complete' , 'compopt' , 'continue' , 'declare' , 'dirs' , 'disown' , 'echo' , 'enable' , 'eval' , 'exec' , 'exit' , 'export' , 'false' , 'fc' , 'fg' , 'get...
Return true if command is invoking bash built - in
19,332
def is_set ( name ) : val = os . environ . get ( name , '0' ) assert val == '0' or val == '1' , f"env var {name} has value {val}, expected 0 or 1" return val == '1'
Helper method to check if given property is set
19,333
def assert_script_in_current_directory ( ) : script = sys . argv [ 0 ] assert os . path . abspath ( os . path . dirname ( script ) ) == os . path . abspath ( '.' ) , f"Change into directory of script {script} and run again."
Assert fail if current directory is different from location of the script
19,334
def load_fixtures ( db , fixtures ) : conn = db . engine . connect ( ) metadata = db . metadata for fixture in fixtures : if 'model' in fixture : module_name , class_name = fixture [ 'model' ] . rsplit ( '.' , 1 ) module = importlib . import_module ( module_name ) model = getattr ( module , class_name ) for fields in f...
Loads the given fixtures into the database .
19,335
def setup_handler ( setup_fixtures_fn , setup_fn ) : def handler ( obj ) : setup_fixtures_fn ( obj ) setup_fn ( obj ) return handler
Returns a function that adds fixtures handling to the setup method .
19,336
def teardown_handler ( teardown_fixtures_fn , teardown_fn ) : def handler ( obj ) : teardown_fn ( obj ) teardown_fixtures_fn ( obj ) return handler
Returns a function that adds fixtures handling to the teardown method .
19,337
def get_child_fn ( attrs , names , bases ) : def call_method ( obj , method ) : if isinstance ( obj , type ) : instance = None owner = obj else : instance = obj owner = obj . __class__ method . __get__ ( instance , owner ) ( ) default_name = names [ 0 ] def default_fn ( obj ) : for cls in bases : if hasattr ( cls , def...
Returns a function from the child class that matches one of the names .
19,338
def print_msg ( msg , header , file = sys . stdout ) : DEFAULT_MSG_BLOCK_WIDTH = 60 side_boarder_length = ( DEFAULT_MSG_BLOCK_WIDTH - ( len ( header ) + 2 ) ) // 2 msg_block_width = side_boarder_length * 2 + ( len ( header ) + 2 ) side_boarder = '#' * side_boarder_length top_boarder = '{0} {1} {2}' . format ( side_boar...
Prints a boardered message to the screen
19,339
def can_persist_fixtures ( ) : if sys . hexversion >= 0x02070000 : return True filename = inspect . stack ( ) [ - 1 ] [ 1 ] executable = os . path . split ( filename ) [ 1 ] return executable in ( 'py.test' , 'nosetests' )
Returns True if it s possible to persist fixtures across tests .
19,340
def read_since_ids ( users ) : since_ids = { } for user in users : if config . has_option ( SECTIONS [ 'INCREMENTS' ] , user ) : since_ids [ user ] = config . getint ( SECTIONS [ 'INCREMENTS' ] , user ) + 1 return since_ids
Read max ids of the last downloads
19,341
def set_max_ids ( max_ids ) : config . read ( CONFIG ) for user , max_id in max_ids . items ( ) : config . set ( SECTIONS [ 'INCREMENTS' ] , user , str ( max_id ) ) with open ( CONFIG , 'w' ) as f : config . write ( f )
Set max ids of the current downloads
19,342
def authenticate ( self , username = None , password = None , actions = None , response = None , authorization = None ) : if response is None : with warnings . catch_warnings ( ) : _ignore_warnings ( self ) response = self . _sessions [ 0 ] . get ( self . _base_url , verify = self . _tlsverify ) if response . ok : retu...
Authenticate to the registry using a username and password an authorization header or otherwise as the anonymous user .
19,343
def list_repos ( self , batch_size = None , iterate = False ) : it = PaginatingResponse ( self , '_base_request' , '_catalog' , 'repositories' , params = { 'n' : batch_size } ) return it if iterate else list ( it )
List all repositories in the registry .
19,344
def pull_blob ( self , digest , size = False , chunk_size = None ) : if chunk_size is None : chunk_size = 8192 r = self . _request ( 'get' , 'blobs/' + digest , stream = True ) class Chunks ( object ) : def __iter__ ( self ) : sha256 = hashlib . sha256 ( ) for chunk in r . iter_content ( chunk_size ) : sha256 . update ...
Download a blob from the registry given the hash of its content .
19,345
def blob_size ( self , digest ) : r = self . _request ( 'head' , 'blobs/' + digest ) return long ( r . headers [ 'content-length' ] )
Return the size of a blob in the registry given the hash of its content .
19,346
def get_manifest_and_response ( self , alias ) : r = self . _request ( 'get' , 'manifests/' + alias , headers = { 'Accept' : _schema2_mimetype + ', ' + _schema1_mimetype } ) return r . content . decode ( 'utf-8' ) , r
Request the manifest for an alias and return the manifest and the response .
19,347
def get_alias ( self , alias = None , manifest = None , verify = True , sizes = False , dcd = None ) : return self . _get_alias ( alias , manifest , verify , sizes , dcd , False )
Get the blob hashes assigned to an alias .
19,348
def _get_dcd ( self , alias ) : return self . _request ( 'head' , 'manifests/{}' . format ( alias ) , headers = { 'Accept' : _schema2_mimetype } , ) . headers . get ( 'Docker-Content-Digest' )
Get the Docker - Content - Digest header for an alias .
19,349
def get_name ( self , name_case = DdlParseBase . NAME_CASE . original ) : if name_case == self . NAME_CASE . lower : return self . _name . lower ( ) elif name_case == self . NAME_CASE . upper : return self . _name . upper ( ) else : return self . _name
Get Name converted case
19,350
def bigquery_data_type ( self ) : BQ_DATA_TYPE_DIC = OrderedDict ( ) BQ_DATA_TYPE_DIC [ "STRING" ] = { None : [ re . compile ( r"(CHAR|TEXT|CLOB|JSON|UUID)" ) ] } BQ_DATA_TYPE_DIC [ "INTEGER" ] = { None : [ re . compile ( r"INT|SERIAL|YEAR" ) ] } BQ_DATA_TYPE_DIC [ "FLOAT" ] = { None : [ re . compile ( r"(FLOAT|DOUBLE)...
Get BigQuery Legacy SQL data type
19,351
def to_bigquery_field ( self , name_case = DdlParseBase . NAME_CASE . original ) : col_name = self . get_name ( name_case ) mode = self . bigquery_mode if self . array_dimensional <= 1 : type = self . bigquery_legacy_data_type else : type = "RECORD" fields = OrderedDict ( ) fields_cur = fields for i in range ( 1 , self...
Generate BigQuery JSON field define
19,352
def to_bigquery_ddl ( self , name_case = DdlParseBase . NAME_CASE . original ) : if self . schema is None : dataset = "dataset" elif name_case == self . NAME_CASE . lower : dataset = self . schema . lower ( ) elif name_case == self . NAME_CASE . upper : dataset = self . schema . upper ( ) else : dataset = self . schema...
Generate BigQuery CREATE TABLE statements
19,353
def parse ( self , ddl = None , source_database = None ) : if ddl is not None : self . _ddl = ddl if source_database is not None : self . source_database = source_database if self . _ddl is None : raise ValueError ( "DDL is not specified" ) ret = self . _DDL_PARSE_EXPR . parseString ( self . _ddl ) if "schema" in ret :...
Parse DDL script .
19,354
def launch ( program , sock , stderr = True , cwd = None , env = None ) : if stderr is True : err = sock elif stderr is False : err = open ( os . devnull , 'wb' ) elif stderr is None : err = None p = subprocess . Popen ( program , shell = type ( program ) not in ( list , tuple ) , stdin = sock , stdout = sock , stderr ...
A static method for launching a process that is connected to a given socket . Same rules from the Process constructor apply .
19,355
def respond ( self , packet , peer , flags = 0 ) : self . sock . sendto ( packet , flags , peer )
Send a message back to a peer .
19,356
def shutdown_rd ( self ) : if self . _sock_send is not None : self . sock . close ( ) else : return self . shutdown ( socket . SHUT_RD )
Send a shutdown signal for reading - you may no longer read from this socket .
19,357
def shutdown_wr ( self ) : if self . _sock_send is not None : self . _sock_send . close ( ) else : return self . shutdown ( socket . SHUT_WR )
Send a shutdown signal for writing - you may no longer write to this socket .
19,358
def _recv_predicate ( self , predicate , timeout = 'default' , raise_eof = True ) : if timeout == 'default' : timeout = self . _timeout self . timed_out = False start = time . time ( ) try : while True : cut_at = predicate ( self . buf ) if cut_at > 0 : break if timeout is not None : time_elapsed = time . time ( ) - st...
Receive until predicate returns a positive integer . The returned number is the size to return .
19,359
def recv_until ( self , s , max_size = None , timeout = 'default' ) : self . _print_recv_header ( '======== Receiving until {0}{timeout_text} ========' , timeout , repr ( s ) ) if max_size is None : max_size = 2 ** 62 def _predicate ( buf ) : try : return min ( buf . index ( s ) + len ( s ) , max_size ) except ValueErr...
Recieve data from the socket until the given substring is observed . Data in the same datagram as the substring following the substring will not be returned and will be cached for future receives .
19,360
def recv_all ( self , timeout = 'default' ) : self . _print_recv_header ( '======== Receiving until close{timeout_text} ========' , timeout ) return self . _recv_predicate ( lambda s : 0 , timeout , raise_eof = False )
Return all data recieved until connection closes .
19,361
def recv_exactly ( self , n , timeout = 'default' ) : self . _print_recv_header ( '======== Receiving until exactly {0}B{timeout_text} ========' , timeout , n ) return self . _recv_predicate ( lambda s : n if len ( s ) >= n else 0 , timeout )
Recieve exactly n bytes
19,362
def send ( self , s ) : self . _print_header ( '======== Sending ({0}) ========' . format ( len ( s ) ) ) self . _log_send ( s ) out = len ( s ) while s : s = s [ self . _send ( s ) : ] return out
Sends all the given data to the socket .
19,363
def interact ( self , insock = sys . stdin , outsock = sys . stdout ) : self . _print_header ( '======== Beginning interactive session ========' ) if hasattr ( outsock , 'buffer' ) : outsock = outsock . buffer self . timed_out = False save_verbose = self . verbose self . verbose = 0 try : if self . buf : outsock . writ...
Connects the socket to the terminal for user interaction . Alternate input and output files may be specified .
19,364
def recv_line ( self , max_size = None , timeout = 'default' , ending = None ) : if ending is None : ending = self . LINE_ENDING return self . recv_until ( ending , max_size , timeout )
Recieve until the next newline default \\ n . The newline string can be changed by changing nc . LINE_ENDING . The newline will be returned as part of the string .
19,365
def send_line ( self , line , ending = None ) : if ending is None : ending = self . LINE_ENDING return self . send ( line + ending )
Write the string to the wire followed by a newline . The newline string can be changed by changing nc . LINE_ENDING .
19,366
def is_active ( self , timperiods ) : now = int ( time . time ( ) ) timperiod = timperiods [ self . modulation_period ] if not timperiod or timperiod . is_time_valid ( now ) : return True return False
Know if this result modulation is active now
19,367
def object ( self , o_type , o_name = None ) : o_found = self . _get_object ( o_type = o_type , o_name = o_name ) if not o_found : return { '_status' : u'ERR' , '_message' : u'Required %s not found.' % o_type } return o_found
Get an object from the scheduler .
19,368
def monitoring_problems ( self ) : if self . app . type != 'scheduler' : return { '_status' : u'ERR' , '_message' : u"This service is only available for a scheduler daemon" } res = self . identity ( ) res . update ( self . app . get_monitoring_problems ( ) ) return res
Get Alignak scheduler monitoring status
19,369
def _wait_new_conf ( self ) : self . app . sched . stop_scheduling ( ) super ( SchedulerInterface , self ) . _wait_new_conf ( )
Ask the scheduler to drop its configuration and wait for a new one .
19,370
def _initial_broks ( self , broker_name ) : with self . app . conf_lock : logger . info ( "A new broker just connected : %s" , broker_name ) return self . app . sched . fill_initial_broks ( broker_name )
Get initial_broks from the scheduler
19,371
def _broks ( self , broker_name ) : logger . debug ( "Getting broks for %s from the scheduler" , broker_name ) for broker_link in list ( self . app . brokers . values ( ) ) : if broker_name == broker_link . name : break else : logger . warning ( "Requesting broks for an unknown broker: %s" , broker_name ) return { } wi...
Get the broks from a scheduler used by brokers
19,372
def _get_objects ( self , o_type ) : if o_type not in [ t for t in self . app . sched . pushed_conf . types_creations ] : return None try : _ , _ , strclss , _ , _ = self . app . sched . pushed_conf . types_creations [ o_type ] o_list = getattr ( self . app . sched , strclss ) except Exception : return None return o_li...
Get an object list from the scheduler
19,373
def _get_object ( self , o_type , o_name = None ) : try : o_found = None o_list = self . _get_objects ( o_type ) if o_list : if o_name is None : return serialize ( o_list , True ) if o_list else None o_found = o_list . find_by_name ( o_name ) if not o_found : o_found = o_list [ o_name ] except Exception : return None r...
Get an object from the scheduler
19,374
def is_a_module ( self , module_type ) : if hasattr ( self , 'type' ) : return module_type in self . type return module_type in self . module_types
Is the module of the required type?
19,375
def serialize ( self ) : res = super ( Module , self ) . serialize ( ) cls = self . __class__ for prop in self . __dict__ : if prop in cls . properties or prop in cls . running_properties or prop in [ 'properties' , 'my_daemon' ] : continue res [ prop ] = getattr ( self , prop ) return res
A module may have some properties that are not defined in the class properties list . Serializing a module is the same as serializing an Item but we also also include all the existing properties that are not defined in the properties or running_properties class list .
19,376
def linkify_s_by_plug ( self ) : for module in self : new_modules = [ ] for related in getattr ( module , 'modules' , [ ] ) : related = related . strip ( ) if not related : continue o_related = self . find_by_name ( related ) if o_related is not None : new_modules . append ( o_related . uuid ) else : self . add_error (...
Link a module to some other modules
19,377
def get_start_of_day ( year , month , day ) : try : timestamp = time . mktime ( ( year , month , day , 00 , 00 , 00 , 0 , 0 , - 1 ) ) except ( OverflowError , ValueError ) : timestamp = 0.0 return int ( timestamp )
Get the timestamp associated to the first second of a specific day
19,378
def get_end_of_day ( year , month , day ) : timestamp = time . mktime ( ( year , month , day , 23 , 59 , 59 , 0 , 0 , - 1 ) ) return int ( timestamp )
Get the timestamp associated to the last second of a specific day
19,379
def get_sec_from_morning ( timestamp ) : t_lt = time . localtime ( timestamp ) return t_lt . tm_hour * 3600 + t_lt . tm_min * 60 + t_lt . tm_sec
Get the number of seconds elapsed since the beginning of the day deducted from the provided timestamp
19,380
def find_day_by_weekday_offset ( year , month , weekday , offset ) : cal = calendar . monthcalendar ( year , month ) if offset < 0 : offset = abs ( offset ) cal . reverse ( ) nb_found = 0 try : for i in range ( 0 , offset + 1 ) : if cal [ i ] [ weekday ] != 0 : nb_found += 1 if nb_found == offset : return cal [ i ] [ w...
Get the day number based on a date and offset
19,381
def find_day_by_offset ( year , month , offset ) : ( _ , days_in_month ) = calendar . monthrange ( year , month ) if offset >= 0 : return min ( offset , days_in_month ) return max ( 1 , days_in_month + offset + 1 )
Get the month day based on date and offset
19,382
def is_time_valid ( self , timestamp ) : sec_from_morning = get_sec_from_morning ( timestamp ) return ( self . is_valid and self . hstart * 3600 + self . mstart * 60 <= sec_from_morning <= self . hend * 3600 + self . mend * 60 )
Check if time is valid for this Timerange
19,383
def is_time_valid ( self , timestamp ) : if self . is_time_day_valid ( timestamp ) : for timerange in self . timeranges : if timerange . is_time_valid ( timestamp ) : return True return False
Check if time is valid for one of the timerange .
19,384
def get_min_sec_from_morning ( self ) : mins = [ ] for timerange in self . timeranges : mins . append ( timerange . get_sec_from_morning ( ) ) return min ( mins )
Get the first second from midnight where a timerange is effective
19,385
def is_time_day_valid ( self , timestamp ) : ( start_time , end_time ) = self . get_start_and_end_time ( timestamp ) return start_time <= timestamp <= end_time
Check if it is within start time and end time of the DateRange
19,386
def get_next_future_timerange_invalid ( self , timestamp ) : sec_from_morning = get_sec_from_morning ( timestamp ) ends = [ ] for timerange in self . timeranges : tr_end = timerange . hend * 3600 + timerange . mend * 60 if tr_end >= sec_from_morning : if tr_end == 86400 : tr_end = 86399 ends . append ( tr_end ) if ends...
Get next invalid time for timeranges
19,387
def get_next_valid_day ( self , timestamp ) : if self . get_next_future_timerange_valid ( timestamp ) is None : ( start_time , _ ) = self . get_start_and_end_time ( get_day ( timestamp ) + 86400 ) else : ( start_time , _ ) = self . get_start_and_end_time ( timestamp ) if timestamp <= start_time : return get_day ( start...
Get next valid day for timerange
19,388
def get_next_valid_time_from_t ( self , timestamp ) : if self . is_time_valid ( timestamp ) : return timestamp t_day = self . get_next_valid_day ( timestamp ) if t_day is None : return t_day if timestamp < t_day : sec_from_morning = self . get_next_future_timerange_valid ( t_day ) else : sec_from_morning = self . get_n...
Get next valid time for time range
19,389
def get_next_invalid_day ( self , timestamp ) : if self . is_time_day_invalid ( timestamp ) : return timestamp next_future_timerange_invalid = self . get_next_future_timerange_invalid ( timestamp ) if next_future_timerange_invalid is None : ( start_time , end_time ) = self . get_start_and_end_time ( get_day ( timestamp...
Get next day where timerange is not active
19,390
def get_next_invalid_time_from_t ( self , timestamp ) : if not self . is_time_valid ( timestamp ) : return timestamp t_day = self . get_next_invalid_day ( timestamp ) if timestamp < t_day : sec_from_morning = self . get_next_future_timerange_invalid ( t_day ) else : sec_from_morning = self . get_next_future_timerange_i...
Get next invalid time for time range
19,391
def get_start_and_end_time ( self , ref = None ) : return ( get_start_of_day ( self . syear , int ( self . smon ) , self . smday ) , get_end_of_day ( self . eyear , int ( self . emon ) , self . emday ) )
Specific function to get start time and end time for CalendarDaterange
19,392
def get_start_and_end_time ( self , ref = None ) : now = time . localtime ( ref ) self . syear = now . tm_year self . month = now . tm_mon self . wday = now . tm_wday day_id = Daterange . get_weekday_id ( self . day ) today_morning = get_start_of_day ( now . tm_year , now . tm_mon , now . tm_mday ) tonight = get_end_of...
Specific function to get start time and end time for StandardDaterange
19,393
def get_start_and_end_time ( self , ref = None ) : now = time . localtime ( ref ) if self . syear == 0 : self . syear = now . tm_year day_start = find_day_by_weekday_offset ( self . syear , self . smon , self . swday , self . swday_offset ) start_time = get_start_of_day ( self . syear , self . smon , day_start ) if sel...
Specific function to get start time and end time for MonthWeekDayDaterange
19,394
def get_start_and_end_time ( self , ref = None ) : now = time . localtime ( ref ) if self . syear == 0 : self . syear = now . tm_year day_start = find_day_by_offset ( self . syear , self . smon , self . smday ) start_time = get_start_of_day ( self . syear , self . smon , day_start ) if self . eyear == 0 : self . eyear ...
Specific function to get start time and end time for MonthDateDaterange
19,395
def get_start_and_end_time ( self , ref = None ) : now = time . localtime ( ref ) if self . syear == 0 : self . syear = now . tm_year month_start_id = now . tm_mon day_start = find_day_by_weekday_offset ( self . syear , month_start_id , self . swday , self . swday_offset ) start_time = get_start_of_day ( self . syear ,...
Specific function to get start time and end time for WeekDayDaterange
19,396
def get_start_and_end_time ( self , ref = None ) : now = time . localtime ( ref ) if self . syear == 0 : self . syear = now . tm_year month_start_id = now . tm_mon day_start = find_day_by_offset ( self . syear , month_start_id , self . smday ) start_time = get_start_of_day ( self . syear , month_start_id , day_start ) ...
Specific function to get start time and end time for MonthDayDaterange
19,397
def get_unknown_check_result_brok ( cmd_line ) : match = re . match ( r'^\[([0-9]{10})] PROCESS_(SERVICE)_CHECK_RESULT;' r'([^\;]*);([^\;]*);([^\;]*);([^\|]*)(?:\|(.*))?' , cmd_line ) if not match : match = re . match ( r'^\[([0-9]{10})] PROCESS_(HOST)_CHECK_RESULT;' r'([^\;]*);([^\;]*);([^\|]*)(?:\|(.*))?' , cmd_line ...
Create unknown check result brok and fill it with command data
19,398
def get_name ( self ) : dependent_host_name = 'unknown' if getattr ( self , 'dependent_host_name' , None ) : dependent_host_name = getattr ( getattr ( self , 'dependent_host_name' ) , 'host_name' , 'unknown' ) host_name = 'unknown' if getattr ( self , 'host_name' , None ) : host_name = getattr ( getattr ( self , 'host_...
Get name based on dependent_host_name and host_name attributes Each attribute is substituted by unknown if attribute does not exist
19,399
def linkify_hd_by_h ( self , hosts ) : for hostdep in self : try : h_name = hostdep . host_name dh_name = hostdep . dependent_host_name host = hosts . find_by_name ( h_name ) if host is None : err = "Error: the host dependency got a bad host_name definition '%s'" % h_name hostdep . add_error ( err ) dephost = hosts . f...
Replace dependent_host_name and host_name in host dependency by the real object