docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Adapt our custom logger.BaseLogger object into a standard logging.Logger object. Adaptations are: - NoOpLogger turns into a logger with a single NullHandler. - SimpleLogger turns into a logger with a StreamHandler and level. Args: logger: Possibly a logger.BaseLogger, or a standard python logging.Logg...
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
468,087
Helper method to retrieve variation ID for given experiment. Args: experiment_id: ID for experiment for which variation needs to be looked up for. Returns: Variation ID corresponding to the experiment. None if no decision available.
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)
468,092
Helper method to save new experiment/variation as part of the user's profile. Args: experiment_id: ID for experiment for which the decision is to be stored. variation_id: ID for variation that the user saw.
def save_variation_for_experiment(self, experiment_id, variation_id): self.experiment_bucket_map.update({ experiment_id: { self.VARIATION_ID_KEY: variation_id } })
468,093
Helper function to generate bucket value in half-closed interval [0, MAX_TRAFFIC_VALUE). Args: bucketing_id: ID for bucketing. Returns: Bucket value corresponding to the provided bucketing ID.
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)
468,100
Determine entity based on bucket value and traffic allocations. Args: bucketing_id: ID to be used for bucketing the user. parent_id: ID representing group or experiment. traffic_allocations: Traffic allocations representing traffic allotted to experiments or variations. Returns: Entity...
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 bucketing ID "%s".' ...
468,101
For a given experiment and bucketing ID determines variation to be shown to user. Args: experiment: Object representing the experiment for which user is to be bucketed. user_id: ID for user. bucketing_id: ID to be used for bucketing the user. Returns: Variation in which user with ID us...
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 use...
468,102
ProjectConfig init method to load and set project config data. Args: datafile: JSON string representing the project. logger: Provides a log message to send log messages to. error_handler: Provides a handle_error method to handle exceptions.
def __init__(self, datafile, logger, error_handler): config = json.loads(datafile) self.logger = logger self.error_handler = error_handler self.version = config.get('version') if self.version not in SUPPORTED_VERSIONS: raise exceptions.UnsupportedDatafileVersionException( enums.E...
468,103
Helper method to generate map from key to entity object for given list of dicts. Args: entity_list: List consisting of dict. key: Key in each dict which will be key in the map. entity_class: Class representing the entity. Returns: Map mapping key to entity object.
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
468,104
Helper method to de-serialize and populate audience map with the condition list and structure. Args: audience_map: Dict mapping audience ID to audience object. Returns: Dict additionally consisting of condition list and structure on every audience object.
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 }) retu...
468,105
Helper method to determine actual value based on type of feature variable. Args: value: Value in string form as it was parsed from datafile. type: Type denoting the feature flag type. Return: Value type-casted based on type of feature variable.
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
468,106
Get experiment for the provided experiment key. Args: experiment_key: Experiment key for which experiment is to be determined. Returns: Experiment corresponding to the provided experiment key.
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...
468,107
Get experiment for the provided experiment ID. Args: experiment_id: Experiment ID for which experiment is to be determined. Returns: Experiment corresponding to the provided experiment ID.
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.E...
468,108
Get group for the provided group ID. Args: group_id: Group ID for which group is to be determined. Returns: Group corresponding to the provided group ID.
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
468,109
Get audience object for the provided audience ID. Args: audience_id: ID of the audience. Returns: Dict representing the audience.
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_ERROR...
468,110
Get variation given experiment and variation key. Args: experiment: Key representing parent experiment of variation. variation_key: Key representing the variation. Returns Object representing the variation.
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...
468,111
Get variation given experiment and variation ID. Args: experiment: Key representing parent experiment of variation. variation_id: ID representing the variation. Returns Object representing the variation.
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 data...
468,112
Get event for the provided event key. Args: event_key: Event key for which event is to be determined. Returns: Event corresponding to the provided event key.
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
468,113
Get attribute ID for the provided attribute key. Args: attribute_key: Attribute key for which attribute is to be fetched. Returns: Attribute ID corresponding to the provided attribute key.
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 ...
468,114
Get feature for the provided feature key. Args: feature_key: Feature key for which feature is to be fetched. Returns: Feature corresponding to the provided feature key.
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
468,115
Get rollout for the provided ID. Args: rollout_id: ID of the rollout to be fetched. Returns: Rollout corresponding to the provided ID.
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
468,116
Get the variable value for the given variation. Args: variable: The Variable for which we are getting the value. variation: The Variation for which we are getting the variable value. Returns: The variable value or None if any of the inputs are invalid.
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...
468,117
Get the variable with the given variable key for the given feature. Args: feature_key: The key of the feature for which we are getting the variable. variable_key: The key of the variable we are getting. Returns: Variable with the given key in the given variation.
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('...
468,118
Sets users to a map of experiments to forced variations. Args: experiment_key: Key for experiment. user_id: The user ID. variation_key: Key for variation. If None, then clear the existing experiment-to-variation mapping. Returns: A boolean value that indicates if the set co...
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: ...
468,119
Gets the forced variation key for the given user and experiment. Args: experiment_key: Key for experiment. user_id: The user ID. Returns: The variation which the given user and experiment should be forced into.
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 e...
468,120
Dispatch the event being represented by the Event object. Args: event: Object holding information about the request to be dispatched to the Optimizely backend.
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), heade...
468,121
Helper method to validate all instantiation parameters. Args: datafile: JSON string representing the project. skip_json_validation: Boolean representing whether JSON schema validation needs to be skipped or not. Raises: Exception if provided instantiation options are valid.
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.event_dis...
468,123
Helper method to validate user inputs. Args: attributes: Dict representing user attributes. event_tags: Dict representing metadata associated with an event. Returns: Boolean True if inputs are valid. False otherwise.
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.INVALID_ATTRIBUT...
468,124
Helper method to send impression event. Args: experiment: Experiment for which impression event is being sent. variation: Variation picked for user for the given experiment. user_id: ID for user. attributes: Dict representing user attributes and values which need to be recorded.
def _send_impression_event(self, experiment, variation, user_id, attributes): impression_event = self.event_builder.create_impression_event(experiment, variation.id, user_id, ...
468,125
Buckets visitor and sends impression event to Optimizely. Args: experiment_key: Experiment which needs to be activated. user_id: ID for user. attributes: Dict representing user attributes and values which need to be recorded. Returns: Variation key representing the variation the user w...
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.format('experiment...
468,127
Send conversion event to Optimizely. Args: event_key: Event key representing the event which needs to be recorded. user_id: ID for user. attributes: Dict representing visitor attributes and values which need to be recorded. event_tags: Dict representing metadata associated with the event.
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('event_key')) ...
468,128
Gets variation where user will be bucketed. Args: experiment_key: Experiment for which user variation needs to be determined. user_id: ID for user. attributes: Dict representing user attributes. Returns: Variation key representing the variation the user will be bucketed in. None ...
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_ERROR.format('...
468,129
Returns true if the feature is enabled for the given user. Args: feature_key: The key of the feature for which we are determining if it is enabled or not for the given user. user_id: ID for user. attributes: Dict representing user attributes. Returns: True if the feature is enabled for...
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_INPUT_ERROR.for...
468,130
Returns the list of features that are enabled for the user. Args: user_id: ID for user. attributes: Dict representing user attributes. Returns: A list of the keys of the features that are enabled for the user.
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.INVA...
468,131
Returns value for a certain boolean variable attached to a feature flag. Args: feature_key: Key of the feature whose variable's value is being accessed. variable_key: Key of the variable whose value is to be accessed. user_id: ID for user. attributes: Dict representing user attributes. ...
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)
468,132
Returns value for a certain double variable attached to a feature flag. Args: feature_key: Key of the feature whose variable's value is being accessed. variable_key: Key of the variable whose value is to be accessed. user_id: ID for user. attributes: Dict representing user attributes. ...
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)
468,133
Returns value for a certain integer variable attached to a feature flag. Args: feature_key: Key of the feature whose variable's value is being accessed. variable_key: Key of the variable whose value is to be accessed. user_id: ID for user. attributes: Dict representing user attributes. ...
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)
468,134
Returns value for a certain string variable attached to a feature. Args: feature_key: Key of the feature whose variable's value is being accessed. variable_key: Key of the variable whose value is to be accessed. user_id: ID for user. attributes: Dict representing user attributes. Retur...
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)
468,135
Force a user into a variation for a given experiment. Args: experiment_key: A string key identifying the experiment. user_id: The user ID. variation_key: A string variation key that specifies the variation which the user. will be forced into. If null, then clear the existing experiment-to-varia...
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.INVALID_INPUT_E...
468,136
Gets the forced variation for a given user and experiment. Args: experiment_key: A string key identifying the experiment. user_id: The user ID. Returns: The forced variation key. None if no forced variation key.
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.format('exp...
468,137
Get params which are used same in both conversion and impression events. Args: user_id: ID for user. attributes: Dict representing user attributes and values which need to be recorded. Returns: Dict consisting of parameters common to both impression and conversion events.
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.EventParams....
468,140
Get attribute(s) information. Args: attributes: Dict representing user attributes and values which need to be recorded. Returns: List consisting of valid attributes for the user. Empty otherwise.
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. if validator.is_attribute_valid(att...
468,141
Get parameters that are required for the impression event to register. Args: experiment: Experiment for which impression needs to be recorded. variation_id: ID for variation which would be presented to user. Returns: Dict consisting of decisions and events info for impression event.
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 }] snapsh...
468,142
Get parameters that are required for the conversion event to register. Args: event_key: Key representing the event which needs to be recorded. event_tags: Dict representing metadata associated with the event. Returns: Dict consisting of the decisions and events info for conversion event.
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.uuid4()) ...
468,143
Create impression Event to be sent to the logging endpoint. Args: experiment: Experiment for which impression needs to be recorded. variation_id: ID for variation which would be presented to user. user_id: ID for user. attributes: Dict representing user attributes and values which need to b...
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].append(impressio...
468,144
Create conversion Event to be sent to the logging endpoint. Args: event_key: Key representing the event which needs to be recorded. user_id: ID for user. attributes: Dict representing user attributes and values. event_tags: Dict representing metadata associated with the event. Returns:...
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].append(conversion_para...
468,145
Deserializer defining how dict objects need to be decoded for audience conditions. Args: obj_dict: Dict representing one audience condition. Returns: List consisting of condition key with corresponding value, type and match.
def _audience_condition_deserializer(obj_dict): return [ obj_dict.get('name'), obj_dict.get('value'), obj_dict.get('type'), obj_dict.get('match') ]
468,154
Deserializes the conditions property into its corresponding components: the condition_structure and the condition_list. Args: conditions_string: String defining valid and/or conditions. Returns: A tuple of (condition_structure, condition_list). condition_structure: nested list of operators and place...
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.JSONDecoder(object_hook=decoder.object_hook)...
468,155
Method to generate json for logging audience condition. Args: index: Index of the condition. Returns: String: Audience condition JSON.
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)
468,157
Method to validate if the value is valid for exact match type evaluation. Args: value: Value to validate. Returns: Boolean: True if value is a string, boolean, or number. Otherwise False.
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
468,158
Evaluate the given exists match condition for the user attributes. Args: index: Index of the condition to be evaluated. Returns: Boolean: True if the user attributes have a non-null value for the given condition, otherwise False.
def exists_evaluator(self, index): attr_name = self.condition_data[index][0] return self.attributes.get(attr_name) is not None
468,160
Evaluate the given greater than match condition for the user attributes. Args: index: Index of the condition to be evaluated. Returns: Boolean: - True if the user attribute value is greater than the condition value. - False if the user attribute value is less than or eq...
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_CONDITION_VAL...
468,161
Evaluate the given substring match condition for the given user attributes. Args: index: Index of the condition to be evaluated. Returns: Boolean: - True if the condition value is a substring of the user attribute value. - False if the condition value is not a substring of the user...
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_CONDITION_VALUE.fo...
468,162
Given a custom attribute audience condition and user attributes, evaluate the condition against the attributes. Args: index: Index of the condition to be evaluated. Returns: Boolean: - True if the user attributes match the given condition. - False if the user attributes don...
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 is None: ...
468,163
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. Args: object_dict: Dict representing an obj...
def object_hook(self, object_dict): instance = self.decoder(object_dict) self.condition_list.append(instance) self.index += 1 return self.index
468,165
Helper method to determine bucketing ID for the user. Args: user_id: ID for user. attributes: Dict representing user attributes. May consist of bucketing ID to be used. Returns: String representing bucketing ID if it is a String type in attributes else return user ID.
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 attrib...
468,167
Determine if a user is forced into a variation for the given experiment and return that variation. Args: experiment: Object representing the experiment for which user is to be bucketed. user_id: ID for the user. Returns: Variation in which the user with ID user_id is forced into. None if no ...
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 vari...
468,168
Determine if the user has a stored variation available for the given experiment and return that. Args: experiment: Object representing the experiment for which user is to be bucketed. user_profile: UserProfile object representing the user's profile. Returns: Variation if available. None othe...
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.i...
468,169
Determine which experiment/variation the user is in for a given rollout. Returns the variation of the first experiment the user qualifies for. Args: rollout: Rollout for which we are getting the variation. user_id: ID for user. attributes: Dict representing user attributes. Returns: ...
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): experiment = self.config.get_experiment_from_ke...
468,171
Determine which experiment in the group the user is bucketed into. Args: group: The group to bucket the user into. bucketing_id: ID to be used for bucketing the user. Returns: Experiment if the user is bucketed into an experiment in the specified group. None otherwise.
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 "%...
468,172
Returns the experiment/variation the user is bucketed in for the given feature. Args: feature: Feature for which we are determining if it is enabled or not for the given user. user_id: ID for user. attributes: Dict representing user attributes. Returns: Decision namedtuple consisting o...
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 = self.config.get_group(feature.groupId) ...
468,173
Add a notification callback to the notification center. Args: notification_type: A string representing the notification type from .helpers.enums.NotificationTypes notification_callback: closure of function to call when event is triggered. Returns: Integer notification id used to remove the n...
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] =...
468,175
Remove a previously added notification callback. Args: notification_id: The numeric id passed back from add_notification_listener Returns: The function returns boolean true if found and removed, false otherwise.
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
468,176
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. Args: notification_type: Type of notification to fire (String from .helpers.enums.NotificationTypes) args: variable list of arguments to the...
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!')
468,177
Evaluates a list of conditions as if the evaluator had been applied to each entry and the results AND-ed together. Args: conditions: List of conditions ex: [operand_1, operand_2]. leaf_evaluator: Function which will be called to evaluate leaf condition values. Returns: Boolean: - True if all o...
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
468,178
Evaluates a list of conditions as if the evaluator had been applied to a single entry and NOT was applied to the result. Args: conditions: List of conditions ex: [operand_1, operand_2]. leaf_evaluator: Function which will be called to evaluate leaf condition values. Returns: Boolean: - True if...
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
468,179
Top level method to evaluate conditions. Args: conditions: Nested array of and/or conditions, or a single leaf condition value of any type. Example: ['and', '0', ['or', '1', '2']] leaf_evaluator: Function which will be called to evaluate leaf condition values. Returns: Boolean: Result ...
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 EVALUATORS_BY...
468,180
Searches for names that match some pattern. Args: term: String used to match names. A name is returned if it matches the whole search term. case_sensitive: Boolean to match case or not, default is False (case insensitive). Return: A Prett...
def search(self, term: str, case_sensitive: bool = False) -> 'PrettyDir': if case_sensitive: return PrettyDir( self.obj, [pattr for pattr in self.pattrs if term in pattr.name] ) else: term = term.lower() return PrettyDir( ...
469,004
Enable hugepages on system. Args: user (str) -- Username to allow access to hugepages to group (str) -- Group name to own hugepages nr_hugepages (int) -- Number of pages to reserve max_map_count (int) -- Number of Virtual Memory Areas a process can own mnt_point (str) -- Directory to mount hug...
def hugepage_support(user, group='hugetlb', nr_hugepages=256, max_map_count=65536, mnt_point='/run/hugepages/kvm', pagesize='2MB', mount=True, set_shmmax=False): group_info = add_group(group) gid = group_info.gr_gid add_user_to_group(user, group) if max_map...
469,574
Merge a list of dictionaries. Args: dicts (list): a list of dictionary objects op (operator): an operator item used to merge the dictionaries. Defaults to :py:func:`operator.add`. Returns: dict: the merged dictionary
def merge_dicts(dicts, op=operator.add): a = None for b in dicts: if a is None: a = b.copy() else: a = dict(a.items() + b.items() + [(k, op(a[k], b[k])) for k in set(b) & set(a)]) return a
470,112
Extract the layer index from a url. Args: url (str): The url to parse. Returns: int: The layer index. Examples: >>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12" >>> arcresthelper.common.getLayerIndex(url) 12
def getLayerIndex(url): urlInfo = None urlSplit = None inx = None try: urlInfo = urlparse.urlparse(url) urlSplit = str(urlInfo.path).split('/') inx = urlSplit[len(urlSplit)-1] if is_number(inx): return int(inx) except: return 0 finally: ...
470,113
Extract the layer name from a url. Args: url (str): The url to parse. Returns: str: The layer name. Examples: >>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12" >>> arcresthelper.common.getLayerIndex(url) 'test'
def getLayerName(url): urlInfo = None urlSplit = None try: urlInfo = urlparse.urlparse(url) urlSplit = str(urlInfo.path).split('/') name = urlSplit[len(urlSplit)-3] return name except: return url finally: urlInfo = None urlSplit = None ...
470,114
Generates a random integer from 0 to `maxrange`, inclusive. Args: maxrange (int): The upper range of integers to randomly choose. Returns: int: The randomly generated integer from :py:func:`random.randint`. Examples: >>> arcresthelper.common.random_int_generator(15) 9
def random_int_generator(maxrange): try: return random.randint(0,maxrange) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "random_int_generator", "line": line, "filename": filename, ...
470,116
Determines if the input is numeric Args: s: The value to check. Returns: bool: ``True`` if the input is numeric, ``False`` otherwise.
def is_number(s): try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False
470,119
Deserializes a JSON configuration file. Args: config_file (str): The path to the JSON file. Returns: dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``.
def init_config_json(config_file): json_data = None try: if os.path.exists(config_file): #Load the config file with open(config_file) as json_file: json_data = json.load(json_file) return unicode_convert(json_data) else: retur...
470,120
Serializes an object to disk. Args: config_file (str): The path on disk to save the file. data (object): The object to serialize.
def write_config_json(config_file, data): outfile = None try: with open(config_file, 'w') as outfile: json.dump(data, outfile) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "init_config_json", ...
470,121
Converts unicode objects to anscii. Args: obj (object): The object to convert. Returns: The object converted to anscii, if possible. For ``dict`` and ``list``, the object type is maintained.
def unicode_convert(obj): try: if isinstance(obj, dict): return {unicode_convert(key): unicode_convert(value) for key, value in obj.items()} elif isinstance(obj, list): return [unicode_convert(element) for element in obj] elif isinstance(obj, str): re...
470,122
Performs a string.replace() on the input object. Args: obj (object): The object to find/replace. It will be cast to ``str``. find (str): The string to search for. replace (str): The string to replace with. Returns: str: The replaced string.
def find_replace_string(obj, find, replace): try: strobj = str(obj) newStr = string.replace(strobj, find, replace) if newStr == strobj: return obj else: return newStr except: line, filename, synerror = trace() raise ArcRestHelperErro...
470,123
Searches an object and performs a find and replace. Args: obj (object): The object to iterate and find/replace. find (str): The string to search for. replace (str): The string to replace with. Returns: object: The object with replaced strings.
def find_replace(obj, find, replace): try: if isinstance(obj, dict): return {find_replace(key,find,replace): find_replace(value,find,replace) for key, value in obj.items()} elif isinstance(obj, list): return [find_replace(element,find,replace) for element in obj] ...
470,124
Creates log file on disk and "Tees" :py:class:`sys.stdout` to console and disk Args: log_file (str): The path on disk to append or create the log file. Returns: file: The opened log file.
def init_log(log_file): #Create the log file log = None try: log = open(log_file, 'a') #Change the output to both the windows and log file #original = sys.stdout sys.stdout = Tee(sys.stdout, log) except: pass return log
470,126
Closes the open file and returns :py:class:`sys.stdout` to the default (i.e., console output). Args: log_file (file): The file object to close.
def close_log(log_file): sys.stdout = sys.__stdout__ if log_file is not None: log_file.close() del log_file
470,127
This operation provides status information about a specific ArcGIS Server federated with Portal for ArcGIS. Parameters: serverId - unique id of the server
def validateAllServers(self): url = self._url + "/servers/validate" params = {"f" : "json"} return self._get(url=url, param_dict=params, proxy_port=self._proxy_port, proxy_url=self._proxy_ur)
470,160
This operation searches groups in the configured enterprise group store. You can narrow down the search using the search filter parameter. Parameters: searchFilter - text value to narrow the search down maxCount - maximum number of records to return
def searchEnterpriseGroups(self, searchFilter="", maxCount=100): params = { "f" : "json", "filter" : searchFilter, "maxCount" : maxCount } url = self._url + "/groups/searchEnterpriseGroups" return self._post(url=url, ...
470,175
This operation allows an administrator to update the idpUsername for an enterprise user in the portal. This is used when migrating from accounts used with web-tier authentication to SAML authentication. Parameters: username - username of the enterprise account idpU...
def updateEnterpriseUser(self, username, idpUsername): params = { "f" : "json", "username" : username, "idpUsername" : idpUsername } url = self._url + "/users/updateEnterpriseUser" return self._post(url=url, param_dic...
470,179
You can use this operation to change which languages will have content displayed in portal search results. Parameters: languages - The JSON object containing all of the possible portal languages and their corresponding status (true or false).
def updateLanguages(self, languages): url = self._url = "/languages/update" params = { "f" : "json", "languages" : languages } return self._post(url=url, param_dict=params, proxy_url=self._proxy_url, ...
470,187
Determines if a folder exists, case insensitively. Args: name (str): The name of the folder to check. folders (list): A list of folder dicts to check against. The dicts must contain the key:value pair ``title``. Returns: bool: ``True`` if the ...
def folderExist(self, name, folders): if name is not None and name != '': folderID = None for folder in folders: if folder['title'].lower() == name.lower(): return True del folders return folderID else: ...
470,239
Publishes a list of items. Args: items_info (list): A list of JSON configuration items to publish. Returns: list: A list of results from :py:meth:`arcrest.manageorg._content.User.addItem`.
def publishItems(self, items_info): if self.securityhandler is None: print ("Security handler required") return itemInfo = None item_results = None item_info = None admin = None try: admin = arcrest.manageorg.Administration(sec...
470,240
Publishes a list of maps. Args: maps_info (list): A list of JSON configuration maps to publish. Returns: list: A list of results from :py:meth:`arcrest.manageorg._content.UserItem.updateItem`.
def publishMap(self, maps_info, fsInfo=None, itInfo=None): if self.securityhandler is None: print ("Security handler required") return itemInfo = None itemId = None map_results = None replaceInfo = None replaceItem = None map_info ...
470,242
Publishes a combination of web maps. Args: maps_info (list): A list of JSON configuration combined web maps to publish. Returns: list: A list of results from :py:meth:`arcrest.manageorg._content.UserItem.updateItem`.
def publishCombinedWebMap(self, maps_info, webmaps): if self.securityhandler is None: print ("Security handler required") return admin = None map_results = None map_info = None operationalLayers = None tableLayers = None item = Non...
470,244
Publishes the layers in a MXD to a feauture service. Args: fs_config (list): A list of JSON configuration feature service details to publish. Returns: dict: A dictionary of results objects.
def publishFsFromMXD(self, fs_config): fs = None res = None resItm = None if self.securityhandler is None: print ("Security handler required") return if self.securityhandler.is_portal: url = self.securityhandler.org_url else: ...
470,245
Publishes feature collections to a feature service. Args: configs (list): A list of JSON configuration feature service details to publish. Returns: dict: A dictionary of results objects.
def publishFeatureCollections(self, configs): if self.securityhandler is None: print ("Security handler required") return config = None res = None resItm = None try: res = [] if isinstance(configs, list): fo...
470,246
Publishes apps to AGOL/Portal Args: app_info (list): A list of JSON configuration apps to publish. map_info (list): Defaults to ``None``. fsInfo (list): Defaults to ``None``. Returns: dict: A dictionary of results objects.
def publishApp(self, app_info, map_info=None, fsInfo=None): if self.securityhandler is None: print ("Security handler required") return appDet = None try: app_results = [] if isinstance(app_info, list): for appDet in app_in...
470,249
Updates a feature service. Args: efs_config (list): A list of JSON configuration feature service details to update. Returns: dict: A dictionary of results objects.
def updateFeatureService(self, efs_config): if self.securityhandler is None: print ("Security handler required") return fsRes = None fst = None fURL = None resItm= None try: fsRes = [] fst = featureservicetools.fea...
470,252
Parses a JSON configuration file to stage content. Args: configFiles (list): A list of JSON files on disk containing configuration data for staging content. dateTimeFormat (str): A valid date formatting directive, as understood by :py:meth:`datetime.datet...
def stageContent(self, configFiles, dateTimeFormat=None): results = None groups = None items = None group = None content = None contentInfo = None startTime = None orgTools = None if dateTimeFormat is None: dateTimeFormat = '...
470,278
Parses a JSON configuration file to create roles. Args: configFiles (list): A list of JSON files on disk containing configuration data for creating roles. dateTimeFormat (str): A valid date formatting directive, as understood by :py:meth:`datetime.datetim...
def createRoles(self, configFiles, dateTimeFormat=None): if dateTimeFormat is None: dateTimeFormat = '%Y-%m-%d %H:%M' scriptStartTime = datetime.datetime.now() try: print ("********************Create Roles********************") print ("Script start...
470,279
Parses a JSON configuration file to create groups. Args: configFiles (list): A list of JSON files on disk containing configuration data for creating groups. dateTimeFormat (str): A valid date formatting directive, as understood by :py:meth:`datetime.datet...
def createGroups(self, configFiles, dateTimeFormat=None): groupInfo = None groupFile = None iconPath = None startTime = None thumbnail = None result = None config = None sciptPath = None orgTools = None if dateTimeFormat is None: ...
470,280
Enables Sync capability for an AGOL feature service. Args: url (str): The URL of the feature service. definition (dict): A dictionary containing valid definition values. Defaults to ``None``. Returns: dict: The result from :py:func:`arcrest.hostedservice.service.Admi...
def enableSync(self, url, definition = None): adminFS = AdminFeatureService(url=url, securityHandler=self._securityHandler) cap = str(adminFS.capabilities) existingDef = {} enableResults = 'skipped' if 'Sync' in cap: return "Sync is already enabled" ...
470,429
Obtains a feature service by item ID. Args: itemId (str): The feature service's item ID. returnURLOnly (bool): A boolean value to return the URL of the feature service. Defaults to ``False``. Returns: When ``returnURLOnly`` is ``True``, the URL of the feature service...
def GetFeatureService(self, itemId, returnURLOnly=False): admin = None item = None try: admin = arcrest.manageorg.Administration(securityHandler=self._securityHandler) if self._securityHandler.valid == False: self._valid = self._securityHandler.va...
470,430
Removes users' content and data. Args: users (str): A comma delimited list of user names. Defaults to ``None``. Warning: When ``users`` is not provided (``None``), all users in the organization will have their data deleted!
def removeUserData(self, users=None): admin = None portal = None user = None adminusercontent = None userFolder = None userContent = None userItem = None folderContent = None try: admin = arcrest.manageorg.Administration(secur...
470,473
Removes users' groups. Args: users (str): A comma delimited list of user names. Defaults to ``None``. Warning: When ``users`` is not provided (``None``), all users in the organization will have their groups deleted!
def removeUserGroups(self, users=None): admin = None userCommunity = None portal = None groupAdmin = None user = None userCommData = None group = None try: admin = arcrest.manageorg.Administration(securityHandler=self._securityHandle...
470,474
Gets all the items owned by a group(s). Args: groupName (list): The name of the group(s) from which to get items. Returns: list: A list of items belonging to the group(s). Notes: If you want to get items from a single group, ``groupName`` can be passe...
def getGroupContentItems(self, groupName): admin = None userCommunity = None groupIds = None groupId = None groupContent = None result = None item = None items = [] try: admin = arcrest.manageorg.Administration(securityHandler...
470,743