repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
JustinLovinger/optimal | optimal/algorithms/gaoperators.py | _fitnesses_to_probabilities | def _fitnesses_to_probabilities(fitnesses):
"""Return a list of probabilities proportional to fitnesses."""
# Do not allow negative fitness values
min_fitness = min(fitnesses)
if min_fitness < 0.0:
# Make smallest fitness value 0
fitnesses = map(lambda f: f - min_fitness, fitnesses)
... | python | def _fitnesses_to_probabilities(fitnesses):
"""Return a list of probabilities proportional to fitnesses."""
# Do not allow negative fitness values
min_fitness = min(fitnesses)
if min_fitness < 0.0:
# Make smallest fitness value 0
fitnesses = map(lambda f: f - min_fitness, fitnesses)
... | [
"def",
"_fitnesses_to_probabilities",
"(",
"fitnesses",
")",
":",
"# Do not allow negative fitness values",
"min_fitness",
"=",
"min",
"(",
"fitnesses",
")",
"if",
"min_fitness",
"<",
"0.0",
":",
"# Make smallest fitness value 0",
"fitnesses",
"=",
"map",
"(",
"lambda",... | Return a list of probabilities proportional to fitnesses. | [
"Return",
"a",
"list",
"of",
"probabilities",
"proportional",
"to",
"fitnesses",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L182-L206 |
JustinLovinger/optimal | optimal/algorithms/gaoperators.py | one_point_crossover | def one_point_crossover(parents):
"""Perform one point crossover on two parent chromosomes.
Select a random position in the chromosome.
Take genes to the left from one parent and the rest from the other parent.
Ex. p1 = xxxxx, p2 = yyyyy, position = 2 (starting at 0), child = xxyyy
"""
# The po... | python | def one_point_crossover(parents):
"""Perform one point crossover on two parent chromosomes.
Select a random position in the chromosome.
Take genes to the left from one parent and the rest from the other parent.
Ex. p1 = xxxxx, p2 = yyyyy, position = 2 (starting at 0), child = xxyyy
"""
# The po... | [
"def",
"one_point_crossover",
"(",
"parents",
")",
":",
"# The point that the chromosomes will be crossed at (see Ex. above)",
"crossover_point",
"=",
"random",
".",
"randint",
"(",
"1",
",",
"len",
"(",
"parents",
"[",
"0",
"]",
")",
"-",
"1",
")",
"return",
"(",... | Perform one point crossover on two parent chromosomes.
Select a random position in the chromosome.
Take genes to the left from one parent and the rest from the other parent.
Ex. p1 = xxxxx, p2 = yyyyy, position = 2 (starting at 0), child = xxyyy | [
"Perform",
"one",
"point",
"crossover",
"on",
"two",
"parent",
"chromosomes",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L212-L223 |
JustinLovinger/optimal | optimal/algorithms/gaoperators.py | uniform_crossover | def uniform_crossover(parents):
"""Perform uniform crossover on two parent chromosomes.
Randomly take genes from one parent or the other.
Ex. p1 = xxxxx, p2 = yyyyy, child = xyxxy
"""
chromosome_length = len(parents[0])
children = [[], []]
for i in range(chromosome_length):
select... | python | def uniform_crossover(parents):
"""Perform uniform crossover on two parent chromosomes.
Randomly take genes from one parent or the other.
Ex. p1 = xxxxx, p2 = yyyyy, child = xyxxy
"""
chromosome_length = len(parents[0])
children = [[], []]
for i in range(chromosome_length):
select... | [
"def",
"uniform_crossover",
"(",
"parents",
")",
":",
"chromosome_length",
"=",
"len",
"(",
"parents",
"[",
"0",
"]",
")",
"children",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"for",
"i",
"in",
"range",
"(",
"chromosome_length",
")",
":",
"selected_pare... | Perform uniform crossover on two parent chromosomes.
Randomly take genes from one parent or the other.
Ex. p1 = xxxxx, p2 = yyyyy, child = xyxxy | [
"Perform",
"uniform",
"crossover",
"on",
"two",
"parent",
"chromosomes",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L230-L248 |
JustinLovinger/optimal | optimal/algorithms/gaoperators.py | random_flip_mutate | def random_flip_mutate(population, mutation_chance):
"""Mutate every chromosome in a population, list is modified in place.
Mutation occurs by randomly flipping bits (genes).
"""
for chromosome in population: # For every chromosome in the population
for i in range(len(chromosome)): # For ever... | python | def random_flip_mutate(population, mutation_chance):
"""Mutate every chromosome in a population, list is modified in place.
Mutation occurs by randomly flipping bits (genes).
"""
for chromosome in population: # For every chromosome in the population
for i in range(len(chromosome)): # For ever... | [
"def",
"random_flip_mutate",
"(",
"population",
",",
"mutation_chance",
")",
":",
"for",
"chromosome",
"in",
"population",
":",
"# For every chromosome in the population",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"chromosome",
")",
")",
":",
"# For every bit in t... | Mutate every chromosome in a population, list is modified in place.
Mutation occurs by randomly flipping bits (genes). | [
"Mutate",
"every",
"chromosome",
"in",
"a",
"population",
"list",
"is",
"modified",
"in",
"place",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L254-L263 |
JustinLovinger/optimal | optimal/optimize.py | _duplicates | def _duplicates(list_):
"""Return dict mapping item -> indices."""
item_indices = {}
for i, item in enumerate(list_):
try:
item_indices[item].append(i)
except KeyError: # First time seen
item_indices[item] = [i]
return item_indices | python | def _duplicates(list_):
"""Return dict mapping item -> indices."""
item_indices = {}
for i, item in enumerate(list_):
try:
item_indices[item].append(i)
except KeyError: # First time seen
item_indices[item] = [i]
return item_indices | [
"def",
"_duplicates",
"(",
"list_",
")",
":",
"item_indices",
"=",
"{",
"}",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"list_",
")",
":",
"try",
":",
"item_indices",
"[",
"item",
"]",
".",
"append",
"(",
"i",
")",
"except",
"KeyError",
":",
... | Return dict mapping item -> indices. | [
"Return",
"dict",
"mapping",
"item",
"-",
">",
"indices",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L718-L726 |
JustinLovinger/optimal | optimal/optimize.py | _parse_parameter_locks | def _parse_parameter_locks(optimizer, meta_parameters, parameter_locks):
"""Synchronize meta_parameters and locked_values.
The union of these two sets will have all necessary parameters.
locked_values will have the parameters specified in parameter_locks.
"""
# WARNING: meta_parameters is modified ... | python | def _parse_parameter_locks(optimizer, meta_parameters, parameter_locks):
"""Synchronize meta_parameters and locked_values.
The union of these two sets will have all necessary parameters.
locked_values will have the parameters specified in parameter_locks.
"""
# WARNING: meta_parameters is modified ... | [
"def",
"_parse_parameter_locks",
"(",
"optimizer",
",",
"meta_parameters",
",",
"parameter_locks",
")",
":",
"# WARNING: meta_parameters is modified inline",
"locked_values",
"=",
"{",
"}",
"if",
"parameter_locks",
":",
"for",
"name",
"in",
"parameter_locks",
":",
"# St... | Synchronize meta_parameters and locked_values.
The union of these two sets will have all necessary parameters.
locked_values will have the parameters specified in parameter_locks. | [
"Synchronize",
"meta_parameters",
"and",
"locked_values",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L740-L756 |
JustinLovinger/optimal | optimal/optimize.py | _get_hyperparameter_solution_size | def _get_hyperparameter_solution_size(meta_parameters):
"""Determine size of binary encoding of parameters.
Also adds binary size information for each parameter.
"""
# WARNING: meta_parameters is modified inline
solution_size = 0
for _, parameters in meta_parameters.iteritems():
if par... | python | def _get_hyperparameter_solution_size(meta_parameters):
"""Determine size of binary encoding of parameters.
Also adds binary size information for each parameter.
"""
# WARNING: meta_parameters is modified inline
solution_size = 0
for _, parameters in meta_parameters.iteritems():
if par... | [
"def",
"_get_hyperparameter_solution_size",
"(",
"meta_parameters",
")",
":",
"# WARNING: meta_parameters is modified inline",
"solution_size",
"=",
"0",
"for",
"_",
",",
"parameters",
"in",
"meta_parameters",
".",
"iteritems",
"(",
")",
":",
"if",
"parameters",
"[",
... | Determine size of binary encoding of parameters.
Also adds binary size information for each parameter. | [
"Determine",
"size",
"of",
"binary",
"encoding",
"of",
"parameters",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L759-L791 |
JustinLovinger/optimal | optimal/optimize.py | _make_hyperparameter_decode_func | def _make_hyperparameter_decode_func(locked_values, meta_parameters):
"""Create a function that converts the binary solution to parameters."""
# Locked parameters are also returned by decode function, but are not
# based on solution
def decode(solution):
"""Convert solution into dict of hyperp... | python | def _make_hyperparameter_decode_func(locked_values, meta_parameters):
"""Create a function that converts the binary solution to parameters."""
# Locked parameters are also returned by decode function, but are not
# based on solution
def decode(solution):
"""Convert solution into dict of hyperp... | [
"def",
"_make_hyperparameter_decode_func",
"(",
"locked_values",
",",
"meta_parameters",
")",
":",
"# Locked parameters are also returned by decode function, but are not",
"# based on solution",
"def",
"decode",
"(",
"solution",
")",
":",
"\"\"\"Convert solution into dict of hyperpar... | Create a function that converts the binary solution to parameters. | [
"Create",
"a",
"function",
"that",
"converts",
"the",
"binary",
"solution",
"to",
"parameters",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L794-L838 |
JustinLovinger/optimal | optimal/optimize.py | _meta_fitness_func | def _meta_fitness_func(parameters,
_optimizer,
_problems,
_master_fitness_dict,
_runs=20):
"""Test a metaheuristic with parameters encoded in solution.
Our goal is to minimize number of evaluation runs until a solution ... | python | def _meta_fitness_func(parameters,
_optimizer,
_problems,
_master_fitness_dict,
_runs=20):
"""Test a metaheuristic with parameters encoded in solution.
Our goal is to minimize number of evaluation runs until a solution ... | [
"def",
"_meta_fitness_func",
"(",
"parameters",
",",
"_optimizer",
",",
"_problems",
",",
"_master_fitness_dict",
",",
"_runs",
"=",
"20",
")",
":",
"# Create the optimizer with parameters encoded in solution",
"optimizer",
"=",
"copy",
".",
"deepcopy",
"(",
"_optimizer... | Test a metaheuristic with parameters encoded in solution.
Our goal is to minimize number of evaluation runs until a solution is found,
while maximizing chance of finding solution to the underlying problem
NOTE: while meta optimization requires a 'known' solution, this solution
can be an estimate to pro... | [
"Test",
"a",
"metaheuristic",
"with",
"parameters",
"encoded",
"in",
"solution",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L841-L886 |
JustinLovinger/optimal | optimal/optimize.py | Problem.copy | def copy(self,
fitness_function=None,
decode_function=None,
fitness_args=None,
decode_args=None,
fitness_kwargs=None,
decode_kwargs=None):
"""Return a copy of this problem.
Optionally replace this problems arguments with thos... | python | def copy(self,
fitness_function=None,
decode_function=None,
fitness_args=None,
decode_args=None,
fitness_kwargs=None,
decode_kwargs=None):
"""Return a copy of this problem.
Optionally replace this problems arguments with thos... | [
"def",
"copy",
"(",
"self",
",",
"fitness_function",
"=",
"None",
",",
"decode_function",
"=",
"None",
",",
"fitness_args",
"=",
"None",
",",
"decode_args",
"=",
"None",
",",
"fitness_kwargs",
"=",
"None",
",",
"decode_kwargs",
"=",
"None",
")",
":",
"if",... | Return a copy of this problem.
Optionally replace this problems arguments with those passed in. | [
"Return",
"a",
"copy",
"of",
"this",
"problem",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L101-L131 |
JustinLovinger/optimal | optimal/optimize.py | Problem.get_fitness | def get_fitness(self, solution):
"""Return fitness for the given solution."""
return self._fitness_function(solution, *self._fitness_args,
**self._fitness_kwargs) | python | def get_fitness(self, solution):
"""Return fitness for the given solution."""
return self._fitness_function(solution, *self._fitness_args,
**self._fitness_kwargs) | [
"def",
"get_fitness",
"(",
"self",
",",
"solution",
")",
":",
"return",
"self",
".",
"_fitness_function",
"(",
"solution",
",",
"*",
"self",
".",
"_fitness_args",
",",
"*",
"*",
"self",
".",
"_fitness_kwargs",
")"
] | Return fitness for the given solution. | [
"Return",
"fitness",
"for",
"the",
"given",
"solution",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L133-L136 |
JustinLovinger/optimal | optimal/optimize.py | Problem.decode_solution | def decode_solution(self, encoded_solution):
"""Return solution from an encoded representation."""
return self._decode_function(encoded_solution, *self._decode_args,
**self._decode_kwargs) | python | def decode_solution(self, encoded_solution):
"""Return solution from an encoded representation."""
return self._decode_function(encoded_solution, *self._decode_args,
**self._decode_kwargs) | [
"def",
"decode_solution",
"(",
"self",
",",
"encoded_solution",
")",
":",
"return",
"self",
".",
"_decode_function",
"(",
"encoded_solution",
",",
"*",
"self",
".",
"_decode_args",
",",
"*",
"*",
"self",
".",
"_decode_kwargs",
")"
] | Return solution from an encoded representation. | [
"Return",
"solution",
"from",
"an",
"encoded",
"representation",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L138-L141 |
JustinLovinger/optimal | optimal/optimize.py | Optimizer.optimize | def optimize(self, problem, max_iterations=100, max_seconds=float('inf'),
cache_encoded=True, cache_solution=False, clear_cache=True,
logging_func=_print_fitnesses,
n_processes=0):
"""Find the optimal inputs for a given fitness function.
Args:
... | python | def optimize(self, problem, max_iterations=100, max_seconds=float('inf'),
cache_encoded=True, cache_solution=False, clear_cache=True,
logging_func=_print_fitnesses,
n_processes=0):
"""Find the optimal inputs for a given fitness function.
Args:
... | [
"def",
"optimize",
"(",
"self",
",",
"problem",
",",
"max_iterations",
"=",
"100",
",",
"max_seconds",
"=",
"float",
"(",
"'inf'",
")",
",",
"cache_encoded",
"=",
"True",
",",
"cache_solution",
"=",
"False",
",",
"clear_cache",
"=",
"True",
",",
"logging_f... | Find the optimal inputs for a given fitness function.
Args:
problem: An instance of Problem. The problem to solve.
max_iterations: The number of iterations to optimize before stopping.
max_seconds: Maximum number of seconds to optimize for, before stopping.
N... | [
"Find",
"the",
"optimal",
"inputs",
"for",
"a",
"given",
"fitness",
"function",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L198-L319 |
JustinLovinger/optimal | optimal/optimize.py | Optimizer._reset_bookkeeping | def _reset_bookkeeping(self):
"""Reset bookkeeping parameters to initial values.
Call before beginning optimization.
"""
self.iteration = 0
self.fitness_runs = 0
self.best_solution = None
self.best_fitness = None
self.solution_found = False | python | def _reset_bookkeeping(self):
"""Reset bookkeeping parameters to initial values.
Call before beginning optimization.
"""
self.iteration = 0
self.fitness_runs = 0
self.best_solution = None
self.best_fitness = None
self.solution_found = False | [
"def",
"_reset_bookkeeping",
"(",
"self",
")",
":",
"self",
".",
"iteration",
"=",
"0",
"self",
".",
"fitness_runs",
"=",
"0",
"self",
".",
"best_solution",
"=",
"None",
"self",
".",
"best_fitness",
"=",
"None",
"self",
".",
"solution_found",
"=",
"False"
... | Reset bookkeeping parameters to initial values.
Call before beginning optimization. | [
"Reset",
"bookkeeping",
"parameters",
"to",
"initial",
"values",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L325-L334 |
JustinLovinger/optimal | optimal/optimize.py | Optimizer._get_fitnesses | def _get_fitnesses(self,
problem,
population,
cache_encoded=True,
cache_solution=False,
pool=None):
"""Get the fitness for every solution in a population.
Args:
problem: Proble... | python | def _get_fitnesses(self,
problem,
population,
cache_encoded=True,
cache_solution=False,
pool=None):
"""Get the fitness for every solution in a population.
Args:
problem: Proble... | [
"def",
"_get_fitnesses",
"(",
"self",
",",
"problem",
",",
"population",
",",
"cache_encoded",
"=",
"True",
",",
"cache_solution",
"=",
"False",
",",
"pool",
"=",
"None",
")",
":",
"fitnesses",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"population",
")",
... | Get the fitness for every solution in a population.
Args:
problem: Problem; The problem that defines fitness.
population: list; List of potential solutions.
pool: None/multiprocessing.Pool; Pool of processes for parallel
decoding and evaluation. | [
"Get",
"the",
"fitness",
"for",
"every",
"solution",
"in",
"a",
"population",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L336-L475 |
JustinLovinger/optimal | optimal/optimize.py | Optimizer._pmap | def _pmap(self, func, items, keys, pool, bookkeeping_dict=None):
"""Efficiently map func over all items.
Calls func only once for duplicate items.
Item duplicates are detected by corresponding keys.
Unless keys is None.
Serial if pool is None, but still skips duplicates... | python | def _pmap(self, func, items, keys, pool, bookkeeping_dict=None):
"""Efficiently map func over all items.
Calls func only once for duplicate items.
Item duplicates are detected by corresponding keys.
Unless keys is None.
Serial if pool is None, but still skips duplicates... | [
"def",
"_pmap",
"(",
"self",
",",
"func",
",",
"items",
",",
"keys",
",",
"pool",
",",
"bookkeeping_dict",
"=",
"None",
")",
":",
"if",
"keys",
"is",
"not",
"None",
":",
"# Otherwise, cannot hash items",
"# Remove duplicates first (use keys)",
"# Create mapping (d... | Efficiently map func over all items.
Calls func only once for duplicate items.
Item duplicates are detected by corresponding keys.
Unless keys is None.
Serial if pool is None, but still skips duplicates. | [
"Efficiently",
"map",
"func",
"over",
"all",
"items",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L477-L517 |
JustinLovinger/optimal | optimal/optimize.py | Optimizer._set_hyperparameters | def _set_hyperparameters(self, parameters):
"""Set internal optimization parameters."""
for name, value in parameters.iteritems():
try:
getattr(self, name)
except AttributeError:
raise ValueError(
'Each parameter in parameters m... | python | def _set_hyperparameters(self, parameters):
"""Set internal optimization parameters."""
for name, value in parameters.iteritems():
try:
getattr(self, name)
except AttributeError:
raise ValueError(
'Each parameter in parameters m... | [
"def",
"_set_hyperparameters",
"(",
"self",
",",
"parameters",
")",
":",
"for",
"name",
",",
"value",
"in",
"parameters",
".",
"iteritems",
"(",
")",
":",
"try",
":",
"getattr",
"(",
"self",
",",
"name",
")",
"except",
"AttributeError",
":",
"raise",
"Va... | Set internal optimization parameters. | [
"Set",
"internal",
"optimization",
"parameters",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L533-L542 |
JustinLovinger/optimal | optimal/optimize.py | Optimizer._get_hyperparameters | def _get_hyperparameters(self):
"""Get internal optimization parameters."""
hyperparameters = {}
for key in self._hyperparameters:
hyperparameters[key] = getattr(self, key)
return hyperparameters | python | def _get_hyperparameters(self):
"""Get internal optimization parameters."""
hyperparameters = {}
for key in self._hyperparameters:
hyperparameters[key] = getattr(self, key)
return hyperparameters | [
"def",
"_get_hyperparameters",
"(",
"self",
")",
":",
"hyperparameters",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_hyperparameters",
":",
"hyperparameters",
"[",
"key",
"]",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"return",
"hyperparameters"
] | Get internal optimization parameters. | [
"Get",
"internal",
"optimization",
"parameters",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L544-L549 |
JustinLovinger/optimal | optimal/optimize.py | Optimizer.optimize_hyperparameters | def optimize_hyperparameters(self,
problems,
parameter_locks=None,
smoothing=20,
max_iterations=100,
_meta_optimizer=None,
... | python | def optimize_hyperparameters(self,
problems,
parameter_locks=None,
smoothing=20,
max_iterations=100,
_meta_optimizer=None,
... | [
"def",
"optimize_hyperparameters",
"(",
"self",
",",
"problems",
",",
"parameter_locks",
"=",
"None",
",",
"smoothing",
"=",
"20",
",",
"max_iterations",
"=",
"100",
",",
"_meta_optimizer",
"=",
"None",
",",
"_low_memory",
"=",
"True",
")",
":",
"if",
"smoot... | Optimize hyperparameters for a given problem.
Args:
parameter_locks: a list of strings, each corresponding to a hyperparamter
that should not be optimized.
problems: Either a single problem, or a list of problem instances,
allowing optim... | [
"Optimize",
"hyperparameters",
"for",
"a",
"given",
"problem",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L551-L642 |
JustinLovinger/optimal | optimal/benchmark.py | compare | def compare(optimizers, problems, runs=20, all_kwargs={}):
"""Compare a set of optimizers.
Args:
optimizers: list/Optimizer; Either a list of optimizers to compare,
or a single optimizer to test on each problem.
problems: list/Problem; Either a problem instance or a list of problem ... | python | def compare(optimizers, problems, runs=20, all_kwargs={}):
"""Compare a set of optimizers.
Args:
optimizers: list/Optimizer; Either a list of optimizers to compare,
or a single optimizer to test on each problem.
problems: list/Problem; Either a problem instance or a list of problem ... | [
"def",
"compare",
"(",
"optimizers",
",",
"problems",
",",
"runs",
"=",
"20",
",",
"all_kwargs",
"=",
"{",
"}",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"optimizers",
",",
"collections",
".",
"Iterable",
")",
"or",
"isinstance",
"(",
"problems",
... | Compare a set of optimizers.
Args:
optimizers: list/Optimizer; Either a list of optimizers to compare,
or a single optimizer to test on each problem.
problems: list/Problem; Either a problem instance or a list of problem instances,
one for each optimizer.
all_kwargs:... | [
"Compare",
"a",
"set",
"of",
"optimizers",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/benchmark.py#L37-L96 |
JustinLovinger/optimal | optimal/benchmark.py | benchmark | def benchmark(optimizer, problem, runs=20, **kwargs):
"""Run an optimizer through a problem multiple times.
Args:
optimizer: Optimizer; The optimizer to benchmark.
problem: Problem; The problem to benchmark on.
runs: int > 0; Number of times that optimize is called on problem.
Retu... | python | def benchmark(optimizer, problem, runs=20, **kwargs):
"""Run an optimizer through a problem multiple times.
Args:
optimizer: Optimizer; The optimizer to benchmark.
problem: Problem; The problem to benchmark on.
runs: int > 0; Number of times that optimize is called on problem.
Retu... | [
"def",
"benchmark",
"(",
"optimizer",
",",
"problem",
",",
"runs",
"=",
"20",
",",
"*",
"*",
"kwargs",
")",
":",
"stats",
"=",
"{",
"'runs'",
":",
"[",
"]",
"}",
"# Disable logging, to avoid spamming the user",
"# TODO: Maybe we shouldn't disable by default?",
"kw... | Run an optimizer through a problem multiple times.
Args:
optimizer: Optimizer; The optimizer to benchmark.
problem: Problem; The problem to benchmark on.
runs: int > 0; Number of times that optimize is called on problem.
Returns:
dict; A dictionary of various statistics. | [
"Run",
"an",
"optimizer",
"through",
"a",
"problem",
"multiple",
"times",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/benchmark.py#L99-L143 |
JustinLovinger/optimal | optimal/benchmark.py | aggregate | def aggregate(all_stats):
"""Combine stats for multiple optimizers to obtain one mean and sd.
Useful for combining stats for the same optimizer class and multiple problems.
Args:
all_stats: dict; output from compare.
"""
aggregate_stats = {'means': [], 'standard_deviations': []}
for op... | python | def aggregate(all_stats):
"""Combine stats for multiple optimizers to obtain one mean and sd.
Useful for combining stats for the same optimizer class and multiple problems.
Args:
all_stats: dict; output from compare.
"""
aggregate_stats = {'means': [], 'standard_deviations': []}
for op... | [
"def",
"aggregate",
"(",
"all_stats",
")",
":",
"aggregate_stats",
"=",
"{",
"'means'",
":",
"[",
"]",
",",
"'standard_deviations'",
":",
"[",
"]",
"}",
"for",
"optimizer_key",
"in",
"all_stats",
":",
"# runs is the mean, for add_mean_sd function",
"mean_stats",
"... | Combine stats for multiple optimizers to obtain one mean and sd.
Useful for combining stats for the same optimizer class and multiple problems.
Args:
all_stats: dict; output from compare. | [
"Combine",
"stats",
"for",
"multiple",
"optimizers",
"to",
"obtain",
"one",
"mean",
"and",
"sd",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/benchmark.py#L146-L169 |
JustinLovinger/optimal | optimal/benchmark.py | _mean_of_runs | def _mean_of_runs(stats, key='runs'):
"""Obtain the mean of stats.
Args:
stats: dict; A set of stats, structured as above.
key: str; Optional key to determine where list of runs is found in stats
"""
num_runs = len(stats[key])
first = stats[key][0]
mean = {}
for stat_key i... | python | def _mean_of_runs(stats, key='runs'):
"""Obtain the mean of stats.
Args:
stats: dict; A set of stats, structured as above.
key: str; Optional key to determine where list of runs is found in stats
"""
num_runs = len(stats[key])
first = stats[key][0]
mean = {}
for stat_key i... | [
"def",
"_mean_of_runs",
"(",
"stats",
",",
"key",
"=",
"'runs'",
")",
":",
"num_runs",
"=",
"len",
"(",
"stats",
"[",
"key",
"]",
")",
"first",
"=",
"stats",
"[",
"key",
"]",
"[",
"0",
"]",
"mean",
"=",
"{",
"}",
"for",
"stat_key",
"in",
"first",... | Obtain the mean of stats.
Args:
stats: dict; A set of stats, structured as above.
key: str; Optional key to determine where list of runs is found in stats | [
"Obtain",
"the",
"mean",
"of",
"stats",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/benchmark.py#L180-L198 |
JustinLovinger/optimal | optimal/benchmark.py | _sd_of_runs | def _sd_of_runs(stats, mean, key='runs'):
"""Obtain the standard deviation of stats.
Args:
stats: dict; A set of stats, structured as above.
mean: dict; Mean for each key in stats.
key: str; Optional key to determine where list of runs is found in stats
"""
num_runs = len(stats... | python | def _sd_of_runs(stats, mean, key='runs'):
"""Obtain the standard deviation of stats.
Args:
stats: dict; A set of stats, structured as above.
mean: dict; Mean for each key in stats.
key: str; Optional key to determine where list of runs is found in stats
"""
num_runs = len(stats... | [
"def",
"_sd_of_runs",
"(",
"stats",
",",
"mean",
",",
"key",
"=",
"'runs'",
")",
":",
"num_runs",
"=",
"len",
"(",
"stats",
"[",
"key",
"]",
")",
"first",
"=",
"stats",
"[",
"key",
"]",
"[",
"0",
"]",
"standard_deviation",
"=",
"{",
"}",
"for",
"... | Obtain the standard deviation of stats.
Args:
stats: dict; A set of stats, structured as above.
mean: dict; Mean for each key in stats.
key: str; Optional key to determine where list of runs is found in stats | [
"Obtain",
"the",
"standard",
"deviation",
"of",
"stats",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/benchmark.py#L201-L221 |
JustinLovinger/optimal | optimal/algorithms/pbil.py | _sample | def _sample(probability_vec):
"""Return random binary string, with given probabilities."""
return map(int,
numpy.random.random(probability_vec.size) <= probability_vec) | python | def _sample(probability_vec):
"""Return random binary string, with given probabilities."""
return map(int,
numpy.random.random(probability_vec.size) <= probability_vec) | [
"def",
"_sample",
"(",
"probability_vec",
")",
":",
"return",
"map",
"(",
"int",
",",
"numpy",
".",
"random",
".",
"random",
"(",
"probability_vec",
".",
"size",
")",
"<=",
"probability_vec",
")"
] | Return random binary string, with given probabilities. | [
"Return",
"random",
"binary",
"string",
"with",
"given",
"probabilities",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/pbil.py#L126-L129 |
JustinLovinger/optimal | optimal/algorithms/pbil.py | _adjust_probability_vec_best | def _adjust_probability_vec_best(population, fitnesses, probability_vec,
adjust_rate):
"""Shift probabilities towards the best solution."""
best_solution = max(zip(fitnesses, population))[1]
# Shift probabilities towards best solution
return _adjust(probability_vec, bes... | python | def _adjust_probability_vec_best(population, fitnesses, probability_vec,
adjust_rate):
"""Shift probabilities towards the best solution."""
best_solution = max(zip(fitnesses, population))[1]
# Shift probabilities towards best solution
return _adjust(probability_vec, bes... | [
"def",
"_adjust_probability_vec_best",
"(",
"population",
",",
"fitnesses",
",",
"probability_vec",
",",
"adjust_rate",
")",
":",
"best_solution",
"=",
"max",
"(",
"zip",
"(",
"fitnesses",
",",
"population",
")",
")",
"[",
"1",
"]",
"# Shift probabilities towards ... | Shift probabilities towards the best solution. | [
"Shift",
"probabilities",
"towards",
"the",
"best",
"solution",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/pbil.py#L132-L138 |
JustinLovinger/optimal | optimal/algorithms/pbil.py | _mutate_probability_vec | def _mutate_probability_vec(probability_vec, mutation_chance, mutation_adjust_rate):
"""Randomly adjust probabilities.
WARNING: Modifies probability_vec argument.
"""
bits_to_mutate = numpy.random.random(probability_vec.size) <= mutation_chance
probability_vec[bits_to_mutate] = _adjust(
pro... | python | def _mutate_probability_vec(probability_vec, mutation_chance, mutation_adjust_rate):
"""Randomly adjust probabilities.
WARNING: Modifies probability_vec argument.
"""
bits_to_mutate = numpy.random.random(probability_vec.size) <= mutation_chance
probability_vec[bits_to_mutate] = _adjust(
pro... | [
"def",
"_mutate_probability_vec",
"(",
"probability_vec",
",",
"mutation_chance",
",",
"mutation_adjust_rate",
")",
":",
"bits_to_mutate",
"=",
"numpy",
".",
"random",
".",
"random",
"(",
"probability_vec",
".",
"size",
")",
"<=",
"mutation_chance",
"probability_vec",... | Randomly adjust probabilities.
WARNING: Modifies probability_vec argument. | [
"Randomly",
"adjust",
"probabilities",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/pbil.py#L141-L149 |
JustinLovinger/optimal | optimal/algorithms/pbil.py | PBIL.next_population | def next_population(self, population, fitnesses):
"""Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
lis... | python | def next_population(self, population, fitnesses):
"""Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
lis... | [
"def",
"next_population",
"(",
"self",
",",
"population",
",",
"fitnesses",
")",
":",
"# Update probability vector",
"self",
".",
"_probability_vec",
"=",
"_adjust_probability_vec_best",
"(",
"population",
",",
"fitnesses",
",",
"self",
".",
"_probability_vec",
",",
... | Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
list; a list of solutions. | [
"Make",
"a",
"new",
"population",
"after",
"each",
"optimization",
"iteration",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/pbil.py#L102-L123 |
JustinLovinger/optimal | optimal/examples/benchmark_gaoperators.py | benchmark_multi | def benchmark_multi(optimizer):
"""Benchmark an optimizer configuration on multiple functions."""
# Get our benchmark stats
all_stats = benchmark.compare(optimizer, PROBLEMS, runs=100)
return benchmark.aggregate(all_stats) | python | def benchmark_multi(optimizer):
"""Benchmark an optimizer configuration on multiple functions."""
# Get our benchmark stats
all_stats = benchmark.compare(optimizer, PROBLEMS, runs=100)
return benchmark.aggregate(all_stats) | [
"def",
"benchmark_multi",
"(",
"optimizer",
")",
":",
"# Get our benchmark stats",
"all_stats",
"=",
"benchmark",
".",
"compare",
"(",
"optimizer",
",",
"PROBLEMS",
",",
"runs",
"=",
"100",
")",
"return",
"benchmark",
".",
"aggregate",
"(",
"all_stats",
")"
] | Benchmark an optimizer configuration on multiple functions. | [
"Benchmark",
"an",
"optimizer",
"configuration",
"on",
"multiple",
"functions",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/examples/benchmark_gaoperators.py#L49-L53 |
JustinLovinger/optimal | optimal/algorithms/crossentropy.py | _sample | def _sample(probabilities, population_size):
"""Return a random population, drawn with regard to a set of probabilities"""
population = []
for _ in range(population_size):
solution = []
for probability in probabilities:
# probability of 1.0: always 1
# probability of ... | python | def _sample(probabilities, population_size):
"""Return a random population, drawn with regard to a set of probabilities"""
population = []
for _ in range(population_size):
solution = []
for probability in probabilities:
# probability of 1.0: always 1
# probability of ... | [
"def",
"_sample",
"(",
"probabilities",
",",
"population_size",
")",
":",
"population",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"population_size",
")",
":",
"solution",
"=",
"[",
"]",
"for",
"probability",
"in",
"probabilities",
":",
"# probability of... | Return a random population, drawn with regard to a set of probabilities | [
"Return",
"a",
"random",
"population",
"drawn",
"with",
"regard",
"to",
"a",
"set",
"of",
"probabilities"
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/crossentropy.py#L112-L125 |
JustinLovinger/optimal | optimal/algorithms/crossentropy.py | _chance | def _chance(solution, pdf):
"""Return the chance of obtaining a solution from a pdf.
The probability of many independant weighted "coin flips" (one for each bit)
"""
# 1.0 - abs(bit - p) gives probability of bit given p
return _prod([1.0 - abs(bit - p) for bit, p in zip(solution, pdf)]) | python | def _chance(solution, pdf):
"""Return the chance of obtaining a solution from a pdf.
The probability of many independant weighted "coin flips" (one for each bit)
"""
# 1.0 - abs(bit - p) gives probability of bit given p
return _prod([1.0 - abs(bit - p) for bit, p in zip(solution, pdf)]) | [
"def",
"_chance",
"(",
"solution",
",",
"pdf",
")",
":",
"# 1.0 - abs(bit - p) gives probability of bit given p",
"return",
"_prod",
"(",
"[",
"1.0",
"-",
"abs",
"(",
"bit",
"-",
"p",
")",
"for",
"bit",
",",
"p",
"in",
"zip",
"(",
"solution",
",",
"pdf",
... | Return the chance of obtaining a solution from a pdf.
The probability of many independant weighted "coin flips" (one for each bit) | [
"Return",
"the",
"chance",
"of",
"obtaining",
"a",
"solution",
"from",
"a",
"pdf",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/crossentropy.py#L132-L138 |
JustinLovinger/optimal | optimal/algorithms/crossentropy.py | _pdf_value | def _pdf_value(pdf, population, fitnesses, fitness_threshold):
"""Give the value of a pdf.
This represents the likelihood of a pdf generating solutions
that exceed the threshold.
"""
# Add the chance of obtaining a solution from the pdf
# when the fitness for that solution exceeds a threshold
... | python | def _pdf_value(pdf, population, fitnesses, fitness_threshold):
"""Give the value of a pdf.
This represents the likelihood of a pdf generating solutions
that exceed the threshold.
"""
# Add the chance of obtaining a solution from the pdf
# when the fitness for that solution exceeds a threshold
... | [
"def",
"_pdf_value",
"(",
"pdf",
",",
"population",
",",
"fitnesses",
",",
"fitness_threshold",
")",
":",
"# Add the chance of obtaining a solution from the pdf",
"# when the fitness for that solution exceeds a threshold",
"value",
"=",
"0.0",
"for",
"solution",
",",
"fitness... | Give the value of a pdf.
This represents the likelihood of a pdf generating solutions
that exceed the threshold. | [
"Give",
"the",
"value",
"of",
"a",
"pdf",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/crossentropy.py#L141-L158 |
JustinLovinger/optimal | optimal/algorithms/crossentropy.py | _update_pdf | def _update_pdf(population, fitnesses, pdfs, quantile):
"""Find a better pdf, based on fitnesses."""
# First we determine a fitness threshold based on a quantile of fitnesses
fitness_threshold = _get_quantile_cutoff(fitnesses, quantile)
# Then check all of our possible pdfs with a stochastic program
... | python | def _update_pdf(population, fitnesses, pdfs, quantile):
"""Find a better pdf, based on fitnesses."""
# First we determine a fitness threshold based on a quantile of fitnesses
fitness_threshold = _get_quantile_cutoff(fitnesses, quantile)
# Then check all of our possible pdfs with a stochastic program
... | [
"def",
"_update_pdf",
"(",
"population",
",",
"fitnesses",
",",
"pdfs",
",",
"quantile",
")",
":",
"# First we determine a fitness threshold based on a quantile of fitnesses",
"fitness_threshold",
"=",
"_get_quantile_cutoff",
"(",
"fitnesses",
",",
"quantile",
")",
"# Then ... | Find a better pdf, based on fitnesses. | [
"Find",
"a",
"better",
"pdf",
"based",
"on",
"fitnesses",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/crossentropy.py#L175-L181 |
JustinLovinger/optimal | optimal/helpers.py | binary_to_float | def binary_to_float(binary_list, lower_bound, upper_bound):
"""Return a floating point number between lower and upper bounds, from binary.
Args:
binary_list: list<int>; List of 0s and 1s.
The number of bits in this list determine the number of possible
values between lower and u... | python | def binary_to_float(binary_list, lower_bound, upper_bound):
"""Return a floating point number between lower and upper bounds, from binary.
Args:
binary_list: list<int>; List of 0s and 1s.
The number of bits in this list determine the number of possible
values between lower and u... | [
"def",
"binary_to_float",
"(",
"binary_list",
",",
"lower_bound",
",",
"upper_bound",
")",
":",
"# Edge case for empty binary_list",
"if",
"binary_list",
"==",
"[",
"]",
":",
"# With 0 bits, only one value can be represented,",
"# and we default to lower_bound",
"return",
"lo... | Return a floating point number between lower and upper bounds, from binary.
Args:
binary_list: list<int>; List of 0s and 1s.
The number of bits in this list determine the number of possible
values between lower and upper bound.
Increase the size of binary_list for more p... | [
"Return",
"a",
"floating",
"point",
"number",
"between",
"lower",
"and",
"upper",
"bounds",
"from",
"binary",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/helpers.py#L34-L71 |
JustinLovinger/optimal | optimal/helpers.py | binary_to_int | def binary_to_int(binary_list, lower_bound=0, upper_bound=None):
"""Return the base 10 integer corresponding to a binary list.
The maximum value is determined by the number of bits in binary_list,
and upper_bound. The greater allowed by the two.
Args:
binary_list: list<int>; List of 0s and 1s.
... | python | def binary_to_int(binary_list, lower_bound=0, upper_bound=None):
"""Return the base 10 integer corresponding to a binary list.
The maximum value is determined by the number of bits in binary_list,
and upper_bound. The greater allowed by the two.
Args:
binary_list: list<int>; List of 0s and 1s.
... | [
"def",
"binary_to_int",
"(",
"binary_list",
",",
"lower_bound",
"=",
"0",
",",
"upper_bound",
"=",
"None",
")",
":",
"# Edge case for empty binary_list",
"if",
"binary_list",
"==",
"[",
"]",
":",
"# With 0 bits, only one value can be represented,",
"# and we default to lo... | Return the base 10 integer corresponding to a binary list.
The maximum value is determined by the number of bits in binary_list,
and upper_bound. The greater allowed by the two.
Args:
binary_list: list<int>; List of 0s and 1s.
lower_bound: Minimum value for output, inclusive.
A b... | [
"Return",
"the",
"base",
"10",
"integer",
"corresponding",
"to",
"a",
"binary",
"list",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/helpers.py#L74-L111 |
JustinLovinger/optimal | optimal/algorithms/baseline.py | _int_to_binary | def _int_to_binary(integer, size=None):
"""Return bit list representation of integer.
If size is given, binary string is padded with 0s, or clipped to the size.
"""
binary_list = map(int, format(integer, 'b'))
if size is None:
return binary_list
else:
if len(binary_list) > size... | python | def _int_to_binary(integer, size=None):
"""Return bit list representation of integer.
If size is given, binary string is padded with 0s, or clipped to the size.
"""
binary_list = map(int, format(integer, 'b'))
if size is None:
return binary_list
else:
if len(binary_list) > size... | [
"def",
"_int_to_binary",
"(",
"integer",
",",
"size",
"=",
"None",
")",
":",
"binary_list",
"=",
"map",
"(",
"int",
",",
"format",
"(",
"integer",
",",
"'b'",
")",
")",
"if",
"size",
"is",
"None",
":",
"return",
"binary_list",
"else",
":",
"if",
"len... | Return bit list representation of integer.
If size is given, binary string is padded with 0s, or clipped to the size. | [
"Return",
"bit",
"list",
"representation",
"of",
"integer",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/baseline.py#L164-L182 |
JustinLovinger/optimal | optimal/algorithms/baseline.py | _RandomOptimizer.next_population | def next_population(self, population, fitnesses):
"""Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
lis... | python | def next_population(self, population, fitnesses):
"""Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
lis... | [
"def",
"next_population",
"(",
"self",
",",
"population",
",",
"fitnesses",
")",
":",
"return",
"common",
".",
"make_population",
"(",
"self",
".",
"_population_size",
",",
"self",
".",
"_generate_solution",
")"
] | Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
list; a list of solutions. | [
"Make",
"a",
"new",
"population",
"after",
"each",
"optimization",
"iteration",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/baseline.py#L63-L73 |
JustinLovinger/optimal | optimal/algorithms/baseline.py | RandomReal._generate_solution | def _generate_solution(self):
"""Return a single random solution."""
return common.random_real_solution(
self._solution_size, self._lower_bounds, self._upper_bounds) | python | def _generate_solution(self):
"""Return a single random solution."""
return common.random_real_solution(
self._solution_size, self._lower_bounds, self._upper_bounds) | [
"def",
"_generate_solution",
"(",
"self",
")",
":",
"return",
"common",
".",
"random_real_solution",
"(",
"self",
".",
"_solution_size",
",",
"self",
".",
"_lower_bounds",
",",
"self",
".",
"_upper_bounds",
")"
] | Return a single random solution. | [
"Return",
"a",
"single",
"random",
"solution",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/baseline.py#L108-L111 |
JustinLovinger/optimal | optimal/algorithms/baseline.py | ExhaustiveBinary.next_population | def next_population(self, population, fitnesses):
"""Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
lis... | python | def next_population(self, population, fitnesses):
"""Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
lis... | [
"def",
"next_population",
"(",
"self",
",",
"population",
",",
"fitnesses",
")",
":",
"return",
"[",
"self",
".",
"_next_solution",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"_population_size",
")",
"]"
] | Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
list; a list of solutions. | [
"Make",
"a",
"new",
"population",
"after",
"each",
"optimization",
"iteration",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/baseline.py#L147-L156 |
cloudsigma/cgroupspy | cgroupspy/trees.py | BaseTree._build_tree | def _build_tree(self):
"""
Build a full or a partial tree, depending on the groups/sub-groups specified.
"""
groups = self._groups or self.get_children_paths(self.root_path)
for group in groups:
node = Node(name=group, parent=self.root)
self.root.children... | python | def _build_tree(self):
"""
Build a full or a partial tree, depending on the groups/sub-groups specified.
"""
groups = self._groups or self.get_children_paths(self.root_path)
for group in groups:
node = Node(name=group, parent=self.root)
self.root.children... | [
"def",
"_build_tree",
"(",
"self",
")",
":",
"groups",
"=",
"self",
".",
"_groups",
"or",
"self",
".",
"get_children_paths",
"(",
"self",
".",
"root_path",
")",
"for",
"group",
"in",
"groups",
":",
"node",
"=",
"Node",
"(",
"name",
"=",
"group",
",",
... | Build a full or a partial tree, depending on the groups/sub-groups specified. | [
"Build",
"a",
"full",
"or",
"a",
"partial",
"tree",
"depending",
"on",
"the",
"groups",
"/",
"sub",
"-",
"groups",
"specified",
"."
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/trees.py#L71-L80 |
cloudsigma/cgroupspy | cgroupspy/trees.py | BaseTree._init_sub_groups | def _init_sub_groups(self, parent):
"""
Initialise sub-groups, and create any that do not already exist.
"""
if self._sub_groups:
for sub_group in self._sub_groups:
for component in split_path_components(sub_group):
fp = os.path.join(paren... | python | def _init_sub_groups(self, parent):
"""
Initialise sub-groups, and create any that do not already exist.
"""
if self._sub_groups:
for sub_group in self._sub_groups:
for component in split_path_components(sub_group):
fp = os.path.join(paren... | [
"def",
"_init_sub_groups",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"_sub_groups",
":",
"for",
"sub_group",
"in",
"self",
".",
"_sub_groups",
":",
"for",
"component",
"in",
"split_path_components",
"(",
"sub_group",
")",
":",
"fp",
"=",
"os... | Initialise sub-groups, and create any that do not already exist. | [
"Initialise",
"sub",
"-",
"groups",
"and",
"create",
"any",
"that",
"do",
"not",
"already",
"exist",
"."
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/trees.py#L82-L99 |
cloudsigma/cgroupspy | cgroupspy/trees.py | BaseTree._init_children | def _init_children(self, parent):
"""
Initialise each node's children - essentially build the tree.
"""
for dir_name in self.get_children_paths(parent.full_path):
child = Node(name=dir_name, parent=parent)
parent.children.append(child)
self._init_chil... | python | def _init_children(self, parent):
"""
Initialise each node's children - essentially build the tree.
"""
for dir_name in self.get_children_paths(parent.full_path):
child = Node(name=dir_name, parent=parent)
parent.children.append(child)
self._init_chil... | [
"def",
"_init_children",
"(",
"self",
",",
"parent",
")",
":",
"for",
"dir_name",
"in",
"self",
".",
"get_children_paths",
"(",
"parent",
".",
"full_path",
")",
":",
"child",
"=",
"Node",
"(",
"name",
"=",
"dir_name",
",",
"parent",
"=",
"parent",
")",
... | Initialise each node's children - essentially build the tree. | [
"Initialise",
"each",
"node",
"s",
"children",
"-",
"essentially",
"build",
"the",
"tree",
"."
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/trees.py#L101-L109 |
cloudsigma/cgroupspy | cgroupspy/nodes.py | Node.full_path | def full_path(self):
"""Absolute system path to the node"""
if self.parent:
return os.path.join(self.parent.full_path, self.name)
return self.name | python | def full_path(self):
"""Absolute system path to the node"""
if self.parent:
return os.path.join(self.parent.full_path, self.name)
return self.name | [
"def",
"full_path",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"parent",
".",
"full_path",
",",
"self",
".",
"name",
")",
"return",
"self",
".",
"name"
] | Absolute system path to the node | [
"Absolute",
"system",
"path",
"to",
"the",
"node"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L87-L92 |
cloudsigma/cgroupspy | cgroupspy/nodes.py | Node.path | def path(self):
"""Node's relative path from the root node"""
if self.parent:
try:
parent_path = self.parent.path.encode()
except AttributeError:
parent_path = self.parent.path
return os.path.join(parent_path, self.name)
return... | python | def path(self):
"""Node's relative path from the root node"""
if self.parent:
try:
parent_path = self.parent.path.encode()
except AttributeError:
parent_path = self.parent.path
return os.path.join(parent_path, self.name)
return... | [
"def",
"path",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"try",
":",
"parent_path",
"=",
"self",
".",
"parent",
".",
"path",
".",
"encode",
"(",
")",
"except",
"AttributeError",
":",
"parent_path",
"=",
"self",
".",
"parent",
".",
"pat... | Node's relative path from the root node | [
"Node",
"s",
"relative",
"path",
"from",
"the",
"root",
"node"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L95-L104 |
cloudsigma/cgroupspy | cgroupspy/nodes.py | Node._get_node_type | def _get_node_type(self):
"""Returns the current node's type"""
if self.parent is None:
return self.NODE_ROOT
elif self.parent.node_type == self.NODE_ROOT:
return self.NODE_CONTROLLER_ROOT
elif b".slice" in self.name or b'.partition' in self.name:
ret... | python | def _get_node_type(self):
"""Returns the current node's type"""
if self.parent is None:
return self.NODE_ROOT
elif self.parent.node_type == self.NODE_ROOT:
return self.NODE_CONTROLLER_ROOT
elif b".slice" in self.name or b'.partition' in self.name:
ret... | [
"def",
"_get_node_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"self",
".",
"NODE_ROOT",
"elif",
"self",
".",
"parent",
".",
"node_type",
"==",
"self",
".",
"NODE_ROOT",
":",
"return",
"self",
".",
"NODE_CONTROL... | Returns the current node's type | [
"Returns",
"the",
"current",
"node",
"s",
"type"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L106-L118 |
cloudsigma/cgroupspy | cgroupspy/nodes.py | Node._get_controller_type | def _get_controller_type(self):
"""Returns the current node's controller type"""
if self.node_type == self.NODE_CONTROLLER_ROOT and self.name in self.CONTROLLERS:
return self.name
elif self.parent:
return self.parent.controller_type
else:
return None | python | def _get_controller_type(self):
"""Returns the current node's controller type"""
if self.node_type == self.NODE_CONTROLLER_ROOT and self.name in self.CONTROLLERS:
return self.name
elif self.parent:
return self.parent.controller_type
else:
return None | [
"def",
"_get_controller_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"node_type",
"==",
"self",
".",
"NODE_CONTROLLER_ROOT",
"and",
"self",
".",
"name",
"in",
"self",
".",
"CONTROLLERS",
":",
"return",
"self",
".",
"name",
"elif",
"self",
".",
"parent"... | Returns the current node's controller type | [
"Returns",
"the",
"current",
"node",
"s",
"controller",
"type"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L120-L128 |
cloudsigma/cgroupspy | cgroupspy/nodes.py | Node.create_cgroup | def create_cgroup(self, name):
"""
Create a cgroup by name and attach it under this node.
"""
node = Node(name, parent=self)
if node in self.children:
raise RuntimeError('Node {} already exists under {}'.format(name, self.path))
name = name.encode()
f... | python | def create_cgroup(self, name):
"""
Create a cgroup by name and attach it under this node.
"""
node = Node(name, parent=self)
if node in self.children:
raise RuntimeError('Node {} already exists under {}'.format(name, self.path))
name = name.encode()
f... | [
"def",
"create_cgroup",
"(",
"self",
",",
"name",
")",
":",
"node",
"=",
"Node",
"(",
"name",
",",
"parent",
"=",
"self",
")",
"if",
"node",
"in",
"self",
".",
"children",
":",
"raise",
"RuntimeError",
"(",
"'Node {} already exists under {}'",
".",
"format... | Create a cgroup by name and attach it under this node. | [
"Create",
"a",
"cgroup",
"by",
"name",
"and",
"attach",
"it",
"under",
"this",
"node",
"."
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L137-L149 |
cloudsigma/cgroupspy | cgroupspy/nodes.py | Node.delete_cgroup | def delete_cgroup(self, name):
"""
Delete a cgroup by name and detach it from this node.
Raises OSError if the cgroup is not empty.
"""
name = name.encode()
fp = os.path.join(self.full_path, name)
if os.path.exists(fp):
os.rmdir(fp)
node = Node... | python | def delete_cgroup(self, name):
"""
Delete a cgroup by name and detach it from this node.
Raises OSError if the cgroup is not empty.
"""
name = name.encode()
fp = os.path.join(self.full_path, name)
if os.path.exists(fp):
os.rmdir(fp)
node = Node... | [
"def",
"delete_cgroup",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"name",
".",
"encode",
"(",
")",
"fp",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"full_path",
",",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"... | Delete a cgroup by name and detach it from this node.
Raises OSError if the cgroup is not empty. | [
"Delete",
"a",
"cgroup",
"by",
"name",
"and",
"detach",
"it",
"from",
"this",
"node",
".",
"Raises",
"OSError",
"if",
"the",
"cgroup",
"is",
"not",
"empty",
"."
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L151-L164 |
cloudsigma/cgroupspy | cgroupspy/nodes.py | Node.delete_empty_children | def delete_empty_children(self):
"""
Walk through the children of this node and delete any that are empty.
"""
for child in self.children:
child.delete_empty_children()
try:
if os.path.exists(child.full_path):
os.rmdir(child.ful... | python | def delete_empty_children(self):
"""
Walk through the children of this node and delete any that are empty.
"""
for child in self.children:
child.delete_empty_children()
try:
if os.path.exists(child.full_path):
os.rmdir(child.ful... | [
"def",
"delete_empty_children",
"(",
"self",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"delete_empty_children",
"(",
")",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"child",
".",
"full_path",
")",
":",
"o... | Walk through the children of this node and delete any that are empty. | [
"Walk",
"through",
"the",
"children",
"of",
"this",
"node",
"and",
"delete",
"any",
"that",
"are",
"empty",
"."
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L166-L176 |
cloudsigma/cgroupspy | cgroupspy/nodes.py | NodeControlGroup.add_node | def add_node(self, node):
"""
A a Node object to the group. Only one node per cgroup is supported
"""
if self.controllers.get(node.controller_type, None):
raise RuntimeError("Cannot add node {} to the node group. A node for {} group is already assigned".format(
... | python | def add_node(self, node):
"""
A a Node object to the group. Only one node per cgroup is supported
"""
if self.controllers.get(node.controller_type, None):
raise RuntimeError("Cannot add node {} to the node group. A node for {} group is already assigned".format(
... | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"controllers",
".",
"get",
"(",
"node",
".",
"controller_type",
",",
"None",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot add node {} to the node group. A node for {} group is already ass... | A a Node object to the group. Only one node per cgroup is supported | [
"A",
"a",
"Node",
"object",
"to",
"the",
"group",
".",
"Only",
"one",
"node",
"per",
"cgroup",
"is",
"supported"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L219-L231 |
cloudsigma/cgroupspy | cgroupspy/nodes.py | NodeControlGroup.group_tasks | def group_tasks(self):
"""All tasks in the hierarchy, affected by this group."""
tasks = set()
for node in walk_tree(self):
for ctrl in node.controllers.values():
tasks.update(ctrl.tasks)
return tasks | python | def group_tasks(self):
"""All tasks in the hierarchy, affected by this group."""
tasks = set()
for node in walk_tree(self):
for ctrl in node.controllers.values():
tasks.update(ctrl.tasks)
return tasks | [
"def",
"group_tasks",
"(",
"self",
")",
":",
"tasks",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"walk_tree",
"(",
"self",
")",
":",
"for",
"ctrl",
"in",
"node",
".",
"controllers",
".",
"values",
"(",
")",
":",
"tasks",
".",
"update",
"(",
"ctrl",... | All tasks in the hierarchy, affected by this group. | [
"All",
"tasks",
"in",
"the",
"hierarchy",
"affected",
"by",
"this",
"group",
"."
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L241-L247 |
cloudsigma/cgroupspy | cgroupspy/nodes.py | NodeControlGroup.tasks | def tasks(self):
"""Tasks in this exact group"""
tasks = set()
for ctrl in self.controllers.values():
tasks.update(ctrl.tasks)
return tasks | python | def tasks(self):
"""Tasks in this exact group"""
tasks = set()
for ctrl in self.controllers.values():
tasks.update(ctrl.tasks)
return tasks | [
"def",
"tasks",
"(",
"self",
")",
":",
"tasks",
"=",
"set",
"(",
")",
"for",
"ctrl",
"in",
"self",
".",
"controllers",
".",
"values",
"(",
")",
":",
"tasks",
".",
"update",
"(",
"ctrl",
".",
"tasks",
")",
"return",
"tasks"
] | Tasks in this exact group | [
"Tasks",
"in",
"this",
"exact",
"group"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L250-L255 |
cloudsigma/cgroupspy | cgroupspy/controllers.py | Controller.filepath | def filepath(self, filename):
"""The full path to a file"""
return os.path.join(self.node.full_path, filename) | python | def filepath(self, filename):
"""The full path to a file"""
return os.path.join(self.node.full_path, filename) | [
"def",
"filepath",
"(",
"self",
",",
"filename",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"node",
".",
"full_path",
",",
"filename",
")"
] | The full path to a file | [
"The",
"full",
"path",
"to",
"a",
"file"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/controllers.py#L48-L51 |
cloudsigma/cgroupspy | cgroupspy/controllers.py | Controller.get_property | def get_property(self, filename):
"""Opens the file and reads the value"""
with open(self.filepath(filename)) as f:
return f.read().strip() | python | def get_property(self, filename):
"""Opens the file and reads the value"""
with open(self.filepath(filename)) as f:
return f.read().strip() | [
"def",
"get_property",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"self",
".",
"filepath",
"(",
"filename",
")",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")"
] | Opens the file and reads the value | [
"Opens",
"the",
"file",
"and",
"reads",
"the",
"value"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/controllers.py#L53-L57 |
cloudsigma/cgroupspy | cgroupspy/controllers.py | Controller.set_property | def set_property(self, filename, value):
"""Opens the file and writes the value"""
with open(self.filepath(filename), "w") as f:
return f.write(str(value)) | python | def set_property(self, filename, value):
"""Opens the file and writes the value"""
with open(self.filepath(filename), "w") as f:
return f.write(str(value)) | [
"def",
"set_property",
"(",
"self",
",",
"filename",
",",
"value",
")",
":",
"with",
"open",
"(",
"self",
".",
"filepath",
"(",
"filename",
")",
",",
"\"w\"",
")",
"as",
"f",
":",
"return",
"f",
".",
"write",
"(",
"str",
"(",
"value",
")",
")"
] | Opens the file and writes the value | [
"Opens",
"the",
"file",
"and",
"writes",
"the",
"value"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/controllers.py#L59-L63 |
cloudsigma/cgroupspy | cgroupspy/utils.py | walk_tree | def walk_tree(root):
"""Pre-order depth-first"""
yield root
for child in root.children:
for el in walk_tree(child):
yield el | python | def walk_tree(root):
"""Pre-order depth-first"""
yield root
for child in root.children:
for el in walk_tree(child):
yield el | [
"def",
"walk_tree",
"(",
"root",
")",
":",
"yield",
"root",
"for",
"child",
"in",
"root",
".",
"children",
":",
"for",
"el",
"in",
"walk_tree",
"(",
"child",
")",
":",
"yield",
"el"
] | Pre-order depth-first | [
"Pre",
"-",
"order",
"depth",
"-",
"first"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/utils.py#L32-L38 |
cloudsigma/cgroupspy | cgroupspy/utils.py | walk_up_tree | def walk_up_tree(root):
"""Post-order depth-first"""
for child in root.children:
for el in walk_up_tree(child):
yield el
yield root | python | def walk_up_tree(root):
"""Post-order depth-first"""
for child in root.children:
for el in walk_up_tree(child):
yield el
yield root | [
"def",
"walk_up_tree",
"(",
"root",
")",
":",
"for",
"child",
"in",
"root",
".",
"children",
":",
"for",
"el",
"in",
"walk_up_tree",
"(",
"child",
")",
":",
"yield",
"el",
"yield",
"root"
] | Post-order depth-first | [
"Post",
"-",
"order",
"depth",
"-",
"first"
] | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/utils.py#L41-L47 |
cloudsigma/cgroupspy | cgroupspy/utils.py | get_device_major_minor | def get_device_major_minor(dev_path):
"""
Returns the device (major, minor) tuple for simplicity
:param dev_path: Path to the device
:return: (device major, device minor)
:rtype: (int, int)
"""
stat = os.lstat(dev_path)
return os.major(stat.st_rdev), os.minor(stat.st_rdev) | python | def get_device_major_minor(dev_path):
"""
Returns the device (major, minor) tuple for simplicity
:param dev_path: Path to the device
:return: (device major, device minor)
:rtype: (int, int)
"""
stat = os.lstat(dev_path)
return os.major(stat.st_rdev), os.minor(stat.st_rdev) | [
"def",
"get_device_major_minor",
"(",
"dev_path",
")",
":",
"stat",
"=",
"os",
".",
"lstat",
"(",
"dev_path",
")",
"return",
"os",
".",
"major",
"(",
"stat",
".",
"st_rdev",
")",
",",
"os",
".",
"minor",
"(",
"stat",
".",
"st_rdev",
")"
] | Returns the device (major, minor) tuple for simplicity
:param dev_path: Path to the device
:return: (device major, device minor)
:rtype: (int, int) | [
"Returns",
"the",
"device",
"(",
"major",
"minor",
")",
"tuple",
"for",
"simplicity",
":",
"param",
"dev_path",
":",
"Path",
"to",
"the",
"device",
":",
"return",
":",
"(",
"device",
"major",
"device",
"minor",
")",
":",
"rtype",
":",
"(",
"int",
"int"... | train | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/utils.py#L50-L58 |
globality-corp/openapi | openapi/base.py | SchemaAware.validate | def validate(self):
"""
Validate that this instance matches its schema.
"""
schema = Schema(self.__class__.SCHEMA)
resolver = RefResolver.from_schema(
schema,
store=REGISTRY,
)
validate(self, schema, resolver=resolver) | python | def validate(self):
"""
Validate that this instance matches its schema.
"""
schema = Schema(self.__class__.SCHEMA)
resolver = RefResolver.from_schema(
schema,
store=REGISTRY,
)
validate(self, schema, resolver=resolver) | [
"def",
"validate",
"(",
"self",
")",
":",
"schema",
"=",
"Schema",
"(",
"self",
".",
"__class__",
".",
"SCHEMA",
")",
"resolver",
"=",
"RefResolver",
".",
"from_schema",
"(",
"schema",
",",
"store",
"=",
"REGISTRY",
",",
")",
"validate",
"(",
"self",
"... | Validate that this instance matches its schema. | [
"Validate",
"that",
"this",
"instance",
"matches",
"its",
"schema",
"."
] | train | https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/base.py#L48-L58 |
globality-corp/openapi | openapi/base.py | SchemaAware.dumps | def dumps(self):
"""
Dump this instance as YAML.
"""
with closing(StringIO()) as fileobj:
self.dump(fileobj)
return fileobj.getvalue() | python | def dumps(self):
"""
Dump this instance as YAML.
"""
with closing(StringIO()) as fileobj:
self.dump(fileobj)
return fileobj.getvalue() | [
"def",
"dumps",
"(",
"self",
")",
":",
"with",
"closing",
"(",
"StringIO",
"(",
")",
")",
"as",
"fileobj",
":",
"self",
".",
"dump",
"(",
"fileobj",
")",
"return",
"fileobj",
".",
"getvalue",
"(",
")"
] | Dump this instance as YAML. | [
"Dump",
"this",
"instance",
"as",
"YAML",
"."
] | train | https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/base.py#L67-L74 |
globality-corp/openapi | openapi/base.py | SchemaAware.loads | def loads(cls, s):
"""
Load an instance of this class from YAML.
"""
with closing(StringIO(s)) as fileobj:
return cls.load(fileobj) | python | def loads(cls, s):
"""
Load an instance of this class from YAML.
"""
with closing(StringIO(s)) as fileobj:
return cls.load(fileobj) | [
"def",
"loads",
"(",
"cls",
",",
"s",
")",
":",
"with",
"closing",
"(",
"StringIO",
"(",
"s",
")",
")",
"as",
"fileobj",
":",
"return",
"cls",
".",
"load",
"(",
"fileobj",
")"
] | Load an instance of this class from YAML. | [
"Load",
"an",
"instance",
"of",
"this",
"class",
"from",
"YAML",
"."
] | train | https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/base.py#L85-L91 |
globality-corp/openapi | openapi/base.py | SchemaAwareDict.property_schema | def property_schema(self, key):
"""
Lookup the schema for a specific property.
"""
schema = self.__class__.SCHEMA
# first try plain properties
plain_schema = schema.get("properties", {}).get(key)
if plain_schema is not None:
return plain_schema
... | python | def property_schema(self, key):
"""
Lookup the schema for a specific property.
"""
schema = self.__class__.SCHEMA
# first try plain properties
plain_schema = schema.get("properties", {}).get(key)
if plain_schema is not None:
return plain_schema
... | [
"def",
"property_schema",
"(",
"self",
",",
"key",
")",
":",
"schema",
"=",
"self",
".",
"__class__",
".",
"SCHEMA",
"# first try plain properties",
"plain_schema",
"=",
"schema",
".",
"get",
"(",
"\"properties\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"key... | Lookup the schema for a specific property. | [
"Lookup",
"the",
"schema",
"for",
"a",
"specific",
"property",
"."
] | train | https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/base.py#L141-L158 |
globality-corp/openapi | openapi/model.py | make | def make(class_name, base, schema):
"""
Create a new schema aware type.
"""
return type(class_name, (base,), dict(SCHEMA=schema)) | python | def make(class_name, base, schema):
"""
Create a new schema aware type.
"""
return type(class_name, (base,), dict(SCHEMA=schema)) | [
"def",
"make",
"(",
"class_name",
",",
"base",
",",
"schema",
")",
":",
"return",
"type",
"(",
"class_name",
",",
"(",
"base",
",",
")",
",",
"dict",
"(",
"SCHEMA",
"=",
"schema",
")",
")"
] | Create a new schema aware type. | [
"Create",
"a",
"new",
"schema",
"aware",
"type",
"."
] | train | https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/model.py#L11-L15 |
globality-corp/openapi | openapi/model.py | make_definition | def make_definition(name, base, schema):
"""
Create a new definition.
"""
class_name = make_class_name(name)
cls = register(make(class_name, base, schema))
globals()[class_name] = cls | python | def make_definition(name, base, schema):
"""
Create a new definition.
"""
class_name = make_class_name(name)
cls = register(make(class_name, base, schema))
globals()[class_name] = cls | [
"def",
"make_definition",
"(",
"name",
",",
"base",
",",
"schema",
")",
":",
"class_name",
"=",
"make_class_name",
"(",
"name",
")",
"cls",
"=",
"register",
"(",
"make",
"(",
"class_name",
",",
"base",
",",
"schema",
")",
")",
"globals",
"(",
")",
"[",... | Create a new definition. | [
"Create",
"a",
"new",
"definition",
"."
] | train | https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/model.py#L18-L25 |
globality-corp/openapi | openapi/registry.py | register | def register(cls):
"""
Register a class.
"""
definition_name = make_definition_name(cls.__name__)
REGISTRY[definition_name] = cls
return cls | python | def register(cls):
"""
Register a class.
"""
definition_name = make_definition_name(cls.__name__)
REGISTRY[definition_name] = cls
return cls | [
"def",
"register",
"(",
"cls",
")",
":",
"definition_name",
"=",
"make_definition_name",
"(",
"cls",
".",
"__name__",
")",
"REGISTRY",
"[",
"definition_name",
"]",
"=",
"cls",
"return",
"cls"
] | Register a class. | [
"Register",
"a",
"class",
"."
] | train | https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/registry.py#L12-L19 |
globality-corp/openapi | openapi/registry.py | lookup | def lookup(schema):
"""
Lookup a class by property schema.
"""
if not isinstance(schema, dict) or "$ref" not in schema:
return None
ref = schema["$ref"]
return REGISTRY.get(ref) | python | def lookup(schema):
"""
Lookup a class by property schema.
"""
if not isinstance(schema, dict) or "$ref" not in schema:
return None
ref = schema["$ref"]
return REGISTRY.get(ref) | [
"def",
"lookup",
"(",
"schema",
")",
":",
"if",
"not",
"isinstance",
"(",
"schema",
",",
"dict",
")",
"or",
"\"$ref\"",
"not",
"in",
"schema",
":",
"return",
"None",
"ref",
"=",
"schema",
"[",
"\"$ref\"",
"]",
"return",
"REGISTRY",
".",
"get",
"(",
"... | Lookup a class by property schema. | [
"Lookup",
"a",
"class",
"by",
"property",
"schema",
"."
] | train | https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/registry.py#L22-L32 |
thecynic/pylutron | pylutron/__init__.py | LutronConnection.connect | def connect(self):
"""Connects to the lutron controller."""
if self._connected or self.is_alive():
raise ConnectionExistsError("Already connected")
# After starting the thread we wait for it to post us
# an event signifying that connection is established. This
# ensures that the caller only re... | python | def connect(self):
"""Connects to the lutron controller."""
if self._connected or self.is_alive():
raise ConnectionExistsError("Already connected")
# After starting the thread we wait for it to post us
# an event signifying that connection is established. This
# ensures that the caller only re... | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connected",
"or",
"self",
".",
"is_alive",
"(",
")",
":",
"raise",
"ConnectionExistsError",
"(",
"\"Already connected\"",
")",
"# After starting the thread we wait for it to post us",
"# an event signifying t... | Connects to the lutron controller. | [
"Connects",
"to",
"the",
"lutron",
"controller",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L63-L72 |
thecynic/pylutron | pylutron/__init__.py | LutronConnection._send_locked | def _send_locked(self, cmd):
"""Sends the specified command to the lutron controller.
Assumes self._lock is held.
"""
_LOGGER.debug("Sending: %s" % cmd)
try:
self._telnet.write(cmd.encode('ascii') + b'\r\n')
except BrokenPipeError:
self._disconnect_locked() | python | def _send_locked(self, cmd):
"""Sends the specified command to the lutron controller.
Assumes self._lock is held.
"""
_LOGGER.debug("Sending: %s" % cmd)
try:
self._telnet.write(cmd.encode('ascii') + b'\r\n')
except BrokenPipeError:
self._disconnect_locked() | [
"def",
"_send_locked",
"(",
"self",
",",
"cmd",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Sending: %s\"",
"%",
"cmd",
")",
"try",
":",
"self",
".",
"_telnet",
".",
"write",
"(",
"cmd",
".",
"encode",
"(",
"'ascii'",
")",
"+",
"b'\\r\\n'",
")",
"exce... | Sends the specified command to the lutron controller.
Assumes self._lock is held. | [
"Sends",
"the",
"specified",
"command",
"to",
"the",
"lutron",
"controller",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L74-L83 |
thecynic/pylutron | pylutron/__init__.py | LutronConnection._do_login_locked | def _do_login_locked(self):
"""Executes the login procedure (telnet) as well as setting up some
connection defaults like turning off the prompt, etc."""
self._telnet = telnetlib.Telnet(self._host)
self._telnet.read_until(LutronConnection.USER_PROMPT)
self._telnet.write(self._user + b'\r\n')
self... | python | def _do_login_locked(self):
"""Executes the login procedure (telnet) as well as setting up some
connection defaults like turning off the prompt, etc."""
self._telnet = telnetlib.Telnet(self._host)
self._telnet.read_until(LutronConnection.USER_PROMPT)
self._telnet.write(self._user + b'\r\n')
self... | [
"def",
"_do_login_locked",
"(",
"self",
")",
":",
"self",
".",
"_telnet",
"=",
"telnetlib",
".",
"Telnet",
"(",
"self",
".",
"_host",
")",
"self",
".",
"_telnet",
".",
"read_until",
"(",
"LutronConnection",
".",
"USER_PROMPT",
")",
"self",
".",
"_telnet",
... | Executes the login procedure (telnet) as well as setting up some
connection defaults like turning off the prompt, etc. | [
"Executes",
"the",
"login",
"procedure",
"(",
"telnet",
")",
"as",
"well",
"as",
"setting",
"up",
"some",
"connection",
"defaults",
"like",
"turning",
"off",
"the",
"prompt",
"etc",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L93-L109 |
thecynic/pylutron | pylutron/__init__.py | LutronConnection._disconnect_locked | def _disconnect_locked(self):
"""Closes the current connection. Assume self._lock is held."""
self._connected = False
self._connect_cond.notify_all()
self._telnet = None
_LOGGER.warning("Disconnected") | python | def _disconnect_locked(self):
"""Closes the current connection. Assume self._lock is held."""
self._connected = False
self._connect_cond.notify_all()
self._telnet = None
_LOGGER.warning("Disconnected") | [
"def",
"_disconnect_locked",
"(",
"self",
")",
":",
"self",
".",
"_connected",
"=",
"False",
"self",
".",
"_connect_cond",
".",
"notify_all",
"(",
")",
"self",
".",
"_telnet",
"=",
"None",
"_LOGGER",
".",
"warning",
"(",
"\"Disconnected\"",
")"
] | Closes the current connection. Assume self._lock is held. | [
"Closes",
"the",
"current",
"connection",
".",
"Assume",
"self",
".",
"_lock",
"is",
"held",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L111-L116 |
thecynic/pylutron | pylutron/__init__.py | LutronConnection._maybe_reconnect | def _maybe_reconnect(self):
"""Reconnects to the controller if we have been previously disconnected."""
with self._lock:
if not self._connected:
_LOGGER.info("Connecting")
self._do_login_locked()
self._connected = True
self._connect_cond.notify_all()
_LOGGER.info("... | python | def _maybe_reconnect(self):
"""Reconnects to the controller if we have been previously disconnected."""
with self._lock:
if not self._connected:
_LOGGER.info("Connecting")
self._do_login_locked()
self._connected = True
self._connect_cond.notify_all()
_LOGGER.info("... | [
"def",
"_maybe_reconnect",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"not",
"self",
".",
"_connected",
":",
"_LOGGER",
".",
"info",
"(",
"\"Connecting\"",
")",
"self",
".",
"_do_login_locked",
"(",
")",
"self",
".",
"_connected",
"=... | Reconnects to the controller if we have been previously disconnected. | [
"Reconnects",
"to",
"the",
"controller",
"if",
"we",
"have",
"been",
"previously",
"disconnected",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L118-L126 |
thecynic/pylutron | pylutron/__init__.py | LutronConnection.run | def run(self):
"""Main thread function to maintain connection and receive remote status."""
_LOGGER.info("Started")
while True:
self._maybe_reconnect()
line = ''
try:
# If someone is sending a command, we can lose our connection so grab a
# copy beforehand. We don't need th... | python | def run(self):
"""Main thread function to maintain connection and receive remote status."""
_LOGGER.info("Started")
while True:
self._maybe_reconnect()
line = ''
try:
# If someone is sending a command, we can lose our connection so grab a
# copy beforehand. We don't need th... | [
"def",
"run",
"(",
"self",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Started\"",
")",
"while",
"True",
":",
"self",
".",
"_maybe_reconnect",
"(",
")",
"line",
"=",
"''",
"try",
":",
"# If someone is sending a command, we can lose our connection so grab a",
"# copy... | Main thread function to maintain connection and receive remote status. | [
"Main",
"thread",
"function",
"to",
"maintain",
"connection",
"and",
"receive",
"remote",
"status",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L128-L149 |
thecynic/pylutron | pylutron/__init__.py | LutronXmlDbParser.parse | def parse(self):
"""Main entrypoint into the parser. It interprets and creates all the
relevant Lutron objects and stuffs them into the appropriate hierarchy."""
import xml.etree.ElementTree as ET
root = ET.fromstring(self._xml_db_str)
# The structure is something like this:
# <Areas>
# <... | python | def parse(self):
"""Main entrypoint into the parser. It interprets and creates all the
relevant Lutron objects and stuffs them into the appropriate hierarchy."""
import xml.etree.ElementTree as ET
root = ET.fromstring(self._xml_db_str)
# The structure is something like this:
# <Areas>
# <... | [
"def",
"parse",
"(",
"self",
")",
":",
"import",
"xml",
".",
"etree",
".",
"ElementTree",
"as",
"ET",
"root",
"=",
"ET",
".",
"fromstring",
"(",
"self",
".",
"_xml_db_str",
")",
"# The structure is something like this:",
"# <Areas>",
"# <Area ...>",
"# <De... | Main entrypoint into the parser. It interprets and creates all the
relevant Lutron objects and stuffs them into the appropriate hierarchy. | [
"Main",
"entrypoint",
"into",
"the",
"parser",
".",
"It",
"interprets",
"and",
"creates",
"all",
"the",
"relevant",
"Lutron",
"objects",
"and",
"stuffs",
"them",
"into",
"the",
"appropriate",
"hierarchy",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L166-L190 |
thecynic/pylutron | pylutron/__init__.py | LutronXmlDbParser._parse_area | def _parse_area(self, area_xml):
"""Parses an Area tag, which is effectively a room, depending on how the
Lutron controller programming was done."""
area = Area(self._lutron,
name=area_xml.get('Name'),
integration_id=int(area_xml.get('IntegrationID')),
occupan... | python | def _parse_area(self, area_xml):
"""Parses an Area tag, which is effectively a room, depending on how the
Lutron controller programming was done."""
area = Area(self._lutron,
name=area_xml.get('Name'),
integration_id=int(area_xml.get('IntegrationID')),
occupan... | [
"def",
"_parse_area",
"(",
"self",
",",
"area_xml",
")",
":",
"area",
"=",
"Area",
"(",
"self",
".",
"_lutron",
",",
"name",
"=",
"area_xml",
".",
"get",
"(",
"'Name'",
")",
",",
"integration_id",
"=",
"int",
"(",
"area_xml",
".",
"get",
"(",
"'Integ... | Parses an Area tag, which is effectively a room, depending on how the
Lutron controller programming was done. | [
"Parses",
"an",
"Area",
"tag",
"which",
"is",
"effectively",
"a",
"room",
"depending",
"on",
"how",
"the",
"Lutron",
"controller",
"programming",
"was",
"done",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L192-L227 |
thecynic/pylutron | pylutron/__init__.py | LutronXmlDbParser._parse_output | def _parse_output(self, output_xml):
"""Parses an output, which is generally a switch controlling a set of
lights/outlets, etc."""
output = Output(self._lutron,
name=output_xml.get('Name'),
watts=int(output_xml.get('Wattage')),
output_type=output_x... | python | def _parse_output(self, output_xml):
"""Parses an output, which is generally a switch controlling a set of
lights/outlets, etc."""
output = Output(self._lutron,
name=output_xml.get('Name'),
watts=int(output_xml.get('Wattage')),
output_type=output_x... | [
"def",
"_parse_output",
"(",
"self",
",",
"output_xml",
")",
":",
"output",
"=",
"Output",
"(",
"self",
".",
"_lutron",
",",
"name",
"=",
"output_xml",
".",
"get",
"(",
"'Name'",
")",
",",
"watts",
"=",
"int",
"(",
"output_xml",
".",
"get",
"(",
"'Wa... | Parses an output, which is generally a switch controlling a set of
lights/outlets, etc. | [
"Parses",
"an",
"output",
"which",
"is",
"generally",
"a",
"switch",
"controlling",
"a",
"set",
"of",
"lights",
"/",
"outlets",
"etc",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L229-L237 |
thecynic/pylutron | pylutron/__init__.py | LutronXmlDbParser._parse_keypad | def _parse_keypad(self, keypad_xml):
"""Parses a keypad device (the Visor receiver is technically a keypad too)."""
keypad = Keypad(self._lutron,
name=keypad_xml.get('Name'),
integration_id=int(keypad_xml.get('IntegrationID')))
components = keypad_xml.find('Components... | python | def _parse_keypad(self, keypad_xml):
"""Parses a keypad device (the Visor receiver is technically a keypad too)."""
keypad = Keypad(self._lutron,
name=keypad_xml.get('Name'),
integration_id=int(keypad_xml.get('IntegrationID')))
components = keypad_xml.find('Components... | [
"def",
"_parse_keypad",
"(",
"self",
",",
"keypad_xml",
")",
":",
"keypad",
"=",
"Keypad",
"(",
"self",
".",
"_lutron",
",",
"name",
"=",
"keypad_xml",
".",
"get",
"(",
"'Name'",
")",
",",
"integration_id",
"=",
"int",
"(",
"keypad_xml",
".",
"get",
"(... | Parses a keypad device (the Visor receiver is technically a keypad too). | [
"Parses",
"a",
"keypad",
"device",
"(",
"the",
"Visor",
"receiver",
"is",
"technically",
"a",
"keypad",
"too",
")",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L239-L257 |
thecynic/pylutron | pylutron/__init__.py | LutronXmlDbParser._parse_button | def _parse_button(self, keypad, component_xml):
"""Parses a button device that part of a keypad."""
button_xml = component_xml.find('Button')
name = button_xml.get('Engraving')
button_type = button_xml.get('ButtonType')
direction = button_xml.get('Direction')
# Hybrid keypads have dimmer buttons... | python | def _parse_button(self, keypad, component_xml):
"""Parses a button device that part of a keypad."""
button_xml = component_xml.find('Button')
name = button_xml.get('Engraving')
button_type = button_xml.get('ButtonType')
direction = button_xml.get('Direction')
# Hybrid keypads have dimmer buttons... | [
"def",
"_parse_button",
"(",
"self",
",",
"keypad",
",",
"component_xml",
")",
":",
"button_xml",
"=",
"component_xml",
".",
"find",
"(",
"'Button'",
")",
"name",
"=",
"button_xml",
".",
"get",
"(",
"'Engraving'",
")",
"button_type",
"=",
"button_xml",
".",
... | Parses a button device that part of a keypad. | [
"Parses",
"a",
"button",
"device",
"that",
"part",
"of",
"a",
"keypad",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L259-L275 |
thecynic/pylutron | pylutron/__init__.py | LutronXmlDbParser._parse_led | def _parse_led(self, keypad, component_xml):
"""Parses an LED device that part of a keypad."""
component_num = int(component_xml.get('ComponentNumber'))
led_num = component_num - 80
led = Led(self._lutron, keypad,
name=('LED %d' % led_num),
led_num=led_num,
comp... | python | def _parse_led(self, keypad, component_xml):
"""Parses an LED device that part of a keypad."""
component_num = int(component_xml.get('ComponentNumber'))
led_num = component_num - 80
led = Led(self._lutron, keypad,
name=('LED %d' % led_num),
led_num=led_num,
comp... | [
"def",
"_parse_led",
"(",
"self",
",",
"keypad",
",",
"component_xml",
")",
":",
"component_num",
"=",
"int",
"(",
"component_xml",
".",
"get",
"(",
"'ComponentNumber'",
")",
")",
"led_num",
"=",
"component_num",
"-",
"80",
"led",
"=",
"Led",
"(",
"self",
... | Parses an LED device that part of a keypad. | [
"Parses",
"an",
"LED",
"device",
"that",
"part",
"of",
"a",
"keypad",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L277-L285 |
thecynic/pylutron | pylutron/__init__.py | LutronXmlDbParser._parse_motion_sensor | def _parse_motion_sensor(self, sensor_xml):
"""Parses a motion sensor object.
TODO: We don't actually do anything with these yet. There's a lot of info
that needs to be managed to do this right. We'd have to manage the occupancy
groups, what's assigned to them, and when they go (un)occupied. We'll hand... | python | def _parse_motion_sensor(self, sensor_xml):
"""Parses a motion sensor object.
TODO: We don't actually do anything with these yet. There's a lot of info
that needs to be managed to do this right. We'd have to manage the occupancy
groups, what's assigned to them, and when they go (un)occupied. We'll hand... | [
"def",
"_parse_motion_sensor",
"(",
"self",
",",
"sensor_xml",
")",
":",
"return",
"MotionSensor",
"(",
"self",
".",
"_lutron",
",",
"name",
"=",
"sensor_xml",
".",
"get",
"(",
"'Name'",
")",
",",
"integration_id",
"=",
"int",
"(",
"sensor_xml",
".",
"get"... | Parses a motion sensor object.
TODO: We don't actually do anything with these yet. There's a lot of info
that needs to be managed to do this right. We'd have to manage the occupancy
groups, what's assigned to them, and when they go (un)occupied. We'll handle
this later. | [
"Parses",
"a",
"motion",
"sensor",
"object",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L287-L297 |
thecynic/pylutron | pylutron/__init__.py | Lutron.subscribe | def subscribe(self, obj, handler):
"""Subscribes to status updates of the requested object.
DEPRECATED
The handler will be invoked when the controller sends a notification
regarding changed state. The user can then further query the object for the
state itself."""
if not isinstance(obj, Lutron... | python | def subscribe(self, obj, handler):
"""Subscribes to status updates of the requested object.
DEPRECATED
The handler will be invoked when the controller sends a notification
regarding changed state. The user can then further query the object for the
state itself."""
if not isinstance(obj, Lutron... | [
"def",
"subscribe",
"(",
"self",
",",
"obj",
",",
"handler",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"LutronEntity",
")",
":",
"raise",
"InvalidSubscription",
"(",
"\"Subscription target not a LutronEntity\"",
")",
"_LOGGER",
".",
"warning",
"(",
... | Subscribes to status updates of the requested object.
DEPRECATED
The handler will be invoked when the controller sends a notification
regarding changed state. The user can then further query the object for the
state itself. | [
"Subscribes",
"to",
"status",
"updates",
"of",
"the",
"requested",
"object",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L330-L344 |
thecynic/pylutron | pylutron/__init__.py | Lutron.register_id | def register_id(self, cmd_type, obj):
"""Registers an object (through its integration id) to receive update
notifications. This is the core mechanism how Output and Keypad objects get
notified when the controller sends status updates."""
ids = self._ids.setdefault(cmd_type, {})
if obj.id in ids:
... | python | def register_id(self, cmd_type, obj):
"""Registers an object (through its integration id) to receive update
notifications. This is the core mechanism how Output and Keypad objects get
notified when the controller sends status updates."""
ids = self._ids.setdefault(cmd_type, {})
if obj.id in ids:
... | [
"def",
"register_id",
"(",
"self",
",",
"cmd_type",
",",
"obj",
")",
":",
"ids",
"=",
"self",
".",
"_ids",
".",
"setdefault",
"(",
"cmd_type",
",",
"{",
"}",
")",
"if",
"obj",
".",
"id",
"in",
"ids",
":",
"raise",
"IntegrationIdExistsError",
"self",
... | Registers an object (through its integration id) to receive update
notifications. This is the core mechanism how Output and Keypad objects get
notified when the controller sends status updates. | [
"Registers",
"an",
"object",
"(",
"through",
"its",
"integration",
"id",
")",
"to",
"receive",
"update",
"notifications",
".",
"This",
"is",
"the",
"core",
"mechanism",
"how",
"Output",
"and",
"Keypad",
"objects",
"get",
"notified",
"when",
"the",
"controller"... | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L346-L353 |
thecynic/pylutron | pylutron/__init__.py | Lutron._dispatch_legacy_subscriber | def _dispatch_legacy_subscriber(self, obj, *args, **kwargs):
"""This dispatches the registered callback for 'obj'. This is only used
for legacy subscribers since new users should register with the target
object directly."""
if obj in self._legacy_subscribers:
self._legacy_subscribers[obj](obj) | python | def _dispatch_legacy_subscriber(self, obj, *args, **kwargs):
"""This dispatches the registered callback for 'obj'. This is only used
for legacy subscribers since new users should register with the target
object directly."""
if obj in self._legacy_subscribers:
self._legacy_subscribers[obj](obj) | [
"def",
"_dispatch_legacy_subscriber",
"(",
"self",
",",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"obj",
"in",
"self",
".",
"_legacy_subscribers",
":",
"self",
".",
"_legacy_subscribers",
"[",
"obj",
"]",
"(",
"obj",
")"
] | This dispatches the registered callback for 'obj'. This is only used
for legacy subscribers since new users should register with the target
object directly. | [
"This",
"dispatches",
"the",
"registered",
"callback",
"for",
"obj",
".",
"This",
"is",
"only",
"used",
"for",
"legacy",
"subscribers",
"since",
"new",
"users",
"should",
"register",
"with",
"the",
"target",
"object",
"directly",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L355-L360 |
thecynic/pylutron | pylutron/__init__.py | Lutron._recv | def _recv(self, line):
"""Invoked by the connection manager to process incoming data."""
if line == '':
return
# Only handle query response messages, which are also sent on remote status
# updates (e.g. user manually pressed a keypad button)
if line[0] != Lutron.OP_RESPONSE:
_LOGGER.debu... | python | def _recv(self, line):
"""Invoked by the connection manager to process incoming data."""
if line == '':
return
# Only handle query response messages, which are also sent on remote status
# updates (e.g. user manually pressed a keypad button)
if line[0] != Lutron.OP_RESPONSE:
_LOGGER.debu... | [
"def",
"_recv",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
"==",
"''",
":",
"return",
"# Only handle query response messages, which are also sent on remote status",
"# updates (e.g. user manually pressed a keypad button)",
"if",
"line",
"[",
"0",
"]",
"!=",
"Lutron... | Invoked by the connection manager to process incoming data. | [
"Invoked",
"by",
"the",
"connection",
"manager",
"to",
"process",
"incoming",
"data",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L362-L383 |
thecynic/pylutron | pylutron/__init__.py | Lutron.send | def send(self, op, cmd, integration_id, *args):
"""Formats and sends the requested command to the Lutron controller."""
out_cmd = ",".join(
(cmd, str(integration_id)) + tuple((str(x) for x in args)))
self._conn.send(op + out_cmd) | python | def send(self, op, cmd, integration_id, *args):
"""Formats and sends the requested command to the Lutron controller."""
out_cmd = ",".join(
(cmd, str(integration_id)) + tuple((str(x) for x in args)))
self._conn.send(op + out_cmd) | [
"def",
"send",
"(",
"self",
",",
"op",
",",
"cmd",
",",
"integration_id",
",",
"*",
"args",
")",
":",
"out_cmd",
"=",
"\",\"",
".",
"join",
"(",
"(",
"cmd",
",",
"str",
"(",
"integration_id",
")",
")",
"+",
"tuple",
"(",
"(",
"str",
"(",
"x",
"... | Formats and sends the requested command to the Lutron controller. | [
"Formats",
"and",
"sends",
"the",
"requested",
"command",
"to",
"the",
"Lutron",
"controller",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L389-L393 |
thecynic/pylutron | pylutron/__init__.py | Lutron.load_xml_db | def load_xml_db(self):
"""Load the Lutron database from the server."""
import urllib.request
xmlfile = urllib.request.urlopen('http://' + self._host + '/DbXmlInfo.xml')
xml_db = xmlfile.read()
xmlfile.close()
_LOGGER.info("Loaded xml db")
parser = LutronXmlDbParser(lutron=self, xml_db_str=... | python | def load_xml_db(self):
"""Load the Lutron database from the server."""
import urllib.request
xmlfile = urllib.request.urlopen('http://' + self._host + '/DbXmlInfo.xml')
xml_db = xmlfile.read()
xmlfile.close()
_LOGGER.info("Loaded xml db")
parser = LutronXmlDbParser(lutron=self, xml_db_str=... | [
"def",
"load_xml_db",
"(",
"self",
")",
":",
"import",
"urllib",
".",
"request",
"xmlfile",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"'http://'",
"+",
"self",
".",
"_host",
"+",
"'/DbXmlInfo.xml'",
")",
"xml_db",
"=",
"xmlfile",
".",
"read",
"... | Load the Lutron database from the server. | [
"Load",
"the",
"Lutron",
"database",
"from",
"the",
"server",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L395-L412 |
thecynic/pylutron | pylutron/__init__.py | _RequestHelper.request | def request(self, action):
"""Request an action to be performed, in case one."""
ev = threading.Event()
first = False
with self.__lock:
if len(self.__events) == 0:
first = True
self.__events.append(ev)
if first:
action()
return ev | python | def request(self, action):
"""Request an action to be performed, in case one."""
ev = threading.Event()
first = False
with self.__lock:
if len(self.__events) == 0:
first = True
self.__events.append(ev)
if first:
action()
return ev | [
"def",
"request",
"(",
"self",
",",
"action",
")",
":",
"ev",
"=",
"threading",
".",
"Event",
"(",
")",
"first",
"=",
"False",
"with",
"self",
".",
"__lock",
":",
"if",
"len",
"(",
"self",
".",
"__events",
")",
"==",
"0",
":",
"first",
"=",
"True... | Request an action to be performed, in case one. | [
"Request",
"an",
"action",
"to",
"be",
"performed",
"in",
"case",
"one",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L441-L451 |
thecynic/pylutron | pylutron/__init__.py | LutronEntity._dispatch_event | def _dispatch_event(self, event: LutronEvent, params: Dict):
"""Dispatches the specified event to all the subscribers."""
for handler, context in self._subscribers:
handler(self, context, event, params) | python | def _dispatch_event(self, event: LutronEvent, params: Dict):
"""Dispatches the specified event to all the subscribers."""
for handler, context in self._subscribers:
handler(self, context, event, params) | [
"def",
"_dispatch_event",
"(",
"self",
",",
"event",
":",
"LutronEvent",
",",
"params",
":",
"Dict",
")",
":",
"for",
"handler",
",",
"context",
"in",
"self",
".",
"_subscribers",
":",
"handler",
"(",
"self",
",",
"context",
",",
"event",
",",
"params",
... | Dispatches the specified event to all the subscribers. | [
"Dispatches",
"the",
"specified",
"event",
"to",
"all",
"the",
"subscribers",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L485-L488 |
thecynic/pylutron | pylutron/__init__.py | LutronEntity.subscribe | def subscribe(self, handler: LutronEventHandler, context):
"""Subscribes to events from this entity.
handler: A callable object that takes the following arguments (in order)
obj: the LutrongEntity object that generated the event
context: user-supplied (to subscribe()) context object
... | python | def subscribe(self, handler: LutronEventHandler, context):
"""Subscribes to events from this entity.
handler: A callable object that takes the following arguments (in order)
obj: the LutrongEntity object that generated the event
context: user-supplied (to subscribe()) context object
... | [
"def",
"subscribe",
"(",
"self",
",",
"handler",
":",
"LutronEventHandler",
",",
"context",
")",
":",
"self",
".",
"_subscribers",
".",
"append",
"(",
"(",
"handler",
",",
"context",
")",
")"
] | Subscribes to events from this entity.
handler: A callable object that takes the following arguments (in order)
obj: the LutrongEntity object that generated the event
context: user-supplied (to subscribe()) context object
event: the LutronEvent that was generated.
... | [
"Subscribes",
"to",
"events",
"from",
"this",
"entity",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L490-L501 |
thecynic/pylutron | pylutron/__init__.py | Output.handle_update | def handle_update(self, args):
"""Handles an event update for this object, e.g. dimmer level change."""
_LOGGER.debug("handle_update %d -- %s" % (self._integration_id, args))
state = int(args[0])
if state != Output._ACTION_ZONE_LEVEL:
return False
level = float(args[1])
_LOGGER.debug("Upda... | python | def handle_update(self, args):
"""Handles an event update for this object, e.g. dimmer level change."""
_LOGGER.debug("handle_update %d -- %s" % (self._integration_id, args))
state = int(args[0])
if state != Output._ACTION_ZONE_LEVEL:
return False
level = float(args[1])
_LOGGER.debug("Upda... | [
"def",
"handle_update",
"(",
"self",
",",
"args",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"handle_update %d -- %s\"",
"%",
"(",
"self",
".",
"_integration_id",
",",
"args",
")",
")",
"state",
"=",
"int",
"(",
"args",
"[",
"0",
"]",
")",
"if",
"state"... | Handles an event update for this object, e.g. dimmer level change. | [
"Handles",
"an",
"event",
"update",
"for",
"this",
"object",
"e",
".",
"g",
".",
"dimmer",
"level",
"change",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L555-L567 |
thecynic/pylutron | pylutron/__init__.py | Output.__do_query_level | def __do_query_level(self):
"""Helper to perform the actual query the current dimmer level of the
output. For pure on/off loads the result is either 0.0 or 100.0."""
self._lutron.send(Lutron.OP_QUERY, Output._CMD_TYPE, self._integration_id,
Output._ACTION_ZONE_LEVEL) | python | def __do_query_level(self):
"""Helper to perform the actual query the current dimmer level of the
output. For pure on/off loads the result is either 0.0 or 100.0."""
self._lutron.send(Lutron.OP_QUERY, Output._CMD_TYPE, self._integration_id,
Output._ACTION_ZONE_LEVEL) | [
"def",
"__do_query_level",
"(",
"self",
")",
":",
"self",
".",
"_lutron",
".",
"send",
"(",
"Lutron",
".",
"OP_QUERY",
",",
"Output",
".",
"_CMD_TYPE",
",",
"self",
".",
"_integration_id",
",",
"Output",
".",
"_ACTION_ZONE_LEVEL",
")"
] | Helper to perform the actual query the current dimmer level of the
output. For pure on/off loads the result is either 0.0 or 100.0. | [
"Helper",
"to",
"perform",
"the",
"actual",
"query",
"the",
"current",
"dimmer",
"level",
"of",
"the",
"output",
".",
"For",
"pure",
"on",
"/",
"off",
"loads",
"the",
"result",
"is",
"either",
"0",
".",
"0",
"or",
"100",
".",
"0",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L569-L573 |
thecynic/pylutron | pylutron/__init__.py | Output.level | def level(self):
"""Returns the current output level by querying the remote controller."""
ev = self._query_waiters.request(self.__do_query_level)
ev.wait(1.0)
return self._level | python | def level(self):
"""Returns the current output level by querying the remote controller."""
ev = self._query_waiters.request(self.__do_query_level)
ev.wait(1.0)
return self._level | [
"def",
"level",
"(",
"self",
")",
":",
"ev",
"=",
"self",
".",
"_query_waiters",
".",
"request",
"(",
"self",
".",
"__do_query_level",
")",
"ev",
".",
"wait",
"(",
"1.0",
")",
"return",
"self",
".",
"_level"
] | Returns the current output level by querying the remote controller. | [
"Returns",
"the",
"current",
"output",
"level",
"by",
"querying",
"the",
"remote",
"controller",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L580-L584 |
thecynic/pylutron | pylutron/__init__.py | Output.level | def level(self, new_level):
"""Sets the new output level."""
if self._level == new_level:
return
self._lutron.send(Lutron.OP_EXECUTE, Output._CMD_TYPE, self._integration_id,
Output._ACTION_ZONE_LEVEL, "%.2f" % new_level)
self._level = new_level | python | def level(self, new_level):
"""Sets the new output level."""
if self._level == new_level:
return
self._lutron.send(Lutron.OP_EXECUTE, Output._CMD_TYPE, self._integration_id,
Output._ACTION_ZONE_LEVEL, "%.2f" % new_level)
self._level = new_level | [
"def",
"level",
"(",
"self",
",",
"new_level",
")",
":",
"if",
"self",
".",
"_level",
"==",
"new_level",
":",
"return",
"self",
".",
"_lutron",
".",
"send",
"(",
"Lutron",
".",
"OP_EXECUTE",
",",
"Output",
".",
"_CMD_TYPE",
",",
"self",
".",
"_integrat... | Sets the new output level. | [
"Sets",
"the",
"new",
"output",
"level",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L587-L593 |
thecynic/pylutron | pylutron/__init__.py | KeypadComponent.handle_update | def handle_update(self, action, params):
"""Handle the specified action on this component."""
_LOGGER.debug('Keypad: "%s" Handling "%s" Action: %s Params: %s"' % (
self._keypad.name, self.name, action, params))
return False | python | def handle_update(self, action, params):
"""Handle the specified action on this component."""
_LOGGER.debug('Keypad: "%s" Handling "%s" Action: %s Params: %s"' % (
self._keypad.name, self.name, action, params))
return False | [
"def",
"handle_update",
"(",
"self",
",",
"action",
",",
"params",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Keypad: \"%s\" Handling \"%s\" Action: %s Params: %s\"'",
"%",
"(",
"self",
".",
"_keypad",
".",
"name",
",",
"self",
".",
"name",
",",
"action",
",",
... | Handle the specified action on this component. | [
"Handle",
"the",
"specified",
"action",
"on",
"this",
"component",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L640-L644 |
thecynic/pylutron | pylutron/__init__.py | Button.press | def press(self):
"""Triggers a simulated button press to the Keypad."""
self._lutron.send(Lutron.OP_EXECUTE, Keypad._CMD_TYPE, self._keypad.id,
self.component_number, Button._ACTION_PRESS) | python | def press(self):
"""Triggers a simulated button press to the Keypad."""
self._lutron.send(Lutron.OP_EXECUTE, Keypad._CMD_TYPE, self._keypad.id,
self.component_number, Button._ACTION_PRESS) | [
"def",
"press",
"(",
"self",
")",
":",
"self",
".",
"_lutron",
".",
"send",
"(",
"Lutron",
".",
"OP_EXECUTE",
",",
"Keypad",
".",
"_CMD_TYPE",
",",
"self",
".",
"_keypad",
".",
"id",
",",
"self",
".",
"component_number",
",",
"Button",
".",
"_ACTION_PR... | Triggers a simulated button press to the Keypad. | [
"Triggers",
"a",
"simulated",
"button",
"press",
"to",
"the",
"Keypad",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L687-L690 |
thecynic/pylutron | pylutron/__init__.py | Button.handle_update | def handle_update(self, action, params):
"""Handle the specified action on this component."""
_LOGGER.debug('Keypad: "%s" %s Action: %s Params: %s"' % (
self._keypad.name, self, action, params))
ev_map = {
Button._ACTION_PRESS: Button.Event.PRESSED,
Button._ACTION_RELEASE: ... | python | def handle_update(self, action, params):
"""Handle the specified action on this component."""
_LOGGER.debug('Keypad: "%s" %s Action: %s Params: %s"' % (
self._keypad.name, self, action, params))
ev_map = {
Button._ACTION_PRESS: Button.Event.PRESSED,
Button._ACTION_RELEASE: ... | [
"def",
"handle_update",
"(",
"self",
",",
"action",
",",
"params",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Keypad: \"%s\" %s Action: %s Params: %s\"'",
"%",
"(",
"self",
".",
"_keypad",
".",
"name",
",",
"self",
",",
"action",
",",
"params",
")",
")",
"e... | Handle the specified action on this component. | [
"Handle",
"the",
"specified",
"action",
"on",
"this",
"component",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L692-L705 |
thecynic/pylutron | pylutron/__init__.py | Led.__do_query_state | def __do_query_state(self):
"""Helper to perform the actual query for the current LED state."""
self._lutron.send(Lutron.OP_QUERY, Keypad._CMD_TYPE, self._keypad.id,
self.component_number, Led._ACTION_LED_STATE) | python | def __do_query_state(self):
"""Helper to perform the actual query for the current LED state."""
self._lutron.send(Lutron.OP_QUERY, Keypad._CMD_TYPE, self._keypad.id,
self.component_number, Led._ACTION_LED_STATE) | [
"def",
"__do_query_state",
"(",
"self",
")",
":",
"self",
".",
"_lutron",
".",
"send",
"(",
"Lutron",
".",
"OP_QUERY",
",",
"Keypad",
".",
"_CMD_TYPE",
",",
"self",
".",
"_keypad",
".",
"id",
",",
"self",
".",
"component_number",
",",
"Led",
".",
"_ACT... | Helper to perform the actual query for the current LED state. | [
"Helper",
"to",
"perform",
"the",
"actual",
"query",
"for",
"the",
"current",
"LED",
"state",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L738-L741 |
thecynic/pylutron | pylutron/__init__.py | Led.state | def state(self):
"""Returns the current LED state by querying the remote controller."""
ev = self._query_waiters.request(self.__do_query_state)
ev.wait(1.0)
return self._state | python | def state(self):
"""Returns the current LED state by querying the remote controller."""
ev = self._query_waiters.request(self.__do_query_state)
ev.wait(1.0)
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"ev",
"=",
"self",
".",
"_query_waiters",
".",
"request",
"(",
"self",
".",
"__do_query_state",
")",
"ev",
".",
"wait",
"(",
"1.0",
")",
"return",
"self",
".",
"_state"
] | Returns the current LED state by querying the remote controller. | [
"Returns",
"the",
"current",
"LED",
"state",
"by",
"querying",
"the",
"remote",
"controller",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L749-L753 |
thecynic/pylutron | pylutron/__init__.py | Led.state | def state(self, new_state: bool):
"""Sets the new led state.
new_state: bool
"""
self._lutron.send(Lutron.OP_EXECUTE, Keypad._CMD_TYPE, self._keypad.id,
self.component_number, Led._ACTION_LED_STATE,
int(new_state))
self._state = new_state | python | def state(self, new_state: bool):
"""Sets the new led state.
new_state: bool
"""
self._lutron.send(Lutron.OP_EXECUTE, Keypad._CMD_TYPE, self._keypad.id,
self.component_number, Led._ACTION_LED_STATE,
int(new_state))
self._state = new_state | [
"def",
"state",
"(",
"self",
",",
"new_state",
":",
"bool",
")",
":",
"self",
".",
"_lutron",
".",
"send",
"(",
"Lutron",
".",
"OP_EXECUTE",
",",
"Keypad",
".",
"_CMD_TYPE",
",",
"self",
".",
"_keypad",
".",
"id",
",",
"self",
".",
"component_number",
... | Sets the new led state.
new_state: bool | [
"Sets",
"the",
"new",
"led",
"state",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L756-L764 |
thecynic/pylutron | pylutron/__init__.py | Led.handle_update | def handle_update(self, action, params):
"""Handle the specified action on this component."""
_LOGGER.debug('Keypad: "%s" %s Action: %s Params: %s"' % (
self._keypad.name, self, action, params))
if action != Led._ACTION_LED_STATE:
_LOGGER.debug("Unknown action %d for led %d in keypad... | python | def handle_update(self, action, params):
"""Handle the specified action on this component."""
_LOGGER.debug('Keypad: "%s" %s Action: %s Params: %s"' % (
self._keypad.name, self, action, params))
if action != Led._ACTION_LED_STATE:
_LOGGER.debug("Unknown action %d for led %d in keypad... | [
"def",
"handle_update",
"(",
"self",
",",
"action",
",",
"params",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Keypad: \"%s\" %s Action: %s Params: %s\"'",
"%",
"(",
"self",
".",
"_keypad",
".",
"name",
",",
"self",
",",
"action",
",",
"params",
")",
")",
"i... | Handle the specified action on this component. | [
"Handle",
"the",
"specified",
"action",
"on",
"this",
"component",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L766-L781 |
thecynic/pylutron | pylutron/__init__.py | Keypad.add_button | def add_button(self, button):
"""Adds a button that's part of this keypad. We'll use this to
dispatch button events."""
self._buttons.append(button)
self._components[button.component_number] = button | python | def add_button(self, button):
"""Adds a button that's part of this keypad. We'll use this to
dispatch button events."""
self._buttons.append(button)
self._components[button.component_number] = button | [
"def",
"add_button",
"(",
"self",
",",
"button",
")",
":",
"self",
".",
"_buttons",
".",
"append",
"(",
"button",
")",
"self",
".",
"_components",
"[",
"button",
".",
"component_number",
"]",
"=",
"button"
] | Adds a button that's part of this keypad. We'll use this to
dispatch button events. | [
"Adds",
"a",
"button",
"that",
"s",
"part",
"of",
"this",
"keypad",
".",
"We",
"ll",
"use",
"this",
"to",
"dispatch",
"button",
"events",
"."
] | train | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L802-L806 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.