idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
244,000 | def reset_logger ( name , level = None , handler = None ) : # Make the logger and set its level. if level is None : level = logging . INFO logger = logging . getLogger ( name ) logger . setLevel ( level ) # Make the handler and attach it. handler = handler or logging . StreamHandler ( ) handler . setFormatter ( logging... | Make a standard python logger object with default formatter handler etc . | 139 | 13 |
244,001 | def adapt_logger ( logger ) : if isinstance ( logger , logging . Logger ) : return logger # Use the standard python logger created by these classes. if isinstance ( logger , ( SimpleLogger , NoOpLogger ) ) : return logger . logger # Otherwise, return whatever we were given because we can't adapt. return logger | Adapt our custom logger . BaseLogger object into a standard logging . Logger object . | 72 | 18 |
244,002 | def get_variation_for_experiment ( self , experiment_id ) : return self . experiment_bucket_map . get ( experiment_id , { self . VARIATION_ID_KEY : None } ) . get ( self . VARIATION_ID_KEY ) | Helper method to retrieve variation ID for given experiment . | 61 | 10 |
244,003 | def get_numeric_value ( event_tags , logger = None ) : logger_message_debug = None numeric_metric_value = None if event_tags is None : logger_message_debug = 'Event tags is undefined.' elif not isinstance ( event_tags , dict ) : logger_message_debug = 'Event tags is not a dictionary.' elif NUMERIC_METRIC_TYPE not in ev... | A smart getter of the numeric value from the event tags . | 623 | 13 |
244,004 | def hash ( key , seed = 0x0 ) : key = bytearray ( xencode ( key ) ) def fmix ( h ) : h ^= h >> 16 h = ( h * 0x85ebca6b ) & 0xFFFFFFFF h ^= h >> 13 h = ( h * 0xc2b2ae35 ) & 0xFFFFFFFF h ^= h >> 16 return h length = len ( key ) nblocks = int ( length / 4 ) h1 = seed c1 = 0xcc9e2d51 c2 = 0x1b873593 # body for block_start ... | Implements 32bit murmur3 hash . | 507 | 10 |
244,005 | def hash64 ( key , seed = 0x0 , x64arch = True ) : hash_128 = hash128 ( key , seed , x64arch ) unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF if unsigned_val1 & 0x8000000000000000 == 0 : signed_val1 = unsigned_val1 else : signed_val1 = - ( ( unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF ) + 1 ) unsigned_val2 = ( hash_128 >> 64 ) &... | Implements 64bit murmur3 hash . Returns a tuple . | 182 | 14 |
244,006 | def hash_bytes ( key , seed = 0x0 , x64arch = True ) : hash_128 = hash128 ( key , seed , x64arch ) bytestring = '' for i in xrange ( 0 , 16 , 1 ) : lsbyte = hash_128 & 0xFF bytestring = bytestring + str ( chr ( lsbyte ) ) hash_128 = hash_128 >> 8 return bytestring | Implements 128bit murmur3 hash . Returns a byte string . | 93 | 15 |
244,007 | def _generate_bucket_value ( self , bucketing_id ) : ratio = float ( self . _generate_unsigned_hash_code_32_bit ( bucketing_id ) ) / MAX_HASH_VALUE return math . floor ( ratio * MAX_TRAFFIC_VALUE ) | Helper function to generate bucket value in half - closed interval [ 0 MAX_TRAFFIC_VALUE ) . | 67 | 23 |
244,008 | def find_bucket ( self , bucketing_id , parent_id , traffic_allocations ) : bucketing_key = BUCKETING_ID_TEMPLATE . format ( bucketing_id = bucketing_id , parent_id = parent_id ) bucketing_number = self . _generate_bucket_value ( bucketing_key ) self . config . logger . debug ( 'Assigned bucket %s to user with bucketin... | Determine entity based on bucket value and traffic allocations . | 179 | 12 |
244,009 | def bucket ( self , experiment , user_id , bucketing_id ) : if not experiment : return None # Determine if experiment is in a mutually exclusive group if experiment . groupPolicy in GROUP_POLICIES : group = self . config . get_group ( experiment . groupId ) if not group : return None user_experiment_id = self . find_bu... | For a given experiment and bucketing ID determines variation to be shown to user . | 361 | 16 |
244,010 | def _generate_key_map ( entity_list , key , entity_class ) : key_map = { } for obj in entity_list : key_map [ obj [ key ] ] = entity_class ( * * obj ) return key_map | Helper method to generate map from key to entity object for given list of dicts . | 55 | 17 |
244,011 | def _deserialize_audience ( audience_map ) : for audience in audience_map . values ( ) : condition_structure , condition_list = condition_helper . loads ( audience . conditions ) audience . __dict__ . update ( { 'conditionStructure' : condition_structure , 'conditionList' : condition_list } ) return audience_map | Helper method to de - serialize and populate audience map with the condition list and structure . | 79 | 18 |
244,012 | def get_typecast_value ( self , value , type ) : if type == entities . Variable . Type . BOOLEAN : return value == 'true' elif type == entities . Variable . Type . INTEGER : return int ( value ) elif type == entities . Variable . Type . DOUBLE : return float ( value ) else : return value | Helper method to determine actual value based on type of feature variable . | 77 | 13 |
244,013 | def get_experiment_from_key ( self , experiment_key ) : experiment = self . experiment_key_map . get ( experiment_key ) if experiment : return experiment self . logger . error ( 'Experiment key "%s" is not in datafile.' % experiment_key ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( e... | Get experiment for the provided experiment key . | 100 | 8 |
244,014 | def get_experiment_from_id ( self , experiment_id ) : experiment = self . experiment_id_map . get ( experiment_id ) if experiment : return experiment self . logger . error ( 'Experiment ID "%s" is not in datafile.' % experiment_id ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( enums .... | Get experiment for the provided experiment ID . | 100 | 8 |
244,015 | def get_group ( self , group_id ) : group = self . group_id_map . get ( group_id ) if group : return group self . logger . error ( 'Group ID "%s" is not in datafile.' % group_id ) self . error_handler . handle_error ( exceptions . InvalidGroupException ( enums . Errors . INVALID_GROUP_ID_ERROR ) ) return None | Get group for the provided group ID . | 90 | 8 |
244,016 | def get_audience ( self , audience_id ) : audience = self . audience_id_map . get ( audience_id ) if audience : return audience self . logger . error ( 'Audience ID "%s" is not in datafile.' % audience_id ) self . error_handler . handle_error ( exceptions . InvalidAudienceException ( ( enums . Errors . INVALID_AUDIENCE... | Get audience object for the provided audience ID . | 92 | 9 |
244,017 | def get_variation_from_key ( self , experiment_key , variation_key ) : variation_map = self . variation_key_map . get ( experiment_key ) if variation_map : variation = variation_map . get ( variation_key ) if variation : return variation else : self . logger . error ( 'Variation key "%s" is not in datafile.' % variatio... | Get variation given experiment and variation key . | 184 | 8 |
244,018 | def get_variation_from_id ( self , experiment_key , variation_id ) : variation_map = self . variation_id_map . get ( experiment_key ) if variation_map : variation = variation_map . get ( variation_id ) if variation : return variation else : self . logger . error ( 'Variation ID "%s" is not in datafile.' % variation_id ... | Get variation given experiment and variation ID . | 184 | 8 |
244,019 | def get_event ( self , event_key ) : event = self . event_key_map . get ( event_key ) if event : return event self . logger . error ( 'Event "%s" is not in datafile.' % event_key ) self . error_handler . handle_error ( exceptions . InvalidEventException ( enums . Errors . INVALID_EVENT_KEY_ERROR ) ) return None | Get event for the provided event key . | 90 | 8 |
244,020 | def get_attribute_id ( self , attribute_key ) : attribute = self . attribute_key_map . get ( attribute_key ) has_reserved_prefix = attribute_key . startswith ( RESERVED_ATTRIBUTE_PREFIX ) if attribute : if has_reserved_prefix : self . logger . warning ( ( 'Attribute %s unexpectedly has reserved prefix %s; using attribu... | Get attribute ID for the provided attribute key . | 194 | 9 |
244,021 | def get_feature_from_key ( self , feature_key ) : feature = self . feature_key_map . get ( feature_key ) if feature : return feature self . logger . error ( 'Feature "%s" is not in datafile.' % feature_key ) return None | Get feature for the provided feature key . | 61 | 8 |
244,022 | def get_rollout_from_id ( self , rollout_id ) : layer = self . rollout_id_map . get ( rollout_id ) if layer : return layer self . logger . error ( 'Rollout with ID "%s" is not in datafile.' % rollout_id ) return None | Get rollout for the provided ID . | 65 | 7 |
244,023 | def get_variable_value_for_variation ( self , variable , variation ) : if not variable or not variation : return None if variation . id not in self . variation_variable_usage_map : self . logger . error ( 'Variation with ID "%s" is not in the datafile.' % variation . id ) return None # Get all variable usages for the g... | Get the variable value for the given variation . | 241 | 9 |
244,024 | def get_variable_for_feature ( self , feature_key , variable_key ) : feature = self . feature_key_map . get ( feature_key ) if not feature : self . logger . error ( 'Feature with key "%s" not found in the datafile.' % feature_key ) return None if variable_key not in feature . variables : self . logger . error ( 'Variab... | Get the variable with the given variable key for the given feature . | 115 | 13 |
244,025 | def set_forced_variation ( self , experiment_key , user_id , variation_key ) : experiment = self . get_experiment_from_key ( experiment_key ) if not experiment : # The invalid experiment key will be logged inside this call. return False experiment_id = experiment . id if variation_key is None : if user_id in self . for... | Sets users to a map of experiments to forced variations . | 450 | 12 |
244,026 | def get_forced_variation ( self , experiment_key , user_id ) : if user_id not in self . forced_variation_map : self . logger . debug ( 'User "%s" is not in the forced variation map.' % user_id ) return None experiment = self . get_experiment_from_key ( experiment_key ) if not experiment : # The invalid experiment key w... | Gets the forced variation key for the given user and experiment . | 289 | 13 |
244,027 | def dispatch_event ( event ) : try : if event . http_verb == enums . HTTPVerbs . GET : requests . get ( event . url , params = event . params , timeout = REQUEST_TIMEOUT ) . raise_for_status ( ) elif event . http_verb == enums . HTTPVerbs . POST : requests . post ( event . url , data = json . dumps ( event . params ) ,... | Dispatch the event being represented by the Event object . | 145 | 10 |
244,028 | def _validate_instantiation_options ( self , datafile , skip_json_validation ) : if not skip_json_validation and not validator . is_datafile_valid ( datafile ) : raise exceptions . InvalidInputException ( enums . Errors . INVALID_INPUT_ERROR . format ( 'datafile' ) ) if not validator . is_event_dispatcher_valid ( self ... | Helper method to validate all instantiation parameters . | 229 | 9 |
244,029 | def _validate_user_inputs ( self , attributes = None , event_tags = None ) : if attributes and not validator . are_attributes_valid ( attributes ) : self . logger . error ( 'Provided attributes are in an invalid format.' ) self . error_handler . handle_error ( exceptions . InvalidAttributeException ( enums . Errors . I... | Helper method to validate user inputs . | 172 | 7 |
244,030 | def _send_impression_event ( self , experiment , variation , user_id , attributes ) : impression_event = self . event_builder . create_impression_event ( experiment , variation . id , user_id , attributes ) self . logger . debug ( 'Dispatching impression event to URL %s with params %s.' % ( impression_event . url , imp... | Helper method to send impression event . | 156 | 7 |
244,031 | def _get_feature_variable_for_type ( self , feature_key , variable_key , variable_type , user_id , attributes ) : if not validator . is_non_empty_string ( feature_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'feature_key' ) ) return None if not validator . is_non_empty_string ( variab... | Helper method to determine value for a certain variable attached to a feature flag based on type of variable . | 765 | 20 |
244,032 | def activate ( self , experiment_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'activate' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . forma... | Buckets visitor and sends impression event to Optimizely . | 300 | 13 |
244,033 | def track ( self , event_key , user_id , attributes = None , event_tags = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'track' ) ) return if not validator . is_non_empty_string ( event_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format... | Send conversion event to Optimizely . | 391 | 8 |
244,034 | def get_variation ( self , experiment_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_variation' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERR... | Gets variation where user will be bucketed . | 391 | 10 |
244,035 | def is_feature_enabled ( self , feature_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'is_feature_enabled' ) ) return False if not validator . is_non_empty_string ( feature_key ) : self . logger . error ( enums . Errors . INVALID_INPU... | Returns true if the feature is enabled for the given user . | 502 | 12 |
244,036 | def get_enabled_features ( self , user_id , attributes = None ) : enabled_features = [ ] if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_enabled_features' ) ) return enabled_features if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors ... | Returns the list of features that are enabled for the user . | 185 | 12 |
244,037 | def get_feature_variable_boolean ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . BOOLEAN return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes ) | Returns value for a certain boolean variable attached to a feature flag . | 75 | 13 |
244,038 | def get_feature_variable_double ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . DOUBLE return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes ) | Returns value for a certain double variable attached to a feature flag . | 73 | 13 |
244,039 | def get_feature_variable_integer ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . INTEGER return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes ) | Returns value for a certain integer variable attached to a feature flag . | 73 | 13 |
244,040 | def get_feature_variable_string ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . STRING return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes ) | Returns value for a certain string variable attached to a feature . | 72 | 12 |
244,041 | def set_forced_variation ( self , experiment_key , user_id , variation_key ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'set_forced_variation' ) ) return False if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALI... | Force a user into a variation for a given experiment . | 184 | 11 |
244,042 | def get_forced_variation ( self , experiment_key , user_id ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_forced_variation' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . f... | Gets the forced variation for a given user and experiment . | 194 | 12 |
244,043 | def is_user_in_experiment ( config , experiment , attributes , logger ) : audience_conditions = experiment . getAudienceConditionsOrIds ( ) logger . debug ( audience_logs . EVALUATING_AUDIENCES_COMBINED . format ( experiment . key , json . dumps ( audience_conditions ) ) ) # Return True in case there are no audiences i... | Determine for given experiment if user satisfies the audiences for the experiment . | 445 | 15 |
244,044 | def _get_common_params ( self , user_id , attributes ) : commonParams = { } commonParams [ self . EventParams . PROJECT_ID ] = self . _get_project_id ( ) commonParams [ self . EventParams . ACCOUNT_ID ] = self . _get_account_id ( ) visitor = { } visitor [ self . EventParams . END_USER_ID ] = user_id visitor [ self . Ev... | Get params which are used same in both conversion and impression events . | 313 | 13 |
244,045 | def _get_required_params_for_impression ( self , experiment , variation_id ) : snapshot = { } snapshot [ self . EventParams . DECISIONS ] = [ { self . EventParams . EXPERIMENT_ID : experiment . id , self . EventParams . VARIATION_ID : variation_id , self . EventParams . CAMPAIGN_ID : experiment . layerId } ] snapshot [... | Get parameters that are required for the impression event to register . | 175 | 12 |
244,046 | def _get_required_params_for_conversion ( self , event_key , event_tags ) : snapshot = { } event_dict = { self . EventParams . EVENT_ID : self . config . get_event ( event_key ) . id , self . EventParams . TIME : self . _get_time ( ) , self . EventParams . KEY : event_key , self . EventParams . UUID : str ( uuid . uuid... | Get parameters that are required for the conversion event to register . | 268 | 12 |
244,047 | def create_impression_event ( self , experiment , variation_id , user_id , attributes ) : params = self . _get_common_params ( user_id , attributes ) impression_params = self . _get_required_params_for_impression ( experiment , variation_id ) params [ self . EventParams . USERS ] [ 0 ] [ self . EventParams . SNAPSHOTS ... | Create impression Event to be sent to the logging endpoint . | 127 | 11 |
244,048 | def create_conversion_event ( self , event_key , user_id , attributes , event_tags ) : params = self . _get_common_params ( user_id , attributes ) conversion_params = self . _get_required_params_for_conversion ( event_key , event_tags ) params [ self . EventParams . USERS ] [ 0 ] [ self . EventParams . SNAPSHOTS ] . ap... | Create conversion Event to be sent to the logging endpoint . | 131 | 11 |
244,049 | def _audience_condition_deserializer ( obj_dict ) : return [ obj_dict . get ( 'name' ) , obj_dict . get ( 'value' ) , obj_dict . get ( 'type' ) , obj_dict . get ( 'match' ) ] | Deserializer defining how dict objects need to be decoded for audience conditions . | 62 | 16 |
244,050 | def _get_condition_json ( self , index ) : condition = self . condition_data [ index ] condition_log = { 'name' : condition [ 0 ] , 'value' : condition [ 1 ] , 'type' : condition [ 2 ] , 'match' : condition [ 3 ] } return json . dumps ( condition_log ) | Method to generate json for logging audience condition . | 73 | 9 |
244,051 | def is_value_type_valid_for_exact_conditions ( self , value ) : # No need to check for bool since bool is a subclass of int if isinstance ( value , string_types ) or isinstance ( value , ( numbers . Integral , float ) ) : return True return False | Method to validate if the value is valid for exact match type evaluation . | 66 | 14 |
244,052 | def exists_evaluator ( self , index ) : attr_name = self . condition_data [ index ] [ 0 ] return self . attributes . get ( attr_name ) is not None | Evaluate the given exists match condition for the user attributes . | 43 | 13 |
244,053 | def greater_than_evaluator ( self , index ) : condition_name = self . condition_data [ index ] [ 0 ] condition_value = self . condition_data [ index ] [ 1 ] user_value = self . attributes . get ( condition_name ) if not validator . is_finite_number ( condition_value ) : self . logger . warning ( audience_logs . UNKNOWN... | Evaluate the given greater than match condition for the user attributes . | 243 | 14 |
244,054 | def substring_evaluator ( self , index ) : condition_name = self . condition_data [ index ] [ 0 ] condition_value = self . condition_data [ index ] [ 1 ] user_value = self . attributes . get ( condition_name ) if not isinstance ( condition_value , string_types ) : self . logger . warning ( audience_logs . UNKNOWN_CONDI... | Evaluate the given substring match condition for the given user attributes . | 177 | 15 |
244,055 | def evaluate ( self , index ) : if self . condition_data [ index ] [ 2 ] != self . CUSTOM_ATTRIBUTE_CONDITION_TYPE : self . logger . warning ( audience_logs . UNKNOWN_CONDITION_TYPE . format ( self . _get_condition_json ( index ) ) ) return None condition_match = self . condition_data [ index ] [ 3 ] if condition_match... | Given a custom attribute audience condition and user attributes evaluate the condition against the attributes . | 324 | 16 |
244,056 | def object_hook ( self , object_dict ) : instance = self . decoder ( object_dict ) self . condition_list . append ( instance ) self . index += 1 return self . index | Hook which when passed into a json . JSONDecoder will replace each dict in a json string with its index and convert the dict to an object as defined by the passed in condition_decoder . The newly created condition object is appended to the conditions_list . | 42 | 55 |
244,057 | def _get_bucketing_id ( self , user_id , attributes ) : attributes = attributes or { } bucketing_id = attributes . get ( enums . ControlAttributes . BUCKETING_ID ) if bucketing_id is not None : if isinstance ( bucketing_id , string_types ) : return bucketing_id self . logger . warning ( 'Bucketing ID attribute is not a... | Helper method to determine bucketing ID for the user . | 103 | 11 |
244,058 | def get_forced_variation ( self , experiment , user_id ) : forced_variations = experiment . forcedVariations if forced_variations and user_id in forced_variations : variation_key = forced_variations . get ( user_id ) variation = self . config . get_variation_from_key ( experiment . key , variation_key ) if variation : ... | Determine if a user is forced into a variation for the given experiment and return that variation . | 117 | 20 |
244,059 | def get_stored_variation ( self , experiment , user_profile ) : user_id = user_profile . user_id variation_id = user_profile . get_variation_for_experiment ( experiment . id ) if variation_id : variation = self . config . get_variation_from_id ( experiment . key , variation_id ) if variation : self . logger . info ( 'F... | Determine if the user has a stored variation available for the given experiment and return that . | 129 | 19 |
244,060 | def get_variation ( self , experiment , user_id , attributes , ignore_user_profile = False ) : # Check if experiment is running if not experiment_helper . is_experiment_running ( experiment ) : self . logger . info ( 'Experiment "%s" is not running.' % experiment . key ) return None # Check if the user is forced into a... | Top - level function to help determine variation user should be put in . | 533 | 14 |
244,061 | def get_experiment_in_group ( self , group , bucketing_id ) : experiment_id = self . bucketer . find_bucket ( bucketing_id , group . id , group . trafficAllocation ) if experiment_id : experiment = self . config . get_experiment_from_id ( experiment_id ) if experiment : self . logger . info ( 'User with bucketing ID "%... | Determine which experiment in the group the user is bucketed into . | 158 | 15 |
244,062 | def add_notification_listener ( self , notification_type , notification_callback ) : if notification_type not in self . notifications : self . notifications [ notification_type ] = [ ( self . notification_id , notification_callback ) ] else : if reduce ( lambda a , b : a + 1 , filter ( lambda tup : tup [ 1 ] == notific... | Add a notification callback to the notification center . | 143 | 9 |
244,063 | def remove_notification_listener ( self , notification_id ) : for v in self . notifications . values ( ) : toRemove = list ( filter ( lambda tup : tup [ 0 ] == notification_id , v ) ) if len ( toRemove ) > 0 : v . remove ( toRemove [ 0 ] ) return True return False | Remove a previously added notification callback . | 74 | 7 |
244,064 | def send_notifications ( self , notification_type , * args ) : if notification_type in self . notifications : for notification_id , callback in self . notifications [ notification_type ] : try : callback ( * args ) except : self . logger . exception ( 'Problem calling notify callback!' ) | Fires off the notification for the specific event . Uses var args to pass in a arbitrary list of parameter according to which notification type was fired . | 63 | 29 |
244,065 | def and_evaluator ( conditions , leaf_evaluator ) : saw_null_result = False for condition in conditions : result = evaluate ( condition , leaf_evaluator ) if result is False : return False if result is None : saw_null_result = True return None if saw_null_result else True | Evaluates a list of conditions as if the evaluator had been applied to each entry and the results AND - ed together . | 69 | 27 |
244,066 | def not_evaluator ( conditions , leaf_evaluator ) : if not len ( conditions ) > 0 : return None result = evaluate ( conditions [ 0 ] , leaf_evaluator ) return None if result is None else not result | Evaluates a list of conditions as if the evaluator had been applied to a single entry and NOT was applied to the result . | 51 | 28 |
244,067 | def evaluate ( conditions , leaf_evaluator ) : if isinstance ( conditions , list ) : if conditions [ 0 ] in list ( EVALUATORS_BY_OPERATOR_TYPE . keys ( ) ) : return EVALUATORS_BY_OPERATOR_TYPE [ conditions [ 0 ] ] ( conditions [ 1 : ] , leaf_evaluator ) else : # assume OR when operator is not explicit. return EVALUATOR... | Top level method to evaluate conditions . | 136 | 7 |
244,068 | def data_objet_class ( data_mode = 'value' , time_mode = 'framewise' ) : classes_table = { ( 'value' , 'global' ) : GlobalValueObject , ( 'value' , 'event' ) : EventValueObject , ( 'value' , 'segment' ) : SegmentValueObject , ( 'value' , 'framewise' ) : FrameValueObject , ( 'label' , 'global' ) : GlobalLabelObject , ( ... | Factory function for Analyzer result | 185 | 6 |
244,069 | def JSON_NumpyArrayEncoder ( obj ) : if isinstance ( obj , np . ndarray ) : return { 'numpyArray' : obj . tolist ( ) , 'dtype' : obj . dtype . __str__ ( ) } elif isinstance ( obj , np . generic ) : return np . asscalar ( obj ) else : print type ( obj ) raise TypeError ( repr ( obj ) + " is not JSON serializable" ) | Define Specialize JSON encoder for numpy array | 101 | 11 |
244,070 | def render ( self ) : fig , ax = plt . subplots ( ) self . data_object . _render_plot ( ax ) return fig | Render a matplotlib figure from the analyzer result | 33 | 11 |
244,071 | def new_result ( self , data_mode = 'value' , time_mode = 'framewise' ) : from datetime import datetime result = AnalyzerResult ( data_mode = data_mode , time_mode = time_mode ) # Automatically write known metadata result . id_metadata . date = datetime . now ( ) . replace ( microsecond = 0 ) . isoformat ( ' ' ) result... | Create a new result | 396 | 4 |
244,072 | def downmix_to_mono ( process_func ) : import functools @ functools . wraps ( process_func ) def wrapper ( analyzer , frames , eod ) : # Pre-processing if frames . ndim > 1 : downmix_frames = frames . mean ( axis = - 1 ) else : downmix_frames = frames # Processing process_func ( analyzer , downmix_frames , eod ) return... | Pre - processing decorator that downmixes frames from multi - channel to mono | 99 | 16 |
244,073 | def frames_adapter ( process_func ) : import functools import numpy as np class framesBuffer ( object ) : def __init__ ( self , blocksize , stepsize ) : self . blocksize = blocksize self . stepsize = stepsize self . buffer = None def frames ( self , frames , eod ) : if self . buffer is not None : stack = np . concatena... | Pre - processing decorator that adapt frames to match input_blocksize and input_stepsize of the decorated analyzer | 632 | 24 |
244,074 | def get_uri ( self ) : if self . source_file and os . path . exists ( self . source_file . path ) : return self . source_file . path elif self . source_url : return self . source_url return None | Return the Item source | 54 | 4 |
244,075 | def get_audio_duration ( self ) : decoder = timeside . core . get_processor ( 'file_decoder' ) ( uri = self . get_uri ( ) ) return decoder . uri_total_duration | Return item audio duration | 51 | 4 |
244,076 | def get_results_path ( self ) : result_path = os . path . join ( RESULTS_ROOT , self . uuid ) if not os . path . exists ( result_path ) : os . makedirs ( result_path ) return result_path | Return Item result path | 58 | 4 |
244,077 | def get_uri ( source ) : import gst src_info = source_info ( source ) if src_info [ 'is_file' ] : # Is this a file? return get_uri ( src_info [ 'uri' ] ) elif gst . uri_is_valid ( source ) : # Is this a valid URI source for Gstreamer uri_protocol = gst . uri_get_protocol ( source ) if gst . uri_protocol_is_supported ( ... | Check a media source as a valid file or uri and return the proper uri | 169 | 17 |
244,078 | def sha1sum_file ( filename ) : import hashlib import io sha1 = hashlib . sha1 ( ) chunk_size = sha1 . block_size * io . DEFAULT_BUFFER_SIZE with open ( filename , 'rb' ) as f : for chunk in iter ( lambda : f . read ( chunk_size ) , b'' ) : sha1 . update ( chunk ) return sha1 . hexdigest ( ) | Return the secure hash digest with sha1 algorithm for a given file | 99 | 14 |
244,079 | def sha1sum_url ( url ) : import hashlib import urllib from contextlib import closing sha1 = hashlib . sha1 ( ) chunk_size = sha1 . block_size * 8192 max_file_size = 10 * 1024 * 1024 # 10Mo limit in case of very large file total_read = 0 with closing ( urllib . urlopen ( url ) ) as url_obj : for chunk in iter ( lambda ... | Return the secure hash digest with sha1 algorithm for a given url | 152 | 14 |
244,080 | def sha1sum_numpy ( np_array ) : import hashlib return hashlib . sha1 ( np_array . view ( np . uint8 ) ) . hexdigest ( ) | Return the secure hash digest with sha1 algorithm for a numpy array | 43 | 15 |
244,081 | def import_module_with_exceptions ( name , package = None ) : from timeside . core import _WITH_AUBIO , _WITH_YAAFE , _WITH_VAMP if name . count ( '.server.' ) : # TODO: # Temporary skip all timeside.server submodules before check dependencies return try : import_module ( name , package ) except VampImportError : # No ... | Wrapper around importlib . import_module to import TimeSide subpackage and ignoring ImportError if Aubio Yaafe and Vamp Host are not available | 241 | 31 |
244,082 | def check_vamp ( ) : try : from timeside . plugins . analyzer . externals import vamp_plugin except VampImportError : warnings . warn ( 'Vamp host is not available' , ImportWarning , stacklevel = 2 ) _WITH_VAMP = False else : _WITH_VAMP = True del vamp_plugin return _WITH_VAMP | Check Vamp host availability | 84 | 5 |
244,083 | def im_watermark ( im , inputtext , font = None , color = None , opacity = .6 , margin = ( 30 , 30 ) ) : if im . mode != "RGBA" : im = im . convert ( "RGBA" ) textlayer = Image . new ( "RGBA" , im . size , ( 0 , 0 , 0 , 0 ) ) textdraw = ImageDraw . Draw ( textlayer ) textsize = textdraw . textsize ( inputtext , font = ... | imprints a PIL image with the indicated text in lower - right corner | 187 | 15 |
244,084 | def nextpow2 ( value ) : if value >= 1 : return 2 ** np . ceil ( np . log2 ( value ) ) . astype ( int ) elif value > 0 : return 1 elif value == 0 : return 0 else : raise ValueError ( 'Value must be positive' ) | Compute the nearest power of two greater or equal to the input value | 65 | 14 |
244,085 | def blocksize ( self , input_totalframes ) : blocksize = input_totalframes if self . pad : mod = input_totalframes % self . buffer_size if mod : blocksize += self . buffer_size - mod return blocksize | Return the total number of frames that this adapter will output according to the input_totalframes argument | 61 | 22 |
244,086 | def append_processor ( self , proc , source_proc = None ) : if source_proc is None and len ( self . processors ) : source_proc = self . processors [ 0 ] if source_proc and not isinstance ( source_proc , Processor ) : raise TypeError ( 'source_proc must be a Processor or None' ) if not isinstance ( proc , Processor ) : ... | Append a new processor to the pipe | 378 | 8 |
244,087 | def simple_host_process ( argslist ) : vamp_host = 'vamp-simple-host' command = [ vamp_host ] command . extend ( argslist ) # try ? stdout = subprocess . check_output ( command , stderr = subprocess . STDOUT ) . splitlines ( ) return stdout | Call vamp - simple - host | 72 | 7 |
244,088 | def set_scale ( self ) : f_min = float ( self . lower_freq ) f_max = float ( self . higher_freq ) y_min = f_min y_max = f_max for y in range ( self . image_height ) : freq = y_min + y / ( self . image_height - 1.0 ) * ( y_max - y_min ) fft_bin = freq / f_max * ( self . fft_size / 2 + 1 ) if fft_bin < self . fft_size / ... | generate the lookup which translates y - coordinate to fft - bin | 167 | 14 |
244,089 | def dict_from_hdf5 ( dict_like , h5group ) : # Read attributes for name , value in h5group . attrs . items ( ) : dict_like [ name ] = value | Load a dictionnary - like object from a h5 file group | 45 | 14 |
244,090 | def get_frames ( self ) : nb_frames = self . input_totalframes // self . output_blocksize if self . input_totalframes % self . output_blocksize == 0 : nb_frames -= 1 # Last frame must send eod=True for index in xrange ( 0 , nb_frames * self . output_blocksize , self . output_blocksize ) : yield ( self . samples [ index... | Define an iterator that will return frames at the given blocksize | 134 | 13 |
244,091 | def implementations ( interface , recurse = True , abstract = False ) : result = [ ] find_implementations ( interface , recurse , abstract , result ) return result | Returns the components implementing interface and if recurse any of the descendants of interface . If abstract is True also return the abstract implementations . | 36 | 26 |
244,092 | def find_implementations ( interface , recurse , abstract , result ) : for item in MetaComponent . implementations : if ( item [ 'interface' ] == interface and ( abstract or not item [ 'abstract' ] ) ) : extend_unique ( result , [ item [ 'class' ] ] ) if recurse : subinterfaces = interface . __subclasses__ ( ) if subin... | Find implementations of an interface or of one of its descendants and extend result with the classes found . | 108 | 19 |
244,093 | def draw_peaks ( self , x , peaks , line_color ) : y1 = self . image_height * 0.5 - peaks [ 0 ] * ( self . image_height - 4 ) * 0.5 y2 = self . image_height * 0.5 - peaks [ 1 ] * ( self . image_height - 4 ) * 0.5 if self . previous_y : self . draw . line ( [ self . previous_x , self . previous_y , x , y1 , x , y2 ] , l... | Draw 2 peaks at x | 184 | 5 |
244,094 | def draw_peaks_inverted ( self , x , peaks , line_color ) : y1 = self . image_height * 0.5 - peaks [ 0 ] * ( self . image_height - 4 ) * 0.5 y2 = self . image_height * 0.5 - peaks [ 1 ] * ( self . image_height - 4 ) * 0.5 if self . previous_y and x < self . image_width - 1 : if y1 < y2 : self . draw . line ( ( x , 0 , ... | Draw 2 inverted peaks at x | 266 | 6 |
244,095 | def draw_anti_aliased_pixels ( self , x , y1 , y2 , color ) : y_max = max ( y1 , y2 ) y_max_int = int ( y_max ) alpha = y_max - y_max_int if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self . image_height : current_pix = self . pixel [ int ( x ) , y_max_int + 1 ] r = int ( ( 1 - alpha ) * current_pix [ 0 ] + alpha ... | vertical anti - aliasing at y1 and y2 | 385 | 12 |
244,096 | def post_process ( self ) : self . image . putdata ( self . pixels ) self . image = self . image . transpose ( Image . ROTATE_90 ) | Apply last 2D transforms | 38 | 5 |
244,097 | def write_metadata ( self ) : import mutagen from mutagen import id3 id3 = id3 . ID3 ( self . filename ) for tag in self . metadata . keys ( ) : value = self . metadata [ tag ] frame = mutagen . id3 . Frames [ tag ] ( 3 , value ) try : id3 . add ( frame ) except : raise IOError ( 'EncoderError: cannot tag "' + tag + '"... | Write all ID3v2 . 4 tags to file from self . metadata | 119 | 15 |
244,098 | def main ( args = sys . argv [ 1 : ] ) : opt = docopt ( main . __doc__ . strip ( ) , args , options_first = True ) config_logging ( opt [ '--verbose' ] ) if opt [ 'check' ] : check_backends ( opt [ '--title' ] ) elif opt [ 'extract' ] : handler = fulltext . get if opt [ '--file' ] : handler = _handle_open for path in o... | Extract text from a file . | 145 | 7 |
244,099 | def is_binary ( f ) : # NOTE: order matters here. We don't bail on Python 2 just yet. Both # codecs.open() and io.open() can open in text mode, both set the encoding # attribute. We must do that check first. # If it has a decoding attribute with a value, it is text mode. if getattr ( f , "encoding" , None ) : return Fa... | Return True if binary mode . | 253 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.