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
cleverhans-lab/cleverhans
e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d
cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py
python
ClassificationBatches.serialize
(self, fobj)
Serializes data stored in this class.
Serializes data stored in this class.
[ "Serializes", "data", "stored", "in", "this", "class", "." ]
def serialize(self, fobj): """Serializes data stored in this class.""" pickle.dump(self._data, fobj)
[ "def", "serialize", "(", "self", ",", "fobj", ")", ":", "pickle", ".", "dump", "(", "self", ".", "_data", ",", "fobj", ")" ]
https://github.com/cleverhans-lab/cleverhans/blob/e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d/cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L246-L248
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/xdg/Mime.py
python
is_text_file
(path)
Guess whether a file contains text or binary data. Heuristic: binary if the first 32 bytes include ASCII control characters. This rule may change in future versions. .. versionadded:: 1.0
Guess whether a file contains text or binary data. Heuristic: binary if the first 32 bytes include ASCII control characters. This rule may change in future versions. .. versionadded:: 1.0
[ "Guess", "whether", "a", "file", "contains", "text", "or", "binary", "data", ".", "Heuristic", ":", "binary", "if", "the", "first", "32", "bytes", "include", "ASCII", "control", "characters", ".", "This", "rule", "may", "change", "in", "future", "versions", ...
def is_text_file(path): """Guess whether a file contains text or binary data. Heuristic: binary if the first 32 bytes include ASCII control characters. This rule may change in future versions. .. versionadded:: 1.0 """ try: f = open(path, 'rb') except IOError: return False with f: return _is_text(f.read(32))
[ "def", "is_text_file", "(", "path", ")", ":", "try", ":", "f", "=", "open", "(", "path", ",", "'rb'", ")", "except", "IOError", ":", "return", "False", "with", "f", ":", "return", "_is_text", "(", "f", ".", "read", "(", "32", ")", ")" ]
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/xdg/Mime.py#L696-L710
JacquesLucke/animation_nodes
b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1
animation_nodes/nodes/mesh/set_bevel_edge_weight.py
python
SetBevelEdgeWeightNode.execute
(self, object, weights)
return object
[]
def execute(self, object, weights): if object is None: return None if object.type != "MESH": self.raiseErrorMessage("Object is not a mesh object.") if object.mode != "OBJECT": self.raiseErrorMessage("Object is not in object mode.") if not object.data.use_customdata_edge_bevel: object.data.use_customdata_edge_bevel = True weights = VirtualDoubleList.create(weights, 0).materialize(len(object.data.edges)) object.data.edges.foreach_set('bevel_weight', weights) object.data.update() return object
[ "def", "execute", "(", "self", ",", "object", ",", "weights", ")", ":", "if", "object", "is", "None", ":", "return", "None", "if", "object", ".", "type", "!=", "\"MESH\"", ":", "self", ".", "raiseErrorMessage", "(", "\"Object is not a mesh object.\"", ")", ...
https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/nodes/mesh/set_bevel_edge_weight.py#L19-L34
onaio/onadata
89ad16744e8f247fb748219476f6ac295869a95f
onadata/libs/serializers/floip_serializer.py
python
FloipSerializer.get_profile
(self, value)
return 'data-package'
Returns the data-package profile.
Returns the data-package profile.
[ "Returns", "the", "data", "-", "package", "profile", "." ]
def get_profile(self, value): # pylint: disable=no-self-use,W0613 """ Returns the data-package profile. """ return 'data-package'
[ "def", "get_profile", "(", "self", ",", "value", ")", ":", "# pylint: disable=no-self-use,W0613", "return", "'data-package'" ]
https://github.com/onaio/onadata/blob/89ad16744e8f247fb748219476f6ac295869a95f/onadata/libs/serializers/floip_serializer.py#L139-L143
scikit-learn/scikit-learn
1d1aadd0711b87d2a11c80aad15df6f8cf156712
sklearn/cluster/_bicluster.py
python
_bistochastic_normalize
(X, max_iter=1000, tol=1e-5)
return X_scaled
Normalize rows and columns of ``X`` simultaneously so that all rows sum to one constant and all columns sum to a different constant.
Normalize rows and columns of ``X`` simultaneously so that all rows sum to one constant and all columns sum to a different constant.
[ "Normalize", "rows", "and", "columns", "of", "X", "simultaneously", "so", "that", "all", "rows", "sum", "to", "one", "constant", "and", "all", "columns", "sum", "to", "a", "different", "constant", "." ]
def _bistochastic_normalize(X, max_iter=1000, tol=1e-5): """Normalize rows and columns of ``X`` simultaneously so that all rows sum to one constant and all columns sum to a different constant. """ # According to paper, this can also be done more efficiently with # deviation reduction and balancing algorithms. X = make_nonnegative(X) X_scaled = X for _ in range(max_iter): X_new, _, _ = _scale_normalize(X_scaled) if issparse(X): dist = norm(X_scaled.data - X.data) else: dist = norm(X_scaled - X_new) X_scaled = X_new if dist is not None and dist < tol: break return X_scaled
[ "def", "_bistochastic_normalize", "(", "X", ",", "max_iter", "=", "1000", ",", "tol", "=", "1e-5", ")", ":", "# According to paper, this can also be done more efficiently with", "# deviation reduction and balancing algorithms.", "X", "=", "make_nonnegative", "(", "X", ")", ...
https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/cluster/_bicluster.py#L46-L64
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/threading.py
python
_Event.set
(self)
Set the internal flag to true. All threads waiting for the flag to become true are awakened. Threads that call wait() once the flag is true will not block at all.
Set the internal flag to true.
[ "Set", "the", "internal", "flag", "to", "true", "." ]
def set(self): """Set the internal flag to true. All threads waiting for the flag to become true are awakened. Threads that call wait() once the flag is true will not block at all. """ self.__cond.acquire() try: self.__flag = True self.__cond.notify_all() finally: self.__cond.release()
[ "def", "set", "(", "self", ")", ":", "self", ".", "__cond", ".", "acquire", "(", ")", "try", ":", "self", ".", "__flag", "=", "True", "self", ".", "__cond", ".", "notify_all", "(", ")", "finally", ":", "self", ".", "__cond", ".", "release", "(", ...
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/threading.py#L576-L588
bokeh/bokeh
a00e59da76beb7b9f83613533cfd3aced1df5f06
bokeh/core/property/bases.py
python
Property.from_json
(self, json: Any, *, models: Dict[ID, HasProps] | None = None)
return json
Convert from JSON-compatible values into a value for this property. JSON-compatible values are: list, dict, number, string, bool, None
Convert from JSON-compatible values into a value for this property.
[ "Convert", "from", "JSON", "-", "compatible", "values", "into", "a", "value", "for", "this", "property", "." ]
def from_json(self, json: Any, *, models: Dict[ID, HasProps] | None = None) -> T: """ Convert from JSON-compatible values into a value for this property. JSON-compatible values are: list, dict, number, string, bool, None """ return json
[ "def", "from_json", "(", "self", ",", "json", ":", "Any", ",", "*", ",", "models", ":", "Dict", "[", "ID", ",", "HasProps", "]", "|", "None", "=", "None", ")", "->", "T", ":", "return", "json" ]
https://github.com/bokeh/bokeh/blob/a00e59da76beb7b9f83613533cfd3aced1df5f06/bokeh/core/property/bases.py#L264-L270
zhaoolee/StarsAndClown
b2d4039cad2f9232b691e5976f787b49a0a2c113
node_modules/npmi/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.copy
(self)
return self.__class__(self)
od.copy() -> a shallow copy of od
od.copy() -> a shallow copy of od
[ "od", ".", "copy", "()", "-", ">", "a", "shallow", "copy", "of", "od" ]
def copy(self): 'od.copy() -> a shallow copy of od' return self.__class__(self)
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "self", ")" ]
https://github.com/zhaoolee/StarsAndClown/blob/b2d4039cad2f9232b691e5976f787b49a0a2c113/node_modules/npmi/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py#L249-L251
IntelAI/models
1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c
models/language_translation/tensorflow/transformer_mlperf/inference/bfloat16/transformer/translate.py
python
_trim_and_decode
(ids, subtokenizer)
Trim EOS and PAD tokens from ids, and decode to return a string.
Trim EOS and PAD tokens from ids, and decode to return a string.
[ "Trim", "EOS", "and", "PAD", "tokens", "from", "ids", "and", "decode", "to", "return", "a", "string", "." ]
def _trim_and_decode(ids, subtokenizer): """Trim EOS and PAD tokens from ids, and decode to return a string.""" try: index = list(ids).index(tokenizer.EOS_ID) return subtokenizer.decode(ids[:index]) except ValueError: # No EOS found in sequence return subtokenizer.decode(ids)
[ "def", "_trim_and_decode", "(", "ids", ",", "subtokenizer", ")", ":", "try", ":", "index", "=", "list", "(", "ids", ")", ".", "index", "(", "tokenizer", ".", "EOS_ID", ")", "return", "subtokenizer", ".", "decode", "(", "ids", "[", ":", "index", "]", ...
https://github.com/IntelAI/models/blob/1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c/models/language_translation/tensorflow/transformer_mlperf/inference/bfloat16/transformer/translate.py#L97-L103
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
Xtra/autopep8.py
python
Container.is_string
(self)
return False
[]
def is_string(self): return False
[ "def", "is_string", "(", "self", ")", ":", "return", "False" ]
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/Xtra/autopep8.py#L2037-L2038
eight04/ComicCrawler
9ace390a6772940d65c96b1579433f3ccbdaccbf
comiccrawler/cli.py
python
console_download
(url, savepath)
Download url to savepath.
Download url to savepath.
[ "Download", "url", "to", "savepath", "." ]
def console_download(url, savepath): """Download url to savepath.""" # pylint: disable=import-outside-toplevel from .mission import Mission from .analyzer import Analyzer from .crawler import download mission = Mission(url=url) Analyzer(mission).analyze() download(mission, savepath)
[ "def", "console_download", "(", "url", ",", "savepath", ")", ":", "# pylint: disable=import-outside-toplevel", "from", ".", "mission", "import", "Mission", "from", ".", "analyzer", "import", "Analyzer", "from", ".", "crawler", "import", "download", "mission", "=", ...
https://github.com/eight04/ComicCrawler/blob/9ace390a6772940d65c96b1579433f3ccbdaccbf/comiccrawler/cli.py#L32-L41
barseghyanartur/django-fobi
a998feae007d7fe3637429a80e42952ec7cda79f
src/fobi/contrib/apps/drf_integration/form_elements/fields/time/base.py
python
TimeInputPlugin.get_custom_field_instances
(self, form_element_plugin, request=None, form_entry=None, form_element_entries=None, **kwargs)
return [ DRFIntegrationFormElementPluginProcessor( field_class=TimeField, field_kwargs=field_kwargs ) ]
Get form field instances.
Get form field instances.
[ "Get", "form", "field", "instances", "." ]
def get_custom_field_instances(self, form_element_plugin, request=None, form_entry=None, form_element_entries=None, **kwargs): """Get form field instances.""" field_kwargs = { 'required': form_element_plugin.data.required, 'initial': form_element_plugin.data.initial, 'label': form_element_plugin.data.label, 'help_text': form_element_plugin.data.help_text, # 'input_formats': form_element_plugin.data.input_formats, } return [ DRFIntegrationFormElementPluginProcessor( field_class=TimeField, field_kwargs=field_kwargs ) ]
[ "def", "get_custom_field_instances", "(", "self", ",", "form_element_plugin", ",", "request", "=", "None", ",", "form_entry", "=", "None", ",", "form_element_entries", "=", "None", ",", "*", "*", "kwargs", ")", ":", "field_kwargs", "=", "{", "'required'", ":",...
https://github.com/barseghyanartur/django-fobi/blob/a998feae007d7fe3637429a80e42952ec7cda79f/src/fobi/contrib/apps/drf_integration/form_elements/fields/time/base.py#L30-L49
caktux/pytrader
b45b216dab3db78d6028d85e9a6f80419c22cea0
api.py
python
OrderBook.add_own
(self, order)
called by api when a new order has been acked after it has been submitted or after a receiving a user_order message for a new order. This is a separate method from _add_own because we additionally need to fire a bunch of signals when this happens
called by api when a new order has been acked after it has been submitted or after a receiving a user_order message for a new order. This is a separate method from _add_own because we additionally need to fire a bunch of signals when this happens
[ "called", "by", "api", "when", "a", "new", "order", "has", "been", "acked", "after", "it", "has", "been", "submitted", "or", "after", "a", "receiving", "a", "user_order", "message", "for", "a", "new", "order", ".", "This", "is", "a", "separate", "method"...
def add_own(self, order): """called by api when a new order has been acked after it has been submitted or after a receiving a user_order message for a new order. This is a separate method from _add_own because we additionally need to fire a bunch of signals when this happens""" if not self.have_own_oid(order.oid): self.debug("### adding order:", order.typ, order.price, order.volume, order.oid) self._add_own(order) self.signal_own_added(self, (order)) self.signal_changed(self, None) self.signal_owns_changed(self, None)
[ "def", "add_own", "(", "self", ",", "order", ")", ":", "if", "not", "self", ".", "have_own_oid", "(", "order", ".", "oid", ")", ":", "self", ".", "debug", "(", "\"### adding order:\"", ",", "order", ".", "typ", ",", "order", ".", "price", ",", "order...
https://github.com/caktux/pytrader/blob/b45b216dab3db78d6028d85e9a6f80419c22cea0/api.py#L1749-L1759
elastic/apm-agent-python
67ce41e492f91d0aaf9fdb599e11d42e5f0ea198
elasticapm/metrics/base_metrics.py
python
MetricsRegistry.__init__
(self, client, tags=None)
Creates a new metric registry :param client: client instance :param tags:
Creates a new metric registry
[ "Creates", "a", "new", "metric", "registry" ]
def __init__(self, client, tags=None): """ Creates a new metric registry :param client: client instance :param tags: """ self.client = client self._metricsets = {} self._tags = tags or {} self._collect_timer = None super(MetricsRegistry, self).__init__()
[ "def", "__init__", "(", "self", ",", "client", ",", "tags", "=", "None", ")", ":", "self", ".", "client", "=", "client", "self", ".", "_metricsets", "=", "{", "}", "self", ".", "_tags", "=", "tags", "or", "{", "}", "self", ".", "_collect_timer", "=...
https://github.com/elastic/apm-agent-python/blob/67ce41e492f91d0aaf9fdb599e11d42e5f0ea198/elasticapm/metrics/base_metrics.py#L47-L58
quantumlib/OpenFermion
6187085f2a7707012b68370b625acaeed547e62b
src/openfermion/ops/operators/majorana_operator.py
python
_merge_majorana_terms
(left_term, right_term)
return tuple(merged_term), parity % 2
Merge two Majorana terms. Args: left_term (Tuple[int]): The left-hand term right_term (Tuple[int]): The right-hand term Returns: Tuple[Tuple[int], int]. The first object returned is a sorted list representing the indices acted upon. The second object is the parity of the term. A parity of 1 indicates that the term should include a minus sign.
Merge two Majorana terms.
[ "Merge", "two", "Majorana", "terms", "." ]
def _merge_majorana_terms(left_term, right_term): """Merge two Majorana terms. Args: left_term (Tuple[int]): The left-hand term right_term (Tuple[int]): The right-hand term Returns: Tuple[Tuple[int], int]. The first object returned is a sorted list representing the indices acted upon. The second object is the parity of the term. A parity of 1 indicates that the term should include a minus sign. """ merged_term = [] parity = 0 i, j = 0, 0 while i < len(left_term) and j < len(right_term): if left_term[i] < right_term[j]: merged_term.append(left_term[i]) i += 1 elif left_term[i] > right_term[j]: merged_term.append(right_term[j]) j += 1 parity += len(left_term) - i else: parity += len(left_term) - i - 1 i += 1 j += 1 if i == len(left_term): merged_term.extend(right_term[j:]) else: merged_term.extend(left_term[i:]) return tuple(merged_term), parity % 2
[ "def", "_merge_majorana_terms", "(", "left_term", ",", "right_term", ")", ":", "merged_term", "=", "[", "]", "parity", "=", "0", "i", ",", "j", "=", "0", ",", "0", "while", "i", "<", "len", "(", "left_term", ")", "and", "j", "<", "len", "(", "right...
https://github.com/quantumlib/OpenFermion/blob/6187085f2a7707012b68370b625acaeed547e62b/src/openfermion/ops/operators/majorana_operator.py#L301-L333
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/pwiki/StringOps.py
python
unicodeToCompFilename
(us)
return "".join(result)
Encode a unicode filename to a filename compatible to (hopefully) any filesystem encoding by converting unicode to '=xx' for characters up to 255 and '$xxxx' above. Each 'x represents a hex character. Be aware that the returned filename may be too long to be allowed in the used filesystem.
Encode a unicode filename to a filename compatible to (hopefully) any filesystem encoding by converting unicode to '=xx' for characters up to 255 and '$xxxx' above. Each 'x represents a hex character. Be aware that the returned filename may be too long to be allowed in the used filesystem.
[ "Encode", "a", "unicode", "filename", "to", "a", "filename", "compatible", "to", "(", "hopefully", ")", "any", "filesystem", "encoding", "by", "converting", "unicode", "to", "=", "xx", "for", "characters", "up", "to", "255", "and", "$xxxx", "above", ".", "...
def unicodeToCompFilename(us): """ Encode a unicode filename to a filename compatible to (hopefully) any filesystem encoding by converting unicode to '=xx' for characters up to 255 and '$xxxx' above. Each 'x represents a hex character. Be aware that the returned filename may be too long to be allowed in the used filesystem. """ result = [] for c in us: if ord(c) > 255: result.append("$%04x" % ord(c)) continue if c in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"+\ "{}()+-_,.%": # Allowed characters result.append(str(c)) continue result.append("=%02x" % ord(c)) return "".join(result)
[ "def", "unicodeToCompFilename", "(", "us", ")", ":", "result", "=", "[", "]", "for", "c", "in", "us", ":", "if", "ord", "(", "c", ")", ">", "255", ":", "result", ".", "append", "(", "\"$%04x\"", "%", "ord", "(", "c", ")", ")", "continue", "if", ...
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/pwiki/StringOps.py#L191-L213
linkchecker/linkchecker
d1078ed8480e5cfc4264d0dbf026b45b45aede4d
linkcheck/director/logger.py
python
Logger.end_log_output
(self, **kwargs)
End output of all configured loggers.
End output of all configured loggers.
[ "End", "output", "of", "all", "configured", "loggers", "." ]
def end_log_output(self, **kwargs): """ End output of all configured loggers. """ for logger in self.loggers: logger.end_output(**kwargs)
[ "def", "end_log_output", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "logger", "in", "self", ".", "loggers", ":", "logger", ".", "end_output", "(", "*", "*", "kwargs", ")" ]
https://github.com/linkchecker/linkchecker/blob/d1078ed8480e5cfc4264d0dbf026b45b45aede4d/linkcheck/director/logger.py#L42-L47
Pagure/pagure
512f23f5cd1f965276969747792edeb1215cba68
pagure/lib/tasks.py
python
refresh_remote_pr
(self, session, name, namespace, user, requestid)
return ret( "ui_ns.request_pull", username=user, namespace=namespace, repo=name, requestid=requestid, )
Refresh the local clone of a git repository used in a remote pull-request.
Refresh the local clone of a git repository used in a remote pull-request.
[ "Refresh", "the", "local", "clone", "of", "a", "git", "repository", "used", "in", "a", "remote", "pull", "-", "request", "." ]
def refresh_remote_pr(self, session, name, namespace, user, requestid): """Refresh the local clone of a git repository used in a remote pull-request. """ project = pagure.lib.query._get_project( session, namespace=namespace, name=name, user=user ) request = pagure.lib.query.search_pull_requests( session, project_id=project.id, requestid=requestid ) _log.debug( "refreshing remote pull-request: %s/#%s", request.project.fullname, request.id, ) clonepath = pagure.utils.get_remote_repo_path( request.remote_git, request.branch_from ) repo = pagure.lib.repo.PagureRepo(clonepath) repo.pull(branch=request.branch_from, force=True) refresh_pr_cache.delay(name, namespace, user) del repo return ret( "ui_ns.request_pull", username=user, namespace=namespace, repo=name, requestid=requestid, )
[ "def", "refresh_remote_pr", "(", "self", ",", "session", ",", "name", ",", "namespace", ",", "user", ",", "requestid", ")", ":", "project", "=", "pagure", ".", "lib", ".", "query", ".", "_get_project", "(", "session", ",", "namespace", "=", "namespace", ...
https://github.com/Pagure/pagure/blob/512f23f5cd1f965276969747792edeb1215cba68/pagure/lib/tasks.py#L570-L602
olemb/dbfread
dce544641065d966c76a97864b4e9908ec922ce8
dbfread/ifiles.py
python
ifind
(pat, ext=None)
Look for a file in a case insensitive way. Returns filename it a matching file was found, or None if it was not.
Look for a file in a case insensitive way.
[ "Look", "for", "a", "file", "in", "a", "case", "insensitive", "way", "." ]
def ifind(pat, ext=None): """Look for a file in a case insensitive way. Returns filename it a matching file was found, or None if it was not. """ if ext: pat = os.path.splitext(pat)[0] + ext files = iglob(pat) if files: return files[0] # Return an arbitrary file else: return None
[ "def", "ifind", "(", "pat", ",", "ext", "=", "None", ")", ":", "if", "ext", ":", "pat", "=", "os", ".", "path", ".", "splitext", "(", "pat", ")", "[", "0", "]", "+", "ext", "files", "=", "iglob", "(", "pat", ")", "if", "files", ":", "return",...
https://github.com/olemb/dbfread/blob/dce544641065d966c76a97864b4e9908ec922ce8/dbfread/ifiles.py#L48-L60
cbrgm/telegram-robot-rss
58fe98de427121fdc152c8df0721f1891174e6c9
venv/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py
python
pyparsing_common.convertToDate
(fmt="%Y-%m-%d")
return cvt_fn
Helper to create a parse action for converting parsed date string to Python datetime.date Params - - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"}) Example:: date_expr = pyparsing_common.iso8601_date.copy() date_expr.setParseAction(pyparsing_common.convertToDate()) print(date_expr.parseString("1999-12-31")) prints:: [datetime.date(1999, 12, 31)]
Helper to create a parse action for converting parsed date string to Python datetime.date
[ "Helper", "to", "create", "a", "parse", "action", "for", "converting", "parsed", "date", "string", "to", "Python", "datetime", ".", "date" ]
def convertToDate(fmt="%Y-%m-%d"): """ Helper to create a parse action for converting parsed date string to Python datetime.date Params - - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"}) Example:: date_expr = pyparsing_common.iso8601_date.copy() date_expr.setParseAction(pyparsing_common.convertToDate()) print(date_expr.parseString("1999-12-31")) prints:: [datetime.date(1999, 12, 31)] """ def cvt_fn(s,l,t): try: return datetime.strptime(t[0], fmt).date() except ValueError as ve: raise ParseException(s, l, str(ve)) return cvt_fn
[ "def", "convertToDate", "(", "fmt", "=", "\"%Y-%m-%d\"", ")", ":", "def", "cvt_fn", "(", "s", ",", "l", ",", "t", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "t", "[", "0", "]", ",", "fmt", ")", ".", "date", "(", ")", "exc...
https://github.com/cbrgm/telegram-robot-rss/blob/58fe98de427121fdc152c8df0721f1891174e6c9/venv/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py#L5547-L5566
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/dayu/v20180709/models.py
python
SchedulingDomain.__init__
(self)
r""" :param Domain: 调度域名 :type Domain: str :param BGPIpList: BGP线路IP列表 :type BGPIpList: list of str :param CTCCIpList: 电信线路IP列表 :type CTCCIpList: list of str :param CUCCIpList: 联通线路IP列表 :type CUCCIpList: list of str :param CMCCIpList: 移动线路IP列表 :type CMCCIpList: list of str :param OverseaIpList: 海外线路IP列表 :type OverseaIpList: list of str :param Method: 调度方式,当前仅支持优先级, 取值为priority :type Method: str :param CreateTime: 创建时间 :type CreateTime: str :param TTL: ttl :type TTL: int :param Status: 状态 注意:此字段可能返回 null,表示取不到有效值。 :type Status: int :param ModifyTime: 修改时间 注意:此字段可能返回 null,表示取不到有效值。 :type ModifyTime: str
r""" :param Domain: 调度域名 :type Domain: str :param BGPIpList: BGP线路IP列表 :type BGPIpList: list of str :param CTCCIpList: 电信线路IP列表 :type CTCCIpList: list of str :param CUCCIpList: 联通线路IP列表 :type CUCCIpList: list of str :param CMCCIpList: 移动线路IP列表 :type CMCCIpList: list of str :param OverseaIpList: 海外线路IP列表 :type OverseaIpList: list of str :param Method: 调度方式,当前仅支持优先级, 取值为priority :type Method: str :param CreateTime: 创建时间 :type CreateTime: str :param TTL: ttl :type TTL: int :param Status: 状态 注意:此字段可能返回 null,表示取不到有效值。 :type Status: int :param ModifyTime: 修改时间 注意:此字段可能返回 null,表示取不到有效值。 :type ModifyTime: str
[ "r", ":", "param", "Domain", ":", "调度域名", ":", "type", "Domain", ":", "str", ":", "param", "BGPIpList", ":", "BGP线路IP列表", ":", "type", "BGPIpList", ":", "list", "of", "str", ":", "param", "CTCCIpList", ":", "电信线路IP列表", ":", "type", "CTCCIpList", ":", "...
def __init__(self): r""" :param Domain: 调度域名 :type Domain: str :param BGPIpList: BGP线路IP列表 :type BGPIpList: list of str :param CTCCIpList: 电信线路IP列表 :type CTCCIpList: list of str :param CUCCIpList: 联通线路IP列表 :type CUCCIpList: list of str :param CMCCIpList: 移动线路IP列表 :type CMCCIpList: list of str :param OverseaIpList: 海外线路IP列表 :type OverseaIpList: list of str :param Method: 调度方式,当前仅支持优先级, 取值为priority :type Method: str :param CreateTime: 创建时间 :type CreateTime: str :param TTL: ttl :type TTL: int :param Status: 状态 注意:此字段可能返回 null,表示取不到有效值。 :type Status: int :param ModifyTime: 修改时间 注意:此字段可能返回 null,表示取不到有效值。 :type ModifyTime: str """ self.Domain = None self.BGPIpList = None self.CTCCIpList = None self.CUCCIpList = None self.CMCCIpList = None self.OverseaIpList = None self.Method = None self.CreateTime = None self.TTL = None self.Status = None self.ModifyTime = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Domain", "=", "None", "self", ".", "BGPIpList", "=", "None", "self", ".", "CTCCIpList", "=", "None", "self", ".", "CUCCIpList", "=", "None", "self", ".", "CMCCIpList", "=", "None", "self", ".", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/dayu/v20180709/models.py#L9816-L9853
naver/claf
6f45b1ecca0aa2b3bcf99e79c9cb2c915ba0bf3b
claf/model/base.py
python
ModelBase.make_predictions
(self, features)
for Metrics
for Metrics
[ "for", "Metrics" ]
def make_predictions(self, features): """ for Metrics """ raise NotImplementedError
[ "def", "make_predictions", "(", "self", ",", "features", ")", ":", "raise", "NotImplementedError" ]
https://github.com/naver/claf/blob/6f45b1ecca0aa2b3bcf99e79c9cb2c915ba0bf3b/claf/model/base.py#L26-L31
pillone/usntssearch
24b5e5bc4b6af2589d95121c4d523dc58cb34273
NZBmegasearch/mechanize/_form.py
python
MimeWriter.startbody
(self, ctype=None, plist=[], prefix=1, add_to_http_hdrs=0, content_type=1)
return self._fp
prefix is ignored if add_to_http_hdrs is true.
prefix is ignored if add_to_http_hdrs is true.
[ "prefix", "is", "ignored", "if", "add_to_http_hdrs", "is", "true", "." ]
def startbody(self, ctype=None, plist=[], prefix=1, add_to_http_hdrs=0, content_type=1): """ prefix is ignored if add_to_http_hdrs is true. """ if content_type and ctype: for name, value in plist: ctype = ctype + ';\r\n %s=%s' % (name, value) self.addheader("Content-Type", ctype, prefix=prefix, add_to_http_hdrs=add_to_http_hdrs) self.flushheaders() if not add_to_http_hdrs: self._fp.write("\r\n") self._first_part = True return self._fp
[ "def", "startbody", "(", "self", ",", "ctype", "=", "None", ",", "plist", "=", "[", "]", ",", "prefix", "=", "1", ",", "add_to_http_hdrs", "=", "0", ",", "content_type", "=", "1", ")", ":", "if", "content_type", "and", "ctype", ":", "for", "name", ...
https://github.com/pillone/usntssearch/blob/24b5e5bc4b6af2589d95121c4d523dc58cb34273/NZBmegasearch/mechanize/_form.py#L305-L318
conjure-up/conjure-up
d2bf8ab8e71ff01321d0e691a8d3e3833a047678
conjureup/controllers/juju/vspheresetup/tui.py
python
VSphereSetupController.render
(self)
return controllers.use('controllerpicker').render()
[]
def render(self): return controllers.use('controllerpicker').render()
[ "def", "render", "(", "self", ")", ":", "return", "controllers", ".", "use", "(", "'controllerpicker'", ")", ".", "render", "(", ")" ]
https://github.com/conjure-up/conjure-up/blob/d2bf8ab8e71ff01321d0e691a8d3e3833a047678/conjureup/controllers/juju/vspheresetup/tui.py#L7-L8
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/component_validation_result_entity.py
python
ComponentValidationResultEntity.disconnected_node_acknowledged
(self, disconnected_node_acknowledged)
Sets the disconnected_node_acknowledged of this ComponentValidationResultEntity. Acknowledges that this node is disconnected to allow for mutable requests to proceed. :param disconnected_node_acknowledged: The disconnected_node_acknowledged of this ComponentValidationResultEntity. :type: bool
Sets the disconnected_node_acknowledged of this ComponentValidationResultEntity. Acknowledges that this node is disconnected to allow for mutable requests to proceed.
[ "Sets", "the", "disconnected_node_acknowledged", "of", "this", "ComponentValidationResultEntity", ".", "Acknowledges", "that", "this", "node", "is", "disconnected", "to", "allow", "for", "mutable", "requests", "to", "proceed", "." ]
def disconnected_node_acknowledged(self, disconnected_node_acknowledged): """ Sets the disconnected_node_acknowledged of this ComponentValidationResultEntity. Acknowledges that this node is disconnected to allow for mutable requests to proceed. :param disconnected_node_acknowledged: The disconnected_node_acknowledged of this ComponentValidationResultEntity. :type: bool """ self._disconnected_node_acknowledged = disconnected_node_acknowledged
[ "def", "disconnected_node_acknowledged", "(", "self", ",", "disconnected_node_acknowledged", ")", ":", "self", ".", "_disconnected_node_acknowledged", "=", "disconnected_node_acknowledged" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/component_validation_result_entity.py#L236-L245
ranaroussi/pystore
ed9beca774312811527c80d199c3cf437623477b
pystore/collection.py
python
Collection.__init__
(self, collection, datastore, engine="fastparquet")
[]
def __init__(self, collection, datastore, engine="fastparquet"): self.engine = engine self.datastore = datastore self.collection = collection self.items = self.list_items() self.snapshots = self.list_snapshots()
[ "def", "__init__", "(", "self", ",", "collection", ",", "datastore", ",", "engine", "=", "\"fastparquet\"", ")", ":", "self", ".", "engine", "=", "engine", "self", ".", "datastore", "=", "datastore", "self", ".", "collection", "=", "collection", "self", "....
https://github.com/ranaroussi/pystore/blob/ed9beca774312811527c80d199c3cf437623477b/pystore/collection.py#L36-L41
JoinMarket-Org/joinmarket-clientserver
8b3d21f226185e31aa10e8e16cdfc719cea4a98e
jmbitcoin/jmbitcoin/secp256k1_ecies.py
python
ecies_encrypt
(message, pubkey)
return base64.b64encode(encrypted + mac)
Take a message in bytes and a secp256k1 public key in compressed byte serialization, and output the ECIES encryption, using magic bytes as defined in this module, sha512 for the key expansion, and AES-CBC for the encryption; these choices are aligned with that used by Electrum.
Take a message in bytes and a secp256k1 public key in compressed byte serialization, and output the ECIES encryption, using magic bytes as defined in this module, sha512 for the key expansion, and AES-CBC for the encryption; these choices are aligned with that used by Electrum.
[ "Take", "a", "message", "in", "bytes", "and", "a", "secp256k1", "public", "key", "in", "compressed", "byte", "serialization", "and", "output", "the", "ECIES", "encryption", "using", "magic", "bytes", "as", "defined", "in", "this", "module", "sha512", "for", ...
def ecies_encrypt(message, pubkey): """ Take a message in bytes and a secp256k1 public key in compressed byte serialization, and output the ECIES encryption, using magic bytes as defined in this module, sha512 for the key expansion, and AES-CBC for the encryption; these choices are aligned with that used by Electrum. """ # create an ephemeral pubkey for this encryption: while True: r = os.urandom(32) # use compressed serialization of the pubkey R: try: R = btc.privkey_to_pubkey(r + b"\x01") break except: # accounts for improbable overflow: continue # note that this is *not* ECDH as in the secp256k1_ecdh module, # since it uses sha512: ecdh_key = btc.multiply(r, pubkey) key = hashlib.sha512(ecdh_key).digest() iv, key_e, key_m = key[0:16], key[16:32], key[32:] ciphertext = aes_encrypt(key_e, message, iv=iv) encrypted = ECIES_MAGIC_BYTES + R + ciphertext mac = hmac.new(key_m, encrypted, hashlib.sha256).digest() return base64.b64encode(encrypted + mac)
[ "def", "ecies_encrypt", "(", "message", ",", "pubkey", ")", ":", "# create an ephemeral pubkey for this encryption:", "while", "True", ":", "r", "=", "os", ".", "urandom", "(", "32", ")", "# use compressed serialization of the pubkey R:", "try", ":", "R", "=", "btc"...
https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/8b3d21f226185e31aa10e8e16cdfc719cea4a98e/jmbitcoin/jmbitcoin/secp256k1_ecies.py#L34-L59
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/commands/user.py
python
WhoamiCommand.run
(self)
[]
def run(self): print( ANSI.red( "WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use " "`huggingface-cli whoami` instead." ) ) token = HfFolder.get_token() if token is None: print("Not logged in") exit() try: user, orgs = whoami(token) print(user) if orgs: print(ANSI.bold("orgs: "), ",".join(orgs)) except HTTPError as e: print(e) print(ANSI.red(e.response.text)) exit(1)
[ "def", "run", "(", "self", ")", ":", "print", "(", "ANSI", ".", "red", "(", "\"WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use \"", "\"`huggingface-cli whoami` instead.\"", ")", ")", "token", "=", "HfFolder", ".", "get_token", "(", "...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/commands/user.py#L179-L198
pynamodb/PynamoDB
5136edde90dade15f9b376edbfcd9f0ea7498171
pynamodb/attributes.py
python
TTLAttribute.deserialize
(self, value)
return datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc)
Deserializes a timestamp (Unix time) as a UTC datetime.
Deserializes a timestamp (Unix time) as a UTC datetime.
[ "Deserializes", "a", "timestamp", "(", "Unix", "time", ")", "as", "a", "UTC", "datetime", "." ]
def deserialize(self, value): """ Deserializes a timestamp (Unix time) as a UTC datetime. """ timestamp = json.loads(value) return datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc)
[ "def", "deserialize", "(", "self", ",", "value", ")", ":", "timestamp", "=", "json", ".", "loads", "(", "value", ")", "return", "datetime", ".", "utcfromtimestamp", "(", "timestamp", ")", ".", "replace", "(", "tzinfo", "=", "timezone", ".", "utc", ")" ]
https://github.com/pynamodb/PynamoDB/blob/5136edde90dade15f9b376edbfcd9f0ea7498171/pynamodb/attributes.py#L687-L692
taomujian/linbing
fe772a58f41e3b046b51a866bdb7e4655abaf51a
python/main.py
python
system_list
(request : VueRequest)
查看系统设置信息的接口 :param: :return str response: 需要返回的数据
查看系统设置信息的接口
[ "查看系统设置信息的接口" ]
async def system_list(request : VueRequest): """ 查看系统设置信息的接口 :param: :return str response: 需要返回的数据 """ try: response = {'code': '', 'message': '', 'data': '', 'total': ''} request = rsa_crypto.decrypt(request.data) request = json.loads(request) token = request['token'] query_str = { 'type': 'token', 'data': token } username_result = mysqldb.username(query_str) if username_result == 'L1001': response['code'] = 'L1001' response['message'] = '系统异常' return response elif username_result == None: response['code'] = 'L1003' response['message'] = '认证失败' return response else: data = { 'proxy': config.get('request', 'proxy'), 'timeout': config.get('request', 'timeout') } data_list = [] data_list.append(data) response['code'] = 'L1000' response['message'] = '请求成功' response['total'] = 1 response['data'] = data_list return response except Exception as e: print(e) response['code'] = 'L1001' response['message'] = '系统异常' return response
[ "async", "def", "system_list", "(", "request", ":", "VueRequest", ")", ":", "try", ":", "response", "=", "{", "'code'", ":", "''", ",", "'message'", ":", "''", ",", "'data'", ":", "''", ",", "'total'", ":", "''", "}", "request", "=", "rsa_crypto", "....
https://github.com/taomujian/linbing/blob/fe772a58f41e3b046b51a866bdb7e4655abaf51a/python/main.py#L2110-L2154
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/xml/sax/xmlreader.py
python
InputSource.getPublicId
(self)
return self.__public_id
Returns the public identifier of this InputSource.
Returns the public identifier of this InputSource.
[ "Returns", "the", "public", "identifier", "of", "this", "InputSource", "." ]
def getPublicId(self): "Returns the public identifier of this InputSource." return self.__public_id
[ "def", "getPublicId", "(", "self", ")", ":", "return", "self", ".", "__public_id" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/xml/sax/xmlreader.py#L214-L216
pyvista/pyvista
012dbb95a9aae406c3cd4cd94fc8c477f871e426
pyvista/core/pointset.py
python
ExplicitStructuredGrid.hide_cells
(self, ind: Sequence[int], inplace=False)
return grid
Hide specific cells. Hides cells by setting the ghost cell array to ``HIDDENCELL``. Parameters ---------- ind : sequence(int) Cell indices to be hidden. A boolean array of the same size as the number of cells also is acceptable. inplace : bool, optional This method is applied to this grid if ``True`` (default) or to a copy otherwise. Returns ------- ExplicitStructuredGrid or None A deep copy of this grid if ``inplace=False`` with the hidden cells, or this grid with the hidden cells if otherwise. Examples -------- >>> from pyvista import examples >>> grid = examples.load_explicit_structured() >>> grid = grid.hide_cells(range(80, 120)) >>> grid.plot(color='w', show_edges=True, show_bounds=True)
Hide specific cells.
[ "Hide", "specific", "cells", "." ]
def hide_cells(self, ind: Sequence[int], inplace=False) -> 'ExplicitStructuredGrid': """Hide specific cells. Hides cells by setting the ghost cell array to ``HIDDENCELL``. Parameters ---------- ind : sequence(int) Cell indices to be hidden. A boolean array of the same size as the number of cells also is acceptable. inplace : bool, optional This method is applied to this grid if ``True`` (default) or to a copy otherwise. Returns ------- ExplicitStructuredGrid or None A deep copy of this grid if ``inplace=False`` with the hidden cells, or this grid with the hidden cells if otherwise. Examples -------- >>> from pyvista import examples >>> grid = examples.load_explicit_structured() >>> grid = grid.hide_cells(range(80, 120)) >>> grid.plot(color='w', show_edges=True, show_bounds=True) """ ind_arr = np.asanyarray(ind) if inplace: array = np.zeros(self.n_cells, dtype=np.uint8) array[ind_arr] = _vtk.vtkDataSetAttributes.HIDDENCELL name = _vtk.vtkDataSetAttributes.GhostArrayName() self.cell_data[name] = array return self grid = self.copy() grid.hide_cells(ind, inplace=True) return grid
[ "def", "hide_cells", "(", "self", ",", "ind", ":", "Sequence", "[", "int", "]", ",", "inplace", "=", "False", ")", "->", "'ExplicitStructuredGrid'", ":", "ind_arr", "=", "np", ".", "asanyarray", "(", "ind", ")", "if", "inplace", ":", "array", "=", "np"...
https://github.com/pyvista/pyvista/blob/012dbb95a9aae406c3cd4cd94fc8c477f871e426/pyvista/core/pointset.py#L2206-L2247
gpodder/mygpo
7a028ad621d05d4ca0d58fd22fb92656c8835e43
mygpo/administration/views.py
python
MergeBase._get_podcasts
(self, request)
return podcasts
[]
def _get_podcasts(self, request): podcasts = [] for n in count(): podcast_url = request.POST.get("feed%d" % n, None) if podcast_url is None: break if not podcast_url: continue p = Podcast.objects.get(urls__url=podcast_url) podcasts.append(p) return podcasts
[ "def", "_get_podcasts", "(", "self", ",", "request", ")", ":", "podcasts", "=", "[", "]", "for", "n", "in", "count", "(", ")", ":", "podcast_url", "=", "request", ".", "POST", ".", "get", "(", "\"feed%d\"", "%", "n", ",", "None", ")", "if", "podcas...
https://github.com/gpodder/mygpo/blob/7a028ad621d05d4ca0d58fd22fb92656c8835e43/mygpo/administration/views.py#L120-L133
xiaomi-automl/FairNAS
fa0d393ee8e1dc7ff290119bbf8df1513eee9a2c
accuracy.py
python
accuracy
(output, target, topk=(1,))
return res
Calc top1 and top5 :param output: logits :param target: groundtruth :param topk: top1 and top5 :return:
Calc top1 and top5 :param output: logits :param target: groundtruth :param topk: top1 and top5 :return:
[ "Calc", "top1", "and", "top5", ":", "param", "output", ":", "logits", ":", "param", "target", ":", "groundtruth", ":", "param", "topk", ":", "top1", "and", "top5", ":", "return", ":" ]
def accuracy(output, target, topk=(1,)): """ Calc top1 and top5 :param output: logits :param target: groundtruth :param topk: top1 and top5 :return: """ maxk = max(topk) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0)) return res
[ "def", "accuracy", "(", "output", ",", "target", ",", "topk", "=", "(", "1", ",", ")", ")", ":", "maxk", "=", "max", "(", "topk", ")", "_", ",", "pred", "=", "output", ".", "topk", "(", "maxk", ",", "1", ",", "True", ",", "True", ")", "pred",...
https://github.com/xiaomi-automl/FairNAS/blob/fa0d393ee8e1dc7ff290119bbf8df1513eee9a2c/accuracy.py#L4-L20
mail-in-a-box/mailinabox
520caf65571c0cdbac88e7fb56c04bacfb112778
management/daemon.py
python
unauthorized
(error)
return auth_service.make_unauthorized_response()
[]
def unauthorized(error): return auth_service.make_unauthorized_response()
[ "def", "unauthorized", "(", "error", ")", ":", "return", "auth_service", ".", "make_unauthorized_response", "(", ")" ]
https://github.com/mail-in-a-box/mailinabox/blob/520caf65571c0cdbac88e7fb56c04bacfb112778/management/daemon.py#L106-L107
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/lib-tk/Tkinter.py
python
getboolean
(s)
return _default_root.tk.getboolean(s)
Convert true and false to integer values 1 and 0.
Convert true and false to integer values 1 and 0.
[ "Convert", "true", "and", "false", "to", "integer", "values", "1", "and", "0", "." ]
def getboolean(s): """Convert true and false to integer values 1 and 0.""" return _default_root.tk.getboolean(s)
[ "def", "getboolean", "(", "s", ")", ":", "return", "_default_root", ".", "tk", ".", "getboolean", "(", "s", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/lib-tk/Tkinter.py#L428-L430
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
libs/requests/packages/urllib3/packages/ordered_dict.py
python
OrderedDict.setdefault
(self, key, default=None)
return default
od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od
od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od
[ "od", ".", "setdefault", "(", "k", "[", "d", "]", ")", "-", ">", "od", ".", "get", "(", "k", "d", ")", "also", "set", "od", "[", "k", "]", "=", "d", "if", "k", "not", "in", "od" ]
def setdefault(self, key, default=None): 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od' if key in self: return self[key] self[key] = default return default
[ "def", "setdefault", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "in", "self", ":", "return", "self", "[", "key", "]", "self", "[", "key", "]", "=", "default", "return", "default" ]
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/requests/packages/urllib3/packages/ordered_dict.py#L190-L195
dit/dit
2853cb13110c5a5b2fa7ad792e238e2177013da2
dit/math/ops.py
python
Operations.add
(self, x, y)
Abstract base class
Abstract base class
[ "Abstract", "base", "class" ]
def add(self, x, y): """ Abstract base class """ raise NotImplementedError
[ "def", "add", "(", "self", ",", "x", ",", "y", ")", ":", "raise", "NotImplementedError" ]
https://github.com/dit/dit/blob/2853cb13110c5a5b2fa7ad792e238e2177013da2/dit/math/ops.py#L251-L253
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/life_event_service/client.py
python
LifeEventServiceClient.parse_common_location_path
(path: str)
return m.groupdict() if m else {}
Parse a location path into its component segments.
Parse a location path into its component segments.
[ "Parse", "a", "location", "path", "into", "its", "component", "segments", "." ]
def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match( r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path ) return m.groupdict() if m else {}
[ "def", "parse_common_location_path", "(", "path", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "m", "=", "re", ".", "match", "(", "r\"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$\"", ",", "path", ")", "return", "m", ".", "groupdi...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/life_event_service/client.py#L228-L233
yuanli2333/Teacher-free-Knowledge-Distillation
ca9f966ea13c06ba0d427d104002d7dd9442779b
ImageNet_train/main.py
python
AverageMeter.__init__
(self, name, fmt=':f')
[]
def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset()
[ "def", "__init__", "(", "self", ",", "name", ",", "fmt", "=", "':f'", ")", ":", "self", ".", "name", "=", "name", "self", ".", "fmt", "=", "fmt", "self", ".", "reset", "(", ")" ]
https://github.com/yuanli2333/Teacher-free-Knowledge-Distillation/blob/ca9f966ea13c06ba0d427d104002d7dd9442779b/ImageNet_train/main.py#L447-L450
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
mysite/base/view_helpers.py
python
clear_static_cache
(path)
Atomically destroy the static file cache for a certain path.
Atomically destroy the static file cache for a certain path.
[ "Atomically", "destroy", "the", "static", "file", "cache", "for", "a", "certain", "path", "." ]
def clear_static_cache(path): '''Atomically destroy the static file cache for a certain path.''' # Steps: fully_qualified_path = os.path.join(django.conf.settings.WEB_ROOT, path) # 0. Create new temp dir try: new_temp_path = tempfile.mkdtemp( dir=django.conf.settings.WEB_ROOT + '/') except OSError, e: if e.errno == 28: # No space left on device # Aww shucks, we can't do it the smart way. # We just set new_temp_path to the old path, then # and let shutil remove it. shutil.rmtree(fully_qualified_path) return # We are done. # 1. Atomically move the path that we want to expire into the new directory try: os.rename(fully_qualified_path, os.path.join(new_temp_path, 'old')) except OSError, e: if e.errno == 2: # No such file or directory # Well, that means the cache is already clear. # We still have to nuke new_temp_path though! pass else: raise # 2. shutil.rmtree() the new path shutil.rmtree(new_temp_path)
[ "def", "clear_static_cache", "(", "path", ")", ":", "# Steps:", "fully_qualified_path", "=", "os", ".", "path", ".", "join", "(", "django", ".", "conf", ".", "settings", ".", "WEB_ROOT", ",", "path", ")", "# 0. Create new temp dir", "try", ":", "new_temp_path"...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/mysite/base/view_helpers.py#L95-L124
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/files.py
python
PaperCreateError.is_invalid_file_extension
(self)
return self._tag == 'invalid_file_extension'
Check if the union tag is ``invalid_file_extension``. :rtype: bool
Check if the union tag is ``invalid_file_extension``.
[ "Check", "if", "the", "union", "tag", "is", "invalid_file_extension", "." ]
def is_invalid_file_extension(self): """ Check if the union tag is ``invalid_file_extension``. :rtype: bool """ return self._tag == 'invalid_file_extension'
[ "def", "is_invalid_file_extension", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'invalid_file_extension'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/files.py#L5284-L5290
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/inspect.py
python
BoundArguments.kwargs
(self)
return kwargs
[]
def kwargs(self): kwargs = {} kwargs_started = False for param_name, param in self._signature.parameters.items(): if not kwargs_started: if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): kwargs_started = True else: if param_name not in self.arguments: kwargs_started = True continue if not kwargs_started: continue try: arg = self.arguments[param_name] except KeyError: pass else: if param.kind == _VAR_KEYWORD: # **kwargs kwargs.update(arg) else: # plain keyword argument kwargs[param_name] = arg return kwargs
[ "def", "kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "}", "kwargs_started", "=", "False", "for", "param_name", ",", "param", "in", "self", ".", "_signature", ".", "parameters", ".", "items", "(", ")", ":", "if", "not", "kwargs_started", ":", "if...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/inspect.py#L2804-L2831
aleju/imgaug
0101108d4fed06bc5056c4a03e2bcb0216dac326
imgaug/augmenters/geometric.py
python
WithPolarWarping._warp_heatmaps_
(cls, heatmaps)
return cls._warp_maps_(heatmaps, "arr_0to1", False)
[]
def _warp_heatmaps_(cls, heatmaps): return cls._warp_maps_(heatmaps, "arr_0to1", False)
[ "def", "_warp_heatmaps_", "(", "cls", ",", "heatmaps", ")", ":", "return", "cls", ".", "_warp_maps_", "(", "heatmaps", ",", "\"arr_0to1\"", ",", "False", ")" ]
https://github.com/aleju/imgaug/blob/0101108d4fed06bc5056c4a03e2bcb0216dac326/imgaug/augmenters/geometric.py#L5468-L5469
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
clr_node_info2
(*args)
return _idaapi.clr_node_info2(*args)
clr_node_info2(gid, node, flags)
clr_node_info2(gid, node, flags)
[ "clr_node_info2", "(", "gid", "node", "flags", ")" ]
def clr_node_info2(*args): """ clr_node_info2(gid, node, flags) """ return _idaapi.clr_node_info2(*args)
[ "def", "clr_node_info2", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "clr_node_info2", "(", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L50881-L50885
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/network/conf.py
python
add_transport
(module_name)
[]
def add_transport(module_name): try: confmodule = importlib.import_module( 'network.transports.{}.conf'.format(module_name)) if not confmodule: logging.warning('Import failed: %s', module_name) return if not hasattr(confmodule, 'TransportConf'): logging.warning('TransportConf is not present in %s', module_name) return t = confmodule.TransportConf if t.name is None: t.name = module_name transports[t.name] = t logging.debug('Transport loaded: %s', t.name) except Exception, e: logging.exception('Transport disabled: %s: %s', module_name, e)
[ "def", "add_transport", "(", "module_name", ")", ":", "try", ":", "confmodule", "=", "importlib", ".", "import_module", "(", "'network.transports.{}.conf'", ".", "format", "(", "module_name", ")", ")", "if", "not", "confmodule", ":", "logging", ".", "warning", ...
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/network/conf.py#L21-L42
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/jinja2/loaders.py
python
BaseLoader.load
(self, environment, name, globals=None)
return environment.template_class.from_code(environment, code, globals, uptodate)
Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly.
Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly.
[ "Loads", "a", "template", ".", "This", "method", "looks", "up", "the", "template", "in", "the", "cache", "or", "loads", "one", "by", "calling", ":", "meth", ":", "get_source", ".", "Subclasses", "should", "not", "override", "this", "method", "as", "loaders...
def load(self, environment, name, globals=None): """Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly. """ code = None if globals is None: globals = {} # first we try to get the source for this template together # with the filename and the uptodate function. source, filename, uptodate = self.get_source(environment, name) # try to load the code from the bytecode cache if there is a # bytecode cache configured. bcc = environment.bytecode_cache if bcc is not None: bucket = bcc.get_bucket(environment, name, filename, source) code = bucket.code # if we don't have code so far (not cached, no longer up to # date) etc. we compile the template if code is None: code = environment.compile(source, name, filename) # if the bytecode cache is available and the bucket doesn't # have a code so far, we give the bucket the new code and put # it back to the bytecode cache. if bcc is not None and bucket.code is None: bucket.code = code bcc.set_bucket(bucket) return environment.template_class.from_code(environment, code, globals, uptodate)
[ "def", "load", "(", "self", ",", "environment", ",", "name", ",", "globals", "=", "None", ")", ":", "code", "=", "None", "if", "globals", "is", "None", ":", "globals", "=", "{", "}", "# first we try to get the source for this template together", "# with the file...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/jinja2/loaders.py#L100-L135
barseghyanartur/django-fobi
a998feae007d7fe3637429a80e42952ec7cda79f
examples/simple/override_select_model_object_plugin/forms.py
python
SelectModelObjectInputForm.__init__
(self, *args, **kwargs)
In order to avoid static calls to `get_registered_models`.
In order to avoid static calls to `get_registered_models`.
[ "In", "order", "to", "avoid", "static", "calls", "to", "get_registered_models", "." ]
def __init__(self, *args, **kwargs): """In order to avoid static calls to `get_registered_models`.""" super(SelectModelObjectInputForm, self).__init__(*args, **kwargs) self.fields['model'].choices = get_registered_models( ignore=IGNORED_MODELS )
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "SelectModelObjectInputForm", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "fields", "[", "'model'",...
https://github.com/barseghyanartur/django-fobi/blob/a998feae007d7fe3637429a80e42952ec7cda79f/examples/simple/override_select_model_object_plugin/forms.py#L70-L75
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/scripts/nextpenbox.py
python
reaver
()
[]
def reaver(): print """ Reaver has been designed to be a robust and practical attack against Wi-Fi Protected Setup WPS registrar PINs in order to recover WPA/WPA2 passphrases. It has been tested against a wide variety of access points and WPS implementations 1 to accept / 0 to decline """ creaver = raw_input("y / n :") if creaver in yes: os.system("apt-get -y install build-essential libpcap-dev sqlite3 libsqlite3-dev aircrack-ng pixiewps") os.system("git clone https://github.com/t6x/reaver-wps-fork-t6x.git") os.system("cd reaver-wps-fork-t6x/src/ & ./configure") os.system("cd reaver-wps-fork-t6x/src/ & make") elif creaver in no: clearScr(); wire() elif creaver == "": menu() else: menu()
[ "def", "reaver", "(", ")", ":", "print", "\"\"\"\n Reaver has been designed to be a robust and practical attack against Wi-Fi Protected Setup\n WPS registrar PINs in order to recover WPA/WPA2 passphrases. It has been tested against a\n wide variety of access points and WPS implementations...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/nextpenbox.py#L576-L594
arviz-devs/arviz
17b1a48b577ba9776a31e7e57a8a8af63e826901
arviz/data/io_pystan.py
python
PyStanConverter.predictions_to_xarray
(self)
return ( dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=self.dims), dict_to_dataset(data_warmup, library=self.pystan, coords=self.coords, dims=self.dims), )
Convert predictions samples to xarray.
Convert predictions samples to xarray.
[ "Convert", "predictions", "samples", "to", "xarray", "." ]
def predictions_to_xarray(self): """Convert predictions samples to xarray.""" posterior = self.posterior predictions = self.predictions data, data_warmup = get_draws( posterior, variables=predictions, warmup=self.save_warmup, dtypes=self.dtypes ) return ( dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=self.dims), dict_to_dataset(data_warmup, library=self.pystan, coords=self.coords, dims=self.dims), )
[ "def", "predictions_to_xarray", "(", "self", ")", ":", "posterior", "=", "self", ".", "posterior", "predictions", "=", "self", ".", "predictions", "data", ",", "data_warmup", "=", "get_draws", "(", "posterior", ",", "variables", "=", "predictions", ",", "warmu...
https://github.com/arviz-devs/arviz/blob/17b1a48b577ba9776a31e7e57a8a8af63e826901/arviz/data/io_pystan.py#L196-L206
athena-team/athena
e704884ec6a3a947769d892aa267578038e49ecb
athena/data/text_featurizer.py
python
TextFeaturizer.decode
(self, sequences)
return self.model.decode(sequences)
conver a list of ids to a sentence
conver a list of ids to a sentence
[ "conver", "a", "list", "of", "ids", "to", "a", "sentence" ]
def decode(self, sequences): """conver a list of ids to a sentence """ return self.model.decode(sequences)
[ "def", "decode", "(", "self", ",", "sequences", ")", ":", "return", "self", ".", "model", ".", "decode", "(", "sequences", ")" ]
https://github.com/athena-team/athena/blob/e704884ec6a3a947769d892aa267578038e49ecb/athena/data/text_featurizer.py#L224-L227
MegviiDetection/video_analyst
f4d1bccb1c698961fed3cb70808f1177fab13bdd
videoanalyst/data/builder.py
python
get_config
(task_list: List)
return cfg_dict
r""" Get available component list config Returns ------- Dict[str, CfgNode] config with list of available components
r""" Get available component list config
[ "r", "Get", "available", "component", "list", "config" ]
def get_config(task_list: List) -> Dict[str, CfgNode]: r""" Get available component list config Returns ------- Dict[str, CfgNode] config with list of available components """ cfg_dict = {task: CfgNode() for task in task_list} for task in cfg_dict: cfg = cfg_dict[task] cfg["exp_name"] = "" cfg["exp_save"] = "snapshots" cfg["num_epochs"] = 1 cfg["minibatch"] = 32 cfg["num_workers"] = 4 cfg["nr_image_per_epoch"] = 150000 cfg["pin_memory"] = True cfg["datapipeline"] = datapipeline_builder.get_config(task_list)[task] cfg["sampler"] = sampler_builder.get_config(task_list)[task] cfg["transformer"] = transformer_builder.get_config(task_list)[task] cfg["target"] = target_builder.get_config(task_list)[task] return cfg_dict
[ "def", "get_config", "(", "task_list", ":", "List", ")", "->", "Dict", "[", "str", ",", "CfgNode", "]", ":", "cfg_dict", "=", "{", "task", ":", "CfgNode", "(", ")", "for", "task", "in", "task_list", "}", "for", "task", "in", "cfg_dict", ":", "cfg", ...
https://github.com/MegviiDetection/video_analyst/blob/f4d1bccb1c698961fed3cb70808f1177fab13bdd/videoanalyst/data/builder.py#L75-L100
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/pkg_resources/_vendor/six.py
python
_import_module
(name)
return sys.modules[name]
Import module, returning the module after the last dot.
Import module, returning the module after the last dot.
[ "Import", "module", "returning", "the", "module", "after", "the", "last", "dot", "." ]
def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
[ "def", "_import_module", "(", "name", ")", ":", "__import__", "(", "name", ")", "return", "sys", ".", "modules", "[", "name", "]" ]
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pkg_resources/_vendor/six.py#L80-L83
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Demo/newmetaclasses/Eiffel.py
python
EiffelMethodWrapper.__call__
(self, *args, **kwargs)
return self._descr.callmethod(self._inst, args, kwargs)
[]
def __call__(self, *args, **kwargs): return self._descr.callmethod(self._inst, args, kwargs)
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_descr", ".", "callmethod", "(", "self", ".", "_inst", ",", "args", ",", "kwargs", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Demo/newmetaclasses/Eiffel.py#L58-L59
serverdensity/sd-agent
66f0031b6be369c28e69414eb6172b5685a5110e
sdagent.py
python
Application.log_request
(self, handler)
Override the tornado logging method. If everything goes well, log level is DEBUG. Otherwise it's WARNING or ERROR depending on the response code.
Override the tornado logging method. If everything goes well, log level is DEBUG. Otherwise it's WARNING or ERROR depending on the response code.
[ "Override", "the", "tornado", "logging", "method", ".", "If", "everything", "goes", "well", "log", "level", "is", "DEBUG", ".", "Otherwise", "it", "s", "WARNING", "or", "ERROR", "depending", "on", "the", "response", "code", "." ]
def log_request(self, handler): """ Override the tornado logging method. If everything goes well, log level is DEBUG. Otherwise it's WARNING or ERROR depending on the response code. """ if handler.get_status() < 400: log_method = log.debug elif handler.get_status() < 500: log_method = log.warning else: log_method = log.error request_time = 1000.0 * handler.request.request_time() log_method( u"%d %s %.2fms", handler.get_status(), handler._request_summary(), request_time )
[ "def", "log_request", "(", "self", ",", "handler", ")", ":", "if", "handler", ".", "get_status", "(", ")", "<", "400", ":", "log_method", "=", "log", ".", "debug", "elif", "handler", ".", "get_status", "(", ")", "<", "500", ":", "log_method", "=", "l...
https://github.com/serverdensity/sd-agent/blob/66f0031b6be369c28e69414eb6172b5685a5110e/sdagent.py#L458-L474
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/ext/makerbot_pyserial/serialjava.py
python
JavaSerial.getCTS
(self)
Read terminal status line: Clear To Send
Read terminal status line: Clear To Send
[ "Read", "terminal", "status", "line", ":", "Clear", "To", "Send" ]
def getCTS(self): """Read terminal status line: Clear To Send""" if not self.sPort: raise portNotOpenError self.sPort.isCTS()
[ "def", "getCTS", "(", "self", ")", ":", "if", "not", "self", ".", "sPort", ":", "raise", "portNotOpenError", "self", ".", "sPort", ".", "isCTS", "(", ")" ]
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/ext/makerbot_pyserial/serialjava.py#L207-L210
DamnWidget/anaconda
a9998fb362320f907d5ccbc6fcf5b62baca677c0
anaconda_lib/linting/pycodestyle.py
python
StandardReport.init_file
(self, filename, lines, expected, line_offset)
return super(StandardReport, self).init_file( filename, lines, expected, line_offset)
Signal a new file.
Signal a new file.
[ "Signal", "a", "new", "file", "." ]
def init_file(self, filename, lines, expected, line_offset): """Signal a new file.""" self._deferred_print = [] return super(StandardReport, self).init_file( filename, lines, expected, line_offset)
[ "def", "init_file", "(", "self", ",", "filename", ",", "lines", ",", "expected", ",", "line_offset", ")", ":", "self", ".", "_deferred_print", "=", "[", "]", "return", "super", "(", "StandardReport", ",", "self", ")", ".", "init_file", "(", "filename", "...
https://github.com/DamnWidget/anaconda/blob/a9998fb362320f907d5ccbc6fcf5b62baca677c0/anaconda_lib/linting/pycodestyle.py#L2292-L2296
pyFFTW/pyFFTW
86df872d4d489ad79b97f93a9512e9f63a0258e0
pyfftw/_version.py
python
git_pieces_from_vcs
(tag_prefix, root, verbose, run_command=run_command)
return pieces
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
Get version from 'git describe' in the root of the source tree.
[ "Get", "version", "from", "git", "describe", "in", "the", "root", "of", "the", "source", "tree", "." ]
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces
[ "def", "git_pieces_from_vcs", "(", "tag_prefix", ",", "root", ",", "verbose", ",", "run_command", "=", "run_command", ")", ":", "GITS", "=", "[", "\"git\"", "]", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "GITS", "=", "[", "\"git.cmd\"", ",", ...
https://github.com/pyFFTW/pyFFTW/blob/86df872d4d489ad79b97f93a9512e9f63a0258e0/pyfftw/_version.py#L217-L305
huawei-noah/vega
d9f13deede7f2b584e4b1d32ffdb833856129989
vega/trainer/callbacks/callback_list.py
python
CallbackList.before_epoch
(self, epoch, logs=None)
Call before_epoch of the managed callbacks.
Call before_epoch of the managed callbacks.
[ "Call", "before_epoch", "of", "the", "managed", "callbacks", "." ]
def before_epoch(self, epoch, logs=None): """Call before_epoch of the managed callbacks.""" logs = logs or {} for callback in self.callbacks: callback.before_epoch(epoch, logs)
[ "def", "before_epoch", "(", "self", ",", "epoch", ",", "logs", "=", "None", ")", ":", "logs", "=", "logs", "or", "{", "}", "for", "callback", "in", "self", ".", "callbacks", ":", "callback", ".", "before_epoch", "(", "epoch", ",", "logs", ")" ]
https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/trainer/callbacks/callback_list.py#L161-L165
vrnetlab/vrnetlab
28c144042efbf59ae500da6eac3f983ea346ffda
sros/docker/launch.py
python
SROS_cp.gen_mgmt
(self)
return res
Generate mgmt interface(s) We override the default function since we want a NIC to the vFPC
Generate mgmt interface(s)
[ "Generate", "mgmt", "interface", "(", "s", ")" ]
def gen_mgmt(self): """ Generate mgmt interface(s) We override the default function since we want a NIC to the vFPC """ # call parent function to generate first mgmt interface (e1000) res = super(SROS_cp, self).gen_mgmt() # add virtio NIC for internal control plane interface to vFPC res.append("-device") res.append("e1000,netdev=vcp-int,mac=%s" % vrnetlab.gen_mac(1)) res.append("-netdev") res.append("tap,ifname=vcp-int,id=vcp-int,script=no,downscript=no") return res
[ "def", "gen_mgmt", "(", "self", ")", ":", "# call parent function to generate first mgmt interface (e1000)", "res", "=", "super", "(", "SROS_cp", ",", "self", ")", ".", "gen_mgmt", "(", ")", "# add virtio NIC for internal control plane interface to vFPC", "res", ".", "app...
https://github.com/vrnetlab/vrnetlab/blob/28c144042efbf59ae500da6eac3f983ea346ffda/sros/docker/launch.py#L220-L232
aio-libs/aiohttp-cors
1627c08638e4c83022abffacab753b09896d1b9a
aiohttp_cors/resource_options.py
python
_is_proper_sequence
(seq)
return (isinstance(seq, collections.abc.Sequence) and not isinstance(seq, str))
Returns is seq is sequence and not string.
Returns is seq is sequence and not string.
[ "Returns", "is", "seq", "is", "sequence", "and", "not", "string", "." ]
def _is_proper_sequence(seq): """Returns is seq is sequence and not string.""" return (isinstance(seq, collections.abc.Sequence) and not isinstance(seq, str))
[ "def", "_is_proper_sequence", "(", "seq", ")", ":", "return", "(", "isinstance", "(", "seq", ",", "collections", ".", "abc", ".", "Sequence", ")", "and", "not", "isinstance", "(", "seq", ",", "str", ")", ")" ]
https://github.com/aio-libs/aiohttp-cors/blob/1627c08638e4c83022abffacab753b09896d1b9a/aiohttp_cors/resource_options.py#L25-L28
nodesign/weio
1d67d705a5c36a2e825ad13feab910b0aca9a2e8
openWrt/files/usr/lib/python2.7/site-packages/tornado/httputil.py
python
HTTPHeaders.parse_line
(self, line)
Updates the dictionary with a single header line. >>> h = HTTPHeaders() >>> h.parse_line("Content-Type: text/html") >>> h.get('content-type') 'text/html'
Updates the dictionary with a single header line.
[ "Updates", "the", "dictionary", "with", "a", "single", "header", "line", "." ]
def parse_line(self, line): """Updates the dictionary with a single header line. >>> h = HTTPHeaders() >>> h.parse_line("Content-Type: text/html") >>> h.get('content-type') 'text/html' """ if line[0].isspace(): # continuation of a multi-line header new_part = ' ' + line.lstrip() self._as_list[self._last_key][-1] += new_part dict.__setitem__(self, self._last_key, self[self._last_key] + new_part) else: name, value = line.split(":", 1) self.add(name, value.strip())
[ "def", "parse_line", "(", "self", ",", "line", ")", ":", "if", "line", "[", "0", "]", ".", "isspace", "(", ")", ":", "# continuation of a multi-line header", "new_part", "=", "' '", "+", "line", ".", "lstrip", "(", ")", "self", ".", "_as_list", "[", "s...
https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/openWrt/files/usr/lib/python2.7/site-packages/tornado/httputil.py#L118-L134
msracver/Deformable-ConvNets
6aeda878a95bcb55eadffbe125804e730574de8d
lib/utils/mask_coco2voc.py
python
segToMask
( S, h, w )
return M
Convert polygon segmentation to binary mask. :param S (float array) : polygon segmentation mask :param h (int) : target mask height :param w (int) : target mask width :return: M (bool 2D array) : binary mask
Convert polygon segmentation to binary mask. :param S (float array) : polygon segmentation mask :param h (int) : target mask height :param w (int) : target mask width :return: M (bool 2D array) : binary mask
[ "Convert", "polygon", "segmentation", "to", "binary", "mask", ".", ":", "param", "S", "(", "float", "array", ")", ":", "polygon", "segmentation", "mask", ":", "param", "h", "(", "int", ")", ":", "target", "mask", "height", ":", "param", "w", "(", "int"...
def segToMask( S, h, w ): """ Convert polygon segmentation to binary mask. :param S (float array) : polygon segmentation mask :param h (int) : target mask height :param w (int) : target mask width :return: M (bool 2D array) : binary mask """ M = np.zeros((h,w), dtype=np.bool) for s in S: N = len(s) rr, cc = polygon(np.array(s[1:N:2]).clip(max=h-1), \ np.array(s[0:N:2]).clip(max=w-1)) # (y, x) M[rr, cc] = 1 return M
[ "def", "segToMask", "(", "S", ",", "h", ",", "w", ")", ":", "M", "=", "np", ".", "zeros", "(", "(", "h", ",", "w", ")", ",", "dtype", "=", "np", ".", "bool", ")", "for", "s", "in", "S", ":", "N", "=", "len", "(", "s", ")", "rr", ",", ...
https://github.com/msracver/Deformable-ConvNets/blob/6aeda878a95bcb55eadffbe125804e730574de8d/lib/utils/mask_coco2voc.py#L11-L25
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cdn/v20180606/models.py
python
AdvanceConfig.__init__
(self)
r""" :param Name: 高级配置名称。 注意:此字段可能返回 null,表示取不到有效值。 :type Name: str :param Value: 是否支持高级配置, on:支持 off:不支持 注意:此字段可能返回 null,表示取不到有效值。 :type Value: str
r""" :param Name: 高级配置名称。 注意:此字段可能返回 null,表示取不到有效值。 :type Name: str :param Value: 是否支持高级配置, on:支持 off:不支持 注意:此字段可能返回 null,表示取不到有效值。 :type Value: str
[ "r", ":", "param", "Name", ":", "高级配置名称。", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "Name", ":", "str", ":", "param", "Value", ":", "是否支持高级配置,", "on:支持", "off:不支持", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "Value", ":", "str" ]
def __init__(self): r""" :param Name: 高级配置名称。 注意:此字段可能返回 null,表示取不到有效值。 :type Name: str :param Value: 是否支持高级配置, on:支持 off:不支持 注意:此字段可能返回 null,表示取不到有效值。 :type Value: str """ self.Name = None self.Value = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Name", "=", "None", "self", ".", "Value", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cdn/v20180606/models.py#L409-L421
google/closure-linter
c09c885b4e4fec386ff81cebeb8c66c2b0643d49
closure_linter/checker.py
python
JavaScriptStyleChecker.Check
(self, start_token, limited_doc_checks=False, is_html=False, stop_token=None)
Checks a token stream for lint warnings/errors. Adds a separate pass for computing dependency information based on goog.require and goog.provide statements prior to the main linting pass. Args: start_token: The first token in the token stream. limited_doc_checks: Whether to perform limited checks. is_html: Whether this token stream is HTML. stop_token: If given, checks should stop at this token.
Checks a token stream for lint warnings/errors.
[ "Checks", "a", "token", "stream", "for", "lint", "warnings", "/", "errors", "." ]
def Check(self, start_token, limited_doc_checks=False, is_html=False, stop_token=None): """Checks a token stream for lint warnings/errors. Adds a separate pass for computing dependency information based on goog.require and goog.provide statements prior to the main linting pass. Args: start_token: The first token in the token stream. limited_doc_checks: Whether to perform limited checks. is_html: Whether this token stream is HTML. stop_token: If given, checks should stop at this token. """ self._lint_rules.Initialize(self, limited_doc_checks, is_html) self._state_tracker.DocFlagPass(start_token, self._error_handler) if self._alias_pass: self._alias_pass.Process(start_token) # To maximize the amount of errors that get reported before a parse error # is displayed, don't run the dependency pass if a parse error exists. if self._namespaces_info: self._namespaces_info.Reset() self._ExecutePass(start_token, self._DependencyPass, stop_token) self._ExecutePass(start_token, self._LintPass, stop_token) # If we have a stop_token, we didn't end up reading the whole file and, # thus, don't call Finalize to do end-of-file checks. if not stop_token: self._lint_rules.Finalize(self._state_tracker)
[ "def", "Check", "(", "self", ",", "start_token", ",", "limited_doc_checks", "=", "False", ",", "is_html", "=", "False", ",", "stop_token", "=", "None", ")", ":", "self", ".", "_lint_rules", ".", "Initialize", "(", "self", ",", "limited_doc_checks", ",", "i...
https://github.com/google/closure-linter/blob/c09c885b4e4fec386ff81cebeb8c66c2b0643d49/closure_linter/checker.py#L66-L97
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/voiper/sulley/impacket/ImpactPacket.py
python
TCPOption.get_ts_echo
(self)
[]
def get_ts_echo(self): if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP: raise ImpactPacketException, "Can only retrieve timestamp from TCPOPT_TIMESTAMP option" self.get_long(6)
[ "def", "get_ts_echo", "(", "self", ")", ":", "if", "self", ".", "get_kind", "(", ")", "!=", "TCPOption", ".", "TCPOPT_TIMESTAMP", ":", "raise", "ImpactPacketException", ",", "\"Can only retrieve timestamp from TCPOPT_TIMESTAMP option\"", "self", ".", "get_long", "(", ...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/voiper/sulley/impacket/ImpactPacket.py#L1391-L1394
secdev/scapy
65089071da1acf54622df0b4fa7fc7673d47d3cd
scapy/arch/windows/__init__.py
python
NetworkInterface_Win.modulation
(self)
return self._npcap_get("modu")
Get the 802.11 modulation of the interface. Only available with Npcap.
Get the 802.11 modulation of the interface. Only available with Npcap.
[ "Get", "the", "802", ".", "11", "modulation", "of", "the", "interface", ".", "Only", "available", "with", "Npcap", "." ]
def modulation(self): """Get the 802.11 modulation of the interface. Only available with Npcap.""" # According to https://nmap.org/npcap/guide/npcap-devguide.html#npcap-feature-dot11 # noqa: E501 self._check_npcap_requirement() return self._npcap_get("modu")
[ "def", "modulation", "(", "self", ")", ":", "# According to https://nmap.org/npcap/guide/npcap-devguide.html#npcap-feature-dot11 # noqa: E501", "self", ".", "_check_npcap_requirement", "(", ")", "return", "self", ".", "_npcap_get", "(", "\"modu\"", ")" ]
https://github.com/secdev/scapy/blob/65089071da1acf54622df0b4fa7fc7673d47d3cd/scapy/arch/windows/__init__.py#L465-L470
tahoe-lafs/tahoe-lafs
766a53b5208c03c45ca0a98e97eee76870276aa1
src/allmydata/storage/mutable_schema.py
python
schema_from_header
(header)
return None
Find the schema object that corresponds to a certain version number.
Find the schema object that corresponds to a certain version number.
[ "Find", "the", "schema", "object", "that", "corresponds", "to", "a", "certain", "version", "number", "." ]
def schema_from_header(header): # (int) -> Optional[type] """ Find the schema object that corresponds to a certain version number. """ for schema in ALL_SCHEMAS: if schema.magic_matches(header): return schema return None
[ "def", "schema_from_header", "(", "header", ")", ":", "# (int) -> Optional[type]", "for", "schema", "in", "ALL_SCHEMAS", ":", "if", "schema", ".", "magic_matches", "(", "header", ")", ":", "return", "schema", "return", "None" ]
https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/storage/mutable_schema.py#L136-L144
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_flax_objects.py
python
FlaxElectraForMultipleChoice.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): requires_backends(self, ["flax"])
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "self", ",", "[", "\"flax\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_flax_objects.py#L883-L884
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
included_dependencies/urllib3/_collections.py
python
HTTPHeaderDict.itermerged
(self)
Iterate over all headers, merging duplicate ones together.
Iterate over all headers, merging duplicate ones together.
[ "Iterate", "over", "all", "headers", "merging", "duplicate", "ones", "together", "." ]
def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = self._container[key.lower()] yield val[0], ", ".join(val[1:])
[ "def", "itermerged", "(", "self", ")", ":", "for", "key", "in", "self", ":", "val", "=", "self", ".", "_container", "[", "key", ".", "lower", "(", ")", "]", "yield", "val", "[", "0", "]", ",", "\", \"", ".", "join", "(", "val", "[", "1", ":", ...
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/urllib3/_collections.py#L302-L306
terrencepreilly/darglint
abc26b768cd7135d848223ba53f68323593c33d5
darglint/integrity_checker.py
python
IntegrityChecker._check_raises
(self, docstring, function)
[]
def _check_raises(self, docstring, function): # type: (BaseDocstring, FunctionDescription) -> None if function.is_abstract: return exception_types = docstring.get_items(Sections.RAISES_SECTION) docstring_raises = set(exception_types or []) actual_raises = function.raises ignore_raise = set(self.config.ignore_raise) missing_in_doc = actual_raises - docstring_raises - ignore_raise missing_in_doc = self._remove_ignored( docstring, missing_in_doc, MissingRaiseError, ) for missing in missing_in_doc: self.errors.append( MissingRaiseError(function.function, missing) ) # TODO: Disable by default. # # Should we even include this? It seems like the user # would know if this function would be likely to raise # a certain exception from underlying calls. # missing_in_function = docstring_raises - actual_raises missing_in_function = self._remove_ignored( docstring, missing_in_function, ExcessRaiseError, ) # Remove AssertionError if there is an assert. if 'AssertionError' in missing_in_function: if function.raises_assert: missing_in_function.remove('AssertionError') default_line_numbers = docstring.get_line_numbers( 'raises-section', ) for missing in missing_in_function: line_numbers = docstring.get_line_numbers_for_value( 'raises-section', missing, ) or default_line_numbers self.errors.append( ExcessRaiseError( function.function, missing, line_numbers=line_numbers, ) )
[ "def", "_check_raises", "(", "self", ",", "docstring", ",", "function", ")", ":", "# type: (BaseDocstring, FunctionDescription) -> None", "if", "function", ".", "is_abstract", ":", "return", "exception_types", "=", "docstring", ".", "get_items", "(", "Sections", ".", ...
https://github.com/terrencepreilly/darglint/blob/abc26b768cd7135d848223ba53f68323593c33d5/darglint/integrity_checker.py#L450-L504
vlachoudis/bCNC
67126b4894dabf6579baf47af8d0f9b7de35e6e3
bCNC/Pendant.py
python
Pendant.do_GET
(self)
Respond to a GET request.
Respond to a GET request.
[ "Respond", "to", "a", "GET", "request", "." ]
def do_GET(self): """Respond to a GET request.""" if "?" in self.path: page,arg = self.path.split("?",1) arg = dict(urlparse.parse_qsl(arg)) else: page = self.path arg = None # print self.path,type(self.path) # print page # print arg if page == "/send": if arg is None: return for key,value in arg.items(): if key=="gcode": for line in value.split('\n'): httpd.app.queue.put(line+"\n") elif key=="cmd": httpd.app.pendant.put(urlparse.unquote(value)) #send empty response so browser does not generate errors self.do_HEAD(200, "text/text", cl=len("")) self.wfile.write("".encode()) elif page == "/state": tmp = {} for name in ["controller", "state", "pins", "color", "msg", "wx", "wy", "wz", "wa", "wb", "wc", "mx", "my", "mz", "ma", "mb", "mc", "G", "OvFeed", "OvRapid", "OvSpindle"]: tmp[name] = CNC.vars[name] contentToSend = json.dumps(tmp) self.do_HEAD(200, content="text/text", cl=len(contentToSend)) self.wfile.write(contentToSend.encode()) elif page == "/config": snd = {} snd["rpmmax"] = httpd.app.get("CNC","spindlemax") contentToSend = json.dumps(snd) self.do_HEAD(200, content="text/text", cl=len(contentToSend)) self.wfile.write(contentToSend.encode()) elif page == "/icon": if arg is None: return filename = os.path.join(iconpath, arg["name"]+".gif") self.do_HEAD(200, content="image/gif", cl=os.path.getsize(filename)) try: f = open(filename,"rb") self.wfile.write(f.read()) f.close() except: pass elif page == "/canvas": if not Image: return with tempfile.NamedTemporaryFile(suffix='.ps') as tmp: httpd.app.canvas.postscript( file=tmp.name, colormode='color', ) tmp.flush() try: with tempfile.NamedTemporaryFile(suffix='.gif') as out: Image.open(tmp.name).save(out.name, 'GIF') out.flush() out.seek(0) self.do_HEAD(200, content="image/gif", cl=os.path.getsize(tmp.name)) self.wfile.write(out.read()) except: filename = os.path.join(iconpath, "warn.gif") self.do_HEAD(200, content="image/gif", cl=os.path.getsize(filename)) try: f = open(filename,"rb") self.wfile.write(f.read()) f.close() except: pass elif page == "/camera": if not Camera.hasOpenCV(): return if Pendant.camera is None: Pendant.camera = Camera.Camera("webcam") Pendant.camera.start() if Pendant.camera.read(): Pendant.camera.save("camera.jpg") #cv.imwrite("camera.jpg",img) self.do_HEAD(200, content="image/jpeg", cl=os.path.getsize("camera.jpg")) try: f = open("camera.jpg","rb") self.wfile.write(f.read()) f.close() except: pass else: self.mainPage(page[1:])
[ "def", "do_GET", "(", "self", ")", ":", "if", "\"?\"", "in", "self", ".", "path", ":", "page", ",", "arg", "=", "self", ".", "path", ".", "split", "(", "\"?\"", ",", "1", ")", "arg", "=", "dict", "(", "urlparse", ".", "parse_qsl", "(", "arg", "...
https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/Pendant.py#L72-L165
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_csr.py
python
Yedit.process_edits
(edits, yamlfile)
return {'changed': len(results) > 0, 'results': results}
run through a list of edits and process them one-by-one
run through a list of edits and process them one-by-one
[ "run", "through", "a", "list", "of", "edits", "and", "process", "them", "one", "-", "by", "-", "one" ]
def process_edits(edits, yamlfile): '''run through a list of edits and process them one-by-one''' results = [] for edit in edits: value = Yedit.parse_value(edit['value'], edit.get('value_type', '')) if edit.get('action') == 'update': # pylint: disable=line-too-long curr_value = Yedit.get_curr_value( Yedit.parse_value(edit.get('curr_value')), edit.get('curr_value_format')) rval = yamlfile.update(edit['key'], value, edit.get('index'), curr_value) elif edit.get('action') == 'append': rval = yamlfile.append(edit['key'], value) else: rval = yamlfile.put(edit['key'], value) if rval[0]: results.append({'key': edit['key'], 'edit': rval[1]}) return {'changed': len(results) > 0, 'results': results}
[ "def", "process_edits", "(", "edits", ",", "yamlfile", ")", ":", "results", "=", "[", "]", "for", "edit", "in", "edits", ":", "value", "=", "Yedit", ".", "parse_value", "(", "edit", "[", "'value'", "]", ",", "edit", ".", "get", "(", "'value_type'", "...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_csr.py#L710-L735
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/analyses/cfg/cfg_utils.py
python
SCCPlaceholder.__hash__
(self)
return hash('scc_placeholder_%d' % self.scc_id)
[]
def __hash__(self): return hash('scc_placeholder_%d' % self.scc_id)
[ "def", "__hash__", "(", "self", ")", ":", "return", "hash", "(", "'scc_placeholder_%d'", "%", "self", ".", "scc_id", ")" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/analyses/cfg/cfg_utils.py#L14-L15
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/mobile_device_constant_service/transports/grpc.py
python
MobileDeviceConstantServiceGrpcTransport.__init__
( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, )
Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason.
Instantiate the transport.
[ "Instantiate", "the", "transport", "." ]
def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ self._ssl_channel_credentials = ssl_channel_credentials if channel: # Sanity check: Ensure that channel and credentials are not both # provided. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None elif api_mtls_endpoint: warnings.warn( "api_mtls_endpoint and client_cert_source are deprecated", DeprecationWarning, ) host = ( api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443" ) if credentials is None: credentials, _ = google.auth.default( scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id ) # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._ssl_channel_credentials = ssl_credentials else: host = host if ":" in host else host + ":443" if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, ssl_credentials=ssl_channel_credentials, scopes=self.AUTH_SCOPES, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._stubs = {} # type: Dict[str, Callable] # Run the base constructor. super().__init__( host=host, credentials=credentials, client_info=client_info, )
[ "def", "__init__", "(", "self", ",", "*", ",", "host", ":", "str", "=", "\"googleads.googleapis.com\"", ",", "credentials", ":", "ga_credentials", ".", "Credentials", "=", "None", ",", "credentials_file", ":", "str", "=", "None", ",", "scopes", ":", "Sequenc...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/mobile_device_constant_service/transports/grpc.py#L49-L177
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
tensorflow_dl_models/research/learning_to_remember_rare_events/memory.py
python
LSHMemory.make_update_op
(self, upd_idxs, upd_keys, upd_vals, batch_size, use_recent_idx, intended_output)
return tf.group(*update_ops)
Function that creates all the update ops.
Function that creates all the update ops.
[ "Function", "that", "creates", "all", "the", "update", "ops", "." ]
def make_update_op(self, upd_idxs, upd_keys, upd_vals, batch_size, use_recent_idx, intended_output): """Function that creates all the update ops.""" base_update_op = super(LSHMemory, self).make_update_op( upd_idxs, upd_keys, upd_vals, batch_size, use_recent_idx, intended_output) # compute hash slots to be updated hash_slot_idxs = self.get_hash_slots(upd_keys) # make updates update_ops = [] with tf.control_dependencies([base_update_op]): for i, slot_idxs in enumerate(hash_slot_idxs): # for each slot, choose which entry to replace entry_idx = tf.random_uniform([batch_size], maxval=self.num_per_hash_slot, dtype=tf.int32) entry_mul = 1 - tf.one_hot(entry_idx, self.num_per_hash_slot, dtype=tf.int32) entry_add = (tf.expand_dims(upd_idxs, 1) * tf.one_hot(entry_idx, self.num_per_hash_slot, dtype=tf.int32)) mul_op = tf.scatter_mul(self.hash_slots[i], slot_idxs, entry_mul) with tf.control_dependencies([mul_op]): add_op = tf.scatter_add(self.hash_slots[i], slot_idxs, entry_add) update_ops.append(add_op) return tf.group(*update_ops)
[ "def", "make_update_op", "(", "self", ",", "upd_idxs", ",", "upd_keys", ",", "upd_vals", ",", "batch_size", ",", "use_recent_idx", ",", "intended_output", ")", ":", "base_update_op", "=", "super", "(", "LSHMemory", ",", "self", ")", ".", "make_update_op", "(",...
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/tensorflow_dl_models/research/learning_to_remember_rare_events/memory.py#L358-L387
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/adax/__init__.py
python
async_migrate_entry
(hass: HomeAssistant, config_entry: ConfigEntry)
return True
Migrate old entry.
Migrate old entry.
[ "Migrate", "old", "entry", "." ]
async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Migrate old entry.""" # convert title and unique_id to string if config_entry.version == 1: if isinstance(config_entry.unique_id, int): hass.config_entries.async_update_entry( config_entry, unique_id=str(config_entry.unique_id), title=str(config_entry.title), ) return True
[ "async", "def", "async_migrate_entry", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "ConfigEntry", ")", "->", "bool", ":", "# convert title and unique_id to string", "if", "config_entry", ".", "version", "==", "1", ":", "if", "isinstance", "(", "co...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/adax/__init__.py#L22-L34
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
Languages/IronPython/IronPython/Lib/site.py
python
aliasmbcs
()
On Windows, some default encodings are not provided by Python, while they are always available as "mbcs" in each locale. Make them usable by aliasing to "mbcs" in such a case.
On Windows, some default encodings are not provided by Python, while they are always available as "mbcs" in each locale. Make them usable by aliasing to "mbcs" in such a case.
[ "On", "Windows", "some", "default", "encodings", "are", "not", "provided", "by", "Python", "while", "they", "are", "always", "available", "as", "mbcs", "in", "each", "locale", ".", "Make", "them", "usable", "by", "aliasing", "to", "mbcs", "in", "such", "a"...
def aliasmbcs(): """On Windows, some default encodings are not provided by Python, while they are always available as "mbcs" in each locale. Make them usable by aliasing to "mbcs" in such a case.""" if sys.platform == 'win32': import locale, codecs enc = locale.getdefaultlocale()[1] if enc.startswith('cp'): # "cp***" ? try: codecs.lookup(enc) except LookupError: import encodings encodings._cache[enc] = encodings._unknown encodings.aliases.aliases[enc] = 'mbcs'
[ "def", "aliasmbcs", "(", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "import", "locale", ",", "codecs", "enc", "=", "locale", ".", "getdefaultlocale", "(", ")", "[", "1", "]", "if", "enc", ".", "startswith", "(", "'cp'", ")", ":", ...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/Languages/IronPython/IronPython/Lib/site.py#L476-L489
jobovy/galpy
8e6a230bbe24ce16938db10053f92eb17fe4bb52
galpy/df/sphericaldf.py
python
sphericaldf.__call__
(self,*args,**kwargs)
return self._call_internal(E,L,Lz)
NAME: __call__ PURPOSE: return the DF INPUT: Either: a) (E,L,Lz): tuple of E and (optionally) L and (optionally) Lz. Each may be Quantity b) R,vR,vT,z,vz,phi: c) Orbit instance: orbit.Orbit instance and if specific time then orbit.Orbit(t) OUTPUT: Value of DF HISTORY: 2020-07-22 - Written - Lane (UofT)
NAME:
[ "NAME", ":" ]
def __call__(self,*args,**kwargs): """ NAME: __call__ PURPOSE: return the DF INPUT: Either: a) (E,L,Lz): tuple of E and (optionally) L and (optionally) Lz. Each may be Quantity b) R,vR,vT,z,vz,phi: c) Orbit instance: orbit.Orbit instance and if specific time then orbit.Orbit(t) OUTPUT: Value of DF HISTORY: 2020-07-22 - Written - Lane (UofT) """ # Get E,L,Lz if len(args) == 1: if not isinstance(args[0],Orbit): # Assume tuple (E,L,Lz) E,L,Lz= (args[0]+(None,None))[:3] else: # Orbit E= args[0].E(pot=self._pot,use_physical=False) L= numpy.sqrt(numpy.sum(args[0].L(use_physical=False)**2.)) Lz= args[0].Lz(use_physical=False) E= numpy.atleast_1d(conversion.parse_energy(E,vo=self._vo)) L= numpy.atleast_1d(conversion.parse_angmom(L,ro=self._ro, vo=self._vo)) Lz= numpy.atleast_1d(conversion.parse_angmom(Lz,ro=self._vo, vo=self._vo)) else: # Assume R,vR,vT,z,vz,(phi) R,vR,vT,z,vz, phi= (args+(None,))[:6] R= conversion.parse_length(R,ro=self._ro) vR= conversion.parse_velocity(vR,vo=self._vo) vT= conversion.parse_velocity(vT,vo=self._vo) z= conversion.parse_length(z,ro=self._ro) vz= conversion.parse_velocity(vz,vo=self._vo) vtotSq= vR**2.+vT**2.+vz**2. E= numpy.atleast_1d(0.5*vtotSq+_evaluatePotentials(self._pot,R,z)) Lz= numpy.atleast_1d(R*vT) r= numpy.sqrt(R**2.+z**2.) vrad= (R*vR+z*vz)/r L= numpy.atleast_1d(numpy.sqrt(vtotSq-vrad**2.)*r) return self._call_internal(E,L,Lz)
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Get E,L,Lz", "if", "len", "(", "args", ")", "==", "1", ":", "if", "not", "isinstance", "(", "args", "[", "0", "]", ",", "Orbit", ")", ":", "# Assume tuple (E,L,...
https://github.com/jobovy/galpy/blob/8e6a230bbe24ce16938db10053f92eb17fe4bb52/galpy/df/sphericaldf.py#L94-L151
hubblestack/hubble
763142474edcecdec5fd25591dc29c3536e8f969
hubblestack/modules/upstart_service.py
python
_default_runlevel
()
return runlevel
Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot
Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot
[ "Try", "to", "figure", "out", "the", "default", "runlevel", ".", "It", "is", "kept", "in", "/", "etc", "/", "init", "/", "rc", "-", "sysinit", ".", "conf", "but", "can", "be", "overridden", "with", "entries", "in", "/", "etc", "/", "inittab", "or", ...
def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with hubblestack.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = hubblestack.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with hubblestack.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = hubblestack.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with hubblestack.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = hubblestack.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel
[ "def", "_default_runlevel", "(", ")", ":", "# Try to get the \"main\" default. If this fails, throw up our", "# hands and just guess \"2\", because things are horribly broken", "try", ":", "with", "hubblestack", ".", "utils", ".", "files", ".", "fopen", "(", "'/etc/init/rc-sysin...
https://github.com/hubblestack/hubble/blob/763142474edcecdec5fd25591dc29c3536e8f969/hubblestack/modules/upstart_service.py#L306-L348
eandersson/amqpstorm
7f57cf1291c8b3817527c10aae317aa1702654bc
amqpstorm/management/api.py
python
ManagementApi.healthchecks
(self)
return self._healthchecks
RabbitMQ Healthchecks. e.g. :: client.healthchecks.get() :rtype: amqpstorm.management.healthchecks.Healthchecks
RabbitMQ Healthchecks.
[ "RabbitMQ", "Healthchecks", "." ]
def healthchecks(self): """RabbitMQ Healthchecks. e.g. :: client.healthchecks.get() :rtype: amqpstorm.management.healthchecks.Healthchecks """ return self._healthchecks
[ "def", "healthchecks", "(", "self", ")", ":", "return", "self", ".", "_healthchecks" ]
https://github.com/eandersson/amqpstorm/blob/7f57cf1291c8b3817527c10aae317aa1702654bc/amqpstorm/management/api.py#L123-L133
twschiller/open-synthesis
4c765c1105eea31a039dde25e53ee8d3612dd206
openach/templatetags/board_extras.py
python
is_private
(board)
return board.permissions.read_board in [ AuthLevels.board_creator.key, AuthLevels.collaborators.key, ]
Return True iff the board is only readable by the owner and/or collaborators.
Return True iff the board is only readable by the owner and/or collaborators.
[ "Return", "True", "iff", "the", "board", "is", "only", "readable", "by", "the", "owner", "and", "/", "or", "collaborators", "." ]
def is_private(board): """Return True iff the board is only readable by the owner and/or collaborators.""" return board.permissions.read_board in [ AuthLevels.board_creator.key, AuthLevels.collaborators.key, ]
[ "def", "is_private", "(", "board", ")", ":", "return", "board", ".", "permissions", ".", "read_board", "in", "[", "AuthLevels", ".", "board_creator", ".", "key", ",", "AuthLevels", ".", "collaborators", ".", "key", ",", "]" ]
https://github.com/twschiller/open-synthesis/blob/4c765c1105eea31a039dde25e53ee8d3612dd206/openach/templatetags/board_extras.py#L234-L239
crossbario/autobahn-python
fa9f2da0c5005574e63456a3a04f00e405744014
autobahn/wamp/message.py
python
Challenge.marshal
(self)
return [Challenge.MESSAGE_TYPE, self.method, self.extra]
Marshal this object into a raw message for subsequent serialization to bytes. :returns: The serialized raw message. :rtype: list
Marshal this object into a raw message for subsequent serialization to bytes.
[ "Marshal", "this", "object", "into", "a", "raw", "message", "for", "subsequent", "serialization", "to", "bytes", "." ]
def marshal(self): """ Marshal this object into a raw message for subsequent serialization to bytes. :returns: The serialized raw message. :rtype: list """ return [Challenge.MESSAGE_TYPE, self.method, self.extra]
[ "def", "marshal", "(", "self", ")", ":", "return", "[", "Challenge", ".", "MESSAGE_TYPE", ",", "self", ".", "method", ",", "self", ".", "extra", "]" ]
https://github.com/crossbario/autobahn-python/blob/fa9f2da0c5005574e63456a3a04f00e405744014/autobahn/wamp/message.py#L1174-L1181
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/indexes/multi.py
python
MultiIndex.levshape
(self)
return tuple(len(x) for x in self.levels)
A tuple with the length of each level.
A tuple with the length of each level.
[ "A", "tuple", "with", "the", "length", "of", "each", "level", "." ]
def levshape(self): """A tuple with the length of each level.""" return tuple(len(x) for x in self.levels)
[ "def", "levshape", "(", "self", ")", ":", "return", "tuple", "(", "len", "(", "x", ")", "for", "x", "in", "self", ".", "levels", ")" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/indexes/multi.py#L1729-L1731
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/psutil/__init__.py
python
Process.__str__
(self)
return "%s.%s(%s)" % ( self.__class__.__module__, self.__class__.__name__, ", ".join(["%s=%r" % (k, v) for k, v in info.items()]))
[]
def __str__(self): try: info = collections.OrderedDict() except AttributeError: info = {} # Python 2.6 info["pid"] = self.pid try: info["name"] = self.name() if self._create_time: info['started'] = _pprint_secs(self._create_time) except ZombieProcess: info["status"] = "zombie" except NoSuchProcess: info["status"] = "terminated" except AccessDenied: pass return "%s.%s(%s)" % ( self.__class__.__module__, self.__class__.__name__, ", ".join(["%s=%r" % (k, v) for k, v in info.items()]))
[ "def", "__str__", "(", "self", ")", ":", "try", ":", "info", "=", "collections", ".", "OrderedDict", "(", ")", "except", "AttributeError", ":", "info", "=", "{", "}", "# Python 2.6", "info", "[", "\"pid\"", "]", "=", "self", ".", "pid", "try", ":", "...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/psutil/__init__.py#L495-L514
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
8.Scrapy爬虫框架/portia_examle/lib/python2.7/site.py
python
addbuilddir
()
Append ./build/lib.<platform> in case we're running in the build dir (especially for Guido :-)
Append ./build/lib.<platform> in case we're running in the build dir (especially for Guido :-)
[ "Append", ".", "/", "build", "/", "lib", ".", "<platform", ">", "in", "case", "we", "re", "running", "in", "the", "build", "dir", "(", "especially", "for", "Guido", ":", "-", ")" ]
def addbuilddir(): """Append ./build/lib.<platform> in case we're running in the build dir (especially for Guido :-)""" from distutils.util import get_platform s = "build/lib.%s-%.3s" % (get_platform(), sys.version) if hasattr(sys, 'gettotalrefcount'): s += '-pydebug' s = os.path.join(os.path.dirname(sys.path[-1]), s) sys.path.append(s)
[ "def", "addbuilddir", "(", ")", ":", "from", "distutils", ".", "util", "import", "get_platform", "s", "=", "\"build/lib.%s-%.3s\"", "%", "(", "get_platform", "(", ")", ",", "sys", ".", "version", ")", "if", "hasattr", "(", "sys", ",", "'gettotalrefcount'", ...
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/8.Scrapy爬虫框架/portia_examle/lib/python2.7/site.py#L133-L141
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/telnetlib.py
python
Telnet.process_rawq
(self)
Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence.
Transfer from raw queue to cooked queue.
[ "Transfer", "from", "raw", "queue", "to", "cooked", "queue", "." ]
def process_rawq(self): """Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence. """ buf = [b'', b''] try: while self.rawq: c = self.rawq_getchar() if not self.iacseq: if c == theNULL: continue if c == b"\021": continue if c != IAC: buf[self.sb] = buf[self.sb] + c continue else: self.iacseq += c elif len(self.iacseq) == 1: # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]' if c in (DO, DONT, WILL, WONT): self.iacseq += c continue self.iacseq = b'' if c == IAC: buf[self.sb] = buf[self.sb] + c else: if c == SB: # SB ... SE start. self.sb = 1 self.sbdataq = b'' elif c == SE: self.sb = 0 self.sbdataq = self.sbdataq + buf[1] buf[1] = b'' if self.option_callback: # Callback is supposed to look into # the sbdataq self.option_callback(self.sock, c, NOOPT) else: # We can't offer automatic processing of # suboptions. Alas, we should not get any # unless we did a WILL/DO before. self.msg('IAC %d not recognized' % ord(c)) elif len(self.iacseq) == 2: cmd = self.iacseq[1:2] self.iacseq = b'' opt = c if cmd in (DO, DONT): self.msg('IAC %s %d', cmd == DO and 'DO' or 'DONT', ord(opt)) if self.option_callback: self.option_callback(self.sock, cmd, opt) else: self.sock.sendall(IAC + WONT + opt) elif cmd in (WILL, WONT): self.msg('IAC %s %d', cmd == WILL and 'WILL' or 'WONT', ord(opt)) if self.option_callback: self.option_callback(self.sock, cmd, opt) else: self.sock.sendall(IAC + DONT + opt) except EOFError: # raised by self.rawq_getchar() self.iacseq = b'' # Reset on EOF self.sb = 0 self.cookedq = self.cookedq + buf[0] self.sbdataq = self.sbdataq + buf[1]
[ "def", "process_rawq", "(", "self", ")", ":", "buf", "=", "[", "b''", ",", "b''", "]", "try", ":", "while", "self", ".", "rawq", ":", "c", "=", "self", ".", "rawq_getchar", "(", ")", "if", "not", "self", ".", "iacseq", ":", "if", "c", "==", "th...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/telnetlib.py#L424-L493
GoogleCloudPlatform/professional-services
0c707aa97437f3d154035ef8548109b7882f71da
examples/cloudml-collaborative-filtering/preprocessing/run_preprocess.py
python
get_pipeline_options
(args, config)
return pipeline_options
Returns pipeline options based on args and confs.
Returns pipeline options based on args and confs.
[ "Returns", "pipeline", "options", "based", "on", "args", "and", "confs", "." ]
def get_pipeline_options(args, config): """Returns pipeline options based on args and confs.""" options = {"project": str(config.get("project"))} if args.cloud: if not args.job_name: raise ValueError("Job name must be specified for cloud runs.") if not args.job_dir: raise ValueError("Job dir must be specified for cloud runs.") options.update({ "job_name": args.job_name, "max_num_workers": int(config.get("max_num_workers")), "setup_file": os.path.abspath(get_relative_path( "../setup.py")), "staging_location": os.path.join(args.job_dir, "staging"), "temp_location": os.path.join(args.job_dir, "tmp"), "region": config.get("region"), }) pipeline_options = beam.pipeline.PipelineOptions(flags=[], **options) return pipeline_options
[ "def", "get_pipeline_options", "(", "args", ",", "config", ")", ":", "options", "=", "{", "\"project\"", ":", "str", "(", "config", ".", "get", "(", "\"project\"", ")", ")", "}", "if", "args", ".", "cloud", ":", "if", "not", "args", ".", "job_name", ...
https://github.com/GoogleCloudPlatform/professional-services/blob/0c707aa97437f3d154035ef8548109b7882f71da/examples/cloudml-collaborative-filtering/preprocessing/run_preprocess.py#L95-L113
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/random.py
python
Random.gauss
(self, mu, sigma)
return mu + z*sigma
Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls.
Gaussian distribution.
[ "Gaussian", "distribution", "." ]
def gauss(self, mu, sigma): """Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls. """ # When x and y are two variables from [0, 1), uniformly # distributed, then # # cos(2*pi*x)*sqrt(-2*log(1-y)) # sin(2*pi*x)*sqrt(-2*log(1-y)) # # are two *independent* variables with normal distribution # (mu = 0, sigma = 1). # (Lambert Meertens) # (corrected version; bug discovered by Mike Miller, fixed by LM) # Multithreading note: When two threads call this function # simultaneously, it is possible that they will receive the # same return value. The window is very small though. To # avoid this, you have to use a lock around all calls. (I # didn't want to slow this down in the serial case by using a # lock here.) random = self.random z = self.gauss_next self.gauss_next = None if z is None: x2pi = random() * TWOPI g2rad = _sqrt(-2.0 * _log(1.0 - random())) z = _cos(x2pi) * g2rad self.gauss_next = _sin(x2pi) * g2rad return mu + z*sigma
[ "def", "gauss", "(", "self", ",", "mu", ",", "sigma", ")", ":", "# When x and y are two variables from [0, 1), uniformly", "# distributed, then", "#", "# cos(2*pi*x)*sqrt(-2*log(1-y))", "# sin(2*pi*x)*sqrt(-2*log(1-y))", "#", "# are two *independent* variables with normal distr...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/random.py#L562-L599
guillaumegenthial/im2latex
8e25d7ec2097e2c6515bbb5b41e8f16b79339967
model/components/beam_search_decoder_cell.py
python
BeamSearchDecoderCell.finalize
(self, final_outputs, final_state)
return DecoderOutput(logits=final_outputs.logits, ids=final_outputs.ids)
Args: final_outputs: structure of tensors of shape [time dimension, batch_size, beam_size, d] final_state: instance of BeamSearchDecoderOutput Returns: [time, batch, beam, ...] structure of Tensor
Args: final_outputs: structure of tensors of shape [time dimension, batch_size, beam_size, d] final_state: instance of BeamSearchDecoderOutput
[ "Args", ":", "final_outputs", ":", "structure", "of", "tensors", "of", "shape", "[", "time", "dimension", "batch_size", "beam_size", "d", "]", "final_state", ":", "instance", "of", "BeamSearchDecoderOutput" ]
def finalize(self, final_outputs, final_state): """ Args: final_outputs: structure of tensors of shape [time dimension, batch_size, beam_size, d] final_state: instance of BeamSearchDecoderOutput Returns: [time, batch, beam, ...] structure of Tensor """ # reverse the time dimension maximum_iterations = tf.shape(final_outputs.ids)[0] final_outputs = nest.map_structure(lambda t: tf.reverse(t, axis=[0]), final_outputs) # initial states def create_ta(d): return tf.TensorArray(dtype=d, size=maximum_iterations) initial_time = tf.constant(0, dtype=tf.int32) initial_outputs_ta = nest.map_structure(create_ta, self.final_output_dtype) initial_parents = tf.tile( tf.expand_dims(tf.range(self._beam_size), axis=0), multiples=[self._batch_size, 1]) def condition(time, outputs_ta, parents): return tf.less(time, maximum_iterations) # beam search decoding cell def body(time, outputs_ta, parents): # get ids, logits and parents predicted at time step by decoder input_t = nest.map_structure(lambda t: t[time], final_outputs) # extract the entries corresponding to parents new_state = nest.map_structure( lambda t: gather_helper(t, parents, self._batch_size, self._beam_size), input_t) # create new output new_output = DecoderOutput(logits=new_state.logits, ids=new_state.ids) # write beam ids outputs_ta = nest.map_structure(lambda ta, out: ta.write(time, out), outputs_ta, new_output) return (time + 1), outputs_ta, parents res = tf.while_loop( condition, body, loop_vars=[initial_time, initial_outputs_ta, initial_parents], back_prop=False) # unfold and stack the structure from the nested tas final_outputs = nest.map_structure(lambda ta: ta.stack(), res[1]) # reverse time step final_outputs = nest.map_structure(lambda t: tf.reverse(t, axis=[0]), final_outputs) return DecoderOutput(logits=final_outputs.logits, ids=final_outputs.ids)
[ "def", "finalize", "(", "self", ",", "final_outputs", ",", "final_state", ")", ":", "# reverse the time dimension", "maximum_iterations", "=", "tf", ".", "shape", "(", "final_outputs", ".", "ids", ")", "[", "0", "]", "final_outputs", "=", "nest", ".", "map_str...
https://github.com/guillaumegenthial/im2latex/blob/8e25d7ec2097e2c6515bbb5b41e8f16b79339967/model/components/beam_search_decoder_cell.py#L199-L262
Ekultek/Dagon
f065d7bbd7598f9a8c43bd12ba6b528cfef7377e
thirdparty/des/pydes.py
python
des.encrypt
(self, data, pad=None, padmode=None)
return self.crypt(data, des.ENCRYPT)
encrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes.
encrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes.
[ "encrypt", "(", "data", "[", "pad", "]", "[", "padmode", "]", ")", "-", ">", "bytes", "data", ":", "Bytes", "to", "be", "encrypted", "pad", ":", "Optional", "argument", "for", "encryption", "padding", ".", "Must", "only", "be", "one", "byte", "padmode"...
def encrypt(self, data, pad=None, padmode=None): """encrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes. """ data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) data = self._padData(data, pad, padmode) return self.crypt(data, des.ENCRYPT)
[ "def", "encrypt", "(", "self", ",", "data", ",", "pad", "=", "None", ",", "padmode", "=", "None", ")", ":", "data", "=", "self", ".", "_guardAgainstUnicode", "(", "data", ")", "if", "pad", "is", "not", "None", ":", "pad", "=", "self", ".", "_guardA...
https://github.com/Ekultek/Dagon/blob/f065d7bbd7598f9a8c43bd12ba6b528cfef7377e/thirdparty/des/pydes.py#L627-L642
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/np/ufunc/deviceufunc.py
python
_gen_src_for_indexing
(aref, adims, atype)
return "{aref}[{sliced}]".format(aref=aref, sliced=_gen_src_index(adims, atype))
[]
def _gen_src_for_indexing(aref, adims, atype): return "{aref}[{sliced}]".format(aref=aref, sliced=_gen_src_index(adims, atype))
[ "def", "_gen_src_for_indexing", "(", "aref", ",", "adims", ",", "atype", ")", ":", "return", "\"{aref}[{sliced}]\"", ".", "format", "(", "aref", "=", "aref", ",", "sliced", "=", "_gen_src_index", "(", "adims", ",", "atype", ")", ")" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/np/ufunc/deviceufunc.py#L522-L524
Rapptz/RoboDanny
1fb95d76d1b7685e2e2ff950e11cddfc96efbfec
cogs/utils/paginator.py
python
RoboPages.numbered_page
(self, button: discord.ui.Button, interaction: discord.Interaction)
lets you type a page number to go to
lets you type a page number to go to
[ "lets", "you", "type", "a", "page", "number", "to", "go", "to" ]
async def numbered_page(self, button: discord.ui.Button, interaction: discord.Interaction): """lets you type a page number to go to""" if self.input_lock.locked(): await interaction.response.send_message('Already waiting for your response...', ephemeral=True) return if self.message is None: return async with self.input_lock: channel = self.message.channel author_id = interaction.user and interaction.user.id await interaction.response.send_message('What page do you want to go to?', ephemeral=True) def message_check(m): return m.author.id == author_id and channel == m.channel and m.content.isdigit() try: msg = await self.ctx.bot.wait_for('message', check=message_check, timeout=30.0) except asyncio.TimeoutError: await interaction.followup.send('Took too long.', ephemeral=True) await asyncio.sleep(5) else: page = int(msg.content) await msg.delete() await self.show_checked_page(interaction, page - 1)
[ "async", "def", "numbered_page", "(", "self", ",", "button", ":", "discord", ".", "ui", ".", "Button", ",", "interaction", ":", "discord", ".", "Interaction", ")", ":", "if", "self", ".", "input_lock", ".", "locked", "(", ")", ":", "await", "interaction"...
https://github.com/Rapptz/RoboDanny/blob/1fb95d76d1b7685e2e2ff950e11cddfc96efbfec/cogs/utils/paginator.py#L166-L191
Scille/umongo
d83c17a8c6d40e8318d913eb25454c7c56e23c3f
umongo/data_proxy.py
python
data_proxy_factory
(basename, schema, strict=True)
return data_proxy_cls
Generate a DataProxy from the given schema. This way all generic informations (like schema and fields lookups) are kept inside the DataProxy class and it instances are just flyweights.
Generate a DataProxy from the given schema.
[ "Generate", "a", "DataProxy", "from", "the", "given", "schema", "." ]
def data_proxy_factory(basename, schema, strict=True): """ Generate a DataProxy from the given schema. This way all generic informations (like schema and fields lookups) are kept inside the DataProxy class and it instances are just flyweights. """ cls_name = "%sDataProxy" % basename nmspc = { '__slots__': (), 'schema': schema, '_fields': schema.fields, '_fields_from_mongo_key': {v.attribute or k: v for k, v in schema.fields.items()} } data_proxy_cls = type(cls_name, (BaseDataProxy if strict else BaseNonStrictDataProxy, ), nmspc) return data_proxy_cls
[ "def", "data_proxy_factory", "(", "basename", ",", "schema", ",", "strict", "=", "True", ")", ":", "cls_name", "=", "\"%sDataProxy\"", "%", "basename", "nmspc", "=", "{", "'__slots__'", ":", "(", ")", ",", "'schema'", ":", "schema", ",", "'_fields'", ":", ...
https://github.com/Scille/umongo/blob/d83c17a8c6d40e8318d913eb25454c7c56e23c3f/umongo/data_proxy.py#L225-L243
JPaulMora/Pyrit
f0f1913c645b445dd391fb047b812b5ba511782c
cpyrit/storage.py
python
FSEssidStore.__setitem__
(self, (essid, key), results)
Store a iterable of (password,PMK)-tuples under the given ESSID and key.
Store a iterable of (password,PMK)-tuples under the given ESSID and key.
[ "Store", "a", "iterable", "of", "(", "password", "PMK", ")", "-", "tuples", "under", "the", "given", "ESSID", "and", "key", "." ]
def __setitem__(self, (essid, key), results): """Store a iterable of (password,PMK)-tuples under the given ESSID and key. """ if essid not in self.essids: raise KeyError("ESSID not in store.") filename = os.path.join(self.essids[essid][0], key) + '.pyr' with open(filename, 'wb') as f: f.write(PYR2_Buffer.pack(essid, results)) self.essids[essid][1][key] = filename
[ "def", "__setitem__", "(", "self", ",", "(", "essid", ",", "key", ")", ",", "results", ")", ":", "if", "essid", "not", "in", "self", ".", "essids", ":", "raise", "KeyError", "(", "\"ESSID not in store.\"", ")", "filename", "=", "os", ".", "path", ".", ...
https://github.com/JPaulMora/Pyrit/blob/f0f1913c645b445dd391fb047b812b5ba511782c/cpyrit/storage.py#L436-L445
mlflow/mlflow
364aca7daf0fcee3ec407ae0b1b16d9cb3085081
mlflow/sklearn/utils.py
python
_create_child_runs_for_parameter_search
( autologging_client, cv_estimator, parent_run, max_tuning_runs, child_tags=None )
Creates a collection of child runs for a parameter search training session. Runs are reconstructed from the `cv_results_` attribute of the specified trained parameter search estimator - `cv_estimator`, which provides relevant performance metrics for each point in the parameter search space. One child run is created for each point in the parameter search space. For additional information, see `https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html`_. :param autologging_client: An instance of `MlflowAutologgingQueueingClient` used for efficiently logging run data to MLflow Tracking. :param cv_estimator: The trained parameter search estimator for which to create child runs. :param parent_run: A py:class:`mlflow.entities.Run` object referring to the parent parameter search run for which child runs should be created. :param child_tags: An optional dictionary of MLflow tag keys and values to log for each child run.
Creates a collection of child runs for a parameter search training session. Runs are reconstructed from the `cv_results_` attribute of the specified trained parameter search estimator - `cv_estimator`, which provides relevant performance metrics for each point in the parameter search space. One child run is created for each point in the parameter search space. For additional information, see `https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html`_.
[ "Creates", "a", "collection", "of", "child", "runs", "for", "a", "parameter", "search", "training", "session", ".", "Runs", "are", "reconstructed", "from", "the", "cv_results_", "attribute", "of", "the", "specified", "trained", "parameter", "search", "estimator", ...
def _create_child_runs_for_parameter_search( autologging_client, cv_estimator, parent_run, max_tuning_runs, child_tags=None ): """ Creates a collection of child runs for a parameter search training session. Runs are reconstructed from the `cv_results_` attribute of the specified trained parameter search estimator - `cv_estimator`, which provides relevant performance metrics for each point in the parameter search space. One child run is created for each point in the parameter search space. For additional information, see `https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html`_. :param autologging_client: An instance of `MlflowAutologgingQueueingClient` used for efficiently logging run data to MLflow Tracking. :param cv_estimator: The trained parameter search estimator for which to create child runs. :param parent_run: A py:class:`mlflow.entities.Run` object referring to the parent parameter search run for which child runs should be created. :param child_tags: An optional dictionary of MLflow tag keys and values to log for each child run. """ import pandas as pd def first_custom_rank_column(df): column_names = df.columns.values for col_name in column_names: if "rank_test_" in col_name: return col_name # Use the start time of the parent parameter search run as a rough estimate for the # start time of child runs, since we cannot precisely determine when each point # in the parameter search space was explored child_run_start_time = parent_run.info.start_time child_run_end_time = int(time.time() * 1000) seed_estimator = cv_estimator.estimator # In the unlikely case that a seed of a parameter search estimator is, # itself, a parameter search estimator, we should avoid logging the untuned # parameters of the seeds's seed estimator should_log_params_deeply = not _is_parameter_search_estimator(seed_estimator) # Each row of `cv_results_` only provides parameters that vary across # the user-specified parameter grid. In order to log the complete set # of parameters for each child run, we fetch the parameters defined by # the seed estimator and update them with parameter subset specified # in the result row base_params = seed_estimator.get_params(deep=should_log_params_deeply) cv_results_df = pd.DataFrame.from_dict(cv_estimator.cv_results_) if max_tuning_runs is None: cv_results_best_n_df = cv_results_df else: rank_column_name = "rank_test_score" if rank_column_name not in cv_results_df.columns.values: rank_column_name = first_custom_rank_column(cv_results_df) warnings.warn( "Top {} child runs will be created based on ordering in {} column.".format( max_tuning_runs, rank_column_name, ) + " You can choose not to limit the number of child runs created by" + " setting `max_tuning_runs=None`." ) cv_results_best_n_df = cv_results_df.nsmallest(max_tuning_runs, rank_column_name) # Log how many child runs will be created vs omitted. _log_child_runs_info(max_tuning_runs, len(cv_results_df)) for _, result_row in cv_results_best_n_df.iterrows(): tags_to_log = dict(child_tags) if child_tags else {} tags_to_log.update({MLFLOW_PARENT_RUN_ID: parent_run.info.run_id}) tags_to_log.update(_get_estimator_info_tags(seed_estimator)) pending_child_run_id = autologging_client.create_run( experiment_id=parent_run.info.experiment_id, start_time=child_run_start_time, tags=tags_to_log, ) params_to_log = dict(base_params) params_to_log.update(result_row.get("params", {})) autologging_client.log_params(run_id=pending_child_run_id, params=params_to_log) # Parameters values are recorded twice in the set of search `cv_results_`: # once within a `params` column with dictionary values and once within # a separate dataframe column that is created for each parameter. To prevent # duplication of parameters, we log the consolidated values from the parameter # dictionary column and filter out the other parameter-specific columns with # names of the form `param_{param_name}`. Additionally, `cv_results_` produces # metrics for each training split, which is fairly verbose; accordingly, we filter # out per-split metrics in favor of aggregate metrics (mean, std, etc.) excluded_metric_prefixes = ["param", "split"] metrics_to_log = { key: value for key, value in result_row.iteritems() if not any([key.startswith(prefix) for prefix in excluded_metric_prefixes]) and isinstance(value, Number) } autologging_client.log_metrics( run_id=pending_child_run_id, metrics=metrics_to_log, ) autologging_client.set_terminated(run_id=pending_child_run_id, end_time=child_run_end_time)
[ "def", "_create_child_runs_for_parameter_search", "(", "autologging_client", ",", "cv_estimator", ",", "parent_run", ",", "max_tuning_runs", ",", "child_tags", "=", "None", ")", ":", "import", "pandas", "as", "pd", "def", "first_custom_rank_column", "(", "df", ")", ...
https://github.com/mlflow/mlflow/blob/364aca7daf0fcee3ec407ae0b1b16d9cb3085081/mlflow/sklearn/utils.py#L605-L704
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/virt.py
python
_is_xen_hyper
()
return "libvirtd" in __salt__["cmd.run"](__grains__["ps"])
Returns a bool whether or not this node is a XEN hypervisor
Returns a bool whether or not this node is a XEN hypervisor
[ "Returns", "a", "bool", "whether", "or", "not", "this", "node", "is", "a", "XEN", "hypervisor" ]
def _is_xen_hyper(): """ Returns a bool whether or not this node is a XEN hypervisor """ try: if __grains__["virtual_subtype"] != "Xen Dom0": return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen("/proc/modules") as fp_: if "xen_" not in salt.utils.stringutils.to_unicode(fp_.read()): return False except OSError: # No /proc/modules? Are we on Windows? Or Solaris? return False return "libvirtd" in __salt__["cmd.run"](__grains__["ps"])
[ "def", "_is_xen_hyper", "(", ")", ":", "try", ":", "if", "__grains__", "[", "\"virtual_subtype\"", "]", "!=", "\"Xen Dom0\"", ":", "return", "False", "except", "KeyError", ":", "# virtual_subtype isn't set everywhere.", "return", "False", "try", ":", "with", "salt...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/virt.py#L5790-L5807
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/lobotomy/core/include/androguard/androguard/core/analysis/ganalysis.py
python
Graph.order
(self)
return len(self.node)
Return the number of nodes in the graph. Returns ------- nnodes : int The number of nodes in the graph. See Also -------- number_of_nodes, __len__ which are identical
Return the number of nodes in the graph.
[ "Return", "the", "number", "of", "nodes", "in", "the", "graph", "." ]
def order(self): """Return the number of nodes in the graph. Returns ------- nnodes : int The number of nodes in the graph. See Also -------- number_of_nodes, __len__ which are identical """ return len(self.node)
[ "def", "order", "(", "self", ")", ":", "return", "len", "(", "self", ".", "node", ")" ]
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/lobotomy/core/include/androguard/androguard/core/analysis/ganalysis.py#L634-L647
baidu-security/openrasp-iast
d4a5643420853a95614d371cf38d5c65ccf9cfd4
openrasp_iast/core/components/rasp_result.py
python
RaspResult.get_query_string
(self)
return self.rasp_result_dict["context"]["querystring"]
获取当前请求的url query Returns: string, 获取的query
获取当前请求的url query
[ "获取当前请求的url", "query" ]
def get_query_string(self): """ 获取当前请求的url query Returns: string, 获取的query """ return self.rasp_result_dict["context"]["querystring"]
[ "def", "get_query_string", "(", "self", ")", ":", "return", "self", ".", "rasp_result_dict", "[", "\"context\"", "]", "[", "\"querystring\"", "]" ]
https://github.com/baidu-security/openrasp-iast/blob/d4a5643420853a95614d371cf38d5c65ccf9cfd4/openrasp_iast/core/components/rasp_result.py#L359-L366
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_label.py
python
OCLabel.add
(self)
return self.openshift_cmd(cmd)
add labels
add labels
[ "add", "labels" ]
def add(self): ''' add labels ''' cmd = self.cmd_template() for label in self.labels: cmd.append("{}={}".format(label['key'], label['value'])) cmd.append("--overwrite") return self.openshift_cmd(cmd)
[ "def", "add", "(", "self", ")", ":", "cmd", "=", "self", ".", "cmd_template", "(", ")", "for", "label", "in", "self", ".", "labels", ":", "cmd", ".", "append", "(", "\"{}={}\"", ".", "format", "(", "label", "[", "'key'", "]", ",", "label", "[", "...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_label.py#L1649-L1658