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
rail-berkeley/d4rl
4aff6f8c46f62f9a57f79caa9287efefa45b6688
d4rl/carla/data_collection_town.py
python
RoamingAgent.run_step
(self)
return control, traffic_light_color
Execute one step of navigation. :return: carla.VehicleControl
Execute one step of navigation. :return: carla.VehicleControl
[ "Execute", "one", "step", "of", "navigation", ".", ":", "return", ":", "carla", ".", "VehicleControl" ]
def run_step(self): """ Execute one step of navigation. :return: carla.VehicleControl """ # is there an obstacle in front of us? hazard_detected = False # retrieve relevant elements for safe navigation, i.e.: traffic lights and other vehicles actor_list = self._world.get_actors() vehicle_list = actor_list.filter("*vehicle*") lights_list = actor_list.filter("*traffic_light*") # check possible obstacles vehicle_state, vehicle = self._is_vehicle_hazard(vehicle_list) if vehicle_state: self._state = AgentState.BLOCKED_BY_VEHICLE hazard_detected = True # check for the state of the traffic lights traffic_light_color = self._is_light_red(lights_list) if traffic_light_color == 'RED' and self._follow_traffic_lights: self._state = AgentState.BLOCKED_RED_LIGHT hazard_detected = True if hazard_detected: control = self.emergency_stop() else: self._state = AgentState.NAVIGATING # standard local planner behavior control = self._local_planner.run_step() return control, traffic_light_color
[ "def", "run_step", "(", "self", ")", ":", "# is there an obstacle in front of us?", "hazard_detected", "=", "False", "# retrieve relevant elements for safe navigation, i.e.: traffic lights and other vehicles", "actor_list", "=", "self", ".", "_world", ".", "get_actors", "(", ")...
https://github.com/rail-berkeley/d4rl/blob/4aff6f8c46f62f9a57f79caa9287efefa45b6688/d4rl/carla/data_collection_town.py#L939-L973
fatchord/WaveRNN
3595219b2f2f5353f0867a7bb59abcb15aba8831
utils/paths.py
python
Paths.get_voc_named_optim
(self, name)
return self.voc_checkpoints/f'{name}_optim.pyt'
Gets the path for the optimizer state in a named voc checkpoint.
Gets the path for the optimizer state in a named voc checkpoint.
[ "Gets", "the", "path", "for", "the", "optimizer", "state", "in", "a", "named", "voc", "checkpoint", "." ]
def get_voc_named_optim(self, name): """Gets the path for the optimizer state in a named voc checkpoint.""" return self.voc_checkpoints/f'{name}_optim.pyt'
[ "def", "get_voc_named_optim", "(", "self", ",", "name", ")", ":", "return", "self", ".", "voc_checkpoints", "/", "f'{name}_optim.pyt'" ]
https://github.com/fatchord/WaveRNN/blob/3595219b2f2f5353f0867a7bb59abcb15aba8831/utils/paths.py#L60-L62
ambakick/Person-Detection-and-Tracking
f925394ac29b5cf321f1ce89a71b193381519a0b
meta_architectures/ssd_meta_arch.py
python
SSDMetaArch.restore_map
(self, fine_tune_checkpoint_type='detection', load_all_detection_checkpoint_vars=False)
return variables_to_restore
Returns a map of variables to load from a foreign checkpoint. See parent class for details. Args: fine_tune_checkpoint_type: whether to restore from a full detection checkpoint (with compatible variable names) or to restore from a classification checkpoint for initialization prior to training. Valid values: `detection`, `classification`. Default 'detection'. load_all_detection_checkpoint_vars: whether to load all variables (when `fine_tune_checkpoint_type='detection'`). If False, only variables within the appropriate scopes are included. Default False. Returns: A dict mapping variable names (to load from a checkpoint) to variables in the model graph. Raises: ValueError: if fine_tune_checkpoint_type is neither `classification` nor `detection`.
Returns a map of variables to load from a foreign checkpoint.
[ "Returns", "a", "map", "of", "variables", "to", "load", "from", "a", "foreign", "checkpoint", "." ]
def restore_map(self, fine_tune_checkpoint_type='detection', load_all_detection_checkpoint_vars=False): """Returns a map of variables to load from a foreign checkpoint. See parent class for details. Args: fine_tune_checkpoint_type: whether to restore from a full detection checkpoint (with compatible variable names) or to restore from a classification checkpoint for initialization prior to training. Valid values: `detection`, `classification`. Default 'detection'. load_all_detection_checkpoint_vars: whether to load all variables (when `fine_tune_checkpoint_type='detection'`). If False, only variables within the appropriate scopes are included. Default False. Returns: A dict mapping variable names (to load from a checkpoint) to variables in the model graph. Raises: ValueError: if fine_tune_checkpoint_type is neither `classification` nor `detection`. """ if fine_tune_checkpoint_type not in ['detection', 'classification']: raise ValueError('Not supported fine_tune_checkpoint_type: {}'.format( fine_tune_checkpoint_type)) variables_to_restore = {} for variable in tf.global_variables(): var_name = variable.op.name if (fine_tune_checkpoint_type == 'detection' and load_all_detection_checkpoint_vars): variables_to_restore[var_name] = variable else: if var_name.startswith(self._extract_features_scope): if fine_tune_checkpoint_type == 'classification': var_name = ( re.split('^' + self._extract_features_scope + '/', var_name)[-1]) variables_to_restore[var_name] = variable return variables_to_restore
[ "def", "restore_map", "(", "self", ",", "fine_tune_checkpoint_type", "=", "'detection'", ",", "load_all_detection_checkpoint_vars", "=", "False", ")", ":", "if", "fine_tune_checkpoint_type", "not", "in", "[", "'detection'", ",", "'classification'", "]", ":", "raise", ...
https://github.com/ambakick/Person-Detection-and-Tracking/blob/f925394ac29b5cf321f1ce89a71b193381519a0b/meta_architectures/ssd_meta_arch.py#L830-L870
out0fmemory/GoAgent-Always-Available
c4254984fea633ce3d1893fe5901debd9f22c2a9
server/lib/google/appengine/_internal/antlr3/streams.py
python
ANTLRFileStream.__init__
(self, fileName, encoding=None)
@param fileName The path to the file to be opened. The file will be opened with mode 'rb'. @param encoding If you set the optional encoding argument, then the data will be decoded on the fly.
@param fileName The path to the file to be opened. The file will be opened with mode 'rb'.
[ "@param", "fileName", "The", "path", "to", "the", "file", "to", "be", "opened", ".", "The", "file", "will", "be", "opened", "with", "mode", "rb", "." ]
def __init__(self, fileName, encoding=None): """ @param fileName The path to the file to be opened. The file will be opened with mode 'rb'. @param encoding If you set the optional encoding argument, then the data will be decoded on the fly. """ self.fileName = fileName fp = codecs.open(fileName, 'rb', encoding) try: data = fp.read() finally: fp.close() ANTLRStringStream.__init__(self, data)
[ "def", "__init__", "(", "self", ",", "fileName", ",", "encoding", "=", "None", ")", ":", "self", ".", "fileName", "=", "fileName", "fp", "=", "codecs", ".", "open", "(", "fileName", ",", "'rb'", ",", "encoding", ")", "try", ":", "data", "=", "fp", ...
https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/_internal/antlr3/streams.py#L523-L541
facebookincubator/FCR
d5a629d062060cfa859b848ff54867e7450c04fd
external/common/fb303/py/gen-py/fb303_asyncio/fb303/FacebookService.py
python
Client.aliveSince
(self, )
return fut
Returns the unix time that the server has been running since
Returns the unix time that the server has been running since
[ "Returns", "the", "unix", "time", "that", "the", "server", "has", "been", "running", "since" ]
def aliveSince(self, ): """ Returns the unix time that the server has been running since """ self._seqid += 1 fut = self._futures[self._seqid] = asyncio.Future(loop=self._loop) self.send_aliveSince() return fut
[ "def", "aliveSince", "(", "self", ",", ")", ":", "self", ".", "_seqid", "+=", "1", "fut", "=", "self", ".", "_futures", "[", "self", ".", "_seqid", "]", "=", "asyncio", ".", "Future", "(", "loop", "=", "self", ".", "_loop", ")", "self", ".", "sen...
https://github.com/facebookincubator/FCR/blob/d5a629d062060cfa859b848ff54867e7450c04fd/external/common/fb303/py/gen-py/fb303_asyncio/fb303/FacebookService.py#L2675-L2682
quantopian/empyrical
40f61b4f229df10898d46d08f7b1bdc543c0f99c
versioneer.py
python
render
(pieces, style)
return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None}
Render the given version pieces into the requested style.
Render the given version pieces into the requested style.
[ "Render", "the", "given", "version", "pieces", "into", "the", "requested", "style", "." ]
def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"]} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None}
[ "def", "render", "(", "pieces", ",", "style", ")", ":", "if", "pieces", "[", "\"error\"", "]", ":", "return", "{", "\"version\"", ":", "\"unknown\"", ",", "\"full-revisionid\"", ":", "pieces", ".", "get", "(", "\"long\"", ")", ",", "\"dirty\"", ":", "Non...
https://github.com/quantopian/empyrical/blob/40f61b4f229df10898d46d08f7b1bdc543c0f99c/versioneer.py#L1362-L1389
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/importlib/_bootstrap_external.py
python
_path_is_mode_type
(path, mode)
return (stat_info.st_mode & 0o170000) == mode
Test whether the path is the specified mode type.
Test whether the path is the specified mode type.
[ "Test", "whether", "the", "path", "is", "the", "specified", "mode", "type", "." ]
def _path_is_mode_type(path, mode): """Test whether the path is the specified mode type.""" try: stat_info = _path_stat(path) except OSError: return False return (stat_info.st_mode & 0o170000) == mode
[ "def", "_path_is_mode_type", "(", "path", ",", "mode", ")", ":", "try", ":", "stat_info", "=", "_path_stat", "(", "path", ")", "except", "OSError", ":", "return", "False", "return", "(", "stat_info", ".", "st_mode", "&", "0o170000", ")", "==", "mode" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/importlib/_bootstrap_external.py#L150-L156
topydo/topydo
57d7577c987515d4b49d5500f666da29080ca3c2
topydo/ui/CLIApplicationBase.py
python
error
(p_string)
Writes an error on the standard error.
Writes an error on the standard error.
[ "Writes", "an", "error", "on", "the", "standard", "error", "." ]
def error(p_string): """ Writes an error on the standard error. """ write(sys.stderr, p_string)
[ "def", "error", "(", "p_string", ")", ":", "write", "(", "sys", ".", "stderr", ",", "p_string", ")" ]
https://github.com/topydo/topydo/blob/57d7577c987515d4b49d5500f666da29080ca3c2/topydo/ui/CLIApplicationBase.py#L125-L127
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/nexml/_nexml.py
python
AAMatrixSeqRow.hasContent_
(self)
[]
def hasContent_(self): if ( self.meta or self.seq is not None or super(AAMatrixSeqRow, self).hasContent_() ): return True else: return False
[ "def", "hasContent_", "(", "self", ")", ":", "if", "(", "self", ".", "meta", "or", "self", ".", "seq", "is", "not", "None", "or", "super", "(", "AAMatrixSeqRow", ",", "self", ")", ".", "hasContent_", "(", ")", ")", ":", "return", "True", "else", ":...
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/nexml/_nexml.py#L13123-L13131
mandiant/capa
c0851fc643793c012f5dd764482133c25c3216c8
capa/rules.py
python
RuleSet._index_rules_by_feature
(rules)
return (easy_rules_by_feature, hard_rules)
split the given rules into two structures: - "easy rules" are indexed by feature, such that you can quickly find the rules that contain a given feature. - "hard rules" are those that contain substring/regex/bytes features or match statements. these continue to be ordered topologically. a rule evaluator can use the "easy rule" index to restrict the candidate rules that might match a given set of features. at this time, a rule evaluator can't do anything special with the "hard rules". it must still do a full top-down match of each rule, in topological order.
split the given rules into two structures: - "easy rules" are indexed by feature, such that you can quickly find the rules that contain a given feature. - "hard rules" are those that contain substring/regex/bytes features or match statements. these continue to be ordered topologically.
[ "split", "the", "given", "rules", "into", "two", "structures", ":", "-", "easy", "rules", "are", "indexed", "by", "feature", "such", "that", "you", "can", "quickly", "find", "the", "rules", "that", "contain", "a", "given", "feature", ".", "-", "hard", "r...
def _index_rules_by_feature(rules) -> Tuple[Dict[Feature, Set[str]], List[str]]: """ split the given rules into two structures: - "easy rules" are indexed by feature, such that you can quickly find the rules that contain a given feature. - "hard rules" are those that contain substring/regex/bytes features or match statements. these continue to be ordered topologically. a rule evaluator can use the "easy rule" index to restrict the candidate rules that might match a given set of features. at this time, a rule evaluator can't do anything special with the "hard rules". it must still do a full top-down match of each rule, in topological order. """ # we'll do a couple phases: # # 1. recursively visit all nodes in all rules, # a. indexing all features # b. recording the types of features found per rule # 2. compute the easy and hard rule sets # 3. remove hard rules from the rules-by-feature index # 4. construct the topologically ordered list of hard rules rules_with_easy_features: Set[str] = set() rules_with_hard_features: Set[str] = set() rules_by_feature: Dict[Feature, Set[str]] = collections.defaultdict(set) def rec(rule_name: str, node: Union[Feature, Statement]): """ walk through a rule's logic tree, indexing the easy and hard rules, and the features referenced by easy rules. """ if isinstance( node, ( # these are the "hard features" # substring: scanning feature capa.features.common.Substring, # regex: scanning feature capa.features.common.Regex, # bytes: scanning feature capa.features.common.Bytes, # match: dependency on another rule, # which we have to evaluate first, # and is therefore tricky. capa.features.common.MatchedRule, ), ): # hard feature: requires scan or match lookup rules_with_hard_features.add(rule_name) elif isinstance(node, capa.features.common.Feature): # easy feature: hash lookup rules_with_easy_features.add(rule_name) rules_by_feature[node].add(rule_name) elif isinstance(node, (ceng.Not)): # `not:` statements are tricky to deal with. # # first, features found under a `not:` should not be indexed, # because they're not wanted to be found. # second, `not:` can be nested under another `not:`, or two, etc. # third, `not:` at the root or directly under an `or:` # means the rule will match against *anything* not specified there, # which is a difficult set of things to compute and index. # # so, if a rule has a `not:` statement, its hard. # as of writing, this is an uncommon statement, with only 6 instances in 740 rules. rules_with_hard_features.add(rule_name) elif isinstance(node, (ceng.Some)) and node.count == 0: # `optional:` and `0 or more:` are tricky to deal with. # # when a subtree is optional, it may match, but not matching # doesn't have any impact either. # now, our rule authors *should* not put this under `or:` # and this is checked by the linter, # but this could still happen (e.g. private rule set without linting) # and would be hard to trace down. # # so better to be safe than sorry and consider this a hard case. rules_with_hard_features.add(rule_name) elif isinstance(node, (ceng.Range)) and node.min == 0: # `count(foo): 0 or more` are tricky to deal with. # because the min is 0, # this subtree *can* match just about any feature # (except the given one) # which is a difficult set of things to compute and index. rules_with_hard_features.add(rule_name) elif isinstance(node, (ceng.Range)): rec(rule_name, node.child) elif isinstance(node, (ceng.And, ceng.Or, ceng.Some)): for child in node.children: rec(rule_name, child) elif isinstance(node, ceng.Statement): # unhandled type of statement. # this should only happen if a new subtype of `Statement` # has since been added to capa. # # ideally, we'd like to use mypy for exhaustiveness checking # for all the subtypes of `Statement`. # but, as far as i can tell, mypy does not support this type # of checking. # # in a way, this makes some intuitive sense: # the set of subtypes of type A is unbounded, # because any user might come along and create a new subtype B, # so mypy can't reason about this set of types. assert False, f"Unhandled value: {node} ({type(node).__name__})" else: # programming error assert_never(node) for rule in rules: rule_name = rule.meta["name"] root = rule.statement rec(rule_name, root) # if a rule has a hard feature, # dont consider it easy, and therefore, # don't index any of its features. # # otherwise, its an easy rule, and index its features for rules_with_feature in rules_by_feature.values(): rules_with_feature.difference_update(rules_with_hard_features) easy_rules_by_feature = rules_by_feature # `rules` is already topologically ordered, # so extract our hard set into the topological ordering. hard_rules = [] for rule in rules: if rule.meta["name"] in rules_with_hard_features: hard_rules.append(rule.meta["name"]) return (easy_rules_by_feature, hard_rules)
[ "def", "_index_rules_by_feature", "(", "rules", ")", "->", "Tuple", "[", "Dict", "[", "Feature", ",", "Set", "[", "str", "]", "]", ",", "List", "[", "str", "]", "]", ":", "# we'll do a couple phases:", "#", "# 1. recursively visit all nodes in all rules,", "# ...
https://github.com/mandiant/capa/blob/c0851fc643793c012f5dd764482133c25c3216c8/capa/rules.py#L1002-L1134
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1_secret_volume_source.py
python
V1SecretVolumeSource.default_mode
(self, default_mode)
Sets the default_mode of this V1SecretVolumeSource. Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set. :param default_mode: The default_mode of this V1SecretVolumeSource. :type: int
Sets the default_mode of this V1SecretVolumeSource. Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
[ "Sets", "the", "default_mode", "of", "this", "V1SecretVolumeSource", ".", "Optional", ":", "mode", "bits", "to", "use", "on", "created", "files", "by", "default", ".", "Must", "be", "a", "value", "between", "0", "and", "0777", ".", "Defaults", "to", "0644"...
def default_mode(self, default_mode): """ Sets the default_mode of this V1SecretVolumeSource. Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set. :param default_mode: The default_mode of this V1SecretVolumeSource. :type: int """ self._default_mode = default_mode
[ "def", "default_mode", "(", "self", ",", "default_mode", ")", ":", "self", ".", "_default_mode", "=", "default_mode" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_secret_volume_source.py#L64-L73
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/html5lib/filters/sanitizer.py
python
Filter.__init__
(self, source, allowed_elements=allowed_elements, allowed_attributes=allowed_attributes, allowed_css_properties=allowed_css_properties, allowed_css_keywords=allowed_css_keywords, allowed_svg_properties=allowed_svg_properties, allowed_protocols=allowed_protocols, allowed_content_types=allowed_content_types, attr_val_is_uri=attr_val_is_uri, svg_attr_val_allows_ref=svg_attr_val_allows_ref, svg_allow_local_href=svg_allow_local_href)
[]
def __init__(self, source, allowed_elements=allowed_elements, allowed_attributes=allowed_attributes, allowed_css_properties=allowed_css_properties, allowed_css_keywords=allowed_css_keywords, allowed_svg_properties=allowed_svg_properties, allowed_protocols=allowed_protocols, allowed_content_types=allowed_content_types, attr_val_is_uri=attr_val_is_uri, svg_attr_val_allows_ref=svg_attr_val_allows_ref, svg_allow_local_href=svg_allow_local_href): super(Filter, self).__init__(source) self.allowed_elements = allowed_elements self.allowed_attributes = allowed_attributes self.allowed_css_properties = allowed_css_properties self.allowed_css_keywords = allowed_css_keywords self.allowed_svg_properties = allowed_svg_properties self.allowed_protocols = allowed_protocols self.allowed_content_types = allowed_content_types self.attr_val_is_uri = attr_val_is_uri self.svg_attr_val_allows_ref = svg_attr_val_allows_ref self.svg_allow_local_href = svg_allow_local_href
[ "def", "__init__", "(", "self", ",", "source", ",", "allowed_elements", "=", "allowed_elements", ",", "allowed_attributes", "=", "allowed_attributes", ",", "allowed_css_properties", "=", "allowed_css_properties", ",", "allowed_css_keywords", "=", "allowed_css_keywords", "...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/html5lib/filters/sanitizer.py#L709-L731
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/idlelib/OutputWindow.py
python
OutputWindow.write
(self, s, tags=(), mark="insert")
[]
def write(self, s, tags=(), mark="insert"): if isinstance(s, (bytes, bytes)): s = s.decode(IOBinding.encoding, "replace") self.text.insert(mark, s, tags) self.text.see(mark) self.text.update()
[ "def", "write", "(", "self", ",", "s", ",", "tags", "=", "(", ")", ",", "mark", "=", "\"insert\"", ")", ":", "if", "isinstance", "(", "s", ",", "(", "bytes", ",", "bytes", ")", ")", ":", "s", "=", "s", ".", "decode", "(", "IOBinding", ".", "e...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/idlelib/OutputWindow.py#L37-L42
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Variables/PathVariable.py
python
_PathVariableClass.PathExists
(self, key, val, env)
validator to check if Path exists
validator to check if Path exists
[ "validator", "to", "check", "if", "Path", "exists" ]
def PathExists(self, key, val, env): """validator to check if Path exists""" if not os.path.exists(val): m = 'Path for option %s does not exist: %s' raise SCons.Errors.UserError(m % (key, val))
[ "def", "PathExists", "(", "self", ",", "key", ",", "val", ",", "env", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "val", ")", ":", "m", "=", "'Path for option %s does not exist: %s'", "raise", "SCons", ".", "Errors", ".", "UserError", ...
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Variables/PathVariable.py#L113-L117
gwpy/gwpy
82becd78d166a32985cb657a54d0d39f6a207739
gwpy/timeseries/timeseries.py
python
TimeSeries.csd_spectrogram
(self, other, stride, fftlength=None, overlap=0, window='hann', nproc=1, **kwargs)
return spectral.average_spectrogram( (self, other), spectral.csd, stride, fftlength=fftlength, overlap=overlap, window=window, nproc=nproc, **kwargs )
Calculate the cross spectral density spectrogram of this `TimeSeries` with 'other'. Parameters ---------- other : `~gwpy.timeseries.TimeSeries` second time-series for cross spectral density calculation stride : `float` number of seconds in single PSD (column of spectrogram). fftlength : `float` number of seconds in single FFT. overlap : `float`, optional number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0 window : `str`, `numpy.ndarray`, optional window function to apply to timeseries prior to FFT, see :func:`scipy.signal.get_window` for details on acceptable formats nproc : `int` maximum number of independent frame reading processes, default is set to single-process file reading. Returns ------- spectrogram : `~gwpy.spectrogram.Spectrogram` time-frequency cross spectrogram as generated from the two input time-series.
Calculate the cross spectral density spectrogram of this `TimeSeries` with 'other'.
[ "Calculate", "the", "cross", "spectral", "density", "spectrogram", "of", "this", "TimeSeries", "with", "other", "." ]
def csd_spectrogram(self, other, stride, fftlength=None, overlap=0, window='hann', nproc=1, **kwargs): """Calculate the cross spectral density spectrogram of this `TimeSeries` with 'other'. Parameters ---------- other : `~gwpy.timeseries.TimeSeries` second time-series for cross spectral density calculation stride : `float` number of seconds in single PSD (column of spectrogram). fftlength : `float` number of seconds in single FFT. overlap : `float`, optional number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0 window : `str`, `numpy.ndarray`, optional window function to apply to timeseries prior to FFT, see :func:`scipy.signal.get_window` for details on acceptable formats nproc : `int` maximum number of independent frame reading processes, default is set to single-process file reading. Returns ------- spectrogram : `~gwpy.spectrogram.Spectrogram` time-frequency cross spectrogram as generated from the two input time-series. """ return spectral.average_spectrogram( (self, other), spectral.csd, stride, fftlength=fftlength, overlap=overlap, window=window, nproc=nproc, **kwargs )
[ "def", "csd_spectrogram", "(", "self", ",", "other", ",", "stride", ",", "fftlength", "=", "None", ",", "overlap", "=", "0", ",", "window", "=", "'hann'", ",", "nproc", "=", "1", ",", "*", "*", "kwargs", ")", ":", "return", "spectral", ".", "average_...
https://github.com/gwpy/gwpy/blob/82becd78d166a32985cb657a54d0d39f6a207739/gwpy/timeseries/timeseries.py#L720-L764
reahl/reahl
86aac47c3a9b5b98e9f77dad4939034a02d54d46
reahl-component/reahl/component/dbutils.py
python
SystemControl.initialise_database
(self)
Ensures a new clean database exists, with a schema created. This drops an existing database if one is present.
Ensures a new clean database exists, with a schema created. This drops an existing database if one is present.
[ "Ensures", "a", "new", "clean", "database", "exists", "with", "a", "schema", "created", ".", "This", "drops", "an", "existing", "database", "if", "one", "is", "present", "." ]
def initialise_database(self): """Ensures a new clean database exists, with a schema created. This drops an existing database if one is present.""" self.drop_database() self.create_database() self.connect() try: self.create_db_tables() finally: self.disconnect()
[ "def", "initialise_database", "(", "self", ")", ":", "self", ".", "drop_database", "(", ")", "self", ".", "create_database", "(", ")", "self", ".", "connect", "(", ")", "try", ":", "self", ".", "create_db_tables", "(", ")", "finally", ":", "self", ".", ...
https://github.com/reahl/reahl/blob/86aac47c3a9b5b98e9f77dad4939034a02d54d46/reahl-component/reahl/component/dbutils.py#L148-L156
mcfletch/pyopengl
02d11dad9ff18e50db10e975c4756e17bf198464
OpenGL/GLES2/NV/conservative_raster_pre_snap_triangles.py
python
glInitConservativeRasterPreSnapTrianglesNV
()
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 glInitConservativeRasterPreSnapTrianglesNV(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
[ "def", "glInitConservativeRasterPreSnapTrianglesNV", "(", ")", ":", "from", "OpenGL", "import", "extensions", "return", "extensions", ".", "hasGLExtension", "(", "_EXTENSION_NAME", ")" ]
https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/GLES2/NV/conservative_raster_pre_snap_triangles.py#L41-L44
weecology/retriever
e5ba505f7b9958c70e60155f3c5495899da27e7e
retriever/lib/engine.py
python
Engine.create_raw_data_dir
(self, path=None)
Check to see if the archive directory exists and creates it if necessary.
Check to see if the archive directory exists and creates it if necessary.
[ "Check", "to", "see", "if", "the", "archive", "directory", "exists", "and", "creates", "it", "if", "necessary", "." ]
def create_raw_data_dir(self, path=None): """Check to see if the archive directory exists and creates it if necessary.""" if not path: path = self.format_data_dir() if not os.path.exists(path): os.makedirs(path)
[ "def", "create_raw_data_dir", "(", "self", ",", "path", "=", "None", ")", ":", "if", "not", "path", ":", "path", "=", "self", ".", "format_data_dir", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedi...
https://github.com/weecology/retriever/blob/e5ba505f7b9958c70e60155f3c5495899da27e7e/retriever/lib/engine.py#L395-L401
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/optparse.py
python
OptionParser.set_default
(self, dest, value)
[]
def set_default(self, dest, value): self.defaults[dest] = value
[ "def", "set_default", "(", "self", ",", "dest", ",", "value", ")", ":", "self", ".", "defaults", "[", "dest", "]", "=", "value" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/optparse.py#L1294-L1295
los-cocos/cocos
3b47281f95d6ee52bb2a357a767f213e670bd601
cocos/gl_framebuffer_object.py
python
FramebufferObject.__del__
(self)
Delete the framebuffer from the GPU memory
Delete the framebuffer from the GPU memory
[ "Delete", "the", "framebuffer", "from", "the", "GPU", "memory" ]
def __del__(self): """Delete the framebuffer from the GPU memory""" id = gl.GLuint(self._id) gl.glDeleteFramebuffersEXT(1, ct.byref(id))
[ "def", "__del__", "(", "self", ")", ":", "id", "=", "gl", ".", "GLuint", "(", "self", ".", "_id", ")", "gl", ".", "glDeleteFramebuffersEXT", "(", "1", ",", "ct", ".", "byref", "(", "id", ")", ")" ]
https://github.com/los-cocos/cocos/blob/3b47281f95d6ee52bb2a357a767f213e670bd601/cocos/gl_framebuffer_object.py#L83-L86
google/spatial-media
000cc7e29cd1d906ff7fd393550f462096406630
spatialmedia/metadata_utils.py
python
spherical_uuid
(metadata)
return uuid_leaf
Constructs a uuid containing spherical metadata. Args: metadata: String, xml to inject in spherical tag. Returns: uuid_leaf: a box containing spherical metadata.
Constructs a uuid containing spherical metadata.
[ "Constructs", "a", "uuid", "containing", "spherical", "metadata", "." ]
def spherical_uuid(metadata): """Constructs a uuid containing spherical metadata. Args: metadata: String, xml to inject in spherical tag. Returns: uuid_leaf: a box containing spherical metadata. """ uuid_leaf = mpeg.Box() assert(len(SPHERICAL_UUID_ID) == 16) uuid_leaf.name = mpeg.constants.TAG_UUID uuid_leaf.header_size = 8 uuid_leaf.content_size = 0 uuid_leaf.contents = SPHERICAL_UUID_ID + metadata.encode("utf-8") uuid_leaf.content_size = len(uuid_leaf.contents) return uuid_leaf
[ "def", "spherical_uuid", "(", "metadata", ")", ":", "uuid_leaf", "=", "mpeg", ".", "Box", "(", ")", "assert", "(", "len", "(", "SPHERICAL_UUID_ID", ")", "==", "16", ")", "uuid_leaf", ".", "name", "=", "mpeg", ".", "constants", ".", "TAG_UUID", "uuid_leaf...
https://github.com/google/spatial-media/blob/000cc7e29cd1d906ff7fd393550f462096406630/spatialmedia/metadata_utils.py#L126-L144
gmarull/asyncqt
5cb38a417608e04256db4bc7eb16dc4db88f7db0
asyncqt/_windows.py
python
_ProactorEventLoop._process_events
(self, events)
Process events from proactor.
Process events from proactor.
[ "Process", "events", "from", "proactor", "." ]
def _process_events(self, events): """Process events from proactor.""" for f, callback, transferred, key, ov in events: try: self._logger.debug('Invoking event callback {}'.format(callback)) value = callback(transferred, key, ov) except OSError as e: self._logger.warning('Event callback failed', exc_info=sys.exc_info()) if not f.done(): f.set_exception(e) else: if not f.cancelled(): f.set_result(value)
[ "def", "_process_events", "(", "self", ",", "events", ")", ":", "for", "f", ",", "callback", ",", "transferred", ",", "key", ",", "ov", "in", "events", ":", "try", ":", "self", ".", "_logger", ".", "debug", "(", "'Invoking event callback {}'", ".", "form...
https://github.com/gmarull/asyncqt/blob/5cb38a417608e04256db4bc7eb16dc4db88f7db0/asyncqt/_windows.py#L38-L50
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/requests/packages/chardet/utf8prober.py
python
UTF8Prober.get_charset_name
(self)
return "utf-8"
[]
def get_charset_name(self): return "utf-8"
[ "def", "get_charset_name", "(", "self", ")", ":", "return", "\"utf-8\"" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/requests/packages/chardet/utf8prober.py#L47-L48
ekonda/sketal
92a829a02973e8822c99c95ca316f85bf20afa3e
plugins/multiuser/chat_random_pair.py
python
PairPlugin.__init__
(self, *commands, prefixes=None, strict=False, text="❤ Любит ❤ "):
Answers with 2 users separated by text `text` defaults to `❤ Любит ❤ `.
Answers with 2 users separated by text `text` defaults to `❤ Любит ❤ `.
[ "Answers", "with", "2", "users", "separated", "by", "text", "text", "defaults", "to", "❤", "Любит", "❤", "." ]
def __init__(self, *commands, prefixes=None, strict=False, text="❤ Любит ❤ "): """Answers with 2 users separated by text `text` defaults to `❤ Любит ❤ `.""" if not commands: commands = ("кто кого",) super().__init__(*commands, prefixes=prefixes, strict=strict) self.text = text self.set_description()
[ "def", "__init__", "(", "self", ",", "*", "commands", ",", "prefixes", "=", "None", ",", "strict", "=", "False", ",", "text", "=", "\"❤ Любит ❤ \"):", "", "", "if", "not", "commands", ":", "commands", "=", "(", "\"кто кого\",)", "", "", "super", "(", ...
https://github.com/ekonda/sketal/blob/92a829a02973e8822c99c95ca316f85bf20afa3e/plugins/multiuser/chat_random_pair.py#L9-L19
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/numpy/ma/core.py
python
MaskedArray.__setitem__
(self, indx, value)
return
x.__setitem__(i, y) <==> x[i]=y Set item described by index. If value is masked, masks those locations.
x.__setitem__(i, y) <==> x[i]=y
[ "x", ".", "__setitem__", "(", "i", "y", ")", "<", "==", ">", "x", "[", "i", "]", "=", "y" ]
def __setitem__(self, indx, value): """ x.__setitem__(i, y) <==> x[i]=y Set item described by index. If value is masked, masks those locations. """ if self is masked: raise MaskError('Cannot alter the masked element.') _data = self._data _mask = self._mask if isinstance(indx, basestring): _data[indx] = value if _mask is nomask: self._mask = _mask = make_mask_none(self.shape, self.dtype) _mask[indx] = getmask(value) return _dtype = _data.dtype nbfields = len(_dtype.names or ()) if value is masked: # The mask wasn't set: create a full version. if _mask is nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) # Now, set the mask to its value. if nbfields: _mask[indx] = tuple([True] * nbfields) else: _mask[indx] = True if not self._isfield: self._sharedmask = False return # Get the _data part of the new value dval = value # Get the _mask part of the new value mval = getattr(value, '_mask', nomask) if nbfields and mval is nomask: mval = tuple([False] * nbfields) if _mask is nomask: # Set the data, then the mask _data[indx] = dval if mval is not nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) _mask[indx] = mval elif not self._hardmask: # Unshare the mask if necessary to avoid propagation # We want to remove the unshare logic from this place in the # future. Note that _sharedmask has lots of false positives. if not self._isfield: if self._sharedmask and not ( # If no one else holds a reference (we have two # references (_mask and self._mask) -- add one for # getrefcount) and the array owns its own data # copying the mask should do nothing. (sys.getrefcount(_mask) == 3) and _mask.flags.owndata): # 2016.01.15 -- v1.11.0 warnings.warn( "setting an item on a masked array which has a shared " "mask will not copy the mask and also change the " "original mask array in the future.\n" "Check the NumPy 1.11 release notes for more " "information.", MaskedArrayFutureWarning, stacklevel=2) self.unshare_mask() _mask = self._mask # Set the data, then the mask _data[indx] = dval _mask[indx] = mval elif hasattr(indx, 'dtype') and (indx.dtype == MaskType): indx = indx * umath.logical_not(_mask) _data[indx] = dval else: if nbfields: err_msg = "Flexible 'hard' masks are not yet supported." raise NotImplementedError(err_msg) mindx = mask_or(_mask[indx], mval, copy=True) dindx = self._data[indx] if dindx.size > 1: np.copyto(dindx, dval, where=~mindx) elif mindx is nomask: dindx = dval _data[indx] = dindx _mask[indx] = mindx return
[ "def", "__setitem__", "(", "self", ",", "indx", ",", "value", ")", ":", "if", "self", "is", "masked", ":", "raise", "MaskError", "(", "'Cannot alter the masked element.'", ")", "_data", "=", "self", ".", "_data", "_mask", "=", "self", ".", "_mask", "if", ...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/numpy/ma/core.py#L3220-L3306
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/urllib3/packages/rfc3986/_mixin.py
python
URIMixin.authority_is_valid
(self, require=False)
return validators.authority_is_valid( self.authority, host=self.host, require=require, )
Determine if the authority component is valid. .. deprecated:: 1.1.0 Use the :class:`~rfc3986.validators.Validator` object instead. :param bool require: Set to ``True`` to require the presence of this component. :returns: ``True`` if the authority is valid. ``False`` otherwise. :rtype: bool
Determine if the authority component is valid.
[ "Determine", "if", "the", "authority", "component", "is", "valid", "." ]
def authority_is_valid(self, require=False): """Determine if the authority component is valid. .. deprecated:: 1.1.0 Use the :class:`~rfc3986.validators.Validator` object instead. :param bool require: Set to ``True`` to require the presence of this component. :returns: ``True`` if the authority is valid. ``False`` otherwise. :rtype: bool """ warnings.warn("Please use rfc3986.validators.Validator instead. " "This method will be eventually removed.", DeprecationWarning) try: self.authority_info() except exc.InvalidAuthority: return False return validators.authority_is_valid( self.authority, host=self.host, require=require, )
[ "def", "authority_is_valid", "(", "self", ",", "require", "=", "False", ")", ":", "warnings", ".", "warn", "(", "\"Please use rfc3986.validators.Validator instead. \"", "\"This method will be eventually removed.\"", ",", "DeprecationWarning", ")", "try", ":", "self", ".",...
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/urllib3/packages/rfc3986/_mixin.py#L125-L151
limodou/uliweb
8bc827fa6bf7bf58aa8136b6c920fe2650c52422
uliweb/lib/werkzeug/wsgi.py
python
pop_path_info
(environ, charset='utf-8', errors='replace')
return to_unicode(rv, charset, errors, allow_none_charset=True)
Removes and returns the next segment of `PATH_INFO`, pushing it onto `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`. If the `charset` is set to `None` a bytestring is returned. If there are empty segments (``'/foo//bar``) these are ignored but properly pushed to the `SCRIPT_NAME`: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> pop_path_info(env) 'a' >>> env['SCRIPT_NAME'] '/foo/a' >>> pop_path_info(env) 'b' >>> env['SCRIPT_NAME'] '/foo/a/b' .. versionadded:: 0.5 .. versionchanged:: 0.9 The path is now decoded and a charset and encoding parameter can be provided. :param environ: the WSGI environment that is modified.
Removes and returns the next segment of `PATH_INFO`, pushing it onto `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`.
[ "Removes", "and", "returns", "the", "next", "segment", "of", "PATH_INFO", "pushing", "it", "onto", "SCRIPT_NAME", ".", "Returns", "None", "if", "there", "is", "nothing", "left", "on", "PATH_INFO", "." ]
def pop_path_info(environ, charset='utf-8', errors='replace'): """Removes and returns the next segment of `PATH_INFO`, pushing it onto `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`. If the `charset` is set to `None` a bytestring is returned. If there are empty segments (``'/foo//bar``) these are ignored but properly pushed to the `SCRIPT_NAME`: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> pop_path_info(env) 'a' >>> env['SCRIPT_NAME'] '/foo/a' >>> pop_path_info(env) 'b' >>> env['SCRIPT_NAME'] '/foo/a/b' .. versionadded:: 0.5 .. versionchanged:: 0.9 The path is now decoded and a charset and encoding parameter can be provided. :param environ: the WSGI environment that is modified. """ path = environ.get('PATH_INFO') if not path: return None script_name = environ.get('SCRIPT_NAME', '') # shift multiple leading slashes over old_path = path path = path.lstrip('/') if path != old_path: script_name += '/' * (len(old_path) - len(path)) if '/' not in path: environ['PATH_INFO'] = '' environ['SCRIPT_NAME'] = script_name + path rv = wsgi_get_bytes(path) else: segment, path = path.split('/', 1) environ['PATH_INFO'] = '/' + path environ['SCRIPT_NAME'] = script_name + segment rv = wsgi_get_bytes(segment) return to_unicode(rv, charset, errors, allow_none_charset=True)
[ "def", "pop_path_info", "(", "environ", ",", "charset", "=", "'utf-8'", ",", "errors", "=", "'replace'", ")", ":", "path", "=", "environ", ".", "get", "(", "'PATH_INFO'", ")", "if", "not", "path", ":", "return", "None", "script_name", "=", "environ", "."...
https://github.com/limodou/uliweb/blob/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/lib/werkzeug/wsgi.py#L249-L298
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/html5lib/tokenizer.py
python
HTMLTokenizer.__iter__
(self)
This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested.
This is where the magic happens.
[ "This", "is", "where", "the", "magic", "happens", "." ]
def __iter__(self): """ This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested. """ self.tokenQueue = deque([]) # Start processing. When EOF is reached self.state will return False # instead of True and the loop will terminate. while self.state(): while self.stream.errors: yield {"type": tokenTypes["ParseError"], "data": self.stream.errors.pop(0)} while self.tokenQueue: yield self.tokenQueue.popleft()
[ "def", "__iter__", "(", "self", ")", ":", "self", ".", "tokenQueue", "=", "deque", "(", "[", "]", ")", "# Start processing. When EOF is reached self.state will return False", "# instead of True and the loop will terminate.", "while", "self", ".", "state", "(", ")", ":",...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/html5lib/tokenizer.py#L57-L71
OpenEndedGroup/Field
4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c
Contents/lib/python/xml/sax/xmlreader.py
python
Locator.getLineNumber
(self)
return -1
Return the line number where the current event ends.
Return the line number where the current event ends.
[ "Return", "the", "line", "number", "where", "the", "current", "event", "ends", "." ]
def getLineNumber(self): "Return the line number where the current event ends." return -1
[ "def", "getLineNumber", "(", "self", ")", ":", "return", "-", "1" ]
https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/xml/sax/xmlreader.py#L173-L175
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/PIL/WebPImagePlugin.py
python
WebPImageFile._reset
(self, reset=True)
[]
def _reset(self, reset=True): if reset: self._decoder.reset() self.__physical_frame = 0 self.__loaded = -1 self.__timestamp = 0
[ "def", "_reset", "(", "self", ",", "reset", "=", "True", ")", ":", "if", "reset", ":", "self", ".", "_decoder", ".", "reset", "(", ")", "self", ".", "__physical_frame", "=", "0", "self", ".", "__loaded", "=", "-", "1", "self", ".", "__timestamp", "...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/PIL/WebPImagePlugin.py#L119-L124
FreeOpcUa/python-opcua
67f15551884d7f11659d52483e7b932999ca3a75
opcua/crypto/uacrypto.py
python
p_sha1
(secret, seed, sizes=())
return tuple(parts)
Derive one or more keys from secret and seed. (See specs part 6, 6.7.5 and RFC 2246 - TLS v1.0) Lengths of keys will match sizes argument
Derive one or more keys from secret and seed. (See specs part 6, 6.7.5 and RFC 2246 - TLS v1.0) Lengths of keys will match sizes argument
[ "Derive", "one", "or", "more", "keys", "from", "secret", "and", "seed", ".", "(", "See", "specs", "part", "6", "6", ".", "7", ".", "5", "and", "RFC", "2246", "-", "TLS", "v1", ".", "0", ")", "Lengths", "of", "keys", "will", "match", "sizes", "arg...
def p_sha1(secret, seed, sizes=()): """ Derive one or more keys from secret and seed. (See specs part 6, 6.7.5 and RFC 2246 - TLS v1.0) Lengths of keys will match sizes argument """ full_size = 0 for size in sizes: full_size += size result = b'' accum = seed while len(result) < full_size: accum = hmac_sha1(secret, accum) result += hmac_sha1(secret, accum + seed) parts = [] for size in sizes: parts.append(result[:size]) result = result[size:] return tuple(parts)
[ "def", "p_sha1", "(", "secret", ",", "seed", ",", "sizes", "=", "(", ")", ")", ":", "full_size", "=", "0", "for", "size", "in", "sizes", ":", "full_size", "+=", "size", "result", "=", "b''", "accum", "=", "seed", "while", "len", "(", "result", ")",...
https://github.com/FreeOpcUa/python-opcua/blob/67f15551884d7f11659d52483e7b932999ca3a75/opcua/crypto/uacrypto.py#L152-L172
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
examples/pytorch/gatv2/train.py
python
EarlyStopping.save_checkpoint
(self, model)
Saves model when validation loss decrease.
Saves model when validation loss decrease.
[ "Saves", "model", "when", "validation", "loss", "decrease", "." ]
def save_checkpoint(self, model): '''Saves model when validation loss decrease.''' torch.save(model.state_dict(), 'es_checkpoint.pt')
[ "def", "save_checkpoint", "(", "self", ",", "model", ")", ":", "torch", ".", "save", "(", "model", ".", "state_dict", "(", ")", ",", "'es_checkpoint.pt'", ")" ]
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/examples/pytorch/gatv2/train.py#L41-L43
tdamdouni/Pythonista
3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad
markdown/markdown2pdf/reportlab/pdfbase/pdfdoc.py
python
Annotation.cvtdict
(self, d, escape=1)
return d
transform dict args from python form to pdf string rep as needed
transform dict args from python form to pdf string rep as needed
[ "transform", "dict", "args", "from", "python", "form", "to", "pdf", "string", "rep", "as", "needed" ]
def cvtdict(self, d, escape=1): """transform dict args from python form to pdf string rep as needed""" Rect = d["Rect"] if not isStr(Rect): d["Rect"] = PDFArray(Rect) d["Contents"] = PDFString(d["Contents"],escape) return d
[ "def", "cvtdict", "(", "self", ",", "d", ",", "escape", "=", "1", ")", ":", "Rect", "=", "d", "[", "\"Rect\"", "]", "if", "not", "isStr", "(", "Rect", ")", ":", "d", "[", "\"Rect\"", "]", "=", "PDFArray", "(", "Rect", ")", "d", "[", "\"Contents...
https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/markdown/markdown2pdf/reportlab/pdfbase/pdfdoc.py#L1564-L1570
xlwings/xlwings
44395c4d18b46f76249279b7d0965e640291499c
xlwings/main.py
python
Picture.name
(self)
return self.impl.name
Returns or sets the name of the picture. .. versionadded:: 0.5.0
Returns or sets the name of the picture.
[ "Returns", "or", "sets", "the", "name", "of", "the", "picture", "." ]
def name(self): """ Returns or sets the name of the picture. .. versionadded:: 0.5.0 """ return self.impl.name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "impl", ".", "name" ]
https://github.com/xlwings/xlwings/blob/44395c4d18b46f76249279b7d0965e640291499c/xlwings/main.py#L3568-L3574
tuckerbalch/QSTK
4981506c37227a72404229d5e1e0887f797a5d57
Legacy/simulator/Simulator.py
python
Simulator.run
(self)
@summary: Run the simulation
[]
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done self.currTimestamp = timestamps[ctr] #self.startTime ctr2= ctr while (timestamps[ctr2]< self.endTime): ctr2+=1 if (ctr2>= len(timestamps)): break #while loop done if (ctr2>= len (timestamps)): self.endTime= timestamps[ctr2-1] else: self.endTime= timestamps[ctr2] if timersActive: print "Simulation timer started at "+ str(self.currTimestamp) totalTime = time.time() cycTime = time.clock() # self.strategyData.currTimestamp = self.currTimestamp i=1 while self.currTimestamp < self.endTime and self.currTimestamp < time.time(): # and self.currTimestamp < self.strategyData.timestampIndex[len(self.strategyData.timestampIndex)-2]: ************POSSIBLE BUG***** JUST TRYING OUT # While not yet reached the end timestamp AND not yet caught up to present AND not yet reached the end of the data # execute the existing orders, then run the strategy and add the new orders beforeExec=time.clock() self.execute() afterExec= time.clock() # self.addOrders(self.strategy(self.portfolio,self.position,self.currTimestamp,self.strategyData)) # self.addOrders(optimizer.execute(self.portfolio,self.position,self.currTimestamp,self.strategyData)) beforeAddOrders= time.clock() self.addOrders(optimizer.execute(self.portfolio,self.position,self.currTimestamp,self.strategyData, self.dataAccess)) afterAddOrders= time.clock() if noisy or timersActive: print '' #newline if mtm: #portValue = self.portfolio.currCash + self.strategyData.calculatePortValue(self.portfolio.currStocks,self.currTimestamp) portValue= float (0.0) print "| %i %.2f |"%(self.currTimestamp,portValue) + " Value from portfolio class: " + str (self.portfolio.calcPortfolioValue(self.currTimestamp, self.dataAccess)) if timersActive and not noisy: print "Strategy at %i took %.4f secs"%(self.currTimestamp,(time.clock()-cycTime)) i+=1 cycTime = time.clock() if noisy and not timersActive: portValue = (self.portfolio.calcPortfolioValue(self.currTimestamp, self.dataAccess)) #self.portfolio.currCash + self.strategyData.calculatePortValue(self.portfolio.currStocks,self.currTimestamp) portfolioValList.append(portValue) print "Strategy at %d completed successfully." % self.currTimestamp print "Current cash: " + str(self.portfolio.currCash) print "Current stocks: %s."%self.portfolio.currStocks print "Current portfolio value: "+ str(portValue)+"\n\n" #print "Current portfolio value: %.2f.\n\n"%(portValue) if noisy and timersActive: portValue = float (self.portfolio.calcPortfolioValue(self.currTimestamp, self.dataAccess)) #self.portfolio.currCash + self.strategyData.calculatePortValue(self.portfolio.currStocks,self.currTimestamp) portfolioValList.append(portValue) print "Strategy at %i took %.4f secs"%(self.currTimestamp,(time.clock()-cycTime)) print "Exec function took: " + str(afterExec - beforeExec) print "Time for addorders: " + str(afterAddOrders - beforeAddOrders) print "Strategy at %d completed successfully." % self.currTimestamp #print "Current cash: %.2f."%(self.portfolio.currCash) print "Current cash: " + str(self.portfolio.currCash) print "Current stocks: %s."%self.portfolio.currStocks #print "Current portfolio value: %.2f.\n\n"%(portValue) print "Current portfolio value: "+ str(portValue)+"\n\n" i+=1 cycTime = time.clock() #self.currTimestamp += self.interval -- Unfortunately this does not work becuase of daylight saving time complications ctr+=1 self.currTimestamp= timestamps[ctr] #self.strategyData.currTimestamp = self.currTimestamp if noisy: print "Simulation complete." if timersActive: print "Simulation complete in %i seconds."%(time.time() - totalTime) self.portfolio.close() self.position.close() self.order.close() #self.strategyData.close() #plotting the portfolio value fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) ax.plot (portfolioValList) ax.set_title('Portfolio value') ax.grid(True) ax.set_xlabel('time') ax.set_ylabel('$') canvas.print_figure('portfolio')
[ "def", "run", "(", "self", ")", ":", "optimizer", "=", "Optimizer", ".", "Optimizer", "(", "self", ".", "listOfStocks", ")", "#optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks)", "timestamps", "=", "list", "(", "self", ".", "dataAccess", ".", "getTimesta...
https://github.com/tuckerbalch/QSTK/blob/4981506c37227a72404229d5e1e0887f797a5d57/Legacy/simulator/Simulator.py#L661-L777
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/google_ads_service/client.py
python
GoogleAdsServiceClient.parse_keyword_plan_ad_group_keyword_path
(path: str)
return m.groupdict() if m else {}
Parse a keyword_plan_ad_group_keyword path into its component segments.
Parse a keyword_plan_ad_group_keyword path into its component segments.
[ "Parse", "a", "keyword_plan_ad_group_keyword", "path", "into", "its", "component", "segments", "." ]
def parse_keyword_plan_ad_group_keyword_path(path: str) -> Dict[str, str]: """Parse a keyword_plan_ad_group_keyword path into its component segments.""" m = re.match( r"^customers/(?P<customer_id>.+?)/keywordPlanAdGroupKeywords/(?P<keyword_plan_ad_group_keyword_id>.+?)$", path, ) return m.groupdict() if m else {}
[ "def", "parse_keyword_plan_ad_group_keyword_path", "(", "path", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "m", "=", "re", ".", "match", "(", "r\"^customers/(?P<customer_id>.+?)/keywordPlanAdGroupKeywords/(?P<keyword_plan_ad_group_keyword_id>.+?)$\"", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/google_ads_service/client.py#L1927-L1933
clalancette/oz
1ab43e88033efa774815c6ebb59ae2841f2980e9
oz/Windows.py
python
Windows_v5._generate_new_iso
(self)
Method to create a new ISO based on the modified CD/DVD.
Method to create a new ISO based on the modified CD/DVD.
[ "Method", "to", "create", "a", "new", "ISO", "based", "on", "the", "modified", "CD", "/", "DVD", "." ]
def _generate_new_iso(self): """ Method to create a new ISO based on the modified CD/DVD. """ self.log.debug("Generating new ISO") oz.ozutil.subprocess_check_output(["genisoimage", "-b", "cdboot/boot.bin", "-no-emul-boot", "-boot-load-seg", "1984", "-boot-load-size", "4", "-iso-level", "2", "-J", "-l", "-D", "-N", "-joliet-long", "-relaxed-filenames", "-v", "-V", "Custom", "-o", self.output_iso, self.iso_contents], printfn=self.log.debug)
[ "def", "_generate_new_iso", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Generating new ISO\"", ")", "oz", ".", "ozutil", ".", "subprocess_check_output", "(", "[", "\"genisoimage\"", ",", "\"-b\"", ",", "\"cdboot/boot.bin\"", ",", "\"-no-emul...
https://github.com/clalancette/oz/blob/1ab43e88033efa774815c6ebb59ae2841f2980e9/oz/Windows.py#L64-L79
ninja-ide/ninja-ide
87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0
ninja_ide/gui/editor/base_editor.py
python
BaseEditor._update_visible_blocks
(self)
Updates the list of visible blocks
Updates the list of visible blocks
[ "Updates", "the", "list", "of", "visible", "blocks" ]
def _update_visible_blocks(self): """Updates the list of visible blocks""" self.__visible_blocks.clear() append = self.__visible_blocks.append block = self.firstVisibleBlock() block_number = block.blockNumber() top = self.blockBoundingGeometry(block).translated( self.contentOffset()).top() bottom = top + self.blockBoundingRect(block).height() editor_height = self.height() while block.isValid(): visible = bottom <= editor_height if not visible: break if block.isVisible(): append((top, block_number, block)) block = block.next() top = bottom bottom = top + self.blockBoundingRect(block).height() block_number += 1
[ "def", "_update_visible_blocks", "(", "self", ")", ":", "self", ".", "__visible_blocks", ".", "clear", "(", ")", "append", "=", "self", ".", "__visible_blocks", ".", "append", "block", "=", "self", ".", "firstVisibleBlock", "(", ")", "block_number", "=", "bl...
https://github.com/ninja-ide/ninja-ide/blob/87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0/ninja_ide/gui/editor/base_editor.py#L116-L137
opendatateam/udata
a295cab3c0e8f086fea1853655011f361ac81b77
udata/core/user/commands.py
python
create
()
Create a new user
Create a new user
[ "Create", "a", "new", "user" ]
def create(): '''Create a new user''' data = { 'first_name': click.prompt('First name'), 'last_name': click.prompt('Last name'), 'email': click.prompt('Email'), 'password': click.prompt('Password', hide_input=True), 'password_confirm': click.prompt('Confirm Password', hide_input=True), } # Until https://github.com/mattupstate/flask-security/issues/672 is fixed with current_app.test_request_context(): form = RegisterForm(MultiDict(data), meta={'csrf': False}) if form.validate(): data['password'] = encrypt_password(data['password']) del data['password_confirm'] data['confirmed_at'] = datetime.utcnow() user = datastore.create_user(**data) success('User(id={u.id} email={u.email}) created'.format(u=user)) return user errors = '\n'.join('\n'.join([str(m) for m in e]) for e in form.errors.values()) exit_with_error('Error creating user', errors)
[ "def", "create", "(", ")", ":", "data", "=", "{", "'first_name'", ":", "click", ".", "prompt", "(", "'First name'", ")", ",", "'last_name'", ":", "click", ".", "prompt", "(", "'Last name'", ")", ",", "'email'", ":", "click", ".", "prompt", "(", "'Email...
https://github.com/opendatateam/udata/blob/a295cab3c0e8f086fea1853655011f361ac81b77/udata/core/user/commands.py#L24-L44
OUCMachineLearning/OUCML
5b54337d7c0316084cb1a74befda2bba96137d4a
One_Day_One_GAN/day4/acgan/acgan.py
python
ACGAN.save_model
(self)
[]
def save_model(self): def save(model, model_name): model_path = "saved_model/%s.json" % model_name weights_path = "saved_model/%s_weights.hdf5" % model_name options = {"file_arch": model_path, "file_weight": weights_path} json_string = model.to_json() open(options['file_arch'], 'w').write(json_string) model.save_weights(options['file_weight']) save(self.generator, "generator") save(self.discriminator, "discriminator")
[ "def", "save_model", "(", "self", ")", ":", "def", "save", "(", "model", ",", "model_name", ")", ":", "model_path", "=", "\"saved_model/%s.json\"", "%", "model_name", "weights_path", "=", "\"saved_model/%s_weights.hdf5\"", "%", "model_name", "options", "=", "{", ...
https://github.com/OUCMachineLearning/OUCML/blob/5b54337d7c0316084cb1a74befda2bba96137d4a/One_Day_One_GAN/day4/acgan/acgan.py#L195-L207
facebookresearch/ParlAI
e4d59c30eef44f1f67105961b82a83fd28d7d78b
parlai/chat_service/services/messenger/messenger_manager.py
python
MessengerManager.__init__
(self, opt)
Create an MessengerManager using the given setup options.
Create an MessengerManager using the given setup options.
[ "Create", "an", "MessengerManager", "using", "the", "given", "setup", "options", "." ]
def __init__(self, opt): """ Create an MessengerManager using the given setup options. """ # Manager attributes super().__init__(opt) self._init_logs() # Read in Config self._parse_config(opt) self._complete_setup()
[ "def", "__init__", "(", "self", ",", "opt", ")", ":", "# Manager attributes", "super", "(", ")", ".", "__init__", "(", "opt", ")", "self", ".", "_init_logs", "(", ")", "# Read in Config", "self", ".", "_parse_config", "(", "opt", ")", "self", ".", "_comp...
https://github.com/facebookresearch/ParlAI/blob/e4d59c30eef44f1f67105961b82a83fd28d7d78b/parlai/chat_service/services/messenger/messenger_manager.py#L33-L43
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/treebeard/mp_tree.py
python
MP_ComplexAddMoveHandler.get_sql_newpath_in_branches
(self, oldpath, newpath)
return sql, vals
:returns: The sql needed to move a branch to another position. .. note:: The generated sql will only update the depth values if needed.
:returns: The sql needed to move a branch to another position.
[ ":", "returns", ":", "The", "sql", "needed", "to", "move", "a", "branch", "to", "another", "position", "." ]
def get_sql_newpath_in_branches(self, oldpath, newpath): """ :returns: The sql needed to move a branch to another position. .. note:: The generated sql will only update the depth values if needed. """ vendor = self.node_cls.get_database_vendor('write') sql1 = "UPDATE %s SET" % ( connection.ops.quote_name( get_result_class(self.node_cls)._meta.db_table), ) # <3 "standard" sql if vendor == 'sqlite': # I know that the third argument in SUBSTR (LENGTH(path)) is # awful, but sqlite fails without it: # OperationalError: wrong number of arguments to function substr() # even when the documentation says that 2 arguments are valid: # http://www.sqlite.org/lang_corefunc.html sqlpath = "%s||SUBSTR(path, %s, LENGTH(path))" elif vendor == 'mysql': # hooray for mysql ignoring standards in their default # configuration! # to make || work as it should, enable ansi mode # http://dev.mysql.com/doc/refman/5.0/en/ansi-mode.html sqlpath = "CONCAT(%s, SUBSTR(path, %s))" else: sqlpath = sql_concat("%s", sql_substr("path", "%s", vendor=vendor), vendor=vendor) sql2 = ["path=%s" % (sqlpath, )] vals = [newpath, len(oldpath) + 1] if len(oldpath) != len(newpath) and vendor != 'mysql': # when using mysql, this won't update the depth and it has to be # done in another query # doesn't even work with sql_mode='ANSI,TRADITIONAL' # TODO: FIND OUT WHY?!?? right now I'm just blaming mysql sql2.append(("depth=" + sql_length("%s", vendor=vendor) + "/%%s") % (sqlpath, )) vals.extend([newpath, len(oldpath) + 1, self.node_cls.steplen]) sql3 = "WHERE path LIKE %s" vals.extend([oldpath + '%']) sql = '%s %s %s' % (sql1, ', '.join(sql2), sql3) return sql, vals
[ "def", "get_sql_newpath_in_branches", "(", "self", ",", "oldpath", ",", "newpath", ")", ":", "vendor", "=", "self", ".", "node_cls", ".", "get_database_vendor", "(", "'write'", ")", "sql1", "=", "\"UPDATE %s SET\"", "%", "(", "connection", ".", "ops", ".", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/treebeard/mp_tree.py#L262-L306
pytrainer/pytrainer
66f3e2b30b48c66e03111248faffc43b8e31c583
pytrainer/main.py
python
pyTrainer.set_logging_level
(self, level)
Set level of information written to log
Set level of information written to log
[ "Set", "level", "of", "information", "written", "to", "log" ]
def set_logging_level(self, level): '''Set level of information written to log''' logging.debug("Setting logger to level: %s", level) logging.getLogger('').setLevel(level) logging.getLogger('sqlalchemy.engine').setLevel(level)
[ "def", "set_logging_level", "(", "self", ",", "level", ")", ":", "logging", ".", "debug", "(", "\"Setting logger to level: %s\"", ",", "level", ")", "logging", ".", "getLogger", "(", "''", ")", ".", "setLevel", "(", "level", ")", "logging", ".", "getLogger",...
https://github.com/pytrainer/pytrainer/blob/66f3e2b30b48c66e03111248faffc43b8e31c583/pytrainer/main.py#L158-L162
kivymd/KivyMD
1cb82f7d2437770f71be7c5a4f7de4b8da61f352
kivymd/uix/snackbar/snackbar.py
python
BaseSnackbar.on_open
(self, *args)
Called when a dialog is opened.
Called when a dialog is opened.
[ "Called", "when", "a", "dialog", "is", "opened", "." ]
def on_open(self, *args): """Called when a dialog is opened."""
[ "def", "on_open", "(", "self", ",", "*", "args", ")", ":" ]
https://github.com/kivymd/KivyMD/blob/1cb82f7d2437770f71be7c5a4f7de4b8da61f352/kivymd/uix/snackbar/snackbar.py#L493-L494
explosion/spaCy
a784b12eff48df9281b184cb7005e66bbd2e3aca
spacy/cli/project/run.py
python
validate_subcommand
( commands: Sequence[str], workflows: Sequence[str], subcommand: str )
Check that a subcommand is valid and defined. Raises an error otherwise. commands (Sequence[str]): The available commands. subcommand (str): The subcommand.
Check that a subcommand is valid and defined. Raises an error otherwise.
[ "Check", "that", "a", "subcommand", "is", "valid", "and", "defined", ".", "Raises", "an", "error", "otherwise", "." ]
def validate_subcommand( commands: Sequence[str], workflows: Sequence[str], subcommand: str ) -> None: """Check that a subcommand is valid and defined. Raises an error otherwise. commands (Sequence[str]): The available commands. subcommand (str): The subcommand. """ if not commands and not workflows: msg.fail(f"No commands or workflows defined in {PROJECT_FILE}", exits=1) if subcommand not in commands and subcommand not in workflows: help_msg = [] if commands: help_msg.append(f"Available commands: {', '.join(commands)}") if workflows: help_msg.append(f"Available workflows: {', '.join(workflows)}") msg.fail( f"Can't find command or workflow '{subcommand}' in {PROJECT_FILE}", ". ".join(help_msg), exits=1, )
[ "def", "validate_subcommand", "(", "commands", ":", "Sequence", "[", "str", "]", ",", "workflows", ":", "Sequence", "[", "str", "]", ",", "subcommand", ":", "str", ")", "->", "None", ":", "if", "not", "commands", "and", "not", "workflows", ":", "msg", ...
https://github.com/explosion/spaCy/blob/a784b12eff48df9281b184cb7005e66bbd2e3aca/spacy/cli/project/run.py#L186-L206
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txweb2/resource.py
python
WrapperResource.getChild
(self, name)
return self.resource.getChild(name)
[]
def getChild(self, name): return self.resource.getChild(name)
[ "def", "getChild", "(", "self", ",", "name", ")", ":", "return", "self", ".", "resource", ".", "getChild", "(", "name", ")" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txweb2/resource.py#L354-L355
ethereum/web3.py
6a90a26ea12e5a789834c9cd6a7ae6d302648f88
ethpm/package.py
python
Package.contract_types
(self)
All contract types included in this package.
All contract types included in this package.
[ "All", "contract", "types", "included", "in", "this", "package", "." ]
def contract_types(self) -> List[str]: """ All contract types included in this package. """ if 'contractTypes' in self.manifest: return sorted(self.manifest['contractTypes'].keys()) else: raise ValueError("No contract types found in manifest; {self.__repr__()}.")
[ "def", "contract_types", "(", "self", ")", "->", "List", "[", "str", "]", ":", "if", "'contractTypes'", "in", "self", ".", "manifest", ":", "return", "sorted", "(", "self", ".", "manifest", "[", "'contractTypes'", "]", ".", "keys", "(", ")", ")", "else...
https://github.com/ethereum/web3.py/blob/6a90a26ea12e5a789834c9cd6a7ae6d302648f88/ethpm/package.py#L194-L201
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/layouts.py
python
grid
(children=[], sizing_mode=None, nrows=None, ncols=None)
return grid
Conveniently create a grid of layoutable objects. Grids are created by using ``GridBox`` model. This gives the most control over the layout of a grid, but is also tedious and may result in unreadable code in practical applications. ``grid()`` function remedies this by reducing the level of control, but in turn providing a more convenient API. Supported patterns: 1. Nested lists of layoutable objects. Assumes the top-level list represents a column and alternates between rows and columns in subsequent nesting levels. One can use ``None`` for padding purpose. >>> grid([p1, [[p2, p3], p4]]) GridBox(children=[ (p1, 0, 0, 1, 2), (p2, 1, 0, 1, 1), (p3, 2, 0, 1, 1), (p4, 1, 1, 2, 1), ]) 2. Nested ``Row`` and ``Column`` instances. Similar to the first pattern, just instead of using nested lists, it uses nested ``Row`` and ``Column`` models. This can be much more readable that the former. Note, however, that only models that don't have ``sizing_mode`` set are used. >>> grid(column(p1, row(column(p2, p3), p4))) GridBox(children=[ (p1, 0, 0, 1, 2), (p2, 1, 0, 1, 1), (p3, 2, 0, 1, 1), (p4, 1, 1, 2, 1), ]) 3. Flat list of layoutable objects. This requires ``nrows`` and/or ``ncols`` to be set. The input list will be rearranged into a 2D array accordingly. One can use ``None`` for padding purpose. >>> grid([p1, p2, p3, p4], ncols=2) GridBox(children=[ (p1, 0, 0, 1, 1), (p2, 0, 1, 1, 1), (p3, 1, 0, 1, 1), (p4, 1, 1, 1, 1), ])
Conveniently create a grid of layoutable objects.
[ "Conveniently", "create", "a", "grid", "of", "layoutable", "objects", "." ]
def grid(children=[], sizing_mode=None, nrows=None, ncols=None): """ Conveniently create a grid of layoutable objects. Grids are created by using ``GridBox`` model. This gives the most control over the layout of a grid, but is also tedious and may result in unreadable code in practical applications. ``grid()`` function remedies this by reducing the level of control, but in turn providing a more convenient API. Supported patterns: 1. Nested lists of layoutable objects. Assumes the top-level list represents a column and alternates between rows and columns in subsequent nesting levels. One can use ``None`` for padding purpose. >>> grid([p1, [[p2, p3], p4]]) GridBox(children=[ (p1, 0, 0, 1, 2), (p2, 1, 0, 1, 1), (p3, 2, 0, 1, 1), (p4, 1, 1, 2, 1), ]) 2. Nested ``Row`` and ``Column`` instances. Similar to the first pattern, just instead of using nested lists, it uses nested ``Row`` and ``Column`` models. This can be much more readable that the former. Note, however, that only models that don't have ``sizing_mode`` set are used. >>> grid(column(p1, row(column(p2, p3), p4))) GridBox(children=[ (p1, 0, 0, 1, 2), (p2, 1, 0, 1, 1), (p3, 2, 0, 1, 1), (p4, 1, 1, 2, 1), ]) 3. Flat list of layoutable objects. This requires ``nrows`` and/or ``ncols`` to be set. The input list will be rearranged into a 2D array accordingly. One can use ``None`` for padding purpose. >>> grid([p1, p2, p3, p4], ncols=2) GridBox(children=[ (p1, 0, 0, 1, 1), (p2, 0, 1, 1, 1), (p3, 1, 0, 1, 1), (p4, 1, 1, 1, 1), ]) """ row = namedtuple("row", ["children"]) col = namedtuple("col", ["children"]) def flatten(layout): Item = namedtuple("Item", ["layout", "r0", "c0", "r1", "c1"]) Grid = namedtuple("Grid", ["nrows", "ncols", "items"]) def gcd(a, b): a, b = abs(a), abs(b) while b != 0: a, b = b, a % b return a def lcm(a, *rest): for b in rest: a = (a*b) // gcd(a, b) return a nonempty = lambda child: child.nrows != 0 and child.ncols != 0 def _flatten(layout): if isinstance(layout, row): children = list(filter(nonempty, map(_flatten, layout.children))) if not children: return Grid(0, 0, []) nrows = lcm(*[ child.nrows for child in children ]) ncols = sum([ child.ncols for child in children ]) items = [] offset = 0 for child in children: factor = nrows//child.nrows for (layout, r0, c0, r1, c1) in child.items: items.append((layout, factor*r0, c0 + offset, factor*r1, c1 + offset)) offset += child.ncols return Grid(nrows, ncols, items) elif isinstance(layout, col): children = list(filter(nonempty, map(_flatten, layout.children))) if not children: return Grid(0, 0, []) nrows = sum([ child.nrows for child in children ]) ncols = lcm(*[ child.ncols for child in children ]) items = [] offset = 0 for child in children: factor = ncols//child.ncols for (layout, r0, c0, r1, c1) in child.items: items.append((layout, r0 + offset, factor*c0, r1 + offset, factor*c1)) offset += child.nrows return Grid(nrows, ncols, items) else: return Grid(1, 1, [Item(layout, 0, 0, 1, 1)]) grid = _flatten(layout) children = [] for (layout, r0, c0, r1, c1) in grid.items: if layout is not None: children.append((layout, r0, c0, r1 - r0, c1 - c0)) return GridBox(children=children) if isinstance(children, list): if nrows is not None or ncols is not None: N = len(children) if ncols is None: ncols = math.ceil(N/nrows) layout = col([ row(children[i:i+ncols]) for i in range(0, N, ncols) ]) else: def traverse(children, level=0): if isinstance(children, list): container = col if level % 2 == 0 else row return container([ traverse(child, level+1) for child in children ]) else: return children layout = traverse(children) elif isinstance(children, LayoutDOM): def is_usable(child): return _has_auto_sizing(child) and child.spacing == 0 def traverse(item, top_level=False): if isinstance(item, Box) and (top_level or is_usable(item)): container = col if isinstance(item, Column) else row return container(list(map(traverse, item.children))) else: return item layout = traverse(children, top_level=True) elif isinstance(children, string_types): raise NotImplementedError else: raise ValueError("expected a list, string or model") grid = flatten(layout) if sizing_mode is not None: grid.sizing_mode = sizing_mode for child in grid.children: layout = child[0] if _has_auto_sizing(layout): layout.sizing_mode = sizing_mode return grid
[ "def", "grid", "(", "children", "=", "[", "]", ",", "sizing_mode", "=", "None", ",", "nrows", "=", "None", ",", "ncols", "=", "None", ")", ":", "row", "=", "namedtuple", "(", "\"row\"", ",", "[", "\"children\"", "]", ")", "col", "=", "namedtuple", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/layouts.py#L342-L504
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_scale.py
python
Yedit.parse_value
(inc_value, vtype='')
return inc_value
determine value type passed
determine value type passed
[ "determine", "value", "type", "passed" ]
def parse_value(inc_value, vtype=''): '''determine value type passed''' true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON', ] false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF'] # It came in as a string but you didn't specify value_type as string # we will convert to bool if it matches any of the above cases if isinstance(inc_value, str) and 'bool' in vtype: if inc_value not in true_bools and inc_value not in false_bools: raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype)) elif isinstance(inc_value, bool) and 'str' in vtype: inc_value = str(inc_value) # There is a special case where '' will turn into None after yaml loading it so skip if isinstance(inc_value, str) and inc_value == '': pass # If vtype is not str then go ahead and attempt to yaml load it. elif isinstance(inc_value, str) and 'str' not in vtype: try: inc_value = yaml.safe_load(inc_value) except Exception: raise YeditException('Could not determine type of incoming value. ' + 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype)) return inc_value
[ "def", "parse_value", "(", "inc_value", ",", "vtype", "=", "''", ")", ":", "true_bools", "=", "[", "'y'", ",", "'Y'", ",", "'yes'", ",", "'Yes'", ",", "'YES'", ",", "'true'", ",", "'True'", ",", "'TRUE'", ",", "'on'", ",", "'On'", ",", "'ON'", ",",...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_scale.py#L671-L697
cortex-lab/phy
9a330b9437a3d0b40a37a201d147224e6e7fb462
phy/cluster/views/raster.py
python
RasterView._get_box_index
(self)
return _index_of(cl, self.all_cluster_ids)
Return, for every spike, its row in the raster plot. This depends on the ordering in self.cluster_ids.
Return, for every spike, its row in the raster plot. This depends on the ordering in self.cluster_ids.
[ "Return", "for", "every", "spike", "its", "row", "in", "the", "raster", "plot", ".", "This", "depends", "on", "the", "ordering", "in", "self", ".", "cluster_ids", "." ]
def _get_box_index(self): """Return, for every spike, its row in the raster plot. This depends on the ordering in self.cluster_ids.""" cl = self.spike_clusters[self.spike_ids] # Sanity check. # assert np.all(np.in1d(cl, self.cluster_ids)) return _index_of(cl, self.all_cluster_ids)
[ "def", "_get_box_index", "(", "self", ")", ":", "cl", "=", "self", ".", "spike_clusters", "[", "self", ".", "spike_ids", "]", "# Sanity check.", "# assert np.all(np.in1d(cl, self.cluster_ids))", "return", "_index_of", "(", "cl", ",", "self", ".", "all_cluster_ids", ...
https://github.com/cortex-lab/phy/blob/9a330b9437a3d0b40a37a201d147224e6e7fb462/phy/cluster/views/raster.py#L112-L118
etsy/logster
a24249886391a8b885d21c882f6fcaa95e29b015
logster/parsers/JsonLogster.py
python
JsonLogster.parse_line
(self, line)
This function should digest the contents of one line at a time, updating object's state variables. Takes a single argument, the line to be parsed.
This function should digest the contents of one line at a time, updating object's state variables. Takes a single argument, the line to be parsed.
[ "This", "function", "should", "digest", "the", "contents", "of", "one", "line", "at", "a", "time", "updating", "object", "s", "state", "variables", ".", "Takes", "a", "single", "argument", "the", "line", "to", "be", "parsed", "." ]
def parse_line(self, line): '''This function should digest the contents of one line at a time, updating object's state variables. Takes a single argument, the line to be parsed.''' try: json_data = json.loads(line) except Exception as e: raise LogsterParsingException("{0} - {1}".format(type(e), e)) self.metrics = self.flatten_object(json.loads(line), self.key_separator, self.key_filter)
[ "def", "parse_line", "(", "self", ",", "line", ")", ":", "try", ":", "json_data", "=", "json", ".", "loads", "(", "line", ")", "except", "Exception", "as", "e", ":", "raise", "LogsterParsingException", "(", "\"{0} - {1}\"", ".", "format", "(", "type", "(...
https://github.com/etsy/logster/blob/a24249886391a8b885d21c882f6fcaa95e29b015/logster/parsers/JsonLogster.py#L88-L96
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_process.py
python
OpenShiftCLI._replace
(self, fname, force=False)
return self.openshift_cmd(cmd)
replace the current object with oc replace
replace the current object with oc replace
[ "replace", "the", "current", "object", "with", "oc", "replace" ]
def _replace(self, fname, force=False): '''replace the current object with oc replace''' # We are removing the 'resourceVersion' to handle # a race condition when modifying oc objects yed = Yedit(fname) results = yed.delete('metadata.resourceVersion') if results[0]: yed.write() cmd = ['replace', '-f', fname] if force: cmd.append('--force') return self.openshift_cmd(cmd)
[ "def", "_replace", "(", "self", ",", "fname", ",", "force", "=", "False", ")", ":", "# We are removing the 'resourceVersion' to handle", "# a race condition when modifying oc objects", "yed", "=", "Yedit", "(", "fname", ")", "results", "=", "yed", ".", "delete", "("...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_process.py#L931-L943
django-nonrel/django-nonrel
4fbfe7344481a5eab8698f79207f09124310131b
django/contrib/gis/geos/prototypes/errcheck.py
python
check_predicate
(result, func, cargs)
Error checking for unary/binary predicate functions.
Error checking for unary/binary predicate functions.
[ "Error", "checking", "for", "unary", "/", "binary", "predicate", "functions", "." ]
def check_predicate(result, func, cargs): "Error checking for unary/binary predicate functions." val = ord(result) # getting the ordinal from the character if val == 1: return True elif val == 0: return False else: raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__)
[ "def", "check_predicate", "(", "result", ",", "func", ",", "cargs", ")", ":", "val", "=", "ord", "(", "result", ")", "# getting the ordinal from the character", "if", "val", "==", "1", ":", "return", "True", "elif", "val", "==", "0", ":", "return", "False"...
https://github.com/django-nonrel/django-nonrel/blob/4fbfe7344481a5eab8698f79207f09124310131b/django/contrib/gis/geos/prototypes/errcheck.py#L53-L59
plaid/plaid-python
8c60fca608e426f3ff30da8857775946d29e122c
plaid/model/transfer_status.py
python
TransferStatus.openapi_types
()
return { 'value': (str,), }
This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type.
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ return { 'value': (str,), }
[ "def", "openapi_types", "(", ")", ":", "return", "{", "'value'", ":", "(", "str", ",", ")", ",", "}" ]
https://github.com/plaid/plaid-python/blob/8c60fca608e426f3ff30da8857775946d29e122c/plaid/model/transfer_status.py#L66-L77
martinRenou/ipycanvas
53348e3f63153fc80459c9f1e76ce73dc75dcd49
ipycanvas/canvas.py
python
Canvas.fill_rects
(self, x, y, width, height=None)
Draw filled rectangles of sizes ``(width, height)`` at the ``(x, y)`` positions. Where ``x``, ``y``, ``width`` and ``height`` arguments are NumPy arrays, lists or scalar values. If ``height`` is None, it is set to the same value as width.
Draw filled rectangles of sizes ``(width, height)`` at the ``(x, y)`` positions.
[ "Draw", "filled", "rectangles", "of", "sizes", "(", "width", "height", ")", "at", "the", "(", "x", "y", ")", "positions", "." ]
def fill_rects(self, x, y, width, height=None): """Draw filled rectangles of sizes ``(width, height)`` at the ``(x, y)`` positions. Where ``x``, ``y``, ``width`` and ``height`` arguments are NumPy arrays, lists or scalar values. If ``height`` is None, it is set to the same value as width. """ args = [] buffers = [] populate_args(x, args, buffers) populate_args(y, args, buffers) populate_args(width, args, buffers) if height is None: args.append(args[-1]) else: populate_args(height, args, buffers) self._send_canvas_command(COMMANDS['fillRects'], args, buffers)
[ "def", "fill_rects", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", "=", "None", ")", ":", "args", "=", "[", "]", "buffers", "=", "[", "]", "populate_args", "(", "x", ",", "args", ",", "buffers", ")", "populate_args", "(", "y", ","...
https://github.com/martinRenou/ipycanvas/blob/53348e3f63153fc80459c9f1e76ce73dc75dcd49/ipycanvas/canvas.py#L482-L500
gnome-terminator/terminator
ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1
terminatorlib/util.py
python
shell_lookup
()
Find an appropriate shell for the user
Find an appropriate shell for the user
[ "Find", "an", "appropriate", "shell", "for", "the", "user" ]
def shell_lookup(): """Find an appropriate shell for the user""" try: usershell = pwd.getpwuid(os.getuid())[6] except KeyError: usershell = None shells = [usershell, 'bash', 'zsh', 'tcsh', 'ksh', 'csh', 'sh'] for shell in shells: if shell is None: continue elif os.path.isfile(shell): return(shell) else: rshell = path_lookup(shell) if rshell is not None: dbg('shell_lookup: Found %s at %s' % (shell, rshell)) return(rshell) dbg('shell_lookup: Unable to locate a shell')
[ "def", "shell_lookup", "(", ")", ":", "try", ":", "usershell", "=", "pwd", ".", "getpwuid", "(", "os", ".", "getuid", "(", ")", ")", "[", "6", "]", "except", "KeyError", ":", "usershell", "=", "None", "shells", "=", "[", "usershell", ",", "'bash'", ...
https://github.com/gnome-terminator/terminator/blob/ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1/terminatorlib/util.py#L145-L163
GoogleChrome/chromium-dashboard
7ef9184080fc4cdf11efbe29dba27f95f07a20d9
internals/notifier.py
python
accumulate_reasons
(addr_reasons, user_list, reason)
Add a reason string for each user.
Add a reason string for each user.
[ "Add", "a", "reason", "string", "for", "each", "user", "." ]
def accumulate_reasons(addr_reasons, user_list, reason): """Add a reason string for each user.""" for user in user_list: if type(user) == str: addr_reasons[user].append(reason) else: addr_reasons[user.email].append(reason)
[ "def", "accumulate_reasons", "(", "addr_reasons", ",", "user_list", ",", "reason", ")", ":", "for", "user", "in", "user_list", ":", "if", "type", "(", "user", ")", "==", "str", ":", "addr_reasons", "[", "user", "]", ".", "append", "(", "reason", ")", "...
https://github.com/GoogleChrome/chromium-dashboard/blob/7ef9184080fc4cdf11efbe29dba27f95f07a20d9/internals/notifier.py#L77-L83
zhang-can/ECO-pytorch
355c3866b35cdaa5d451263c1f3291c150e22eeb
tf_model_zoo/models/neural_gpu/neural_gpu.py
python
sigmoid_cutoff
(x, cutoff)
return tf.minimum(1.0, tf.maximum(0.0, cutoff * y - d))
Sigmoid with cutoff, e.g., 1.2sigmoid(x) - 0.1.
Sigmoid with cutoff, e.g., 1.2sigmoid(x) - 0.1.
[ "Sigmoid", "with", "cutoff", "e", ".", "g", ".", "1", ".", "2sigmoid", "(", "x", ")", "-", "0", ".", "1", "." ]
def sigmoid_cutoff(x, cutoff): """Sigmoid with cutoff, e.g., 1.2sigmoid(x) - 0.1.""" y = tf.sigmoid(x) if cutoff < 1.01: return y d = (cutoff - 1.0) / 2.0 return tf.minimum(1.0, tf.maximum(0.0, cutoff * y - d))
[ "def", "sigmoid_cutoff", "(", "x", ",", "cutoff", ")", ":", "y", "=", "tf", ".", "sigmoid", "(", "x", ")", "if", "cutoff", "<", "1.01", ":", "return", "y", "d", "=", "(", "cutoff", "-", "1.0", ")", "/", "2.0", "return", "tf", ".", "minimum", "(...
https://github.com/zhang-can/ECO-pytorch/blob/355c3866b35cdaa5d451263c1f3291c150e22eeb/tf_model_zoo/models/neural_gpu/neural_gpu.py#L41-L46
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/ttLib/tables/otConverters.py
python
UShort.readArray
(self, reader, font, tableDict, count)
return reader.readUShortArray(count)
[]
def readArray(self, reader, font, tableDict, count): return reader.readUShortArray(count)
[ "def", "readArray", "(", "self", ",", "reader", ",", "font", ",", "tableDict", ",", "count", ")", ":", "return", "reader", ".", "readUShortArray", "(", "count", ")" ]
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/ttLib/tables/otConverters.py#L290-L291
dagwieers/mrepo
a55cbc737d8bade92070d38e4dbb9a24be4b477f
up2date_client/rpmUtils.py
python
checkHeaderForFileConfigExcludes
(h,package,ts)
[]
def checkHeaderForFileConfigExcludes(h,package,ts): fflag = 0 cfg = config.initUp2dateConfig() # might as well just do this once... fileNames = h['filenames'] or [] fileMD5s = h['filemd5s'] or [] fileFlags = h['fileflags'] or [] installedHdr = installedHeader(h['name'],ts) if not installedHdr: #throw a fault? should this happen? return None installedFileNames = installedHdr['filenames'] or [] installedFileMD5s = installedHdr['filemd5s'] or [] # print "installedFileMD5s: %s" % installedFileMD5s removedList = [] if cfg["forceInstall"]: return None # shrug, the apt headers dont have this, not much # we can do about it... Kind of odd considering how # paranoid apt is supposed to be about breaking configs... if not fileMD5s: return None if not fileFlags: return None fileSkipList = cfg["fileSkipList"] # bleah, have to use the index here because # of rpm's storing of filenames and their md5sums in parallel lists for f_i in range(len(fileNames)): # code to see if we want to disable this for pattern in fileSkipList: if fnmatch.fnmatch(fileNames[f_i],pattern): # got to get a better string to use here removedList.append((package, "File Name/pattern")) fflag = 1 break # if we found a matching file, no need to # examine the rest in this package if fflag: break configFilesToIgnore = cfg["configFilesToIgnore"] or [] # cfg reads are a little heavier in this code base, so # might as well avoid doing them for every single file noReplaceConfig = cfg["noReplaceConfig"] for f_i in range(len(fileNames)): # Deal with config files if noReplaceConfig: # check for files that are config files, but skips those that # arent going to be replaced anyway # (1 << 4) == rpm.RPMFILE_NOREPLACE if it existed if fileFlags[f_i] & rpm.RPMFILE_CONFIG and not \ fileFlags[f_i] & (1 << 4): if fileNames[f_i] not in configFilesToIgnore: # check if config file and if so, if modified if checkModified(f_i, fileNames, fileMD5s, installedFileNames, installedFileMD5s): removedList.append((package, "Config modified")) fflag = 1 break if fflag: break if len(removedList): return removedList else: return None
[ "def", "checkHeaderForFileConfigExcludes", "(", "h", ",", "package", ",", "ts", ")", ":", "fflag", "=", "0", "cfg", "=", "config", ".", "initUp2dateConfig", "(", ")", "# might as well just do this once...", "fileNames", "=", "h", "[", "'filenames'", "]", "or", ...
https://github.com/dagwieers/mrepo/blob/a55cbc737d8bade92070d38e4dbb9a24be4b477f/up2date_client/rpmUtils.py#L212-L292
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/angrdb/db.py
python
AngrDB.get_info
(session, key)
return db_info.value
Get an information entry from the database. :param session: :param key: :return:
Get an information entry from the database.
[ "Get", "an", "information", "entry", "from", "the", "database", "." ]
def get_info(session, key): """ Get an information entry from the database. :param session: :param key: :return: """ db_info = session.query(DbInformation).filter_by(key=key).scalar() if db_info is None: return None return db_info.value
[ "def", "get_info", "(", "session", ",", "key", ")", ":", "db_info", "=", "session", ".", "query", "(", "DbInformation", ")", ".", "filter_by", "(", "key", "=", "key", ")", ".", "scalar", "(", ")", "if", "db_info", "is", "None", ":", "return", "None",...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/angrdb/db.py#L77-L89
reviewboard/rbtools
b4838a640b458641ffd233093ae65971d0b4d529
rbtools/commands/setup_repo.py
python
SetupRepo._display_rb_repositories
(self, closest_paths, repo_paths)
Display all repositories found for a Review Board server. Args: closest_paths (list of unicode) A list of best-matching repositories from a valid Review Board server. repo_paths (dict) A dictionary containing repository metadata.
Display all repositories found for a Review Board server.
[ "Display", "all", "repositories", "found", "for", "a", "Review", "Board", "server", "." ]
def _display_rb_repositories(self, closest_paths, repo_paths): """Display all repositories found for a Review Board server. Args: closest_paths (list of unicode) A list of best-matching repositories from a valid Review Board server. repo_paths (dict) A dictionary containing repository metadata. """ for i, repo_url in enumerate(closest_paths): repo = repo_paths[repo_url] self.stdout.write( '%(num)d) "%(repo_name)s" (%(repo_url)s)' % { 'num': i + 1, 'repo_name': repo['name'], 'repo_url': repo_url, })
[ "def", "_display_rb_repositories", "(", "self", ",", "closest_paths", ",", "repo_paths", ")", ":", "for", "i", ",", "repo_url", "in", "enumerate", "(", "closest_paths", ")", ":", "repo", "=", "repo_paths", "[", "repo_url", "]", "self", ".", "stdout", ".", ...
https://github.com/reviewboard/rbtools/blob/b4838a640b458641ffd233093ae65971d0b4d529/rbtools/commands/setup_repo.py#L252-L271
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/functions/combinatorial/numbers.py
python
harmonic._eval_rewrite_as_digamma
(self, n, m=1)
return self.rewrite(polygamma)
[]
def _eval_rewrite_as_digamma(self, n, m=1): from sympy.functions.special.gamma_functions import polygamma return self.rewrite(polygamma)
[ "def", "_eval_rewrite_as_digamma", "(", "self", ",", "n", ",", "m", "=", "1", ")", ":", "from", "sympy", ".", "functions", ".", "special", ".", "gamma_functions", "import", "polygamma", "return", "self", ".", "rewrite", "(", "polygamma", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/functions/combinatorial/numbers.py#L595-L597
lohriialo/photoshop-scripting-python
6b97da967a5d0a45e54f7c99631b29773b923f09
api_reference/photoshop_CC_2018.py
python
_PICTFileSaveOptions.__iter__
(self)
return win32com.client.util.Iterator(ob, None)
Return a Python iterator for this object
Return a Python iterator for this object
[ "Return", "a", "Python", "iterator", "for", "this", "object" ]
def __iter__(self): "Return a Python iterator for this object" try: ob = self._oleobj_.InvokeTypes(-4,LCID,3,(13, 10),()) except pythoncom.error: raise TypeError("This object does not support enumeration") return win32com.client.util.Iterator(ob, None)
[ "def", "__iter__", "(", "self", ")", ":", "try", ":", "ob", "=", "self", ".", "_oleobj_", ".", "InvokeTypes", "(", "-", "4", ",", "LCID", ",", "3", ",", "(", "13", ",", "10", ")", ",", "(", ")", ")", "except", "pythoncom", ".", "error", ":", ...
https://github.com/lohriialo/photoshop-scripting-python/blob/6b97da967a5d0a45e54f7c99631b29773b923f09/api_reference/photoshop_CC_2018.py#L5512-L5518
Yelp/py_zipkin
d56d05d8d72f19440d3be8edda80dc4c402a6356
py_zipkin/encoding/protobuf/__init__.py
python
_hex_to_bytes
(hex_id)
Encodes to hexadecimal ids to big-endian binary. :param hex_id: hexadecimal id to encode. :type hex_id: str :return: binary representation. :type: bytes
Encodes to hexadecimal ids to big-endian binary.
[ "Encodes", "to", "hexadecimal", "ids", "to", "big", "-", "endian", "binary", "." ]
def _hex_to_bytes(hex_id): """Encodes to hexadecimal ids to big-endian binary. :param hex_id: hexadecimal id to encode. :type hex_id: str :return: binary representation. :type: bytes """ if len(hex_id) <= 16: int_id = unsigned_hex_to_signed_int(hex_id) return struct.pack(">q", int_id) else: # There's no 16-bytes encoding in Python's struct. So we convert the # id as 2 64 bit ids and then concatenate the result. # NOTE: we count 16 chars from the right (:-16) rather than the left so # that ids with less than 32 chars will be correctly pre-padded with 0s. high_id = unsigned_hex_to_signed_int(hex_id[:-16]) high_bin = struct.pack(">q", high_id) low_id = unsigned_hex_to_signed_int(hex_id[-16:]) low_bin = struct.pack(">q", low_id) return high_bin + low_bin
[ "def", "_hex_to_bytes", "(", "hex_id", ")", ":", "if", "len", "(", "hex_id", ")", "<=", "16", ":", "int_id", "=", "unsigned_hex_to_signed_int", "(", "hex_id", ")", "return", "struct", ".", "pack", "(", "\">q\"", ",", "int_id", ")", "else", ":", "# There'...
https://github.com/Yelp/py_zipkin/blob/d56d05d8d72f19440d3be8edda80dc4c402a6356/py_zipkin/encoding/protobuf/__init__.py#L90-L113
tosher/Mediawiker
81bf97cace59bedcb1668e7830b85c36e014428e
lib/Crypto.osx.x64/Crypto/Cipher/DES3.py
python
adjust_key_parity
(key_in)
return key_out
Set the parity bits in a TDES key. :param key_in: the TDES key whose bits need to be adjusted :type key_in: byte string :returns: a copy of ``key_in``, with the parity bits correctly set :rtype: byte string :raises ValueError: if the TDES key is not 16 or 24 bytes long :raises ValueError: if the TDES key degenerates into Single DES
Set the parity bits in a TDES key.
[ "Set", "the", "parity", "bits", "in", "a", "TDES", "key", "." ]
def adjust_key_parity(key_in): """Set the parity bits in a TDES key. :param key_in: the TDES key whose bits need to be adjusted :type key_in: byte string :returns: a copy of ``key_in``, with the parity bits correctly set :rtype: byte string :raises ValueError: if the TDES key is not 16 or 24 bytes long :raises ValueError: if the TDES key degenerates into Single DES """ def parity_byte(key_byte): parity = 1 for i in range(1, 8): parity ^= (key_byte >> i) & 1 return (key_byte & 0xFE) | parity if len(key_in) not in key_size: raise ValueError("Not a valid TDES key") key_out = b"".join([ bchr(parity_byte(bord(x))) for x in key_in ]) if key_out[:8] == key_out[8:16] or key_out[-16:-8] == key_out[-8:]: raise ValueError("Triple DES key degenerates to single DES") return key_out
[ "def", "adjust_key_parity", "(", "key_in", ")", ":", "def", "parity_byte", "(", "key_byte", ")", ":", "parity", "=", "1", "for", "i", "in", "range", "(", "1", ",", "8", ")", ":", "parity", "^=", "(", "key_byte", ">>", "i", ")", "&", "1", "return", ...
https://github.com/tosher/Mediawiker/blob/81bf97cace59bedcb1668e7830b85c36e014428e/lib/Crypto.osx.x64/Crypto/Cipher/DES3.py#L60-L87
Anaconda-Platform/anaconda-project
df5ec33c12591e6512436d38d36c6132fa2e9618
anaconda_project/project_commands.py
python
ProjectCommand._choose_args_and_shell
(self, environ, extra_args=None)
return (args, shell)
[]
def _choose_args_and_shell(self, environ, extra_args=None): assert extra_args is None or isinstance(extra_args, list) args = None shell = False if not self.supports_http_options and (self.notebook or self.bokeh_app): # drop the http arguments extra_args = _ArgsTransformer().transform_args(extra_args) if self.notebook is not None: path = os.path.join(environ['PROJECT_DIR'], self.notebook) args = ['jupyter-notebook', path] if self.supports_http_options: extra_args = _NotebookArgsTransformer(self).transform_args(extra_args) if self.bokeh_app is not None: path = os.path.join(environ['PROJECT_DIR'], self.bokeh_app) args = ['bokeh', 'serve', path] if self.supports_http_options: extra_args = _BokehArgsTransformer().transform_args(extra_args) if self.args is not None: args = self.args if args is not None: if extra_args is not None: args = args + extra_args return args, False command = self._attributes.get(self._shell_field(), None) if (command is not None) and self.supports_http_options: args = [_append_extra_args_to_command_line(command, extra_args)] shell = True elif command: shell = True args = _TemplateArgsTransformer().parse_and_template(command, environ, extra_args) if args is None: # see conda.misc::launch for what we're copying app_entry = self._attributes.get('conda_app_entry', None) if app_entry is not None: # conda.misc uses plain split and not shlex or # anything like that, we need to match its # interpretation parsed = app_entry.split() args = [] for arg in parsed: if '${PREFIX}' in arg: arg = arg.replace('${PREFIX}', conda_api.environ_get_prefix(environ)) args.append(arg) if extra_args is not None: args = args + extra_args # args can be None if the command doesn't work on our platform return (args, shell)
[ "def", "_choose_args_and_shell", "(", "self", ",", "environ", ",", "extra_args", "=", "None", ")", ":", "assert", "extra_args", "is", "None", "or", "isinstance", "(", "extra_args", ",", "list", ")", "args", "=", "None", "shell", "=", "False", "if", "not", ...
https://github.com/Anaconda-Platform/anaconda-project/blob/df5ec33c12591e6512436d38d36c6132fa2e9618/anaconda_project/project_commands.py#L471-L526
lightkurve/lightkurve
70d1c4cd1ab30f24c83e54bdcea4dd16624bfd9c
src/lightkurve/seismology/core.py
python
Seismology.estimate_deltanu
(self, method="acf2d", numax=None)
return result
Returns the average value of the large frequency spacing, DeltaNu, of the seismic oscillations of the target. At present, the only method supported is based on using an autocorrelation function (ACF2D). This method is implemented by the `~lightkurve.seismology.estimate_deltanu_acf2d` function which requires the parameter `numax`. For details and literature references, please read the detailed docstring of this function by typing ``lightkurve.seismology.estimate_deltanu_acf2d?`` in a Python terminal or notebook. Parameters ---------- method : str Method to use. Only ``"acf2d"`` is supported at this time. Returns ------- deltanu : `~lightkurve.seismology.SeismologyQuantity` DeltaNu of the periodogram, including details on the units and method.
Returns the average value of the large frequency spacing, DeltaNu, of the seismic oscillations of the target.
[ "Returns", "the", "average", "value", "of", "the", "large", "frequency", "spacing", "DeltaNu", "of", "the", "seismic", "oscillations", "of", "the", "target", "." ]
def estimate_deltanu(self, method="acf2d", numax=None): """Returns the average value of the large frequency spacing, DeltaNu, of the seismic oscillations of the target. At present, the only method supported is based on using an autocorrelation function (ACF2D). This method is implemented by the `~lightkurve.seismology.estimate_deltanu_acf2d` function which requires the parameter `numax`. For details and literature references, please read the detailed docstring of this function by typing ``lightkurve.seismology.estimate_deltanu_acf2d?`` in a Python terminal or notebook. Parameters ---------- method : str Method to use. Only ``"acf2d"`` is supported at this time. Returns ------- deltanu : `~lightkurve.seismology.SeismologyQuantity` DeltaNu of the periodogram, including details on the units and method. """ method = validate_method(method, supported_methods=["acf2d"]) numax = self._validate_numax(numax) if method == "acf2d": from .deltanu_estimators import estimate_deltanu_acf2d result = estimate_deltanu_acf2d(self.periodogram, numax=numax) self.deltanu = result return result
[ "def", "estimate_deltanu", "(", "self", ",", "method", "=", "\"acf2d\"", ",", "numax", "=", "None", ")", ":", "method", "=", "validate_method", "(", "method", ",", "supported_methods", "=", "[", "\"acf2d\"", "]", ")", "numax", "=", "self", ".", "_validate_...
https://github.com/lightkurve/lightkurve/blob/70d1c4cd1ab30f24c83e54bdcea4dd16624bfd9c/src/lightkurve/seismology/core.py#L670-L698
google/personfinder
475f4c0ce916036d39bae2d480cde07126550875
app/record_writer.py
python
RecordCsvWriter.__init__
(self, io, fields=None, write_header=True)
Initializer. Args: io (io): CSV is written to this. fields (list of str): A custom list of fields which are written. write_header (bool): Write the header row at the beginning.
Initializer. Args: io (io): CSV is written to this. fields (list of str): A custom list of fields which are written. write_header (bool): Write the header row at the beginning.
[ "Initializer", ".", "Args", ":", "io", "(", "io", ")", ":", "CSV", "is", "written", "to", "this", ".", "fields", "(", "list", "of", "str", ")", ":", "A", "custom", "list", "of", "fields", "which", "are", "written", ".", "write_header", "(", "bool", ...
def __init__(self, io, fields=None, write_header=True): """Initializer. Args: io (io): CSV is written to this. fields (list of str): A custom list of fields which are written. write_header (bool): Write the header row at the beginning. """ self.io = io if fields: self.fields = fields self.writer = csv.writer(self.io) if write_header: self.writer.writerow(self.fields)
[ "def", "__init__", "(", "self", ",", "io", ",", "fields", "=", "None", ",", "write_header", "=", "True", ")", ":", "self", ".", "io", "=", "io", "if", "fields", ":", "self", ".", "fields", "=", "fields", "self", ".", "writer", "=", "csv", ".", "w...
https://github.com/google/personfinder/blob/475f4c0ce916036d39bae2d480cde07126550875/app/record_writer.py#L42-L55
pycalphad/pycalphad
631c41c3d041d4e8a47c57d0f25d078344b9da52
pycalphad/codegen/callables.py
python
build_callables
(dbf, comps, phases, models, parameter_symbols=None, output='GM', build_gradients=True, build_hessians=False, additional_statevars=None)
return {output: _callables}
Create a compiled callables dictionary. Parameters ---------- dbf : Database A Database object comps : list List of component names phases : list List of phase names models : dict Dictionary of {phase_name: Model subclass} parameter_symbols : list, optional List of string or SymPy Symbols that will be overridden in the callables. output : str, optional Output property of the particular Model to sample. Defaults to 'GM' build_gradients : bool, optional Whether or not to build gradient functions. Defaults to True. build_hessians : bool, optional Whether or not to build Hessian functions. Defaults to False. additional_statevars : set, optional State variables to include in the callables that may not be in the models (e.g. from conditions) verbose : bool, optional Print the name of the phase when its callables are built Returns ------- callables : dict Dictionary of keyword argument callables to pass to equilibrium. Maps {'output' -> {'function' -> {'phase_name' -> AutowrapFunction()}}. Notes ----- *All* the state variables used in calculations must be specified. If these are not specified as state variables of the models (e.g. often the case for v.N), then it must be supplied by the additional_statevars keyword argument. Examples -------- >>> from pycalphad import Database, equilibrium, variables as v >>> from pycalphad.codegen.callables import build_callables >>> from pycalphad.core.utils import instantiate_models >>> dbf = Database('AL-NI.tdb') >>> comps = ['AL', 'NI', 'VA'] >>> phases = ['LIQUID', 'AL3NI5', 'AL3NI2', 'AL3NI'] >>> models = instantiate_models(dbf, comps, phases) >>> callables = build_callables(dbf, comps, phases, models, additional_statevars={v.P, v.T, v.N}) >>> 'GM' in callables.keys() True >>> 'massfuncs' in callables['GM'] True >>> conditions = {v.P: 101325, v.T: 2500, v.X('AL'): 0.2} >>> equilibrium(dbf, comps, phases, conditions, callables=callables)
Create a compiled callables dictionary.
[ "Create", "a", "compiled", "callables", "dictionary", "." ]
def build_callables(dbf, comps, phases, models, parameter_symbols=None, output='GM', build_gradients=True, build_hessians=False, additional_statevars=None): """ Create a compiled callables dictionary. Parameters ---------- dbf : Database A Database object comps : list List of component names phases : list List of phase names models : dict Dictionary of {phase_name: Model subclass} parameter_symbols : list, optional List of string or SymPy Symbols that will be overridden in the callables. output : str, optional Output property of the particular Model to sample. Defaults to 'GM' build_gradients : bool, optional Whether or not to build gradient functions. Defaults to True. build_hessians : bool, optional Whether or not to build Hessian functions. Defaults to False. additional_statevars : set, optional State variables to include in the callables that may not be in the models (e.g. from conditions) verbose : bool, optional Print the name of the phase when its callables are built Returns ------- callables : dict Dictionary of keyword argument callables to pass to equilibrium. Maps {'output' -> {'function' -> {'phase_name' -> AutowrapFunction()}}. Notes ----- *All* the state variables used in calculations must be specified. If these are not specified as state variables of the models (e.g. often the case for v.N), then it must be supplied by the additional_statevars keyword argument. Examples -------- >>> from pycalphad import Database, equilibrium, variables as v >>> from pycalphad.codegen.callables import build_callables >>> from pycalphad.core.utils import instantiate_models >>> dbf = Database('AL-NI.tdb') >>> comps = ['AL', 'NI', 'VA'] >>> phases = ['LIQUID', 'AL3NI5', 'AL3NI2', 'AL3NI'] >>> models = instantiate_models(dbf, comps, phases) >>> callables = build_callables(dbf, comps, phases, models, additional_statevars={v.P, v.T, v.N}) >>> 'GM' in callables.keys() True >>> 'massfuncs' in callables['GM'] True >>> conditions = {v.P: 101325, v.T: 2500, v.X('AL'): 0.2} >>> equilibrium(dbf, comps, phases, conditions, callables=callables) """ additional_statevars = set(additional_statevars) if additional_statevars is not None else set() parameter_symbols = parameter_symbols if parameter_symbols is not None else [] parameter_symbols = sorted([wrap_symbol(x) for x in parameter_symbols], key=str) comps = sorted(unpack_components(dbf, comps)) pure_elements = get_pure_elements(dbf, comps) _callables = { 'massfuncs': {}, 'massgradfuncs': {}, 'masshessfuncs': {}, 'formulamolefuncs': {}, 'formulamolegradfuncs': {}, 'formulamolehessfuncs': {}, 'callables': {}, 'grad_callables': {}, 'hess_callables': {}, 'internal_cons_func': {}, 'internal_cons_jac': {}, 'internal_cons_hess': {}, } state_variables = get_state_variables(models=models) state_variables |= additional_statevars if not {v.T, v.P, v.N}.issubset(state_variables): warnings.warn("State variables in `build_callables` are not {{N, P, T}}, but {}. This can lead to incorrectly " "calculated values if the state variables used to call the generated functions do not match the " "state variables used to create them. State variables can be added with the " "`additional_statevars` argument.".format(state_variables)) state_variables = sorted(state_variables, key=str) for name in phases: mod = models[name] site_fracs = mod.site_fractions try: out = getattr(mod, output) except AttributeError: raise AttributeError('Missing Model attribute {0} specified for {1}' .format(output, mod.__class__)) # Build the callables of the output # Only force undefineds to zero if we're not overriding them undefs = {x for x in out.free_symbols if not isinstance(x, v.StateVariable)} - set(parameter_symbols) undef_vals = repeat(0., len(undefs)) out = out.xreplace(dict(zip(undefs, undef_vals))) build_output = build_functions(out, tuple(state_variables + site_fracs), parameters=parameter_symbols, include_grad=build_gradients, include_hess=build_hessians) cf, gf, hf = build_output.func, build_output.grad, build_output.hess _callables['callables'][name] = cf _callables['grad_callables'][name] = gf _callables['hess_callables'][name] = hf # Build the callables for mass # TODO: In principle, we should also check for undefs in mod.moles() mcf, mgf, mhf = zip(*[build_functions(mod.moles(el), state_variables + site_fracs, include_obj=True, include_grad=build_gradients, include_hess=build_hessians, parameters=parameter_symbols) for el in pure_elements]) _callables['massfuncs'][name] = mcf _callables['massgradfuncs'][name] = mgf _callables['masshessfuncs'][name] = mhf # Build the callables for moles per formula unit # TODO: In principle, we should also check for undefs in mod.moles() fmcf, fmgf, fmhf = zip(*[build_functions(mod.moles(el, per_formula_unit=True), state_variables + site_fracs, include_obj=True, include_grad=build_gradients, include_hess=build_hessians, parameters=parameter_symbols) for el in pure_elements]) _callables['formulamolefuncs'][name] = fmcf _callables['formulamolegradfuncs'][name] = fmgf _callables['formulamolehessfuncs'][name] = fmhf return {output: _callables}
[ "def", "build_callables", "(", "dbf", ",", "comps", ",", "phases", ",", "models", ",", "parameter_symbols", "=", "None", ",", "output", "=", "'GM'", ",", "build_gradients", "=", "True", ",", "build_hessians", "=", "False", ",", "additional_statevars", "=", "...
https://github.com/pycalphad/pycalphad/blob/631c41c3d041d4e8a47c57d0f25d078344b9da52/pycalphad/codegen/callables.py#L11-L146
cea-sec/miasm
09376c524aedc7920a7eda304d6095e12f6958f4
miasm/core/objc.py
python
CTypesManagerNotPacked.union_compute_align_size
(self, align_max, size)
return align_max, size
Compute the alignment and size of the current union (not packed)
Compute the alignment and size of the current union (not packed)
[ "Compute", "the", "alignment", "and", "size", "of", "the", "current", "union", "(", "not", "packed", ")" ]
def union_compute_align_size(self, align_max, size): """Compute the alignment and size of the current union (not packed)""" return align_max, size
[ "def", "union_compute_align_size", "(", "self", ",", "align_max", ",", "size", ")", ":", "return", "align_max", ",", "size" ]
https://github.com/cea-sec/miasm/blob/09376c524aedc7920a7eda304d6095e12f6958f4/miasm/core/objc.py#L1623-L1626
vslavik/bakefile
0757295c3e4ac23cd1e0767c77c14c2256ed16e1
3rdparty/antlr3/python-runtime/antlr3/tree.py
python
TreeNodeStream.replaceChildren
(self, parent, startChildIndex, stopChildIndex, t)
Replace from start to stop child index of parent with t, which might be a list. Number of children may be different after this call. The stream is notified because it is walking the tree and might need to know you are monkeying with the underlying tree. Also, it might be able to modify the node stream to avoid restreaming for future phases. If parent is null, don't do anything; must be at root of overall tree. Can't replace whatever points to the parent externally. Do nothing.
Replace from start to stop child index of parent with t, which might be a list. Number of children may be different after this call. The stream is notified because it is walking the tree and might need to know you are monkeying with the underlying tree. Also, it might be able to modify the node stream to avoid restreaming for future phases.
[ "Replace", "from", "start", "to", "stop", "child", "index", "of", "parent", "with", "t", "which", "might", "be", "a", "list", ".", "Number", "of", "children", "may", "be", "different", "after", "this", "call", ".", "The", "stream", "is", "notified", "bec...
def replaceChildren(self, parent, startChildIndex, stopChildIndex, t): """ Replace from start to stop child index of parent with t, which might be a list. Number of children may be different after this call. The stream is notified because it is walking the tree and might need to know you are monkeying with the underlying tree. Also, it might be able to modify the node stream to avoid restreaming for future phases. If parent is null, don't do anything; must be at root of overall tree. Can't replace whatever points to the parent externally. Do nothing. """ raise NotImplementedError
[ "def", "replaceChildren", "(", "self", ",", "parent", ",", "startChildIndex", ",", "stopChildIndex", ",", "t", ")", ":", "raise", "NotImplementedError" ]
https://github.com/vslavik/bakefile/blob/0757295c3e4ac23cd1e0767c77c14c2256ed16e1/3rdparty/antlr3/python-runtime/antlr3/tree.py#L1736-L1749
nipy/nibabel
4703f4d8e32be4cec30e829c2d93ebe54759bb62
nibabel/nicom/csareader.py
python
get_vector
(csa_dict, tag_name, n)
return np.array(items)
[]
def get_vector(csa_dict, tag_name, n): try: items = csa_dict['tags'][tag_name]['items'] except KeyError: return None if len(items) == 0: return None if len(items) != n: raise ValueError('Expecting %d vector' % n) return np.array(items)
[ "def", "get_vector", "(", "csa_dict", ",", "tag_name", ",", "n", ")", ":", "try", ":", "items", "=", "csa_dict", "[", "'tags'", "]", "[", "tag_name", "]", "[", "'items'", "]", "except", "KeyError", ":", "return", "None", "if", "len", "(", "items", ")...
https://github.com/nipy/nibabel/blob/4703f4d8e32be4cec30e829c2d93ebe54759bb62/nibabel/nicom/csareader.py#L174-L183
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/multiprocessing/managers.py
python
Server.number_of_objects
(self, c)
return len(self.id_to_refcount)
Number of shared objects
Number of shared objects
[ "Number", "of", "shared", "objects" ]
def number_of_objects(self, c): ''' Number of shared objects ''' # Doesn't use (len(self.id_to_obj) - 1) as we shouldn't count ident='0' return len(self.id_to_refcount)
[ "def", "number_of_objects", "(", "self", ",", "c", ")", ":", "# Doesn't use (len(self.id_to_obj) - 1) as we shouldn't count ident='0'", "return", "len", "(", "self", ".", "id_to_refcount", ")" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/multiprocessing/managers.py#L334-L339
google/tf_mesh_renderer
7564430975d8239a8a9cdf0c0959d7ac723b9a08
mesh_renderer/camera_utils.py
python
euler_matrices
(angles)
return tf.transpose(reshaped, [2, 0, 1])
Computes a XYZ Tait-Bryan (improper Euler angle) rotation. Returns 4x4 matrices for convenient multiplication with other transformations. Args: angles: a [batch_size, 3] tensor containing X, Y, and Z angles in radians. Returns: a [batch_size, 4, 4] tensor of matrices.
Computes a XYZ Tait-Bryan (improper Euler angle) rotation.
[ "Computes", "a", "XYZ", "Tait", "-", "Bryan", "(", "improper", "Euler", "angle", ")", "rotation", "." ]
def euler_matrices(angles): """Computes a XYZ Tait-Bryan (improper Euler angle) rotation. Returns 4x4 matrices for convenient multiplication with other transformations. Args: angles: a [batch_size, 3] tensor containing X, Y, and Z angles in radians. Returns: a [batch_size, 4, 4] tensor of matrices. """ s = tf.sin(angles) c = tf.cos(angles) # Rename variables for readability in the matrix definition below. c0, c1, c2 = (c[:, 0], c[:, 1], c[:, 2]) s0, s1, s2 = (s[:, 0], s[:, 1], s[:, 2]) zeros = tf.zeros_like(s[:, 0]) ones = tf.ones_like(s[:, 0]) # pyformat: disable flattened = tf.concat( [ c2 * c1, c2 * s1 * s0 - c0 * s2, s2 * s0 + c2 * c0 * s1, zeros, c1 * s2, c2 * c0 + s2 * s1 * s0, c0 * s2 * s1 - c2 * s0, zeros, -s1, c1 * s0, c1 * c0, zeros, zeros, zeros, zeros, ones ], axis=0) # pyformat: enable reshaped = tf.reshape(flattened, [4, 4, -1]) return tf.transpose(reshaped, [2, 0, 1])
[ "def", "euler_matrices", "(", "angles", ")", ":", "s", "=", "tf", ".", "sin", "(", "angles", ")", "c", "=", "tf", ".", "cos", "(", "angles", ")", "# Rename variables for readability in the matrix definition below.", "c0", ",", "c1", ",", "c2", "=", "(", "c...
https://github.com/google/tf_mesh_renderer/blob/7564430975d8239a8a9cdf0c0959d7ac723b9a08/mesh_renderer/camera_utils.py#L121-L152
mathics/Mathics
318e06dea8f1c70758a50cb2f95c9900150e3a68
mathics/builtin/intfns/combinatorial.py
python
_BooleanDissimilarity.apply
(self, u, v, evaluation)
return self._compute(len(py_u), *counts)
%(name)s[u_List, v_List]
%(name)s[u_List, v_List]
[ "%", "(", "name", ")", "s", "[", "u_List", "v_List", "]" ]
def apply(self, u, v, evaluation): "%(name)s[u_List, v_List]" if len(u.leaves) != len(v.leaves): return py_u = _BooleanDissimilarity._to_bool_vector(u) if py_u is None: return py_v = _BooleanDissimilarity._to_bool_vector(v) if py_v is None: return counts = [0, 0, 0, 0] for a, b in zip(py_u, py_v): counts[(a << 1) + b] += 1 return self._compute(len(py_u), *counts)
[ "def", "apply", "(", "self", ",", "u", ",", "v", ",", "evaluation", ")", ":", "if", "len", "(", "u", ".", "leaves", ")", "!=", "len", "(", "v", ".", "leaves", ")", ":", "return", "py_u", "=", "_BooleanDissimilarity", ".", "_to_bool_vector", "(", "u...
https://github.com/mathics/Mathics/blob/318e06dea8f1c70758a50cb2f95c9900150e3a68/mathics/builtin/intfns/combinatorial.py#L114-L127
benediktschmitt/py-ts3
043a6a896169d39464f6f754e2afd300f74eefa5
ts3/response.py
python
TS3Response.__getitem__
(self, index)
return self.parsed[index]
[]
def __getitem__(self, index): return self.parsed[index]
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "return", "self", ".", "parsed", "[", "index", "]" ]
https://github.com/benediktschmitt/py-ts3/blob/043a6a896169d39464f6f754e2afd300f74eefa5/ts3/response.py#L152-L153
CLUEbenchmark/CLUE
5bd39732734afecb490cf18a5212e692dbf2c007
baselines/models/bert/tokenization.py
python
convert_tokens_to_ids
(vocab, tokens)
return convert_by_vocab(vocab, tokens)
[]
def convert_tokens_to_ids(vocab, tokens): return convert_by_vocab(vocab, tokens)
[ "def", "convert_tokens_to_ids", "(", "vocab", ",", "tokens", ")", ":", "return", "convert_by_vocab", "(", "vocab", ",", "tokens", ")" ]
https://github.com/CLUEbenchmark/CLUE/blob/5bd39732734afecb490cf18a5212e692dbf2c007/baselines/models/bert/tokenization.py#L144-L145
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/webapp2-2.3/webapp2_extras/appengine/auth/models.py
python
User.get_by_auth_id
(cls, auth_id)
return cls.query(cls.auth_ids == auth_id).get()
Returns a user object based on a auth_id. :param auth_id: String representing a unique id for the user. Examples: - own:username - google:username :returns: A user object.
Returns a user object based on a auth_id.
[ "Returns", "a", "user", "object", "based", "on", "a", "auth_id", "." ]
def get_by_auth_id(cls, auth_id): """Returns a user object based on a auth_id. :param auth_id: String representing a unique id for the user. Examples: - own:username - google:username :returns: A user object. """ return cls.query(cls.auth_ids == auth_id).get()
[ "def", "get_by_auth_id", "(", "cls", ",", "auth_id", ")", ":", "return", "cls", ".", "query", "(", "cls", ".", "auth_ids", "==", "auth_id", ")", ".", "get", "(", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/webapp2-2.3/webapp2_extras/appengine/auth/models.py#L222-L233
aiogram/aiogram
4d2d81138681d730270819579f22b3a0001c43a5
aiogram/bot/api.py
python
check_result
(method_name: str, content_type: str, status_code: int, body: str)
Checks whether `result` is a valid API response. A result is considered invalid if: - The server returned an HTTP response code other than 200 - The content of the result is invalid JSON. - The method call was unsuccessful (The JSON 'ok' field equals False) :param method_name: The name of the method called :param status_code: status code :param content_type: content type of result :param body: result body :return: The result parsed to a JSON dictionary :raises ApiException: if one of the above listed cases is applicable
Checks whether `result` is a valid API response. A result is considered invalid if: - The server returned an HTTP response code other than 200 - The content of the result is invalid JSON. - The method call was unsuccessful (The JSON 'ok' field equals False)
[ "Checks", "whether", "result", "is", "a", "valid", "API", "response", ".", "A", "result", "is", "considered", "invalid", "if", ":", "-", "The", "server", "returned", "an", "HTTP", "response", "code", "other", "than", "200", "-", "The", "content", "of", "...
def check_result(method_name: str, content_type: str, status_code: int, body: str): """ Checks whether `result` is a valid API response. A result is considered invalid if: - The server returned an HTTP response code other than 200 - The content of the result is invalid JSON. - The method call was unsuccessful (The JSON 'ok' field equals False) :param method_name: The name of the method called :param status_code: status code :param content_type: content type of result :param body: result body :return: The result parsed to a JSON dictionary :raises ApiException: if one of the above listed cases is applicable """ log.debug('Response for %s: [%d] "%r"', method_name, status_code, body) if content_type != 'application/json': raise exceptions.NetworkError(f"Invalid response with content type {content_type}: \"{body}\"") try: result_json = json.loads(body) except ValueError: result_json = {} description = result_json.get('description') or body parameters = types.ResponseParameters(**result_json.get('parameters', {}) or {}) if HTTPStatus.OK <= status_code <= HTTPStatus.IM_USED: return result_json.get('result') elif parameters.retry_after: raise exceptions.RetryAfter(parameters.retry_after) elif parameters.migrate_to_chat_id: raise exceptions.MigrateToChat(parameters.migrate_to_chat_id) elif status_code == HTTPStatus.BAD_REQUEST: exceptions.BadRequest.detect(description) elif status_code == HTTPStatus.NOT_FOUND: exceptions.NotFound.detect(description) elif status_code == HTTPStatus.CONFLICT: exceptions.ConflictError.detect(description) elif status_code in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN): exceptions.Unauthorized.detect(description) elif status_code == HTTPStatus.REQUEST_ENTITY_TOO_LARGE: raise exceptions.NetworkError('File too large for uploading. ' 'Check telegram api limits https://core.telegram.org/bots/api#senddocument') elif status_code >= HTTPStatus.INTERNAL_SERVER_ERROR: if 'restart' in description: raise exceptions.RestartingTelegram() raise exceptions.TelegramAPIError(description) raise exceptions.TelegramAPIError(f"{description} [{status_code}]")
[ "def", "check_result", "(", "method_name", ":", "str", ",", "content_type", ":", "str", ",", "status_code", ":", "int", ",", "body", ":", "str", ")", ":", "log", ".", "debug", "(", "'Response for %s: [%d] \"%r\"'", ",", "method_name", ",", "status_code", ","...
https://github.com/aiogram/aiogram/blob/4d2d81138681d730270819579f22b3a0001c43a5/aiogram/bot/api.py#L80-L129
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/datetime.py
python
_call_tzinfo_method
(tzinfo, methname, tzinfoarg)
return getattr(tzinfo, methname)(tzinfoarg)
[]
def _call_tzinfo_method(tzinfo, methname, tzinfoarg): if tzinfo is None: return None return getattr(tzinfo, methname)(tzinfoarg)
[ "def", "_call_tzinfo_method", "(", "tzinfo", ",", "methname", ",", "tzinfoarg", ")", ":", "if", "tzinfo", "is", "None", ":", "return", "None", "return", "getattr", "(", "tzinfo", ",", "methname", ")", "(", "tzinfoarg", ")" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/datetime.py#L220-L223
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
rope/base/pyobjectsdef.py
python
PyFunction.__init__
(self, pycore, ast_node, parent)
[]
def __init__(self, pycore, ast_node, parent): AbstractFunction.__init__(self) PyDefinedObject.__init__(self, pycore, ast_node, parent) self.arguments = self.ast_node.args self.parameter_pyobjects = pynames._Inferred( self._infer_parameters, self.get_module()._get_concluded_data()) self.returned = pynames._Inferred(self._infer_returned) self.parameter_pynames = None
[ "def", "__init__", "(", "self", ",", "pycore", ",", "ast_node", ",", "parent", ")", ":", "AbstractFunction", ".", "__init__", "(", "self", ")", "PyDefinedObject", ".", "__init__", "(", "self", ",", "pycore", ",", "ast_node", ",", "parent", ")", "self", "...
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/base/pyobjectsdef.py#L13-L20
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
rope/refactor/patchedast.py
python
_PatchingASTWalker._is_elif
(self, node)
return 'elif' in (word, alt_word)
[]
def _is_elif(self, node): if not isinstance(node, ast.If): return False offset = self.lines.get_line_start(node.lineno) + node.col_offset word = self.source[offset:offset + 4] # XXX: This is a bug; the offset does not point to the first alt_word = self.source[offset - 5:offset - 1] return 'elif' in (word, alt_word)
[ "def", "_is_elif", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "ast", ".", "If", ")", ":", "return", "False", "offset", "=", "self", ".", "lines", ".", "get_line_start", "(", "node", ".", "lineno", ")", "+", "no...
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/refactor/patchedast.py#L455-L462
mne-tools/mne-python
f90b303ce66a8415e64edd4605b09ac0179c1ebf
mne/viz/circle.py
python
plot_channel_labels_circle
(labels, colors=None, picks=None, **kwargs)
return _plot_connectivity_circle(con, node_names, **kwargs)
Plot labels for each channel in a circle plot. .. note:: This primarily makes sense for sEEG channels where each channel can be assigned an anatomical label as the electrode passes through various brain areas. Parameters ---------- labels : dict Lists of labels (values) associated with each channel (keys). colors : dict The color (value) for each label (key). picks : list | tuple The channels to consider. **kwargs : kwargs Keyword arguments for ``plot_connectivity_circle``. Returns ------- fig : instance of matplotlib.figure.Figure The figure handle. axes : instance of matplotlib.projections.polar.PolarAxes The subplot handle.
Plot labels for each channel in a circle plot.
[ "Plot", "labels", "for", "each", "channel", "in", "a", "circle", "plot", "." ]
def plot_channel_labels_circle(labels, colors=None, picks=None, **kwargs): """Plot labels for each channel in a circle plot. .. note:: This primarily makes sense for sEEG channels where each channel can be assigned an anatomical label as the electrode passes through various brain areas. Parameters ---------- labels : dict Lists of labels (values) associated with each channel (keys). colors : dict The color (value) for each label (key). picks : list | tuple The channels to consider. **kwargs : kwargs Keyword arguments for ``plot_connectivity_circle``. Returns ------- fig : instance of matplotlib.figure.Figure The figure handle. axes : instance of matplotlib.projections.polar.PolarAxes The subplot handle. """ from matplotlib.colors import LinearSegmentedColormap _validate_type(labels, dict, 'labels') _validate_type(colors, (dict, None), 'colors') _validate_type(picks, (list, tuple, None), 'picks') if picks is not None: labels = {k: v for k, v in labels.items() if k in picks} ch_names = list(labels.keys()) all_labels = list(set([label for val in labels.values() for label in val])) n_labels = len(all_labels) if colors is not None: for label in all_labels: if label not in colors: raise ValueError(f'No color provided for {label} in `colors`') # update all_labels, there may be unconnected labels in colors all_labels = list(colors.keys()) n_labels = len(all_labels) # make colormap label_colors = [colors[label] for label in all_labels] node_colors = ['black'] * len(ch_names) + label_colors label_cmap = LinearSegmentedColormap.from_list( 'label_cmap', label_colors, N=len(label_colors)) else: node_colors = None node_names = ch_names + all_labels con = np.zeros((len(node_names), len(node_names))) * np.nan for idx, ch_name in enumerate(ch_names): for label in labels[ch_name]: node_idx = node_names.index(label) label_color = all_labels.index(label) / n_labels con[idx, node_idx] = con[node_idx, idx] = label_color # symmetric # plot node_order = ch_names + all_labels[::-1] node_angles = circular_layout(node_names, node_order, start_pos=90, group_boundaries=[0, len(ch_names)]) # provide defaults but don't overwrite if 'node_angles' not in kwargs: kwargs.update(node_angles=node_angles) if 'colorbar' not in kwargs: kwargs.update(colorbar=False) if 'node_colors' not in kwargs: kwargs.update(node_colors=node_colors) if 'vmin' not in kwargs: kwargs.update(vmin=0) if 'vmax' not in kwargs: kwargs.update(vmax=1) if 'colormap' not in kwargs: kwargs.update(colormap=label_cmap) return _plot_connectivity_circle(con, node_names, **kwargs)
[ "def", "plot_channel_labels_circle", "(", "labels", ",", "colors", "=", "None", ",", "picks", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "matplotlib", ".", "colors", "import", "LinearSegmentedColormap", "_validate_type", "(", "labels", ",", "dict"...
https://github.com/mne-tools/mne-python/blob/f90b303ce66a8415e64edd4605b09ac0179c1ebf/mne/viz/circle.py#L339-L414
samuelclay/NewsBlur
2c45209df01a1566ea105e04d499367f32ac9ad2
apps/feed_import/models.py
python
OPMLExporter.__init__
(self, user)
[]
def __init__(self, user): self.user = user self.fetch_feeds()
[ "def", "__init__", "(", "self", ",", "user", ")", ":", "self", ".", "user", "=", "user", "self", ".", "fetch_feeds", "(", ")" ]
https://github.com/samuelclay/NewsBlur/blob/2c45209df01a1566ea105e04d499367f32ac9ad2/apps/feed_import/models.py#L49-L51
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/parser/aiml_parser.py
python
AIMLParser.pattern_parser
(self)
return self._pattern_parser
[]
def pattern_parser(self): return self._pattern_parser
[ "def", "pattern_parser", "(", "self", ")", ":", "return", "self", ".", "_pattern_parser" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/parser/aiml_parser.py#L92-L93
plone/Products.CMFPlone
83137764e3e7e4fe60d03c36dfc6ba9c7c543324
Products/CMFPlone/interfaces/constrains.py
python
IConstrainTypes.getLocallyAllowedTypes
()
Get the list of FTI ids for the types which should be allowed to be added in this container.
Get the list of FTI ids for the types which should be allowed to be added in this container.
[ "Get", "the", "list", "of", "FTI", "ids", "for", "the", "types", "which", "should", "be", "allowed", "to", "be", "added", "in", "this", "container", "." ]
def getLocallyAllowedTypes(): """ Get the list of FTI ids for the types which should be allowed to be added in this container. """
[ "def", "getLocallyAllowedTypes", "(", ")", ":" ]
https://github.com/plone/Products.CMFPlone/blob/83137764e3e7e4fe60d03c36dfc6ba9c7c543324/Products/CMFPlone/interfaces/constrains.py#L27-L31
GeospatialPython/pyshp
05e18f5171a6346a675646cb8bc7a8f84ed8d5d6
shapefile.py
python
Writer.__enter__
(self)
return self
Enter phase of context manager.
Enter phase of context manager.
[ "Enter", "phase", "of", "context", "manager", "." ]
def __enter__(self): """ Enter phase of context manager. """ return self
[ "def", "__enter__", "(", "self", ")", ":", "return", "self" ]
https://github.com/GeospatialPython/pyshp/blob/05e18f5171a6346a675646cb8bc7a8f84ed8d5d6/shapefile.py#L1727-L1731
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/_xmlplus/xpath/CoreFunctions.py
python
Not
(context, object)
return (not Conversions.BooleanValue(object) and boolean.true) or boolean.false
Function: <boolean> not(<boolean>)
Function: <boolean> not(<boolean>)
[ "Function", ":", "<boolean", ">", "not", "(", "<boolean", ">", ")" ]
def Not(context, object): """Function: <boolean> not(<boolean>)""" return (not Conversions.BooleanValue(object) and boolean.true) or boolean.false
[ "def", "Not", "(", "context", ",", "object", ")", ":", "return", "(", "not", "Conversions", ".", "BooleanValue", "(", "object", ")", "and", "boolean", ".", "true", ")", "or", "boolean", ".", "false" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/_xmlplus/xpath/CoreFunctions.py#L246-L248
ansible-collections/community.general
3faffe8f47968a2400ba3c896c8901c03001a194
plugins/modules/storage/vexata/vexata_volume.py
python
get_volume
(module, array)
Retrieve a named volume if it exists, None if absent.
Retrieve a named volume if it exists, None if absent.
[ "Retrieve", "a", "named", "volume", "if", "it", "exists", "None", "if", "absent", "." ]
def get_volume(module, array): """Retrieve a named volume if it exists, None if absent.""" name = module.params['name'] try: vols = array.list_volumes() vol = filter(lambda v: v['name'] == name, vols) if len(vol) == 1: return vol[0] else: return None except Exception: module.fail_json(msg='Error while attempting to retrieve volumes.')
[ "def", "get_volume", "(", "module", ",", "array", ")", ":", "name", "=", "module", ".", "params", "[", "'name'", "]", "try", ":", "vols", "=", "array", ".", "list_volumes", "(", ")", "vol", "=", "filter", "(", "lambda", "v", ":", "v", "[", "'name'"...
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/modules/storage/vexata/vexata_volume.py#L76-L87
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/lib-tk/ttk.py
python
Style.__init__
(self, master=None)
[]
def __init__(self, master=None): master = setup_master(master) if not getattr(master, '_tile_loaded', False): # Load tile now, if needed _load_tile(master) self.master = master self.tk = self.master.tk
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ")", ":", "master", "=", "setup_master", "(", "master", ")", "if", "not", "getattr", "(", "master", ",", "'_tile_loaded'", ",", "False", ")", ":", "# Load tile now, if needed", "_load_tile", "(", ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/lib-tk/ttk.py#L367-L375
facebookresearch/mobile-vision
f40401a44e86bb3ba9c1b66e7700e15f96b880cb
mobile_cv/arch/layers/misc.py
python
Conv2d.cast
(cls, module: "Conv2d")
return module
Cast mobile_cv.arch.layers.Conv2d to a normal conv2d
Cast mobile_cv.arch.layers.Conv2d to a normal conv2d
[ "Cast", "mobile_cv", ".", "arch", ".", "layers", ".", "Conv2d", "to", "a", "normal", "conv2d" ]
def cast(cls, module: "Conv2d"): """Cast mobile_cv.arch.layers.Conv2d to a normal conv2d""" assert type(module) == cls module = copy.deepcopy(module) assert module.norm is None assert module.activation is None module.__class__ = torch.nn.Conv2d return module
[ "def", "cast", "(", "cls", ",", "module", ":", "\"Conv2d\"", ")", ":", "assert", "type", "(", "module", ")", "==", "cls", "module", "=", "copy", ".", "deepcopy", "(", "module", ")", "assert", "module", ".", "norm", "is", "None", "assert", "module", "...
https://github.com/facebookresearch/mobile-vision/blob/f40401a44e86bb3ba9c1b66e7700e15f96b880cb/mobile_cv/arch/layers/misc.py#L134-L141
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/table/index.py
python
TableLoc.__getitem__
(self, item)
return self.table[rows]
Retrieve Table rows by value slice. Parameters ---------- item : column element, list, ndarray, slice or tuple Can be a value of the table primary index, a list/ndarray of such values, or a value slice (both endpoints are included). If a tuple is provided, the first element must be an index to use instead of the primary key, and the second element must be as above.
Retrieve Table rows by value slice.
[ "Retrieve", "Table", "rows", "by", "value", "slice", "." ]
def __getitem__(self, item): """ Retrieve Table rows by value slice. Parameters ---------- item : column element, list, ndarray, slice or tuple Can be a value of the table primary index, a list/ndarray of such values, or a value slice (both endpoints are included). If a tuple is provided, the first element must be an index to use instead of the primary key, and the second element must be as above. """ rows = self._get_rows(item) if len(rows) == 0: # no matches found raise KeyError(f'No matches found for key {item}') elif len(rows) == 1: # single row return self.table[rows[0]] return self.table[rows]
[ "def", "__getitem__", "(", "self", ",", "item", ")", ":", "rows", "=", "self", ".", "_get_rows", "(", "item", ")", "if", "len", "(", "rows", ")", "==", "0", ":", "# no matches found", "raise", "KeyError", "(", "f'No matches found for key {item}'", ")", "el...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/table/index.py#L860-L879
subbarayudu-j/TheAlgorithms-Python
bb29dc55faf5b98b1e9f0b1f11a9dd15525386a3
Maths/absMin.py
python
absMin
(x)
return j
# >>>absMin([0,5,1,11]) 0 # >>absMin([3,-10,-2]) -2
# >>>absMin([0,5,1,11]) 0 # >>absMin([3,-10,-2]) -2
[ "#", ">>>", "absMin", "(", "[", "0", "5", "1", "11", "]", ")", "0", "#", ">>", "absMin", "(", "[", "3", "-", "10", "-", "2", "]", ")", "-", "2" ]
def absMin(x): """ # >>>absMin([0,5,1,11]) 0 # >>absMin([3,-10,-2]) -2 """ j = x[0] for i in x: if absVal(i) < absVal(j): j = i return j
[ "def", "absMin", "(", "x", ")", ":", "j", "=", "x", "[", "0", "]", "for", "i", "in", "x", ":", "if", "absVal", "(", "i", ")", "<", "absVal", "(", "j", ")", ":", "j", "=", "i", "return", "j" ]
https://github.com/subbarayudu-j/TheAlgorithms-Python/blob/bb29dc55faf5b98b1e9f0b1f11a9dd15525386a3/Maths/absMin.py#L2-L13
art-programmer/PlaneNet
ccc4423d278388d01cb3300be992b951b90acc7a
html.py
python
TestCase.test_unicode
(self)
make sure unicode input works and results in unicode output
make sure unicode input works and results in unicode output
[ "make", "sure", "unicode", "input", "works", "and", "results", "in", "unicode", "output" ]
def test_unicode(self): 'make sure unicode input works and results in unicode output' h = HTML(newlines=False) # Python 3 compat try: unicode = unicode TEST = 'euro \xe2\x82\xac'.decode('utf8') except: unicode = str TEST = 'euro €' h.p(TEST) self.assertEquals(unicode(h), '<p>%s</p>' % TEST)
[ "def", "test_unicode", "(", "self", ")", ":", "h", "=", "HTML", "(", "newlines", "=", "False", ")", "# Python 3 compat", "try", ":", "unicode", "=", "unicode", "TEST", "=", "'euro \\xe2\\x82\\xac'", ".", "decode", "(", "'utf8'", ")", "except", ":", "unicod...
https://github.com/art-programmer/PlaneNet/blob/ccc4423d278388d01cb3300be992b951b90acc7a/html.py#L567-L578
wbond/asn1crypto
9ae350f212532dfee7f185f6b3eda24753249cf3
asn1crypto/crl.py
python
CertificateList.authority_key_identifier_value
(self)
return self._authority_key_identifier_value
This extension helps in identifying the public key with which to validate the authenticity of the CRL. :return: None or an AuthorityKeyIdentifier object
This extension helps in identifying the public key with which to validate the authenticity of the CRL.
[ "This", "extension", "helps", "in", "identifying", "the", "public", "key", "with", "which", "to", "validate", "the", "authenticity", "of", "the", "CRL", "." ]
def authority_key_identifier_value(self): """ This extension helps in identifying the public key with which to validate the authenticity of the CRL. :return: None or an AuthorityKeyIdentifier object """ if self._processed_extensions is False: self._set_extensions() return self._authority_key_identifier_value
[ "def", "authority_key_identifier_value", "(", "self", ")", ":", "if", "self", ".", "_processed_extensions", "is", "False", ":", "self", ".", "_set_extensions", "(", ")", "return", "self", ".", "_authority_key_identifier_value" ]
https://github.com/wbond/asn1crypto/blob/9ae350f212532dfee7f185f6b3eda24753249cf3/asn1crypto/crl.py#L397-L408
suavecode/SUAVE
4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5
trunk/SUAVE/Methods/Weights/Correlations/Raymer/prop_system.py
python
nacelle_Raymer
(vehicle, WENG)
return WNAC * Units.lbs
Calculates the nacelle weight based on the Raymer method Assumptions: 1) All nacelles are identical 2) The number of nacelles is the same as the number of engines Source: Aircraft Design: A Conceptual Approach (2nd edition) Inputs: vehicle - data dictionary with vehicle properties [dimensionless] -.ultimate_load: ultimate load factor of aircraft nacelle - data dictionary for the specific nacelle that is being estimated [dimensionless] -lenght: total length of engine [m] -diameter: diameter of nacelle [m] WENG - dry engine weight [kg] Outputs: WNAC: nacelle weight [kg] Properties Used: N/A
Calculates the nacelle weight based on the Raymer method Assumptions: 1) All nacelles are identical 2) The number of nacelles is the same as the number of engines Source: Aircraft Design: A Conceptual Approach (2nd edition)
[ "Calculates", "the", "nacelle", "weight", "based", "on", "the", "Raymer", "method", "Assumptions", ":", "1", ")", "All", "nacelles", "are", "identical", "2", ")", "The", "number", "of", "nacelles", "is", "the", "same", "as", "the", "number", "of", "engines...
def nacelle_Raymer(vehicle, WENG): """ Calculates the nacelle weight based on the Raymer method Assumptions: 1) All nacelles are identical 2) The number of nacelles is the same as the number of engines Source: Aircraft Design: A Conceptual Approach (2nd edition) Inputs: vehicle - data dictionary with vehicle properties [dimensionless] -.ultimate_load: ultimate load factor of aircraft nacelle - data dictionary for the specific nacelle that is being estimated [dimensionless] -lenght: total length of engine [m] -diameter: diameter of nacelle [m] WENG - dry engine weight [kg] Outputs: WNAC: nacelle weight [kg] Properties Used: N/A """ nacelle_tag = list(vehicle.nacelles.keys())[0] ref_nacelle = vehicle.nacelles[nacelle_tag] NENG = len(vehicle.nacelles) Kng = 1 # assuming the engine is not pylon mounted Nlt = ref_nacelle.length / Units.ft Nw = ref_nacelle.diameter / Units.ft Wec = 2.331 * WENG ** 0.901 * 1.18 Sn = 2 * np.pi * Nw/2 * Nlt + np.pi * Nw**2/4 * 2 WNAC = 0.6724 * Kng * Nlt ** 0.1 * Nw ** 0.294 * vehicle.envelope.ultimate_load ** 0.119 \ * Wec ** 0.611 * NENG * 0.984 * Sn ** 0.224 return WNAC * Units.lbs
[ "def", "nacelle_Raymer", "(", "vehicle", ",", "WENG", ")", ":", "nacelle_tag", "=", "list", "(", "vehicle", ".", "nacelles", ".", "keys", "(", ")", ")", "[", "0", "]", "ref_nacelle", "=", "vehicle", ".", "nacelles", "[", "nacelle_tag", "]", "NENG", "="...
https://github.com/suavecode/SUAVE/blob/4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5/trunk/SUAVE/Methods/Weights/Correlations/Raymer/prop_system.py#L66-L101
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/infrastructure/server_header.py
python
server_header.get_long_desc
(self)
return """ This plugin GETs the server header and saves the result to the knowledge base. Nothing strange, just do a GET request to the url and save the server headers to the kb. A smarter way to check the server type is with the hmap plugin. """
:return: A DETAILED description of the plugin functions and features.
:return: A DETAILED description of the plugin functions and features.
[ ":", "return", ":", "A", "DETAILED", "description", "of", "the", "plugin", "functions", "and", "features", "." ]
def get_long_desc(self): """ :return: A DETAILED description of the plugin functions and features. """ return """ This plugin GETs the server header and saves the result to the knowledge base. Nothing strange, just do a GET request to the url and save the server headers to the kb. A smarter way to check the server type is with the hmap plugin. """
[ "def", "get_long_desc", "(", "self", ")", ":", "return", "\"\"\"\n This plugin GETs the server header and saves the result to the\n knowledge base.\n\n Nothing strange, just do a GET request to the url and save the server\n headers to the kb. A smarter way to check the serv...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/infrastructure/server_header.py#L157-L168
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/OpenSSL/SSL.py
python
Connection.bio_read
(self, bufsiz)
return _ffi.buffer(buf, result)[:]
If the Connection was created with a memory BIO, this method can be used to read bytes from the write end of that memory BIO. Many Connection methods will add bytes which must be read in this manner or the buffer will eventually fill up and the Connection will be able to take no further actions. :param bufsiz: The maximum number of bytes to read :return: The string read.
If the Connection was created with a memory BIO, this method can be used to read bytes from the write end of that memory BIO. Many Connection methods will add bytes which must be read in this manner or the buffer will eventually fill up and the Connection will be able to take no further actions.
[ "If", "the", "Connection", "was", "created", "with", "a", "memory", "BIO", "this", "method", "can", "be", "used", "to", "read", "bytes", "from", "the", "write", "end", "of", "that", "memory", "BIO", ".", "Many", "Connection", "methods", "will", "add", "b...
def bio_read(self, bufsiz): """ If the Connection was created with a memory BIO, this method can be used to read bytes from the write end of that memory BIO. Many Connection methods will add bytes which must be read in this manner or the buffer will eventually fill up and the Connection will be able to take no further actions. :param bufsiz: The maximum number of bytes to read :return: The string read. """ if self._from_ssl is None: raise TypeError("Connection sock was not None") if not isinstance(bufsiz, integer_types): raise TypeError("bufsiz must be an integer") buf = _no_zero_allocator("char[]", bufsiz) result = _lib.BIO_read(self._from_ssl, buf, bufsiz) if result <= 0: self._handle_bio_errors(self._from_ssl, result) return _ffi.buffer(buf, result)[:]
[ "def", "bio_read", "(", "self", ",", "bufsiz", ")", ":", "if", "self", ".", "_from_ssl", "is", "None", ":", "raise", "TypeError", "(", "\"Connection sock was not None\"", ")", "if", "not", "isinstance", "(", "bufsiz", ",", "integer_types", ")", ":", "raise",...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/OpenSSL/SSL.py#L1868-L1890
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/pupylib/PupyJob.py
python
Thread._get_my_tid
(self)
determines this (self's) thread id
determines this (self's) thread id
[ "determines", "this", "(", "self", "s", ")", "thread", "id" ]
def _get_my_tid(self): """determines this (self's) thread id""" if not self.isAlive(): raise threading.ThreadError("the thread is not active") # do we have it cached? if hasattr(self, "_thread_id"): return self._thread_id # no, look for it in the _active dict for tid, tobj in threading._active.items(): if tobj is self: self._thread_id = tid return tid raise AssertionError("could not determine the thread's id")
[ "def", "_get_my_tid", "(", "self", ")", ":", "if", "not", "self", ".", "isAlive", "(", ")", ":", "raise", "threading", ".", "ThreadError", "(", "\"the thread is not active\"", ")", "# do we have it cached?", "if", "hasattr", "(", "self", ",", "\"_thread_id\"", ...
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/pupylib/PupyJob.py#L45-L60