code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
dist = self.transform(X, batch_size)
# Sort the distances and get the indices of the two smallest distances
# for each datapoint.
res = dist.argsort(1)[:, :2]
# Lookup the euclidean distance between these points in the distance
# grid
dgrid = self.distanc... | def topographic_error(self, X, batch_size=1) | Calculate the topographic error.
The topographic error is a measure of the spatial organization of the
map. Maps in which the most similar neurons are also close on the
grid have low topographic error and indicate that a problem has been
learned correctly.
Formally, the topogra... | 4.74459 | 5.122267 | 0.926268 |
dgrid = self.distance_grid.reshape(self.num_neurons, self.num_neurons)
for x, y in zip(*np.nonzero(dgrid <= distance)):
if x != y:
yield x, y | def neighbors(self, distance=2.0) | Get all neighbors for all neurons. | 4.220258 | 3.772717 | 1.118626 |
differences = np.zeros(self.num_neurons)
num_neighbors = np.zeros(self.num_neurons)
distance, _ = self.distance_function(self.weights, self.weights)
for x, y in self.neighbors():
differences[x] += distance[x, y]
num_neighbors[x] += 1
return diff... | def neighbor_difference(self) | Get the euclidean distance between a node and its neighbors. | 3.392682 | 3.094888 | 1.096221 |
distance, _ = self.distance_function(X, self.weights)
dists_per_neuron = defaultdict(list)
for x, y in zip(np.argmin(distance, 1), distance):
dists_per_neuron[x].append(y[x])
out = np.zeros(self.num_neurons)
average_spread = {k: np.mean(v)
... | def spread(self, X) | Calculate the average spread for each node.
The average spread is a measure of how far each neuron is from the
data points which cluster to it.
Parameters
----------
X : numpy array
The input data.
Returns
-------
spread : numpy array
... | 3.171334 | 3.108465 | 1.020225 |
receptive_fields = defaultdict(list)
predictions = self.predict(X, batch_size)
if len(predictions) != len(identities):
raise ValueError("X and identities are not the same length: "
"{0} and {1}".format(len(X), len(identities)))
for idx,... | def receptive_field(self,
X,
identities,
max_len=10,
threshold=0.9,
batch_size=1) | Calculate the receptive field of the SOM on some data.
The receptive field is the common ending of all sequences which
lead to the activation of a given BMU. If a SOM is well-tuned to
specific sequences, it will have longer receptive fields, and therefore
gives a better description of t... | 3.003191 | 3.110613 | 0.965466 |
distances = self.transform(X)
if len(distances) != len(identities):
raise ValueError("X and identities are not the same length: "
"{0} and {1}".format(len(X), len(identities)))
node_match = []
for d in distances.__getattribute__(self.a... | def invert_projection(self, X, identities) | Calculate the inverted projection.
The inverted projectio of a SOM is created by association each weight
with the input which matches it the most, thus giving a good
approximation of the "influence" of each input item.
Works best for symbolic (instead of continuous) input data.
... | 4.264562 | 5.009065 | 0.851369 |
first_dim = self.map_dimensions[0]
if len(self.map_dimensions) != 1:
second_dim = np.prod(self.map_dimensions[1:])
else:
second_dim = 1
# Reshape to appropriate dimensions
return self.weights.reshape((first_dim,
... | def map_weights(self) | Reshaped weights for visualization.
The weights are reshaped as
(W.shape[0], prod(W.shape[1:-1]), W.shape[2]).
This allows one to easily see patterns, even for hyper-dimensional
soms.
For one-dimensional SOMs, the returned array is of shape
(W.shape[0], 1, W.shape[2])
... | 3.900901 | 3.633668 | 1.073544 |
data = json.load(open(path))
weights = data['weights']
weights = np.asarray(weights, dtype=np.float64)
s = cls(data['map_dimensions'],
data['params']['lr']['orig'],
data['data_dimensionality'],
influence=data['params']['infl']['o... | 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. | 4.954109 | 4.940228 | 1.00281 |
LOG.info('Interacting with the CDN...')
with indicator.Spinner(run=self.run_indicator):
cdn_item = self._cdn()
self.print_virt_table(cdn_item.headers) | def start(self) | Return a list of objects from the API for a container. | 26.554277 | 24.239273 | 1.095506 |
headers = dict()
cdn_enabled = self.job_args.get('cdn_enabled')
if cdn_enabled:
headers['x-cdn-enabled'] = True
cdn_disabled = self.job_args.get('cdn_disabled')
if cdn_disabled:
headers['x-cdn-enabled'] = False
cdn_logs_enabled = self.... | def _cdn(self) | Retrieve a long list of all files in a container.
:return final_list, list_count, last_obj: | 1.871333 | 1.858119 | 1.007112 |
LOG.info('Removing directory [ %s ]', directory)
local_files = self._drectory_local_files(directory=directory)
for file_name in local_files:
try:
os.remove(file_name['local_object'])
except OSError as exp:
LOG.error(str(exp))
... | def remove_dirs(self, directory) | Delete a directory recursively.
:param directory: $PATH to directory.
:type directory: ``str`` | 3.806926 | 3.774116 | 1.008693 |
if self.job_args.get('cdn_containers'):
if not self.job_args.get('fields'):
self.job_args['fields'] = [
'name',
'cdn_enabled',
'log_retention',
'ttl'
]
url = self.job_... | def _list_contents(self, last_obj=None, single_page_return=False) | Retrieve a long list of all files in a container.
:return final_list, list_count, last_obj: | 3.834565 | 3.936194 | 0.974181 |
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(co... | 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``) | 3.119315 | 3.004044 | 1.038372 |
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
... | def _index_fs(self) | Returns a deque object full of local file system items.
:returns: ``deque`` | 4.054912 | 3.5934 | 1.128433 |
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(... | def match_filter(self, idx_list, pattern, dict_type=False,
dict_key='name') | Return Matched items in indexed files.
:param idx_list:
:return list | 2.815038 | 3.027731 | 0.929752 |
# 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)
... | def print_horiz_table(self, data) | Print a horizontal pretty table from data. | 2.91562 | 2.929811 | 0.995156 |
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) | def print_virt_table(self, data) | Print a vertical pretty table from data. | 3.497416 | 3.324751 | 1.051933 |
if self.job_args.get('colorized'):
print(cloud_utils.return_colorized(msg=message, color=color_level))
else:
print(message) | def printer(self, message, color_level='info') | Print Messages and Log it.
:param message: item to print to screen | 8.244164 | 9.062454 | 0.909705 |
edge = float(edge)
# dice
c = ops.Cube(edge, center=True)
s = ops.Sphere(edge * 3 / 4, center=True)
dice = c & s
# points
c = ops.Circle(edge / 12, _fn=fn)
h = 0.7
point = c.linear_extrude(height=h)
point1 = point.translate([0, 0, ... | def dice(edge=15, fn=32) | dice | 2.311261 | 2.301135 | 1.0044 |
# 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... | 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. | 4.909495 | 4.471183 | 1.09803 |
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... | 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 t... | 4.022207 | 3.795546 | 1.059718 |
# 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 | 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 ... | 3.213262 | 3.249631 | 0.988808 |
self._usr = usr
self._pwd = pwd | def login(self, usr, pwd) | Use login() to Log in with a username and password. | 6.961803 | 5.916667 | 1.176643 |
msg = MIMEText(msg)
msg['Subject'] = subject
msg['From'] = me
msg['To'] = to
server = smtplib.SMTP(self.host, self.port)
server.starttls()
# Check if user and password defined
if self._usr and self._pwd:
server.login(self._usr, self._p... | def send(self, me, to, subject, msg) | Send Message | 2.49476 | 2.46805 | 1.010822 |
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._ini... | 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 le... | 2.56239 | 2.734844 | 0.936942 |
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']
... | def _init_weights(self,
X) | Set the weights and normalize data before starting training. | 3.019789 | 3.009215 | 1.003514 |
# 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_ste... | def _pre_train(self,
stop_param_updates,
num_epochs,
updates_epoch) | Set parameters and constants before training. | 4.807107 | 4.799721 | 1.001539 |
self.fit(X,
num_epochs,
updates_epoch,
stop_param_updates,
batch_size,
show_progressbar)
return self.predict(X, batch_size=batch_size) | 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. | 1.993346 | 2.056046 | 0.969505 |
self.fit(X,
num_epochs,
updates_epoch,
stop_param_updates,
batch_size,
show_progressbar,
show_epoch)
return self.transform(X, batch_size=batch_size) | 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. | 1.991124 | 1.916088 | 1.039161 |
# Create batches
X_ = self._create_batches(X, batch_size)
X_len = np.prod(X.shape[:-1])
update_step = np.ceil(X_.shape[0] / updates_epoch)
# Initialize the previous activation
prev = self._init_prev(X_)
influences = self._update_params(constants)
... | def _epoch(self,
X,
epoch_idx,
batch_size,
updates_epoch,
constants,
show_progressbar) | Run a single epoch.
This function shuffles the data internally,
as this improves performance.
Parameters
----------
X : numpy array
The training data.
epoch_idx : int
The current epoch
batch_size : int
The batch size
u... | 4.793439 | 4.789326 | 1.000859 |
for k, v in constants.items():
self.params[k]['value'] *= v
influence = self._calculate_influence(self.params['infl']['value'])
return influence * self.params['lr']['value'] | def _update_params(self, constants) | Update params and return new influence. | 6.155217 | 4.538703 | 1.356162 |
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 | 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. | 2.439706 | 2.282792 | 1.068738 |
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)... | def _propagate(self, x, influences, **kwargs) | Propagate a single batch of examples through the network. | 5.408792 | 5.049916 | 1.071066 |
bmu = self._get_bmu(activations)
influence = influences[bmu]
update = np.multiply(diff_x, influence)
return update | def backward(self, diff_x, influences, activations, **kwargs) | Backward pass through the network, including update.
Parameters
----------
diff_x : numpy array
A matrix containing the differences between the input and neurons.
influences : numpy array
A matrix containing the influence each neuron has on each
other... | 4.713687 | 4.803451 | 0.981313 |
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 ... | 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. | 2.967225 | 2.775983 | 1.068892 |
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]
ac... | 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, ... | 3.096286 | 3.463324 | 0.894021 |
dist = self.transform(X, batch_size, show_progressbar)
res = dist.__getattribute__(self.argfunc)(1)
return res | 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_progres... | 9.994594 | 19.875259 | 0.502866 |
dist = self.transform(X, batch_size)
res = dist.__getattribute__(self.valfunc)(1)
return res | 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
---... | 13.606217 | 21.986876 | 0.618834 |
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']['o... | 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. | 5.01877 | 5.032507 | 0.99727 |
to_save = {}
for x in self.param_names:
attr = self.__getattribute__(x)
if type(attr) == np.ndarray:
attr = [[float(x) for x in row] for row in attr]
elif isinstance(attr, types.FunctionType):
attr = attr.__name__
t... | def save(self, path) | Save a SOM to a JSON file. | 2.738763 | 2.631188 | 1.040885 |
_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 ... | 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`` | 4.102559 | 3.751257 | 1.093649 |
for endpoint in endpoint_list:
region_get = endpoint.get('region', '')
if region.lower() == region_get.lower():
return http.parse_url(url=endpoint.get(lookup))
else:
raise exceptions.AuthenticationProblem(
'Region "%s" was not found in your Service Catalog.'... | def get_service_url(region, endpoint_list, lookup) | Lookup a service URL from the *endpoint_list*.
:param region: ``str``
:param endpoint_list: ``list``
:param lookup: ``str``
:return: ``object`` | 5.222947 | 5.614089 | 0.930328 |
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',
... | def get_headers(self) | Setup headers for authentication request. | 5.918675 | 5.05548 | 1.170744 |
auth_dict = dict()
LOG.debug('Authentication Headers %s', auth_response.headers)
try:
auth_dict['os_token'] = auth_response.headers['x-auth-token']
auth_dict['storage_url'] = urlparse.urlparse(
auth_response.headers['x-storage-url']
)... | def parse_auth_response(auth_response) | Parse the auth response and return the tenant, token, and username.
:param auth_response: the full object returned from an auth call
:returns: ``dict`` | 4.357756 | 4.669044 | 0.933329 |
return self.req.post(url, headers, body=body) | def auth_request(self, url, headers, body) | Perform auth request for token. | 8.680254 | 9.701241 | 0.894757 |
if self.job_args['os_auth_version'] == 'v1.0':
return dict()
else:
setup = {
'username': self.job_args.get('os_user')
}
# Check if any prefix items are set. A prefix should be a
# dictionary with keys matching the os... | def parse_reqtype(self) | Return the authentication body. | 2.821354 | 2.690529 | 1.048624 |
auth_dict = dict()
auth_response = auth_response.json()
LOG.debug('Authentication Response Body [ %s ]', auth_response)
access = auth_response.get('access')
access_token = access.get('token')
access_tenant = access_token.get('tenant')
access_user = acce... | def parse_auth_response(self, auth_response) | Parse the auth response and return the tenant, token, and username.
:param auth_response: the full object returned from an auth call
:returns: ``dict`` | 3.99326 | 4.031323 | 0.990558 |
try:
auth_url = self.job_args['os_auth_url']
if 'tokens' not in auth_url:
if not auth_url.endswith('/'):
auth_url = '%s/' % auth_url
auth_url = urlparse.urljoin(auth_url, 'tokens')
return auth_url
except Ke... | def parse_region(self) | Pull region/auth url information from context. | 5.742074 | 4.736104 | 1.212404 |
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,
... | def execute() | This is the run section of the application Turbolift. | 6.733424 | 6.205424 | 1.085087 |
try:
with open(log_file, 'a') as LogFile:
LogFile.write(msg + os.linesep)
except:
raise Exception('Error Configuring PyLogger.TextStorage Class.')
return os.path.isfile(log_file) | def write(self, log_file, msg) | Append message to .log file | 6.79158 | 6.541058 | 1.0383 |
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 | def read(self, log_file) | Read messages from .log file | 2.751787 | 2.797413 | 0.98369 |
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 | 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
... | 2.334756 | 2.495051 | 0.935755 |
if not self.is_fit:
raise ValueError("The scaler has not been fit yet.")
return (X-self.mean) / (self.std + 10e-7) | def transform(self, X) | Transform your data to zero mean unit variance. | 3.805911 | 3.477885 | 1.094318 |
def deco_retry(f):
@functools.wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck:
time.sleep(mdelay)
... | def retry(ExceptionToCheck, tries=3, delay=1, backoff=1) | Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ExceptionToCheck: the exception to check. may be a tuple of
... | 1.380864 | 1.43699 | 0.960942 |
# Stupid Hack For Public Cloud so it is not overwhelmed with API requests.
if wait is not None:
time.sleep(wait)
else:
time.sleep(random.randrange(1, most)) | def stupid_hack(most=10, wait=None) | Return a random time between 1 - 10 Seconds. | 7.298807 | 6.379129 | 1.14417 |
# Time constants
fmt = '%Y-%m-%dT%H:%M:%S.%f'
date = datetime.datetime
date_delta = datetime.timedelta
now = datetime.datetime.utcnow()
return fmt, date, date_delta, now | def time_stamp() | Setup time functions
:returns: ``tuple`` | 4.738221 | 4.769747 | 0.99339 |
return list(dict((val[key], val) for val in dlist).values()) | def unique_list_dicts(dlist, key) | Return a list of dictionaries which are sorted for only unique entries.
:param dlist:
:param key:
:return list: | 6.103787 | 7.242936 | 0.842723 |
try:
try:
return urllib.quote(obj)
except AttributeError:
return urllib.parse.quote(obj)
except KeyError:
return obj | 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`` | 4.389904 | 3.204251 | 1.370025 |
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 = s... | 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. | 6.391622 | 5.91252 | 1.081032 |
# Load any authentication plugins as needed
job_args = utils.check_auth_plugin(job_args)
# Set the auth version
auth_version = utils.get_authversion(job_args=job_args)
# Define the base headers that are used in all authentications
auth_headers = {
'Content-Type': 'application/jso... | def authenticate(job_args) | Authentication For Openstack API.
Pulls the full Openstack Service Catalog Credentials are the Users API
Username and Key/Password.
Set a DC Endpoint and Authentication URL for the OpenStack environment | 2.619562 | 2.752523 | 0.951695 |
for key, value in kargs.items():
setattr(self, key, value) | def _config(self, **kargs) | ReConfigure Package | 3.211306 | 2.832054 | 1.133914 |
if hasattr(self, key):
return getattr(self, key)
else:
return False | def getConfig(self, key) | Get a Config Value | 3.59586 | 3.575498 | 1.005695 |
self.FILTERS.append(filter)
return "FILTER#{}".format(len(self.FILTERS) - 1) | def addFilter(self, filter) | Register Custom Filter | 5.56391 | 5.36877 | 1.036347 |
self.ACTIONS.append(action)
return "ACTION#{}".format(len(self.ACTIONS) - 1) | def addAction(self, action) | Register Custom Action | 5.448914 | 5.237567 | 1.040352 |
filter = filter.split('#')
del self.FILTERS[int(filter[1])]
return True | def removeFilter(self, filter) | Remove Registered Filter | 9.181118 | 8.201486 | 1.119446 |
action = action.split('#')
del self.ACTIONS[int(action[1])]
return True | def removeAction(self, action) | Remove Registered Action | 8.48841 | 8.024831 | 1.057768 |
self._execActions('info', msg)
msg = self._execFilters('info', msg)
self._processMsg('info', msg)
self._sendMsg('info', msg) | def info(self, msg) | Log Info Messages | 6.35238 | 6.531177 | 0.972624 |
self._execActions('warning', msg)
msg = self._execFilters('warning', msg)
self._processMsg('warning', msg)
self._sendMsg('warning', msg) | def warning(self, msg) | Log Warning Messages | 6.629594 | 6.736843 | 0.98408 |
self._execActions('error', msg)
msg = self._execFilters('error', msg)
self._processMsg('error', msg)
self._sendMsg('error', msg) | def error(self, msg) | Log Error Messages | 6.716203 | 6.692862 | 1.003488 |
self._execActions('critical', msg)
msg = self._execFilters('critical', msg)
self._processMsg('critical', msg)
self._sendMsg('critical', msg) | def critical(self, msg) | Log Critical Messages | 6.564767 | 6.810733 | 0.963886 |
self._execActions('log', msg)
msg = self._execFilters('log', msg)
self._processMsg('log', msg)
self._sendMsg('log', msg) | def log(self, msg) | Log Normal Messages | 6.69574 | 6.655566 | 1.006036 |
now = datetime.datetime.now()
# Check If Path not provided
if self.LOG_FILE_PATH == '':
self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'
# Build absolute Path
log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log'
... | def _processMsg(self, type, msg) | Process Debug Messages | 3.547632 | 3.44864 | 1.028705 |
self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT)
self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) | def _configMailer(self) | Config Mailer Class | 3.027756 | 2.885257 | 1.049389 |
if self.ALERT_STATUS and type in self.ALERT_TYPES:
self._configMailer()
self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) | def _sendMsg(self, type, msg) | Send Alert Message To Emails | 7.504693 | 5.988158 | 1.253256 |
for filter in self.FILTERS:
msg = filter(type, msg)
return msg | def _execFilters(self, type, msg) | Execute Registered Filters | 4.917615 | 4.092607 | 1.201585 |
for action in self.ACTIONS:
action(type, msg) | def _execActions(self, type, msg) | Execute Registered Actions | 6.774474 | 5.707819 | 1.186876 |
try:
return isinstance(item, (basestring, unicode))
except NameError:
return isinstance(item, str) | def check_basestring(item) | Return ``bol`` on string check item.
:param item: Item to check if its a string
:type item: ``str``
:returns: ``bol`` | 2.704093 | 3.924403 | 0.689046 |
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):
... | def predict_distance(self, X, batch_size=1, show_progressbar=False) | Predict distances to some input data. | 3.514675 | 3.477346 | 1.010735 |
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)(... | def generate(self, num_to_generate, starting_place) | Generate data based on some initial position. | 5.419595 | 5.290033 | 1.024492 |
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_ = distan... | 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 arra... | 5.923327 | 5.048465 | 1.173293 |
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... | 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
... | 2.801881 | 2.587288 | 1.082942 |
diff_y = kwargs['diff_y']
bmu = self._get_bmu(activations)
influence = influences[bmu]
# Update
x_update = np.multiply(diff_x, influence)
y_update = np.multiply(diff_y, influence)
return x_update, y_update | def backward(self, diff_x, influences, activations, **kwargs) | Backward pass through the network, including update.
Parameters
----------
diff_x : numpy array
A matrix containing the differences between the input and neurons.
influences : numpy array
A matrix containing the influence each neuron has on each
other... | 3.515429 | 3.792269 | 0.926999 |
LOG.info('Listing options...')
with indicator.Spinner(**self.indicator_options):
objects_list = self._list_contents()
if not objects_list:
return
if isinstance(objects_list[0], dict):
filter_dlo = self.job_args.get('filter_dlo')
... | def start(self) | Return a list of objects from the API for a container. | 4.281073 | 4.149299 | 1.031758 |
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)
)
... | 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`` | 2.555058 | 2.740333 | 0.932389 |
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:
... | 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``
... | 4.402935 | 4.459778 | 0.987254 |
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 ... | def _putter(self, uri, headers, local_object=None) | Place object into the container.
:param uri:
:param headers:
:param local_object: | 3.615595 | 3.776777 | 0.957323 |
if self.job_args.get('sync'):
sync = self._sync_check(
uri=uri,
headers=headers,
local_object=local_object
)
if not sync:
return None
# perform Object HEAD request
resp = self.http.get(... | def _getter(self, uri, headers, local_object) | Perform HEAD request on a specified object in the container.
:param uri: ``str``
:param headers: ``dict`` | 2.495582 | 2.514121 | 0.992626 |
# perform Object HEAD request
resp = self.http.delete(url=uri, headers=headers)
self._resp_exception(resp=resp)
return resp | def _deleter(self, uri, headers) | Perform HEAD request on a specified object in the container.
:param uri: ``str``
:param headers: ``dict`` | 10.937421 | 10.34908 | 1.05685 |
# perform Object HEAD request
resp = self.http.head(url=uri, headers=headers)
self._resp_exception(resp=resp)
return resp | def _header_getter(self, uri, headers) | Perform HEAD request on a specified object in the container.
:param uri: ``str``
:param headers: ``dict`` | 9.438706 | 9.992957 | 0.944536 |
resp = self.http.post(url=uri, body=None, headers=headers)
self._resp_exception(resp=resp)
return resp | def _header_poster(self, uri, headers) | POST Headers on a specified object in the container.
:param uri: ``str``
:param headers: ``dict`` | 6.294487 | 7.006077 | 0.898433 |
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... | 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: | 3.284371 | 3.335149 | 0.984775 |
# 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._o... | 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`` | 4.570749 | 4.807789 | 0.950697 |
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_cod... | 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: | 3.361977 | 3.384933 | 0.993218 |
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... | 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: | 4.011998 | 4.19401 | 0.956602 |
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(
u... | 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: | 3.953724 | 4.847767 | 0.815576 |
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... | def container_cdn_command(self, url, container, container_object,
cdn_headers) | Command your CDN enabled Container.
:param url:
:param container: | 4.266304 | 5.095855 | 0.837211 |
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:... | def put_container(self, url, container, container_headers=None) | Create a container if it is not Found.
:param url:
:param container: | 3.902883 | 4.287501 | 0.910293 |
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,
... | 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 c... | 3.827127 | 5.173535 | 0.739751 |
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
) | def get_items(self, url, container, container_object, local_object) | Get an objects from a container.
:param url:
:param container: | 4.33952 | 5.345065 | 0.811874 |
headers, container_uri = self._return_base_data(
url=url,
container=container,
container_object=container_object
)
return self._deleter(uri=container_uri, headers=headers) | def delete_items(self, url, container, container_object=None) | Deletes an objects in a container.
:param url:
:param container: | 5.029753 | 6.665953 | 0.754544 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.