repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
mdscruggs/ga | ga/examples/irrigation.py | IrrigationGA.eval_fitness | def eval_fitness(self, chromosome):
"""
Return the number of plants reached by the sprinkler.
Returns a large penalty for sprinkler locations outside the map.
"""
# convert DNA to represented sprinkler coordinates
sx, sy = self.translator.translate_chromosome(chromosome)... | python | def eval_fitness(self, chromosome):
"""
Return the number of plants reached by the sprinkler.
Returns a large penalty for sprinkler locations outside the map.
"""
# convert DNA to represented sprinkler coordinates
sx, sy = self.translator.translate_chromosome(chromosome)... | [
"def",
"eval_fitness",
"(",
"self",
",",
"chromosome",
")",
":",
"# convert DNA to represented sprinkler coordinates",
"sx",
",",
"sy",
"=",
"self",
".",
"translator",
".",
"translate_chromosome",
"(",
"chromosome",
")",
"# check for invalid points",
"penalty",
"=",
"... | Return the number of plants reached by the sprinkler.
Returns a large penalty for sprinkler locations outside the map. | [
"Return",
"the",
"number",
"of",
"plants",
"reached",
"by",
"the",
"sprinkler",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/irrigation.py#L118-L158 |
mdscruggs/ga | ga/examples/irrigation.py | IrrigationGA.map_sprinkler | 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.
"""
# convert strings (rows) to lists of characters for easier map editing
maplist = [list(s) for s in self.maplist... | python | 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.
"""
# convert strings (rows) to lists of characters for easier map editing
maplist = [list(s) for s in self.maplist... | [
"def",
"map_sprinkler",
"(",
"self",
",",
"sx",
",",
"sy",
",",
"watered_crop",
"=",
"'^'",
",",
"watered_field",
"=",
"'_'",
",",
"dry_field",
"=",
"' '",
",",
"dry_crop",
"=",
"'x'",
")",
":",
"# convert strings (rows) to lists of characters for easier map editi... | Return a version of the ASCII map showing reached crop cells. | [
"Return",
"a",
"version",
"of",
"the",
"ASCII",
"map",
"showing",
"reached",
"crop",
"cells",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/irrigation.py#L160-L181 |
brejoc/django-intercoolerjs | demo/counter/views.py | index | def index(request, template_name="index.html"):
"""\
The index view, which basically just displays a button and increments
a counter.
"""
if request.GET.get('ic-request'):
counter, created = Counter.objects.get_or_create(pk=1)
counter.value += 1
counter.save()
else:
... | python | def index(request, template_name="index.html"):
"""\
The index view, which basically just displays a button and increments
a counter.
"""
if request.GET.get('ic-request'):
counter, created = Counter.objects.get_or_create(pk=1)
counter.value += 1
counter.save()
else:
... | [
"def",
"index",
"(",
"request",
",",
"template_name",
"=",
"\"index.html\"",
")",
":",
"if",
"request",
".",
"GET",
".",
"get",
"(",
"'ic-request'",
")",
":",
"counter",
",",
"created",
"=",
"Counter",
".",
"objects",
".",
"get_or_create",
"(",
"pk",
"="... | \
The index view, which basically just displays a button and increments
a counter. | [
"\\",
"The",
"index",
"view",
"which",
"basically",
"just",
"displays",
"a",
"button",
"and",
"increments",
"a",
"counter",
"."
] | train | https://github.com/brejoc/django-intercoolerjs/blob/cc92b914204bfcb9eae3dc658e2063dff67636fc/demo/counter/views.py#L6-L21 |
mdscruggs/ga | ga/algorithms.py | BaseGeneticAlgorithm.get_fitness | def get_fitness(self, chromosome):
""" Get the fitness score for a chromosome, using the cached value if available. """
fitness = self.fitness_cache.get(chromosome.dna)
if fitness is None:
fitness = self.eval_fitness(chromosome)
self.fitness_cache[chromosome.dna] = fitne... | python | def get_fitness(self, chromosome):
""" Get the fitness score for a chromosome, using the cached value if available. """
fitness = self.fitness_cache.get(chromosome.dna)
if fitness is None:
fitness = self.eval_fitness(chromosome)
self.fitness_cache[chromosome.dna] = fitne... | [
"def",
"get_fitness",
"(",
"self",
",",
"chromosome",
")",
":",
"fitness",
"=",
"self",
".",
"fitness_cache",
".",
"get",
"(",
"chromosome",
".",
"dna",
")",
"if",
"fitness",
"is",
"None",
":",
"fitness",
"=",
"self",
".",
"eval_fitness",
"(",
"chromosom... | Get the fitness score for a chromosome, using the cached value if available. | [
"Get",
"the",
"fitness",
"score",
"for",
"a",
"chromosome",
"using",
"the",
"cached",
"value",
"if",
"available",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/algorithms.py#L77-L85 |
mdscruggs/ga | ga/algorithms.py | BaseGeneticAlgorithm.compete | 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. ... | python | 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. ... | [
"def",
"compete",
"(",
"self",
",",
"chromosomes",
")",
":",
"# update overall fitness for this run",
"self",
".",
"sort",
"(",
"chromosomes",
")",
"min_fit",
"=",
"self",
".",
"get_fitness",
"(",
"chromosomes",
"[",
"0",
"]",
")",
"max_fit",
"=",
"self",
".... | 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... | [
"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",
... | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/algorithms.py#L103-L147 |
mdscruggs/ga | ga/algorithms.py | BaseGeneticAlgorithm.reproduce | 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
... | python | 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
... | [
"def",
"reproduce",
"(",
"self",
",",
"survivors",
",",
"p_crossover",
",",
"two_point_crossover",
"=",
"False",
",",
"target_size",
"=",
"None",
")",
":",
"assert",
"0",
"<=",
"p_crossover",
"<=",
"1",
"if",
"not",
"target_size",
":",
"target_size",
"=",
... | 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... | [
"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",
"fi... | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/algorithms.py#L149-L197 |
mdscruggs/ga | ga/algorithms.py | BaseGeneticAlgorithm.mutate | def mutate(self, chromosomes, p_mutate):
"""
Call every chromosome's ``mutate`` method.
p_mutate: probability of mutation in [0, 1]
"""
assert 0 <= p_mutate <= 1
for chromosome in chromosomes:
chromosome.mutate(p_mutate) | python | def mutate(self, chromosomes, p_mutate):
"""
Call every chromosome's ``mutate`` method.
p_mutate: probability of mutation in [0, 1]
"""
assert 0 <= p_mutate <= 1
for chromosome in chromosomes:
chromosome.mutate(p_mutate) | [
"def",
"mutate",
"(",
"self",
",",
"chromosomes",
",",
"p_mutate",
")",
":",
"assert",
"0",
"<=",
"p_mutate",
"<=",
"1",
"for",
"chromosome",
"in",
"chromosomes",
":",
"chromosome",
".",
"mutate",
"(",
"p_mutate",
")"
] | Call every chromosome's ``mutate`` method.
p_mutate: probability of mutation in [0, 1] | [
"Call",
"every",
"chromosome",
"s",
"mutate",
"method",
".",
"p_mutate",
":",
"probability",
"of",
"mutation",
"in",
"[",
"0",
"1",
"]"
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/algorithms.py#L199-L208 |
mdscruggs/ga | ga/algorithms.py | BaseGeneticAlgorithm.run | 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:
... | python | 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:
... | [
"def",
"run",
"(",
"self",
",",
"generations",
",",
"p_mutate",
",",
"p_crossover",
",",
"elitist",
"=",
"True",
",",
"two_point_crossover",
"=",
"False",
",",
"refresh_after",
"=",
"None",
",",
"quit_after",
"=",
"None",
")",
":",
"start_time",
"=",
"time... | 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... | [
"Run",
"a",
"standard",
"genetic",
"algorithm",
"simulation",
"for",
"a",
"set",
"number",
"of",
"generations",
"(",
"iterations",
")",
"each",
"consisting",
"of",
"the",
"following",
"ordered",
"steps",
":",
"1",
".",
"competition",
"/",
"survival",
"of",
"... | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/algorithms.py#L219-L306 |
mdscruggs/ga | ga/chromosomes.py | Chromosome.create_random | 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 chromos... | python | 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 chromos... | [
"def",
"create_random",
"(",
"cls",
",",
"gene_length",
",",
"n",
"=",
"1",
",",
"gene_class",
"=",
"BinaryGene",
")",
":",
"assert",
"issubclass",
"(",
"gene_class",
",",
"BaseGene",
")",
"chromosomes",
"=",
"[",
"]",
"# when gene_length is scalar, convert to a... | 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
... | [
"Create",
"1",
"or",
"more",
"chromosomes",
"with",
"randomly",
"generated",
"DNA",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/chromosomes.py#L12-L36 |
mdscruggs/ga | ga/chromosomes.py | Chromosome.dna | 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... | python | 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... | [
"def",
"dna",
"(",
"self",
",",
"dna",
")",
":",
"assert",
"self",
".",
"length",
"==",
"len",
"(",
"dna",
")",
"i",
"=",
"0",
"for",
"gene",
"in",
"self",
".",
"genes",
":",
"gene",
".",
"dna",
"=",
"dna",
"[",
"i",
":",
"i",
"+",
"gene",
... | 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:
... | [
"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... | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/chromosomes.py#L53-L72 |
mdscruggs/ga | ga/chromosomes.py | Chromosome.crossover | 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... | python | 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... | [
"def",
"crossover",
"(",
"self",
",",
"chromosome",
",",
"point1",
",",
"point2",
"=",
"None",
")",
":",
"assert",
"self",
".",
"length",
"==",
"chromosome",
".",
"length",
"if",
"point2",
"is",
"None",
":",
"new_dna",
"=",
"self",
".",
"dna",
"[",
"... | 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
... | [
"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",
... | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/chromosomes.py#L79-L114 |
mdscruggs/ga | ga/chromosomes.py | Chromosome.mutate | def mutate(self, p_mutate):
"""
Check all genes in this chromosome for mutation.
p_mutate: probability for mutation to occur
"""
assert 0 <= p_mutate <= 1
for gene in self.genes:
gene.mutate(p_mutate) | python | def mutate(self, p_mutate):
"""
Check all genes in this chromosome for mutation.
p_mutate: probability for mutation to occur
"""
assert 0 <= p_mutate <= 1
for gene in self.genes:
gene.mutate(p_mutate) | [
"def",
"mutate",
"(",
"self",
",",
"p_mutate",
")",
":",
"assert",
"0",
"<=",
"p_mutate",
"<=",
"1",
"for",
"gene",
"in",
"self",
".",
"genes",
":",
"gene",
".",
"mutate",
"(",
"p_mutate",
")"
] | Check all genes in this chromosome for mutation.
p_mutate: probability for mutation to occur | [
"Check",
"all",
"genes",
"in",
"this",
"chromosome",
"for",
"mutation",
".",
"p_mutate",
":",
"probability",
"for",
"mutation",
"to",
"occur"
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/chromosomes.py#L116-L125 |
mdscruggs/ga | ga/chromosomes.py | Chromosome.copy | def copy(self):
""" Return a new instance of this chromosome by copying its genes. """
genes = [g.copy() for g in self.genes]
return type(self)(genes) | python | def copy(self):
""" Return a new instance of this chromosome by copying its genes. """
genes = [g.copy() for g in self.genes]
return type(self)(genes) | [
"def",
"copy",
"(",
"self",
")",
":",
"genes",
"=",
"[",
"g",
".",
"copy",
"(",
")",
"for",
"g",
"in",
"self",
".",
"genes",
"]",
"return",
"type",
"(",
"self",
")",
"(",
"genes",
")"
] | Return a new instance of this chromosome by copying its genes. | [
"Return",
"a",
"new",
"instance",
"of",
"this",
"chromosome",
"by",
"copying",
"its",
"genes",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/chromosomes.py#L127-L130 |
mdscruggs/ga | ga/chromosomes.py | ReorderingSetChromosome.check_genes | def check_genes(self):
""" Assert that every DNA choice is represented by exactly one gene. """
gene_dna_set = set([g.dna for g in self.genes])
assert gene_dna_set == self.dna_choices_set | python | def check_genes(self):
""" Assert that every DNA choice is represented by exactly one gene. """
gene_dna_set = set([g.dna for g in self.genes])
assert gene_dna_set == self.dna_choices_set | [
"def",
"check_genes",
"(",
"self",
")",
":",
"gene_dna_set",
"=",
"set",
"(",
"[",
"g",
".",
"dna",
"for",
"g",
"in",
"self",
".",
"genes",
"]",
")",
"assert",
"gene_dna_set",
"==",
"self",
".",
"dna_choices_set"
] | Assert that every DNA choice is represented by exactly one gene. | [
"Assert",
"that",
"every",
"DNA",
"choice",
"is",
"represented",
"by",
"exactly",
"one",
"gene",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/chromosomes.py#L160-L163 |
pymacaron/pymacaron | pymacaron/crash.py | report_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)"""
# Don't report errors if NO_ERROR_REP... | python | 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)"""
# Don't report errors if NO_ERROR_REP... | [
"def",
"report_error",
"(",
"title",
"=",
"None",
",",
"data",
"=",
"{",
"}",
",",
"caught",
"=",
"None",
",",
"is_fatal",
"=",
"False",
")",
":",
"# Don't report errors if NO_ERROR_REPORTING set to 1 (set by run_acceptance_tests)",
"if",
"os",
".",
"environ",
"."... | 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) | [
"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"... | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/crash.py#L50-L123 |
pymacaron/pymacaron | pymacaron/crash.py | populate_error_report | def populate_error_report(data):
"""Add generic stats to the error report"""
# 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_pat... | python | def populate_error_report(data):
"""Add generic stats to the error report"""
# 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_pat... | [
"def",
"populate_error_report",
"(",
"data",
")",
":",
"# Did pymacaron_core set a call_id and call_path?",
"call_id",
",",
"call_path",
"=",
"''",
",",
"''",
"if",
"hasattr",
"(",
"stack",
".",
"top",
",",
"'call_id'",
")",
":",
"call_id",
"=",
"stack",
".",
... | Add generic stats to the error report | [
"Add",
"generic",
"stats",
"to",
"the",
"error",
"report"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/crash.py#L126-L196 |
pymacaron/pymacaron | pymacaron/crash.py | generate_crash_handler_decorator | def generate_crash_handler_decorator(error_decorator=None):
"""Return the crash_handler to pass to pymacaron_core, with optional error decoration"""
def crash_handler(f):
"""Return a decorator that reports failed api calls via the error_reporter,
for use on every server endpoint"""
@wr... | python | def generate_crash_handler_decorator(error_decorator=None):
"""Return the crash_handler to pass to pymacaron_core, with optional error decoration"""
def crash_handler(f):
"""Return a decorator that reports failed api calls via the error_reporter,
for use on every server endpoint"""
@wr... | [
"def",
"generate_crash_handler_decorator",
"(",
"error_decorator",
"=",
"None",
")",
":",
"def",
"crash_handler",
"(",
"f",
")",
":",
"\"\"\"Return a decorator that reports failed api calls via the error_reporter,\n for use on every server endpoint\"\"\"",
"@",
"wraps",
"(",... | Return the crash_handler to pass to pymacaron_core, with optional error decoration | [
"Return",
"the",
"crash_handler",
"to",
"pass",
"to",
"pymacaron_core",
"with",
"optional",
"error",
"decoration"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/crash.py#L199-L367 |
openstack/python-monascaclient | monascaclient/v2_0/metrics.py | MetricsManager.create | def create(self, **kwargs):
"""Create a metric."""
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 = sel... | python | def create(self, **kwargs):
"""Create a metric."""
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 = sel... | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"url_str",
"=",
"self",
".",
"base_url",
"if",
"'tenant_id'",
"in",
"kwargs",
":",
"url_str",
"=",
"url_str",
"+",
"'?tenant_id=%s'",
"%",
"kwargs",
"[",
"'tenant_id'",
"]",
"del",
"kwargs"... | Create a metric. | [
"Create",
"a",
"metric",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/metrics.py#L23-L32 |
tristantao/py-ms-cognitive | py_ms_cognitive/py_ms_cognitive_search/py_ms_cognitive_search.py | PyMsCognitiveSearch.get_json_results | def get_json_results(self, response):
'''
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_resu... | python | def get_json_results(self, response):
'''
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_resu... | [
"def",
"get_json_results",
"(",
"self",
",",
"response",
")",
":",
"try",
":",
"# return the proper JSON object, or error code if request didn't go through.",
"self",
".",
"most_recent_json",
"=",
"response",
".",
"json",
"(",
")",
"json_results",
"=",
"response",
".",
... | Parses the request result and returns the JSON object. Handles all errors. | [
"Parses",
"the",
"request",
"result",
"and",
"returns",
"the",
"JSON",
"object",
".",
"Handles",
"all",
"errors",
"."
] | train | https://github.com/tristantao/py-ms-cognitive/blob/8f4b10df1b4bf1f2c9af64218cfcdc35176b75e7/py_ms_cognitive/py_ms_cognitive_search/py_ms_cognitive_search.py#L38-L67 |
tristantao/py-ms-cognitive | py_ms_cognitive/py_ms_cognitive_search/py_ms_cognitive_search.py | PyMsCognitiveSearch.search_all | 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
'''
quota_left = quota
results = []
... | python | 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
'''
quota_left = quota
results = []
... | [
"def",
"search_all",
"(",
"self",
",",
"quota",
"=",
"50",
",",
"format",
"=",
"'json'",
")",
":",
"quota_left",
"=",
"quota",
"results",
"=",
"[",
"]",
"while",
"quota_left",
">",
"0",
":",
"more_results",
"=",
"self",
".",
"_search",
"(",
"quota_left... | 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 | [
"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"
] | train | https://github.com/tristantao/py-ms-cognitive/blob/8f4b10df1b4bf1f2c9af64218cfcdc35176b75e7/py_ms_cognitive/py_ms_cognitive_search/py_ms_cognitive_search.py#L73-L89 |
openstack/python-monascaclient | monascaclient/common/utils.py | format_parameters | def format_parameters(params):
'''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(';') ... | python | def format_parameters(params):
'''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(';') ... | [
"def",
"format_parameters",
"(",
"params",
")",
":",
"if",
"not",
"params",
":",
"return",
"{",
"}",
"# expect multiple invocations of --parameters but fall back",
"# to ; delimited if only one --parameters is specified",
"if",
"len",
"(",
"params",
")",
"==",
"1",
":",
... | Reformat parameters into dict of format expected by the API. | [
"Reformat",
"parameters",
"into",
"dict",
"of",
"format",
"expected",
"by",
"the",
"API",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/common/utils.py#L91-L121 |
openstack/python-monascaclient | monascaclient/v2_0/alarms.py | AlarmsManager.delete | def delete(self, **kwargs):
"""Delete a specific alarm."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
resp = self.client.delete(url_str)
return resp | python | def delete(self, **kwargs):
"""Delete a specific alarm."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
resp = self.client.delete(url_str)
return resp | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"url_str",
"=",
"self",
".",
"base_url",
"+",
"'/%s'",
"%",
"kwargs",
"[",
"'alarm_id'",
"]",
"resp",
"=",
"self",
".",
"client",
".",
"delete",
"(",
"url_str",
")",
"return",
"resp"
] | Delete a specific alarm. | [
"Delete",
"a",
"specific",
"alarm",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/alarms.py#L39-L43 |
openstack/python-monascaclient | monascaclient/v2_0/alarms.py | AlarmsManager.history | def history(self, **kwargs):
"""History of a specific alarm."""
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)
retu... | python | def history(self, **kwargs):
"""History of a specific alarm."""
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)
retu... | [
"def",
"history",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"url_str",
"=",
"self",
".",
"base_url",
"+",
"'/%s/state-history'",
"%",
"kwargs",
"[",
"'alarm_id'",
"]",
"del",
"kwargs",
"[",
"'alarm_id'",
"]",
"if",
"kwargs",
":",
"url_str",
"=",
... | History of a specific alarm. | [
"History",
"of",
"a",
"specific",
"alarm",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/alarms.py#L79-L86 |
openstack/python-monascaclient | monascaclient/v2_0/alarms.py | AlarmsManager.history_list | def history_list(self, **kwargs):
"""History list of alarm state."""
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 =... | python | def history_list(self, **kwargs):
"""History list of alarm state."""
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 =... | [
"def",
"history_list",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"url_str",
"=",
"self",
".",
"base_url",
"+",
"'/state-history/'",
"if",
"'dimensions'",
"in",
"kwargs",
":",
"dimstr",
"=",
"self",
".",
"get_dimensions_url_string",
"(",
"kwargs",
"[",
... | History list of alarm state. | [
"History",
"list",
"of",
"alarm",
"state",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/alarms.py#L88-L97 |
pymacaron/pymacaron | pymacaron/api.py | do_version | def do_version():
"""Return version details of the running server api"""
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))
ret... | python | def do_version():
"""Return version details of the running server api"""
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))
ret... | [
"def",
"do_version",
"(",
")",
":",
"v",
"=",
"ApiPool",
".",
"ping",
".",
"model",
".",
"Version",
"(",
"name",
"=",
"ApiPool",
"(",
")",
".",
"current_server_name",
",",
"version",
"=",
"ApiPool",
"(",
")",
".",
"current_server_api",
".",
"get_version"... | Return version details of the running server api | [
"Return",
"version",
"details",
"of",
"the",
"running",
"server",
"api"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/api.py#L27-L35 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_metric_create | def do_metric_create(mc, args):
'''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'... | python | def do_metric_create(mc, args):
'''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'... | [
"def",
"do_metric_create",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"if",
"args",
".",
"dimensions",
":",
"fields",
"[",
"'dimensions'",
"]",
"=",
"utils",
".",
"format_parameter... | Create metric. | [
"Create",
"metric",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L72-L89 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_metric_create_raw | def do_metric_create_raw(mc, args):
'''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') | python | def do_metric_create_raw(mc, args):
'''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",
")",
":",
"try",
":",
"mc",
".",
"metrics",
".",
"create",
"(",
"*",
"*",
"args",
".",
"jsonbody",
")",
"except",
"(",
"osc_exc",
".",
"ClientException",
",",
"k_exc",
".",
"HttpError",
")",
"as",
... | Create metric from raw json body. | [
"Create",
"metric",
"from",
"raw",
"json",
"body",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L95-L102 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_metric_name_list | def do_metric_name_list(mc, args):
'''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_... | python | def do_metric_name_list(mc, args):
'''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_... | [
"def",
"do_metric_name_list",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"if",
"args",
".",
"dimensions",
":",
"fields",
"[",
"'dimensions'",
"]",
"=",
"utils",
".",
"format_dimensions_query",
"(",
"args",
".",
"dimensions",
")",
"if",
"a... | List names of metrics. | [
"List",
"names",
"of",
"metrics",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L119-L140 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_metric_list | def do_metric_list(mc, args):
'''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:
... | python | def do_metric_list(mc, args):
'''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:
... | [
"def",
"do_metric_list",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"if",
"args",
".",
"name",
":",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"if",
"args",
".",
"dimensions",
":",
"fields",
"[",
"'dimensions'",
"]",
"=... | List metrics for this tenant. | [
"List",
"metrics",
"for",
"this",
"tenant",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L164-L206 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_dimension_name_list | def do_dimension_name_list(mc, args):
'''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:
fie... | python | def do_dimension_name_list(mc, args):
'''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:
fie... | [
"def",
"do_dimension_name_list",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"if",
"args",
".",
"metric_name",
":",
"fields",
"[",
"'metric_name'",
"]",
"=",
"args",
".",
"metric_name",
"if",
"args",
".",
"limit",
":",
"fields",
"[",
"'l... | List names of metric dimensions. | [
"List",
"names",
"of",
"metric",
"dimensions",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L220-L243 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_dimension_value_list | def do_dimension_value_list(mc, args):
'''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['offse... | python | def do_dimension_value_list(mc, args):
'''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['offse... | [
"def",
"do_dimension_value_list",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'dimension_name'",
"]",
"=",
"args",
".",
"dimension_name",
"if",
"args",
".",
"metric_name",
":",
"fields",
"[",
"'metric_name'",
"]",
"=",
"args"... | List names of metric dimensions. | [
"List",
"names",
"of",
"metric",
"dimensions",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L259-L283 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_metric_statistics | def do_metric_statistics(mc, args):
'''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... | python | def do_metric_statistics(mc, args):
'''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... | [
"def",
"do_metric_statistics",
"(",
"mc",
",",
"args",
")",
":",
"statistic_types",
"=",
"[",
"'AVG'",
",",
"'MIN'",
",",
"'MAX'",
",",
"'COUNT'",
",",
"'SUM'",
"]",
"statlist",
"=",
"args",
".",
"statistics",
".",
"split",
"(",
"','",
")",
"for",
"sta... | List measurement statistics for the specified metric. | [
"List",
"measurement",
"statistics",
"for",
"the",
"specified",
"metric",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L477-L554 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_notification_show | def do_notification_show(mc, args):
'''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.detai... | python | def do_notification_show(mc, args):
'''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.detai... | [
"def",
"do_notification_show",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'notification_id'",
"]",
"=",
"args",
".",
"id",
"try",
":",
"notification",
"=",
"mc",
".",
"notifications",
".",
"get",
"(",
"*",
"*",
"fields",... | Describe the notification. | [
"Describe",
"the",
"notification",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L593-L613 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_notification_list | def do_notification_list(mc, args):
'''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:
fi... | python | def do_notification_list(mc, args):
'''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:
fi... | [
"def",
"do_notification_list",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"if",
"args",
".",
"limit",
":",
"fields",
"[",
"'limit'",
"]",
"=",
"args",
".",
"limit",
"if",
"args",
".",
"offset",
":",
"fields",
"[",
"'offset'",
"]",
"... | List notifications for this tenant. | [
"List",
"notifications",
"for",
"this",
"tenant",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L625-L673 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_notification_delete | def do_notification_delete(mc, args):
'''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:
... | python | def do_notification_delete(mc, args):
'''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:
... | [
"def",
"do_notification_delete",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'notification_id'",
"]",
"=",
"args",
".",
"id",
"try",
":",
"mc",
".",
"notifications",
".",
"delete",
"(",
"*",
"*",
"fields",
")",
"except",
... | Delete notification. | [
"Delete",
"notification",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L678-L687 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_notification_update | def do_notification_update(mc, args):
'''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
fi... | python | def do_notification_update(mc, args):
'''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
fi... | [
"def",
"do_notification_update",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'notification_id'",
"]",
"=",
"args",
".",
"id",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"fields",
"[",
"'type'",
"]",
"=",
"a... | Update notification. | [
"Update",
"notification",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L700-L716 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_definition_create | def do_alarm_definition_create(mc, args):
'''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_acti... | python | def do_alarm_definition_create(mc, args):
'''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_acti... | [
"def",
"do_alarm_definition_create",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"if",
"args",
".",
"description",
":",
"fields",
"[",
"'description'",
"]",
"=",
"args",
".",
"descr... | Create an alarm definition. | [
"Create",
"an",
"alarm",
"definition",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L788-L812 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_definition_list | def do_alarm_definition_list(mc, args):
'''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(arg... | python | def do_alarm_definition_list(mc, args):
'''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(arg... | [
"def",
"do_alarm_definition_list",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"if",
"args",
".",
"name",
":",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"if",
"args",
".",
"dimensions",
":",
"fields",
"[",
"'dimensions'",
... | List alarm definitions for this tenant. | [
"List",
"alarm",
"definitions",
"for",
"this",
"tenant",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L867-L918 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_definition_delete | def do_alarm_definition_delete(mc, args):
'''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))
... | python | def do_alarm_definition_delete(mc, args):
'''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))
... | [
"def",
"do_alarm_definition_delete",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'alarm_id'",
"]",
"=",
"args",
".",
"id",
"try",
":",
"mc",
".",
"alarm_definitions",
".",
"delete",
"(",
"*",
"*",
"fields",
")",
"except",... | Delete the alarm definition. | [
"Delete",
"the",
"alarm",
"definition",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L923-L932 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_definition_update | def do_alarm_definition_update(mc, args):
'''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_action... | python | def do_alarm_definition_update(mc, args):
'''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_action... | [
"def",
"do_alarm_definition_update",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'alarm_id'",
"]",
"=",
"args",
".",
"id",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"fields",
"[",
"'description'",
"]",
"=",
... | Update the alarm definition. | [
"Update",
"the",
"alarm",
"definition",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L962-L987 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_definition_patch | def do_alarm_definition_patch(mc, args):
'''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.expre... | python | def do_alarm_definition_patch(mc, args):
'''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.expre... | [
"def",
"do_alarm_definition_patch",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'alarm_id'",
"]",
"=",
"args",
".",
"id",
"if",
"args",
".",
"name",
":",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"if",
"... | Patch the alarm definition. | [
"Patch",
"the",
"alarm",
"definition",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1014-L1047 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_list | def do_alarm_list(mc, args):
'''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... | python | def do_alarm_list(mc, args):
'''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... | [
"def",
"do_alarm_list",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"if",
"args",
".",
"alarm_definition_id",
":",
"fields",
"[",
"'alarm_definition_id'",
"]",
"=",
"args",
".",
"alarm_definition_id",
"if",
"args",
".",
"metric_name",
":",
"... | List alarms for this tenant. | [
"List",
"alarms",
"for",
"this",
"tenant",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1082-L1157 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_show | def do_alarm_show(mc, args):
'''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... | python | def do_alarm_show(mc, args):
'''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... | [
"def",
"do_alarm_show",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'alarm_id'",
"]",
"=",
"args",
".",
"id",
"try",
":",
"alarm",
"=",
"mc",
".",
"alarms",
".",
"get",
"(",
"*",
"*",
"fields",
")",
"except",
"(",
... | Describe the alarm. | [
"Describe",
"the",
"alarm",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1162-L1182 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_update | def do_alarm_update(mc, args):
'''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
field... | python | def do_alarm_update(mc, args):
'''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
field... | [
"def",
"do_alarm_update",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'alarm_id'",
"]",
"=",
"args",
".",
"id",
"if",
"args",
".",
"state",
".",
"upper",
"(",
")",
"not",
"in",
"state_types",
":",
"errmsg",
"=",
"(",
... | Update the alarm state. | [
"Update",
"the",
"alarm",
"state",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1193-L1210 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_delete | def do_alarm_delete(mc, args):
'''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('Successful... | python | def do_alarm_delete(mc, args):
'''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('Successful... | [
"def",
"do_alarm_delete",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'alarm_id'",
"]",
"=",
"args",
".",
"id",
"try",
":",
"mc",
".",
"alarms",
".",
"delete",
"(",
"*",
"*",
"fields",
")",
"except",
"(",
"osc_exc",
... | Delete the alarm. | [
"Delete",
"the",
"alarm",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1246-L1255 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_count | def do_alarm_count(mc, args):
'''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.for... | python | def do_alarm_count(mc, args):
'''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.for... | [
"def",
"do_alarm_count",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"if",
"args",
".",
"alarm_definition_id",
":",
"fields",
"[",
"'alarm_definition_id'",
"]",
"=",
"args",
".",
"alarm_definition_id",
"if",
"args",
".",
"metric_name",
":",
... | Count alarms. | [
"Count",
"alarms",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1315-L1364 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_history | def do_alarm_history(mc, args):
'''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.ClientExc... | python | def do_alarm_history(mc, args):
'''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.ClientExc... | [
"def",
"do_alarm_history",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'alarm_id'",
"]",
"=",
"args",
".",
"id",
"if",
"args",
".",
"limit",
":",
"fields",
"[",
"'limit'",
"]",
"=",
"args",
".",
"limit",
"if",
"args",... | Alarm state transition history. | [
"Alarm",
"state",
"transition",
"history",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1373-L1386 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_alarm_history_list | def do_alarm_history_list(mc, args):
'''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:
f... | python | def do_alarm_history_list(mc, args):
'''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:
f... | [
"def",
"do_alarm_history_list",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"if",
"args",
".",
"dimensions",
":",
"fields",
"[",
"'dimensions'",
"]",
"=",
"utils",
".",
"format_parameters",
"(",
"args",
".",
"dimensions",
")",
"if",
"args"... | List alarms state history. | [
"List",
"alarms",
"state",
"history",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1405-L1424 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | do_notification_type_list | def do_notification_type_list(mc, args):
'''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 ar... | python | def do_notification_type_list(mc, args):
'''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 ar... | [
"def",
"do_notification_type_list",
"(",
"mc",
",",
"args",
")",
":",
"try",
":",
"notification_types",
"=",
"mc",
".",
"notificationtypes",
".",
"list",
"(",
")",
"except",
"(",
"osc_exc",
".",
"ClientException",
",",
"k_exc",
".",
"HttpError",
")",
"as",
... | List notification types supported by monasca. | [
"List",
"notification",
"types",
"supported",
"by",
"monasca",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1427-L1441 |
pymacaron/pymacaron | pymacaron/auth.py | requires_auth | 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
"""
@wraps(f)
def requires_auth_decorator(*args, **kwargs):
try:
... | python | 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
"""
@wraps(f)
def requires_auth_decorator(*args, **kwargs):
try:
... | [
"def",
"requires_auth",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"requires_auth_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"authenticate_http_request",
"(",
")",
"except",
"PyMacaronException",
"as",
"e",
... | 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 | [
"A",
"decorator",
"for",
"flask",
"api",
"methods",
"that",
"validates",
"auth0",
"tokens",
"hence",
"ensuring",
"that",
"the",
"user",
"is",
"authenticated",
".",
"Code",
"coped",
"from",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"auth0",
"/",
... | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/auth.py#L25-L41 |
pymacaron/pymacaron | pymacaron/auth.py | add_auth | def add_auth(f):
"""A decorator that adds the authentication header to requests arguments"""
def add_auth_decorator(*args, **kwargs):
token = get_user_token()
if 'headers' not in kwargs:
kwargs['headers'] = {}
kwargs['headers']['Authorization'] = "Bearer %s" % token
... | python | def add_auth(f):
"""A decorator that adds the authentication header to requests arguments"""
def add_auth_decorator(*args, **kwargs):
token = get_user_token()
if 'headers' not in kwargs:
kwargs['headers'] = {}
kwargs['headers']['Authorization'] = "Bearer %s" % token
... | [
"def",
"add_auth",
"(",
"f",
")",
":",
"def",
"add_auth_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"token",
"=",
"get_user_token",
"(",
")",
"if",
"'headers'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'headers'",
"]",
"=",
"{... | A decorator that adds the authentication header to requests arguments | [
"A",
"decorator",
"that",
"adds",
"the",
"authentication",
"header",
"to",
"requests",
"arguments"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/auth.py#L44-L54 |
pymacaron/pymacaron | pymacaron/auth.py | load_auth_token | def load_auth_token(token, load=True):
"""Validate an auth0 token. Returns the token's payload, or an exception
of the type:"""
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_a... | python | def load_auth_token(token, load=True):
"""Validate an auth0 token. Returns the token's payload, or an exception
of the type:"""
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_a... | [
"def",
"load_auth_token",
"(",
"token",
",",
"load",
"=",
"True",
")",
":",
"assert",
"get_config",
"(",
")",
".",
"jwt_secret",
",",
"\"No JWT secret configured for pymacaron\"",
"assert",
"get_config",
"(",
")",
".",
"jwt_issuer",
",",
"\"No JWT issuer configured ... | Validate an auth0 token. Returns the token's payload, or an exception
of the type: | [
"Validate",
"an",
"auth0",
"token",
".",
"Returns",
"the",
"token",
"s",
"payload",
"or",
"an",
"exception",
"of",
"the",
"type",
":"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/auth.py#L61-L113 |
pymacaron/pymacaron | pymacaron/auth.py | authenticate_http_request | 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.
... | python | 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.
... | [
"def",
"authenticate_http_request",
"(",
"token",
"=",
"None",
")",
":",
"if",
"token",
":",
"auth",
"=",
"token",
"else",
":",
"auth",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'Authorization'",
",",
"None",
")",
"if",
"not",
"auth",
":",
"aut... | 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... | [
"Validate",
"auth0",
"tokens",
"passed",
"in",
"the",
"request",
"s",
"header",
"hence",
"ensuring",
"that",
"the",
"user",
"is",
"authenticated",
".",
"Code",
"copied",
"from",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"auth0",
"/",
"auth0",
"... | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/auth.py#L115-L150 |
pymacaron/pymacaron | pymacaron/auth.py | generate_token | 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"""
assert user_id, "No user_id passed to generate_token()"
assert isinstance(data, dict), "generate_token(data=) should be a dic... | python | 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"""
assert user_id, "No user_id passed to generate_token()"
assert isinstance(data, dict), "generate_token(data=) should be a dic... | [
"def",
"generate_token",
"(",
"user_id",
",",
"expire_in",
"=",
"None",
",",
"data",
"=",
"{",
"}",
",",
"issuer",
"=",
"None",
",",
"iat",
"=",
"None",
")",
":",
"assert",
"user_id",
",",
"\"No user_id passed to generate_token()\"",
"assert",
"isinstance",
... | Generate a new JWT token for this user_id. Default expiration date
is 1 year from creation time | [
"Generate",
"a",
"new",
"JWT",
"token",
"for",
"this",
"user_id",
".",
"Default",
"expiration",
"date",
"is",
"1",
"year",
"from",
"creation",
"time"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/auth.py#L156-L200 |
pymacaron/pymacaron | pymacaron/auth.py | get_user_token | def get_user_token():
"""Return the authenticated user's auth token"""
if not hasattr(stack.top, 'current_user'):
return ''
current_user = stack.top.current_user
return current_user.get('token', '') | python | def get_user_token():
"""Return the authenticated user's auth token"""
if not hasattr(stack.top, 'current_user'):
return ''
current_user = stack.top.current_user
return current_user.get('token', '') | [
"def",
"get_user_token",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"stack",
".",
"top",
",",
"'current_user'",
")",
":",
"return",
"''",
"current_user",
"=",
"stack",
".",
"top",
".",
"current_user",
"return",
"current_user",
".",
"get",
"(",
"'token'",
... | Return the authenticated user's auth token | [
"Return",
"the",
"authenticated",
"user",
"s",
"auth",
"token"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/auth.py#L249-L254 |
pymacaron/pymacaron | pymacaron/auth.py | get_token_issuer | def get_token_issuer():
"""Return the issuer in which this user's token was created"""
try:
current_user = stack.top.current_user
return current_user.get('iss', get_config().jwt_issuer)
except Exception:
pass
return get_config().jwt_issuer | python | def get_token_issuer():
"""Return the issuer in which this user's token was created"""
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",
"(",
")",
":",
"try",
":",
"current_user",
"=",
"stack",
".",
"top",
".",
"current_user",
"return",
"current_user",
".",
"get",
"(",
"'iss'",
",",
"get_config",
"(",
")",
".",
"jwt_issuer",
")",
"except",
"Exception",
":",
"pass"... | Return the issuer in which this user's token was created | [
"Return",
"the",
"issuer",
"in",
"which",
"this",
"user",
"s",
"token",
"was",
"created"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/auth.py#L257-L264 |
tristantao/py-ms-cognitive | py_ms_cognitive/py_ms_cognitive_search/py_ms_cognitive_news_search.py | PyMsCognitiveNewsSearch._search | def _search(self, limit, format):
'''
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.
... | python | def _search(self, limit, format):
'''
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.
... | [
"def",
"_search",
"(",
"self",
",",
"limit",
",",
"format",
")",
":",
"limit",
"=",
"min",
"(",
"limit",
",",
"self",
".",
"MAX_SEARCH_PER_QUERY",
")",
"payload",
"=",
"{",
"'q'",
":",
"self",
".",
"query",
",",
"'count'",
":",
"limit",
",",
"#curren... | Returns a list of result objects, with the url for the next page MsCognitive search url. | [
"Returns",
"a",
"list",
"of",
"result",
"objects",
"with",
"the",
"url",
"for",
"the",
"next",
"page",
"MsCognitive",
"search",
"url",
"."
] | train | https://github.com/tristantao/py-ms-cognitive/blob/8f4b10df1b4bf1f2c9af64218cfcdc35176b75e7/py_ms_cognitive/py_ms_cognitive_search/py_ms_cognitive_news_search.py#L22-L41 |
openstack/python-monascaclient | monascaclient/v2_0/notifications.py | NotificationsManager.create | def create(self, **kwargs):
"""Create a notification."""
body = self.client.create(url=self.base_url,
json=kwargs)
return body | python | def create(self, **kwargs):
"""Create a notification."""
body = self.client.create(url=self.base_url,
json=kwargs)
return body | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"self",
".",
"client",
".",
"create",
"(",
"url",
"=",
"self",
".",
"base_url",
",",
"json",
"=",
"kwargs",
")",
"return",
"body"
] | Create a notification. | [
"Create",
"a",
"notification",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/notifications.py#L23-L27 |
openstack/python-monascaclient | monascaclient/v2_0/notifications.py | NotificationsManager.get | def get(self, **kwargs):
"""Get the details for a specific notification."""
# 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)
... | python | def get(self, **kwargs):
"""Get the details for a specific notification."""
# 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)
... | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# NOTE(trebskit) should actually be find_one, but",
"# monasca does not support expected response format",
"url",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"base_url",
",",
"kwargs",
"[",
"'notification_id'",
... | Get the details for a specific notification. | [
"Get",
"the",
"details",
"for",
"a",
"specific",
"notification",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/notifications.py#L29-L37 |
openstack/python-monascaclient | monascaclient/v2_0/notifications.py | NotificationsManager.delete | def delete(self, **kwargs):
"""Delete a notification."""
url = self.base_url + '/%s' % kwargs['notification_id']
resp = self.client.delete(url=url)
return resp | python | def delete(self, **kwargs):
"""Delete a notification."""
url = self.base_url + '/%s' % kwargs['notification_id']
resp = self.client.delete(url=url)
return resp | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/%s'",
"%",
"kwargs",
"[",
"'notification_id'",
"]",
"resp",
"=",
"self",
".",
"client",
".",
"delete",
"(",
"url",
"=",
"url",
")",
"retur... | Delete a notification. | [
"Delete",
"a",
"notification",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/notifications.py#L43-L47 |
openstack/python-monascaclient | monascaclient/v2_0/alarm_definitions.py | AlarmDefinitionsManager.create | def create(self, **kwargs):
"""Create an alarm definition."""
resp = self.client.create(url=self.base_url,
json=kwargs)
return resp | python | def create(self, **kwargs):
"""Create an alarm definition."""
resp = self.client.create(url=self.base_url,
json=kwargs)
return resp | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
"=",
"self",
".",
"client",
".",
"create",
"(",
"url",
"=",
"self",
".",
"base_url",
",",
"json",
"=",
"kwargs",
")",
"return",
"resp"
] | Create an alarm definition. | [
"Create",
"an",
"alarm",
"definition",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/alarm_definitions.py#L23-L27 |
openstack/python-monascaclient | monascaclient/v2_0/alarm_definitions.py | AlarmDefinitionsManager.update | def update(self, **kwargs):
"""Update a specific alarm definition."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
del kwargs['alarm_id']
resp = self.client.create(url=url_str,
method='PUT',
json=kwargs)
... | python | def update(self, **kwargs):
"""Update a specific alarm definition."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
del kwargs['alarm_id']
resp = self.client.create(url=url_str,
method='PUT',
json=kwargs)
... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"url_str",
"=",
"self",
".",
"base_url",
"+",
"'/%s'",
"%",
"kwargs",
"[",
"'alarm_id'",
"]",
"del",
"kwargs",
"[",
"'alarm_id'",
"]",
"resp",
"=",
"self",
".",
"client",
".",
"create",... | Update a specific alarm definition. | [
"Update",
"a",
"specific",
"alarm",
"definition",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/alarm_definitions.py#L49-L58 |
mdscruggs/ga | ga/examples/polynomials.py | PolyModelGA.compute_y | def compute_y(self, coefficients, num_x):
""" Return calculated y-values for the domain of x-values in [1, num_x]. """
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 | python | def compute_y(self, coefficients, num_x):
""" Return calculated y-values for the domain of x-values in [1, num_x]. """
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",
")",
":",
"y_vals",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"num_x",
"+",
"1",
")",
":",
"y",
"=",
"sum",
"(",
"[",
"c",
"*",
"x",
"**",
"i",
"for",
"i",
"... | Return calculated y-values for the domain of x-values in [1, num_x]. | [
"Return",
"calculated",
"y",
"-",
"values",
"for",
"the",
"domain",
"of",
"x",
"-",
"values",
"in",
"[",
"1",
"num_x",
"]",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/polynomials.py#L34-L42 |
mdscruggs/ga | ga/examples/polynomials.py | PolyModelGA.compute_err | 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: lis... | python | 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: lis... | [
"def",
"compute_err",
"(",
"self",
",",
"solution_y",
",",
"coefficients",
")",
":",
"error",
"=",
"0",
"for",
"modeled",
",",
"expected",
"in",
"zip",
"(",
"solution_y",
",",
"self",
".",
"expected_values",
")",
":",
"error",
"+=",
"abs",
"(",
"modeled"... | 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... | [
"Return",
"an",
"error",
"value",
"by",
"finding",
"the",
"absolute",
"difference",
"for",
"each",
"element",
"in",
"a",
"list",
"of",
"solution",
"-",
"generated",
"y",
"-",
"values",
"versus",
"expected",
"values",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/polynomials.py#L44-L63 |
mdscruggs/ga | ga/examples/polynomials.py | PolyModelGA.eval_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
"""
coefficients = self.translator.translate_chromosome(chromosome)
... | python | 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
"""
coefficients = self.translator.translate_chromosome(chromosome)
... | [
"def",
"eval_fitness",
"(",
"self",
",",
"chromosome",
")",
":",
"coefficients",
"=",
"self",
".",
"translator",
".",
"translate_chromosome",
"(",
"chromosome",
")",
"solution_y",
"=",
"self",
".",
"compute_y",
"(",
"coefficients",
",",
"self",
".",
"num_x",
... | Evaluate the polynomial equation using coefficients represented by a
solution/chromosome, returning its error as the solution's fitness.
return: fitness value | [
"Evaluate",
"the",
"polynomial",
"equation",
"using",
"coefficients",
"represented",
"by",
"a",
"solution",
"/",
"chromosome",
"returning",
"its",
"error",
"as",
"the",
"solution",
"s",
"fitness",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/polynomials.py#L65-L76 |
fabaff/python-mystrom | pymystrom/cli.py | read_config | def read_config(ip, mac):
"""Read the current configuration of a myStrom device."""
click.echo("Read configuration from %s" % ip)
request = requests.get(
'http://{}/{}/{}/'.format(ip, URI, mac), timeout=TIMEOUT)
print(request.json()) | python | def read_config(ip, mac):
"""Read the current configuration of a myStrom device."""
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",
")",
":",
"click",
".",
"echo",
"(",
"\"Read configuration from %s\"",
"%",
"ip",
")",
"request",
"=",
"requests",
".",
"get",
"(",
"'http://{}/{}/{}/'",
".",
"format",
"(",
"ip",
",",
"URI",
",",
"mac",
")",
... | Read the current configuration of a myStrom device. | [
"Read",
"the",
"current",
"configuration",
"of",
"a",
"myStrom",
"device",
"."
] | train | https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/cli.py#L35-L40 |
fabaff/python-mystrom | pymystrom/cli.py | write_config | def write_config(ip, mac, single, double, long, touch):
"""Write the current configuration of a myStrom button."""
click.echo("Write configuration to device %s" % ip)
data = {
'single': single,
'double': double,
'long': long,
'touch': touch,
}
request = requests.post(... | python | def write_config(ip, mac, single, double, long, touch):
"""Write the current configuration of a myStrom button."""
click.echo("Write configuration to device %s" % ip)
data = {
'single': single,
'double': double,
'long': long,
'touch': touch,
}
request = requests.post(... | [
"def",
"write_config",
"(",
"ip",
",",
"mac",
",",
"single",
",",
"double",
",",
"long",
",",
"touch",
")",
":",
"click",
".",
"echo",
"(",
"\"Write configuration to device %s\"",
"%",
"ip",
")",
"data",
"=",
"{",
"'single'",
":",
"single",
",",
"'double... | Write the current configuration of a myStrom button. | [
"Write",
"the",
"current",
"configuration",
"of",
"a",
"myStrom",
"button",
"."
] | train | https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/cli.py#L61-L74 |
fabaff/python-mystrom | pymystrom/cli.py | write_ha_config | def write_ha_config(ip, mac, hass, port, id):
"""Write the configuration for Home Assistant to a myStrom button."""
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),
... | python | def write_ha_config(ip, mac, hass, port, id):
"""Write the configuration for Home Assistant to a myStrom button."""
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),
... | [
"def",
"write_ha_config",
"(",
"ip",
",",
"mac",
",",
"hass",
",",
"port",
",",
"id",
")",
":",
"click",
".",
"echo",
"(",
"\"Write configuration for Home Assistant to device %s...\"",
"%",
"ip",
")",
"action",
"=",
"\"get://{1}:{2}/api/mystrom?{0}={3}\"",
"data",
... | Write the configuration for Home Assistant to a myStrom button. | [
"Write",
"the",
"configuration",
"for",
"Home",
"Assistant",
"to",
"a",
"myStrom",
"button",
"."
] | train | https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/cli.py#L89-L106 |
fabaff/python-mystrom | pymystrom/cli.py | reset_config | def reset_config(ip, mac):
"""Reset the current configuration of a myStrom WiFi Button."""
click.echo("Reset configuration of button %s..." % ip)
data = {
'single': "",
'double': "",
'long': "",
'touch': "",
}
request = requests.post(
'http://{}/{}/{}/'.format... | python | def reset_config(ip, mac):
"""Reset the current configuration of a myStrom WiFi Button."""
click.echo("Reset configuration of button %s..." % ip)
data = {
'single': "",
'double': "",
'long': "",
'touch': "",
}
request = requests.post(
'http://{}/{}/{}/'.format... | [
"def",
"reset_config",
"(",
"ip",
",",
"mac",
")",
":",
"click",
".",
"echo",
"(",
"\"Reset configuration of button %s...\"",
"%",
"ip",
")",
"data",
"=",
"{",
"'single'",
":",
"\"\"",
",",
"'double'",
":",
"\"\"",
",",
"'long'",
":",
"\"\"",
",",
"'touc... | Reset the current configuration of a myStrom WiFi Button. | [
"Reset",
"the",
"current",
"configuration",
"of",
"a",
"myStrom",
"WiFi",
"Button",
"."
] | train | https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/cli.py#L114-L127 |
fabaff/python-mystrom | pymystrom/cli.py | color | def color(ip, mac, hue, saturation, value):
"""Switch the bulb on with the given color."""
bulb = MyStromBulb(ip, mac)
bulb.set_color_hsv(hue, saturation, value) | python | def color(ip, mac, hue, saturation, value):
"""Switch the bulb on with the given color."""
bulb = MyStromBulb(ip, mac)
bulb.set_color_hsv(hue, saturation, value) | [
"def",
"color",
"(",
"ip",
",",
"mac",
",",
"hue",
",",
"saturation",
",",
"value",
")",
":",
"bulb",
"=",
"MyStromBulb",
"(",
"ip",
",",
"mac",
")",
"bulb",
".",
"set_color_hsv",
"(",
"hue",
",",
"saturation",
",",
"value",
")"
] | Switch the bulb on with the given color. | [
"Switch",
"the",
"bulb",
"on",
"with",
"the",
"given",
"color",
"."
] | train | https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/cli.py#L157-L160 |
pymacaron/pymacaron | pymacaron/utils.py | is_ec2_instance | def is_ec2_instance():
"""Try fetching instance metadata at 'curl http://169.254.169.254/latest/meta-data/'
to see if host is on an ec2 instance"""
# Note: this code assumes that docker containers running on ec2 instances
# inherit instances metadata, which they do as of 2016-08-25
global IS_EC2_I... | python | def is_ec2_instance():
"""Try fetching instance metadata at 'curl http://169.254.169.254/latest/meta-data/'
to see if host is on an ec2 instance"""
# Note: this code assumes that docker containers running on ec2 instances
# inherit instances metadata, which they do as of 2016-08-25
global IS_EC2_I... | [
"def",
"is_ec2_instance",
"(",
")",
":",
"# Note: this code assumes that docker containers running on ec2 instances",
"# inherit instances metadata, which they do as of 2016-08-25",
"global",
"IS_EC2_INSTANCE",
"if",
"IS_EC2_INSTANCE",
"!=",
"-",
"1",
":",
"# Returned the cached value"... | Try fetching instance metadata at 'curl http://169.254.169.254/latest/meta-data/'
to see if host is on an ec2 instance | [
"Try",
"fetching",
"instance",
"metadata",
"at",
"curl",
"http",
":",
"//",
"169",
".",
"254",
".",
"169",
".",
"254",
"/",
"latest",
"/",
"meta",
"-",
"data",
"/",
"to",
"see",
"if",
"host",
"is",
"on",
"an",
"ec2",
"instance"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/utils.py#L17-L41 |
pymacaron/pymacaron | pymacaron/utils.py | to_epoch | def to_epoch(t):
"""Take a datetime, either as a string or a datetime.datetime object,
and return the corresponding epoch"""
if isinstance(t, str):
if '+' not in t:
t = t + '+00:00'
t = parser.parse(t)
elif t.tzinfo is None or t.tzinfo.utcoffset(t) is None:
t = t.repl... | python | def to_epoch(t):
"""Take a datetime, either as a string or a datetime.datetime object,
and return the corresponding epoch"""
if isinstance(t, str):
if '+' not in t:
t = t + '+00:00'
t = parser.parse(t)
elif t.tzinfo is None or t.tzinfo.utcoffset(t) is None:
t = t.repl... | [
"def",
"to_epoch",
"(",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"str",
")",
":",
"if",
"'+'",
"not",
"in",
"t",
":",
"t",
"=",
"t",
"+",
"'+00:00'",
"t",
"=",
"parser",
".",
"parse",
"(",
"t",
")",
"elif",
"t",
".",
"tzinfo",
"is",
... | Take a datetime, either as a string or a datetime.datetime object,
and return the corresponding epoch | [
"Take",
"a",
"datetime",
"either",
"as",
"a",
"string",
"or",
"a",
"datetime",
".",
"datetime",
"object",
"and",
"return",
"the",
"corresponding",
"epoch"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/utils.py#L48-L60 |
pymacaron/pymacaron | pymacaron/utils.py | get_container_version | def get_container_version():
"""Return the version of the docker container running the present server,
or '' if not in a container"""
root_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
version_file = os.path.join(root_dir, 'VERSION')
if os.path.exists(version_file):
with open(version_... | python | def get_container_version():
"""Return the version of the docker container running the present server,
or '' if not in a container"""
root_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
version_file = os.path.join(root_dir, 'VERSION')
if os.path.exists(version_file):
with open(version_... | [
"def",
"get_container_version",
"(",
")",
":",
"root_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"version_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | Return the version of the docker container running the present server,
or '' if not in a container | [
"Return",
"the",
"version",
"of",
"the",
"docker",
"container",
"running",
"the",
"present",
"server",
"or",
"if",
"not",
"in",
"a",
"container"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/utils.py#L68-L76 |
pymacaron/pymacaron | pymacaron/utils.py | get_app_name | def get_app_name():
"""Return a generic name for this app, usefull when reporting to monitoring/logging frameworks"""
conf = get_config()
if is_ec2_instance():
return conf.app_name_live if hasattr(conf, 'app_name_live') else 'PYMACARON_LIVE'
else:
return conf.app_name_dev if hasattr(conf... | python | def get_app_name():
"""Return a generic name for this app, usefull when reporting to monitoring/logging frameworks"""
conf = get_config()
if is_ec2_instance():
return conf.app_name_live if hasattr(conf, 'app_name_live') else 'PYMACARON_LIVE'
else:
return conf.app_name_dev if hasattr(conf... | [
"def",
"get_app_name",
"(",
")",
":",
"conf",
"=",
"get_config",
"(",
")",
"if",
"is_ec2_instance",
"(",
")",
":",
"return",
"conf",
".",
"app_name_live",
"if",
"hasattr",
"(",
"conf",
",",
"'app_name_live'",
")",
"else",
"'PYMACARON_LIVE'",
"else",
":",
"... | Return a generic name for this app, usefull when reporting to monitoring/logging frameworks | [
"Return",
"a",
"generic",
"name",
"for",
"this",
"app",
"usefull",
"when",
"reporting",
"to",
"monitoring",
"/",
"logging",
"frameworks"
] | train | https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/utils.py#L79-L85 |
mdscruggs/ga | ga/examples/__init__.py | run_all | def run_all(plot=True, seed=None):
""" Run all examples. """
if seed is not None:
import random
random.seed(seed)
print("Running biggest_multiple.py")
biggest_multiple.run(plot=plot)
print("Running polynomials.py")
polynomials.run(plot=plot)
print("Running travelling_sales... | python | def run_all(plot=True, seed=None):
""" Run all examples. """
if seed is not None:
import random
random.seed(seed)
print("Running biggest_multiple.py")
biggest_multiple.run(plot=plot)
print("Running polynomials.py")
polynomials.run(plot=plot)
print("Running travelling_sales... | [
"def",
"run_all",
"(",
"plot",
"=",
"True",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"not",
"None",
":",
"import",
"random",
"random",
".",
"seed",
"(",
"seed",
")",
"print",
"(",
"\"Running biggest_multiple.py\"",
")",
"biggest_multiple",
... | Run all examples. | [
"Run",
"all",
"examples",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/__init__.py#L9-L25 |
mdscruggs/ga | ga/genes.py | BaseGene.create_random | def create_random(cls, length, **kwargs):
"""
Return a new instance of this gene class with random DNA,
with characters chosen from ``GENETIC_MATERIAL_OPTIONS``.
length: the number of characters in the randomized DNA
**kwargs: forwarded to the ``cls`` constructor
... | python | def create_random(cls, length, **kwargs):
"""
Return a new instance of this gene class with random DNA,
with characters chosen from ``GENETIC_MATERIAL_OPTIONS``.
length: the number of characters in the randomized DNA
**kwargs: forwarded to the ``cls`` constructor
... | [
"def",
"create_random",
"(",
"cls",
",",
"length",
",",
"*",
"*",
"kwargs",
")",
":",
"dna",
"=",
"''",
".",
"join",
"(",
"[",
"random",
".",
"choice",
"(",
"cls",
".",
"GENETIC_MATERIAL_OPTIONS",
")",
"for",
"_",
"in",
"range",
"(",
"length",
")",
... | Return a new instance of this gene class with random DNA,
with characters chosen from ``GENETIC_MATERIAL_OPTIONS``.
length: the number of characters in the randomized DNA
**kwargs: forwarded to the ``cls`` constructor | [
"Return",
"a",
"new",
"instance",
"of",
"this",
"gene",
"class",
"with",
"random",
"DNA",
"with",
"characters",
"chosen",
"from",
"GENETIC_MATERIAL_OPTIONS",
".",
"length",
":",
"the",
"number",
"of",
"characters",
"in",
"the",
"randomized",
"DNA",
"**",
"kwar... | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/genes.py#L16-L25 |
mdscruggs/ga | ga/genes.py | BaseGene.mutate | def mutate(self, p_mutate):
"""
Simulate mutation against a probability.
p_mutate: probability for mutation to occur
"""
new_dna = []
for bit in self.dna:
if random.random() < p_mutate:
new_bit = bit
while new_bit ==... | python | def mutate(self, p_mutate):
"""
Simulate mutation against a probability.
p_mutate: probability for mutation to occur
"""
new_dna = []
for bit in self.dna:
if random.random() < p_mutate:
new_bit = bit
while new_bit ==... | [
"def",
"mutate",
"(",
"self",
",",
"p_mutate",
")",
":",
"new_dna",
"=",
"[",
"]",
"for",
"bit",
"in",
"self",
".",
"dna",
":",
"if",
"random",
".",
"random",
"(",
")",
"<",
"p_mutate",
":",
"new_bit",
"=",
"bit",
"while",
"new_bit",
"==",
"bit",
... | Simulate mutation against a probability.
p_mutate: probability for mutation to occur | [
"Simulate",
"mutation",
"against",
"a",
"probability",
".",
"p_mutate",
":",
"probability",
"for",
"mutation",
"to",
"occur"
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/genes.py#L61-L79 |
mdscruggs/ga | ga/genes.py | BaseGene.copy | def copy(self):
""" Return a new instance of this gene with the same DNA. """
return type(self)(self.dna, suppressed=self.suppressed, name=self.name) | python | def copy(self):
""" Return a new instance of this gene with the same DNA. """
return type(self)(self.dna, suppressed=self.suppressed, name=self.name) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"type",
"(",
"self",
")",
"(",
"self",
".",
"dna",
",",
"suppressed",
"=",
"self",
".",
"suppressed",
",",
"name",
"=",
"self",
".",
"name",
")"
] | Return a new instance of this gene with the same DNA. | [
"Return",
"a",
"new",
"instance",
"of",
"this",
"gene",
"with",
"the",
"same",
"DNA",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/genes.py#L81-L83 |
mdscruggs/ga | ga/genes.py | BaseGene._check_dna | def _check_dna(self, dna):
""" Check that a DNA string only contains characters in ``GENETIC_MATERIAL_OPTIONS``. """
valid_chars = set(self.GENETIC_MATERIAL_OPTIONS)
assert all(char in valid_chars for char in dna) | python | def _check_dna(self, dna):
""" Check that a DNA string only contains characters in ``GENETIC_MATERIAL_OPTIONS``. """
valid_chars = set(self.GENETIC_MATERIAL_OPTIONS)
assert all(char in valid_chars for char in dna) | [
"def",
"_check_dna",
"(",
"self",
",",
"dna",
")",
":",
"valid_chars",
"=",
"set",
"(",
"self",
".",
"GENETIC_MATERIAL_OPTIONS",
")",
"assert",
"all",
"(",
"char",
"in",
"valid_chars",
"for",
"char",
"in",
"dna",
")"
] | Check that a DNA string only contains characters in ``GENETIC_MATERIAL_OPTIONS``. | [
"Check",
"that",
"a",
"DNA",
"string",
"only",
"contains",
"characters",
"in",
"GENETIC_MATERIAL_OPTIONS",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/genes.py#L85-L88 |
mdscruggs/ga | ga/genes.py | BinaryGene.mutate | def mutate(self, p_mutate):
"""
Check each element for mutation, swapping "0" for "1" and vice-versa.
"""
new_dna = []
for bit in self.dna:
if random.random() < p_mutate:
bit = '1' if bit == '0' else '0'
new_dna.ap... | python | def mutate(self, p_mutate):
"""
Check each element for mutation, swapping "0" for "1" and vice-versa.
"""
new_dna = []
for bit in self.dna:
if random.random() < p_mutate:
bit = '1' if bit == '0' else '0'
new_dna.ap... | [
"def",
"mutate",
"(",
"self",
",",
"p_mutate",
")",
":",
"new_dna",
"=",
"[",
"]",
"for",
"bit",
"in",
"self",
".",
"dna",
":",
"if",
"random",
".",
"random",
"(",
")",
"<",
"p_mutate",
":",
"bit",
"=",
"'1'",
"if",
"bit",
"==",
"'0'",
"else",
... | Check each element for mutation, swapping "0" for "1" and vice-versa. | [
"Check",
"each",
"element",
"for",
"mutation",
"swapping",
"0",
"for",
"1",
"and",
"vice",
"-",
"versa",
"."
] | train | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/genes.py#L104-L116 |
castle/castle-python | castle/utils.py | deep_merge | def deep_merge(base, extra):
"""
Deeply merge two dictionaries, overriding existing keys in the base.
:param base: The base dictionary which will be merged into.
:param extra: The dictionary to merge into the base. Keys from this
dictionary will take precedence.
"""
if extra is None:
... | python | def deep_merge(base, extra):
"""
Deeply merge two dictionaries, overriding existing keys in the base.
:param base: The base dictionary which will be merged into.
:param extra: The dictionary to merge into the base. Keys from this
dictionary will take precedence.
"""
if extra is None:
... | [
"def",
"deep_merge",
"(",
"base",
",",
"extra",
")",
":",
"if",
"extra",
"is",
"None",
":",
"return",
"for",
"key",
",",
"value",
"in",
"extra",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"if",
"key",
"in",
"base",
":",
"del",... | Deeply merge two dictionaries, overriding existing keys in the base.
:param base: The base dictionary which will be merged into.
:param extra: The dictionary to merge into the base. Keys from this
dictionary will take precedence. | [
"Deeply",
"merge",
"two",
"dictionaries",
"overriding",
"existing",
"keys",
"in",
"the",
"base",
"."
] | train | https://github.com/castle/castle-python/blob/5f8736932e4b6ecdb712885eef393b6c0c53cfeb/castle/utils.py#L9-L29 |
openstack/python-monascaclient | monascaclient/osc/migration.py | make_client | def make_client(api_version, session=None,
endpoint=None, service_type='monitoring'):
"""Returns an monitoring API client."""
client_cls = utils.get_client_class('monitoring', api_version, VERSION_MAP)
c = client_cls(
session=session,
service_type=service_type,
endpo... | python | def make_client(api_version, session=None,
endpoint=None, service_type='monitoring'):
"""Returns an monitoring API client."""
client_cls = utils.get_client_class('monitoring', api_version, VERSION_MAP)
c = client_cls(
session=session,
service_type=service_type,
endpo... | [
"def",
"make_client",
"(",
"api_version",
",",
"session",
"=",
"None",
",",
"endpoint",
"=",
"None",
",",
"service_type",
"=",
"'monitoring'",
")",
":",
"client_cls",
"=",
"utils",
".",
"get_client_class",
"(",
"'monitoring'",
",",
"api_version",
",",
"VERSION... | Returns an monitoring API client. | [
"Returns",
"an",
"monitoring",
"API",
"client",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/osc/migration.py#L34-L47 |
openstack/python-monascaclient | monascaclient/osc/migration.py | create_command_class | def create_command_class(name, func_module):
"""Dynamically creates subclass of MigratingCommand.
Method takes name of the function, module it is part of
and builds the subclass of :py:class:`MigratingCommand`.
Having a subclass of :py:class:`cliff.command.Command` is mandatory
for the osc-lib inte... | python | def create_command_class(name, func_module):
"""Dynamically creates subclass of MigratingCommand.
Method takes name of the function, module it is part of
and builds the subclass of :py:class:`MigratingCommand`.
Having a subclass of :py:class:`cliff.command.Command` is mandatory
for the osc-lib inte... | [
"def",
"create_command_class",
"(",
"name",
",",
"func_module",
")",
":",
"cmd_name",
"=",
"name",
"[",
"3",
":",
"]",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"callback",
"=",
"getattr",
"(",
"func_module",
",",
"name",
")",
"desc",
"=",
"callback... | Dynamically creates subclass of MigratingCommand.
Method takes name of the function, module it is part of
and builds the subclass of :py:class:`MigratingCommand`.
Having a subclass of :py:class:`cliff.command.Command` is mandatory
for the osc-lib integration.
:param name: name of the function
... | [
"Dynamically",
"creates",
"subclass",
"of",
"MigratingCommand",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/osc/migration.py#L50-L85 |
openstack/python-monascaclient | monascaclient/client.py | _session | def _session(kwargs):
"""Returns or reuses session.
Method takes care of providing instance of
session object for the client.
:param kwargs: all params (without api_version) client was initialized with
:type kwargs: dict
:returns: session object
:rtype keystoneauth1.session.Session
"... | python | def _session(kwargs):
"""Returns or reuses session.
Method takes care of providing instance of
session object for the client.
:param kwargs: all params (without api_version) client was initialized with
:type kwargs: dict
:returns: session object
:rtype keystoneauth1.session.Session
"... | [
"def",
"_session",
"(",
"kwargs",
")",
":",
"if",
"'session'",
"in",
"kwargs",
":",
"LOG",
".",
"debug",
"(",
"'Reusing session'",
")",
"sess",
"=",
"kwargs",
".",
"get",
"(",
"'session'",
")",
"if",
"not",
"isinstance",
"(",
"sess",
",",
"k_session",
... | Returns or reuses session.
Method takes care of providing instance of
session object for the client.
:param kwargs: all params (without api_version) client was initialized with
:type kwargs: dict
:returns: session object
:rtype keystoneauth1.session.Session | [
"Returns",
"or",
"reuses",
"session",
"."
] | train | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/client.py#L45-L69 |
uchicago-cs/deepdish | deepdish/util/saveable.py | Saveable.load | def load(cls, path):
"""
Loads an instance of the class from a file.
Parameters
----------
path : str
Path to an HDF5 file.
Examples
--------
This is an abstract data type, but let us say that ``Foo`` inherits
from ``Saveable``. To co... | python | def load(cls, path):
"""
Loads an instance of the class from a file.
Parameters
----------
path : str
Path to an HDF5 file.
Examples
--------
This is an abstract data type, but let us say that ``Foo`` inherits
from ``Saveable``. To co... | [
"def",
"load",
"(",
"cls",
",",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"cls",
".",
"load_from_dict",
"(",
"{",
"}",
")",
"else",
":",
"d",
"=",
"io",
".",
"load",
"(",
"path",
")",
"return",
"cls",
".",
"load_from_dict",
"("... | Loads an instance of the class from a file.
Parameters
----------
path : str
Path to an HDF5 file.
Examples
--------
This is an abstract data type, but let us say that ``Foo`` inherits
from ``Saveable``. To construct an object of this class from a fi... | [
"Loads",
"an",
"instance",
"of",
"the",
"class",
"from",
"a",
"file",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/util/saveable.py#L17-L38 |
uchicago-cs/deepdish | deepdish/util/saveable.py | NamedRegistry.register | def register(cls, name):
"""Decorator to register a class."""
def register_decorator(reg_cls):
def name_func(self):
return name
reg_cls.name = property(name_func)
assert issubclass(reg_cls, cls), \
"Must be subclass matching your NamedR... | python | def register(cls, name):
"""Decorator to register a class."""
def register_decorator(reg_cls):
def name_func(self):
return name
reg_cls.name = property(name_func)
assert issubclass(reg_cls, cls), \
"Must be subclass matching your NamedR... | [
"def",
"register",
"(",
"cls",
",",
"name",
")",
":",
"def",
"register_decorator",
"(",
"reg_cls",
")",
":",
"def",
"name_func",
"(",
"self",
")",
":",
"return",
"name",
"reg_cls",
".",
"name",
"=",
"property",
"(",
"name_func",
")",
"assert",
"issubclas... | Decorator to register a class. | [
"Decorator",
"to",
"register",
"a",
"class",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/util/saveable.py#L104-L114 |
uchicago-cs/deepdish | deepdish/util/saveable.py | NamedRegistry.construct | def construct(cls, name, *args, **kwargs):
"""
Constructs an instance of an object given its name.
"""
return cls.REGISTRY[name](*args, **kwargs) | python | def construct(cls, name, *args, **kwargs):
"""
Constructs an instance of an object given its name.
"""
return cls.REGISTRY[name](*args, **kwargs) | [
"def",
"construct",
"(",
"cls",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"REGISTRY",
"[",
"name",
"]",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Constructs an instance of an object given its name. | [
"Constructs",
"an",
"instance",
"of",
"an",
"object",
"given",
"its",
"name",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/util/saveable.py#L124-L128 |
uchicago-cs/deepdish | deepdish/conf.py | config | def config():
"""
Loads and returns a ConfigParser from ``~/.deepdish.conf``.
"""
conf = ConfigParser()
# Set up defaults
conf.add_section('io')
conf.set('io', 'compression', 'zlib')
conf.read(os.path.expanduser('~/.deepdish.conf'))
return conf | python | def config():
"""
Loads and returns a ConfigParser from ``~/.deepdish.conf``.
"""
conf = ConfigParser()
# Set up defaults
conf.add_section('io')
conf.set('io', 'compression', 'zlib')
conf.read(os.path.expanduser('~/.deepdish.conf'))
return conf | [
"def",
"config",
"(",
")",
":",
"conf",
"=",
"ConfigParser",
"(",
")",
"# Set up defaults",
"conf",
".",
"add_section",
"(",
"'io'",
")",
"conf",
".",
"set",
"(",
"'io'",
",",
"'compression'",
",",
"'zlib'",
")",
"conf",
".",
"read",
"(",
"os",
".",
... | Loads and returns a ConfigParser from ``~/.deepdish.conf``. | [
"Loads",
"and",
"returns",
"a",
"ConfigParser",
"from",
"~",
"/",
".",
"deepdish",
".",
"conf",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/conf.py#L10-L20 |
uchicago-cs/deepdish | deepdish/image.py | resize_by_factor | def resize_by_factor(im, factor):
"""
Resizes the image according to a factor. The image is pre-filtered
with a Gaussian and then resampled with bilinear interpolation.
This function uses scikit-image and essentially combines its
`pyramid_reduce` with `pyramid_expand` into one function.
Return... | python | def resize_by_factor(im, factor):
"""
Resizes the image according to a factor. The image is pre-filtered
with a Gaussian and then resampled with bilinear interpolation.
This function uses scikit-image and essentially combines its
`pyramid_reduce` with `pyramid_expand` into one function.
Return... | [
"def",
"resize_by_factor",
"(",
"im",
",",
"factor",
")",
":",
"_import_skimage",
"(",
")",
"from",
"skimage",
".",
"transform",
".",
"pyramids",
"import",
"pyramid_reduce",
",",
"pyramid_expand",
"if",
"factor",
"<",
"1",
":",
"return",
"pyramid_reduce",
"(",... | Resizes the image according to a factor. The image is pre-filtered
with a Gaussian and then resampled with bilinear interpolation.
This function uses scikit-image and essentially combines its
`pyramid_reduce` with `pyramid_expand` into one function.
Returns the same object if factor is 1, not a copy.
... | [
"Resizes",
"the",
"image",
"according",
"to",
"a",
"factor",
".",
"The",
"image",
"is",
"pre",
"-",
"filtered",
"with",
"a",
"Gaussian",
"and",
"then",
"resampled",
"with",
"bilinear",
"interpolation",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L26-L50 |
uchicago-cs/deepdish | deepdish/image.py | asgray | def asgray(im):
"""
Takes an image and returns its grayscale version by averaging the color
channels. if an alpha channel is present, it will simply be ignored. If a
grayscale image is given, the original image is returned.
Parameters
----------
image : ndarray, ndim 2 or 3
RGB or ... | python | def asgray(im):
"""
Takes an image and returns its grayscale version by averaging the color
channels. if an alpha channel is present, it will simply be ignored. If a
grayscale image is given, the original image is returned.
Parameters
----------
image : ndarray, ndim 2 or 3
RGB or ... | [
"def",
"asgray",
"(",
"im",
")",
":",
"if",
"im",
".",
"ndim",
"==",
"2",
":",
"return",
"im",
"elif",
"im",
".",
"ndim",
"==",
"3",
"and",
"im",
".",
"shape",
"[",
"2",
"]",
"in",
"(",
"3",
",",
"4",
")",
":",
"return",
"im",
"[",
"...",
... | Takes an image and returns its grayscale version by averaging the color
channels. if an alpha channel is present, it will simply be ignored. If a
grayscale image is given, the original image is returned.
Parameters
----------
image : ndarray, ndim 2 or 3
RGB or grayscale image.
Return... | [
"Takes",
"an",
"image",
"and",
"returns",
"its",
"grayscale",
"version",
"by",
"averaging",
"the",
"color",
"channels",
".",
"if",
"an",
"alpha",
"channel",
"is",
"present",
"it",
"will",
"simply",
"be",
"ignored",
".",
"If",
"a",
"grayscale",
"image",
"is... | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L71-L92 |
uchicago-cs/deepdish | deepdish/image.py | crop | def crop(im, size):
"""
Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping.
"""
diff = [im.shape[index] - size[index] for index in (0, 1)]
im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 + size[1]]
re... | python | def crop(im, size):
"""
Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping.
"""
diff = [im.shape[index] - size[index] for index in (0, 1)]
im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 + size[1]]
re... | [
"def",
"crop",
"(",
"im",
",",
"size",
")",
":",
"diff",
"=",
"[",
"im",
".",
"shape",
"[",
"index",
"]",
"-",
"size",
"[",
"index",
"]",
"for",
"index",
"in",
"(",
"0",
",",
"1",
")",
"]",
"im2",
"=",
"im",
"[",
"diff",
"[",
"0",
"]",
"/... | Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping. | [
"Crops",
"an",
"image",
"in",
"the",
"center",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L95-L106 |
uchicago-cs/deepdish | deepdish/image.py | crop_or_pad | def crop_or_pad(im, size, value=0):
"""
Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping.
"""
diff = [im.shape[index] - size[index] for index in (0, 1)]
im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 +... | python | def crop_or_pad(im, size, value=0):
"""
Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping.
"""
diff = [im.shape[index] - size[index] for index in (0, 1)]
im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 +... | [
"def",
"crop_or_pad",
"(",
"im",
",",
"size",
",",
"value",
"=",
"0",
")",
":",
"diff",
"=",
"[",
"im",
".",
"shape",
"[",
"index",
"]",
"-",
"size",
"[",
"index",
"]",
"for",
"index",
"in",
"(",
"0",
",",
"1",
")",
"]",
"im2",
"=",
"im",
"... | Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping. | [
"Crops",
"an",
"image",
"in",
"the",
"center",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L109-L120 |
uchicago-cs/deepdish | deepdish/image.py | load | def load(path, dtype=np.float64):
"""
Loads an image from file.
Parameters
----------
path : str
Path to image file.
dtype : np.dtype
Defaults to ``np.float64``, which means the image will be returned as a
float with values between 0 and 1. If ``np.uint8`` is specified, ... | python | def load(path, dtype=np.float64):
"""
Loads an image from file.
Parameters
----------
path : str
Path to image file.
dtype : np.dtype
Defaults to ``np.float64``, which means the image will be returned as a
float with values between 0 and 1. If ``np.uint8`` is specified, ... | [
"def",
"load",
"(",
"path",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
":",
"_import_skimage",
"(",
")",
"import",
"skimage",
".",
"io",
"im",
"=",
"skimage",
".",
"io",
".",
"imread",
"(",
"path",
")",
"if",
"dtype",
"==",
"np",
".",
"uint8",
... | Loads an image from file.
Parameters
----------
path : str
Path to image file.
dtype : np.dtype
Defaults to ``np.float64``, which means the image will be returned as a
float with values between 0 and 1. If ``np.uint8`` is specified, the
values will be between 0 and 255 a... | [
"Loads",
"an",
"image",
"from",
"file",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L135-L157 |
uchicago-cs/deepdish | deepdish/image.py | load_raw | def load_raw(path):
"""
Load image using PIL/Pillow without any processing. This is particularly
useful for palette images, which will be loaded using their palette index
values as opposed to `load` which will convert them to RGB.
Parameters
----------
path : str
Path to image file.... | python | def load_raw(path):
"""
Load image using PIL/Pillow without any processing. This is particularly
useful for palette images, which will be loaded using their palette index
values as opposed to `load` which will convert them to RGB.
Parameters
----------
path : str
Path to image file.... | [
"def",
"load_raw",
"(",
"path",
")",
":",
"_import_pil",
"(",
")",
"from",
"PIL",
"import",
"Image",
"return",
"np",
".",
"array",
"(",
"Image",
".",
"open",
"(",
"path",
")",
")"
] | Load image using PIL/Pillow without any processing. This is particularly
useful for palette images, which will be loaded using their palette index
values as opposed to `load` which will convert them to RGB.
Parameters
----------
path : str
Path to image file. | [
"Load",
"image",
"using",
"PIL",
"/",
"Pillow",
"without",
"any",
"processing",
".",
"This",
"is",
"particularly",
"useful",
"for",
"palette",
"images",
"which",
"will",
"be",
"loaded",
"using",
"their",
"palette",
"index",
"values",
"as",
"opposed",
"to",
"... | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L160-L173 |
uchicago-cs/deepdish | deepdish/image.py | save | def save(path, im):
"""
Saves an image to file.
If the image is type float, it will assume to have values in [0, 1].
Parameters
----------
path : str
Path to which the image will be saved.
im : ndarray (image)
Image.
"""
from PIL import Image
if im.dtype == np.u... | python | def save(path, im):
"""
Saves an image to file.
If the image is type float, it will assume to have values in [0, 1].
Parameters
----------
path : str
Path to which the image will be saved.
im : ndarray (image)
Image.
"""
from PIL import Image
if im.dtype == np.u... | [
"def",
"save",
"(",
"path",
",",
"im",
")",
":",
"from",
"PIL",
"import",
"Image",
"if",
"im",
".",
"dtype",
"==",
"np",
".",
"uint8",
":",
"pil_im",
"=",
"Image",
".",
"fromarray",
"(",
"im",
")",
"else",
":",
"pil_im",
"=",
"Image",
".",
"froma... | Saves an image to file.
If the image is type float, it will assume to have values in [0, 1].
Parameters
----------
path : str
Path to which the image will be saved.
im : ndarray (image)
Image. | [
"Saves",
"an",
"image",
"to",
"file",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L176-L194 |
uchicago-cs/deepdish | deepdish/image.py | integrate | def integrate(ii, r0, c0, r1, c1):
"""
Use an integral image to integrate over a given window.
Parameters
----------
ii : ndarray
Integral image.
r0, c0 : int
Top-left corner of block to be summed.
r1, c1 : int
Bottom-right corner of block to be summed.
Returns
... | python | def integrate(ii, r0, c0, r1, c1):
"""
Use an integral image to integrate over a given window.
Parameters
----------
ii : ndarray
Integral image.
r0, c0 : int
Top-left corner of block to be summed.
r1, c1 : int
Bottom-right corner of block to be summed.
Returns
... | [
"def",
"integrate",
"(",
"ii",
",",
"r0",
",",
"c0",
",",
"r1",
",",
"c1",
")",
":",
"# This line is modified",
"S",
"=",
"np",
".",
"zeros",
"(",
"ii",
".",
"shape",
"[",
"-",
"1",
"]",
")",
"S",
"+=",
"ii",
"[",
"r1",
",",
"c1",
"]",
"if",
... | Use an integral image to integrate over a given window.
Parameters
----------
ii : ndarray
Integral image.
r0, c0 : int
Top-left corner of block to be summed.
r1, c1 : int
Bottom-right corner of block to be summed.
Returns
-------
S : int
Integral (sum) ... | [
"Use",
"an",
"integral",
"image",
"to",
"integrate",
"over",
"a",
"given",
"window",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L197-L230 |
uchicago-cs/deepdish | deepdish/image.py | offset | def offset(img, offset, fill_value=0):
"""
Moves the contents of image without changing the image size. The missing
values are given a specified fill value.
Parameters
----------
img : array
Image.
offset : (vertical_offset, horizontal_offset)
Tuple of length 2, specifying t... | python | def offset(img, offset, fill_value=0):
"""
Moves the contents of image without changing the image size. The missing
values are given a specified fill value.
Parameters
----------
img : array
Image.
offset : (vertical_offset, horizontal_offset)
Tuple of length 2, specifying t... | [
"def",
"offset",
"(",
"img",
",",
"offset",
",",
"fill_value",
"=",
"0",
")",
":",
"sh",
"=",
"img",
".",
"shape",
"if",
"sh",
"==",
"(",
"0",
",",
"0",
")",
":",
"return",
"img",
"else",
":",
"x",
"=",
"np",
".",
"empty",
"(",
"sh",
")",
"... | Moves the contents of image without changing the image size. The missing
values are given a specified fill value.
Parameters
----------
img : array
Image.
offset : (vertical_offset, horizontal_offset)
Tuple of length 2, specifying the offset along the two axes.
fill_value : dtyp... | [
"Moves",
"the",
"contents",
"of",
"image",
"without",
"changing",
"the",
"image",
"size",
".",
"The",
"missing",
"values",
"are",
"given",
"a",
"specified",
"fill",
"value",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L233-L258 |
uchicago-cs/deepdish | deepdish/image.py | bounding_box | def bounding_box(alpha, threshold=0.1):
"""
Returns a bounding box of the support.
Parameters
----------
alpha : ndarray, ndim=2
Any one-channel image where the background has zero or low intensity.
threshold : float
The threshold that divides background from foreground.
Re... | python | def bounding_box(alpha, threshold=0.1):
"""
Returns a bounding box of the support.
Parameters
----------
alpha : ndarray, ndim=2
Any one-channel image where the background has zero or low intensity.
threshold : float
The threshold that divides background from foreground.
Re... | [
"def",
"bounding_box",
"(",
"alpha",
",",
"threshold",
"=",
"0.1",
")",
":",
"assert",
"alpha",
".",
"ndim",
"==",
"2",
"# Take the bounding box of the support, with a certain threshold.",
"supp_axs",
"=",
"[",
"alpha",
".",
"max",
"(",
"axis",
"=",
"1",
"-",
... | Returns a bounding box of the support.
Parameters
----------
alpha : ndarray, ndim=2
Any one-channel image where the background has zero or low intensity.
threshold : float
The threshold that divides background from foreground.
Returns
-------
bounding_box : (top, left, bot... | [
"Returns",
"a",
"bounding",
"box",
"of",
"the",
"support",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L261-L286 |
uchicago-cs/deepdish | deepdish/image.py | bounding_box_as_binary_map | def bounding_box_as_binary_map(alpha, threshold=0.1):
"""
Similar to `bounding_box`, except returns the bounding box as a
binary map the same size as the input.
Same parameters as `bounding_box`.
Returns
-------
binary_map : ndarray, ndim=2, dtype=np.bool_
Binary map with True if o... | python | def bounding_box_as_binary_map(alpha, threshold=0.1):
"""
Similar to `bounding_box`, except returns the bounding box as a
binary map the same size as the input.
Same parameters as `bounding_box`.
Returns
-------
binary_map : ndarray, ndim=2, dtype=np.bool_
Binary map with True if o... | [
"def",
"bounding_box_as_binary_map",
"(",
"alpha",
",",
"threshold",
"=",
"0.1",
")",
":",
"bb",
"=",
"bounding_box",
"(",
"alpha",
")",
"x",
"=",
"np",
".",
"zeros",
"(",
"alpha",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"bool_",
")",
"x",
"[",
... | Similar to `bounding_box`, except returns the bounding box as a
binary map the same size as the input.
Same parameters as `bounding_box`.
Returns
-------
binary_map : ndarray, ndim=2, dtype=np.bool_
Binary map with True if object and False if background. | [
"Similar",
"to",
"bounding_box",
"except",
"returns",
"the",
"bounding",
"box",
"as",
"a",
"binary",
"map",
"the",
"same",
"size",
"as",
"the",
"input",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L289-L305 |
uchicago-cs/deepdish | deepdish/image.py | extract_patches | def extract_patches(images, patch_shape, samples_per_image=40, seed=0,
cycle=True):
"""
Takes a set of images and yields randomly chosen patches of specified size.
Parameters
----------
images : iterable
The images have to be iterable, and each element must be a Numpy ar... | python | def extract_patches(images, patch_shape, samples_per_image=40, seed=0,
cycle=True):
"""
Takes a set of images and yields randomly chosen patches of specified size.
Parameters
----------
images : iterable
The images have to be iterable, and each element must be a Numpy ar... | [
"def",
"extract_patches",
"(",
"images",
",",
"patch_shape",
",",
"samples_per_image",
"=",
"40",
",",
"seed",
"=",
"0",
",",
"cycle",
"=",
"True",
")",
":",
"rs",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
")",
"for",
"Xi",
"in",
"it... | Takes a set of images and yields randomly chosen patches of specified size.
Parameters
----------
images : iterable
The images have to be iterable, and each element must be a Numpy array
with at least two spatial 2 dimensions as the first and second axis.
patch_shape : tuple, length 2
... | [
"Takes",
"a",
"set",
"of",
"images",
"and",
"yields",
"randomly",
"chosen",
"patches",
"of",
"specified",
"size",
"."
] | train | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L308-L366 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.