code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
score = 0
number = self.translator.translate_gene(chromosome.genes[0])
for factor in self.factors:
if number % factor == 0:
score += 1
else:
score -= 1
# check for optimal solution
if score == len(self.factors):
... | def eval_fitness(self, chromosome) | Convert a 1-gene chromosome into an integer and calculate its fitness
by checking it against each required factor.
return: fitness value | 6.905066 | 6.595008 | 1.047014 |
try:
request = requests.get(
'{}/{}/'.format(self.resource, URI), timeout=self.timeout)
raw_data = request.json()
# Doesn't always work !!!!!
#self._mac = next(iter(self.raw_data))
self.data = raw_data[self._mac]
re... | def get_status(self) | Get the details from the bulb. | 6.907961 | 6.372213 | 1.084076 |
self.get_status()
try:
self.state = self.data['on']
except TypeError:
self.state = False
return bool(self.state) | def get_bulb_state(self) | Get the relay state. | 4.9753 | 4.119745 | 1.207672 |
self.get_status()
try:
self.consumption = self.data['power']
except TypeError:
self.consumption = 0
return self.consumption | def get_power(self) | Get current power. | 4.794488 | 4.110303 | 1.166456 |
self.get_status()
try:
self.firmware = self.data['fw_version']
except TypeError:
self.firmware = 'Unknown'
return self.firmware | def get_firmware(self) | Get the current firmware version. | 4.450844 | 4.015077 | 1.108533 |
self.get_status()
try:
self.brightness = self.data['color'].split(';')[-1]
except TypeError:
self.brightness = 0
return self.brightness | def get_brightness(self) | Get current brightness. | 5.026187 | 4.466158 | 1.125394 |
self.get_status()
try:
self.transition_time = self.data['ramp']
except TypeError:
self.transition_time = 0
return self.transition_time | def get_transition_time(self) | Get the transition time in ms. | 4.915161 | 4.298031 | 1.143584 |
self.get_status()
try:
self.color = self.data['color']
self.mode = self.data['mode']
except TypeError:
self.color = 0
self.mode = ''
return {'color': self.color, 'mode': self.mode} | def get_color(self) | Get current color. | 3.367772 | 3.123672 | 1.078145 |
try:
data = "action=on&color={};{};{}".format(hue, saturation, value)
request = requests.post(
'{}/{}/{}'.format(self.resource, URI, self._mac),
data=data, timeout=self.timeout)
if request.status_code == 200:
self.data[... | def set_color_hsv(self, hue, saturation, value) | Turn the bulb on with the given values as HSV. | 4.925832 | 4.420393 | 1.114342 |
for i in range(0, 359):
self.set_color_hsv(i, 100, 100)
time.sleep(duration/359) | def set_rainbow(self, duration) | Turn the bulb on and create a rainbow. | 2.969947 | 2.74387 | 1.082394 |
self.set_transition_time(duration/100)
for i in range(0, duration):
try:
data = "action=on&color=3;{}".format(i)
request = requests.post(
'{}/{}/{}'.format(self.resource, URI, self._mac),
data=data, timeout=self... | def set_sunrise(self, duration) | Turn the bulb on and create a sunrise. | 5.237138 | 4.59028 | 1.140919 |
self.set_transition_time(100)
for step in range(0, int(duration/2)):
self.set_color_hsv(hsv1[0], hsv1[1], hsv1[2])
time.sleep(1)
self.set_color_hsv(hsv2[0], hsv2[1], hsv2[2])
time.sleep(1) | def set_flashing(self, duration, hsv1, hsv2) | Turn the bulb on, flashing with two colors. | 1.9406 | 1.820912 | 1.06573 |
try:
request = requests.post(
'{}/{}/{}/'.format(self.resource, URI, self._mac),
data={'action': 'off'}, timeout=self.timeout)
if request.status_code == 200:
pass
except requests.exceptions.ConnectionError:
rais... | def set_off(self) | Turn the bulb off. | 5.680908 | 5.281594 | 1.075605 |
assert isinstance(chromosome, Chromosome)
return [self.translate_gene(g) for g in chromosome] | def translate_chromosome(self, chromosome) | Translate all the genes in a chromosome.
chromosome: a ``chromosomes.Chromosome`` instance to translate
return: a list of translation products for the genes in the chromosome | 4.221361 | 4.041618 | 1.044473 |
if self.signed:
sign = 1 if gene.dna[0] == '0' else -1
base_start_idx = 1
else:
sign = 1
base_start_idx = 0
base = sign * int(gene.dna[base_start_idx:base_start_idx + self.significand_length], base=2)
exponent_sign = 1 if... | def translate_gene(self, gene) | Translate a gene with binary DNA into a base-10 floating point real number.
Parses the DNA in this manner:
1. The first bit determines the sign of the integer portion of the result (0=positive, 1=negative)
2. The next ``significand_length`` bits of the DNA are converted into a base-... | 3.019446 | 2.353003 | 1.283231 |
if not path:
raise Exception("Missing path to api swagger files")
if type(apis) is not list:
raise Exception("'apis' should be a list of api names")
if len(apis) == 0:
raise Exception("'apis' is an empty list - Expected at least one api name")
... | def load_clients(self, path=None, apis=[]) | Generate client libraries for the given apis, without starting an
api server | 3.273541 | 3.233263 | 1.012458 |
if not path:
raise Exception("Missing path to api swagger files")
if type(ignore) is not list:
raise Exception("'ignore' should be a list of api names")
# Always ignore pym-config.yaml
ignore.append('pym-config')
# Find all swagger apis under ... | def load_apis(self, path, ignore=[], include_crash_api=False) | Load all swagger files found at the given path, except those whose
names are in the 'ignore' list | 2.680046 | 2.657665 | 1.008421 |
assert path
if not self.apis:
raise Exception("You must call .load_apis() before .publish_apis()")
# Infer the live host url from pym-config.yaml
proto = 'http'
if hasattr(get_config(), 'aws_cert_arn'):
proto = 'https'
live_host = "%s:... | def publish_apis(self, path='doc') | Publish all loaded apis on under the uri /<path>/<api-name>, by
redirecting to http://petstore.swagger.io/ | 2.8498 | 2.741711 | 1.039424 |
# Check arguments
if type(serve) is str:
serve = [serve]
elif type(serve) is list:
pass
else:
raise Exception("'serve' should be an api name or a list of api names")
if len(serve) == 0:
raise Exception("You must specify a... | def start(self, serve=[]) | Load all apis, either as local apis served by the flask app, or as
remote apis to be called from whithin the app's endpoints, then start
the app server | 3.996657 | 3.932806 | 1.016236 |
if not name or not status or not code:
raise Exception("Can't create Exception class %s: you must set both name, status and code" % name)
myexception = type(name, (PyMacaronException, ), {"code": code, "status": status})
globals()[name] = myexception
if code in code_to_class:
raise ... | def add_error(name=None, code=None, status=None) | Create a new Exception class | 4.413546 | 4.031498 | 1.094766 |
assert str(type(error).__name__) == 'Error'
if error.error in code_to_class:
e = code_to_class[error.error](error.error_description)
if error.error_id:
e.error_id = error.error_id
if error.user_message:
e.user_message = error.user_message
return e.htt... | def responsify(error) | Take an Error model and return it as a Flask response | 3.409544 | 3.440305 | 0.991058 |
if hasattr(o, 'error') and hasattr(o, 'error_description') and hasattr(o, 'status'):
return True
return False | def is_error(o) | True if o is an instance of a swagger Error model or a flask Response of
an error model | 3.805404 | 4.023026 | 0.945906 |
if isinstance(e, PyMacaronException):
return e.to_model()
if isinstance(e, PyMacaronCoreException) and e.__class__.__name__ == 'ValidationError':
return ValidationError(str(e)).to_model()
# Turn this exception into a PyMacaron Error model
return UnhandledServerError(str(e)).to_mo... | def format_error(e) | Take an exception caught within pymacaron_core and turn it into a
bravado-core Error instance | 6.198989 | 4.576963 | 1.354389 |
code = e.error
if code in code_to_class:
raise code_to_class[code](e.error_description)
else:
raise InternalServerError(e.error_description) | def raise_error(e) | Take a bravado-core Error model and raise it as an exception | 3.588063 | 3.343827 | 1.073041 |
data = {
'status': self.status,
'error': self.code.upper(),
'error_description': str(self)
}
if self.error_caught:
data['error_caught'] = pformat(self.error_caught)
if self.error_id:
data['error_id'] = self.error_id
... | def http_reply(self) | Return a Flask reply object describing this error | 3.004959 | 2.744479 | 1.094911 |
e = ApiPool().current_server_api.model.Error(
status=self.status,
error=self.code.upper(),
error_description=str(self),
)
if self.error_id:
e.error_id = self.error_id
if self.user_message:
e.user_message = self.user_mes... | def to_model(self) | Return a bravado-core Error instance | 4.377315 | 3.951742 | 1.107692 |
ga.sort(chromosomes)
fitness = [ga.eval_fitness(c) for c in chromosomes]
min_fit = min(fitness)
fit_range = max(fitness) - min_fit
if fit_range == 0:
# all chromosomes have equal chance of being chosen
n = len(chromosomes)
return [i / n for i in range(1, n + 1)... | def compute_fitness_cdf(chromosomes, ga) | Return a list of fitness-weighted cumulative probabilities for a set of chromosomes.
chromosomes: chromosomes to use for fitness-based calculations
ga: ``algorithms.BaseGeneticAlgorithm`` used to obtain fitness values using its ``eval_fitness`` method
return: list of fitness-weighted cumulative... | 3.124834 | 2.985733 | 1.046589 |
assert len(seq) == len(cdf)
rand = random.random()
for i, e in enumerate(seq):
cp = cdf[i]
assert 0 <= cp <= 1
if rand < cp:
return e | def weighted_choice(seq, cdf) | Select a random element from a sequence, given cumulative probabilities of selection.
See ``compute_fitness_cdf`` function for obtaining cumulative probabilities.
seq: sequence to select from
cdf: sequence with 1 cumulative probability value in [0, 1] for each element in ``seq``
return:... | 3.223867 | 3.228055 | 0.998703 |
url_str = self.base_url + path
if dim_key and dim_key in kwargs:
dim_str = self.get_dimensions_url_string(kwargs[dim_key])
kwargs[dim_key] = dim_str
if kwargs:
url_str += '?%s' % parse.urlencode(kwargs, True)
body = self.client.list(
... | def _list(self, path, dim_key=None, **kwargs) | Get a list of metrics. | 3.444565 | 3.328413 | 1.034897 |
maplist = []
with StringIO(mapstr) as infile:
for row in infile:
maplist.append(row.strip())
return maplist | def mapstr_to_list(mapstr) | Convert an ASCII map string with rows to a list of strings, 1 string per row. | 4.001971 | 3.201804 | 1.249911 |
dx = sx - x
dy = sy - y
return math.sqrt(dx ** 2 + dy ** 2) <= r | def sprinkler_reaches_cell(x, y, sx, sy, r) | Return whether a cell is within the radius of the sprinkler.
x: column index of cell
y: row index of cell
sx: column index of sprinkler
sy: row index of sprinkler
r: sprinkler radius | 2.605093 | 3.615263 | 0.720582 |
# convert DNA to represented sprinkler coordinates
sx, sy = self.translator.translate_chromosome(chromosome)
# check for invalid points
penalty = 0
if sx >= self.w:
penalty += self.w * self.h
if sy >= self.h:
penalty += self.w * self.h
... | def eval_fitness(self, chromosome) | Return the number of plants reached by the sprinkler.
Returns a large penalty for sprinkler locations outside the map. | 3.030192 | 2.885137 | 1.050277 |
# convert strings (rows) to lists of characters for easier map editing
maplist = [list(s) for s in self.maplist]
for y, row in enumerate(maplist):
for x, cell in enumerate(row):
if sprinkler_reaches_cell(x, y, sx, sy, self.r):
if cell == ... | def map_sprinkler(self, sx, sy, watered_crop='^', watered_field='_', dry_field=' ', dry_crop='x') | Return a version of the ASCII map showing reached crop cells. | 3.375755 | 3.179224 | 1.061817 |
if request.GET.get('ic-request'):
counter, created = Counter.objects.get_or_create(pk=1)
counter.value += 1
counter.save()
else:
counter, created = Counter.objects.get_or_create(pk=1)
print(counter.value)
context = dict(
value=counter.value,
)
ret... | def index(request, template_name="index.html") | \
The index view, which basically just displays a button and increments
a counter. | 2.585593 | 2.274202 | 1.136923 |
fitness = self.fitness_cache.get(chromosome.dna)
if fitness is None:
fitness = self.eval_fitness(chromosome)
self.fitness_cache[chromosome.dna] = fitness
return fitness | def get_fitness(self, chromosome) | Get the fitness score for a chromosome, using the cached value if available. | 2.711878 | 2.279685 | 1.189584 |
# update overall fitness for this run
self.sort(chromosomes)
min_fit = self.get_fitness(chromosomes[0])
max_fit = self.get_fitness(chromosomes[-1])
if min_fit < self.min_fit_ever:
self.min_fit_ever = min_fit
if max_fit > self.max_fit_ever:
... | def compete(self, chromosomes) | Simulate competition/survival of the fittest.
The fitness of each chromosome is used to calculate a survival probability
based on how it compares to the overall fitness range of the run and the
fitness range of the current generation. The ``abs_fit_weight`` and
``rel_fit_weight... | 3.129188 | 2.966467 | 1.054853 |
assert 0 <= p_crossover <= 1
if not target_size:
target_size = self.orig_pop_size
num_survivors = len(survivors)
# compute reproduction cumulative probabilities
# weakest member gets p=0 but can be crossed-over with
cdf = co... | def reproduce(self, survivors, p_crossover, two_point_crossover=False, target_size=None) | Reproduces the population from a pool of surviving chromosomes
until a target population size is met. Offspring are created
by selecting a survivor. Survivors with higher fitness have a
greater chance to be selected for reproduction.
Genetic crossover events may occur for each o... | 3.814072 | 3.584857 | 1.06394 |
assert 0 <= p_mutate <= 1
for chromosome in chromosomes:
chromosome.mutate(p_mutate) | def mutate(self, chromosomes, p_mutate) | Call every chromosome's ``mutate`` method.
p_mutate: probability of mutation in [0, 1] | 3.231795 | 2.907717 | 1.111454 |
start_time = time.time()
assert 0 <= p_mutate <= 1
assert 0 <= p_crossover <= 1
# these values guaranteed to be replaced in first generation
self.min_fit_ever = 1e999999999
self.max_fit_ever = -1e999999999
self.generation_fitte... | def run(self, generations, p_mutate, p_crossover, elitist=True, two_point_crossover=False,
refresh_after=None, quit_after=None) | Run a standard genetic algorithm simulation for a set number
of generations (iterations), each consisting of the following
ordered steps:
1. competition/survival of the fittest (``compete`` method)
2. reproduction (``reproduce`` method)
3. mutation (``mutate`` me... | 2.665993 | 2.453709 | 1.086516 |
assert issubclass(gene_class, BaseGene)
chromosomes = []
# when gene_length is scalar, convert to a list to keep subsequent code simple
if not hasattr(gene_length, '__iter__'):
gene_length = [gene_length]
for _ in range(n):
genes = [gene_class.c... | def create_random(cls, gene_length, n=1, gene_class=BinaryGene) | Create 1 or more chromosomes with randomly generated DNA.
gene_length: int (or sequence of ints) describing gene DNA length
n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromosome
gene_class: subclass of ``ga.chromosomes.BaseGene`` to use for genes
... | 2.856671 | 2.741691 | 1.041938 |
assert self.length == len(dna)
i = 0
for gene in self.genes:
gene.dna = dna[i:i + gene.length]
i += gene.length | def dna(self, dna) | Replace this chromosome's DNA with new DNA of equal length,
assigning the new DNA to the chromosome's genes sequentially.
For example, if a chromosome contains these genes...
1. 100100
2. 011011
...and the new DNA is 111111000000, the genes become:
... | 3.780675 | 3.392981 | 1.114263 |
assert self.length == chromosome.length
if point2 is None:
new_dna = self.dna[:point1] + chromosome.dna[point1:]
other_new_dna = chromosome.dna[:point1] + self.dna[point1:]
self.dna = new_dna
chromosome.dna = other_new_dna
else:
... | def crossover(self, chromosome, point1, point2=None) | Exchange DNA with another chromosome of equal length at one or two common points.
For example, consider chromosomes:
1. 11110000
2. 00001111
If the crossover point is 4, the exchange results in a new DNA arrangement:
1. 11111111
2. 00000000
... | 1.838618 | 1.734122 | 1.060259 |
assert 0 <= p_mutate <= 1
for gene in self.genes:
gene.mutate(p_mutate) | def mutate(self, p_mutate) | Check all genes in this chromosome for mutation.
p_mutate: probability for mutation to occur | 3.171633 | 3.371398 | 0.940747 |
genes = [g.copy() for g in self.genes]
return type(self)(genes) | def copy(self) | Return a new instance of this chromosome by copying its genes. | 5.733597 | 3.309407 | 1.732515 |
gene_dna_set = set([g.dna for g in self.genes])
assert gene_dna_set == self.dna_choices_set | def check_genes(self) | Assert that every DNA choice is represented by exactly one gene. | 6.860276 | 5.376161 | 1.276055 |
# Don't report errors if NO_ERROR_REPORTING set to 1 (set by run_acceptance_tests)
if os.environ.get('DO_REPORT_ERROR', None):
# Force error reporting
pass
elif os.environ.get('NO_ERROR_REPORTING', '') == '1':
log.info("NO_ERROR_REPORTING is set: not reporting error!")
... | def report_error(title=None, data={}, caught=None, is_fatal=False) | Format a crash report and send it somewhere relevant. There are two
types of crashes: fatal crashes (backend errors) or non-fatal ones (just
reporting a glitch, but the api call did not fail) | 4.196409 | 4.137753 | 1.014176 |
# Did pymacaron_core set a call_id and call_path?
call_id, call_path = '', ''
if hasattr(stack.top, 'call_id'):
call_id = stack.top.call_id
if hasattr(stack.top, 'call_path'):
call_path = stack.top.call_path
# Unique ID associated to all responses associated to a given
# c... | def populate_error_report(data) | Add generic stats to the error report | 2.874407 | 2.874022 | 1.000134 |
url_str = self.base_url
if 'tenant_id' in kwargs:
url_str = url_str + '?tenant_id=%s' % kwargs['tenant_id']
del kwargs['tenant_id']
data = kwargs['jsonbody'] if 'jsonbody' in kwargs else kwargs
body = self.client.create(url=url_str, json=data)
re... | def create(self, **kwargs) | Create a metric. | 3.402823 | 3.313148 | 1.027066 |
'''
Parses the request result and returns the JSON object. Handles all errors.
'''
try:
# return the proper JSON object, or error code if request didn't go through.
self.most_recent_json = response.json()
json_results = response.json()
if r... | def get_json_results(self, response) | Parses the request result and returns the JSON object. Handles all errors. | 3.51422 | 3.228019 | 1.088661 |
'''
Returns a single list containing up to 'limit' Result objects
Will keep requesting until quota is met
Will also truncate extra results to return exactly the given quota
'''
quota_left = quota
results = []
while quota_left > 0:
more_results ... | def search_all(self, quota=50, format='json') | Returns a single list containing up to 'limit' Result objects
Will keep requesting until quota is met
Will also truncate extra results to return exactly the given quota | 4.840281 | 1.984155 | 2.439467 |
'''Reformat parameters into dict of format expected by the API.'''
if not params:
return {}
# expect multiple invocations of --parameters but fall back
# to ; delimited if only one --parameters is specified
if len(params) == 1:
if params[0].find(';') != -1: # found
par... | def format_parameters(params) | Reformat parameters into dict of format expected by the API. | 3.597345 | 3.292366 | 1.092632 |
url_str = self.base_url + '/%s' % kwargs['alarm_id']
resp = self.client.delete(url_str)
return resp | def delete(self, **kwargs) | Delete a specific alarm. | 4.515698 | 3.297559 | 1.369406 |
url_str = self.base_url + '/%s/state-history' % kwargs['alarm_id']
del kwargs['alarm_id']
if kwargs:
url_str = url_str + '?%s' % parse.urlencode(kwargs, True)
resp = self.client.list(url_str)
return resp['elements'] if type(resp) is dict else resp | def history(self, **kwargs) | History of a specific alarm. | 4.21553 | 3.59824 | 1.171553 |
url_str = self.base_url + '/state-history/'
if 'dimensions' in kwargs:
dimstr = self.get_dimensions_url_string(kwargs['dimensions'])
kwargs['dimensions'] = dimstr
if kwargs:
url_str = url_str + '?%s' % parse.urlencode(kwargs, True)
resp = self... | def history_list(self, **kwargs) | History list of alarm state. | 3.789623 | 3.585792 | 1.056844 |
v = ApiPool.ping.model.Version(
name=ApiPool().current_server_name,
version=ApiPool().current_server_api.get_version(),
container=get_container_version(),
)
log.info("/version: " + pprint.pformat(v))
return v | def do_version() | Return version details of the running server api | 9.226583 | 8.104307 | 1.138479 |
'''Create metric.'''
fields = {}
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format_parameters(args.dimensions)
fields['timestamp'] = args.time
fields['value'] = args.value
if args.value_meta:
fields['value_meta'] = utils.format_parameters(args... | def do_metric_create(mc, args) | Create metric. | 2.737671 | 2.789613 | 0.98138 |
'''Create metric from raw json body.'''
try:
mc.metrics.create(**args.jsonbody)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
print('Successfully created metric') | def do_metric_create_raw(mc, args) | Create metric from raw json body. | 5.661487 | 5.743372 | 0.985743 |
'''List names of metrics.'''
fields = {}
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
if args.tenant_id:
fields['tenant_id'] = a... | def do_metric_name_list(mc, args) | List names of metrics. | 2.666991 | 2.668651 | 0.999378 |
'''List metrics for this tenant.'''
fields = {}
if args.name:
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.o... | def do_metric_list(mc, args) | List metrics for this tenant. | 2.393118 | 2.342466 | 1.021623 |
'''List names of metric dimensions.'''
fields = {}
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
if args.tenant_id:
fields['tenant_id'] = args.tenant_id
... | def do_dimension_name_list(mc, args) | List names of metric dimensions. | 2.602111 | 2.56707 | 1.01365 |
'''List names of metric dimensions.'''
fields = {}
fields['dimension_name'] = args.dimension_name
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
if args.tenant_id... | def do_dimension_value_list(mc, args) | List names of metric dimensions. | 2.637657 | 2.593017 | 1.017215 |
'''List measurement statistics for the specified metric.'''
statistic_types = ['AVG', 'MIN', 'MAX', 'COUNT', 'SUM']
statlist = args.statistics.split(',')
for stat in statlist:
if stat.upper() not in statistic_types:
errmsg = ('Invalid type, not one of [' +
', '.... | def do_metric_statistics(mc, args) | List measurement statistics for the specified metric. | 2.345892 | 2.310685 | 1.015237 |
'''Describe the notification.'''
fields = {}
fields['notification_id'] = args.id
try:
notification = mc.notifications.get(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
if args.json:... | def do_notification_show(mc, args) | Describe the notification. | 3.139399 | 3.062311 | 1.025173 |
'''List notifications for this tenant.'''
fields = {}
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
if args.sort_by:
sort_by = args.sort_by.split(',')
for field in sort_by:
field_values = field.lower().split()
... | def do_notification_list(mc, args) | List notifications for this tenant. | 2.269768 | 2.271528 | 0.999225 |
'''Delete notification.'''
fields = {}
fields['notification_id'] = args.id
try:
mc.notifications.delete(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
print('Successfully deleted not... | def do_notification_delete(mc, args) | Delete notification. | 4.204732 | 4.478261 | 0.938921 |
'''Update notification.'''
fields = {}
fields['notification_id'] = args.id
fields['name'] = args.name
fields['type'] = args.type
fields['address'] = args.address
if not _validate_notification_period(args.period, args.type.upper()):
return
fields['period'] = args.period
try:
... | def do_notification_update(mc, args) | Update notification. | 3.66185 | 3.745104 | 0.97777 |
'''Create an alarm definition.'''
fields = {}
fields['name'] = args.name
if args.description:
fields['description'] = args.description
fields['expression'] = args.expression
if args.alarm_actions:
fields['alarm_actions'] = args.alarm_actions
if args.ok_actions:
fields... | def do_alarm_definition_create(mc, args) | Create an alarm definition. | 2.012232 | 2.102805 | 0.956928 |
'''List alarm definitions for this tenant.'''
fields = {}
if args.name:
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.severity:
if not _validate_severity(args.severity):
return
... | def do_alarm_definition_list(mc, args) | List alarm definitions for this tenant. | 2.237218 | 2.243517 | 0.997192 |
'''Delete the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
try:
mc.alarm_definitions.delete(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
print('Successfully delete... | def do_alarm_definition_delete(mc, args) | Delete the alarm definition. | 4.110177 | 4.427707 | 0.928286 |
'''Update the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
fields['name'] = args.name
fields['description'] = args.description
fields['expression'] = args.expression
fields['alarm_actions'] = _arg_split_patch_update(args.alarm_actions)
fields['ok_actions'] = _arg_split_p... | def do_alarm_definition_update(mc, args) | Update the alarm definition. | 2.553672 | 2.60853 | 0.97897 |
'''Patch the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
if args.name:
fields['name'] = args.name
if args.description:
fields['description'] = args.description
if args.expression:
fields['expression'] = args.expression
if args.alarm_actions:
... | def do_alarm_definition_patch(mc, args) | Patch the alarm definition. | 2.367432 | 2.407897 | 0.983195 |
'''List alarms for this tenant.'''
fields = {}
if args.alarm_definition_id:
fields['alarm_definition_id'] = args.alarm_definition_id
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.metric_dimensions:
fields['metric_dimensions'] = utils.format_dimensions_... | def do_alarm_list(mc, args) | List alarms for this tenant. | 1.895365 | 1.88943 | 1.003141 |
'''Describe the alarm.'''
fields = {}
fields['alarm_id'] = args.id
try:
alarm = mc.alarms.get(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
if args.json:
print(utils.jso... | def do_alarm_show(mc, args) | Describe the alarm. | 3.463572 | 3.445838 | 1.005146 |
'''Update the alarm state.'''
fields = {}
fields['alarm_id'] = args.id
if args.state.upper() not in state_types:
errmsg = ('Invalid state, not one of [' +
', '.join(state_types) + ']')
print(errmsg)
return
fields['state'] = args.state
fie... | def do_alarm_update(mc, args) | Update the alarm state. | 3.565914 | 3.657654 | 0.974918 |
'''Delete the alarm.'''
fields = {}
fields['alarm_id'] = args.id
try:
mc.alarms.delete(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
print('Successfully deleted alarm') | def do_alarm_delete(mc, args) | Delete the alarm. | 4.102488 | 4.396788 | 0.933065 |
'''Count alarms.'''
fields = {}
if args.alarm_definition_id:
fields['alarm_definition_id'] = args.alarm_definition_id
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.metric_dimensions:
fields['metric_dimensions'] = utils.format_dimensions_query(args.metr... | def do_alarm_count(mc, args) | Count alarms. | 2.228163 | 2.230428 | 0.998985 |
'''Alarm state transition history.'''
fields = {}
fields['alarm_id'] = args.id
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
try:
alarm = mc.alarms.history(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
... | def do_alarm_history(mc, args) | Alarm state transition history. | 3.538407 | 3.477921 | 1.017391 |
'''List alarms state history.'''
fields = {}
if args.dimensions:
fields['dimensions'] = utils.format_parameters(args.dimensions)
if args.starttime:
_translate_starttime(args)
fields['start_time'] = args.starttime
if args.endtime:
fields['end_time'] = args.endtime
... | def do_alarm_history_list(mc, args) | List alarms state history. | 3.02456 | 2.987988 | 1.01224 |
'''List notification types supported by monasca.'''
try:
notification_types = mc.notificationtypes.list()
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
if args.json:
print(utils.json_for... | def do_notification_type_list(mc, args) | List notification types supported by monasca. | 3.459196 | 3.281495 | 1.054152 |
@wraps(f)
def requires_auth_decorator(*args, **kwargs):
try:
authenticate_http_request()
except PyMacaronException as e:
return e.http_reply()
return f(*args, **kwargs)
return requires_auth_decorator | def requires_auth(f) | A decorator for flask api methods that validates auth0 tokens, hence ensuring
that the user is authenticated. Code coped from:
https://github.com/auth0/auth0-python/tree/master/examples/flask-api | 4.747804 | 4.580714 | 1.036477 |
def add_auth_decorator(*args, **kwargs):
token = get_user_token()
if 'headers' not in kwargs:
kwargs['headers'] = {}
kwargs['headers']['Authorization'] = "Bearer %s" % token
return f(*args, **kwargs)
return add_auth_decorator | def add_auth(f) | A decorator that adds the authentication header to requests arguments | 2.624234 | 2.386258 | 1.099728 |
assert get_config().jwt_secret, "No JWT secret configured for pymacaron"
assert get_config().jwt_issuer, "No JWT issuer configured for pymacaron"
assert get_config().jwt_audience, "No JWT audience configured for pymacaron"
log.info("Validating token, using issuer:%s, audience:%s, secret:%s***" % ... | def load_auth_token(token, load=True) | Validate an auth0 token. Returns the token's payload, or an exception
of the type: | 2.814744 | 2.873864 | 0.979428 |
if token:
auth = token
else:
auth = request.headers.get('Authorization', None)
if not auth:
auth = request.cookies.get('token', None)
if auth:
auth = unquote_plus(auth)
log.debug("Validating Auth header [%s]" % auth)
if not auth:
raise Aut... | def authenticate_http_request(token=None) | Validate auth0 tokens passed in the request's header, hence ensuring
that the user is authenticated. Code copied from:
https://github.com/auth0/auth0-python/tree/master/examples/flask-api
Return a PntCommonException if failed to validate authentication.
Otherwise, return the token's payload (Also store... | 2.485782 | 2.481123 | 1.001878 |
assert user_id, "No user_id passed to generate_token()"
assert isinstance(data, dict), "generate_token(data=) should be a dictionary"
assert get_config().jwt_secret, "No JWT secret configured in pymacaron"
if not issuer:
issuer = get_config().jwt_issuer
assert issuer, "No JWT issuer c... | def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None) | Generate a new JWT token for this user_id. Default expiration date
is 1 year from creation time | 2.765407 | 2.813454 | 0.982922 |
if not hasattr(stack.top, 'current_user'):
return ''
current_user = stack.top.current_user
return current_user.get('token', '') | def get_user_token() | Return the authenticated user's auth token | 4.339983 | 4.165375 | 1.041919 |
try:
current_user = stack.top.current_user
return current_user.get('iss', get_config().jwt_issuer)
except Exception:
pass
return get_config().jwt_issuer | def get_token_issuer() | Return the issuer in which this user's token was created | 5.190298 | 5.171706 | 1.003595 |
'''
Returns a list of result objects, with the url for the next page MsCognitive search url.
'''
limit = min(limit, self.MAX_SEARCH_PER_QUERY)
payload = {
'q' : self.query,
'count' : limit, #currently 50 is max per search.
'offset': self.current_offs... | def _search(self, limit, format) | Returns a list of result objects, with the url for the next page MsCognitive search url. | 5.004123 | 3.697093 | 1.353529 |
body = self.client.create(url=self.base_url,
json=kwargs)
return body | def create(self, **kwargs) | Create a notification. | 7.326129 | 7.179703 | 1.020394 |
# NOTE(trebskit) should actually be find_one, but
# monasca does not support expected response format
url = '%s/%s' % (self.base_url, kwargs['notification_id'])
resp = self.client.list(path=url)
return resp | def get(self, **kwargs) | Get the details for a specific notification. | 10.4008 | 9.292778 | 1.119235 |
url = self.base_url + '/%s' % kwargs['notification_id']
resp = self.client.delete(url=url)
return resp | def delete(self, **kwargs) | Delete a notification. | 4.328597 | 3.184176 | 1.359409 |
resp = self.client.create(url=self.base_url,
json=kwargs)
return resp | def create(self, **kwargs) | Create an alarm definition. | 5.904532 | 5.210533 | 1.133192 |
url_str = self.base_url + '/%s' % kwargs['alarm_id']
del kwargs['alarm_id']
resp = self.client.create(url=url_str,
method='PUT',
json=kwargs)
return resp | def update(self, **kwargs) | Update a specific alarm definition. | 5.059439 | 3.857611 | 1.311547 |
y_vals = []
for x in range(1, num_x + 1):
y = sum([c * x ** i for i, c in enumerate(coefficients[::-1])])
y_vals.append(y)
return y_vals | def compute_y(self, coefficients, num_x) | Return calculated y-values for the domain of x-values in [1, num_x]. | 2.513303 | 2.263386 | 1.110417 |
error = 0
for modeled, expected in zip(solution_y, self.expected_values):
error += abs(modeled - expected)
if any([c < 0 for c in coefficients]):
error *= 1.5
return error | def compute_err(self, solution_y, coefficients) | Return an error value by finding the absolute difference for each
element in a list of solution-generated y-values versus expected values.
Compounds error by 50% for each negative coefficient in the solution.
solution_y: list of y-values produced by a solution
coefficients: list of p... | 4.658242 | 4.049188 | 1.150414 |
coefficients = self.translator.translate_chromosome(chromosome)
solution_y = self.compute_y(coefficients, self.num_x)
fitness = -1 * self.compute_err(solution_y, coefficients)
return fitness | def eval_fitness(self, chromosome) | Evaluate the polynomial equation using coefficients represented by a
solution/chromosome, returning its error as the solution's fitness.
return: fitness value | 6.768581 | 6.512247 | 1.039362 |
click.echo("Read configuration from %s" % ip)
request = requests.get(
'http://{}/{}/{}/'.format(ip, URI, mac), timeout=TIMEOUT)
print(request.json()) | def read_config(ip, mac) | Read the current configuration of a myStrom device. | 6.022268 | 5.832089 | 1.032609 |
click.echo("Write configuration to device %s" % ip)
data = {
'single': single,
'double': double,
'long': long,
'touch': touch,
}
request = requests.post(
'http://{}/{}/{}/'.format(ip, URI, mac), data=data, timeout=TIMEOUT)
if request.status_code == 200:
... | def write_config(ip, mac, single, double, long, touch) | Write the current configuration of a myStrom button. | 2.994429 | 3.075883 | 0.973518 |
click.echo("Write configuration for Home Assistant to device %s..." % ip)
action = "get://{1}:{2}/api/mystrom?{0}={3}"
data = {
'single': action.format('single', hass, port, id),
'double': action.format('double', hass, port, id),
'long': action.format('long', hass, port, id),... | def write_ha_config(ip, mac, hass, port, id) | Write the configuration for Home Assistant to a myStrom button. | 5.66156 | 5.022772 | 1.127178 |
click.echo("Reset configuration of button %s..." % ip)
data = {
'single': "",
'double': "",
'long': "",
'touch': "",
}
request = requests.post(
'http://{}/{}/{}/'.format(ip, URI, mac), data=data, timeout=TIMEOUT)
if request.status_code == 200:
cl... | def reset_config(ip, mac) | Reset the current configuration of a myStrom WiFi Button. | 4.631117 | 4.365462 | 1.060854 |
bulb = MyStromBulb(ip, mac)
bulb.set_color_hsv(hue, saturation, value) | def color(ip, mac, hue, saturation, value) | Switch the bulb on with the given color. | 4.650482 | 4.586259 | 1.014003 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.