idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
19,800
def no_block_read ( output ) : _buffer = "" if not fcntl : return _buffer o_fd = output . fileno ( ) o_fl = fcntl . fcntl ( o_fd , fcntl . F_GETFL ) fcntl . fcntl ( o_fd , fcntl . F_SETFL , o_fl | os . O_NONBLOCK ) try : _buffer = output . read ( ) except Exception : pass return _buffer
Try to read a file descriptor in a non blocking mode
19,801
def get_local_environnement ( self ) : local_env = os . environ . copy ( ) for local_var in self . env : local_env [ local_var ] = self . env [ local_var ] return local_env
Mix the environment and the environment variables into a new local environment dictionary
19,802
def execute ( self ) : self . status = ACT_STATUS_LAUNCHED self . check_time = time . time ( ) self . wait_time = 0.0001 self . last_poll = self . check_time self . local_env = self . get_local_environnement ( ) self . stdoutdata = '' self . stderrdata = '' logger . debug ( "Launch command: '%s', ref: %s, timeout: %s" ...
Start this action command in a subprocess .
19,803
def copy_shell__ ( self , new_i ) : for prop in ONLY_COPY_PROP : setattr ( new_i , prop , getattr ( self , prop ) ) return new_i
Create all attributes listed in ONLY_COPY_PROP and return self with these attributes .
19,804
def get_contacts_by_explosion ( self , contactgroups ) : self . already_exploded = True if self . rec_tag : logger . error ( "[contactgroup::%s] got a loop in contactgroup definition" , self . get_name ( ) ) if hasattr ( self , 'members' ) : return self . members return '' self . rec_tag = True cg_mbrs = self . get_con...
Get contacts of this group
19,805
def add_member ( self , contact_name , contactgroup_name ) : contactgroup = self . find_by_name ( contactgroup_name ) if not contactgroup : contactgroup = Contactgroup ( { 'contactgroup_name' : contactgroup_name , 'alias' : contactgroup_name , 'members' : contact_name } ) self . add_contactgroup ( contactgroup ) else :...
Add a contact string to a contact member if the contact group do not exist create it
19,806
def linkify_contactgroups_contacts ( self , contacts ) : for contactgroup in self : mbrs = contactgroup . get_contacts ( ) new_mbrs = [ ] for mbr in mbrs : mbr = mbr . strip ( ) if mbr == '' : continue member = contacts . find_by_name ( mbr ) if member is not None : new_mbrs . append ( member . uuid ) else : contactgro...
Link the contacts with contactgroups
19,807
def explode ( self ) : for tmp_cg in list ( self . items . values ( ) ) : tmp_cg . already_exploded = False for contactgroup in list ( self . items . values ( ) ) : if contactgroup . already_exploded : continue for tmp_cg in list ( self . items . values ( ) ) : tmp_cg . rec_tag = False contactgroup . get_contacts_by_ex...
Fill members with contactgroup_members
19,808
def add_flapping_change ( self , sample ) : cls = self . __class__ if not self . flap_detection_enabled or not cls . enable_flap_detection : return self . flapping_changes . append ( sample ) flap_history = cls . flap_history if len ( self . flapping_changes ) > flap_history : self . flapping_changes . pop ( 0 )
Add a flapping sample and keep cls . flap_history samples
19,809
def add_attempt ( self ) : self . attempt += 1 self . attempt = min ( self . attempt , self . max_check_attempts )
Add an attempt when a object is a non - ok state
19,810
def do_check_freshness ( self , hosts , services , timeperiods , macromodulations , checkmodulations , checks , when ) : now = when cls = self . __class__ if not self . in_checking and self . freshness_threshold and not self . freshness_expired : if os . getenv ( 'ALIGNAK_LOG_CHECKS' , None ) : logger . info ( "--ALC--...
Check freshness and schedule a check now if necessary .
19,811
def update_business_impact_value ( self , hosts , services , timeperiods , bi_modulations ) : if self . my_own_business_impact == - 1 : self . my_own_business_impact = self . business_impact in_modulation = False for bi_modulation_id in self . business_impact_modulations : bi_modulation = bi_modulations [ bi_modulation...
We update our business_impact value with the max of the impacts business_impact if we got impacts . And save our configuration business_impact if we do not have do it before If we do not have impacts we revert our value
19,812
def no_more_a_problem ( self , hosts , services , timeperiods , bi_modulations ) : was_pb = self . is_problem if self . is_problem : self . is_problem = False for impact_id in self . impacts : if impact_id in hosts : impact = hosts [ impact_id ] else : impact = services [ impact_id ] impact . unregister_a_problem ( sel...
Remove this objects as an impact for other schedulingitem .
19,813
def register_a_problem ( self , prob , hosts , services , timeperiods , bi_modulations ) : if prob . uuid in self . source_problems : return [ ] now = time . time ( ) was_an_impact = self . is_impact self . is_impact = True impacts = [ ] if self . is_impact : logger . debug ( "I am impacted: %s" , self ) if self . is_p...
Call recursively by potentials impacts so they update their source_problems list . But do not go below if the problem is not a real one for me like If I ve got multiple parents for examples
19,814
def unregister_a_problem ( self , prob ) : self . source_problems . remove ( prob . uuid ) if not self . source_problems : self . is_impact = False self . unset_impact_state ( ) self . broks . append ( self . get_update_status_brok ( ) )
Remove the problem from our problems list and check if we are still impacted
19,815
def is_enable_action_dependent ( self , hosts , services ) : enable_action = False for ( dep_id , status , _ , _ ) in self . act_depend_of : if 'n' in status : enable_action = True else : if dep_id in hosts : dep = hosts [ dep_id ] else : dep = services [ dep_id ] p_is_down = False dep_match = [ dep . is_state ( stat )...
Check if dependencies states match dependencies statuses This basically means that a dependency is in a bad state and it can explain this object state .
19,816
def check_and_set_unreachability ( self , hosts , services ) : parent_is_down = [ ] for ( dep_id , _ , _ , _ ) in self . act_depend_of : if dep_id in hosts : dep = hosts [ dep_id ] else : dep = services [ dep_id ] if dep . state in [ 'd' , 'DOWN' , 'c' , 'CRITICAL' , 'u' , 'UNKNOWN' , 'x' , 'UNREACHABLE' ] : parent_is_...
Check if all dependencies are down if yes set this object as unreachable .
19,817
def compensate_system_time_change ( self , difference ) : for prop in ( 'last_notification' , 'last_state_change' , 'last_hard_state_change' ) : val = getattr ( self , prop ) val = max ( 0 , val + difference ) setattr ( self , prop , val )
If a system time change occurs we have to update properties time related to reflect change
19,818
def remove_in_progress_check ( self , check ) : if check in self . checks_in_progress : self . checks_in_progress . remove ( check ) self . update_in_checking ( )
Remove check from check in progress
19,819
def remove_in_progress_notification ( self , notification ) : if notification . uuid in self . notifications_in_progress : notification . status = ACT_STATUS_ZOMBIE del self . notifications_in_progress [ notification . uuid ]
Remove a notification and mark them as zombie
19,820
def remove_in_progress_notifications ( self , master = True ) : for notification in list ( self . notifications_in_progress . values ( ) ) : if master and notification . contact : continue if notification . type in [ u'DOWNTIMESTART' , u'DOWNTIMEEND' , u'DOWNTIMECANCELLED' , u'CUSTOM' , u'ACKNOWLEDGEMENT' ] : continue ...
Remove all notifications from notifications_in_progress
19,821
def check_for_flexible_downtime ( self , timeperiods , hosts , services ) : status_updated = False for downtime_id in self . downtimes : downtime = self . downtimes [ downtime_id ] if downtime . fixed or downtime . is_in_effect : continue if downtime . start_time <= self . last_chk and downtime . end_time >= self . las...
Enter in a downtime if necessary and raise start notification When a non Ok state occurs we try to raise a flexible downtime .
19,822
def update_hard_unknown_phase_state ( self ) : self . was_in_hard_unknown_reach_phase = self . in_hard_unknown_reach_phase if self . state_type != 'HARD' or self . last_state_type != 'HARD' : self . in_hard_unknown_reach_phase = False if not self . in_hard_unknown_reach_phase : if self . state == 'UNKNOWN' and self . l...
Update in_hard_unknown_reach_phase attribute and was_in_hard_unknown_reach_phase UNKNOWN during a HARD state are not so important and they should not raise notif about it
19,823
def update_notification_command ( self , notif , contact , macromodulations , timeperiods , host_ref = None ) : cls = self . __class__ macrosolver = MacroResolver ( ) data = self . get_data_for_notifications ( contact , notif , host_ref ) notif . command = macrosolver . resolve_command ( notif . command_call , data , m...
Update the notification command by resolving Macros And because we are just launching the notification we can say that this contact has been notified
19,824
def is_escalable ( self , notification , escalations , timeperiods ) : cls = self . __class__ in_notif_time = time . time ( ) - notification . creation_time for escalation_id in self . escalations : escalation = escalations [ escalation_id ] escalation_period = timeperiods [ escalation . escalation_period ] if escalati...
Check if a notification can be escalated . Basically call is_eligible for each escalation
19,825
def get_next_notification_time ( self , notif , escalations , timeperiods ) : res = None now = time . time ( ) cls = self . __class__ notification_interval = self . notification_interval in_notif_time = time . time ( ) - notif . creation_time for escalation_id in self . escalations : escalation = escalations [ escalati...
Get the next notification time for a notification Take the standard notification_interval or ask for our escalation if one of them need a smaller value to escalade
19,826
def get_business_rule_output ( self , hosts , services , macromodulations , timeperiods ) : got_business_rule = getattr ( self , 'got_business_rule' , False ) if got_business_rule is False or self . business_rule is None : return "" output_template = self . business_rule_output_template if not output_template : return ...
Returns a status string for business rules based items formatted using business_rule_output_template attribute as template .
19,827
def business_rule_notification_is_blocked ( self , hosts , services ) : acknowledged = 0 for src_prob_id in self . source_problems : if src_prob_id in hosts : src_prob = hosts [ src_prob_id ] else : src_prob = services [ src_prob_id ] if src_prob . last_hard_state_id != 0 : if src_prob . problem_has_been_acknowledged :...
Process business rule notifications behaviour . If all problems have been acknowledged no notifications should be sent if state is not OK . By default downtimes are ignored unless explicitly told to be treated as acknowledgements through with the business_rule_downtime_as_ack set .
19,828
def fill_data_brok_from ( self , data , brok_type ) : super ( SchedulingItem , self ) . fill_data_brok_from ( data , brok_type ) if brok_type == 'check_result' : data [ 'command_name' ] = '' if self . check_command : data [ 'command_name' ] = self . check_command . command . command_name
Fill data brok dependent on the brok_type
19,829
def acknowledge_problem ( self , notification_period , hosts , services , sticky , notify , author , comment , end_time = 0 ) : comm = None logger . debug ( "Acknowledge requested for %s %s." , self . my_type , self . get_name ( ) ) if self . state != self . ok_up : if self . problem_has_been_acknowledged and self . ac...
Add an acknowledge
19,830
def check_for_expire_acknowledge ( self ) : if ( self . acknowledgement and self . acknowledgement . end_time != 0 and self . acknowledgement . end_time < time . time ( ) ) : self . unacknowledge_problem ( )
If have acknowledge and is expired delete it
19,831
def unacknowledge_problem ( self ) : if self . problem_has_been_acknowledged : logger . debug ( "[item::%s] deleting acknowledge of %s" , self . get_name ( ) , self . get_full_name ( ) ) self . problem_has_been_acknowledged = False if self . my_type == 'host' : self . broks . append ( self . acknowledgement . get_expir...
Remove the acknowledge reset the flag . The comment is deleted
19,832
def unacknowledge_problem_if_not_sticky ( self ) : if hasattr ( self , 'acknowledgement' ) and self . acknowledgement is not None : if not self . acknowledgement . sticky : self . unacknowledge_problem ( )
Remove the acknowledge if it is not sticky
19,833
def set_impact_state ( self ) : cls = self . __class__ if cls . enable_problem_impacts_states_change : logger . debug ( "%s is impacted and goes UNREACHABLE" , self ) self . state_before_impact = self . state self . state_id_before_impact = self . state_id self . state_changed_since_impact = False self . set_unreachabl...
We just go an impact so we go unreachable But only if we enable this state change in the conf
19,834
def unset_impact_state ( self ) : cls = self . __class__ if cls . enable_problem_impacts_states_change and not self . state_changed_since_impact : self . state = self . state_before_impact self . state_id = self . state_id_before_impact
Unset impact only if impact state change is set in configuration
19,835
def find_by_filter ( self , filters , all_items ) : items = [ ] for i in self : failed = False if hasattr ( i , "host" ) : all_items [ "service" ] = i else : all_items [ "host" ] = i for filt in filters : if not filt ( all_items ) : failed = True break if failed is False : items . append ( i ) return items
Find items by filters
19,836
def add_act_dependency ( self , son_id , parent_id , notif_failure_criteria , dep_period , inherits_parents ) : if son_id in self : son = self [ son_id ] else : msg = "Dependency son (%s) unknown, configuration error" % son_id self . add_error ( msg ) parent = self [ parent_id ] son . act_depend_of . append ( ( parent_...
Add a logical dependency for actions between two hosts or services .
19,837
def del_act_dependency ( self , son_id , parent_id ) : son = self [ son_id ] parent = self [ parent_id ] to_del = [ ] for ( host , status , timeperiod , inherits_parent ) in son . act_depend_of : if host == parent_id : to_del . append ( ( host , status , timeperiod , inherits_parent ) ) for tup in to_del : son . act_de...
Remove act_dependency between two hosts or services .
19,838
def add_chk_dependency ( self , son_id , parent_id , notif_failure_criteria , dep_period , inherits_parents ) : son = self [ son_id ] parent = self [ parent_id ] son . chk_depend_of . append ( ( parent_id , notif_failure_criteria , 'logic_dep' , dep_period , inherits_parents ) ) parent . chk_depend_of_me . append ( ( s...
Add a logical dependency for checks between two hosts or services .
19,839
def create_business_rules ( self , hosts , services , hostgroups , servicegroups , macromodulations , timeperiods ) : for item in self : item . create_business_rules ( hosts , services , hostgroups , servicegroups , macromodulations , timeperiods )
Loop on hosts or services and call SchedulingItem . create_business_rules
19,840
def get_services_by_explosion ( self , servicegroups ) : self . already_exploded = True if self . rec_tag : logger . error ( "[servicegroup::%s] got a loop in servicegroup definition" , self . get_name ( ) ) if hasattr ( self , 'members' ) : return self . members return '' self . rec_tag = True sg_mbrs = self . get_ser...
Get all services of this servicegroup and add it in members container
19,841
def explode ( self ) : for tmp_sg in list ( self . items . values ( ) ) : tmp_sg . already_exploded = False for servicegroup in list ( self . items . values ( ) ) : if servicegroup . already_exploded : continue for tmp_sg in list ( self . items . values ( ) ) : tmp_sg . rec_tag = False servicegroup . get_services_by_ex...
Get services and put them in members container
19,842
def setup_logger ( logger_configuration_file , log_dir = None , process_name = '' , log_file = '' ) : logger_ = logging . getLogger ( ALIGNAK_LOGGER_NAME ) for handler in logger_ . handlers : if not process_name : break if getattr ( handler , '_name' , None ) == 'daemons' : for hdlr in logger_ . handlers : if 'alignak_...
Configure the provided logger - get and update the content of the Json configuration file - configure the logger with this file
19,843
def set_log_console ( log_level = logging . INFO ) : logger_ = logging . getLogger ( ALIGNAK_LOGGER_NAME ) logger_ . setLevel ( log_level ) csh = ColorStreamHandler ( sys . stdout ) csh . setFormatter ( Formatter ( '[%(asctime)s] %(levelname)s: [%(name)s] %(message)s' , "%Y-%m-%d %H:%M:%S" ) ) logger_ . addHandler ( cs...
Set the Alignak daemons logger have a console log handler .
19,844
def set_log_level ( log_level = logging . INFO , handlers = None ) : logger_ = logging . getLogger ( ALIGNAK_LOGGER_NAME ) logger_ . setLevel ( log_level ) if handlers is not None : for handler in logger_ . handlers : if getattr ( handler , '_name' , None ) in handlers : handler . setLevel ( log_level )
Set the Alignak logger log level . This is mainly used for the arbiter verify code to set the log level at INFO level whatever the configured log level is set .
19,845
def make_monitoring_log ( level , message , timestamp = None , to_logger = False ) : level = level . lower ( ) if level not in [ 'debug' , 'info' , 'warning' , 'error' , 'critical' ] : return False if to_logger : logging . getLogger ( ALIGNAK_LOGGER_NAME ) . debug ( "Monitoring log: %s / %s" , level , message ) message...
Function used to build the monitoring log .
19,846
def want_service_notification ( self , notifways , timeperiods , timestamp , state , n_type , business_impact , cmd = None ) : if not self . service_notifications_enabled : return False for downtime_id in self . downtimes : downtime = self . downtimes [ downtime_id ] if downtime . is_in_effect : self . in_scheduled_dow...
Check if notification options match the state of the service
19,847
def want_host_notification ( self , notifways , timeperiods , timestamp , state , n_type , business_impact , cmd = None ) : if not self . host_notifications_enabled : return False for downtime in self . downtimes : if downtime . is_in_effect : self . in_scheduled_downtime = True return False self . in_scheduled_downtim...
Check if notification options match the state of the host
19,848
def explode ( self , contactgroups , notificationways ) : self . apply_partial_inheritance ( 'contactgroups' ) for prop in Contact . special_properties : if prop == 'contact_name' : continue self . apply_partial_inheritance ( prop ) for contact in self : if not ( hasattr ( contact , 'contact_name' ) and hasattr ( conta...
Explode all contact for each contactsgroup
19,849
def hook_save_retention ( self , scheduler ) : if not self . enabled : logger . warning ( "Alignak retention module is not enabled." "Saving objects state is not possible." ) return None try : start_time = time . time ( ) data_to_save = scheduler . get_retention_data ( ) if not data_to_save : logger . warning ( "Aligna...
Save retention data to a Json formated file
19,850
def get_check_command ( self , timeperiods , t_to_go ) : if not self . check_period or timeperiods [ self . check_period ] . is_time_valid ( t_to_go ) : return self . check_command return None
Get the check_command if we are in the check period modulation
19,851
def linkify ( self , timeperiods , commands ) : self . linkify_with_timeperiods ( timeperiods , 'check_period' ) self . linkify_one_command_with_commands ( commands , 'check_command' )
Replace check_period by real Timeperiod object into each CheckModulation Replace check_command by real Command object into each CheckModulation
19,852
def new_inner_member ( self , name = None , params = None ) : if name is None : name = 'Generated_checkmodulation_%s' % uuid . uuid4 ( ) if params is None : params = { } params [ 'checkmodulation_name' ] = name checkmodulation = CheckModulation ( params ) self . add_item ( checkmodulation )
Create a CheckModulation object and add it to items
19,853
def open ( self ) : if not self . _is_connected : print ( "Connecting to arduino on {}... " . format ( self . device ) , end = "" ) self . comm = serial . Serial ( ) self . comm . port = self . device self . comm . baudrate = self . baud_rate self . comm . timeout = self . timeout self . dtr = self . enable_dtr self . ...
Open the serial connection .
19,854
def close ( self ) : if self . _is_connected : self . comm . close ( ) self . _is_connected = False
Close serial connection .
19,855
def receive ( self , arg_formats = None ) : msg = [ [ ] ] raw_msg = [ ] escaped = False command_sep_found = False while True : tmp = self . board . read ( ) raw_msg . append ( tmp ) if escaped : if tmp in self . _escaped_characters : msg [ - 1 ] . append ( tmp ) escaped = False else : msg [ - 1 ] . append ( self . _byt...
Recieve commands coming off the serial port .
19,856
def _send_char ( self , value ) : if type ( value ) != str and type ( value ) != bytes : err = "char requires a string or bytes array of length 1" raise ValueError ( err ) if len ( value ) != 1 : err = "char must be a single character, not \"{}\"" . format ( value ) raise ValueError ( err ) if type ( value ) != bytes :...
Convert a single char to a bytes object .
19,857
def _send_byte ( self , value ) : if type ( value ) != int : new_value = int ( value ) if self . give_warnings : w = "Coercing {} into int ({})" . format ( value , new_value ) warnings . warn ( w , Warning ) value = new_value if value > 255 or value < 0 : err = "Value {} exceeds the size of the board's byte." . format ...
Convert a numerical value into an integer then to a byte object . Check bounds for byte .
19,858
def _send_int ( self , value ) : if type ( value ) != int : new_value = int ( value ) if self . give_warnings : w = "Coercing {} into int ({})" . format ( value , new_value ) warnings . warn ( w , Warning ) value = new_value if value > self . board . int_max or value < self . board . int_min : err = "Value {} exceeds t...
Convert a numerical value into an integer then to a bytes object Check bounds for signed int .
19,859
def _send_unsigned_int ( self , value ) : if type ( value ) != int : new_value = int ( value ) if self . give_warnings : w = "Coercing {} into int ({})" . format ( value , new_value ) warnings . warn ( w , Warning ) value = new_value if value > self . board . unsigned_int_max or value < self . board . unsigned_int_min ...
Convert a numerical value into an integer then to a bytes object . Check bounds for unsigned int .
19,860
def _send_long ( self , value ) : if type ( value ) != int : new_value = int ( value ) if self . give_warnings : w = "Coercing {} into int ({})" . format ( value , new_value ) warnings . warn ( w , Warning ) value = new_value if value > self . board . long_max or value < self . board . long_min : err = "Value {} exceed...
Convert a numerical value into an integer then to a bytes object . Check bounds for signed long .
19,861
def _send_unsigned_long ( self , value ) : if type ( value ) != int : new_value = int ( value ) if self . give_warnings : w = "Coercing {} into int ({})" . format ( value , new_value ) warnings . warn ( w , Warning ) value = new_value if value > self . board . unsigned_long_max or value < self . board . unsigned_long_m...
Convert a numerical value into an integer then to a bytes object . Check bounds for unsigned long .
19,862
def _send_string ( self , value ) : if type ( value ) != bytes : value = "{}" . format ( value ) . encode ( "ascii" ) return value
Convert a string to a bytes object . If value is not a string it is be converted to one with a standard string . format call .
19,863
def _send_bool ( self , value ) : if type ( value ) != bool and value not in [ 0 , 1 ] : err = "{} is not boolean." . format ( value ) raise ValueError ( err ) return struct . pack ( "?" , value )
Convert a boolean value into a bytes object . Uses 0 and 1 as output .
19,864
def _recv_guess ( self , value ) : if self . give_warnings : w = "Warning: Guessing input format for {}. This can give wildly incorrect values. Consider specifying a format and sending binary data." . format ( value ) warnings . warn ( w , Warning ) tmp_value = value . decode ( ) try : float ( tmp_value ) if len ( tmp_...
Take the binary spew and try to make it into a float or integer . If that can t be done return a string .
19,865
def _add_full_message ( gelf_dict , record ) : full_message = None if record . exc_info : full_message = '\n' . join ( traceback . format_exception ( * record . exc_info ) ) if record . exc_text : full_message = record . exc_text if full_message : gelf_dict [ "full_message" ] = full_message
Add the full_message field to the gelf_dict if any traceback information exists within the logging record
19,866
def _resolve_host ( fqdn , localname ) : if fqdn : return socket . getfqdn ( ) elif localname is not None : return localname return socket . gethostname ( )
Resolve the host GELF field
19,867
def _add_debugging_fields ( gelf_dict , record ) : gelf_dict . update ( { 'file' : record . pathname , 'line' : record . lineno , '_function' : record . funcName , '_pid' : record . process , '_thread_name' : record . threadName , } ) pn = getattr ( record , 'processName' , None ) if pn is not None : gelf_dict [ '_proc...
Add debugging fields to the given gelf_dict
19,868
def _add_extra_fields ( gelf_dict , record ) : skip_list = ( 'args' , 'asctime' , 'created' , 'exc_info' , 'exc_text' , 'filename' , 'funcName' , 'id' , 'levelname' , 'levelno' , 'lineno' , 'module' , 'msecs' , 'message' , 'msg' , 'name' , 'pathname' , 'process' , 'processName' , 'relativeCreated' , 'thread' , 'threadN...
Add extra fields to the given gelf_dict
19,869
def _pack_gelf_dict ( gelf_dict ) : gelf_dict = BaseGELFHandler . _sanitize_to_unicode ( gelf_dict ) packed = json . dumps ( gelf_dict , separators = ',:' , default = BaseGELFHandler . _object_to_json ) return packed . encode ( 'utf-8' )
Convert a given gelf_dict to a JSON - encoded string thus creating an uncompressed GELF log ready for consumption by Graylog .
19,870
def _sanitize_to_unicode ( obj ) : if isinstance ( obj , dict ) : return dict ( ( BaseGELFHandler . _sanitize_to_unicode ( k ) , BaseGELFHandler . _sanitize_to_unicode ( v ) ) for k , v in obj . items ( ) ) if isinstance ( obj , ( list , tuple ) ) : return obj . __class__ ( [ BaseGELFHandler . _sanitize_to_unicode ( i ...
Convert all strings records of the object to unicode
19,871
def _object_to_json ( obj ) : if isinstance ( obj , datetime . datetime ) : return obj . isoformat ( ) return repr ( obj )
Convert objects that cannot be natively serialized into JSON into their string representation
19,872
def makeSocket ( self , timeout = 1 ) : plain_socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) if hasattr ( plain_socket , 'settimeout' ) : plain_socket . settimeout ( timeout ) wrapped_socket = ssl . wrap_socket ( plain_socket , ca_certs = self . ca_certs , cert_reqs = self . reqs , keyfile = self ...
Override SocketHandler . makeSocket to allow creating wrapped TLS sockets
19,873
def to_unicode ( string ) : if isinstance ( string , six . binary_type ) : return string . decode ( 'utf8' ) if isinstance ( string , six . text_type ) : return string if six . PY2 : return unicode ( string ) return str ( string )
Ensure a passed string is unicode
19,874
def to_utf8 ( string ) : if isinstance ( string , six . text_type ) : return string . encode ( 'utf8' ) if isinstance ( string , six . binary_type ) : return string return str ( string )
Encode a string as a UTF8 bytestring . This function could be passed a bytestring or unicode string so must distinguish between the two .
19,875
def dict_to_unicode ( raw_dict ) : decoded = { } for key , value in raw_dict . items ( ) : decoded [ to_unicode ( key ) ] = map ( to_unicode , value ) return decoded
Ensure all keys and values in a dict are unicode .
19,876
def unicode_urlencode ( query , doseq = True ) : pairs = [ ] for key , value in query . items ( ) : if isinstance ( value , list ) : value = list ( map ( to_utf8 , value ) ) else : value = to_utf8 ( value ) pairs . append ( ( to_utf8 ( key ) , value ) ) encoded_query = dict ( pairs ) xx = urlencode ( encoded_query , do...
Custom wrapper around urlencode to support unicode
19,877
def parse ( url_str ) : url_str = to_unicode ( url_str ) result = urlparse ( url_str ) netloc_parts = result . netloc . rsplit ( '@' , 1 ) if len ( netloc_parts ) == 1 : username = password = None host = netloc_parts [ 0 ] else : user_and_pass = netloc_parts [ 0 ] . split ( ':' ) if len ( user_and_pass ) == 2 : usernam...
Extract all parts from a URL string and return them as a dictionary
19,878
def netloc ( self ) : url = self . _tuple if url . username and url . password : netloc = '%s:%s@%s' % ( url . username , url . password , url . host ) elif url . username and not url . password : netloc = '%s@%s' % ( url . username , url . host ) else : netloc = url . host if url . port : netloc = '%s:%s' % ( netloc ,...
Return the netloc
19,879
def host ( self , value = None ) : if value is not None : return URL . _mutate ( self , host = value ) return self . _tuple . host
Return the host
19,880
def username ( self , value = None ) : if value is not None : return URL . _mutate ( self , username = value ) return unicode_unquote ( self . _tuple . username )
Return or set the username
19,881
def password ( self , value = None ) : if value is not None : return URL . _mutate ( self , password = value ) return unicode_unquote ( self . _tuple . password )
Return or set the password
19,882
def scheme ( self , value = None ) : if value is not None : return URL . _mutate ( self , scheme = value ) return self . _tuple . scheme
Return or set the scheme .
19,883
def path ( self , value = None ) : if value is not None : if not value . startswith ( '/' ) : value = '/' + value encoded_value = unicode_quote ( value ) return URL . _mutate ( self , path = encoded_value ) return self . _tuple . path
Return or set the path
19,884
def query ( self , value = None ) : if value is not None : return URL . _mutate ( self , query = value ) return self . _tuple . query
Return or set the query string
19,885
def port ( self , value = None ) : if value is not None : return URL . _mutate ( self , port = value ) return self . _tuple . port
Return or set the port
19,886
def path_segment ( self , index , value = None , default = None ) : if value is not None : segments = list ( self . path_segments ( ) ) segments [ index ] = unicode_quote_path_segment ( value ) new_path = '/' + '/' . join ( segments ) if self . _tuple . path . endswith ( '/' ) : new_path += '/' return URL . _mutate ( s...
Return the path segment at the given index
19,887
def path_segments ( self , value = None ) : if value is not None : encoded_values = map ( unicode_quote_path_segment , value ) new_path = '/' + '/' . join ( encoded_values ) return URL . _mutate ( self , path = new_path ) parts = self . _tuple . path . split ( '/' ) segments = parts [ 1 : ] if self . _tuple . path . en...
Return the path segments
19,888
def add_path_segment ( self , value ) : segments = self . path_segments ( ) + ( to_unicode ( value ) , ) return self . path_segments ( segments )
Add a new path segment to the end of the current string
19,889
def query_param ( self , key , value = None , default = None , as_list = False ) : parse_result = self . query_params ( ) if value is not None : if isinstance ( value , ( list , tuple ) ) : value = list ( map ( to_unicode , value ) ) else : value = to_unicode ( value ) parse_result [ to_unicode ( key ) ] = value return...
Return or set a query parameter for the given key
19,890
def append_query_param ( self , key , value ) : values = self . query_param ( key , as_list = True , default = [ ] ) values . append ( value ) return self . query_param ( key , values )
Append a query parameter
19,891
def query_params ( self , value = None ) : if value is not None : return URL . _mutate ( self , query = unicode_urlencode ( value , doseq = True ) ) query = '' if self . _tuple . query is None else self . _tuple . query if not six . PY3 : result = parse_qs ( to_utf8 ( query ) , True ) return dict_to_unicode ( result ) ...
Return or set a dictionary of query params
19,892
def remove_query_param ( self , key , value = None ) : parse_result = self . query_params ( ) if value is not None : index = parse_result [ key ] . index ( value ) del parse_result [ key ] [ index ] else : del parse_result [ key ] return URL . _mutate ( self , query = unicode_urlencode ( parse_result , doseq = True ) )
Remove a query param from a URL
19,893
def expand ( template , variables = None ) : if variables is None : variables = { } return patterns . sub ( functools . partial ( _replace , variables ) , template )
Expand a URL template string using the passed variables
19,894
def _format_pair_no_equals ( explode , separator , escape , key , value ) : if not value : return key return _format_pair ( explode , separator , escape , key , value )
Format a key value pair but don t include the equals sign when there is no value
19,895
def _format_pair_with_equals ( explode , separator , escape , key , value ) : if not value : return key + '=' return _format_pair ( explode , separator , escape , key , value )
Format a key value pair including the equals sign when there is no value
19,896
def _replace ( variables , match ) : expression = match . group ( 1 ) ( prefix_char , separator_char , split_fn , escape_fn , format_fn ) = operator_map . get ( expression [ 0 ] , defaults ) replacements = [ ] for key , modify_fn , explode in split_fn ( expression ) : if key in variables : variable = modify_fn ( variab...
Return the appropriate replacement for match using the passed variables
19,897
def predict ( self , document_path : str , model_name : str , consent_id : str = None ) -> Prediction : content_type = self . _get_content_type ( document_path ) consent_id = consent_id or str ( uuid4 ( ) ) document_id = self . _upload_document ( document_path , content_type , consent_id ) prediction_response = self . ...
Run inference and create prediction on document . This method takes care of creating and uploading a document specified by document_path . as well as running inference using model specified by model_name to create prediction on the document .
19,898
def send_feedback ( self , document_id : str , feedback : List [ Field ] ) -> dict : return self . post_document_id ( document_id , feedback )
Send feedback to the model . This method takes care of sending feedback related to document specified by document_id . Feedback consists of ground truth values for the document specified as a list of Field instances .
19,899
def extra_what ( file , h = None ) : tests = [ ] def test_pdf ( h , f ) : if b'PDF' in h [ 0 : 10 ] : return 'pdf' tests . append ( test_pdf ) f = None try : if h is None : if isinstance ( file , ( str , PathLike ) ) : f = open ( file , 'rb' ) h = f . read ( 32 ) else : location = file . tell ( ) h = file . read ( 32 )...
Code mostly copied from imghdr . what