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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-windows/x86/cffi/backend_ctypes.py | python | CTypesData.__hash__ | (self) | return hash(self._convert_to_address(None)) | [] | def __hash__(self):
return hash(self._convert_to_address(None)) | [
"def",
"__hash__",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"self",
".",
"_convert_to_address",
"(",
"None",
")",
")"
] | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/cffi/backend_ctypes.py#L139-L140 | |||
caiiiac/Machine-Learning-with-Python | 1a26c4467da41ca4ebc3d5bd789ea942ef79422f | MachineLearning/venv/lib/python3.5/site-packages/pip/_vendor/pkg_resources/__init__.py | python | MemoizedZipManifests.load | (self, path) | return self[path].manifest | Load a manifest at path or return a suitable manifest already loaded. | Load a manifest at path or return a suitable manifest already loaded. | [
"Load",
"a",
"manifest",
"at",
"path",
"or",
"return",
"a",
"suitable",
"manifest",
"already",
"loaded",
"."
] | def load(self, path):
"""
Load a manifest at path or return a suitable manifest already loaded.
"""
path = os.path.normpath(path)
mtime = os.stat(path).st_mtime
if path not in self or self[path].mtime != mtime:
manifest = self.build(path)
self[path] = self.manifest_mod(manifest, mtime)
return self[path].manifest | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"mtime",
"=",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mtime",
"if",
"path",
"not",
"in",
"self",
"or",
"self",
"[",
"pat... | https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pip/_vendor/pkg_resources/__init__.py#L1638-L1649 | |
RasaHQ/rasa | 54823b68c1297849ba7ae841a4246193cd1223a1 | rasa/shared/core/trackers.py | python | get_trackers_for_conversation_sessions | (
tracker: DialogueStateTracker,
) | return [
DialogueStateTracker.from_events(
tracker.sender_id,
evts,
tracker.slots.values(),
sender_source=tracker.sender_source,
)
for evts in split_conversations
] | Generate trackers for `tracker` that are split by conversation sessions.
Args:
tracker: Instance of `DialogueStateTracker` to split.
Returns:
The trackers split by conversation sessions. | Generate trackers for `tracker` that are split by conversation sessions. | [
"Generate",
"trackers",
"for",
"tracker",
"that",
"are",
"split",
"by",
"conversation",
"sessions",
"."
] | def get_trackers_for_conversation_sessions(
tracker: DialogueStateTracker,
) -> List[DialogueStateTracker]:
"""Generate trackers for `tracker` that are split by conversation sessions.
Args:
tracker: Instance of `DialogueStateTracker` to split.
Returns:
The trackers split by conversation sessions.
"""
split_conversations = events.split_events(
tracker.events,
ActionExecuted,
{"action_name": ACTION_SESSION_START_NAME},
include_splitting_event=True,
)
return [
DialogueStateTracker.from_events(
tracker.sender_id,
evts,
tracker.slots.values(),
sender_source=tracker.sender_source,
)
for evts in split_conversations
] | [
"def",
"get_trackers_for_conversation_sessions",
"(",
"tracker",
":",
"DialogueStateTracker",
",",
")",
"->",
"List",
"[",
"DialogueStateTracker",
"]",
":",
"split_conversations",
"=",
"events",
".",
"split_events",
"(",
"tracker",
".",
"events",
",",
"ActionExecuted"... | https://github.com/RasaHQ/rasa/blob/54823b68c1297849ba7ae841a4246193cd1223a1/rasa/shared/core/trackers.py#L900-L926 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/engines/stalekey.py | python | start | (interval=3600, expire=604800) | Start the engine | Start the engine | [
"Start",
"the",
"engine"
] | def start(interval=3600, expire=604800):
"""
Start the engine
"""
ck = salt.utils.minions.CkMinions(__opts__)
presence_file = "{}/presence.p".format(__opts__["cachedir"])
wheel = salt.wheel.WheelClient(__opts__)
while True:
log.debug("Checking for present minions")
minions = {}
error, minions = _read_presence(presence_file)
if error:
time.sleep(interval)
continue
minion_keys = _get_keys()
now = time.time()
present = ck.connected_ids()
# For our existing keys, check which are present
for m in minion_keys:
# If we have a key that's not in the presence file,
# it may be a new minion # It could also mean this
# is the first time this engine is running and no
# presence file was found
if m not in minions:
minions[m] = now
elif m in present:
minions[m] = now
log.debug("Finished checking for present minions")
# Delete old keys
stale_keys = []
for m, seen in minions.items():
if now - expire > seen:
stale_keys.append(m)
if stale_keys:
minions = _delete_keys(stale_keys, minions)
error = _write_presence(presence_file, minions)
time.sleep(interval) | [
"def",
"start",
"(",
"interval",
"=",
"3600",
",",
"expire",
"=",
"604800",
")",
":",
"ck",
"=",
"salt",
".",
"utils",
".",
"minions",
".",
"CkMinions",
"(",
"__opts__",
")",
"presence_file",
"=",
"\"{}/presence.p\"",
".",
"format",
"(",
"__opts__",
"[",... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/engines/stalekey.py#L101-L144 | ||
pgq/skytools-legacy | 8b7e6c118572a605d28b7a3403c96aeecfd0d272 | python/skytools/scripting.py | python | BaseScript.reset | (self) | Something bad happened, reset all state. | Something bad happened, reset all state. | [
"Something",
"bad",
"happened",
"reset",
"all",
"state",
"."
] | def reset(self):
"Something bad happened, reset all state."
pass | [
"def",
"reset",
"(",
"self",
")",
":",
"pass"
] | https://github.com/pgq/skytools-legacy/blob/8b7e6c118572a605d28b7a3403c96aeecfd0d272/python/skytools/scripting.py#L531-L533 | ||
numenta/nupic | b9ebedaf54f49a33de22d8d44dff7c765cdb5548 | src/nupic/algorithms/backtracking_tm.py | python | BacktrackingTM.printParameters | (self) | Print the parameter settings for the TM. | Print the parameter settings for the TM. | [
"Print",
"the",
"parameter",
"settings",
"for",
"the",
"TM",
"."
] | def printParameters(self):
"""
Print the parameter settings for the TM.
"""
print "numberOfCols=", self.numberOfCols
print "cellsPerColumn=", self.cellsPerColumn
print "minThreshold=", self.minThreshold
print "newSynapseCount=", self.newSynapseCount
print "activationThreshold=", self.activationThreshold
print
print "initialPerm=", self.initialPerm
print "connectedPerm=", self.connectedPerm
print "permanenceInc=", self.permanenceInc
print "permanenceDec=", self.permanenceDec
print "permanenceMax=", self.permanenceMax
print "globalDecay=", self.globalDecay
print
print "doPooling=", self.doPooling
print "segUpdateValidDuration=", self.segUpdateValidDuration
print "pamLength=", self.pamLength | [
"def",
"printParameters",
"(",
"self",
")",
":",
"print",
"\"numberOfCols=\"",
",",
"self",
".",
"numberOfCols",
"print",
"\"cellsPerColumn=\"",
",",
"self",
".",
"cellsPerColumn",
"print",
"\"minThreshold=\"",
",",
"self",
".",
"minThreshold",
"print",
"\"newSynaps... | https://github.com/numenta/nupic/blob/b9ebedaf54f49a33de22d8d44dff7c765cdb5548/src/nupic/algorithms/backtracking_tm.py#L1126-L1145 | ||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/openpyxl-2.6.4/openpyxl/descriptors/base.py | python | _convert | (expected_type, value) | return value | Check value is of or can be converted to expected type. | Check value is of or can be converted to expected type. | [
"Check",
"value",
"is",
"of",
"or",
"can",
"be",
"converted",
"to",
"expected",
"type",
"."
] | def _convert(expected_type, value):
"""
Check value is of or can be converted to expected type.
"""
if not isinstance(value, expected_type):
try:
value = expected_type(value)
except:
raise TypeError('expected ' + str(expected_type))
return value | [
"def",
"_convert",
"(",
"expected_type",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"expected_type",
")",
":",
"try",
":",
"value",
"=",
"expected_type",
"(",
"value",
")",
"except",
":",
"raise",
"TypeError",
"(",
"'expected '",... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/openpyxl-2.6.4/openpyxl/descriptors/base.py#L51-L60 | |
pyg-team/pytorch_geometric | b920e9a3a64e22c8356be55301c88444ff051cae | torch_geometric/nn/conv/supergat_conv.py | python | SuperGATConv.positive_sampling | (self, edge_index: Tensor) | return pos_edge_index | [] | def positive_sampling(self, edge_index: Tensor) -> Tensor:
pos_edge_index, _ = dropout_adj(edge_index,
p=1. - self.edge_sample_ratio,
training=self.training)
return pos_edge_index | [
"def",
"positive_sampling",
"(",
"self",
",",
"edge_index",
":",
"Tensor",
")",
"->",
"Tensor",
":",
"pos_edge_index",
",",
"_",
"=",
"dropout_adj",
"(",
"edge_index",
",",
"p",
"=",
"1.",
"-",
"self",
".",
"edge_sample_ratio",
",",
"training",
"=",
"self"... | https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/nn/conv/supergat_conv.py#L249-L253 | |||
beeware/ouroboros | a29123c6fab6a807caffbb7587cf548e0c370296 | ouroboros/tkinter/__init__.py | python | Canvas.create_oval | (self, *args, **kw) | return self._create('oval', args, kw) | Create oval with coordinates x1,y1,x2,y2. | Create oval with coordinates x1,y1,x2,y2. | [
"Create",
"oval",
"with",
"coordinates",
"x1",
"y1",
"x2",
"y2",
"."
] | def create_oval(self, *args, **kw):
"""Create oval with coordinates x1,y1,x2,y2."""
return self._create('oval', args, kw) | [
"def",
"create_oval",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_create",
"(",
"'oval'",
",",
"args",
",",
"kw",
")"
] | https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/tkinter/__init__.py#L2336-L2338 | |
codelv/enaml-native | 04c3a015bcd649f374c5ecd98fcddba5e4fbdbdc | src/enamlnative/android/android_spinner.py | python | AndroidSpinner.init_widget | (self) | Initialize the underlying widget. | Initialize the underlying widget. | [
"Initialize",
"the",
"underlying",
"widget",
"."
] | def init_widget(self):
""" Initialize the underlying widget.
"""
w = self.widget
# Selection listener
w.setAdapter(self.adapter)
w.setOnItemSelectedListener(w.getId())
w.onItemSelected.connect(self.on_item_selected)
w.onNothingSelected.connect(self.on_nothing_selected)
super(AndroidSpinner, self).init_widget() | [
"def",
"init_widget",
"(",
"self",
")",
":",
"w",
"=",
"self",
".",
"widget",
"# Selection listener",
"w",
".",
"setAdapter",
"(",
"self",
".",
"adapter",
")",
"w",
".",
"setOnItemSelectedListener",
"(",
"w",
".",
"getId",
"(",
")",
")",
"w",
".",
"onI... | https://github.com/codelv/enaml-native/blob/04c3a015bcd649f374c5ecd98fcddba5e4fbdbdc/src/enamlnative/android/android_spinner.py#L65-L75 | ||
SFDO-Tooling/CumulusCI | 825ae1f122b25dc41761c52a4ddfa1938d2a4b6e | cumulusci/tasks/bulkdata/mapping_parser.py | python | parse_from_yaml | (source: Union[str, Path, IO]) | return MappingSteps.parse_from_yaml(source) | Parse from a path, url, path-like or file-like | Parse from a path, url, path-like or file-like | [
"Parse",
"from",
"a",
"path",
"url",
"path",
"-",
"like",
"or",
"file",
"-",
"like"
] | def parse_from_yaml(source: Union[str, Path, IO]) -> Dict:
"Parse from a path, url, path-like or file-like"
return MappingSteps.parse_from_yaml(source) | [
"def",
"parse_from_yaml",
"(",
"source",
":",
"Union",
"[",
"str",
",",
"Path",
",",
"IO",
"]",
")",
"->",
"Dict",
":",
"return",
"MappingSteps",
".",
"parse_from_yaml",
"(",
"source",
")"
] | https://github.com/SFDO-Tooling/CumulusCI/blob/825ae1f122b25dc41761c52a4ddfa1938d2a4b6e/cumulusci/tasks/bulkdata/mapping_parser.py#L474-L476 | |
tensorflow/models | 6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3 | official/legacy/transformer/data_download.py | python | get_raw_files | (raw_dir, data_source) | return raw_files | Return raw files from source.
Downloads/extracts if needed.
Args:
raw_dir: string directory to store raw files
data_source: dictionary with
{"url": url of compressed dataset containing input and target files
"input": file with data in input language
"target": file with data in target language}
Returns:
dictionary with
{"inputs": list of files containing data in input language
"targets": list of files containing corresponding data in target language
} | Return raw files from source. | [
"Return",
"raw",
"files",
"from",
"source",
"."
] | def get_raw_files(raw_dir, data_source):
"""Return raw files from source.
Downloads/extracts if needed.
Args:
raw_dir: string directory to store raw files
data_source: dictionary with
{"url": url of compressed dataset containing input and target files
"input": file with data in input language
"target": file with data in target language}
Returns:
dictionary with
{"inputs": list of files containing data in input language
"targets": list of files containing corresponding data in target language
}
"""
raw_files = {
"inputs": [],
"targets": [],
} # keys
for d in data_source:
input_file, target_file = download_and_extract(raw_dir, d["url"],
d["input"], d["target"])
raw_files["inputs"].append(input_file)
raw_files["targets"].append(target_file)
return raw_files | [
"def",
"get_raw_files",
"(",
"raw_dir",
",",
"data_source",
")",
":",
"raw_files",
"=",
"{",
"\"inputs\"",
":",
"[",
"]",
",",
"\"targets\"",
":",
"[",
"]",
",",
"}",
"# keys",
"for",
"d",
"in",
"data_source",
":",
"input_file",
",",
"target_file",
"=",
... | https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/legacy/transformer/data_download.py#L109-L136 | |
lvpengyuan/masktextspotter.caffe2 | da99ef31f5ccb4de5248bb881d5b4a291910c8ae | tools/train_net.py | python | test_model | (model_file, multi_gpu_testing, opts=None) | Test a model. | Test a model. | [
"Test",
"a",
"model",
"."
] | def test_model(model_file, multi_gpu_testing, opts=None):
"""Test a model."""
# All arguments to inference functions are passed via cfg
cfg.TEST.WEIGHTS = model_file
# Clear memory before inference
workspace.ResetWorkspace()
# Run inference
test_net.main(multi_gpu_testing=multi_gpu_testing) | [
"def",
"test_model",
"(",
"model_file",
",",
"multi_gpu_testing",
",",
"opts",
"=",
"None",
")",
":",
"# All arguments to inference functions are passed via cfg",
"cfg",
".",
"TEST",
".",
"WEIGHTS",
"=",
"model_file",
"# Clear memory before inference",
"workspace",
".",
... | https://github.com/lvpengyuan/masktextspotter.caffe2/blob/da99ef31f5ccb4de5248bb881d5b4a291910c8ae/tools/train_net.py#L359-L366 | ||
Kozea/WeasyPrint | 6cce2978165134e37683cb5b3d156cac6a11a7f9 | weasyprint/layout/preferred.py | python | _block_content_width | (context, box, function, outer) | return adjust(box, outer, width) | Helper to create ``block_*_content_width.`` | Helper to create ``block_*_content_width.`` | [
"Helper",
"to",
"create",
"block_",
"*",
"_content_width",
"."
] | def _block_content_width(context, box, function, outer):
"""Helper to create ``block_*_content_width.``"""
width = box.style['width']
if width == 'auto' or width.unit == '%':
# "percentages on the following properties are treated instead as
# though they were the following: width: auto"
# http://dbaron.org/css/intrinsic/#outer-intrinsic
children_widths = [
function(context, child, outer=True) for child in box.children
if not child.is_absolutely_positioned()]
width = max(children_widths) if children_widths else 0
else:
assert width.unit == 'px'
width = width.value
return adjust(box, outer, width) | [
"def",
"_block_content_width",
"(",
"context",
",",
"box",
",",
"function",
",",
"outer",
")",
":",
"width",
"=",
"box",
".",
"style",
"[",
"'width'",
"]",
"if",
"width",
"==",
"'auto'",
"or",
"width",
".",
"unit",
"==",
"'%'",
":",
"# \"percentages on t... | https://github.com/Kozea/WeasyPrint/blob/6cce2978165134e37683cb5b3d156cac6a11a7f9/weasyprint/layout/preferred.py#L90-L105 | |
exodrifter/unity-python | bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d | Lib/mhlib.py | python | Message.getbodytext | (self, decode = 1) | return output.getvalue() | Return the message's body text as string. This undoes a
Content-Transfer-Encoding, but does not interpret other MIME
features (e.g. multipart messages). To suppress decoding,
pass 0 as an argument. | Return the message's body text as string. This undoes a
Content-Transfer-Encoding, but does not interpret other MIME
features (e.g. multipart messages). To suppress decoding,
pass 0 as an argument. | [
"Return",
"the",
"message",
"s",
"body",
"text",
"as",
"string",
".",
"This",
"undoes",
"a",
"Content",
"-",
"Transfer",
"-",
"Encoding",
"but",
"does",
"not",
"interpret",
"other",
"MIME",
"features",
"(",
"e",
".",
"g",
".",
"multipart",
"messages",
")... | def getbodytext(self, decode = 1):
"""Return the message's body text as string. This undoes a
Content-Transfer-Encoding, but does not interpret other MIME
features (e.g. multipart messages). To suppress decoding,
pass 0 as an argument."""
self.fp.seek(self.startofbody)
encoding = self.getencoding()
if not decode or encoding in ('', '7bit', '8bit', 'binary'):
return self.fp.read()
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
output = StringIO()
mimetools.decode(self.fp, output, encoding)
return output.getvalue() | [
"def",
"getbodytext",
"(",
"self",
",",
"decode",
"=",
"1",
")",
":",
"self",
".",
"fp",
".",
"seek",
"(",
"self",
".",
"startofbody",
")",
"encoding",
"=",
"self",
".",
"getencoding",
"(",
")",
"if",
"not",
"decode",
"or",
"encoding",
"in",
"(",
"... | https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/mhlib.py#L695-L710 | |
microsoft/TextWorld | c419bb63a92c7f6960aa004a367fb18894043e7f | textworld/core.py | python | Wrapper.__call__ | (self, env: Environment) | return self | Args:
env: environment to wrap.
Returns:
The wrapped environment. | Args:
env: environment to wrap. | [
"Args",
":",
"env",
":",
"environment",
"to",
"wrap",
"."
] | def __call__(self, env: Environment) -> Environment:
"""
Args:
env: environment to wrap.
Returns:
The wrapped environment.
"""
self._wrap(env)
return self | [
"def",
"__call__",
"(",
"self",
",",
"env",
":",
"Environment",
")",
"->",
"Environment",
":",
"self",
".",
"_wrap",
"(",
"env",
")",
"return",
"self"
] | https://github.com/microsoft/TextWorld/blob/c419bb63a92c7f6960aa004a367fb18894043e7f/textworld/core.py#L300-L309 | |
MDudek-ICS/TRISIS-TRITON-HATMAN | 15a00af7fd1040f0430729d024427601f84886a1 | decompiled_code/library/fnmatch.py | python | fnmatch | (name, pat) | return fnmatchcase(name, pat) | Test whether FILENAME matches PATTERN.
Patterns are Unix shell style:
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
An initial period in FILENAME is not special.
Both FILENAME and PATTERN are first case-normalized
if the operating system requires it.
If you don't want this, use fnmatchcase(FILENAME, PATTERN). | Test whether FILENAME matches PATTERN.
Patterns are Unix shell style:
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
An initial period in FILENAME is not special.
Both FILENAME and PATTERN are first case-normalized
if the operating system requires it.
If you don't want this, use fnmatchcase(FILENAME, PATTERN). | [
"Test",
"whether",
"FILENAME",
"matches",
"PATTERN",
".",
"Patterns",
"are",
"Unix",
"shell",
"style",
":",
"*",
"matches",
"everything",
"?",
"matches",
"any",
"single",
"character",
"[",
"seq",
"]",
"matches",
"any",
"character",
"in",
"seq",
"[",
"!seq",
... | def fnmatch(name, pat):
"""Test whether FILENAME matches PATTERN.
Patterns are Unix shell style:
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
An initial period in FILENAME is not special.
Both FILENAME and PATTERN are first case-normalized
if the operating system requires it.
If you don't want this, use fnmatchcase(FILENAME, PATTERN).
"""
import os
name = os.path.normcase(name)
pat = os.path.normcase(pat)
return fnmatchcase(name, pat) | [
"def",
"fnmatch",
"(",
"name",
",",
"pat",
")",
":",
"import",
"os",
"name",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"name",
")",
"pat",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"pat",
")",
"return",
"fnmatchcase",
"(",
"name",
",",
"p... | https://github.com/MDudek-ICS/TRISIS-TRITON-HATMAN/blob/15a00af7fd1040f0430729d024427601f84886a1/decompiled_code/library/fnmatch.py#L29-L47 | |
MaybeShewill-CV/lanenet-lane-detection | 94be8d9a66c7bbda5ad99b10492bc406c8aee45f | data_provider/tf_io_pipline_tools.py | python | int64_feature | (value) | return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) | :return: | [] | def int64_feature(value):
"""
:return:
"""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) | [
"def",
"int64_feature",
"(",
"value",
")",
":",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"int64_list",
"=",
"tf",
".",
"train",
".",
"Int64List",
"(",
"value",
"=",
"[",
"value",
"]",
")",
")"
] | https://github.com/MaybeShewill-CV/lanenet-lane-detection/blob/94be8d9a66c7bbda5ad99b10492bc406c8aee45f/data_provider/tf_io_pipline_tools.py#L29-L34 | ||
PokemonGoF/PokemonGo-Bot-Desktop | 4bfa94f0183406c6a86f93645eff7abd3ad4ced8 | build/pywin/Lib/distutils/emxccompiler.py | python | get_versions | () | return (gcc_version, ld_version) | Try to find out the versions of gcc and ld.
If not possible it returns None for it. | Try to find out the versions of gcc and ld.
If not possible it returns None for it. | [
"Try",
"to",
"find",
"out",
"the",
"versions",
"of",
"gcc",
"and",
"ld",
".",
"If",
"not",
"possible",
"it",
"returns",
"None",
"for",
"it",
"."
] | def get_versions():
""" Try to find out the versions of gcc and ld.
If not possible it returns None for it.
"""
from distutils.version import StrictVersion
from distutils.spawn import find_executable
import re
gcc_exe = find_executable('gcc')
if gcc_exe:
out = os.popen(gcc_exe + ' -dumpversion','r')
try:
out_string = out.read()
finally:
out.close()
result = re.search('(\d+\.\d+\.\d+)',out_string)
if result:
gcc_version = StrictVersion(result.group(1))
else:
gcc_version = None
else:
gcc_version = None
# EMX ld has no way of reporting version number, and we use GCC
# anyway - so we can link OMF DLLs
ld_version = None
return (gcc_version, ld_version) | [
"def",
"get_versions",
"(",
")",
":",
"from",
"distutils",
".",
"version",
"import",
"StrictVersion",
"from",
"distutils",
".",
"spawn",
"import",
"find_executable",
"import",
"re",
"gcc_exe",
"=",
"find_executable",
"(",
"'gcc'",
")",
"if",
"gcc_exe",
":",
"o... | https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/distutils/emxccompiler.py#L294-L319 | |
privacyidea/privacyidea | 9490c12ddbf77a34ac935b082d09eb583dfafa2c | privacyidea/lib/tokens/u2ftoken.py | python | U2fTokenClass.create_challenge | (self, transactionid=None, options=None) | return True, message, db_challenge.transaction_id, reply_dict | This method creates a challenge, which is submitted to the user.
The submitted challenge will be preserved in the challenge
database.
If no transaction id is given, the system will create a transaction
id and return it, so that the response can refer to this transaction.
:param transactionid: the id of this challenge
:param options: the request context parameters / data
:type options: dict
:return: tuple of (bool, message, transactionid, attributes)
:rtype: tuple
The return tuple builds up like this:
``bool`` if submit was successful;
``message`` which is displayed in the JSON response;
additional challenge ``reply_dict``, which are displayed in the JSON challenges response. | This method creates a challenge, which is submitted to the user.
The submitted challenge will be preserved in the challenge
database. | [
"This",
"method",
"creates",
"a",
"challenge",
"which",
"is",
"submitted",
"to",
"the",
"user",
".",
"The",
"submitted",
"challenge",
"will",
"be",
"preserved",
"in",
"the",
"challenge",
"database",
"."
] | def create_challenge(self, transactionid=None, options=None):
"""
This method creates a challenge, which is submitted to the user.
The submitted challenge will be preserved in the challenge
database.
If no transaction id is given, the system will create a transaction
id and return it, so that the response can refer to this transaction.
:param transactionid: the id of this challenge
:param options: the request context parameters / data
:type options: dict
:return: tuple of (bool, message, transactionid, attributes)
:rtype: tuple
The return tuple builds up like this:
``bool`` if submit was successful;
``message`` which is displayed in the JSON response;
additional challenge ``reply_dict``, which are displayed in the JSON challenges response.
"""
options = options or {}
message = get_action_values_from_options(SCOPE.AUTH,
"{0!s}_{1!s}".format(self.get_class_type(),
ACTION.CHALLENGETEXT),
options)or _(u'Please confirm with your U2F token ({0!s})').format(
self.token.description)
validity = int(get_from_config('DefaultChallengeValidityTime', 120))
tokentype = self.get_tokentype().lower()
lookup_for = tokentype.capitalize() + 'ChallengeValidityTime'
validity = int(get_from_config(lookup_for, validity))
# if a transaction id is given, check if there are other u2f token and
# reuse the challenge
challenge = None
if transactionid:
for c in get_challenges(transaction_id=transactionid):
if get_tokens(serial=c.serial, tokentype=self.get_class_type(),
count=True):
challenge = c.challenge
break
if not challenge:
nonce = geturandom(32)
challenge = hexlify_and_unicode(nonce)
else:
nonce = binascii.unhexlify(challenge)
# Create the challenge in the database
db_challenge = Challenge(self.token.serial,
transaction_id=transactionid,
challenge=challenge,
data=None,
session=options.get("session"),
validitytime=validity)
db_challenge.save()
sec_object = self.token.get_otpkey()
key_handle_hex = sec_object.getKey()
key_handle_bin = binascii.unhexlify(key_handle_hex)
key_handle_url = url_encode(key_handle_bin)
challenge_url = url_encode(nonce)
u2f_sign_request = {"appId": self.get_tokeninfo("appId"),
"version": U2F_Version,
"challenge": challenge_url,
"keyHandle": key_handle_url}
image_url = IMAGES.get(self.token.description.lower().split()[0], "")
reply_dict = {"attributes": {"u2fSignRequest": u2f_sign_request,
"hideResponseInput": self.client_mode != CLIENTMODE.INTERACTIVE,
"img": image_url},
"image": image_url}
return True, message, db_challenge.transaction_id, reply_dict | [
"def",
"create_challenge",
"(",
"self",
",",
"transactionid",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"message",
"=",
"get_action_values_from_options",
"(",
"SCOPE",
".",
"AUTH",
",",
"\"{0!s}_{1!s}\"",
... | https://github.com/privacyidea/privacyidea/blob/9490c12ddbf77a34ac935b082d09eb583dfafa2c/privacyidea/lib/tokens/u2ftoken.py#L419-L491 | |
ahmetcemturan/SFACT | 7576e29ba72b33e5058049b77b7b558875542747 | skeinforge_application/skeinforge_plugins/craft_plugins/fillet.py | python | BevelSkein.parseInitialization | ( self, repository ) | Parse gcode initialization and store the parameters. | Parse gcode initialization and store the parameters. | [
"Parse",
"gcode",
"initialization",
"and",
"store",
"the",
"parameters",
"."
] | def parseInitialization( self, repository ):
'Parse gcode initialization and store the parameters.'
for self.lineIndex in xrange(len(self.lines)):
line = self.lines[self.lineIndex]
splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
firstWord = gcodec.getFirstWord(splitLine)
self.distanceFeedRate.parseSplitLine(firstWord, splitLine)
if firstWord == '(</extruderInitialization>)':
self.distanceFeedRate.addTagBracketedProcedure('fillet')
return
elif firstWord == '(<edgeWidth>':
edgeWidth = abs(float(splitLine[1]))
self.curveSection = 0.7 * edgeWidth
self.filletRadius = edgeWidth/2
self.minimumRadius = 0.1 * edgeWidth
self.reversalSlowdownDistance = edgeWidth * repository.reversalSlowdownDistanceOverEdgeWidth.value
self.distanceFeedRate.addLine(line) | [
"def",
"parseInitialization",
"(",
"self",
",",
"repository",
")",
":",
"for",
"self",
".",
"lineIndex",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"lines",
")",
")",
":",
"line",
"=",
"self",
".",
"lines",
"[",
"self",
".",
"lineIndex",
"]",
"spl... | https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/skeinforge_application/skeinforge_plugins/craft_plugins/fillet.py#L198-L214 | ||
exodrifter/unity-python | bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d | Lib/pprint.py | python | pprint | (object, stream=None, indent=1, width=80, depth=None) | Pretty-print a Python object to a stream [default is sys.stdout]. | Pretty-print a Python object to a stream [default is sys.stdout]. | [
"Pretty",
"-",
"print",
"a",
"Python",
"object",
"to",
"a",
"stream",
"[",
"default",
"is",
"sys",
".",
"stdout",
"]",
"."
] | def pprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
printer = PrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object) | [
"def",
"pprint",
"(",
"object",
",",
"stream",
"=",
"None",
",",
"indent",
"=",
"1",
",",
"width",
"=",
"80",
",",
"depth",
"=",
"None",
")",
":",
"printer",
"=",
"PrettyPrinter",
"(",
"stream",
"=",
"stream",
",",
"indent",
"=",
"indent",
",",
"wi... | https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/pprint.py#L55-L59 | ||
malwaredllc/byob | 3924dd6aea6d0421397cdf35f692933b340bfccf | web-gui/buildyourownbotnet/core/payloads.py | python | Payload.show | (self, attribute) | Show value of an attribute
`Required`
:param str attribute: payload attribute to show
Returns attribute(s) as a dictionary (JSON) object | Show value of an attribute | [
"Show",
"value",
"of",
"an",
"attribute"
] | def show(self, attribute):
"""
Show value of an attribute
`Required`
:param str attribute: payload attribute to show
Returns attribute(s) as a dictionary (JSON) object
"""
try:
attribute = str(attribute)
if 'jobs' in attribute:
return json.dumps({a: status(self.handlers[a].name) for a in self.handlers if self.handlers[a].is_alive()})
elif 'info' in attribute:
return json.dumps(self.info)
elif hasattr(self, attribute):
try:
return json.dumps(getattr(self, attribute))
except:
try:
return json.dumps(vars(getattr(self, attribute)))
except: pass
elif hasattr(self, str('_%s' % attribute)):
try:
return json.dumps(getattr(self, str('_%s' % attribute)))
except:
try:
return json.dumps(vars(getattr(self, str('_%s' % attribute))))
except: pass
else:
return self.show.usage
except Exception as e:
log("'{}' error: {}".format(self.show.__name__, str(e))) | [
"def",
"show",
"(",
"self",
",",
"attribute",
")",
":",
"try",
":",
"attribute",
"=",
"str",
"(",
"attribute",
")",
"if",
"'jobs'",
"in",
"attribute",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"a",
":",
"status",
"(",
"self",
".",
"handlers",
... | https://github.com/malwaredllc/byob/blob/3924dd6aea6d0421397cdf35f692933b340bfccf/web-gui/buildyourownbotnet/core/payloads.py#L477-L510 | ||
androguard/androguard | 8d091cbb309c0c50bf239f805cc1e0931b8dcddc | androguard/core/analysis/auto.py | python | DefaultAndroAnalysis.finish | (self, log) | This method is called before the end of the analysis
:param log: an object which corresponds to an unique app | This method is called before the end of the analysis | [
"This",
"method",
"is",
"called",
"before",
"the",
"end",
"of",
"the",
"analysis"
] | def finish(self, log):
"""
This method is called before the end of the analysis
:param log: an object which corresponds to an unique app
"""
pass | [
"def",
"finish",
"(",
"self",
",",
"log",
")",
":",
"pass"
] | https://github.com/androguard/androguard/blob/8d091cbb309c0c50bf239f805cc1e0931b8dcddc/androguard/core/analysis/auto.py#L387-L393 | ||
CalciferZh/SMPL | efb0741db05e074fd66a32e7b40d4ce0357af7ed | smpl_tf.py | python | pack | (x) | return ret | Append zero tensors of shape [4, 3] to a batch of [4, 1] shape tensor.
Parameter:
----------
x: A tensor of shape [batch_size, 4, 1]
Return:
------
A tensor of shape [batch_size, 4, 4] after appending. | Append zero tensors of shape [4, 3] to a batch of [4, 1] shape tensor. | [
"Append",
"zero",
"tensors",
"of",
"shape",
"[",
"4",
"3",
"]",
"to",
"a",
"batch",
"of",
"[",
"4",
"1",
"]",
"shape",
"tensor",
"."
] | def pack(x):
"""
Append zero tensors of shape [4, 3] to a batch of [4, 1] shape tensor.
Parameter:
----------
x: A tensor of shape [batch_size, 4, 1]
Return:
------
A tensor of shape [batch_size, 4, 4] after appending.
"""
ret = tf.concat(
(tf.zeros((x.get_shape().as_list()[0], 4, 3), dtype=tf.float64), x),
axis=2
)
return ret | [
"def",
"pack",
"(",
"x",
")",
":",
"ret",
"=",
"tf",
".",
"concat",
"(",
"(",
"tf",
".",
"zeros",
"(",
"(",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"0",
"]",
",",
"4",
",",
"3",
")",
",",
"dtype",
"=",
"tf",
".",
... | https://github.com/CalciferZh/SMPL/blob/efb0741db05e074fd66a32e7b40d4ce0357af7ed/smpl_tf.py#L58-L75 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/traceback.py | python | print_exc | (limit=None, file=None, chain=True) | Shorthand for 'print_exception(*sys.exc_info(), limit, file)'. | Shorthand for 'print_exception(*sys.exc_info(), limit, file)'. | [
"Shorthand",
"for",
"print_exception",
"(",
"*",
"sys",
".",
"exc_info",
"()",
"limit",
"file",
")",
"."
] | def print_exc(limit=None, file=None, chain=True):
"""Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain) | [
"def",
"print_exc",
"(",
"limit",
"=",
"None",
",",
"file",
"=",
"None",
",",
"chain",
"=",
"True",
")",
":",
"print_exception",
"(",
"*",
"sys",
".",
"exc_info",
"(",
")",
",",
"limit",
"=",
"limit",
",",
"file",
"=",
"file",
",",
"chain",
"=",
... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/traceback.py#L177-L179 | ||
morepath/morepath | 09972904229f807da75c75d8825af1495057acdc | morepath/app.py | python | App._verify_identity | (self, identity) | return False | Returns True if the claimed identity can be verified.
Look in the database to verify the identity, or in case of auth
tokens, always consider known identities to be correct.
:param: :class:`morepath.Identity` instance.
:return: ``True`` if identity can be verified. By default no identity
can be verified so this returns ``False``. | Returns True if the claimed identity can be verified. | [
"Returns",
"True",
"if",
"the",
"claimed",
"identity",
"can",
"be",
"verified",
"."
] | def _verify_identity(self, identity):
"""Returns True if the claimed identity can be verified.
Look in the database to verify the identity, or in case of auth
tokens, always consider known identities to be correct.
:param: :class:`morepath.Identity` instance.
:return: ``True`` if identity can be verified. By default no identity
can be verified so this returns ``False``.
"""
return False | [
"def",
"_verify_identity",
"(",
"self",
",",
"identity",
")",
":",
"return",
"False"
] | https://github.com/morepath/morepath/blob/09972904229f807da75c75d8825af1495057acdc/morepath/app.py#L313-L323 | |
oxwhirl/smac | 456d133f40030e60f27bc7a85d2c5bdf96f6ad56 | smac/env/multiagentenv.py | python | MultiAgentEnv.save_replay | (self) | Save a replay. | Save a replay. | [
"Save",
"a",
"replay",
"."
] | def save_replay(self):
"""Save a replay."""
raise NotImplementedError | [
"def",
"save_replay",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/oxwhirl/smac/blob/456d133f40030e60f27bc7a85d2c5bdf96f6ad56/smac/env/multiagentenv.py#L56-L58 | ||
magenta/magenta | be6558f1a06984faff6d6949234f5fe9ad0ffdb5 | magenta/models/gansynth/lib/generate_util.py | python | get_random_instruments | (model, total_time, secs_per_instrument=2.0) | return z_instruments, t_instruments | Get random latent vectors evenly spaced in time. | Get random latent vectors evenly spaced in time. | [
"Get",
"random",
"latent",
"vectors",
"evenly",
"spaced",
"in",
"time",
"."
] | def get_random_instruments(model, total_time, secs_per_instrument=2.0):
"""Get random latent vectors evenly spaced in time."""
n_instruments = int(total_time / secs_per_instrument)
z_instruments = model.generate_z(n_instruments)
t_instruments = np.linspace(-.0001, total_time, n_instruments)
return z_instruments, t_instruments | [
"def",
"get_random_instruments",
"(",
"model",
",",
"total_time",
",",
"secs_per_instrument",
"=",
"2.0",
")",
":",
"n_instruments",
"=",
"int",
"(",
"total_time",
"/",
"secs_per_instrument",
")",
"z_instruments",
"=",
"model",
".",
"generate_z",
"(",
"n_instrumen... | https://github.com/magenta/magenta/blob/be6558f1a06984faff6d6949234f5fe9ad0ffdb5/magenta/models/gansynth/lib/generate_util.py#L52-L57 | |
pysathq/pysat | 07bf3a5a4428d40eca804e7ebdf4f496aadf4213 | pysat/solvers.py | python | Solver.get_status | (self) | The result of a previous SAT call is stored in an internal
variable and can be later obtained using this method.
:rtype: Boolean or ``None``.
``None`` is returned if a previous SAT call was interrupted. | The result of a previous SAT call is stored in an internal
variable and can be later obtained using this method. | [
"The",
"result",
"of",
"a",
"previous",
"SAT",
"call",
"is",
"stored",
"in",
"an",
"internal",
"variable",
"and",
"can",
"be",
"later",
"obtained",
"using",
"this",
"method",
"."
] | def get_status(self):
"""
The result of a previous SAT call is stored in an internal
variable and can be later obtained using this method.
:rtype: Boolean or ``None``.
``None`` is returned if a previous SAT call was interrupted.
"""
if self.solver:
return self.solver.get_status() | [
"def",
"get_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"solver",
":",
"return",
"self",
".",
"solver",
".",
"get_status",
"(",
")"
] | https://github.com/pysathq/pysat/blob/07bf3a5a4428d40eca804e7ebdf4f496aadf4213/pysat/solvers.py#L733-L744 | ||
Veil-Framework/Veil | c825577bbc97db04be5c47e004369038491f6b7a | tools/ordnance/payloads/x86/rev_tcp.py | python | ShellcodeModule.gen_shellcode | (self) | return | Invoked by main menu, generates code | Invoked by main menu, generates code | [
"Invoked",
"by",
"main",
"menu",
"generates",
"code"
] | def gen_shellcode(self):
'''Invoked by main menu, generates code'''
self.payload_gen()
return | [
"def",
"gen_shellcode",
"(",
"self",
")",
":",
"self",
".",
"payload_gen",
"(",
")",
"return"
] | https://github.com/Veil-Framework/Veil/blob/c825577bbc97db04be5c47e004369038491f6b7a/tools/ordnance/payloads/x86/rev_tcp.py#L60-L63 | |
andrewowens/multisensory | 8a5b44a7294a9440c72075ef433b1011a1ba2d9e | src/aolib/util.py | python | check_print | (b, msg = None) | Prints the assert message to stderr if it failed | Prints the assert message to stderr if it failed | [
"Prints",
"the",
"assert",
"message",
"to",
"stderr",
"if",
"it",
"failed"
] | def check_print(b, msg = None):
""" Prints the assert message to stderr if it failed """
if not b:
if msg is not None:
print >>sys.stderr, msg
fail('Check failed %s' % ('' if msg is None else msg)) | [
"def",
"check_print",
"(",
"b",
",",
"msg",
"=",
"None",
")",
":",
"if",
"not",
"b",
":",
"if",
"msg",
"is",
"not",
"None",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"msg",
"fail",
"(",
"'Check failed %s'",
"%",
"(",
"''",
"if",
"msg",
"is",... | https://github.com/andrewowens/multisensory/blob/8a5b44a7294a9440c72075ef433b1011a1ba2d9e/src/aolib/util.py#L1904-L1909 | ||
cortex-lab/phy | 9a330b9437a3d0b40a37a201d147224e6e7fb462 | phy/plot/interact.py | python | Stacked.update_visual | (self, visual) | Update a visual. | Update a visual. | [
"Update",
"a",
"visual",
"."
] | def update_visual(self, visual):
"""Update a visual."""
BaseLayout.update_visual(self, visual)
if 'n_boxes' in visual.program:
visual.program['n_boxes'] = self.n_boxes
visual.program['u_box_size'] = self._box_scaling
visual.program['u_top_origin'] = self._origin == 'top' | [
"def",
"update_visual",
"(",
"self",
",",
"visual",
")",
":",
"BaseLayout",
".",
"update_visual",
"(",
"self",
",",
"visual",
")",
"if",
"'n_boxes'",
"in",
"visual",
".",
"program",
":",
"visual",
".",
"program",
"[",
"'n_boxes'",
"]",
"=",
"self",
".",
... | https://github.com/cortex-lab/phy/blob/9a330b9437a3d0b40a37a201d147224e6e7fb462/phy/plot/interact.py#L407-L413 | ||
mikedh/trimesh | 6b1e05616b44e6dd708d9bc748b211656ebb27ec | trimesh/base.py | python | Trimesh.area_faces | (self) | return area_faces | The area of each face in the mesh.
Returns
---------
area_faces : (n, ) float
Area of each face | The area of each face in the mesh. | [
"The",
"area",
"of",
"each",
"face",
"in",
"the",
"mesh",
"."
] | def area_faces(self):
"""
The area of each face in the mesh.
Returns
---------
area_faces : (n, ) float
Area of each face
"""
area_faces = triangles.area(
crosses=self.triangles_cross,
sum=False)
return area_faces | [
"def",
"area_faces",
"(",
"self",
")",
":",
"area_faces",
"=",
"triangles",
".",
"area",
"(",
"crosses",
"=",
"self",
".",
"triangles_cross",
",",
"sum",
"=",
"False",
")",
"return",
"area_faces"
] | https://github.com/mikedh/trimesh/blob/6b1e05616b44e6dd708d9bc748b211656ebb27ec/trimesh/base.py#L2555-L2567 | |
noamraph/dreampie | b09ee546ec099ee6549c649692ceb129e05fb229 | dulwich/diff_tree.py | python | RenameDetector.changes_with_renames | (self, tree1_id, tree2_id, want_unchanged=False) | return self._sorted_changes() | Iterate TreeChanges between two tree SHAs, with rename detection. | Iterate TreeChanges between two tree SHAs, with rename detection. | [
"Iterate",
"TreeChanges",
"between",
"two",
"tree",
"SHAs",
"with",
"rename",
"detection",
"."
] | def changes_with_renames(self, tree1_id, tree2_id, want_unchanged=False):
"""Iterate TreeChanges between two tree SHAs, with rename detection."""
self._reset()
self._want_unchanged = want_unchanged
self._collect_changes(tree1_id, tree2_id)
self._find_exact_renames()
self._find_content_rename_candidates()
self._choose_content_renames()
self._join_modifies()
self._prune_unchanged()
return self._sorted_changes() | [
"def",
"changes_with_renames",
"(",
"self",
",",
"tree1_id",
",",
"tree2_id",
",",
"want_unchanged",
"=",
"False",
")",
":",
"self",
".",
"_reset",
"(",
")",
"self",
".",
"_want_unchanged",
"=",
"want_unchanged",
"self",
".",
"_collect_changes",
"(",
"tree1_id... | https://github.com/noamraph/dreampie/blob/b09ee546ec099ee6549c649692ceb129e05fb229/dulwich/diff_tree.py#L567-L577 | |
los-cocos/cocos | 3b47281f95d6ee52bb2a357a767f213e670bd601 | cocos/mapcolliders.py | python | RectMapCollider.collide_top | (self, obj) | placeholder, called when collision with obj's top side detected | placeholder, called when collision with obj's top side detected | [
"placeholder",
"called",
"when",
"collision",
"with",
"obj",
"s",
"top",
"side",
"detected"
] | def collide_top(self, obj):
"""placeholder, called when collision with obj's top side detected"""
pass | [
"def",
"collide_top",
"(",
"self",
",",
"obj",
")",
":",
"pass"
] | https://github.com/los-cocos/cocos/blob/3b47281f95d6ee52bb2a357a767f213e670bd601/cocos/mapcolliders.py#L96-L98 | ||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-0.96/django/contrib/auth/decorators.py | python | permission_required | (perm, login_url=LOGIN_URL) | return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url) | Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if necessary. | Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if necessary. | [
"Decorator",
"for",
"views",
"that",
"checks",
"whether",
"a",
"user",
"has",
"a",
"particular",
"permission",
"enabled",
"redirecting",
"to",
"the",
"log",
"-",
"in",
"page",
"if",
"necessary",
"."
] | def permission_required(perm, login_url=LOGIN_URL):
"""
Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if necessary.
"""
return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url) | [
"def",
"permission_required",
"(",
"perm",
",",
"login_url",
"=",
"LOGIN_URL",
")",
":",
"return",
"user_passes_test",
"(",
"lambda",
"u",
":",
"u",
".",
"has_perm",
"(",
"perm",
")",
",",
"login_url",
"=",
"login_url",
")"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-0.96/django/contrib/auth/decorators.py#L30-L35 | |
asappresearch/flambe | 98f10f859fe9223fd2d1d76d430f77cdbddc0956 | flambe/nn/distance/hyperbolic.py | python | norm | (x) | return n | Compute the norm | Compute the norm | [
"Compute",
"the",
"norm"
] | def norm(x):
"""Compute the norm"""
n = torch.sqrt(torch.abs(mdot(x, x)))
return n | [
"def",
"norm",
"(",
"x",
")",
":",
"n",
"=",
"torch",
".",
"sqrt",
"(",
"torch",
".",
"abs",
"(",
"mdot",
"(",
"x",
",",
"x",
")",
")",
")",
"return",
"n"
] | https://github.com/asappresearch/flambe/blob/98f10f859fe9223fd2d1d76d430f77cdbddc0956/flambe/nn/distance/hyperbolic.py#L42-L45 | |
twisted/twisted | dee676b040dd38b847ea6fb112a712cb5e119490 | src/twisted/web/client.py | python | HTTPConnectionPool._putConnection | (self, key, connection) | Return a persistent connection to the pool. This will be called by
L{HTTP11ClientProtocol} when the connection becomes quiescent. | Return a persistent connection to the pool. This will be called by
L{HTTP11ClientProtocol} when the connection becomes quiescent. | [
"Return",
"a",
"persistent",
"connection",
"to",
"the",
"pool",
".",
"This",
"will",
"be",
"called",
"by",
"L",
"{",
"HTTP11ClientProtocol",
"}",
"when",
"the",
"connection",
"becomes",
"quiescent",
"."
] | def _putConnection(self, key, connection):
"""
Return a persistent connection to the pool. This will be called by
L{HTTP11ClientProtocol} when the connection becomes quiescent.
"""
if connection.state != "QUIESCENT":
# Log with traceback for debugging purposes:
try:
raise RuntimeError(
"BUG: Non-quiescent protocol added to connection pool."
)
except BaseException:
self._log.failure(
"BUG: Non-quiescent protocol added to connection pool."
)
return
connections = self._connections.setdefault(key, [])
if len(connections) == self.maxPersistentPerHost:
dropped = connections.pop(0)
dropped.transport.loseConnection()
self._timeouts[dropped].cancel()
del self._timeouts[dropped]
connections.append(connection)
cid = self._reactor.callLater(
self.cachedConnectionTimeout, self._removeConnection, key, connection
)
self._timeouts[connection] = cid | [
"def",
"_putConnection",
"(",
"self",
",",
"key",
",",
"connection",
")",
":",
"if",
"connection",
".",
"state",
"!=",
"\"QUIESCENT\"",
":",
"# Log with traceback for debugging purposes:",
"try",
":",
"raise",
"RuntimeError",
"(",
"\"BUG: Non-quiescent protocol added to... | https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/web/client.py#L1427-L1453 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_configmap.py | python | OCConfigMap.run_ansible | (params, check_mode) | return {'failed': True, 'msg': 'Unknown state passed. {}'.format(state)} | run the ansible idempotent code | run the ansible idempotent code | [
"run",
"the",
"ansible",
"idempotent",
"code"
] | def run_ansible(params, check_mode):
'''run the ansible idempotent code'''
oc_cm = OCConfigMap(params['name'],
params['from_file'],
params['from_literal'],
params['state'],
params['namespace'],
kubeconfig=params['kubeconfig'],
verbose=params['debug'])
state = params['state']
api_rval = oc_cm.get()
if 'failed' in api_rval:
return {'failed': True, 'msg': api_rval}
#####
# Get
#####
if state == 'list':
return {'changed': False, 'results': api_rval, 'state': state}
if not params['name']:
return {'failed': True,
'msg': 'Please specify a name when state is absent|present.'}
########
# Delete
########
if state == 'absent':
if not Utils.exists(api_rval['results'], params['name']):
return {'changed': False, 'state': 'absent'}
if check_mode:
return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete.'}
api_rval = oc_cm.delete()
if api_rval['returncode'] != 0:
return {'failed': True, 'msg': api_rval}
return {'changed': True, 'results': api_rval, 'state': state}
########
# Create
########
if state == 'present':
if not Utils.exists(api_rval['results'], params['name']):
if check_mode:
return {'changed': True, 'msg': 'Would have performed a create.'}
api_rval = oc_cm.create()
if api_rval['returncode'] != 0:
return {'failed': True, 'msg': api_rval}
api_rval = oc_cm.get()
if api_rval['returncode'] != 0:
return {'failed': True, 'msg': api_rval}
return {'changed': True, 'results': api_rval, 'state': state}
########
# Update
########
if oc_cm.needs_update():
api_rval = oc_cm.update()
if api_rval['returncode'] != 0:
return {'failed': True, 'msg': api_rval}
api_rval = oc_cm.get()
if api_rval['returncode'] != 0:
return {'failed': True, 'msg': api_rval}
return {'changed': True, 'results': api_rval, 'state': state}
return {'changed': False, 'results': api_rval, 'state': state}
return {'failed': True, 'msg': 'Unknown state passed. {}'.format(state)} | [
"def",
"run_ansible",
"(",
"params",
",",
"check_mode",
")",
":",
"oc_cm",
"=",
"OCConfigMap",
"(",
"params",
"[",
"'name'",
"]",
",",
"params",
"[",
"'from_file'",
"]",
",",
"params",
"[",
"'from_literal'",
"]",
",",
"params",
"[",
"'state'",
"]",
",",
... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_configmap.py#L1565-L1650 | |
markovmodel/PyEMMA | e9d08d715dde17ceaa96480a9ab55d5e87d3a4b3 | versioneer.py | python | register_vcs_handler | (vcs, method) | return decorate | Decorator to mark a method as the handler for a particular VCS. | Decorator to mark a method as the handler for a particular VCS. | [
"Decorator",
"to",
"mark",
"a",
"method",
"as",
"the",
"handler",
"for",
"a",
"particular",
"VCS",
"."
] | def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate | [
"def",
"register_vcs_handler",
"(",
"vcs",
",",
"method",
")",
":",
"# decorator",
"def",
"decorate",
"(",
"f",
")",
":",
"\"\"\"Store f in HANDLERS[vcs][method].\"\"\"",
"if",
"vcs",
"not",
"in",
"HANDLERS",
":",
"HANDLERS",
"[",
"vcs",
"]",
"=",
"{",
"}",
... | https://github.com/markovmodel/PyEMMA/blob/e9d08d715dde17ceaa96480a9ab55d5e87d3a4b3/versioneer.py#L373-L381 | |
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | rpython/translator/translator.py | python | TranslationContext.about | (self, x, f=None) | Interactive debugging helper | Interactive debugging helper | [
"Interactive",
"debugging",
"helper"
] | def about(self, x, f=None):
"""Interactive debugging helper """
if f is None:
f = sys.stdout
if isinstance(x, Block):
for graph in self.graphs:
if x in graph.iterblocks():
print >>f, '%s is a %s' % (x, x.__class__)
print >>f, 'in %s' % (graph,)
break
else:
print >>f, '%s is a %s at some unknown location' % (
x, x.__class__.__name__)
print >>f, 'containing the following operations:'
for op in x.operations:
print >>f, " ",op
print >>f, '--end--'
return
raise TypeError("don't know about %r" % x) | [
"def",
"about",
"(",
"self",
",",
"x",
",",
"f",
"=",
"None",
")",
":",
"if",
"f",
"is",
"None",
":",
"f",
"=",
"sys",
".",
"stdout",
"if",
"isinstance",
"(",
"x",
",",
"Block",
")",
":",
"for",
"graph",
"in",
"self",
".",
"graphs",
":",
"if"... | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/rpython/translator/translator.py#L99-L117 | ||
GNS3/gns3-gui | da8adbaa18ab60e053af2a619efd468f4c8950f3 | gns3/spice_console.py | python | spiceConsole | (node, port, command) | Start a SPICE console program.
:param node: Node instance
:param port: port number
:param command: command to be executed | Start a SPICE console program. | [
"Start",
"a",
"SPICE",
"console",
"program",
"."
] | def spiceConsole(node, port, command):
"""
Start a SPICE console program.
:param node: Node instance
:param port: port number
:param command: command to be executed
"""
if len(command.strip(' ')) == 0:
log.error("SPICE client is not configured")
return
name = node.name()
host = node.consoleHost()
# ipv6 support
if ":" in host:
host = "[{}]".format(host)
# replace the place-holders by the actual values
command = command.replace("%h", host)
command = command.replace("%p", str(port))
command = command.replace("%d", name.replace('"', '\\"'))
command = command.replace("%i", node.project().id())
command = command.replace("%n", str(node.id()))
try:
log.debug('starting SPICE program "{}"'.format(command))
if sys.platform.startswith("win"):
# use the string on Windows
subprocess.Popen(command)
else:
# use arguments on other platforms
args = shlex.split(command)
subprocess.Popen(args, env=os.environ)
except (OSError, ValueError, subprocess.SubprocessError) as e:
log.error("Could not start SPICE program with command '{}': {}".format(command, e)) | [
"def",
"spiceConsole",
"(",
"node",
",",
"port",
",",
"command",
")",
":",
"if",
"len",
"(",
"command",
".",
"strip",
"(",
"' '",
")",
")",
"==",
"0",
":",
"log",
".",
"error",
"(",
"\"SPICE client is not configured\"",
")",
"return",
"name",
"=",
"nod... | https://github.com/GNS3/gns3-gui/blob/da8adbaa18ab60e053af2a619efd468f4c8950f3/gns3/spice_console.py#L33-L70 | ||
rowliny/DiffHelper | ab3a96f58f9579d0023aed9ebd785f4edf26f8af | Tool/SitePackages/click/core.py | python | Command.format_options | (self, ctx: Context, formatter: HelpFormatter) | Writes all the options into the formatter if they exist. | Writes all the options into the formatter if they exist. | [
"Writes",
"all",
"the",
"options",
"into",
"the",
"formatter",
"if",
"they",
"exist",
"."
] | def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
"""Writes all the options into the formatter if they exist."""
opts = []
for param in self.get_params(ctx):
rv = param.get_help_record(ctx)
if rv is not None:
opts.append(rv)
if opts:
with formatter.section(_("Options")):
formatter.write_dl(opts) | [
"def",
"format_options",
"(",
"self",
",",
"ctx",
":",
"Context",
",",
"formatter",
":",
"HelpFormatter",
")",
"->",
"None",
":",
"opts",
"=",
"[",
"]",
"for",
"param",
"in",
"self",
".",
"get_params",
"(",
"ctx",
")",
":",
"rv",
"=",
"param",
".",
... | https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/click/core.py#L1342-L1352 | ||
Unidata/siphon | d8ede355114801bf7a05db20dfe49ab132723f86 | src/siphon/simplewebservice/ndbc.py | python | NDBC._parse_cwind | (content) | return df | Parse continuous wind data (10 minute average).
Parameters
----------
content : str
Data to parse
Returns
-------
:class:`pandas.DataFrame` containing the data | Parse continuous wind data (10 minute average). | [
"Parse",
"continuous",
"wind",
"data",
"(",
"10",
"minute",
"average",
")",
"."
] | def _parse_cwind(content):
"""Parse continuous wind data (10 minute average).
Parameters
----------
content : str
Data to parse
Returns
-------
:class:`pandas.DataFrame` containing the data
"""
col_names = ['year', 'month', 'day', 'hour', 'minute',
'wind_direction', 'wind_speed', 'gust_direction',
'wind_gust', 'gust_time']
col_units = {'wind_direction': 'degrees',
'wind_speed': 'meters/second',
'gust_direction': 'degrees',
'wind_gust': 'meters/second',
'gust_time': None,
'time': None}
df = pd.read_csv(StringIO(content), comment='#', na_values='MM',
names=col_names, sep=r'\s+')
df['gust_direction'] = df['gust_direction'].replace(999, np.nan)
df['wind_gust'] = df['wind_gust'].replace(99.0, np.nan)
df['time'] = pd.to_datetime(df[['year', 'month', 'day', 'hour', 'minute']], utc=True)
df['hours'] = np.floor(df['gust_time'] / 100)
df['minutes'] = df['gust_time'] - df['hours'] * 100
df['hours'] = df['hours'].replace(99, np.nan)
df['minutes'] = df['minutes'].replace(99, np.nan)
df['gust_time'] = pd.to_datetime(df[['year', 'month', 'day', 'hours', 'minutes']],
utc=True)
df = df.drop(columns=['year', 'month', 'day', 'hour', 'minute',
'hours', 'minutes'])
df.units = col_units
return df | [
"def",
"_parse_cwind",
"(",
"content",
")",
":",
"col_names",
"=",
"[",
"'year'",
",",
"'month'",
",",
"'day'",
",",
"'hour'",
",",
"'minute'",
",",
"'wind_direction'",
",",
"'wind_speed'",
",",
"'gust_direction'",
",",
"'wind_gust'",
",",
"'gust_time'",
"]",
... | https://github.com/Unidata/siphon/blob/d8ede355114801bf7a05db20dfe49ab132723f86/src/siphon/simplewebservice/ndbc.py#L154-L192 | |
spotify/luigi | c3b66f4a5fa7eaa52f9a72eb6704b1049035c789 | luigi/date_interval.py | python | Date.__init__ | (self, y, m, d) | [] | def __init__(self, y, m, d):
a = datetime.date(y, m, d)
b = datetime.date(y, m, d) + datetime.timedelta(1)
super(Date, self).__init__(a, b) | [
"def",
"__init__",
"(",
"self",
",",
"y",
",",
"m",
",",
"d",
")",
":",
"a",
"=",
"datetime",
".",
"date",
"(",
"y",
",",
"m",
",",
"d",
")",
"b",
"=",
"datetime",
".",
"date",
"(",
"y",
",",
"m",
",",
"d",
")",
"+",
"datetime",
".",
"tim... | https://github.com/spotify/luigi/blob/c3b66f4a5fa7eaa52f9a72eb6704b1049035c789/luigi/date_interval.py#L160-L163 | ||||
alvinwan/TexSoup | f91d4e71b21aa6852378d2d60ecc551b39e05bf0 | TexSoup/data.py | python | TexArgs.reverse | (self) | r"""Reverse both the list and the proxy `.all`.
>>> args = TexArgs(['\n', BraceGroup('arg1'), BracketGroup('arg2')])
>>> args.reverse()
>>> args.all
[BracketGroup('arg2'), BraceGroup('arg1'), '\n']
>>> args
[BracketGroup('arg2'), BraceGroup('arg1')] | r"""Reverse both the list and the proxy `.all`. | [
"r",
"Reverse",
"both",
"the",
"list",
"and",
"the",
"proxy",
".",
"all",
"."
] | def reverse(self):
r"""Reverse both the list and the proxy `.all`.
>>> args = TexArgs(['\n', BraceGroup('arg1'), BracketGroup('arg2')])
>>> args.reverse()
>>> args.all
[BracketGroup('arg2'), BraceGroup('arg1'), '\n']
>>> args
[BracketGroup('arg2'), BraceGroup('arg1')]
"""
super().reverse()
self.all.reverse() | [
"def",
"reverse",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"reverse",
"(",
")",
"self",
".",
"all",
".",
"reverse",
"(",
")"
] | https://github.com/alvinwan/TexSoup/blob/f91d4e71b21aa6852378d2d60ecc551b39e05bf0/TexSoup/data.py#L1382-L1393 | ||
taigaio/taiga-back | 60ccd74c80e12056d0385b2900fd180d0826e21c | taiga/base/api/request.py | python | clone_request | (request, method) | return ret | Internal helper method to clone a request, replacing with a different
HTTP method. Used for checking permissions against other methods. | Internal helper method to clone a request, replacing with a different
HTTP method. Used for checking permissions against other methods. | [
"Internal",
"helper",
"method",
"to",
"clone",
"a",
"request",
"replacing",
"with",
"a",
"different",
"HTTP",
"method",
".",
"Used",
"for",
"checking",
"permissions",
"against",
"other",
"methods",
"."
] | def clone_request(request, method):
"""
Internal helper method to clone a request, replacing with a different
HTTP method. Used for checking permissions against other methods.
"""
ret = Request(request=request._request,
parsers=request.parsers,
authenticators=request.authenticators,
negotiator=request.negotiator,
parser_context=request.parser_context)
ret._data = request._data
ret._files = request._files
ret._content_type = request._content_type
ret._stream = request._stream
ret._method = method
if hasattr(request, "_user"):
ret._user = request._user
if hasattr(request, "_auth"):
ret._auth = request._auth
if hasattr(request, "_authenticator"):
ret._authenticator = request._authenticator
return ret | [
"def",
"clone_request",
"(",
"request",
",",
"method",
")",
":",
"ret",
"=",
"Request",
"(",
"request",
"=",
"request",
".",
"_request",
",",
"parsers",
"=",
"request",
".",
"parsers",
",",
"authenticators",
"=",
"request",
".",
"authenticators",
",",
"neg... | https://github.com/taigaio/taiga-back/blob/60ccd74c80e12056d0385b2900fd180d0826e21c/taiga/base/api/request.py#L109-L130 | |
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/mailbox.py | python | Maildir.close | (self) | return | Flush and close the mailbox. | Flush and close the mailbox. | [
"Flush",
"and",
"close",
"the",
"mailbox",
"."
] | def close(self):
"""Flush and close the mailbox."""
return | [
"def",
"close",
"(",
"self",
")",
":",
"return"
] | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/mailbox.py#L440-L442 | |
numba/numba | bf480b9e0da858a65508c2b17759a72ee6a44c51 | numba/cuda/cudadrv/driver.py | python | Context.create_stream | (self) | return Stream(weakref.proxy(self), handle,
_stream_finalizer(self.deallocations, handle)) | [] | def create_stream(self):
if USE_NV_BINDING:
# The default stream creation flag, specifying that the created
# stream synchronizes with stream 0 (this is different from the
# default stream, which we define also as CU_STREAM_DEFAULT when
# the NV binding is in use).
flags = binding.CUstream_flags.CU_STREAM_DEFAULT.value
handle = driver.cuStreamCreate(flags)
else:
handle = drvapi.cu_stream()
driver.cuStreamCreate(byref(handle), 0)
return Stream(weakref.proxy(self), handle,
_stream_finalizer(self.deallocations, handle)) | [
"def",
"create_stream",
"(",
"self",
")",
":",
"if",
"USE_NV_BINDING",
":",
"# The default stream creation flag, specifying that the created",
"# stream synchronizes with stream 0 (this is different from the",
"# default stream, which we define also as CU_STREAM_DEFAULT when",
"# the NV bind... | https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cuda/cudadrv/driver.py#L1456-L1468 | |||
piglei/uwsgi-sloth | cac86de5a9a4c43728b3941628d9fd55910252ce | uwsgi_sloth/commands/start.py | python | update_html_symlink | (html_dir) | Maintail symlink: "today.html", "yesterday.html" | Maintail symlink: "today.html", "yesterday.html" | [
"Maintail",
"symlink",
":",
"today",
".",
"html",
"yesterday",
".",
"html"
] | def update_html_symlink(html_dir):
""""Maintail symlink: "today.html", "yesterday.html" """
today = datetime.date.today()
yesterday = datetime.date.today() - datetime.timedelta(days=1)
for from_date, alias_name in (
(today, 'today.html'), (yesterday, 'yesterday.html')):
from_date_file_path = os.path.join(html_dir, 'day_%s.html' % from_date)
symlink_path = os.path.join(html_dir, alias_name)
try:
os.unlink(symlink_path)
except OSError:
pass
os.symlink(from_date_file_path, symlink_path) | [
"def",
"update_html_symlink",
"(",
"html_dir",
")",
":",
"today",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"yesterday",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"1",
")",
... | https://github.com/piglei/uwsgi-sloth/blob/cac86de5a9a4c43728b3941628d9fd55910252ce/uwsgi_sloth/commands/start.py#L37-L50 | ||
rwth-i6/returnn | f2d718a197a280b0d5f0fd91a7fcb8658560dddb | returnn/datasets/generating.py | python | LibriSpeechCorpus.get_current_seq_order | (self) | return self._seq_order | :rtype: typing.Sequence[int] | :rtype: typing.Sequence[int] | [
":",
"rtype",
":",
"typing",
".",
"Sequence",
"[",
"int",
"]"
] | def get_current_seq_order(self):
"""
:rtype: typing.Sequence[int]
"""
assert self._seq_order is not None
return self._seq_order | [
"def",
"get_current_seq_order",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_seq_order",
"is",
"not",
"None",
"return",
"self",
".",
"_seq_order"
] | https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/datasets/generating.py#L1786-L1791 | |
IJDykeman/wangTiles | 7c1ee2095ebdf7f72bce07d94c6484915d5cae8b | experimental_code/tiles_3d/venv/lib/python2.7/site-packages/pip/_vendor/distlib/locators.py | python | PyPIRPCLocator.get_distribution_names | (self) | return set(self.client.list_packages()) | Return all the distribution names known to this locator. | Return all the distribution names known to this locator. | [
"Return",
"all",
"the",
"distribution",
"names",
"known",
"to",
"this",
"locator",
"."
] | def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
return set(self.client.list_packages()) | [
"def",
"get_distribution_names",
"(",
"self",
")",
":",
"return",
"set",
"(",
"self",
".",
"client",
".",
"list_packages",
"(",
")",
")"
] | https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv/lib/python2.7/site-packages/pip/_vendor/distlib/locators.py#L376-L380 | |
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/tokenize.py | python | untokenize | (iterable) | return out | Transform tokens back into Python source code.
It returns a bytes object, encoded using the ENCODING
token, which is the first token sequence output by tokenize.
Each element returned by the iterable must be a token sequence
with at least two elements, a token number and token value. If
only two tokens are passed, the resulting output is poor.
Round-trip invariant for full input:
Untokenized source will match input source exactly
Round-trip invariant for limited input:
# Output bytes will tokenize back to the input
t1 = [tok[:2] for tok in tokenize(f.readline)]
newcode = untokenize(t1)
readline = BytesIO(newcode).readline
t2 = [tok[:2] for tok in tokenize(readline)]
assert t1 == t2 | Transform tokens back into Python source code.
It returns a bytes object, encoded using the ENCODING
token, which is the first token sequence output by tokenize. | [
"Transform",
"tokens",
"back",
"into",
"Python",
"source",
"code",
".",
"It",
"returns",
"a",
"bytes",
"object",
"encoded",
"using",
"the",
"ENCODING",
"token",
"which",
"is",
"the",
"first",
"token",
"sequence",
"output",
"by",
"tokenize",
"."
] | def untokenize(iterable):
"""Transform tokens back into Python source code.
It returns a bytes object, encoded using the ENCODING
token, which is the first token sequence output by tokenize.
Each element returned by the iterable must be a token sequence
with at least two elements, a token number and token value. If
only two tokens are passed, the resulting output is poor.
Round-trip invariant for full input:
Untokenized source will match input source exactly
Round-trip invariant for limited input:
# Output bytes will tokenize back to the input
t1 = [tok[:2] for tok in tokenize(f.readline)]
newcode = untokenize(t1)
readline = BytesIO(newcode).readline
t2 = [tok[:2] for tok in tokenize(readline)]
assert t1 == t2
"""
ut = Untokenizer()
out = ut.untokenize(iterable)
if ut.encoding is not None:
out = out.encode(ut.encoding)
return out | [
"def",
"untokenize",
"(",
"iterable",
")",
":",
"ut",
"=",
"Untokenizer",
"(",
")",
"out",
"=",
"ut",
".",
"untokenize",
"(",
"iterable",
")",
"if",
"ut",
".",
"encoding",
"is",
"not",
"None",
":",
"out",
"=",
"out",
".",
"encode",
"(",
"ut",
".",
... | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tokenize.py#L257-L281 | |
mbj4668/pyang | 97523476e7ada8609d27fd47880e1b5061073dc3 | pyang/statements.py | python | get_primitive_type | (stmt) | return type_name | Recurses through the typedefs and returns
the most primitive YANG type defined. | Recurses through the typedefs and returns
the most primitive YANG type defined. | [
"Recurses",
"through",
"the",
"typedefs",
"and",
"returns",
"the",
"most",
"primitive",
"YANG",
"type",
"defined",
"."
] | def get_primitive_type(stmt):
"""Recurses through the typedefs and returns
the most primitive YANG type defined.
"""
type_obj = stmt.search_one('type')
type_name = getattr(type_obj, 'arg', None)
typedef_obj = getattr(type_obj, 'i_typedef', None)
if typedef_obj:
type_name = get_primitive_type(typedef_obj)
elif type_obj and not check_primitive_type(type_obj):
raise Exception('%s is not a primitive! Incomplete parse tree?' %
type_name)
return type_name | [
"def",
"get_primitive_type",
"(",
"stmt",
")",
":",
"type_obj",
"=",
"stmt",
".",
"search_one",
"(",
"'type'",
")",
"type_name",
"=",
"getattr",
"(",
"type_obj",
",",
"'arg'",
",",
"None",
")",
"typedef_obj",
"=",
"getattr",
"(",
"type_obj",
",",
"'i_typed... | https://github.com/mbj4668/pyang/blob/97523476e7ada8609d27fd47880e1b5061073dc3/pyang/statements.py#L3475-L3487 | |
weechat/scripts | 99ec0e7eceefabb9efb0f11ec26d45d6e8e84335 | python/maskmatch.py | python | is_mask_ignored | (mask) | return False | Validate if banmask is in the ignored banmask list. | Validate if banmask is in the ignored banmask list. | [
"Validate",
"if",
"banmask",
"is",
"in",
"the",
"ignored",
"banmask",
"list",
"."
] | def is_mask_ignored(mask):
"""Validate if banmask is in the ignored banmask list."""
ignored = w.config_get_plugin("ignore_masks").split(",")
for banmask in ignored:
if mask == banmask:
return True
return False | [
"def",
"is_mask_ignored",
"(",
"mask",
")",
":",
"ignored",
"=",
"w",
".",
"config_get_plugin",
"(",
"\"ignore_masks\"",
")",
".",
"split",
"(",
"\",\"",
")",
"for",
"banmask",
"in",
"ignored",
":",
"if",
"mask",
"==",
"banmask",
":",
"return",
"True",
"... | https://github.com/weechat/scripts/blob/99ec0e7eceefabb9efb0f11ec26d45d6e8e84335/python/maskmatch.py#L309-L317 | |
robinhood/thorn | 486a53ebcf6373ff306a8d17dc016d78e880fcd6 | thorn/app.py | python | Thorn.Settings | (self) | return self.subclass_with_self(self.settings_cls) | [] | def Settings(self):
# type: () -> type
return self.subclass_with_self(self.settings_cls) | [
"def",
"Settings",
"(",
"self",
")",
":",
"# type: () -> type",
"return",
"self",
".",
"subclass_with_self",
"(",
"self",
".",
"settings_cls",
")"
] | https://github.com/robinhood/thorn/blob/486a53ebcf6373ff306a8d17dc016d78e880fcd6/thorn/app.py#L146-L148 | |||
kovidgoyal/calibre | 2b41671370f2a9eb1109b9ae901ccf915f1bd0c8 | src/calibre/ebooks/rtf2xml/colors.py | python | Colors.__in_color_func | (self, line) | Requires:
line
Returns:
nothing
Logic:
Check if the end of the color table has been reached. If so,
change the state to after the color table.
Otherwise, get a function by passing the self.__token_info to the
state dictionary. | Requires:
line
Returns:
nothing
Logic:
Check if the end of the color table has been reached. If so,
change the state to after the color table.
Otherwise, get a function by passing the self.__token_info to the
state dictionary. | [
"Requires",
":",
"line",
"Returns",
":",
"nothing",
"Logic",
":",
"Check",
"if",
"the",
"end",
"of",
"the",
"color",
"table",
"has",
"been",
"reached",
".",
"If",
"so",
"change",
"the",
"state",
"to",
"after",
"the",
"color",
"table",
".",
"Otherwise",
... | def __in_color_func(self, line):
"""
Requires:
line
Returns:
nothing
Logic:
Check if the end of the color table has been reached. If so,
change the state to after the color table.
Otherwise, get a function by passing the self.__token_info to the
state dictionary.
"""
# mi<mk<clrtbl-beg
# cw<ci<red_______<nu<00
if self.__token_info == 'mi<mk<clrtbl-end':
self.__state = 'after_color_table'
else:
action = self.__state_dict.get(self.__token_info)
if action is None:
sys.stderr.write('in module colors.py\n'
'function is self.__in_color_func\n'
'no action for %s' % self.__token_info
)
action(line) | [
"def",
"__in_color_func",
"(",
"self",
",",
"line",
")",
":",
"# mi<mk<clrtbl-beg",
"# cw<ci<red_______<nu<00",
"if",
"self",
".",
"__token_info",
"==",
"'mi<mk<clrtbl-end'",
":",
"self",
".",
"__state",
"=",
"'after_color_table'",
"else",
":",
"action",
"=",
"sel... | https://github.com/kovidgoyal/calibre/blob/2b41671370f2a9eb1109b9ae901ccf915f1bd0c8/src/calibre/ebooks/rtf2xml/colors.py#L119-L142 | ||
brython-dev/brython | 9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3 | www/src/Lib/contextlib.py | python | push | (self, exit) | return exit | Registers a callback with the standard __exit__ method signature.
Can suppress exceptions the same way __exit__ method can.
Also accepts any object with an __exit__ method (registering a call
to the method instead of the object itself). | Registers a callback with the standard __exit__ method signature. | [
"Registers",
"a",
"callback",
"with",
"the",
"standard",
"__exit__",
"method",
"signature",
"."
] | def push(self, exit):
"""Registers a callback with the standard __exit__ method signature.
Can suppress exceptions the same way __exit__ method can.
Also accepts any object with an __exit__ method (registering a call
to the method instead of the object itself).
"""
# We use an unbound method rather than a bound method to follow
# the standard lookup behaviour for special methods.
_cb_type = type(exit)
try:
exit_method = _cb_type.__exit__
except AttributeError:
# Not a context manager, so assume it's a callable.
self._push_exit_callback(exit)
else:
self._push_cm_exit(exit, exit_method)
return exit | [
"def",
"push",
"(",
"self",
",",
"exit",
")",
":",
"# We use an unbound method rather than a bound method to follow",
"# the standard lookup behaviour for special methods.",
"_cb_type",
"=",
"type",
"(",
"exit",
")",
"try",
":",
"exit_method",
"=",
"_cb_type",
".",
"__exi... | https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/contextlib.py#L462-L480 | |
haiwen/seafile-docker | 2d2461d4c8cab3458ec9832611c419d47506c300 | cluster/scripts/setup-seafile-mysql.py | python | get_param_val | (arg, env, default=None) | return arg or os.environ.get(env, default) | [] | def get_param_val(arg, env, default=None):
return arg or os.environ.get(env, default) | [
"def",
"get_param_val",
"(",
"arg",
",",
"env",
",",
"default",
"=",
"None",
")",
":",
"return",
"arg",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"env",
",",
"default",
")"
] | https://github.com/haiwen/seafile-docker/blob/2d2461d4c8cab3458ec9832611c419d47506c300/cluster/scripts/setup-seafile-mysql.py#L1288-L1289 | |||
natashamjaques/neural_chat | ddb977bb4602a67c460d02231e7bbf7b2cb49a97 | ParlAI/parlai/core/utils.py | python | warn_once | (msg, warningtype=None) | Raise a warning, but only once.
:param str msg: Message to display
:param Warning warningtype: Type of warning, e.g. DeprecationWarning | Raise a warning, but only once. | [
"Raise",
"a",
"warning",
"but",
"only",
"once",
"."
] | def warn_once(msg, warningtype=None):
"""
Raise a warning, but only once.
:param str msg: Message to display
:param Warning warningtype: Type of warning, e.g. DeprecationWarning
"""
global _seen_warnings
if msg not in _seen_warnings:
_seen_warnings.add(msg)
warnings.warn(msg, warningtype, stacklevel=2) | [
"def",
"warn_once",
"(",
"msg",
",",
"warningtype",
"=",
"None",
")",
":",
"global",
"_seen_warnings",
"if",
"msg",
"not",
"in",
"_seen_warnings",
":",
"_seen_warnings",
".",
"add",
"(",
"msg",
")",
"warnings",
".",
"warn",
"(",
"msg",
",",
"warningtype",
... | https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/core/utils.py#L1242-L1252 | ||
keiffster/program-y | 8c99b56f8c32f01a7b9887b5daae9465619d0385 | src/programy/clients/restful/asyncio/microsoft/client.py | python | MicrosoftBotClient.__init__ | (self, argument_parser=None) | [] | def __init__(self, argument_parser=None):
FlaskRestBotClient.__init__(self, 'microsoft', argument_parser)
YLogger.debug(self, "Microsoft Client is running....")
outputLog(None, "Microsoft Client loaded") | [
"def",
"__init__",
"(",
"self",
",",
"argument_parser",
"=",
"None",
")",
":",
"FlaskRestBotClient",
".",
"__init__",
"(",
"self",
",",
"'microsoft'",
",",
"argument_parser",
")",
"YLogger",
".",
"debug",
"(",
"self",
",",
"\"Microsoft Client is running....\"",
... | https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/clients/restful/asyncio/microsoft/client.py#L31-L36 | ||||
Dentosal/python-sc2 | e816cce83772d1aee1291b86b300b69405aa96b4 | sc2/game_data.py | python | AbilityData.button_name | (self) | return self._proto.button_name | For Stimpack this returns 'Stimpack' | For Stimpack this returns 'Stimpack' | [
"For",
"Stimpack",
"this",
"returns",
"Stimpack"
] | def button_name(self) -> str:
""" For Stimpack this returns 'Stimpack' """
return self._proto.button_name | [
"def",
"button_name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_proto",
".",
"button_name"
] | https://github.com/Dentosal/python-sc2/blob/e816cce83772d1aee1291b86b300b69405aa96b4/sc2/game_data.py#L110-L112 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-1.3/django/contrib/gis/geos/geometry.py | python | GEOSGeometry.ogr | (self) | Returns the OGR Geometry for this Geometry. | Returns the OGR Geometry for this Geometry. | [
"Returns",
"the",
"OGR",
"Geometry",
"for",
"this",
"Geometry",
"."
] | def ogr(self):
"Returns the OGR Geometry for this Geometry."
if gdal.HAS_GDAL:
if self.srid:
return gdal.OGRGeometry(self.wkb, self.srid)
else:
return gdal.OGRGeometry(self.wkb)
else:
raise GEOSException('GDAL required to convert to an OGRGeometry.') | [
"def",
"ogr",
"(",
"self",
")",
":",
"if",
"gdal",
".",
"HAS_GDAL",
":",
"if",
"self",
".",
"srid",
":",
"return",
"gdal",
".",
"OGRGeometry",
"(",
"self",
".",
"wkb",
",",
"self",
".",
"srid",
")",
"else",
":",
"return",
"gdal",
".",
"OGRGeometry"... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/contrib/gis/geos/geometry.py#L466-L474 | ||
biocore/scikit-bio | ecdfc7941d8c21eb2559ff1ab313d6e9348781da | skbio/sequence/_grammared_sequence.py | python | GrammaredSequence.gap_chars | (cls) | Return characters defined as gaps.
Returns
-------
set
Characters defined as gaps. | Return characters defined as gaps. | [
"Return",
"characters",
"defined",
"as",
"gaps",
"."
] | def gap_chars(cls):
"""Return characters defined as gaps.
Returns
-------
set
Characters defined as gaps.
"""
raise NotImplementedError | [
"def",
"gap_chars",
"(",
"cls",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/biocore/scikit-bio/blob/ecdfc7941d8c21eb2559ff1ab313d6e9348781da/skbio/sequence/_grammared_sequence.py#L229-L238 | ||
enzienaudio/hvcc | 30e47328958d600c54889e2a254c3f17f2b2fd06 | generators/ir2c/SignalSamphold.py | python | SignalSamphold.get_C_process | (clazz, obj_type, process_dict, args) | return [
"__hv_samphold_f(&sSamphold_{0}, VIf({1}), VIf({2}), VOf({3}));".format(
process_dict["id"],
HeavyObject._c_buffer(process_dict["inputBuffers"][0]),
HeavyObject._c_buffer(process_dict["inputBuffers"][1]),
HeavyObject._c_buffer(process_dict["outputBuffers"][0]))] | [] | def get_C_process(clazz, obj_type, process_dict, args):
return [
"__hv_samphold_f(&sSamphold_{0}, VIf({1}), VIf({2}), VOf({3}));".format(
process_dict["id"],
HeavyObject._c_buffer(process_dict["inputBuffers"][0]),
HeavyObject._c_buffer(process_dict["inputBuffers"][1]),
HeavyObject._c_buffer(process_dict["outputBuffers"][0]))] | [
"def",
"get_C_process",
"(",
"clazz",
",",
"obj_type",
",",
"process_dict",
",",
"args",
")",
":",
"return",
"[",
"\"__hv_samphold_f(&sSamphold_{0}, VIf({1}), VIf({2}), VOf({3}));\"",
".",
"format",
"(",
"process_dict",
"[",
"\"id\"",
"]",
",",
"HeavyObject",
".",
"... | https://github.com/enzienaudio/hvcc/blob/30e47328958d600c54889e2a254c3f17f2b2fd06/generators/ir2c/SignalSamphold.py#L44-L50 | |||
graalvm/mx | 29c0debab406352df3af246be2f8973be5db69ae | mx_proftool.py | python | ProftoolProfiler.version | (self) | return "1.0" | [] | def version(self):
return "1.0" | [
"def",
"version",
"(",
"self",
")",
":",
"return",
"\"1.0\""
] | https://github.com/graalvm/mx/blob/29c0debab406352df3af246be2f8973be5db69ae/mx_proftool.py#L1362-L1363 | |||
devbisme/skidl | 458709a10b28a864d25ae2c2b44c6103d4ddb291 | examples/bricolage/briccolage_galg.py | python | vreg | (vin, vout, vadj, gnd) | Voltage regulator similar to NCP1117. | Voltage regulator similar to NCP1117. | [
"Voltage",
"regulator",
"similar",
"to",
"NCP1117",
"."
] | def vreg(vin, vout, vadj, gnd):
'''Voltage regulator similar to NCP1117.'''
v_bandgap = v(dc_value=1.25 @ u_V) # Bandgap voltage of 1.25V.
v_o_a = vcvs(gain=1.0) # Replicate voltage diff (vout - vadj).
v_o_a['ip, in'] += vout, vadj
# Generate the difference between the bandgap and v_o_a
v_bandgap['p,n'] += v_o_a['op'], gnd
vdiff = v_o_a['on']
# Generate a current that keeps (vout - vadj) == bandgap.
i_out = G(gain=1e8 / (1 @ u_Ohm))
i_out['ip, in'] += vdiff, gnd
i_out['op, on'] += vout, gnd
# Output a small current from the adjustment pin.
i_adj = I(dc_value=50 @ u_uA)
i_adj['p,n'] += vadj, gnd | [
"def",
"vreg",
"(",
"vin",
",",
"vout",
",",
"vadj",
",",
"gnd",
")",
":",
"v_bandgap",
"=",
"v",
"(",
"dc_value",
"=",
"1.25",
"@",
"u_V",
")",
"# Bandgap voltage of 1.25V.",
"v_o_a",
"=",
"vcvs",
"(",
"gain",
"=",
"1.0",
")",
"# Replicate voltage diff ... | https://github.com/devbisme/skidl/blob/458709a10b28a864d25ae2c2b44c6103d4ddb291/examples/bricolage/briccolage_galg.py#L10-L24 | ||
xtiankisutsa/MARA_Framework | ac4ac88bfd38f33ae8780a606ed09ab97177c562 | tools/qark/qark/lib/BeautifulSoup.py | python | PageElement.toEncoding | (self, s, encoding=None) | return s | Encodes an object to a string in some encoding, or to Unicode.
. | Encodes an object to a string in some encoding, or to Unicode.
. | [
"Encodes",
"an",
"object",
"to",
"a",
"string",
"in",
"some",
"encoding",
"or",
"to",
"Unicode",
".",
"."
] | def toEncoding(self, s, encoding=None):
"""Encodes an object to a string in some encoding, or to Unicode.
."""
if isinstance(s, unicode):
if encoding:
s = s.encode(encoding)
elif isinstance(s, str):
if encoding:
s = s.encode(encoding)
else:
s = unicode(s)
else:
if encoding:
s = self.toEncoding(str(s), encoding)
else:
s = unicode(s)
return s | [
"def",
"toEncoding",
"(",
"self",
",",
"s",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"if",
"encoding",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"encoding",
")",
"elif",
"isinstance",
"(",
"s",
... | https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/qark/qark/lib/BeautifulSoup.py#L421-L437 | |
giacomocerquone/UnivaqBot | 754519befe24dcc3c4a658160b727de7b14a6b21 | libs/utils.py | python | get_soup_from_url | (url) | return None | Download a webpage and return its BeautifulSoup | Download a webpage and return its BeautifulSoup | [
"Download",
"a",
"webpage",
"and",
"return",
"its",
"BeautifulSoup"
] | def get_soup_from_url(url):
"""Download a webpage and return its BeautifulSoup"""
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'accept-encoding': 'gzip,deflate,sdch',
'accept-language': 'it-IT',
}
request = requests.get(url, headers=headers)
if request.status_code == 200:
return bs4.BeautifulSoup(request.text, 'html.parser')
fmt = 'Error! get_soup_from_url({}) --> Status: {}'
print(fmt.format(url, request.status_code))
return None | [
"def",
"get_soup_from_url",
"(",
"url",
")",
":",
"headers",
"=",
"{",
"'user-agent'",
":",
"'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)'",
",",
"'accept'",
":",
"'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'",
",",
"'accept-charset'",
":",
"'ISO-8859-1,... | https://github.com/giacomocerquone/UnivaqBot/blob/754519befe24dcc3c4a658160b727de7b14a6b21/libs/utils.py#L106-L122 | |
freewym/espresso | 6671c507350295269e38add57dbe601dcb8e6ecf | espresso/data/asr_chain_dataset.py | python | AsrChainDataset._match_src_tgt | (self) | Makes utterances in src and tgt the same order in terms of
their utt_ids. Removes those that are only present in one of them. | Makes utterances in src and tgt the same order in terms of
their utt_ids. Removes those that are only present in one of them. | [
"Makes",
"utterances",
"in",
"src",
"and",
"tgt",
"the",
"same",
"order",
"in",
"terms",
"of",
"their",
"utt_ids",
".",
"Removes",
"those",
"that",
"are",
"only",
"present",
"in",
"one",
"of",
"them",
"."
] | def _match_src_tgt(self):
"""Makes utterances in src and tgt the same order in terms of
their utt_ids. Removes those that are only present in one of them."""
assert self.tgt is not None
if self.src.utt_ids == self.tgt.utt_ids:
return
tgt_utt_ids_set = set(self.tgt.utt_ids)
src_indices = [
i for i, id in enumerate(self.src.utt_ids) if id in tgt_utt_ids_set
]
self.src.filter_and_reorder(src_indices)
self.src_sizes = np.array(self.src.sizes)
try:
tgt_indices = list(map(self.tgt.utt_ids.index, self.src.utt_ids))
except ValueError:
raise ValueError(
"Unable to find some utt_id(s) in tgt. which is unlikely to happen. "
"Something must be wrong."
)
self.tgt.filter_and_reorder(tgt_indices)
self.tgt_sizes = np.array(self.tgt.sizes)
assert self.src.utt_ids == self.tgt.utt_ids | [
"def",
"_match_src_tgt",
"(",
"self",
")",
":",
"assert",
"self",
".",
"tgt",
"is",
"not",
"None",
"if",
"self",
".",
"src",
".",
"utt_ids",
"==",
"self",
".",
"tgt",
".",
"utt_ids",
":",
"return",
"tgt_utt_ids_set",
"=",
"set",
"(",
"self",
".",
"tg... | https://github.com/freewym/espresso/blob/6671c507350295269e38add57dbe601dcb8e6ecf/espresso/data/asr_chain_dataset.py#L242-L263 | ||
ConvLab/ConvLab | a04582a77537c1a706fbf64715baa9ad0be1301a | convlab/lib/logger.py | python | get_logger | (__name__) | return module_logger | Create a child logger specific to a module | Create a child logger specific to a module | [
"Create",
"a",
"child",
"logger",
"specific",
"to",
"a",
"module"
] | def get_logger(__name__):
'''Create a child logger specific to a module'''
module_logger = logging.getLogger(__name__)
def nl(msg, *args, **kwargs):
return module_logger.log(NEW_LVLS['NL'], msg, *args, **kwargs)
def act(msg, *args, **kwargs):
return module_logger.log(NEW_LVLS['ACT'], msg, *args, **kwargs)
def state(msg, *args, **kwargs):
return module_logger.log(NEW_LVLS['STATE'], msg, *args, **kwargs)
setattr(module_logger, 'nl', nl)
setattr(module_logger, 'act', act)
setattr(module_logger, 'state', state)
return module_logger | [
"def",
"get_logger",
"(",
"__name__",
")",
":",
"module_logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"def",
"nl",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"module_logger",
".",
"log",
"(",
"NEW_LVLS... | https://github.com/ConvLab/ConvLab/blob/a04582a77537c1a706fbf64715baa9ad0be1301a/convlab/lib/logger.py#L101-L118 | |
Chaffelson/nipyapi | d3b186fd701ce308c2812746d98af9120955e810 | nipyapi/nifi/models/controller_service_dto.py | python | ControllerServiceDTO.type | (self, type) | Sets the type of this ControllerServiceDTO.
The type of the controller service.
:param type: The type of this ControllerServiceDTO.
:type: str | Sets the type of this ControllerServiceDTO.
The type of the controller service. | [
"Sets",
"the",
"type",
"of",
"this",
"ControllerServiceDTO",
".",
"The",
"type",
"of",
"the",
"controller",
"service",
"."
] | def type(self, type):
"""
Sets the type of this ControllerServiceDTO.
The type of the controller service.
:param type: The type of this ControllerServiceDTO.
:type: str
"""
self._type = type | [
"def",
"type",
"(",
"self",
",",
"type",
")",
":",
"self",
".",
"_type",
"=",
"type"
] | https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/controller_service_dto.py#L283-L292 | ||
Trusted-AI/adversarial-robustness-toolbox | 9fabffdbb92947efa1ecc5d825d634d30dfbaf29 | art/estimators/classification/catboost.py | python | CatBoostARTClassifier.fit | (self, x: np.ndarray, y: np.ndarray, **kwargs) | Fit the classifier on the training set `(x, y)`.
:param x: Training data.
:param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).
:param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the
`fit` function in `catboost.core.CatBoostClassifier` and will be passed to this function as such. | Fit the classifier on the training set `(x, y)`. | [
"Fit",
"the",
"classifier",
"on",
"the",
"training",
"set",
"(",
"x",
"y",
")",
"."
] | def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:
"""
Fit the classifier on the training set `(x, y)`.
:param x: Training data.
:param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).
:param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the
`fit` function in `catboost.core.CatBoostClassifier` and will be passed to this function as such.
"""
# Apply preprocessing
x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)
self._model.fit(x_preprocessed, y_preprocessed, **kwargs)
self.nb_classes = self._get_nb_classes() | [
"def",
"fit",
"(",
"self",
",",
"x",
":",
"np",
".",
"ndarray",
",",
"y",
":",
"np",
".",
"ndarray",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"# Apply preprocessing",
"x_preprocessed",
",",
"y_preprocessed",
"=",
"self",
".",
"_apply_preprocessin... | https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/9fabffdbb92947efa1ecc5d825d634d30dfbaf29/art/estimators/classification/catboost.py#L110-L123 | ||
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/bdf/cards/nodes.py | python | GRDSET.Cd | (self) | return self.cd.cid | Gets the output coordinate system
Returns
-------
cd : int
the output coordinate system | Gets the output coordinate system | [
"Gets",
"the",
"output",
"coordinate",
"system"
] | def Cd(self):
"""
Gets the output coordinate system
Returns
-------
cd : int
the output coordinate system
"""
if self.cd_ref is None:
return self.cd
return self.cd.cid | [
"def",
"Cd",
"(",
"self",
")",
":",
"if",
"self",
".",
"cd_ref",
"is",
"None",
":",
"return",
"self",
".",
"cd",
"return",
"self",
".",
"cd",
".",
"cid"
] | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/nodes.py#L683-L695 | |
privacyidea/privacyidea | 9490c12ddbf77a34ac935b082d09eb583dfafa2c | privacyidea/models.py | python | MonitoringStats.__init__ | (self, timestamp, key, value) | Create a new database entry in the monitoring stats table
:param timestamp: The time of the measurement point
:type timestamp: timezone-naive datetime
:param key: The key of the measurement
:type key: basestring
:param value: The value of the measurement
:type value: Int | Create a new database entry in the monitoring stats table
:param timestamp: The time of the measurement point
:type timestamp: timezone-naive datetime
:param key: The key of the measurement
:type key: basestring
:param value: The value of the measurement
:type value: Int | [
"Create",
"a",
"new",
"database",
"entry",
"in",
"the",
"monitoring",
"stats",
"table",
":",
"param",
"timestamp",
":",
"The",
"time",
"of",
"the",
"measurement",
"point",
":",
"type",
"timestamp",
":",
"timezone",
"-",
"naive",
"datetime",
":",
"param",
"... | def __init__(self, timestamp, key, value):
"""
Create a new database entry in the monitoring stats table
:param timestamp: The time of the measurement point
:type timestamp: timezone-naive datetime
:param key: The key of the measurement
:type key: basestring
:param value: The value of the measurement
:type value: Int
"""
self.timestamp = timestamp
self.stats_key = key
self.stats_value = value | [
"def",
"__init__",
"(",
"self",
",",
"timestamp",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"timestamp",
"=",
"timestamp",
"self",
".",
"stats_key",
"=",
"key",
"self",
".",
"stats_value",
"=",
"value"
] | https://github.com/privacyidea/privacyidea/blob/9490c12ddbf77a34ac935b082d09eb583dfafa2c/privacyidea/models.py#L3055-L3067 | ||
bendmorris/static-python | 2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473 | Lib/urllib/request.py | python | URLopener.addheader | (self, *args) | Add a header to be used by the HTTP interface only
e.g. u.addheader('Accept', 'sound/basic') | Add a header to be used by the HTTP interface only
e.g. u.addheader('Accept', 'sound/basic') | [
"Add",
"a",
"header",
"to",
"be",
"used",
"by",
"the",
"HTTP",
"interface",
"only",
"e",
".",
"g",
".",
"u",
".",
"addheader",
"(",
"Accept",
"sound",
"/",
"basic",
")"
] | def addheader(self, *args):
"""Add a header to be used by the HTTP interface only
e.g. u.addheader('Accept', 'sound/basic')"""
self.addheaders.append(args) | [
"def",
"addheader",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"addheaders",
".",
"append",
"(",
"args",
")"
] | https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/urllib/request.py#L1647-L1650 | ||
wangzheng0822/algo | b2c1228ff915287ad7ebeae4355fa26854ea1557 | python/23_binarytree/binary_search_tree.py | python | BinarySearchTree.get_max | (self) | return n.val | 返回最大值节点
:return: | 返回最大值节点
:return: | [
"返回最大值节点",
":",
"return",
":"
] | def get_max(self):
"""
返回最大值节点
:return:
"""
if self.root is None:
return None
n = self.root
while n.right:
n = n.right
return n.val | [
"def",
"get_max",
"(",
"self",
")",
":",
"if",
"self",
".",
"root",
"is",
"None",
":",
"return",
"None",
"n",
"=",
"self",
".",
"root",
"while",
"n",
".",
"right",
":",
"n",
"=",
"n",
".",
"right",
"return",
"n",
".",
"val"
] | https://github.com/wangzheng0822/algo/blob/b2c1228ff915287ad7ebeae4355fa26854ea1557/python/23_binarytree/binary_search_tree.py#L171-L182 | |
raffaele-forte/climber | 5530a780446e35b1ce977bae140557050fe0b47c | Exscript/util/url.py | python | Url.to_string | (self) | return str(self) | Returns the URL, including all attributes, as a string.
@rtype: str
@return: A URL. | Returns the URL, including all attributes, as a string. | [
"Returns",
"the",
"URL",
"including",
"all",
"attributes",
"as",
"a",
"string",
"."
] | def to_string(self):
"""
Returns the URL, including all attributes, as a string.
@rtype: str
@return: A URL.
"""
return str(self) | [
"def",
"to_string",
"(",
"self",
")",
":",
"return",
"str",
"(",
"self",
")"
] | https://github.com/raffaele-forte/climber/blob/5530a780446e35b1ce977bae140557050fe0b47c/Exscript/util/url.py#L145-L152 | |
nickoala/telepot | 4bfe4eeb5e48b40e72976ee085a1b0a941ef3cf2 | telepot/__init__.py | python | Bot.getChatAdministrators | (self, chat_id) | return self._api_request('getChatAdministrators', _rectify(p)) | See: https://core.telegram.org/bots/api#getchatadministrators | See: https://core.telegram.org/bots/api#getchatadministrators | [
"See",
":",
"https",
":",
"//",
"core",
".",
"telegram",
".",
"org",
"/",
"bots",
"/",
"api#getchatadministrators"
] | def getChatAdministrators(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchatadministrators """
p = _strip(locals())
return self._api_request('getChatAdministrators', _rectify(p)) | [
"def",
"getChatAdministrators",
"(",
"self",
",",
"chat_id",
")",
":",
"p",
"=",
"_strip",
"(",
"locals",
"(",
")",
")",
"return",
"self",
".",
"_api_request",
"(",
"'getChatAdministrators'",
",",
"_rectify",
"(",
"p",
")",
")"
] | https://github.com/nickoala/telepot/blob/4bfe4eeb5e48b40e72976ee085a1b0a941ef3cf2/telepot/__init__.py#L826-L829 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/flipr/config_flow.py | python | ConfigFlow.async_step_user | (self, user_input=None) | return self.async_create_entry(
title=self._flipr_id,
data={
CONF_EMAIL: self._username,
CONF_PASSWORD: self._password,
CONF_FLIPR_ID: self._flipr_id,
},
) | Handle the initial step. | Handle the initial step. | [
"Handle",
"the",
"initial",
"step",
"."
] | async def async_step_user(self, user_input=None):
"""Handle the initial step."""
if user_input is None:
return self._show_setup_form()
self._username = user_input[CONF_EMAIL]
self._password = user_input[CONF_PASSWORD]
errors = {}
if not self._flipr_id:
try:
flipr_ids = await self._authenticate_and_search_flipr()
except HTTPError:
errors["base"] = "invalid_auth"
except (Timeout, ConnectionError):
errors["base"] = "cannot_connect"
except Exception as exception: # pylint: disable=broad-except
errors["base"] = "unknown"
_LOGGER.exception(exception)
if not errors and not flipr_ids:
# No flipr_id found. Tell the user with an error message.
errors["base"] = "no_flipr_id_found"
if errors:
return self._show_setup_form(errors)
if len(flipr_ids) == 1:
self._flipr_id = flipr_ids[0]
else:
# If multiple flipr found (rare case), we ask the user to choose one in a select box.
# The user will have to run config_flow as many times as many fliprs he has.
self._possible_flipr_ids = flipr_ids
return await self.async_step_flipr_id()
# Check if already configured
await self.async_set_unique_id(self._flipr_id)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=self._flipr_id,
data={
CONF_EMAIL: self._username,
CONF_PASSWORD: self._password,
CONF_FLIPR_ID: self._flipr_id,
},
) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"None",
":",
"return",
"self",
".",
"_show_setup_form",
"(",
")",
"self",
".",
"_username",
"=",
"user_input",
"[",
"CONF_EMAIL",
"]",
"self... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/flipr/config_flow.py#L28-L74 | |
apache/tvm | 6eb4ed813ebcdcd9558f0906a1870db8302ff1e0 | python/tvm/relay/analysis/analysis.py | python | check_kind | (t, mod=None) | Check that the type is well kinded and return the kind.
For example, this mean type cannot has tensor of tensor, or is a tuple type
of 2 shapes.
Parameters
----------
t : tvm.relay.Type
The type to check
mod : Optional[tvm.IRModule]
The global module.
Returns
-------
kind : Kind
the kind of t
Examples
--------
.. code:: python
assert check_kind(relay.TupleType([relay.TypeParam('tp1', relay.Kind.Shape)])) == Shape
assert check_kind(relay.TupleType([relay.TypeParam('tp1', relay.Kind.Type)])) == Type | Check that the type is well kinded and return the kind.
For example, this mean type cannot has tensor of tensor, or is a tuple type
of 2 shapes. | [
"Check",
"that",
"the",
"type",
"is",
"well",
"kinded",
"and",
"return",
"the",
"kind",
".",
"For",
"example",
"this",
"mean",
"type",
"cannot",
"has",
"tensor",
"of",
"tensor",
"or",
"is",
"a",
"tuple",
"type",
"of",
"2",
"shapes",
"."
] | def check_kind(t, mod=None):
"""Check that the type is well kinded and return the kind.
For example, this mean type cannot has tensor of tensor, or is a tuple type
of 2 shapes.
Parameters
----------
t : tvm.relay.Type
The type to check
mod : Optional[tvm.IRModule]
The global module.
Returns
-------
kind : Kind
the kind of t
Examples
--------
.. code:: python
assert check_kind(relay.TupleType([relay.TypeParam('tp1', relay.Kind.Shape)])) == Shape
assert check_kind(relay.TupleType([relay.TypeParam('tp1', relay.Kind.Type)])) == Type
"""
if mod is not None:
return _ffi_api.check_kind(t, mod)
else:
return _ffi_api.check_kind(t) | [
"def",
"check_kind",
"(",
"t",
",",
"mod",
"=",
"None",
")",
":",
"if",
"mod",
"is",
"not",
"None",
":",
"return",
"_ffi_api",
".",
"check_kind",
"(",
"t",
",",
"mod",
")",
"else",
":",
"return",
"_ffi_api",
".",
"check_kind",
"(",
"t",
")"
] | https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/relay/analysis/analysis.py#L63-L91 | ||
guillermooo/dart-sublime-bundle | d891fb36c98ca0b111a35cba109b05a16b6c4b83 | lib/pub_package.py | python | DartFile.is_example | (self) | return self.has_prefix(project.path_to_example) | Returns `True` if the view's path is under the 'example' dir. | Returns `True` if the view's path is under the 'example' dir. | [
"Returns",
"True",
"if",
"the",
"view",
"s",
"path",
"is",
"under",
"the",
"example",
"dir",
"."
] | def is_example(self):
'''Returns `True` if the view's path is under the 'example' dir.
'''
assert self.path, 'view has not been saved yet'
project = PubPackage.from_path(self.path)
if not (project and project.path_to_example):
return False
return self.has_prefix(project.path_to_example) | [
"def",
"is_example",
"(",
"self",
")",
":",
"assert",
"self",
".",
"path",
",",
"'view has not been saved yet'",
"project",
"=",
"PubPackage",
".",
"from_path",
"(",
"self",
".",
"path",
")",
"if",
"not",
"(",
"project",
"and",
"project",
".",
"path_to_examp... | https://github.com/guillermooo/dart-sublime-bundle/blob/d891fb36c98ca0b111a35cba109b05a16b6c4b83/lib/pub_package.py#L280-L287 | |
CouchPotato/CouchPotatoServer | 7260c12f72447ddb6f062367c6dfbda03ecd4e9c | libs/suds/builder.py | python | Builder.add_attributes | (self, data, type) | add required attributes | add required attributes | [
"add",
"required",
"attributes"
] | def add_attributes(self, data, type):
""" add required attributes """
for attr, ancestry in type.attributes():
name = '_%s' % attr.name
value = attr.get_default()
setattr(data, name, value) | [
"def",
"add_attributes",
"(",
"self",
",",
"data",
",",
"type",
")",
":",
"for",
"attr",
",",
"ancestry",
"in",
"type",
".",
"attributes",
"(",
")",
":",
"name",
"=",
"'_%s'",
"%",
"attr",
".",
"name",
"value",
"=",
"attr",
".",
"get_default",
"(",
... | https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/suds/builder.py#L95-L100 | ||
hgrecco/pint | befdffb9d767fb354fc756660a33268c0f8d48e1 | pint/quantity.py | python | Quantity.units | (self) | return self._REGISTRY.Unit(self._units) | Quantity's units. Long form for `u` | Quantity's units. Long form for `u` | [
"Quantity",
"s",
"units",
".",
"Long",
"form",
"for",
"u"
] | def units(self) -> "Unit":
"""Quantity's units. Long form for `u`"""
return self._REGISTRY.Unit(self._units) | [
"def",
"units",
"(",
"self",
")",
"->",
"\"Unit\"",
":",
"return",
"self",
".",
"_REGISTRY",
".",
"Unit",
"(",
"self",
".",
"_units",
")"
] | https://github.com/hgrecco/pint/blob/befdffb9d767fb354fc756660a33268c0f8d48e1/pint/quantity.py#L521-L523 | |
xonsh/xonsh | b76d6f994f22a4078f602f8b386f4ec280c8461f | xonsh/pretty.py | python | _type_pprint | (obj, p, cycle) | The pprint for classes and types. | The pprint for classes and types. | [
"The",
"pprint",
"for",
"classes",
"and",
"types",
"."
] | def _type_pprint(obj, p, cycle):
"""The pprint for classes and types."""
# Heap allocated types might not have the module attribute,
# and others may set it to None.
# Checks for a __repr__ override in the metaclass
if type(obj).__repr__ is not type.__repr__:
_repr_pprint(obj, p, cycle)
return
mod = _safe_getattr(obj, "__module__", None)
try:
name = obj.__qualname__
if not isinstance(name, str):
# This can happen if the type implements __qualname__ as a property
# or other descriptor in Python 2.
raise Exception("Try __name__")
except Exception:
name = obj.__name__
if not isinstance(name, str):
name = "<unknown type>"
if mod in (None, "__builtin__", "builtins", "exceptions"):
p.text(name)
else:
p.text(mod + "." + name) | [
"def",
"_type_pprint",
"(",
"obj",
",",
"p",
",",
"cycle",
")",
":",
"# Heap allocated types might not have the module attribute,",
"# and others may set it to None.",
"# Checks for a __repr__ override in the metaclass",
"if",
"type",
"(",
"obj",
")",
".",
"__repr__",
"is",
... | https://github.com/xonsh/xonsh/blob/b76d6f994f22a4078f602f8b386f4ec280c8461f/xonsh/pretty.py#L704-L729 | ||
armijnhemel/binaryanalysis-ng | 34c655ed71d3d022ee49c4e1271002b2ebf40001 | src/UnpackManager.py | python | UnpackManager.remove_data_unpack_directory_tree | (self) | Remove the unpacking directory, including any
data that might accidentily have been left behind. | Remove the unpacking directory, including any
data that might accidentily have been left behind. | [
"Remove",
"the",
"unpacking",
"directory",
"including",
"any",
"data",
"that",
"might",
"accidentily",
"have",
"been",
"left",
"behind",
"."
] | def remove_data_unpack_directory_tree(self):
'''Remove the unpacking directory, including any
data that might accidentily have been left behind.'''
# TODO: use exception
if not (self.unpackroot / self.dataunpackdirectory).exists():
return
# dirwalk = os.walk(os.path.join(self.unpackroot, self.dataunpackdirectory))
dirwalk = os.walk(self.unpackroot / self.dataunpackdirectory)
for direntries in dirwalk:
# make sure all subdirectories and files can
# be accessed and then removed by first changing the
# permissions of all the files.
for subdir in direntries[1]:
subdirname = os.path.join(direntries[0], subdir)
if not os.path.islink(subdirname):
os.chmod(subdirname,
stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
for filenameentry in direntries[2]:
fullfilename = os.path.join(direntries[0], filenameentry)
if not os.path.islink(fullfilename):
os.chmod(fullfilename,
stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
shutil.rmtree(os.path.join(self.unpackroot, self.dataunpackdirectory)) | [
"def",
"remove_data_unpack_directory_tree",
"(",
"self",
")",
":",
"# TODO: use exception",
"if",
"not",
"(",
"self",
".",
"unpackroot",
"/",
"self",
".",
"dataunpackdirectory",
")",
".",
"exists",
"(",
")",
":",
"return",
"# dirwalk = os.walk(os.path.join(self.unpack... | https://github.com/armijnhemel/binaryanalysis-ng/blob/34c655ed71d3d022ee49c4e1271002b2ebf40001/src/UnpackManager.py#L104-L126 | ||
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/pip/_vendor/distlib/manifest.py | python | Manifest._glob_to_re | (self, pattern) | return pattern_re | Translate a shell-like glob pattern to a regular expression.
Return a string containing the regex. Differs from
'fnmatch.translate()' in that '*' does not match "special characters"
(which are platform-specific). | Translate a shell-like glob pattern to a regular expression. | [
"Translate",
"a",
"shell",
"-",
"like",
"glob",
"pattern",
"to",
"a",
"regular",
"expression",
"."
] | def _glob_to_re(self, pattern):
"""Translate a shell-like glob pattern to a regular expression.
Return a string containing the regex. Differs from
'fnmatch.translate()' in that '*' does not match "special characters"
(which are platform-specific).
"""
pattern_re = fnmatch.translate(pattern)
# '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
# IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
# and by extension they shouldn't match such "special characters" under
# any OS. So change all non-escaped dots in the RE to match any
# character except the special characters (currently: just os.sep).
sep = os.sep
if os.sep == '\\':
# we're using a regex to manipulate a regex, so we need
# to escape the backslash twice
sep = r'\\\\'
escaped = r'\1[^%s]' % sep
pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
return pattern_re | [
"def",
"_glob_to_re",
"(",
"self",
",",
"pattern",
")",
":",
"pattern_re",
"=",
"fnmatch",
".",
"translate",
"(",
"pattern",
")",
"# '?' and '*' in the glob pattern become '.' and '.*' in the RE, which",
"# IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,",
"#... | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pip/_vendor/distlib/manifest.py#L372-L393 | |
fossasia/visdom | 026958a66ce743f59e8f5232e974138c76b31675 | py/visdom/__init__.py | python | Visdom.mesh | (self, X, Y=None, win=None, env=None, opts=None) | return self._send({
'data': data,
'win': win,
'eid': env,
'layout': _opts2layout(opts),
'opts': opts,
}) | This function draws a mesh plot from a set of vertices defined in an
`Nx2` or `Nx3` matrix `X`, and polygons defined in an optional `Mx2` or
`Mx3` matrix `Y`.
The following `opts` are supported:
- `opts.color`: color (`string`)
- `opts.opacity`: opacity of polygons (`number` between 0 and 1) | This function draws a mesh plot from a set of vertices defined in an
`Nx2` or `Nx3` matrix `X`, and polygons defined in an optional `Mx2` or
`Mx3` matrix `Y`. | [
"This",
"function",
"draws",
"a",
"mesh",
"plot",
"from",
"a",
"set",
"of",
"vertices",
"defined",
"in",
"an",
"Nx2",
"or",
"Nx3",
"matrix",
"X",
"and",
"polygons",
"defined",
"in",
"an",
"optional",
"Mx2",
"or",
"Mx3",
"matrix",
"Y",
"."
] | def mesh(self, X, Y=None, win=None, env=None, opts=None):
"""
This function draws a mesh plot from a set of vertices defined in an
`Nx2` or `Nx3` matrix `X`, and polygons defined in an optional `Mx2` or
`Mx3` matrix `Y`.
The following `opts` are supported:
- `opts.color`: color (`string`)
- `opts.opacity`: opacity of polygons (`number` between 0 and 1)
"""
opts = {} if opts is None else opts
_title2str(opts)
_assert_opts(opts)
X = np.asarray(X)
assert X.ndim == 2, 'X must have 2 dimensions'
assert X.shape[1] == 2 or X.shape[1] == 3, 'X must have 2 or 3 columns'
is3d = X.shape[1] == 3
ispoly = Y is not None
if ispoly:
Y = np.asarray(Y)
assert Y.ndim == 2, 'Y must have 2 dimensions'
assert Y.shape[1] == X.shape[1], \
'X and Y must have same number of columns'
data = [{
'x': X[:, 0].tolist(),
'y': X[:, 1].tolist(),
'z': X[:, 2].tolist() if is3d else None,
'i': Y[:, 0].tolist() if ispoly else None,
'j': Y[:, 1].tolist() if ispoly else None,
'k': Y[:, 2].tolist() if is3d and ispoly else None,
'color': opts.get('color'),
'opacity': opts.get('opacity'),
'type': 'mesh3d' if is3d else 'mesh',
}]
return self._send({
'data': data,
'win': win,
'eid': env,
'layout': _opts2layout(opts),
'opts': opts,
}) | [
"def",
"mesh",
"(",
"self",
",",
"X",
",",
"Y",
"=",
"None",
",",
"win",
"=",
"None",
",",
"env",
"=",
"None",
",",
"opts",
"=",
"None",
")",
":",
"opts",
"=",
"{",
"}",
"if",
"opts",
"is",
"None",
"else",
"opts",
"_title2str",
"(",
"opts",
"... | https://github.com/fossasia/visdom/blob/026958a66ce743f59e8f5232e974138c76b31675/py/visdom/__init__.py#L2209-L2253 | |
pyscf/pyscf | 0adfb464333f5ceee07b664f291d4084801bae64 | pyscf/fci/direct_spin1.py | python | trans_rdm12 | (cibra, ciket, norb, nelec, link_index=None, reorder=True) | return dm1, dm2 | r'''Spin traced transition 1- and 2-particle transition density matrices.
1pdm[p,q] = :math:`\langle q^\dagger p\rangle`;
2pdm[p,q,r,s] = :math:`\langle p^\dagger r^\dagger s q\rangle`. | r'''Spin traced transition 1- and 2-particle transition density matrices. | [
"r",
"Spin",
"traced",
"transition",
"1",
"-",
"and",
"2",
"-",
"particle",
"transition",
"density",
"matrices",
"."
] | def trans_rdm12(cibra, ciket, norb, nelec, link_index=None, reorder=True):
r'''Spin traced transition 1- and 2-particle transition density matrices.
1pdm[p,q] = :math:`\langle q^\dagger p\rangle`;
2pdm[p,q,r,s] = :math:`\langle p^\dagger r^\dagger s q\rangle`.
'''
#(dm1a, dm1b), (dm2aa, dm2ab, dm2ba, dm2bb) = \
# trans_rdm12s(cibra, ciket, norb, nelec, link_index, reorder)
#return dm1a+dm1b, dm2aa+dm2ab+dm2ba+dm2bb
dm1, dm2 = rdm.make_rdm12_spin1('FCItdm12kern_sf', cibra, ciket,
norb, nelec, link_index, 2)
if reorder:
dm1, dm2 = rdm.reorder_rdm(dm1, dm2, inplace=True)
return dm1, dm2 | [
"def",
"trans_rdm12",
"(",
"cibra",
",",
"ciket",
",",
"norb",
",",
"nelec",
",",
"link_index",
"=",
"None",
",",
"reorder",
"=",
"True",
")",
":",
"#(dm1a, dm1b), (dm2aa, dm2ab, dm2ba, dm2bb) = \\",
"# trans_rdm12s(cibra, ciket, norb, nelec, link_index, reorder)",
... | https://github.com/pyscf/pyscf/blob/0adfb464333f5ceee07b664f291d4084801bae64/pyscf/fci/direct_spin1.py#L416-L429 | |
medbenali/CyberScan | ca85794cfce5e83e9cc5fca1512ba6edf2f14dee | scapy/packet.py | python | Packet.sprintf | (self, fmt, relax=1) | return s | sprintf(format, [relax=1]) -> str
where format is a string that can include directives. A directive begins and
ends by % and has the following format %[fmt[r],][cls[:nb].]field%.
fmt is a classic printf directive, "r" can be appended for raw substitution
(ex: IP.flags=0x18 instead of SA), nb is the number of the layer we want
(ex: for IP/IP packets, IP:2.src is the src of the upper IP layer).
Special case : "%.time%" is the creation time.
Ex : p.sprintf("%.time% %-15s,IP.src% -> %-15s,IP.dst% %IP.chksum% "
"%03xr,IP.proto% %r,TCP.flags%")
Moreover, the format string can include conditionnal statements. A conditionnal
statement looks like : {layer:string} where layer is a layer name, and string
is the string to insert in place of the condition if it is true, i.e. if layer
is present. If layer is preceded by a "!", the result si inverted. Conditions
can be imbricated. A valid statement can be :
p.sprintf("This is a{TCP: TCP}{UDP: UDP}{ICMP:n ICMP} packet")
p.sprintf("{IP:%IP.dst% {ICMP:%ICMP.type%}{TCP:%TCP.dport%}}")
A side effect is that, to obtain "{" and "}" characters, you must use
"%(" and "%)". | sprintf(format, [relax=1]) -> str
where format is a string that can include directives. A directive begins and
ends by % and has the following format %[fmt[r],][cls[:nb].]field%. | [
"sprintf",
"(",
"format",
"[",
"relax",
"=",
"1",
"]",
")",
"-",
">",
"str",
"where",
"format",
"is",
"a",
"string",
"that",
"can",
"include",
"directives",
".",
"A",
"directive",
"begins",
"and",
"ends",
"by",
"%",
"and",
"has",
"the",
"following",
... | def sprintf(self, fmt, relax=1):
"""sprintf(format, [relax=1]) -> str
where format is a string that can include directives. A directive begins and
ends by % and has the following format %[fmt[r],][cls[:nb].]field%.
fmt is a classic printf directive, "r" can be appended for raw substitution
(ex: IP.flags=0x18 instead of SA), nb is the number of the layer we want
(ex: for IP/IP packets, IP:2.src is the src of the upper IP layer).
Special case : "%.time%" is the creation time.
Ex : p.sprintf("%.time% %-15s,IP.src% -> %-15s,IP.dst% %IP.chksum% "
"%03xr,IP.proto% %r,TCP.flags%")
Moreover, the format string can include conditionnal statements. A conditionnal
statement looks like : {layer:string} where layer is a layer name, and string
is the string to insert in place of the condition if it is true, i.e. if layer
is present. If layer is preceded by a "!", the result si inverted. Conditions
can be imbricated. A valid statement can be :
p.sprintf("This is a{TCP: TCP}{UDP: UDP}{ICMP:n ICMP} packet")
p.sprintf("{IP:%IP.dst% {ICMP:%ICMP.type%}{TCP:%TCP.dport%}}")
A side effect is that, to obtain "{" and "}" characters, you must use
"%(" and "%)".
"""
escape = { "%": "%",
"(": "{",
")": "}" }
# Evaluate conditions
while "{" in fmt:
i = fmt.rindex("{")
j = fmt[i+1:].index("}")
cond = fmt[i+1:i+j+1]
k = cond.find(":")
if k < 0:
raise Scapy_Exception("Bad condition in format string: [%s] (read sprintf doc!)"%cond)
cond,format = cond[:k],cond[k+1:]
res = False
if cond[0] == "!":
res = True
cond = cond[1:]
if self.haslayer(cond):
res = not res
if not res:
format = ""
fmt = fmt[:i]+format+fmt[i+j+2:]
# Evaluate directives
s = ""
while "%" in fmt:
i = fmt.index("%")
s += fmt[:i]
fmt = fmt[i+1:]
if fmt and fmt[0] in escape:
s += escape[fmt[0]]
fmt = fmt[1:]
continue
try:
i = fmt.index("%")
sfclsfld = fmt[:i]
fclsfld = sfclsfld.split(",")
if len(fclsfld) == 1:
f = "s"
clsfld = fclsfld[0]
elif len(fclsfld) == 2:
f,clsfld = fclsfld
else:
raise Scapy_Exception
if "." in clsfld:
cls,fld = clsfld.split(".")
else:
cls = self.__class__.__name__
fld = clsfld
num = 1
if ":" in cls:
cls,num = cls.split(":")
num = int(num)
fmt = fmt[i+1:]
except:
raise Scapy_Exception("Bad format string [%%%s%s]" % (fmt[:25], fmt[25:] and "..."))
else:
if fld == "time":
val = time.strftime("%H:%M:%S.%%06i", time.localtime(self.time)) % int((self.time-int(self.time))*1000000)
elif cls == self.__class__.__name__ and hasattr(self, fld):
if num > 1:
val = self.payload.sprintf("%%%s,%s:%s.%s%%" % (f,cls,num-1,fld), relax)
f = "s"
elif f[-1] == "r": # Raw field value
val = getattr(self,fld)
f = f[:-1]
if not f:
f = "s"
else:
val = getattr(self,fld)
if fld in self.fieldtype:
val = self.fieldtype[fld].i2repr(self,val)
else:
val = self.payload.sprintf("%%%s%%" % sfclsfld, relax)
f = "s"
s += ("%"+f) % val
s += fmt
return s | [
"def",
"sprintf",
"(",
"self",
",",
"fmt",
",",
"relax",
"=",
"1",
")",
":",
"escape",
"=",
"{",
"\"%\"",
":",
"\"%\"",
",",
"\"(\"",
":",
"\"{\"",
",",
"\")\"",
":",
"\"}\"",
"}",
"# Evaluate conditions ",
"while",
"\"{\"",
"in",
"fmt",
":",
"i",
... | https://github.com/medbenali/CyberScan/blob/ca85794cfce5e83e9cc5fca1512ba6edf2f14dee/scapy/packet.py#L831-L934 | |
MDudek-ICS/TRISIS-TRITON-HATMAN | 15a00af7fd1040f0430729d024427601f84886a1 | decompiled_code/library/StringIO.py | python | StringIO.flush | (self) | Flush the internal buffer | Flush the internal buffer | [
"Flush",
"the",
"internal",
"buffer"
] | def flush(self):
"""Flush the internal buffer
"""
_complain_ifclosed(self.closed) | [
"def",
"flush",
"(",
"self",
")",
":",
"_complain_ifclosed",
"(",
"self",
".",
"closed",
")"
] | https://github.com/MDudek-ICS/TRISIS-TRITON-HATMAN/blob/15a00af7fd1040f0430729d024427601f84886a1/decompiled_code/library/StringIO.py#L267-L270 | ||
FenTechSolutions/CausalDiscoveryToolbox | 073b13a5076390147e95763bab73775c59e6d891 | cdt/data/causal_mechanisms.py | python | GaussianProcessMix_Mechanism.__call__ | (self, causes) | return effect | Run the mechanism. | Run the mechanism. | [
"Run",
"the",
"mechanism",
"."
] | def __call__(self, causes):
"""Run the mechanism."""
effect = np.zeros((self.points, 1))
# Compute each cause's contribution
if(causes.shape[1] > 0):
mix = np.hstack((causes, self.noise))
effect[:, 0] = self.mechanism(mix)
else:
effect[:, 0] = self.mechanism(self.noise)
return effect | [
"def",
"__call__",
"(",
"self",
",",
"causes",
")",
":",
"effect",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"points",
",",
"1",
")",
")",
"# Compute each cause's contribution",
"if",
"(",
"causes",
".",
"shape",
"[",
"1",
"]",
">",
"0",
")",
... | https://github.com/FenTechSolutions/CausalDiscoveryToolbox/blob/073b13a5076390147e95763bab73775c59e6d891/cdt/data/causal_mechanisms.py#L268-L278 | |
kupferlauncher/kupfer | 1c1e9bcbce05a82f503f68f8b3955c20b02639b3 | kupfer/main.py | python | setup_locale_and_gettext | () | Set up localization with gettext | Set up localization with gettext | [
"Set",
"up",
"localization",
"with",
"gettext"
] | def setup_locale_and_gettext():
"""Set up localization with gettext"""
package_name = "kupfer"
localedir = "./locale"
try:
from kupfer import version_subst
except ImportError:
pass
else:
package_name = version_subst.PACKAGE_NAME
localedir = version_subst.LOCALEDIR
# Install _() builtin for gettext; always returning unicode objects
# also install ngettext()
gettext.install(package_name, localedir=localedir, #unicode=True,
names=("ngettext",))
# For Gtk.Builder, we need to call the C library gettext functions
# As well as set the codeset to avoid locale-dependent translation
# of the message catalog
locale.bindtextdomain(package_name, localedir)
locale.bind_textdomain_codeset(package_name, "UTF-8")
# to load in current locale properly for sorting etc
try:
locale.setlocale(locale.LC_ALL, "")
except locale.Error:
pass | [
"def",
"setup_locale_and_gettext",
"(",
")",
":",
"package_name",
"=",
"\"kupfer\"",
"localedir",
"=",
"\"./locale\"",
"try",
":",
"from",
"kupfer",
"import",
"version_subst",
"except",
"ImportError",
":",
"pass",
"else",
":",
"package_name",
"=",
"version_subst",
... | https://github.com/kupferlauncher/kupfer/blob/1c1e9bcbce05a82f503f68f8b3955c20b02639b3/kupfer/main.py#L7-L31 | ||
SuLab/WikidataIntegrator | 7900658ed08d9d582726beed50d9ad25f985e678 | wikidataintegrator/wdi_core.py | python | WDString.__init__ | (self, value, prop_nr, is_reference=False, is_qualifier=False, snak_type='value', references=None,
qualifiers=None, rank='normal', check_qualifier_equality=True) | Constructor, calls the superclass WDBaseDataType
:param value: The string to be used as the value
:type value: str
:param prop_nr: The WD item ID for this claim
:type prop_nr: str with a 'P' prefix followed by digits
:param is_reference: Whether this snak is a reference
:type is_reference: boolean
:param is_qualifier: Whether this snak is a qualifier
:type is_qualifier: boolean
:param snak_type: The snak type, either 'value', 'somevalue' or 'novalue'
:type snak_type: str
:param references: List with reference objects
:type references: A WD data type with subclass of WDBaseDataType
:param qualifiers: List with qualifier objects
:type qualifiers: A WD data type with subclass of WDBaseDataType
:param rank: WD rank of a snak with value 'preferred', 'normal' or 'deprecated'
:type rank: str | Constructor, calls the superclass WDBaseDataType | [
"Constructor",
"calls",
"the",
"superclass",
"WDBaseDataType"
] | def __init__(self, value, prop_nr, is_reference=False, is_qualifier=False, snak_type='value', references=None,
qualifiers=None, rank='normal', check_qualifier_equality=True):
"""
Constructor, calls the superclass WDBaseDataType
:param value: The string to be used as the value
:type value: str
:param prop_nr: The WD item ID for this claim
:type prop_nr: str with a 'P' prefix followed by digits
:param is_reference: Whether this snak is a reference
:type is_reference: boolean
:param is_qualifier: Whether this snak is a qualifier
:type is_qualifier: boolean
:param snak_type: The snak type, either 'value', 'somevalue' or 'novalue'
:type snak_type: str
:param references: List with reference objects
:type references: A WD data type with subclass of WDBaseDataType
:param qualifiers: List with qualifier objects
:type qualifiers: A WD data type with subclass of WDBaseDataType
:param rank: WD rank of a snak with value 'preferred', 'normal' or 'deprecated'
:type rank: str
"""
super(WDString, self).__init__(value=value, snak_type=snak_type, data_type=self.DTYPE,
is_reference=is_reference, is_qualifier=is_qualifier, references=references,
qualifiers=qualifiers, rank=rank, prop_nr=prop_nr,
check_qualifier_equality=check_qualifier_equality)
self.set_value(value=value) | [
"def",
"__init__",
"(",
"self",
",",
"value",
",",
"prop_nr",
",",
"is_reference",
"=",
"False",
",",
"is_qualifier",
"=",
"False",
",",
"snak_type",
"=",
"'value'",
",",
"references",
"=",
"None",
",",
"qualifiers",
"=",
"None",
",",
"rank",
"=",
"'norm... | https://github.com/SuLab/WikidataIntegrator/blob/7900658ed08d9d582726beed50d9ad25f985e678/wikidataintegrator/wdi_core.py#L2289-L2317 | ||
tmbo/questionary | 4c528fa90a0e2c446778420b8638f7176a6e7b5e | questionary/form.py | python | Form.unsafe_ask_async | (self, patch_stdout: bool = False) | return {
f.key: await f.question.unsafe_ask_async(patch_stdout)
for f in self.form_fields
} | Ask the questions using asyncio and return user response.
Does not catch keyboard interrupts.
Args:
patch_stdout: Ensure that the prompt renders correctly if other threads
are printing to stdout.
Returns:
The answers from the form. | Ask the questions using asyncio and return user response. | [
"Ask",
"the",
"questions",
"using",
"asyncio",
"and",
"return",
"user",
"response",
"."
] | async def unsafe_ask_async(self, patch_stdout: bool = False) -> Dict[str, Any]:
"""Ask the questions using asyncio and return user response.
Does not catch keyboard interrupts.
Args:
patch_stdout: Ensure that the prompt renders correctly if other threads
are printing to stdout.
Returns:
The answers from the form.
"""
return {
f.key: await f.question.unsafe_ask_async(patch_stdout)
for f in self.form_fields
} | [
"async",
"def",
"unsafe_ask_async",
"(",
"self",
",",
"patch_stdout",
":",
"bool",
"=",
"False",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"f",
".",
"key",
":",
"await",
"f",
".",
"question",
".",
"unsafe_ask_async",
"(",
"p... | https://github.com/tmbo/questionary/blob/4c528fa90a0e2c446778420b8638f7176a6e7b5e/questionary/form.py#L59-L74 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/Django-1.11.29/django/template/defaultfilters.py | python | striptags | (value) | return strip_tags(value) | Strips all [X]HTML tags. | Strips all [X]HTML tags. | [
"Strips",
"all",
"[",
"X",
"]",
"HTML",
"tags",
"."
] | def striptags(value):
"""Strips all [X]HTML tags."""
return strip_tags(value) | [
"def",
"striptags",
"(",
"value",
")",
":",
"return",
"strip_tags",
"(",
"value",
")"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/template/defaultfilters.py#L512-L514 | |
freedombox/FreedomBox | 335a7f92cc08f27981f838a7cddfc67740598e54 | plinth/modules/firewall/components.py | python | Firewall.ports_details | (self) | return ports_details | Retrieve details of ports associated with this component.. | Retrieve details of ports associated with this component.. | [
"Retrieve",
"details",
"of",
"ports",
"associated",
"with",
"this",
"component",
".."
] | def ports_details(self):
"""Retrieve details of ports associated with this component.."""
ports_details = []
for port in self.ports:
ports_details.append({
'name': port,
'details': firewall.get_port_details(port),
})
return ports_details | [
"def",
"ports_details",
"(",
"self",
")",
":",
"ports_details",
"=",
"[",
"]",
"for",
"port",
"in",
"self",
".",
"ports",
":",
"ports_details",
".",
"append",
"(",
"{",
"'name'",
":",
"port",
",",
"'details'",
":",
"firewall",
".",
"get_port_details",
"(... | https://github.com/freedombox/FreedomBox/blob/335a7f92cc08f27981f838a7cddfc67740598e54/plinth/modules/firewall/components.py#L37-L46 | |
tensorflow/tensor2tensor | 2a33b152d7835af66a6d20afe7961751047e28dd | tensor2tensor/utils/video_metrics.py | python | get_zipped_dataset_from_predictions | (predictions) | return iterator, feed_dict, num_videos | Creates dataset from in-memory predictions. | Creates dataset from in-memory predictions. | [
"Creates",
"dataset",
"from",
"in",
"-",
"memory",
"predictions",
"."
] | def get_zipped_dataset_from_predictions(predictions):
"""Creates dataset from in-memory predictions."""
targets = stack_data_given_key(predictions, "targets")
outputs = stack_data_given_key(predictions, "outputs")
num_videos, num_steps = targets.shape[:2]
# Truncate output time-steps to match target time-steps
outputs = outputs[:, :num_steps]
targets_placeholder = tf.placeholder(targets.dtype, targets.shape)
outputs_placeholder = tf.placeholder(outputs.dtype, outputs.shape)
dataset = tf.data.Dataset.from_tensor_slices(
(targets_placeholder, outputs_placeholder))
iterator = dataset.make_initializable_iterator()
feed_dict = {targets_placeholder: targets,
outputs_placeholder: outputs}
return iterator, feed_dict, num_videos | [
"def",
"get_zipped_dataset_from_predictions",
"(",
"predictions",
")",
":",
"targets",
"=",
"stack_data_given_key",
"(",
"predictions",
",",
"\"targets\"",
")",
"outputs",
"=",
"stack_data_given_key",
"(",
"predictions",
",",
"\"outputs\"",
")",
"num_videos",
",",
"nu... | https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/utils/video_metrics.py#L116-L132 | |
rhinstaller/anaconda | 63edc8680f1b05cbfe11bef28703acba808c5174 | pyanaconda/ui/gui/spokes/subscription.py | python | SubscriptionSpoke._update_register_button_state | (self) | Update register button state.
The button is only sensitive if no processing is ongoing
and we either have enough authentication data to register
or the system is subscribed, so we can unregister it. | Update register button state. | [
"Update",
"register",
"button",
"state",
"."
] | def _update_register_button_state(self):
"""Update register button state.
The button is only sensitive if no processing is ongoing
and we either have enough authentication data to register
or the system is subscribed, so we can unregister it.
"""
button_sensitive = False
if self._registration_controls_enabled:
# if we are subscribed, we can always unregister
if self.subscription_attached:
button_sensitive = True
# check if credentials are sufficient for registration
elif self.authentication_method == AuthenticationMethod.USERNAME_PASSWORD:
button_sensitive = username_password_sufficient(self.subscription_request)
elif self.authentication_method == AuthenticationMethod.ORG_KEY:
button_sensitive = org_keys_sufficient(self.subscription_request)
self._register_button.set_sensitive(button_sensitive) | [
"def",
"_update_register_button_state",
"(",
"self",
")",
":",
"button_sensitive",
"=",
"False",
"if",
"self",
".",
"_registration_controls_enabled",
":",
"# if we are subscribed, we can always unregister",
"if",
"self",
".",
"subscription_attached",
":",
"button_sensitive",
... | https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/ui/gui/spokes/subscription.py#L1115-L1132 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.