id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
6,900
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 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", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/pbil.py#L126-L129
6,901
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, best_solution, adjust_rate)
python
def _adjust_probability_vec_best(population, fitnesses, probability_vec, adjust_rate): best_solution = max(zip(fitnesses, population))[1] # Shift probabilities towards best solution return _adjust(probability_vec, best_solution, adjust_rate)
[ "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", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/pbil.py#L132-L138
6,902
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( probability_vec[bits_to_mutate], numpy.random.random(numpy.sum(bits_to_mutate)), mutation_adjust_rate)
python
def _mutate_probability_vec(probability_vec, mutation_chance, mutation_adjust_rate): bits_to_mutate = numpy.random.random(probability_vec.size) <= mutation_chance probability_vec[bits_to_mutate] = _adjust( probability_vec[bits_to_mutate], numpy.random.random(numpy.sum(bits_to_mutate)), mutation_adjust_rate)
[ "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", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/pbil.py#L141-L149
6,903
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): # 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", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/examples/benchmark_gaoperators.py#L49-L53
6,904
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 0.0: always 0 if random.uniform(0.0, 1.0) < probability: solution.append(1) else: solution.append(0) population.append(solution) return population
python
def _sample(probabilities, population_size): population = [] for _ in range(population_size): solution = [] for probability in probabilities: # probability of 1.0: always 1 # probability of 0.0: always 0 if random.uniform(0.0, 1.0) < probability: solution.append(1) else: solution.append(0) population.append(solution) return population
[ "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" ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/crossentropy.py#L112-L125
6,905
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): # 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", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/crossentropy.py#L132-L138
6,906
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 value = 0.0 for solution, fitness in zip(population, fitnesses): if fitness >= fitness_threshold: # 1.0 + chance to avoid issues with chance of 0 value += math.log(1.0 + _chance(solution, pdf)) # The official equation states that value is now divided by len(fitnesses) # however, this is unnecessary when we are only obtaining the best pdf, # because every solution is of the same size return value
python
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 in zip(population, fitnesses): if fitness >= fitness_threshold: # 1.0 + chance to avoid issues with chance of 0 value += math.log(1.0 + _chance(solution, pdf)) # The official equation states that value is now divided by len(fitnesses) # however, this is unnecessary when we are only obtaining the best pdf, # because every solution is of the same size return value
[ "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", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/crossentropy.py#L141-L158
6,907
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 return _best_pdf(pdfs, population, fitnesses, fitness_threshold)
python
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 check all of our possible pdfs with a stochastic program return _best_pdf(pdfs, population, fitnesses, fitness_threshold)
[ "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", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/crossentropy.py#L175-L181
6,908
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 upper bound. Increase the size of binary_list for more precise floating points. lower_bound: Minimum value for output, inclusive. A binary list of 0s will have this value. upper_bound: Maximum value for output, inclusive. A binary list of 1s will have this value. Returns: float; A floating point number. """ # 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 lower_bound # A little bit of math gets us a floating point # number between upper and lower bound # We look at the relative position of # the integer corresponding to our binary list # between the upper and lower bound, # and offset that by lower bound return (( # Range between lower and upper bound float(upper_bound - lower_bound) # Divided by the maximum possible integer / (2**len(binary_list) - 1) # Times the integer represented by the given binary * binary_to_int(binary_list)) # Plus the lower bound + lower_bound)
python
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 lower_bound # A little bit of math gets us a floating point # number between upper and lower bound # We look at the relative position of # the integer corresponding to our binary list # between the upper and lower bound, # and offset that by lower bound return (( # Range between lower and upper bound float(upper_bound - lower_bound) # Divided by the maximum possible integer / (2**len(binary_list) - 1) # Times the integer represented by the given binary * binary_to_int(binary_list)) # Plus the lower bound + lower_bound)
[ "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 precise floating points. lower_bound: Minimum value for output, inclusive. A binary list of 0s will have this value. upper_bound: Maximum value for output, inclusive. A binary list of 1s will have this value. Returns: float; A floating point number.
[ "Return", "a", "floating", "point", "number", "between", "lower", "and", "upper", "bounds", "from", "binary", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/helpers.py#L34-L71
6,909
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. lower_bound: Minimum value for output, inclusive. A binary list of 0s will have this value. upper_bound: Maximum value for output, inclusive. If greater than this bound, we "bounce back". Ex. w/ upper_bound = 2: [0, 1, 2, 2, 1, 0] Ex. raw_integer = 11, upper_bound = 10, return = 10 raw_integer = 12, upper_bound = 10, return = 9 Returns: int; Integer value of the binary input. """ # 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 lower_bound else: # The builtin int construction can take a base argument, # but it requires a string, # so we convert our binary list to a string integer = int(''.join([str(bit) for bit in binary_list]), 2) # Trim if over upper_bound if (upper_bound is not None) and integer + lower_bound > upper_bound: # Bounce back. Ex. w/ upper_bound = 2: [0, 1, 2, 2, 1, 0] return upper_bound - (integer % (upper_bound - lower_bound + 1)) else: # Not over upper_bound return integer + lower_bound
python
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 lower_bound return lower_bound else: # The builtin int construction can take a base argument, # but it requires a string, # so we convert our binary list to a string integer = int(''.join([str(bit) for bit in binary_list]), 2) # Trim if over upper_bound if (upper_bound is not None) and integer + lower_bound > upper_bound: # Bounce back. Ex. w/ upper_bound = 2: [0, 1, 2, 2, 1, 0] return upper_bound - (integer % (upper_bound - lower_bound + 1)) else: # Not over upper_bound return integer + lower_bound
[ "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 binary list of 0s will have this value. upper_bound: Maximum value for output, inclusive. If greater than this bound, we "bounce back". Ex. w/ upper_bound = 2: [0, 1, 2, 2, 1, 0] Ex. raw_integer = 11, upper_bound = 10, return = 10 raw_integer = 12, upper_bound = 10, return = 9 Returns: int; Integer value of the binary input.
[ "Return", "the", "base", "10", "integer", "corresponding", "to", "a", "binary", "list", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/helpers.py#L74-L111
6,910
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: # Too long, take only last n return binary_list[len(binary_list)-size:] elif size > len(binary_list): # Too short, pad return [0]*(size-len(binary_list)) + binary_list else: # Just right return binary_list
python
def _int_to_binary(integer, size=None): binary_list = map(int, format(integer, 'b')) if size is None: return binary_list else: if len(binary_list) > size: # Too long, take only last n return binary_list[len(binary_list)-size:] elif size > len(binary_list): # Too short, pad return [0]*(size-len(binary_list)) + binary_list else: # Just right return binary_list
[ "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", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/baseline.py#L164-L182
6,911
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 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", "." ]
ab48a4961697338cc32d50e3a6b06ac989e39c3f
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/baseline.py#L108-L111
6,912
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(parent.full_path, component) if os.path.exists(fp): node = Node(name=component, parent=parent) parent.children.append(node) else: node = parent.create_cgroup(component) parent = node self._init_children(node) else: self._init_children(parent)
python
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.path.join(parent.full_path, component) if os.path.exists(fp): node = Node(name=component, parent=parent) parent.children.append(node) else: node = parent.create_cgroup(component) parent = node self._init_children(node) else: self._init_children(parent)
[ "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", "." ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/trees.py#L82-L99
6,913
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_children(child)
python
def _init_children(self, parent): for dir_name in self.get_children_paths(parent.full_path): child = Node(name=dir_name, parent=parent) parent.children.append(child) self._init_children(child)
[ "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", "." ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/trees.py#L101-L109
6,914
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): 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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L87-L92
6,915
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 b"/"
python
def path(self): 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 b"/"
[ "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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L95-L104
6,916
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: return self.NODE_SLICE elif b".scope" in self.name: return self.NODE_SCOPE else: return self.NODE_CGROUP
python
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_CONTROLLER_ROOT elif b".slice" in self.name or b'.partition' in self.name: return self.NODE_SLICE elif b".scope" in self.name: return self.NODE_SCOPE else: return self.NODE_CGROUP
[ "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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L106-L118
6,917
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): 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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L120-L128
6,918
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() fp = os.path.join(self.full_path, name) os.mkdir(fp) self.children.append(node) return node
python
def create_cgroup(self, name): node = Node(name, parent=self) if node in self.children: raise RuntimeError('Node {} already exists under {}'.format(name, self.path)) name = name.encode() fp = os.path.join(self.full_path, name) os.mkdir(fp) self.children.append(node) return node
[ "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", "." ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L137-L149
6,919
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(name, parent=self) try: self.children.remove(node) except ValueError: return
python
def delete_cgroup(self, name): name = name.encode() fp = os.path.join(self.full_path, name) if os.path.exists(fp): os.rmdir(fp) node = Node(name, parent=self) try: self.children.remove(node) except ValueError: return
[ "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", "." ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L151-L164
6,920
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.full_path) except OSError: pass else: self.children.remove(child)
python
def delete_empty_children(self): for child in self.children: child.delete_empty_children() try: if os.path.exists(child.full_path): os.rmdir(child.full_path) except OSError: pass else: self.children.remove(child)
[ "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", "." ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L166-L176
6,921
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( node, node.controller_type )) self.nodes.append(node) if node.controller: self.controllers[node.controller_type] = node.controller setattr(self, node.controller_type, node.controller)
python
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 assigned".format( node, node.controller_type )) self.nodes.append(node) if node.controller: self.controllers[node.controller_type] = node.controller setattr(self, node.controller_type, node.controller)
[ "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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L219-L231
6,922
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): 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", "." ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L241-L247
6,923
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 = 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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L250-L255
6,924
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): 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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/controllers.py#L48-L51
6,925
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): 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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/controllers.py#L53-L57
6,926
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): 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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/controllers.py#L59-L63
6,927
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): 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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/utils.py#L32-L38
6,928
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): 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" ]
e705ac4ccdfe33d8ecc700e9a35a9556084449ca
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/utils.py#L41-L47
6,929
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): 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", "." ]
ee1de8468abeb800e3ad0134952726cdce6b2459
https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/base.py#L48-L58
6,930
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): 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", "." ]
ee1de8468abeb800e3ad0134952726cdce6b2459
https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/base.py#L67-L74
6,931
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): 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", "." ]
ee1de8468abeb800e3ad0134952726cdce6b2459
https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/base.py#L85-L91
6,932
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 # then try pattern properties pattern_properties = schema.get("patternProperties", {}) for pattern, pattern_schema in pattern_properties.items(): if match(pattern, key): return pattern_schema # finally try additional properties (defaults to true per JSON Schema) return schema.get("additionalProperties", True)
python
def property_schema(self, key): schema = self.__class__.SCHEMA # first try plain properties plain_schema = schema.get("properties", {}).get(key) if plain_schema is not None: return plain_schema # then try pattern properties pattern_properties = schema.get("patternProperties", {}) for pattern, pattern_schema in pattern_properties.items(): if match(pattern, key): return pattern_schema # finally try additional properties (defaults to true per JSON Schema) return schema.get("additionalProperties", True)
[ "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", "." ]
ee1de8468abeb800e3ad0134952726cdce6b2459
https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/base.py#L141-L158
6,933
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): 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", "." ]
ee1de8468abeb800e3ad0134952726cdce6b2459
https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/model.py#L11-L15
6,934
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): 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", "." ]
ee1de8468abeb800e3ad0134952726cdce6b2459
https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/model.py#L18-L25
6,935
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): 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", "." ]
ee1de8468abeb800e3ad0134952726cdce6b2459
https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/registry.py#L12-L19
6,936
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): 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", "." ]
ee1de8468abeb800e3ad0134952726cdce6b2459
https://github.com/globality-corp/openapi/blob/ee1de8468abeb800e3ad0134952726cdce6b2459/openapi/registry.py#L22-L32
6,937
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 resumes when we are fully connected. self.start() with self._lock: self._connect_cond.wait_for(lambda: self._connected)
python
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 that connection is established. This # ensures that the caller only resumes when we are fully connected. self.start() with self._lock: self._connect_cond.wait_for(lambda: self._connected)
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L63-L72
6,938
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): _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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L74-L83
6,939
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L111-L116
6,940
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("Connected")
python
def _maybe_reconnect(self): with self._lock: if not self._connected: _LOGGER.info("Connecting") self._do_login_locked() self._connected = True self._connect_cond.notify_all() _LOGGER.info("Connected")
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L118-L126
6,941
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 the lock because if the connection is # open, we are the only ones that will read from telnet (the reconnect # code runs synchronously in this loop). t = self._telnet if t is not None: line = t.read_until(b"\n") except EOFError: try: self._lock.acquire() self._disconnect_locked() continue finally: self._lock.release() self._recv_cb(line.decode('ascii').rstrip())
python
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 beforehand. We don't need the lock because if the connection is # open, we are the only ones that will read from telnet (the reconnect # code runs synchronously in this loop). t = self._telnet if t is not None: line = t.read_until(b"\n") except EOFError: try: self._lock.acquire() self._disconnect_locked() continue finally: self._lock.release() self._recv_cb(line.decode('ascii').rstrip())
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L128-L149
6,942
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> # <Area ...> # <DeviceGroups ...> # <Scenes ...> # <ShadeGroups ...> # <Outputs ...> # <Areas ...> # <Area ...> # First area is useless, it's the top-level project area that defines the # "house". It contains the real nested Areas tree, which is the one we want. top_area = root.find('Areas').find('Area') self.project_name = top_area.get('Name') areas = top_area.find('Areas') for area_xml in areas.getiterator('Area'): area = self._parse_area(area_xml) self.areas.append(area) return True
python
def parse(self): import xml.etree.ElementTree as ET root = ET.fromstring(self._xml_db_str) # The structure is something like this: # <Areas> # <Area ...> # <DeviceGroups ...> # <Scenes ...> # <ShadeGroups ...> # <Outputs ...> # <Areas ...> # <Area ...> # First area is useless, it's the top-level project area that defines the # "house". It contains the real nested Areas tree, which is the one we want. top_area = root.find('Areas').find('Area') self.project_name = top_area.get('Name') areas = top_area.find('Areas') for area_xml in areas.getiterator('Area'): area = self._parse_area(area_xml) self.areas.append(area) return True
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L166-L190
6,943
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')), occupancy_group_id=area_xml.get('OccupancyGroupAssignedToID')) for output_xml in area_xml.find('Outputs'): output = self._parse_output(output_xml) area.add_output(output) # device group in our case means keypad # device_group.get('Name') is the location of the keypad for device_group in area_xml.find('DeviceGroups'): if device_group.tag == 'DeviceGroup': devs = device_group.find('Devices') elif device_group.tag == 'Device': devs = [device_group] else: _LOGGER.info("Unknown tag in DeviceGroups child %s" % devs) devs = [] for device_xml in devs: if device_xml.tag != 'Device': continue if device_xml.get('DeviceType') in ( 'SEETOUCH_KEYPAD', 'SEETOUCH_TABLETOP_KEYPAD', 'PICO_KEYPAD', 'HYBRID_SEETOUCH_KEYPAD', 'MAIN_REPEATER'): keypad = self._parse_keypad(device_xml) area.add_keypad(keypad) elif device_xml.get('DeviceType') == 'MOTION_SENSOR': motion_sensor = self._parse_motion_sensor(device_xml) area.add_sensor(motion_sensor) #elif device_xml.get('DeviceType') == 'VISOR_CONTROL_RECEIVER': return area
python
def _parse_area(self, area_xml): area = Area(self._lutron, name=area_xml.get('Name'), integration_id=int(area_xml.get('IntegrationID')), occupancy_group_id=area_xml.get('OccupancyGroupAssignedToID')) for output_xml in area_xml.find('Outputs'): output = self._parse_output(output_xml) area.add_output(output) # device group in our case means keypad # device_group.get('Name') is the location of the keypad for device_group in area_xml.find('DeviceGroups'): if device_group.tag == 'DeviceGroup': devs = device_group.find('Devices') elif device_group.tag == 'Device': devs = [device_group] else: _LOGGER.info("Unknown tag in DeviceGroups child %s" % devs) devs = [] for device_xml in devs: if device_xml.tag != 'Device': continue if device_xml.get('DeviceType') in ( 'SEETOUCH_KEYPAD', 'SEETOUCH_TABLETOP_KEYPAD', 'PICO_KEYPAD', 'HYBRID_SEETOUCH_KEYPAD', 'MAIN_REPEATER'): keypad = self._parse_keypad(device_xml) area.add_keypad(keypad) elif device_xml.get('DeviceType') == 'MOTION_SENSOR': motion_sensor = self._parse_motion_sensor(device_xml) area.add_sensor(motion_sensor) #elif device_xml.get('DeviceType') == 'VISOR_CONTROL_RECEIVER': return area
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L192-L227
6,944
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 which have no engravings. if button_type == 'SingleSceneRaiseLower': name = 'Dimmer ' + direction if not name: name = "Unknown Button" button = Button(self._lutron, keypad, name=name, num=int(component_xml.get('ComponentNumber')), button_type=button_type, direction=direction) return button
python
def _parse_button(self, keypad, component_xml): 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 which have no engravings. if button_type == 'SingleSceneRaiseLower': name = 'Dimmer ' + direction if not name: name = "Unknown Button" button = Button(self._lutron, keypad, name=name, num=int(component_xml.get('ComponentNumber')), button_type=button_type, direction=direction) return button
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L259-L275
6,945
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, component_num=component_num) return led
python
def _parse_led(self, keypad, component_xml): 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, component_num=component_num) return led
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L277-L285
6,946
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 handle this later. """ return MotionSensor(self._lutron, name=sensor_xml.get('Name'), integration_id=int(sensor_xml.get('IntegrationID')))
python
def _parse_motion_sensor(self, sensor_xml): return MotionSensor(self._lutron, name=sensor_xml.get('Name'), integration_id=int(sensor_xml.get('IntegrationID')))
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L287-L297
6,947
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, LutronEntity): raise InvalidSubscription("Subscription target not a LutronEntity") _LOGGER.warning("DEPRECATED: Subscribing via Lutron.subscribe is obsolete. " "Please use LutronEntity.subscribe") if obj not in self._legacy_subscribers: self._legacy_subscribers[obj] = handler obj.subscribe(self._dispatch_legacy_subscriber, None)
python
def subscribe(self, obj, handler): if not isinstance(obj, LutronEntity): raise InvalidSubscription("Subscription target not a LutronEntity") _LOGGER.warning("DEPRECATED: Subscribing via Lutron.subscribe is obsolete. " "Please use LutronEntity.subscribe") if obj not in self._legacy_subscribers: self._legacy_subscribers[obj] = handler obj.subscribe(self._dispatch_legacy_subscriber, None)
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L330-L344
6,948
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L355-L360
6,949
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.debug("ignoring %s" % line) return parts = line[1:].split(',') cmd_type = parts[0] integration_id = int(parts[1]) args = parts[2:] if cmd_type not in self._ids: _LOGGER.info("Unknown cmd %s (%s)" % (cmd_type, line)) return ids = self._ids[cmd_type] if integration_id not in ids: _LOGGER.warning("Unknown id %d (%s)" % (integration_id, line)) return obj = ids[integration_id] handled = obj.handle_update(args)
python
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.OP_RESPONSE: _LOGGER.debug("ignoring %s" % line) return parts = line[1:].split(',') cmd_type = parts[0] integration_id = int(parts[1]) args = parts[2:] if cmd_type not in self._ids: _LOGGER.info("Unknown cmd %s (%s)" % (cmd_type, line)) return ids = self._ids[cmd_type] if integration_id not in ids: _LOGGER.warning("Unknown id %d (%s)" % (integration_id, line)) return obj = ids[integration_id] handled = obj.handle_update(args)
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L362-L383
6,950
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L389-L393
6,951
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=xml_db) assert(parser.parse()) # throw our own exception self._areas = parser.areas self._name = parser.project_name _LOGGER.info('Found Lutron project: %s, %d areas' % ( self._name, len(self.areas))) return True
python
def load_xml_db(self): 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=xml_db) assert(parser.parse()) # throw our own exception self._areas = parser.areas self._name = parser.project_name _LOGGER.info('Found Lutron project: %s, %d areas' % ( self._name, len(self.areas))) return True
[ "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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L395-L412
6,952
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L441-L451
6,953
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L485-L488
6,954
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 event: the LutronEvent that was generated. params: a dict of event-specific parameters context: User-supplied, opaque object that will be passed to handler. """ self._subscribers.append((handler, context))
python
def subscribe(self, handler: LutronEventHandler, context): self._subscribers.append((handler, context))
[ "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. params: a dict of event-specific parameters context: User-supplied, opaque object that will be passed to handler.
[ "Subscribes", "to", "events", "from", "this", "entity", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L490-L501
6,955
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L580-L584
6,956
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L587-L593
6,957
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L687-L690
6,958
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L738-L741
6,959
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L749-L753
6,960
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L756-L764
6,961
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): 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", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L802-L806
6,962
thecynic/pylutron
pylutron/__init__.py
Keypad.add_led
def add_led(self, led): """Add an LED that's part of this keypad.""" self._leds.append(led) self._components[led.component_number] = led
python
def add_led(self, led): self._leds.append(led) self._components[led.component_number] = led
[ "def", "add_led", "(", "self", ",", "led", ")", ":", "self", ".", "_leds", ".", "append", "(", "led", ")", "self", ".", "_components", "[", "led", ".", "component_number", "]", "=", "led" ]
Add an LED that's part of this keypad.
[ "Add", "an", "LED", "that", "s", "part", "of", "this", "keypad", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L808-L811
6,963
thecynic/pylutron
pylutron/__init__.py
Keypad.handle_update
def handle_update(self, args): """The callback invoked by the main event loop if there's an event from this keypad.""" component = int(args[0]) action = int(args[1]) params = [int(x) for x in args[2:]] _LOGGER.debug("Updating %d(%s): c=%d a=%d params=%s" % ( self._integration_id, self._name, component, action, params)) if component in self._components: return self._components[component].handle_update(action, params) return False
python
def handle_update(self, args): component = int(args[0]) action = int(args[1]) params = [int(x) for x in args[2:]] _LOGGER.debug("Updating %d(%s): c=%d a=%d params=%s" % ( self._integration_id, self._name, component, action, params)) if component in self._components: return self._components[component].handle_update(action, params) return False
[ "def", "handle_update", "(", "self", ",", "args", ")", ":", "component", "=", "int", "(", "args", "[", "0", "]", ")", "action", "=", "int", "(", "args", "[", "1", "]", ")", "params", "=", "[", "int", "(", "x", ")", "for", "x", "in", "args", "...
The callback invoked by the main event loop if there's an event from this keypad.
[ "The", "callback", "invoked", "by", "the", "main", "event", "loop", "if", "there", "s", "an", "event", "from", "this", "keypad", "." ]
4d9222c96ef7ac7ac458031c058ad93ec31cebbf
https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L833-L842
6,964
oasis-open/cti-pattern-validator
stix2patterns/validator.py
run_validator
def run_validator(pattern): """ Validates a pattern against the STIX Pattern grammar. Error messages are returned in a list. The test passed if the returned list is empty. """ start = '' if isinstance(pattern, six.string_types): start = pattern[:2] pattern = InputStream(pattern) if not start: start = pattern.readline()[:2] pattern.seek(0) parseErrListener = STIXPatternErrorListener() lexer = STIXPatternLexer(pattern) # it always adds a console listener by default... remove it. lexer.removeErrorListeners() stream = CommonTokenStream(lexer) parser = STIXPatternParser(stream) parser.buildParseTrees = False # it always adds a console listener by default... remove it. parser.removeErrorListeners() parser.addErrorListener(parseErrListener) # To improve error messages, replace "<INVALID>" in the literal # names with symbolic names. This is a hack, but seemed like # the simplest workaround. for i, lit_name in enumerate(parser.literalNames): if lit_name == u"<INVALID>": parser.literalNames[i] = parser.symbolicNames[i] parser.pattern() # replace with easier-to-understand error message if not (start[0] == '[' or start == '(['): parseErrListener.err_strings[0] = "FAIL: Error found at line 1:0. " \ "input is missing square brackets" return parseErrListener.err_strings
python
def run_validator(pattern): start = '' if isinstance(pattern, six.string_types): start = pattern[:2] pattern = InputStream(pattern) if not start: start = pattern.readline()[:2] pattern.seek(0) parseErrListener = STIXPatternErrorListener() lexer = STIXPatternLexer(pattern) # it always adds a console listener by default... remove it. lexer.removeErrorListeners() stream = CommonTokenStream(lexer) parser = STIXPatternParser(stream) parser.buildParseTrees = False # it always adds a console listener by default... remove it. parser.removeErrorListeners() parser.addErrorListener(parseErrListener) # To improve error messages, replace "<INVALID>" in the literal # names with symbolic names. This is a hack, but seemed like # the simplest workaround. for i, lit_name in enumerate(parser.literalNames): if lit_name == u"<INVALID>": parser.literalNames[i] = parser.symbolicNames[i] parser.pattern() # replace with easier-to-understand error message if not (start[0] == '[' or start == '(['): parseErrListener.err_strings[0] = "FAIL: Error found at line 1:0. " \ "input is missing square brackets" return parseErrListener.err_strings
[ "def", "run_validator", "(", "pattern", ")", ":", "start", "=", "''", "if", "isinstance", "(", "pattern", ",", "six", ".", "string_types", ")", ":", "start", "=", "pattern", "[", ":", "2", "]", "pattern", "=", "InputStream", "(", "pattern", ")", "if", ...
Validates a pattern against the STIX Pattern grammar. Error messages are returned in a list. The test passed if the returned list is empty.
[ "Validates", "a", "pattern", "against", "the", "STIX", "Pattern", "grammar", ".", "Error", "messages", "are", "returned", "in", "a", "list", ".", "The", "test", "passed", "if", "the", "returned", "list", "is", "empty", "." ]
753a6901120db25f0c8550607de1eab4440d59df
https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/validator.py#L31-L74
6,965
oasis-open/cti-pattern-validator
stix2patterns/validator.py
validate
def validate(user_input, ret_errs=False, print_errs=False): """ Wrapper for run_validator function that returns True if the user_input contains a valid STIX pattern or False otherwise. The error messages may also be returned or printed based upon the ret_errs and print_errs arg values. """ errs = run_validator(user_input) passed = len(errs) == 0 if print_errs: for err in errs: print(err) if ret_errs: return passed, errs return passed
python
def validate(user_input, ret_errs=False, print_errs=False): errs = run_validator(user_input) passed = len(errs) == 0 if print_errs: for err in errs: print(err) if ret_errs: return passed, errs return passed
[ "def", "validate", "(", "user_input", ",", "ret_errs", "=", "False", ",", "print_errs", "=", "False", ")", ":", "errs", "=", "run_validator", "(", "user_input", ")", "passed", "=", "len", "(", "errs", ")", "==", "0", "if", "print_errs", ":", "for", "er...
Wrapper for run_validator function that returns True if the user_input contains a valid STIX pattern or False otherwise. The error messages may also be returned or printed based upon the ret_errs and print_errs arg values.
[ "Wrapper", "for", "run_validator", "function", "that", "returns", "True", "if", "the", "user_input", "contains", "a", "valid", "STIX", "pattern", "or", "False", "otherwise", ".", "The", "error", "messages", "may", "also", "be", "returned", "or", "printed", "ba...
753a6901120db25f0c8550607de1eab4440d59df
https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/validator.py#L77-L95
6,966
oasis-open/cti-pattern-validator
stix2patterns/validator.py
main
def main(): """ Continues to validate patterns until it encounters EOF within a pattern file or Ctrl-C is pressed by the user. """ parser = argparse.ArgumentParser(description='Validate STIX Patterns.') parser.add_argument('-f', '--file', help="Specify this arg to read patterns from a file.", type=argparse.FileType("r")) args = parser.parse_args() pass_count = fail_count = 0 # I tried using a generator (where each iteration would run raw_input()), # but raw_input()'s behavior seems to change when called from within a # generator: I only get one line, then the generator completes! I don't # know why behavior changes... import functools if args.file: nextpattern = args.file.readline else: nextpattern = functools.partial(six.moves.input, "Enter a pattern to validate: ") try: while True: pattern = nextpattern() if not pattern: break tests_passed, err_strings = validate(pattern, True) if tests_passed: print("\nPASS: %s" % pattern) pass_count += 1 else: for err in err_strings: print(err, '\n') fail_count += 1 except (EOFError, KeyboardInterrupt): pass finally: if args.file: args.file.close() print("\nPASSED:", pass_count, " patterns") print("FAILED:", fail_count, " patterns")
python
def main(): parser = argparse.ArgumentParser(description='Validate STIX Patterns.') parser.add_argument('-f', '--file', help="Specify this arg to read patterns from a file.", type=argparse.FileType("r")) args = parser.parse_args() pass_count = fail_count = 0 # I tried using a generator (where each iteration would run raw_input()), # but raw_input()'s behavior seems to change when called from within a # generator: I only get one line, then the generator completes! I don't # know why behavior changes... import functools if args.file: nextpattern = args.file.readline else: nextpattern = functools.partial(six.moves.input, "Enter a pattern to validate: ") try: while True: pattern = nextpattern() if not pattern: break tests_passed, err_strings = validate(pattern, True) if tests_passed: print("\nPASS: %s" % pattern) pass_count += 1 else: for err in err_strings: print(err, '\n') fail_count += 1 except (EOFError, KeyboardInterrupt): pass finally: if args.file: args.file.close() print("\nPASSED:", pass_count, " patterns") print("FAILED:", fail_count, " patterns")
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Validate STIX Patterns.'", ")", "parser", ".", "add_argument", "(", "'-f'", ",", "'--file'", ",", "help", "=", "\"Specify this arg to read patterns from a file...
Continues to validate patterns until it encounters EOF within a pattern file or Ctrl-C is pressed by the user.
[ "Continues", "to", "validate", "patterns", "until", "it", "encounters", "EOF", "within", "a", "pattern", "file", "or", "Ctrl", "-", "C", "is", "pressed", "by", "the", "user", "." ]
753a6901120db25f0c8550607de1eab4440d59df
https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/validator.py#L98-L143
6,967
alexhayes/django-pdfkit
django_pdfkit/views.py
PDFView.get
def get(self, request, *args, **kwargs): """ Return a HTTPResponse either of a PDF file or HTML. :rtype: HttpResponse """ if 'html' in request.GET: # Output HTML content = self.render_html(*args, **kwargs) return HttpResponse(content) else: # Output PDF content = self.render_pdf(*args, **kwargs) response = HttpResponse(content, content_type='application/pdf') if (not self.inline or 'download' in request.GET) and 'inline' not in request.GET: response['Content-Disposition'] = 'attachment; filename=%s' % self.get_filename() response['Content-Length'] = len(content) return response
python
def get(self, request, *args, **kwargs): if 'html' in request.GET: # Output HTML content = self.render_html(*args, **kwargs) return HttpResponse(content) else: # Output PDF content = self.render_pdf(*args, **kwargs) response = HttpResponse(content, content_type='application/pdf') if (not self.inline or 'download' in request.GET) and 'inline' not in request.GET: response['Content-Disposition'] = 'attachment; filename=%s' % self.get_filename() response['Content-Length'] = len(content) return response
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'html'", "in", "request", ".", "GET", ":", "# Output HTML", "content", "=", "self", ".", "render_html", "(", "*", "args", ",", "*", "*", "kwargs"...
Return a HTTPResponse either of a PDF file or HTML. :rtype: HttpResponse
[ "Return", "a", "HTTPResponse", "either", "of", "a", "PDF", "file", "or", "HTML", "." ]
02774ae2cb67d05dd5e4cb50661c56464ebb2413
https://github.com/alexhayes/django-pdfkit/blob/02774ae2cb67d05dd5e4cb50661c56464ebb2413/django_pdfkit/views.py#L31-L53
6,968
alexhayes/django-pdfkit
django_pdfkit/views.py
PDFView.render_pdf
def render_pdf(self, *args, **kwargs): """ Render the PDF and returns as bytes. :rtype: bytes """ html = self.render_html(*args, **kwargs) options = self.get_pdfkit_options() if 'debug' in self.request.GET and settings.DEBUG: options['debug-javascript'] = 1 kwargs = {} wkhtmltopdf_bin = os.environ.get('WKHTMLTOPDF_BIN') if wkhtmltopdf_bin: kwargs['configuration'] = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_bin) pdf = pdfkit.from_string(html, False, options, **kwargs) return pdf
python
def render_pdf(self, *args, **kwargs): html = self.render_html(*args, **kwargs) options = self.get_pdfkit_options() if 'debug' in self.request.GET and settings.DEBUG: options['debug-javascript'] = 1 kwargs = {} wkhtmltopdf_bin = os.environ.get('WKHTMLTOPDF_BIN') if wkhtmltopdf_bin: kwargs['configuration'] = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_bin) pdf = pdfkit.from_string(html, False, options, **kwargs) return pdf
[ "def", "render_pdf", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "html", "=", "self", ".", "render_html", "(", "*", "args", ",", "*", "*", "kwargs", ")", "options", "=", "self", ".", "get_pdfkit_options", "(", ")", "if", "'deb...
Render the PDF and returns as bytes. :rtype: bytes
[ "Render", "the", "PDF", "and", "returns", "as", "bytes", "." ]
02774ae2cb67d05dd5e4cb50661c56464ebb2413
https://github.com/alexhayes/django-pdfkit/blob/02774ae2cb67d05dd5e4cb50661c56464ebb2413/django_pdfkit/views.py#L55-L74
6,969
alexhayes/django-pdfkit
django_pdfkit/views.py
PDFView.get_filename
def get_filename(self): """ Return ``self.filename`` if set otherwise return the template basename with a ``.pdf`` extension. :rtype: str """ if self.filename is None: name = splitext(basename(self.template_name))[0] return '{}.pdf'.format(name) return self.filename
python
def get_filename(self): if self.filename is None: name = splitext(basename(self.template_name))[0] return '{}.pdf'.format(name) return self.filename
[ "def", "get_filename", "(", "self", ")", ":", "if", "self", ".", "filename", "is", "None", ":", "name", "=", "splitext", "(", "basename", "(", "self", ".", "template_name", ")", ")", "[", "0", "]", "return", "'{}.pdf'", ".", "format", "(", "name", ")...
Return ``self.filename`` if set otherwise return the template basename with a ``.pdf`` extension. :rtype: str
[ "Return", "self", ".", "filename", "if", "set", "otherwise", "return", "the", "template", "basename", "with", "a", ".", "pdf", "extension", "." ]
02774ae2cb67d05dd5e4cb50661c56464ebb2413
https://github.com/alexhayes/django-pdfkit/blob/02774ae2cb67d05dd5e4cb50661c56464ebb2413/django_pdfkit/views.py#L90-L100
6,970
alexhayes/django-pdfkit
django_pdfkit/views.py
PDFView.render_html
def render_html(self, *args, **kwargs): """ Renders the template. :rtype: str """ static_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.STATIC_URL) media_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.MEDIA_URL) with override_settings(STATIC_URL=static_url, MEDIA_URL=media_url): template = loader.get_template(self.template_name) context = self.get_context_data(*args, **kwargs) html = template.render(context) return html
python
def render_html(self, *args, **kwargs): static_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.STATIC_URL) media_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.MEDIA_URL) with override_settings(STATIC_URL=static_url, MEDIA_URL=media_url): template = loader.get_template(self.template_name) context = self.get_context_data(*args, **kwargs) html = template.render(context) return html
[ "def", "render_html", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "static_url", "=", "'%s://%s%s'", "%", "(", "self", ".", "request", ".", "scheme", ",", "self", ".", "request", ".", "get_host", "(", ")", ",", "settings", ".", ...
Renders the template. :rtype: str
[ "Renders", "the", "template", "." ]
02774ae2cb67d05dd5e4cb50661c56464ebb2413
https://github.com/alexhayes/django-pdfkit/blob/02774ae2cb67d05dd5e4cb50661c56464ebb2413/django_pdfkit/views.py#L102-L115
6,971
oasis-open/cti-pattern-validator
stix2patterns/pattern.py
Pattern.inspect
def inspect(self): """ Inspect a pattern. This gives information regarding the sorts of operations, content, etc in use in the pattern. :return: Pattern information """ inspector = stix2patterns.inspector.InspectionListener() self.walk(inspector) return inspector.pattern_data()
python
def inspect(self): inspector = stix2patterns.inspector.InspectionListener() self.walk(inspector) return inspector.pattern_data()
[ "def", "inspect", "(", "self", ")", ":", "inspector", "=", "stix2patterns", ".", "inspector", ".", "InspectionListener", "(", ")", "self", ".", "walk", "(", "inspector", ")", "return", "inspector", ".", "pattern_data", "(", ")" ]
Inspect a pattern. This gives information regarding the sorts of operations, content, etc in use in the pattern. :return: Pattern information
[ "Inspect", "a", "pattern", ".", "This", "gives", "information", "regarding", "the", "sorts", "of", "operations", "content", "etc", "in", "use", "in", "the", "pattern", "." ]
753a6901120db25f0c8550607de1eab4440d59df
https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/pattern.py#L36-L47
6,972
oasis-open/cti-pattern-validator
stix2patterns/pattern.py
Pattern.__do_parse
def __do_parse(self, pattern_str): """ Parses the given pattern and returns the antlr parse tree. :param pattern_str: The STIX pattern :return: The parse tree :raises ParseException: If there is a parse error """ in_ = antlr4.InputStream(pattern_str) lexer = STIXPatternLexer(in_) lexer.removeErrorListeners() # remove the default "console" listener token_stream = antlr4.CommonTokenStream(lexer) parser = STIXPatternParser(token_stream) parser.removeErrorListeners() # remove the default "console" listener error_listener = ParserErrorListener() parser.addErrorListener(error_listener) # I found no public API for this... # The default error handler tries to keep parsing, and I don't # think that's appropriate here. (These error handlers are only for # handling the built-in RecognitionException errors.) parser._errHandler = antlr4.BailErrorStrategy() # To improve error messages, replace "<INVALID>" in the literal # names with symbolic names. This is a hack, but seemed like # the simplest workaround. for i, lit_name in enumerate(parser.literalNames): if lit_name == u"<INVALID>": parser.literalNames[i] = parser.symbolicNames[i] # parser.setTrace(True) try: tree = parser.pattern() # print(tree.toStringTree(recog=parser)) return tree except antlr4.error.Errors.ParseCancellationException as e: # The cancellation exception wraps the real RecognitionException # which caused the parser to bail. real_exc = e.args[0] # I want to bail when the first error is hit. But I also want # a decent error message. When an error is encountered in # Parser.match(), the BailErrorStrategy produces the # ParseCancellationException. It is not a subclass of # RecognitionException, so none of the 'except' clauses which would # normally report an error are invoked. # # Error message creation is buried in the ErrorStrategy, and I can # (ab)use the API to get a message: register an error listener with # the parser, force an error report, then get the message out of the # listener. Error listener registration is above; now we force its # invocation. Wish this could be cleaner... parser._errHandler.reportError(parser, real_exc) # should probably chain exceptions if we can... # Should I report the cancellation or recognition exception as the # cause...? six.raise_from(ParseException(error_listener.error_message), real_exc)
python
def __do_parse(self, pattern_str): in_ = antlr4.InputStream(pattern_str) lexer = STIXPatternLexer(in_) lexer.removeErrorListeners() # remove the default "console" listener token_stream = antlr4.CommonTokenStream(lexer) parser = STIXPatternParser(token_stream) parser.removeErrorListeners() # remove the default "console" listener error_listener = ParserErrorListener() parser.addErrorListener(error_listener) # I found no public API for this... # The default error handler tries to keep parsing, and I don't # think that's appropriate here. (These error handlers are only for # handling the built-in RecognitionException errors.) parser._errHandler = antlr4.BailErrorStrategy() # To improve error messages, replace "<INVALID>" in the literal # names with symbolic names. This is a hack, but seemed like # the simplest workaround. for i, lit_name in enumerate(parser.literalNames): if lit_name == u"<INVALID>": parser.literalNames[i] = parser.symbolicNames[i] # parser.setTrace(True) try: tree = parser.pattern() # print(tree.toStringTree(recog=parser)) return tree except antlr4.error.Errors.ParseCancellationException as e: # The cancellation exception wraps the real RecognitionException # which caused the parser to bail. real_exc = e.args[0] # I want to bail when the first error is hit. But I also want # a decent error message. When an error is encountered in # Parser.match(), the BailErrorStrategy produces the # ParseCancellationException. It is not a subclass of # RecognitionException, so none of the 'except' clauses which would # normally report an error are invoked. # # Error message creation is buried in the ErrorStrategy, and I can # (ab)use the API to get a message: register an error listener with # the parser, force an error report, then get the message out of the # listener. Error listener registration is above; now we force its # invocation. Wish this could be cleaner... parser._errHandler.reportError(parser, real_exc) # should probably chain exceptions if we can... # Should I report the cancellation or recognition exception as the # cause...? six.raise_from(ParseException(error_listener.error_message), real_exc)
[ "def", "__do_parse", "(", "self", ",", "pattern_str", ")", ":", "in_", "=", "antlr4", ".", "InputStream", "(", "pattern_str", ")", "lexer", "=", "STIXPatternLexer", "(", "in_", ")", "lexer", ".", "removeErrorListeners", "(", ")", "# remove the default \"console\...
Parses the given pattern and returns the antlr parse tree. :param pattern_str: The STIX pattern :return: The parse tree :raises ParseException: If there is a parse error
[ "Parses", "the", "given", "pattern", "and", "returns", "the", "antlr", "parse", "tree", "." ]
753a6901120db25f0c8550607de1eab4440d59df
https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/pattern.py#L56-L117
6,973
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
Response.exists
def exists(self): """ Returns true if the job is still running or zero-os still knows about this job ID After a job is finished, a job remains on zero-os for max of 5min where you still can read the job result after the 5 min is gone, the job result is no more fetchable :return: bool """ r = self._client._redis flag = '{}:flag'.format(self._queue) return bool(r.exists(flag))
python
def exists(self): r = self._client._redis flag = '{}:flag'.format(self._queue) return bool(r.exists(flag))
[ "def", "exists", "(", "self", ")", ":", "r", "=", "self", ".", "_client", ".", "_redis", "flag", "=", "'{}:flag'", ".", "format", "(", "self", ".", "_queue", ")", "return", "bool", "(", "r", ".", "exists", "(", "flag", ")", ")" ]
Returns true if the job is still running or zero-os still knows about this job ID After a job is finished, a job remains on zero-os for max of 5min where you still can read the job result after the 5 min is gone, the job result is no more fetchable :return: bool
[ "Returns", "true", "if", "the", "job", "is", "still", "running", "or", "zero", "-", "os", "still", "knows", "about", "this", "job", "ID" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L162-L172
6,974
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
Response.stream
def stream(self, callback=None): """ Runtime copy of job messages. This required the 'stream` flag to be set to True otherwise it will not be able to copy any output, while it will block until the process exits. :note: This function will block until it reaches end of stream or the process is no longer running. :param callback: callback method that will get called for each received message callback accepts 3 arguments - level int: the log message levels, refer to the docs for available levels and their meanings - message str: the actual output message - flags int: flags associated with this message - 0x2 means EOF with success exit status - 0x4 means EOF with error for example (eof = flag & 0x6) eof will be true for last message u will ever receive on this callback. Note: if callback is none, a default callback will be used that prints output on stdout/stderr based on level. :return: None """ if callback is None: callback = Response.__default if not callable(callback): raise Exception('callback must be callable') queue = 'stream:%s' % self.id r = self._client._redis # we can terminate quickly by checking if the process is not running and it has no queued output. # if not self.running and r.llen(queue) == 0: # return while True: data = r.blpop(queue, 10) if data is None: if not self.running: break continue _, body = data payload = json.loads(body.decode()) message = payload['message'] line = message['message'] meta = message['meta'] callback(meta >> 16, line, meta & 0xff) if meta & 0x6 != 0: break
python
def stream(self, callback=None): if callback is None: callback = Response.__default if not callable(callback): raise Exception('callback must be callable') queue = 'stream:%s' % self.id r = self._client._redis # we can terminate quickly by checking if the process is not running and it has no queued output. # if not self.running and r.llen(queue) == 0: # return while True: data = r.blpop(queue, 10) if data is None: if not self.running: break continue _, body = data payload = json.loads(body.decode()) message = payload['message'] line = message['message'] meta = message['meta'] callback(meta >> 16, line, meta & 0xff) if meta & 0x6 != 0: break
[ "def", "stream", "(", "self", ",", "callback", "=", "None", ")", ":", "if", "callback", "is", "None", ":", "callback", "=", "Response", ".", "__default", "if", "not", "callable", "(", "callback", ")", ":", "raise", "Exception", "(", "'callback must be call...
Runtime copy of job messages. This required the 'stream` flag to be set to True otherwise it will not be able to copy any output, while it will block until the process exits. :note: This function will block until it reaches end of stream or the process is no longer running. :param callback: callback method that will get called for each received message callback accepts 3 arguments - level int: the log message levels, refer to the docs for available levels and their meanings - message str: the actual output message - flags int: flags associated with this message - 0x2 means EOF with success exit status - 0x4 means EOF with error for example (eof = flag & 0x6) eof will be true for last message u will ever receive on this callback. Note: if callback is none, a default callback will be used that prints output on stdout/stderr based on level. :return: None
[ "Runtime", "copy", "of", "job", "messages", ".", "This", "required", "the", "stream", "flag", "to", "be", "set", "to", "True", "otherwise", "it", "will", "not", "be", "able", "to", "copy", "any", "output", "while", "it", "will", "block", "until", "the", ...
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L187-L237
6,975
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
JSONResponse.get
def get(self, timeout=None): """ Get response as json, will fail if the job doesn't return a valid json response :param timeout: client side timeout in seconds :return: int """ result = super().get(timeout) if result.state != 'SUCCESS': raise ResultError(result.data, result.code) if result.level != 20: raise ResultError('not a json response: %d' % result.level, 406) return json.loads(result.data)
python
def get(self, timeout=None): result = super().get(timeout) if result.state != 'SUCCESS': raise ResultError(result.data, result.code) if result.level != 20: raise ResultError('not a json response: %d' % result.level, 406) return json.loads(result.data)
[ "def", "get", "(", "self", ",", "timeout", "=", "None", ")", ":", "result", "=", "super", "(", ")", ".", "get", "(", "timeout", ")", "if", "result", ".", "state", "!=", "'SUCCESS'", ":", "raise", "ResultError", "(", "result", ".", "data", ",", "res...
Get response as json, will fail if the job doesn't return a valid json response :param timeout: client side timeout in seconds :return: int
[ "Get", "response", "as", "json", "will", "fail", "if", "the", "job", "doesn", "t", "return", "a", "valid", "json", "response" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L280-L293
6,976
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
JobManager.list
def list(self, id=None): """ List all running jobs :param id: optional ID for the job to list """ args = {'id': id} self._job_chk.check(args) return self._client.json('job.list', args)
python
def list(self, id=None): args = {'id': id} self._job_chk.check(args) return self._client.json('job.list', args)
[ "def", "list", "(", "self", ",", "id", "=", "None", ")", ":", "args", "=", "{", "'id'", ":", "id", "}", "self", ".", "_job_chk", ".", "check", "(", "args", ")", "return", "self", ".", "_client", ".", "json", "(", "'job.list'", ",", "args", ")" ]
List all running jobs :param id: optional ID for the job to list
[ "List", "all", "running", "jobs" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L372-L380
6,977
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
JobManager.kill
def kill(self, id, signal=signal.SIGTERM): """ Kill a job with given id :WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable :param id: job id to kill """ args = { 'id': id, 'signal': int(signal), } self._kill_chk.check(args) return self._client.json('job.kill', args)
python
def kill(self, id, signal=signal.SIGTERM): args = { 'id': id, 'signal': int(signal), } self._kill_chk.check(args) return self._client.json('job.kill', args)
[ "def", "kill", "(", "self", ",", "id", ",", "signal", "=", "signal", ".", "SIGTERM", ")", ":", "args", "=", "{", "'id'", ":", "id", ",", "'signal'", ":", "int", "(", "signal", ")", ",", "}", "self", ".", "_kill_chk", ".", "check", "(", "args", ...
Kill a job with given id :WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable :param id: job id to kill
[ "Kill", "a", "job", "with", "given", "id" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L382-L395
6,978
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
ProcessManager.list
def list(self, id=None): """ List all running processes :param id: optional PID for the process to list """ args = {'pid': id} self._process_chk.check(args) return self._client.json('process.list', args)
python
def list(self, id=None): args = {'pid': id} self._process_chk.check(args) return self._client.json('process.list', args)
[ "def", "list", "(", "self", ",", "id", "=", "None", ")", ":", "args", "=", "{", "'pid'", ":", "id", "}", "self", ".", "_process_chk", ".", "check", "(", "args", ")", "return", "self", ".", "_client", ".", "json", "(", "'process.list'", ",", "args",...
List all running processes :param id: optional PID for the process to list
[ "List", "all", "running", "processes" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L411-L419
6,979
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
FilesystemManager.open
def open(self, file, mode='r', perm=0o0644): """ Opens a file on the node :param file: file path to open :param mode: open mode :param perm: file permission in octet form mode: 'r' read only 'w' write only (truncate) '+' read/write 'x' create if not exist 'a' append :return: a file descriptor """ args = { 'file': file, 'mode': mode, 'perm': perm, } return self._client.json('filesystem.open', args)
python
def open(self, file, mode='r', perm=0o0644): args = { 'file': file, 'mode': mode, 'perm': perm, } return self._client.json('filesystem.open', args)
[ "def", "open", "(", "self", ",", "file", ",", "mode", "=", "'r'", ",", "perm", "=", "0o0644", ")", ":", "args", "=", "{", "'file'", ":", "file", ",", "'mode'", ":", "mode", ",", "'perm'", ":", "perm", ",", "}", "return", "self", ".", "_client", ...
Opens a file on the node :param file: file path to open :param mode: open mode :param perm: file permission in octet form mode: 'r' read only 'w' write only (truncate) '+' read/write 'x' create if not exist 'a' append :return: a file descriptor
[ "Opens", "a", "file", "on", "the", "node" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L442-L464
6,980
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
FilesystemManager.move
def move(self, path, destination): """ Move a path to destination :param path: source :param destination: destination :return: """ args = { 'path': path, 'destination': destination, } return self._client.json('filesystem.move', args)
python
def move(self, path, destination): args = { 'path': path, 'destination': destination, } return self._client.json('filesystem.move', args)
[ "def", "move", "(", "self", ",", "path", ",", "destination", ")", ":", "args", "=", "{", "'path'", ":", "path", ",", "'destination'", ":", "destination", ",", "}", "return", "self", ".", "_client", ".", "json", "(", "'filesystem.move'", ",", "args", ")...
Move a path to destination :param path: source :param destination: destination :return:
[ "Move", "a", "path", "to", "destination" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L516-L529
6,981
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
FilesystemManager.read
def read(self, fd): """ Read a block from the given file descriptor :param fd: file descriptor :return: bytes """ args = { 'fd': fd, } data = self._client.json('filesystem.read', args) return base64.decodebytes(data.encode())
python
def read(self, fd): args = { 'fd': fd, } data = self._client.json('filesystem.read', args) return base64.decodebytes(data.encode())
[ "def", "read", "(", "self", ",", "fd", ")", ":", "args", "=", "{", "'fd'", ":", "fd", ",", "}", "data", "=", "self", ".", "_client", ".", "json", "(", "'filesystem.read'", ",", "args", ")", "return", "base64", ".", "decodebytes", "(", "data", ".", ...
Read a block from the given file descriptor :param fd: file descriptor :return: bytes
[ "Read", "a", "block", "from", "the", "given", "file", "descriptor" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L567-L579
6,982
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
FilesystemManager.write
def write(self, fd, bytes): """ Write a block of bytes to an open file descriptor (that is open with one of the writing modes :param fd: file descriptor :param bytes: bytes block to write :return: :note: don't overkill the node with large byte chunks, also for large file upload check the upload method. """ args = { 'fd': fd, 'block': base64.encodebytes(bytes).decode(), } return self._client.json('filesystem.write', args)
python
def write(self, fd, bytes): args = { 'fd': fd, 'block': base64.encodebytes(bytes).decode(), } return self._client.json('filesystem.write', args)
[ "def", "write", "(", "self", ",", "fd", ",", "bytes", ")", ":", "args", "=", "{", "'fd'", ":", "fd", ",", "'block'", ":", "base64", ".", "encodebytes", "(", "bytes", ")", ".", "decode", "(", ")", ",", "}", "return", "self", ".", "_client", ".", ...
Write a block of bytes to an open file descriptor (that is open with one of the writing modes :param fd: file descriptor :param bytes: bytes block to write :return: :note: don't overkill the node with large byte chunks, also for large file upload check the upload method.
[ "Write", "a", "block", "of", "bytes", "to", "an", "open", "file", "descriptor", "(", "that", "is", "open", "with", "one", "of", "the", "writing", "modes" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L581-L596
6,983
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
BaseClient.bash
def bash(self, script, stdin='', queue=None, max_time=None, stream=False, tags=None, id=None): """ Execute a bash script, or run a process inside a bash shell. :param script: Script to execute (can be multiline script) :param stdin: Stdin data to feed to the script :param id: job id. Auto generated if not defined. :return: """ args = { 'script': script, 'stdin': stdin, } self._bash_chk.check(args) response = self.raw(command='bash', arguments=args, queue=queue, max_time=max_time, stream=stream, tags=tags, id=id) return response
python
def bash(self, script, stdin='', queue=None, max_time=None, stream=False, tags=None, id=None): args = { 'script': script, 'stdin': stdin, } self._bash_chk.check(args) response = self.raw(command='bash', arguments=args, queue=queue, max_time=max_time, stream=stream, tags=tags, id=id) return response
[ "def", "bash", "(", "self", ",", "script", ",", "stdin", "=", "''", ",", "queue", "=", "None", ",", "max_time", "=", "None", ",", "stream", "=", "False", ",", "tags", "=", "None", ",", "id", "=", "None", ")", ":", "args", "=", "{", "'script'", ...
Execute a bash script, or run a process inside a bash shell. :param script: Script to execute (can be multiline script) :param stdin: Stdin data to feed to the script :param id: job id. Auto generated if not defined. :return:
[ "Execute", "a", "bash", "script", "or", "run", "a", "process", "inside", "a", "bash", "shell", "." ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L820-L837
6,984
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
ContainerManager.terminate
def terminate(self, container): """ Terminate a container given it's id :param container: container id :return: """ self._client_chk.check(container) args = { 'container': int(container), } response = self._client.raw('corex.terminate', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to terminate container: %s' % result.data)
python
def terminate(self, container): self._client_chk.check(container) args = { 'container': int(container), } response = self._client.raw('corex.terminate', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to terminate container: %s' % result.data)
[ "def", "terminate", "(", "self", ",", "container", ")", ":", "self", ".", "_client_chk", ".", "check", "(", "container", ")", "args", "=", "{", "'container'", ":", "int", "(", "container", ")", ",", "}", "response", "=", "self", ".", "_client", ".", ...
Terminate a container given it's id :param container: container id :return:
[ "Terminate", "a", "container", "given", "it", "s", "id" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1126-L1141
6,985
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
ContainerManager.nic_add
def nic_add(self, container, nic): """ Hot plug a nic into a container :param container: container ID :param nic: { 'type': nic_type # one of default, bridge, zerotier, macvlan, passthrough, vlan, or vxlan (note, vlan and vxlan only supported by ovs) 'id': id # depends on the type bridge: bridge name, zerotier: network id, macvlan: the parent link name, passthrough: the link name, vlan: the vlan tag, vxlan: the vxlan id 'name': name of the nic inside the container (ignored in zerotier type) 'hwaddr': Mac address of nic. 'config': { # config is only honored for bridge, vlan, and vxlan types 'dhcp': bool, 'cidr': static_ip # ip/mask 'gateway': gateway 'dns': [dns] } } :return: """ args = { 'container': container, 'nic': nic } self._nic_add.check(args) return self._client.json('corex.nic-add', args)
python
def nic_add(self, container, nic): args = { 'container': container, 'nic': nic } self._nic_add.check(args) return self._client.json('corex.nic-add', args)
[ "def", "nic_add", "(", "self", ",", "container", ",", "nic", ")", ":", "args", "=", "{", "'container'", ":", "container", ",", "'nic'", ":", "nic", "}", "self", ".", "_nic_add", ".", "check", "(", "args", ")", "return", "self", ".", "_client", ".", ...
Hot plug a nic into a container :param container: container ID :param nic: { 'type': nic_type # one of default, bridge, zerotier, macvlan, passthrough, vlan, or vxlan (note, vlan and vxlan only supported by ovs) 'id': id # depends on the type bridge: bridge name, zerotier: network id, macvlan: the parent link name, passthrough: the link name, vlan: the vlan tag, vxlan: the vxlan id 'name': name of the nic inside the container (ignored in zerotier type) 'hwaddr': Mac address of nic. 'config': { # config is only honored for bridge, vlan, and vxlan types 'dhcp': bool, 'cidr': static_ip # ip/mask 'gateway': gateway 'dns': [dns] } } :return:
[ "Hot", "plug", "a", "nic", "into", "a", "container" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1143-L1174
6,986
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
ContainerManager.nic_remove
def nic_remove(self, container, index): """ Hot unplug of nic from a container Note: removing a nic, doesn't remove the nic from the container info object, instead it sets it's state to `destroyed`. :param container: container ID :param index: index of the nic as returned in the container object info (as shown by container.list()) :return: """ args = { 'container': container, 'index': index } self._nic_remove.check(args) return self._client.json('corex.nic-remove', args)
python
def nic_remove(self, container, index): args = { 'container': container, 'index': index } self._nic_remove.check(args) return self._client.json('corex.nic-remove', args)
[ "def", "nic_remove", "(", "self", ",", "container", ",", "index", ")", ":", "args", "=", "{", "'container'", ":", "container", ",", "'index'", ":", "index", "}", "self", ".", "_nic_remove", ".", "check", "(", "args", ")", "return", "self", ".", "_clien...
Hot unplug of nic from a container Note: removing a nic, doesn't remove the nic from the container info object, instead it sets it's state to `destroyed`. :param container: container ID :param index: index of the nic as returned in the container object info (as shown by container.list()) :return:
[ "Hot", "unplug", "of", "nic", "from", "a", "container" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1176-L1193
6,987
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
ContainerManager.client
def client(self, container): """ Return a client instance that is bound to that container. :param container: container id :return: Client object bound to the specified container id Return a ContainerResponse from container.create """ self._client_chk.check(container) return ContainerClient(self._client, int(container))
python
def client(self, container): self._client_chk.check(container) return ContainerClient(self._client, int(container))
[ "def", "client", "(", "self", ",", "container", ")", ":", "self", ".", "_client_chk", ".", "check", "(", "container", ")", "return", "ContainerClient", "(", "self", ".", "_client", ",", "int", "(", "container", ")", ")" ]
Return a client instance that is bound to that container. :param container: container id :return: Client object bound to the specified container id Return a ContainerResponse from container.create
[ "Return", "a", "client", "instance", "that", "is", "bound", "to", "that", "container", "." ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1195-L1205
6,988
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
ContainerManager.backup
def backup(self, container, url): """ Backup a container to the given restic url all restic urls are supported :param container: :param url: Url to restic repo examples (file:///path/to/restic/?password=<password>) :return: Json response to the backup job (do .get() to get the snapshot ID """ args = { 'container': container, 'url': url, } return JSONResponse(self._client.raw('corex.backup', args))
python
def backup(self, container, url): args = { 'container': container, 'url': url, } return JSONResponse(self._client.raw('corex.backup', args))
[ "def", "backup", "(", "self", ",", "container", ",", "url", ")", ":", "args", "=", "{", "'container'", ":", "container", ",", "'url'", ":", "url", ",", "}", "return", "JSONResponse", "(", "self", ".", "_client", ".", "raw", "(", "'corex.backup'", ",", ...
Backup a container to the given restic url all restic urls are supported :param container: :param url: Url to restic repo examples (file:///path/to/restic/?password=<password>) :return: Json response to the backup job (do .get() to get the snapshot ID
[ "Backup", "a", "container", "to", "the", "given", "restic", "url", "all", "restic", "urls", "are", "supported" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1207-L1225
6,989
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
ContainerManager.restore
def restore(self, url, tags=None): """ Full restore of a container backup. This restore method will recreate an exact copy of the backedup container (including same network setup, and other configurations as defined by the `create` method. To just restore the container data, and use new configuration, use the create method instead with the `root_url` set to `restic:<url>` :param url: Snapshot url, the snapshot ID is passed as a url fragment examples: `file:///path/to/restic/repo?password=<password>#<snapshot-id>` :param tags: this will always override the original container tags (even if not set) :return: """ args = { 'url': url, } return JSONResponse(self._client.raw('corex.restore', args, tags=tags))
python
def restore(self, url, tags=None): args = { 'url': url, } return JSONResponse(self._client.raw('corex.restore', args, tags=tags))
[ "def", "restore", "(", "self", ",", "url", ",", "tags", "=", "None", ")", ":", "args", "=", "{", "'url'", ":", "url", ",", "}", "return", "JSONResponse", "(", "self", ".", "_client", ".", "raw", "(", "'corex.restore'", ",", "args", ",", "tags", "="...
Full restore of a container backup. This restore method will recreate an exact copy of the backedup container (including same network setup, and other configurations as defined by the `create` method. To just restore the container data, and use new configuration, use the create method instead with the `root_url` set to `restic:<url>` :param url: Snapshot url, the snapshot ID is passed as a url fragment examples: `file:///path/to/restic/repo?password=<password>#<snapshot-id>` :param tags: this will always override the original container tags (even if not set) :return:
[ "Full", "restore", "of", "a", "container", "backup", ".", "This", "restore", "method", "will", "recreate", "an", "exact", "copy", "of", "the", "backedup", "container", "(", "including", "same", "network", "setup", "and", "other", "configurations", "as", "defin...
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1227-L1246
6,990
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
BridgeManager.delete
def delete(self, bridge): """ Delete a bridge by name :param bridge: bridge name :return: """ args = { 'name': bridge, } self._bridge_chk.check(args) return self._client.json('bridge.delete', args)
python
def delete(self, bridge): args = { 'name': bridge, } self._bridge_chk.check(args) return self._client.json('bridge.delete', args)
[ "def", "delete", "(", "self", ",", "bridge", ")", ":", "args", "=", "{", "'name'", ":", "bridge", ",", "}", "self", ".", "_bridge_chk", ".", "check", "(", "args", ")", "return", "self", ".", "_client", ".", "json", "(", "'bridge.delete'", ",", "args"...
Delete a bridge by name :param bridge: bridge name :return:
[ "Delete", "a", "bridge", "by", "name" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1563-L1576
6,991
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
BridgeManager.nic_add
def nic_add(self, bridge, nic): """ Attach a nic to a bridge :param bridge: bridge name :param nic: nic name """ args = { 'name': bridge, 'nic': nic, } self._nic_add_chk.check(args) return self._client.json('bridge.nic-add', args)
python
def nic_add(self, bridge, nic): args = { 'name': bridge, 'nic': nic, } self._nic_add_chk.check(args) return self._client.json('bridge.nic-add', args)
[ "def", "nic_add", "(", "self", ",", "bridge", ",", "nic", ")", ":", "args", "=", "{", "'name'", ":", "bridge", ",", "'nic'", ":", "nic", ",", "}", "self", ".", "_nic_add_chk", ".", "check", "(", "args", ")", "return", "self", ".", "_client", ".", ...
Attach a nic to a bridge :param bridge: bridge name :param nic: nic name
[ "Attach", "a", "nic", "to", "a", "bridge" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1578-L1593
6,992
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
BridgeManager.nic_remove
def nic_remove(self, nic): """ Detach a nic from a bridge :param nic: nic name to detach """ args = { 'nic': nic, } self._nic_remove_chk.check(args) return self._client.json('bridge.nic-remove', args)
python
def nic_remove(self, nic): args = { 'nic': nic, } self._nic_remove_chk.check(args) return self._client.json('bridge.nic-remove', args)
[ "def", "nic_remove", "(", "self", ",", "nic", ")", ":", "args", "=", "{", "'nic'", ":", "nic", ",", "}", "self", ".", "_nic_remove_chk", ".", "check", "(", "args", ")", "return", "self", ".", "_client", ".", "json", "(", "'bridge.nic-remove'", ",", "...
Detach a nic from a bridge :param nic: nic name to detach
[ "Detach", "a", "nic", "from", "a", "bridge" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1595-L1608
6,993
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
BridgeManager.nic_list
def nic_list(self, bridge): """ List nics attached to bridge :param bridge: bridge name """ args = { 'name': bridge, } self._bridge_chk.check(args) return self._client.json('bridge.nic-list', args)
python
def nic_list(self, bridge): args = { 'name': bridge, } self._bridge_chk.check(args) return self._client.json('bridge.nic-list', args)
[ "def", "nic_list", "(", "self", ",", "bridge", ")", ":", "args", "=", "{", "'name'", ":", "bridge", ",", "}", "self", ".", "_bridge_chk", ".", "check", "(", "args", ")", "return", "self", ".", "_client", ".", "json", "(", "'bridge.nic-list'", ",", "a...
List nics attached to bridge :param bridge: bridge name
[ "List", "nics", "attached", "to", "bridge" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1610-L1623
6,994
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
DiskManager.list
def list(self): """ List available block devices """ response = self._client.raw('disk.list', {}) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to list disks: %s' % result.stderr) if result.level != 20: # 20 is JSON output. raise RuntimeError('invalid response type from disk.list command') data = result.data.strip() if data: return json.loads(data) else: return {}
python
def list(self): response = self._client.raw('disk.list', {}) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to list disks: %s' % result.stderr) if result.level != 20: # 20 is JSON output. raise RuntimeError('invalid response type from disk.list command') data = result.data.strip() if data: return json.loads(data) else: return {}
[ "def", "list", "(", "self", ")", ":", "response", "=", "self", ".", "_client", ".", "raw", "(", "'disk.list'", ",", "{", "}", ")", "result", "=", "response", ".", "get", "(", ")", "if", "result", ".", "state", "!=", "'SUCCESS'", ":", "raise", "Runt...
List available block devices
[ "List", "available", "block", "devices" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1670-L1688
6,995
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
DiskManager.getinfo
def getinfo(self, disk, part=''): """ Get more info about a disk or a disk partition :param disk: (/dev/sda, /dev/sdb, etc..) :param part: (/dev/sda1, /dev/sdb2, etc...) :return: a dict with {"blocksize", "start", "size", and "free" sections} """ args = { "disk": disk, "part": part, } self._getpart_chk.check(args) response = self._client.raw('disk.getinfo', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to get info: %s' % result.data) if result.level != 20: # 20 is JSON output. raise RuntimeError('invalid response type from disk.getinfo command') data = result.data.strip() if data: return json.loads(data) else: return {}
python
def getinfo(self, disk, part=''): args = { "disk": disk, "part": part, } self._getpart_chk.check(args) response = self._client.raw('disk.getinfo', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to get info: %s' % result.data) if result.level != 20: # 20 is JSON output. raise RuntimeError('invalid response type from disk.getinfo command') data = result.data.strip() if data: return json.loads(data) else: return {}
[ "def", "getinfo", "(", "self", ",", "disk", ",", "part", "=", "''", ")", ":", "args", "=", "{", "\"disk\"", ":", "disk", ",", "\"part\"", ":", "part", ",", "}", "self", ".", "_getpart_chk", ".", "check", "(", "args", ")", "response", "=", "self", ...
Get more info about a disk or a disk partition :param disk: (/dev/sda, /dev/sdb, etc..) :param part: (/dev/sda1, /dev/sdb2, etc...) :return: a dict with {"blocksize", "start", "size", and "free" sections}
[ "Get", "more", "info", "about", "a", "disk", "or", "a", "disk", "partition" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1710-L1739
6,996
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
DiskManager.seektime
def seektime(self, disk): """ Gives seek latency on disk which is a very good indication to the `type` of the disk. it's a very good way to verify if the underlying disk type is SSD or HDD :param disk: disk path or name (/dev/sda, or sda) :return: a dict as follows {'device': '<device-path>', 'elapsed': <seek-time in us', 'type': '<SSD or HDD>'} """ args = { 'disk': disk, } self._seektime_chk.check(args) return self._client.json("disk.seektime", args)
python
def seektime(self, disk): args = { 'disk': disk, } self._seektime_chk.check(args) return self._client.json("disk.seektime", args)
[ "def", "seektime", "(", "self", ",", "disk", ")", ":", "args", "=", "{", "'disk'", ":", "disk", ",", "}", "self", ".", "_seektime_chk", ".", "check", "(", "args", ")", "return", "self", ".", "_client", ".", "json", "(", "\"disk.seektime\"", ",", "arg...
Gives seek latency on disk which is a very good indication to the `type` of the disk. it's a very good way to verify if the underlying disk type is SSD or HDD :param disk: disk path or name (/dev/sda, or sda) :return: a dict as follows {'device': '<device-path>', 'elapsed': <seek-time in us', 'type': '<SSD or HDD>'}
[ "Gives", "seek", "latency", "on", "disk", "which", "is", "a", "very", "good", "indication", "to", "the", "type", "of", "the", "disk", ".", "it", "s", "a", "very", "good", "way", "to", "verify", "if", "the", "underlying", "disk", "type", "is", "SSD", ...
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1845-L1859
6,997
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
BtrfsManager.device_add
def device_add(self, mountpoint, *device): """ Add one or more devices to btrfs filesystem mounted under `mountpoint` :param mountpoint: mount point of the btrfs system :param devices: one ore more devices to add :return: """ if len(device) == 0: return args = { 'mountpoint': mountpoint, 'devices': device, } self._device_chk.check(args) self._client.sync('btrfs.device_add', args)
python
def device_add(self, mountpoint, *device): if len(device) == 0: return args = { 'mountpoint': mountpoint, 'devices': device, } self._device_chk.check(args) self._client.sync('btrfs.device_add', args)
[ "def", "device_add", "(", "self", ",", "mountpoint", ",", "*", "device", ")", ":", "if", "len", "(", "device", ")", "==", "0", ":", "return", "args", "=", "{", "'mountpoint'", ":", "mountpoint", ",", "'devices'", ":", "device", ",", "}", "self", ".",...
Add one or more devices to btrfs filesystem mounted under `mountpoint` :param mountpoint: mount point of the btrfs system :param devices: one ore more devices to add :return:
[ "Add", "one", "or", "more", "devices", "to", "btrfs", "filesystem", "mounted", "under", "mountpoint" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1927-L1945
6,998
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
BtrfsManager.subvol_snapshot
def subvol_snapshot(self, source, destination, read_only=False): """ Take a snapshot :param source: source path of subvol :param destination: destination path of snapshot :param read_only: Set read-only on the snapshot :return: """ args = { "source": source, "destination": destination, "read_only": read_only, } self._subvol_snapshot_chk.check(args) self._client.sync('btrfs.subvol_snapshot', args)
python
def subvol_snapshot(self, source, destination, read_only=False): args = { "source": source, "destination": destination, "read_only": read_only, } self._subvol_snapshot_chk.check(args) self._client.sync('btrfs.subvol_snapshot', args)
[ "def", "subvol_snapshot", "(", "self", ",", "source", ",", "destination", ",", "read_only", "=", "False", ")", ":", "args", "=", "{", "\"source\"", ":", "source", ",", "\"destination\"", ":", "destination", ",", "\"read_only\"", ":", "read_only", ",", "}", ...
Take a snapshot :param source: source path of subvol :param destination: destination path of snapshot :param read_only: Set read-only on the snapshot :return:
[ "Take", "a", "snapshot" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2015-L2032
6,999
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
ZerotierManager.join
def join(self, network): """ Join a zerotier network :param network: network id to join :return: """ args = {'network': network} self._network_chk.check(args) response = self._client.raw('zerotier.join', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to join zerotier network: %s', result.stderr)
python
def join(self, network): args = {'network': network} self._network_chk.check(args) response = self._client.raw('zerotier.join', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to join zerotier network: %s', result.stderr)
[ "def", "join", "(", "self", ",", "network", ")", ":", "args", "=", "{", "'network'", ":", "network", "}", "self", ".", "_network_chk", ".", "check", "(", "args", ")", "response", "=", "self", ".", "_client", ".", "raw", "(", "'zerotier.join'", ",", "...
Join a zerotier network :param network: network id to join :return:
[ "Join", "a", "zerotier", "network" ]
69f6ce845ab8b8ad805a79a415227e7ac566c218
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2043-L2056