Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function: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, 'cond...
[ " Helper method to de-serialize and populate audience map with the condition list and structure.\n\n Args:\n audience_map: Dict mapping audience ID to audience object.\n\n Returns:\n Dict additionally consisting of condition list and structure on every audience object.\n " ]
Please provide a description of the function: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) ...
[ " Helper method to determine actual value based on type of feature variable.\n\n Args:\n value: Value in string form as it was parsed from datafile.\n type: Type denoting the feature flag type.\n\n Return:\n Value type-casted based on type of feature variable.\n " ]
Please provide a description of the function: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_...
[ " Get experiment for the provided experiment key.\n\n Args:\n experiment_key: Experiment key for which experiment is to be determined.\n\n Returns:\n Experiment corresponding to the provided experiment key.\n " ]
Please provide a description of the function: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(...
[ " Get experiment for the provided experiment ID.\n\n Args:\n experiment_id: Experiment ID for which experiment is to be determined.\n\n Returns:\n Experiment corresponding to the provided experiment ID.\n " ]
Please provide a description of the function: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...
[ " Get group for the provided group ID.\n\n Args:\n group_id: Group ID for which group is to be determined.\n\n Returns:\n Group corresponding to the provided group ID.\n " ]
Please provide a description of the function: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.InvalidAudienceE...
[ " Get audience object for the provided audience ID.\n\n Args:\n audience_id: ID of the audience.\n\n Returns:\n Dict representing the audience.\n " ]
Please provide a description of the function: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: se...
[ " Get variation given experiment and variation key.\n\n Args:\n experiment: Key representing parent experiment of variation.\n variation_key: Key representing the variation.\n\n Returns\n Object representing the variation.\n " ]
Please provide a description of the function: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.l...
[ " Get variation given experiment and variation ID.\n\n Args:\n experiment: Key representing parent experiment of variation.\n variation_id: ID representing the variation.\n\n Returns\n Object representing the variation.\n " ]
Please provide a description of the function: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.INVALI...
[ " Get event for the provided event key.\n\n Args:\n event_key: Event key for which event is to be determined.\n\n Returns:\n Event corresponding to the provided event key.\n " ]
Please provide a description of the function: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 %...
[ " Get attribute ID for the provided attribute key.\n\n Args:\n attribute_key: Attribute key for which attribute is to be fetched.\n\n Returns:\n Attribute ID corresponding to the provided attribute key.\n " ]
Please provide a description of the function: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.\n\n Args:\n feature_key: Feature key for which feature is to be fetched.\n\n Returns:\n Feature corresponding to the provided feature key.\n " ]
Please provide a description of the function: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.\n\n Args:\n rollout_id: ID of the rollout to be fetched.\n\n Returns:\n Rollout corresponding to the provided ID.\n " ]
Please provide a description of the function: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....
[ " Get the variable value for the given variation.\n\n Args:\n variable: The Variable for which we are getting the value.\n variation: The Variation for which we are getting the variable value.\n\n Returns:\n The variable value or None if any of the inputs are invalid.\n " ]
Please provide a description of the function: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...
[ " Get the variable with the given variable key for the given feature.\n\n Args:\n feature_key: The key of the feature for which we are getting the variable.\n variable_key: The key of the variable we are getting.\n\n Returns:\n Variable with the given key in the given variation.\n " ]
Please provide a description of the function: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 = exper...
[ " Sets users to a map of experiments to forced variations.\n\n Args:\n experiment_key: Key for experiment.\n user_id: The user ID.\n variation_key: Key for variation. If None, then clear the existing experiment-to-variation mapping.\n\n Returns:\n A boolean value that indicates...
Please provide a description of the function: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)...
[ " Gets the forced variation key for the given user and experiment.\n\n Args:\n experiment_key: Key for experiment.\n user_id: The user ID.\n\n Returns:\n The variation which the given user and experiment should be forced into.\n " ]
Please provide a description of the function: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( ev...
[ " Dispatch the event being represented by the Event object.\n\n Args:\n event: Object holding information about the request to be dispatched to the Optimizely backend.\n " ]
Please provide a description of the function: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 valid...
[ " Helper method to validate all instantiation parameters.\n\n Args:\n datafile: JSON string representing the project.\n skip_json_validation: Boolean representing whether JSON schema validation needs to be skipped or not.\n\n Raises:\n Exception if provided instantiation options are valid.\n ...
Please provide a description of the function: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.InvalidAtt...
[ " Helper method to validate user inputs.\n\n Args:\n attributes: Dict representing user attributes.\n event_tags: Dict representing metadata associated with an event.\n\n Returns:\n Boolean True if inputs are valid. False otherwise.\n\n " ]
Please provide a description of the function:def _send_impression_event(self, experiment, variation, user_id, attributes): impression_event = self.event_builder.create_impression_event(experiment, variation.id, ...
[ " Helper method to send impression event.\n\n Args:\n experiment: Experiment for which impression event is being sent.\n variation: Variation picked for user for the given experiment.\n user_id: ID for user.\n attributes: Dict representing user attributes and values which need to be recorded....
Please provide a description of the function: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 ...
[ " Helper method to determine value for a certain variable attached to a feature flag based on type of variable.\n\n Args:\n feature_key: Key of the feature whose variable's value is being accessed.\n variable_key: Key of the variable whose value is to be accessed.\n variable_type: Type of variable...
Please provide a description of the function: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....
[ " Buckets visitor and sends impression event to Optimizely.\n\n Args:\n experiment_key: Experiment which needs to be activated.\n user_id: ID for user.\n attributes: Dict representing user attributes and values which need to be recorded.\n\n Returns:\n Variation key representing the variat...
Please provide a description of the function: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.Erro...
[ " Send conversion event to Optimizely.\n\n Args:\n event_key: Event key representing the event which needs to be recorded.\n user_id: ID for user.\n attributes: Dict representing visitor attributes and values which need to be recorded.\n event_tags: Dict representing metadata associated with ...
Please provide a description of the function: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.er...
[ " Gets variation where user will be bucketed.\n\n Args:\n experiment_key: Experiment for which user variation needs to be determined.\n user_id: ID for user.\n attributes: Dict representing user attributes.\n\n Returns:\n Variation key representing the variation the user will be bucketed i...
Please provide a description of the function: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.logg...
[ " Returns true if the feature is enabled for the given user.\n\n Args:\n feature_key: The key of the feature for which we are determining if it is enabled or not for the given user.\n user_id: ID for user.\n attributes: Dict representing user attributes.\n\n Returns:\n True if the feature ...
Please provide a description of the function: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_type...
[ " Returns the list of features that are enabled for the user.\n\n Args:\n user_id: ID for user.\n attributes: Dict representing user attributes.\n\n Returns:\n A list of the keys of the features that are enabled for the user.\n " ]
Please provide a description of the function: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.\n\n Args:\n feature_key: Key of the feature whose variable's value is being accessed.\n variable_key: Key of the variable whose value is to be accessed.\n user_id: ID for user.\n attributes: Dict representing user attr...
Please provide a description of the function: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.\n\n Args:\n feature_key: Key of the feature whose variable's value is being accessed.\n variable_key: Key of the variable whose value is to be accessed.\n user_id: ID for user.\n attributes: Dict representing user attri...
Please provide a description of the function: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.\n\n Args:\n feature_key: Key of the feature whose variable's value is being accessed.\n variable_key: Key of the variable whose value is to be accessed.\n user_id: ID for user.\n attributes: Dict representing user attr...
Please provide a description of the function: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.\n\n Args:\n feature_key: Key of the feature whose variable's value is being accessed.\n variable_key: Key of the variable whose value is to be accessed.\n user_id: ID for user.\n attributes: Dict representing user attributes...
Please provide a description of the function: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): s...
[ " Force a user into a variation for a given experiment.\n\n Args:\n experiment_key: A string key identifying the experiment.\n user_id: The user ID.\n variation_key: A string variation key that specifies the variation which the user.\n will be forced into. If null, then clear the existing experim...
Please provide a description of the function: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...
[ " Gets the forced variation for a given user and experiment.\n\n Args:\n experiment_key: A string key identifying the experiment.\n user_id: The user ID.\n\n Returns:\n The forced variation key. None if no forced variation key.\n " ]
Please provide a description of the function: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...
[ " Determine for given experiment if user satisfies the audiences for the experiment.\n\n Args:\n config: project_config.ProjectConfig object representing the project.\n experiment: Object representing the experiment.\n attributes: Dict representing user attributes which will be used in determining\n ...
Please provide a description of the function: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_USE...
[ " Get params which are used same in both conversion and impression events.\n\n Args:\n user_id: ID for user.\n attributes: Dict representing user attributes and values which need to be recorded.\n\n Returns:\n Dict consisting of parameters common to both impression and conversion events.\n " ...
Please provide a description of the function:def _get_attributes(self, attributes): params = [] if isinstance(attributes, dict): for attribute_key in attributes.keys(): attribute_value = attributes.get(attribute_key) # Omit attribute values that are not supported by the log endpoint...
[ " Get attribute(s) information.\n\n Args:\n attributes: Dict representing user attributes and values which need to be recorded.\n\n Returns:\n List consisting of valid attributes for the user. Empty otherwise.\n " ]
Please provide a description of the function: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.CAMPA...
[ " Get parameters that are required for the impression event to register.\n\n Args:\n experiment: Experiment for which impression needs to be recorded.\n variation_id: ID for variation which would be presented to user.\n\n Returns:\n Dict consisting of decisions and events info for impression ev...
Please provide a description of the function: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, ...
[ " Get parameters that are required for the conversion event to register.\n\n Args:\n event_key: Key representing the event which needs to be recorded.\n event_tags: Dict representing metadata associated with the event.\n\n Returns:\n Dict consisting of the decisions and events info for conversi...
Please provide a description of the function: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]...
[ " Create impression Event to be sent to the logging endpoint.\n\n Args:\n experiment: Experiment for which impression needs to be recorded.\n variation_id: ID for variation which would be presented to user.\n user_id: ID for user.\n attributes: Dict representing user attributes and values whi...
Please provide a description of the function: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....
[ " Create conversion Event to be sent to the logging endpoint.\n\n Args:\n event_key: Key representing the event which needs to be recorded.\n user_id: ID for user.\n attributes: Dict representing user attributes and values.\n event_tags: Dict representing metadata associated with the event.\n...
Please provide a description of the function: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.\n\n Args:\n obj_dict: Dict representing one audience condition.\n\n Returns:\n List consisting of condition key with corresponding value, type and match.\n " ]
Please provide a description of the function:def loads(conditions_string): decoder = ConditionDecoder(_audience_condition_deserializer) # Create a custom JSONDecoder using the ConditionDecoder's object_hook method # to create the condition_structure as well as populate the condition_list json_decoder = json...
[ " Deserializes the conditions property into its corresponding\n components: the condition_structure and the condition_list.\n\n Args:\n conditions_string: String defining valid and/or conditions.\n\n Returns:\n A tuple of (condition_structure, condition_list).\n condition_structure: nested list of opera...
Please provide a description of the function: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.\n\n Args:\n index: Index of the condition.\n\n Returns:\n String: Audience condition JSON.\n " ]
Please provide a description of the function: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.\n\n Args:\n value: Value to validate.\n\n Returns:\n Boolean: True if value is a string, boolean, or number. Otherwise False.\n " ]
Please provide a description of the function: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.\n\n Args:\n index: Index of the condition to be evaluated.\n\n Returns:\n Boolean: True if the user attributes have a non-null value for the given condition,\n otherwise False.\n " ]
Please provide a description of the function: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.logge...
[ " Evaluate the given greater than match condition for the user attributes.\n\n Args:\n index: Index of the condition to be evaluated.\n\n Returns:\n Boolean:\n - True if the user attribute value is greater than the condition value.\n - False if the user attribute value is l...
Please provide a description of the function: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.war...
[ " Evaluate the given substring match condition for the given user attributes.\n\n Args:\n index: Index of the condition to be evaluated.\n\n Returns:\n Boolean:\n - True if the condition value is a substring of the user attribute value.\n - False if the condition value is not a substri...
Please provide a description of the function: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...
[ " Given a custom attribute audience condition and user attributes, evaluate the\n condition against the attributes.\n\n Args:\n index: Index of the condition to be evaluated.\n\n Returns:\n Boolean:\n - True if the user attributes match the given condition.\n - False if the user...
Please provide a description of the function: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\n in a json string with its index and convert the dict to an object as defined\n by the passed in condition_decoder. The newly created condition object is\n appended to the conditions_list.\n\n Args:\n object_dict: Dict represe...
Please provide a description of the function: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 ...
[ " Helper method to determine bucketing ID for the user.\n\n Args:\n user_id: ID for user.\n attributes: Dict representing user attributes. May consist of bucketing ID to be used.\n\n Returns:\n String representing bucketing ID if it is a String type in attributes else return user ID.\n " ]
Please provide a description of the function: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...
[ " Determine if a user is forced into a variation for the given experiment and return that variation.\n\n Args:\n experiment: Object representing the experiment for which user is to be bucketed.\n user_id: ID for the user.\n\n Returns:\n Variation in which the user with ID user_id is forced into...
Please provide a description of the function: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_...
[ " Determine if the user has a stored variation available for the given experiment and return that.\n\n Args:\n experiment: Object representing the experiment for which user is to be bucketed.\n user_profile: UserProfile object representing the user's profile.\n\n Returns:\n Variation if availab...
Please provide a description of the function: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) re...
[ " Top-level function to help determine variation user should be put in.\n\n First, check if experiment is running.\n Second, check if user is forced in a variation.\n Third, check if there is a stored decision for the user and return the corresponding variation.\n Fourth, figure out if user is in the ex...
Please provide a description of the function:def get_variation_for_rollout(self, rollout, user_id, attributes=None): # Go through each experiment in order and try to get the variation for the user if rollout and len(rollout.experiments) > 0: for idx in range(len(rollout.experiments) - 1): ex...
[ " Determine which experiment/variation the user is in for a given rollout.\n Returns the variation of the first experiment the user qualifies for.\n\n Args:\n rollout: Rollout for which we are getting the variation.\n user_id: ID for user.\n attributes: Dict representing user attributes.\n\n ...
Please provide a description of the function: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: ...
[ " Determine which experiment in the group the user is bucketed into.\n\n Args:\n group: The group to bucket the user into.\n bucketing_id: ID to be used for bucketing the user.\n\n Returns:\n Experiment if the user is bucketed into an experiment in the specified group. None otherwise.\n " ]
Please provide a description of the function:def get_variation_for_feature(self, feature, user_id, attributes=None): experiment = None variation = None bucketing_id = self._get_bucketing_id(user_id, attributes) # First check if the feature is in a mutex group if feature.groupId: group =...
[ " Returns the experiment/variation the user is bucketed in for the given feature.\n\n Args:\n feature: Feature for which we are determining if it is enabled or not for the given user.\n user_id: ID for user.\n attributes: Dict representing user attributes.\n\n Returns:\n Decision namedtupl...
Please provide a description of the function: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...
[ " Add a notification callback to the notification center.\n\n Args:\n notification_type: A string representing the notification type from .helpers.enums.NotificationTypes\n notification_callback: closure of function to call when event is triggered.\n\n Returns:\n Integer notification id used to...
Please provide a description of the function: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.\n\n Args:\n notification_id: The numeric id passed back from add_notification_listener\n\n Returns:\n The function returns boolean true if found and removed, false otherwise.\n " ]
Please provide a description of the function: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(...
[ " Fires off the notification for the specific event. Uses var args to pass in a\n arbitrary list of parameter according to which notification type was fired.\n\n Args:\n notification_type: Type of notification to fire (String from .helpers.enums.NotificationTypes)\n args: variable list of argum...
Please provide a description of the function: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_n...
[ " Evaluates a list of conditions as if the evaluator had been applied\n to each entry and the results AND-ed together.\n\n Args:\n conditions: List of conditions ex: [operand_1, operand_2].\n leaf_evaluator: Function which will be called to evaluate leaf condition values.\n\n Returns:\n Boolean:\n ...
Please provide a description of the function: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\n to a single entry and NOT was applied to the result.\n\n Args:\n conditions: List of conditions ex: [operand_1, operand_2].\n leaf_evaluator: Function which will be called to evaluate leaf condition values.\n\n Returns:\n Boolean:\n...
Please provide a description of the function: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 operato...
[ " Top level method to evaluate conditions.\n\n Args:\n conditions: Nested array of and/or conditions, or a single leaf condition value of any type.\n Example: ['and', '0', ['or', '1', '2']]\n leaf_evaluator: Function which will be called to evaluate leaf condition values.\n\n Returns:\n Bo...
Please provide a description of the function:def data_objet_class(data_mode='value', time_mode='framewise'): classes_table = {('value', 'global'): GlobalValueObject, ('value', 'event'): EventValueObject, ('value', 'segment'): SegmentValueObject, ('...
[ "\n Factory function for Analyzer result\n " ]
Please provide a description of the function:def JSON_NumpyArrayEncoder(obj): '''Define Specialize JSON encoder for numpy array''' if isinstance(obj, np.ndarray): return {'numpyArray': obj.tolist(), 'dtype': obj.dtype.__str__()} elif isinstance(obj, np.generic): return np.ass...
[]
Please provide a description of the function:def to_hdf5(self, h5group): # Write attributes name = 'label_type' if self.__getattribute__(name) is not None: h5group.attrs[name] = self.__getattribute__(name) for name in ['label', 'description']: subgroup =...
[ "\n Save a dictionnary-like object inside a h5 file group\n " ]
Please provide a description of the function:def render(self): '''Render a matplotlib figure from the analyzer result Return the figure, use fig.show() to display if neeeded ''' fig, ax = plt.subplots() self.data_object._render_plot(ax) return fig
[]
Please provide a description of the function:def new_result(self, data_mode='value', time_mode='framewise'): ''' Create a new result Attributes ---------- data_object : MetadataObject id_metadata : MetadataObject audio_metadata : MetadataObject frame_meta...
[]
Please provide a description of the function:def downmix_to_mono(process_func): ''' Pre-processing decorator that downmixes frames from multi-channel to mono Downmix is achieved by averaging all channels >>> from timeside.core.preprocessors import downmix_to_mono >>> @downmix_to_mono ... def p...
[]
Please provide a description of the function:def frames_adapter(process_func): ''' Pre-processing decorator that adapt frames to match input_blocksize and input_stepsize of the decorated analyzer >>> from timeside.core.preprocessors import frames_adapter >>> @frames_adapter ... def process(anal...
[]
Please provide a description of the function: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" ]
Please provide a description of the function:def get_audio_duration(self): decoder = timeside.core.get_processor('file_decoder')( uri=self.get_uri()) return decoder.uri_total_duration
[ "\n Return item audio duration\n " ]
Please provide a description of the function: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
[ "\n Return Item result path\n " ]
Please provide a description of the function:def numpy_array_to_gst_buffer(frames, chunk_size, num_samples, sample_rate): from gst import Buffer buf = Buffer(getbuffer(frames.astype("float32"))) # Set its timestamp and duration buf.timestamp = gst.util_uint64_scale(num_samples, gst.SECOND, sample_r...
[ " gstreamer buffer to numpy array conversion " ]
Please provide a description of the function:def gst_buffer_to_numpy_array(buf, chan): samples = frombuffer(buf.data, dtype='float32').reshape((-1, chan)) return samples
[ " gstreamer buffer to numpy array conversion " ]
Please provide a description of the function: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.ur...
[ "\n Check a media source as a valid file or uri and return the proper uri\n " ]
Please provide a description of the function:def sha1sum_file(filename): ''' Return the secure hash digest with sha1 algorithm for a given file >>> from timeside.core.tools.test_samples import samples >>> wav_file = samples["C4_scale.wav"] >>> print sha1sum_file(wav_file) a598e78d0b5c90da54a77e...
[]
Please provide a description of the function:def sha1sum_url(url): '''Return the secure hash digest with sha1 algorithm for a given url >>> url = "https://github.com/yomguy/timeside-samples/raw/master/samples/guitar.wav" >>> print sha1sum_url(url) 08301c3f9a8d60926f31e253825cc74263e52ad1 ''' i...
[]
Please provide a description of the function:def sha1sum_numpy(np_array): ''' Return the secure hash digest with sha1 algorithm for a numpy array ''' import hashlib return hashlib.sha1(np_array.view(np.uint8)).hexdigest()
[]
Please provide a description of the function: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 ...
[ "Wrapper around importlib.import_module to import TimeSide subpackage\n and ignoring ImportError if Aubio, Yaafe and Vamp Host are not available" ]
Please provide a description of the function:def check_aubio(): "Check Aubio availability" try: import aubio except ImportError: warnings.warn('Aubio librairy is not available', ImportWarning, stacklevel=2) _WITH_AUBIO = False else: _WITH_AUBIO = Tru...
[]
Please provide a description of the function:def check_yaafe(): "Check Aubio availability" try: import yaafelib except ImportError: warnings.warn('Yaafe librairy is not available', ImportWarning, stacklevel=2) _WITH_YAAFE = False else: _WITH_YAAFE = ...
[]
Please provide a description of the function:def check_vamp(): "Check Vamp host availability" try: from timeside.plugins.analyzer.externals import vamp_plugin except VampImportError: warnings.warn('Vamp host is not available', ImportWarning, stacklevel=2) _WITH...
[]
Please provide a description of the function:def interpolate_colors(colors, flat=False, num_colors=256): palette = [] for i in range(num_colors): index = (i * (len(colors) - 1)) / (num_colors - 1.0) index_int = int(index) alpha = index - float(index_int) if alpha > 0: ...
[ " Given a list of colors, create a larger list of colors interpolating\n the first one. If flatten is True a list of numers will be returned. If\n False, a list of (r,g,b) tuples. num_colors is the number of colors wanted\n in the final list " ]
Please provide a description of the function:def downsample(vector, factor): if (len(vector) % factor): print "Length of 'vector' is not divisible by 'factor'=%d!" % factor return 0 vector.shape = (len(vector) / factor, factor) return numpy.mean(vector, axis=1)
[ "\n downsample(vector, factor):\n Downsample (by averaging) a vector by an integer factor.\n " ]
Please provide a description of the function:def smooth(x, window_len=10, window='hanning'): # TODO: the window parameter could be the window itself if an array # instead of a string if x.ndim != 1: raise ValueError("smooth only accepts 1 dimension arrays.") if x.size < window_len: ...
[ "\n Smooth the data using a window with requested size.\n\n This method is based on the convolution of a scaled window with the signal.\n The signal is prepared by introducing reflected copies of the signal\n (with the window size) in both ends so that transient parts are minimized\n in the begining ...
Please provide a description of the function: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.texts...
[ "imprints a PIL image with the indicated text in lower-right corner" ]
Please provide a description of the function:def peaks(samples): max_index = numpy.argmax(samples) max_value = samples[max_index] min_index = numpy.argmin(samples) min_value = samples[min_index] if min_index < max_index: return (min_value, max_value) else: return (max_valu...
[ " Find the minimum and maximum peak of the samples.\n Returns that pair in the order they were found.\n So if min was found first, it returns (min, max) else the other way around. " ]
Please provide a description of the function: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" ]
Please provide a description of the function:def get_dependencies(env_yml_file): import yaml with open_here(env_yml_file) as f: environment = yaml.load(f) conda_dependencies = [] package_map = { 'pytables': 'tables', # insert 'tables' instead of 'pytables' 'yaafe': '', ...
[ "\n Read the dependencies from a Conda environment file in YAML\n and return a list of such dependencies (from conda and pip list)\n Be sure to match packages specification for each of:\n - Conda : http://conda.pydata.org/docs/spec.html#build-version-spec\n - Pip & Setuptool :\n - http://python...
Please provide a description of the function: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\n according to the input_totalframes argument" ]
Please provide a description of the function:def process(self, frames, eod): src_index = 0 remaining = len(frames) while remaining: space = self.buffer_size - self.len copylen = remaining < space and remaining or space src = frames[src_index:src_inde...
[ "Returns an iterator over tuples of the form (buffer, eod)\n where buffer is a fixed-sized block of data, and eod indicates whether\n this is the last block.\n In case padding is deactivated the last block may be smaller than\n the buffer size.\n " ]
Please provide a description of the function:def append_processor(self, proc, source_proc=None): "Append a new processor to the pipe" if source_proc is None and len(self.processors): source_proc = self.processors[0] if source_proc and not isinstance(source_proc, Processor): ...
[]
Please provide a description of the function:def run(self, channels=None, samplerate=None, blocksize=None): source = self.processors[0] items = self.processors[1:] # Check if any processor in items need to force the samplerate force_samplerate = set([item.force_samplerate for ...
[ "Setup/reset all processors in cascade" ]
Please provide a description of the function: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() retur...
[ "Call vamp-simple-host" ]
Please provide a description of the function: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) ...
[ "generate the lookup which translates y-coordinate to fft-bin" ]
Please provide a description of the function:def dict_to_hdf5(dict_like, h5group): # Write attributes for key, value in dict_like.items(): if value is not None: h5group.attrs[str(key)] = value
[ "\n Save a dictionnary-like object inside a h5 file group\n " ]
Please provide a description of the function:def dict_from_hdf5(dict_like, h5group): # Read attributes for name, value in h5group.attrs.items(): dict_like[name] = value
[ "\n Load a dictionnary-like object from a h5 file group\n " ]
Please provide a description of the function:def get_frames(self): "Define an iterator that will return frames at the given blocksize" nb_frames = self.input_totalframes // self.output_blocksize if self.input_totalframes % self.output_blocksize == 0: nb_frames -= 1 # Last frame mus...
[]
Please provide a description of the function:def validate_parameters(cls, parameters, schema=None): if schema is None: schema = cls.get_parameters_schema() jsonschema.validate(parameters, schema)
[ "Validate parameters format against schema specification\n Raises:\n - ValidationError if the instance is invalid\n - SchemaError if the schema itself is invalid\n " ]
Please provide a description of the function: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\n the descendants of interface. If abstract is True, also return the\n abstract implementations." ]
Please provide a description of the function:def extend_unique(list1, list2): for item in list2: if item not in list1: list1.append(item)
[ "Extend list1 with list2 as list.extend(), but doesn't append duplicates\n to list1" ]