text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Return a list of objects to delete. <END_TASK> <USER_TASK:> Description: def _return_container_objects(self): """Return a list of objects to delete. The return tuple will indicate if it was a userd efined list of objects as True of False. The list of objects is a list of dictionaries with the key being "container_object". :returns: tuple (``bol``, ``list``) """
container_objects = self.job_args.get('object') if container_objects: return True, [{'container_object': i} for i in container_objects] container_objects = self.job_args.get('objects_file') if container_objects: container_objects = os.path.expanduser(container_objects) if os.path.isfile(container_objects): with open(container_objects) as f: return True, [ {'container_object': i.rstrip('\n')} for i in f.readlines() ] container_objects = self._list_contents() pattern_match = self.job_args.get('pattern_match') if pattern_match: container_objects = self.match_filter( idx_list=container_objects, pattern=pattern_match, dict_type=True, dict_key='name' ) # Reformat list for processing if container_objects and isinstance(container_objects[0], dict): return False, self._return_deque([ {'container_object': i['name']} for i in container_objects ]) else: return False, self._return_deque()
<SYSTEM_TASK:> Returns a deque object full of local file system items. <END_TASK> <USER_TASK:> Description: def _index_fs(self): """Returns a deque object full of local file system items. :returns: ``deque`` """
indexed_objects = self._return_deque() directory = self.job_args.get('directory') if directory: indexed_objects = self._return_deque( deque=indexed_objects, item=self._drectory_local_files( directory=directory ) ) object_names = self.job_args.get('object') if object_names: indexed_objects = self._return_deque( deque=indexed_objects, item=self._named_local_files( object_names=object_names ) ) return indexed_objects
<SYSTEM_TASK:> Return Matched items in indexed files. <END_TASK> <USER_TASK:> Description: def match_filter(self, idx_list, pattern, dict_type=False, dict_key='name'): """Return Matched items in indexed files. :param idx_list: :return list """
if dict_type is False: return self._return_deque([ obj for obj in idx_list if re.search(pattern, obj) ]) elif dict_type is True: return self._return_deque([ obj for obj in idx_list if re.search(pattern, obj.get(dict_key)) ]) else: return self._return_deque()
<SYSTEM_TASK:> Print a horizontal pretty table from data. <END_TASK> <USER_TASK:> Description: def print_horiz_table(self, data): """Print a horizontal pretty table from data."""
# Build list of returned objects return_objects = list() fields = self.job_args.get('fields') if not fields: fields = set() for item_dict in data: for field_item in item_dict.keys(): fields.add(field_item) fields = sorted(fields) for obj in data: item_struct = dict() for item in fields: item_struct[item] = obj.get(item) else: return_objects.append(item_struct) table = prettytable.PrettyTable(fields) for obj in return_objects: table.add_row([obj.get(i) for i in fields]) for tbl in table.align.keys(): table.align[tbl] = 'l' sort_key = self.job_args.get('sort_by') if sort_key: table.sortby = sort_key self.printer(table)
<SYSTEM_TASK:> Print a vertical pretty table from data. <END_TASK> <USER_TASK:> Description: def print_virt_table(self, data): """Print a vertical pretty table from data."""
table = prettytable.PrettyTable() keys = sorted(data.keys()) table.add_column('Keys', keys) table.add_column('Values', [data.get(i) for i in keys]) for tbl in table.align.keys(): table.align[tbl] = 'l' self.printer(table)
<SYSTEM_TASK:> Print Messages and Log it. <END_TASK> <USER_TASK:> Description: def printer(self, message, color_level='info'): """Print Messages and Log it. :param message: item to print to screen """
if self.job_args.get('colorized'): print(cloud_utils.return_colorized(msg=message, color=color_level)) else: print(message)
<SYSTEM_TASK:> Return an imported object. <END_TASK> <USER_TASK:> Description: def _get_method(method): """Return an imported object. :param method: ``str`` DOT notation for import with Colin used to separate the class used for the job. :returns: ``object`` Loaded class object from imported method. """
# Split the class out from the job module = method.split(':') # Set the import module _module_import = module[0] # Set the class name to use class_name = module[-1] # import the module module_import = __import__(_module_import, fromlist=[class_name]) # Return the attributes for the imported module and class return getattr(module_import, class_name)
<SYSTEM_TASK:> The run manager. <END_TASK> <USER_TASK:> Description: def run_manager(self, job_override=None): """The run manager. The run manager is responsible for loading the plugin required based on what the user has inputted using the parsed_command value as found in the job_args dict. If the user provides a *job_override* the method will attempt to import the module and class as provided by the user. Before the method attempts to run any job the run manager will first authenticate to the the cloud provider. :param job_override: ``str`` DOT notation for import with Colin used to separate the class used for the job. """
for arg_name, arg_value in self.job_args.items(): if arg_name.endswith('_headers'): if isinstance(arg_value, list): self.job_args[arg_name] = self._list_headers( headers=arg_value ) elif not arg_name: self.job_args[arg_name] = self._str_headers( header=arg_value ) else: self.job_args[arg_name] = dict() # Set base header for the user-agent self.job_args['base_headers']['User-Agent'] = 'turbolift' LOG.info('Authenticating') indicator_options = {'run': self.job_args.get('run_indicator', True)} with indicator.Spinner(**indicator_options): LOG.debug('Authenticate against the Service API') self.job_args.update(auth.authenticate(job_args=self.job_args)) if job_override: action = self._get_method(method=job_override) else: parsed_command = self.job_args.get('parsed_command') if not parsed_command: raise exceptions.NoCommandProvided( 'Please provide a command. Basic commands are: %s', list(self.job_map.keys()) ) else: action = self._get_method(method=self.job_map[parsed_command]) run = action(job_args=self.job_args) run.start()
<SYSTEM_TASK:> Initialize the weights by calculating the range of the data. <END_TASK> <USER_TASK:> Description: def range_initialization(X, num_weights): """ Initialize the weights by calculating the range of the data. The data range is calculated by reshaping the input matrix to a 2D matrix, and then taking the min and max values over the columns. Parameters ---------- X : numpy array The input data. The data range is calculated over the last axis. num_weights : int The number of weights to initialize. Returns ------- new_weights : numpy array A new version of the weights, initialized to the data range specified by X. """
# Randomly initialize weights to cover the range of each feature. X_ = X.reshape(-1, X.shape[-1]) min_val, max_val = X_.min(0), X_.max(0) data_range = max_val - min_val return data_range * np.random.rand(num_weights, X.shape[-1]) + min_val
<SYSTEM_TASK:> Fit the learner to some data. <END_TASK> <USER_TASK:> Description: def fit(self, X, num_epochs=10, updates_epoch=None, stop_param_updates=dict(), batch_size=1, show_progressbar=False, show_epoch=False, refit=True): """ Fit the learner to some data. Parameters ---------- X : numpy array. The input data. num_epochs : int, optional, default 10 The number of epochs to train for. updates_epoch : int, optional, default 10 The number of updates to perform on the learning rate and neighborhood per epoch. 10 suffices for most problems. stop_param_updates : dict The epoch at which to stop updating each param. This means that the specified parameter will be reduced to 0 at the specified epoch. batch_size : int, optional, default 100 The batch size to use. Warning: batching can change your performance dramatically, depending on the task. show_progressbar : bool, optional, default False Whether to show a progressbar during training. show_epoch : bool, optional, default False Whether to print the epoch number to stdout """
if self.data_dimensionality is None: self.data_dimensionality = X.shape[-1] self.weights = np.zeros((self.num_neurons, self.data_dimensionality)) X = self._check_input(X) if not self.trained or refit: X = self._init_weights(X) else: if self.scaler is not None: self.weights = self.scaler.transform(self.weights) if updates_epoch is None: X_len = X.shape[0] updates_epoch = np.min([50, X_len // batch_size]) constants = self._pre_train(stop_param_updates, num_epochs, updates_epoch) start = time.time() for epoch in tqdm(range(num_epochs), disable=not show_epoch): logger.info("Epoch {0} of {1}".format(epoch+1, num_epochs)) self._epoch(X, epoch, batch_size, updates_epoch, constants, show_progressbar) self.trained = True if self.scaler is not None: self.weights = self.scaler.inverse_transform(self.weights) logger.info("Total train time: {0}".format(time.time() - start))
<SYSTEM_TASK:> Set the weights and normalize data before starting training. <END_TASK> <USER_TASK:> Description: def _init_weights(self, X): """Set the weights and normalize data before starting training."""
X = np.asarray(X, dtype=np.float64) if self.scaler is not None: X = self.scaler.fit_transform(X) if self.initializer is not None: self.weights = self.initializer(X, self.num_neurons) for v in self.params.values(): v['value'] = v['orig'] return X
<SYSTEM_TASK:> Set parameters and constants before training. <END_TASK> <USER_TASK:> Description: def _pre_train(self, stop_param_updates, num_epochs, updates_epoch): """Set parameters and constants before training."""
# Calculate the total number of updates given early stopping. updates = {k: stop_param_updates.get(k, num_epochs) * updates_epoch for k, v in self.params.items()} # Calculate the value of a single step given the number of allowed # updates. single_steps = {k: np.exp(-((1.0 - (1.0 / v))) * self.params[k]['factor']) for k, v in updates.items()} # Calculate the factor given the true factor and the value of a # single step. constants = {k: np.exp(-self.params[k]['factor']) / v for k, v in single_steps.items()} return constants
<SYSTEM_TASK:> First fit, then predict. <END_TASK> <USER_TASK:> Description: def fit_predict(self, X, num_epochs=10, updates_epoch=10, stop_param_updates=dict(), batch_size=1, show_progressbar=False): """First fit, then predict."""
self.fit(X, num_epochs, updates_epoch, stop_param_updates, batch_size, show_progressbar) return self.predict(X, batch_size=batch_size)
<SYSTEM_TASK:> First fit, then transform. <END_TASK> <USER_TASK:> Description: def fit_transform(self, X, num_epochs=10, updates_epoch=10, stop_param_updates=dict(), batch_size=1, show_progressbar=False, show_epoch=False): """First fit, then transform."""
self.fit(X, num_epochs, updates_epoch, stop_param_updates, batch_size, show_progressbar, show_epoch) return self.transform(X, batch_size=batch_size)
<SYSTEM_TASK:> Create batches out of a sequence of data. <END_TASK> <USER_TASK:> Description: def _create_batches(self, X, batch_size, shuffle_data=True): """ Create batches out of a sequence of data. This function will append zeros to the end of your data to ensure that all batches are even-sized. These are masked out during training. """
if shuffle_data: X = shuffle(X) if batch_size > X.shape[0]: batch_size = X.shape[0] max_x = int(np.ceil(X.shape[0] / batch_size)) X = np.resize(X, (max_x, batch_size, X.shape[-1])) return X
<SYSTEM_TASK:> Propagate a single batch of examples through the network. <END_TASK> <USER_TASK:> Description: def _propagate(self, x, influences, **kwargs): """Propagate a single batch of examples through the network."""
activation, difference_x = self.forward(x) update = self.backward(difference_x, influences, activation) # If batch size is 1 we can leave out the call to mean. if update.shape[0] == 1: self.weights += update[0] else: self.weights += update.mean(0) return activation
<SYSTEM_TASK:> Check the input for validity. <END_TASK> <USER_TASK:> Description: def _check_input(self, X): """ Check the input for validity. Ensures that the input data, X, is a 2-dimensional matrix, and that the second dimension of this matrix has the same dimensionality as the weight matrix. """
if np.ndim(X) == 1: X = np.reshape(X, (1, -1)) if X.ndim != 2: raise ValueError("Your data is not a 2D matrix. " "Actual size: {0}".format(X.shape)) if X.shape[1] != self.data_dimensionality: raise ValueError("Your data size != weight dim: {0}, " "expected {1}".format(X.shape[1], self.data_dimensionality)) return X
<SYSTEM_TASK:> Transform input to a distance matrix by measuring the L2 distance. <END_TASK> <USER_TASK:> Description: def transform(self, X, batch_size=100, show_progressbar=False): """ Transform input to a distance matrix by measuring the L2 distance. Parameters ---------- X : numpy array. The input data. batch_size : int, optional, default 100 The batch size to use in transformation. This may affect the transformation in stateful, i.e. sequential SOMs. show_progressbar : bool Whether to show a progressbar during transformation. Returns ------- transformed : numpy array A matrix containing the distance from each datapoint to all neurons. The distance is normally expressed as euclidean distance, but can be any arbitrary metric. """
X = self._check_input(X) batched = self._create_batches(X, batch_size, shuffle_data=False) activations = [] prev = self._init_prev(batched) for x in tqdm(batched, disable=not show_progressbar): prev = self.forward(x, prev_activation=prev)[0] activations.extend(prev) activations = np.asarray(activations, dtype=np.float64) activations = activations[:X.shape[0]] return activations.reshape(X.shape[0], self.num_neurons)
<SYSTEM_TASK:> Predict the BMU for each input data. <END_TASK> <USER_TASK:> Description: def predict(self, X, batch_size=1, show_progressbar=False): """ Predict the BMU for each input data. Parameters ---------- X : numpy array. The input data. batch_size : int, optional, default 100 The batch size to use in prediction. This may affect prediction in stateful, i.e. sequential SOMs. show_progressbar : bool Whether to show a progressbar during prediction. Returns ------- predictions : numpy array An array containing the BMU for each input data point. """
dist = self.transform(X, batch_size, show_progressbar) res = dist.__getattribute__(self.argfunc)(1) return res
<SYSTEM_TASK:> Calculate the quantization error. <END_TASK> <USER_TASK:> Description: def quantization_error(self, X, batch_size=1): """ Calculate the quantization error. Find the the minimum euclidean distance between the units and some input. Parameters ---------- X : numpy array. The input data. batch_size : int The batch size to use for processing. Returns ------- error : numpy array The error for each data point. """
dist = self.transform(X, batch_size) res = dist.__getattribute__(self.valfunc)(1) return res
<SYSTEM_TASK:> Load a SOM from a JSON file saved with this package. <END_TASK> <USER_TASK:> Description: def load(cls, path): """ Load a SOM from a JSON file saved with this package. Parameters ---------- path : str The path to the JSON file. Returns ------- s : cls A som of the specified class. """
data = json.load(open(path)) weights = data['weights'] weights = np.asarray(weights, dtype=np.float64) s = cls(data['num_neurons'], data['data_dimensionality'], data['params']['lr']['orig'], neighborhood=data['params']['infl']['orig'], valfunc=data['valfunc'], argfunc=data['argfunc'], lr_lambda=data['params']['lr']['factor'], nb_lambda=data['params']['nb']['factor']) s.weights = weights s.trained = True return s
<SYSTEM_TASK:> Get or infer the auth version. <END_TASK> <USER_TASK:> Description: def get_authversion(job_args): """Get or infer the auth version. Based on the information found in the *AUTH_VERSION_MAP* the authentication version will be set to a correct value as determined by the **os_auth_version** parameter as found in the `job_args`. :param job_args: ``dict`` :returns: ``str`` """
_version = job_args.get('os_auth_version') for version, variants in AUTH_VERSION_MAP.items(): if _version in variants: authversion = job_args['os_auth_version'] = version return authversion else: raise exceptions.AuthenticationProblem( "Auth Version must be one of %s.", list(AUTH_VERSION_MAP.keys()) )
<SYSTEM_TASK:> Setup headers for authentication request. <END_TASK> <USER_TASK:> Description: def get_headers(self): """Setup headers for authentication request."""
try: return { 'X-Auth-User': self.job_args['os_user'], 'X-Auth-Key': self.job_args['os_apikey'] } except KeyError as exp: raise exceptions.AuthenticationProblem( 'Missing Credentials. Error: %s', exp )
<SYSTEM_TASK:> Perform auth request for token. <END_TASK> <USER_TASK:> Description: def auth_request(self, url, headers, body): """Perform auth request for token."""
return self.req.post(url, headers, body=body)
<SYSTEM_TASK:> This is the run section of the application Turbolift. <END_TASK> <USER_TASK:> Description: def execute(): """This is the run section of the application Turbolift."""
if len(sys.argv) <= 1: raise SystemExit( 'No Arguments provided. use [--help] for more information.' ) # Capture user arguments _args = arguments.ArgumentParserator( arguments_dict=turbolift.ARGUMENTS, env_name='TURBO', epilog=turbolift.VINFO, title='Turbolift', detail='Multiprocessing Swift CLI tool.', description='Manage Swift easily and fast.' ) user_args = _args.arg_parser() user_args['run_indicator'] = True debug_log = False stream_logs = True # Load system logging if user_args.get('debug'): debug_log = True user_args['run_indicator'] = False # Load system logging if user_args.get('quiet'): stream_logs = False user_args['run_indicator'] = False _logging = logger.LogSetup( debug_logging=debug_log, colorized_messages=user_args.get('colorized', False) ) _logging.default_logger(name='turbolift', enable_stream=stream_logs) job = worker.Worker(job_args=user_args) job.run_manager()
<SYSTEM_TASK:> Read messages from .log file <END_TASK> <USER_TASK:> Description: def read(self, log_file): """ Read messages from .log file """
if os.path.isdir(os.path.dirname(log_file)) and os.path.isfile(log_file): with open(log_file, 'r') as LogFile: data = LogFile.readlines() data = "".join(line for line in data) else: data = '' return data
<SYSTEM_TASK:> Fit the scaler based on some data. <END_TASK> <USER_TASK:> Description: def fit(self, X): """ Fit the scaler based on some data. Takes the columnwise mean and standard deviation of the entire input array. If the array has more than 2 dimensions, it is flattened. Parameters ---------- X : numpy array Returns ------- scaled : numpy array A scaled version of said array. """
if X.ndim > 2: X = X.reshape((np.prod(X.shape[:-1]), X.shape[-1])) self.mean = X.mean(0) self.std = X.std(0) self.is_fit = True return self
<SYSTEM_TASK:> Transform your data to zero mean unit variance. <END_TASK> <USER_TASK:> Description: def transform(self, X): """Transform your data to zero mean unit variance."""
if not self.is_fit: raise ValueError("The scaler has not been fit yet.") return (X-self.mean) / (self.std + 10e-7)
<SYSTEM_TASK:> Return a list of dictionaries which are sorted for only unique entries. <END_TASK> <USER_TASK:> Description: def unique_list_dicts(dlist, key): """Return a list of dictionaries which are sorted for only unique entries. :param dlist: :param key: :return list: """
return list(dict((val[key], val) for val in dlist).values())
<SYSTEM_TASK:> Return a Quoted URL. <END_TASK> <USER_TASK:> Description: def quoter(obj): """Return a Quoted URL. The quote function will return a URL encoded string. If there is an exception in the job which results in a "KeyError" the original string will be returned as it will be assumed to already be URL encoded. :param obj: ``basestring`` :return: ``str`` """
try: try: return urllib.quote(obj) except AttributeError: return urllib.parse.quote(obj) except KeyError: return obj
<SYSTEM_TASK:> Clone objects from one container to another. <END_TASK> <USER_TASK:> Description: def start(self): """Clone objects from one container to another. This method was built to clone a container between data-centers while using the same credentials. The method assumes that an authentication token will be valid within the two data centers. """
LOG.info('Clone warm up...') # Create the target args self._target_auth() last_list_obj = None while True: self.indicator_options['msg'] = 'Gathering object list' with indicator.Spinner(**self.indicator_options): objects_list = self._list_contents( single_page_return=True, last_obj=last_list_obj ) if not objects_list: return last_obj = utils.byte_encode(objects_list[-1].get('name')) LOG.info( 'Last object [ %s ] Last object in the list [ %s ]', last_obj, last_list_obj ) if last_list_obj == last_obj: return else: last_list_obj = last_obj self._clone_worker(objects_list=objects_list)
<SYSTEM_TASK:> Remove Registered Filter <END_TASK> <USER_TASK:> Description: def removeFilter(self, filter): """ Remove Registered Filter """
filter = filter.split('#') del self.FILTERS[int(filter[1])] return True
<SYSTEM_TASK:> Remove Registered Action <END_TASK> <USER_TASK:> Description: def removeAction(self, action): """ Remove Registered Action """
action = action.split('#') del self.ACTIONS[int(action[1])] return True
<SYSTEM_TASK:> Execute Registered Filters <END_TASK> <USER_TASK:> Description: def _execFilters(self, type, msg): """ Execute Registered Filters """
for filter in self.FILTERS: msg = filter(type, msg) return msg
<SYSTEM_TASK:> Execute Registered Actions <END_TASK> <USER_TASK:> Description: def _execActions(self, type, msg): """ Execute Registered Actions """
for action in self.ACTIONS: action(type, msg)
<SYSTEM_TASK:> Authentication plugins. <END_TASK> <USER_TASK:> Description: def auth_plugins(auth_plugins=None): """Authentication plugins. Usage, Add any plugin here that will serve as a rapid means to authenticate to an OpenStack environment. Syntax is as follows: >>> __auth_plugins__ = { ... 'new_plugin_name': { ... 'os_auth_url': 'https://localhost:5000/v2.0/tokens', ... 'os_prefix': { ... 'os_apikey': 'apiKeyCredentials', ... 'os_password': 'passwordCredentials' ... }, ... 'args': { ... 'commands': [ ... '--new-plugin-name-auth' ... ], ... 'choices': [ ... 'RegionOne' ... ], ... 'help': 'Authentication plugin for New Plugin Name', ... 'default': os.environ.get('OS_NEW_PLUGIN_AUTH', None), ... 'metavar': '[REGION]' ... } ... } ... } If the subdomain is in the auth url, as is the case with hp, add "%(region)s" to the "os_auth_url" value. The region value from the list of choices will be used as the string replacement. Note that if the `os_prefix` key is added the system will override the authentication body prefix with the string provided. At this time the choices are os_apikey, os_password, os_token. All key entries are optional and should one not be specified with a credential type a `NotImplementedError` will be raised. :param auth_plugins: Additional plugins to add in :type auth_plugins: ``dict`` :returns: ``dict`` """
__auth_plugins__ = { 'os_rax_auth': { 'os_auth_url': 'https://identity.api.rackspacecloud.com/v2.0/' 'tokens', 'os_prefix': { 'os_apikey': 'RAX-KSKEY:apiKeyCredentials', 'os_password': 'passwordCredentials' }, 'args': { 'commands': [ '--os-rax-auth' ], 'choices': [ 'dfw', 'ord', 'iad', 'syd', 'hkg', 'lon' ], 'help': 'Authentication Plugin for Rackspace Cloud' ' env[OS_RAX_AUTH]', 'default': os.environ.get('OS_RAX_AUTH', None), 'metavar': '[REGION]' } }, 'rax_auth_v1': { 'os_auth_version': 'v1.0', 'os_auth_url': 'https://identity.api.rackspacecloud.com/v1.0', 'args': { 'commands': [ '--rax-auth-v1' ], 'action': 'store_true', 'help': 'Authentication Plugin for Rackspace Cloud V1' } }, 'os_rax_auth_lon': { 'os_auth_url': 'https://lon.identity.api.rackspacecloud.com/' 'v2.0/tokens', 'os_prefix': { 'os_apikey': 'RAX-KSKEY:apiKeyCredentials', 'os_password': 'passwordCredentials' }, 'args': { 'commands': [ '--os-rax-auth-lon' ], 'choices': [ 'lon' ], 'help': 'Authentication Plugin for Rackspace Cloud' ' env[OS_RAX_AUTH_LON]', 'default': os.environ.get('OS_RAX_AUTH_LON', None), 'metavar': '[REGION]' } }, 'os_hp_auth': { 'os_auth_url': 'https://%(region)s.identity.hpcloudsvc.com:35357/' 'v2.0/tokens', 'os_prefix': { 'os_password': 'passwordCredentials' }, 'args': { 'commands': [ '--os-hp-auth' ], 'choices': [ 'region-b.geo-1', 'region-a.geo-1' ], 'help': 'Authentication Plugin for HP Cloud' ' env[OS_HP_AUTH]', 'default': os.environ.get('OS_HP_AUTH', None), 'metavar': '[REGION]' } } } if auth_plugins: __auth_plugins__.update(auth_plugins) return __auth_plugins__
<SYSTEM_TASK:> Predict distances to some input data. <END_TASK> <USER_TASK:> Description: def predict_distance(self, X, batch_size=1, show_progressbar=False): """Predict distances to some input data."""
X = self._check_input(X) X_shape = reduce(np.multiply, X.shape[:-1], 1) batched = self._create_batches(X, batch_size, shuffle_data=False) activations = [] activation = self._init_prev(batched) for x in tqdm(batched, disable=not show_progressbar): activation = self.forward(x, prev_activation=activation)[0] activations.append(activation) act = np.asarray(activations, dtype=np.float64).transpose((1, 0, 2)) act = act[:X_shape] return act.reshape(X_shape, self.num_neurons)
<SYSTEM_TASK:> Generate data based on some initial position. <END_TASK> <USER_TASK:> Description: def generate(self, num_to_generate, starting_place): """Generate data based on some initial position."""
res = [] activ = starting_place[None, :] index = activ.__getattribute__(self.argfunc)(1) item = self.weights[index] for x in range(num_to_generate): activ = self.forward(item, prev_activation=activ)[0] index = activ.__getattribute__(self.argfunc)(1) res.append(index) item = self.weights[index] return res
<SYSTEM_TASK:> Perform a forward pass through the network. <END_TASK> <USER_TASK:> Description: def forward(self, x, **kwargs): """ Perform a forward pass through the network. The forward pass in recursive som is based on a combination between the activation in the last time-step and the current time-step. Parameters ---------- x : numpy array The input data. prev_activation : numpy array. The activation of the network in the previous time-step. Returns ------- activations : tuple of activations and differences A tuple containing the activation of each unit, the differences between the weights and input and the differences between the context input and context weights. """
prev = kwargs['prev_activation'] # Differences is the components of the weights subtracted from # the weight vector. distance_x, diff_x = self.distance_function(x, self.weights) distance_y, diff_y = self.distance_function(prev, self.context_weights) x_ = distance_x * self.alpha y_ = distance_y * self.beta activation = np.exp(-(x_ + y_)) return activation, diff_x, diff_y
<SYSTEM_TASK:> Load a recursive SOM from a JSON file. <END_TASK> <USER_TASK:> Description: def load(cls, path): """ Load a recursive SOM from a JSON file. You can use this function to load weights of other SOMs. If there are no context weights, they will be set to 0. Parameters ---------- path : str The path to the JSON file. Returns ------- s : cls A som of the specified class. """
data = json.load(open(path)) weights = data['weights'] weights = np.asarray(weights, dtype=np.float64) try: context_weights = data['context_weights'] context_weights = np.asarray(context_weights, dtype=np.float64) except KeyError: context_weights = np.zeros((len(weights), len(weights))) try: alpha = data['alpha'] beta = data['beta'] except KeyError: alpha = 1.0 beta = 1.0 s = cls(data['map_dimensions'], data['data_dimensionality'], data['params']['lr']['orig'], influence=data['params']['infl']['orig'], alpha=alpha, beta=beta, lr_lambda=data['params']['lr']['factor'], infl_lambda=data['params']['infl']['factor']) s.weights = weights s.context_weights = context_weights s.trained = True return s
<SYSTEM_TASK:> Return headers and a parsed url. <END_TASK> <USER_TASK:> Description: def _return_base_data(self, url, container, container_object=None, container_headers=None, object_headers=None): """Return headers and a parsed url. :param url: :param container: :param container_object: :param container_headers: :return: ``tuple`` """
headers = self.job_args['base_headers'] headers.update({'X-Auth-Token': self.job_args['os_token']}) _container_uri = url.geturl().rstrip('/') if container: _container_uri = '%s/%s' % ( _container_uri, cloud_utils.quoter(container) ) if container_object: _container_uri = '%s/%s' % ( _container_uri, cloud_utils.quoter(container_object) ) if object_headers: headers.update(object_headers) if container_headers: headers.update(container_headers) return headers, urlparse.urlparse(_container_uri)
<SYSTEM_TASK:> Make many PUT request for a single chunked object. <END_TASK> <USER_TASK:> Description: def _chunk_putter(self, uri, open_file, headers=None): """Make many PUT request for a single chunked object. Objects that are processed by this method have a SHA256 hash appended to the name as well as a count for object indexing which starts at 0. To make a PUT request pass, ``url`` :param uri: ``str`` :param open_file: ``object`` :param headers: ``dict`` """
count = 0 dynamic_hash = hashlib.sha256(self.job_args.get('container')) dynamic_hash = dynamic_hash.hexdigest() while True: # Read in a chunk of an open file file_object = open_file.read(self.job_args.get('chunk_size')) if not file_object: break # When a chuck is present store it as BytesIO with io.BytesIO(file_object) as file_object: # store the parsed URI for the chunk chunk_uri = urlparse.urlparse( '%s.%s.%s' % ( uri.geturl(), dynamic_hash, count ) ) # Increment the count as soon as it is used count += 1 # Check if the read chunk already exists sync = self._sync_check( uri=chunk_uri, headers=headers, file_object=file_object ) if not sync: continue # PUT the chunk _resp = self.http.put( url=chunk_uri, body=file_object, headers=headers ) self._resp_exception(resp=_resp) LOG.debug(_resp.__dict__)
<SYSTEM_TASK:> Place object into the container. <END_TASK> <USER_TASK:> Description: def _putter(self, uri, headers, local_object=None): """Place object into the container. :param uri: :param headers: :param local_object: """
if not local_object: return self.http.put(url=uri, headers=headers) with open(local_object, 'rb') as f_open: large_object_size = self.job_args.get('large_object_size') if not large_object_size: large_object_size = 5153960756 if os.path.getsize(local_object) > large_object_size: # Remove the manifest entry while working with chunks manifest = headers.pop('X-Object-Manifest') # Feed the open file through the chunk process self._chunk_putter( uri=uri, open_file=f_open, headers=headers ) # Upload the 0 byte object with the manifest path headers.update({'X-Object-Manifest': manifest}) return self.http.put(url=uri, headers=headers) else: if self.job_args.get('sync'): sync = self._sync_check( uri=uri, headers=headers, local_object=local_object ) if not sync: return None return self.http.put( url=uri, body=f_open, headers=headers )
<SYSTEM_TASK:> POST Headers on a specified object in the container. <END_TASK> <USER_TASK:> Description: def _header_poster(self, uri, headers): """POST Headers on a specified object in the container. :param uri: ``str`` :param headers: ``dict`` """
resp = self.http.post(url=uri, body=None, headers=headers) self._resp_exception(resp=resp) return resp
<SYSTEM_TASK:> Return an index of objects from within the container. <END_TASK> <USER_TASK:> Description: def _obj_index(self, uri, base_path, marked_path, headers, spr=False): """Return an index of objects from within the container. :param uri: :param base_path: :param marked_path: :param headers: :param spr: "single page return" Limit the returned data to one page :type spr: ``bol`` :return: """
object_list = list() l_obj = None container_uri = uri.geturl() while True: marked_uri = urlparse.urljoin(container_uri, marked_path) resp = self.http.get(url=marked_uri, headers=headers) self._resp_exception(resp=resp) return_list = resp.json() if spr: return return_list time_offset = self.job_args.get('time_offset') for obj in return_list: if time_offset: # Get the last_modified data from the Object. time_delta = cloud_utils.TimeDelta( job_args=self.job_args, last_modified=time_offset ) if time_delta: object_list.append(obj) else: object_list.append(obj) if object_list: last_obj_in_list = object_list[-1].get('name') else: last_obj_in_list = None if l_obj == last_obj_in_list: return object_list else: l_obj = last_obj_in_list marked_path = self._last_marker( base_path=base_path, last_object=l_obj )
<SYSTEM_TASK:> Get a list of all objects in a container. <END_TASK> <USER_TASK:> Description: def _list_getter(self, uri, headers, last_obj=None, spr=False): """Get a list of all objects in a container. :param uri: :param headers: :return list: :param spr: "single page return" Limit the returned data to one page :type spr: ``bol`` """
# Quote the file path. base_path = marked_path = ('%s?limit=10000&format=json' % uri.path) if last_obj: marked_path = self._last_marker( base_path=base_path, last_object=cloud_utils.quoter(last_obj) ) file_list = self._obj_index( uri=uri, base_path=base_path, marked_path=marked_path, headers=headers, spr=spr ) LOG.debug( 'Found [ %d ] entries(s) at [ %s ]', len(file_list), uri.geturl() ) if spr: return file_list else: return cloud_utils.unique_list_dicts( dlist=file_list, key='name' )
<SYSTEM_TASK:> If we encounter an exception in our upload. <END_TASK> <USER_TASK:> Description: def _resp_exception(self, resp): """If we encounter an exception in our upload. we will look at how we can attempt to resolve the exception. :param resp: """
message = [ 'Url: [ %s ] Reason: [ %s ] Request: [ %s ] Status Code: [ %s ]. ', resp.url, resp.reason, resp.request, resp.status_code ] # Check to make sure we have all the bits needed if not hasattr(resp, 'status_code'): message[0] += 'No Status to check. Turbolift will retry...' raise exceptions.SystemProblem(message) elif resp is None: message[0] += 'No response information. Turbolift will retry...' raise exceptions.SystemProblem(message) elif resp.status_code == 401: message[0] += ( 'Turbolift experienced an Authentication issue. Turbolift' ' will retry...' ) self.job_args.update(auth.authenticate(self.job_args)) raise exceptions.SystemProblem(message) elif resp.status_code == 404: message[0] += 'Item not found.' LOG.debug(*message) elif resp.status_code == 409: message[0] += ( 'Request Conflict. Turbolift is abandoning this...' ) elif resp.status_code == 413: return_headers = resp.headers retry_after = return_headers.get('retry_after', 10) cloud_utils.stupid_hack(wait=retry_after) message[0] += ( 'The System encountered an API limitation and will' ' continue in [ %s ] Seconds' % retry_after ) raise exceptions.SystemProblem(message) elif resp.status_code == 502: message[0] += ( 'Failure making Connection. Turbolift will retry...' ) raise exceptions.SystemProblem(message) elif resp.status_code == 503: cloud_utils.stupid_hack(wait=10) message[0] += 'SWIFT-API FAILURE' raise exceptions.SystemProblem(message) elif resp.status_code == 504: cloud_utils.stupid_hack(wait=10) message[0] += 'Gateway Failure.' raise exceptions.SystemProblem(message) elif resp.status_code >= 300: message[0] += 'General exception.' raise exceptions.SystemProblem(message) else: LOG.debug(*message)
<SYSTEM_TASK:> Builds a long list of objects found in a container. <END_TASK> <USER_TASK:> Description: def list_items(self, url, container=None, last_obj=None, spr=False): """Builds a long list of objects found in a container. NOTE: This could be millions of Objects. :param url: :param container: :param last_obj: :param spr: "single page return" Limit the returned data to one page :type spr: ``bol`` :return None | list: """
headers, container_uri = self._return_base_data( url=url, container=container ) if container: resp = self._header_getter(uri=container_uri, headers=headers) if resp.status_code == 404: LOG.info('Container [ %s ] not found.', container) return [resp] return self._list_getter( uri=container_uri, headers=headers, last_obj=last_obj, spr=spr )
<SYSTEM_TASK:> Update an existing object in a swift container. <END_TASK> <USER_TASK:> Description: def update_object(self, url, container, container_object, object_headers, container_headers): """Update an existing object in a swift container. This method will place new headers on an existing object or container. :param url: :param container: :param container_object: """
headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object, container_headers=container_headers, object_headers=object_headers, ) return self._header_poster( uri=container_uri, headers=headers )
<SYSTEM_TASK:> Command your CDN enabled Container. <END_TASK> <USER_TASK:> Description: def container_cdn_command(self, url, container, container_object, cdn_headers): """Command your CDN enabled Container. :param url: :param container: """
headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object, object_headers=cdn_headers ) if self.job_args.get('purge'): return self._deleter( uri=container_uri, headers=headers ) else: return self._header_poster( uri=container_uri, headers=headers )
<SYSTEM_TASK:> Create a container if it is not Found. <END_TASK> <USER_TASK:> Description: def put_container(self, url, container, container_headers=None): """Create a container if it is not Found. :param url: :param container: """
headers, container_uri = self._return_base_data( url=url, container=container, container_headers=container_headers ) resp = self._header_getter( uri=container_uri, headers=headers ) if resp.status_code == 404: return self._putter(uri=container_uri, headers=headers) else: return resp
<SYSTEM_TASK:> This is the Sync method which uploads files to the swift repository <END_TASK> <USER_TASK:> Description: def put_object(self, url, container, container_object, local_object, object_headers, meta=None): """This is the Sync method which uploads files to the swift repository if they are not already found. If a file "name" is found locally and in the swift repository an MD5 comparison is done between the two files. If the MD5 is miss-matched the local file is uploaded to the repository. If custom meta data is specified, and the object exists the method will put the metadata onto the object. :param url: :param container: :param container_object: """
headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object, container_headers=object_headers, object_headers=meta ) return self._putter( uri=container_uri, headers=headers, local_object=local_object )
<SYSTEM_TASK:> Get an objects from a container. <END_TASK> <USER_TASK:> Description: def get_items(self, url, container, container_object, local_object): """Get an objects from a container. :param url: :param container: """
headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object ) return self._getter( uri=container_uri, headers=headers, local_object=local_object )
<SYSTEM_TASK:> Deletes an objects in a container. <END_TASK> <USER_TASK:> Description: def delete_items(self, url, container, container_object=None): """Deletes an objects in a container. :param url: :param container: """
headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object ) return self._deleter(uri=container_uri, headers=headers)
<SYSTEM_TASK:> Get indices of bmus, sorted by their distance from input. <END_TASK> <USER_TASK:> Description: def _get_bmu(self, activations): """Get indices of bmus, sorted by their distance from input."""
# If the neural gas is a recursive neural gas, we need reverse argsort. if self.argfunc == 'argmax': activations = -activations sort = np.argsort(activations, 1) return sort.argsort()
<SYSTEM_TASK:> Calculate the ranking influence. <END_TASK> <USER_TASK:> Description: def _calculate_influence(self, influence_lambda): """Calculate the ranking influence."""
return np.exp(-np.arange(self.num_neurons) / influence_lambda)[:, None]
<SYSTEM_TASK:> Shuffles a list of `items` in place. <END_TASK> <USER_TASK:> Description: def _shuffle_items(items, bucket_key=None, disable=None, seed=None, session=None): """ Shuffles a list of `items` in place. If `bucket_key` is None, items are shuffled across the entire list. `bucket_key` is an optional function called for each item in `items` to calculate the key of bucket in which the item falls. Bucket defines the boundaries across which items will not be shuffled. `disable` is a function that takes an item and returns a falsey value if this item is ok to be shuffled. It returns a truthy value otherwise and the truthy value is used as part of the item's key when determining the bucket it belongs to. """
if seed is not None: random.seed(seed) # If `bucket_key` is falsey, shuffle is global. if not bucket_key and not disable: random.shuffle(items) return def get_full_bucket_key(item): assert bucket_key or disable if bucket_key and disable: return ItemKey(bucket=bucket_key(item, session), disabled=disable(item, session)) elif disable: return ItemKey(disabled=disable(item, session)) else: return ItemKey(bucket=bucket_key(item, session)) # For a sequence of items A1, A2, B1, B2, C1, C2, # where key(A1) == key(A2) == key(C1) == key(C2), # items A1, A2, C1, and C2 will end up in the same bucket. buckets = OrderedDict() for item in items: full_bucket_key = get_full_bucket_key(item) if full_bucket_key not in buckets: buckets[full_bucket_key] = [] buckets[full_bucket_key].append(item) # Shuffle inside a bucket bucket_keys = list(buckets.keys()) for full_bucket_key in buckets.keys(): if full_bucket_key.bucket == FAILED_FIRST_LAST_FAILED_BUCKET_KEY: # Do not shuffle the last failed bucket continue if not full_bucket_key.disabled: random.shuffle(buckets[full_bucket_key]) # Shuffle buckets # Only the first bucket can be FAILED_FIRST_LAST_FAILED_BUCKET_KEY if bucket_keys and bucket_keys[0].bucket == FAILED_FIRST_LAST_FAILED_BUCKET_KEY: new_bucket_keys = list(buckets.keys())[1:] random.shuffle(new_bucket_keys) new_bucket_keys.insert(0, bucket_keys[0]) else: new_bucket_keys = list(buckets.keys()) random.shuffle(new_bucket_keys) items[:] = [item for bk in new_bucket_keys for item in buckets[bk]] return
<SYSTEM_TASK:> Registers a function that calculates test item key for the specified bucket type. <END_TASK> <USER_TASK:> Description: def bucket_type_key(bucket_type): """ Registers a function that calculates test item key for the specified bucket type. """
def decorator(f): @functools.wraps(f) def wrapped(item, session): key = f(item) if session is not None: for handler in session.random_order_bucket_type_key_handlers: key = handler(item, key) return key bucket_type_keys[bucket_type] = wrapped return wrapped return decorator
<SYSTEM_TASK:> generic bitpay usigned wrapper <END_TASK> <USER_TASK:> Description: def unsigned_request(self, path, payload=None): """ generic bitpay usigned wrapper passing a payload will do a POST, otherwise a GET """
headers = {"content-type": "application/json", "accept": "application/json", "X-accept-version": "2.0.0"} try: if payload: response = requests.post(self.uri + path, verify=self.verify, data=json.dumps(payload), headers=headers) else: response = requests.get(self.uri + path, verify=self.verify, headers=headers) except Exception as pro: raise BitPayConnectionError('Connection refused') return response
<SYSTEM_TASK:> Example application that watches for an event from a specific RF device. <END_TASK> <USER_TASK:> Description: def main(): """ Example application that watches for an event from a specific RF device. This feature allows you to watch for events from RF devices if you have an RF receiver. This is useful in the case of internal sensors, which don't emit a FAULT if the sensor is tripped and the panel is armed STAY. It also will monitor sensors that aren't configured. NOTE: You must have an RF receiver installed and enabled in your panel for RFX messages to be seen. """
try: # Retrieve the first USB device device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handler and open the device device.on_rfx_message += handle_rfx with device.open(baudrate=BAUDRATE): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
<SYSTEM_TASK:> Fire event and call all handler functions <END_TASK> <USER_TASK:> Description: def fire(self, *args, **kwargs): """Fire event and call all handler functions You can call EventHandler object itself like e(*args, **kwargs) instead of e.fire(*args, **kwargs). """
for func in self._getfunctionlist(): if type(func) == EventHandler: func.fire(*args, **kwargs) else: func(self.obj, *args, **kwargs)
<SYSTEM_TASK:> Example application that opens a serial device and prints messages to the terminal. <END_TASK> <USER_TASK:> Description: def main(): """ Example application that opens a serial device and prints messages to the terminal. """
try: # Retrieve the specified serial device. device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handler and open the device device.on_message += handle_message # Override the default SerialDevice baudrate since we're using a USB device # over serial in this example. with device.open(baudrate=BAUDRATE): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
<SYSTEM_TASK:> Initializes our device as an SSL connection. <END_TASK> <USER_TASK:> Description: def _init_ssl(self): """ Initializes our device as an SSL connection. :raises: :py:class:`~alarmdecoder.util.CommError` """
if not have_openssl: raise ImportError('SSL sockets have been disabled due to missing requirement: pyopenssl.') try: ctx = SSL.Context(SSL.TLSv1_METHOD) if isinstance(self.ssl_key, crypto.PKey): ctx.use_privatekey(self.ssl_key) else: ctx.use_privatekey_file(self.ssl_key) if isinstance(self.ssl_certificate, crypto.X509): ctx.use_certificate(self.ssl_certificate) else: ctx.use_certificate_file(self.ssl_certificate) if isinstance(self.ssl_ca, crypto.X509): store = ctx.get_cert_store() store.add_cert(self.ssl_ca) else: ctx.load_verify_locations(self.ssl_ca, None) verify_method = SSL.VERIFY_PEER if (self._ssl_allow_self_signed): verify_method = SSL.VERIFY_NONE ctx.set_verify(verify_method, self._verify_ssl_callback) self._device = SSL.Connection(ctx, self._device) except SSL.Error as err: raise CommError('Error setting up SSL connection.', err)
<SYSTEM_TASK:> Returns the best n_local_max frequencies <END_TASK> <USER_TASK:> Description: def get_best_frequencies(self): """ Returns the best n_local_max frequencies """
return self.freq[self.best_local_optima], self.per[self.best_local_optima]
<SYSTEM_TASK:> Computes the selected criterion over a grid of frequencies <END_TASK> <USER_TASK:> Description: def finetune_best_frequencies(self, fresolution=1e-5, n_local_optima=10): """ Computes the selected criterion over a grid of frequencies around a specified amount of local optima of the periodograms. This function is intended for additional fine tuning of the results obtained with grid_search """
# Find the local optima local_optima_index = [] for k in range(1, len(self.per)-1): if self.per[k-1] < self.per[k] and self.per[k+1] < self.per[k]: local_optima_index.append(k) local_optima_index = np.array(local_optima_index) if(len(local_optima_index) < n_local_optima): print("Warning: Not enough local maxima found in the periodogram, skipping finetuning") return # Keep only n_local_optima best_local_optima = local_optima_index[np.argsort(self.per[local_optima_index])][::-1] if n_local_optima > 0: best_local_optima = best_local_optima[:n_local_optima] else: best_local_optima = best_local_optima[0] # Do finetuning around each local optima for j in range(n_local_optima): freq_fine = self.freq[best_local_optima[j]] - self.fres_grid for k in range(0, int(2.0*self.fres_grid/fresolution)): cost = self.compute_metric(freq_fine) if cost > self.per[best_local_optima[j]]: self.per[best_local_optima[j]] = cost self.freq[best_local_optima[j]] = freq_fine freq_fine += fresolution # Sort them in descending order idx = np.argsort(self.per[best_local_optima])[::-1] if n_local_optima > 0: self.best_local_optima = best_local_optima[idx] else: self.best_local_optima = best_local_optima
<SYSTEM_TASK:> Updates the states in the primary AlarmDecoder object based on <END_TASK> <USER_TASK:> Description: def update(self, message): """ Updates the states in the primary AlarmDecoder object based on the LRR message provided. :param message: LRR message object :type message: :py:class:`~alarmdecoder.messages.LRRMessage` """
# Firmware version < 2.2a.8.6 if message.version == 1: if message.event_type == 'ALARM_PANIC': self._alarmdecoder._update_panic_status(True) elif message.event_type == 'CANCEL': self._alarmdecoder._update_panic_status(False) # Firmware version >= 2.2a.8.6 elif message.version == 2: source = message.event_source if source == LRR_EVENT_TYPE.CID: self._handle_cid_message(message) elif source == LRR_EVENT_TYPE.DSC: self._handle_dsc_message(message) elif source == LRR_EVENT_TYPE.ADEMCO: self._handle_ademco_message(message) elif source == LRR_EVENT_TYPE.ALARMDECODER: self._handle_alarmdecoder_message(message) elif source == LRR_EVENT_TYPE.UNKNOWN: self._handle_unknown_message(message) else: pass
<SYSTEM_TASK:> Retrieves the boolean status of an LRR message. <END_TASK> <USER_TASK:> Description: def _get_event_status(self, message): """ Retrieves the boolean status of an LRR message. :param message: LRR message object :type message: :py:class:`~alarmdecoder.messages.LRRMessage` :returns: Boolean indicating whether the event was triggered or restored. """
status = None if message.event_status == LRR_EVENT_STATUS.TRIGGER: status = True elif message.event_status == LRR_EVENT_STATUS.RESTORE: status = False return status
<SYSTEM_TASK:> Returns all serial ports present. <END_TASK> <USER_TASK:> Description: def find_all(pattern=None): """ Returns all serial ports present. :param pattern: pattern to search for when retrieving serial ports :type pattern: string :returns: list of devices :raises: :py:class:`~alarmdecoder.util.CommError` """
devices = [] try: if pattern: devices = serial.tools.list_ports.grep(pattern) else: devices = serial.tools.list_ports.comports() except serial.SerialException as err: raise CommError('Error enumerating serial devices: {0}'.format(str(err)), err) return devices
<SYSTEM_TASK:> Parse the message from the device. <END_TASK> <USER_TASK:> Description: def _parse_message(self, data): """ Parse the message from the device. :param data: message data :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError` """
match = self._regex.match(str(data)) if match is None: raise InvalidMessageError('Received invalid message: {0}'.format(data)) header, self.bitfield, self.numeric_code, self.panel_data, alpha = match.group(1, 2, 3, 4, 5) is_bit_set = lambda bit: not self.bitfield[bit] == "0" self.ready = is_bit_set(1) self.armed_away = is_bit_set(2) self.armed_home = is_bit_set(3) self.backlight_on = is_bit_set(4) self.programming_mode = is_bit_set(5) self.beeps = int(self.bitfield[6], 16) self.zone_bypassed = is_bit_set(7) self.ac_power = is_bit_set(8) self.chime_on = is_bit_set(9) self.alarm_event_occurred = is_bit_set(10) self.alarm_sounding = is_bit_set(11) self.battery_low = is_bit_set(12) self.entry_delay_off = is_bit_set(13) self.fire_alarm = is_bit_set(14) self.check_zone = is_bit_set(15) self.perimeter_only = is_bit_set(16) self.system_fault = is_bit_set(17) if self.bitfield[18] in list(PANEL_TYPES): self.panel_type = PANEL_TYPES[self.bitfield[18]] # pos 20-21 - Unused. self.text = alpha.strip('"') self.mask = int(self.panel_data[3:3+8], 16) if self.panel_type in (ADEMCO, DSC): if int(self.panel_data[19:21], 16) & 0x01 > 0: # Current cursor location on the alpha display. self.cursor_location = int(self.panel_data[21:23], 16)
<SYSTEM_TASK:> Parses and returns the numeric code as an integer. <END_TASK> <USER_TASK:> Description: def parse_numeric_code(self, force_hex=False): """ Parses and returns the numeric code as an integer. The numeric code can be either base 10 or base 16, depending on where the message came from. :param force_hex: force the numeric code to be processed as base 16. :type force_hex: boolean :raises: ValueError """
code = None got_error = False if not force_hex: try: code = int(self.numeric_code) except ValueError: got_error = True if force_hex or got_error: try: code = int(self.numeric_code, 16) except ValueError: raise return code
<SYSTEM_TASK:> Example application that opens a device that has been exposed to the network <END_TASK> <USER_TASK:> Description: def main(): """ Example application that opens a device that has been exposed to the network with ser2sock or similar serial-to-IP software. """
try: # Retrieve an AD2 device that has been exposed with ser2sock on localhost:10000. device = AlarmDecoder(SocketDevice(interface=(HOSTNAME, PORT))) # Set up an event handler and open the device device.on_message += handle_message with device.open(): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
<SYSTEM_TASK:> Parse the raw message from the device. <END_TASK> <USER_TASK:> Description: def _parse_message(self, data): """ Parse the raw message from the device. :param data: message data :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError` """
try: header, values = data.split(':') address, channel, value = values.split(',') self.address = int(address) self.channel = int(channel) self.value = int(value) except ValueError: raise InvalidMessageError('Received invalid message: {0}'.format(data)) if header == '!EXP': self.type = ExpanderMessage.ZONE elif header == '!REL': self.type = ExpanderMessage.RELAY else: raise InvalidMessageError('Unknown expander message header: {0}'.format(data))
<SYSTEM_TASK:> Retrieves the human-readable description of an LRR event. <END_TASK> <USER_TASK:> Description: def get_event_description(event_type, event_code): """ Retrieves the human-readable description of an LRR event. :param event_type: Base LRR event type. Use LRR_EVENT_TYPE.* :type event_type: int :param event_code: LRR event code :type event_code: int :returns: string """
description = 'Unknown' lookup_map = LRR_TYPE_MAP.get(event_type, None) if lookup_map is not None: description = lookup_map.get(event_code, description) return description
<SYSTEM_TASK:> Retrieves the LRR_EVENT_TYPE corresponding to the prefix provided.abs <END_TASK> <USER_TASK:> Description: def get_event_source(prefix): """ Retrieves the LRR_EVENT_TYPE corresponding to the prefix provided.abs :param prefix: Prefix to convert to event type :type prefix: string :returns: int """
source = LRR_EVENT_TYPE.UNKNOWN if prefix == 'CID': source = LRR_EVENT_TYPE.CID elif prefix == 'DSC': source = LRR_EVENT_TYPE.DSC elif prefix == 'AD2': source = LRR_EVENT_TYPE.ALARMDECODER elif prefix == 'ADEMCO': source = LRR_EVENT_TYPE.ADEMCO return source
<SYSTEM_TASK:> Sends data to the `AlarmDecoder`_ device. <END_TASK> <USER_TASK:> Description: def send(self, data): """ Sends data to the `AlarmDecoder`_ device. :param data: data to send :type data: string """
if self._device: if isinstance(data, str): data = str.encode(data) # Hack to support unicode under Python 2.x if sys.version_info < (3,): if isinstance(data, unicode): data = bytes(data) self._device.write(data)
<SYSTEM_TASK:> Build a configuration string that's compatible with the AlarmDecoder configuration <END_TASK> <USER_TASK:> Description: def get_config_string(self): """ Build a configuration string that's compatible with the AlarmDecoder configuration command from the current values in the object. :returns: string """
config_entries = [] # HACK: This is ugly.. but I can't think of an elegant way of doing it. config_entries.append(('ADDRESS', '{0}'.format(self.address))) config_entries.append(('CONFIGBITS', '{0:x}'.format(self.configbits))) config_entries.append(('MASK', '{0:x}'.format(self.address_mask))) config_entries.append(('EXP', ''.join(['Y' if z else 'N' for z in self.emulate_zone]))) config_entries.append(('REL', ''.join(['Y' if r else 'N' for r in self.emulate_relay]))) config_entries.append(('LRR', 'Y' if self.emulate_lrr else 'N')) config_entries.append(('DEDUPLICATE', 'Y' if self.deduplicate else 'N')) config_entries.append(('MODE', list(PANEL_TYPES)[list(PANEL_TYPES.values()).index(self.mode)])) config_entries.append(('COM', 'Y' if self.emulate_com else 'N')) config_string = '&'.join(['='.join(t) for t in config_entries]) return '&'.join(['='.join(t) for t in config_entries])
<SYSTEM_TASK:> Faults a zone if we are emulating a zone expander. <END_TASK> <USER_TASK:> Description: def fault_zone(self, zone, simulate_wire_problem=False): """ Faults a zone if we are emulating a zone expander. :param zone: zone to fault :type zone: int :param simulate_wire_problem: Whether or not to simulate a wire fault :type simulate_wire_problem: bool """
# Allow ourselves to also be passed an address/channel combination # for zone expanders. # # Format (expander index, channel) if isinstance(zone, tuple): expander_idx, channel = zone zone = self._zonetracker.expander_to_zone(expander_idx, channel) status = 2 if simulate_wire_problem else 1 self.send("L{0:02}{1}\r".format(zone, status))
<SYSTEM_TASK:> Wires up the internal device events. <END_TASK> <USER_TASK:> Description: def _wire_events(self): """ Wires up the internal device events. """
self._device.on_open += self._on_open self._device.on_close += self._on_close self._device.on_read += self._on_read self._device.on_write += self._on_write self._zonetracker.on_fault += self._on_zone_fault self._zonetracker.on_restore += self._on_zone_restore
<SYSTEM_TASK:> Parses keypad messages from the panel. <END_TASK> <USER_TASK:> Description: def _handle_message(self, data): """ Parses keypad messages from the panel. :param data: keypad data to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.Message` """
try: data = data.decode('utf-8') except: raise InvalidMessageError('Decode failed for message: {0}'.format(data)) if data is not None: data = data.lstrip('\0') if data is None or data == '': raise InvalidMessageError() msg = None header = data[0:4] if header[0] != '!' or header == '!KPM': msg = self._handle_keypad_message(data) elif header == '!EXP' or header == '!REL': msg = self._handle_expander_message(data) elif header == '!RFX': msg = self._handle_rfx(data) elif header == '!LRR': msg = self._handle_lrr(data) elif header == '!AUI': msg = self._handle_aui(data) elif data.startswith('!Ready'): self.on_boot() elif data.startswith('!CONFIG'): self._handle_config(data) elif data.startswith('!VER'): self._handle_version(data) elif data.startswith('!Sending'): self._handle_sending(data) return msg
<SYSTEM_TASK:> Handles received version data. <END_TASK> <USER_TASK:> Description: def _handle_version(self, data): """ Handles received version data. :param data: Version string to parse :type data: string """
_, version_string = data.split(':') version_parts = version_string.split(',') self.serial_number = version_parts[0] self.version_number = version_parts[1] self.version_flags = version_parts[2]
<SYSTEM_TASK:> Handles received configuration data. <END_TASK> <USER_TASK:> Description: def _handle_config(self, data): """ Handles received configuration data. :param data: Configuration string to parse :type data: string """
_, config_string = data.split('>') for setting in config_string.split('&'): key, val = setting.split('=') if key == 'ADDRESS': self.address = int(val) elif key == 'CONFIGBITS': self.configbits = int(val, 16) elif key == 'MASK': self.address_mask = int(val, 16) elif key == 'EXP': self.emulate_zone = [val[z] == 'Y' for z in list(range(5))] elif key == 'REL': self.emulate_relay = [val[r] == 'Y' for r in list(range(4))] elif key == 'LRR': self.emulate_lrr = (val == 'Y') elif key == 'DEDUPLICATE': self.deduplicate = (val == 'Y') elif key == 'MODE': self.mode = PANEL_TYPES[val] elif key == 'COM': self.emulate_com = (val == 'Y') self.on_config_received()
<SYSTEM_TASK:> Handles results of a keypress send. <END_TASK> <USER_TASK:> Description: def _handle_sending(self, data): """ Handles results of a keypress send. :param data: Sending string to parse :type data: string """
matches = re.match('^!Sending(\.{1,5})done.*', data) if matches is not None: good_send = False if len(matches.group(1)) < 5: good_send = True self.on_sending_received(status=good_send, message=data)
<SYSTEM_TASK:> Uses the provided message to update the AC power state. <END_TASK> <USER_TASK:> Description: def _update_power_status(self, message=None, status=None): """ Uses the provided message to update the AC power state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: power status, overrides message bits. :type status: bool :returns: bool indicating the new status """
power_status = status if isinstance(message, Message): power_status = message.ac_power if power_status is None: return if power_status != self._power_status: self._power_status, old_status = power_status, self._power_status if old_status is not None: self.on_power_changed(status=self._power_status) return self._power_status
<SYSTEM_TASK:> Uses the provided message to update the Chime state. <END_TASK> <USER_TASK:> Description: def _update_chime_status(self, message=None, status=None): """ Uses the provided message to update the Chime state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: chime status, overrides message bits. :type status: bool :returns: bool indicating the new status """
chime_status = status if isinstance(message, Message): chime_status = message.chime_on if chime_status is None: return if chime_status != self._chime_status: self._chime_status, old_status = chime_status, self._chime_status if old_status is not None: self.on_chime_changed(status=self._chime_status) return self._chime_status
<SYSTEM_TASK:> Uses the provided message to update the alarm state. <END_TASK> <USER_TASK:> Description: def _update_alarm_status(self, message=None, status=None, zone=None, user=None): """ Uses the provided message to update the alarm state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: alarm status, overrides message bits. :type status: bool :param user: user associated with alarm event :type user: string :returns: bool indicating the new status """
alarm_status = status alarm_zone = zone if isinstance(message, Message): alarm_status = message.alarm_sounding alarm_zone = message.parse_numeric_code() if alarm_status != self._alarm_status: self._alarm_status, old_status = alarm_status, self._alarm_status if old_status is not None or status is not None: if self._alarm_status: self.on_alarm(zone=alarm_zone) else: self.on_alarm_restored(zone=alarm_zone, user=user) return self._alarm_status
<SYSTEM_TASK:> Uses the provided message to update the zone bypass state. <END_TASK> <USER_TASK:> Description: def _update_zone_bypass_status(self, message=None, status=None, zone=None): """ Uses the provided message to update the zone bypass state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: bypass status, overrides message bits. :type status: bool :param zone: zone associated with bypass event :type zone: int :returns: dictionary {Zone:True|False,...} Zone can be None if LRR CID Bypass checking is disabled or we do not know what zones but know something is bypassed. """
bypass_status = status if isinstance(message, Message): bypass_status = message.zone_bypassed if bypass_status is None: return old_bypass_status = self._bypass_status.get(zone, None) if bypass_status != old_bypass_status: if bypass_status == False and zone is None: self._bypass_status = {} else: self._bypass_status[zone] = bypass_status if old_bypass_status is not None or message is None or (old_bypass_status is None and bypass_status is True): self.on_bypass(status=bypass_status, zone=zone) return bypass_status
<SYSTEM_TASK:> Uses the provided message to update the armed state. <END_TASK> <USER_TASK:> Description: def _update_armed_status(self, message=None, status=None, status_stay=None): """ Uses the provided message to update the armed state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: armed status, overrides message bits :type status: bool :param status_stay: armed stay status, overrides message bits :type status_stay: bool :returns: bool indicating the new status """
arm_status = status stay_status = status_stay if isinstance(message, Message): arm_status = message.armed_away stay_status = message.armed_home if arm_status is None or stay_status is None: return self._armed_status, old_status = arm_status, self._armed_status self._armed_stay, old_stay = stay_status, self._armed_stay if arm_status != old_status or stay_status != old_stay: if old_status is not None or message is None: if self._armed_status or self._armed_stay: self.on_arm(stay=stay_status) else: self.on_disarm() return self._armed_status or self._armed_stay
<SYSTEM_TASK:> Uses the provided message to update the battery state. <END_TASK> <USER_TASK:> Description: def _update_battery_status(self, message=None, status=None): """ Uses the provided message to update the battery state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: battery status, overrides message bits :type status: bool :returns: boolean indicating the new status """
battery_status = status if isinstance(message, Message): battery_status = message.battery_low if battery_status is None: return last_status, last_update = self._battery_status if battery_status == last_status: self._battery_status = (last_status, time.time()) else: if battery_status is True or time.time() > last_update + self._battery_timeout: self._battery_status = (battery_status, time.time()) self.on_low_battery(status=battery_status) return self._battery_status[0]
<SYSTEM_TASK:> Uses the provided message to update the fire alarm state. <END_TASK> <USER_TASK:> Description: def _update_fire_status(self, message=None, status=None): """ Uses the provided message to update the fire alarm state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: fire status, overrides message bits :type status: bool :returns: boolean indicating the new status """
fire_status = status last_status = self._fire_status if isinstance(message, Message): # Quirk in Ademco panels. The fire bit drops on "SYSTEM LO BAT" messages. # FIXME: does not support non english panels. if self.mode == ADEMCO and message.text.startswith("SYSTEM"): fire_status = last_status else: fire_status = message.fire_alarm if fire_status is None: return if fire_status != self._fire_status: self._fire_status, old_status = fire_status, self._fire_status if old_status is not None: self.on_fire(status=self._fire_status) return self._fire_status
<SYSTEM_TASK:> Updates the panic status of the alarm panel. <END_TASK> <USER_TASK:> Description: def _update_panic_status(self, status=None): """ Updates the panic status of the alarm panel. :param status: status to use to update :type status: boolean :returns: boolean indicating the new status """
if status is None: return if status != self._panic_status: self._panic_status, old_status = status, self._panic_status if old_status is not None: self.on_panic(status=self._panic_status) return self._panic_status
<SYSTEM_TASK:> Uses the provided message to update the expander states. <END_TASK> <USER_TASK:> Description: def _update_expander_status(self, message): """ Uses the provided message to update the expander states. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.ExpanderMessage` :returns: boolean indicating the new status """
if message.type == ExpanderMessage.RELAY: self._relay_status[(message.address, message.channel)] = message.value self.on_relay_changed(message=message) return self._relay_status[(message.address, message.channel)]
<SYSTEM_TASK:> Internal handler for opening the device. <END_TASK> <USER_TASK:> Description: def _on_open(self, sender, *args, **kwargs): """ Internal handler for opening the device. """
self.get_config() self.get_version() self.on_open()
<SYSTEM_TASK:> Internal handler for reading from the device. <END_TASK> <USER_TASK:> Description: def _on_read(self, sender, *args, **kwargs): """ Internal handler for reading from the device. """
data = kwargs.get('data', None) self.on_read(data=data) self._handle_message(data)
<SYSTEM_TASK:> Internal handler for writing to the device. <END_TASK> <USER_TASK:> Description: def _on_write(self, sender, *args, **kwargs): """ Internal handler for writing to the device. """
self.on_write(data=kwargs.get('data', None))
<SYSTEM_TASK:> Update zone statuses based on the current message. <END_TASK> <USER_TASK:> Description: def update(self, message): """ Update zone statuses based on the current message. :param message: message to use to update the zone tracking :type message: :py:class:`~alarmdecoder.messages.Message` or :py:class:`~alarmdecoder.messages.ExpanderMessage` """
if isinstance(message, ExpanderMessage): zone = -1 if message.type == ExpanderMessage.ZONE: zone = self.expander_to_zone(message.address, message.channel, self.alarmdecoder_object.mode) if zone != -1: status = Zone.CLEAR if message.value == 1: status = Zone.FAULT elif message.value == 2: status = Zone.CHECK # NOTE: Expander zone faults are handled differently than # regular messages. We don't include them in # self._zones_faulted because they are not reported # by the panel in it's rolling list of faults. try: self._update_zone(zone, status=status) except IndexError: self._add_zone(zone, status=status, expander=True) else: # Panel is ready, restore all zones. # # NOTE: This will need to be updated to support panels with # multiple partitions. In it's current state a ready on # partition #1 will end up clearing all zones, even if they # exist elsewhere and it shouldn't. # # NOTE: SYSTEM messages provide inconsistent ready statuses. This # may need to be extended later for other panels. if message.ready and not message.text.startswith("SYSTEM"): for zone in self._zones_faulted: self._update_zone(zone, Zone.CLEAR) self._last_zone_fault = 0 # Process fault elif self.alarmdecoder_object.mode != DSC and (message.check_zone or message.text.startswith("FAULT") or message.text.startswith("ALARM")): zone = message.parse_numeric_code() # NOTE: Odd case for ECP failures. Apparently they report as # zone 191 (0xBF) regardless of whether or not the # 3-digit mode is enabled... so we have to pull it out # of the alpha message. if zone == 191: zone_regex = re.compile('^CHECK (\d+).*$') match = zone_regex.match(message.text) if match is None: return zone = match.group(1) # Add new zones and clear expired ones. if zone in self._zones_faulted: self._update_zone(zone) self._clear_zones(zone) else: status = Zone.FAULT if message.check_zone: status = Zone.CHECK self._add_zone(zone, status=status) self._zones_faulted.append(zone) self._zones_faulted.sort() # Save our spot for the next message. self._last_zone_fault = zone self._clear_expired_zones()
<SYSTEM_TASK:> Convert an address and channel into a zone number. <END_TASK> <USER_TASK:> Description: def expander_to_zone(self, address, channel, panel_type=ADEMCO): """ Convert an address and channel into a zone number. :param address: expander address :type address: int :param channel: channel :type channel: int :returns: zone number associated with an address and channel """
zone = -1 if panel_type == ADEMCO: # TODO: This is going to need to be reworked to support the larger # panels without fixed addressing on the expanders. idx = address - 7 # Expanders start at address 7. zone = address + channel + (idx * 7) + 1 elif panel_type == DSC: zone = (address * 8) + channel return zone
<SYSTEM_TASK:> Clear all expired zones from our status list. <END_TASK> <USER_TASK:> Description: def _clear_zones(self, zone): """ Clear all expired zones from our status list. :param zone: current zone being processed :type zone: int """
cleared_zones = [] found_last_faulted = found_current = at_end = False # First pass: Find our start spot. it = iter(self._zones_faulted) try: while not found_last_faulted: z = next(it) if z == self._last_zone_fault: found_last_faulted = True break except StopIteration: at_end = True # Continue until we find our end point and add zones in # between to our clear list. try: while not at_end and not found_current: z = next(it) if z == zone: found_current = True break else: cleared_zones += [z] except StopIteration: pass # Second pass: roll through the list again if we didn't find # our end point and remove everything until we do. if not found_current: it = iter(self._zones_faulted) try: while not found_current: z = next(it) if z == zone: found_current = True break else: cleared_zones += [z] except StopIteration: pass # Actually remove the zones and trigger the restores. for z in cleared_zones: self._update_zone(z, Zone.CLEAR)
<SYSTEM_TASK:> Adds a zone to the internal zone list. <END_TASK> <USER_TASK:> Description: def _add_zone(self, zone, name='', status=Zone.CLEAR, expander=False): """ Adds a zone to the internal zone list. :param zone: zone number :type zone: int :param name: human readable zone name :type name: string :param status: zone status :type status: int """
if not zone in self._zones: self._zones[zone] = Zone(zone=zone, name=name, status=None, expander=expander) self._update_zone(zone, status=status)
<SYSTEM_TASK:> Determine if a zone is expired or not. <END_TASK> <USER_TASK:> Description: def _zone_expired(self, zone): """ Determine if a zone is expired or not. :param zone: zone number :type zone: int :returns: whether or not the zone is expired """
return (time.time() > self._zones[zone].timestamp + Zonetracker.EXPIRE) and self._zones[zone].expander is False
<SYSTEM_TASK:> Example application that periodically faults a virtual zone and then <END_TASK> <USER_TASK:> Description: def main(): """ Example application that periodically faults a virtual zone and then restores it. This is an advanced feature that allows you to emulate a virtual zone. When the AlarmDecoder is configured to emulate a zone expander we can fault and restore those zones programmatically at will. These events can also be seen by others, such as home automation platforms which allows you to connect other devices or services and monitor them as you would any physical zone. For example, you could connect a ZigBee device and receiver and fault or restore it's zone(s) based on the data received. In order for this to happen you need to perform a couple configuration steps: 1. Enable zone expander emulation on your AlarmDecoder device by hitting '!' in a terminal and going through the prompts. 2. Enable the zone expander in your panel programming. """
try: # Retrieve the first USB device device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handlers and open the device device.on_zone_fault += handle_zone_fault device.on_zone_restore += handle_zone_restore with device.open(baudrate=BAUDRATE): last_update = time.time() while True: if time.time() - last_update > WAIT_TIME: last_update = time.time() device.fault_zone(TARGET_ZONE) time.sleep(1) except Exception as ex: print('Exception:', ex)