nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
flexxui/flexx
69b85b308b505a8621305458a5094f2a6addd720
flexx/ui/widgets/_tree.py
python
TreeItem.user_collapsed
(self, collapsed)
return d
Event emitted when the user (un)collapses this item. Has ``old_value`` and ``new_value`` attributes.
Event emitted when the user (un)collapses this item. Has ``old_value`` and ``new_value`` attributes.
[ "Event", "emitted", "when", "the", "user", "(", "un", ")", "collapses", "this", "item", ".", "Has", "old_value", "and", "new_value", "attributes", "." ]
def user_collapsed(self, collapsed): """ Event emitted when the user (un)collapses this item. Has ``old_value`` and ``new_value`` attributes. """ d = {'old_value': self.collapsed, 'new_value': collapsed} self.set_collapsed(collapsed) return d
[ "def", "user_collapsed", "(", "self", ",", "collapsed", ")", ":", "d", "=", "{", "'old_value'", ":", "self", ".", "collapsed", ",", "'new_value'", ":", "collapsed", "}", "self", ".", "set_collapsed", "(", "collapsed", ")", "return", "d" ]
https://github.com/flexxui/flexx/blob/69b85b308b505a8621305458a5094f2a6addd720/flexx/ui/widgets/_tree.py#L527-L533
pytorch/botorch
f85fb8ff36d21e21bdb881d107982fb6d5d78704
botorch/acquisition/knowledge_gradient.py
python
qKnowledgeGradient.evaluate
(self, X: Tensor, bounds: Tensor, **kwargs: Any)
return values.mean(dim=0)
r"""Evaluate qKnowledgeGradient on the candidate set `X_actual` by solving the inner optimization problem. Args: X: A `b x q x d` Tensor with `b` t-batches of `q` design points each. Unlike `forward()`, this does not include solutions of the inner optimization problem. bounds: A `2 x d` tensor of lower and upper bounds for each column of the solutions to the inner problem. kwargs: Additional keyword arguments. This includes the options for optimization of the inner problem, i.e. `num_restarts`, `raw_samples`, an `options` dictionary to be passed on to the optimization helpers, and a `scipy_options` dictionary to be passed to `scipy.minimize`. Returns: A Tensor of shape `b`. For t-batch b, the q-KG value of the design `X[b]` is averaged across the fantasy models. NOTE: If `current_value` is not provided, then this is not the true KG value of `X[b]`.
r"""Evaluate qKnowledgeGradient on the candidate set `X_actual` by solving the inner optimization problem.
[ "r", "Evaluate", "qKnowledgeGradient", "on", "the", "candidate", "set", "X_actual", "by", "solving", "the", "inner", "optimization", "problem", "." ]
def evaluate(self, X: Tensor, bounds: Tensor, **kwargs: Any) -> Tensor: r"""Evaluate qKnowledgeGradient on the candidate set `X_actual` by solving the inner optimization problem. Args: X: A `b x q x d` Tensor with `b` t-batches of `q` design points each. Unlike `forward()`, this does not include solutions of the inner optimization problem. bounds: A `2 x d` tensor of lower and upper bounds for each column of the solutions to the inner problem. kwargs: Additional keyword arguments. This includes the options for optimization of the inner problem, i.e. `num_restarts`, `raw_samples`, an `options` dictionary to be passed on to the optimization helpers, and a `scipy_options` dictionary to be passed to `scipy.minimize`. Returns: A Tensor of shape `b`. For t-batch b, the q-KG value of the design `X[b]` is averaged across the fantasy models. NOTE: If `current_value` is not provided, then this is not the true KG value of `X[b]`. """ if hasattr(self, "expand"): X = self.expand(X) # construct the fantasy model of shape `num_fantasies x b` fantasy_model = self.model.fantasize( X=X, sampler=self.sampler, observation_noise=True ) # get the value function value_function = _get_value_function( model=fantasy_model, objective=self.objective, sampler=self.inner_sampler, project=getattr(self, "project", None), ) from botorch.generation.gen import gen_candidates_scipy # optimize the inner problem from botorch.optim.initializers import gen_value_function_initial_conditions initial_conditions = gen_value_function_initial_conditions( acq_function=value_function, bounds=bounds, num_restarts=kwargs.get("num_restarts", 20), raw_samples=kwargs.get("raw_samples", 1024), current_model=self.model, options={**kwargs.get("options", {}), **kwargs.get("scipy_options", {})}, ) _, values = gen_candidates_scipy( initial_conditions=initial_conditions, acquisition_function=value_function, lower_bounds=bounds[0], upper_bounds=bounds[1], options=kwargs.get("scipy_options"), ) # get the maximizer for each batch values, _ = torch.max(values, dim=0) if self.current_value is not None: values = values - self.current_value # NOTE: using getattr to cover both no-attribute with qKG and None with qMFKG if getattr(self, "cost_aware_utility", None) is not None: values = self.cost_aware_utility( X=X, deltas=values, sampler=self.cost_sampler ) # return average over the fantasy samples return values.mean(dim=0)
[ "def", "evaluate", "(", "self", ",", "X", ":", "Tensor", ",", "bounds", ":", "Tensor", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Tensor", ":", "if", "hasattr", "(", "self", ",", "\"expand\"", ")", ":", "X", "=", "self", ".", "expand", "(", "X", ")", "# construct the fantasy model of shape `num_fantasies x b`", "fantasy_model", "=", "self", ".", "model", ".", "fantasize", "(", "X", "=", "X", ",", "sampler", "=", "self", ".", "sampler", ",", "observation_noise", "=", "True", ")", "# get the value function", "value_function", "=", "_get_value_function", "(", "model", "=", "fantasy_model", ",", "objective", "=", "self", ".", "objective", ",", "sampler", "=", "self", ".", "inner_sampler", ",", "project", "=", "getattr", "(", "self", ",", "\"project\"", ",", "None", ")", ",", ")", "from", "botorch", ".", "generation", ".", "gen", "import", "gen_candidates_scipy", "# optimize the inner problem", "from", "botorch", ".", "optim", ".", "initializers", "import", "gen_value_function_initial_conditions", "initial_conditions", "=", "gen_value_function_initial_conditions", "(", "acq_function", "=", "value_function", ",", "bounds", "=", "bounds", ",", "num_restarts", "=", "kwargs", ".", "get", "(", "\"num_restarts\"", ",", "20", ")", ",", "raw_samples", "=", "kwargs", ".", "get", "(", "\"raw_samples\"", ",", "1024", ")", ",", "current_model", "=", "self", ".", "model", ",", "options", "=", "{", "*", "*", "kwargs", ".", "get", "(", "\"options\"", ",", "{", "}", ")", ",", "*", "*", "kwargs", ".", "get", "(", "\"scipy_options\"", ",", "{", "}", ")", "}", ",", ")", "_", ",", "values", "=", "gen_candidates_scipy", "(", "initial_conditions", "=", "initial_conditions", ",", "acquisition_function", "=", "value_function", ",", "lower_bounds", "=", "bounds", "[", "0", "]", ",", "upper_bounds", "=", "bounds", "[", "1", "]", ",", "options", "=", "kwargs", ".", "get", "(", "\"scipy_options\"", ")", ",", ")", "# get the maximizer for each batch", "values", ",", "_", "=", "torch", ".", "max", "(", "values", ",", "dim", "=", "0", ")", "if", "self", ".", "current_value", "is", "not", "None", ":", "values", "=", "values", "-", "self", ".", "current_value", "# NOTE: using getattr to cover both no-attribute with qKG and None with qMFKG", "if", "getattr", "(", "self", ",", "\"cost_aware_utility\"", ",", "None", ")", "is", "not", "None", ":", "values", "=", "self", ".", "cost_aware_utility", "(", "X", "=", "X", ",", "deltas", "=", "values", ",", "sampler", "=", "self", ".", "cost_sampler", ")", "# return average over the fantasy samples", "return", "values", ".", "mean", "(", "dim", "=", "0", ")" ]
https://github.com/pytorch/botorch/blob/f85fb8ff36d21e21bdb881d107982fb6d5d78704/botorch/acquisition/knowledge_gradient.py#L192-L260
PyHDI/Pyverilog
2a42539bebd1b4587ee577d491ff002d0cc7295d
pyverilog/vparser/parser.py
python
VerilogParser.p_casecontent_condition_one
(self, p)
casecontent_condition : expression
casecontent_condition : expression
[ "casecontent_condition", ":", "expression" ]
def p_casecontent_condition_one(self, p): 'casecontent_condition : expression' p[0] = (p[1],) p.set_lineno(0, p.lineno(1))
[ "def", "p_casecontent_condition_one", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "(", "p", "[", "1", "]", ",", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lineno", "(", "1", ")", ")" ]
https://github.com/PyHDI/Pyverilog/blob/2a42539bebd1b4587ee577d491ff002d0cc7295d/pyverilog/vparser/parser.py#L1704-L1707
deepmind/pysc2
05b28ef0d85aa5eef811bc49ff4c0cbe496c0adb
pysc2/bin/replay_actions.py
python
ReplayProcessor.process_replay
(self, controller, replay_data, map_data, player_id)
Process a single replay, updating the stats.
Process a single replay, updating the stats.
[ "Process", "a", "single", "replay", "updating", "the", "stats", "." ]
def process_replay(self, controller, replay_data, map_data, player_id): """Process a single replay, updating the stats.""" self._update_stage("start_replay") controller.start_replay(sc_pb.RequestStartReplay( replay_data=replay_data, map_data=map_data, options=interface, observed_player_id=player_id)) feat = features.features_from_game_info(controller.game_info()) self.stats.replay_stats.replays += 1 self._update_stage("step") controller.step() while True: self.stats.replay_stats.steps += 1 self._update_stage("observe") obs = controller.observe() for action in obs.actions: act_fl = action.action_feature_layer if act_fl.HasField("unit_command"): self.stats.replay_stats.made_abilities[ act_fl.unit_command.ability_id] += 1 if act_fl.HasField("camera_move"): self.stats.replay_stats.camera_move += 1 if act_fl.HasField("unit_selection_point"): self.stats.replay_stats.select_pt += 1 if act_fl.HasField("unit_selection_rect"): self.stats.replay_stats.select_rect += 1 if action.action_ui.HasField("control_group"): self.stats.replay_stats.control_group += 1 try: func = feat.reverse_action(action).function except ValueError: func = -1 self.stats.replay_stats.made_actions[func] += 1 for valid in obs.observation.abilities: self.stats.replay_stats.valid_abilities[valid.ability_id] += 1 for u in obs.observation.raw_data.units: self.stats.replay_stats.unit_ids[u.unit_type] += 1 for b in u.buff_ids: self.stats.replay_stats.buffs[b] += 1 for u in obs.observation.raw_data.player.upgrade_ids: self.stats.replay_stats.upgrades[u] += 1 for e in obs.observation.raw_data.effects: self.stats.replay_stats.effects[e.effect_id] += 1 for ability_id in feat.available_actions(obs.observation): self.stats.replay_stats.valid_actions[ability_id] += 1 if obs.player_result: break self._update_stage("step") controller.step(FLAGS.step_mul)
[ "def", "process_replay", "(", "self", ",", "controller", ",", "replay_data", ",", "map_data", ",", "player_id", ")", ":", "self", ".", "_update_stage", "(", "\"start_replay\"", ")", "controller", ".", "start_replay", "(", "sc_pb", ".", "RequestStartReplay", "(", "replay_data", "=", "replay_data", ",", "map_data", "=", "map_data", ",", "options", "=", "interface", ",", "observed_player_id", "=", "player_id", ")", ")", "feat", "=", "features", ".", "features_from_game_info", "(", "controller", ".", "game_info", "(", ")", ")", "self", ".", "stats", ".", "replay_stats", ".", "replays", "+=", "1", "self", ".", "_update_stage", "(", "\"step\"", ")", "controller", ".", "step", "(", ")", "while", "True", ":", "self", ".", "stats", ".", "replay_stats", ".", "steps", "+=", "1", "self", ".", "_update_stage", "(", "\"observe\"", ")", "obs", "=", "controller", ".", "observe", "(", ")", "for", "action", "in", "obs", ".", "actions", ":", "act_fl", "=", "action", ".", "action_feature_layer", "if", "act_fl", ".", "HasField", "(", "\"unit_command\"", ")", ":", "self", ".", "stats", ".", "replay_stats", ".", "made_abilities", "[", "act_fl", ".", "unit_command", ".", "ability_id", "]", "+=", "1", "if", "act_fl", ".", "HasField", "(", "\"camera_move\"", ")", ":", "self", ".", "stats", ".", "replay_stats", ".", "camera_move", "+=", "1", "if", "act_fl", ".", "HasField", "(", "\"unit_selection_point\"", ")", ":", "self", ".", "stats", ".", "replay_stats", ".", "select_pt", "+=", "1", "if", "act_fl", ".", "HasField", "(", "\"unit_selection_rect\"", ")", ":", "self", ".", "stats", ".", "replay_stats", ".", "select_rect", "+=", "1", "if", "action", ".", "action_ui", ".", "HasField", "(", "\"control_group\"", ")", ":", "self", ".", "stats", ".", "replay_stats", ".", "control_group", "+=", "1", "try", ":", "func", "=", "feat", ".", "reverse_action", "(", "action", ")", ".", "function", "except", "ValueError", ":", "func", "=", "-", "1", "self", ".", "stats", ".", "replay_stats", ".", "made_actions", "[", "func", "]", "+=", "1", "for", "valid", "in", "obs", ".", "observation", ".", "abilities", ":", "self", ".", "stats", ".", "replay_stats", ".", "valid_abilities", "[", "valid", ".", "ability_id", "]", "+=", "1", "for", "u", "in", "obs", ".", "observation", ".", "raw_data", ".", "units", ":", "self", ".", "stats", ".", "replay_stats", ".", "unit_ids", "[", "u", ".", "unit_type", "]", "+=", "1", "for", "b", "in", "u", ".", "buff_ids", ":", "self", ".", "stats", ".", "replay_stats", ".", "buffs", "[", "b", "]", "+=", "1", "for", "u", "in", "obs", ".", "observation", ".", "raw_data", ".", "player", ".", "upgrade_ids", ":", "self", ".", "stats", ".", "replay_stats", ".", "upgrades", "[", "u", "]", "+=", "1", "for", "e", "in", "obs", ".", "observation", ".", "raw_data", ".", "effects", ":", "self", ".", "stats", ".", "replay_stats", ".", "effects", "[", "e", ".", "effect_id", "]", "+=", "1", "for", "ability_id", "in", "feat", ".", "available_actions", "(", "obs", ".", "observation", ")", ":", "self", ".", "stats", ".", "replay_stats", ".", "valid_actions", "[", "ability_id", "]", "+=", "1", "if", "obs", ".", "player_result", ":", "break", "self", ".", "_update_stage", "(", "\"step\"", ")", "controller", ".", "step", "(", "FLAGS", ".", "step_mul", ")" ]
https://github.com/deepmind/pysc2/blob/05b28ef0d85aa5eef811bc49ff4c0cbe496c0adb/pysc2/bin/replay_actions.py#L263-L323
eXascaleInfolab/PyExPool
c4c546782478bc4bf68f332fc59097b8c15ca8f7
mpepool.py
python
ExecPool.__finalize__
(self)
Late clear up called after the garbage collection (unlikely to be used)
Late clear up called after the garbage collection (unlikely to be used)
[ "Late", "clear", "up", "called", "after", "the", "garbage", "collection", "(", "unlikely", "to", "be", "used", ")" ]
def __finalize__(self): """Late clear up called after the garbage collection (unlikely to be used)""" self.__terminate()
[ "def", "__finalize__", "(", "self", ")", ":", "self", ".", "__terminate", "(", ")" ]
https://github.com/eXascaleInfolab/PyExPool/blob/c4c546782478bc4bf68f332fc59097b8c15ca8f7/mpepool.py#L1959-L1961
machow/siuba
f5b36f840401225416f937900cb945923ced1629
siuba/dply/vector.py
python
between
(x, left, right, default = False)
return x.between(left, right)
Return whether a value is between left and right (including either side). Example: >>> between(pd.Series([1,2,3]), 0, 2) 0 True 1 True 2 False dtype: bool Note: This is a thin wrapper around pd.Series.between(left, right)
Return whether a value is between left and right (including either side).
[ "Return", "whether", "a", "value", "is", "between", "left", "and", "right", "(", "including", "either", "side", ")", "." ]
def between(x, left, right, default = False): """Return whether a value is between left and right (including either side). Example: >>> between(pd.Series([1,2,3]), 0, 2) 0 True 1 True 2 False dtype: bool Note: This is a thin wrapper around pd.Series.between(left, right) """ # note: NA -> False, in tidyverse NA -> NA if default is not False: raise TypeError("between function must use default = False for pandas Series") return x.between(left, right)
[ "def", "between", "(", "x", ",", "left", ",", "right", ",", "default", "=", "False", ")", ":", "# note: NA -> False, in tidyverse NA -> NA", "if", "default", "is", "not", "False", ":", "raise", "TypeError", "(", "\"between function must use default = False for pandas Series\"", ")", "return", "x", ".", "between", "(", "left", ",", "right", ")" ]
https://github.com/machow/siuba/blob/f5b36f840401225416f937900cb945923ced1629/siuba/dply/vector.py#L241-L259
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/logging/__init__.py
python
Formatter.formatTime
(self, record, datefmt=None)
return s
Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the 'converter' attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the 'converter' attribute in the Formatter class.
Return the creation time of the specified LogRecord as formatted text.
[ "Return", "the", "creation", "time", "of", "the", "specified", "LogRecord", "as", "formatted", "text", "." ]
def formatTime(self, record, datefmt=None): """ Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the 'converter' attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the 'converter' attribute in the Formatter class. """ ct = self.converter(record.created) if datefmt: s = time.strftime(datefmt, ct) else: t = time.strftime("%Y-%m-%d %H:%M:%S", ct) s = "%s,%03d" % (t, record.msecs) return s
[ "def", "formatTime", "(", "self", ",", "record", ",", "datefmt", "=", "None", ")", ":", "ct", "=", "self", ".", "converter", "(", "record", ".", "created", ")", "if", "datefmt", ":", "s", "=", "time", ".", "strftime", "(", "datefmt", ",", "ct", ")", "else", ":", "t", "=", "time", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ",", "ct", ")", "s", "=", "\"%s,%03d\"", "%", "(", "t", ",", "record", ".", "msecs", ")", "return", "s" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/logging/__init__.py#L404-L428
seasonSH/WarpGAN
794e24d9c3abce08c0e95f975ce5914ccaa2e1bb
models/interpolate_spline.py
python
_pairwise_squared_distance_matrix
(x)
return squared_dists
Pairwise squared distance among a (batch) matrix's rows (2nd dim). This saves a bit of computation vs. using _cross_squared_distance_matrix(x,x) Args: x: `[batch_size, n, d]` float `Tensor` Returns: squared_dists: `[batch_size, n, n]` float `Tensor`, where squared_dists[b,i,j] = ||x[b,i,:] - x[b,j,:]||^2
Pairwise squared distance among a (batch) matrix's rows (2nd dim).
[ "Pairwise", "squared", "distance", "among", "a", "(", "batch", ")", "matrix", "s", "rows", "(", "2nd", "dim", ")", "." ]
def _pairwise_squared_distance_matrix(x): """Pairwise squared distance among a (batch) matrix's rows (2nd dim). This saves a bit of computation vs. using _cross_squared_distance_matrix(x,x) Args: x: `[batch_size, n, d]` float `Tensor` Returns: squared_dists: `[batch_size, n, n]` float `Tensor`, where squared_dists[b,i,j] = ||x[b,i,:] - x[b,j,:]||^2 """ x_x_transpose = math_ops.matmul(x, x, adjoint_b=True) x_norm_squared = array_ops.matrix_diag_part(x_x_transpose) x_norm_squared_tile = array_ops.expand_dims(x_norm_squared, 2) # squared_dists[b,i,j] = ||x_bi - x_bj||^2 = x_bi'x_bi- 2x_bi'x_bj + x_bj'x_bj squared_dists = x_norm_squared_tile - 2 * x_x_transpose + array_ops.transpose( x_norm_squared_tile, [0, 2, 1]) return squared_dists
[ "def", "_pairwise_squared_distance_matrix", "(", "x", ")", ":", "x_x_transpose", "=", "math_ops", ".", "matmul", "(", "x", ",", "x", ",", "adjoint_b", "=", "True", ")", "x_norm_squared", "=", "array_ops", ".", "matrix_diag_part", "(", "x_x_transpose", ")", "x_norm_squared_tile", "=", "array_ops", ".", "expand_dims", "(", "x_norm_squared", ",", "2", ")", "# squared_dists[b,i,j] = ||x_bi - x_bj||^2 = x_bi'x_bi- 2x_bi'x_bj + x_bj'x_bj", "squared_dists", "=", "x_norm_squared_tile", "-", "2", "*", "x_x_transpose", "+", "array_ops", ".", "transpose", "(", "x_norm_squared_tile", ",", "[", "0", ",", "2", ",", "1", "]", ")", "return", "squared_dists" ]
https://github.com/seasonSH/WarpGAN/blob/794e24d9c3abce08c0e95f975ce5914ccaa2e1bb/models/interpolate_spline.py#L59-L80
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
twistlock/datadog_checks/twistlock/twistlock.py
python
TwistlockCheck._analyze_vulnerability
(self, vuln, host=False, image=False)
[]
def _analyze_vulnerability(self, vuln, host=False, image=False): cve_id = vuln.get('id') # if it doesn't have a cve id, it's probably an invalid record if not cve_id: return description = vuln.get('description') published = vuln.get('published') published_date = datetime.fromtimestamp(int(published)) if published_date < self.last_run: if host: vuln_type = 'hosts' elif image: vuln_type = 'images' else: vuln_type = 'systems' msg_text = """ There is a new CVE affecting your {}: {} """.format( vuln_type, description ) event = { 'timestamp': time.mktime(published_date.timetuple()), 'event_type': 'twistlock', 'msg_title': cve_id, 'msg_text': msg_text, "tags": self._config.tags, "aggregation_key": cve_id, 'host': self.hostname, } self.event(event)
[ "def", "_analyze_vulnerability", "(", "self", ",", "vuln", ",", "host", "=", "False", ",", "image", "=", "False", ")", ":", "cve_id", "=", "vuln", ".", "get", "(", "'id'", ")", "# if it doesn't have a cve id, it's probably an invalid record", "if", "not", "cve_id", ":", "return", "description", "=", "vuln", ".", "get", "(", "'description'", ")", "published", "=", "vuln", ".", "get", "(", "'published'", ")", "published_date", "=", "datetime", ".", "fromtimestamp", "(", "int", "(", "published", ")", ")", "if", "published_date", "<", "self", ".", "last_run", ":", "if", "host", ":", "vuln_type", "=", "'hosts'", "elif", "image", ":", "vuln_type", "=", "'images'", "else", ":", "vuln_type", "=", "'systems'", "msg_text", "=", "\"\"\"\n There is a new CVE affecting your {}:\n {}\n \"\"\"", ".", "format", "(", "vuln_type", ",", "description", ")", "event", "=", "{", "'timestamp'", ":", "time", ".", "mktime", "(", "published_date", ".", "timetuple", "(", ")", ")", ",", "'event_type'", ":", "'twistlock'", ",", "'msg_title'", ":", "cve_id", ",", "'msg_text'", ":", "msg_text", ",", "\"tags\"", ":", "self", ".", "_config", ".", "tags", ",", "\"aggregation_key\"", ":", "cve_id", ",", "'host'", ":", "self", ".", "hostname", ",", "}", "self", ".", "event", "(", "event", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/twistlock/datadog_checks/twistlock/twistlock.py#L231-L268
saleor/saleor
2221bdf61b037c660ffc2d1efa484d8efe8172f5
saleor/graphql/order/mutations/orders.py
python
clean_void_payment
(payment)
Check for payment errors.
Check for payment errors.
[ "Check", "for", "payment", "errors", "." ]
def clean_void_payment(payment): """Check for payment errors.""" clean_payment(payment) if not payment.is_active: raise ValidationError( { "payment": ValidationError( "Only pre-authorized payments can be voided", code=OrderErrorCode.VOID_INACTIVE_PAYMENT, ) } )
[ "def", "clean_void_payment", "(", "payment", ")", ":", "clean_payment", "(", "payment", ")", "if", "not", "payment", ".", "is_active", ":", "raise", "ValidationError", "(", "{", "\"payment\"", ":", "ValidationError", "(", "\"Only pre-authorized payments can be voided\"", ",", "code", "=", "OrderErrorCode", ".", "VOID_INACTIVE_PAYMENT", ",", ")", "}", ")" ]
https://github.com/saleor/saleor/blob/2221bdf61b037c660ffc2d1efa484d8efe8172f5/saleor/graphql/order/mutations/orders.py#L121-L132
google/neural-logic-machines
3f8a8966c54d13d2658c77c03793a9a98a283e22
difflogic/envs/graph/graph_env.py
python
PathGraphEnv._gen
(self)
return st[ind], ed[ind]
Sample the starting node and the destination according to the distance.
Sample the starting node and the destination according to the distance.
[ "Sample", "the", "starting", "node", "and", "the", "destination", "according", "to", "the", "distance", "." ]
def _gen(self): """Sample the starting node and the destination according to the distance.""" dist_matrix = self._graph.get_shortest() st, ed = np.where(dist_matrix == self.dist) if len(st) == 0: return None ind = random.randint(len(st)) return st[ind], ed[ind]
[ "def", "_gen", "(", "self", ")", ":", "dist_matrix", "=", "self", ".", "_graph", ".", "get_shortest", "(", ")", "st", ",", "ed", "=", "np", ".", "where", "(", "dist_matrix", "==", "self", ".", "dist", ")", "if", "len", "(", "st", ")", "==", "0", ":", "return", "None", "ind", "=", "random", ".", "randint", "(", "len", "(", "st", ")", ")", "return", "st", "[", "ind", "]", ",", "ed", "[", "ind", "]" ]
https://github.com/google/neural-logic-machines/blob/3f8a8966c54d13d2658c77c03793a9a98a283e22/difflogic/envs/graph/graph_env.py#L115-L122
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/gui/api_call_router_with_approval_checks.py
python
ApiCallRouterWithApprovalChecks.GetGrrBinaryBlob
(self, args, context=None)
return self.delegate.GetGrrBinaryBlob(args, context=context)
[]
def GetGrrBinaryBlob(self, args, context=None): self.access_checker.CheckIfUserIsAdmin(context.username) return self.delegate.GetGrrBinaryBlob(args, context=context)
[ "def", "GetGrrBinaryBlob", "(", "self", ",", "args", ",", "context", "=", "None", ")", ":", "self", ".", "access_checker", ".", "CheckIfUserIsAdmin", "(", "context", ".", "username", ")", "return", "self", ".", "delegate", ".", "GetGrrBinaryBlob", "(", "args", ",", "context", "=", "context", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_call_router_with_approval_checks.py#L867-L870
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/sre_parse.py
python
Pattern.closegroup
(self, gid)
[]
def closegroup(self, gid): self.open.remove(gid)
[ "def", "closegroup", "(", "self", ",", "gid", ")", ":", "self", ".", "open", ".", "remove", "(", "gid", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/sre_parse.py#L87-L88
pgq/skytools-legacy
8b7e6c118572a605d28b7a3403c96aeecfd0d272
python/pgq/cascade/admin.py
python
CascadeAdmin.find_provider
(self, node_name)
return self.find_root_node()
[]
def find_provider(self, node_name): if self.node_alive(node_name): info = self.get_node_info(node_name) return info.provider_node nodelist = self.queue_info.member_map.keys() for n in nodelist: if n == node_name: continue if not self.node_alive(n): continue if node_name in self.get_node_subscriber_list(n): return n return self.find_root_node()
[ "def", "find_provider", "(", "self", ",", "node_name", ")", ":", "if", "self", ".", "node_alive", "(", "node_name", ")", ":", "info", "=", "self", ".", "get_node_info", "(", "node_name", ")", "return", "info", ".", "provider_node", "nodelist", "=", "self", ".", "queue_info", ".", "member_map", ".", "keys", "(", ")", "for", "n", "in", "nodelist", ":", "if", "n", "==", "node_name", ":", "continue", "if", "not", "self", ".", "node_alive", "(", "n", ")", ":", "continue", "if", "node_name", "in", "self", ".", "get_node_subscriber_list", "(", "n", ")", ":", "return", "n", "return", "self", ".", "find_root_node", "(", ")" ]
https://github.com/pgq/skytools-legacy/blob/8b7e6c118572a605d28b7a3403c96aeecfd0d272/python/pgq/cascade/admin.py#L851-L863
polyaxon/polyaxon
e28d82051c2b61a84d06ce4d2388a40fc8565469
src/core/polyaxon/connections/gcp/gcs.py
python
GCSService.get_blob
(self, blob, bucket_name=None)
return obj
Get a file in Google Cloud Storage. Args: blob: `str`. the path to the object to check in the Google cloud storage bucket. bucket_name: `str`. Name of the bucket in which the file is stored
Get a file in Google Cloud Storage.
[ "Get", "a", "file", "in", "Google", "Cloud", "Storage", "." ]
def get_blob(self, blob, bucket_name=None): """ Get a file in Google Cloud Storage. Args: blob: `str`. the path to the object to check in the Google cloud storage bucket. bucket_name: `str`. Name of the bucket in which the file is stored """ if not bucket_name: bucket_name, blob = self.parse_gcs_url(blob) bucket = self.get_bucket(bucket_name) # Wrap google.cloud.storage's blob to raise if the file doesn't exist obj = bucket.get_blob(blob) if obj is None: raise PolyaxonStoresException("File does not exist: {}".format(blob)) return obj
[ "def", "get_blob", "(", "self", ",", "blob", ",", "bucket_name", "=", "None", ")", ":", "if", "not", "bucket_name", ":", "bucket_name", ",", "blob", "=", "self", ".", "parse_gcs_url", "(", "blob", ")", "bucket", "=", "self", ".", "get_bucket", "(", "bucket_name", ")", "# Wrap google.cloud.storage's blob to raise if the file doesn't exist", "obj", "=", "bucket", ".", "get_blob", "(", "blob", ")", "if", "obj", "is", "None", ":", "raise", "PolyaxonStoresException", "(", "\"File does not exist: {}\"", ".", "format", "(", "blob", ")", ")", "return", "obj" ]
https://github.com/polyaxon/polyaxon/blob/e28d82051c2b61a84d06ce4d2388a40fc8565469/src/core/polyaxon/connections/gcp/gcs.py#L81-L99
Gsllchb/Handright
c32d62d6a4c7ccad78c5a464cf0273a0004f943e
handright/_util.py
python
NumericOrderedSet.__contains__
(self, item)
return item in self._set
[]
def __contains__(self, item) -> bool: return item in self._set
[ "def", "__contains__", "(", "self", ",", "item", ")", "->", "bool", ":", "return", "item", "in", "self", ".", "_set" ]
https://github.com/Gsllchb/Handright/blob/c32d62d6a4c7ccad78c5a464cf0273a0004f943e/handright/_util.py#L88-L89
kerlomz/captcha_trainer
72b0cd02c66a9b44073820098155b3278c8bde61
app.py
python
Wizard.listbox_scrollbar
(listbox: tk.Listbox)
[]
def listbox_scrollbar(listbox: tk.Listbox): y_scrollbar = tk.Scrollbar( listbox, command=listbox.yview ) y_scrollbar.pack(side=tk.RIGHT, fill=tk.Y) listbox.config(yscrollcommand=y_scrollbar.set)
[ "def", "listbox_scrollbar", "(", "listbox", ":", "tk", ".", "Listbox", ")", ":", "y_scrollbar", "=", "tk", ".", "Scrollbar", "(", "listbox", ",", "command", "=", "listbox", ".", "yview", ")", "y_scrollbar", ".", "pack", "(", "side", "=", "tk", ".", "RIGHT", ",", "fill", "=", "tk", ".", "Y", ")", "listbox", ".", "config", "(", "yscrollcommand", "=", "y_scrollbar", ".", "set", ")" ]
https://github.com/kerlomz/captcha_trainer/blob/72b0cd02c66a9b44073820098155b3278c8bde61/app.py#L860-L865
pyeventsourcing/eventsourcing
f5a36f434ab2631890092b6c7714b8fb8c94dc7c
eventsourcing/persistence.py
python
InfrastructureFactory.is_snapshotting_enabled
(self)
return strtobool(self.env.get(self.IS_SNAPSHOTTING_ENABLED, "no"))
Decides whether or not snapshotting is enabled by reading environment variable 'IS_SNAPSHOTTING_ENABLED'. Snapshotting is not enabled by default.
Decides whether or not snapshotting is enabled by reading environment variable 'IS_SNAPSHOTTING_ENABLED'. Snapshotting is not enabled by default.
[ "Decides", "whether", "or", "not", "snapshotting", "is", "enabled", "by", "reading", "environment", "variable", "IS_SNAPSHOTTING_ENABLED", ".", "Snapshotting", "is", "not", "enabled", "by", "default", "." ]
def is_snapshotting_enabled(self) -> bool: """ Decides whether or not snapshotting is enabled by reading environment variable 'IS_SNAPSHOTTING_ENABLED'. Snapshotting is not enabled by default. """ return strtobool(self.env.get(self.IS_SNAPSHOTTING_ENABLED, "no"))
[ "def", "is_snapshotting_enabled", "(", "self", ")", "->", "bool", ":", "return", "strtobool", "(", "self", ".", "env", ".", "get", "(", "self", ".", "IS_SNAPSHOTTING_ENABLED", ",", "\"no\"", ")", ")" ]
https://github.com/pyeventsourcing/eventsourcing/blob/f5a36f434ab2631890092b6c7714b8fb8c94dc7c/eventsourcing/persistence.py#L729-L735
catalyst-team/catalyst
678dc06eda1848242df010b7f34adb572def2598
catalyst/callbacks/metric.py
python
IMetricCallback.on_loader_end
(self, runner: "IRunner")
On loader end action Args: runner: current runner
On loader end action
[ "On", "loader", "end", "action" ]
def on_loader_end(self, runner: "IRunner") -> None: """ On loader end action Args: runner: current runner """ pass
[ "def", "on_loader_end", "(", "self", ",", "runner", ":", "\"IRunner\"", ")", "->", "None", ":", "pass" ]
https://github.com/catalyst-team/catalyst/blob/678dc06eda1848242df010b7f34adb572def2598/catalyst/callbacks/metric.py#L36-L43
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/setup.py
python
_async_when_setup
( hass: core.HomeAssistant, component: str, when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]], start_event: bool, )
Call a method when a component is setup or the start event fires.
Call a method when a component is setup or the start event fires.
[ "Call", "a", "method", "when", "a", "component", "is", "setup", "or", "the", "start", "event", "fires", "." ]
def _async_when_setup( hass: core.HomeAssistant, component: str, when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]], start_event: bool, ) -> None: """Call a method when a component is setup or the start event fires.""" async def when_setup() -> None: """Call the callback.""" try: await when_setup_cb(hass, component) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error handling when_setup callback for %s", component) if component in hass.config.components: hass.async_create_task(when_setup()) return listeners: list[CALLBACK_TYPE] = [] async def _matched_event(event: core.Event) -> None: """Call the callback when we matched an event.""" for listener in listeners: listener() await when_setup() async def _loaded_event(event: core.Event) -> None: """Call the callback if we loaded the expected component.""" if event.data[ATTR_COMPONENT] == component: await _matched_event(event) listeners.append(hass.bus.async_listen(EVENT_COMPONENT_LOADED, _loaded_event)) if start_event: listeners.append( hass.bus.async_listen(EVENT_HOMEASSISTANT_START, _matched_event) )
[ "def", "_async_when_setup", "(", "hass", ":", "core", ".", "HomeAssistant", ",", "component", ":", "str", ",", "when_setup_cb", ":", "Callable", "[", "[", "core", ".", "HomeAssistant", ",", "str", "]", ",", "Awaitable", "[", "None", "]", "]", ",", "start_event", ":", "bool", ",", ")", "->", "None", ":", "async", "def", "when_setup", "(", ")", "->", "None", ":", "\"\"\"Call the callback.\"\"\"", "try", ":", "await", "when_setup_cb", "(", "hass", ",", "component", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "_LOGGER", ".", "exception", "(", "\"Error handling when_setup callback for %s\"", ",", "component", ")", "if", "component", "in", "hass", ".", "config", ".", "components", ":", "hass", ".", "async_create_task", "(", "when_setup", "(", ")", ")", "return", "listeners", ":", "list", "[", "CALLBACK_TYPE", "]", "=", "[", "]", "async", "def", "_matched_event", "(", "event", ":", "core", ".", "Event", ")", "->", "None", ":", "\"\"\"Call the callback when we matched an event.\"\"\"", "for", "listener", "in", "listeners", ":", "listener", "(", ")", "await", "when_setup", "(", ")", "async", "def", "_loaded_event", "(", "event", ":", "core", ".", "Event", ")", "->", "None", ":", "\"\"\"Call the callback if we loaded the expected component.\"\"\"", "if", "event", ".", "data", "[", "ATTR_COMPONENT", "]", "==", "component", ":", "await", "_matched_event", "(", "event", ")", "listeners", ".", "append", "(", "hass", ".", "bus", ".", "async_listen", "(", "EVENT_COMPONENT_LOADED", ",", "_loaded_event", ")", ")", "if", "start_event", ":", "listeners", ".", "append", "(", "hass", ".", "bus", ".", "async_listen", "(", "EVENT_HOMEASSISTANT_START", ",", "_matched_event", ")", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/setup.py#L380-L416
arskom/spyne
88b8e278335f03c7e615b913d6dabc2b8141730e
spyne/store/relational/util.py
python
database_exists
(url)
Check if a database exists. :param url: A SQLAlchemy engine URL. Performs backend-specific testing to quickly determine if a database exists on the server. :: database_exists('postgresql://postgres@localhost/name') #=> False create_database('postgresql://postgres@localhost/name') database_exists('postgresql://postgres@localhost/name') #=> True Supports checking against a constructed URL as well. :: engine = create_engine('postgresql://postgres@localhost/name') database_exists(engine.url) #=> False create_database(engine.url) database_exists(engine.url) #=> True
Check if a database exists.
[ "Check", "if", "a", "database", "exists", "." ]
def database_exists(url): """Check if a database exists. :param url: A SQLAlchemy engine URL. Performs backend-specific testing to quickly determine if a database exists on the server. :: database_exists('postgresql://postgres@localhost/name') #=> False create_database('postgresql://postgres@localhost/name') database_exists('postgresql://postgres@localhost/name') #=> True Supports checking against a constructed URL as well. :: engine = create_engine('postgresql://postgres@localhost/name') database_exists(engine.url) #=> False create_database(engine.url) database_exists(engine.url) #=> True """ url = copy(make_url(url)) database = url.database if url.drivername.startswith('postgres'): url.database = 'postgres' elif not url.drivername.startswith('sqlite'): url.database = None engine = create_engine(url) if engine.dialect.name == 'postgresql': text = "SELECT 1 FROM pg_database WHERE datname='%s'" % database return bool(engine.execute(text).scalar()) elif engine.dialect.name == 'mysql': text = ("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA " "WHERE SCHEMA_NAME = '%s'" % database) return bool(engine.execute(text).scalar()) elif engine.dialect.name == 'sqlite': return database == ':memory:' or os.path.exists(database) else: text = 'SELECT 1' try: url.database = database engine = create_engine(url) engine.execute(text) return True except (ProgrammingError, OperationalError): return False
[ "def", "database_exists", "(", "url", ")", ":", "url", "=", "copy", "(", "make_url", "(", "url", ")", ")", "database", "=", "url", ".", "database", "if", "url", ".", "drivername", ".", "startswith", "(", "'postgres'", ")", ":", "url", ".", "database", "=", "'postgres'", "elif", "not", "url", ".", "drivername", ".", "startswith", "(", "'sqlite'", ")", ":", "url", ".", "database", "=", "None", "engine", "=", "create_engine", "(", "url", ")", "if", "engine", ".", "dialect", ".", "name", "==", "'postgresql'", ":", "text", "=", "\"SELECT 1 FROM pg_database WHERE datname='%s'\"", "%", "database", "return", "bool", "(", "engine", ".", "execute", "(", "text", ")", ".", "scalar", "(", ")", ")", "elif", "engine", ".", "dialect", ".", "name", "==", "'mysql'", ":", "text", "=", "(", "\"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA \"", "\"WHERE SCHEMA_NAME = '%s'\"", "%", "database", ")", "return", "bool", "(", "engine", ".", "execute", "(", "text", ")", ".", "scalar", "(", ")", ")", "elif", "engine", ".", "dialect", ".", "name", "==", "'sqlite'", ":", "return", "database", "==", "':memory:'", "or", "os", ".", "path", ".", "exists", "(", "database", ")", "else", ":", "text", "=", "'SELECT 1'", "try", ":", "url", ".", "database", "=", "database", "engine", "=", "create_engine", "(", "url", ")", "engine", ".", "execute", "(", "text", ")", "return", "True", "except", "(", "ProgrammingError", ",", "OperationalError", ")", ":", "return", "False" ]
https://github.com/arskom/spyne/blob/88b8e278335f03c7e615b913d6dabc2b8141730e/spyne/store/relational/util.py#L92-L143
spotify/luigi
c3b66f4a5fa7eaa52f9a72eb6704b1049035c789
luigi/contrib/ssh.py
python
RemoteFileSystem.get
(self, path, local_path)
[]
def get(self, path, local_path): # Create folder if it does not exist normpath = os.path.normpath(local_path) folder = os.path.dirname(normpath) if folder: try: os.makedirs(folder) except OSError: pass tmp_local_path = local_path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) self._scp("%s:%s" % (self.remote_context._host_ref(), path), tmp_local_path) os.rename(tmp_local_path, local_path)
[ "def", "get", "(", "self", ",", "path", ",", "local_path", ")", ":", "# Create folder if it does not exist", "normpath", "=", "os", ".", "path", ".", "normpath", "(", "local_path", ")", "folder", "=", "os", ".", "path", ".", "dirname", "(", "normpath", ")", "if", "folder", ":", "try", ":", "os", ".", "makedirs", "(", "folder", ")", "except", "OSError", ":", "pass", "tmp_local_path", "=", "local_path", "+", "'-luigi-tmp-%09d'", "%", "random", ".", "randrange", "(", "0", ",", "1e10", ")", "self", ".", "_scp", "(", "\"%s:%s\"", "%", "(", "self", ".", "remote_context", ".", "_host_ref", "(", ")", ",", "path", ")", ",", "tmp_local_path", ")", "os", ".", "rename", "(", "tmp_local_path", ",", "local_path", ")" ]
https://github.com/spotify/luigi/blob/c3b66f4a5fa7eaa52f9a72eb6704b1049035c789/luigi/contrib/ssh.py#L261-L273
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/astroprint/printer/__init__.py
python
Printer.selectFile
(self, filename, sd, printAfterSelect=False, printJobId=None)
return True
[]
def selectFile(self, filename, sd, printAfterSelect=False, printJobId=None): if not self.isConnected() or self.isBusy() or self.isStreaming(): self._logger.info("Cannot load file: printer not connected or currently busy") return False self._setProgressData(0, None, None, None, 1) self._setCurrentZ(None) if not os.path.exists(filename) or not os.path.isfile(filename): raise IOError("File %s does not exist" % filename) filesize = os.stat(filename).st_size eventManager().fire(Events.FILE_SELECTED, { "file": filename, "origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL }) self._setJobData(filename, filesize, sd) self.refreshStateData() self._currentFile = { 'filename': filename, 'size': filesize, 'origin': FileDestinations.SDCARD if sd else FileDestinations.LOCAL, 'start_time': None, 'progress': None, 'position': None } if printAfterSelect: self.startPrint(printJobId) return True
[ "def", "selectFile", "(", "self", ",", "filename", ",", "sd", ",", "printAfterSelect", "=", "False", ",", "printJobId", "=", "None", ")", ":", "if", "not", "self", ".", "isConnected", "(", ")", "or", "self", ".", "isBusy", "(", ")", "or", "self", ".", "isStreaming", "(", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Cannot load file: printer not connected or currently busy\"", ")", "return", "False", "self", ".", "_setProgressData", "(", "0", ",", "None", ",", "None", ",", "None", ",", "1", ")", "self", ".", "_setCurrentZ", "(", "None", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", "or", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "raise", "IOError", "(", "\"File %s does not exist\"", "%", "filename", ")", "filesize", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "eventManager", "(", ")", ".", "fire", "(", "Events", ".", "FILE_SELECTED", ",", "{", "\"file\"", ":", "filename", ",", "\"origin\"", ":", "FileDestinations", ".", "SDCARD", "if", "sd", "else", "FileDestinations", ".", "LOCAL", "}", ")", "self", ".", "_setJobData", "(", "filename", ",", "filesize", ",", "sd", ")", "self", ".", "refreshStateData", "(", ")", "self", ".", "_currentFile", "=", "{", "'filename'", ":", "filename", ",", "'size'", ":", "filesize", ",", "'origin'", ":", "FileDestinations", ".", "SDCARD", "if", "sd", "else", "FileDestinations", ".", "LOCAL", ",", "'start_time'", ":", "None", ",", "'progress'", ":", "None", ",", "'position'", ":", "None", "}", "if", "printAfterSelect", ":", "self", ".", "startPrint", "(", "printJobId", ")", "return", "True" ]
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/printer/__init__.py#L742-L775
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/statistics.py
python
_counts
(data)
return table
[]
def _counts(data): # Generate a table of sorted (value, frequency) pairs. table = collections.Counter(iter(data)).most_common() if not table: return table # Extract the values with the highest frequency. maxfreq = table[0][1] for i in range(1, len(table)): if table[i][1] != maxfreq: table = table[:i] break return table
[ "def", "_counts", "(", "data", ")", ":", "# Generate a table of sorted (value, frequency) pairs.", "table", "=", "collections", ".", "Counter", "(", "iter", "(", "data", ")", ")", ".", "most_common", "(", ")", "if", "not", "table", ":", "return", "table", "# Extract the values with the highest frequency.", "maxfreq", "=", "table", "[", "0", "]", "[", "1", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "table", ")", ")", ":", "if", "table", "[", "i", "]", "[", "1", "]", "!=", "maxfreq", ":", "table", "=", "table", "[", ":", "i", "]", "break", "return", "table" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/statistics.py#L294-L305
poodarchu/Det3D
01258d8cb26656c5b950f8d41f9dcc1dd62a391e
det3d/torchie/fileio/io.py
python
load
(file, file_format=None, **kwargs)
return obj
Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file extension, otherwise use the specified one. Currently supported formats include "json", "yaml/yml" and "pickle/pkl". Returns: The content from the file.
Load data from json/yaml/pickle files.
[ "Load", "data", "from", "json", "/", "yaml", "/", "pickle", "files", "." ]
def load(file, file_format=None, **kwargs): """Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file extension, otherwise use the specified one. Currently supported formats include "json", "yaml/yml" and "pickle/pkl". Returns: The content from the file. """ if isinstance(file, Path): file = str(file) if file_format is None and is_str(file): file_format = file.split(".")[-1] if file_format not in file_handlers: raise TypeError("Unsupported format: {}".format(file_format)) handler = file_handlers[file_format] if is_str(file): obj = handler.load_from_path(file, **kwargs) elif hasattr(file, "read"): obj = handler.load_from_fileobj(file, **kwargs) else: raise TypeError('"file" must be a filepath str or a file-object') return obj
[ "def", "load", "(", "file", ",", "file_format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "file", ",", "Path", ")", ":", "file", "=", "str", "(", "file", ")", "if", "file_format", "is", "None", "and", "is_str", "(", "file", ")", ":", "file_format", "=", "file", ".", "split", "(", "\".\"", ")", "[", "-", "1", "]", "if", "file_format", "not", "in", "file_handlers", ":", "raise", "TypeError", "(", "\"Unsupported format: {}\"", ".", "format", "(", "file_format", ")", ")", "handler", "=", "file_handlers", "[", "file_format", "]", "if", "is_str", "(", "file", ")", ":", "obj", "=", "handler", ".", "load_from_path", "(", "file", ",", "*", "*", "kwargs", ")", "elif", "hasattr", "(", "file", ",", "\"read\"", ")", ":", "obj", "=", "handler", ".", "load_from_fileobj", "(", "file", ",", "*", "*", "kwargs", ")", "else", ":", "raise", "TypeError", "(", "'\"file\" must be a filepath str or a file-object'", ")", "return", "obj" ]
https://github.com/poodarchu/Det3D/blob/01258d8cb26656c5b950f8d41f9dcc1dd62a391e/det3d/torchie/fileio/io.py#L15-L45
NUAA-AL/ALiPy
bc69062c7129d597a9e54b9eb409c6fcb1f36a3c
alipy/experiment/stopping_criteria.py
python
StoppingCriteria.reset
(self)
Reset the current state to the initial.
Reset the current state to the initial.
[ "Reset", "the", "current", "state", "to", "the", "initial", "." ]
def reset(self): """ Reset the current state to the initial. """ self.value = self._init_value self._start_time = time.perf_counter() self._current_iter = 0 self._accum_cost = 0 self._current_unlabel = 100 self._percent = 0
[ "def", "reset", "(", "self", ")", ":", "self", ".", "value", "=", "self", ".", "_init_value", "self", ".", "_start_time", "=", "time", ".", "perf_counter", "(", ")", "self", ".", "_current_iter", "=", "0", "self", ".", "_accum_cost", "=", "0", "self", ".", "_current_unlabel", "=", "100", "self", ".", "_percent", "=", "0" ]
https://github.com/NUAA-AL/ALiPy/blob/bc69062c7129d597a9e54b9eb409c6fcb1f36a3c/alipy/experiment/stopping_criteria.py#L130-L139
MacSysadmin/pymacadmin
0f53c35cf9f540641c6d1bdaaf15e6c45fd36e66
pymacds-dist/pymacds/__init__.py
python
AddNodeToSearchPath
(node)
Adds a given DS node to the /Search path.
Adds a given DS node to the /Search path.
[ "Adds", "a", "given", "DS", "node", "to", "the", "/", "Search", "path", "." ]
def AddNodeToSearchPath(node): """Adds a given DS node to the /Search path.""" _ModifyCSPSearchPathForPath('append', node, '/Search')
[ "def", "AddNodeToSearchPath", "(", "node", ")", ":", "_ModifyCSPSearchPathForPath", "(", "'append'", ",", "node", ",", "'/Search'", ")" ]
https://github.com/MacSysadmin/pymacadmin/blob/0f53c35cf9f540641c6d1bdaaf15e6c45fd36e66/pymacds-dist/pymacds/__init__.py#L140-L142
Sprytile/Sprytile
6b68d0069aef5bfed6ab40d1d5a94a3382b41619
sprytile_gui.py
python
VIEW3D_OP_SprytileGui.draw_to_viewport
(view_min, view_max, show_extra, label_counter, tilegrid, sprytile_data, cursor_loc, region, rv3d, middle_btn, context)
Draw the offscreen texture into the viewport
Draw the offscreen texture into the viewport
[ "Draw", "the", "offscreen", "texture", "into", "the", "viewport" ]
def draw_to_viewport(view_min, view_max, show_extra, label_counter, tilegrid, sprytile_data, cursor_loc, region, rv3d, middle_btn, context): """Draw the offscreen texture into the viewport""" projection_mat = sprytile_utils.get_ortho2D_matrix(0, context.region.width, 0, context.region.height) # Prepare some data that will be used for drawing grid_size = VIEW3D_OP_SprytileGui.loaded_grid.grid tile_sel = VIEW3D_OP_SprytileGui.loaded_grid.tile_selection padding = VIEW3D_OP_SprytileGui.loaded_grid.padding margin = VIEW3D_OP_SprytileGui.loaded_grid.margin is_pixel = sprytile_utils.grid_is_single_pixel(VIEW3D_OP_SprytileGui.loaded_grid) # Draw work plane VIEW3D_OP_SprytileGui.draw_work_plane(projection_mat, grid_size, sprytile_data, cursor_loc, region, rv3d, middle_btn) # Setup GL for drawing the offscreen texture bgl.glActiveTexture(bgl.GL_TEXTURE0) bgl.glBindTexture(bgl.GL_TEXTURE_2D, VIEW3D_OP_SprytileGui.texture) # Backup texture settings old_mag_filter = Buffer(bgl.GL_INT, 1) glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, old_mag_filter) old_wrap_S = Buffer(GL_INT, 1) old_wrap_T = Buffer(GL_INT, 1) glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, old_wrap_S) glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, old_wrap_T) # Set texture filter bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER, bgl.GL_NEAREST) bgl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) bgl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) bgl.glEnable(bgl.GL_TEXTURE_2D) bgl.glEnable(bgl.GL_BLEND) # Draw the preview tile if middle_btn is False: VIEW3D_OP_SprytileGui.draw_preview_tile(context, region, rv3d, projection_mat) # Calculate actual view size view_size = int(view_max.x - view_min.x), int(view_max.y - view_min.y) # Save the original scissor box, and then set new scissor setting scissor_box = bgl.Buffer(bgl.GL_INT, [4]) bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, scissor_box) bgl.glScissor(int(view_min.x) + scissor_box[0] - 1, int(view_min.y) + scissor_box[1] - 1, view_size[0] + 1, view_size[1] + 1) bgl.glEnable(bgl.GL_SCISSOR_TEST) # Draw the tile select UI VIEW3D_OP_SprytileGui.draw_tile_select_ui(projection_mat, view_min, view_max, view_size, VIEW3D_OP_SprytileGui.tex_size, grid_size, tile_sel, padding, margin, show_extra, is_pixel) # restore opengl defaults bgl.glScissor(scissor_box[0], scissor_box[1], scissor_box[2], scissor_box[3]) bgl.glDisable(bgl.GL_SCISSOR_TEST) bgl.glLineWidth(1) bgl.glTexParameteriv(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER, old_mag_filter) bgl.glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, old_wrap_S) bgl.glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, old_wrap_T) # Draw label font_id = 0 font_size = 16 pad = 5 if label_counter > 0: import math def ease_out_circ(t, b, c, d): t /= d t -= 1 return c * math.sqrt(1 - t * t) + b box_pad = font_size + (pad * 2) fade = label_counter fade = ease_out_circ(fade, 0, VIEW3D_OP_SprytileGui.label_frames, VIEW3D_OP_SprytileGui.label_frames) fade /= VIEW3D_OP_SprytileGui.label_frames color = (0.0, 0.0, 0.0, 0.75 * fade) vtx = [(view_min.x, view_max.y + box_pad), (view_min.x, view_max.y), (view_max.x, view_max.y + +box_pad), (view_max.x, view_max.y)] VIEW3D_OP_SprytileGui.draw_full_quad(vtx, projection_mat, color) blf.color(font_id, 1.0, 1.0, 1.0, 1.0 * fade) blf.size(font_id, font_size, 72) x_pos = view_min.x + pad y_pos = view_max.y + pad label_string = "%dx%d" % (tilegrid.grid[0], tilegrid.grid[1]) if tilegrid.name != "": label_string = "%s - %s" % (label_string, tilegrid.name) blf.position(font_id, x_pos, y_pos, 0) blf.draw(font_id, label_string) if tilegrid.grid[0] == 1 and tilegrid.grid[1] == 1: size_text = "%dx%d" % (tile_sel[2], tile_sel[3]) blf.size(font_id, font_size, 72) size = blf.dimensions(font_id, size_text) x_pos = view_max.x - size[0] - pad y_pos = view_max.y + pad blf.position(font_id, x_pos, y_pos, 0) blf.draw(font_id, size_text) bgl.glDisable(bgl.GL_BLEND) bgl.glDisable(bgl.GL_TEXTURE_2D)
[ "def", "draw_to_viewport", "(", "view_min", ",", "view_max", ",", "show_extra", ",", "label_counter", ",", "tilegrid", ",", "sprytile_data", ",", "cursor_loc", ",", "region", ",", "rv3d", ",", "middle_btn", ",", "context", ")", ":", "projection_mat", "=", "sprytile_utils", ".", "get_ortho2D_matrix", "(", "0", ",", "context", ".", "region", ".", "width", ",", "0", ",", "context", ".", "region", ".", "height", ")", "# Prepare some data that will be used for drawing", "grid_size", "=", "VIEW3D_OP_SprytileGui", ".", "loaded_grid", ".", "grid", "tile_sel", "=", "VIEW3D_OP_SprytileGui", ".", "loaded_grid", ".", "tile_selection", "padding", "=", "VIEW3D_OP_SprytileGui", ".", "loaded_grid", ".", "padding", "margin", "=", "VIEW3D_OP_SprytileGui", ".", "loaded_grid", ".", "margin", "is_pixel", "=", "sprytile_utils", ".", "grid_is_single_pixel", "(", "VIEW3D_OP_SprytileGui", ".", "loaded_grid", ")", "# Draw work plane", "VIEW3D_OP_SprytileGui", ".", "draw_work_plane", "(", "projection_mat", ",", "grid_size", ",", "sprytile_data", ",", "cursor_loc", ",", "region", ",", "rv3d", ",", "middle_btn", ")", "# Setup GL for drawing the offscreen texture", "bgl", ".", "glActiveTexture", "(", "bgl", ".", "GL_TEXTURE0", ")", "bgl", ".", "glBindTexture", "(", "bgl", ".", "GL_TEXTURE_2D", ",", "VIEW3D_OP_SprytileGui", ".", "texture", ")", "# Backup texture settings", "old_mag_filter", "=", "Buffer", "(", "bgl", ".", "GL_INT", ",", "1", ")", "glGetTexParameteriv", "(", "GL_TEXTURE_2D", ",", "GL_TEXTURE_MAG_FILTER", ",", "old_mag_filter", ")", "old_wrap_S", "=", "Buffer", "(", "GL_INT", ",", "1", ")", "old_wrap_T", "=", "Buffer", "(", "GL_INT", ",", "1", ")", "glGetTexParameteriv", "(", "GL_TEXTURE_2D", ",", "GL_TEXTURE_WRAP_S", ",", "old_wrap_S", ")", "glGetTexParameteriv", "(", "GL_TEXTURE_2D", ",", "GL_TEXTURE_WRAP_T", ",", "old_wrap_T", ")", "# Set texture filter", "bgl", ".", "glTexParameteri", "(", "bgl", ".", "GL_TEXTURE_2D", ",", "bgl", ".", "GL_TEXTURE_MAG_FILTER", ",", "bgl", ".", "GL_NEAREST", ")", "bgl", ".", "glTexParameteri", "(", "GL_TEXTURE_2D", ",", "GL_TEXTURE_WRAP_S", ",", "GL_REPEAT", ")", "bgl", ".", "glTexParameteri", "(", "GL_TEXTURE_2D", ",", "GL_TEXTURE_WRAP_T", ",", "GL_REPEAT", ")", "bgl", ".", "glEnable", "(", "bgl", ".", "GL_TEXTURE_2D", ")", "bgl", ".", "glEnable", "(", "bgl", ".", "GL_BLEND", ")", "# Draw the preview tile", "if", "middle_btn", "is", "False", ":", "VIEW3D_OP_SprytileGui", ".", "draw_preview_tile", "(", "context", ",", "region", ",", "rv3d", ",", "projection_mat", ")", "# Calculate actual view size", "view_size", "=", "int", "(", "view_max", ".", "x", "-", "view_min", ".", "x", ")", ",", "int", "(", "view_max", ".", "y", "-", "view_min", ".", "y", ")", "# Save the original scissor box, and then set new scissor setting", "scissor_box", "=", "bgl", ".", "Buffer", "(", "bgl", ".", "GL_INT", ",", "[", "4", "]", ")", "bgl", ".", "glGetIntegerv", "(", "bgl", ".", "GL_SCISSOR_BOX", ",", "scissor_box", ")", "bgl", ".", "glScissor", "(", "int", "(", "view_min", ".", "x", ")", "+", "scissor_box", "[", "0", "]", "-", "1", ",", "int", "(", "view_min", ".", "y", ")", "+", "scissor_box", "[", "1", "]", "-", "1", ",", "view_size", "[", "0", "]", "+", "1", ",", "view_size", "[", "1", "]", "+", "1", ")", "bgl", ".", "glEnable", "(", "bgl", ".", "GL_SCISSOR_TEST", ")", "# Draw the tile select UI", "VIEW3D_OP_SprytileGui", ".", "draw_tile_select_ui", "(", "projection_mat", ",", "view_min", ",", "view_max", ",", "view_size", ",", "VIEW3D_OP_SprytileGui", ".", "tex_size", ",", "grid_size", ",", "tile_sel", ",", "padding", ",", "margin", ",", "show_extra", ",", "is_pixel", ")", "# restore opengl defaults", "bgl", ".", "glScissor", "(", "scissor_box", "[", "0", "]", ",", "scissor_box", "[", "1", "]", ",", "scissor_box", "[", "2", "]", ",", "scissor_box", "[", "3", "]", ")", "bgl", ".", "glDisable", "(", "bgl", ".", "GL_SCISSOR_TEST", ")", "bgl", ".", "glLineWidth", "(", "1", ")", "bgl", ".", "glTexParameteriv", "(", "bgl", ".", "GL_TEXTURE_2D", ",", "bgl", ".", "GL_TEXTURE_MAG_FILTER", ",", "old_mag_filter", ")", "bgl", ".", "glTexParameteriv", "(", "GL_TEXTURE_2D", ",", "GL_TEXTURE_WRAP_S", ",", "old_wrap_S", ")", "bgl", ".", "glTexParameteriv", "(", "GL_TEXTURE_2D", ",", "GL_TEXTURE_WRAP_T", ",", "old_wrap_T", ")", "# Draw label", "font_id", "=", "0", "font_size", "=", "16", "pad", "=", "5", "if", "label_counter", ">", "0", ":", "import", "math", "def", "ease_out_circ", "(", "t", ",", "b", ",", "c", ",", "d", ")", ":", "t", "/=", "d", "t", "-=", "1", "return", "c", "*", "math", ".", "sqrt", "(", "1", "-", "t", "*", "t", ")", "+", "b", "box_pad", "=", "font_size", "+", "(", "pad", "*", "2", ")", "fade", "=", "label_counter", "fade", "=", "ease_out_circ", "(", "fade", ",", "0", ",", "VIEW3D_OP_SprytileGui", ".", "label_frames", ",", "VIEW3D_OP_SprytileGui", ".", "label_frames", ")", "fade", "/=", "VIEW3D_OP_SprytileGui", ".", "label_frames", "color", "=", "(", "0.0", ",", "0.0", ",", "0.0", ",", "0.75", "*", "fade", ")", "vtx", "=", "[", "(", "view_min", ".", "x", ",", "view_max", ".", "y", "+", "box_pad", ")", ",", "(", "view_min", ".", "x", ",", "view_max", ".", "y", ")", ",", "(", "view_max", ".", "x", ",", "view_max", ".", "y", "+", "+", "box_pad", ")", ",", "(", "view_max", ".", "x", ",", "view_max", ".", "y", ")", "]", "VIEW3D_OP_SprytileGui", ".", "draw_full_quad", "(", "vtx", ",", "projection_mat", ",", "color", ")", "blf", ".", "color", "(", "font_id", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", "*", "fade", ")", "blf", ".", "size", "(", "font_id", ",", "font_size", ",", "72", ")", "x_pos", "=", "view_min", ".", "x", "+", "pad", "y_pos", "=", "view_max", ".", "y", "+", "pad", "label_string", "=", "\"%dx%d\"", "%", "(", "tilegrid", ".", "grid", "[", "0", "]", ",", "tilegrid", ".", "grid", "[", "1", "]", ")", "if", "tilegrid", ".", "name", "!=", "\"\"", ":", "label_string", "=", "\"%s - %s\"", "%", "(", "label_string", ",", "tilegrid", ".", "name", ")", "blf", ".", "position", "(", "font_id", ",", "x_pos", ",", "y_pos", ",", "0", ")", "blf", ".", "draw", "(", "font_id", ",", "label_string", ")", "if", "tilegrid", ".", "grid", "[", "0", "]", "==", "1", "and", "tilegrid", ".", "grid", "[", "1", "]", "==", "1", ":", "size_text", "=", "\"%dx%d\"", "%", "(", "tile_sel", "[", "2", "]", ",", "tile_sel", "[", "3", "]", ")", "blf", ".", "size", "(", "font_id", ",", "font_size", ",", "72", ")", "size", "=", "blf", ".", "dimensions", "(", "font_id", ",", "size_text", ")", "x_pos", "=", "view_max", ".", "x", "-", "size", "[", "0", "]", "-", "pad", "y_pos", "=", "view_max", ".", "y", "+", "pad", "blf", ".", "position", "(", "font_id", ",", "x_pos", ",", "y_pos", ",", "0", ")", "blf", ".", "draw", "(", "font_id", ",", "size_text", ")", "bgl", ".", "glDisable", "(", "bgl", ".", "GL_BLEND", ")", "bgl", ".", "glDisable", "(", "bgl", ".", "GL_TEXTURE_2D", ")" ]
https://github.com/Sprytile/Sprytile/blob/6b68d0069aef5bfed6ab40d1d5a94a3382b41619/sprytile_gui.py#L958-L1060
aneisch/home-assistant-config
86e381fde9609cb8871c439c433c12989e4e225d
custom_components/hacs/operational/setup.py
python
async_startup_wrapper_for_config_entry
()
return startup_result
Startup wrapper for ui config.
Startup wrapper for ui config.
[ "Startup", "wrapper", "for", "ui", "config", "." ]
async def async_startup_wrapper_for_config_entry(): """Startup wrapper for ui config.""" hacs = get_hacs() try: startup_result = await async_hacs_startup() except AIOGitHubAPIException: startup_result = False if not startup_result: raise ConfigEntryNotReady(hacs.system.disabled_reason) hacs.enable_hacs() return startup_result
[ "async", "def", "async_startup_wrapper_for_config_entry", "(", ")", ":", "hacs", "=", "get_hacs", "(", ")", "try", ":", "startup_result", "=", "await", "async_hacs_startup", "(", ")", "except", "AIOGitHubAPIException", ":", "startup_result", "=", "False", "if", "not", "startup_result", ":", "raise", "ConfigEntryNotReady", "(", "hacs", ".", "system", ".", "disabled_reason", ")", "hacs", ".", "enable_hacs", "(", ")", "return", "startup_result" ]
https://github.com/aneisch/home-assistant-config/blob/86e381fde9609cb8871c439c433c12989e4e225d/custom_components/hacs/operational/setup.py#L119-L130
brechtm/rinohtype
d03096f9b1b0ba2d821a25356d84dc6d3028c96c
src/rinoh/layout.py
python
FlowableTarget.__init__
(self, document_part, *args, **kwargs)
Initialize this flowable target. `document_part` is the :class:`Document` this flowable target is part of.
Initialize this flowable target.
[ "Initialize", "this", "flowable", "target", "." ]
def __init__(self, document_part, *args, **kwargs): """Initialize this flowable target. `document_part` is the :class:`Document` this flowable target is part of.""" from .flowable import StaticGroupedFlowables self.flowables = StaticGroupedFlowables([]) super().__init__(*args, **kwargs)
[ "def", "__init__", "(", "self", ",", "document_part", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", ".", "flowable", "import", "StaticGroupedFlowables", "self", ".", "flowables", "=", "StaticGroupedFlowables", "(", "[", "]", ")", "super", "(", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/brechtm/rinohtype/blob/d03096f9b1b0ba2d821a25356d84dc6d3028c96c/src/rinoh/layout.py#L76-L84
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/logging/__init__.py
python
Handler.createLock
(self)
return
Acquire a thread lock for serializing access to the underlying I/O.
Acquire a thread lock for serializing access to the underlying I/O.
[ "Acquire", "a", "thread", "lock", "for", "serializing", "access", "to", "the", "underlying", "I", "/", "O", "." ]
def createLock(self): """ Acquire a thread lock for serializing access to the underlying I/O. """ if thread: self.lock = threading.RLock() else: self.lock = None return
[ "def", "createLock", "(", "self", ")", ":", "if", "thread", ":", "self", ".", "lock", "=", "threading", ".", "RLock", "(", ")", "else", ":", "self", ".", "lock", "=", "None", "return" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/logging/__init__.py#L591-L599
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/plugins/view/relview.py
python
RelationshipView._get_configure_page_funcs
(self)
return [self.content_panel, self.config_panel]
Return a list of functions that create gtk elements to use in the notebook pages of the Configure dialog :return: list of functions
Return a list of functions that create gtk elements to use in the notebook pages of the Configure dialog
[ "Return", "a", "list", "of", "functions", "that", "create", "gtk", "elements", "to", "use", "in", "the", "notebook", "pages", "of", "the", "Configure", "dialog" ]
def _get_configure_page_funcs(self): """ Return a list of functions that create gtk elements to use in the notebook pages of the Configure dialog :return: list of functions """ return [self.content_panel, self.config_panel]
[ "def", "_get_configure_page_funcs", "(", "self", ")", ":", "return", "[", "self", ".", "content_panel", ",", "self", ".", "config_panel", "]" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/plugins/view/relview.py#L1915-L1922
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/_pyio.py
python
IncrementalNewlineDecoder.reset
(self)
[]
def reset(self): self.seennl = 0 self.pendingcr = False if self.decoder is not None: self.decoder.reset()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "seennl", "=", "0", "self", ".", "pendingcr", "=", "False", "if", "self", ".", "decoder", "is", "not", "None", ":", "self", ".", "decoder", ".", "reset", "(", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/_pyio.py#L1431-L1435
thaines/helit
04bd36ee0fb6b762c63d746e2cd8813641dceda9
handwriting/hst/generate.py
python
combine_seperate
(lg_layout)
return ret
Given a line graph layout (List of (homography, line graph) pairs) this merges them all together into a single LineGraph. This version doesn't do anything clever.
Given a line graph layout (List of (homography, line graph) pairs) this merges them all together into a single LineGraph. This version doesn't do anything clever.
[ "Given", "a", "line", "graph", "layout", "(", "List", "of", "(", "homography", "line", "graph", ")", "pairs", ")", "this", "merges", "them", "all", "together", "into", "a", "single", "LineGraph", ".", "This", "version", "doesn", "t", "do", "anything", "clever", "." ]
def combine_seperate(lg_layout): """Given a line graph layout (List of (homography, line graph) pairs) this merges them all together into a single LineGraph. This version doesn't do anything clever.""" args = [] for hg, lg in lg_layout: args.append(hg) args.append(lg) ret = LineGraph() ret.from_many(*args) return ret
[ "def", "combine_seperate", "(", "lg_layout", ")", ":", "args", "=", "[", "]", "for", "hg", ",", "lg", "in", "lg_layout", ":", "args", ".", "append", "(", "hg", ")", "args", ".", "append", "(", "lg", ")", "ret", "=", "LineGraph", "(", ")", "ret", ".", "from_many", "(", "*", "args", ")", "return", "ret" ]
https://github.com/thaines/helit/blob/04bd36ee0fb6b762c63d746e2cd8813641dceda9/handwriting/hst/generate.py#L419-L428
packetloop/packetpig
6e101090224df219123ff5f6ab4c37524637571f
lib/scripts/impacket/impacket/dot11.py
python
RadioTap.get_data_retries
( self )
return values[0]
Get the number of data retries a transmitted frame used.
Get the number of data retries a transmitted frame used.
[ "Get", "the", "number", "of", "data", "retries", "a", "transmitted", "frame", "used", "." ]
def get_data_retries( self ): "Get the number of data retries a transmitted frame used." values=self.__get_field_values(self.RTF_DATA_RETRIES) if not values: return None return values[0]
[ "def", "get_data_retries", "(", "self", ")", ":", "values", "=", "self", ".", "__get_field_values", "(", "self", ".", "RTF_DATA_RETRIES", ")", "if", "not", "values", ":", "return", "None", "return", "values", "[", "0", "]" ]
https://github.com/packetloop/packetpig/blob/6e101090224df219123ff5f6ab4c37524637571f/lib/scripts/impacket/impacket/dot11.py#L1995-L2001
indico/indico
1579ea16235bbe5f22a308b79c5902c85374721f
indico/modules/events/contributions/models/contributions.py
python
Contribution.log
(self, *args, **kwargs)
Log with prefilled metadata for the contribution.
Log with prefilled metadata for the contribution.
[ "Log", "with", "prefilled", "metadata", "for", "the", "contribution", "." ]
def log(self, *args, **kwargs): """Log with prefilled metadata for the contribution.""" self.event.log(*args, meta={'contribution_id': self.id}, **kwargs)
[ "def", "log", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "event", ".", "log", "(", "*", "args", ",", "meta", "=", "{", "'contribution_id'", ":", "self", ".", "id", "}", ",", "*", "*", "kwargs", ")" ]
https://github.com/indico/indico/blob/1579ea16235bbe5f22a308b79c5902c85374721f/indico/modules/events/contributions/models/contributions.py#L577-L579
narc0tiq/factorio-updater
ac977cd4984bc2ffa4de391f07b119402da23919
update_factorio.py
python
get_updater_data
(user, token)
return r.json()
[]
def get_updater_data(user, token): payload = {'username': user, 'token': token, 'apiVersion': 2} r = requests.get('https://updater.factorio.com/get-available-versions', params=payload) if r.status_code != 200: raise DownloadFailed('Could not download version list.', r.status_code) if glob['verbose']: if token is not None: print(r.url.replace(token, '<secret>')) else: print(r.url) return r.json()
[ "def", "get_updater_data", "(", "user", ",", "token", ")", ":", "payload", "=", "{", "'username'", ":", "user", ",", "'token'", ":", "token", ",", "'apiVersion'", ":", "2", "}", "r", "=", "requests", ".", "get", "(", "'https://updater.factorio.com/get-available-versions'", ",", "params", "=", "payload", ")", "if", "r", ".", "status_code", "!=", "200", ":", "raise", "DownloadFailed", "(", "'Could not download version list.'", ",", "r", ".", "status_code", ")", "if", "glob", "[", "'verbose'", "]", ":", "if", "token", "is", "not", "None", ":", "print", "(", "r", ".", "url", ".", "replace", "(", "token", ",", "'<secret>'", ")", ")", "else", ":", "print", "(", "r", ".", "url", ")", "return", "r", ".", "json", "(", ")" ]
https://github.com/narc0tiq/factorio-updater/blob/ac977cd4984bc2ffa4de391f07b119402da23919/update_factorio.py#L68-L78
inspurer/WorkAttendanceSystem
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/distlib/index.py
python
PackageIndex.verify_signature
(self, signature_filename, data_filename, keystore=None)
return rc == 0
Verify a signature for a file. :param signature_filename: The pathname to the file containing the signature. :param data_filename: The pathname to the file containing the signed data. :param keystore: The path to a directory which contains the keys used in verification. If not specified, the instance's ``gpg_home`` attribute is used instead. :return: True if the signature was verified, else False.
Verify a signature for a file.
[ "Verify", "a", "signature", "for", "a", "file", "." ]
def verify_signature(self, signature_filename, data_filename, keystore=None): """ Verify a signature for a file. :param signature_filename: The pathname to the file containing the signature. :param data_filename: The pathname to the file containing the signed data. :param keystore: The path to a directory which contains the keys used in verification. If not specified, the instance's ``gpg_home`` attribute is used instead. :return: True if the signature was verified, else False. """ if not self.gpg: raise DistlibException('verification unavailable because gpg ' 'unavailable') cmd = self.get_verify_command(signature_filename, data_filename, keystore) rc, stdout, stderr = self.run_command(cmd) if rc not in (0, 1): raise DistlibException('verify command failed with error ' 'code %s' % rc) return rc == 0
[ "def", "verify_signature", "(", "self", ",", "signature_filename", ",", "data_filename", ",", "keystore", "=", "None", ")", ":", "if", "not", "self", ".", "gpg", ":", "raise", "DistlibException", "(", "'verification unavailable because gpg '", "'unavailable'", ")", "cmd", "=", "self", ".", "get_verify_command", "(", "signature_filename", ",", "data_filename", ",", "keystore", ")", "rc", ",", "stdout", ",", "stderr", "=", "self", ".", "run_command", "(", "cmd", ")", "if", "rc", "not", "in", "(", "0", ",", "1", ")", ":", "raise", "DistlibException", "(", "'verify command failed with error '", "'code %s'", "%", "rc", ")", "return", "rc", "==", "0" ]
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/distlib/index.py#L349-L372
google-research/albert
932b41f0319fbef7efd069d5ff545e3358574e19
optimization.py
python
AdamWeightDecayOptimizer._do_use_weight_decay
(self, param_name)
return True
Whether to use L2 weight decay for `param_name`.
Whether to use L2 weight decay for `param_name`.
[ "Whether", "to", "use", "L2", "weight", "decay", "for", "param_name", "." ]
def _do_use_weight_decay(self, param_name): """Whether to use L2 weight decay for `param_name`.""" if not self.weight_decay_rate: return False if self.exclude_from_weight_decay: for r in self.exclude_from_weight_decay: if re.search(r, param_name) is not None: return False return True
[ "def", "_do_use_weight_decay", "(", "self", ",", "param_name", ")", ":", "if", "not", "self", ".", "weight_decay_rate", ":", "return", "False", "if", "self", ".", "exclude_from_weight_decay", ":", "for", "r", "in", "self", ".", "exclude_from_weight_decay", ":", "if", "re", ".", "search", "(", "r", ",", "param_name", ")", "is", "not", "None", ":", "return", "False", "return", "True" ]
https://github.com/google-research/albert/blob/932b41f0319fbef7efd069d5ff545e3358574e19/optimization.py#L193-L201
hyde/hyde
7f415402cc3e007a746eb2b5bc102281fdb415bd
hyde/generator.py
python
Generator.generate_resource_at_path
(self, resource_path=None, incremental=False)
Generates a single resource. If resource_path is non-existent or empty, generates the entire website.
Generates a single resource. If resource_path is non-existent or empty, generates the entire website.
[ "Generates", "a", "single", "resource", ".", "If", "resource_path", "is", "non", "-", "existent", "or", "empty", "generates", "the", "entire", "website", "." ]
def generate_resource_at_path(self, resource_path=None, incremental=False): """ Generates a single resource. If resource_path is non-existent or empty, generates the entire website. """ if not self.generated_once and not incremental: return self.generate_all() self.load_template_if_needed() self.load_site_if_needed() resource = None if resource_path: resource = self.site.content.resource_from_path(resource_path) self.generate_resource(resource, incremental)
[ "def", "generate_resource_at_path", "(", "self", ",", "resource_path", "=", "None", ",", "incremental", "=", "False", ")", ":", "if", "not", "self", ".", "generated_once", "and", "not", "incremental", ":", "return", "self", ".", "generate_all", "(", ")", "self", ".", "load_template_if_needed", "(", ")", "self", ".", "load_site_if_needed", "(", ")", "resource", "=", "None", "if", "resource_path", ":", "resource", "=", "self", ".", "site", ".", "content", ".", "resource_from_path", "(", "resource_path", ")", "self", ".", "generate_resource", "(", "resource", ",", "incremental", ")" ]
https://github.com/hyde/hyde/blob/7f415402cc3e007a746eb2b5bc102281fdb415bd/hyde/generator.py#L267-L281
owid/covid-19-data
936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92
scripts/src/cowidev/utils/clean/strings.py
python
clean_string
(text_raw: str)
return text_new
Clean column name.
Clean column name.
[ "Clean", "column", "name", "." ]
def clean_string(text_raw: str): """Clean column name.""" text_new = unicodedata.normalize("NFKC", text_raw).strip() return text_new
[ "def", "clean_string", "(", "text_raw", ":", "str", ")", ":", "text_new", "=", "unicodedata", ".", "normalize", "(", "\"NFKC\"", ",", "text_raw", ")", ".", "strip", "(", ")", "return", "text_new" ]
https://github.com/owid/covid-19-data/blob/936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92/scripts/src/cowidev/utils/clean/strings.py#L4-L7
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/astroprint/boxrouter/handlers/__init__.py
python
BoxRouterMessageHandler.__init__
(self, weakRefBoxRouter, wsClient)
[]
def __init__(self, weakRefBoxRouter, wsClient): self._weakRefBoxRouter = weakRefBoxRouter self._weakWs = weakref.ref(wsClient) self._logger = logging.getLogger(__name__) self._subscribers = 0
[ "def", "__init__", "(", "self", ",", "weakRefBoxRouter", ",", "wsClient", ")", ":", "self", ".", "_weakRefBoxRouter", "=", "weakRefBoxRouter", "self", ".", "_weakWs", "=", "weakref", ".", "ref", "(", "wsClient", ")", "self", ".", "_logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "self", ".", "_subscribers", "=", "0" ]
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/boxrouter/handlers/__init__.py#L12-L16
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/requests/sessions.py
python
Session.get
(self, url, **kwargs)
return self.request('GET', url, **kwargs)
Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
Sends a GET request. Returns :class:`Response` object.
[ "Sends", "a", "GET", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def get(self, url, **kwargs): """Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs)
[ "def", "get", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'GET'", ",", "url", ",", "*", "*", "kwargs", ")" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/requests/sessions.py#L492-L501
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/mako/template.py
python
Template.cache
(self)
return cache.Cache(self)
[]
def cache(self): return cache.Cache(self)
[ "def", "cache", "(", "self", ")", ":", "return", "cache", ".", "Cache", "(", "self", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/mako/template.py#L446-L447
matt-graham/mici
aa209e2cf698bb9e0c7c733d7b6a5557ab5df190
mici/matrices.py
python
DenseSymmetricMatrix.__init__
(self, array, eigvec=None, eigval=None)
Args: array (array): Explicit 2D array representation of matrix. eigvec (None or array or OrthogonalMatrix): Optional. If specified either a 2D array or an `OrthogonalMatrix` instance, in both cases the columns of the matrix corresponding to the orthonormal set of eigenvectors of the matrix being constructed. eigval (None or array): Optional. If specified a 1D array containing the eigenvalues of the matrix being constructed, with `eigval[i]` the eigenvalue associated with column `i` of `eigvec`.
Args: array (array): Explicit 2D array representation of matrix. eigvec (None or array or OrthogonalMatrix): Optional. If specified either a 2D array or an `OrthogonalMatrix` instance, in both cases the columns of the matrix corresponding to the orthonormal set of eigenvectors of the matrix being constructed. eigval (None or array): Optional. If specified a 1D array containing the eigenvalues of the matrix being constructed, with `eigval[i]` the eigenvalue associated with column `i` of `eigvec`.
[ "Args", ":", "array", "(", "array", ")", ":", "Explicit", "2D", "array", "representation", "of", "matrix", ".", "eigvec", "(", "None", "or", "array", "or", "OrthogonalMatrix", ")", ":", "Optional", ".", "If", "specified", "either", "a", "2D", "array", "or", "an", "OrthogonalMatrix", "instance", "in", "both", "cases", "the", "columns", "of", "the", "matrix", "corresponding", "to", "the", "orthonormal", "set", "of", "eigenvectors", "of", "the", "matrix", "being", "constructed", ".", "eigval", "(", "None", "or", "array", ")", ":", "Optional", ".", "If", "specified", "a", "1D", "array", "containing", "the", "eigenvalues", "of", "the", "matrix", "being", "constructed", "with", "eigval", "[", "i", "]", "the", "eigenvalue", "associated", "with", "column", "i", "of", "eigvec", "." ]
def __init__(self, array, eigvec=None, eigval=None): """ Args: array (array): Explicit 2D array representation of matrix. eigvec (None or array or OrthogonalMatrix): Optional. If specified either a 2D array or an `OrthogonalMatrix` instance, in both cases the columns of the matrix corresponding to the orthonormal set of eigenvectors of the matrix being constructed. eigval (None or array): Optional. If specified a 1D array containing the eigenvalues of the matrix being constructed, with `eigval[i]` the eigenvalue associated with column `i` of `eigvec`. """ super().__init__(array.shape, _array=array) if isinstance(eigvec, np.ndarray): eigvec = OrthogonalMatrix(eigvec) self._eigvec = eigvec self._eigval = eigval
[ "def", "__init__", "(", "self", ",", "array", ",", "eigvec", "=", "None", ",", "eigval", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "array", ".", "shape", ",", "_array", "=", "array", ")", "if", "isinstance", "(", "eigvec", ",", "np", ".", "ndarray", ")", ":", "eigvec", "=", "OrthogonalMatrix", "(", "eigvec", ")", "self", ".", "_eigvec", "=", "eigvec", "self", ".", "_eigval", "=", "eigval" ]
https://github.com/matt-graham/mici/blob/aa209e2cf698bb9e0c7c733d7b6a5557ab5df190/mici/matrices.py#L1319-L1337
Ultimaker/Uranium
66da853cd9a04edd3a8a03526fac81e83c03f5aa
UM/Qt/ListModel.py
python
ListModel.data
(self, index, role)
return self._items[index.row()][self._role_names[role].decode("utf-8")]
Reimplemented from QAbstractListModel
Reimplemented from QAbstractListModel
[ "Reimplemented", "from", "QAbstractListModel" ]
def data(self, index, role): """Reimplemented from QAbstractListModel""" if not index.isValid(): return QVariant() return self._items[index.row()][self._role_names[role].decode("utf-8")]
[ "def", "data", "(", "self", ",", "index", ",", "role", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "QVariant", "(", ")", "return", "self", ".", "_items", "[", "index", ".", "row", "(", ")", "]", "[", "self", ".", "_role_names", "[", "role", "]", ".", "decode", "(", "\"utf-8\"", ")", "]" ]
https://github.com/Ultimaker/Uranium/blob/66da853cd9a04edd3a8a03526fac81e83c03f5aa/UM/Qt/ListModel.py#L48-L53
gnome-terminator/terminator
ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1
terminatorlib/ipc.py
python
new_window
(session, options)
Call the dbus method to open a new window
Call the dbus method to open a new window
[ "Call", "the", "dbus", "method", "to", "open", "a", "new", "window" ]
def new_window(session, options): """Call the dbus method to open a new window""" print(session.new_window())
[ "def", "new_window", "(", "session", ",", "options", ")", ":", "print", "(", "session", ".", "new_window", "(", ")", ")" ]
https://github.com/gnome-terminator/terminator/blob/ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1/terminatorlib/ipc.py#L351-L353
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/xml/sax/xmlreader.py
python
IncrementalParser.close
(self)
This method is called when the entire XML document has been passed to the parser through the feed method, to notify the parser that there are no more data. This allows the parser to do the final checks on the document and empty the internal data buffer. The parser will not be ready to parse another document until the reset method has been called. close may raise SAXException.
This method is called when the entire XML document has been passed to the parser through the feed method, to notify the parser that there are no more data. This allows the parser to do the final checks on the document and empty the internal data buffer.
[ "This", "method", "is", "called", "when", "the", "entire", "XML", "document", "has", "been", "passed", "to", "the", "parser", "through", "the", "feed", "method", "to", "notify", "the", "parser", "that", "there", "are", "no", "more", "data", ".", "This", "allows", "the", "parser", "to", "do", "the", "final", "checks", "on", "the", "document", "and", "empty", "the", "internal", "data", "buffer", "." ]
def close(self): """This method is called when the entire XML document has been passed to the parser through the feed method, to notify the parser that there are no more data. This allows the parser to do the final checks on the document and empty the internal data buffer. The parser will not be ready to parse another document until the reset method has been called. close may raise SAXException.""" raise NotImplementedError("This method must be implemented!")
[ "def", "close", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"This method must be implemented!\"", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/xml/sax/xmlreader.py#L141-L152
aimi-cn/AILearners
5aec29a13fbb145a7a55e41ceedb5b42f5bbb1a0
src/py2.x/ml/jqxxsz/2.KNN/KNN.py
python
createDataSet
()
return group, labels
创建数据集和标签 调用方式 import kNN group, labels = kNN.createDataSet()
创建数据集和标签 调用方式 import kNN group, labels = kNN.createDataSet()
[ "创建数据集和标签", "调用方式", "import", "kNN", "group", "labels", "=", "kNN", ".", "createDataSet", "()" ]
def createDataSet(): """ 创建数据集和标签 调用方式 import kNN group, labels = kNN.createDataSet() """ group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]]) labels = ['A','A','B','B'] return group, labels
[ "def", "createDataSet", "(", ")", ":", "group", "=", "array", "(", "[", "[", "1.0", ",", "1.1", "]", ",", "[", "1.0", ",", "1.0", "]", ",", "[", "0", ",", "0", "]", ",", "[", "0", ",", "0.1", "]", "]", ")", "labels", "=", "[", "'A'", ",", "'A'", ",", "'B'", ",", "'B'", "]", "return", "group", ",", "labels" ]
https://github.com/aimi-cn/AILearners/blob/5aec29a13fbb145a7a55e41ceedb5b42f5bbb1a0/src/py2.x/ml/jqxxsz/2.KNN/KNN.py#L25-L34
matthew-brett/transforms3d
f185e866ecccb66c545559bc9f2e19cb5025e0ab
transforms3d/_gohlketransforms.py
python
quaternion_slerp
(quat0, quat1, fraction, spin=0, shortestpath=True)
return q0
Return spherical linear interpolation between two quaternions. >>> q0 = random_quaternion() >>> q1 = random_quaternion() >>> q = quaternion_slerp(q0, q1, 0) >>> numpy.allclose(q, q0) True >>> q = quaternion_slerp(q0, q1, 1, 1) >>> numpy.allclose(q, q1) True >>> q = quaternion_slerp(q0, q1, 0.5) >>> angle = math.acos(numpy.dot(q0, q)) >>> numpy.allclose(2, math.acos(numpy.dot(q0, q1)) / angle) or \ numpy.allclose(2, math.acos(-numpy.dot(q0, q1)) / angle) True
Return spherical linear interpolation between two quaternions.
[ "Return", "spherical", "linear", "interpolation", "between", "two", "quaternions", "." ]
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True): """Return spherical linear interpolation between two quaternions. >>> q0 = random_quaternion() >>> q1 = random_quaternion() >>> q = quaternion_slerp(q0, q1, 0) >>> numpy.allclose(q, q0) True >>> q = quaternion_slerp(q0, q1, 1, 1) >>> numpy.allclose(q, q1) True >>> q = quaternion_slerp(q0, q1, 0.5) >>> angle = math.acos(numpy.dot(q0, q)) >>> numpy.allclose(2, math.acos(numpy.dot(q0, q1)) / angle) or \ numpy.allclose(2, math.acos(-numpy.dot(q0, q1)) / angle) True """ q0 = unit_vector(quat0[:4]) q1 = unit_vector(quat1[:4]) if fraction == 0.0: return q0 elif fraction == 1.0: return q1 d = numpy.dot(q0, q1) if abs(abs(d) - 1.0) < _EPS: return q0 if shortestpath and d < 0.0: # invert rotation d = -d numpy.negative(q1, q1) angle = math.acos(d) + spin * math.pi if abs(angle) < _EPS: return q0 isin = 1.0 / math.sin(angle) q0 *= math.sin((1.0 - fraction) * angle) * isin q1 *= math.sin(fraction * angle) * isin q0 += q1 return q0
[ "def", "quaternion_slerp", "(", "quat0", ",", "quat1", ",", "fraction", ",", "spin", "=", "0", ",", "shortestpath", "=", "True", ")", ":", "q0", "=", "unit_vector", "(", "quat0", "[", ":", "4", "]", ")", "q1", "=", "unit_vector", "(", "quat1", "[", ":", "4", "]", ")", "if", "fraction", "==", "0.0", ":", "return", "q0", "elif", "fraction", "==", "1.0", ":", "return", "q1", "d", "=", "numpy", ".", "dot", "(", "q0", ",", "q1", ")", "if", "abs", "(", "abs", "(", "d", ")", "-", "1.0", ")", "<", "_EPS", ":", "return", "q0", "if", "shortestpath", "and", "d", "<", "0.0", ":", "# invert rotation", "d", "=", "-", "d", "numpy", ".", "negative", "(", "q1", ",", "q1", ")", "angle", "=", "math", ".", "acos", "(", "d", ")", "+", "spin", "*", "math", ".", "pi", "if", "abs", "(", "angle", ")", "<", "_EPS", ":", "return", "q0", "isin", "=", "1.0", "/", "math", ".", "sin", "(", "angle", ")", "q0", "*=", "math", ".", "sin", "(", "(", "1.0", "-", "fraction", ")", "*", "angle", ")", "*", "isin", "q1", "*=", "math", ".", "sin", "(", "fraction", "*", "angle", ")", "*", "isin", "q0", "+=", "q1", "return", "q0" ]
https://github.com/matthew-brett/transforms3d/blob/f185e866ecccb66c545559bc9f2e19cb5025e0ab/transforms3d/_gohlketransforms.py#L1436-L1474
MDAnalysis/mdanalysis
3488df3cdb0c29ed41c4fb94efe334b541e31b21
package/MDAnalysis/lib/picklable_file_io.py
python
gzip_pickle_open
(name, mode='rb')
Open a gzip-compressed file in binary or text mode with pickle function implemented. This function returns a GzipPicklable object when given the "rb" or "r" reading mode, or a GzipPicklable object wrapped in a TextIOPicklable class with the "rt" reading mode. It can be used as a context manager, and replace the built-in :func:`gzip.open` function in read mode that only returns an unpicklable file object. Note ---- Can be only used with read mode. Parameters ---------- name : str either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened. mode: {'r', 'rt', 'rb'} (optional) 'r': open for reading in binary mode; 'rt': read in text mode; 'rb': read in binary mode; (default) Returns ------- stream-like object: GzipPicklable or TextIOPicklable when mode is 'rt', returns TextIOPicklable; when mode is 'r' or 'rb', returns GzipPicklable Raises ------ ValueError if `mode` is not one of the allowed read modes Examples ------- open as context manager:: with gzip_pickle_open('filename') as f: line = f.readline() open as function:: f = gzip_pickle_open('filename') line = f.readline() f.close() See Also -------- :func:`io.open` :func:`gzip.open` :func:`MDAnalysis.lib.util.anyopen` :func:`MDAnalysis.lib.picklable_file_io.pickle_open` :func:`MDAnalysis.lib.picklable_file_io.bz2_pickle_open` .. versionadded:: 2.0.0
Open a gzip-compressed file in binary or text mode with pickle function implemented.
[ "Open", "a", "gzip", "-", "compressed", "file", "in", "binary", "or", "text", "mode", "with", "pickle", "function", "implemented", "." ]
def gzip_pickle_open(name, mode='rb'): """Open a gzip-compressed file in binary or text mode with pickle function implemented. This function returns a GzipPicklable object when given the "rb" or "r" reading mode, or a GzipPicklable object wrapped in a TextIOPicklable class with the "rt" reading mode. It can be used as a context manager, and replace the built-in :func:`gzip.open` function in read mode that only returns an unpicklable file object. Note ---- Can be only used with read mode. Parameters ---------- name : str either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened. mode: {'r', 'rt', 'rb'} (optional) 'r': open for reading in binary mode; 'rt': read in text mode; 'rb': read in binary mode; (default) Returns ------- stream-like object: GzipPicklable or TextIOPicklable when mode is 'rt', returns TextIOPicklable; when mode is 'r' or 'rb', returns GzipPicklable Raises ------ ValueError if `mode` is not one of the allowed read modes Examples ------- open as context manager:: with gzip_pickle_open('filename') as f: line = f.readline() open as function:: f = gzip_pickle_open('filename') line = f.readline() f.close() See Also -------- :func:`io.open` :func:`gzip.open` :func:`MDAnalysis.lib.util.anyopen` :func:`MDAnalysis.lib.picklable_file_io.pickle_open` :func:`MDAnalysis.lib.picklable_file_io.bz2_pickle_open` .. versionadded:: 2.0.0 """ if mode not in {'r', 'rt', 'rb'}: raise ValueError("Only read mode ('r', 'rt', 'rb') " "files can be pickled.") gz_mode = mode.replace("t", "") binary_file = GzipPicklable(name, gz_mode) if "t" in mode: return TextIOPicklable(binary_file) else: return binary_file
[ "def", "gzip_pickle_open", "(", "name", ",", "mode", "=", "'rb'", ")", ":", "if", "mode", "not", "in", "{", "'r'", ",", "'rt'", ",", "'rb'", "}", ":", "raise", "ValueError", "(", "\"Only read mode ('r', 'rt', 'rb') \"", "\"files can be pickled.\"", ")", "gz_mode", "=", "mode", ".", "replace", "(", "\"t\"", ",", "\"\"", ")", "binary_file", "=", "GzipPicklable", "(", "name", ",", "gz_mode", ")", "if", "\"t\"", "in", "mode", ":", "return", "TextIOPicklable", "(", "binary_file", ")", "else", ":", "return", "binary_file" ]
https://github.com/MDAnalysis/mdanalysis/blob/3488df3cdb0c29ed41c4fb94efe334b541e31b21/package/MDAnalysis/lib/picklable_file_io.py#L485-L554
openai/safety-gym
f31042f2f9ee61b9034dd6a416955972911544f5
safety_gym/envs/engine.py
python
Engine.build_goal_button
(self)
Pick a new goal button, maybe with resampling due to hazards
Pick a new goal button, maybe with resampling due to hazards
[ "Pick", "a", "new", "goal", "button", "maybe", "with", "resampling", "due", "to", "hazards" ]
def build_goal_button(self): ''' Pick a new goal button, maybe with resampling due to hazards ''' self.goal_button = self.rs.choice(self.buttons_num)
[ "def", "build_goal_button", "(", "self", ")", ":", "self", ".", "goal_button", "=", "self", ".", "rs", ".", "choice", "(", "self", ".", "buttons_num", ")" ]
https://github.com/openai/safety-gym/blob/f31042f2f9ee61b9034dd6a416955972911544f5/safety_gym/envs/engine.py#L842-L844
mcfletch/pyopengl
02d11dad9ff18e50db10e975c4756e17bf198464
OpenGL/GL/NV/conservative_raster.py
python
glInitConservativeRasterNV
()
return extensions.hasGLExtension( _EXTENSION_NAME )
Return boolean indicating whether this extension is available
Return boolean indicating whether this extension is available
[ "Return", "boolean", "indicating", "whether", "this", "extension", "is", "available" ]
def glInitConservativeRasterNV(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
[ "def", "glInitConservativeRasterNV", "(", ")", ":", "from", "OpenGL", "import", "extensions", "return", "extensions", ".", "hasGLExtension", "(", "_EXTENSION_NAME", ")" ]
https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/GL/NV/conservative_raster.py#L36-L39
openstack/manila
142990edc027e14839d5deaf4954dd6fc88de15e
manila/share_group/api.py
python
API.delete_share_group_snapshot
(self, context, snap)
Delete share group snapshot.
Delete share group snapshot.
[ "Delete", "share", "group", "snapshot", "." ]
def delete_share_group_snapshot(self, context, snap): """Delete share group snapshot.""" snap_id = snap['id'] statuses = (constants.STATUS_AVAILABLE, constants.STATUS_ERROR) share_group = self.db.share_group_get(context, snap['share_group_id']) if not snap['status'] in statuses: msg = (_("Share group snapshot status must be one of" " %(statuses)s") % {"statuses": statuses}) raise exception.InvalidShareGroupSnapshot(reason=msg) self.db.share_group_snapshot_update( context, snap_id, {'status': constants.STATUS_DELETING}) try: reservations = QUOTAS.reserve( context, share_group_snapshots=-1, project_id=snap['project_id'], user_id=snap['user_id'], ) except exception.OverQuota as e: reservations = None LOG.exception( ("Failed to update quota for deleting share group snapshot: " "%s"), e) # Cast to share manager self.share_rpcapi.delete_share_group_snapshot( context, snap, share_group['host']) if reservations: QUOTAS.commit( context, reservations, project_id=snap['project_id'], user_id=snap['user_id'], )
[ "def", "delete_share_group_snapshot", "(", "self", ",", "context", ",", "snap", ")", ":", "snap_id", "=", "snap", "[", "'id'", "]", "statuses", "=", "(", "constants", ".", "STATUS_AVAILABLE", ",", "constants", ".", "STATUS_ERROR", ")", "share_group", "=", "self", ".", "db", ".", "share_group_get", "(", "context", ",", "snap", "[", "'share_group_id'", "]", ")", "if", "not", "snap", "[", "'status'", "]", "in", "statuses", ":", "msg", "=", "(", "_", "(", "\"Share group snapshot status must be one of\"", "\" %(statuses)s\"", ")", "%", "{", "\"statuses\"", ":", "statuses", "}", ")", "raise", "exception", ".", "InvalidShareGroupSnapshot", "(", "reason", "=", "msg", ")", "self", ".", "db", ".", "share_group_snapshot_update", "(", "context", ",", "snap_id", ",", "{", "'status'", ":", "constants", ".", "STATUS_DELETING", "}", ")", "try", ":", "reservations", "=", "QUOTAS", ".", "reserve", "(", "context", ",", "share_group_snapshots", "=", "-", "1", ",", "project_id", "=", "snap", "[", "'project_id'", "]", ",", "user_id", "=", "snap", "[", "'user_id'", "]", ",", ")", "except", "exception", ".", "OverQuota", "as", "e", ":", "reservations", "=", "None", "LOG", ".", "exception", "(", "(", "\"Failed to update quota for deleting share group snapshot: \"", "\"%s\"", ")", ",", "e", ")", "# Cast to share manager", "self", ".", "share_rpcapi", ".", "delete_share_group_snapshot", "(", "context", ",", "snap", ",", "share_group", "[", "'host'", "]", ")", "if", "reservations", ":", "QUOTAS", ".", "commit", "(", "context", ",", "reservations", ",", "project_id", "=", "snap", "[", "'project_id'", "]", ",", "user_id", "=", "snap", "[", "'user_id'", "]", ",", ")" ]
https://github.com/openstack/manila/blob/142990edc027e14839d5deaf4954dd6fc88de15e/manila/share_group/api.py#L441-L476
huhamhire/huhamhire-hosts
33b9c49e7a4045b00e0c0df06f25e9ce8a037761
gui/qdialog_ui.py
python
QDialogUI.set_func_list
(self, new=0)
Draw the function list and decide whether to load the default selection configuration or not. :param new: A flag indicating whether to load the default selection configuration or not. Default value is `0`. === =================== new Operation === =================== 0 Use user config. 1 Use default config. === =================== :type new: int
Draw the function list and decide whether to load the default selection configuration or not.
[ "Draw", "the", "function", "list", "and", "decide", "whether", "to", "load", "the", "default", "selection", "configuration", "or", "not", "." ]
def set_func_list(self, new=0): """ Draw the function list and decide whether to load the default selection configuration or not. :param new: A flag indicating whether to load the default selection configuration or not. Default value is `0`. === =================== new Operation === =================== 0 Use user config. 1 Use default config. === =================== :type new: int """ self.ui.Functionlist.clear() self.ui.FunctionsBox.setTitle(_translate( "Util", "Functions", None)) if new: for ip in range(2): choice, defaults, slices = RetrieveData.get_choice(ip) if os.path.isfile(self.custom): choice.insert(0, [4, 1, 0, "customize"]) defaults[0x04] = [1] for i in range(len(slices)): slices[i] += 1 slices.insert(0, 0) self.choice[ip] = choice self.slices[ip] = slices funcs = [] for func in choice: if func[1] in defaults[func[0]]: funcs.append(1) else: funcs.append(0) self._funcs[ip] = funcs
[ "def", "set_func_list", "(", "self", ",", "new", "=", "0", ")", ":", "self", ".", "ui", ".", "Functionlist", ".", "clear", "(", ")", "self", ".", "ui", ".", "FunctionsBox", ".", "setTitle", "(", "_translate", "(", "\"Util\"", ",", "\"Functions\"", ",", "None", ")", ")", "if", "new", ":", "for", "ip", "in", "range", "(", "2", ")", ":", "choice", ",", "defaults", ",", "slices", "=", "RetrieveData", ".", "get_choice", "(", "ip", ")", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "custom", ")", ":", "choice", ".", "insert", "(", "0", ",", "[", "4", ",", "1", ",", "0", ",", "\"customize\"", "]", ")", "defaults", "[", "0x04", "]", "=", "[", "1", "]", "for", "i", "in", "range", "(", "len", "(", "slices", ")", ")", ":", "slices", "[", "i", "]", "+=", "1", "slices", ".", "insert", "(", "0", ",", "0", ")", "self", ".", "choice", "[", "ip", "]", "=", "choice", "self", ".", "slices", "[", "ip", "]", "=", "slices", "funcs", "=", "[", "]", "for", "func", "in", "choice", ":", "if", "func", "[", "1", "]", "in", "defaults", "[", "func", "[", "0", "]", "]", ":", "funcs", ".", "append", "(", "1", ")", "else", ":", "funcs", ".", "append", "(", "0", ")", "self", ".", "_funcs", "[", "ip", "]", "=", "funcs" ]
https://github.com/huhamhire/huhamhire-hosts/blob/33b9c49e7a4045b00e0c0df06f25e9ce8a037761/gui/qdialog_ui.py#L247-L283
LuxCoreRender/BlendLuxCore
bf31ca58501d54c02acd97001b6db7de81da7cbf
ui/view_layer.py
python
LUXCORE_VIEWLAYER_PT_layer.draw
(self, context)
[]
def draw(self, context): layout = self.layout layout.use_property_split = True flow = layout.grid_flow(row_major=True, columns=0, even_columns=True, even_rows=False, align=False) layout.use_property_split = True scene = context.scene rd = scene.render layer = context.view_layer col = flow.column() col.prop(layer, "use", text="Use for Rendering") col = flow.column() col.prop(rd, "use_single_layer", text="Render Single Layer")
[ "def", "draw", "(", "self", ",", "context", ")", ":", "layout", "=", "self", ".", "layout", "layout", ".", "use_property_split", "=", "True", "flow", "=", "layout", ".", "grid_flow", "(", "row_major", "=", "True", ",", "columns", "=", "0", ",", "even_columns", "=", "True", ",", "even_rows", "=", "False", ",", "align", "=", "False", ")", "layout", ".", "use_property_split", "=", "True", "scene", "=", "context", ".", "scene", "rd", "=", "scene", ".", "render", "layer", "=", "context", ".", "view_layer", "col", "=", "flow", ".", "column", "(", ")", "col", ".", "prop", "(", "layer", ",", "\"use\"", ",", "text", "=", "\"Use for Rendering\"", ")", "col", "=", "flow", ".", "column", "(", ")", "col", ".", "prop", "(", "rd", ",", "\"use_single_layer\"", ",", "text", "=", "\"Render Single Layer\"", ")" ]
https://github.com/LuxCoreRender/BlendLuxCore/blob/bf31ca58501d54c02acd97001b6db7de81da7cbf/ui/view_layer.py#L12-L28
ritiek/spotify-downloader
28ca1614bb2567ce01dd31ad946e5b30a54398ea
spotdl/metadata/provider_base.py
python
StreamsBase.getworst
(self)
return self.streams[-1]
Returns the audio stream with the lowest bitrate.
Returns the audio stream with the lowest bitrate.
[ "Returns", "the", "audio", "stream", "with", "the", "lowest", "bitrate", "." ]
def getworst(self): """ Returns the audio stream with the lowest bitrate. """ return self.streams[-1]
[ "def", "getworst", "(", "self", ")", ":", "return", "self", ".", "streams", "[", "-", "1", "]" ]
https://github.com/ritiek/spotify-downloader/blob/28ca1614bb2567ce01dd31ad946e5b30a54398ea/spotdl/metadata/provider_base.py#L40-L45
tensorflow/kfac
fe90e36c3e0b42c73e4a34835a66f6d45e2a442d
kfac/python/keras/utils.py
python
_get_verified_dict
(container, container_name, layer_names)
Verifies that loss_weights/fisher_approx conform to their specs.
Verifies that loss_weights/fisher_approx conform to their specs.
[ "Verifies", "that", "loss_weights", "/", "fisher_approx", "conform", "to", "their", "specs", "." ]
def _get_verified_dict(container, container_name, layer_names): """Verifies that loss_weights/fisher_approx conform to their specs.""" if container is None or container == {}: # pylint: disable=g-explicit-bool-comparison # The explicit comparison prevents empty lists from passing. return {} elif isinstance(container, dict): string_keys = { str(k) for k in container if isinstance(k, six.string_types) and not k.startswith(_CLASS_NAME_PREFIX) } if string_keys - set(layer_names): raise ValueError('There is a {} without a matching layer' .format(container_name)) return container elif isinstance(container, list): if len(layer_names) != len(container): raise ValueError('Number of {} and layers don\'t match.' .format(container_name)) return dict(zip(layer_names, container)) else: raise ValueError('{} must be a list or dict'.format(container_name))
[ "def", "_get_verified_dict", "(", "container", ",", "container_name", ",", "layer_names", ")", ":", "if", "container", "is", "None", "or", "container", "==", "{", "}", ":", "# pylint: disable=g-explicit-bool-comparison", "# The explicit comparison prevents empty lists from passing.", "return", "{", "}", "elif", "isinstance", "(", "container", ",", "dict", ")", ":", "string_keys", "=", "{", "str", "(", "k", ")", "for", "k", "in", "container", "if", "isinstance", "(", "k", ",", "six", ".", "string_types", ")", "and", "not", "k", ".", "startswith", "(", "_CLASS_NAME_PREFIX", ")", "}", "if", "string_keys", "-", "set", "(", "layer_names", ")", ":", "raise", "ValueError", "(", "'There is a {} without a matching layer'", ".", "format", "(", "container_name", ")", ")", "return", "container", "elif", "isinstance", "(", "container", ",", "list", ")", ":", "if", "len", "(", "layer_names", ")", "!=", "len", "(", "container", ")", ":", "raise", "ValueError", "(", "'Number of {} and layers don\\'t match.'", ".", "format", "(", "container_name", ")", ")", "return", "dict", "(", "zip", "(", "layer_names", ",", "container", ")", ")", "else", ":", "raise", "ValueError", "(", "'{} must be a list or dict'", ".", "format", "(", "container_name", ")", ")" ]
https://github.com/tensorflow/kfac/blob/fe90e36c3e0b42c73e4a34835a66f6d45e2a442d/kfac/python/keras/utils.py#L96-L116
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/alerts/alerttools.py
python
testAchievableVisualOnsetOffset
(component)
Test whether start and end times are less than 1 screen refresh.
Test whether start and end times are less than 1 screen refresh.
[ "Test", "whether", "start", "and", "end", "times", "are", "less", "than", "1", "screen", "refresh", "." ]
def testAchievableVisualOnsetOffset(component): """Test whether start and end times are less than 1 screen refresh. """ if component.type not in ["Text", "Aperture", "Dots", "EnvGrating", "Form", "Grating", "Image", "Movie", "NoiseStim", "Polygon"]: return if "startType" not in component.params or "stopType" not in component.params: return startVal = component.params['startVal'].val stopVal = component.params['stopVal'].val if testFloat(startVal): if component.params['startType'] == "time (s)": # Test times are greater than 1 screen refresh for 60Hz and 100Hz monitors if not float.is_integer(float(startVal)) and float(startVal) < 1.0 / 60: alert(3110, component, {'type': 'start', 'time': startVal, 'Hz': 60}) if not float.is_integer(float(startVal)) and float(startVal) < 1.0 / 100: alert(3110, component, {'type': 'start', 'time': startVal, 'Hz': 100}) if testFloat(stopVal): if component.params['stopType'] == "duration (s)": # Test times are greater than 1 screen refresh for 60Hz and 100Hz monitors if not float.is_integer(float(stopVal)) and float(stopVal) < 1.0 / 60: alert(3110, component, {'type': 'stop', 'time': stopVal, 'Hz': 60}) if not float.is_integer(float(stopVal)) and float(stopVal) < 1.0 / 100: alert(3110, component, {'type': 'stop', 'time': stopVal, 'Hz': 100})
[ "def", "testAchievableVisualOnsetOffset", "(", "component", ")", ":", "if", "component", ".", "type", "not", "in", "[", "\"Text\"", ",", "\"Aperture\"", ",", "\"Dots\"", ",", "\"EnvGrating\"", ",", "\"Form\"", ",", "\"Grating\"", ",", "\"Image\"", ",", "\"Movie\"", ",", "\"NoiseStim\"", ",", "\"Polygon\"", "]", ":", "return", "if", "\"startType\"", "not", "in", "component", ".", "params", "or", "\"stopType\"", "not", "in", "component", ".", "params", ":", "return", "startVal", "=", "component", ".", "params", "[", "'startVal'", "]", ".", "val", "stopVal", "=", "component", ".", "params", "[", "'stopVal'", "]", ".", "val", "if", "testFloat", "(", "startVal", ")", ":", "if", "component", ".", "params", "[", "'startType'", "]", "==", "\"time (s)\"", ":", "# Test times are greater than 1 screen refresh for 60Hz and 100Hz monitors", "if", "not", "float", ".", "is_integer", "(", "float", "(", "startVal", ")", ")", "and", "float", "(", "startVal", ")", "<", "1.0", "/", "60", ":", "alert", "(", "3110", ",", "component", ",", "{", "'type'", ":", "'start'", ",", "'time'", ":", "startVal", ",", "'Hz'", ":", "60", "}", ")", "if", "not", "float", ".", "is_integer", "(", "float", "(", "startVal", ")", ")", "and", "float", "(", "startVal", ")", "<", "1.0", "/", "100", ":", "alert", "(", "3110", ",", "component", ",", "{", "'type'", ":", "'start'", ",", "'time'", ":", "startVal", ",", "'Hz'", ":", "100", "}", ")", "if", "testFloat", "(", "stopVal", ")", ":", "if", "component", ".", "params", "[", "'stopType'", "]", "==", "\"duration (s)\"", ":", "# Test times are greater than 1 screen refresh for 60Hz and 100Hz monitors", "if", "not", "float", ".", "is_integer", "(", "float", "(", "stopVal", ")", ")", "and", "float", "(", "stopVal", ")", "<", "1.0", "/", "60", ":", "alert", "(", "3110", ",", "component", ",", "{", "'type'", ":", "'stop'", ",", "'time'", ":", "stopVal", ",", "'Hz'", ":", "60", "}", ")", "if", "not", "float", ".", "is_integer", "(", "float", "(", "stopVal", ")", ")", "and", "float", "(", "stopVal", ")", "<", "1.0", "/", "100", ":", "alert", "(", "3110", ",", "component", ",", "{", "'type'", ":", "'stop'", ",", "'time'", ":", "stopVal", ",", "'Hz'", ":", "100", "}", ")" ]
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/alerts/alerttools.py#L170-L198
carnal0wnage/weirdAAL
c14e36d7bb82447f38a43da203f4bc29429f4cf4
libs/aws/brute.py
python
brute_iot_permissions
()
return generic_permission_bruteforcer('iot', tests)
http://boto3.readthedocs.io/en/latest/reference/services/iot.html
http://boto3.readthedocs.io/en/latest/reference/services/iot.html
[ "http", ":", "//", "boto3", ".", "readthedocs", ".", "io", "/", "en", "/", "latest", "/", "reference", "/", "services", "/", "iot", ".", "html" ]
def brute_iot_permissions(): ''' http://boto3.readthedocs.io/en/latest/reference/services/iot.html ''' print("### Enumerating IoT Permissions ###") tests = [('ListThings', 'list_things', (), {}), ('ListPolicies', 'list_policies', (), {}), ('ListCertificates', 'list_certificates', (), {}), ] return generic_permission_bruteforcer('iot', tests)
[ "def", "brute_iot_permissions", "(", ")", ":", "print", "(", "\"### Enumerating IoT Permissions ###\"", ")", "tests", "=", "[", "(", "'ListThings'", ",", "'list_things'", ",", "(", ")", ",", "{", "}", ")", ",", "(", "'ListPolicies'", ",", "'list_policies'", ",", "(", ")", ",", "{", "}", ")", ",", "(", "'ListCertificates'", ",", "'list_certificates'", ",", "(", ")", ",", "{", "}", ")", ",", "]", "return", "generic_permission_bruteforcer", "(", "'iot'", ",", "tests", ")" ]
https://github.com/carnal0wnage/weirdAAL/blob/c14e36d7bb82447f38a43da203f4bc29429f4cf4/libs/aws/brute.py#L1316-L1324
zhengxiaotian/geek_crawler
40ef4b0ccb4d8fa27dcff394c73baffc485e52aa
geek_crawler.py
python
Cookie.list_to_dict
(lis)
return result
列表转换成字典的方法 Args: lis: 列表内容 Returns: 转换后的字典
列表转换成字典的方法 Args: lis: 列表内容 Returns: 转换后的字典
[ "列表转换成字典的方法", "Args", ":", "lis", ":", "列表内容", "Returns", ":", "转换后的字典" ]
def list_to_dict(lis): """ 列表转换成字典的方法 Args: lis: 列表内容 Returns: 转换后的字典 """ result = {} for ind in lis: try: ind = ind.split('=') result[ind[0]] = ind[1] except IndexError: continue return result
[ "def", "list_to_dict", "(", "lis", ")", ":", "result", "=", "{", "}", "for", "ind", "in", "lis", ":", "try", ":", "ind", "=", "ind", ".", "split", "(", "'='", ")", "result", "[", "ind", "[", "0", "]", "]", "=", "ind", "[", "1", "]", "except", "IndexError", ":", "continue", "return", "result" ]
https://github.com/zhengxiaotian/geek_crawler/blob/40ef4b0ccb4d8fa27dcff394c73baffc485e52aa/geek_crawler.py#L108-L123
morganstanley/treadmill
f18267c665baf6def4374d21170198f63ff1cde4
lib/python/treadmill/cron/__init__.py
python
create_job
(scheduler, job_id, job_name, func, func_kwargs, trigger_args)
return job
Create a new job/model.
Create a new job/model.
[ "Create", "a", "new", "job", "/", "model", "." ]
def create_job(scheduler, job_id, job_name, func, func_kwargs, trigger_args): """Create a new job/model. """ _LOGGER.debug( 'job_id: %s, job_name: %s, func: %s, func_kwargs: %r, trigger_args: ' '%r', job_id, job_name, func, func_kwargs, trigger_args ) job = get_job(scheduler, job_id) if job: raise exc.FoundError('{} already exists'.format(job_id)) _LOGGER.info('Adding job %s', job_id) try: job = scheduler.add_job( func, trigger='cron', id=job_id, name=job_name, misfire_grace_time=ONE_DAY_IN_SECS, kwargs=func_kwargs, **trigger_args ) except ValueError as err: raise exc.InvalidInputError( __name__, str(err), ) return job
[ "def", "create_job", "(", "scheduler", ",", "job_id", ",", "job_name", ",", "func", ",", "func_kwargs", ",", "trigger_args", ")", ":", "_LOGGER", ".", "debug", "(", "'job_id: %s, job_name: %s, func: %s, func_kwargs: %r, trigger_args: '", "'%r'", ",", "job_id", ",", "job_name", ",", "func", ",", "func_kwargs", ",", "trigger_args", ")", "job", "=", "get_job", "(", "scheduler", ",", "job_id", ")", "if", "job", ":", "raise", "exc", ".", "FoundError", "(", "'{} already exists'", ".", "format", "(", "job_id", ")", ")", "_LOGGER", ".", "info", "(", "'Adding job %s'", ",", "job_id", ")", "try", ":", "job", "=", "scheduler", ".", "add_job", "(", "func", ",", "trigger", "=", "'cron'", ",", "id", "=", "job_id", ",", "name", "=", "job_name", ",", "misfire_grace_time", "=", "ONE_DAY_IN_SECS", ",", "kwargs", "=", "func_kwargs", ",", "*", "*", "trigger_args", ")", "except", "ValueError", "as", "err", ":", "raise", "exc", ".", "InvalidInputError", "(", "__name__", ",", "str", "(", "err", ")", ",", ")", "return", "job" ]
https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/cron/__init__.py#L132-L161
fictorial/pygameui
af6a35f347d6fafa66c4255bbbe38736d842ff65
pygameui/view.py
python
View.size_to_fit
(self)
[]
def size_to_fit(self): rect = self.frame for child in self.children: rect = rect.union(child.frame) self.frame = rect self.layout()
[ "def", "size_to_fit", "(", "self", ")", ":", "rect", "=", "self", ".", "frame", "for", "child", "in", "self", ".", "children", ":", "rect", "=", "rect", ".", "union", "(", "child", ".", "frame", ")", "self", ".", "frame", "=", "rect", "self", ".", "layout", "(", ")" ]
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L93-L98
web2py/web2py
095905c4e010a1426c729483d912e270a51b7ba8
scripts/extract_oracle_models.py
python
define_table
(conn, table)
Output single table definition
Output single table definition
[ "Output", "single", "table", "definition" ]
def define_table(conn, table): "Output single table definition" fields = get_fields(conn, table) pks = primarykeys(conn, table) print "db.define_table('%s'," % (table, ) for field in fields: fname = field['COLUMN_NAME'] fdef = define_field(conn, table, field, pks) if fname not in pks and is_unique(conn, table, field): fdef['unique'] = "True" if fdef['type'] == "'id'" and fname in pks: pks.pop(pks.index(fname)) print " Field('%s', %s)," % (fname, ', '.join(["%s=%s" % (k, fdef[k]) for k in KWARGS if k in fdef and fdef[k]])) if pks: print " primarykey=[%s]," % ", ".join(["'%s'" % pk for pk in pks]) print " migrate=migrate)" print
[ "def", "define_table", "(", "conn", ",", "table", ")", ":", "fields", "=", "get_fields", "(", "conn", ",", "table", ")", "pks", "=", "primarykeys", "(", "conn", ",", "table", ")", "print", "\"db.define_table('%s',\"", "%", "(", "table", ",", ")", "for", "field", "in", "fields", ":", "fname", "=", "field", "[", "'COLUMN_NAME'", "]", "fdef", "=", "define_field", "(", "conn", ",", "table", ",", "field", ",", "pks", ")", "if", "fname", "not", "in", "pks", "and", "is_unique", "(", "conn", ",", "table", ",", "field", ")", ":", "fdef", "[", "'unique'", "]", "=", "\"True\"", "if", "fdef", "[", "'type'", "]", "==", "\"'id'\"", "and", "fname", "in", "pks", ":", "pks", ".", "pop", "(", "pks", ".", "index", "(", "fname", ")", ")", "print", "\" Field('%s', %s),\"", "%", "(", "fname", ",", "', '", ".", "join", "(", "[", "\"%s=%s\"", "%", "(", "k", ",", "fdef", "[", "k", "]", ")", "for", "k", "in", "KWARGS", "if", "k", "in", "fdef", "and", "fdef", "[", "k", "]", "]", ")", ")", "if", "pks", ":", "print", "\" primarykey=[%s],\"", "%", "\", \"", ".", "join", "(", "[", "\"'%s'\"", "%", "pk", "for", "pk", "in", "pks", "]", ")", "print", "\" migrate=migrate)\"", "print" ]
https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/scripts/extract_oracle_models.py#L268-L286
AI-ON/Multitask-and-Transfer-Learning
31e0798d436e314ddbc64c4a6b935df1b2160e50
architectures/chainer/models/predictive_autoencoder.py
python
Classifier.__init__
(self, predictor, weight=0.75)
[]
def __init__(self, predictor, weight=0.75): super(Classifier, self).__init__() with self.init_scope(): self.predictor = predictor self.weight = float(weight) self.y_image = None self.y_action = None self.image_mask = None
[ "def", "__init__", "(", "self", ",", "predictor", ",", "weight", "=", "0.75", ")", ":", "super", "(", "Classifier", ",", "self", ")", ".", "__init__", "(", ")", "with", "self", ".", "init_scope", "(", ")", ":", "self", ".", "predictor", "=", "predictor", "self", ".", "weight", "=", "float", "(", "weight", ")", "self", ".", "y_image", "=", "None", "self", ".", "y_action", "=", "None", "self", ".", "image_mask", "=", "None" ]
https://github.com/AI-ON/Multitask-and-Transfer-Learning/blob/31e0798d436e314ddbc64c4a6b935df1b2160e50/architectures/chainer/models/predictive_autoencoder.py#L107-L114
spectralpython/spectral
e1cd919f5f66abddc219b76926450240feaaed8f
spectral/image.py
python
Image.params
(self)
return p
Return an object containing the SpyFile parameters.
Return an object containing the SpyFile parameters.
[ "Return", "an", "object", "containing", "the", "SpyFile", "parameters", "." ]
def params(self): '''Return an object containing the SpyFile parameters.''' class P: pass p = P() p.nbands = self.nbands p.nrows = self.nrows p.ncols = self.ncols p.metadata = self.metadata p.dtype = self.dtype return p
[ "def", "params", "(", "self", ")", ":", "class", "P", ":", "pass", "p", "=", "P", "(", ")", "p", ".", "nbands", "=", "self", ".", "nbands", "p", ".", "nrows", "=", "self", ".", "nrows", "p", ".", "ncols", "=", "self", ".", "ncols", "p", ".", "metadata", "=", "self", ".", "metadata", "p", ".", "dtype", "=", "self", ".", "dtype", "return", "p" ]
https://github.com/spectralpython/spectral/blob/e1cd919f5f66abddc219b76926450240feaaed8f/spectral/image.py#L33-L46
scikit-learn/scikit-learn
1d1aadd0711b87d2a11c80aad15df6f8cf156712
examples/classification/plot_lda.py
python
generate_data
(n_samples, n_features)
return X, y
Generate random blob-ish data with noisy features. This returns an array of input data with shape `(n_samples, n_features)` and an array of `n_samples` target labels. Only one feature contains discriminative information, the other features contain only noise.
Generate random blob-ish data with noisy features.
[ "Generate", "random", "blob", "-", "ish", "data", "with", "noisy", "features", "." ]
def generate_data(n_samples, n_features): """Generate random blob-ish data with noisy features. This returns an array of input data with shape `(n_samples, n_features)` and an array of `n_samples` target labels. Only one feature contains discriminative information, the other features contain only noise. """ X, y = make_blobs(n_samples=n_samples, n_features=1, centers=[[-2], [2]]) # add non-discriminative features if n_features > 1: X = np.hstack([X, np.random.randn(n_samples, n_features - 1)]) return X, y
[ "def", "generate_data", "(", "n_samples", ",", "n_features", ")", ":", "X", ",", "y", "=", "make_blobs", "(", "n_samples", "=", "n_samples", ",", "n_features", "=", "1", ",", "centers", "=", "[", "[", "-", "2", "]", ",", "[", "2", "]", "]", ")", "# add non-discriminative features", "if", "n_features", ">", "1", ":", "X", "=", "np", ".", "hstack", "(", "[", "X", ",", "np", ".", "random", ".", "randn", "(", "n_samples", ",", "n_features", "-", "1", ")", "]", ")", "return", "X", ",", "y" ]
https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/examples/classification/plot_lda.py#L26-L40
cylc/cylc-flow
5ec221143476c7c616c156b74158edfbcd83794a
cylc/flow/xtrigger_mgr.py
python
XtriggerManager._get_xtrigs
(self, itask: TaskProxy, unsat_only: bool = False, sigs_only: bool = False)
return res
(Internal helper method.) Args: itask (TaskProxy): TaskProxy unsat_only (bool): whether to retrieve only unsatisfied xtriggers or not sigs_only (bool): whether to append only the function signature or not Returns: List[Union[str, Tuple[str, str, SubFuncContext, bool]]]: a list with either signature (if sigs_only True) or with tuples of label, signature, function context, and flag for satisfied.
(Internal helper method.)
[ "(", "Internal", "helper", "method", ".", ")" ]
def _get_xtrigs(self, itask: TaskProxy, unsat_only: bool = False, sigs_only: bool = False): """(Internal helper method.) Args: itask (TaskProxy): TaskProxy unsat_only (bool): whether to retrieve only unsatisfied xtriggers or not sigs_only (bool): whether to append only the function signature or not Returns: List[Union[str, Tuple[str, str, SubFuncContext, bool]]]: a list with either signature (if sigs_only True) or with tuples of label, signature, function context, and flag for satisfied. """ res = [] for label, satisfied in itask.state.xtriggers.items(): if unsat_only and satisfied: continue ctx = self.get_xtrig_ctx(itask, label) sig = ctx.get_signature() if sigs_only: res.append(sig) else: res.append((label, sig, ctx, satisfied)) return res
[ "def", "_get_xtrigs", "(", "self", ",", "itask", ":", "TaskProxy", ",", "unsat_only", ":", "bool", "=", "False", ",", "sigs_only", ":", "bool", "=", "False", ")", ":", "res", "=", "[", "]", "for", "label", ",", "satisfied", "in", "itask", ".", "state", ".", "xtriggers", ".", "items", "(", ")", ":", "if", "unsat_only", "and", "satisfied", ":", "continue", "ctx", "=", "self", ".", "get_xtrig_ctx", "(", "itask", ",", "label", ")", "sig", "=", "ctx", ".", "get_signature", "(", ")", "if", "sigs_only", ":", "res", ".", "append", "(", "sig", ")", "else", ":", "res", ".", "append", "(", "(", "label", ",", "sig", ",", "ctx", ",", "satisfied", ")", ")", "return", "res" ]
https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/xtrigger_mgr.py#L207-L232
google-research/tensor2robot
484a15ee63df412f1f7e53861c936630ad31124b
meta_learning/preprocessors.py
python
create_maml_label_spec
(label_spec)
return utils.flatten_spec_structure( utils.copy_tensorspec(label_spec, batch_size=-1, prefix='meta_labels'))
Create a meta feature from existing base_model specs. Args: label_spec: A hierarchy of TensorSpecs(subclasses) or Tensors. Returns: An instance of TensorSpecStruct representing a valid meta learning tensor_spec for computing the outer loss.
Create a meta feature from existing base_model specs.
[ "Create", "a", "meta", "feature", "from", "existing", "base_model", "specs", "." ]
def create_maml_label_spec(label_spec): """Create a meta feature from existing base_model specs. Args: label_spec: A hierarchy of TensorSpecs(subclasses) or Tensors. Returns: An instance of TensorSpecStruct representing a valid meta learning tensor_spec for computing the outer loss. """ return utils.flatten_spec_structure( utils.copy_tensorspec(label_spec, batch_size=-1, prefix='meta_labels'))
[ "def", "create_maml_label_spec", "(", "label_spec", ")", ":", "return", "utils", ".", "flatten_spec_structure", "(", "utils", ".", "copy_tensorspec", "(", "label_spec", ",", "batch_size", "=", "-", "1", ",", "prefix", "=", "'meta_labels'", ")", ")" ]
https://github.com/google-research/tensor2robot/blob/484a15ee63df412f1f7e53861c936630ad31124b/meta_learning/preprocessors.py#L69-L80
otsaloma/gaupol
6dec7826654d223c71a8d3279dcd967e95c46714
aeidon/markups/subrip.py
python
SubRip.italicize
(self, text, bounds=None)
return "".join((text[:a], "<i>{}</i>".format(text[a:z]), text[z:]))
Return italicized `text`.
Return italicized `text`.
[ "Return", "italicized", "text", "." ]
def italicize(self, text, bounds=None): """Return italicized `text`.""" a, z = bounds or (0, len(text)) return "".join((text[:a], "<i>{}</i>".format(text[a:z]), text[z:]))
[ "def", "italicize", "(", "self", ",", "text", ",", "bounds", "=", "None", ")", ":", "a", ",", "z", "=", "bounds", "or", "(", "0", ",", "len", "(", "text", ")", ")", "return", "\"\"", ".", "join", "(", "(", "text", "[", ":", "a", "]", ",", "\"<i>{}</i>\"", ".", "format", "(", "text", "[", "a", ":", "z", "]", ")", ",", "text", "[", "z", ":", "]", ")", ")" ]
https://github.com/otsaloma/gaupol/blob/6dec7826654d223c71a8d3279dcd967e95c46714/aeidon/markups/subrip.py#L71-L74
graphcore/examples
46d2b7687b829778369fc6328170a7b14761e5c6
code_examples/tensorflow2/adversarial_generalized_method_of_moments/tf2_AdGMoM.py
python
gaussian_kernel
(x, precision, normalizer)
A multi-dimensional symmetric gaussian kernel.
A multi-dimensional symmetric gaussian kernel.
[ "A", "multi", "-", "dimensional", "symmetric", "gaussian", "kernel", "." ]
def gaussian_kernel(x, precision, normalizer): """A multi-dimensional symmetric gaussian kernel.""" with tf.name_scope("GaussianKernel"): dimension = x.get_shape().as_list()[-1] last = tf.pow(2. * np.pi, dimension / 2.) pre_last = tf.reduce_sum(tf.pow(x, 2), axis=-1, keepdims=True) pre_last_reduced = tf.reshape(pre_last, x.get_shape().as_list()[:-1]) y = tf.math.multiply(tf.pow(precision, 2) / 2., pre_last_reduced) w = tf.exp(-y) / last t = tf.pow(tf.abs(precision), dimension) kernel = tf.math.multiply(t, w) return tf.math.multiply(1. / normalizer, kernel)
[ "def", "gaussian_kernel", "(", "x", ",", "precision", ",", "normalizer", ")", ":", "with", "tf", ".", "name_scope", "(", "\"GaussianKernel\"", ")", ":", "dimension", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "-", "1", "]", "last", "=", "tf", ".", "pow", "(", "2.", "*", "np", ".", "pi", ",", "dimension", "/", "2.", ")", "pre_last", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "pow", "(", "x", ",", "2", ")", ",", "axis", "=", "-", "1", ",", "keepdims", "=", "True", ")", "pre_last_reduced", "=", "tf", ".", "reshape", "(", "pre_last", ",", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", ":", "-", "1", "]", ")", "y", "=", "tf", ".", "math", ".", "multiply", "(", "tf", ".", "pow", "(", "precision", ",", "2", ")", "/", "2.", ",", "pre_last_reduced", ")", "w", "=", "tf", ".", "exp", "(", "-", "y", ")", "/", "last", "t", "=", "tf", ".", "pow", "(", "tf", ".", "abs", "(", "precision", ")", ",", "dimension", ")", "kernel", "=", "tf", ".", "math", ".", "multiply", "(", "t", ",", "w", ")", "return", "tf", ".", "math", ".", "multiply", "(", "1.", "/", "normalizer", ",", "kernel", ")" ]
https://github.com/graphcore/examples/blob/46d2b7687b829778369fc6328170a7b14761e5c6/code_examples/tensorflow2/adversarial_generalized_method_of_moments/tf2_AdGMoM.py#L323-L334
Chia-Network/chia-blockchain
34d44c1324ae634a0896f7b02eaa2802af9526cd
chia/util/keyring_wrapper.py
python
KeyringWrapper.migrate_legacy_keyring_interactive
(self)
Handle importing keys from the legacy keyring into the new keyring. Prior to beginning, we'll ensure that we at least suggest setting a master passphrase and backing up mnemonic seeds. After importing keys from the legacy keyring, we'll perform a before/after comparison of the keyring contents, and on success we'll prompt to cleanup the legacy keyring.
Handle importing keys from the legacy keyring into the new keyring.
[ "Handle", "importing", "keys", "from", "the", "legacy", "keyring", "into", "the", "new", "keyring", "." ]
def migrate_legacy_keyring_interactive(self): """ Handle importing keys from the legacy keyring into the new keyring. Prior to beginning, we'll ensure that we at least suggest setting a master passphrase and backing up mnemonic seeds. After importing keys from the legacy keyring, we'll perform a before/after comparison of the keyring contents, and on success we'll prompt to cleanup the legacy keyring. """ from chia.cmds.passphrase_funcs import async_update_daemon_migration_completed_if_running # Make sure the user is ready to begin migration. response = self.confirm_migration() if not response: print("Skipping migration. Unable to proceed") exit(0) try: results = self.migrate_legacy_keys() success = self.verify_migration_results(results) if success: print(f"Keyring migration completed successfully ({str(self.keyring.keyring_path)})\n") except Exception as e: print(f"\nMigration failed: {e}") print("Leaving legacy keyring intact") exit(1) # Ask if we should clean up the legacy keyring if self.confirm_legacy_keyring_cleanup(results): self.cleanup_legacy_keyring(results) print("Removed keys from old keyring") else: print("Keys in old keyring left intact") # Notify the daemon (if running) that migration has completed asyncio.get_event_loop().run_until_complete(async_update_daemon_migration_completed_if_running())
[ "def", "migrate_legacy_keyring_interactive", "(", "self", ")", ":", "from", "chia", ".", "cmds", ".", "passphrase_funcs", "import", "async_update_daemon_migration_completed_if_running", "# Make sure the user is ready to begin migration.", "response", "=", "self", ".", "confirm_migration", "(", ")", "if", "not", "response", ":", "print", "(", "\"Skipping migration. Unable to proceed\"", ")", "exit", "(", "0", ")", "try", ":", "results", "=", "self", ".", "migrate_legacy_keys", "(", ")", "success", "=", "self", ".", "verify_migration_results", "(", "results", ")", "if", "success", ":", "print", "(", "f\"Keyring migration completed successfully ({str(self.keyring.keyring_path)})\\n\"", ")", "except", "Exception", "as", "e", ":", "print", "(", "f\"\\nMigration failed: {e}\"", ")", "print", "(", "\"Leaving legacy keyring intact\"", ")", "exit", "(", "1", ")", "# Ask if we should clean up the legacy keyring", "if", "self", ".", "confirm_legacy_keyring_cleanup", "(", "results", ")", ":", "self", ".", "cleanup_legacy_keyring", "(", "results", ")", "print", "(", "\"Removed keys from old keyring\"", ")", "else", ":", "print", "(", "\"Keys in old keyring left intact\"", ")", "# Notify the daemon (if running) that migration has completed", "asyncio", ".", "get_event_loop", "(", ")", ".", "run_until_complete", "(", "async_update_daemon_migration_completed_if_running", "(", ")", ")" ]
https://github.com/Chia-Network/chia-blockchain/blob/34d44c1324ae634a0896f7b02eaa2802af9526cd/chia/util/keyring_wrapper.py#L497-L533
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
examples/meter_reader/reader_infer.py
python
MeterReader.filter_bboxes
(self, det_results, score_threshold)
return filtered_results
过滤置信度低于阈值的检测框 参数: det_results (list[dict]): 检测模型预测接口的返回值。 score_threshold (float):置信度阈值。 返回: filtered_results (list[dict]): 过滤后的检测狂。
过滤置信度低于阈值的检测框
[ "过滤置信度低于阈值的检测框" ]
def filter_bboxes(self, det_results, score_threshold): """过滤置信度低于阈值的检测框 参数: det_results (list[dict]): 检测模型预测接口的返回值。 score_threshold (float):置信度阈值。 返回: filtered_results (list[dict]): 过滤后的检测狂。 """ filtered_results = list() for res in det_results: if res['score'] > score_threshold: filtered_results.append(res) return filtered_results
[ "def", "filter_bboxes", "(", "self", ",", "det_results", ",", "score_threshold", ")", ":", "filtered_results", "=", "list", "(", ")", "for", "res", "in", "det_results", ":", "if", "res", "[", "'score'", "]", ">", "score_threshold", ":", "filtered_results", ".", "append", "(", "res", ")", "return", "filtered_results" ]
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/examples/meter_reader/reader_infer.py#L168-L183
inconvergent/svgsort
de54f1973d87009c37ff9755ebd5ee880f08e3f4
svgsort/svgpathtools/polytools.py
python
poly_real_part
(poly)
return np.poly1d(poly.coeffs.real)
Deprecated.
Deprecated.
[ "Deprecated", "." ]
def poly_real_part(poly): """Deprecated.""" return np.poly1d(poly.coeffs.real)
[ "def", "poly_real_part", "(", "poly", ")", ":", "return", "np", ".", "poly1d", "(", "poly", ".", "coeffs", ".", "real", ")" ]
https://github.com/inconvergent/svgsort/blob/de54f1973d87009c37ff9755ebd5ee880f08e3f4/svgsort/svgpathtools/polytools.py#L73-L75
docker/docker-py
a48a5a9647761406d66e8271f19fab7fa0c5f582
docker/utils/fnmatch.py
python
fnmatchcase
(name, pat)
return re_pat.match(name) is not None
Test whether FILENAME matches PATTERN, including case. This is a version of fnmatch() which doesn't case-normalize its arguments.
Test whether FILENAME matches PATTERN, including case. This is a version of fnmatch() which doesn't case-normalize its arguments.
[ "Test", "whether", "FILENAME", "matches", "PATTERN", "including", "case", ".", "This", "is", "a", "version", "of", "fnmatch", "()", "which", "doesn", "t", "case", "-", "normalize", "its", "arguments", "." ]
def fnmatchcase(name, pat): """Test whether FILENAME matches PATTERN, including case. This is a version of fnmatch() which doesn't case-normalize its arguments. """ try: re_pat = _cache[pat] except KeyError: res = translate(pat) if len(_cache) >= _MAXCACHE: _cache.clear() _cache[pat] = re_pat = re.compile(res) return re_pat.match(name) is not None
[ "def", "fnmatchcase", "(", "name", ",", "pat", ")", ":", "try", ":", "re_pat", "=", "_cache", "[", "pat", "]", "except", "KeyError", ":", "res", "=", "translate", "(", "pat", ")", "if", "len", "(", "_cache", ")", ">=", "_MAXCACHE", ":", "_cache", ".", "clear", "(", ")", "_cache", "[", "pat", "]", "=", "re_pat", "=", "re", ".", "compile", "(", "res", ")", "return", "re_pat", ".", "match", "(", "name", ")", "is", "not", "None" ]
https://github.com/docker/docker-py/blob/a48a5a9647761406d66e8271f19fab7fa0c5f582/docker/utils/fnmatch.py#L47-L60
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/packages.py
python
get_latest_package
(name, range_=None, paths=None, error=False)
Get the latest package for a given package name. Args: name (str): Package name. range_ (`VersionRange`): Version range to search within. paths (list of str, optional): paths to search for package families, defaults to `config.packages_path`. error (bool): If True, raise an error if no package is found. Returns: `Package` object, or None if no package is found.
Get the latest package for a given package name.
[ "Get", "the", "latest", "package", "for", "a", "given", "package", "name", "." ]
def get_latest_package(name, range_=None, paths=None, error=False): """Get the latest package for a given package name. Args: name (str): Package name. range_ (`VersionRange`): Version range to search within. paths (list of str, optional): paths to search for package families, defaults to `config.packages_path`. error (bool): If True, raise an error if no package is found. Returns: `Package` object, or None if no package is found. """ it = iter_packages(name, range_=range_, paths=paths) try: return max(it, key=lambda x: x.version) except ValueError: # empty sequence if error: # FIXME this isn't correct, since the pkg fam may exist but a pkg # in the range does not. raise PackageFamilyNotFoundError("No such package family %r" % name) return None
[ "def", "get_latest_package", "(", "name", ",", "range_", "=", "None", ",", "paths", "=", "None", ",", "error", "=", "False", ")", ":", "it", "=", "iter_packages", "(", "name", ",", "range_", "=", "range_", ",", "paths", "=", "paths", ")", "try", ":", "return", "max", "(", "it", ",", "key", "=", "lambda", "x", ":", "x", ".", "version", ")", "except", "ValueError", ":", "# empty sequence", "if", "error", ":", "# FIXME this isn't correct, since the pkg fam may exist but a pkg", "# in the range does not.", "raise", "PackageFamilyNotFoundError", "(", "\"No such package family %r\"", "%", "name", ")", "return", "None" ]
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/packages.py#L900-L921
steveKapturowski/tensorflow-rl
6dc58da69bad0349a646cfc94ea9c5d1eada8351
utils/cts.py
python
CTS.sample
(self, context, rejection_sampling=True)
return symbol
Samples a symbol from the model. Args: context: As per ``update()``. rejection_sampling: Whether to ignore samples from the prior. Returns: A symbol sampled according to the model. The default mode of operation is rejection sampling, which will ignore draws from the prior. This allows us to avoid providing an alphabet in full, and typically produces more pleasing samples (because they are never drawn from data for which we have no prior). If the full alphabet is provided (by setting self.alphabet) then `rejection_sampling` may be set to False. In this case, models may sample symbols in contexts they have never appeared in. This latter mode of operation is the mathematically correct one.
Samples a symbol from the model. Args: context: As per ``update()``. rejection_sampling: Whether to ignore samples from the prior. Returns: A symbol sampled according to the model. The default mode of operation is rejection sampling, which will ignore draws from the prior. This allows us to avoid providing an alphabet in full, and typically produces more pleasing samples (because they are never drawn from data for which we have no prior). If the full alphabet is provided (by setting self.alphabet) then `rejection_sampling` may be set to False. In this case, models may sample symbols in contexts they have never appeared in. This latter mode of operation is the mathematically correct one.
[ "Samples", "a", "symbol", "from", "the", "model", ".", "Args", ":", "context", ":", "As", "per", "update", "()", ".", "rejection_sampling", ":", "Whether", "to", "ignore", "samples", "from", "the", "prior", ".", "Returns", ":", "A", "symbol", "sampled", "according", "to", "the", "model", ".", "The", "default", "mode", "of", "operation", "is", "rejection", "sampling", "which", "will", "ignore", "draws", "from", "the", "prior", ".", "This", "allows", "us", "to", "avoid", "providing", "an", "alphabet", "in", "full", "and", "typically", "produces", "more", "pleasing", "samples", "(", "because", "they", "are", "never", "drawn", "from", "data", "for", "which", "we", "have", "no", "prior", ")", ".", "If", "the", "full", "alphabet", "is", "provided", "(", "by", "setting", "self", ".", "alphabet", ")", "then", "rejection_sampling", "may", "be", "set", "to", "False", ".", "In", "this", "case", "models", "may", "sample", "symbols", "in", "contexts", "they", "have", "never", "appeared", "in", ".", "This", "latter", "mode", "of", "operation", "is", "the", "mathematically", "correct", "one", "." ]
def sample(self, context, rejection_sampling=True): """Samples a symbol from the model. Args: context: As per ``update()``. rejection_sampling: Whether to ignore samples from the prior. Returns: A symbol sampled according to the model. The default mode of operation is rejection sampling, which will ignore draws from the prior. This allows us to avoid providing an alphabet in full, and typically produces more pleasing samples (because they are never drawn from data for which we have no prior). If the full alphabet is provided (by setting self.alphabet) then `rejection_sampling` may be set to False. In this case, models may sample symbols in contexts they have never appeared in. This latter mode of operation is the mathematically correct one. """ if self._time == 0 and rejection_sampling: raise Error('Cannot do rejection sampling on prior') self._check_context(context) symbol = self._root.sample(context, rejection_sampling) num_rejections = 0 while rejection_sampling and symbol is None: num_rejections += 1 if num_rejections >= MAX_SAMPLE_REJECTIONS: symbol = self._root.estimator.sample(rejection_sampling=True) # There should be *some* symbol in the root estimator. assert symbol is not None else: symbol = self._root.sample(context, rejection_sampling=True) return symbol
[ "def", "sample", "(", "self", ",", "context", ",", "rejection_sampling", "=", "True", ")", ":", "if", "self", ".", "_time", "==", "0", "and", "rejection_sampling", ":", "raise", "Error", "(", "'Cannot do rejection sampling on prior'", ")", "self", ".", "_check_context", "(", "context", ")", "symbol", "=", "self", ".", "_root", ".", "sample", "(", "context", ",", "rejection_sampling", ")", "num_rejections", "=", "0", "while", "rejection_sampling", "and", "symbol", "is", "None", ":", "num_rejections", "+=", "1", "if", "num_rejections", ">=", "MAX_SAMPLE_REJECTIONS", ":", "symbol", "=", "self", ".", "_root", ".", "estimator", ".", "sample", "(", "rejection_sampling", "=", "True", ")", "# There should be *some* symbol in the root estimator.", "assert", "symbol", "is", "not", "None", "else", ":", "symbol", "=", "self", ".", "_root", ".", "sample", "(", "context", ",", "rejection_sampling", "=", "True", ")", "return", "symbol" ]
https://github.com/steveKapturowski/tensorflow-rl/blob/6dc58da69bad0349a646cfc94ea9c5d1eada8351/utils/cts.py#L400-L431
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/gluon/contrib/pysimplesoap/c14n.py
python
_inclusiveNamespacePrefixes
(node, context, unsuppressedPrefixes)
return inclusive, unused_namespace_dict
http://www.w3.org/TR/xml-exc-c14n/ InclusiveNamespaces PrefixList parameter, which lists namespace prefixes that are handled in the manner described by the Canonical XML Recommendation
http://www.w3.org/TR/xml-exc-c14n/ InclusiveNamespaces PrefixList parameter, which lists namespace prefixes that are handled in the manner described by the Canonical XML Recommendation
[ "http", ":", "//", "www", ".", "w3", ".", "org", "/", "TR", "/", "xml", "-", "exc", "-", "c14n", "/", "InclusiveNamespaces", "PrefixList", "parameter", "which", "lists", "namespace", "prefixes", "that", "are", "handled", "in", "the", "manner", "described", "by", "the", "Canonical", "XML", "Recommendation" ]
def _inclusiveNamespacePrefixes(node, context, unsuppressedPrefixes): '''http://www.w3.org/TR/xml-exc-c14n/ InclusiveNamespaces PrefixList parameter, which lists namespace prefixes that are handled in the manner described by the Canonical XML Recommendation''' inclusive = [] if node.prefix: usedPrefixes = ['xmlns:%s' %node.prefix] else: usedPrefixes = ['xmlns'] for a in _attrs(node): if a.nodeName.startswith('xmlns') or not a.prefix: continue usedPrefixes.append('xmlns:%s' %a.prefix) unused_namespace_dict = {} for attr in context: n = attr.nodeName if n in unsuppressedPrefixes: inclusive.append(attr) elif n.startswith('xmlns:') and n[6:] in unsuppressedPrefixes: inclusive.append(attr) elif n.startswith('xmlns') and n[5:] in unsuppressedPrefixes: inclusive.append(attr) elif attr.nodeName in usedPrefixes: inclusive.append(attr) elif n.startswith('xmlns:'): unused_namespace_dict[n] = attr.value return inclusive, unused_namespace_dict
[ "def", "_inclusiveNamespacePrefixes", "(", "node", ",", "context", ",", "unsuppressedPrefixes", ")", ":", "inclusive", "=", "[", "]", "if", "node", ".", "prefix", ":", "usedPrefixes", "=", "[", "'xmlns:%s'", "%", "node", ".", "prefix", "]", "else", ":", "usedPrefixes", "=", "[", "'xmlns'", "]", "for", "a", "in", "_attrs", "(", "node", ")", ":", "if", "a", ".", "nodeName", ".", "startswith", "(", "'xmlns'", ")", "or", "not", "a", ".", "prefix", ":", "continue", "usedPrefixes", ".", "append", "(", "'xmlns:%s'", "%", "a", ".", "prefix", ")", "unused_namespace_dict", "=", "{", "}", "for", "attr", "in", "context", ":", "n", "=", "attr", ".", "nodeName", "if", "n", "in", "unsuppressedPrefixes", ":", "inclusive", ".", "append", "(", "attr", ")", "elif", "n", ".", "startswith", "(", "'xmlns:'", ")", "and", "n", "[", "6", ":", "]", "in", "unsuppressedPrefixes", ":", "inclusive", ".", "append", "(", "attr", ")", "elif", "n", ".", "startswith", "(", "'xmlns'", ")", "and", "n", "[", "5", ":", "]", "in", "unsuppressedPrefixes", ":", "inclusive", ".", "append", "(", "attr", ")", "elif", "attr", ".", "nodeName", "in", "usedPrefixes", ":", "inclusive", ".", "append", "(", "attr", ")", "elif", "n", ".", "startswith", "(", "'xmlns:'", ")", ":", "unused_namespace_dict", "[", "n", "]", "=", "attr", ".", "value", "return", "inclusive", ",", "unused_namespace_dict" ]
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/gluon/contrib/pysimplesoap/c14n.py#L111-L139
miketeo/pysmb
fc3faca073385b8abc4a503bb4439f849840f94c
python2/smb/base.py
python
SharedFile.isReadOnly
(self)
return bool(self.file_attributes & ATTR_READONLY)
A convenient property to return True if this file resource is read-only on the remote server
A convenient property to return True if this file resource is read-only on the remote server
[ "A", "convenient", "property", "to", "return", "True", "if", "this", "file", "resource", "is", "read", "-", "only", "on", "the", "remote", "server" ]
def isReadOnly(self): """A convenient property to return True if this file resource is read-only on the remote server""" return bool(self.file_attributes & ATTR_READONLY)
[ "def", "isReadOnly", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "file_attributes", "&", "ATTR_READONLY", ")" ]
https://github.com/miketeo/pysmb/blob/fc3faca073385b8abc4a503bb4439f849840f94c/python2/smb/base.py#L3021-L3023
davidhalter/parso
ee5edaf22ff3941cbdfa4efd8cb3e8f69779fd56
parso/python/diff.py
python
_NodesTree.parsed_until_line
(self)
return self._working_stack[-1].get_last_line(self.prefix)
[]
def parsed_until_line(self): return self._working_stack[-1].get_last_line(self.prefix)
[ "def", "parsed_until_line", "(", "self", ")", ":", "return", "self", ".", "_working_stack", "[", "-", "1", "]", ".", "get_last_line", "(", "self", ".", "prefix", ")" ]
https://github.com/davidhalter/parso/blob/ee5edaf22ff3941cbdfa4efd8cb3e8f69779fd56/parso/python/diff.py#L602-L603
peeringdb/peeringdb
47c6a699267b35663898f8d261159bdae9720f04
peeringdb_server/ixf.py
python
Importer.notify_error
(self, error)
Notifie the exchange and AC of any errors that were encountered when the IX-F data was parsed.
Notifie the exchange and AC of any errors that were encountered when the IX-F data was parsed.
[ "Notifie", "the", "exchange", "and", "AC", "of", "any", "errors", "that", "were", "encountered", "when", "the", "IX", "-", "F", "data", "was", "parsed", "." ]
def notify_error(self, error): """ Notifie the exchange and AC of any errors that were encountered when the IX-F data was parsed. """ if not self.save: return reversion.set_user(self.ticket_user) now = datetime.datetime.now(datetime.timezone.utc) notified = self.ixlan.ixf_ixp_import_error_notified self.ixlan.ixf_ixp_import_error if notified: diff = (now - notified).total_seconds() / 3600 if diff < settings.IXF_PARSE_ERROR_NOTIFICATION_PERIOD: return self.ixlan.ixf_ixp_import_error_notified = now self.ixlan.ixf_ixp_import_error = error self.ixlan.save() ixf_member_data = IXFMemberData(ixlan=self.ixlan, asn=0) subject = "Could not process IX-F Data" template = loader.get_template("email/notify-ixf-source-error.txt") message = template.render( {"error": error, "dt": now, "instance": ixf_member_data} ) # AC does not want ticket here as per #794 # self._ticket(ixf_member_data, subject, message) if ixf_member_data.ix_contacts: self._email( subject, message, ixf_member_data.ix_contacts, ix=ixf_member_data.ix )
[ "def", "notify_error", "(", "self", ",", "error", ")", ":", "if", "not", "self", ".", "save", ":", "return", "reversion", ".", "set_user", "(", "self", ".", "ticket_user", ")", "now", "=", "datetime", ".", "datetime", ".", "now", "(", "datetime", ".", "timezone", ".", "utc", ")", "notified", "=", "self", ".", "ixlan", ".", "ixf_ixp_import_error_notified", "self", ".", "ixlan", ".", "ixf_ixp_import_error", "if", "notified", ":", "diff", "=", "(", "now", "-", "notified", ")", ".", "total_seconds", "(", ")", "/", "3600", "if", "diff", "<", "settings", ".", "IXF_PARSE_ERROR_NOTIFICATION_PERIOD", ":", "return", "self", ".", "ixlan", ".", "ixf_ixp_import_error_notified", "=", "now", "self", ".", "ixlan", ".", "ixf_ixp_import_error", "=", "error", "self", ".", "ixlan", ".", "save", "(", ")", "ixf_member_data", "=", "IXFMemberData", "(", "ixlan", "=", "self", ".", "ixlan", ",", "asn", "=", "0", ")", "subject", "=", "\"Could not process IX-F Data\"", "template", "=", "loader", ".", "get_template", "(", "\"email/notify-ixf-source-error.txt\"", ")", "message", "=", "template", ".", "render", "(", "{", "\"error\"", ":", "error", ",", "\"dt\"", ":", "now", ",", "\"instance\"", ":", "ixf_member_data", "}", ")", "# AC does not want ticket here as per #794", "# self._ticket(ixf_member_data, subject, message)", "if", "ixf_member_data", ".", "ix_contacts", ":", "self", ".", "_email", "(", "subject", ",", "message", ",", "ixf_member_data", ".", "ix_contacts", ",", "ix", "=", "ixf_member_data", ".", "ix", ")" ]
https://github.com/peeringdb/peeringdb/blob/47c6a699267b35663898f8d261159bdae9720f04/peeringdb_server/ixf.py#L1969-L2009
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pkg_resources/_vendor/pyparsing.py
python
ParserElement._parseNoCache
( self, instring, loc, doActions=True, callPreParse=True )
return loc, retTokens
[]
def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ): debugging = ( self.debug ) #and doActions ) if debugging or self.failAction: #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )) if (self.debugActions[0] ): self.debugActions[0]( instring, loc, self ) if callPreParse and self.callPreparse: preloc = self.preParse( instring, loc ) else: preloc = loc tokensStart = preloc try: try: loc,tokens = self.parseImpl( instring, preloc, doActions ) except IndexError: raise ParseException( instring, len(instring), self.errmsg, self ) except ParseBaseException as err: #~ print ("Exception raised:", err) if self.debugActions[2]: self.debugActions[2]( instring, tokensStart, self, err ) if self.failAction: self.failAction( instring, tokensStart, self, err ) raise else: if callPreParse and self.callPreparse: preloc = self.preParse( instring, loc ) else: preloc = loc tokensStart = preloc if self.mayIndexError or loc >= len(instring): try: loc,tokens = self.parseImpl( instring, preloc, doActions ) except IndexError: raise ParseException( instring, len(instring), self.errmsg, self ) else: loc,tokens = self.parseImpl( instring, preloc, doActions ) tokens = self.postParse( instring, loc, tokens ) retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults ) if self.parseAction and (doActions or self.callDuringTry): if debugging: try: for fn in self.parseAction: tokens = fn( instring, tokensStart, retTokens ) if tokens is not None: retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), modal=self.modalResults ) except ParseBaseException as err: #~ print "Exception raised in user parse action:", err if (self.debugActions[2] ): self.debugActions[2]( instring, tokensStart, self, err ) raise else: for fn in self.parseAction: tokens = fn( instring, tokensStart, retTokens ) if tokens is not None: retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), modal=self.modalResults ) if debugging: #~ print ("Matched",self,"->",retTokens.asList()) if (self.debugActions[1] ): self.debugActions[1]( instring, tokensStart, loc, self, retTokens ) return loc, retTokens
[ "def", "_parseNoCache", "(", "self", ",", "instring", ",", "loc", ",", "doActions", "=", "True", ",", "callPreParse", "=", "True", ")", ":", "debugging", "=", "(", "self", ".", "debug", ")", "#and doActions )", "if", "debugging", "or", "self", ".", "failAction", ":", "#~ print (\"Match\",self,\"at loc\",loc,\"(%d,%d)\" % ( lineno(loc,instring), col(loc,instring) ))", "if", "(", "self", ".", "debugActions", "[", "0", "]", ")", ":", "self", ".", "debugActions", "[", "0", "]", "(", "instring", ",", "loc", ",", "self", ")", "if", "callPreParse", "and", "self", ".", "callPreparse", ":", "preloc", "=", "self", ".", "preParse", "(", "instring", ",", "loc", ")", "else", ":", "preloc", "=", "loc", "tokensStart", "=", "preloc", "try", ":", "try", ":", "loc", ",", "tokens", "=", "self", ".", "parseImpl", "(", "instring", ",", "preloc", ",", "doActions", ")", "except", "IndexError", ":", "raise", "ParseException", "(", "instring", ",", "len", "(", "instring", ")", ",", "self", ".", "errmsg", ",", "self", ")", "except", "ParseBaseException", "as", "err", ":", "#~ print (\"Exception raised:\", err)", "if", "self", ".", "debugActions", "[", "2", "]", ":", "self", ".", "debugActions", "[", "2", "]", "(", "instring", ",", "tokensStart", ",", "self", ",", "err", ")", "if", "self", ".", "failAction", ":", "self", ".", "failAction", "(", "instring", ",", "tokensStart", ",", "self", ",", "err", ")", "raise", "else", ":", "if", "callPreParse", "and", "self", ".", "callPreparse", ":", "preloc", "=", "self", ".", "preParse", "(", "instring", ",", "loc", ")", "else", ":", "preloc", "=", "loc", "tokensStart", "=", "preloc", "if", "self", ".", "mayIndexError", "or", "loc", ">=", "len", "(", "instring", ")", ":", "try", ":", "loc", ",", "tokens", "=", "self", ".", "parseImpl", "(", "instring", ",", "preloc", ",", "doActions", ")", "except", "IndexError", ":", "raise", "ParseException", "(", "instring", ",", "len", "(", "instring", ")", ",", "self", ".", "errmsg", ",", "self", ")", "else", ":", "loc", ",", "tokens", "=", "self", ".", "parseImpl", "(", "instring", ",", "preloc", ",", "doActions", ")", "tokens", "=", "self", ".", "postParse", "(", "instring", ",", "loc", ",", "tokens", ")", "retTokens", "=", "ParseResults", "(", "tokens", ",", "self", ".", "resultsName", ",", "asList", "=", "self", ".", "saveAsList", ",", "modal", "=", "self", ".", "modalResults", ")", "if", "self", ".", "parseAction", "and", "(", "doActions", "or", "self", ".", "callDuringTry", ")", ":", "if", "debugging", ":", "try", ":", "for", "fn", "in", "self", ".", "parseAction", ":", "tokens", "=", "fn", "(", "instring", ",", "tokensStart", ",", "retTokens", ")", "if", "tokens", "is", "not", "None", ":", "retTokens", "=", "ParseResults", "(", "tokens", ",", "self", ".", "resultsName", ",", "asList", "=", "self", ".", "saveAsList", "and", "isinstance", "(", "tokens", ",", "(", "ParseResults", ",", "list", ")", ")", ",", "modal", "=", "self", ".", "modalResults", ")", "except", "ParseBaseException", "as", "err", ":", "#~ print \"Exception raised in user parse action:\", err", "if", "(", "self", ".", "debugActions", "[", "2", "]", ")", ":", "self", ".", "debugActions", "[", "2", "]", "(", "instring", ",", "tokensStart", ",", "self", ",", "err", ")", "raise", "else", ":", "for", "fn", "in", "self", ".", "parseAction", ":", "tokens", "=", "fn", "(", "instring", ",", "tokensStart", ",", "retTokens", ")", "if", "tokens", "is", "not", "None", ":", "retTokens", "=", "ParseResults", "(", "tokens", ",", "self", ".", "resultsName", ",", "asList", "=", "self", ".", "saveAsList", "and", "isinstance", "(", "tokens", ",", "(", "ParseResults", ",", "list", ")", ")", ",", "modal", "=", "self", ".", "modalResults", ")", "if", "debugging", ":", "#~ print (\"Matched\",self,\"->\",retTokens.asList())", "if", "(", "self", ".", "debugActions", "[", "1", "]", ")", ":", "self", ".", "debugActions", "[", "1", "]", "(", "instring", ",", "tokensStart", ",", "loc", ",", "self", ",", "retTokens", ")", "return", "loc", ",", "retTokens" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pkg_resources/_vendor/pyparsing.py#L1347-L1417
skylines-project/skylines
ce68ee280af05498b3859fc2c199b08043ad58a9
skylines/commands/flights/find_meetings.py
python
FindMeetings.run
(self, force, _async, **kwargs)
[]
def run(self, force, _async, **kwargs): q = db.session.query(Flight) q = q.order_by(Flight.id) q = select(q, **kwargs) if not q: quit() if not force: q = q.filter(Flight.needs_analysis == True) if _async: current_app.add_celery() self.incremental(lambda f: self.do(f, _async=_async), q)
[ "def", "run", "(", "self", ",", "force", ",", "_async", ",", "*", "*", "kwargs", ")", ":", "q", "=", "db", ".", "session", ".", "query", "(", "Flight", ")", "q", "=", "q", ".", "order_by", "(", "Flight", ".", "id", ")", "q", "=", "select", "(", "q", ",", "*", "*", "kwargs", ")", "if", "not", "q", ":", "quit", "(", ")", "if", "not", "force", ":", "q", "=", "q", ".", "filter", "(", "Flight", ".", "needs_analysis", "==", "True", ")", "if", "_async", ":", "current_app", ".", "add_celery", "(", ")", "self", ".", "incremental", "(", "lambda", "f", ":", "self", ".", "do", "(", "f", ",", "_async", "=", "_async", ")", ",", "q", ")" ]
https://github.com/skylines-project/skylines/blob/ce68ee280af05498b3859fc2c199b08043ad58a9/skylines/commands/flights/find_meetings.py#L29-L44
NiklasRosenstein/myo-python
80967f206ae6f0a0eb9808319840680e6e60f1bf
myo/_ffi.py
python
Event.warmup_result
(self)
return WarmupResult(libmyo.libmyo_event_get_warmup_result(self._handle))
[]
def warmup_result(self): if self.type != EventType.warmup_completed: raise InvalidOperation() return WarmupResult(libmyo.libmyo_event_get_warmup_result(self._handle))
[ "def", "warmup_result", "(", "self", ")", ":", "if", "self", ".", "type", "!=", "EventType", ".", "warmup_completed", ":", "raise", "InvalidOperation", "(", ")", "return", "WarmupResult", "(", "libmyo", ".", "libmyo_event_get_warmup_result", "(", "self", ".", "_handle", ")", ")" ]
https://github.com/NiklasRosenstein/myo-python/blob/80967f206ae6f0a0eb9808319840680e6e60f1bf/myo/_ffi.py#L344-L347
NoxArt/SublimeText2-FTPSync
5893073bf081a0c7d51dff26fac77f2163d8d71f
lib3/ftplib.py
python
FTP.voidresp
(self)
return resp
Expect a response beginning with '2'.
Expect a response beginning with '2'.
[ "Expect", "a", "response", "beginning", "with", "2", "." ]
def voidresp(self): """Expect a response beginning with '2'.""" resp = self.getresp() if resp[:1] != '2': raise error_reply(resp) return resp
[ "def", "voidresp", "(", "self", ")", ":", "resp", "=", "self", ".", "getresp", "(", ")", "if", "resp", "[", ":", "1", "]", "!=", "'2'", ":", "raise", "error_reply", "(", "resp", ")", "return", "resp" ]
https://github.com/NoxArt/SublimeText2-FTPSync/blob/5893073bf081a0c7d51dff26fac77f2163d8d71f/lib3/ftplib.py#L246-L251
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pyasn1/type/univ.py
python
Choice.getName
(self, innerFlag=False)
Return the name of currently assigned component of the |ASN.1| object. Returns ------- : :py:class:`str` |ASN.1| component name
Return the name of currently assigned component of the |ASN.1| object.
[ "Return", "the", "name", "of", "currently", "assigned", "component", "of", "the", "|ASN", ".", "1|", "object", "." ]
def getName(self, innerFlag=False): """Return the name of currently assigned component of the |ASN.1| object. Returns ------- : :py:class:`str` |ASN.1| component name """ if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: if innerFlag: c = self._componentValues[self._currentIdx] if isinstance(c, Choice): return c.getName(innerFlag) return self.componentType.getNameByPosition(self._currentIdx)
[ "def", "getName", "(", "self", ",", "innerFlag", "=", "False", ")", ":", "if", "self", ".", "_currentIdx", "is", "None", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Component not chosen'", ")", "else", ":", "if", "innerFlag", ":", "c", "=", "self", ".", "_componentValues", "[", "self", ".", "_currentIdx", "]", "if", "isinstance", "(", "c", ",", "Choice", ")", ":", "return", "c", ".", "getName", "(", "innerFlag", ")", "return", "self", ".", "componentType", ".", "getNameByPosition", "(", "self", ".", "_currentIdx", ")" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pyasn1/type/univ.py#L3161-L3176
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_edit.py
python
Yedit.process_edits
(edits, yamlfile)
return {'changed': len(results) > 0, 'results': results}
run through a list of edits and process them one-by-one
run through a list of edits and process them one-by-one
[ "run", "through", "a", "list", "of", "edits", "and", "process", "them", "one", "-", "by", "-", "one" ]
def process_edits(edits, yamlfile): '''run through a list of edits and process them one-by-one''' results = [] for edit in edits: value = Yedit.parse_value(edit['value'], edit.get('value_type', '')) if edit.get('action') == 'update': # pylint: disable=line-too-long curr_value = Yedit.get_curr_value( Yedit.parse_value(edit.get('curr_value')), edit.get('curr_value_format')) rval = yamlfile.update(edit['key'], value, edit.get('index'), curr_value) elif edit.get('action') == 'append': rval = yamlfile.append(edit['key'], value) else: rval = yamlfile.put(edit['key'], value) if rval[0]: results.append({'key': edit['key'], 'edit': rval[1]}) return {'changed': len(results) > 0, 'results': results}
[ "def", "process_edits", "(", "edits", ",", "yamlfile", ")", ":", "results", "=", "[", "]", "for", "edit", "in", "edits", ":", "value", "=", "Yedit", ".", "parse_value", "(", "edit", "[", "'value'", "]", ",", "edit", ".", "get", "(", "'value_type'", ",", "''", ")", ")", "if", "edit", ".", "get", "(", "'action'", ")", "==", "'update'", ":", "# pylint: disable=line-too-long", "curr_value", "=", "Yedit", ".", "get_curr_value", "(", "Yedit", ".", "parse_value", "(", "edit", ".", "get", "(", "'curr_value'", ")", ")", ",", "edit", ".", "get", "(", "'curr_value_format'", ")", ")", "rval", "=", "yamlfile", ".", "update", "(", "edit", "[", "'key'", "]", ",", "value", ",", "edit", ".", "get", "(", "'index'", ")", ",", "curr_value", ")", "elif", "edit", ".", "get", "(", "'action'", ")", "==", "'append'", ":", "rval", "=", "yamlfile", ".", "append", "(", "edit", "[", "'key'", "]", ",", "value", ")", "else", ":", "rval", "=", "yamlfile", ".", "put", "(", "edit", "[", "'key'", "]", ",", "value", ")", "if", "rval", "[", "0", "]", ":", "results", ".", "append", "(", "{", "'key'", ":", "edit", "[", "'key'", "]", ",", "'edit'", ":", "rval", "[", "1", "]", "}", ")", "return", "{", "'changed'", ":", "len", "(", "results", ")", ">", "0", ",", "'results'", ":", "results", "}" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_edit.py#L752-L777
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/core/compute_management_client.py
python
ComputeManagementClient.reset_instance_pool
(self, instance_pool_id, **kwargs)
Performs the reset (immediate power off and power on) action on the specified instance pool, which performs the action on all the instances in the pool. :param str instance_pool_id: (required) The `OCID`__ of the instance pool. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param str opc_retry_token: (optional) A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations (for example, if a resource has been deleted and purged from the system, then a retry of the original creation request may be rejected). :param str if_match: (optional) For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.core.models.InstancePool` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/core/reset_instance_pool.py.html>`__ to see an example of how to use reset_instance_pool API.
Performs the reset (immediate power off and power on) action on the specified instance pool, which performs the action on all the instances in the pool.
[ "Performs", "the", "reset", "(", "immediate", "power", "off", "and", "power", "on", ")", "action", "on", "the", "specified", "instance", "pool", "which", "performs", "the", "action", "on", "all", "the", "instances", "in", "the", "pool", "." ]
def reset_instance_pool(self, instance_pool_id, **kwargs): """ Performs the reset (immediate power off and power on) action on the specified instance pool, which performs the action on all the instances in the pool. :param str instance_pool_id: (required) The `OCID`__ of the instance pool. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param str opc_retry_token: (optional) A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations (for example, if a resource has been deleted and purged from the system, then a retry of the original creation request may be rejected). :param str if_match: (optional) For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.core.models.InstancePool` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/core/reset_instance_pool.py.html>`__ to see an example of how to use reset_instance_pool API. """ resource_path = "/instancePools/{instancePoolId}/actions/reset" method = "POST" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "opc_retry_token", "if_match" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "reset_instance_pool got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "instancePoolId": instance_pool_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "opc-retry-token": kwargs.get("opc_retry_token", missing), "if-match": kwargs.get("if_match", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_retry_token_if_needed(header_params) self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, response_type="InstancePool") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, response_type="InstancePool")
[ "def", "reset_instance_pool", "(", "self", ",", "instance_pool_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/instancePools/{instancePoolId}/actions/reset\"", "method", "=", "\"POST\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"retry_strategy\"", ",", "\"opc_retry_token\"", ",", "\"if_match\"", "]", "extra_kwargs", "=", "[", "_key", "for", "_key", "in", "six", ".", "iterkeys", "(", "kwargs", ")", "if", "_key", "not", "in", "expected_kwargs", "]", "if", "extra_kwargs", ":", "raise", "ValueError", "(", "\"reset_instance_pool got unknown kwargs: {!r}\"", ".", "format", "(", "extra_kwargs", ")", ")", "path_params", "=", "{", "\"instancePoolId\"", ":", "instance_pool_id", "}", "path_params", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "path_params", ")", "if", "v", "is", "not", "missing", "}", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "path_params", ")", ":", "if", "v", "is", "None", "or", "(", "isinstance", "(", "v", ",", "six", ".", "string_types", ")", "and", "len", "(", "v", ".", "strip", "(", ")", ")", "==", "0", ")", ":", "raise", "ValueError", "(", "'Parameter {} cannot be None, whitespace or empty string'", ".", "format", "(", "k", ")", ")", "header_params", "=", "{", "\"accept\"", ":", "\"application/json\"", ",", "\"content-type\"", ":", "\"application/json\"", ",", "\"opc-retry-token\"", ":", "kwargs", ".", "get", "(", "\"opc_retry_token\"", ",", "missing", ")", ",", "\"if-match\"", ":", "kwargs", ".", "get", "(", "\"if_match\"", ",", "missing", ")", "}", "header_params", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "header_params", ")", "if", "v", "is", "not", "missing", "and", "v", "is", "not", "None", "}", "retry_strategy", "=", "self", ".", "base_client", ".", "get_preferred_retry_strategy", "(", "operation_retry_strategy", "=", "kwargs", ".", "get", "(", "'retry_strategy'", ")", ",", "client_retry_strategy", "=", "self", ".", "retry_strategy", ")", "if", "retry_strategy", ":", "if", "not", "isinstance", "(", "retry_strategy", ",", "retry", ".", "NoneRetryStrategy", ")", ":", "self", ".", "base_client", ".", "add_opc_retry_token_if_needed", "(", "header_params", ")", "self", ".", "base_client", ".", "add_opc_client_retries_header", "(", "header_params", ")", "retry_strategy", ".", "add_circuit_breaker_callback", "(", "self", ".", "circuit_breaker_callback", ")", "return", "retry_strategy", ".", "make_retrying_call", "(", "self", ".", "base_client", ".", "call_api", ",", "resource_path", "=", "resource_path", ",", "method", "=", "method", ",", "path_params", "=", "path_params", ",", "header_params", "=", "header_params", ",", "response_type", "=", "\"InstancePool\"", ")", "else", ":", "return", "self", ".", "base_client", ".", "call_api", "(", "resource_path", "=", "resource_path", ",", "method", "=", "method", ",", "path_params", "=", "path_params", ",", "header_params", "=", "header_params", ",", "response_type", "=", "\"InstancePool\"", ")" ]
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/core/compute_management_client.py#L2302-L2394
ztosec/hunter
4ee5cca8dc5fc5d7e631e935517bd0f493c30a37
SqlmapCelery/sqlmap/lib/controller/handler.py
python
setHandler
()
Detect which is the target web application back-end database management system.
Detect which is the target web application back-end database management system.
[ "Detect", "which", "is", "the", "target", "web", "application", "back", "-", "end", "database", "management", "system", "." ]
def setHandler(): """ Detect which is the target web application back-end database management system. """ items = [ (DBMS.MYSQL, MYSQL_ALIASES, MySQLMap, MySQLConn), (DBMS.ORACLE, ORACLE_ALIASES, OracleMap, OracleConn), (DBMS.PGSQL, PGSQL_ALIASES, PostgreSQLMap, PostgreSQLConn), (DBMS.MSSQL, MSSQL_ALIASES, MSSQLServerMap, MSSQLServerConn), (DBMS.SQLITE, SQLITE_ALIASES, SQLiteMap, SQLiteConn), (DBMS.ACCESS, ACCESS_ALIASES, AccessMap, AccessConn), (DBMS.FIREBIRD, FIREBIRD_ALIASES, FirebirdMap, FirebirdConn), (DBMS.MAXDB, MAXDB_ALIASES, MaxDBMap, MaxDBConn), (DBMS.SYBASE, SYBASE_ALIASES, SybaseMap, SybaseConn), (DBMS.DB2, DB2_ALIASES, DB2Map, DB2Conn), (DBMS.HSQLDB, HSQLDB_ALIASES, HSQLDBMap, HSQLDBConn), (DBMS.INFORMIX, INFORMIX_ALIASES, InformixMap, InformixConn), ] _ = max(_ if (Backend.getIdentifiedDbms() or "").lower() in _[1] else None for _ in items) if _: items.remove(_) items.insert(0, _) for dbms, aliases, Handler, Connector in items: handler = Handler() conf.dbmsConnector = Connector() if conf.direct: dialect = DBMS_DICT[dbms][3] if dialect: sqlalchemy = SQLAlchemy(dialect=dialect) sqlalchemy.connect() if sqlalchemy.connector: conf.dbmsConnector = sqlalchemy else: try: conf.dbmsConnector.connect() except NameError: pass else: conf.dbmsConnector.connect() if handler.checkDbms(): if kb.resolutionDbms: conf.dbmsHandler = max(_ for _ in items if _[0] == kb.resolutionDbms)[2]() else: conf.dbmsHandler = handler conf.dbmsHandler._dbms = dbms break else: conf.dbmsConnector = None # At this point back-end DBMS is correctly fingerprinted, no need # to enforce it anymore Backend.flushForcedDbms()
[ "def", "setHandler", "(", ")", ":", "items", "=", "[", "(", "DBMS", ".", "MYSQL", ",", "MYSQL_ALIASES", ",", "MySQLMap", ",", "MySQLConn", ")", ",", "(", "DBMS", ".", "ORACLE", ",", "ORACLE_ALIASES", ",", "OracleMap", ",", "OracleConn", ")", ",", "(", "DBMS", ".", "PGSQL", ",", "PGSQL_ALIASES", ",", "PostgreSQLMap", ",", "PostgreSQLConn", ")", ",", "(", "DBMS", ".", "MSSQL", ",", "MSSQL_ALIASES", ",", "MSSQLServerMap", ",", "MSSQLServerConn", ")", ",", "(", "DBMS", ".", "SQLITE", ",", "SQLITE_ALIASES", ",", "SQLiteMap", ",", "SQLiteConn", ")", ",", "(", "DBMS", ".", "ACCESS", ",", "ACCESS_ALIASES", ",", "AccessMap", ",", "AccessConn", ")", ",", "(", "DBMS", ".", "FIREBIRD", ",", "FIREBIRD_ALIASES", ",", "FirebirdMap", ",", "FirebirdConn", ")", ",", "(", "DBMS", ".", "MAXDB", ",", "MAXDB_ALIASES", ",", "MaxDBMap", ",", "MaxDBConn", ")", ",", "(", "DBMS", ".", "SYBASE", ",", "SYBASE_ALIASES", ",", "SybaseMap", ",", "SybaseConn", ")", ",", "(", "DBMS", ".", "DB2", ",", "DB2_ALIASES", ",", "DB2Map", ",", "DB2Conn", ")", ",", "(", "DBMS", ".", "HSQLDB", ",", "HSQLDB_ALIASES", ",", "HSQLDBMap", ",", "HSQLDBConn", ")", ",", "(", "DBMS", ".", "INFORMIX", ",", "INFORMIX_ALIASES", ",", "InformixMap", ",", "InformixConn", ")", ",", "]", "_", "=", "max", "(", "_", "if", "(", "Backend", ".", "getIdentifiedDbms", "(", ")", "or", "\"\"", ")", ".", "lower", "(", ")", "in", "_", "[", "1", "]", "else", "None", "for", "_", "in", "items", ")", "if", "_", ":", "items", ".", "remove", "(", "_", ")", "items", ".", "insert", "(", "0", ",", "_", ")", "for", "dbms", ",", "aliases", ",", "Handler", ",", "Connector", "in", "items", ":", "handler", "=", "Handler", "(", ")", "conf", ".", "dbmsConnector", "=", "Connector", "(", ")", "if", "conf", ".", "direct", ":", "dialect", "=", "DBMS_DICT", "[", "dbms", "]", "[", "3", "]", "if", "dialect", ":", "sqlalchemy", "=", "SQLAlchemy", "(", "dialect", "=", "dialect", ")", "sqlalchemy", ".", "connect", "(", ")", "if", "sqlalchemy", ".", "connector", ":", "conf", ".", "dbmsConnector", "=", "sqlalchemy", "else", ":", "try", ":", "conf", ".", "dbmsConnector", ".", "connect", "(", ")", "except", "NameError", ":", "pass", "else", ":", "conf", ".", "dbmsConnector", ".", "connect", "(", ")", "if", "handler", ".", "checkDbms", "(", ")", ":", "if", "kb", ".", "resolutionDbms", ":", "conf", ".", "dbmsHandler", "=", "max", "(", "_", "for", "_", "in", "items", "if", "_", "[", "0", "]", "==", "kb", ".", "resolutionDbms", ")", "[", "2", "]", "(", ")", "else", ":", "conf", ".", "dbmsHandler", "=", "handler", "conf", ".", "dbmsHandler", ".", "_dbms", "=", "dbms", "break", "else", ":", "conf", ".", "dbmsConnector", "=", "None", "# At this point back-end DBMS is correctly fingerprinted, no need", "# to enforce it anymore", "Backend", ".", "flushForcedDbms", "(", ")" ]
https://github.com/ztosec/hunter/blob/4ee5cca8dc5fc5d7e631e935517bd0f493c30a37/SqlmapCelery/sqlmap/lib/controller/handler.py#L52-L112
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/babel/numbers.py
python
format_decimal
(number, format=None, locale=LC_NUMERIC)
return pattern.apply(number, locale)
u"""Return the given decimal number formatted for a specific locale. >>> format_decimal(1.2345, locale='en_US') u'1.234' >>> format_decimal(1.2346, locale='en_US') u'1.235' >>> format_decimal(-1.2346, locale='en_US') u'-1.235' >>> format_decimal(1.2345, locale='sv_SE') u'1,234' >>> format_decimal(1.2345, locale='de') u'1,234' The appropriate thousands grouping and the decimal separator are used for each locale: >>> format_decimal(12345.5, locale='en_US') u'12,345.5' :param number: the number to format :param format: :param locale: the `Locale` object or locale identifier
u"""Return the given decimal number formatted for a specific locale.
[ "u", "Return", "the", "given", "decimal", "number", "formatted", "for", "a", "specific", "locale", "." ]
def format_decimal(number, format=None, locale=LC_NUMERIC): u"""Return the given decimal number formatted for a specific locale. >>> format_decimal(1.2345, locale='en_US') u'1.234' >>> format_decimal(1.2346, locale='en_US') u'1.235' >>> format_decimal(-1.2346, locale='en_US') u'-1.235' >>> format_decimal(1.2345, locale='sv_SE') u'1,234' >>> format_decimal(1.2345, locale='de') u'1,234' The appropriate thousands grouping and the decimal separator are used for each locale: >>> format_decimal(12345.5, locale='en_US') u'12,345.5' :param number: the number to format :param format: :param locale: the `Locale` object or locale identifier """ locale = Locale.parse(locale) if not format: format = locale.decimal_formats.get(format) pattern = parse_pattern(format) return pattern.apply(number, locale)
[ "def", "format_decimal", "(", "number", ",", "format", "=", "None", ",", "locale", "=", "LC_NUMERIC", ")", ":", "locale", "=", "Locale", ".", "parse", "(", "locale", ")", "if", "not", "format", ":", "format", "=", "locale", ".", "decimal_formats", ".", "get", "(", "format", ")", "pattern", "=", "parse_pattern", "(", "format", ")", "return", "pattern", ".", "apply", "(", "number", ",", "locale", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/babel/numbers.py#L315-L343
usableprivacy/upribox
2c8f5fb7cd714db269716fe1894185be923e697e
roles/arp/files/apate/lib/util.py
python
get_mac
(ip, interface)
Returns the according MAC address for the provided IP address. Args: ip (str): IP address used to get MAC address. interface (str): Interface used to send ARP request. Results: According MAC address as string (11:22:33:44:55:66) or None if no answer has been received.
Returns the according MAC address for the provided IP address.
[ "Returns", "the", "according", "MAC", "address", "for", "the", "provided", "IP", "address", "." ]
def get_mac(ip, interface): """Returns the according MAC address for the provided IP address. Args: ip (str): IP address used to get MAC address. interface (str): Interface used to send ARP request. Results: According MAC address as string (11:22:33:44:55:66) or None if no answer has been received. """ ans, unans = srp(Ether(dst=ETHER_BROADCAST) / ARP(pdst=ip), timeout=2, iface=interface, inter=0.1, verbose=0) for snd, rcv in ans: return rcv.sprintf(r"%Ether.src%")
[ "def", "get_mac", "(", "ip", ",", "interface", ")", ":", "ans", ",", "unans", "=", "srp", "(", "Ether", "(", "dst", "=", "ETHER_BROADCAST", ")", "/", "ARP", "(", "pdst", "=", "ip", ")", ",", "timeout", "=", "2", ",", "iface", "=", "interface", ",", "inter", "=", "0.1", ",", "verbose", "=", "0", ")", "for", "snd", ",", "rcv", "in", "ans", ":", "return", "rcv", ".", "sprintf", "(", "r\"%Ether.src%\"", ")" ]
https://github.com/usableprivacy/upribox/blob/2c8f5fb7cd714db269716fe1894185be923e697e/roles/arp/files/apate/lib/util.py#L28-L41
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
qa/qa_instance.py
python
TestInstanceExportNoTarget
(instance)
gnt-backup export (without target node, should fail)
gnt-backup export (without target node, should fail)
[ "gnt", "-", "backup", "export", "(", "without", "target", "node", "should", "fail", ")" ]
def TestInstanceExportNoTarget(instance): """gnt-backup export (without target node, should fail)""" AssertCommand(["gnt-backup", "export", instance.name], fail=True)
[ "def", "TestInstanceExportNoTarget", "(", "instance", ")", ":", "AssertCommand", "(", "[", "\"gnt-backup\"", ",", "\"export\"", ",", "instance", ".", "name", "]", ",", "fail", "=", "True", ")" ]
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/qa/qa_instance.py#L1106-L1108
Xavier-Lam/wechat-django
258e193e9ec9558709e889fd105c9bf474b013e6
wechat_django/models/template.py
python
Template.sync
(cls, app)
同步微信模板 :type app: wechat_django.models.WeChatApp
同步微信模板 :type app: wechat_django.models.WeChatApp
[ "同步微信模板", ":", "type", "app", ":", "wechat_django", ".", "models", ".", "WeChatApp" ]
def sync(cls, app): """ 同步微信模板 :type app: wechat_django.models.WeChatApp """ if app.type & AppType.SERVICEAPP: resp = app.client.template.get_all_private_template() templates = resp["template_list"] elif app.type & AppType.MINIPROGRAM: templates = list(cls._iter_wxa_templates(app)) else: raise WeChatAbilityError(WeChatAbilityError.TEMPLATE) with transaction.atomic(): (app.templates .exclude(template_id__in=[t["template_id"] for t in templates]) .delete()) rv = [] for t in templates: defaults = dict(app=app) defaults.update({ k: v for k, v in t.items() if k in model_fields(cls)}) template = app.templates.update_or_create( app=app, template_id=t["template_id"], defaults=defaults )[0] rv.append(template) return rv
[ "def", "sync", "(", "cls", ",", "app", ")", ":", "if", "app", ".", "type", "&", "AppType", ".", "SERVICEAPP", ":", "resp", "=", "app", ".", "client", ".", "template", ".", "get_all_private_template", "(", ")", "templates", "=", "resp", "[", "\"template_list\"", "]", "elif", "app", ".", "type", "&", "AppType", ".", "MINIPROGRAM", ":", "templates", "=", "list", "(", "cls", ".", "_iter_wxa_templates", "(", "app", ")", ")", "else", ":", "raise", "WeChatAbilityError", "(", "WeChatAbilityError", ".", "TEMPLATE", ")", "with", "transaction", ".", "atomic", "(", ")", ":", "(", "app", ".", "templates", ".", "exclude", "(", "template_id__in", "=", "[", "t", "[", "\"template_id\"", "]", "for", "t", "in", "templates", "]", ")", ".", "delete", "(", ")", ")", "rv", "=", "[", "]", "for", "t", "in", "templates", ":", "defaults", "=", "dict", "(", "app", "=", "app", ")", "defaults", ".", "update", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "t", ".", "items", "(", ")", "if", "k", "in", "model_fields", "(", "cls", ")", "}", ")", "template", "=", "app", ".", "templates", ".", "update_or_create", "(", "app", "=", "app", ",", "template_id", "=", "t", "[", "\"template_id\"", "]", ",", "defaults", "=", "defaults", ")", "[", "0", "]", "rv", ".", "append", "(", "template", ")", "return", "rv" ]
https://github.com/Xavier-Lam/wechat-django/blob/258e193e9ec9558709e889fd105c9bf474b013e6/wechat_django/models/template.py#L41-L68
ethereum/trinity
6383280c5044feb06695ac2f7bc1100b7bcf4fe0
trinity/_utils/eip1085.py
python
Account.to_dict
(self)
return AccountDetails({ 'balance': self.balance, 'nonce': self.nonce, 'code': self.code, 'storage': self.storage, })
[]
def to_dict(self) -> AccountDetails: return AccountDetails({ 'balance': self.balance, 'nonce': self.nonce, 'code': self.code, 'storage': self.storage, })
[ "def", "to_dict", "(", "self", ")", "->", "AccountDetails", ":", "return", "AccountDetails", "(", "{", "'balance'", ":", "self", ".", "balance", ",", "'nonce'", ":", "self", ".", "nonce", ",", "'code'", ":", "self", ".", "code", ",", "'storage'", ":", "self", ".", "storage", ",", "}", ")" ]
https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/trinity/_utils/eip1085.py#L75-L81
paramiko/paramiko
88f35a537428e430f7f26eee8026715e357b55d6
paramiko/file.py
python
BufferedFile.readinto
(self, buff)
return len(data)
Read up to ``len(buff)`` bytes into ``bytearray`` *buff* and return the number of bytes read. :returns: The number of bytes read.
Read up to ``len(buff)`` bytes into ``bytearray`` *buff* and return the number of bytes read.
[ "Read", "up", "to", "len", "(", "buff", ")", "bytes", "into", "bytearray", "*", "buff", "*", "and", "return", "the", "number", "of", "bytes", "read", "." ]
def readinto(self, buff): """ Read up to ``len(buff)`` bytes into ``bytearray`` *buff* and return the number of bytes read. :returns: The number of bytes read. """ data = self.read(len(buff)) buff[: len(data)] = data return len(data)
[ "def", "readinto", "(", "self", ",", "buff", ")", ":", "data", "=", "self", ".", "read", "(", "len", "(", "buff", ")", ")", "buff", "[", ":", "len", "(", "data", ")", "]", "=", "data", "return", "len", "(", "data", ")" ]
https://github.com/paramiko/paramiko/blob/88f35a537428e430f7f26eee8026715e357b55d6/paramiko/file.py#L160-L170
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventDetails.is_legal_holds_release_a_hold_details
(self)
return self._tag == 'legal_holds_release_a_hold_details'
Check if the union tag is ``legal_holds_release_a_hold_details``. :rtype: bool
Check if the union tag is ``legal_holds_release_a_hold_details``.
[ "Check", "if", "the", "union", "tag", "is", "legal_holds_release_a_hold_details", "." ]
def is_legal_holds_release_a_hold_details(self): """ Check if the union tag is ``legal_holds_release_a_hold_details``. :rtype: bool """ return self._tag == 'legal_holds_release_a_hold_details'
[ "def", "is_legal_holds_release_a_hold_details", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'legal_holds_release_a_hold_details'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L13679-L13685
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
portia_examle/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/chardetect.py
python
main
(argv=None)
Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str
Handles command line arguments and gets things started.
[ "Handles", "command", "line", "arguments", "and", "gets", "things", "started", "." ]
def main(argv=None): ''' Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str ''' # Get command line arguments parser = argparse.ArgumentParser( description="Takes one or more file paths and reports their detected \ encodings", formatter_class=argparse.ArgumentDefaultsHelpFormatter, conflict_handler='resolve') parser.add_argument('input', help='File whose encoding we would like to determine.', type=argparse.FileType('rb'), nargs='*', default=[sys.stdin]) parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(__version__)) args = parser.parse_args(argv) for f in args.input: if f.isatty(): print("You are running chardetect interactively. Press " + "CTRL-D twice at the start of a blank line to signal the " + "end of your input. If you want help, run chardetect " + "--help\n", file=sys.stderr) print(description_of(f, f.name))
[ "def", "main", "(", "argv", "=", "None", ")", ":", "# Get command line arguments", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Takes one or more file paths and reports their detected \\\n encodings\"", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ",", "conflict_handler", "=", "'resolve'", ")", "parser", ".", "add_argument", "(", "'input'", ",", "help", "=", "'File whose encoding we would like to determine.'", ",", "type", "=", "argparse", ".", "FileType", "(", "'rb'", ")", ",", "nargs", "=", "'*'", ",", "default", "=", "[", "sys", ".", "stdin", "]", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "'%(prog)s {0}'", ".", "format", "(", "__version__", ")", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "for", "f", "in", "args", ".", "input", ":", "if", "f", ".", "isatty", "(", ")", ":", "print", "(", "\"You are running chardetect interactively. Press \"", "+", "\"CTRL-D twice at the start of a blank line to signal the \"", "+", "\"end of your input. If you want help, run chardetect \"", "+", "\"--help\\n\"", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "description_of", "(", "f", ",", "f", ".", "name", ")", ")" ]
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/portia_examle/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/chardetect.py#L48-L76
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tdmq/v20200217/models.py
python
ModifyAMQPVHostRequest.__init__
(self)
r""" :param ClusterId: 集群ID :type ClusterId: str :param VHostId: vhost名称,3-64个字符,只能包含字母、数字、“-”及“_” :type VHostId: str :param MsgTtl: 未消费消息的保留时间,以毫秒为单位,60秒-15天 :type MsgTtl: int :param Remark: 说明,最大128个字符 :type Remark: str
r""" :param ClusterId: 集群ID :type ClusterId: str :param VHostId: vhost名称,3-64个字符,只能包含字母、数字、“-”及“_” :type VHostId: str :param MsgTtl: 未消费消息的保留时间,以毫秒为单位,60秒-15天 :type MsgTtl: int :param Remark: 说明,最大128个字符 :type Remark: str
[ "r", ":", "param", "ClusterId", ":", "集群ID", ":", "type", "ClusterId", ":", "str", ":", "param", "VHostId", ":", "vhost名称,3", "-", "64个字符,只能包含字母、数字、“", "-", "”及“_”", ":", "type", "VHostId", ":", "str", ":", "param", "MsgTtl", ":", "未消费消息的保留时间,以毫秒为单位,60秒", "-", "15天", ":", "type", "MsgTtl", ":", "int", ":", "param", "Remark", ":", "说明,最大128个字符", ":", "type", "Remark", ":", "str" ]
def __init__(self): r""" :param ClusterId: 集群ID :type ClusterId: str :param VHostId: vhost名称,3-64个字符,只能包含字母、数字、“-”及“_” :type VHostId: str :param MsgTtl: 未消费消息的保留时间,以毫秒为单位,60秒-15天 :type MsgTtl: int :param Remark: 说明,最大128个字符 :type Remark: str """ self.ClusterId = None self.VHostId = None self.MsgTtl = None self.Remark = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ClusterId", "=", "None", "self", ".", "VHostId", "=", "None", "self", ".", "MsgTtl", "=", "None", "self", ".", "Remark", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tdmq/v20200217/models.py#L6100-L6114
tensorflow/tfx
b4a6b83269815ed12ba9df9e9154c7376fef2ea0
tfx/orchestration/portable/outputs_utils.py
python
tag_executor_output_with_version
( executor_output: execution_result_pb2.ExecutorOutput)
Tag output artifacts in ExecutorOutput with the current TFX version.
Tag output artifacts in ExecutorOutput with the current TFX version.
[ "Tag", "output", "artifacts", "in", "ExecutorOutput", "with", "the", "current", "TFX", "version", "." ]
def tag_executor_output_with_version( executor_output: execution_result_pb2.ExecutorOutput): """Tag output artifacts in ExecutorOutput with the current TFX version.""" for unused_key, artifacts in executor_output.output_artifacts.items(): for artifact in artifacts.artifacts: if (artifact_utils.ARTIFACT_TFX_VERSION_CUSTOM_PROPERTY_KEY not in artifact.custom_properties): artifact.custom_properties[ artifact_utils .ARTIFACT_TFX_VERSION_CUSTOM_PROPERTY_KEY].string_value = ( version.__version__)
[ "def", "tag_executor_output_with_version", "(", "executor_output", ":", "execution_result_pb2", ".", "ExecutorOutput", ")", ":", "for", "unused_key", ",", "artifacts", "in", "executor_output", ".", "output_artifacts", ".", "items", "(", ")", ":", "for", "artifact", "in", "artifacts", ".", "artifacts", ":", "if", "(", "artifact_utils", ".", "ARTIFACT_TFX_VERSION_CUSTOM_PROPERTY_KEY", "not", "in", "artifact", ".", "custom_properties", ")", ":", "artifact", ".", "custom_properties", "[", "artifact_utils", ".", "ARTIFACT_TFX_VERSION_CUSTOM_PROPERTY_KEY", "]", ".", "string_value", "=", "(", "version", ".", "__version__", ")" ]
https://github.com/tensorflow/tfx/blob/b4a6b83269815ed12ba9df9e9154c7376fef2ea0/tfx/orchestration/portable/outputs_utils.py#L252-L262
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
24-class-metaprog/tinyenums/nanoenum.py
python
KeyIsValueDict.__missing__
(self, key)
return key
[]
def __missing__(self, key): if key.startswith('__') and key.endswith('__'): raise KeyError(key) self[key] = key return key
[ "def", "__missing__", "(", "self", ",", "key", ")", ":", "if", "key", ".", "startswith", "(", "'__'", ")", "and", "key", ".", "endswith", "(", "'__'", ")", ":", "raise", "KeyError", "(", "key", ")", "self", "[", "key", "]", "=", "key", "return", "key" ]
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/24-class-metaprog/tinyenums/nanoenum.py#L28-L32