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 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,200 | SALib/SALib | src/SALib/sample/ff.py | cli_action | def cli_action(args):
"""Run sampling method
Parameters
----------
args : argparse namespace
"""
problem = read_param_file(args.paramfile)
param_values = sample(problem, seed=args.seed)
np.savetxt(args.output, param_values, delimiter=args.delimiter,
fmt='%.' + str(args.precision) + 'e') | python | def cli_action(args):
"""Run sampling method
Parameters
----------
args : argparse namespace
"""
problem = read_param_file(args.paramfile)
param_values = sample(problem, seed=args.seed)
np.savetxt(args.output, param_values, delimiter=args.delimiter,
fmt='%.' + str(args.precision) + 'e') | [
"def",
"cli_action",
"(",
"args",
")",
":",
"problem",
"=",
"read_param_file",
"(",
"args",
".",
"paramfile",
")",
"param_values",
"=",
"sample",
"(",
"problem",
",",
"seed",
"=",
"args",
".",
"seed",
")",
"np",
".",
"savetxt",
"(",
"args",
".",
"output",
",",
"param_values",
",",
"delimiter",
"=",
"args",
".",
"delimiter",
",",
"fmt",
"=",
"'%.'",
"+",
"str",
"(",
"args",
".",
"precision",
")",
"+",
"'e'",
")"
] | Run sampling method
Parameters
----------
args : argparse namespace | [
"Run",
"sampling",
"method"
] | 9744d73bb17cfcffc8282c7dc4a727efdc4bea3f | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/ff.py#L135-L145 |
227,201 | SALib/SALib | src/SALib/sample/common_args.py | setup | def setup(parser):
"""Add common sampling options to CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object
"""
parser.add_argument(
'-p', '--paramfile', type=str, required=True,
help='Parameter Range File')
parser.add_argument(
'-o', '--output', type=str, required=True, help='Output File')
parser.add_argument(
'-s', '--seed', type=int, required=False, default=None,
help='Random Seed')
parser.add_argument(
'--delimiter', type=str, required=False, default=' ',
help='Column delimiter')
parser.add_argument('--precision', type=int, required=False,
default=8, help='Output floating-point precision')
return parser | python | def setup(parser):
"""Add common sampling options to CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object
"""
parser.add_argument(
'-p', '--paramfile', type=str, required=True,
help='Parameter Range File')
parser.add_argument(
'-o', '--output', type=str, required=True, help='Output File')
parser.add_argument(
'-s', '--seed', type=int, required=False, default=None,
help='Random Seed')
parser.add_argument(
'--delimiter', type=str, required=False, default=' ',
help='Column delimiter')
parser.add_argument('--precision', type=int, required=False,
default=8, help='Output floating-point precision')
return parser | [
"def",
"setup",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'-p'",
",",
"'--paramfile'",
",",
"type",
"=",
"str",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'Parameter Range File'",
")",
"parser",
".",
"add_argument",
"(",
"'-o'",
",",
"'--output'",
",",
"type",
"=",
"str",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'Output File'",
")",
"parser",
".",
"add_argument",
"(",
"'-s'",
",",
"'--seed'",
",",
"type",
"=",
"int",
",",
"required",
"=",
"False",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Random Seed'",
")",
"parser",
".",
"add_argument",
"(",
"'--delimiter'",
",",
"type",
"=",
"str",
",",
"required",
"=",
"False",
",",
"default",
"=",
"' '",
",",
"help",
"=",
"'Column delimiter'",
")",
"parser",
".",
"add_argument",
"(",
"'--precision'",
",",
"type",
"=",
"int",
",",
"required",
"=",
"False",
",",
"default",
"=",
"8",
",",
"help",
"=",
"'Output floating-point precision'",
")",
"return",
"parser"
] | Add common sampling options to CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object | [
"Add",
"common",
"sampling",
"options",
"to",
"CLI",
"parser",
"."
] | 9744d73bb17cfcffc8282c7dc4a727efdc4bea3f | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/common_args.py#L4-L29 |
227,202 | SALib/SALib | src/SALib/sample/common_args.py | run_cli | def run_cli(cli_parser, run_sample, known_args=None):
"""Run sampling with CLI arguments.
Parameters
----------
cli_parser : function
Function to add method specific arguments to parser
run_sample: function
Method specific function that runs the sampling
known_args: list [optional]
Additional arguments to parse
Returns
----------
argparse object
"""
parser = create(cli_parser)
args = parser.parse_args(known_args)
run_sample(args) | python | def run_cli(cli_parser, run_sample, known_args=None):
"""Run sampling with CLI arguments.
Parameters
----------
cli_parser : function
Function to add method specific arguments to parser
run_sample: function
Method specific function that runs the sampling
known_args: list [optional]
Additional arguments to parse
Returns
----------
argparse object
"""
parser = create(cli_parser)
args = parser.parse_args(known_args)
run_sample(args) | [
"def",
"run_cli",
"(",
"cli_parser",
",",
"run_sample",
",",
"known_args",
"=",
"None",
")",
":",
"parser",
"=",
"create",
"(",
"cli_parser",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"known_args",
")",
"run_sample",
"(",
"args",
")"
] | Run sampling with CLI arguments.
Parameters
----------
cli_parser : function
Function to add method specific arguments to parser
run_sample: function
Method specific function that runs the sampling
known_args: list [optional]
Additional arguments to parse
Returns
----------
argparse object | [
"Run",
"sampling",
"with",
"CLI",
"arguments",
"."
] | 9744d73bb17cfcffc8282c7dc4a727efdc4bea3f | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/common_args.py#L54-L73 |
227,203 | SALib/SALib | src/SALib/sample/morris/strategy.py | Strategy.run_checks | def run_checks(number_samples, k_choices):
"""Runs checks on `k_choices`
"""
assert isinstance(k_choices, int), \
"Number of optimal trajectories should be an integer"
if k_choices < 2:
raise ValueError(
"The number of optimal trajectories must be set to 2 or more.")
if k_choices >= number_samples:
msg = "The number of optimal trajectories should be less than the \
number of samples"
raise ValueError(msg) | python | def run_checks(number_samples, k_choices):
"""Runs checks on `k_choices`
"""
assert isinstance(k_choices, int), \
"Number of optimal trajectories should be an integer"
if k_choices < 2:
raise ValueError(
"The number of optimal trajectories must be set to 2 or more.")
if k_choices >= number_samples:
msg = "The number of optimal trajectories should be less than the \
number of samples"
raise ValueError(msg) | [
"def",
"run_checks",
"(",
"number_samples",
",",
"k_choices",
")",
":",
"assert",
"isinstance",
"(",
"k_choices",
",",
"int",
")",
",",
"\"Number of optimal trajectories should be an integer\"",
"if",
"k_choices",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"The number of optimal trajectories must be set to 2 or more.\"",
")",
"if",
"k_choices",
">=",
"number_samples",
":",
"msg",
"=",
"\"The number of optimal trajectories should be less than the \\\n number of samples\"",
"raise",
"ValueError",
"(",
"msg",
")"
] | Runs checks on `k_choices` | [
"Runs",
"checks",
"on",
"k_choices"
] | 9744d73bb17cfcffc8282c7dc4a727efdc4bea3f | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/strategy.py#L123-L135 |
227,204 | SALib/SALib | src/SALib/sample/morris/strategy.py | Strategy._make_index_list | def _make_index_list(num_samples, num_params, num_groups=None):
"""Identify indices of input sample associated with each trajectory
For each trajectory, identifies the indexes of the input sample which
is a function of the number of factors/groups and the number of samples
Arguments
---------
num_samples : int
The number of trajectories
num_params : int
The number of parameters
num_groups : int
The number of groups
Returns
-------
list of numpy.ndarray
Example
-------
>>> BruteForce()._make_index_list(num_samples=4, num_params=3,
num_groups=2)
[np.array([0, 1, 2]), np.array([3, 4, 5]), np.array([6, 7, 8]),
np.array([9, 10, 11])]
"""
if num_groups is None:
num_groups = num_params
index_list = []
for j in range(num_samples):
index_list.append(np.arange(num_groups + 1) + j * (num_groups + 1))
return index_list | python | def _make_index_list(num_samples, num_params, num_groups=None):
"""Identify indices of input sample associated with each trajectory
For each trajectory, identifies the indexes of the input sample which
is a function of the number of factors/groups and the number of samples
Arguments
---------
num_samples : int
The number of trajectories
num_params : int
The number of parameters
num_groups : int
The number of groups
Returns
-------
list of numpy.ndarray
Example
-------
>>> BruteForce()._make_index_list(num_samples=4, num_params=3,
num_groups=2)
[np.array([0, 1, 2]), np.array([3, 4, 5]), np.array([6, 7, 8]),
np.array([9, 10, 11])]
"""
if num_groups is None:
num_groups = num_params
index_list = []
for j in range(num_samples):
index_list.append(np.arange(num_groups + 1) + j * (num_groups + 1))
return index_list | [
"def",
"_make_index_list",
"(",
"num_samples",
",",
"num_params",
",",
"num_groups",
"=",
"None",
")",
":",
"if",
"num_groups",
"is",
"None",
":",
"num_groups",
"=",
"num_params",
"index_list",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"num_samples",
")",
":",
"index_list",
".",
"append",
"(",
"np",
".",
"arange",
"(",
"num_groups",
"+",
"1",
")",
"+",
"j",
"*",
"(",
"num_groups",
"+",
"1",
")",
")",
"return",
"index_list"
] | Identify indices of input sample associated with each trajectory
For each trajectory, identifies the indexes of the input sample which
is a function of the number of factors/groups and the number of samples
Arguments
---------
num_samples : int
The number of trajectories
num_params : int
The number of parameters
num_groups : int
The number of groups
Returns
-------
list of numpy.ndarray
Example
-------
>>> BruteForce()._make_index_list(num_samples=4, num_params=3,
num_groups=2)
[np.array([0, 1, 2]), np.array([3, 4, 5]), np.array([6, 7, 8]),
np.array([9, 10, 11])] | [
"Identify",
"indices",
"of",
"input",
"sample",
"associated",
"with",
"each",
"trajectory"
] | 9744d73bb17cfcffc8282c7dc4a727efdc4bea3f | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/strategy.py#L138-L170 |
227,205 | SALib/SALib | src/SALib/sample/morris/strategy.py | Strategy.compile_output | def compile_output(self, input_sample, num_samples, num_params,
maximum_combo, num_groups=None):
"""Picks the trajectories from the input
Arguments
---------
input_sample : numpy.ndarray
num_samples : int
num_params : int
maximum_combo : list
num_groups : int
"""
if num_groups is None:
num_groups = num_params
self.check_input_sample(input_sample, num_groups, num_samples)
index_list = self._make_index_list(num_samples, num_params, num_groups)
output = np.zeros(
(np.size(maximum_combo) * (num_groups + 1), num_params))
for counter, combo in enumerate(maximum_combo):
output[index_list[counter]] = np.array(
input_sample[index_list[combo]])
return output | python | def compile_output(self, input_sample, num_samples, num_params,
maximum_combo, num_groups=None):
"""Picks the trajectories from the input
Arguments
---------
input_sample : numpy.ndarray
num_samples : int
num_params : int
maximum_combo : list
num_groups : int
"""
if num_groups is None:
num_groups = num_params
self.check_input_sample(input_sample, num_groups, num_samples)
index_list = self._make_index_list(num_samples, num_params, num_groups)
output = np.zeros(
(np.size(maximum_combo) * (num_groups + 1), num_params))
for counter, combo in enumerate(maximum_combo):
output[index_list[counter]] = np.array(
input_sample[index_list[combo]])
return output | [
"def",
"compile_output",
"(",
"self",
",",
"input_sample",
",",
"num_samples",
",",
"num_params",
",",
"maximum_combo",
",",
"num_groups",
"=",
"None",
")",
":",
"if",
"num_groups",
"is",
"None",
":",
"num_groups",
"=",
"num_params",
"self",
".",
"check_input_sample",
"(",
"input_sample",
",",
"num_groups",
",",
"num_samples",
")",
"index_list",
"=",
"self",
".",
"_make_index_list",
"(",
"num_samples",
",",
"num_params",
",",
"num_groups",
")",
"output",
"=",
"np",
".",
"zeros",
"(",
"(",
"np",
".",
"size",
"(",
"maximum_combo",
")",
"*",
"(",
"num_groups",
"+",
"1",
")",
",",
"num_params",
")",
")",
"for",
"counter",
",",
"combo",
"in",
"enumerate",
"(",
"maximum_combo",
")",
":",
"output",
"[",
"index_list",
"[",
"counter",
"]",
"]",
"=",
"np",
".",
"array",
"(",
"input_sample",
"[",
"index_list",
"[",
"combo",
"]",
"]",
")",
"return",
"output"
] | Picks the trajectories from the input
Arguments
---------
input_sample : numpy.ndarray
num_samples : int
num_params : int
maximum_combo : list
num_groups : int | [
"Picks",
"the",
"trajectories",
"from",
"the",
"input"
] | 9744d73bb17cfcffc8282c7dc4a727efdc4bea3f | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/strategy.py#L172-L198 |
227,206 | SALib/SALib | src/SALib/sample/morris/strategy.py | Strategy.check_input_sample | def check_input_sample(input_sample, num_params, num_samples):
"""Check the `input_sample` is valid
Checks input sample is:
- the correct size
- values between 0 and 1
Arguments
---------
input_sample : numpy.ndarray
num_params : int
num_samples : int
"""
assert type(input_sample) == np.ndarray, \
"Input sample is not an numpy array"
assert input_sample.shape[0] == (num_params + 1) * num_samples, \
"Input sample does not match number of parameters or groups"
assert np.any((input_sample >= 0) | (input_sample <= 1)), \
"Input sample must be scaled between 0 and 1" | python | def check_input_sample(input_sample, num_params, num_samples):
"""Check the `input_sample` is valid
Checks input sample is:
- the correct size
- values between 0 and 1
Arguments
---------
input_sample : numpy.ndarray
num_params : int
num_samples : int
"""
assert type(input_sample) == np.ndarray, \
"Input sample is not an numpy array"
assert input_sample.shape[0] == (num_params + 1) * num_samples, \
"Input sample does not match number of parameters or groups"
assert np.any((input_sample >= 0) | (input_sample <= 1)), \
"Input sample must be scaled between 0 and 1" | [
"def",
"check_input_sample",
"(",
"input_sample",
",",
"num_params",
",",
"num_samples",
")",
":",
"assert",
"type",
"(",
"input_sample",
")",
"==",
"np",
".",
"ndarray",
",",
"\"Input sample is not an numpy array\"",
"assert",
"input_sample",
".",
"shape",
"[",
"0",
"]",
"==",
"(",
"num_params",
"+",
"1",
")",
"*",
"num_samples",
",",
"\"Input sample does not match number of parameters or groups\"",
"assert",
"np",
".",
"any",
"(",
"(",
"input_sample",
">=",
"0",
")",
"|",
"(",
"input_sample",
"<=",
"1",
")",
")",
",",
"\"Input sample must be scaled between 0 and 1\""
] | Check the `input_sample` is valid
Checks input sample is:
- the correct size
- values between 0 and 1
Arguments
---------
input_sample : numpy.ndarray
num_params : int
num_samples : int | [
"Check",
"the",
"input_sample",
"is",
"valid"
] | 9744d73bb17cfcffc8282c7dc4a727efdc4bea3f | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/strategy.py#L201-L219 |
227,207 | SALib/SALib | src/SALib/sample/morris/strategy.py | Strategy.compute_distance | def compute_distance(m, l):
'''Compute distance between two trajectories
Returns
-------
numpy.ndarray
'''
if np.shape(m) != np.shape(l):
raise ValueError("Input matrices are different sizes")
if np.array_equal(m, l):
# print("Trajectory %s and %s are equal" % (m, l))
distance = 0
else:
distance = np.array(np.sum(cdist(m, l)), dtype=np.float32)
return distance | python | def compute_distance(m, l):
'''Compute distance between two trajectories
Returns
-------
numpy.ndarray
'''
if np.shape(m) != np.shape(l):
raise ValueError("Input matrices are different sizes")
if np.array_equal(m, l):
# print("Trajectory %s and %s are equal" % (m, l))
distance = 0
else:
distance = np.array(np.sum(cdist(m, l)), dtype=np.float32)
return distance | [
"def",
"compute_distance",
"(",
"m",
",",
"l",
")",
":",
"if",
"np",
".",
"shape",
"(",
"m",
")",
"!=",
"np",
".",
"shape",
"(",
"l",
")",
":",
"raise",
"ValueError",
"(",
"\"Input matrices are different sizes\"",
")",
"if",
"np",
".",
"array_equal",
"(",
"m",
",",
"l",
")",
":",
"# print(\"Trajectory %s and %s are equal\" % (m, l))",
"distance",
"=",
"0",
"else",
":",
"distance",
"=",
"np",
".",
"array",
"(",
"np",
".",
"sum",
"(",
"cdist",
"(",
"m",
",",
"l",
")",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"return",
"distance"
] | Compute distance between two trajectories
Returns
-------
numpy.ndarray | [
"Compute",
"distance",
"between",
"two",
"trajectories"
] | 9744d73bb17cfcffc8282c7dc4a727efdc4bea3f | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/strategy.py#L222-L238 |
227,208 | SALib/SALib | src/SALib/sample/morris/strategy.py | Strategy.compute_distance_matrix | def compute_distance_matrix(self, input_sample, num_samples, num_params,
num_groups=None,
local_optimization=False):
"""Computes the distance between each and every trajectory
Each entry in the matrix represents the sum of the geometric distances
between all the pairs of points of the two trajectories
If the `groups` argument is filled, then the distances are still
calculated for each trajectory,
Arguments
---------
input_sample : numpy.ndarray
The input sample of trajectories for which to compute
the distance matrix
num_samples : int
The number of trajectories
num_params : int
The number of factors
num_groups : int, default=None
The number of groups
local_optimization : bool, default=False
If True, fills the lower triangle of the distance matrix
Returns
-------
distance_matrix : numpy.ndarray
"""
if num_groups:
self.check_input_sample(input_sample, num_groups, num_samples)
else:
self.check_input_sample(input_sample, num_params, num_samples)
index_list = self._make_index_list(num_samples, num_params, num_groups)
distance_matrix = np.zeros(
(num_samples, num_samples), dtype=np.float32)
for j in range(num_samples):
input_1 = input_sample[index_list[j]]
for k in range(j + 1, num_samples):
input_2 = input_sample[index_list[k]]
# Fills the lower triangle of the matrix
if local_optimization is True:
distance_matrix[j, k] = self.compute_distance(
input_1, input_2)
distance_matrix[k, j] = self.compute_distance(input_1, input_2)
return distance_matrix | python | def compute_distance_matrix(self, input_sample, num_samples, num_params,
num_groups=None,
local_optimization=False):
"""Computes the distance between each and every trajectory
Each entry in the matrix represents the sum of the geometric distances
between all the pairs of points of the two trajectories
If the `groups` argument is filled, then the distances are still
calculated for each trajectory,
Arguments
---------
input_sample : numpy.ndarray
The input sample of trajectories for which to compute
the distance matrix
num_samples : int
The number of trajectories
num_params : int
The number of factors
num_groups : int, default=None
The number of groups
local_optimization : bool, default=False
If True, fills the lower triangle of the distance matrix
Returns
-------
distance_matrix : numpy.ndarray
"""
if num_groups:
self.check_input_sample(input_sample, num_groups, num_samples)
else:
self.check_input_sample(input_sample, num_params, num_samples)
index_list = self._make_index_list(num_samples, num_params, num_groups)
distance_matrix = np.zeros(
(num_samples, num_samples), dtype=np.float32)
for j in range(num_samples):
input_1 = input_sample[index_list[j]]
for k in range(j + 1, num_samples):
input_2 = input_sample[index_list[k]]
# Fills the lower triangle of the matrix
if local_optimization is True:
distance_matrix[j, k] = self.compute_distance(
input_1, input_2)
distance_matrix[k, j] = self.compute_distance(input_1, input_2)
return distance_matrix | [
"def",
"compute_distance_matrix",
"(",
"self",
",",
"input_sample",
",",
"num_samples",
",",
"num_params",
",",
"num_groups",
"=",
"None",
",",
"local_optimization",
"=",
"False",
")",
":",
"if",
"num_groups",
":",
"self",
".",
"check_input_sample",
"(",
"input_sample",
",",
"num_groups",
",",
"num_samples",
")",
"else",
":",
"self",
".",
"check_input_sample",
"(",
"input_sample",
",",
"num_params",
",",
"num_samples",
")",
"index_list",
"=",
"self",
".",
"_make_index_list",
"(",
"num_samples",
",",
"num_params",
",",
"num_groups",
")",
"distance_matrix",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_samples",
",",
"num_samples",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"for",
"j",
"in",
"range",
"(",
"num_samples",
")",
":",
"input_1",
"=",
"input_sample",
"[",
"index_list",
"[",
"j",
"]",
"]",
"for",
"k",
"in",
"range",
"(",
"j",
"+",
"1",
",",
"num_samples",
")",
":",
"input_2",
"=",
"input_sample",
"[",
"index_list",
"[",
"k",
"]",
"]",
"# Fills the lower triangle of the matrix",
"if",
"local_optimization",
"is",
"True",
":",
"distance_matrix",
"[",
"j",
",",
"k",
"]",
"=",
"self",
".",
"compute_distance",
"(",
"input_1",
",",
"input_2",
")",
"distance_matrix",
"[",
"k",
",",
"j",
"]",
"=",
"self",
".",
"compute_distance",
"(",
"input_1",
",",
"input_2",
")",
"return",
"distance_matrix"
] | Computes the distance between each and every trajectory
Each entry in the matrix represents the sum of the geometric distances
between all the pairs of points of the two trajectories
If the `groups` argument is filled, then the distances are still
calculated for each trajectory,
Arguments
---------
input_sample : numpy.ndarray
The input sample of trajectories for which to compute
the distance matrix
num_samples : int
The number of trajectories
num_params : int
The number of factors
num_groups : int, default=None
The number of groups
local_optimization : bool, default=False
If True, fills the lower triangle of the distance matrix
Returns
-------
distance_matrix : numpy.ndarray | [
"Computes",
"the",
"distance",
"between",
"each",
"and",
"every",
"trajectory"
] | 9744d73bb17cfcffc8282c7dc4a727efdc4bea3f | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/strategy.py#L240-L290 |
227,209 | nicodv/kmodes | kmodes/kmodes.py | move_point_cat | def move_point_cat(point, ipoint, to_clust, from_clust, cl_attr_freq,
membship, centroids):
"""Move point between clusters, categorical attributes."""
membship[to_clust, ipoint] = 1
membship[from_clust, ipoint] = 0
# Update frequencies of attributes in cluster.
for iattr, curattr in enumerate(point):
to_attr_counts = cl_attr_freq[to_clust][iattr]
from_attr_counts = cl_attr_freq[from_clust][iattr]
# Increment the attribute count for the new "to" cluster
to_attr_counts[curattr] += 1
current_attribute_value_freq = to_attr_counts[curattr]
current_centroid_value = centroids[to_clust][iattr]
current_centroid_freq = to_attr_counts[current_centroid_value]
if current_centroid_freq < current_attribute_value_freq:
# We have incremented this value to the new mode. Update the centroid.
centroids[to_clust][iattr] = curattr
# Decrement the attribute count for the old "from" cluster
from_attr_counts[curattr] -= 1
old_centroid_value = centroids[from_clust][iattr]
if old_centroid_value == curattr:
# We have just removed a count from the old centroid value. We need to
# recalculate the centroid as it may no longer be the maximum
centroids[from_clust][iattr] = get_max_value_key(from_attr_counts)
return cl_attr_freq, membship, centroids | python | def move_point_cat(point, ipoint, to_clust, from_clust, cl_attr_freq,
membship, centroids):
"""Move point between clusters, categorical attributes."""
membship[to_clust, ipoint] = 1
membship[from_clust, ipoint] = 0
# Update frequencies of attributes in cluster.
for iattr, curattr in enumerate(point):
to_attr_counts = cl_attr_freq[to_clust][iattr]
from_attr_counts = cl_attr_freq[from_clust][iattr]
# Increment the attribute count for the new "to" cluster
to_attr_counts[curattr] += 1
current_attribute_value_freq = to_attr_counts[curattr]
current_centroid_value = centroids[to_clust][iattr]
current_centroid_freq = to_attr_counts[current_centroid_value]
if current_centroid_freq < current_attribute_value_freq:
# We have incremented this value to the new mode. Update the centroid.
centroids[to_clust][iattr] = curattr
# Decrement the attribute count for the old "from" cluster
from_attr_counts[curattr] -= 1
old_centroid_value = centroids[from_clust][iattr]
if old_centroid_value == curattr:
# We have just removed a count from the old centroid value. We need to
# recalculate the centroid as it may no longer be the maximum
centroids[from_clust][iattr] = get_max_value_key(from_attr_counts)
return cl_attr_freq, membship, centroids | [
"def",
"move_point_cat",
"(",
"point",
",",
"ipoint",
",",
"to_clust",
",",
"from_clust",
",",
"cl_attr_freq",
",",
"membship",
",",
"centroids",
")",
":",
"membship",
"[",
"to_clust",
",",
"ipoint",
"]",
"=",
"1",
"membship",
"[",
"from_clust",
",",
"ipoint",
"]",
"=",
"0",
"# Update frequencies of attributes in cluster.",
"for",
"iattr",
",",
"curattr",
"in",
"enumerate",
"(",
"point",
")",
":",
"to_attr_counts",
"=",
"cl_attr_freq",
"[",
"to_clust",
"]",
"[",
"iattr",
"]",
"from_attr_counts",
"=",
"cl_attr_freq",
"[",
"from_clust",
"]",
"[",
"iattr",
"]",
"# Increment the attribute count for the new \"to\" cluster",
"to_attr_counts",
"[",
"curattr",
"]",
"+=",
"1",
"current_attribute_value_freq",
"=",
"to_attr_counts",
"[",
"curattr",
"]",
"current_centroid_value",
"=",
"centroids",
"[",
"to_clust",
"]",
"[",
"iattr",
"]",
"current_centroid_freq",
"=",
"to_attr_counts",
"[",
"current_centroid_value",
"]",
"if",
"current_centroid_freq",
"<",
"current_attribute_value_freq",
":",
"# We have incremented this value to the new mode. Update the centroid.",
"centroids",
"[",
"to_clust",
"]",
"[",
"iattr",
"]",
"=",
"curattr",
"# Decrement the attribute count for the old \"from\" cluster",
"from_attr_counts",
"[",
"curattr",
"]",
"-=",
"1",
"old_centroid_value",
"=",
"centroids",
"[",
"from_clust",
"]",
"[",
"iattr",
"]",
"if",
"old_centroid_value",
"==",
"curattr",
":",
"# We have just removed a count from the old centroid value. We need to",
"# recalculate the centroid as it may no longer be the maximum",
"centroids",
"[",
"from_clust",
"]",
"[",
"iattr",
"]",
"=",
"get_max_value_key",
"(",
"from_attr_counts",
")",
"return",
"cl_attr_freq",
",",
"membship",
",",
"centroids"
] | Move point between clusters, categorical attributes. | [
"Move",
"point",
"between",
"clusters",
"categorical",
"attributes",
"."
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L83-L112 |
227,210 | nicodv/kmodes | kmodes/kmodes.py | _labels_cost | def _labels_cost(X, centroids, dissim, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-modes algorithm.
"""
X = check_array(X)
n_points = X.shape[0]
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint, curpoint in enumerate(X):
diss = dissim(centroids, curpoint, X=X, membship=membship)
clust = np.argmin(diss)
labels[ipoint] = clust
cost += diss[clust]
return labels, cost | python | def _labels_cost(X, centroids, dissim, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-modes algorithm.
"""
X = check_array(X)
n_points = X.shape[0]
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint, curpoint in enumerate(X):
diss = dissim(centroids, curpoint, X=X, membship=membship)
clust = np.argmin(diss)
labels[ipoint] = clust
cost += diss[clust]
return labels, cost | [
"def",
"_labels_cost",
"(",
"X",
",",
"centroids",
",",
"dissim",
",",
"membship",
"=",
"None",
")",
":",
"X",
"=",
"check_array",
"(",
"X",
")",
"n_points",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"cost",
"=",
"0.",
"labels",
"=",
"np",
".",
"empty",
"(",
"n_points",
",",
"dtype",
"=",
"np",
".",
"uint16",
")",
"for",
"ipoint",
",",
"curpoint",
"in",
"enumerate",
"(",
"X",
")",
":",
"diss",
"=",
"dissim",
"(",
"centroids",
",",
"curpoint",
",",
"X",
"=",
"X",
",",
"membship",
"=",
"membship",
")",
"clust",
"=",
"np",
".",
"argmin",
"(",
"diss",
")",
"labels",
"[",
"ipoint",
"]",
"=",
"clust",
"cost",
"+=",
"diss",
"[",
"clust",
"]",
"return",
"labels",
",",
"cost"
] | Calculate labels and cost function given a matrix of points and
a list of centroids for the k-modes algorithm. | [
"Calculate",
"labels",
"and",
"cost",
"function",
"given",
"a",
"matrix",
"of",
"points",
"and",
"a",
"list",
"of",
"centroids",
"for",
"the",
"k",
"-",
"modes",
"algorithm",
"."
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L115-L131 |
227,211 | nicodv/kmodes | kmodes/kmodes.py | _k_modes_iter | def _k_modes_iter(X, centroids, cl_attr_freq, membship, dissim, random_state):
"""Single iteration of k-modes clustering algorithm"""
moves = 0
for ipoint, curpoint in enumerate(X):
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
cl_attr_freq, membship, centroids = move_point_cat(
curpoint, ipoint, clust, old_clust, cl_attr_freq, membship, centroids
)
# In case of an empty cluster, reinitialize with a random point
# from the largest cluster.
if not membship[old_clust, :].any():
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_freq, membship, centroids = move_point_cat(
X[rindx], rindx, old_clust, from_clust, cl_attr_freq, membship, centroids
)
return centroids, moves | python | def _k_modes_iter(X, centroids, cl_attr_freq, membship, dissim, random_state):
"""Single iteration of k-modes clustering algorithm"""
moves = 0
for ipoint, curpoint in enumerate(X):
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
cl_attr_freq, membship, centroids = move_point_cat(
curpoint, ipoint, clust, old_clust, cl_attr_freq, membship, centroids
)
# In case of an empty cluster, reinitialize with a random point
# from the largest cluster.
if not membship[old_clust, :].any():
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_freq, membship, centroids = move_point_cat(
X[rindx], rindx, old_clust, from_clust, cl_attr_freq, membship, centroids
)
return centroids, moves | [
"def",
"_k_modes_iter",
"(",
"X",
",",
"centroids",
",",
"cl_attr_freq",
",",
"membship",
",",
"dissim",
",",
"random_state",
")",
":",
"moves",
"=",
"0",
"for",
"ipoint",
",",
"curpoint",
"in",
"enumerate",
"(",
"X",
")",
":",
"clust",
"=",
"np",
".",
"argmin",
"(",
"dissim",
"(",
"centroids",
",",
"curpoint",
",",
"X",
"=",
"X",
",",
"membship",
"=",
"membship",
")",
")",
"if",
"membship",
"[",
"clust",
",",
"ipoint",
"]",
":",
"# Point is already in its right place.",
"continue",
"# Move point, and update old/new cluster frequencies and centroids.",
"moves",
"+=",
"1",
"old_clust",
"=",
"np",
".",
"argwhere",
"(",
"membship",
"[",
":",
",",
"ipoint",
"]",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"cl_attr_freq",
",",
"membship",
",",
"centroids",
"=",
"move_point_cat",
"(",
"curpoint",
",",
"ipoint",
",",
"clust",
",",
"old_clust",
",",
"cl_attr_freq",
",",
"membship",
",",
"centroids",
")",
"# In case of an empty cluster, reinitialize with a random point",
"# from the largest cluster.",
"if",
"not",
"membship",
"[",
"old_clust",
",",
":",
"]",
".",
"any",
"(",
")",
":",
"from_clust",
"=",
"membship",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
".",
"argmax",
"(",
")",
"choices",
"=",
"[",
"ii",
"for",
"ii",
",",
"ch",
"in",
"enumerate",
"(",
"membship",
"[",
"from_clust",
",",
":",
"]",
")",
"if",
"ch",
"]",
"rindx",
"=",
"random_state",
".",
"choice",
"(",
"choices",
")",
"cl_attr_freq",
",",
"membship",
",",
"centroids",
"=",
"move_point_cat",
"(",
"X",
"[",
"rindx",
"]",
",",
"rindx",
",",
"old_clust",
",",
"from_clust",
",",
"cl_attr_freq",
",",
"membship",
",",
"centroids",
")",
"return",
"centroids",
",",
"moves"
] | Single iteration of k-modes clustering algorithm | [
"Single",
"iteration",
"of",
"k",
"-",
"modes",
"clustering",
"algorithm"
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L134-L162 |
227,212 | nicodv/kmodes | kmodes/kmodes.py | k_modes | def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs):
"""k-modes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-modes does not support sparse data.")
X = check_array(X, dtype=None)
# Convert the categorical values in X to integers for speed.
# Based on the unique values in X, we can make a mapping to achieve this.
X, enc_map = encode_features(X)
n_points, n_attrs = X.shape
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = unique
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_modes_single(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_modes_single)(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best] | python | def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs):
"""k-modes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-modes does not support sparse data.")
X = check_array(X, dtype=None)
# Convert the categorical values in X to integers for speed.
# Based on the unique values in X, we can make a mapping to achieve this.
X, enc_map = encode_features(X)
n_points, n_attrs = X.shape
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = unique
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_modes_single(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_modes_single)(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best] | [
"def",
"k_modes",
"(",
"X",
",",
"n_clusters",
",",
"max_iter",
",",
"dissim",
",",
"init",
",",
"n_init",
",",
"verbose",
",",
"random_state",
",",
"n_jobs",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"if",
"sparse",
".",
"issparse",
"(",
"X",
")",
":",
"raise",
"TypeError",
"(",
"\"k-modes does not support sparse data.\"",
")",
"X",
"=",
"check_array",
"(",
"X",
",",
"dtype",
"=",
"None",
")",
"# Convert the categorical values in X to integers for speed.",
"# Based on the unique values in X, we can make a mapping to achieve this.",
"X",
",",
"enc_map",
"=",
"encode_features",
"(",
"X",
")",
"n_points",
",",
"n_attrs",
"=",
"X",
".",
"shape",
"assert",
"n_clusters",
"<=",
"n_points",
",",
"\"Cannot have more clusters ({}) \"",
"\"than data points ({}).\"",
".",
"format",
"(",
"n_clusters",
",",
"n_points",
")",
"# Are there more n_clusters than unique rows? Then set the unique",
"# rows as initial values and skip iteration.",
"unique",
"=",
"get_unique_rows",
"(",
"X",
")",
"n_unique",
"=",
"unique",
".",
"shape",
"[",
"0",
"]",
"if",
"n_unique",
"<=",
"n_clusters",
":",
"max_iter",
"=",
"0",
"n_init",
"=",
"1",
"n_clusters",
"=",
"n_unique",
"init",
"=",
"unique",
"results",
"=",
"[",
"]",
"seeds",
"=",
"random_state",
".",
"randint",
"(",
"np",
".",
"iinfo",
"(",
"np",
".",
"int32",
")",
".",
"max",
",",
"size",
"=",
"n_init",
")",
"if",
"n_jobs",
"==",
"1",
":",
"for",
"init_no",
"in",
"range",
"(",
"n_init",
")",
":",
"results",
".",
"append",
"(",
"k_modes_single",
"(",
"X",
",",
"n_clusters",
",",
"n_points",
",",
"n_attrs",
",",
"max_iter",
",",
"dissim",
",",
"init",
",",
"init_no",
",",
"verbose",
",",
"seeds",
"[",
"init_no",
"]",
")",
")",
"else",
":",
"results",
"=",
"Parallel",
"(",
"n_jobs",
"=",
"n_jobs",
",",
"verbose",
"=",
"0",
")",
"(",
"delayed",
"(",
"k_modes_single",
")",
"(",
"X",
",",
"n_clusters",
",",
"n_points",
",",
"n_attrs",
",",
"max_iter",
",",
"dissim",
",",
"init",
",",
"init_no",
",",
"verbose",
",",
"seed",
")",
"for",
"init_no",
",",
"seed",
"in",
"enumerate",
"(",
"seeds",
")",
")",
"all_centroids",
",",
"all_labels",
",",
"all_costs",
",",
"all_n_iters",
"=",
"zip",
"(",
"*",
"results",
")",
"best",
"=",
"np",
".",
"argmin",
"(",
"all_costs",
")",
"if",
"n_init",
">",
"1",
"and",
"verbose",
":",
"print",
"(",
"\"Best run was number {}\"",
".",
"format",
"(",
"best",
"+",
"1",
")",
")",
"return",
"all_centroids",
"[",
"best",
"]",
",",
"enc_map",
",",
"all_labels",
"[",
"best",
"]",
",",
"all_costs",
"[",
"best",
"]",
",",
"all_n_iters",
"[",
"best",
"]"
] | k-modes algorithm | [
"k",
"-",
"modes",
"algorithm"
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L243-L287 |
227,213 | nicodv/kmodes | kmodes/kmodes.py | KModes.fit | def fit(self, X, y=None, **kwargs):
"""Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
"""
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self | python | def fit(self, X, y=None, **kwargs):
"""Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
"""
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"X",
"=",
"pandas_to_numpy",
"(",
"X",
")",
"random_state",
"=",
"check_random_state",
"(",
"self",
".",
"random_state",
")",
"self",
".",
"_enc_cluster_centroids",
",",
"self",
".",
"_enc_map",
",",
"self",
".",
"labels_",
",",
"self",
".",
"cost_",
",",
"self",
".",
"n_iter_",
"=",
"k_modes",
"(",
"X",
",",
"self",
".",
"n_clusters",
",",
"self",
".",
"max_iter",
",",
"self",
".",
"cat_dissim",
",",
"self",
".",
"init",
",",
"self",
".",
"n_init",
",",
"self",
".",
"verbose",
",",
"random_state",
",",
"self",
".",
"n_jobs",
")",
"return",
"self"
] | Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features] | [
"Compute",
"k",
"-",
"modes",
"clustering",
"."
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L381-L401 |
227,214 | nicodv/kmodes | kmodes/kmodes.py | KModes.fit_predict | def fit_predict(self, X, y=None, **kwargs):
"""Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
"""
return self.fit(X, **kwargs).predict(X, **kwargs) | python | def fit_predict(self, X, y=None, **kwargs):
"""Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
"""
return self.fit(X, **kwargs).predict(X, **kwargs) | [
"def",
"fit_predict",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"fit",
"(",
"X",
",",
"*",
"*",
"kwargs",
")",
".",
"predict",
"(",
"X",
",",
"*",
"*",
"kwargs",
")"
] | Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X). | [
"Compute",
"cluster",
"centroids",
"and",
"predict",
"cluster",
"index",
"for",
"each",
"sample",
"."
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L403-L409 |
227,215 | nicodv/kmodes | kmodes/util/__init__.py | get_max_value_key | def get_max_value_key(dic):
"""Gets the key for the maximum value in a dict."""
v = np.array(list(dic.values()))
k = np.array(list(dic.keys()))
maxima = np.where(v == np.max(v))[0]
if len(maxima) == 1:
return k[maxima[0]]
else:
# In order to be consistent, always selects the minimum key
# (guaranteed to be unique) when there are multiple maximum values.
return k[maxima[np.argmin(k[maxima])]] | python | def get_max_value_key(dic):
"""Gets the key for the maximum value in a dict."""
v = np.array(list(dic.values()))
k = np.array(list(dic.keys()))
maxima = np.where(v == np.max(v))[0]
if len(maxima) == 1:
return k[maxima[0]]
else:
# In order to be consistent, always selects the minimum key
# (guaranteed to be unique) when there are multiple maximum values.
return k[maxima[np.argmin(k[maxima])]] | [
"def",
"get_max_value_key",
"(",
"dic",
")",
":",
"v",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"dic",
".",
"values",
"(",
")",
")",
")",
"k",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"dic",
".",
"keys",
"(",
")",
")",
")",
"maxima",
"=",
"np",
".",
"where",
"(",
"v",
"==",
"np",
".",
"max",
"(",
"v",
")",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"maxima",
")",
"==",
"1",
":",
"return",
"k",
"[",
"maxima",
"[",
"0",
"]",
"]",
"else",
":",
"# In order to be consistent, always selects the minimum key",
"# (guaranteed to be unique) when there are multiple maximum values.",
"return",
"k",
"[",
"maxima",
"[",
"np",
".",
"argmin",
"(",
"k",
"[",
"maxima",
"]",
")",
"]",
"]"
] | Gets the key for the maximum value in a dict. | [
"Gets",
"the",
"key",
"for",
"the",
"maximum",
"value",
"in",
"a",
"dict",
"."
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/util/__init__.py#L12-L23 |
227,216 | nicodv/kmodes | kmodes/util/__init__.py | decode_centroids | def decode_centroids(encoded, mapping):
"""Decodes the encoded centroids array back to the original data
labels using a list of mappings.
"""
decoded = []
for ii in range(encoded.shape[1]):
# Invert the mapping so that we can decode.
inv_mapping = {v: k for k, v in mapping[ii].items()}
decoded.append(np.vectorize(inv_mapping.__getitem__)(encoded[:, ii]))
return np.atleast_2d(np.array(decoded)).T | python | def decode_centroids(encoded, mapping):
"""Decodes the encoded centroids array back to the original data
labels using a list of mappings.
"""
decoded = []
for ii in range(encoded.shape[1]):
# Invert the mapping so that we can decode.
inv_mapping = {v: k for k, v in mapping[ii].items()}
decoded.append(np.vectorize(inv_mapping.__getitem__)(encoded[:, ii]))
return np.atleast_2d(np.array(decoded)).T | [
"def",
"decode_centroids",
"(",
"encoded",
",",
"mapping",
")",
":",
"decoded",
"=",
"[",
"]",
"for",
"ii",
"in",
"range",
"(",
"encoded",
".",
"shape",
"[",
"1",
"]",
")",
":",
"# Invert the mapping so that we can decode.",
"inv_mapping",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"mapping",
"[",
"ii",
"]",
".",
"items",
"(",
")",
"}",
"decoded",
".",
"append",
"(",
"np",
".",
"vectorize",
"(",
"inv_mapping",
".",
"__getitem__",
")",
"(",
"encoded",
"[",
":",
",",
"ii",
"]",
")",
")",
"return",
"np",
".",
"atleast_2d",
"(",
"np",
".",
"array",
"(",
"decoded",
")",
")",
".",
"T"
] | Decodes the encoded centroids array back to the original data
labels using a list of mappings. | [
"Decodes",
"the",
"encoded",
"centroids",
"array",
"back",
"to",
"the",
"original",
"data",
"labels",
"using",
"a",
"list",
"of",
"mappings",
"."
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/util/__init__.py#L54-L63 |
227,217 | nicodv/kmodes | kmodes/kprototypes.py | move_point_num | def move_point_num(point, to_clust, from_clust, cl_attr_sum, cl_memb_sum):
"""Move point between clusters, numerical attributes."""
# Update sum of attributes in cluster.
for iattr, curattr in enumerate(point):
cl_attr_sum[to_clust][iattr] += curattr
cl_attr_sum[from_clust][iattr] -= curattr
# Update sums of memberships in cluster
cl_memb_sum[to_clust] += 1
cl_memb_sum[from_clust] -= 1
return cl_attr_sum, cl_memb_sum | python | def move_point_num(point, to_clust, from_clust, cl_attr_sum, cl_memb_sum):
"""Move point between clusters, numerical attributes."""
# Update sum of attributes in cluster.
for iattr, curattr in enumerate(point):
cl_attr_sum[to_clust][iattr] += curattr
cl_attr_sum[from_clust][iattr] -= curattr
# Update sums of memberships in cluster
cl_memb_sum[to_clust] += 1
cl_memb_sum[from_clust] -= 1
return cl_attr_sum, cl_memb_sum | [
"def",
"move_point_num",
"(",
"point",
",",
"to_clust",
",",
"from_clust",
",",
"cl_attr_sum",
",",
"cl_memb_sum",
")",
":",
"# Update sum of attributes in cluster.",
"for",
"iattr",
",",
"curattr",
"in",
"enumerate",
"(",
"point",
")",
":",
"cl_attr_sum",
"[",
"to_clust",
"]",
"[",
"iattr",
"]",
"+=",
"curattr",
"cl_attr_sum",
"[",
"from_clust",
"]",
"[",
"iattr",
"]",
"-=",
"curattr",
"# Update sums of memberships in cluster",
"cl_memb_sum",
"[",
"to_clust",
"]",
"+=",
"1",
"cl_memb_sum",
"[",
"from_clust",
"]",
"-=",
"1",
"return",
"cl_attr_sum",
",",
"cl_memb_sum"
] | Move point between clusters, numerical attributes. | [
"Move",
"point",
"between",
"clusters",
"numerical",
"attributes",
"."
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L28-L37 |
227,218 | nicodv/kmodes | kmodes/kprototypes.py | _split_num_cat | def _split_num_cat(X, categorical):
"""Extract numerical and categorical columns.
Convert to numpy arrays, if needed.
:param X: Feature matrix
:param categorical: Indices of categorical columns
"""
Xnum = np.asanyarray(X[:, [ii for ii in range(X.shape[1])
if ii not in categorical]]).astype(np.float64)
Xcat = np.asanyarray(X[:, categorical])
return Xnum, Xcat | python | def _split_num_cat(X, categorical):
"""Extract numerical and categorical columns.
Convert to numpy arrays, if needed.
:param X: Feature matrix
:param categorical: Indices of categorical columns
"""
Xnum = np.asanyarray(X[:, [ii for ii in range(X.shape[1])
if ii not in categorical]]).astype(np.float64)
Xcat = np.asanyarray(X[:, categorical])
return Xnum, Xcat | [
"def",
"_split_num_cat",
"(",
"X",
",",
"categorical",
")",
":",
"Xnum",
"=",
"np",
".",
"asanyarray",
"(",
"X",
"[",
":",
",",
"[",
"ii",
"for",
"ii",
"in",
"range",
"(",
"X",
".",
"shape",
"[",
"1",
"]",
")",
"if",
"ii",
"not",
"in",
"categorical",
"]",
"]",
")",
".",
"astype",
"(",
"np",
".",
"float64",
")",
"Xcat",
"=",
"np",
".",
"asanyarray",
"(",
"X",
"[",
":",
",",
"categorical",
"]",
")",
"return",
"Xnum",
",",
"Xcat"
] | Extract numerical and categorical columns.
Convert to numpy arrays, if needed.
:param X: Feature matrix
:param categorical: Indices of categorical columns | [
"Extract",
"numerical",
"and",
"categorical",
"columns",
".",
"Convert",
"to",
"numpy",
"arrays",
"if",
"needed",
"."
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L40-L50 |
227,219 | nicodv/kmodes | kmodes/kprototypes.py | _labels_cost | def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-prototypes algorithm.
"""
n_points = Xnum.shape[0]
Xnum = check_array(Xnum)
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint in range(n_points):
# Numerical cost = sum of Euclidean distances
num_costs = num_dissim(centroids[0], Xnum[ipoint])
cat_costs = cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
# Gamma relates the categorical cost to the numerical cost.
tot_costs = num_costs + gamma * cat_costs
clust = np.argmin(tot_costs)
labels[ipoint] = clust
cost += tot_costs[clust]
return labels, cost | python | def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-prototypes algorithm.
"""
n_points = Xnum.shape[0]
Xnum = check_array(Xnum)
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint in range(n_points):
# Numerical cost = sum of Euclidean distances
num_costs = num_dissim(centroids[0], Xnum[ipoint])
cat_costs = cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
# Gamma relates the categorical cost to the numerical cost.
tot_costs = num_costs + gamma * cat_costs
clust = np.argmin(tot_costs)
labels[ipoint] = clust
cost += tot_costs[clust]
return labels, cost | [
"def",
"_labels_cost",
"(",
"Xnum",
",",
"Xcat",
",",
"centroids",
",",
"num_dissim",
",",
"cat_dissim",
",",
"gamma",
",",
"membship",
"=",
"None",
")",
":",
"n_points",
"=",
"Xnum",
".",
"shape",
"[",
"0",
"]",
"Xnum",
"=",
"check_array",
"(",
"Xnum",
")",
"cost",
"=",
"0.",
"labels",
"=",
"np",
".",
"empty",
"(",
"n_points",
",",
"dtype",
"=",
"np",
".",
"uint16",
")",
"for",
"ipoint",
"in",
"range",
"(",
"n_points",
")",
":",
"# Numerical cost = sum of Euclidean distances",
"num_costs",
"=",
"num_dissim",
"(",
"centroids",
"[",
"0",
"]",
",",
"Xnum",
"[",
"ipoint",
"]",
")",
"cat_costs",
"=",
"cat_dissim",
"(",
"centroids",
"[",
"1",
"]",
",",
"Xcat",
"[",
"ipoint",
"]",
",",
"X",
"=",
"Xcat",
",",
"membship",
"=",
"membship",
")",
"# Gamma relates the categorical cost to the numerical cost.",
"tot_costs",
"=",
"num_costs",
"+",
"gamma",
"*",
"cat_costs",
"clust",
"=",
"np",
".",
"argmin",
"(",
"tot_costs",
")",
"labels",
"[",
"ipoint",
"]",
"=",
"clust",
"cost",
"+=",
"tot_costs",
"[",
"clust",
"]",
"return",
"labels",
",",
"cost"
] | Calculate labels and cost function given a matrix of points and
a list of centroids for the k-prototypes algorithm. | [
"Calculate",
"labels",
"and",
"cost",
"function",
"given",
"a",
"matrix",
"of",
"points",
"and",
"a",
"list",
"of",
"centroids",
"for",
"the",
"k",
"-",
"prototypes",
"algorithm",
"."
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L53-L73 |
227,220 | nicodv/kmodes | kmodes/kprototypes.py | _k_prototypes_iter | def _k_prototypes_iter(Xnum, Xcat, centroids, cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma, random_state):
"""Single iteration of the k-prototypes algorithm"""
moves = 0
for ipoint in range(Xnum.shape[0]):
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) +
gamma * cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
# Note that membship gets updated by kmodes.move_point_cat.
# move_point_num only updates things specific to the k-means part.
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[ipoint], clust, old_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[ipoint], ipoint, clust, old_clust,
cl_attr_freq, membship, centroids[1]
)
# Update old and new centroids for numerical attributes using
# the means and sums of all values
for iattr in range(len(Xnum[ipoint])):
for curc in (clust, old_clust):
if cl_memb_sum[curc]:
centroids[0][curc, iattr] = cl_attr_sum[curc, iattr] / cl_memb_sum[curc]
else:
centroids[0][curc, iattr] = 0.
# In case of an empty cluster, reinitialize with a random point
# from largest cluster.
if not cl_memb_sum[old_clust]:
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[rindx], old_clust, from_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[rindx], rindx, old_clust, from_clust,
cl_attr_freq, membship, centroids[1]
)
return centroids, moves | python | def _k_prototypes_iter(Xnum, Xcat, centroids, cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma, random_state):
"""Single iteration of the k-prototypes algorithm"""
moves = 0
for ipoint in range(Xnum.shape[0]):
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) +
gamma * cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
# Note that membship gets updated by kmodes.move_point_cat.
# move_point_num only updates things specific to the k-means part.
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[ipoint], clust, old_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[ipoint], ipoint, clust, old_clust,
cl_attr_freq, membship, centroids[1]
)
# Update old and new centroids for numerical attributes using
# the means and sums of all values
for iattr in range(len(Xnum[ipoint])):
for curc in (clust, old_clust):
if cl_memb_sum[curc]:
centroids[0][curc, iattr] = cl_attr_sum[curc, iattr] / cl_memb_sum[curc]
else:
centroids[0][curc, iattr] = 0.
# In case of an empty cluster, reinitialize with a random point
# from largest cluster.
if not cl_memb_sum[old_clust]:
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[rindx], old_clust, from_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[rindx], rindx, old_clust, from_clust,
cl_attr_freq, membship, centroids[1]
)
return centroids, moves | [
"def",
"_k_prototypes_iter",
"(",
"Xnum",
",",
"Xcat",
",",
"centroids",
",",
"cl_attr_sum",
",",
"cl_memb_sum",
",",
"cl_attr_freq",
",",
"membship",
",",
"num_dissim",
",",
"cat_dissim",
",",
"gamma",
",",
"random_state",
")",
":",
"moves",
"=",
"0",
"for",
"ipoint",
"in",
"range",
"(",
"Xnum",
".",
"shape",
"[",
"0",
"]",
")",
":",
"clust",
"=",
"np",
".",
"argmin",
"(",
"num_dissim",
"(",
"centroids",
"[",
"0",
"]",
",",
"Xnum",
"[",
"ipoint",
"]",
")",
"+",
"gamma",
"*",
"cat_dissim",
"(",
"centroids",
"[",
"1",
"]",
",",
"Xcat",
"[",
"ipoint",
"]",
",",
"X",
"=",
"Xcat",
",",
"membship",
"=",
"membship",
")",
")",
"if",
"membship",
"[",
"clust",
",",
"ipoint",
"]",
":",
"# Point is already in its right place.",
"continue",
"# Move point, and update old/new cluster frequencies and centroids.",
"moves",
"+=",
"1",
"old_clust",
"=",
"np",
".",
"argwhere",
"(",
"membship",
"[",
":",
",",
"ipoint",
"]",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"# Note that membship gets updated by kmodes.move_point_cat.",
"# move_point_num only updates things specific to the k-means part.",
"cl_attr_sum",
",",
"cl_memb_sum",
"=",
"move_point_num",
"(",
"Xnum",
"[",
"ipoint",
"]",
",",
"clust",
",",
"old_clust",
",",
"cl_attr_sum",
",",
"cl_memb_sum",
")",
"cl_attr_freq",
",",
"membship",
",",
"centroids",
"[",
"1",
"]",
"=",
"kmodes",
".",
"move_point_cat",
"(",
"Xcat",
"[",
"ipoint",
"]",
",",
"ipoint",
",",
"clust",
",",
"old_clust",
",",
"cl_attr_freq",
",",
"membship",
",",
"centroids",
"[",
"1",
"]",
")",
"# Update old and new centroids for numerical attributes using",
"# the means and sums of all values",
"for",
"iattr",
"in",
"range",
"(",
"len",
"(",
"Xnum",
"[",
"ipoint",
"]",
")",
")",
":",
"for",
"curc",
"in",
"(",
"clust",
",",
"old_clust",
")",
":",
"if",
"cl_memb_sum",
"[",
"curc",
"]",
":",
"centroids",
"[",
"0",
"]",
"[",
"curc",
",",
"iattr",
"]",
"=",
"cl_attr_sum",
"[",
"curc",
",",
"iattr",
"]",
"/",
"cl_memb_sum",
"[",
"curc",
"]",
"else",
":",
"centroids",
"[",
"0",
"]",
"[",
"curc",
",",
"iattr",
"]",
"=",
"0.",
"# In case of an empty cluster, reinitialize with a random point",
"# from largest cluster.",
"if",
"not",
"cl_memb_sum",
"[",
"old_clust",
"]",
":",
"from_clust",
"=",
"membship",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
".",
"argmax",
"(",
")",
"choices",
"=",
"[",
"ii",
"for",
"ii",
",",
"ch",
"in",
"enumerate",
"(",
"membship",
"[",
"from_clust",
",",
":",
"]",
")",
"if",
"ch",
"]",
"rindx",
"=",
"random_state",
".",
"choice",
"(",
"choices",
")",
"cl_attr_sum",
",",
"cl_memb_sum",
"=",
"move_point_num",
"(",
"Xnum",
"[",
"rindx",
"]",
",",
"old_clust",
",",
"from_clust",
",",
"cl_attr_sum",
",",
"cl_memb_sum",
")",
"cl_attr_freq",
",",
"membship",
",",
"centroids",
"[",
"1",
"]",
"=",
"kmodes",
".",
"move_point_cat",
"(",
"Xcat",
"[",
"rindx",
"]",
",",
"rindx",
",",
"old_clust",
",",
"from_clust",
",",
"cl_attr_freq",
",",
"membship",
",",
"centroids",
"[",
"1",
"]",
")",
"return",
"centroids",
",",
"moves"
] | Single iteration of the k-prototypes algorithm | [
"Single",
"iteration",
"of",
"the",
"k",
"-",
"prototypes",
"algorithm"
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L76-L127 |
227,221 | nicodv/kmodes | kmodes/kprototypes.py | k_prototypes | def k_prototypes(X, categorical, n_clusters, max_iter, num_dissim, cat_dissim,
gamma, init, n_init, verbose, random_state, n_jobs):
"""k-prototypes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-prototypes does not support sparse data.")
if categorical is None or not categorical:
raise NotImplementedError(
"No categorical data selected, effectively doing k-means. "
"Present a list of categorical columns, or use scikit-learn's "
"KMeans instead."
)
if isinstance(categorical, int):
categorical = [categorical]
assert len(categorical) != X.shape[1], \
"All columns are categorical, use k-modes instead of k-prototypes."
assert max(categorical) < X.shape[1], \
"Categorical index larger than number of columns."
ncatattrs = len(categorical)
nnumattrs = X.shape[1] - ncatattrs
n_points = X.shape[0]
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
# Convert the categorical values in Xcat to integers for speed.
# Based on the unique values in Xcat, we can make a mapping to achieve this.
Xcat, enc_map = encode_features(Xcat)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = list(_split_num_cat(unique, categorical))
init[1], _ = encode_features(init[1], enc_map)
# Estimate a good value for gamma, which determines the weighing of
# categorical values in clusters (see Huang [1997]).
if gamma is None:
gamma = 0.5 * Xnum.std()
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_prototypes_single)(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
# Note: return gamma in case it was automatically determined.
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best], gamma | python | def k_prototypes(X, categorical, n_clusters, max_iter, num_dissim, cat_dissim,
gamma, init, n_init, verbose, random_state, n_jobs):
"""k-prototypes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-prototypes does not support sparse data.")
if categorical is None or not categorical:
raise NotImplementedError(
"No categorical data selected, effectively doing k-means. "
"Present a list of categorical columns, or use scikit-learn's "
"KMeans instead."
)
if isinstance(categorical, int):
categorical = [categorical]
assert len(categorical) != X.shape[1], \
"All columns are categorical, use k-modes instead of k-prototypes."
assert max(categorical) < X.shape[1], \
"Categorical index larger than number of columns."
ncatattrs = len(categorical)
nnumattrs = X.shape[1] - ncatattrs
n_points = X.shape[0]
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
# Convert the categorical values in Xcat to integers for speed.
# Based on the unique values in Xcat, we can make a mapping to achieve this.
Xcat, enc_map = encode_features(Xcat)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = list(_split_num_cat(unique, categorical))
init[1], _ = encode_features(init[1], enc_map)
# Estimate a good value for gamma, which determines the weighing of
# categorical values in clusters (see Huang [1997]).
if gamma is None:
gamma = 0.5 * Xnum.std()
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_prototypes_single)(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
# Note: return gamma in case it was automatically determined.
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best], gamma | [
"def",
"k_prototypes",
"(",
"X",
",",
"categorical",
",",
"n_clusters",
",",
"max_iter",
",",
"num_dissim",
",",
"cat_dissim",
",",
"gamma",
",",
"init",
",",
"n_init",
",",
"verbose",
",",
"random_state",
",",
"n_jobs",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"if",
"sparse",
".",
"issparse",
"(",
"X",
")",
":",
"raise",
"TypeError",
"(",
"\"k-prototypes does not support sparse data.\"",
")",
"if",
"categorical",
"is",
"None",
"or",
"not",
"categorical",
":",
"raise",
"NotImplementedError",
"(",
"\"No categorical data selected, effectively doing k-means. \"",
"\"Present a list of categorical columns, or use scikit-learn's \"",
"\"KMeans instead.\"",
")",
"if",
"isinstance",
"(",
"categorical",
",",
"int",
")",
":",
"categorical",
"=",
"[",
"categorical",
"]",
"assert",
"len",
"(",
"categorical",
")",
"!=",
"X",
".",
"shape",
"[",
"1",
"]",
",",
"\"All columns are categorical, use k-modes instead of k-prototypes.\"",
"assert",
"max",
"(",
"categorical",
")",
"<",
"X",
".",
"shape",
"[",
"1",
"]",
",",
"\"Categorical index larger than number of columns.\"",
"ncatattrs",
"=",
"len",
"(",
"categorical",
")",
"nnumattrs",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"-",
"ncatattrs",
"n_points",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"assert",
"n_clusters",
"<=",
"n_points",
",",
"\"Cannot have more clusters ({}) \"",
"\"than data points ({}).\"",
".",
"format",
"(",
"n_clusters",
",",
"n_points",
")",
"Xnum",
",",
"Xcat",
"=",
"_split_num_cat",
"(",
"X",
",",
"categorical",
")",
"Xnum",
",",
"Xcat",
"=",
"check_array",
"(",
"Xnum",
")",
",",
"check_array",
"(",
"Xcat",
",",
"dtype",
"=",
"None",
")",
"# Convert the categorical values in Xcat to integers for speed.",
"# Based on the unique values in Xcat, we can make a mapping to achieve this.",
"Xcat",
",",
"enc_map",
"=",
"encode_features",
"(",
"Xcat",
")",
"# Are there more n_clusters than unique rows? Then set the unique",
"# rows as initial values and skip iteration.",
"unique",
"=",
"get_unique_rows",
"(",
"X",
")",
"n_unique",
"=",
"unique",
".",
"shape",
"[",
"0",
"]",
"if",
"n_unique",
"<=",
"n_clusters",
":",
"max_iter",
"=",
"0",
"n_init",
"=",
"1",
"n_clusters",
"=",
"n_unique",
"init",
"=",
"list",
"(",
"_split_num_cat",
"(",
"unique",
",",
"categorical",
")",
")",
"init",
"[",
"1",
"]",
",",
"_",
"=",
"encode_features",
"(",
"init",
"[",
"1",
"]",
",",
"enc_map",
")",
"# Estimate a good value for gamma, which determines the weighing of",
"# categorical values in clusters (see Huang [1997]).",
"if",
"gamma",
"is",
"None",
":",
"gamma",
"=",
"0.5",
"*",
"Xnum",
".",
"std",
"(",
")",
"results",
"=",
"[",
"]",
"seeds",
"=",
"random_state",
".",
"randint",
"(",
"np",
".",
"iinfo",
"(",
"np",
".",
"int32",
")",
".",
"max",
",",
"size",
"=",
"n_init",
")",
"if",
"n_jobs",
"==",
"1",
":",
"for",
"init_no",
"in",
"range",
"(",
"n_init",
")",
":",
"results",
".",
"append",
"(",
"k_prototypes_single",
"(",
"Xnum",
",",
"Xcat",
",",
"nnumattrs",
",",
"ncatattrs",
",",
"n_clusters",
",",
"n_points",
",",
"max_iter",
",",
"num_dissim",
",",
"cat_dissim",
",",
"gamma",
",",
"init",
",",
"init_no",
",",
"verbose",
",",
"seeds",
"[",
"init_no",
"]",
")",
")",
"else",
":",
"results",
"=",
"Parallel",
"(",
"n_jobs",
"=",
"n_jobs",
",",
"verbose",
"=",
"0",
")",
"(",
"delayed",
"(",
"k_prototypes_single",
")",
"(",
"Xnum",
",",
"Xcat",
",",
"nnumattrs",
",",
"ncatattrs",
",",
"n_clusters",
",",
"n_points",
",",
"max_iter",
",",
"num_dissim",
",",
"cat_dissim",
",",
"gamma",
",",
"init",
",",
"init_no",
",",
"verbose",
",",
"seed",
")",
"for",
"init_no",
",",
"seed",
"in",
"enumerate",
"(",
"seeds",
")",
")",
"all_centroids",
",",
"all_labels",
",",
"all_costs",
",",
"all_n_iters",
"=",
"zip",
"(",
"*",
"results",
")",
"best",
"=",
"np",
".",
"argmin",
"(",
"all_costs",
")",
"if",
"n_init",
">",
"1",
"and",
"verbose",
":",
"print",
"(",
"\"Best run was number {}\"",
".",
"format",
"(",
"best",
"+",
"1",
")",
")",
"# Note: return gamma in case it was automatically determined.",
"return",
"all_centroids",
"[",
"best",
"]",
",",
"enc_map",
",",
"all_labels",
"[",
"best",
"]",
",",
"all_costs",
"[",
"best",
"]",
",",
"all_n_iters",
"[",
"best",
"]",
",",
"gamma"
] | k-prototypes algorithm | [
"k",
"-",
"prototypes",
"algorithm"
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L255-L327 |
227,222 | nicodv/kmodes | kmodes/kprototypes.py | KPrototypes.fit | def fit(self, X, y=None, categorical=None):
"""Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data
"""
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
# If self.gamma is None, gamma will be automatically determined from
# the data. The function below returns its value.
self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\
self.n_iter_, self.gamma = k_prototypes(X,
categorical,
self.n_clusters,
self.max_iter,
self.num_dissim,
self.cat_dissim,
self.gamma,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self | python | def fit(self, X, y=None, categorical=None):
"""Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data
"""
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
# If self.gamma is None, gamma will be automatically determined from
# the data. The function below returns its value.
self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\
self.n_iter_, self.gamma = k_prototypes(X,
categorical,
self.n_clusters,
self.max_iter,
self.num_dissim,
self.cat_dissim,
self.gamma,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"categorical",
"=",
"None",
")",
":",
"if",
"categorical",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"categorical",
",",
"(",
"int",
",",
"list",
",",
"tuple",
")",
")",
",",
"\"The 'categorical' \\\n argument needs to be an integer with the index of the categorical \\\n column in your data, or a list or tuple of several of them, \\\n but it is a {}.\"",
".",
"format",
"(",
"type",
"(",
"categorical",
")",
")",
"X",
"=",
"pandas_to_numpy",
"(",
"X",
")",
"random_state",
"=",
"check_random_state",
"(",
"self",
".",
"random_state",
")",
"# If self.gamma is None, gamma will be automatically determined from",
"# the data. The function below returns its value.",
"self",
".",
"_enc_cluster_centroids",
",",
"self",
".",
"_enc_map",
",",
"self",
".",
"labels_",
",",
"self",
".",
"cost_",
",",
"self",
".",
"n_iter_",
",",
"self",
".",
"gamma",
"=",
"k_prototypes",
"(",
"X",
",",
"categorical",
",",
"self",
".",
"n_clusters",
",",
"self",
".",
"max_iter",
",",
"self",
".",
"num_dissim",
",",
"self",
".",
"cat_dissim",
",",
"self",
".",
"gamma",
",",
"self",
".",
"init",
",",
"self",
".",
"n_init",
",",
"self",
".",
"verbose",
",",
"random_state",
",",
"self",
".",
"n_jobs",
")",
"return",
"self"
] | Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data | [
"Compute",
"k",
"-",
"prototypes",
"clustering",
"."
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L431-L463 |
227,223 | nicodv/kmodes | kmodes/util/dissim.py | euclidean_dissim | def euclidean_dissim(a, b, **_):
"""Euclidean distance dissimilarity function"""
if np.isnan(a).any() or np.isnan(b).any():
raise ValueError("Missing values detected in numerical columns.")
return np.sum((a - b) ** 2, axis=1) | python | def euclidean_dissim(a, b, **_):
"""Euclidean distance dissimilarity function"""
if np.isnan(a).any() or np.isnan(b).any():
raise ValueError("Missing values detected in numerical columns.")
return np.sum((a - b) ** 2, axis=1) | [
"def",
"euclidean_dissim",
"(",
"a",
",",
"b",
",",
"*",
"*",
"_",
")",
":",
"if",
"np",
".",
"isnan",
"(",
"a",
")",
".",
"any",
"(",
")",
"or",
"np",
".",
"isnan",
"(",
"b",
")",
".",
"any",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Missing values detected in numerical columns.\"",
")",
"return",
"np",
".",
"sum",
"(",
"(",
"a",
"-",
"b",
")",
"**",
"2",
",",
"axis",
"=",
"1",
")"
] | Euclidean distance dissimilarity function | [
"Euclidean",
"distance",
"dissimilarity",
"function"
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/util/dissim.py#L13-L17 |
227,224 | nicodv/kmodes | kmodes/util/dissim.py | ng_dissim | def ng_dissim(a, b, X=None, membship=None):
"""Ng et al.'s dissimilarity measure, as presented in
Michael K. Ng, Mark Junjie Li, Joshua Zhexue Huang, and Zengyou He, "On the
Impact of Dissimilarity Measure in k-Modes Clustering Algorithm", IEEE
Transactions on Pattern Analysis and Machine Intelligence, Vol. 29, No. 3,
January, 2007
This function can potentially speed up training convergence.
Note that membship must be a rectangular array such that the
len(membship) = len(a) and len(membship[i]) = X.shape[1]
In case of missing membship, this function reverts back to
matching dissimilarity (e.g., when predicting).
"""
# Without membership, revert to matching dissimilarity
if membship is None:
return matching_dissim(a, b)
def calc_cjr(b, X, memj, idr):
"""Num objects w/ category value x_{i,r} for rth attr in jth cluster"""
xcids = np.where(memj == 1)
return float((np.take(X, xcids, axis=0)[0][:, idr] == b[idr]).sum(0))
def calc_dissim(b, X, memj, idr):
# Size of jth cluster
cj = float(np.sum(memj))
return (1.0 - (calc_cjr(b, X, memj, idr) / cj)) if cj != 0.0 else 0.0
if len(membship) != a.shape[0] and len(membship[0]) != X.shape[1]:
raise ValueError("'membship' must be a rectangular array where "
"the number of rows in 'membship' equals the "
"number of rows in 'a' and the number of "
"columns in 'membship' equals the number of rows in 'X'.")
return np.array([np.array([calc_dissim(b, X, membship[idj], idr)
if b[idr] == t else 1.0
for idr, t in enumerate(val_a)]).sum(0)
for idj, val_a in enumerate(a)]) | python | def ng_dissim(a, b, X=None, membship=None):
"""Ng et al.'s dissimilarity measure, as presented in
Michael K. Ng, Mark Junjie Li, Joshua Zhexue Huang, and Zengyou He, "On the
Impact of Dissimilarity Measure in k-Modes Clustering Algorithm", IEEE
Transactions on Pattern Analysis and Machine Intelligence, Vol. 29, No. 3,
January, 2007
This function can potentially speed up training convergence.
Note that membship must be a rectangular array such that the
len(membship) = len(a) and len(membship[i]) = X.shape[1]
In case of missing membship, this function reverts back to
matching dissimilarity (e.g., when predicting).
"""
# Without membership, revert to matching dissimilarity
if membship is None:
return matching_dissim(a, b)
def calc_cjr(b, X, memj, idr):
"""Num objects w/ category value x_{i,r} for rth attr in jth cluster"""
xcids = np.where(memj == 1)
return float((np.take(X, xcids, axis=0)[0][:, idr] == b[idr]).sum(0))
def calc_dissim(b, X, memj, idr):
# Size of jth cluster
cj = float(np.sum(memj))
return (1.0 - (calc_cjr(b, X, memj, idr) / cj)) if cj != 0.0 else 0.0
if len(membship) != a.shape[0] and len(membship[0]) != X.shape[1]:
raise ValueError("'membship' must be a rectangular array where "
"the number of rows in 'membship' equals the "
"number of rows in 'a' and the number of "
"columns in 'membship' equals the number of rows in 'X'.")
return np.array([np.array([calc_dissim(b, X, membship[idj], idr)
if b[idr] == t else 1.0
for idr, t in enumerate(val_a)]).sum(0)
for idj, val_a in enumerate(a)]) | [
"def",
"ng_dissim",
"(",
"a",
",",
"b",
",",
"X",
"=",
"None",
",",
"membship",
"=",
"None",
")",
":",
"# Without membership, revert to matching dissimilarity",
"if",
"membship",
"is",
"None",
":",
"return",
"matching_dissim",
"(",
"a",
",",
"b",
")",
"def",
"calc_cjr",
"(",
"b",
",",
"X",
",",
"memj",
",",
"idr",
")",
":",
"\"\"\"Num objects w/ category value x_{i,r} for rth attr in jth cluster\"\"\"",
"xcids",
"=",
"np",
".",
"where",
"(",
"memj",
"==",
"1",
")",
"return",
"float",
"(",
"(",
"np",
".",
"take",
"(",
"X",
",",
"xcids",
",",
"axis",
"=",
"0",
")",
"[",
"0",
"]",
"[",
":",
",",
"idr",
"]",
"==",
"b",
"[",
"idr",
"]",
")",
".",
"sum",
"(",
"0",
")",
")",
"def",
"calc_dissim",
"(",
"b",
",",
"X",
",",
"memj",
",",
"idr",
")",
":",
"# Size of jth cluster",
"cj",
"=",
"float",
"(",
"np",
".",
"sum",
"(",
"memj",
")",
")",
"return",
"(",
"1.0",
"-",
"(",
"calc_cjr",
"(",
"b",
",",
"X",
",",
"memj",
",",
"idr",
")",
"/",
"cj",
")",
")",
"if",
"cj",
"!=",
"0.0",
"else",
"0.0",
"if",
"len",
"(",
"membship",
")",
"!=",
"a",
".",
"shape",
"[",
"0",
"]",
"and",
"len",
"(",
"membship",
"[",
"0",
"]",
")",
"!=",
"X",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"'membship' must be a rectangular array where \"",
"\"the number of rows in 'membship' equals the \"",
"\"number of rows in 'a' and the number of \"",
"\"columns in 'membship' equals the number of rows in 'X'.\"",
")",
"return",
"np",
".",
"array",
"(",
"[",
"np",
".",
"array",
"(",
"[",
"calc_dissim",
"(",
"b",
",",
"X",
",",
"membship",
"[",
"idj",
"]",
",",
"idr",
")",
"if",
"b",
"[",
"idr",
"]",
"==",
"t",
"else",
"1.0",
"for",
"idr",
",",
"t",
"in",
"enumerate",
"(",
"val_a",
")",
"]",
")",
".",
"sum",
"(",
"0",
")",
"for",
"idj",
",",
"val_a",
"in",
"enumerate",
"(",
"a",
")",
"]",
")"
] | Ng et al.'s dissimilarity measure, as presented in
Michael K. Ng, Mark Junjie Li, Joshua Zhexue Huang, and Zengyou He, "On the
Impact of Dissimilarity Measure in k-Modes Clustering Algorithm", IEEE
Transactions on Pattern Analysis and Machine Intelligence, Vol. 29, No. 3,
January, 2007
This function can potentially speed up training convergence.
Note that membship must be a rectangular array such that the
len(membship) = len(a) and len(membship[i]) = X.shape[1]
In case of missing membship, this function reverts back to
matching dissimilarity (e.g., when predicting). | [
"Ng",
"et",
"al",
".",
"s",
"dissimilarity",
"measure",
"as",
"presented",
"in",
"Michael",
"K",
".",
"Ng",
"Mark",
"Junjie",
"Li",
"Joshua",
"Zhexue",
"Huang",
"and",
"Zengyou",
"He",
"On",
"the",
"Impact",
"of",
"Dissimilarity",
"Measure",
"in",
"k",
"-",
"Modes",
"Clustering",
"Algorithm",
"IEEE",
"Transactions",
"on",
"Pattern",
"Analysis",
"and",
"Machine",
"Intelligence",
"Vol",
".",
"29",
"No",
".",
"3",
"January",
"2007"
] | cdb19fe5448aba1bf501626694bb52e68eafab45 | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/util/dissim.py#L20-L58 |
227,225 | Bogdanp/dramatiq | dramatiq/results/backend.py | ResultBackend.store_result | def store_result(self, message, result: Result, ttl: int) -> None:
"""Store a result in the backend.
Parameters:
message(Message)
result(object): Must be serializable.
ttl(int): The maximum amount of time the result may be
stored in the backend for.
"""
message_key = self.build_message_key(message)
return self._store(message_key, result, ttl) | python | def store_result(self, message, result: Result, ttl: int) -> None:
"""Store a result in the backend.
Parameters:
message(Message)
result(object): Must be serializable.
ttl(int): The maximum amount of time the result may be
stored in the backend for.
"""
message_key = self.build_message_key(message)
return self._store(message_key, result, ttl) | [
"def",
"store_result",
"(",
"self",
",",
"message",
",",
"result",
":",
"Result",
",",
"ttl",
":",
"int",
")",
"->",
"None",
":",
"message_key",
"=",
"self",
".",
"build_message_key",
"(",
"message",
")",
"return",
"self",
".",
"_store",
"(",
"message_key",
",",
"result",
",",
"ttl",
")"
] | Store a result in the backend.
Parameters:
message(Message)
result(object): Must be serializable.
ttl(int): The maximum amount of time the result may be
stored in the backend for. | [
"Store",
"a",
"result",
"in",
"the",
"backend",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/results/backend.py#L98-L108 |
227,226 | Bogdanp/dramatiq | dramatiq/results/backend.py | ResultBackend.build_message_key | def build_message_key(self, message) -> str:
"""Given a message, return its globally-unique key.
Parameters:
message(Message)
Returns:
str
"""
message_key = "%(namespace)s:%(queue_name)s:%(actor_name)s:%(message_id)s" % {
"namespace": self.namespace,
"queue_name": q_name(message.queue_name),
"actor_name": message.actor_name,
"message_id": message.message_id,
}
return hashlib.md5(message_key.encode("utf-8")).hexdigest() | python | def build_message_key(self, message) -> str:
"""Given a message, return its globally-unique key.
Parameters:
message(Message)
Returns:
str
"""
message_key = "%(namespace)s:%(queue_name)s:%(actor_name)s:%(message_id)s" % {
"namespace": self.namespace,
"queue_name": q_name(message.queue_name),
"actor_name": message.actor_name,
"message_id": message.message_id,
}
return hashlib.md5(message_key.encode("utf-8")).hexdigest() | [
"def",
"build_message_key",
"(",
"self",
",",
"message",
")",
"->",
"str",
":",
"message_key",
"=",
"\"%(namespace)s:%(queue_name)s:%(actor_name)s:%(message_id)s\"",
"%",
"{",
"\"namespace\"",
":",
"self",
".",
"namespace",
",",
"\"queue_name\"",
":",
"q_name",
"(",
"message",
".",
"queue_name",
")",
",",
"\"actor_name\"",
":",
"message",
".",
"actor_name",
",",
"\"message_id\"",
":",
"message",
".",
"message_id",
",",
"}",
"return",
"hashlib",
".",
"md5",
"(",
"message_key",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")"
] | Given a message, return its globally-unique key.
Parameters:
message(Message)
Returns:
str | [
"Given",
"a",
"message",
"return",
"its",
"globally",
"-",
"unique",
"key",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/results/backend.py#L110-L125 |
227,227 | Bogdanp/dramatiq | dramatiq/results/backend.py | ResultBackend._store | def _store(self, message_key: str, result: Result, ttl: int) -> None: # pragma: no cover
"""Store a result in the backend. Subclasses may implement
this method if they want to use the default implementation of
set_result.
"""
raise NotImplementedError("%(classname)r does not implement _store()" % {
"classname": type(self).__name__,
}) | python | def _store(self, message_key: str, result: Result, ttl: int) -> None: # pragma: no cover
"""Store a result in the backend. Subclasses may implement
this method if they want to use the default implementation of
set_result.
"""
raise NotImplementedError("%(classname)r does not implement _store()" % {
"classname": type(self).__name__,
}) | [
"def",
"_store",
"(",
"self",
",",
"message_key",
":",
"str",
",",
"result",
":",
"Result",
",",
"ttl",
":",
"int",
")",
"->",
"None",
":",
"# pragma: no cover",
"raise",
"NotImplementedError",
"(",
"\"%(classname)r does not implement _store()\"",
"%",
"{",
"\"classname\"",
":",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"}",
")"
] | Store a result in the backend. Subclasses may implement
this method if they want to use the default implementation of
set_result. | [
"Store",
"a",
"result",
"in",
"the",
"backend",
".",
"Subclasses",
"may",
"implement",
"this",
"method",
"if",
"they",
"want",
"to",
"use",
"the",
"default",
"implementation",
"of",
"set_result",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/results/backend.py#L136-L143 |
227,228 | Bogdanp/dramatiq | dramatiq/rate_limits/rate_limiter.py | RateLimiter.acquire | def acquire(self, *, raise_on_failure=True):
"""Attempt to acquire a slot under this rate limiter.
Parameters:
raise_on_failure(bool): Whether or not failures should raise an
exception. If this is false, the context manager will instead
return a boolean value representing whether or not the rate
limit slot was acquired.
Returns:
bool: Whether or not the slot could be acquired.
"""
acquired = False
try:
acquired = self._acquire()
if raise_on_failure and not acquired:
raise RateLimitExceeded("rate limit exceeded for key %(key)r" % vars(self))
yield acquired
finally:
if acquired:
self._release() | python | def acquire(self, *, raise_on_failure=True):
"""Attempt to acquire a slot under this rate limiter.
Parameters:
raise_on_failure(bool): Whether or not failures should raise an
exception. If this is false, the context manager will instead
return a boolean value representing whether or not the rate
limit slot was acquired.
Returns:
bool: Whether or not the slot could be acquired.
"""
acquired = False
try:
acquired = self._acquire()
if raise_on_failure and not acquired:
raise RateLimitExceeded("rate limit exceeded for key %(key)r" % vars(self))
yield acquired
finally:
if acquired:
self._release() | [
"def",
"acquire",
"(",
"self",
",",
"*",
",",
"raise_on_failure",
"=",
"True",
")",
":",
"acquired",
"=",
"False",
"try",
":",
"acquired",
"=",
"self",
".",
"_acquire",
"(",
")",
"if",
"raise_on_failure",
"and",
"not",
"acquired",
":",
"raise",
"RateLimitExceeded",
"(",
"\"rate limit exceeded for key %(key)r\"",
"%",
"vars",
"(",
"self",
")",
")",
"yield",
"acquired",
"finally",
":",
"if",
"acquired",
":",
"self",
".",
"_release",
"(",
")"
] | Attempt to acquire a slot under this rate limiter.
Parameters:
raise_on_failure(bool): Whether or not failures should raise an
exception. If this is false, the context manager will instead
return a boolean value representing whether or not the rate
limit slot was acquired.
Returns:
bool: Whether or not the slot could be acquired. | [
"Attempt",
"to",
"acquire",
"a",
"slot",
"under",
"this",
"rate",
"limiter",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/rate_limits/rate_limiter.py#L56-L78 |
227,229 | Bogdanp/dramatiq | dramatiq/middleware/prometheus.py | flock | def flock(path):
"""Attempt to acquire a POSIX file lock.
"""
with open(path, "w+") as lf:
try:
fcntl.flock(lf, fcntl.LOCK_EX | fcntl.LOCK_NB)
acquired = True
yield acquired
except OSError:
acquired = False
yield acquired
finally:
if acquired:
fcntl.flock(lf, fcntl.LOCK_UN) | python | def flock(path):
"""Attempt to acquire a POSIX file lock.
"""
with open(path, "w+") as lf:
try:
fcntl.flock(lf, fcntl.LOCK_EX | fcntl.LOCK_NB)
acquired = True
yield acquired
except OSError:
acquired = False
yield acquired
finally:
if acquired:
fcntl.flock(lf, fcntl.LOCK_UN) | [
"def",
"flock",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"w+\"",
")",
"as",
"lf",
":",
"try",
":",
"fcntl",
".",
"flock",
"(",
"lf",
",",
"fcntl",
".",
"LOCK_EX",
"|",
"fcntl",
".",
"LOCK_NB",
")",
"acquired",
"=",
"True",
"yield",
"acquired",
"except",
"OSError",
":",
"acquired",
"=",
"False",
"yield",
"acquired",
"finally",
":",
"if",
"acquired",
":",
"fcntl",
".",
"flock",
"(",
"lf",
",",
"fcntl",
".",
"LOCK_UN",
")"
] | Attempt to acquire a POSIX file lock. | [
"Attempt",
"to",
"acquire",
"a",
"POSIX",
"file",
"lock",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/middleware/prometheus.py#L227-L242 |
227,230 | Bogdanp/dramatiq | dramatiq/message.py | Message.copy | def copy(self, **attributes):
"""Create a copy of this message.
"""
updated_options = attributes.pop("options", {})
options = self.options.copy()
options.update(updated_options)
return self._replace(**attributes, options=options) | python | def copy(self, **attributes):
"""Create a copy of this message.
"""
updated_options = attributes.pop("options", {})
options = self.options.copy()
options.update(updated_options)
return self._replace(**attributes, options=options) | [
"def",
"copy",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"updated_options",
"=",
"attributes",
".",
"pop",
"(",
"\"options\"",
",",
"{",
"}",
")",
"options",
"=",
"self",
".",
"options",
".",
"copy",
"(",
")",
"options",
".",
"update",
"(",
"updated_options",
")",
"return",
"self",
".",
"_replace",
"(",
"*",
"*",
"attributes",
",",
"options",
"=",
"options",
")"
] | Create a copy of this message. | [
"Create",
"a",
"copy",
"of",
"this",
"message",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/message.py#L103-L109 |
227,231 | Bogdanp/dramatiq | dramatiq/message.py | Message.get_result | def get_result(self, *, backend=None, block=False, timeout=None):
"""Get the result associated with this message from a result
backend.
Warning:
If you use multiple result backends or brokers you should
always pass the backend parameter. This method is only able
to infer the result backend off of the default broker.
Parameters:
backend(ResultBackend): The result backend to use to get the
result. If omitted, this method will try to find and use
the result backend on the default broker instance.
block(bool): Whether or not to block while waiting for a
result.
timeout(int): The maximum amount of time, in ms, to block
while waiting for a result.
Raises:
RuntimeError: If there is no result backend on the default
broker.
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
object: The result.
"""
if not backend:
broker = get_broker()
for middleware in broker.middleware:
if isinstance(middleware, Results):
backend = middleware.backend
break
else:
raise RuntimeError("The default broker doesn't have a results backend.")
return backend.get_result(self, block=block, timeout=timeout) | python | def get_result(self, *, backend=None, block=False, timeout=None):
"""Get the result associated with this message from a result
backend.
Warning:
If you use multiple result backends or brokers you should
always pass the backend parameter. This method is only able
to infer the result backend off of the default broker.
Parameters:
backend(ResultBackend): The result backend to use to get the
result. If omitted, this method will try to find and use
the result backend on the default broker instance.
block(bool): Whether or not to block while waiting for a
result.
timeout(int): The maximum amount of time, in ms, to block
while waiting for a result.
Raises:
RuntimeError: If there is no result backend on the default
broker.
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
object: The result.
"""
if not backend:
broker = get_broker()
for middleware in broker.middleware:
if isinstance(middleware, Results):
backend = middleware.backend
break
else:
raise RuntimeError("The default broker doesn't have a results backend.")
return backend.get_result(self, block=block, timeout=timeout) | [
"def",
"get_result",
"(",
"self",
",",
"*",
",",
"backend",
"=",
"None",
",",
"block",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"backend",
":",
"broker",
"=",
"get_broker",
"(",
")",
"for",
"middleware",
"in",
"broker",
".",
"middleware",
":",
"if",
"isinstance",
"(",
"middleware",
",",
"Results",
")",
":",
"backend",
"=",
"middleware",
".",
"backend",
"break",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"The default broker doesn't have a results backend.\"",
")",
"return",
"backend",
".",
"get_result",
"(",
"self",
",",
"block",
"=",
"block",
",",
"timeout",
"=",
"timeout",
")"
] | Get the result associated with this message from a result
backend.
Warning:
If you use multiple result backends or brokers you should
always pass the backend parameter. This method is only able
to infer the result backend off of the default broker.
Parameters:
backend(ResultBackend): The result backend to use to get the
result. If omitted, this method will try to find and use
the result backend on the default broker instance.
block(bool): Whether or not to block while waiting for a
result.
timeout(int): The maximum amount of time, in ms, to block
while waiting for a result.
Raises:
RuntimeError: If there is no result backend on the default
broker.
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
object: The result. | [
"Get",
"the",
"result",
"associated",
"with",
"this",
"message",
"from",
"a",
"result",
"backend",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/message.py#L111-L147 |
227,232 | Bogdanp/dramatiq | dramatiq/common.py | compute_backoff | def compute_backoff(attempts, *, factor=5, jitter=True, max_backoff=2000, max_exponent=32):
"""Compute an exponential backoff value based on some number of attempts.
Parameters:
attempts(int): The number of attempts there have been so far.
factor(int): The number of milliseconds to multiply each backoff by.
max_backoff(int): The max number of milliseconds to backoff by.
max_exponent(int): The maximum backoff exponent.
Returns:
tuple: The new number of attempts and the backoff in milliseconds.
"""
exponent = min(attempts, max_exponent)
backoff = min(factor * 2 ** exponent, max_backoff)
if jitter:
backoff /= 2
backoff = int(backoff + uniform(0, backoff))
return attempts + 1, backoff | python | def compute_backoff(attempts, *, factor=5, jitter=True, max_backoff=2000, max_exponent=32):
"""Compute an exponential backoff value based on some number of attempts.
Parameters:
attempts(int): The number of attempts there have been so far.
factor(int): The number of milliseconds to multiply each backoff by.
max_backoff(int): The max number of milliseconds to backoff by.
max_exponent(int): The maximum backoff exponent.
Returns:
tuple: The new number of attempts and the backoff in milliseconds.
"""
exponent = min(attempts, max_exponent)
backoff = min(factor * 2 ** exponent, max_backoff)
if jitter:
backoff /= 2
backoff = int(backoff + uniform(0, backoff))
return attempts + 1, backoff | [
"def",
"compute_backoff",
"(",
"attempts",
",",
"*",
",",
"factor",
"=",
"5",
",",
"jitter",
"=",
"True",
",",
"max_backoff",
"=",
"2000",
",",
"max_exponent",
"=",
"32",
")",
":",
"exponent",
"=",
"min",
"(",
"attempts",
",",
"max_exponent",
")",
"backoff",
"=",
"min",
"(",
"factor",
"*",
"2",
"**",
"exponent",
",",
"max_backoff",
")",
"if",
"jitter",
":",
"backoff",
"/=",
"2",
"backoff",
"=",
"int",
"(",
"backoff",
"+",
"uniform",
"(",
"0",
",",
"backoff",
")",
")",
"return",
"attempts",
"+",
"1",
",",
"backoff"
] | Compute an exponential backoff value based on some number of attempts.
Parameters:
attempts(int): The number of attempts there have been so far.
factor(int): The number of milliseconds to multiply each backoff by.
max_backoff(int): The max number of milliseconds to backoff by.
max_exponent(int): The maximum backoff exponent.
Returns:
tuple: The new number of attempts and the backoff in milliseconds. | [
"Compute",
"an",
"exponential",
"backoff",
"value",
"based",
"on",
"some",
"number",
"of",
"attempts",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/common.py#L24-L41 |
227,233 | Bogdanp/dramatiq | dramatiq/common.py | join_all | def join_all(joinables, timeout):
"""Wait on a list of objects that can be joined with a total
timeout represented by ``timeout``.
Parameters:
joinables(object): Objects with a join method.
timeout(int): The total timeout in milliseconds.
"""
started, elapsed = current_millis(), 0
for ob in joinables:
ob.join(timeout=timeout / 1000)
elapsed = current_millis() - started
timeout = max(0, timeout - elapsed) | python | def join_all(joinables, timeout):
"""Wait on a list of objects that can be joined with a total
timeout represented by ``timeout``.
Parameters:
joinables(object): Objects with a join method.
timeout(int): The total timeout in milliseconds.
"""
started, elapsed = current_millis(), 0
for ob in joinables:
ob.join(timeout=timeout / 1000)
elapsed = current_millis() - started
timeout = max(0, timeout - elapsed) | [
"def",
"join_all",
"(",
"joinables",
",",
"timeout",
")",
":",
"started",
",",
"elapsed",
"=",
"current_millis",
"(",
")",
",",
"0",
"for",
"ob",
"in",
"joinables",
":",
"ob",
".",
"join",
"(",
"timeout",
"=",
"timeout",
"/",
"1000",
")",
"elapsed",
"=",
"current_millis",
"(",
")",
"-",
"started",
"timeout",
"=",
"max",
"(",
"0",
",",
"timeout",
"-",
"elapsed",
")"
] | Wait on a list of objects that can be joined with a total
timeout represented by ``timeout``.
Parameters:
joinables(object): Objects with a join method.
timeout(int): The total timeout in milliseconds. | [
"Wait",
"on",
"a",
"list",
"of",
"objects",
"that",
"can",
"be",
"joined",
"with",
"a",
"total",
"timeout",
"represented",
"by",
"timeout",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/common.py#L86-L98 |
227,234 | Bogdanp/dramatiq | dramatiq/common.py | dq_name | def dq_name(queue_name):
"""Returns the delayed queue name for a given queue. If the given
queue name already belongs to a delayed queue, then it is returned
unchanged.
"""
if queue_name.endswith(".DQ"):
return queue_name
if queue_name.endswith(".XQ"):
queue_name = queue_name[:-3]
return queue_name + ".DQ" | python | def dq_name(queue_name):
"""Returns the delayed queue name for a given queue. If the given
queue name already belongs to a delayed queue, then it is returned
unchanged.
"""
if queue_name.endswith(".DQ"):
return queue_name
if queue_name.endswith(".XQ"):
queue_name = queue_name[:-3]
return queue_name + ".DQ" | [
"def",
"dq_name",
"(",
"queue_name",
")",
":",
"if",
"queue_name",
".",
"endswith",
"(",
"\".DQ\"",
")",
":",
"return",
"queue_name",
"if",
"queue_name",
".",
"endswith",
"(",
"\".XQ\"",
")",
":",
"queue_name",
"=",
"queue_name",
"[",
":",
"-",
"3",
"]",
"return",
"queue_name",
"+",
"\".DQ\""
] | Returns the delayed queue name for a given queue. If the given
queue name already belongs to a delayed queue, then it is returned
unchanged. | [
"Returns",
"the",
"delayed",
"queue",
"name",
"for",
"a",
"given",
"queue",
".",
"If",
"the",
"given",
"queue",
"name",
"already",
"belongs",
"to",
"a",
"delayed",
"queue",
"then",
"it",
"is",
"returned",
"unchanged",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/common.py#L109-L119 |
227,235 | Bogdanp/dramatiq | dramatiq/common.py | xq_name | def xq_name(queue_name):
"""Returns the dead letter queue name for a given queue. If the
given queue name belongs to a delayed queue, the dead letter queue
name for the original queue is generated.
"""
if queue_name.endswith(".XQ"):
return queue_name
if queue_name.endswith(".DQ"):
queue_name = queue_name[:-3]
return queue_name + ".XQ" | python | def xq_name(queue_name):
"""Returns the dead letter queue name for a given queue. If the
given queue name belongs to a delayed queue, the dead letter queue
name for the original queue is generated.
"""
if queue_name.endswith(".XQ"):
return queue_name
if queue_name.endswith(".DQ"):
queue_name = queue_name[:-3]
return queue_name + ".XQ" | [
"def",
"xq_name",
"(",
"queue_name",
")",
":",
"if",
"queue_name",
".",
"endswith",
"(",
"\".XQ\"",
")",
":",
"return",
"queue_name",
"if",
"queue_name",
".",
"endswith",
"(",
"\".DQ\"",
")",
":",
"queue_name",
"=",
"queue_name",
"[",
":",
"-",
"3",
"]",
"return",
"queue_name",
"+",
"\".XQ\""
] | Returns the dead letter queue name for a given queue. If the
given queue name belongs to a delayed queue, the dead letter queue
name for the original queue is generated. | [
"Returns",
"the",
"dead",
"letter",
"queue",
"name",
"for",
"a",
"given",
"queue",
".",
"If",
"the",
"given",
"queue",
"name",
"belongs",
"to",
"a",
"delayed",
"queue",
"the",
"dead",
"letter",
"queue",
"name",
"for",
"the",
"original",
"queue",
"is",
"generated",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/common.py#L122-L132 |
227,236 | Bogdanp/dramatiq | dramatiq/broker.py | get_broker | def get_broker() -> "Broker":
"""Get the global broker instance. If no global broker is set,
this initializes a RabbitmqBroker and returns it.
Returns:
Broker: The default Broker.
"""
global global_broker
if global_broker is None:
from .brokers.rabbitmq import RabbitmqBroker
set_broker(RabbitmqBroker(
host="127.0.0.1",
port=5672,
heartbeat=5,
connection_attempts=5,
blocked_connection_timeout=30,
))
return global_broker | python | def get_broker() -> "Broker":
"""Get the global broker instance. If no global broker is set,
this initializes a RabbitmqBroker and returns it.
Returns:
Broker: The default Broker.
"""
global global_broker
if global_broker is None:
from .brokers.rabbitmq import RabbitmqBroker
set_broker(RabbitmqBroker(
host="127.0.0.1",
port=5672,
heartbeat=5,
connection_attempts=5,
blocked_connection_timeout=30,
))
return global_broker | [
"def",
"get_broker",
"(",
")",
"->",
"\"Broker\"",
":",
"global",
"global_broker",
"if",
"global_broker",
"is",
"None",
":",
"from",
".",
"brokers",
".",
"rabbitmq",
"import",
"RabbitmqBroker",
"set_broker",
"(",
"RabbitmqBroker",
"(",
"host",
"=",
"\"127.0.0.1\"",
",",
"port",
"=",
"5672",
",",
"heartbeat",
"=",
"5",
",",
"connection_attempts",
"=",
"5",
",",
"blocked_connection_timeout",
"=",
"30",
",",
")",
")",
"return",
"global_broker"
] | Get the global broker instance. If no global broker is set,
this initializes a RabbitmqBroker and returns it.
Returns:
Broker: The default Broker. | [
"Get",
"the",
"global",
"broker",
"instance",
".",
"If",
"no",
"global",
"broker",
"is",
"set",
"this",
"initializes",
"a",
"RabbitmqBroker",
"and",
"returns",
"it",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/broker.py#L26-L44 |
227,237 | Bogdanp/dramatiq | dramatiq/broker.py | Broker.add_middleware | def add_middleware(self, middleware, *, before=None, after=None):
"""Add a middleware object to this broker. The middleware is
appended to the end of the middleware list by default.
You can specify another middleware (by class) as a reference
point for where the new middleware should be added.
Parameters:
middleware(Middleware): The middleware.
before(type): Add this middleware before a specific one.
after(type): Add this middleware after a specific one.
Raises:
ValueError: When either ``before`` or ``after`` refer to a
middleware that hasn't been registered yet.
"""
assert not (before and after), \
"provide either 'before' or 'after', but not both"
if before or after:
for i, m in enumerate(self.middleware): # noqa
if isinstance(m, before or after):
break
else:
raise ValueError("Middleware %r not found" % (before or after))
if before:
self.middleware.insert(i, middleware)
else:
self.middleware.insert(i + 1, middleware)
else:
self.middleware.append(middleware)
self.actor_options |= middleware.actor_options
for actor_name in self.get_declared_actors():
middleware.after_declare_actor(self, actor_name)
for queue_name in self.get_declared_queues():
middleware.after_declare_queue(self, queue_name)
for queue_name in self.get_declared_delay_queues():
middleware.after_declare_delay_queue(self, queue_name) | python | def add_middleware(self, middleware, *, before=None, after=None):
"""Add a middleware object to this broker. The middleware is
appended to the end of the middleware list by default.
You can specify another middleware (by class) as a reference
point for where the new middleware should be added.
Parameters:
middleware(Middleware): The middleware.
before(type): Add this middleware before a specific one.
after(type): Add this middleware after a specific one.
Raises:
ValueError: When either ``before`` or ``after`` refer to a
middleware that hasn't been registered yet.
"""
assert not (before and after), \
"provide either 'before' or 'after', but not both"
if before or after:
for i, m in enumerate(self.middleware): # noqa
if isinstance(m, before or after):
break
else:
raise ValueError("Middleware %r not found" % (before or after))
if before:
self.middleware.insert(i, middleware)
else:
self.middleware.insert(i + 1, middleware)
else:
self.middleware.append(middleware)
self.actor_options |= middleware.actor_options
for actor_name in self.get_declared_actors():
middleware.after_declare_actor(self, actor_name)
for queue_name in self.get_declared_queues():
middleware.after_declare_queue(self, queue_name)
for queue_name in self.get_declared_delay_queues():
middleware.after_declare_delay_queue(self, queue_name) | [
"def",
"add_middleware",
"(",
"self",
",",
"middleware",
",",
"*",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
")",
":",
"assert",
"not",
"(",
"before",
"and",
"after",
")",
",",
"\"provide either 'before' or 'after', but not both\"",
"if",
"before",
"or",
"after",
":",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"self",
".",
"middleware",
")",
":",
"# noqa",
"if",
"isinstance",
"(",
"m",
",",
"before",
"or",
"after",
")",
":",
"break",
"else",
":",
"raise",
"ValueError",
"(",
"\"Middleware %r not found\"",
"%",
"(",
"before",
"or",
"after",
")",
")",
"if",
"before",
":",
"self",
".",
"middleware",
".",
"insert",
"(",
"i",
",",
"middleware",
")",
"else",
":",
"self",
".",
"middleware",
".",
"insert",
"(",
"i",
"+",
"1",
",",
"middleware",
")",
"else",
":",
"self",
".",
"middleware",
".",
"append",
"(",
"middleware",
")",
"self",
".",
"actor_options",
"|=",
"middleware",
".",
"actor_options",
"for",
"actor_name",
"in",
"self",
".",
"get_declared_actors",
"(",
")",
":",
"middleware",
".",
"after_declare_actor",
"(",
"self",
",",
"actor_name",
")",
"for",
"queue_name",
"in",
"self",
".",
"get_declared_queues",
"(",
")",
":",
"middleware",
".",
"after_declare_queue",
"(",
"self",
",",
"queue_name",
")",
"for",
"queue_name",
"in",
"self",
".",
"get_declared_delay_queues",
"(",
")",
":",
"middleware",
".",
"after_declare_delay_queue",
"(",
"self",
",",
"queue_name",
")"
] | Add a middleware object to this broker. The middleware is
appended to the end of the middleware list by default.
You can specify another middleware (by class) as a reference
point for where the new middleware should be added.
Parameters:
middleware(Middleware): The middleware.
before(type): Add this middleware before a specific one.
after(type): Add this middleware after a specific one.
Raises:
ValueError: When either ``before`` or ``after`` refer to a
middleware that hasn't been registered yet. | [
"Add",
"a",
"middleware",
"object",
"to",
"this",
"broker",
".",
"The",
"middleware",
"is",
"appended",
"to",
"the",
"end",
"of",
"the",
"middleware",
"list",
"by",
"default",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/broker.py#L102-L144 |
227,238 | Bogdanp/dramatiq | dramatiq/broker.py | Broker.declare_actor | def declare_actor(self, actor): # pragma: no cover
"""Declare a new actor on this broker. Declaring an Actor
twice replaces the first actor with the second by name.
Parameters:
actor(Actor): The actor being declared.
"""
self.emit_before("declare_actor", actor)
self.declare_queue(actor.queue_name)
self.actors[actor.actor_name] = actor
self.emit_after("declare_actor", actor) | python | def declare_actor(self, actor): # pragma: no cover
"""Declare a new actor on this broker. Declaring an Actor
twice replaces the first actor with the second by name.
Parameters:
actor(Actor): The actor being declared.
"""
self.emit_before("declare_actor", actor)
self.declare_queue(actor.queue_name)
self.actors[actor.actor_name] = actor
self.emit_after("declare_actor", actor) | [
"def",
"declare_actor",
"(",
"self",
",",
"actor",
")",
":",
"# pragma: no cover",
"self",
".",
"emit_before",
"(",
"\"declare_actor\"",
",",
"actor",
")",
"self",
".",
"declare_queue",
"(",
"actor",
".",
"queue_name",
")",
"self",
".",
"actors",
"[",
"actor",
".",
"actor_name",
"]",
"=",
"actor",
"self",
".",
"emit_after",
"(",
"\"declare_actor\"",
",",
"actor",
")"
] | Declare a new actor on this broker. Declaring an Actor
twice replaces the first actor with the second by name.
Parameters:
actor(Actor): The actor being declared. | [
"Declare",
"a",
"new",
"actor",
"on",
"this",
"broker",
".",
"Declaring",
"an",
"Actor",
"twice",
"replaces",
"the",
"first",
"actor",
"with",
"the",
"second",
"by",
"name",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/broker.py#L166-L176 |
227,239 | Bogdanp/dramatiq | dramatiq/brokers/rabbitmq.py | URLRabbitmqBroker | def URLRabbitmqBroker(url, *, middleware=None):
"""Alias for the RabbitMQ broker that takes a connection URL as a
positional argument.
Parameters:
url(str): A connection string.
middleware(list[Middleware]): The middleware to add to this
broker.
"""
warnings.warn(
"Use RabbitmqBroker with the 'url' parameter instead of URLRabbitmqBroker.",
DeprecationWarning, stacklevel=2,
)
return RabbitmqBroker(url=url, middleware=middleware) | python | def URLRabbitmqBroker(url, *, middleware=None):
"""Alias for the RabbitMQ broker that takes a connection URL as a
positional argument.
Parameters:
url(str): A connection string.
middleware(list[Middleware]): The middleware to add to this
broker.
"""
warnings.warn(
"Use RabbitmqBroker with the 'url' parameter instead of URLRabbitmqBroker.",
DeprecationWarning, stacklevel=2,
)
return RabbitmqBroker(url=url, middleware=middleware) | [
"def",
"URLRabbitmqBroker",
"(",
"url",
",",
"*",
",",
"middleware",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use RabbitmqBroker with the 'url' parameter instead of URLRabbitmqBroker.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"return",
"RabbitmqBroker",
"(",
"url",
"=",
"url",
",",
"middleware",
"=",
"middleware",
")"
] | Alias for the RabbitMQ broker that takes a connection URL as a
positional argument.
Parameters:
url(str): A connection string.
middleware(list[Middleware]): The middleware to add to this
broker. | [
"Alias",
"for",
"the",
"RabbitMQ",
"broker",
"that",
"takes",
"a",
"connection",
"URL",
"as",
"a",
"positional",
"argument",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/brokers/rabbitmq.py#L387-L400 |
227,240 | Bogdanp/dramatiq | dramatiq/brokers/rabbitmq.py | RabbitmqBroker.close | def close(self):
"""Close all open RabbitMQ connections.
"""
# The main thread may keep connections open for a long time
# w/o publishing heartbeats, which means that they'll end up
# being closed by the time the broker is closed. When that
# happens, pika logs a bunch of scary stuff so we want to
# filter that out.
logging_filter = _IgnoreScaryLogs()
logging.getLogger("pika.adapters.base_connection").addFilter(logging_filter)
logging.getLogger("pika.adapters.blocking_connection").addFilter(logging_filter)
self.logger.debug("Closing channels and connections...")
for channel_or_conn in chain(self.channels, self.connections):
try:
channel_or_conn.close()
except pika.exceptions.AMQPError:
pass
except Exception: # pragma: no cover
self.logger.debug("Encountered an error while closing %r.", channel_or_conn, exc_info=True)
self.logger.debug("Channels and connections closed.") | python | def close(self):
"""Close all open RabbitMQ connections.
"""
# The main thread may keep connections open for a long time
# w/o publishing heartbeats, which means that they'll end up
# being closed by the time the broker is closed. When that
# happens, pika logs a bunch of scary stuff so we want to
# filter that out.
logging_filter = _IgnoreScaryLogs()
logging.getLogger("pika.adapters.base_connection").addFilter(logging_filter)
logging.getLogger("pika.adapters.blocking_connection").addFilter(logging_filter)
self.logger.debug("Closing channels and connections...")
for channel_or_conn in chain(self.channels, self.connections):
try:
channel_or_conn.close()
except pika.exceptions.AMQPError:
pass
except Exception: # pragma: no cover
self.logger.debug("Encountered an error while closing %r.", channel_or_conn, exc_info=True)
self.logger.debug("Channels and connections closed.") | [
"def",
"close",
"(",
"self",
")",
":",
"# The main thread may keep connections open for a long time",
"# w/o publishing heartbeats, which means that they'll end up",
"# being closed by the time the broker is closed. When that",
"# happens, pika logs a bunch of scary stuff so we want to",
"# filter that out.",
"logging_filter",
"=",
"_IgnoreScaryLogs",
"(",
")",
"logging",
".",
"getLogger",
"(",
"\"pika.adapters.base_connection\"",
")",
".",
"addFilter",
"(",
"logging_filter",
")",
"logging",
".",
"getLogger",
"(",
"\"pika.adapters.blocking_connection\"",
")",
".",
"addFilter",
"(",
"logging_filter",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Closing channels and connections...\"",
")",
"for",
"channel_or_conn",
"in",
"chain",
"(",
"self",
".",
"channels",
",",
"self",
".",
"connections",
")",
":",
"try",
":",
"channel_or_conn",
".",
"close",
"(",
")",
"except",
"pika",
".",
"exceptions",
".",
"AMQPError",
":",
"pass",
"except",
"Exception",
":",
"# pragma: no cover",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Encountered an error while closing %r.\"",
",",
"channel_or_conn",
",",
"exc_info",
"=",
"True",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Channels and connections closed.\"",
")"
] | Close all open RabbitMQ connections. | [
"Close",
"all",
"open",
"RabbitMQ",
"connections",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/brokers/rabbitmq.py#L147-L168 |
227,241 | Bogdanp/dramatiq | dramatiq/brokers/rabbitmq.py | RabbitmqBroker.declare_queue | def declare_queue(self, queue_name):
"""Declare a queue. Has no effect if a queue with the given
name already exists.
Parameters:
queue_name(str): The name of the new queue.
Raises:
ConnectionClosed: If the underlying channel or connection
has been closed.
"""
attempts = 1
while True:
try:
if queue_name not in self.queues:
self.emit_before("declare_queue", queue_name)
self._declare_queue(queue_name)
self.queues.add(queue_name)
self.emit_after("declare_queue", queue_name)
delayed_name = dq_name(queue_name)
self._declare_dq_queue(queue_name)
self.delay_queues.add(delayed_name)
self.emit_after("declare_delay_queue", delayed_name)
self._declare_xq_queue(queue_name)
break
except (pika.exceptions.AMQPConnectionError,
pika.exceptions.AMQPChannelError) as e: # pragma: no cover
# Delete the channel and the connection so that the next
# caller may initiate new ones of each.
del self.channel
del self.connection
attempts += 1
if attempts > MAX_DECLARE_ATTEMPTS:
raise ConnectionClosed(e) from None
self.logger.debug(
"Retrying declare due to closed connection. [%d/%d]",
attempts, MAX_DECLARE_ATTEMPTS,
) | python | def declare_queue(self, queue_name):
"""Declare a queue. Has no effect if a queue with the given
name already exists.
Parameters:
queue_name(str): The name of the new queue.
Raises:
ConnectionClosed: If the underlying channel or connection
has been closed.
"""
attempts = 1
while True:
try:
if queue_name not in self.queues:
self.emit_before("declare_queue", queue_name)
self._declare_queue(queue_name)
self.queues.add(queue_name)
self.emit_after("declare_queue", queue_name)
delayed_name = dq_name(queue_name)
self._declare_dq_queue(queue_name)
self.delay_queues.add(delayed_name)
self.emit_after("declare_delay_queue", delayed_name)
self._declare_xq_queue(queue_name)
break
except (pika.exceptions.AMQPConnectionError,
pika.exceptions.AMQPChannelError) as e: # pragma: no cover
# Delete the channel and the connection so that the next
# caller may initiate new ones of each.
del self.channel
del self.connection
attempts += 1
if attempts > MAX_DECLARE_ATTEMPTS:
raise ConnectionClosed(e) from None
self.logger.debug(
"Retrying declare due to closed connection. [%d/%d]",
attempts, MAX_DECLARE_ATTEMPTS,
) | [
"def",
"declare_queue",
"(",
"self",
",",
"queue_name",
")",
":",
"attempts",
"=",
"1",
"while",
"True",
":",
"try",
":",
"if",
"queue_name",
"not",
"in",
"self",
".",
"queues",
":",
"self",
".",
"emit_before",
"(",
"\"declare_queue\"",
",",
"queue_name",
")",
"self",
".",
"_declare_queue",
"(",
"queue_name",
")",
"self",
".",
"queues",
".",
"add",
"(",
"queue_name",
")",
"self",
".",
"emit_after",
"(",
"\"declare_queue\"",
",",
"queue_name",
")",
"delayed_name",
"=",
"dq_name",
"(",
"queue_name",
")",
"self",
".",
"_declare_dq_queue",
"(",
"queue_name",
")",
"self",
".",
"delay_queues",
".",
"add",
"(",
"delayed_name",
")",
"self",
".",
"emit_after",
"(",
"\"declare_delay_queue\"",
",",
"delayed_name",
")",
"self",
".",
"_declare_xq_queue",
"(",
"queue_name",
")",
"break",
"except",
"(",
"pika",
".",
"exceptions",
".",
"AMQPConnectionError",
",",
"pika",
".",
"exceptions",
".",
"AMQPChannelError",
")",
"as",
"e",
":",
"# pragma: no cover",
"# Delete the channel and the connection so that the next",
"# caller may initiate new ones of each.",
"del",
"self",
".",
"channel",
"del",
"self",
".",
"connection",
"attempts",
"+=",
"1",
"if",
"attempts",
">",
"MAX_DECLARE_ATTEMPTS",
":",
"raise",
"ConnectionClosed",
"(",
"e",
")",
"from",
"None",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Retrying declare due to closed connection. [%d/%d]\"",
",",
"attempts",
",",
"MAX_DECLARE_ATTEMPTS",
",",
")"
] | Declare a queue. Has no effect if a queue with the given
name already exists.
Parameters:
queue_name(str): The name of the new queue.
Raises:
ConnectionClosed: If the underlying channel or connection
has been closed. | [
"Declare",
"a",
"queue",
".",
"Has",
"no",
"effect",
"if",
"a",
"queue",
"with",
"the",
"given",
"name",
"already",
"exists",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/brokers/rabbitmq.py#L183-L224 |
227,242 | Bogdanp/dramatiq | dramatiq/brokers/rabbitmq.py | RabbitmqBroker.get_queue_message_counts | def get_queue_message_counts(self, queue_name):
"""Get the number of messages in a queue. This method is only
meant to be used in unit and integration tests.
Parameters:
queue_name(str): The queue whose message counts to get.
Returns:
tuple: A triple representing the number of messages in the
queue, its delayed queue and its dead letter queue.
"""
queue_response = self._declare_queue(queue_name)
dq_queue_response = self._declare_dq_queue(queue_name)
xq_queue_response = self._declare_xq_queue(queue_name)
return (
queue_response.method.message_count,
dq_queue_response.method.message_count,
xq_queue_response.method.message_count,
) | python | def get_queue_message_counts(self, queue_name):
"""Get the number of messages in a queue. This method is only
meant to be used in unit and integration tests.
Parameters:
queue_name(str): The queue whose message counts to get.
Returns:
tuple: A triple representing the number of messages in the
queue, its delayed queue and its dead letter queue.
"""
queue_response = self._declare_queue(queue_name)
dq_queue_response = self._declare_dq_queue(queue_name)
xq_queue_response = self._declare_xq_queue(queue_name)
return (
queue_response.method.message_count,
dq_queue_response.method.message_count,
xq_queue_response.method.message_count,
) | [
"def",
"get_queue_message_counts",
"(",
"self",
",",
"queue_name",
")",
":",
"queue_response",
"=",
"self",
".",
"_declare_queue",
"(",
"queue_name",
")",
"dq_queue_response",
"=",
"self",
".",
"_declare_dq_queue",
"(",
"queue_name",
")",
"xq_queue_response",
"=",
"self",
".",
"_declare_xq_queue",
"(",
"queue_name",
")",
"return",
"(",
"queue_response",
".",
"method",
".",
"message_count",
",",
"dq_queue_response",
".",
"method",
".",
"message_count",
",",
"xq_queue_response",
".",
"method",
".",
"message_count",
",",
")"
] | Get the number of messages in a queue. This method is only
meant to be used in unit and integration tests.
Parameters:
queue_name(str): The queue whose message counts to get.
Returns:
tuple: A triple representing the number of messages in the
queue, its delayed queue and its dead letter queue. | [
"Get",
"the",
"number",
"of",
"messages",
"in",
"a",
"queue",
".",
"This",
"method",
"is",
"only",
"meant",
"to",
"be",
"used",
"in",
"unit",
"and",
"integration",
"tests",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/brokers/rabbitmq.py#L318-L336 |
227,243 | Bogdanp/dramatiq | dramatiq/rate_limits/barrier.py | Barrier.create | def create(self, parties):
"""Create the barrier for the given number of parties.
Parameters:
parties(int): The number of parties to wait for.
Returns:
bool: Whether or not the new barrier was successfully created.
"""
assert parties > 0, "parties must be a positive integer."
return self.backend.add(self.key, parties, self.ttl) | python | def create(self, parties):
"""Create the barrier for the given number of parties.
Parameters:
parties(int): The number of parties to wait for.
Returns:
bool: Whether or not the new barrier was successfully created.
"""
assert parties > 0, "parties must be a positive integer."
return self.backend.add(self.key, parties, self.ttl) | [
"def",
"create",
"(",
"self",
",",
"parties",
")",
":",
"assert",
"parties",
">",
"0",
",",
"\"parties must be a positive integer.\"",
"return",
"self",
".",
"backend",
".",
"add",
"(",
"self",
".",
"key",
",",
"parties",
",",
"self",
".",
"ttl",
")"
] | Create the barrier for the given number of parties.
Parameters:
parties(int): The number of parties to wait for.
Returns:
bool: Whether or not the new barrier was successfully created. | [
"Create",
"the",
"barrier",
"for",
"the",
"given",
"number",
"of",
"parties",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/rate_limits/barrier.py#L50-L60 |
227,244 | Bogdanp/dramatiq | dramatiq/rate_limits/barrier.py | Barrier.wait | def wait(self, *, block=True, timeout=None):
"""Signal that a party has reached the barrier.
Warning:
Barrier blocking is currently only supported by the stub and
Redis backends.
Warning:
Re-using keys between blocking calls may lead to undefined
behaviour. Make sure your barrier keys are always unique
(use a UUID).
Parameters:
block(bool): Whether or not to block while waiting for the
other parties.
timeout(int): The maximum number of milliseconds to wait for
the barrier to be cleared.
Returns:
bool: Whether or not the barrier has been reached by all parties.
"""
cleared = not self.backend.decr(self.key, 1, 1, self.ttl)
if cleared:
self.backend.wait_notify(self.key_events, self.ttl)
return True
if block:
return self.backend.wait(self.key_events, timeout)
return False | python | def wait(self, *, block=True, timeout=None):
"""Signal that a party has reached the barrier.
Warning:
Barrier blocking is currently only supported by the stub and
Redis backends.
Warning:
Re-using keys between blocking calls may lead to undefined
behaviour. Make sure your barrier keys are always unique
(use a UUID).
Parameters:
block(bool): Whether or not to block while waiting for the
other parties.
timeout(int): The maximum number of milliseconds to wait for
the barrier to be cleared.
Returns:
bool: Whether or not the barrier has been reached by all parties.
"""
cleared = not self.backend.decr(self.key, 1, 1, self.ttl)
if cleared:
self.backend.wait_notify(self.key_events, self.ttl)
return True
if block:
return self.backend.wait(self.key_events, timeout)
return False | [
"def",
"wait",
"(",
"self",
",",
"*",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"cleared",
"=",
"not",
"self",
".",
"backend",
".",
"decr",
"(",
"self",
".",
"key",
",",
"1",
",",
"1",
",",
"self",
".",
"ttl",
")",
"if",
"cleared",
":",
"self",
".",
"backend",
".",
"wait_notify",
"(",
"self",
".",
"key_events",
",",
"self",
".",
"ttl",
")",
"return",
"True",
"if",
"block",
":",
"return",
"self",
".",
"backend",
".",
"wait",
"(",
"self",
".",
"key_events",
",",
"timeout",
")",
"return",
"False"
] | Signal that a party has reached the barrier.
Warning:
Barrier blocking is currently only supported by the stub and
Redis backends.
Warning:
Re-using keys between blocking calls may lead to undefined
behaviour. Make sure your barrier keys are always unique
(use a UUID).
Parameters:
block(bool): Whether or not to block while waiting for the
other parties.
timeout(int): The maximum number of milliseconds to wait for
the barrier to be cleared.
Returns:
bool: Whether or not the barrier has been reached by all parties. | [
"Signal",
"that",
"a",
"party",
"has",
"reached",
"the",
"barrier",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/rate_limits/barrier.py#L62-L91 |
227,245 | Bogdanp/dramatiq | dramatiq/middleware/threading.py | raise_thread_exception | def raise_thread_exception(thread_id, exception):
"""Raise an exception in a thread.
Currently, this is only available on CPython.
Note:
This works by setting an async exception in the thread. This means
that the exception will only get called the next time that thread
acquires the GIL. Concretely, this means that this middleware can't
cancel system calls.
"""
if current_platform == "CPython":
_raise_thread_exception_cpython(thread_id, exception)
else:
message = "Setting thread exceptions (%s) is not supported for your current platform (%r)."
exctype = (exception if inspect.isclass(exception) else type(exception)).__name__
logger.critical(message, exctype, current_platform) | python | def raise_thread_exception(thread_id, exception):
"""Raise an exception in a thread.
Currently, this is only available on CPython.
Note:
This works by setting an async exception in the thread. This means
that the exception will only get called the next time that thread
acquires the GIL. Concretely, this means that this middleware can't
cancel system calls.
"""
if current_platform == "CPython":
_raise_thread_exception_cpython(thread_id, exception)
else:
message = "Setting thread exceptions (%s) is not supported for your current platform (%r)."
exctype = (exception if inspect.isclass(exception) else type(exception)).__name__
logger.critical(message, exctype, current_platform) | [
"def",
"raise_thread_exception",
"(",
"thread_id",
",",
"exception",
")",
":",
"if",
"current_platform",
"==",
"\"CPython\"",
":",
"_raise_thread_exception_cpython",
"(",
"thread_id",
",",
"exception",
")",
"else",
":",
"message",
"=",
"\"Setting thread exceptions (%s) is not supported for your current platform (%r).\"",
"exctype",
"=",
"(",
"exception",
"if",
"inspect",
".",
"isclass",
"(",
"exception",
")",
"else",
"type",
"(",
"exception",
")",
")",
".",
"__name__",
"logger",
".",
"critical",
"(",
"message",
",",
"exctype",
",",
"current_platform",
")"
] | Raise an exception in a thread.
Currently, this is only available on CPython.
Note:
This works by setting an async exception in the thread. This means
that the exception will only get called the next time that thread
acquires the GIL. Concretely, this means that this middleware can't
cancel system calls. | [
"Raise",
"an",
"exception",
"in",
"a",
"thread",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/middleware/threading.py#L43-L59 |
227,246 | Bogdanp/dramatiq | dramatiq/watcher.py | setup_file_watcher | def setup_file_watcher(path, use_polling=False):
"""Sets up a background thread that watches for source changes and
automatically sends SIGHUP to the current process whenever a file
changes.
"""
if use_polling:
observer_class = watchdog.observers.polling.PollingObserver
else:
observer_class = EVENTED_OBSERVER
file_event_handler = _SourceChangesHandler(patterns=["*.py"])
file_watcher = observer_class()
file_watcher.schedule(file_event_handler, path, recursive=True)
file_watcher.start()
return file_watcher | python | def setup_file_watcher(path, use_polling=False):
"""Sets up a background thread that watches for source changes and
automatically sends SIGHUP to the current process whenever a file
changes.
"""
if use_polling:
observer_class = watchdog.observers.polling.PollingObserver
else:
observer_class = EVENTED_OBSERVER
file_event_handler = _SourceChangesHandler(patterns=["*.py"])
file_watcher = observer_class()
file_watcher.schedule(file_event_handler, path, recursive=True)
file_watcher.start()
return file_watcher | [
"def",
"setup_file_watcher",
"(",
"path",
",",
"use_polling",
"=",
"False",
")",
":",
"if",
"use_polling",
":",
"observer_class",
"=",
"watchdog",
".",
"observers",
".",
"polling",
".",
"PollingObserver",
"else",
":",
"observer_class",
"=",
"EVENTED_OBSERVER",
"file_event_handler",
"=",
"_SourceChangesHandler",
"(",
"patterns",
"=",
"[",
"\"*.py\"",
"]",
")",
"file_watcher",
"=",
"observer_class",
"(",
")",
"file_watcher",
".",
"schedule",
"(",
"file_event_handler",
",",
"path",
",",
"recursive",
"=",
"True",
")",
"file_watcher",
".",
"start",
"(",
")",
"return",
"file_watcher"
] | Sets up a background thread that watches for source changes and
automatically sends SIGHUP to the current process whenever a file
changes. | [
"Sets",
"up",
"a",
"background",
"thread",
"that",
"watches",
"for",
"source",
"changes",
"and",
"automatically",
"sends",
"SIGHUP",
"to",
"the",
"current",
"process",
"whenever",
"a",
"file",
"changes",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/watcher.py#L16-L30 |
227,247 | Bogdanp/dramatiq | dramatiq/brokers/stub.py | StubBroker.declare_queue | def declare_queue(self, queue_name):
"""Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue.
"""
if queue_name not in self.queues:
self.emit_before("declare_queue", queue_name)
self.queues[queue_name] = Queue()
self.emit_after("declare_queue", queue_name)
delayed_name = dq_name(queue_name)
self.queues[delayed_name] = Queue()
self.delay_queues.add(delayed_name)
self.emit_after("declare_delay_queue", delayed_name) | python | def declare_queue(self, queue_name):
"""Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue.
"""
if queue_name not in self.queues:
self.emit_before("declare_queue", queue_name)
self.queues[queue_name] = Queue()
self.emit_after("declare_queue", queue_name)
delayed_name = dq_name(queue_name)
self.queues[delayed_name] = Queue()
self.delay_queues.add(delayed_name)
self.emit_after("declare_delay_queue", delayed_name) | [
"def",
"declare_queue",
"(",
"self",
",",
"queue_name",
")",
":",
"if",
"queue_name",
"not",
"in",
"self",
".",
"queues",
":",
"self",
".",
"emit_before",
"(",
"\"declare_queue\"",
",",
"queue_name",
")",
"self",
".",
"queues",
"[",
"queue_name",
"]",
"=",
"Queue",
"(",
")",
"self",
".",
"emit_after",
"(",
"\"declare_queue\"",
",",
"queue_name",
")",
"delayed_name",
"=",
"dq_name",
"(",
"queue_name",
")",
"self",
".",
"queues",
"[",
"delayed_name",
"]",
"=",
"Queue",
"(",
")",
"self",
".",
"delay_queues",
".",
"add",
"(",
"delayed_name",
")",
"self",
".",
"emit_after",
"(",
"\"declare_delay_queue\"",
",",
"delayed_name",
")"
] | Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue. | [
"Declare",
"a",
"queue",
".",
"Has",
"no",
"effect",
"if",
"a",
"queue",
"with",
"the",
"given",
"name",
"has",
"already",
"been",
"declared",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/brokers/stub.py#L66-L81 |
227,248 | Bogdanp/dramatiq | dramatiq/brokers/stub.py | StubBroker.flush_all | def flush_all(self):
"""Drop all messages from all declared queues.
"""
for queue_name in chain(self.queues, self.delay_queues):
self.flush(queue_name) | python | def flush_all(self):
"""Drop all messages from all declared queues.
"""
for queue_name in chain(self.queues, self.delay_queues):
self.flush(queue_name) | [
"def",
"flush_all",
"(",
"self",
")",
":",
"for",
"queue_name",
"in",
"chain",
"(",
"self",
".",
"queues",
",",
"self",
".",
"delay_queues",
")",
":",
"self",
".",
"flush",
"(",
"queue_name",
")"
] | Drop all messages from all declared queues. | [
"Drop",
"all",
"messages",
"from",
"all",
"declared",
"queues",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/brokers/stub.py#L123-L127 |
227,249 | Bogdanp/dramatiq | dramatiq/composition.py | pipeline.run | def run(self, *, delay=None):
"""Run this pipeline.
Parameters:
delay(int): The minimum amount of time, in milliseconds, the
pipeline should be delayed by.
Returns:
pipeline: Itself.
"""
self.broker.enqueue(self.messages[0], delay=delay)
return self | python | def run(self, *, delay=None):
"""Run this pipeline.
Parameters:
delay(int): The minimum amount of time, in milliseconds, the
pipeline should be delayed by.
Returns:
pipeline: Itself.
"""
self.broker.enqueue(self.messages[0], delay=delay)
return self | [
"def",
"run",
"(",
"self",
",",
"*",
",",
"delay",
"=",
"None",
")",
":",
"self",
".",
"broker",
".",
"enqueue",
"(",
"self",
".",
"messages",
"[",
"0",
"]",
",",
"delay",
"=",
"delay",
")",
"return",
"self"
] | Run this pipeline.
Parameters:
delay(int): The minimum amount of time, in milliseconds, the
pipeline should be delayed by.
Returns:
pipeline: Itself. | [
"Run",
"this",
"pipeline",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L101-L112 |
227,250 | Bogdanp/dramatiq | dramatiq/composition.py | pipeline.get_result | def get_result(self, *, block=False, timeout=None):
"""Get the result of this pipeline.
Pipeline results are represented by the result of the last
message in the chain.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
object: The result.
"""
return self.messages[-1].get_result(block=block, timeout=timeout) | python | def get_result(self, *, block=False, timeout=None):
"""Get the result of this pipeline.
Pipeline results are represented by the result of the last
message in the chain.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
object: The result.
"""
return self.messages[-1].get_result(block=block, timeout=timeout) | [
"def",
"get_result",
"(",
"self",
",",
"*",
",",
"block",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"messages",
"[",
"-",
"1",
"]",
".",
"get_result",
"(",
"block",
"=",
"block",
",",
"timeout",
"=",
"timeout",
")"
] | Get the result of this pipeline.
Pipeline results are represented by the result of the last
message in the chain.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
object: The result. | [
"Get",
"the",
"result",
"of",
"this",
"pipeline",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L114-L132 |
227,251 | Bogdanp/dramatiq | dramatiq/composition.py | pipeline.get_results | def get_results(self, *, block=False, timeout=None):
"""Get the results of each job in the pipeline.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
A result generator.
"""
deadline = None
if timeout:
deadline = time.monotonic() + timeout / 1000
for message in self.messages:
if deadline:
timeout = max(0, int((deadline - time.monotonic()) * 1000))
yield message.get_result(block=block, timeout=timeout) | python | def get_results(self, *, block=False, timeout=None):
"""Get the results of each job in the pipeline.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
A result generator.
"""
deadline = None
if timeout:
deadline = time.monotonic() + timeout / 1000
for message in self.messages:
if deadline:
timeout = max(0, int((deadline - time.monotonic()) * 1000))
yield message.get_result(block=block, timeout=timeout) | [
"def",
"get_results",
"(",
"self",
",",
"*",
",",
"block",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"deadline",
"=",
"None",
"if",
"timeout",
":",
"deadline",
"=",
"time",
".",
"monotonic",
"(",
")",
"+",
"timeout",
"/",
"1000",
"for",
"message",
"in",
"self",
".",
"messages",
":",
"if",
"deadline",
":",
"timeout",
"=",
"max",
"(",
"0",
",",
"int",
"(",
"(",
"deadline",
"-",
"time",
".",
"monotonic",
"(",
")",
")",
"*",
"1000",
")",
")",
"yield",
"message",
".",
"get_result",
"(",
"block",
"=",
"block",
",",
"timeout",
"=",
"timeout",
")"
] | Get the results of each job in the pipeline.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
A result generator. | [
"Get",
"the",
"results",
"of",
"each",
"job",
"in",
"the",
"pipeline",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L134-L157 |
227,252 | Bogdanp/dramatiq | dramatiq/composition.py | group.run | def run(self, *, delay=None):
"""Run the actors in this group.
Parameters:
delay(int): The minimum amount of time, in milliseconds,
each message in the group should be delayed by.
"""
for child in self.children:
if isinstance(child, (group, pipeline)):
child.run(delay=delay)
else:
self.broker.enqueue(child, delay=delay)
return self | python | def run(self, *, delay=None):
"""Run the actors in this group.
Parameters:
delay(int): The minimum amount of time, in milliseconds,
each message in the group should be delayed by.
"""
for child in self.children:
if isinstance(child, (group, pipeline)):
child.run(delay=delay)
else:
self.broker.enqueue(child, delay=delay)
return self | [
"def",
"run",
"(",
"self",
",",
"*",
",",
"delay",
"=",
"None",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"(",
"group",
",",
"pipeline",
")",
")",
":",
"child",
".",
"run",
"(",
"delay",
"=",
"delay",
")",
"else",
":",
"self",
".",
"broker",
".",
"enqueue",
"(",
"child",
",",
"delay",
"=",
"delay",
")",
"return",
"self"
] | Run the actors in this group.
Parameters:
delay(int): The minimum amount of time, in milliseconds,
each message in the group should be delayed by. | [
"Run",
"the",
"actors",
"in",
"this",
"group",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L220-L233 |
227,253 | Bogdanp/dramatiq | dramatiq/composition.py | group.get_results | def get_results(self, *, block=False, timeout=None):
"""Get the results of each job in the group.
Parameters:
block(bool): Whether or not to block until the results are stored.
timeout(int): The maximum amount of time, in milliseconds,
to wait for results when block is True. Defaults to 10
seconds.
Raises:
ResultMissing: When block is False and the results aren't set.
ResultTimeout: When waiting for results times out.
Returns:
A result generator.
"""
deadline = None
if timeout:
deadline = time.monotonic() + timeout / 1000
for child in self.children:
if deadline:
timeout = max(0, int((deadline - time.monotonic()) * 1000))
if isinstance(child, group):
yield list(child.get_results(block=block, timeout=timeout))
else:
yield child.get_result(block=block, timeout=timeout) | python | def get_results(self, *, block=False, timeout=None):
"""Get the results of each job in the group.
Parameters:
block(bool): Whether or not to block until the results are stored.
timeout(int): The maximum amount of time, in milliseconds,
to wait for results when block is True. Defaults to 10
seconds.
Raises:
ResultMissing: When block is False and the results aren't set.
ResultTimeout: When waiting for results times out.
Returns:
A result generator.
"""
deadline = None
if timeout:
deadline = time.monotonic() + timeout / 1000
for child in self.children:
if deadline:
timeout = max(0, int((deadline - time.monotonic()) * 1000))
if isinstance(child, group):
yield list(child.get_results(block=block, timeout=timeout))
else:
yield child.get_result(block=block, timeout=timeout) | [
"def",
"get_results",
"(",
"self",
",",
"*",
",",
"block",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"deadline",
"=",
"None",
"if",
"timeout",
":",
"deadline",
"=",
"time",
".",
"monotonic",
"(",
")",
"+",
"timeout",
"/",
"1000",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"deadline",
":",
"timeout",
"=",
"max",
"(",
"0",
",",
"int",
"(",
"(",
"deadline",
"-",
"time",
".",
"monotonic",
"(",
")",
")",
"*",
"1000",
")",
")",
"if",
"isinstance",
"(",
"child",
",",
"group",
")",
":",
"yield",
"list",
"(",
"child",
".",
"get_results",
"(",
"block",
"=",
"block",
",",
"timeout",
"=",
"timeout",
")",
")",
"else",
":",
"yield",
"child",
".",
"get_result",
"(",
"block",
"=",
"block",
",",
"timeout",
"=",
"timeout",
")"
] | Get the results of each job in the group.
Parameters:
block(bool): Whether or not to block until the results are stored.
timeout(int): The maximum amount of time, in milliseconds,
to wait for results when block is True. Defaults to 10
seconds.
Raises:
ResultMissing: When block is False and the results aren't set.
ResultTimeout: When waiting for results times out.
Returns:
A result generator. | [
"Get",
"the",
"results",
"of",
"each",
"job",
"in",
"the",
"group",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L235-L262 |
227,254 | Bogdanp/dramatiq | dramatiq/composition.py | group.wait | def wait(self, *, timeout=None):
"""Block until all the jobs in the group have finished or
until the timeout expires.
Parameters:
timeout(int): The maximum amount of time, in ms, to wait.
Defaults to 10 seconds.
"""
for _ in self.get_results(block=True, timeout=timeout): # pragma: no cover
pass | python | def wait(self, *, timeout=None):
"""Block until all the jobs in the group have finished or
until the timeout expires.
Parameters:
timeout(int): The maximum amount of time, in ms, to wait.
Defaults to 10 seconds.
"""
for _ in self.get_results(block=True, timeout=timeout): # pragma: no cover
pass | [
"def",
"wait",
"(",
"self",
",",
"*",
",",
"timeout",
"=",
"None",
")",
":",
"for",
"_",
"in",
"self",
".",
"get_results",
"(",
"block",
"=",
"True",
",",
"timeout",
"=",
"timeout",
")",
":",
"# pragma: no cover",
"pass"
] | Block until all the jobs in the group have finished or
until the timeout expires.
Parameters:
timeout(int): The maximum amount of time, in ms, to wait.
Defaults to 10 seconds. | [
"Block",
"until",
"all",
"the",
"jobs",
"in",
"the",
"group",
"have",
"finished",
"or",
"until",
"the",
"timeout",
"expires",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L264-L273 |
227,255 | Bogdanp/dramatiq | dramatiq/actor.py | actor | def actor(fn=None, *, actor_class=Actor, actor_name=None, queue_name="default", priority=0, broker=None, **options):
"""Declare an actor.
Examples:
>>> import dramatiq
>>> @dramatiq.actor
... def add(x, y):
... print(x + y)
...
>>> add
Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add')
>>> add(1, 2)
3
>>> add.send(1, 2)
Message(
queue_name='default',
actor_name='add',
args=(1, 2), kwargs={}, options={},
message_id='e0d27b45-7900-41da-bb97-553b8a081206',
message_timestamp=1497862448685)
Parameters:
fn(callable): The function to wrap.
actor_class(type): Type created by the decorator. Defaults to
:class:`Actor` but can be any callable as long as it returns an
actor and takes the same arguments as the :class:`Actor` class.
actor_name(str): The name of the actor.
queue_name(str): The name of the queue to use.
priority(int): The actor's global priority. If two tasks have
been pulled on a worker concurrently and one has a higher
priority than the other then it will be processed first.
Lower numbers represent higher priorities.
broker(Broker): The broker to use with this actor.
**options(dict): Arbitrary options that vary with the set of
middleware that you use. See ``get_broker().actor_options``.
Returns:
Actor: The decorated function.
"""
def decorator(fn):
nonlocal actor_name, broker
actor_name = actor_name or fn.__name__
if not _queue_name_re.fullmatch(queue_name):
raise ValueError(
"Queue names must start with a letter or an underscore followed "
"by any number of letters, digits, dashes or underscores."
)
broker = broker or get_broker()
invalid_options = set(options) - broker.actor_options
if invalid_options:
invalid_options_list = ", ".join(invalid_options)
raise ValueError((
"The following actor options are undefined: %s. "
"Did you forget to add a middleware to your Broker?"
) % invalid_options_list)
return actor_class(
fn, actor_name=actor_name, queue_name=queue_name,
priority=priority, broker=broker, options=options,
)
if fn is None:
return decorator
return decorator(fn) | python | def actor(fn=None, *, actor_class=Actor, actor_name=None, queue_name="default", priority=0, broker=None, **options):
"""Declare an actor.
Examples:
>>> import dramatiq
>>> @dramatiq.actor
... def add(x, y):
... print(x + y)
...
>>> add
Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add')
>>> add(1, 2)
3
>>> add.send(1, 2)
Message(
queue_name='default',
actor_name='add',
args=(1, 2), kwargs={}, options={},
message_id='e0d27b45-7900-41da-bb97-553b8a081206',
message_timestamp=1497862448685)
Parameters:
fn(callable): The function to wrap.
actor_class(type): Type created by the decorator. Defaults to
:class:`Actor` but can be any callable as long as it returns an
actor and takes the same arguments as the :class:`Actor` class.
actor_name(str): The name of the actor.
queue_name(str): The name of the queue to use.
priority(int): The actor's global priority. If two tasks have
been pulled on a worker concurrently and one has a higher
priority than the other then it will be processed first.
Lower numbers represent higher priorities.
broker(Broker): The broker to use with this actor.
**options(dict): Arbitrary options that vary with the set of
middleware that you use. See ``get_broker().actor_options``.
Returns:
Actor: The decorated function.
"""
def decorator(fn):
nonlocal actor_name, broker
actor_name = actor_name or fn.__name__
if not _queue_name_re.fullmatch(queue_name):
raise ValueError(
"Queue names must start with a letter or an underscore followed "
"by any number of letters, digits, dashes or underscores."
)
broker = broker or get_broker()
invalid_options = set(options) - broker.actor_options
if invalid_options:
invalid_options_list = ", ".join(invalid_options)
raise ValueError((
"The following actor options are undefined: %s. "
"Did you forget to add a middleware to your Broker?"
) % invalid_options_list)
return actor_class(
fn, actor_name=actor_name, queue_name=queue_name,
priority=priority, broker=broker, options=options,
)
if fn is None:
return decorator
return decorator(fn) | [
"def",
"actor",
"(",
"fn",
"=",
"None",
",",
"*",
",",
"actor_class",
"=",
"Actor",
",",
"actor_name",
"=",
"None",
",",
"queue_name",
"=",
"\"default\"",
",",
"priority",
"=",
"0",
",",
"broker",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"nonlocal",
"actor_name",
",",
"broker",
"actor_name",
"=",
"actor_name",
"or",
"fn",
".",
"__name__",
"if",
"not",
"_queue_name_re",
".",
"fullmatch",
"(",
"queue_name",
")",
":",
"raise",
"ValueError",
"(",
"\"Queue names must start with a letter or an underscore followed \"",
"\"by any number of letters, digits, dashes or underscores.\"",
")",
"broker",
"=",
"broker",
"or",
"get_broker",
"(",
")",
"invalid_options",
"=",
"set",
"(",
"options",
")",
"-",
"broker",
".",
"actor_options",
"if",
"invalid_options",
":",
"invalid_options_list",
"=",
"\", \"",
".",
"join",
"(",
"invalid_options",
")",
"raise",
"ValueError",
"(",
"(",
"\"The following actor options are undefined: %s. \"",
"\"Did you forget to add a middleware to your Broker?\"",
")",
"%",
"invalid_options_list",
")",
"return",
"actor_class",
"(",
"fn",
",",
"actor_name",
"=",
"actor_name",
",",
"queue_name",
"=",
"queue_name",
",",
"priority",
"=",
"priority",
",",
"broker",
"=",
"broker",
",",
"options",
"=",
"options",
",",
")",
"if",
"fn",
"is",
"None",
":",
"return",
"decorator",
"return",
"decorator",
"(",
"fn",
")"
] | Declare an actor.
Examples:
>>> import dramatiq
>>> @dramatiq.actor
... def add(x, y):
... print(x + y)
...
>>> add
Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add')
>>> add(1, 2)
3
>>> add.send(1, 2)
Message(
queue_name='default',
actor_name='add',
args=(1, 2), kwargs={}, options={},
message_id='e0d27b45-7900-41da-bb97-553b8a081206',
message_timestamp=1497862448685)
Parameters:
fn(callable): The function to wrap.
actor_class(type): Type created by the decorator. Defaults to
:class:`Actor` but can be any callable as long as it returns an
actor and takes the same arguments as the :class:`Actor` class.
actor_name(str): The name of the actor.
queue_name(str): The name of the queue to use.
priority(int): The actor's global priority. If two tasks have
been pulled on a worker concurrently and one has a higher
priority than the other then it will be processed first.
Lower numbers represent higher priorities.
broker(Broker): The broker to use with this actor.
**options(dict): Arbitrary options that vary with the set of
middleware that you use. See ``get_broker().actor_options``.
Returns:
Actor: The decorated function. | [
"Declare",
"an",
"actor",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L157-L225 |
227,256 | Bogdanp/dramatiq | dramatiq/actor.py | Actor.message | def message(self, *args, **kwargs):
"""Build a message. This method is useful if you want to
compose actors. See the actor composition documentation for
details.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Examples:
>>> (add.message(1, 2) | add.message(3))
pipeline([add(1, 2), add(3)])
Returns:
Message: A message that can be enqueued on a broker.
"""
return self.message_with_options(args=args, kwargs=kwargs) | python | def message(self, *args, **kwargs):
"""Build a message. This method is useful if you want to
compose actors. See the actor composition documentation for
details.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Examples:
>>> (add.message(1, 2) | add.message(3))
pipeline([add(1, 2), add(3)])
Returns:
Message: A message that can be enqueued on a broker.
"""
return self.message_with_options(args=args, kwargs=kwargs) | [
"def",
"message",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"message_with_options",
"(",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")"
] | Build a message. This method is useful if you want to
compose actors. See the actor composition documentation for
details.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Examples:
>>> (add.message(1, 2) | add.message(3))
pipeline([add(1, 2), add(3)])
Returns:
Message: A message that can be enqueued on a broker. | [
"Build",
"a",
"message",
".",
"This",
"method",
"is",
"useful",
"if",
"you",
"want",
"to",
"compose",
"actors",
".",
"See",
"the",
"actor",
"composition",
"documentation",
"for",
"details",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L54-L70 |
227,257 | Bogdanp/dramatiq | dramatiq/actor.py | Actor.message_with_options | def message_with_options(self, *, args=None, kwargs=None, **options):
"""Build a message with an arbitray set of processing options.
This method is useful if you want to compose actors. See the
actor composition documentation for details.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: A message that can be enqueued on a broker.
"""
for name in ["on_failure", "on_success"]:
callback = options.get(name)
if isinstance(callback, Actor):
options[name] = callback.actor_name
elif not isinstance(callback, (type(None), str)):
raise TypeError(name + " value must be an Actor")
return Message(
queue_name=self.queue_name,
actor_name=self.actor_name,
args=args or (), kwargs=kwargs or {},
options=options,
) | python | def message_with_options(self, *, args=None, kwargs=None, **options):
"""Build a message with an arbitray set of processing options.
This method is useful if you want to compose actors. See the
actor composition documentation for details.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: A message that can be enqueued on a broker.
"""
for name in ["on_failure", "on_success"]:
callback = options.get(name)
if isinstance(callback, Actor):
options[name] = callback.actor_name
elif not isinstance(callback, (type(None), str)):
raise TypeError(name + " value must be an Actor")
return Message(
queue_name=self.queue_name,
actor_name=self.actor_name,
args=args or (), kwargs=kwargs or {},
options=options,
) | [
"def",
"message_with_options",
"(",
"self",
",",
"*",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"for",
"name",
"in",
"[",
"\"on_failure\"",
",",
"\"on_success\"",
"]",
":",
"callback",
"=",
"options",
".",
"get",
"(",
"name",
")",
"if",
"isinstance",
"(",
"callback",
",",
"Actor",
")",
":",
"options",
"[",
"name",
"]",
"=",
"callback",
".",
"actor_name",
"elif",
"not",
"isinstance",
"(",
"callback",
",",
"(",
"type",
"(",
"None",
")",
",",
"str",
")",
")",
":",
"raise",
"TypeError",
"(",
"name",
"+",
"\" value must be an Actor\"",
")",
"return",
"Message",
"(",
"queue_name",
"=",
"self",
".",
"queue_name",
",",
"actor_name",
"=",
"self",
".",
"actor_name",
",",
"args",
"=",
"args",
"or",
"(",
")",
",",
"kwargs",
"=",
"kwargs",
"or",
"{",
"}",
",",
"options",
"=",
"options",
",",
")"
] | Build a message with an arbitray set of processing options.
This method is useful if you want to compose actors. See the
actor composition documentation for details.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: A message that can be enqueued on a broker. | [
"Build",
"a",
"message",
"with",
"an",
"arbitray",
"set",
"of",
"processing",
"options",
".",
"This",
"method",
"is",
"useful",
"if",
"you",
"want",
"to",
"compose",
"actors",
".",
"See",
"the",
"actor",
"composition",
"documentation",
"for",
"details",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L72-L99 |
227,258 | Bogdanp/dramatiq | dramatiq/actor.py | Actor.send | def send(self, *args, **kwargs):
"""Asynchronously send a message to this actor.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Returns:
Message: The enqueued message.
"""
return self.send_with_options(args=args, kwargs=kwargs) | python | def send(self, *args, **kwargs):
"""Asynchronously send a message to this actor.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Returns:
Message: The enqueued message.
"""
return self.send_with_options(args=args, kwargs=kwargs) | [
"def",
"send",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"send_with_options",
"(",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")"
] | Asynchronously send a message to this actor.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Returns:
Message: The enqueued message. | [
"Asynchronously",
"send",
"a",
"message",
"to",
"this",
"actor",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L101-L111 |
227,259 | Bogdanp/dramatiq | dramatiq/actor.py | Actor.send_with_options | def send_with_options(self, *, args=None, kwargs=None, delay=None, **options):
"""Asynchronously send a message to this actor, along with an
arbitrary set of processing options for the broker and
middleware.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
delay(int): The minimum amount of time, in milliseconds, the
message should be delayed by.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: The enqueued message.
"""
message = self.message_with_options(args=args, kwargs=kwargs, **options)
return self.broker.enqueue(message, delay=delay) | python | def send_with_options(self, *, args=None, kwargs=None, delay=None, **options):
"""Asynchronously send a message to this actor, along with an
arbitrary set of processing options for the broker and
middleware.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
delay(int): The minimum amount of time, in milliseconds, the
message should be delayed by.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: The enqueued message.
"""
message = self.message_with_options(args=args, kwargs=kwargs, **options)
return self.broker.enqueue(message, delay=delay) | [
"def",
"send_with_options",
"(",
"self",
",",
"*",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"delay",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"message",
"=",
"self",
".",
"message_with_options",
"(",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
",",
"*",
"*",
"options",
")",
"return",
"self",
".",
"broker",
".",
"enqueue",
"(",
"message",
",",
"delay",
"=",
"delay",
")"
] | Asynchronously send a message to this actor, along with an
arbitrary set of processing options for the broker and
middleware.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
delay(int): The minimum amount of time, in milliseconds, the
message should be delayed by.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: The enqueued message. | [
"Asynchronously",
"send",
"a",
"message",
"to",
"this",
"actor",
"along",
"with",
"an",
"arbitrary",
"set",
"of",
"processing",
"options",
"for",
"the",
"broker",
"and",
"middleware",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L113-L130 |
227,260 | Bogdanp/dramatiq | dramatiq/worker.py | Worker.start | def start(self):
"""Initialize the worker boot sequence and start up all the
worker threads.
"""
self.broker.emit_before("worker_boot", self)
worker_middleware = _WorkerMiddleware(self)
self.broker.add_middleware(worker_middleware)
for _ in range(self.worker_threads):
self._add_worker()
self.broker.emit_after("worker_boot", self) | python | def start(self):
"""Initialize the worker boot sequence and start up all the
worker threads.
"""
self.broker.emit_before("worker_boot", self)
worker_middleware = _WorkerMiddleware(self)
self.broker.add_middleware(worker_middleware)
for _ in range(self.worker_threads):
self._add_worker()
self.broker.emit_after("worker_boot", self) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"broker",
".",
"emit_before",
"(",
"\"worker_boot\"",
",",
"self",
")",
"worker_middleware",
"=",
"_WorkerMiddleware",
"(",
"self",
")",
"self",
".",
"broker",
".",
"add_middleware",
"(",
"worker_middleware",
")",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"worker_threads",
")",
":",
"self",
".",
"_add_worker",
"(",
")",
"self",
".",
"broker",
".",
"emit_after",
"(",
"\"worker_boot\"",
",",
"self",
")"
] | Initialize the worker boot sequence and start up all the
worker threads. | [
"Initialize",
"the",
"worker",
"boot",
"sequence",
"and",
"start",
"up",
"all",
"the",
"worker",
"threads",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L80-L91 |
227,261 | Bogdanp/dramatiq | dramatiq/worker.py | Worker.pause | def pause(self):
"""Pauses all the worker threads.
"""
for child in chain(self.consumers.values(), self.workers):
child.pause()
for child in chain(self.consumers.values(), self.workers):
child.paused_event.wait() | python | def pause(self):
"""Pauses all the worker threads.
"""
for child in chain(self.consumers.values(), self.workers):
child.pause()
for child in chain(self.consumers.values(), self.workers):
child.paused_event.wait() | [
"def",
"pause",
"(",
"self",
")",
":",
"for",
"child",
"in",
"chain",
"(",
"self",
".",
"consumers",
".",
"values",
"(",
")",
",",
"self",
".",
"workers",
")",
":",
"child",
".",
"pause",
"(",
")",
"for",
"child",
"in",
"chain",
"(",
"self",
".",
"consumers",
".",
"values",
"(",
")",
",",
"self",
".",
"workers",
")",
":",
"child",
".",
"paused_event",
".",
"wait",
"(",
")"
] | Pauses all the worker threads. | [
"Pauses",
"all",
"the",
"worker",
"threads",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L93-L100 |
227,262 | Bogdanp/dramatiq | dramatiq/worker.py | Worker.resume | def resume(self):
"""Resumes all the worker threads.
"""
for child in chain(self.consumers.values(), self.workers):
child.resume() | python | def resume(self):
"""Resumes all the worker threads.
"""
for child in chain(self.consumers.values(), self.workers):
child.resume() | [
"def",
"resume",
"(",
"self",
")",
":",
"for",
"child",
"in",
"chain",
"(",
"self",
".",
"consumers",
".",
"values",
"(",
")",
",",
"self",
".",
"workers",
")",
":",
"child",
".",
"resume",
"(",
")"
] | Resumes all the worker threads. | [
"Resumes",
"all",
"the",
"worker",
"threads",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L102-L106 |
227,263 | Bogdanp/dramatiq | dramatiq/worker.py | Worker.stop | def stop(self, timeout=600000):
"""Gracefully stop the Worker and all of its consumers and
workers.
Parameters:
timeout(int): The number of milliseconds to wait for
everything to shut down.
"""
self.broker.emit_before("worker_shutdown", self)
self.logger.info("Shutting down...")
# Stop workers before consumers. The consumers are kept alive
# during this process so that heartbeats keep being sent to
# the broker while workers finish their current tasks.
self.logger.debug("Stopping workers...")
for thread in self.workers:
thread.stop()
join_all(self.workers, timeout)
self.logger.debug("Workers stopped.")
self.logger.debug("Stopping consumers...")
for thread in self.consumers.values():
thread.stop()
join_all(self.consumers.values(), timeout)
self.logger.debug("Consumers stopped.")
self.logger.debug("Requeueing in-memory messages...")
messages_by_queue = defaultdict(list)
for _, message in iter_queue(self.work_queue):
messages_by_queue[message.queue_name].append(message)
for queue_name, messages in messages_by_queue.items():
try:
self.consumers[queue_name].requeue_messages(messages)
except ConnectionError:
self.logger.warning("Failed to requeue messages on queue %r.", queue_name, exc_info=True)
self.logger.debug("Done requeueing in-progress messages.")
self.logger.debug("Closing consumers...")
for consumer in self.consumers.values():
consumer.close()
self.logger.debug("Consumers closed.")
self.broker.emit_after("worker_shutdown", self)
self.logger.info("Worker has been shut down.") | python | def stop(self, timeout=600000):
"""Gracefully stop the Worker and all of its consumers and
workers.
Parameters:
timeout(int): The number of milliseconds to wait for
everything to shut down.
"""
self.broker.emit_before("worker_shutdown", self)
self.logger.info("Shutting down...")
# Stop workers before consumers. The consumers are kept alive
# during this process so that heartbeats keep being sent to
# the broker while workers finish their current tasks.
self.logger.debug("Stopping workers...")
for thread in self.workers:
thread.stop()
join_all(self.workers, timeout)
self.logger.debug("Workers stopped.")
self.logger.debug("Stopping consumers...")
for thread in self.consumers.values():
thread.stop()
join_all(self.consumers.values(), timeout)
self.logger.debug("Consumers stopped.")
self.logger.debug("Requeueing in-memory messages...")
messages_by_queue = defaultdict(list)
for _, message in iter_queue(self.work_queue):
messages_by_queue[message.queue_name].append(message)
for queue_name, messages in messages_by_queue.items():
try:
self.consumers[queue_name].requeue_messages(messages)
except ConnectionError:
self.logger.warning("Failed to requeue messages on queue %r.", queue_name, exc_info=True)
self.logger.debug("Done requeueing in-progress messages.")
self.logger.debug("Closing consumers...")
for consumer in self.consumers.values():
consumer.close()
self.logger.debug("Consumers closed.")
self.broker.emit_after("worker_shutdown", self)
self.logger.info("Worker has been shut down.") | [
"def",
"stop",
"(",
"self",
",",
"timeout",
"=",
"600000",
")",
":",
"self",
".",
"broker",
".",
"emit_before",
"(",
"\"worker_shutdown\"",
",",
"self",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Shutting down...\"",
")",
"# Stop workers before consumers. The consumers are kept alive",
"# during this process so that heartbeats keep being sent to",
"# the broker while workers finish their current tasks.",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Stopping workers...\"",
")",
"for",
"thread",
"in",
"self",
".",
"workers",
":",
"thread",
".",
"stop",
"(",
")",
"join_all",
"(",
"self",
".",
"workers",
",",
"timeout",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Workers stopped.\"",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Stopping consumers...\"",
")",
"for",
"thread",
"in",
"self",
".",
"consumers",
".",
"values",
"(",
")",
":",
"thread",
".",
"stop",
"(",
")",
"join_all",
"(",
"self",
".",
"consumers",
".",
"values",
"(",
")",
",",
"timeout",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Consumers stopped.\"",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Requeueing in-memory messages...\"",
")",
"messages_by_queue",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"_",
",",
"message",
"in",
"iter_queue",
"(",
"self",
".",
"work_queue",
")",
":",
"messages_by_queue",
"[",
"message",
".",
"queue_name",
"]",
".",
"append",
"(",
"message",
")",
"for",
"queue_name",
",",
"messages",
"in",
"messages_by_queue",
".",
"items",
"(",
")",
":",
"try",
":",
"self",
".",
"consumers",
"[",
"queue_name",
"]",
".",
"requeue_messages",
"(",
"messages",
")",
"except",
"ConnectionError",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Failed to requeue messages on queue %r.\"",
",",
"queue_name",
",",
"exc_info",
"=",
"True",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Done requeueing in-progress messages.\"",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Closing consumers...\"",
")",
"for",
"consumer",
"in",
"self",
".",
"consumers",
".",
"values",
"(",
")",
":",
"consumer",
".",
"close",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Consumers closed.\"",
")",
"self",
".",
"broker",
".",
"emit_after",
"(",
"\"worker_shutdown\"",
",",
"self",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Worker has been shut down.\"",
")"
] | Gracefully stop the Worker and all of its consumers and
workers.
Parameters:
timeout(int): The number of milliseconds to wait for
everything to shut down. | [
"Gracefully",
"stop",
"the",
"Worker",
"and",
"all",
"of",
"its",
"consumers",
"and",
"workers",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L108-L153 |
227,264 | Bogdanp/dramatiq | dramatiq/worker.py | Worker.join | def join(self):
"""Wait for this worker to complete its work in progress.
This method is useful when testing code.
"""
while True:
for consumer in self.consumers.values():
consumer.delay_queue.join()
self.work_queue.join()
# If nothing got put on the delay queues while we were
# joining on the work queue then it shoud be safe to exit.
# This could still miss stuff but the chances are slim.
for consumer in self.consumers.values():
if consumer.delay_queue.unfinished_tasks:
break
else:
if self.work_queue.unfinished_tasks:
continue
return | python | def join(self):
"""Wait for this worker to complete its work in progress.
This method is useful when testing code.
"""
while True:
for consumer in self.consumers.values():
consumer.delay_queue.join()
self.work_queue.join()
# If nothing got put on the delay queues while we were
# joining on the work queue then it shoud be safe to exit.
# This could still miss stuff but the chances are slim.
for consumer in self.consumers.values():
if consumer.delay_queue.unfinished_tasks:
break
else:
if self.work_queue.unfinished_tasks:
continue
return | [
"def",
"join",
"(",
"self",
")",
":",
"while",
"True",
":",
"for",
"consumer",
"in",
"self",
".",
"consumers",
".",
"values",
"(",
")",
":",
"consumer",
".",
"delay_queue",
".",
"join",
"(",
")",
"self",
".",
"work_queue",
".",
"join",
"(",
")",
"# If nothing got put on the delay queues while we were",
"# joining on the work queue then it shoud be safe to exit.",
"# This could still miss stuff but the chances are slim.",
"for",
"consumer",
"in",
"self",
".",
"consumers",
".",
"values",
"(",
")",
":",
"if",
"consumer",
".",
"delay_queue",
".",
"unfinished_tasks",
":",
"break",
"else",
":",
"if",
"self",
".",
"work_queue",
".",
"unfinished_tasks",
":",
"continue",
"return"
] | Wait for this worker to complete its work in progress.
This method is useful when testing code. | [
"Wait",
"for",
"this",
"worker",
"to",
"complete",
"its",
"work",
"in",
"progress",
".",
"This",
"method",
"is",
"useful",
"when",
"testing",
"code",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L155-L174 |
227,265 | Bogdanp/dramatiq | dramatiq/worker.py | _ConsumerThread.handle_delayed_messages | def handle_delayed_messages(self):
"""Enqueue any delayed messages whose eta has passed.
"""
for eta, message in iter_queue(self.delay_queue):
if eta > current_millis():
self.delay_queue.put((eta, message))
self.delay_queue.task_done()
break
queue_name = q_name(message.queue_name)
new_message = message.copy(queue_name=queue_name)
del new_message.options["eta"]
self.broker.enqueue(new_message)
self.post_process_message(message)
self.delay_queue.task_done() | python | def handle_delayed_messages(self):
"""Enqueue any delayed messages whose eta has passed.
"""
for eta, message in iter_queue(self.delay_queue):
if eta > current_millis():
self.delay_queue.put((eta, message))
self.delay_queue.task_done()
break
queue_name = q_name(message.queue_name)
new_message = message.copy(queue_name=queue_name)
del new_message.options["eta"]
self.broker.enqueue(new_message)
self.post_process_message(message)
self.delay_queue.task_done() | [
"def",
"handle_delayed_messages",
"(",
"self",
")",
":",
"for",
"eta",
",",
"message",
"in",
"iter_queue",
"(",
"self",
".",
"delay_queue",
")",
":",
"if",
"eta",
">",
"current_millis",
"(",
")",
":",
"self",
".",
"delay_queue",
".",
"put",
"(",
"(",
"eta",
",",
"message",
")",
")",
"self",
".",
"delay_queue",
".",
"task_done",
"(",
")",
"break",
"queue_name",
"=",
"q_name",
"(",
"message",
".",
"queue_name",
")",
"new_message",
"=",
"message",
".",
"copy",
"(",
"queue_name",
"=",
"queue_name",
")",
"del",
"new_message",
".",
"options",
"[",
"\"eta\"",
"]",
"self",
".",
"broker",
".",
"enqueue",
"(",
"new_message",
")",
"self",
".",
"post_process_message",
"(",
"message",
")",
"self",
".",
"delay_queue",
".",
"task_done",
"(",
")"
] | Enqueue any delayed messages whose eta has passed. | [
"Enqueue",
"any",
"delayed",
"messages",
"whose",
"eta",
"has",
"passed",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L285-L300 |
227,266 | Bogdanp/dramatiq | dramatiq/worker.py | _ConsumerThread.handle_message | def handle_message(self, message):
"""Handle a message received off of the underlying consumer.
If the message has an eta, delay it. Otherwise, put it on the
work queue.
"""
try:
if "eta" in message.options:
self.logger.debug("Pushing message %r onto delay queue.", message.message_id)
self.broker.emit_before("delay_message", message)
self.delay_queue.put((message.options.get("eta", 0), message))
else:
actor = self.broker.get_actor(message.actor_name)
self.logger.debug("Pushing message %r onto work queue.", message.message_id)
self.work_queue.put((actor.priority, message))
except ActorNotFound:
self.logger.error(
"Received message for undefined actor %r. Moving it to the DLQ.",
message.actor_name, exc_info=True,
)
message.fail()
self.post_process_message(message) | python | def handle_message(self, message):
"""Handle a message received off of the underlying consumer.
If the message has an eta, delay it. Otherwise, put it on the
work queue.
"""
try:
if "eta" in message.options:
self.logger.debug("Pushing message %r onto delay queue.", message.message_id)
self.broker.emit_before("delay_message", message)
self.delay_queue.put((message.options.get("eta", 0), message))
else:
actor = self.broker.get_actor(message.actor_name)
self.logger.debug("Pushing message %r onto work queue.", message.message_id)
self.work_queue.put((actor.priority, message))
except ActorNotFound:
self.logger.error(
"Received message for undefined actor %r. Moving it to the DLQ.",
message.actor_name, exc_info=True,
)
message.fail()
self.post_process_message(message) | [
"def",
"handle_message",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"if",
"\"eta\"",
"in",
"message",
".",
"options",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Pushing message %r onto delay queue.\"",
",",
"message",
".",
"message_id",
")",
"self",
".",
"broker",
".",
"emit_before",
"(",
"\"delay_message\"",
",",
"message",
")",
"self",
".",
"delay_queue",
".",
"put",
"(",
"(",
"message",
".",
"options",
".",
"get",
"(",
"\"eta\"",
",",
"0",
")",
",",
"message",
")",
")",
"else",
":",
"actor",
"=",
"self",
".",
"broker",
".",
"get_actor",
"(",
"message",
".",
"actor_name",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Pushing message %r onto work queue.\"",
",",
"message",
".",
"message_id",
")",
"self",
".",
"work_queue",
".",
"put",
"(",
"(",
"actor",
".",
"priority",
",",
"message",
")",
")",
"except",
"ActorNotFound",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Received message for undefined actor %r. Moving it to the DLQ.\"",
",",
"message",
".",
"actor_name",
",",
"exc_info",
"=",
"True",
",",
")",
"message",
".",
"fail",
"(",
")",
"self",
".",
"post_process_message",
"(",
"message",
")"
] | Handle a message received off of the underlying consumer.
If the message has an eta, delay it. Otherwise, put it on the
work queue. | [
"Handle",
"a",
"message",
"received",
"off",
"of",
"the",
"underlying",
"consumer",
".",
"If",
"the",
"message",
"has",
"an",
"eta",
"delay",
"it",
".",
"Otherwise",
"put",
"it",
"on",
"the",
"work",
"queue",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L302-L323 |
227,267 | Bogdanp/dramatiq | dramatiq/worker.py | _ConsumerThread.post_process_message | def post_process_message(self, message):
"""Called by worker threads whenever they're done processing
individual messages, signaling that each message is ready to
be acked or rejected.
"""
while True:
try:
if message.failed:
self.logger.debug("Rejecting message %r.", message.message_id)
self.broker.emit_before("nack", message)
self.consumer.nack(message)
self.broker.emit_after("nack", message)
else:
self.logger.debug("Acknowledging message %r.", message.message_id)
self.broker.emit_before("ack", message)
self.consumer.ack(message)
self.broker.emit_after("ack", message)
return
# This applies to the Redis broker. The alternative to
# constantly retrying would be to give up here and let the
# message be re-processed after the worker is eventually
# stopped or restarted, but we'd be doing the same work
# twice in that case and the behaviour would surprise
# users who don't deploy frequently.
except ConnectionError as e:
self.logger.warning(
"Failed to post_process_message(%s) due to a connection error: %s\n"
"The operation will be retried in %s seconds until the connection recovers.\n"
"If you restart this worker before this operation succeeds, the message will be re-processed later.",
message, e, POST_PROCESS_MESSAGE_RETRY_DELAY_SECS
)
time.sleep(POST_PROCESS_MESSAGE_RETRY_DELAY_SECS)
continue
# Not much point retrying here so we bail. Most likely,
# the message will be re-run after the worker is stopped
# or restarted (because its ack lease will have expired).
except Exception: # pragma: no cover
self.logger.exception(
"Unhandled error during post_process_message(%s). You've found a bug in Dramatiq. Please report it!\n"
"Although your message has been processed, it will be processed again once this worker is restarted.",
message,
)
return | python | def post_process_message(self, message):
"""Called by worker threads whenever they're done processing
individual messages, signaling that each message is ready to
be acked or rejected.
"""
while True:
try:
if message.failed:
self.logger.debug("Rejecting message %r.", message.message_id)
self.broker.emit_before("nack", message)
self.consumer.nack(message)
self.broker.emit_after("nack", message)
else:
self.logger.debug("Acknowledging message %r.", message.message_id)
self.broker.emit_before("ack", message)
self.consumer.ack(message)
self.broker.emit_after("ack", message)
return
# This applies to the Redis broker. The alternative to
# constantly retrying would be to give up here and let the
# message be re-processed after the worker is eventually
# stopped or restarted, but we'd be doing the same work
# twice in that case and the behaviour would surprise
# users who don't deploy frequently.
except ConnectionError as e:
self.logger.warning(
"Failed to post_process_message(%s) due to a connection error: %s\n"
"The operation will be retried in %s seconds until the connection recovers.\n"
"If you restart this worker before this operation succeeds, the message will be re-processed later.",
message, e, POST_PROCESS_MESSAGE_RETRY_DELAY_SECS
)
time.sleep(POST_PROCESS_MESSAGE_RETRY_DELAY_SECS)
continue
# Not much point retrying here so we bail. Most likely,
# the message will be re-run after the worker is stopped
# or restarted (because its ack lease will have expired).
except Exception: # pragma: no cover
self.logger.exception(
"Unhandled error during post_process_message(%s). You've found a bug in Dramatiq. Please report it!\n"
"Although your message has been processed, it will be processed again once this worker is restarted.",
message,
)
return | [
"def",
"post_process_message",
"(",
"self",
",",
"message",
")",
":",
"while",
"True",
":",
"try",
":",
"if",
"message",
".",
"failed",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Rejecting message %r.\"",
",",
"message",
".",
"message_id",
")",
"self",
".",
"broker",
".",
"emit_before",
"(",
"\"nack\"",
",",
"message",
")",
"self",
".",
"consumer",
".",
"nack",
"(",
"message",
")",
"self",
".",
"broker",
".",
"emit_after",
"(",
"\"nack\"",
",",
"message",
")",
"else",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Acknowledging message %r.\"",
",",
"message",
".",
"message_id",
")",
"self",
".",
"broker",
".",
"emit_before",
"(",
"\"ack\"",
",",
"message",
")",
"self",
".",
"consumer",
".",
"ack",
"(",
"message",
")",
"self",
".",
"broker",
".",
"emit_after",
"(",
"\"ack\"",
",",
"message",
")",
"return",
"# This applies to the Redis broker. The alternative to",
"# constantly retrying would be to give up here and let the",
"# message be re-processed after the worker is eventually",
"# stopped or restarted, but we'd be doing the same work",
"# twice in that case and the behaviour would surprise",
"# users who don't deploy frequently.",
"except",
"ConnectionError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Failed to post_process_message(%s) due to a connection error: %s\\n\"",
"\"The operation will be retried in %s seconds until the connection recovers.\\n\"",
"\"If you restart this worker before this operation succeeds, the message will be re-processed later.\"",
",",
"message",
",",
"e",
",",
"POST_PROCESS_MESSAGE_RETRY_DELAY_SECS",
")",
"time",
".",
"sleep",
"(",
"POST_PROCESS_MESSAGE_RETRY_DELAY_SECS",
")",
"continue",
"# Not much point retrying here so we bail. Most likely,",
"# the message will be re-run after the worker is stopped",
"# or restarted (because its ack lease will have expired).",
"except",
"Exception",
":",
"# pragma: no cover",
"self",
".",
"logger",
".",
"exception",
"(",
"\"Unhandled error during post_process_message(%s). You've found a bug in Dramatiq. Please report it!\\n\"",
"\"Although your message has been processed, it will be processed again once this worker is restarted.\"",
",",
"message",
",",
")",
"return"
] | Called by worker threads whenever they're done processing
individual messages, signaling that each message is ready to
be acked or rejected. | [
"Called",
"by",
"worker",
"threads",
"whenever",
"they",
"re",
"done",
"processing",
"individual",
"messages",
"signaling",
"that",
"each",
"message",
"is",
"ready",
"to",
"be",
"acked",
"or",
"rejected",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L325-L373 |
227,268 | Bogdanp/dramatiq | dramatiq/worker.py | _ConsumerThread.close | def close(self):
"""Close this consumer thread and its underlying connection.
"""
try:
if self.consumer:
self.requeue_messages(m for _, m in iter_queue(self.delay_queue))
self.consumer.close()
except ConnectionError:
pass | python | def close(self):
"""Close this consumer thread and its underlying connection.
"""
try:
if self.consumer:
self.requeue_messages(m for _, m in iter_queue(self.delay_queue))
self.consumer.close()
except ConnectionError:
pass | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"consumer",
":",
"self",
".",
"requeue_messages",
"(",
"m",
"for",
"_",
",",
"m",
"in",
"iter_queue",
"(",
"self",
".",
"delay_queue",
")",
")",
"self",
".",
"consumer",
".",
"close",
"(",
")",
"except",
"ConnectionError",
":",
"pass"
] | Close this consumer thread and its underlying connection. | [
"Close",
"this",
"consumer",
"thread",
"and",
"its",
"underlying",
"connection",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L403-L411 |
227,269 | Bogdanp/dramatiq | dramatiq/worker.py | _WorkerThread.process_message | def process_message(self, message):
"""Process a message pulled off of the work queue then push it
back to its associated consumer for post processing.
Parameters:
message(MessageProxy)
"""
try:
self.logger.debug("Received message %s with id %r.", message, message.message_id)
self.broker.emit_before("process_message", message)
res = None
if not message.failed:
actor = self.broker.get_actor(message.actor_name)
res = actor(*message.args, **message.kwargs)
self.broker.emit_after("process_message", message, result=res)
except SkipMessage:
self.logger.warning("Message %s was skipped.", message)
self.broker.emit_after("skip_message", message)
except BaseException as e:
# Stuff the exception into the message [proxy] so that it
# may be used by the stub broker to provide a nicer
# testing experience.
message.stuff_exception(e)
if isinstance(e, RateLimitExceeded):
self.logger.warning("Rate limit exceeded in message %s: %s.", message, e)
else:
self.logger.warning("Failed to process message %s with unhandled exception.", message, exc_info=True)
self.broker.emit_after("process_message", message, exception=e)
finally:
# NOTE: There is no race here as any message that was
# processed must have come off of a consumer. Therefore,
# there has to be a consumer for that message's queue so
# this is safe. Probably.
self.consumers[message.queue_name].post_process_message(message)
self.work_queue.task_done() | python | def process_message(self, message):
"""Process a message pulled off of the work queue then push it
back to its associated consumer for post processing.
Parameters:
message(MessageProxy)
"""
try:
self.logger.debug("Received message %s with id %r.", message, message.message_id)
self.broker.emit_before("process_message", message)
res = None
if not message.failed:
actor = self.broker.get_actor(message.actor_name)
res = actor(*message.args, **message.kwargs)
self.broker.emit_after("process_message", message, result=res)
except SkipMessage:
self.logger.warning("Message %s was skipped.", message)
self.broker.emit_after("skip_message", message)
except BaseException as e:
# Stuff the exception into the message [proxy] so that it
# may be used by the stub broker to provide a nicer
# testing experience.
message.stuff_exception(e)
if isinstance(e, RateLimitExceeded):
self.logger.warning("Rate limit exceeded in message %s: %s.", message, e)
else:
self.logger.warning("Failed to process message %s with unhandled exception.", message, exc_info=True)
self.broker.emit_after("process_message", message, exception=e)
finally:
# NOTE: There is no race here as any message that was
# processed must have come off of a consumer. Therefore,
# there has to be a consumer for that message's queue so
# this is safe. Probably.
self.consumers[message.queue_name].post_process_message(message)
self.work_queue.task_done() | [
"def",
"process_message",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Received message %s with id %r.\"",
",",
"message",
",",
"message",
".",
"message_id",
")",
"self",
".",
"broker",
".",
"emit_before",
"(",
"\"process_message\"",
",",
"message",
")",
"res",
"=",
"None",
"if",
"not",
"message",
".",
"failed",
":",
"actor",
"=",
"self",
".",
"broker",
".",
"get_actor",
"(",
"message",
".",
"actor_name",
")",
"res",
"=",
"actor",
"(",
"*",
"message",
".",
"args",
",",
"*",
"*",
"message",
".",
"kwargs",
")",
"self",
".",
"broker",
".",
"emit_after",
"(",
"\"process_message\"",
",",
"message",
",",
"result",
"=",
"res",
")",
"except",
"SkipMessage",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Message %s was skipped.\"",
",",
"message",
")",
"self",
".",
"broker",
".",
"emit_after",
"(",
"\"skip_message\"",
",",
"message",
")",
"except",
"BaseException",
"as",
"e",
":",
"# Stuff the exception into the message [proxy] so that it",
"# may be used by the stub broker to provide a nicer",
"# testing experience.",
"message",
".",
"stuff_exception",
"(",
"e",
")",
"if",
"isinstance",
"(",
"e",
",",
"RateLimitExceeded",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Rate limit exceeded in message %s: %s.\"",
",",
"message",
",",
"e",
")",
"else",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Failed to process message %s with unhandled exception.\"",
",",
"message",
",",
"exc_info",
"=",
"True",
")",
"self",
".",
"broker",
".",
"emit_after",
"(",
"\"process_message\"",
",",
"message",
",",
"exception",
"=",
"e",
")",
"finally",
":",
"# NOTE: There is no race here as any message that was",
"# processed must have come off of a consumer. Therefore,",
"# there has to be a consumer for that message's queue so",
"# this is safe. Probably.",
"self",
".",
"consumers",
"[",
"message",
".",
"queue_name",
"]",
".",
"post_process_message",
"(",
"message",
")",
"self",
".",
"work_queue",
".",
"task_done",
"(",
")"
] | Process a message pulled off of the work queue then push it
back to its associated consumer for post processing.
Parameters:
message(MessageProxy) | [
"Process",
"a",
"message",
"pulled",
"off",
"of",
"the",
"work",
"queue",
"then",
"push",
"it",
"back",
"to",
"its",
"associated",
"consumer",
"for",
"post",
"processing",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L456-L497 |
227,270 | github/octodns | octodns/manager.py | Manager.compare | def compare(self, a, b, zone):
'''
Compare zone data between 2 sources.
Note: only things supported by both sources will be considered
'''
self.log.info('compare: a=%s, b=%s, zone=%s', a, b, zone)
try:
a = [self.providers[source] for source in a]
b = [self.providers[source] for source in b]
except KeyError as e:
raise Exception('Unknown source: {}'.format(e.args[0]))
sub_zones = self.configured_sub_zones(zone)
za = Zone(zone, sub_zones)
for source in a:
source.populate(za)
zb = Zone(zone, sub_zones)
for source in b:
source.populate(zb)
return zb.changes(za, _AggregateTarget(a + b)) | python | def compare(self, a, b, zone):
'''
Compare zone data between 2 sources.
Note: only things supported by both sources will be considered
'''
self.log.info('compare: a=%s, b=%s, zone=%s', a, b, zone)
try:
a = [self.providers[source] for source in a]
b = [self.providers[source] for source in b]
except KeyError as e:
raise Exception('Unknown source: {}'.format(e.args[0]))
sub_zones = self.configured_sub_zones(zone)
za = Zone(zone, sub_zones)
for source in a:
source.populate(za)
zb = Zone(zone, sub_zones)
for source in b:
source.populate(zb)
return zb.changes(za, _AggregateTarget(a + b)) | [
"def",
"compare",
"(",
"self",
",",
"a",
",",
"b",
",",
"zone",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'compare: a=%s, b=%s, zone=%s'",
",",
"a",
",",
"b",
",",
"zone",
")",
"try",
":",
"a",
"=",
"[",
"self",
".",
"providers",
"[",
"source",
"]",
"for",
"source",
"in",
"a",
"]",
"b",
"=",
"[",
"self",
".",
"providers",
"[",
"source",
"]",
"for",
"source",
"in",
"b",
"]",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"Exception",
"(",
"'Unknown source: {}'",
".",
"format",
"(",
"e",
".",
"args",
"[",
"0",
"]",
")",
")",
"sub_zones",
"=",
"self",
".",
"configured_sub_zones",
"(",
"zone",
")",
"za",
"=",
"Zone",
"(",
"zone",
",",
"sub_zones",
")",
"for",
"source",
"in",
"a",
":",
"source",
".",
"populate",
"(",
"za",
")",
"zb",
"=",
"Zone",
"(",
"zone",
",",
"sub_zones",
")",
"for",
"source",
"in",
"b",
":",
"source",
".",
"populate",
"(",
"zb",
")",
"return",
"zb",
".",
"changes",
"(",
"za",
",",
"_AggregateTarget",
"(",
"a",
"+",
"b",
")",
")"
] | Compare zone data between 2 sources.
Note: only things supported by both sources will be considered | [
"Compare",
"zone",
"data",
"between",
"2",
"sources",
"."
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/manager.py#L335-L358 |
227,271 | github/octodns | octodns/manager.py | Manager.dump | def dump(self, zone, output_dir, lenient, split, source, *sources):
'''
Dump zone data from the specified source
'''
self.log.info('dump: zone=%s, sources=%s', zone, sources)
# We broke out source to force at least one to be passed, add it to any
# others we got.
sources = [source] + list(sources)
try:
sources = [self.providers[s] for s in sources]
except KeyError as e:
raise Exception('Unknown source: {}'.format(e.args[0]))
clz = YamlProvider
if split:
clz = SplitYamlProvider
target = clz('dump', output_dir)
zone = Zone(zone, self.configured_sub_zones(zone))
for source in sources:
source.populate(zone, lenient=lenient)
plan = target.plan(zone)
if plan is None:
plan = Plan(zone, zone, [], False)
target.apply(plan) | python | def dump(self, zone, output_dir, lenient, split, source, *sources):
'''
Dump zone data from the specified source
'''
self.log.info('dump: zone=%s, sources=%s', zone, sources)
# We broke out source to force at least one to be passed, add it to any
# others we got.
sources = [source] + list(sources)
try:
sources = [self.providers[s] for s in sources]
except KeyError as e:
raise Exception('Unknown source: {}'.format(e.args[0]))
clz = YamlProvider
if split:
clz = SplitYamlProvider
target = clz('dump', output_dir)
zone = Zone(zone, self.configured_sub_zones(zone))
for source in sources:
source.populate(zone, lenient=lenient)
plan = target.plan(zone)
if plan is None:
plan = Plan(zone, zone, [], False)
target.apply(plan) | [
"def",
"dump",
"(",
"self",
",",
"zone",
",",
"output_dir",
",",
"lenient",
",",
"split",
",",
"source",
",",
"*",
"sources",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'dump: zone=%s, sources=%s'",
",",
"zone",
",",
"sources",
")",
"# We broke out source to force at least one to be passed, add it to any",
"# others we got.",
"sources",
"=",
"[",
"source",
"]",
"+",
"list",
"(",
"sources",
")",
"try",
":",
"sources",
"=",
"[",
"self",
".",
"providers",
"[",
"s",
"]",
"for",
"s",
"in",
"sources",
"]",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"Exception",
"(",
"'Unknown source: {}'",
".",
"format",
"(",
"e",
".",
"args",
"[",
"0",
"]",
")",
")",
"clz",
"=",
"YamlProvider",
"if",
"split",
":",
"clz",
"=",
"SplitYamlProvider",
"target",
"=",
"clz",
"(",
"'dump'",
",",
"output_dir",
")",
"zone",
"=",
"Zone",
"(",
"zone",
",",
"self",
".",
"configured_sub_zones",
"(",
"zone",
")",
")",
"for",
"source",
"in",
"sources",
":",
"source",
".",
"populate",
"(",
"zone",
",",
"lenient",
"=",
"lenient",
")",
"plan",
"=",
"target",
".",
"plan",
"(",
"zone",
")",
"if",
"plan",
"is",
"None",
":",
"plan",
"=",
"Plan",
"(",
"zone",
",",
"zone",
",",
"[",
"]",
",",
"False",
")",
"target",
".",
"apply",
"(",
"plan",
")"
] | Dump zone data from the specified source | [
"Dump",
"zone",
"data",
"from",
"the",
"specified",
"source"
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/manager.py#L360-L387 |
227,272 | github/octodns | octodns/provider/dyn.py | _CachingDynZone.flush_zone | def flush_zone(cls, zone_name):
'''Flushes the zone cache, if there is one'''
cls.log.debug('flush_zone: zone_name=%s', zone_name)
try:
del cls._cache[zone_name]
except KeyError:
pass | python | def flush_zone(cls, zone_name):
'''Flushes the zone cache, if there is one'''
cls.log.debug('flush_zone: zone_name=%s', zone_name)
try:
del cls._cache[zone_name]
except KeyError:
pass | [
"def",
"flush_zone",
"(",
"cls",
",",
"zone_name",
")",
":",
"cls",
".",
"log",
".",
"debug",
"(",
"'flush_zone: zone_name=%s'",
",",
"zone_name",
")",
"try",
":",
"del",
"cls",
".",
"_cache",
"[",
"zone_name",
"]",
"except",
"KeyError",
":",
"pass"
] | Flushes the zone cache, if there is one | [
"Flushes",
"the",
"zone",
"cache",
"if",
"there",
"is",
"one"
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/dyn.py#L156-L162 |
227,273 | github/octodns | octodns/provider/azuredns.py | AzureProvider._check_zone | def _check_zone(self, name, create=False):
'''Checks whether a zone specified in a source exist in Azure server.
Note that Azure zones omit end '.' eg: contoso.com vs contoso.com.
Returns the name if it exists.
:param name: Name of a zone to checks
:type name: str
:param create: If True, creates the zone of that name.
:type create: bool
:type return: str or None
'''
self.log.debug('_check_zone: name=%s', name)
try:
if name in self._azure_zones:
return name
self._dns_client.zones.get(self._resource_group, name)
self._azure_zones.add(name)
return name
except CloudError as err:
msg = 'The Resource \'Microsoft.Network/dnszones/{}\''.format(name)
msg += ' under resource group \'{}\''.format(self._resource_group)
msg += ' was not found.'
if msg == err.message:
# Then the only error is that the zone doesn't currently exist
if create:
self.log.debug('_check_zone:no matching zone; creating %s',
name)
create_zone = self._dns_client.zones.create_or_update
create_zone(self._resource_group, name,
Zone(location='global'))
return name
else:
return
raise | python | def _check_zone(self, name, create=False):
'''Checks whether a zone specified in a source exist in Azure server.
Note that Azure zones omit end '.' eg: contoso.com vs contoso.com.
Returns the name if it exists.
:param name: Name of a zone to checks
:type name: str
:param create: If True, creates the zone of that name.
:type create: bool
:type return: str or None
'''
self.log.debug('_check_zone: name=%s', name)
try:
if name in self._azure_zones:
return name
self._dns_client.zones.get(self._resource_group, name)
self._azure_zones.add(name)
return name
except CloudError as err:
msg = 'The Resource \'Microsoft.Network/dnszones/{}\''.format(name)
msg += ' under resource group \'{}\''.format(self._resource_group)
msg += ' was not found.'
if msg == err.message:
# Then the only error is that the zone doesn't currently exist
if create:
self.log.debug('_check_zone:no matching zone; creating %s',
name)
create_zone = self._dns_client.zones.create_or_update
create_zone(self._resource_group, name,
Zone(location='global'))
return name
else:
return
raise | [
"def",
"_check_zone",
"(",
"self",
",",
"name",
",",
"create",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'_check_zone: name=%s'",
",",
"name",
")",
"try",
":",
"if",
"name",
"in",
"self",
".",
"_azure_zones",
":",
"return",
"name",
"self",
".",
"_dns_client",
".",
"zones",
".",
"get",
"(",
"self",
".",
"_resource_group",
",",
"name",
")",
"self",
".",
"_azure_zones",
".",
"add",
"(",
"name",
")",
"return",
"name",
"except",
"CloudError",
"as",
"err",
":",
"msg",
"=",
"'The Resource \\'Microsoft.Network/dnszones/{}\\''",
".",
"format",
"(",
"name",
")",
"msg",
"+=",
"' under resource group \\'{}\\''",
".",
"format",
"(",
"self",
".",
"_resource_group",
")",
"msg",
"+=",
"' was not found.'",
"if",
"msg",
"==",
"err",
".",
"message",
":",
"# Then the only error is that the zone doesn't currently exist",
"if",
"create",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'_check_zone:no matching zone; creating %s'",
",",
"name",
")",
"create_zone",
"=",
"self",
".",
"_dns_client",
".",
"zones",
".",
"create_or_update",
"create_zone",
"(",
"self",
".",
"_resource_group",
",",
"name",
",",
"Zone",
"(",
"location",
"=",
"'global'",
")",
")",
"return",
"name",
"else",
":",
"return",
"raise"
] | Checks whether a zone specified in a source exist in Azure server.
Note that Azure zones omit end '.' eg: contoso.com vs contoso.com.
Returns the name if it exists.
:param name: Name of a zone to checks
:type name: str
:param create: If True, creates the zone of that name.
:type create: bool
:type return: str or None | [
"Checks",
"whether",
"a",
"zone",
"specified",
"in",
"a",
"source",
"exist",
"in",
"Azure",
"server",
"."
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/azuredns.py#L306-L341 |
227,274 | github/octodns | octodns/provider/azuredns.py | AzureProvider._apply_Create | def _apply_Create(self, change):
'''A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void
'''
ar = _AzureRecord(self._resource_group, change.new)
create = self._dns_client.record_sets.create_or_update
create(resource_group_name=ar.resource_group,
zone_name=ar.zone_name,
relative_record_set_name=ar.relative_record_set_name,
record_type=ar.record_type,
parameters=ar.params)
self.log.debug('* Success Create/Update: {}'.format(ar)) | python | def _apply_Create(self, change):
'''A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void
'''
ar = _AzureRecord(self._resource_group, change.new)
create = self._dns_client.record_sets.create_or_update
create(resource_group_name=ar.resource_group,
zone_name=ar.zone_name,
relative_record_set_name=ar.relative_record_set_name,
record_type=ar.record_type,
parameters=ar.params)
self.log.debug('* Success Create/Update: {}'.format(ar)) | [
"def",
"_apply_Create",
"(",
"self",
",",
"change",
")",
":",
"ar",
"=",
"_AzureRecord",
"(",
"self",
".",
"_resource_group",
",",
"change",
".",
"new",
")",
"create",
"=",
"self",
".",
"_dns_client",
".",
"record_sets",
".",
"create_or_update",
"create",
"(",
"resource_group_name",
"=",
"ar",
".",
"resource_group",
",",
"zone_name",
"=",
"ar",
".",
"zone_name",
",",
"relative_record_set_name",
"=",
"ar",
".",
"relative_record_set_name",
",",
"record_type",
"=",
"ar",
".",
"record_type",
",",
"parameters",
"=",
"ar",
".",
"params",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'* Success Create/Update: {}'",
".",
"format",
"(",
"ar",
")",
")"
] | A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void | [
"A",
"record",
"from",
"change",
"must",
"be",
"created",
"."
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/azuredns.py#L450-L467 |
227,275 | github/octodns | octodns/provider/base.py | BaseProvider.apply | def apply(self, plan):
'''
Submits actual planned changes to the provider. Returns the number of
changes made
'''
if self.apply_disabled:
self.log.info('apply: disabled')
return 0
self.log.info('apply: making changes')
self._apply(plan)
return len(plan.changes) | python | def apply(self, plan):
'''
Submits actual planned changes to the provider. Returns the number of
changes made
'''
if self.apply_disabled:
self.log.info('apply: disabled')
return 0
self.log.info('apply: making changes')
self._apply(plan)
return len(plan.changes) | [
"def",
"apply",
"(",
"self",
",",
"plan",
")",
":",
"if",
"self",
".",
"apply_disabled",
":",
"self",
".",
"log",
".",
"info",
"(",
"'apply: disabled'",
")",
"return",
"0",
"self",
".",
"log",
".",
"info",
"(",
"'apply: making changes'",
")",
"self",
".",
"_apply",
"(",
"plan",
")",
"return",
"len",
"(",
"plan",
".",
"changes",
")"
] | Submits actual planned changes to the provider. Returns the number of
changes made | [
"Submits",
"actual",
"planned",
"changes",
"to",
"the",
"provider",
".",
"Returns",
"the",
"number",
"of",
"changes",
"made"
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/base.py#L83-L94 |
227,276 | github/octodns | octodns/provider/ovh.py | OvhProvider._is_valid_dkim | def _is_valid_dkim(self, value):
"""Check if value is a valid DKIM"""
validator_dict = {'h': lambda val: val in ['sha1', 'sha256'],
's': lambda val: val in ['*', 'email'],
't': lambda val: val in ['y', 's'],
'v': lambda val: val == 'DKIM1',
'k': lambda val: val == 'rsa',
'n': lambda _: True,
'g': lambda _: True}
splitted = value.split('\\;')
found_key = False
for splitted_value in splitted:
sub_split = map(lambda x: x.strip(), splitted_value.split("=", 1))
if len(sub_split) < 2:
return False
key, value = sub_split[0], sub_split[1]
if key == "p":
is_valid_key = self._is_valid_dkim_key(value)
if not is_valid_key:
return False
found_key = True
else:
is_valid_key = validator_dict.get(key, lambda _: False)(value)
if not is_valid_key:
return False
return found_key | python | def _is_valid_dkim(self, value):
"""Check if value is a valid DKIM"""
validator_dict = {'h': lambda val: val in ['sha1', 'sha256'],
's': lambda val: val in ['*', 'email'],
't': lambda val: val in ['y', 's'],
'v': lambda val: val == 'DKIM1',
'k': lambda val: val == 'rsa',
'n': lambda _: True,
'g': lambda _: True}
splitted = value.split('\\;')
found_key = False
for splitted_value in splitted:
sub_split = map(lambda x: x.strip(), splitted_value.split("=", 1))
if len(sub_split) < 2:
return False
key, value = sub_split[0], sub_split[1]
if key == "p":
is_valid_key = self._is_valid_dkim_key(value)
if not is_valid_key:
return False
found_key = True
else:
is_valid_key = validator_dict.get(key, lambda _: False)(value)
if not is_valid_key:
return False
return found_key | [
"def",
"_is_valid_dkim",
"(",
"self",
",",
"value",
")",
":",
"validator_dict",
"=",
"{",
"'h'",
":",
"lambda",
"val",
":",
"val",
"in",
"[",
"'sha1'",
",",
"'sha256'",
"]",
",",
"'s'",
":",
"lambda",
"val",
":",
"val",
"in",
"[",
"'*'",
",",
"'email'",
"]",
",",
"'t'",
":",
"lambda",
"val",
":",
"val",
"in",
"[",
"'y'",
",",
"'s'",
"]",
",",
"'v'",
":",
"lambda",
"val",
":",
"val",
"==",
"'DKIM1'",
",",
"'k'",
":",
"lambda",
"val",
":",
"val",
"==",
"'rsa'",
",",
"'n'",
":",
"lambda",
"_",
":",
"True",
",",
"'g'",
":",
"lambda",
"_",
":",
"True",
"}",
"splitted",
"=",
"value",
".",
"split",
"(",
"'\\\\;'",
")",
"found_key",
"=",
"False",
"for",
"splitted_value",
"in",
"splitted",
":",
"sub_split",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"strip",
"(",
")",
",",
"splitted_value",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
")",
"if",
"len",
"(",
"sub_split",
")",
"<",
"2",
":",
"return",
"False",
"key",
",",
"value",
"=",
"sub_split",
"[",
"0",
"]",
",",
"sub_split",
"[",
"1",
"]",
"if",
"key",
"==",
"\"p\"",
":",
"is_valid_key",
"=",
"self",
".",
"_is_valid_dkim_key",
"(",
"value",
")",
"if",
"not",
"is_valid_key",
":",
"return",
"False",
"found_key",
"=",
"True",
"else",
":",
"is_valid_key",
"=",
"validator_dict",
".",
"get",
"(",
"key",
",",
"lambda",
"_",
":",
"False",
")",
"(",
"value",
")",
"if",
"not",
"is_valid_key",
":",
"return",
"False",
"return",
"found_key"
] | Check if value is a valid DKIM | [
"Check",
"if",
"value",
"is",
"a",
"valid",
"DKIM"
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/ovh.py#L315-L341 |
227,277 | github/octodns | octodns/provider/googlecloud.py | GoogleCloudProvider._get_gcloud_records | def _get_gcloud_records(self, gcloud_zone, page_token=None):
""" Generator function which yields ResourceRecordSet for the managed
gcloud zone, until there are no more records to pull.
:param gcloud_zone: zone to pull records from
:type gcloud_zone: google.cloud.dns.ManagedZone
:param page_token: page token for the page to get
:return: a resource record set
:type return: google.cloud.dns.ResourceRecordSet
"""
gcloud_iterator = gcloud_zone.list_resource_record_sets(
page_token=page_token)
for gcloud_record in gcloud_iterator:
yield gcloud_record
# This is to get results which may be on a "paged" page.
# (if more than max_results) entries.
if gcloud_iterator.next_page_token:
for gcloud_record in self._get_gcloud_records(
gcloud_zone, gcloud_iterator.next_page_token):
# yield from is in python 3 only.
yield gcloud_record | python | def _get_gcloud_records(self, gcloud_zone, page_token=None):
""" Generator function which yields ResourceRecordSet for the managed
gcloud zone, until there are no more records to pull.
:param gcloud_zone: zone to pull records from
:type gcloud_zone: google.cloud.dns.ManagedZone
:param page_token: page token for the page to get
:return: a resource record set
:type return: google.cloud.dns.ResourceRecordSet
"""
gcloud_iterator = gcloud_zone.list_resource_record_sets(
page_token=page_token)
for gcloud_record in gcloud_iterator:
yield gcloud_record
# This is to get results which may be on a "paged" page.
# (if more than max_results) entries.
if gcloud_iterator.next_page_token:
for gcloud_record in self._get_gcloud_records(
gcloud_zone, gcloud_iterator.next_page_token):
# yield from is in python 3 only.
yield gcloud_record | [
"def",
"_get_gcloud_records",
"(",
"self",
",",
"gcloud_zone",
",",
"page_token",
"=",
"None",
")",
":",
"gcloud_iterator",
"=",
"gcloud_zone",
".",
"list_resource_record_sets",
"(",
"page_token",
"=",
"page_token",
")",
"for",
"gcloud_record",
"in",
"gcloud_iterator",
":",
"yield",
"gcloud_record",
"# This is to get results which may be on a \"paged\" page.",
"# (if more than max_results) entries.",
"if",
"gcloud_iterator",
".",
"next_page_token",
":",
"for",
"gcloud_record",
"in",
"self",
".",
"_get_gcloud_records",
"(",
"gcloud_zone",
",",
"gcloud_iterator",
".",
"next_page_token",
")",
":",
"# yield from is in python 3 only.",
"yield",
"gcloud_record"
] | Generator function which yields ResourceRecordSet for the managed
gcloud zone, until there are no more records to pull.
:param gcloud_zone: zone to pull records from
:type gcloud_zone: google.cloud.dns.ManagedZone
:param page_token: page token for the page to get
:return: a resource record set
:type return: google.cloud.dns.ResourceRecordSet | [
"Generator",
"function",
"which",
"yields",
"ResourceRecordSet",
"for",
"the",
"managed",
"gcloud",
"zone",
"until",
"there",
"are",
"no",
"more",
"records",
"to",
"pull",
"."
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/googlecloud.py#L150-L171 |
227,278 | github/octodns | octodns/provider/googlecloud.py | GoogleCloudProvider._get_cloud_zones | def _get_cloud_zones(self, page_token=None):
"""Load all ManagedZones into the self._gcloud_zones dict which is
mapped with the dns_name as key.
:return: void
"""
gcloud_zones = self.gcloud_client.list_zones(page_token=page_token)
for gcloud_zone in gcloud_zones:
self._gcloud_zones[gcloud_zone.dns_name] = gcloud_zone
if gcloud_zones.next_page_token:
self._get_cloud_zones(gcloud_zones.next_page_token) | python | def _get_cloud_zones(self, page_token=None):
"""Load all ManagedZones into the self._gcloud_zones dict which is
mapped with the dns_name as key.
:return: void
"""
gcloud_zones = self.gcloud_client.list_zones(page_token=page_token)
for gcloud_zone in gcloud_zones:
self._gcloud_zones[gcloud_zone.dns_name] = gcloud_zone
if gcloud_zones.next_page_token:
self._get_cloud_zones(gcloud_zones.next_page_token) | [
"def",
"_get_cloud_zones",
"(",
"self",
",",
"page_token",
"=",
"None",
")",
":",
"gcloud_zones",
"=",
"self",
".",
"gcloud_client",
".",
"list_zones",
"(",
"page_token",
"=",
"page_token",
")",
"for",
"gcloud_zone",
"in",
"gcloud_zones",
":",
"self",
".",
"_gcloud_zones",
"[",
"gcloud_zone",
".",
"dns_name",
"]",
"=",
"gcloud_zone",
"if",
"gcloud_zones",
".",
"next_page_token",
":",
"self",
".",
"_get_cloud_zones",
"(",
"gcloud_zones",
".",
"next_page_token",
")"
] | Load all ManagedZones into the self._gcloud_zones dict which is
mapped with the dns_name as key.
:return: void | [
"Load",
"all",
"ManagedZones",
"into",
"the",
"self",
".",
"_gcloud_zones",
"dict",
"which",
"is",
"mapped",
"with",
"the",
"dns_name",
"as",
"key",
"."
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/googlecloud.py#L173-L185 |
227,279 | nabla-c0d3/sslyze | sslyze/plugins/robot_plugin.py | RobotTlsRecordPayloads.get_client_key_exchange_record | def get_client_key_exchange_record(
cls,
robot_payload_enum: RobotPmsPaddingPayloadEnum,
tls_version: TlsVersionEnum,
modulus: int,
exponent: int
) -> TlsRsaClientKeyExchangeRecord:
"""A client key exchange record with a hardcoded pre_master_secret, and a valid or invalid padding.
"""
pms_padding = cls._compute_pms_padding(modulus)
tls_version_hex = binascii.b2a_hex(TlsRecordTlsVersionBytes[tls_version.name].value).decode('ascii')
pms_with_padding_payload = cls._CKE_PAYLOADS_HEX[robot_payload_enum]
final_pms = pms_with_padding_payload.format(
pms_padding=pms_padding, tls_version=tls_version_hex, pms=cls._PMS_HEX
)
cke_robot_record = TlsRsaClientKeyExchangeRecord.from_parameters(
tls_version, exponent, modulus, int(final_pms, 16)
)
return cke_robot_record | python | def get_client_key_exchange_record(
cls,
robot_payload_enum: RobotPmsPaddingPayloadEnum,
tls_version: TlsVersionEnum,
modulus: int,
exponent: int
) -> TlsRsaClientKeyExchangeRecord:
"""A client key exchange record with a hardcoded pre_master_secret, and a valid or invalid padding.
"""
pms_padding = cls._compute_pms_padding(modulus)
tls_version_hex = binascii.b2a_hex(TlsRecordTlsVersionBytes[tls_version.name].value).decode('ascii')
pms_with_padding_payload = cls._CKE_PAYLOADS_HEX[robot_payload_enum]
final_pms = pms_with_padding_payload.format(
pms_padding=pms_padding, tls_version=tls_version_hex, pms=cls._PMS_HEX
)
cke_robot_record = TlsRsaClientKeyExchangeRecord.from_parameters(
tls_version, exponent, modulus, int(final_pms, 16)
)
return cke_robot_record | [
"def",
"get_client_key_exchange_record",
"(",
"cls",
",",
"robot_payload_enum",
":",
"RobotPmsPaddingPayloadEnum",
",",
"tls_version",
":",
"TlsVersionEnum",
",",
"modulus",
":",
"int",
",",
"exponent",
":",
"int",
")",
"->",
"TlsRsaClientKeyExchangeRecord",
":",
"pms_padding",
"=",
"cls",
".",
"_compute_pms_padding",
"(",
"modulus",
")",
"tls_version_hex",
"=",
"binascii",
".",
"b2a_hex",
"(",
"TlsRecordTlsVersionBytes",
"[",
"tls_version",
".",
"name",
"]",
".",
"value",
")",
".",
"decode",
"(",
"'ascii'",
")",
"pms_with_padding_payload",
"=",
"cls",
".",
"_CKE_PAYLOADS_HEX",
"[",
"robot_payload_enum",
"]",
"final_pms",
"=",
"pms_with_padding_payload",
".",
"format",
"(",
"pms_padding",
"=",
"pms_padding",
",",
"tls_version",
"=",
"tls_version_hex",
",",
"pms",
"=",
"cls",
".",
"_PMS_HEX",
")",
"cke_robot_record",
"=",
"TlsRsaClientKeyExchangeRecord",
".",
"from_parameters",
"(",
"tls_version",
",",
"exponent",
",",
"modulus",
",",
"int",
"(",
"final_pms",
",",
"16",
")",
")",
"return",
"cke_robot_record"
] | A client key exchange record with a hardcoded pre_master_secret, and a valid or invalid padding. | [
"A",
"client",
"key",
"exchange",
"record",
"with",
"a",
"hardcoded",
"pre_master_secret",
"and",
"a",
"valid",
"or",
"invalid",
"padding",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/robot_plugin.py#L71-L90 |
227,280 | nabla-c0d3/sslyze | sslyze/plugins/robot_plugin.py | RobotTlsRecordPayloads.get_finished_record_bytes | def get_finished_record_bytes(cls, tls_version: TlsVersionEnum) -> bytes:
"""The Finished TLS record corresponding to the hardcoded PMS used in the Client Key Exchange record.
"""
# TODO(AD): The ROBOT poc script uses the same Finished record for all possible client hello (default, GCM,
# etc.); as the Finished record contains a hashes of all previous records, it will be wrong and will cause
# servers to send a TLS Alert 20
# Here just like in the poc script, the Finished message does not match the Client Hello we sent
return b'\x16' + TlsRecordTlsVersionBytes[tls_version.name].value + cls._FINISHED_RECORD | python | def get_finished_record_bytes(cls, tls_version: TlsVersionEnum) -> bytes:
"""The Finished TLS record corresponding to the hardcoded PMS used in the Client Key Exchange record.
"""
# TODO(AD): The ROBOT poc script uses the same Finished record for all possible client hello (default, GCM,
# etc.); as the Finished record contains a hashes of all previous records, it will be wrong and will cause
# servers to send a TLS Alert 20
# Here just like in the poc script, the Finished message does not match the Client Hello we sent
return b'\x16' + TlsRecordTlsVersionBytes[tls_version.name].value + cls._FINISHED_RECORD | [
"def",
"get_finished_record_bytes",
"(",
"cls",
",",
"tls_version",
":",
"TlsVersionEnum",
")",
"->",
"bytes",
":",
"# TODO(AD): The ROBOT poc script uses the same Finished record for all possible client hello (default, GCM,",
"# etc.); as the Finished record contains a hashes of all previous records, it will be wrong and will cause",
"# servers to send a TLS Alert 20",
"# Here just like in the poc script, the Finished message does not match the Client Hello we sent",
"return",
"b'\\x16'",
"+",
"TlsRecordTlsVersionBytes",
"[",
"tls_version",
".",
"name",
"]",
".",
"value",
"+",
"cls",
".",
"_FINISHED_RECORD"
] | The Finished TLS record corresponding to the hardcoded PMS used in the Client Key Exchange record. | [
"The",
"Finished",
"TLS",
"record",
"corresponding",
"to",
"the",
"hardcoded",
"PMS",
"used",
"in",
"the",
"Client",
"Key",
"Exchange",
"record",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/robot_plugin.py#L109-L116 |
227,281 | nabla-c0d3/sslyze | sslyze/plugins/robot_plugin.py | RobotServerResponsesAnalyzer.compute_result_enum | def compute_result_enum(self) -> RobotScanResultEnum:
"""Look at the server's response to each ROBOT payload and return the conclusion of the analysis.
"""
# Ensure the results were consistent
for payload_enum, server_responses in self._payload_responses.items():
# We ran the check twice per payload and the two responses should be the same
if server_responses[0] != server_responses[1]:
return RobotScanResultEnum.UNKNOWN_INCONSISTENT_RESULTS
# Check if the server acts as an oracle by checking if the server replied differently to the payloads
if len(set([server_responses[0] for server_responses in self._payload_responses.values()])) == 1:
# All server responses were identical - no oracle
return RobotScanResultEnum.NOT_VULNERABLE_NO_ORACLE
# All server responses were NOT identical, server is vulnerable
# Check to see if it is a weak oracle
response_1 = self._payload_responses[RobotPmsPaddingPayloadEnum.WRONG_FIRST_TWO_BYTES][0]
response_2 = self._payload_responses[RobotPmsPaddingPayloadEnum.WRONG_POSITION_00][0]
response_3 = self._payload_responses[RobotPmsPaddingPayloadEnum.NO_00_IN_THE_MIDDLE][0]
# From the original script:
# If the response to the invalid PKCS#1 request (oracle_bad1) is equal to both
# requests starting with 0002, we have a weak oracle. This is because the only
# case where we can distinguish valid from invalid requests is when we send
# correctly formatted PKCS#1 message with 0x00 on a correct position. This
# makes our oracle weak
if response_1 == response_2 == response_3:
return RobotScanResultEnum.VULNERABLE_WEAK_ORACLE
else:
return RobotScanResultEnum.VULNERABLE_STRONG_ORACLE | python | def compute_result_enum(self) -> RobotScanResultEnum:
"""Look at the server's response to each ROBOT payload and return the conclusion of the analysis.
"""
# Ensure the results were consistent
for payload_enum, server_responses in self._payload_responses.items():
# We ran the check twice per payload and the two responses should be the same
if server_responses[0] != server_responses[1]:
return RobotScanResultEnum.UNKNOWN_INCONSISTENT_RESULTS
# Check if the server acts as an oracle by checking if the server replied differently to the payloads
if len(set([server_responses[0] for server_responses in self._payload_responses.values()])) == 1:
# All server responses were identical - no oracle
return RobotScanResultEnum.NOT_VULNERABLE_NO_ORACLE
# All server responses were NOT identical, server is vulnerable
# Check to see if it is a weak oracle
response_1 = self._payload_responses[RobotPmsPaddingPayloadEnum.WRONG_FIRST_TWO_BYTES][0]
response_2 = self._payload_responses[RobotPmsPaddingPayloadEnum.WRONG_POSITION_00][0]
response_3 = self._payload_responses[RobotPmsPaddingPayloadEnum.NO_00_IN_THE_MIDDLE][0]
# From the original script:
# If the response to the invalid PKCS#1 request (oracle_bad1) is equal to both
# requests starting with 0002, we have a weak oracle. This is because the only
# case where we can distinguish valid from invalid requests is when we send
# correctly formatted PKCS#1 message with 0x00 on a correct position. This
# makes our oracle weak
if response_1 == response_2 == response_3:
return RobotScanResultEnum.VULNERABLE_WEAK_ORACLE
else:
return RobotScanResultEnum.VULNERABLE_STRONG_ORACLE | [
"def",
"compute_result_enum",
"(",
"self",
")",
"->",
"RobotScanResultEnum",
":",
"# Ensure the results were consistent",
"for",
"payload_enum",
",",
"server_responses",
"in",
"self",
".",
"_payload_responses",
".",
"items",
"(",
")",
":",
"# We ran the check twice per payload and the two responses should be the same",
"if",
"server_responses",
"[",
"0",
"]",
"!=",
"server_responses",
"[",
"1",
"]",
":",
"return",
"RobotScanResultEnum",
".",
"UNKNOWN_INCONSISTENT_RESULTS",
"# Check if the server acts as an oracle by checking if the server replied differently to the payloads",
"if",
"len",
"(",
"set",
"(",
"[",
"server_responses",
"[",
"0",
"]",
"for",
"server_responses",
"in",
"self",
".",
"_payload_responses",
".",
"values",
"(",
")",
"]",
")",
")",
"==",
"1",
":",
"# All server responses were identical - no oracle",
"return",
"RobotScanResultEnum",
".",
"NOT_VULNERABLE_NO_ORACLE",
"# All server responses were NOT identical, server is vulnerable",
"# Check to see if it is a weak oracle",
"response_1",
"=",
"self",
".",
"_payload_responses",
"[",
"RobotPmsPaddingPayloadEnum",
".",
"WRONG_FIRST_TWO_BYTES",
"]",
"[",
"0",
"]",
"response_2",
"=",
"self",
".",
"_payload_responses",
"[",
"RobotPmsPaddingPayloadEnum",
".",
"WRONG_POSITION_00",
"]",
"[",
"0",
"]",
"response_3",
"=",
"self",
".",
"_payload_responses",
"[",
"RobotPmsPaddingPayloadEnum",
".",
"NO_00_IN_THE_MIDDLE",
"]",
"[",
"0",
"]",
"# From the original script:",
"# If the response to the invalid PKCS#1 request (oracle_bad1) is equal to both",
"# requests starting with 0002, we have a weak oracle. This is because the only",
"# case where we can distinguish valid from invalid requests is when we send",
"# correctly formatted PKCS#1 message with 0x00 on a correct position. This",
"# makes our oracle weak",
"if",
"response_1",
"==",
"response_2",
"==",
"response_3",
":",
"return",
"RobotScanResultEnum",
".",
"VULNERABLE_WEAK_ORACLE",
"else",
":",
"return",
"RobotScanResultEnum",
".",
"VULNERABLE_STRONG_ORACLE"
] | Look at the server's response to each ROBOT payload and return the conclusion of the analysis. | [
"Look",
"at",
"the",
"server",
"s",
"response",
"to",
"each",
"ROBOT",
"payload",
"and",
"return",
"the",
"conclusion",
"of",
"the",
"analysis",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/robot_plugin.py#L135-L164 |
227,282 | nabla-c0d3/sslyze | sslyze/plugins/utils/trust_store/trust_store.py | TrustStore.is_extended_validation | def is_extended_validation(self, certificate: Certificate) -> bool:
"""Is the supplied server certificate EV?
"""
if not self.ev_oids:
raise ValueError('No EV OIDs supplied for {} store - cannot detect EV certificates'.format(self.name))
try:
cert_policies_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.CERTIFICATE_POLICIES)
except ExtensionNotFound:
return False
for policy in cert_policies_ext.value:
if policy.policy_identifier in self.ev_oids:
return True
return False | python | def is_extended_validation(self, certificate: Certificate) -> bool:
"""Is the supplied server certificate EV?
"""
if not self.ev_oids:
raise ValueError('No EV OIDs supplied for {} store - cannot detect EV certificates'.format(self.name))
try:
cert_policies_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.CERTIFICATE_POLICIES)
except ExtensionNotFound:
return False
for policy in cert_policies_ext.value:
if policy.policy_identifier in self.ev_oids:
return True
return False | [
"def",
"is_extended_validation",
"(",
"self",
",",
"certificate",
":",
"Certificate",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"ev_oids",
":",
"raise",
"ValueError",
"(",
"'No EV OIDs supplied for {} store - cannot detect EV certificates'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"try",
":",
"cert_policies_ext",
"=",
"certificate",
".",
"extensions",
".",
"get_extension_for_oid",
"(",
"ExtensionOID",
".",
"CERTIFICATE_POLICIES",
")",
"except",
"ExtensionNotFound",
":",
"return",
"False",
"for",
"policy",
"in",
"cert_policies_ext",
".",
"value",
":",
"if",
"policy",
".",
"policy_identifier",
"in",
"self",
".",
"ev_oids",
":",
"return",
"True",
"return",
"False"
] | Is the supplied server certificate EV? | [
"Is",
"the",
"supplied",
"server",
"certificate",
"EV?"
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/trust_store/trust_store.py#L58-L72 |
227,283 | nabla-c0d3/sslyze | sslyze/synchronous_scanner.py | SynchronousScanner.run_scan_command | def run_scan_command(
self,
server_info: ServerConnectivityInfo,
scan_command: PluginScanCommand
) -> PluginScanResult:
"""Run a single scan command against a server; will block until the scan command has been completed.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
Returns:
The result of the scan command, which will be an instance of the scan command's
corresponding PluginScanResult subclass.
"""
plugin_class = self._plugins_repository.get_plugin_class_for_command(scan_command)
plugin = plugin_class()
return plugin.process_task(server_info, scan_command) | python | def run_scan_command(
self,
server_info: ServerConnectivityInfo,
scan_command: PluginScanCommand
) -> PluginScanResult:
"""Run a single scan command against a server; will block until the scan command has been completed.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
Returns:
The result of the scan command, which will be an instance of the scan command's
corresponding PluginScanResult subclass.
"""
plugin_class = self._plugins_repository.get_plugin_class_for_command(scan_command)
plugin = plugin_class()
return plugin.process_task(server_info, scan_command) | [
"def",
"run_scan_command",
"(",
"self",
",",
"server_info",
":",
"ServerConnectivityInfo",
",",
"scan_command",
":",
"PluginScanCommand",
")",
"->",
"PluginScanResult",
":",
"plugin_class",
"=",
"self",
".",
"_plugins_repository",
".",
"get_plugin_class_for_command",
"(",
"scan_command",
")",
"plugin",
"=",
"plugin_class",
"(",
")",
"return",
"plugin",
".",
"process_task",
"(",
"server_info",
",",
"scan_command",
")"
] | Run a single scan command against a server; will block until the scan command has been completed.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
Returns:
The result of the scan command, which will be an instance of the scan command's
corresponding PluginScanResult subclass. | [
"Run",
"a",
"single",
"scan",
"command",
"against",
"a",
"server",
";",
"will",
"block",
"until",
"the",
"scan",
"command",
"has",
"been",
"completed",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/synchronous_scanner.py#L32-L50 |
227,284 | nabla-c0d3/sslyze | sslyze/plugins/utils/trust_store/trust_store_repository.py | TrustStoresRepository.update_default | def update_default(cls) -> 'TrustStoresRepository':
"""Update the default trust stores used by SSLyze.
The latest stores will be downloaded from https://github.com/nabla-c0d3/trust_stores_observatory.
"""
temp_path = mkdtemp()
try:
# Download the latest trust stores
archive_path = join(temp_path, 'trust_stores_as_pem.tar.gz')
urlretrieve(cls._UPDATE_URL, archive_path)
# Extract the archive
extract_path = join(temp_path, 'extracted')
tarfile.open(archive_path).extractall(extract_path)
# Copy the files to SSLyze and overwrite the existing stores
shutil.rmtree(cls._DEFAULT_TRUST_STORES_PATH)
shutil.copytree(extract_path, cls._DEFAULT_TRUST_STORES_PATH)
finally:
shutil.rmtree(temp_path)
# Re-generate the default repo - not thread-safe
cls._DEFAULT_REPOSITORY = cls(cls._DEFAULT_TRUST_STORES_PATH)
return cls._DEFAULT_REPOSITORY | python | def update_default(cls) -> 'TrustStoresRepository':
"""Update the default trust stores used by SSLyze.
The latest stores will be downloaded from https://github.com/nabla-c0d3/trust_stores_observatory.
"""
temp_path = mkdtemp()
try:
# Download the latest trust stores
archive_path = join(temp_path, 'trust_stores_as_pem.tar.gz')
urlretrieve(cls._UPDATE_URL, archive_path)
# Extract the archive
extract_path = join(temp_path, 'extracted')
tarfile.open(archive_path).extractall(extract_path)
# Copy the files to SSLyze and overwrite the existing stores
shutil.rmtree(cls._DEFAULT_TRUST_STORES_PATH)
shutil.copytree(extract_path, cls._DEFAULT_TRUST_STORES_PATH)
finally:
shutil.rmtree(temp_path)
# Re-generate the default repo - not thread-safe
cls._DEFAULT_REPOSITORY = cls(cls._DEFAULT_TRUST_STORES_PATH)
return cls._DEFAULT_REPOSITORY | [
"def",
"update_default",
"(",
"cls",
")",
"->",
"'TrustStoresRepository'",
":",
"temp_path",
"=",
"mkdtemp",
"(",
")",
"try",
":",
"# Download the latest trust stores",
"archive_path",
"=",
"join",
"(",
"temp_path",
",",
"'trust_stores_as_pem.tar.gz'",
")",
"urlretrieve",
"(",
"cls",
".",
"_UPDATE_URL",
",",
"archive_path",
")",
"# Extract the archive",
"extract_path",
"=",
"join",
"(",
"temp_path",
",",
"'extracted'",
")",
"tarfile",
".",
"open",
"(",
"archive_path",
")",
".",
"extractall",
"(",
"extract_path",
")",
"# Copy the files to SSLyze and overwrite the existing stores",
"shutil",
".",
"rmtree",
"(",
"cls",
".",
"_DEFAULT_TRUST_STORES_PATH",
")",
"shutil",
".",
"copytree",
"(",
"extract_path",
",",
"cls",
".",
"_DEFAULT_TRUST_STORES_PATH",
")",
"finally",
":",
"shutil",
".",
"rmtree",
"(",
"temp_path",
")",
"# Re-generate the default repo - not thread-safe",
"cls",
".",
"_DEFAULT_REPOSITORY",
"=",
"cls",
"(",
"cls",
".",
"_DEFAULT_TRUST_STORES_PATH",
")",
"return",
"cls",
".",
"_DEFAULT_REPOSITORY"
] | Update the default trust stores used by SSLyze.
The latest stores will be downloaded from https://github.com/nabla-c0d3/trust_stores_observatory. | [
"Update",
"the",
"default",
"trust",
"stores",
"used",
"by",
"SSLyze",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/trust_store/trust_store_repository.py#L123-L146 |
227,285 | nabla-c0d3/sslyze | sslyze/plugins/openssl_cipher_suites_plugin.py | OpenSslCipherSuitesPlugin._get_preferred_cipher_suite | def _get_preferred_cipher_suite(
cls,
server_connectivity_info: ServerConnectivityInfo,
ssl_version: OpenSslVersionEnum,
accepted_cipher_list: List['AcceptedCipherSuite']
) -> Optional['AcceptedCipherSuite']:
"""Try to detect the server's preferred cipher suite among all cipher suites supported by SSLyze.
"""
if len(accepted_cipher_list) < 2:
return None
accepted_cipher_names = [cipher.openssl_name for cipher in accepted_cipher_list]
should_use_legacy_openssl = None
# For TLS 1.2, we need to figure whether the modern or legacy OpenSSL should be used to connect
if ssl_version == OpenSslVersionEnum.TLSV1_2:
should_use_legacy_openssl = True
# If there are more than two modern-supported cipher suites, use the modern OpenSSL
for cipher_name in accepted_cipher_names:
modern_supported_cipher_count = 0
if not WorkaroundForTls12ForCipherSuites.requires_legacy_openssl(cipher_name):
modern_supported_cipher_count += 1
if modern_supported_cipher_count > 1:
should_use_legacy_openssl = False
break
first_cipher_str = ', '.join(accepted_cipher_names)
# Swap the first two ciphers in the list to see if the server always picks the client's first cipher
second_cipher_str = ', '.join([accepted_cipher_names[1], accepted_cipher_names[0]] + accepted_cipher_names[2:])
try:
first_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, first_cipher_str, should_use_legacy_openssl
)
second_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, second_cipher_str, should_use_legacy_openssl
)
except (SslHandshakeRejected, ConnectionError):
# Could not complete a handshake
return None
if first_cipher.name == second_cipher.name:
# The server has its own preference for picking a cipher suite
return first_cipher
else:
# The server has no preferred cipher suite as it follows the client's preference for picking a cipher suite
return None | python | def _get_preferred_cipher_suite(
cls,
server_connectivity_info: ServerConnectivityInfo,
ssl_version: OpenSslVersionEnum,
accepted_cipher_list: List['AcceptedCipherSuite']
) -> Optional['AcceptedCipherSuite']:
"""Try to detect the server's preferred cipher suite among all cipher suites supported by SSLyze.
"""
if len(accepted_cipher_list) < 2:
return None
accepted_cipher_names = [cipher.openssl_name for cipher in accepted_cipher_list]
should_use_legacy_openssl = None
# For TLS 1.2, we need to figure whether the modern or legacy OpenSSL should be used to connect
if ssl_version == OpenSslVersionEnum.TLSV1_2:
should_use_legacy_openssl = True
# If there are more than two modern-supported cipher suites, use the modern OpenSSL
for cipher_name in accepted_cipher_names:
modern_supported_cipher_count = 0
if not WorkaroundForTls12ForCipherSuites.requires_legacy_openssl(cipher_name):
modern_supported_cipher_count += 1
if modern_supported_cipher_count > 1:
should_use_legacy_openssl = False
break
first_cipher_str = ', '.join(accepted_cipher_names)
# Swap the first two ciphers in the list to see if the server always picks the client's first cipher
second_cipher_str = ', '.join([accepted_cipher_names[1], accepted_cipher_names[0]] + accepted_cipher_names[2:])
try:
first_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, first_cipher_str, should_use_legacy_openssl
)
second_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, second_cipher_str, should_use_legacy_openssl
)
except (SslHandshakeRejected, ConnectionError):
# Could not complete a handshake
return None
if first_cipher.name == second_cipher.name:
# The server has its own preference for picking a cipher suite
return first_cipher
else:
# The server has no preferred cipher suite as it follows the client's preference for picking a cipher suite
return None | [
"def",
"_get_preferred_cipher_suite",
"(",
"cls",
",",
"server_connectivity_info",
":",
"ServerConnectivityInfo",
",",
"ssl_version",
":",
"OpenSslVersionEnum",
",",
"accepted_cipher_list",
":",
"List",
"[",
"'AcceptedCipherSuite'",
"]",
")",
"->",
"Optional",
"[",
"'AcceptedCipherSuite'",
"]",
":",
"if",
"len",
"(",
"accepted_cipher_list",
")",
"<",
"2",
":",
"return",
"None",
"accepted_cipher_names",
"=",
"[",
"cipher",
".",
"openssl_name",
"for",
"cipher",
"in",
"accepted_cipher_list",
"]",
"should_use_legacy_openssl",
"=",
"None",
"# For TLS 1.2, we need to figure whether the modern or legacy OpenSSL should be used to connect",
"if",
"ssl_version",
"==",
"OpenSslVersionEnum",
".",
"TLSV1_2",
":",
"should_use_legacy_openssl",
"=",
"True",
"# If there are more than two modern-supported cipher suites, use the modern OpenSSL",
"for",
"cipher_name",
"in",
"accepted_cipher_names",
":",
"modern_supported_cipher_count",
"=",
"0",
"if",
"not",
"WorkaroundForTls12ForCipherSuites",
".",
"requires_legacy_openssl",
"(",
"cipher_name",
")",
":",
"modern_supported_cipher_count",
"+=",
"1",
"if",
"modern_supported_cipher_count",
">",
"1",
":",
"should_use_legacy_openssl",
"=",
"False",
"break",
"first_cipher_str",
"=",
"', '",
".",
"join",
"(",
"accepted_cipher_names",
")",
"# Swap the first two ciphers in the list to see if the server always picks the client's first cipher",
"second_cipher_str",
"=",
"', '",
".",
"join",
"(",
"[",
"accepted_cipher_names",
"[",
"1",
"]",
",",
"accepted_cipher_names",
"[",
"0",
"]",
"]",
"+",
"accepted_cipher_names",
"[",
"2",
":",
"]",
")",
"try",
":",
"first_cipher",
"=",
"cls",
".",
"_get_selected_cipher_suite",
"(",
"server_connectivity_info",
",",
"ssl_version",
",",
"first_cipher_str",
",",
"should_use_legacy_openssl",
")",
"second_cipher",
"=",
"cls",
".",
"_get_selected_cipher_suite",
"(",
"server_connectivity_info",
",",
"ssl_version",
",",
"second_cipher_str",
",",
"should_use_legacy_openssl",
")",
"except",
"(",
"SslHandshakeRejected",
",",
"ConnectionError",
")",
":",
"# Could not complete a handshake",
"return",
"None",
"if",
"first_cipher",
".",
"name",
"==",
"second_cipher",
".",
"name",
":",
"# The server has its own preference for picking a cipher suite",
"return",
"first_cipher",
"else",
":",
"# The server has no preferred cipher suite as it follows the client's preference for picking a cipher suite",
"return",
"None"
] | Try to detect the server's preferred cipher suite among all cipher suites supported by SSLyze. | [
"Try",
"to",
"detect",
"the",
"server",
"s",
"preferred",
"cipher",
"suite",
"among",
"all",
"cipher",
"suites",
"supported",
"by",
"SSLyze",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/openssl_cipher_suites_plugin.py#L283-L330 |
227,286 | nabla-c0d3/sslyze | sslyze/plugins/openssl_cipher_suites_plugin.py | CipherSuite.name | def name(self) -> str:
"""OpenSSL uses a different naming convention than the corresponding RFCs.
"""
return OPENSSL_TO_RFC_NAMES_MAPPING[self.ssl_version].get(self.openssl_name, self.openssl_name) | python | def name(self) -> str:
"""OpenSSL uses a different naming convention than the corresponding RFCs.
"""
return OPENSSL_TO_RFC_NAMES_MAPPING[self.ssl_version].get(self.openssl_name, self.openssl_name) | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"OPENSSL_TO_RFC_NAMES_MAPPING",
"[",
"self",
".",
"ssl_version",
"]",
".",
"get",
"(",
"self",
".",
"openssl_name",
",",
"self",
".",
"openssl_name",
")"
] | OpenSSL uses a different naming convention than the corresponding RFCs. | [
"OpenSSL",
"uses",
"a",
"different",
"naming",
"convention",
"than",
"the",
"corresponding",
"RFCs",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/openssl_cipher_suites_plugin.py#L366-L369 |
227,287 | nabla-c0d3/sslyze | sslyze/concurrent_scanner.py | ConcurrentScanner.queue_scan_command | def queue_scan_command(self, server_info: ServerConnectivityInfo, scan_command: PluginScanCommand) -> None:
"""Queue a scan command targeting a specific server.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
"""
# Ensure we have the right processes and queues in place for this hostname
self._check_and_create_process(server_info.hostname)
# Add the task to the right queue
self._queued_tasks_nb += 1
if scan_command.is_aggressive:
# Aggressive commands should not be run in parallel against
# a given server so we use the priority queues to prevent this
self._hostname_queues_dict[server_info.hostname].put((server_info, scan_command))
else:
# Normal commands get put in the standard/shared queue
self._task_queue.put((server_info, scan_command)) | python | def queue_scan_command(self, server_info: ServerConnectivityInfo, scan_command: PluginScanCommand) -> None:
"""Queue a scan command targeting a specific server.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
"""
# Ensure we have the right processes and queues in place for this hostname
self._check_and_create_process(server_info.hostname)
# Add the task to the right queue
self._queued_tasks_nb += 1
if scan_command.is_aggressive:
# Aggressive commands should not be run in parallel against
# a given server so we use the priority queues to prevent this
self._hostname_queues_dict[server_info.hostname].put((server_info, scan_command))
else:
# Normal commands get put in the standard/shared queue
self._task_queue.put((server_info, scan_command)) | [
"def",
"queue_scan_command",
"(",
"self",
",",
"server_info",
":",
"ServerConnectivityInfo",
",",
"scan_command",
":",
"PluginScanCommand",
")",
"->",
"None",
":",
"# Ensure we have the right processes and queues in place for this hostname",
"self",
".",
"_check_and_create_process",
"(",
"server_info",
".",
"hostname",
")",
"# Add the task to the right queue",
"self",
".",
"_queued_tasks_nb",
"+=",
"1",
"if",
"scan_command",
".",
"is_aggressive",
":",
"# Aggressive commands should not be run in parallel against",
"# a given server so we use the priority queues to prevent this",
"self",
".",
"_hostname_queues_dict",
"[",
"server_info",
".",
"hostname",
"]",
".",
"put",
"(",
"(",
"server_info",
",",
"scan_command",
")",
")",
"else",
":",
"# Normal commands get put in the standard/shared queue",
"self",
".",
"_task_queue",
".",
"put",
"(",
"(",
"server_info",
",",
"scan_command",
")",
")"
] | Queue a scan command targeting a specific server.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server. | [
"Queue",
"a",
"scan",
"command",
"targeting",
"a",
"specific",
"server",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/concurrent_scanner.py#L83-L102 |
227,288 | nabla-c0d3/sslyze | sslyze/concurrent_scanner.py | ConcurrentScanner.get_results | def get_results(self) -> Iterable[PluginScanResult]:
"""Return the result of previously queued scan commands; new commands cannot be queued once this is called.
Returns:
The results of all the scan commands previously queued. Each result will be an instance of the scan
corresponding command's PluginScanResult subclass. If there was an unexpected error while running the scan
command, it will be a 'PluginRaisedExceptionScanResult' instance instead.
"""
# Put a 'None' sentinel in the queue to let the each process know when every task has been completed
for _ in range(self._get_current_processes_nb()):
self._task_queue.put(None)
for hostname, hostname_queue in self._hostname_queues_dict.items():
for i in range(len(self._processes_dict[hostname])):
hostname_queue.put(None)
received_task_results = 0
# Go on until all the tasks have been completed and all processes are done
expected_task_results = self._queued_tasks_nb + self._get_current_processes_nb()
while received_task_results != expected_task_results:
result = self._result_queue.get()
self._result_queue.task_done()
received_task_results += 1
if result is None:
# Getting None means that one process was done
pass
else:
# Getting an actual result
yield result
# Ensure all the queues and processes are done
self._task_queue.join()
self._result_queue.join()
for hostname_queue in self._hostname_queues_dict.values():
hostname_queue.join()
for process_list in self._processes_dict.values():
for process in process_list:
process.join() | python | def get_results(self) -> Iterable[PluginScanResult]:
"""Return the result of previously queued scan commands; new commands cannot be queued once this is called.
Returns:
The results of all the scan commands previously queued. Each result will be an instance of the scan
corresponding command's PluginScanResult subclass. If there was an unexpected error while running the scan
command, it will be a 'PluginRaisedExceptionScanResult' instance instead.
"""
# Put a 'None' sentinel in the queue to let the each process know when every task has been completed
for _ in range(self._get_current_processes_nb()):
self._task_queue.put(None)
for hostname, hostname_queue in self._hostname_queues_dict.items():
for i in range(len(self._processes_dict[hostname])):
hostname_queue.put(None)
received_task_results = 0
# Go on until all the tasks have been completed and all processes are done
expected_task_results = self._queued_tasks_nb + self._get_current_processes_nb()
while received_task_results != expected_task_results:
result = self._result_queue.get()
self._result_queue.task_done()
received_task_results += 1
if result is None:
# Getting None means that one process was done
pass
else:
# Getting an actual result
yield result
# Ensure all the queues and processes are done
self._task_queue.join()
self._result_queue.join()
for hostname_queue in self._hostname_queues_dict.values():
hostname_queue.join()
for process_list in self._processes_dict.values():
for process in process_list:
process.join() | [
"def",
"get_results",
"(",
"self",
")",
"->",
"Iterable",
"[",
"PluginScanResult",
"]",
":",
"# Put a 'None' sentinel in the queue to let the each process know when every task has been completed",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"_get_current_processes_nb",
"(",
")",
")",
":",
"self",
".",
"_task_queue",
".",
"put",
"(",
"None",
")",
"for",
"hostname",
",",
"hostname_queue",
"in",
"self",
".",
"_hostname_queues_dict",
".",
"items",
"(",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_processes_dict",
"[",
"hostname",
"]",
")",
")",
":",
"hostname_queue",
".",
"put",
"(",
"None",
")",
"received_task_results",
"=",
"0",
"# Go on until all the tasks have been completed and all processes are done",
"expected_task_results",
"=",
"self",
".",
"_queued_tasks_nb",
"+",
"self",
".",
"_get_current_processes_nb",
"(",
")",
"while",
"received_task_results",
"!=",
"expected_task_results",
":",
"result",
"=",
"self",
".",
"_result_queue",
".",
"get",
"(",
")",
"self",
".",
"_result_queue",
".",
"task_done",
"(",
")",
"received_task_results",
"+=",
"1",
"if",
"result",
"is",
"None",
":",
"# Getting None means that one process was done",
"pass",
"else",
":",
"# Getting an actual result",
"yield",
"result",
"# Ensure all the queues and processes are done",
"self",
".",
"_task_queue",
".",
"join",
"(",
")",
"self",
".",
"_result_queue",
".",
"join",
"(",
")",
"for",
"hostname_queue",
"in",
"self",
".",
"_hostname_queues_dict",
".",
"values",
"(",
")",
":",
"hostname_queue",
".",
"join",
"(",
")",
"for",
"process_list",
"in",
"self",
".",
"_processes_dict",
".",
"values",
"(",
")",
":",
"for",
"process",
"in",
"process_list",
":",
"process",
".",
"join",
"(",
")"
] | Return the result of previously queued scan commands; new commands cannot be queued once this is called.
Returns:
The results of all the scan commands previously queued. Each result will be an instance of the scan
corresponding command's PluginScanResult subclass. If there was an unexpected error while running the scan
command, it will be a 'PluginRaisedExceptionScanResult' instance instead. | [
"Return",
"the",
"result",
"of",
"previously",
"queued",
"scan",
"commands",
";",
"new",
"commands",
"cannot",
"be",
"queued",
"once",
"this",
"is",
"called",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/concurrent_scanner.py#L135-L172 |
227,289 | nabla-c0d3/sslyze | sslyze/utils/worker_process.py | WorkerProcess.run | def run(self) -> None:
"""The process will first complete tasks it gets from self.queue_in.
Once it gets notified that all the tasks have been completed, it terminates.
"""
from sslyze.concurrent_scanner import PluginRaisedExceptionScanResult
# Start processing task in the priority queue first
current_queue_in = self.priority_queue_in
while True:
task = current_queue_in.get() # Grab a task from queue_in
if task is None: # All tasks have been completed
current_queue_in.task_done()
if current_queue_in == self.priority_queue_in:
# All high priority tasks have been completed; switch to low priority tasks
current_queue_in = self.queue_in
continue
else:
# All the tasks have been completed; pass on the sentinel to result_queue and exit
self.queue_out.put(None)
break
server_info, scan_command = task
try:
result = self._synchronous_scanner.run_scan_command(server_info, scan_command)
except Exception as e:
# raise
result = PluginRaisedExceptionScanResult(server_info, scan_command, e)
# Send the result to queue_out
self.queue_out.put(result)
current_queue_in.task_done() | python | def run(self) -> None:
"""The process will first complete tasks it gets from self.queue_in.
Once it gets notified that all the tasks have been completed, it terminates.
"""
from sslyze.concurrent_scanner import PluginRaisedExceptionScanResult
# Start processing task in the priority queue first
current_queue_in = self.priority_queue_in
while True:
task = current_queue_in.get() # Grab a task from queue_in
if task is None: # All tasks have been completed
current_queue_in.task_done()
if current_queue_in == self.priority_queue_in:
# All high priority tasks have been completed; switch to low priority tasks
current_queue_in = self.queue_in
continue
else:
# All the tasks have been completed; pass on the sentinel to result_queue and exit
self.queue_out.put(None)
break
server_info, scan_command = task
try:
result = self._synchronous_scanner.run_scan_command(server_info, scan_command)
except Exception as e:
# raise
result = PluginRaisedExceptionScanResult(server_info, scan_command, e)
# Send the result to queue_out
self.queue_out.put(result)
current_queue_in.task_done() | [
"def",
"run",
"(",
"self",
")",
"->",
"None",
":",
"from",
"sslyze",
".",
"concurrent_scanner",
"import",
"PluginRaisedExceptionScanResult",
"# Start processing task in the priority queue first",
"current_queue_in",
"=",
"self",
".",
"priority_queue_in",
"while",
"True",
":",
"task",
"=",
"current_queue_in",
".",
"get",
"(",
")",
"# Grab a task from queue_in",
"if",
"task",
"is",
"None",
":",
"# All tasks have been completed",
"current_queue_in",
".",
"task_done",
"(",
")",
"if",
"current_queue_in",
"==",
"self",
".",
"priority_queue_in",
":",
"# All high priority tasks have been completed; switch to low priority tasks",
"current_queue_in",
"=",
"self",
".",
"queue_in",
"continue",
"else",
":",
"# All the tasks have been completed; pass on the sentinel to result_queue and exit",
"self",
".",
"queue_out",
".",
"put",
"(",
"None",
")",
"break",
"server_info",
",",
"scan_command",
"=",
"task",
"try",
":",
"result",
"=",
"self",
".",
"_synchronous_scanner",
".",
"run_scan_command",
"(",
"server_info",
",",
"scan_command",
")",
"except",
"Exception",
"as",
"e",
":",
"# raise",
"result",
"=",
"PluginRaisedExceptionScanResult",
"(",
"server_info",
",",
"scan_command",
",",
"e",
")",
"# Send the result to queue_out",
"self",
".",
"queue_out",
".",
"put",
"(",
"result",
")",
"current_queue_in",
".",
"task_done",
"(",
")"
] | The process will first complete tasks it gets from self.queue_in.
Once it gets notified that all the tasks have been completed, it terminates. | [
"The",
"process",
"will",
"first",
"complete",
"tasks",
"it",
"gets",
"from",
"self",
".",
"queue_in",
".",
"Once",
"it",
"gets",
"notified",
"that",
"all",
"the",
"tasks",
"have",
"been",
"completed",
"it",
"terminates",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/worker_process.py#L26-L58 |
227,290 | nabla-c0d3/sslyze | sslyze/utils/connection_helpers.py | ProxyTunnelingConnectionHelper.connect_socket | def connect_socket(self, sock: socket.socket) -> None:
"""Setup HTTP tunneling with the configured proxy.
"""
# Setup HTTP tunneling
try:
sock.connect((self._tunnel_host, self._tunnel_port))
except socket.timeout as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
except socket.error as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
# Send a CONNECT request with the host we want to tunnel to
if self._tunnel_basic_auth_token is None:
sock.send(self.HTTP_CONNECT_REQ.format(self._server_host, self._server_port).encode('utf-8'))
else:
sock.send(self.HTTP_CONNECT_REQ_PROXY_AUTH_BASIC.format(
self._server_host, self._server_port, self._tunnel_basic_auth_token
).encode('utf-8'))
http_response = HttpResponseParser.parse_from_socket(sock)
# Check if the proxy was able to connect to the host
if http_response.status != 200:
raise ProxyError(self.ERR_CONNECT_REJECTED) | python | def connect_socket(self, sock: socket.socket) -> None:
"""Setup HTTP tunneling with the configured proxy.
"""
# Setup HTTP tunneling
try:
sock.connect((self._tunnel_host, self._tunnel_port))
except socket.timeout as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
except socket.error as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
# Send a CONNECT request with the host we want to tunnel to
if self._tunnel_basic_auth_token is None:
sock.send(self.HTTP_CONNECT_REQ.format(self._server_host, self._server_port).encode('utf-8'))
else:
sock.send(self.HTTP_CONNECT_REQ_PROXY_AUTH_BASIC.format(
self._server_host, self._server_port, self._tunnel_basic_auth_token
).encode('utf-8'))
http_response = HttpResponseParser.parse_from_socket(sock)
# Check if the proxy was able to connect to the host
if http_response.status != 200:
raise ProxyError(self.ERR_CONNECT_REJECTED) | [
"def",
"connect_socket",
"(",
"self",
",",
"sock",
":",
"socket",
".",
"socket",
")",
"->",
"None",
":",
"# Setup HTTP tunneling",
"try",
":",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"_tunnel_host",
",",
"self",
".",
"_tunnel_port",
")",
")",
"except",
"socket",
".",
"timeout",
"as",
"e",
":",
"raise",
"ProxyError",
"(",
"self",
".",
"ERR_PROXY_OFFLINE",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"raise",
"ProxyError",
"(",
"self",
".",
"ERR_PROXY_OFFLINE",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")",
"# Send a CONNECT request with the host we want to tunnel to",
"if",
"self",
".",
"_tunnel_basic_auth_token",
"is",
"None",
":",
"sock",
".",
"send",
"(",
"self",
".",
"HTTP_CONNECT_REQ",
".",
"format",
"(",
"self",
".",
"_server_host",
",",
"self",
".",
"_server_port",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"else",
":",
"sock",
".",
"send",
"(",
"self",
".",
"HTTP_CONNECT_REQ_PROXY_AUTH_BASIC",
".",
"format",
"(",
"self",
".",
"_server_host",
",",
"self",
".",
"_server_port",
",",
"self",
".",
"_tunnel_basic_auth_token",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"http_response",
"=",
"HttpResponseParser",
".",
"parse_from_socket",
"(",
"sock",
")",
"# Check if the proxy was able to connect to the host",
"if",
"http_response",
".",
"status",
"!=",
"200",
":",
"raise",
"ProxyError",
"(",
"self",
".",
"ERR_CONNECT_REJECTED",
")"
] | Setup HTTP tunneling with the configured proxy. | [
"Setup",
"HTTP",
"tunneling",
"with",
"the",
"configured",
"proxy",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/connection_helpers.py#L63-L85 |
227,291 | nabla-c0d3/sslyze | sslyze/server_connectivity_info.py | ServerConnectivityInfo.get_preconfigured_ssl_connection | def get_preconfigured_ssl_connection(
self,
override_ssl_version: Optional[OpenSslVersionEnum] = None,
ssl_verify_locations: Optional[str] = None,
should_use_legacy_openssl: Optional[bool] = None,
) -> SslConnection:
"""Get an SSLConnection instance with the right SSL configuration for successfully connecting to the server.
Used by all plugins to connect to the server and run scans.
"""
if override_ssl_version is not None:
# Caller wants to override the ssl version to use for this connection
final_ssl_version = override_ssl_version
# Then we don't know which cipher suite is supported by the server for this ssl version
openssl_cipher_string = None
else:
# Use the ssl version and cipher suite that were successful during connectivity testing
final_ssl_version = self.highest_ssl_version_supported
openssl_cipher_string = self.openssl_cipher_string_supported
if should_use_legacy_openssl is not None:
# Caller wants to override which version of OpenSSL to use
# Then we don't know which cipher suite is supported by this version of OpenSSL
openssl_cipher_string = None
if self.client_auth_credentials is not None:
# If we have creds for client authentication, go ahead and use them
should_ignore_client_auth = False
else:
# Ignore client auth requests if the server allows optional TLS client authentication
should_ignore_client_auth = True
# But do not ignore them is client authentication is required so that the right exceptions get thrown
# within the plugins, providing a better output
if self.client_auth_requirement == ClientAuthenticationServerConfigurationEnum.REQUIRED:
should_ignore_client_auth = False
ssl_connection = SslConnectionConfigurator.get_connection(
ssl_version=final_ssl_version,
server_info=self,
openssl_cipher_string=openssl_cipher_string,
ssl_verify_locations=ssl_verify_locations,
should_use_legacy_openssl=should_use_legacy_openssl,
should_ignore_client_auth=should_ignore_client_auth,
)
return ssl_connection | python | def get_preconfigured_ssl_connection(
self,
override_ssl_version: Optional[OpenSslVersionEnum] = None,
ssl_verify_locations: Optional[str] = None,
should_use_legacy_openssl: Optional[bool] = None,
) -> SslConnection:
"""Get an SSLConnection instance with the right SSL configuration for successfully connecting to the server.
Used by all plugins to connect to the server and run scans.
"""
if override_ssl_version is not None:
# Caller wants to override the ssl version to use for this connection
final_ssl_version = override_ssl_version
# Then we don't know which cipher suite is supported by the server for this ssl version
openssl_cipher_string = None
else:
# Use the ssl version and cipher suite that were successful during connectivity testing
final_ssl_version = self.highest_ssl_version_supported
openssl_cipher_string = self.openssl_cipher_string_supported
if should_use_legacy_openssl is not None:
# Caller wants to override which version of OpenSSL to use
# Then we don't know which cipher suite is supported by this version of OpenSSL
openssl_cipher_string = None
if self.client_auth_credentials is not None:
# If we have creds for client authentication, go ahead and use them
should_ignore_client_auth = False
else:
# Ignore client auth requests if the server allows optional TLS client authentication
should_ignore_client_auth = True
# But do not ignore them is client authentication is required so that the right exceptions get thrown
# within the plugins, providing a better output
if self.client_auth_requirement == ClientAuthenticationServerConfigurationEnum.REQUIRED:
should_ignore_client_auth = False
ssl_connection = SslConnectionConfigurator.get_connection(
ssl_version=final_ssl_version,
server_info=self,
openssl_cipher_string=openssl_cipher_string,
ssl_verify_locations=ssl_verify_locations,
should_use_legacy_openssl=should_use_legacy_openssl,
should_ignore_client_auth=should_ignore_client_auth,
)
return ssl_connection | [
"def",
"get_preconfigured_ssl_connection",
"(",
"self",
",",
"override_ssl_version",
":",
"Optional",
"[",
"OpenSslVersionEnum",
"]",
"=",
"None",
",",
"ssl_verify_locations",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"should_use_legacy_openssl",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
")",
"->",
"SslConnection",
":",
"if",
"override_ssl_version",
"is",
"not",
"None",
":",
"# Caller wants to override the ssl version to use for this connection",
"final_ssl_version",
"=",
"override_ssl_version",
"# Then we don't know which cipher suite is supported by the server for this ssl version",
"openssl_cipher_string",
"=",
"None",
"else",
":",
"# Use the ssl version and cipher suite that were successful during connectivity testing",
"final_ssl_version",
"=",
"self",
".",
"highest_ssl_version_supported",
"openssl_cipher_string",
"=",
"self",
".",
"openssl_cipher_string_supported",
"if",
"should_use_legacy_openssl",
"is",
"not",
"None",
":",
"# Caller wants to override which version of OpenSSL to use",
"# Then we don't know which cipher suite is supported by this version of OpenSSL",
"openssl_cipher_string",
"=",
"None",
"if",
"self",
".",
"client_auth_credentials",
"is",
"not",
"None",
":",
"# If we have creds for client authentication, go ahead and use them",
"should_ignore_client_auth",
"=",
"False",
"else",
":",
"# Ignore client auth requests if the server allows optional TLS client authentication",
"should_ignore_client_auth",
"=",
"True",
"# But do not ignore them is client authentication is required so that the right exceptions get thrown",
"# within the plugins, providing a better output",
"if",
"self",
".",
"client_auth_requirement",
"==",
"ClientAuthenticationServerConfigurationEnum",
".",
"REQUIRED",
":",
"should_ignore_client_auth",
"=",
"False",
"ssl_connection",
"=",
"SslConnectionConfigurator",
".",
"get_connection",
"(",
"ssl_version",
"=",
"final_ssl_version",
",",
"server_info",
"=",
"self",
",",
"openssl_cipher_string",
"=",
"openssl_cipher_string",
",",
"ssl_verify_locations",
"=",
"ssl_verify_locations",
",",
"should_use_legacy_openssl",
"=",
"should_use_legacy_openssl",
",",
"should_ignore_client_auth",
"=",
"should_ignore_client_auth",
",",
")",
"return",
"ssl_connection"
] | Get an SSLConnection instance with the right SSL configuration for successfully connecting to the server.
Used by all plugins to connect to the server and run scans. | [
"Get",
"an",
"SSLConnection",
"instance",
"with",
"the",
"right",
"SSL",
"configuration",
"for",
"successfully",
"connecting",
"to",
"the",
"server",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/server_connectivity_info.py#L70-L114 |
227,292 | nabla-c0d3/sslyze | sslyze/cli/command_line_parser.py | CommandLineParser._add_plugin_options | def _add_plugin_options(self, available_plugins: Set[Type[Plugin]]) -> None:
"""Recovers the list of command line options implemented by the available plugins and adds them to the command
line parser.
"""
for plugin_class in available_plugins:
# Add the current plugin's commands to the parser
group = OptionGroup(self._parser, plugin_class.get_title(), plugin_class.get_description())
for option in plugin_class.get_cli_option_group():
group.add_option(option)
self._parser.add_option_group(group) | python | def _add_plugin_options(self, available_plugins: Set[Type[Plugin]]) -> None:
"""Recovers the list of command line options implemented by the available plugins and adds them to the command
line parser.
"""
for plugin_class in available_plugins:
# Add the current plugin's commands to the parser
group = OptionGroup(self._parser, plugin_class.get_title(), plugin_class.get_description())
for option in plugin_class.get_cli_option_group():
group.add_option(option)
self._parser.add_option_group(group) | [
"def",
"_add_plugin_options",
"(",
"self",
",",
"available_plugins",
":",
"Set",
"[",
"Type",
"[",
"Plugin",
"]",
"]",
")",
"->",
"None",
":",
"for",
"plugin_class",
"in",
"available_plugins",
":",
"# Add the current plugin's commands to the parser",
"group",
"=",
"OptionGroup",
"(",
"self",
".",
"_parser",
",",
"plugin_class",
".",
"get_title",
"(",
")",
",",
"plugin_class",
".",
"get_description",
"(",
")",
")",
"for",
"option",
"in",
"plugin_class",
".",
"get_cli_option_group",
"(",
")",
":",
"group",
".",
"add_option",
"(",
"option",
")",
"self",
".",
"_parser",
".",
"add_option_group",
"(",
"group",
")"
] | Recovers the list of command line options implemented by the available plugins and adds them to the command
line parser. | [
"Recovers",
"the",
"list",
"of",
"command",
"line",
"options",
"implemented",
"by",
"the",
"available",
"plugins",
"and",
"adds",
"them",
"to",
"the",
"command",
"line",
"parser",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/cli/command_line_parser.py#L428-L437 |
227,293 | nabla-c0d3/sslyze | setup.py | get_long_description | def get_long_description():
"""Convert the README file into the long description.
"""
with open(path.join(root_path, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
return long_description | python | def get_long_description():
"""Convert the README file into the long description.
"""
with open(path.join(root_path, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
return long_description | [
"def",
"get_long_description",
"(",
")",
":",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"root_path",
",",
"'README.md'",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"long_description",
"=",
"f",
".",
"read",
"(",
")",
"return",
"long_description"
] | Convert the README file into the long description. | [
"Convert",
"the",
"README",
"file",
"into",
"the",
"long",
"description",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/setup.py#L23-L28 |
227,294 | nabla-c0d3/sslyze | setup.py | get_include_files | def get_include_files():
""""Get the list of trust stores so they properly packaged when doing a cx_freeze build.
"""
plugin_data_files = []
trust_stores_pem_path = path.join(root_path, 'sslyze', 'plugins', 'utils', 'trust_store', 'pem_files')
for file in listdir(trust_stores_pem_path):
file = path.join(trust_stores_pem_path, file)
if path.isfile(file): # skip directories
filename = path.basename(file)
plugin_data_files.append((file, path.join('pem_files', filename)))
return plugin_data_files | python | def get_include_files():
""""Get the list of trust stores so they properly packaged when doing a cx_freeze build.
"""
plugin_data_files = []
trust_stores_pem_path = path.join(root_path, 'sslyze', 'plugins', 'utils', 'trust_store', 'pem_files')
for file in listdir(trust_stores_pem_path):
file = path.join(trust_stores_pem_path, file)
if path.isfile(file): # skip directories
filename = path.basename(file)
plugin_data_files.append((file, path.join('pem_files', filename)))
return plugin_data_files | [
"def",
"get_include_files",
"(",
")",
":",
"plugin_data_files",
"=",
"[",
"]",
"trust_stores_pem_path",
"=",
"path",
".",
"join",
"(",
"root_path",
",",
"'sslyze'",
",",
"'plugins'",
",",
"'utils'",
",",
"'trust_store'",
",",
"'pem_files'",
")",
"for",
"file",
"in",
"listdir",
"(",
"trust_stores_pem_path",
")",
":",
"file",
"=",
"path",
".",
"join",
"(",
"trust_stores_pem_path",
",",
"file",
")",
"if",
"path",
".",
"isfile",
"(",
"file",
")",
":",
"# skip directories",
"filename",
"=",
"path",
".",
"basename",
"(",
"file",
")",
"plugin_data_files",
".",
"append",
"(",
"(",
"file",
",",
"path",
".",
"join",
"(",
"'pem_files'",
",",
"filename",
")",
")",
")",
"return",
"plugin_data_files"
] | Get the list of trust stores so they properly packaged when doing a cx_freeze build. | [
"Get",
"the",
"list",
"of",
"trust",
"stores",
"so",
"they",
"properly",
"packaged",
"when",
"doing",
"a",
"cx_freeze",
"build",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/setup.py#L31-L41 |
227,295 | nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.get_dns_subject_alternative_names | def get_dns_subject_alternative_names(certificate: cryptography.x509.Certificate) -> List[str]:
"""Retrieve all the DNS entries of the Subject Alternative Name extension.
"""
subj_alt_names: List[str] = []
try:
san_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
subj_alt_names = san_ext.value.get_values_for_type(DNSName)
except ExtensionNotFound:
pass
return subj_alt_names | python | def get_dns_subject_alternative_names(certificate: cryptography.x509.Certificate) -> List[str]:
"""Retrieve all the DNS entries of the Subject Alternative Name extension.
"""
subj_alt_names: List[str] = []
try:
san_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
subj_alt_names = san_ext.value.get_values_for_type(DNSName)
except ExtensionNotFound:
pass
return subj_alt_names | [
"def",
"get_dns_subject_alternative_names",
"(",
"certificate",
":",
"cryptography",
".",
"x509",
".",
"Certificate",
")",
"->",
"List",
"[",
"str",
"]",
":",
"subj_alt_names",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"try",
":",
"san_ext",
"=",
"certificate",
".",
"extensions",
".",
"get_extension_for_oid",
"(",
"ExtensionOID",
".",
"SUBJECT_ALTERNATIVE_NAME",
")",
"subj_alt_names",
"=",
"san_ext",
".",
"value",
".",
"get_values_for_type",
"(",
"DNSName",
")",
"except",
"ExtensionNotFound",
":",
"pass",
"return",
"subj_alt_names"
] | Retrieve all the DNS entries of the Subject Alternative Name extension. | [
"Retrieve",
"all",
"the",
"DNS",
"entries",
"of",
"the",
"Subject",
"Alternative",
"Name",
"extension",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L24-L33 |
227,296 | nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.matches_hostname | def matches_hostname(cls, certificate: cryptography.x509.Certificate, hostname: str) -> None:
"""Verify that the certificate was issued for the given hostname.
Raises:
CertificateError: If the certificate was not issued for the supplied hostname.
"""
# Extract the names from the certificate to create the properly-formatted dictionary
certificate_names = {
'subject': (tuple([('commonName', name) for name in cls.get_common_names(certificate.subject)]),),
'subjectAltName': tuple([('DNS', name) for name in cls.get_dns_subject_alternative_names(certificate)]),
}
# CertificateError is raised on failure
ssl.match_hostname(certificate_names, hostname) | python | def matches_hostname(cls, certificate: cryptography.x509.Certificate, hostname: str) -> None:
"""Verify that the certificate was issued for the given hostname.
Raises:
CertificateError: If the certificate was not issued for the supplied hostname.
"""
# Extract the names from the certificate to create the properly-formatted dictionary
certificate_names = {
'subject': (tuple([('commonName', name) for name in cls.get_common_names(certificate.subject)]),),
'subjectAltName': tuple([('DNS', name) for name in cls.get_dns_subject_alternative_names(certificate)]),
}
# CertificateError is raised on failure
ssl.match_hostname(certificate_names, hostname) | [
"def",
"matches_hostname",
"(",
"cls",
",",
"certificate",
":",
"cryptography",
".",
"x509",
".",
"Certificate",
",",
"hostname",
":",
"str",
")",
"->",
"None",
":",
"# Extract the names from the certificate to create the properly-formatted dictionary",
"certificate_names",
"=",
"{",
"'subject'",
":",
"(",
"tuple",
"(",
"[",
"(",
"'commonName'",
",",
"name",
")",
"for",
"name",
"in",
"cls",
".",
"get_common_names",
"(",
"certificate",
".",
"subject",
")",
"]",
")",
",",
")",
",",
"'subjectAltName'",
":",
"tuple",
"(",
"[",
"(",
"'DNS'",
",",
"name",
")",
"for",
"name",
"in",
"cls",
".",
"get_dns_subject_alternative_names",
"(",
"certificate",
")",
"]",
")",
",",
"}",
"# CertificateError is raised on failure",
"ssl",
".",
"match_hostname",
"(",
"certificate_names",
",",
"hostname",
")"
] | Verify that the certificate was issued for the given hostname.
Raises:
CertificateError: If the certificate was not issued for the supplied hostname. | [
"Verify",
"that",
"the",
"certificate",
"was",
"issued",
"for",
"the",
"given",
"hostname",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L36-L48 |
227,297 | nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.get_name_as_short_text | def get_name_as_short_text(cls, name_field: cryptography.x509.Name) -> str:
"""Convert a name field returned by the cryptography module to a string suitable for displaying it to the user.
"""
# Name_field is supposed to be a Subject or an Issuer; print the CN if there is one
common_names = cls.get_common_names(name_field)
if common_names:
# We don't support certs with multiple CNs
return common_names[0]
else:
# Otherwise show the whole field
return cls.get_name_as_text(name_field) | python | def get_name_as_short_text(cls, name_field: cryptography.x509.Name) -> str:
"""Convert a name field returned by the cryptography module to a string suitable for displaying it to the user.
"""
# Name_field is supposed to be a Subject or an Issuer; print the CN if there is one
common_names = cls.get_common_names(name_field)
if common_names:
# We don't support certs with multiple CNs
return common_names[0]
else:
# Otherwise show the whole field
return cls.get_name_as_text(name_field) | [
"def",
"get_name_as_short_text",
"(",
"cls",
",",
"name_field",
":",
"cryptography",
".",
"x509",
".",
"Name",
")",
"->",
"str",
":",
"# Name_field is supposed to be a Subject or an Issuer; print the CN if there is one",
"common_names",
"=",
"cls",
".",
"get_common_names",
"(",
"name_field",
")",
"if",
"common_names",
":",
"# We don't support certs with multiple CNs",
"return",
"common_names",
"[",
"0",
"]",
"else",
":",
"# Otherwise show the whole field",
"return",
"cls",
".",
"get_name_as_text",
"(",
"name_field",
")"
] | Convert a name field returned by the cryptography module to a string suitable for displaying it to the user. | [
"Convert",
"a",
"name",
"field",
"returned",
"by",
"the",
"cryptography",
"module",
"to",
"a",
"string",
"suitable",
"for",
"displaying",
"it",
"to",
"the",
"user",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L51-L61 |
227,298 | nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.has_ocsp_must_staple_extension | def has_ocsp_must_staple_extension(certificate: cryptography.x509.Certificate) -> bool:
"""Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066.
"""
has_ocsp_must_staple = False
try:
tls_feature_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE)
for feature_type in tls_feature_ext.value:
if feature_type == cryptography.x509.TLSFeatureType.status_request:
has_ocsp_must_staple = True
break
except ExtensionNotFound:
pass
return has_ocsp_must_staple | python | def has_ocsp_must_staple_extension(certificate: cryptography.x509.Certificate) -> bool:
"""Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066.
"""
has_ocsp_must_staple = False
try:
tls_feature_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE)
for feature_type in tls_feature_ext.value:
if feature_type == cryptography.x509.TLSFeatureType.status_request:
has_ocsp_must_staple = True
break
except ExtensionNotFound:
pass
return has_ocsp_must_staple | [
"def",
"has_ocsp_must_staple_extension",
"(",
"certificate",
":",
"cryptography",
".",
"x509",
".",
"Certificate",
")",
"->",
"bool",
":",
"has_ocsp_must_staple",
"=",
"False",
"try",
":",
"tls_feature_ext",
"=",
"certificate",
".",
"extensions",
".",
"get_extension_for_oid",
"(",
"ExtensionOID",
".",
"TLS_FEATURE",
")",
"for",
"feature_type",
"in",
"tls_feature_ext",
".",
"value",
":",
"if",
"feature_type",
"==",
"cryptography",
".",
"x509",
".",
"TLSFeatureType",
".",
"status_request",
":",
"has_ocsp_must_staple",
"=",
"True",
"break",
"except",
"ExtensionNotFound",
":",
"pass",
"return",
"has_ocsp_must_staple"
] | Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066. | [
"Return",
"True",
"if",
"the",
"certificate",
"has",
"the",
"OCSP",
"Must",
"-",
"Staple",
"extension",
"defined",
"in",
"RFC",
"6066",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L95-L108 |
227,299 | nabla-c0d3/sslyze | sslyze/utils/tls_wrapped_protocol_helpers.py | HttpsHelper.send_request | def send_request(self, ssl_client: SslClient) -> str:
"""Send an HTTP GET to the server and return the HTTP status code.
"""
try:
ssl_client.write(HttpRequestGenerator.get_request(self._hostname))
# Parse the response and print the Location header
http_response = HttpResponseParser.parse_from_ssl_connection(ssl_client)
if http_response.version == 9:
# HTTP 0.9 => Probably not an HTTP response
result = self.ERR_NOT_HTTP
else:
redirect = ''
if 300 <= http_response.status < 400:
redirect_location = http_response.getheader('Location')
if redirect_location:
# Add redirection URL to the result
redirect = f' - {redirect_location}'
result = self.GET_RESULT_FORMAT.format(http_response.status, http_response.reason, redirect)
except socket.timeout:
result = self.ERR_HTTP_TIMEOUT
except IOError:
result = self.ERR_GENERIC
return result | python | def send_request(self, ssl_client: SslClient) -> str:
"""Send an HTTP GET to the server and return the HTTP status code.
"""
try:
ssl_client.write(HttpRequestGenerator.get_request(self._hostname))
# Parse the response and print the Location header
http_response = HttpResponseParser.parse_from_ssl_connection(ssl_client)
if http_response.version == 9:
# HTTP 0.9 => Probably not an HTTP response
result = self.ERR_NOT_HTTP
else:
redirect = ''
if 300 <= http_response.status < 400:
redirect_location = http_response.getheader('Location')
if redirect_location:
# Add redirection URL to the result
redirect = f' - {redirect_location}'
result = self.GET_RESULT_FORMAT.format(http_response.status, http_response.reason, redirect)
except socket.timeout:
result = self.ERR_HTTP_TIMEOUT
except IOError:
result = self.ERR_GENERIC
return result | [
"def",
"send_request",
"(",
"self",
",",
"ssl_client",
":",
"SslClient",
")",
"->",
"str",
":",
"try",
":",
"ssl_client",
".",
"write",
"(",
"HttpRequestGenerator",
".",
"get_request",
"(",
"self",
".",
"_hostname",
")",
")",
"# Parse the response and print the Location header",
"http_response",
"=",
"HttpResponseParser",
".",
"parse_from_ssl_connection",
"(",
"ssl_client",
")",
"if",
"http_response",
".",
"version",
"==",
"9",
":",
"# HTTP 0.9 => Probably not an HTTP response",
"result",
"=",
"self",
".",
"ERR_NOT_HTTP",
"else",
":",
"redirect",
"=",
"''",
"if",
"300",
"<=",
"http_response",
".",
"status",
"<",
"400",
":",
"redirect_location",
"=",
"http_response",
".",
"getheader",
"(",
"'Location'",
")",
"if",
"redirect_location",
":",
"# Add redirection URL to the result",
"redirect",
"=",
"f' - {redirect_location}'",
"result",
"=",
"self",
".",
"GET_RESULT_FORMAT",
".",
"format",
"(",
"http_response",
".",
"status",
",",
"http_response",
".",
"reason",
",",
"redirect",
")",
"except",
"socket",
".",
"timeout",
":",
"result",
"=",
"self",
".",
"ERR_HTTP_TIMEOUT",
"except",
"IOError",
":",
"result",
"=",
"self",
".",
"ERR_GENERIC",
"return",
"result"
] | Send an HTTP GET to the server and return the HTTP status code. | [
"Send",
"an",
"HTTP",
"GET",
"to",
"the",
"server",
"and",
"return",
"the",
"HTTP",
"status",
"code",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/tls_wrapped_protocol_helpers.py#L65-L90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.