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
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
extensions/pyRevitTools.extension/pyRevit.tab/Selection.panel/Pick.splitpushbutton/Pick.pushbutton/script.py
python
PickByCategorySelectionFilter.AllowReference
(self, refer, point)
return False
Not used for selection
Not used for selection
[ "Not", "used", "for", "selection" ]
def AllowReference(self, refer, point): # pylint: disable=W0613 """Not used for selection""" return False
[ "def", "AllowReference", "(", "self", ",", "refer", ",", "point", ")", ":", "# pylint: disable=W0613", "return", "False" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/extensions/pyRevitTools.extension/pyRevit.tab/Selection.panel/Pick.splitpushbutton/Pick.pushbutton/script.py#L37-L39
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail/utils/setup.py
python
sdist.run
(self)
[]
def run(self): self.compile_assets() base_sdist.run(self)
[ "def", "run", "(", "self", ")", ":", "self", ".", "compile_assets", "(", ")", "base_sdist", ".", "run", "(", "self", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail/utils/setup.py#L72-L74
akamai/api-kickstart
209b9543054d03692c5883dc59e3203a0056736d
examples/python/papi_create_datastore_new.py
python
getGroup
()
return (groups_result)
Request the list of groups for the account. Print out how many groups there are, then use the first group where the test property lives.
Request the list of groups for the account. Print out how many groups there are, then use the first group where the test property lives.
[ "Request", "the", "list", "of", "groups", "for", "the", "account", ".", "Print", "out", "how", "many", "groups", "there", "are", "then", "use", "the", "first", "group", "where", "the", "test", "property", "lives", "." ]
def getGroup(): """ Request the list of groups for the account. Print out how many groups there are, then use the first group where the test property lives. """ print print "Requesting the list of groups for this account" groups_result = httpCaller.getResult('/papi/v0/groups') return (groups_result)
[ "def", "getGroup", "(", ")", ":", "print", "print", "\"Requesting the list of groups for this account\"", "groups_result", "=", "httpCaller", ".", "getResult", "(", "'/papi/v0/groups'", ")", "return", "(", "groups_result", ")" ]
https://github.com/akamai/api-kickstart/blob/209b9543054d03692c5883dc59e3203a0056736d/examples/python/papi_create_datastore_new.py#L67-L79
hyperledger/sawtooth-core
704cd5837c21f53642c06ffc97ba7978a77940b0
validator/sawtooth_validator/state/merkle.py
python
MerkleDatabase.__contains__
(self, item)
Does the tree contain an address. Args: item (str): An address. Returns: (bool): True if it does contain, False otherwise.
Does the tree contain an address.
[ "Does", "the", "tree", "contain", "an", "address", "." ]
def __contains__(self, item): """Does the tree contain an address. Args: item (str): An address. Returns: (bool): True if it does contain, False otherwise. """ try: _libexec('merkle_db_contains', self.pointer, item.encode()) # No error implies found return True except KeyError: return False
[ "def", "__contains__", "(", "self", ",", "item", ")", ":", "try", ":", "_libexec", "(", "'merkle_db_contains'", ",", "self", ".", "pointer", ",", "item", ".", "encode", "(", ")", ")", "# No error implies found", "return", "True", "except", "KeyError", ":", ...
https://github.com/hyperledger/sawtooth-core/blob/704cd5837c21f53642c06ffc97ba7978a77940b0/validator/sawtooth_validator/state/merkle.py#L56-L71
holoviz/datashader
25578abde75c7fa28c6633b33cb8d8a1e433da67
datashader/bokeh_ext.py
python
patch_event
(image)
return json.dumps({'events': [{'attr': u'data', 'kind': 'ModelChanged', 'model': image.ds.ref, 'new': data}], 'references': []})
Generates a bokeh patch event message given an InteractiveImage instance. Uses the bokeh messaging protocol for bokeh>=0.12.10 and a custom patch for previous versions. Parameters ---------- image: InteractiveImage InteractiveImage instance with a plot Returns ------- msg: str JSON message containing patch events to update the plot
Generates a bokeh patch event message given an InteractiveImage instance. Uses the bokeh messaging protocol for bokeh>=0.12.10 and a custom patch for previous versions.
[ "Generates", "a", "bokeh", "patch", "event", "message", "given", "an", "InteractiveImage", "instance", ".", "Uses", "the", "bokeh", "messaging", "protocol", "for", "bokeh", ">", "=", "0", ".", "12", ".", "10", "and", "a", "custom", "patch", "for", "previou...
def patch_event(image): """ Generates a bokeh patch event message given an InteractiveImage instance. Uses the bokeh messaging protocol for bokeh>=0.12.10 and a custom patch for previous versions. Parameters ---------- image: InteractiveImage InteractiveImage instance with a plot Returns ------- msg: str JSON message containing patch events to update the plot """ if bokeh_version > '0.12.9': event_obj = image.doc.callbacks if bokeh_version >= '2.4' else image.doc events = list(event_obj._held_events) if not events: return None if bokeh_version > '2.0.0': protocol = Protocol() else: protocol = Protocol("1.0") msg = protocol.create("PATCH-DOC", events) event_obj._held_events = [] return msg data = dict(image.ds.data) data['image'] = [data['image'][0].tolist()] return json.dumps({'events': [{'attr': u'data', 'kind': 'ModelChanged', 'model': image.ds.ref, 'new': data}], 'references': []})
[ "def", "patch_event", "(", "image", ")", ":", "if", "bokeh_version", ">", "'0.12.9'", ":", "event_obj", "=", "image", ".", "doc", ".", "callbacks", "if", "bokeh_version", ">=", "'2.4'", "else", "image", ".", "doc", "events", "=", "list", "(", "event_obj", ...
https://github.com/holoviz/datashader/blob/25578abde75c7fa28c6633b33cb8d8a1e433da67/datashader/bokeh_ext.py#L72-L106
wbond/packagecontrol.io
9f5eb7e3392e6bc2ad979ad32d3dd27ef9c00b20
app/lib/package_control/deps/oscrypto/_mac/_core_foundation_ctypes.py
python
CFHelpers.cf_dictionary_to_dict
(dictionary)
return output
Converts a CFDictionary object into a python dictionary :param dictionary: The CFDictionary to convert :return: A python dict
Converts a CFDictionary object into a python dictionary
[ "Converts", "a", "CFDictionary", "object", "into", "a", "python", "dictionary" ]
def cf_dictionary_to_dict(dictionary): """ Converts a CFDictionary object into a python dictionary :param dictionary: The CFDictionary to convert :return: A python dict """ dict_length = CoreFoundation.CFDictionaryGetCount(dictionary) keys = (CFTypeRef * dict_length)() values = (CFTypeRef * dict_length)() CoreFoundation.CFDictionaryGetKeysAndValues( dictionary, _cast_pointer_p(keys), _cast_pointer_p(values) ) output = {} for index in range(0, dict_length): output[CFHelpers.native(keys[index])] = CFHelpers.native(values[index]) return output
[ "def", "cf_dictionary_to_dict", "(", "dictionary", ")", ":", "dict_length", "=", "CoreFoundation", ".", "CFDictionaryGetCount", "(", "dictionary", ")", "keys", "=", "(", "CFTypeRef", "*", "dict_length", ")", "(", ")", "values", "=", "(", "CFTypeRef", "*", "dic...
https://github.com/wbond/packagecontrol.io/blob/9f5eb7e3392e6bc2ad979ad32d3dd27ef9c00b20/app/lib/package_control/deps/oscrypto/_mac/_core_foundation_ctypes.py#L289-L314
box/box-python-sdk
e8abbb515cfe77d9533df77c807d55d6b494ceaa
boxsdk/client/client.py
python
Client.enterprise
(self, enterprise_id: str)
return self.translator.get('enterprise')(session=self._session, object_id=enterprise_id)
Initialize a :class:`Enterprise` object, whose box ID is enterprise_id. :param enterprise_id: The box id of the :class:`Enterprise` object. :return: A :class:`Enterprise` object with the given enterprise ID.
Initialize a :class:`Enterprise` object, whose box ID is enterprise_id.
[ "Initialize", "a", ":", "class", ":", "Enterprise", "object", "whose", "box", "ID", "is", "enterprise_id", "." ]
def enterprise(self, enterprise_id: str) -> 'Enterprise': """ Initialize a :class:`Enterprise` object, whose box ID is enterprise_id. :param enterprise_id: The box id of the :class:`Enterprise` object. :return: A :class:`Enterprise` object with the given enterprise ID. """ return self.translator.get('enterprise')(session=self._session, object_id=enterprise_id)
[ "def", "enterprise", "(", "self", ",", "enterprise_id", ":", "str", ")", "->", "'Enterprise'", ":", "return", "self", ".", "translator", ".", "get", "(", "'enterprise'", ")", "(", "session", "=", "self", ".", "_session", ",", "object_id", "=", "enterprise_...
https://github.com/box/box-python-sdk/blob/e8abbb515cfe77d9533df77c807d55d6b494ceaa/boxsdk/client/client.py#L408-L417
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/mail/_pop3client.py
python
POP3Client.serverGreeting
(self, greeting)
Handle the server greeting. @type greeting: L{bytes} @param greeting: The server greeting minus the status indicator. For servers implementing APOP authentication, this will contain a challenge string.
Handle the server greeting.
[ "Handle", "the", "server", "greeting", "." ]
def serverGreeting(self, greeting): """ Handle the server greeting. @type greeting: L{bytes} @param greeting: The server greeting minus the status indicator. For servers implementing APOP authentication, this will contain a challenge string. """
[ "def", "serverGreeting", "(", "self", ",", "greeting", ")", ":" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/mail/_pop3client.py#L587-L595
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/scapy/layers/inet6.py
python
IP6ListField.i2len
(self, pkt, i)
return 16*len(i)
[]
def i2len(self, pkt, i): return 16*len(i)
[ "def", "i2len", "(", "self", ",", "pkt", ",", "i", ")", ":", "return", "16", "*", "len", "(", "i", ")" ]
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/layers/inet6.py#L275-L276
citronneur/rdpy
cef16a9f64d836a3221a344ca7d571644280d829
rdpy/core/filetimes.py
python
dt_to_filetime
(dt)
return ft + (dt.microsecond * 10)
Converts a datetime to Microsoft filetime format. If the object is time zone-naive, it is forced to UTC before conversion. >>> "%.0f" % dt_to_filetime(datetime(2009, 7, 25, 23, 0)) '128930364000000000' >>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0, tzinfo=utc)) '116444736000000000' >>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0)) '116444736000000000' >>> dt_to_filetime(datetime(2009, 7, 25, 23, 0, 0, 100)) 128930364000001000
Converts a datetime to Microsoft filetime format. If the object is time zone-naive, it is forced to UTC before conversion.
[ "Converts", "a", "datetime", "to", "Microsoft", "filetime", "format", ".", "If", "the", "object", "is", "time", "zone", "-", "naive", "it", "is", "forced", "to", "UTC", "before", "conversion", "." ]
def dt_to_filetime(dt): """Converts a datetime to Microsoft filetime format. If the object is time zone-naive, it is forced to UTC before conversion. >>> "%.0f" % dt_to_filetime(datetime(2009, 7, 25, 23, 0)) '128930364000000000' >>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0, tzinfo=utc)) '116444736000000000' >>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0)) '116444736000000000' >>> dt_to_filetime(datetime(2009, 7, 25, 23, 0, 0, 100)) 128930364000001000 """ if (dt.tzinfo is None) or (dt.tzinfo.utcoffset(dt) is None): dt = dt.replace(tzinfo=utc) ft = EPOCH_AS_FILETIME + (timegm(dt.timetuple()) * HUNDREDS_OF_NANOSECONDS) return ft + (dt.microsecond * 10)
[ "def", "dt_to_filetime", "(", "dt", ")", ":", "if", "(", "dt", ".", "tzinfo", "is", "None", ")", "or", "(", "dt", ".", "tzinfo", ".", "utcoffset", "(", "dt", ")", "is", "None", ")", ":", "dt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "utc...
https://github.com/citronneur/rdpy/blob/cef16a9f64d836a3221a344ca7d571644280d829/rdpy/core/filetimes.py#L56-L75
spulec/moto
a688c0032596a7dfef122b69a08f2bec3be2e481
moto/dynamodb2/parsing/expressions.py
python
UpdateExpressionFunctionParser._is_possible_start
(cls, token)
Check whether a token is supposed to be a function Args: token(Token): the token to check Returns: bool: True if token is the start of a function.
Check whether a token is supposed to be a function Args: token(Token): the token to check
[ "Check", "whether", "a", "token", "is", "supposed", "to", "be", "a", "function", "Args", ":", "token", "(", "Token", ")", ":", "the", "token", "to", "check" ]
def _is_possible_start(cls, token): """ Check whether a token is supposed to be a function Args: token(Token): the token to check Returns: bool: True if token is the start of a function. """ if token.type == Token.ATTRIBUTE: return token.value in cls.FUNCTIONS.keys() else: return False
[ "def", "_is_possible_start", "(", "cls", ",", "token", ")", ":", "if", "token", ".", "type", "==", "Token", ".", "ATTRIBUTE", ":", "return", "token", ".", "value", "in", "cls", ".", "FUNCTIONS", ".", "keys", "(", ")", "else", ":", "return", "False" ]
https://github.com/spulec/moto/blob/a688c0032596a7dfef122b69a08f2bec3be2e481/moto/dynamodb2/parsing/expressions.py#L848-L860
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/operator.py
python
inv
(a)
return ~a
Same as ~a.
Same as ~a.
[ "Same", "as", "~a", "." ]
def inv(a): "Same as ~a." return ~a
[ "def", "inv", "(", "a", ")", ":", "return", "~", "a" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/operator.py#L91-L93
openstack/python-neutronclient
517bef2c5454dde2eba5cc2194ee857be6be7164
neutronclient/v2_0/client.py
python
Client.show_subnetpool
(self, subnetpool, **_params)
return self.get(self.subnetpool_path % (subnetpool), params=_params)
Fetches information of a certain subnetpool.
Fetches information of a certain subnetpool.
[ "Fetches", "information", "of", "a", "certain", "subnetpool", "." ]
def show_subnetpool(self, subnetpool, **_params): """Fetches information of a certain subnetpool.""" return self.get(self.subnetpool_path % (subnetpool), params=_params)
[ "def", "show_subnetpool", "(", "self", ",", "subnetpool", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "self", ".", "subnetpool_path", "%", "(", "subnetpool", ")", ",", "params", "=", "_params", ")" ]
https://github.com/openstack/python-neutronclient/blob/517bef2c5454dde2eba5cc2194ee857be6be7164/neutronclient/v2_0/client.py#L905-L907
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/nltk/corpus/reader/timit.py
python
TimitCorpusReader.spkrutteranceids
(self, speaker)
return [ utterance for utterance in self._utterances if utterance.startswith(speaker + "/") ]
:return: A list of all utterances associated with a given speaker.
:return: A list of all utterances associated with a given speaker.
[ ":", "return", ":", "A", "list", "of", "all", "utterances", "associated", "with", "a", "given", "speaker", "." ]
def spkrutteranceids(self, speaker): """ :return: A list of all utterances associated with a given speaker. """ return [ utterance for utterance in self._utterances if utterance.startswith(speaker + "/") ]
[ "def", "spkrutteranceids", "(", "self", ",", "speaker", ")", ":", "return", "[", "utterance", "for", "utterance", "in", "self", ".", "_utterances", "if", "utterance", ".", "startswith", "(", "speaker", "+", "\"/\"", ")", "]" ]
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/corpus/reader/timit.py#L251-L260
cronyo/cronyo
cd5abab0871b68bf31b18aac934303928130a441
cronyo/vendor/urllib3/util/retry.py
python
Retry.__init__
( self, total=10, connect=None, read=None, redirect=None, status=None, method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None, backoff_factor=0, raise_on_redirect=True, raise_on_status=True, history=None, respect_retry_after_header=True, remove_headers_on_redirect=DEFAULT_REDIRECT_HEADERS_BLACKLIST, )
[]
def __init__( self, total=10, connect=None, read=None, redirect=None, status=None, method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None, backoff_factor=0, raise_on_redirect=True, raise_on_status=True, history=None, respect_retry_after_header=True, remove_headers_on_redirect=DEFAULT_REDIRECT_HEADERS_BLACKLIST, ): self.total = total self.connect = connect self.read = read self.status = status if redirect is False or total is False: redirect = 0 raise_on_redirect = False self.redirect = redirect self.status_forcelist = status_forcelist or set() self.method_whitelist = method_whitelist self.backoff_factor = backoff_factor self.raise_on_redirect = raise_on_redirect self.raise_on_status = raise_on_status self.history = history or tuple() self.respect_retry_after_header = respect_retry_after_header self.remove_headers_on_redirect = frozenset( [h.lower() for h in remove_headers_on_redirect] )
[ "def", "__init__", "(", "self", ",", "total", "=", "10", ",", "connect", "=", "None", ",", "read", "=", "None", ",", "redirect", "=", "None", ",", "status", "=", "None", ",", "method_whitelist", "=", "DEFAULT_METHOD_WHITELIST", ",", "status_forcelist", "="...
https://github.com/cronyo/cronyo/blob/cd5abab0871b68bf31b18aac934303928130a441/cronyo/vendor/urllib3/util/retry.py#L161-L197
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/scipy/cluster/hierarchy.py
python
inconsistent
(Z, d=2)
return R
Calculates inconsistency statistics on a linkage. Note: This function behaves similarly to the MATLAB(TM) inconsistent function. Parameters ---------- Z : ndarray The :math:`(n-1)` by 4 matrix encoding the linkage (hierarchical clustering). See ``linkage`` documentation for more information on its form. d : int, optional The number of links up to `d` levels below each non-singleton cluster. Returns ------- R : ndarray A :math:`(n-1)` by 5 matrix where the ``i``'th row contains the link statistics for the non-singleton cluster ``i``. The link statistics are computed over the link heights for links :math:`d` levels below the cluster ``i``. ``R[i,0]`` and ``R[i,1]`` are the mean and standard deviation of the link heights, respectively; ``R[i,2]`` is the number of links included in the calculation; and ``R[i,3]`` is the inconsistency coefficient, .. math:: \\frac{\\mathtt{Z[i,2]}-\\mathtt{R[i,0]}} {R[i,1]}
Calculates inconsistency statistics on a linkage.
[ "Calculates", "inconsistency", "statistics", "on", "a", "linkage", "." ]
def inconsistent(Z, d=2): """ Calculates inconsistency statistics on a linkage. Note: This function behaves similarly to the MATLAB(TM) inconsistent function. Parameters ---------- Z : ndarray The :math:`(n-1)` by 4 matrix encoding the linkage (hierarchical clustering). See ``linkage`` documentation for more information on its form. d : int, optional The number of links up to `d` levels below each non-singleton cluster. Returns ------- R : ndarray A :math:`(n-1)` by 5 matrix where the ``i``'th row contains the link statistics for the non-singleton cluster ``i``. The link statistics are computed over the link heights for links :math:`d` levels below the cluster ``i``. ``R[i,0]`` and ``R[i,1]`` are the mean and standard deviation of the link heights, respectively; ``R[i,2]`` is the number of links included in the calculation; and ``R[i,3]`` is the inconsistency coefficient, .. math:: \\frac{\\mathtt{Z[i,2]}-\\mathtt{R[i,0]}} {R[i,1]} """ Z = np.asarray(Z, order='c') Zs = Z.shape is_valid_linkage(Z, throw=True, name='Z') if (not d == np.floor(d)) or d < 0: raise ValueError('The second argument d must be a nonnegative ' 'integer value.') # Since the C code does not support striding using strides. # The dimensions are used instead. [Z] = _copy_arrays_if_base_present([Z]) n = Zs[0] + 1 R = np.zeros((n - 1, 4), dtype=np.double) _hierarchy_wrap.inconsistent_wrap(Z, R, int(n), int(d)) return R
[ "def", "inconsistent", "(", "Z", ",", "d", "=", "2", ")", ":", "Z", "=", "np", ".", "asarray", "(", "Z", ",", "order", "=", "'c'", ")", "Zs", "=", "Z", ".", "shape", "is_valid_linkage", "(", "Z", ",", "throw", "=", "True", ",", "name", "=", "...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/scipy/cluster/hierarchy.py#L989-L1037
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/inspect.py
python
iscode
(object)
return isinstance(object, types.CodeType)
Return true if the object is a code object. Code objects provide these attributes: co_argcount number of arguments (not including * or ** args) co_code string of raw compiled bytecode co_consts tuple of constants used in the bytecode co_filename name of file in which this code object was created co_firstlineno number of first line in Python source code co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg co_lnotab encoded mapping of line numbers to bytecode indices co_name name with which this code object was defined co_names tuple of names of local variables co_nlocals number of local variables co_stacksize virtual machine stack space required co_varnames tuple of names of arguments and local variables
Return true if the object is a code object.
[ "Return", "true", "if", "the", "object", "is", "a", "code", "object", "." ]
def iscode(object): """Return true if the object is a code object. Code objects provide these attributes: co_argcount number of arguments (not including * or ** args) co_code string of raw compiled bytecode co_consts tuple of constants used in the bytecode co_filename name of file in which this code object was created co_firstlineno number of first line in Python source code co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg co_lnotab encoded mapping of line numbers to bytecode indices co_name name with which this code object was defined co_names tuple of names of local variables co_nlocals number of local variables co_stacksize virtual machine stack space required co_varnames tuple of names of arguments and local variables""" return isinstance(object, types.CodeType)
[ "def", "iscode", "(", "object", ")", ":", "return", "isinstance", "(", "object", ",", "types", ".", "CodeType", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/inspect.py#L209-L225
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/pydoc.py
python
ttypager
(text)
Page through text on a text terminal.
Page through text on a text terminal.
[ "Page", "through", "text", "on", "a", "text", "terminal", "." ]
def ttypager(text): """Page through text on a text terminal.""" lines = plain(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding))).split('\n') try: import tty fd = sys.stdin.fileno() old = tty.tcgetattr(fd) tty.setcbreak(fd) getchar = lambda: sys.stdin.read(1) except (ImportError, AttributeError): tty = None getchar = lambda: sys.stdin.readline()[:-1][:1] try: try: h = int(os.environ.get('LINES', 0)) except ValueError: h = 0 if h <= 1: h = 25 r = inc = h - 1 sys.stdout.write(join(lines[:inc], '\n') + '\n') while lines[r:]: sys.stdout.write('-- more --') sys.stdout.flush() c = getchar() if c in ('q', 'Q'): sys.stdout.write('\r \r') break elif c in ('\r', '\n'): sys.stdout.write('\r \r' + lines[r] + '\n') r = r + 1 continue if c in ('b', 'B', '\x1b'): r = r - inc - inc if r < 0: r = 0 sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n') r = r + inc finally: if tty: tty.tcsetattr(fd, tty.TCSAFLUSH, old)
[ "def", "ttypager", "(", "text", ")", ":", "lines", "=", "plain", "(", "_encode", "(", "plain", "(", "text", ")", ",", "getattr", "(", "sys", ".", "stdout", ",", "'encoding'", ",", "_encoding", ")", ")", ")", ".", "split", "(", "'\\n'", ")", "try", ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/pydoc.py#L1436-L1478
nucleic/enaml
65c2a2a2d765e88f2e1103046680571894bb41ed
enaml/core/compiler_nodes.py
python
TemplateInstanceNode.iternodes
(self)
return self.template.iternodes()
Iterate over the nodes of the instantiation. Returns ------- result : generator A generator which yields the unrolled nodes of the template instantiation.
Iterate over the nodes of the instantiation.
[ "Iterate", "over", "the", "nodes", "of", "the", "instantiation", "." ]
def iternodes(self): """ Iterate over the nodes of the instantiation. Returns ------- result : generator A generator which yields the unrolled nodes of the template instantiation. """ return self.template.iternodes()
[ "def", "iternodes", "(", "self", ")", ":", "return", "self", ".", "template", ".", "iternodes", "(", ")" ]
https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/core/compiler_nodes.py#L408-L418
hardbyte/python-can
e7a2b040ee1f0cdd7fd77fbfef0454353166b333
can/io/blf.py
python
BLFWriter.on_message_received
(self, msg)
[]
def on_message_received(self, msg): channel = channel2int(msg.channel) if channel is None: channel = self.channel else: # Many interfaces start channel numbering at 0 which is invalid channel += 1 arb_id = msg.arbitration_id if msg.is_extended_id: arb_id |= CAN_MSG_EXT flags = REMOTE_FLAG if msg.is_remote_frame else 0 if not msg.is_rx: flags |= DIR can_data = bytes(msg.data) if msg.is_error_frame: data = CAN_ERROR_EXT_STRUCT.pack( channel, 0, # length 0, # flags 0, # ecc 0, # position len2dlc(msg.dlc), 0, # frame length arb_id, 0, # ext flags can_data, ) self._add_object(CAN_ERROR_EXT, data, msg.timestamp) elif msg.is_fd: fd_flags = EDL if msg.bitrate_switch: fd_flags |= BRS if msg.error_state_indicator: fd_flags |= ESI data = CAN_FD_MSG_STRUCT.pack( channel, flags, len2dlc(msg.dlc), arb_id, 0, 0, fd_flags, len(can_data), can_data, ) self._add_object(CAN_FD_MESSAGE, data, msg.timestamp) else: data = CAN_MSG_STRUCT.pack(channel, flags, msg.dlc, arb_id, can_data) self._add_object(CAN_MESSAGE, data, msg.timestamp)
[ "def", "on_message_received", "(", "self", ",", "msg", ")", ":", "channel", "=", "channel2int", "(", "msg", ".", "channel", ")", "if", "channel", "is", "None", ":", "channel", "=", "self", ".", "channel", "else", ":", "# Many interfaces start channel numbering...
https://github.com/hardbyte/python-can/blob/e7a2b040ee1f0cdd7fd77fbfef0454353166b333/can/io/blf.py#L427-L477
NifTK/NiftyNet
935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0
niftynet/network/se_resnet.py
python
BottleneckBlock.__init__
(self, n_output_chns, stride, Conv, name='bottleneck')
:param n_output_chns: int, number of output channels :param stride: int, stride to use in the convolutional layers :param Conv: layer, convolutional layer :param name: layer name
[]
def __init__(self, n_output_chns, stride, Conv, name='bottleneck'): """ :param n_output_chns: int, number of output channels :param stride: int, stride to use in the convolutional layers :param Conv: layer, convolutional layer :param name: layer name """ self.n_output_chns = n_output_chns self.stride = stride self.bottle_neck_chns = n_output_chns // 4 self.Conv = Conv super(BottleneckBlock, self).__init__(name=name)
[ "def", "__init__", "(", "self", ",", "n_output_chns", ",", "stride", ",", "Conv", ",", "name", "=", "'bottleneck'", ")", ":", "self", ".", "n_output_chns", "=", "n_output_chns", "self", ".", "stride", "=", "stride", "self", ".", "bottle_neck_chns", "=", "n...
https://github.com/NifTK/NiftyNet/blob/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/network/se_resnet.py#L129-L141
ctfs/write-ups-2014
b02bcbb2737907dd0aa39c5d4df1d1e270958f54
asis-ctf-finals-2014/xorqr/netcatlib/netcatlib.py
python
Netcat.mt_interact
(self)
Multithreaded version of interact().
Multithreaded version of interact().
[ "Multithreaded", "version", "of", "interact", "()", "." ]
def mt_interact(self): """Multithreaded version of interact().""" global mt_interact_exit import thread mt_interact_exit = False threadid = thread.start_new_thread(self.listener, ()) while 1: line = sys.stdin.readline() if not line or mt_interact_exit: break self.write(line)
[ "def", "mt_interact", "(", "self", ")", ":", "global", "mt_interact_exit", "import", "thread", "mt_interact_exit", "=", "False", "threadid", "=", "thread", ".", "start_new_thread", "(", "self", ".", "listener", ",", "(", ")", ")", "while", "1", ":", "line", ...
https://github.com/ctfs/write-ups-2014/blob/b02bcbb2737907dd0aa39c5d4df1d1e270958f54/asis-ctf-finals-2014/xorqr/netcatlib/netcatlib.py#L308-L319
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/op2/tables/oes_stressStrain/real/oes_triax.py
python
RealTriaxArray.build
(self)
sizes the vectorized attributes of the RealTriaxArray
sizes the vectorized attributes of the RealTriaxArray
[ "sizes", "the", "vectorized", "attributes", "of", "the", "RealTriaxArray" ]
def build(self): """sizes the vectorized attributes of the RealTriaxArray""" #print("self.ielement =", self.ielement) #print('ntimes=%s nelements=%s ntotal=%s' % (self.ntimes, self.nelements, self.ntotal)) assert self.ntimes > 0, 'ntimes=%s' % self.ntimes assert self.nelements > 0, 'nelements=%s' % self.nelements assert self.ntotal > 0, 'ntotal=%s' % self.ntotal unused_nnodes_per_element = self.nnodes_per_element self.itime = 0 self.ielement = 0 self.itotal = 0 #self.ntimes = 0 #self.nelements = 0 #print("***name=%s type=%s nnodes_per_element=%s ntimes=%s nelements=%s ntotal=%s" % ( #self.element_name, self.element_type, nnodes_per_element, self.ntimes, self.nelements, self.ntotal)) dtype, idtype, fdtype = get_times_dtype(self.nonlinear_factor, self.size, self.analysis_fmt) _times = zeros(self.ntimes, dtype=dtype) element_node = zeros((self.ntotal, 2), dtype='int32') # [radial, azimuthal, axial, shear, omax, oms, ovm] data = zeros((self.ntimes, self.ntotal, 7), dtype='float32') if self.load_as_h5: #for key, value in sorted(self.data_code.items()): #print(key, value) group = self._get_result_group() self._times = group.create_dataset('_times', data=_times) self.element_node = group.create_dataset('element_node', data=element_node) self.data = group.create_dataset('data', data=data) else: self._times = _times self.element_node = element_node self.data = data
[ "def", "build", "(", "self", ")", ":", "#print(\"self.ielement =\", self.ielement)", "#print('ntimes=%s nelements=%s ntotal=%s' % (self.ntimes, self.nelements, self.ntotal))", "assert", "self", ".", "ntimes", ">", "0", ",", "'ntimes=%s'", "%", "self", ".", "ntimes", "assert",...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/op2/tables/oes_stressStrain/real/oes_triax.py#L51-L85
NordicSemiconductor/pc-nrfutil
d08e742128f2a3dac522601bc6b9f9b2b63952df
nordicsemi/dfu/package.py
python
Package.__create_temp_workspace
()
return tempfile.mkdtemp(prefix="nrf_dfu_pkg_")
[]
def __create_temp_workspace(): return tempfile.mkdtemp(prefix="nrf_dfu_pkg_")
[ "def", "__create_temp_workspace", "(", ")", ":", "return", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "\"nrf_dfu_pkg_\"", ")" ]
https://github.com/NordicSemiconductor/pc-nrfutil/blob/d08e742128f2a3dac522601bc6b9f9b2b63952df/nordicsemi/dfu/package.py#L513-L514
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/transpiler/passes/routing/sabre_swap.py
python
SabreSwap.__init__
(self, coupling_map, heuristic="basic", seed=None, fake_run=False)
r"""SabreSwap initializer. Args: coupling_map (CouplingMap): CouplingMap of the target backend. heuristic (str): The type of heuristic to use when deciding best swap strategy ('basic' or 'lookahead' or 'decay'). seed (int): random seed used to tie-break among candidate swaps. fake_run (bool): if true, it only pretend to do routing, i.e., no swap is effectively added. Additional Information: The search space of possible SWAPs on physical qubits is explored by assigning a score to the layout that would result from each SWAP. The goodness of a layout is evaluated based on how viable it makes the remaining virtual gates that must be applied. A few heuristic cost functions are supported - 'basic': The sum of distances for corresponding physical qubits of interacting virtual qubits in the front_layer. .. math:: H_{basic} = \sum_{gate \in F} D[\pi(gate.q_1)][\pi(gate.q2)] - 'lookahead': This is the sum of two costs: first is the same as the basic cost. Second is the basic cost but now evaluated for the extended set as well (i.e. :math:`|E|` number of upcoming successors to gates in front_layer F). This is weighted by some amount EXTENDED_SET_WEIGHT (W) to signify that upcoming gates are less important that the front_layer. .. math:: H_{decay}=\frac{1}{\left|{F}\right|}\sum_{gate \in F} D[\pi(gate.q_1)][\pi(gate.q2)] + W*\frac{1}{\left|{E}\right|} \sum_{gate \in E} D[\pi(gate.q_1)][\pi(gate.q2)] - 'decay': This is the same as 'lookahead', but the whole cost is multiplied by a decay factor. This increases the cost if the SWAP that generated the trial layout was recently used (i.e. it penalizes increase in depth). .. math:: H_{decay} = max(decay(SWAP.q_1), decay(SWAP.q_2)) { \frac{1}{\left|{F}\right|} \sum_{gate \in F} D[\pi(gate.q_1)][\pi(gate.q2)]\\ + W *\frac{1}{\left|{E}\right|} \sum_{gate \in E} D[\pi(gate.q_1)][\pi(gate.q2)] }
r"""SabreSwap initializer.
[ "r", "SabreSwap", "initializer", "." ]
def __init__(self, coupling_map, heuristic="basic", seed=None, fake_run=False): r"""SabreSwap initializer. Args: coupling_map (CouplingMap): CouplingMap of the target backend. heuristic (str): The type of heuristic to use when deciding best swap strategy ('basic' or 'lookahead' or 'decay'). seed (int): random seed used to tie-break among candidate swaps. fake_run (bool): if true, it only pretend to do routing, i.e., no swap is effectively added. Additional Information: The search space of possible SWAPs on physical qubits is explored by assigning a score to the layout that would result from each SWAP. The goodness of a layout is evaluated based on how viable it makes the remaining virtual gates that must be applied. A few heuristic cost functions are supported - 'basic': The sum of distances for corresponding physical qubits of interacting virtual qubits in the front_layer. .. math:: H_{basic} = \sum_{gate \in F} D[\pi(gate.q_1)][\pi(gate.q2)] - 'lookahead': This is the sum of two costs: first is the same as the basic cost. Second is the basic cost but now evaluated for the extended set as well (i.e. :math:`|E|` number of upcoming successors to gates in front_layer F). This is weighted by some amount EXTENDED_SET_WEIGHT (W) to signify that upcoming gates are less important that the front_layer. .. math:: H_{decay}=\frac{1}{\left|{F}\right|}\sum_{gate \in F} D[\pi(gate.q_1)][\pi(gate.q2)] + W*\frac{1}{\left|{E}\right|} \sum_{gate \in E} D[\pi(gate.q_1)][\pi(gate.q2)] - 'decay': This is the same as 'lookahead', but the whole cost is multiplied by a decay factor. This increases the cost if the SWAP that generated the trial layout was recently used (i.e. it penalizes increase in depth). .. math:: H_{decay} = max(decay(SWAP.q_1), decay(SWAP.q_2)) { \frac{1}{\left|{F}\right|} \sum_{gate \in F} D[\pi(gate.q_1)][\pi(gate.q2)]\\ + W *\frac{1}{\left|{E}\right|} \sum_{gate \in E} D[\pi(gate.q_1)][\pi(gate.q2)] } """ super().__init__() # Assume bidirectional couplings, fixing gate direction is easy later. if coupling_map is None or coupling_map.is_symmetric: self.coupling_map = coupling_map else: self.coupling_map = deepcopy(coupling_map) self.coupling_map.make_symmetric() self.heuristic = heuristic self.seed = seed self.fake_run = fake_run self.applied_predecessors = None self.qubits_decay = None self._bit_indices = None self.dist_matrix = None
[ "def", "__init__", "(", "self", ",", "coupling_map", ",", "heuristic", "=", "\"basic\"", ",", "seed", "=", "None", ",", "fake_run", "=", "False", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "# Assume bidirectional couplings, fixing gate direction is ...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/transpiler/passes/routing/sabre_swap.py#L68-L138
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/numbers.py
python
Complex.real
(self)
Retrieve the real component of this number. This should subclass Real.
Retrieve the real component of this number.
[ "Retrieve", "the", "real", "component", "of", "this", "number", "." ]
def real(self): """Retrieve the real component of this number. This should subclass Real. """ raise NotImplementedError
[ "def", "real", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/numbers.py#L57-L62
dcos/dcos
79b9a39b4e639dc2c9435a869918399b50bfaf24
pkgpanda/actions.py
python
remove_package
(install, repository, package_id)
Remove a package from the local repository. Errors if any packages in package_ids are activated in install. install: pkgpanda.Install repository: pkgpanda.Repository package_id: package ID to remove from repository
Remove a package from the local repository.
[ "Remove", "a", "package", "from", "the", "local", "repository", "." ]
def remove_package(install, repository, package_id): """Remove a package from the local repository. Errors if any packages in package_ids are activated in install. install: pkgpanda.Install repository: pkgpanda.Repository package_id: package ID to remove from repository """ if package_id in install.get_active(): raise PackageConflict("Refusing to remove active package {0}".format(package_id)) sys.stdout.write("\rRemoving: {0}".format(package_id)) sys.stdout.flush() try: # Validate package id, that package is installed. PackageId(package_id) repository.remove(package_id) except ValidationError as ex: raise ValidationError("Invalid package id {0}".format(package_id)) from ex except OSError as ex: raise Exception("Error removing package {0}: {1}".format(package_id, ex)) from ex else: sys.stdout.write("\rRemoved: {0}".format(package_id)) finally: sys.stdout.write("\n") sys.stdout.flush()
[ "def", "remove_package", "(", "install", ",", "repository", ",", "package_id", ")", ":", "if", "package_id", "in", "install", ".", "get_active", "(", ")", ":", "raise", "PackageConflict", "(", "\"Refusing to remove active package {0}\"", ".", "format", "(", "packa...
https://github.com/dcos/dcos/blob/79b9a39b4e639dc2c9435a869918399b50bfaf24/pkgpanda/actions.py#L124-L151
llSourcell/Make_Money_with_Tensorflow
9bedf1af6cf91c099d915bc08253b464dcb2f205
mnist_client.py
python
do_inference
(hostport, work_dir, concurrency, num_tests)
return result_counter.get_error_rate()
Tests PredictionService with concurrent requests. Args: hostport: Host:port address of the PredictionService. work_dir: The full path of working directory for test data set. concurrency: Maximum number of concurrent requests. num_tests: Number of test images to use. Returns: The classification error rate. Raises: IOError: An error occurred processing test data set.
Tests PredictionService with concurrent requests.
[ "Tests", "PredictionService", "with", "concurrent", "requests", "." ]
def do_inference(hostport, work_dir, concurrency, num_tests): """Tests PredictionService with concurrent requests. Args: hostport: Host:port address of the PredictionService. work_dir: The full path of working directory for test data set. concurrency: Maximum number of concurrent requests. num_tests: Number of test images to use. Returns: The classification error rate. Raises: IOError: An error occurred processing test data set. """ test_data_set = mnist_input_data.read_data_sets(work_dir).test host, port = hostport.split(':') channel = implementations.insecure_channel(host, int(port)) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) result_counter = _ResultCounter(num_tests, concurrency) for _ in range(num_tests): request = predict_pb2.PredictRequest() request.model_spec.name = 'mnist' request.model_spec.signature_name = 'predict' image, label = test_data_set.next_batch(1) request.inputs['inputs'].CopyFrom( tf.contrib.util.make_tensor_proto(image[0], shape=[1, 28, 28, 1])) result_counter.throttle() result_future = stub.Predict.future(request, 5.0) # 5 seconds result_future.add_done_callback( _create_rpc_callback(label[0], result_counter)) return result_counter.get_error_rate()
[ "def", "do_inference", "(", "hostport", ",", "work_dir", ",", "concurrency", ",", "num_tests", ")", ":", "test_data_set", "=", "mnist_input_data", ".", "read_data_sets", "(", "work_dir", ")", ".", "test", "host", ",", "port", "=", "hostport", ".", "split", "...
https://github.com/llSourcell/Make_Money_with_Tensorflow/blob/9bedf1af6cf91c099d915bc08253b464dcb2f205/mnist_client.py#L123-L154
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
client_lib/pulp/client/commands/consumer/bind.py
python
ConsumerBindCommand._render_bind_header
(self)
Displays the task header for the bind task.
Displays the task header for the bind task.
[ "Displays", "the", "task", "header", "for", "the", "bind", "task", "." ]
def _render_bind_header(self): """ Displays the task header for the bind task. """ self.prompt.write(_('-- Updating Pulp Server --'), tag='bind-header')
[ "def", "_render_bind_header", "(", "self", ")", ":", "self", ".", "prompt", ".", "write", "(", "_", "(", "'-- Updating Pulp Server --'", ")", ",", "tag", "=", "'bind-header'", ")" ]
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/client_lib/pulp/client/commands/consumer/bind.py#L116-L120
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
example/ctp/option/__init__.py
python
TraderApi.OnRspForQuoteInsert
(self, pInputForQuote, pRspInfo, nRequestID, bIsLast)
询价录入请求响应
询价录入请求响应
[ "询价录入请求响应" ]
def OnRspForQuoteInsert(self, pInputForQuote, pRspInfo, nRequestID, bIsLast): """询价录入请求响应"""
[ "def", "OnRspForQuoteInsert", "(", "self", ",", "pInputForQuote", ",", "pRspInfo", ",", "nRequestID", ",", "bIsLast", ")", ":" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/ctp/option/__init__.py#L564-L565
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/immlib/immlib.py
python
Debugger.getHeapsAddress
(self)
return self.HeapsAddr
Get a the process heaps @rtype: LIST of DWORD @return: List of Heap Address
Get a the process heaps
[ "Get", "a", "the", "process", "heaps" ]
def getHeapsAddress(self): """ Get a the process heaps @rtype: LIST of DWORD @return: List of Heap Address """ self.HeapsAddr = [] peb = self.getPEB() addr = peb.ProcessHeaps[0] for ndx in range(0, peb.NumberOfHeaps): l = self.readLong( addr + ndx * 4 ) if l: self.HeapsAddr.append( l ) return self.HeapsAddr
[ "def", "getHeapsAddress", "(", "self", ")", ":", "self", ".", "HeapsAddr", "=", "[", "]", "peb", "=", "self", ".", "getPEB", "(", ")", "addr", "=", "peb", ".", "ProcessHeaps", "[", "0", "]", "for", "ndx", "in", "range", "(", "0", ",", "peb", ".",...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/immlib/immlib.py#L1402-L1418
boston-dynamics/spot-sdk
5ffa12e6943a47323c7279d86e30346868755f52
python/bosdyn-client/src/bosdyn/client/robot_command.py
python
RobotCommandBuilder.stand_command
(params=None, body_height=0.0, footprint_R_body=geometry.EulerZXY())
return command
Command robot to stand. If the robot is sitting, it will stand up. If the robot is moving, it will come to a stop. Params can specify a trajectory for the body to follow while standing. In the simplest case, this can be a specific position+orientation which the body will hold at. The arguments body_height and footprint_R_body are ignored if params argument is passed. Args: params(spot.MobilityParams): Spot specific parameters for mobility commands. If not set, this will be constructed using other args. body_height(float): Height, meters, to stand at relative to a nominal stand height. footprint_R_body(EulerZXY): The orientation of the body frame with respect to the footprint frame (gravity aligned framed with yaw computed from the stance feet) Returns: RobotCommand, which can be issued to the robot command service.
Command robot to stand. If the robot is sitting, it will stand up. If the robot is moving, it will come to a stop. Params can specify a trajectory for the body to follow while standing. In the simplest case, this can be a specific position+orientation which the body will hold at. The arguments body_height and footprint_R_body are ignored if params argument is passed.
[ "Command", "robot", "to", "stand", ".", "If", "the", "robot", "is", "sitting", "it", "will", "stand", "up", ".", "If", "the", "robot", "is", "moving", "it", "will", "come", "to", "a", "stop", ".", "Params", "can", "specify", "a", "trajectory", "for", ...
def stand_command(params=None, body_height=0.0, footprint_R_body=geometry.EulerZXY()): """ Command robot to stand. If the robot is sitting, it will stand up. If the robot is moving, it will come to a stop. Params can specify a trajectory for the body to follow while standing. In the simplest case, this can be a specific position+orientation which the body will hold at. The arguments body_height and footprint_R_body are ignored if params argument is passed. Args: params(spot.MobilityParams): Spot specific parameters for mobility commands. If not set, this will be constructed using other args. body_height(float): Height, meters, to stand at relative to a nominal stand height. footprint_R_body(EulerZXY): The orientation of the body frame with respect to the footprint frame (gravity aligned framed with yaw computed from the stance feet) Returns: RobotCommand, which can be issued to the robot command service. """ if not params: params = RobotCommandBuilder.mobility_params(body_height=body_height, footprint_R_body=footprint_R_body) any_params = RobotCommandBuilder._to_any(params) mobility_command = mobility_command_pb2.MobilityCommand.Request( stand_request=basic_command_pb2.StandCommand.Request(), params=any_params) command = robot_command_pb2.RobotCommand(mobility_command=mobility_command) return command
[ "def", "stand_command", "(", "params", "=", "None", ",", "body_height", "=", "0.0", ",", "footprint_R_body", "=", "geometry", ".", "EulerZXY", "(", ")", ")", ":", "if", "not", "params", ":", "params", "=", "RobotCommandBuilder", ".", "mobility_params", "(", ...
https://github.com/boston-dynamics/spot-sdk/blob/5ffa12e6943a47323c7279d86e30346868755f52/python/bosdyn-client/src/bosdyn/client/robot_command.py#L791-L816
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
custom/inddex/food.py
python
FoodRow._set_conversion_factors
(self)
[]
def _set_conversion_factors(self): self.conv_factor_gap_code = ConvFactorGaps.NOT_AVAILABLE if (self.food_type == FOOD_ITEM and self._is_std_recipe_ingredient or self.food_type == NON_STANDARD_RECIPE): self.conv_factor_gap_code = ConvFactorGaps.NOT_APPLICABLE elif self.food_type in (FOOD_ITEM, STANDARD_RECIPE) and self.conv_method_code: self.conv_factor_food_code = self.fixtures.conversion_factors.get( (self.food_code, self.conv_method_code, self.conv_option_code)) self.conv_factor_base_term_food_code = self.fixtures.conversion_factors.get( (self.base_term_food_code, self.conv_method_code, self.conv_option_code)) if self.conv_factor_food_code: self.conv_factor_used = 'food_code' self.conv_factor = self.conv_factor_food_code self.conv_factor_gap_code = ConvFactorGaps.AVAILABLE elif self.conv_factor_base_term_food_code: self.conv_factor_used = 'base_term_food_code' self.conv_factor = self.conv_factor_base_term_food_code self.conv_factor_gap_code = ConvFactorGaps.BASE_TERM self.conv_factor_gap_desc = ConvFactorGaps.DESCRIPTIONS[self.conv_factor_gap_code]
[ "def", "_set_conversion_factors", "(", "self", ")", ":", "self", ".", "conv_factor_gap_code", "=", "ConvFactorGaps", ".", "NOT_AVAILABLE", "if", "(", "self", ".", "food_type", "==", "FOOD_ITEM", "and", "self", ".", "_is_std_recipe_ingredient", "or", "self", ".", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/custom/inddex/food.py#L268-L289
JulianEberius/SublimePythonIDE
d70e40abc0c9f347af3204c7b910e0d6bfd6e459
server/lib/python_all/jedi/cache.py
python
_invalidate_star_import_cache_module
(module, only_main=False)
Important if some new modules are being reparsed
Important if some new modules are being reparsed
[ "Important", "if", "some", "new", "modules", "are", "being", "reparsed" ]
def _invalidate_star_import_cache_module(module, only_main=False): """ Important if some new modules are being reparsed """ try: t, modules = _time_caches['star_import_cache_validity'][module] except KeyError: pass else: del _time_caches['star_import_cache_validity'][module]
[ "def", "_invalidate_star_import_cache_module", "(", "module", ",", "only_main", "=", "False", ")", ":", "try", ":", "t", ",", "modules", "=", "_time_caches", "[", "'star_import_cache_validity'", "]", "[", "module", "]", "except", "KeyError", ":", "pass", "else",...
https://github.com/JulianEberius/SublimePythonIDE/blob/d70e40abc0c9f347af3204c7b910e0d6bfd6e459/server/lib/python_all/jedi/cache.py#L174-L181
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
official/vision/beta/projects/yolo/modeling/decoders/yolo_decoder.py
python
YoloFPN.__init__
(self, fpn_depth=4, max_fpn_depth=None, max_csp_stack=None, use_spatial_attention=False, csp_stack=False, activation='leaky', fpn_filter_scale=1, use_sync_bn=False, use_separable_conv=False, norm_momentum=0.99, norm_epsilon=0.001, kernel_initializer='VarianceScaling', kernel_regularizer=None, bias_regularizer=None, **kwargs)
Yolo FPN initialization function (Yolo V4). Args: fpn_depth: `int`, number of layers to use in each FPN path if you choose to use an FPN. max_fpn_depth: `int`, number of layers to use in each FPN path if you choose to use an FPN along the largest FPN level. max_csp_stack: `int`, number of layers to use for CSP on the largest_path only. use_spatial_attention: `bool`, use the spatial attention module. csp_stack: `bool`, CSPize the FPN. activation: `str`, the activation function to use typically leaky or mish. fpn_filter_scale: `int`, scaling factor for the FPN filters. use_sync_bn: if True, use synchronized batch normalization. use_separable_conv: `bool` whether to use separable convs. norm_momentum: `float`, normalization momentum for the moving average. norm_epsilon: `float`, small float added to variance to avoid dividing by zero. kernel_initializer: kernel_initializer for convolutional layers. kernel_regularizer: tf.keras.regularizers.Regularizer object for Conv2D. bias_regularizer: tf.keras.regularizers.Regularizer object for Conv2D. **kwargs: keyword arguments to be passed.
Yolo FPN initialization function (Yolo V4).
[ "Yolo", "FPN", "initialization", "function", "(", "Yolo", "V4", ")", "." ]
def __init__(self, fpn_depth=4, max_fpn_depth=None, max_csp_stack=None, use_spatial_attention=False, csp_stack=False, activation='leaky', fpn_filter_scale=1, use_sync_bn=False, use_separable_conv=False, norm_momentum=0.99, norm_epsilon=0.001, kernel_initializer='VarianceScaling', kernel_regularizer=None, bias_regularizer=None, **kwargs): """Yolo FPN initialization function (Yolo V4). Args: fpn_depth: `int`, number of layers to use in each FPN path if you choose to use an FPN. max_fpn_depth: `int`, number of layers to use in each FPN path if you choose to use an FPN along the largest FPN level. max_csp_stack: `int`, number of layers to use for CSP on the largest_path only. use_spatial_attention: `bool`, use the spatial attention module. csp_stack: `bool`, CSPize the FPN. activation: `str`, the activation function to use typically leaky or mish. fpn_filter_scale: `int`, scaling factor for the FPN filters. use_sync_bn: if True, use synchronized batch normalization. use_separable_conv: `bool` whether to use separable convs. norm_momentum: `float`, normalization momentum for the moving average. norm_epsilon: `float`, small float added to variance to avoid dividing by zero. kernel_initializer: kernel_initializer for convolutional layers. kernel_regularizer: tf.keras.regularizers.Regularizer object for Conv2D. bias_regularizer: tf.keras.regularizers.Regularizer object for Conv2D. **kwargs: keyword arguments to be passed. """ super().__init__(**kwargs) self._fpn_depth = fpn_depth self._max_fpn_depth = max_fpn_depth or self._fpn_depth self._activation = activation self._use_sync_bn = use_sync_bn self._use_separable_conv = use_separable_conv self._norm_momentum = norm_momentum self._norm_epsilon = norm_epsilon self._kernel_initializer = kernel_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._use_spatial_attention = use_spatial_attention self._filter_scale = fpn_filter_scale self._csp_stack = csp_stack self._max_csp_stack = max_csp_stack or min(self._max_fpn_depth, csp_stack) self._base_config = dict( activation=self._activation, use_sync_bn=self._use_sync_bn, use_separable_conv=self._use_separable_conv, kernel_regularizer=self._kernel_regularizer, kernel_initializer=self._kernel_initializer, bias_regularizer=self._bias_regularizer, norm_epsilon=self._norm_epsilon, norm_momentum=self._norm_momentum)
[ "def", "__init__", "(", "self", ",", "fpn_depth", "=", "4", ",", "max_fpn_depth", "=", "None", ",", "max_csp_stack", "=", "None", ",", "use_spatial_attention", "=", "False", ",", "csp_stack", "=", "False", ",", "activation", "=", "'leaky'", ",", "fpn_filter_...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/vision/beta/projects/yolo/modeling/decoders/yolo_decoder.py#L96-L161
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/coordinates/angles.py
python
Angle.signed_dms
(self)
return signed_dms_tuple(np.sign(self.degree), *util.degrees_to_dms(np.abs(self.degree)))
The angle's value in degrees, as a named tuple with ``(sign, d, m, s)`` members. The ``d``, ``m``, ``s`` are thus always positive, and the sign of the angle is given by ``sign``. (This is a read-only property.) This is primarily intended for use with `dms` to generate string representations of coordinates that are correct for negative angles.
The angle's value in degrees, as a named tuple with ``(sign, d, m, s)`` members. The ``d``, ``m``, ``s`` are thus always positive, and the sign of the angle is given by ``sign``. (This is a read-only property.)
[ "The", "angle", "s", "value", "in", "degrees", "as", "a", "named", "tuple", "with", "(", "sign", "d", "m", "s", ")", "members", ".", "The", "d", "m", "s", "are", "thus", "always", "positive", "and", "the", "sign", "of", "the", "angle", "is", "given...
def signed_dms(self): """ The angle's value in degrees, as a named tuple with ``(sign, d, m, s)`` members. The ``d``, ``m``, ``s`` are thus always positive, and the sign of the angle is given by ``sign``. (This is a read-only property.) This is primarily intended for use with `dms` to generate string representations of coordinates that are correct for negative angles. """ return signed_dms_tuple(np.sign(self.degree), *util.degrees_to_dms(np.abs(self.degree)))
[ "def", "signed_dms", "(", "self", ")", ":", "return", "signed_dms_tuple", "(", "np", ".", "sign", "(", "self", ".", "degree", ")", ",", "*", "util", ".", "degrees_to_dms", "(", "np", ".", "abs", "(", "self", ".", "degree", ")", ")", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/coordinates/angles.py#L156-L166
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/ultimatelistctrl.py
python
UltimateListMainWindow.FindItemData
(self, start, data)
return wx.NOT_FOUND
Find an item whose data matches this data. :param `start`: the starting point of the input `data` or the beginning if `start` is -1; :param `data`: the data to look for matches.
Find an item whose data matches this data.
[ "Find", "an", "item", "whose", "data", "matches", "this", "data", "." ]
def FindItemData(self, start, data): """ Find an item whose data matches this data. :param `start`: the starting point of the input `data` or the beginning if `start` is -1; :param `data`: the data to look for matches. """ if start < 0: start = 0 count = self.GetItemCount() for i in range(start, count): line = self.GetLine(i) item = UltimateListItem() item = line.GetItem(0, item) if item._data == data: return i return wx.NOT_FOUND
[ "def", "FindItemData", "(", "self", ",", "start", ",", "data", ")", ":", "if", "start", "<", "0", ":", "start", "=", "0", "count", "=", "self", ".", "GetItemCount", "(", ")", "for", "i", "in", "range", "(", "start", ",", "count", ")", ":", "line"...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/ultimatelistctrl.py#L10118-L10140
pyca/pyopenssl
fb26edde0aa27670c7bb24c0daeb05516e83d7b0
src/OpenSSL/SSL.py
python
Context.use_privatekey
(self, pkey)
Load a private key from a PKey object :param pkey: The PKey object :return: None
Load a private key from a PKey object
[ "Load", "a", "private", "key", "from", "a", "PKey", "object" ]
def use_privatekey(self, pkey): """ Load a private key from a PKey object :param pkey: The PKey object :return: None """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey) if not use_result: self._raise_passphrase_exception()
[ "def", "use_privatekey", "(", "self", ",", "pkey", ")", ":", "if", "not", "isinstance", "(", "pkey", ",", "PKey", ")", ":", "raise", "TypeError", "(", "\"pkey must be a PKey instance\"", ")", "use_result", "=", "_lib", ".", "SSL_CTX_use_PrivateKey", "(", "self...
https://github.com/pyca/pyopenssl/blob/fb26edde0aa27670c7bb24c0daeb05516e83d7b0/src/OpenSSL/SSL.py#L1014-L1026
qiueer/zabbix
31983dedbd59d917ecd71bb6f36b35302673a783
All In One/src/memcache.py
python
MCache.get_item_tval
(self, item)
return val
[]
def get_item_tval(self, item): val = self.get_item_val(item) if val == None:return 0 val = str(val) try: val = int(val) except Exception: try: val = float(val) val = "%.2f" % (val) except Exception: val = str(val) return val
[ "def", "get_item_tval", "(", "self", ",", "item", ")", ":", "val", "=", "self", ".", "get_item_val", "(", "item", ")", "if", "val", "==", "None", ":", "return", "0", "val", "=", "str", "(", "val", ")", "try", ":", "val", "=", "int", "(", "val", ...
https://github.com/qiueer/zabbix/blob/31983dedbd59d917ecd71bb6f36b35302673a783/All In One/src/memcache.py#L160-L172
xiaobai1217/MBMD
246f3434bccb9c8357e0f698995b659578bf1afb
lib/object_detection/core/box_list.py
python
BoxList.transpose_coordinates
(self, scope=None)
Transpose the coordinate representation in a boxlist. Args: scope: name scope of the function.
Transpose the coordinate representation in a boxlist.
[ "Transpose", "the", "coordinate", "representation", "in", "a", "boxlist", "." ]
def transpose_coordinates(self, scope=None): """Transpose the coordinate representation in a boxlist. Args: scope: name scope of the function. """ with tf.name_scope(scope, 'transpose_coordinates'): y_min, x_min, y_max, x_max = tf.split( value=self.get(), num_or_size_splits=4, axis=1) self.set(tf.concat([x_min, y_min, x_max, y_max], 1))
[ "def", "transpose_coordinates", "(", "self", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'transpose_coordinates'", ")", ":", "y_min", ",", "x_min", ",", "y_max", ",", "x_max", "=", "tf", ".", "split", "(", ...
https://github.com/xiaobai1217/MBMD/blob/246f3434bccb9c8357e0f698995b659578bf1afb/lib/object_detection/core/box_list.py#L176-L185
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/keyword_plan_campaign_keyword_service/client.py
python
KeywordPlanCampaignKeywordServiceClient.common_project_path
(project: str,)
return "projects/{project}".format(project=project,)
Return a fully-qualified project string.
Return a fully-qualified project string.
[ "Return", "a", "fully", "-", "qualified", "project", "string", "." ]
def common_project_path(project: str,) -> str: """Return a fully-qualified project string.""" return "projects/{project}".format(project=project,)
[ "def", "common_project_path", "(", "project", ":", "str", ",", ")", "->", "str", ":", "return", "\"projects/{project}\"", ".", "format", "(", "project", "=", "project", ",", ")" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/keyword_plan_campaign_keyword_service/client.py#L247-L249
mik3y/django-db-multitenant
07e52628007c3d4798122956cecb10adbb691682
mapper_examples/mysql_hostname_tenant_mapper.py
python
SimpleTenantMapper.get_tenant_name
(self, request)
return hostname.split('.')[0]
Takes the first part of the hostname as the tenant
Takes the first part of the hostname as the tenant
[ "Takes", "the", "first", "part", "of", "the", "hostname", "as", "the", "tenant" ]
def get_tenant_name(self, request): """Takes the first part of the hostname as the tenant""" hostname = request.get_host().split(':')[0].lower() return hostname.split('.')[0]
[ "def", "get_tenant_name", "(", "self", ",", "request", ")", ":", "hostname", "=", "request", ".", "get_host", "(", ")", ".", "split", "(", "':'", ")", "[", "0", "]", ".", "lower", "(", ")", "return", "hostname", ".", "split", "(", "'.'", ")", "[", ...
https://github.com/mik3y/django-db-multitenant/blob/07e52628007c3d4798122956cecb10adbb691682/mapper_examples/mysql_hostname_tenant_mapper.py#L15-L18
Telefonica/HomePWN
080398174159f856f4155dcb155c6754d1f85ad8
utils/npyscreen/wgwidget.py
python
Widget.edit
(self)
return self._post_edit()
Allow the user to edit the widget: ie. start handling keypresses.
Allow the user to edit the widget: ie. start handling keypresses.
[ "Allow", "the", "user", "to", "edit", "the", "widget", ":", "ie", ".", "start", "handling", "keypresses", "." ]
def edit(self): """Allow the user to edit the widget: ie. start handling keypresses.""" self.editing = 1 self._pre_edit() self._edit_loop() return self._post_edit()
[ "def", "edit", "(", "self", ")", ":", "self", ".", "editing", "=", "1", "self", ".", "_pre_edit", "(", ")", "self", ".", "_edit_loop", "(", ")", "return", "self", ".", "_post_edit", "(", ")" ]
https://github.com/Telefonica/HomePWN/blob/080398174159f856f4155dcb155c6754d1f85ad8/utils/npyscreen/wgwidget.py#L454-L459
algorhythms/LintCode
2520762a1cfbd486081583136396a2b2cac6e4fb
Subarray Sum II.py
python
Solution.subarraySumII
(self, A, start, end)
return cnt
O(n lg n) Binary Search Bound: f[i] - f[j] = start f[i] - f[j'] = end start < end f[j] > f[j'] :param A: an integer array :param start: start an integer :param end: end an integer :return:
O(n lg n) Binary Search Bound: f[i] - f[j] = start f[i] - f[j'] = end start < end f[j] > f[j']
[ "O", "(", "n", "lg", "n", ")", "Binary", "Search", "Bound", ":", "f", "[", "i", "]", "-", "f", "[", "j", "]", "=", "start", "f", "[", "i", "]", "-", "f", "[", "j", "]", "=", "end", "start", "<", "end", "f", "[", "j", "]", ">", "f", "[...
def subarraySumII(self, A, start, end): """ O(n lg n) Binary Search Bound: f[i] - f[j] = start f[i] - f[j'] = end start < end f[j] > f[j'] :param A: an integer array :param start: start an integer :param end: end an integer :return: """ n = len(A) cnt = 0 f = [0 for _ in xrange(n+1)] for i in xrange(1, n+1): f[i] = f[i-1]+A[i-1] # from left f.sort() for i in xrange(n+1): lo = bisect_left(f, f[i]-end, 0, i) hi = bisect_right(f, f[i]-start, 0, i) cnt += hi-lo # 0----lo----hi-----END return cnt
[ "def", "subarraySumII", "(", "self", ",", "A", ",", "start", ",", "end", ")", ":", "n", "=", "len", "(", "A", ")", "cnt", "=", "0", "f", "=", "[", "0", "for", "_", "in", "xrange", "(", "n", "+", "1", ")", "]", "for", "i", "in", "xrange", ...
https://github.com/algorhythms/LintCode/blob/2520762a1cfbd486081583136396a2b2cac6e4fb/Subarray Sum II.py#L20-L47
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
riak/datadog_checks/riak/riak.py
python
Riak.safe_submit_metric
(self, name, value, tags=None)
[]
def safe_submit_metric(self, name, value, tags=None): tags = [] if tags is None else tags try: self.gauge(name, float(value), tags=tags) return except ValueError: self.log.debug("metric name %s cannot be converted to a float: %s", name, value) pass try: self.gauge(name, unicodedata.numeric(value), tags=tags) return except (TypeError, ValueError): self.log.debug("metric name %s cannot be converted to a float even using unicode tools: %s", name, value) pass
[ "def", "safe_submit_metric", "(", "self", ",", "name", ",", "value", ",", "tags", "=", "None", ")", ":", "tags", "=", "[", "]", "if", "tags", "is", "None", "else", "tags", "try", ":", "self", ".", "gauge", "(", "name", ",", "float", "(", "value", ...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/riak/datadog_checks/riak/riak.py#L74-L88
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twill/twill/other_packages/pyparsing.py
python
ParseResults.items
( self )
return [(k,v[-1][0]) for k,v in self.__tokdict.items()]
Returns all named result keys and values as a list of tuples.
Returns all named result keys and values as a list of tuples.
[ "Returns", "all", "named", "result", "keys", "and", "values", "as", "a", "list", "of", "tuples", "." ]
def items( self ): """Returns all named result keys and values as a list of tuples.""" return [(k,v[-1][0]) for k,v in self.__tokdict.items()]
[ "def", "items", "(", "self", ")", ":", "return", "[", "(", "k", ",", "v", "[", "-", "1", "]", "[", "0", "]", ")", "for", "k", ",", "v", "in", "self", ".", "__tokdict", ".", "items", "(", ")", "]" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twill/twill/other_packages/pyparsing.py#L247-L249
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
SearchService2/appscale/search/solr_adapter.py
python
SolrAdapter.delete_documents
(self, app_id, namespace, index_name, ids)
Deletes documents with specified IDs from the index (asynchronously). Args: app_id: a str representing Application ID. namespace: a str representing GAE namespace or None. index_name: a str representing name of Search API index. ids: a list of document IDs to delete.
Deletes documents with specified IDs from the index (asynchronously).
[ "Deletes", "documents", "with", "specified", "IDs", "from", "the", "index", "(", "asynchronously", ")", "." ]
async def delete_documents(self, app_id, namespace, index_name, ids): """ Deletes documents with specified IDs from the index (asynchronously). Args: app_id: a str representing Application ID. namespace: a str representing GAE namespace or None. index_name: a str representing name of Search API index. ids: a list of document IDs to delete. """ collection = get_collection_name(app_id, namespace, index_name) await self.solr.delete_documents(collection, ids)
[ "async", "def", "delete_documents", "(", "self", ",", "app_id", ",", "namespace", ",", "index_name", ",", "ids", ")", ":", "collection", "=", "get_collection_name", "(", "app_id", ",", "namespace", ",", "index_name", ")", "await", "self", ".", "solr", ".", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/SearchService2/appscale/search/solr_adapter.py#L80-L90
kevoreilly/CAPEv2
6cf79c33264624b3604d4cd432cde2a6b4536de6
modules/processing/parsers/CAPE/Fareit.py
python
config
(memdump_path, read=False)
return res
# Get the aPLib header + data buf = re.findall(r"aPLib .*PWDFILE", cData, re.DOTALL|re.MULTILINE) # Strip out the header if buf and len(buf[0]) > 200: cData = buf[0][200:]
# Get the aPLib header + data buf = re.findall(r"aPLib .*PWDFILE", cData, re.DOTALL|re.MULTILINE) # Strip out the header if buf and len(buf[0]) > 200: cData = buf[0][200:]
[ "#", "Get", "the", "aPLib", "header", "+", "data", "buf", "=", "re", ".", "findall", "(", "r", "aPLib", ".", "*", "PWDFILE", "cData", "re", ".", "DOTALL|re", ".", "MULTILINE", ")", "#", "Strip", "out", "the", "header", "if", "buf", "and", "len", "(...
def config(memdump_path, read=False): res = False if read: F = open(memdump_path, "rb").read() else: F = memdump_path """ # Get the aPLib header + data buf = re.findall(r"aPLib .*PWDFILE", cData, re.DOTALL|re.MULTILINE) # Strip out the header if buf and len(buf[0]) > 200: cData = buf[0][200:] """ artifacts_raw = { "controllers": [], "downloads": [], } start = F.find(b"YUIPWDFILE0YUIPKDFILE0YUICRYPTED0YUI1.0") if start: F = F[start - 600 : start + 500] output = re.findall( b"(https?://.[A-Za-z0-9-\\.\\_\\~\\:\\/\\?\\#\\[\\]\\@\\!\\$\\&'\\(\\)\\*\\+\\,\\;\\=]+(?:\\.php|\\.exe|\\.dll))", F ) for url in output: try: if b"\x00" not in url: # url = self._check_valid_url(url) if url is None: continue if gate_url.match(url): artifacts_raw["controllers"].append(url.lower().decode()) elif exe_url.match(url): artifacts_raw["downloads"].append(url.lower().decode()) elif dll_url.match(url): artifacts_raw["downloads"].append(url.lower().decode()) except Exception as e: print(e, sys.exc_info(), "PONY") artifacts_raw["controllers"] = list(set(artifacts_raw["controllers"])) artifacts_raw["downloads"] = list(set(artifacts_raw["downloads"])) if len(artifacts_raw["controllers"]) != 0 or len(artifacts_raw["downloads"]) != 0: res = artifacts_raw return res
[ "def", "config", "(", "memdump_path", ",", "read", "=", "False", ")", ":", "res", "=", "False", "if", "read", ":", "F", "=", "open", "(", "memdump_path", ",", "\"rb\"", ")", ".", "read", "(", ")", "else", ":", "F", "=", "memdump_path", "artifacts_raw...
https://github.com/kevoreilly/CAPEv2/blob/6cf79c33264624b3604d4cd432cde2a6b4536de6/modules/processing/parsers/CAPE/Fareit.py#L25-L69
aploium/zmirror
f3db3048f83d1ea1bf06a94df312dd30d54b96d3
zmirror/utils.py
python
check_global_ua_pass
(ua_str)
该user-agent是否满足全局白名单
该user-agent是否满足全局白名单
[ "该user", "-", "agent是否满足全局白名单" ]
def check_global_ua_pass(ua_str): """该user-agent是否满足全局白名单""" if ua_str is None or not global_ua_white_name: return False ua_str = ua_str.lower() if global_ua_white_name in ua_str: return True else: return False
[ "def", "check_global_ua_pass", "(", "ua_str", ")", ":", "if", "ua_str", "is", "None", "or", "not", "global_ua_white_name", ":", "return", "False", "ua_str", "=", "ua_str", ".", "lower", "(", ")", "if", "global_ua_white_name", "in", "ua_str", ":", "return", "...
https://github.com/aploium/zmirror/blob/f3db3048f83d1ea1bf06a94df312dd30d54b96d3/zmirror/utils.py#L196-L204
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/nltk/translate/gale_church.py
python
trace
(backlinks, source_sents_lens, target_sents_lens)
return links[::-1]
Traverse the alignment cost from the tracebacks and retrieves appropriate sentence pairs. :param backlinks: A dictionary where the key is the alignment points and value is the cost (referencing the LanguageIndependent.PRIORS) :type backlinks: dict :param source_sents_lens: A list of target sentences' lengths :type source_sents_lens: list(int) :param target_sents_lens: A list of target sentences' lengths :type target_sents_lens: list(int)
Traverse the alignment cost from the tracebacks and retrieves appropriate sentence pairs.
[ "Traverse", "the", "alignment", "cost", "from", "the", "tracebacks", "and", "retrieves", "appropriate", "sentence", "pairs", "." ]
def trace(backlinks, source_sents_lens, target_sents_lens): """ Traverse the alignment cost from the tracebacks and retrieves appropriate sentence pairs. :param backlinks: A dictionary where the key is the alignment points and value is the cost (referencing the LanguageIndependent.PRIORS) :type backlinks: dict :param source_sents_lens: A list of target sentences' lengths :type source_sents_lens: list(int) :param target_sents_lens: A list of target sentences' lengths :type target_sents_lens: list(int) """ links = [] position = (len(source_sents_lens), len(target_sents_lens)) while position != (0, 0) and all(p >= 0 for p in position): try: s, t = backlinks[position] except TypeError: position = (position[0] - 1, position[1] - 1) continue for i in range(s): for j in range(t): links.append((position[0] - i - 1, position[1] - j - 1)) position = (position[0] - s, position[1] - t) return links[::-1]
[ "def", "trace", "(", "backlinks", ",", "source_sents_lens", ",", "target_sents_lens", ")", ":", "links", "=", "[", "]", "position", "=", "(", "len", "(", "source_sents_lens", ")", ",", "len", "(", "target_sents_lens", ")", ")", "while", "position", "!=", "...
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/translate/gale_church.py#L96-L121
jay0lee/got-your-back
54c6119c0e78502fa5c92d5354f80a4a95a6e3e6
gyb.py
python
_createHttpObj
(cache=None, timeout=None)
return httplib2.Http(**http_args)
[]
def _createHttpObj(cache=None, timeout=None): http_args = {'cache': cache, 'timeout': timeout} if 'tls_maximum_version' in options: http_args['tls_maximum_version'] = options.tls_maximum_version if 'tls_minimum_version' in options: http_args['tls_minimum_version'] = options.tls_minimum_version return httplib2.Http(**http_args)
[ "def", "_createHttpObj", "(", "cache", "=", "None", ",", "timeout", "=", "None", ")", ":", "http_args", "=", "{", "'cache'", ":", "cache", ",", "'timeout'", ":", "timeout", "}", "if", "'tls_maximum_version'", "in", "options", ":", "http_args", "[", "'tls_m...
https://github.com/jay0lee/got-your-back/blob/54c6119c0e78502fa5c92d5354f80a4a95a6e3e6/gyb.py#L1609-L1615
SforAiDl/Neural-Voice-Cloning-With-Few-Samples
33fb609427657c9492f46507184ecba4dcc272b0
speaker_adaptatation-libri.py
python
MaskedL1Loss.__init__
(self)
[]
def __init__(self): super(MaskedL1Loss, self).__init__() self.criterion = nn.L1Loss(size_average=False)
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "MaskedL1Loss", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "criterion", "=", "nn", ".", "L1Loss", "(", "size_average", "=", "False", ")" ]
https://github.com/SforAiDl/Neural-Voice-Cloning-With-Few-Samples/blob/33fb609427657c9492f46507184ecba4dcc272b0/speaker_adaptatation-libri.py#L304-L306
ProtonVPN/linux-cli
3f4bea1b8a12ed6a31654cc184021ddab6dd56e6
protonvpn_cli/cli.py
python
ProtonVPNCLI.disconnect
(self)
return self.cli_wrapper.disconnect()
Disconnect from ProtonVPN.
Disconnect from ProtonVPN.
[ "Disconnect", "from", "ProtonVPN", "." ]
def disconnect(self): """Disconnect from ProtonVPN.""" return self.cli_wrapper.disconnect()
[ "def", "disconnect", "(", "self", ")", ":", "return", "self", ".", "cli_wrapper", ".", "disconnect", "(", ")" ]
https://github.com/ProtonVPN/linux-cli/blob/3f4bea1b8a12ed6a31654cc184021ddab6dd56e6/protonvpn_cli/cli.py#L139-L141
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/boto-2.46.1/boto/dynamodb2/table.py
python
Table.batch_write
(self)
return BatchTable(self)
Allows the batching of writes to DynamoDB. Since each write/delete call to DynamoDB has a cost associated with it, when loading lots of data, it makes sense to batch them, creating as few calls as possible. This returns a context manager that will transparently handle creating these batches. The object you get back lightly-resembles a ``Table`` object, sharing just the ``put_item`` & ``delete_item`` methods (which are all that DynamoDB can batch in terms of writing data). DynamoDB's maximum batch size is 25 items per request. If you attempt to put/delete more than that, the context manager will batch as many as it can up to that number, then flush them to DynamoDB & continue batching as more calls come in. Example:: # Assuming a table with one record... >>> with users.batch_write() as batch: ... batch.put_item(data={ ... 'username': 'johndoe', ... 'first_name': 'John', ... 'last_name': 'Doe', ... 'owner': 1, ... }) ... # Nothing across the wire yet. ... batch.delete_item(username='bob') ... # Still no requests sent. ... batch.put_item(data={ ... 'username': 'jane', ... 'first_name': 'Jane', ... 'last_name': 'Doe', ... 'date_joined': 127436192, ... }) ... # Nothing yet, but once we leave the context, the ... # put/deletes will be sent.
Allows the batching of writes to DynamoDB.
[ "Allows", "the", "batching", "of", "writes", "to", "DynamoDB", "." ]
def batch_write(self): """ Allows the batching of writes to DynamoDB. Since each write/delete call to DynamoDB has a cost associated with it, when loading lots of data, it makes sense to batch them, creating as few calls as possible. This returns a context manager that will transparently handle creating these batches. The object you get back lightly-resembles a ``Table`` object, sharing just the ``put_item`` & ``delete_item`` methods (which are all that DynamoDB can batch in terms of writing data). DynamoDB's maximum batch size is 25 items per request. If you attempt to put/delete more than that, the context manager will batch as many as it can up to that number, then flush them to DynamoDB & continue batching as more calls come in. Example:: # Assuming a table with one record... >>> with users.batch_write() as batch: ... batch.put_item(data={ ... 'username': 'johndoe', ... 'first_name': 'John', ... 'last_name': 'Doe', ... 'owner': 1, ... }) ... # Nothing across the wire yet. ... batch.delete_item(username='bob') ... # Still no requests sent. ... batch.put_item(data={ ... 'username': 'jane', ... 'first_name': 'Jane', ... 'last_name': 'Doe', ... 'date_joined': 127436192, ... }) ... # Nothing yet, but once we leave the context, the ... # put/deletes will be sent. """ # PHENOMENAL COSMIC DOCS!!! itty-bitty code. return BatchTable(self)
[ "def", "batch_write", "(", "self", ")", ":", "# PHENOMENAL COSMIC DOCS!!! itty-bitty code.", "return", "BatchTable", "(", "self", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/boto-2.46.1/boto/dynamodb2/table.py#L946-L988
carbonblack/cbapi-python
24d677ffd99aee911c2c76ecb5528e4e9320c7cc
src/cbapi/six.py
python
add_metaclass
(metaclass)
return wrapper
Class decorator for creating a class with a metaclass.
Class decorator for creating a class with a metaclass.
[ "Class", "decorator", "for", "creating", "a", "class", "with", "a", "metaclass", "." ]
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper
[ "def", "add_metaclass", "(", "metaclass", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "orig_vars", "=", "cls", ".", "__dict__", ".", "copy", "(", ")", "slots", "=", "orig_vars", ".", "get", "(", "'__slots__'", ")", "if", "slots", "is", "not", "...
https://github.com/carbonblack/cbapi-python/blob/24d677ffd99aee911c2c76ecb5528e4e9320c7cc/src/cbapi/six.py#L814-L827
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/difflib.py
python
Differ.__init__
(self, linejunk=None, charjunk=None)
Construct a text differencer, with optional filters. The two optional keyword parameters are for filter functions: - `linejunk`: A function that should accept a single string argument, and return true iff the string is junk. The module-level function `IS_LINE_JUNK` may be used to filter out lines without visible characters, except for at most one splat ('#'). It is recommended to leave linejunk None; as of Python 2.3, the underlying SequenceMatcher class has grown an adaptive notion of "noise" lines that's better than any static definition the author has ever been able to craft. - `charjunk`: A function that should accept a string of length 1. The module-level function `IS_CHARACTER_JUNK` may be used to filter out whitespace characters (a blank or tab; **note**: bad idea to include newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Construct a text differencer, with optional filters.
[ "Construct", "a", "text", "differencer", "with", "optional", "filters", "." ]
def __init__(self, linejunk=None, charjunk=None): """ Construct a text differencer, with optional filters. The two optional keyword parameters are for filter functions: - `linejunk`: A function that should accept a single string argument, and return true iff the string is junk. The module-level function `IS_LINE_JUNK` may be used to filter out lines without visible characters, except for at most one splat ('#'). It is recommended to leave linejunk None; as of Python 2.3, the underlying SequenceMatcher class has grown an adaptive notion of "noise" lines that's better than any static definition the author has ever been able to craft. - `charjunk`: A function that should accept a string of length 1. The module-level function `IS_CHARACTER_JUNK` may be used to filter out whitespace characters (a blank or tab; **note**: bad idea to include newline in this!). Use of IS_CHARACTER_JUNK is recommended. """ self.linejunk = linejunk self.charjunk = charjunk
[ "def", "__init__", "(", "self", ",", "linejunk", "=", "None", ",", "charjunk", "=", "None", ")", ":", "self", ".", "linejunk", "=", "linejunk", "self", ".", "charjunk", "=", "charjunk" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/difflib.py#L858-L880
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Base/Scripts/CommonServerPython/CommonServerPython.py
python
GetDemistoVersion.__call__
(self)
return self._version
Returns the Demisto version and build number. :return: Demisto version object if Demisto class has attribute demistoVersion, else raises AttributeError :rtype: ``dict``
Returns the Demisto version and build number.
[ "Returns", "the", "Demisto", "version", "and", "build", "number", "." ]
def __call__(self): """Returns the Demisto version and build number. :return: Demisto version object if Demisto class has attribute demistoVersion, else raises AttributeError :rtype: ``dict`` """ if self._version is None: if hasattr(demisto, 'demistoVersion'): self._version = demisto.demistoVersion() else: raise AttributeError('demistoVersion attribute not found.') return self._version
[ "def", "__call__", "(", "self", ")", ":", "if", "self", ".", "_version", "is", "None", ":", "if", "hasattr", "(", "demisto", ",", "'demistoVersion'", ")", ":", "self", ".", "_version", "=", "demisto", ".", "demistoVersion", "(", ")", "else", ":", "rais...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Base/Scripts/CommonServerPython/CommonServerPython.py#L6801-L6812
Zephery/weiboanalysis
bee35996ffdf9f6c4bb9af349f6d4dce6666b6ab
train/boostNB.py
python
setOfWordsToVecTor
(vocabularyList, moodWords)
return np.array(vocabMarked)
SMS内容匹配预料库,标记预料库的词汇出现的次数 :param vocabularyList: :param moodWords: :return:
SMS内容匹配预料库,标记预料库的词汇出现的次数 :param vocabularyList: :param moodWords: :return:
[ "SMS内容匹配预料库,标记预料库的词汇出现的次数", ":", "param", "vocabularyList", ":", ":", "param", "moodWords", ":", ":", "return", ":" ]
def setOfWordsToVecTor(vocabularyList, moodWords): """ SMS内容匹配预料库,标记预料库的词汇出现的次数 :param vocabularyList: :param moodWords: :return: """ vocabMarked = [0] * len(vocabularyList) for smsWord in moodWords: if smsWord in vocabularyList: vocabMarked[vocabularyList.index(smsWord)] += 1 return np.array(vocabMarked)
[ "def", "setOfWordsToVecTor", "(", "vocabularyList", ",", "moodWords", ")", ":", "vocabMarked", "=", "[", "0", "]", "*", "len", "(", "vocabularyList", ")", "for", "smsWord", "in", "moodWords", ":", "if", "smsWord", "in", "vocabularyList", ":", "vocabMarked", ...
https://github.com/Zephery/weiboanalysis/blob/bee35996ffdf9f6c4bb9af349f6d4dce6666b6ab/train/boostNB.py#L66-L77
oddt/oddt
8cf555820d97a692ade81c101ebe10e28bcb3722
oddt/toolkits/rdk.py
python
Residue.idx
(self)
return self._idx
Internal index (0-based) of the Residue
Internal index (0-based) of the Residue
[ "Internal", "index", "(", "0", "-", "based", ")", "of", "the", "Residue" ]
def idx(self): """Internal index (0-based) of the Residue""" return self._idx
[ "def", "idx", "(", "self", ")", ":", "return", "self", ".", "_idx" ]
https://github.com/oddt/oddt/blob/8cf555820d97a692ade81c101ebe10e28bcb3722/oddt/toolkits/rdk.py#L1446-L1448
mne-tools/mne-python
f90b303ce66a8415e64edd4605b09ac0179c1ebf
mne/viz/_figure.py
python
_get_browser
(**kwargs)
return browser
Instantiate a new MNE browse-style figure.
Instantiate a new MNE browse-style figure.
[ "Instantiate", "a", "new", "MNE", "browse", "-", "style", "figure", "." ]
def _get_browser(**kwargs): """Instantiate a new MNE browse-style figure.""" from .utils import _get_figsize_from_config figsize = kwargs.setdefault('figsize', _get_figsize_from_config()) if figsize is None or np.any(np.array(figsize) < 8): kwargs['figsize'] = (8, 8) # Initialize browser backend _init_browser_backend() # Initialize Browser browser = backend._init_browser(**kwargs) return browser
[ "def", "_get_browser", "(", "*", "*", "kwargs", ")", ":", "from", ".", "utils", "import", "_get_figsize_from_config", "figsize", "=", "kwargs", ".", "setdefault", "(", "'figsize'", ",", "_get_figsize_from_config", "(", ")", ")", "if", "figsize", "is", "None", ...
https://github.com/mne-tools/mne-python/blob/f90b303ce66a8415e64edd4605b09ac0179c1ebf/mne/viz/_figure.py#L604-L616
TensorSpeech/TensorflowTTS
34358d82a4c91fd70344872f8ea8a405ea84aedb
tensorflow_tts/models/mb_melgan.py
python
TFPQMF.synthesis
(self, x)
return tf.nn.conv1d(x, self.synthesis_filter, stride=1, padding="VALID")
Synthesis with PQMF. Args: x (Tensor): Input tensor (B, T // subbands, subbands). Returns: Tensor: Output tensor (B, T, 1).
Synthesis with PQMF. Args: x (Tensor): Input tensor (B, T // subbands, subbands). Returns: Tensor: Output tensor (B, T, 1).
[ "Synthesis", "with", "PQMF", ".", "Args", ":", "x", "(", "Tensor", ")", ":", "Input", "tensor", "(", "B", "T", "//", "subbands", "subbands", ")", ".", "Returns", ":", "Tensor", ":", "Output", "tensor", "(", "B", "T", "1", ")", "." ]
def synthesis(self, x): """Synthesis with PQMF. Args: x (Tensor): Input tensor (B, T // subbands, subbands). Returns: Tensor: Output tensor (B, T, 1). """ x = tf.nn.conv1d_transpose( x, self.updown_filter * self.subbands, strides=self.subbands, output_shape=( tf.shape(x)[0], tf.shape(x)[1] * self.subbands, self.subbands, ), ) x = tf.pad(x, [[0, 0], [self.taps // 2, self.taps // 2], [0, 0]]) return tf.nn.conv1d(x, self.synthesis_filter, stride=1, padding="VALID")
[ "def", "synthesis", "(", "self", ",", "x", ")", ":", "x", "=", "tf", ".", "nn", ".", "conv1d_transpose", "(", "x", ",", "self", ".", "updown_filter", "*", "self", ".", "subbands", ",", "strides", "=", "self", ".", "subbands", ",", "output_shape", "="...
https://github.com/TensorSpeech/TensorflowTTS/blob/34358d82a4c91fd70344872f8ea8a405ea84aedb/tensorflow_tts/models/mb_melgan.py#L139-L157
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/config/user.py
python
MultiUserConfig.remove_section
(self, section)
Remove `section` and all options within it.
Remove `section` and all options within it.
[ "Remove", "section", "and", "all", "options", "within", "it", "." ]
def remove_section(self, section): """Remove `section` and all options within it.""" config = self._get_config(section, None) config.remove_section(section)
[ "def", "remove_section", "(", "self", ",", "section", ")", ":", "config", "=", "self", ".", "_get_config", "(", "section", ",", "None", ")", "config", ".", "remove_section", "(", "section", ")" ]
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/config/user.py#L997-L1000
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
libs/codeintel2/lang_javascript.py
python
JavaScriptCiler.incBlock
(self)
Increment the block (scope) count
Increment the block (scope) count
[ "Increment", "the", "block", "(", "scope", ")", "count" ]
def incBlock(self): """Increment the block (scope) count""" self.depth = self.depth+1 log.debug("incBlock: depth:%d, line:%d, currentScope:%r", self.depth, self.lineno, self.currentScope.name) if not self.currentScope: log.debug( "incBlock:: No currentScope available. Defaulting to global file scope.") # Use the global file scope then self.currentScope = self.cile if len(self.objectStack) == 0 or self.currentScope != self.objectStack[-1]: # Not the same scope... self.objectStack.append(self.currentScope) self._scopeStack.append(self.currentScope)
[ "def", "incBlock", "(", "self", ")", ":", "self", ".", "depth", "=", "self", ".", "depth", "+", "1", "log", ".", "debug", "(", "\"incBlock: depth:%d, line:%d, currentScope:%r\"", ",", "self", ".", "depth", ",", "self", ".", "lineno", ",", "self", ".", "c...
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/codeintel2/lang_javascript.py#L1936-L1949
danielfrg/copper
956e9ae607aec461d4fe4f6e7b0ccd9ed556fc79
copper/ml/gdbn/npmat.py
python
CUDAMatrix.set_selected_columns
(self, indices, source)
return self
copies all columns of source into some columns of self. <indices> must be a row vector. Its elements are float32's representing integers, e.g. "34.0" means the integer "34". after this call, for all r,c, self[r,indices[c]]=source[r,c]. This returns self. Negative indices are interpreted in the usual Python way: all elements of <indices> had better be in the range [-self.shape[1], self.shape[1]-1]. This does bounds checking, but out of bounds indices do not raise an exception (because the programmer was lazy). Instead, they result in NaN values in <self>.
copies all columns of source into some columns of self. <indices> must be a row vector. Its elements are float32's representing integers, e.g. "34.0" means the integer "34". after this call, for all r,c, self[r,indices[c]]=source[r,c]. This returns self. Negative indices are interpreted in the usual Python way: all elements of <indices> had better be in the range [-self.shape[1], self.shape[1]-1]. This does bounds checking, but out of bounds indices do not raise an exception (because the programmer was lazy). Instead, they result in NaN values in <self>.
[ "copies", "all", "columns", "of", "source", "into", "some", "columns", "of", "self", ".", "<indices", ">", "must", "be", "a", "row", "vector", ".", "Its", "elements", "are", "float32", "s", "representing", "integers", "e", ".", "g", ".", "34", ".", "0"...
def set_selected_columns(self, indices, source): """ copies all columns of source into some columns of self. <indices> must be a row vector. Its elements are float32's representing integers, e.g. "34.0" means the integer "34". after this call, for all r,c, self[r,indices[c]]=source[r,c]. This returns self. Negative indices are interpreted in the usual Python way: all elements of <indices> had better be in the range [-self.shape[1], self.shape[1]-1]. This does bounds checking, but out of bounds indices do not raise an exception (because the programmer was lazy). Instead, they result in NaN values in <self>. """ assert self.shape[0]==source.shape[0] assert indices.shape[0]==1 assert indices.shape[1]==source.shape[1] for c in range(source.shape[1]): try: self.numpy_array[:,int(indices.numpy_array.ravel()[c])] = source.numpy_array[:,c] except IndexError: self.numpy_array[:,int(indices.numpy_array.ravel()[c])] = np.nan return self
[ "def", "set_selected_columns", "(", "self", ",", "indices", ",", "source", ")", ":", "assert", "self", ".", "shape", "[", "0", "]", "==", "source", ".", "shape", "[", "0", "]", "assert", "indices", ".", "shape", "[", "0", "]", "==", "1", "assert", ...
https://github.com/danielfrg/copper/blob/956e9ae607aec461d4fe4f6e7b0ccd9ed556fc79/copper/ml/gdbn/npmat.py#L165-L187
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/detr/modeling_detr.py
python
NestedTensor.to
(self, device)
return NestedTensor(cast_tensor, cast_mask)
[]
def to(self, device): # type: (Device) -> NestedTensor # noqa cast_tensor = self.tensors.to(device) mask = self.mask if mask is not None: cast_mask = mask.to(device) else: cast_mask = None return NestedTensor(cast_tensor, cast_mask)
[ "def", "to", "(", "self", ",", "device", ")", ":", "# type: (Device) -> NestedTensor # noqa", "cast_tensor", "=", "self", ".", "tensors", ".", "to", "(", "device", ")", "mask", "=", "self", ".", "mask", "if", "mask", "is", "not", "None", ":", "cast_mask", ...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/detr/modeling_detr.py#L2234-L2242
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/volatility-2.3/build/lib/volatility/plugins/vadinfo.py
python
VADInfo.write_vad_control
(self, outfd, vad)
Renders a text version of a (non-short) Vad's control information
Renders a text version of a (non-short) Vad's control information
[ "Renders", "a", "text", "version", "of", "a", "(", "non", "-", "short", ")", "Vad", "s", "control", "information" ]
def write_vad_control(self, outfd, vad): """Renders a text version of a (non-short) Vad's control information""" # even if the ControlArea is not NULL, it is only meaningful # for shared (non private) memory sections. if vad.u.VadFlags.PrivateMemory == 1: return control_area = vad.ControlArea if not control_area: return outfd.write("ControlArea @{0:08x} Segment {1:08x}\n".format(control_area.dereference().obj_offset, control_area.Segment)) outfd.write("Dereference list: Flink {0:08x}, Blink {1:08x}\n".format(control_area.DereferenceList.Flink, control_area.DereferenceList.Blink)) outfd.write("NumberOfSectionReferences: {0:10} NumberOfPfnReferences: {1:10}\n".format(control_area.NumberOfSectionReferences, control_area.NumberOfPfnReferences)) outfd.write("NumberOfMappedViews: {0:10} NumberOfUserReferences: {1:10}\n".format(control_area.NumberOfMappedViews, control_area.NumberOfUserReferences)) outfd.write("WaitingForDeletion Event: {0:08x}\n".format(control_area.WaitingForDeletion)) outfd.write("Control Flags: {0}\n".format(str(control_area.u.Flags))) file_object = vad.FileObject if file_object: outfd.write("FileObject @{0:08x}, Name: {1}\n".format(file_object.obj_offset, str(file_object.FileName or '')))
[ "def", "write_vad_control", "(", "self", ",", "outfd", ",", "vad", ")", ":", "# even if the ControlArea is not NULL, it is only meaningful ", "# for shared (non private) memory sections. ", "if", "vad", ".", "u", ".", "VadFlags", ".", "PrivateMemory", "==", "1", ":", "r...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/volatility-2.3/build/lib/volatility/plugins/vadinfo.py#L138-L160
selfteaching/selfteaching-python-camp
9982ee964b984595e7d664b07c389cddaf158f1e
19100101/zhwycsz/d6_exercise_stats_word.py
python
stats_text_en
(string_en)
统计英文词频 第一步:过滤英文字符,并将string拆分为list。 第二步:清理标点符号。 第三步:使用collections库中的Counter函数进行词频统计并输出结果。
统计英文词频 第一步:过滤英文字符,并将string拆分为list。 第二步:清理标点符号。 第三步:使用collections库中的Counter函数进行词频统计并输出结果。
[ "统计英文词频", "第一步:过滤英文字符,并将string拆分为list。", "第二步:清理标点符号。", "第三步:使用collections库中的Counter函数进行词频统计并输出结果。" ]
def stats_text_en(string_en): ''' 统计英文词频 第一步:过滤英文字符,并将string拆分为list。 第二步:清理标点符号。 第三步:使用collections库中的Counter函数进行词频统计并输出结果。 ''' result = re.sub("[^A-Za-z]", " ", string_en.strip()) #正则表达式 去匹配目标字符串中非a—z也非A—Z的字符 newList = result.split( ) #字符分割 i=0 for i in range(0,len(newList)): #len()得到string的长度 newList[i]=newList[i].strip('*-,.?!') if newList[i]==' ': newList[i].remove(' ') #用于移除列表中某个值的第一个匹配项,去除标点 else: i=i+1 #i+1 继续赋值给i print('1.英文词频统计结果: ',collections.Counter(newList),'\t')
[ "def", "stats_text_en", "(", "string_en", ")", ":", "result", "=", "re", ".", "sub", "(", "\"[^A-Za-z]\"", ",", "\" \"", ",", "string_en", ".", "strip", "(", ")", ")", "#正则表达式 去匹配目标字符串中非a—z也非A—Z的字符", "newList", "=", "result", ".", "split", "(", ")", "#字符分割...
https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/19100101/zhwycsz/d6_exercise_stats_word.py#L28-L43
WerWolv/EdiZon_CheatsConfigsAndScripts
d16d36c7509c01dca770f402babd83ff2e9ae6e7
Scripts/lib/python3.5/datetime.py
python
date.__sub__
(self, other)
return NotImplemented
Subtract two dates, or a date and a timedelta.
Subtract two dates, or a date and a timedelta.
[ "Subtract", "two", "dates", "or", "a", "date", "and", "a", "timedelta", "." ]
def __sub__(self, other): """Subtract two dates, or a date and a timedelta.""" if isinstance(other, timedelta): return self + timedelta(-other.days) if isinstance(other, date): days1 = self.toordinal() days2 = other.toordinal() return timedelta(days1 - days2) return NotImplemented
[ "def", "__sub__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "timedelta", ")", ":", "return", "self", "+", "timedelta", "(", "-", "other", ".", "days", ")", "if", "isinstance", "(", "other", ",", "date", ")", ":", "...
https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/datetime.py#L867-L875
dictation-toolbox/Caster
6c57587cbba783fd5b9e0a5e49e5957c9f73c22c
castervoice/lib/util/pathlib/__init__.py
python
PurePath.is_reserved
(self)
return self._flavour.is_reserved(self._parts)
Return True if the path contains one of the special names reserved by the system, if any.
Return True if the path contains one of the special names reserved by the system, if any.
[ "Return", "True", "if", "the", "path", "contains", "one", "of", "the", "special", "names", "reserved", "by", "the", "system", "if", "any", "." ]
def is_reserved(self): """Return True if the path contains one of the special names reserved by the system, if any.""" return self._flavour.is_reserved(self._parts)
[ "def", "is_reserved", "(", "self", ")", ":", "return", "self", ".", "_flavour", ".", "is_reserved", "(", "self", ".", "_parts", ")" ]
https://github.com/dictation-toolbox/Caster/blob/6c57587cbba783fd5b9e0a5e49e5957c9f73c22c/castervoice/lib/util/pathlib/__init__.py#L1186-L1189
firedrakeproject/firedrake
06ab4975c14c0d4dcb79be55821f8b9e41554125
firedrake/functionspacedata.py
python
set_max_work_functions
(V, val)
Set the maximum number of work functions. :arg V: The function space to set the number of work functions for. :arg val: The new maximum number of work functions. This number is shared between all function spaces with the same :meth:`~.FunctionSpace.ufl_element` and :meth:`~FunctionSpace.mesh`.
Set the maximum number of work functions.
[ "Set", "the", "maximum", "number", "of", "work", "functions", "." ]
def set_max_work_functions(V, val): """Set the maximum number of work functions. :arg V: The function space to set the number of work functions for. :arg val: The new maximum number of work functions. This number is shared between all function spaces with the same :meth:`~.FunctionSpace.ufl_element` and :meth:`~FunctionSpace.mesh`. """ mesh = V.mesh() assert hasattr(mesh, "_shared_data_cache") cache = mesh._shared_data_cache["max_work_functions"] cache[V.ufl_element()] = val
[ "def", "set_max_work_functions", "(", "V", ",", "val", ")", ":", "mesh", "=", "V", ".", "mesh", "(", ")", "assert", "hasattr", "(", "mesh", ",", "\"_shared_data_cache\"", ")", "cache", "=", "mesh", ".", "_shared_data_cache", "[", "\"max_work_functions\"", "]...
https://github.com/firedrakeproject/firedrake/blob/06ab4975c14c0d4dcb79be55821f8b9e41554125/firedrake/functionspacedata.py#L351-L365
mozilla/moztrap
93b34a4cd21c9e08f73d3b1a7630cd873f8418a0
moztrap/view/manage/runs/forms.py
python
RunForm.clean_build
(self)
If this is a series, then null out the build field.
If this is a series, then null out the build field.
[ "If", "this", "is", "a", "series", "then", "null", "out", "the", "build", "field", "." ]
def clean_build(self): """If this is a series, then null out the build field.""" if self.cleaned_data["is_series"]: return None
[ "def", "clean_build", "(", "self", ")", ":", "if", "self", ".", "cleaned_data", "[", "\"is_series\"", "]", ":", "return", "None" ]
https://github.com/mozilla/moztrap/blob/93b34a4cd21c9e08f73d3b1a7630cd873f8418a0/moztrap/view/manage/runs/forms.py#L89-L92
joxeankoret/diaphora
dcb5a25ac9fe23a285b657e5389cf770de7ac928
jkutils/graph_hashes.py
python
CKoretKaramitasHash.calculate
(self, f)
return str(hash)
[]
def calculate(self, f): func = get_func(f) if func is None: return "NO-FUNCTION" flow = FlowChart(func) if flow is None: return "NO-FLOW-GRAPH" hash = 1 # Variables required for calculations of previous ones bb_relations = {} # Iterate through each basic block for block in flow: block_ea = block.start_ea if block.end_ea == 0: continue succs = list(block.succs()) preds = list(block.preds()) hash *= self.get_node_value(len(succs), len(preds)) hash *= self.get_edges_value(block, succs, preds) # ...and each instruction on each basic block for ea in list(Heads(block.start_ea, block.end_ea)): if self.is_call_insn(ea): hash *= FEATURE_CALL l = list(DataRefsFrom(ea)) if len(l) > 0: hash *= FEATURE_DATA_REFS for xref in CodeRefsFrom(ea, 0): tmp_func = get_func(xref) if tmp_func is None or tmp_func.start_ea != func.start_ea: hash *= FEATURE_CALL_REF # Remember the relationships bb_relations[block_ea] = [] # Iterate the succesors of this basic block for succ_block in block.succs(): bb_relations[block_ea].append(succ_block.start_ea) # Iterate the predecessors of this basic block for pred_block in block.preds(): try: bb_relations[pred_block.start_ea].append(block.start_ea) except KeyError: bb_relations[pred_block.start_ea] = [block.start_ea] # Calculate the strongly connected components try: strongly_connected = strongly_connected_components(bb_relations) # ...and get the number of loops out of it for sc in strongly_connected: if len(sc) > 1: hash *= FEATURE_LOOP else: if sc[0] in bb_relations and sc[0] in bb_relations[sc[0]]: hash *= FEATURE_LOOP # And, also, use the number of strongly connected components # to calculate another part of the hash. hash *= (FEATURE_STRONGLY_CONNECTED ** len(strongly_connected)) except: print("Exception:", str(sys.exc_info()[1])) flags = get_func_attr(f, FUNCATTR_FLAGS) if flags & FUNC_NORET: hash *= FEATURE_FUNC_NO_RET if flags & FUNC_LIB: hash *= FEATURE_FUNC_LIB if flags & FUNC_THUNK: hash *= FEATURE_FUNC_THUNK return str(hash)
[ "def", "calculate", "(", "self", ",", "f", ")", ":", "func", "=", "get_func", "(", "f", ")", "if", "func", "is", "None", ":", "return", "\"NO-FUNCTION\"", "flow", "=", "FlowChart", "(", "func", ")", "if", "flow", "is", "None", ":", "return", "\"NO-FL...
https://github.com/joxeankoret/diaphora/blob/dcb5a25ac9fe23a285b657e5389cf770de7ac928/jkutils/graph_hashes.py#L100-L180
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/flask/app.py
python
Flask.url_value_preprocessor
(self, f)
return f
Registers a function as URL value preprocessor for all view functions of the application. It's called before the view functions are called and can modify the url values provided.
Registers a function as URL value preprocessor for all view functions of the application. It's called before the view functions are called and can modify the url values provided.
[ "Registers", "a", "function", "as", "URL", "value", "preprocessor", "for", "all", "view", "functions", "of", "the", "application", ".", "It", "s", "called", "before", "the", "view", "functions", "are", "called", "and", "can", "modify", "the", "url", "values"...
def url_value_preprocessor(self, f): """Registers a function as URL value preprocessor for all view functions of the application. It's called before the view functions are called and can modify the url values provided. """ self.url_value_preprocessors.setdefault(None, []).append(f) return f
[ "def", "url_value_preprocessor", "(", "self", ",", "f", ")", ":", "self", ".", "url_value_preprocessors", ".", "setdefault", "(", "None", ",", "[", "]", ")", ".", "append", "(", "f", ")", "return", "f" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/flask/app.py#L1295-L1301
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/asn1crypto-0.24.0/asn1crypto/core.py
python
ObjectIdentifier.native
(self)
return self._native
The a native Python datatype representation of this value :return: A unicode string or None. If _map is not defined, the unicode string is a string of dotted integers. If _map is defined and the dotted string is present in the _map, the mapped value is returned.
The a native Python datatype representation of this value
[ "The", "a", "native", "Python", "datatype", "representation", "of", "this", "value" ]
def native(self): """ The a native Python datatype representation of this value :return: A unicode string or None. If _map is not defined, the unicode string is a string of dotted integers. If _map is defined and the dotted string is present in the _map, the mapped value is returned. """ if self.contents is None: return None if self._native is None: self._native = self.dotted if self._map is not None and self._native in self._map: self._native = self._map[self._native] return self._native
[ "def", "native", "(", "self", ")", ":", "if", "self", ".", "contents", "is", "None", ":", "return", "None", "if", "self", ".", "_native", "is", "None", ":", "self", ".", "_native", "=", "self", ".", "dotted", "if", "self", ".", "_map", "is", "not",...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/asn1crypto-0.24.0/asn1crypto/core.py#L2920-L2937
donnemartin/viz
dc1ed0690ed3d8cb515c9dbac43bafc59a704789
githubstats/github_stats.py
python
GitHubStats.generate_search_query
(self, language, creation_date_filter=None, stars_filter=None)
return query
Generates the GitHub search query. :type language: str :param language: The current language. :type creation_date_filter: str (optional) :param creation_date_filter: The repo creation date filter. :type stars_filter: str :param stars_filter: The stars filter. :rtype: str :return: The GitHub search query.
Generates the GitHub search query.
[ "Generates", "the", "GitHub", "search", "query", "." ]
def generate_search_query(self, language, creation_date_filter=None, stars_filter=None): """Generates the GitHub search query. :type language: str :param language: The current language. :type creation_date_filter: str (optional) :param creation_date_filter: The repo creation date filter. :type stars_filter: str :param stars_filter: The stars filter. :rtype: str :return: The GitHub search query. """ if creation_date_filter is None: creation_date_filter = 'created:>=2017-01-01' if stars_filter is None: stars_filter = 'stars:>=' + str(self.CFG_MIN_STARS) query = (creation_date_filter + ' ' + stars_filter + ' language:' + language.lower()) return query
[ "def", "generate_search_query", "(", "self", ",", "language", ",", "creation_date_filter", "=", "None", ",", "stars_filter", "=", "None", ")", ":", "if", "creation_date_filter", "is", "None", ":", "creation_date_filter", "=", "'created:>=2017-01-01'", "if", "stars_f...
https://github.com/donnemartin/viz/blob/dc1ed0690ed3d8cb515c9dbac43bafc59a704789/githubstats/github_stats.py#L260-L283
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/numpy/ma/timer_comparison.py
python
ModuleTester.test_2
(self)
Tests conversions and indexing.
Tests conversions and indexing.
[ "Tests", "conversions", "and", "indexing", "." ]
def test_2(self): """ Tests conversions and indexing. """ x1 = np.array([1, 2, 4, 3]) x2 = self.array(x1, mask=[1, 0, 0, 0]) x3 = self.array(x1, mask=[0, 1, 0, 1]) x4 = self.array(x1) # test conversion to strings, no errors str(x2) repr(x2) # tests of indexing assert type(x2[1]) is type(x1[1]) assert x1[1] == x2[1] x1[2] = 9 x2[2] = 9 self.assert_array_equal(x1, x2) x1[1:3] = 99 x2[1:3] = 99 x2[1] = self.masked x2[1:3] = self.masked x2[:] = x1 x2[1] = self.masked x3[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0]) x4[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0]) x1 = np.arange(5)*1.0 x2 = self.masked_values(x1, 3.0) x1 = self.array([1, 'hello', 2, 3], object) x2 = np.array([1, 'hello', 2, 3], object) # check that no error occurs. x1[1] x2[1] assert x1[1:1].shape == (0,) # Tests copy-size n = [0, 0, 1, 0, 0] m = self.make_mask(n) m2 = self.make_mask(m) assert(m is m2) m3 = self.make_mask(m, copy=1) assert(m is not m3)
[ "def", "test_2", "(", "self", ")", ":", "x1", "=", "np", ".", "array", "(", "[", "1", ",", "2", ",", "4", ",", "3", "]", ")", "x2", "=", "self", ".", "array", "(", "x1", ",", "mask", "=", "[", "1", ",", "0", ",", "0", ",", "0", "]", "...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/numpy/ma/timer_comparison.py#L154-L194
espeed/bulbs
628e5b14f0249f9ca4fa1ceea6f2af2dca45f75a
bulbs/rexster/client.py
python
RexsterClient.gremlin
(self, script, params=None, load=None)
return self.request.post(gremlin_path, params)
Executes a Gremlin script and returns the Response. :param script: Gremlin script to execute. :type script: str :param params: Param bindings for the script. :type params: dict :rtype: RexsterResponse
Executes a Gremlin script and returns the Response.
[ "Executes", "a", "Gremlin", "script", "and", "returns", "the", "Response", "." ]
def gremlin(self, script, params=None, load=None): """ Executes a Gremlin script and returns the Response. :param script: Gremlin script to execute. :type script: str :param params: Param bindings for the script. :type params: dict :rtype: RexsterResponse """ params = dict(script=script, params=params) if self.config.server_scripts is True: params["load"] = load or [self.scripts.default_namespace] return self.request.post(gremlin_path, params)
[ "def", "gremlin", "(", "self", ",", "script", ",", "params", "=", "None", ",", "load", "=", "None", ")", ":", "params", "=", "dict", "(", "script", "=", "script", ",", "params", "=", "params", ")", "if", "self", ".", "config", ".", "server_scripts", ...
https://github.com/espeed/bulbs/blob/628e5b14f0249f9ca4fa1ceea6f2af2dca45f75a/bulbs/rexster/client.py#L340-L356
databricks/databricks-cli
6c429d4f581fc99f54cbf9239879434310037cc7
databricks_cli/groups/api.py
python
GroupsApi.list_all
(self)
return self.client.get_groups()
Return all of the groups in an organization.
Return all of the groups in an organization.
[ "Return", "all", "of", "the", "groups", "in", "an", "organization", "." ]
def list_all(self): """Return all of the groups in an organization.""" return self.client.get_groups()
[ "def", "list_all", "(", "self", ")", ":", "return", "self", ".", "client", ".", "get_groups", "(", ")" ]
https://github.com/databricks/databricks-cli/blob/6c429d4f581fc99f54cbf9239879434310037cc7/databricks_cli/groups/api.py#L50-L52
erevus-cn/pocscan
5fef32b1abe22a9f666ad3aacfd1f99d784cb72d
pocscan/plugins/pocsuite/packages/requests/api.py
python
put
(url, data=None, **kwargs)
return request('put', url, data=data, **kwargs)
Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes.
Sends a PUT request. Returns :class:`Response` object.
[ "Sends", "a", "PUT", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def put(url, data=None, **kwargs): """Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. """ return request('put', url, data=data, **kwargs)
[ "def", "put", "(", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "request", "(", "'put'", ",", "url", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
https://github.com/erevus-cn/pocscan/blob/5fef32b1abe22a9f666ad3aacfd1f99d784cb72d/pocscan/plugins/pocsuite/packages/requests/api.py#L91-L99
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py
python
_SixMetaPathImporter._add_module
(self, mod, *fullnames)
[]
def _add_module(self, mod, *fullnames): for fullname in fullnames: self.known_modules[self.name + "." + fullname] = mod
[ "def", "_add_module", "(", "self", ",", "mod", ",", "*", "fullnames", ")", ":", "for", "fullname", "in", "fullnames", ":", "self", ".", "known_modules", "[", "self", ".", "name", "+", "\".\"", "+", "fullname", "]", "=", "mod" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py#L177-L179
yueyoum/social-oauth
80600ea737355b20931c8a0b5223f5b68175d930
example/_bottle.py
python
Route.reset
(self)
Forget any cached values. The next time :attr:`call` is accessed, all plugins are re-applied.
Forget any cached values. The next time :attr:`call` is accessed, all plugins are re-applied.
[ "Forget", "any", "cached", "values", ".", "The", "next", "time", ":", "attr", ":", "call", "is", "accessed", "all", "plugins", "are", "re", "-", "applied", "." ]
def reset(self): ''' Forget any cached values. The next time :attr:`call` is accessed, all plugins are re-applied. ''' self.__dict__.pop('call', None)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "__dict__", ".", "pop", "(", "'call'", ",", "None", ")" ]
https://github.com/yueyoum/social-oauth/blob/80600ea737355b20931c8a0b5223f5b68175d930/example/_bottle.py#L483-L486
google/clusterfuzz
f358af24f414daa17a3649b143e71ea71871ef59
src/clusterfuzz/_internal/build_management/revisions.py
python
_get_revision
(component_revision_dict)
return component_revision_dict['rev']
Return revision for a component revision dict.
Return revision for a component revision dict.
[ "Return", "revision", "for", "a", "component", "revision", "dict", "." ]
def _get_revision(component_revision_dict): """Return revision for a component revision dict.""" return component_revision_dict['rev']
[ "def", "_get_revision", "(", "component_revision_dict", ")", ":", "return", "component_revision_dict", "[", "'rev'", "]" ]
https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/clusterfuzz/_internal/build_management/revisions.py#L171-L173
MicrosoftResearch/Azimuth
84eb013b8dde7132357a9b69206e99a4c65e2b89
azimuth/metrics.py
python
precision_at_k
(r, k)
return np.mean(r)
Score is precision @ k Relevance is binary (nonzero is relevant). >>> r = [0, 0, 1] >>> precision_at_k(r, 1) 0.0 >>> precision_at_k(r, 2) 0.0 >>> precision_at_k(r, 3) 0.33333333333333331 >>> precision_at_k(r, 4) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: Relevance score length < k Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) Returns: Precision @ k Raises: ValueError: len(r) must be >= k
Score is precision @ k
[ "Score", "is", "precision", "@", "k" ]
def precision_at_k(r, k): """Score is precision @ k Relevance is binary (nonzero is relevant). >>> r = [0, 0, 1] >>> precision_at_k(r, 1) 0.0 >>> precision_at_k(r, 2) 0.0 >>> precision_at_k(r, 3) 0.33333333333333331 >>> precision_at_k(r, 4) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: Relevance score length < k Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) Returns: Precision @ k Raises: ValueError: len(r) must be >= k """ assert k >= 1 r = np.asarray(r)[:k] != 0 if r.size != k: raise ValueError('Relevance score length < k') return np.mean(r)
[ "def", "precision_at_k", "(", "r", ",", "k", ")", ":", "assert", "k", ">=", "1", "r", "=", "np", ".", "asarray", "(", "r", ")", "[", ":", "k", "]", "!=", "0", "if", "r", ".", "size", "!=", "k", ":", "raise", "ValueError", "(", "'Relevance score...
https://github.com/MicrosoftResearch/Azimuth/blob/84eb013b8dde7132357a9b69206e99a4c65e2b89/azimuth/metrics.py#L75-L107
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/ipmi.py
python
set_user_name
(uid, name, **kwargs)
Set user name :param uid: user number [1:16] :param name: username (limit of 16bytes) :param kwargs: - api_host=127.0.0.1 - api_user=admin - api_pass=example - api_port=623 - api_kg=None CLI Examples: .. code-block:: bash salt-call ipmi.set_user_name uid=2 name='steverweber'
Set user name
[ "Set", "user", "name" ]
def set_user_name(uid, name, **kwargs): """ Set user name :param uid: user number [1:16] :param name: username (limit of 16bytes) :param kwargs: - api_host=127.0.0.1 - api_user=admin - api_pass=example - api_port=623 - api_kg=None CLI Examples: .. code-block:: bash salt-call ipmi.set_user_name uid=2 name='steverweber' """ with _IpmiCommand(**kwargs) as s: return s.set_user_name(uid, name)
[ "def", "set_user_name", "(", "uid", ",", "name", ",", "*", "*", "kwargs", ")", ":", "with", "_IpmiCommand", "(", "*", "*", "kwargs", ")", "as", "s", ":", "return", "s", ".", "set_user_name", "(", "uid", ",", "name", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/ipmi.py#L498-L518
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/bsddb/dbtables.py
python
bsdTableDB.ListTableColumns
(self, table)
Return a list of columns in the given table. [] if the table doesn't exist.
Return a list of columns in the given table. [] if the table doesn't exist.
[ "Return", "a", "list", "of", "columns", "in", "the", "given", "table", ".", "[]", "if", "the", "table", "doesn", "t", "exist", "." ]
def ListTableColumns(self, table): """Return a list of columns in the given table. [] if the table doesn't exist. """ assert isinstance(table, str) if contains_metastrings(table): raise ValueError, "bad table name: contains reserved metastrings" columnlist_key = _columns_key(table) if not getattr(self.db, "has_key")(columnlist_key): return [] pickledcolumnlist = getattr(self.db, "get_bytes", self.db.get)(columnlist_key) if pickledcolumnlist: return pickle.loads(pickledcolumnlist) else: return []
[ "def", "ListTableColumns", "(", "self", ",", "table", ")", ":", "assert", "isinstance", "(", "table", ",", "str", ")", "if", "contains_metastrings", "(", "table", ")", ":", "raise", "ValueError", ",", "\"bad table name: contains reserved metastrings\"", "columnlist_...
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/bsddb/dbtables.py#L357-L373
anchore/anchore-engine
bb18b70e0cbcad58beb44cd439d00067d8f7ea8b
anchore_engine/services/apiext/api/controllers/image_imports.py
python
import_image_packages
(operation_id)
return content_upload(operation_id, "packages", request)
POST /imports/images/{operation_id}/packages :param operation_id: :param sbom: :return:
POST /imports/images/{operation_id}/packages
[ "POST", "/", "imports", "/", "images", "/", "{", "operation_id", "}", "/", "packages" ]
def import_image_packages(operation_id): """ POST /imports/images/{operation_id}/packages :param operation_id: :param sbom: :return: """ return content_upload(operation_id, "packages", request)
[ "def", "import_image_packages", "(", "operation_id", ")", ":", "return", "content_upload", "(", "operation_id", ",", "\"packages\"", ",", "request", ")" ]
https://github.com/anchore/anchore-engine/blob/bb18b70e0cbcad58beb44cd439d00067d8f7ea8b/anchore_engine/services/apiext/api/controllers/image_imports.py#L243-L252
microsoft/unilm
65f15af2a307ebb64cfb25adf54375b002e6fe8d
infoxlm/fairseq/fairseq/data/legacy/block_pair_dataset.py
python
BlockPairDataset._fetch_block
(self, start_ds_idx, offset, end_ds_idx, length)
return buffer[s:e]
Fetch a block of tokens based on its dataset idx
Fetch a block of tokens based on its dataset idx
[ "Fetch", "a", "block", "of", "tokens", "based", "on", "its", "dataset", "idx" ]
def _fetch_block(self, start_ds_idx, offset, end_ds_idx, length): """ Fetch a block of tokens based on its dataset idx """ buffer = torch.cat( [self.dataset[idx] for idx in range(start_ds_idx, end_ds_idx + 1)] ) s, e = offset, offset + length return buffer[s:e]
[ "def", "_fetch_block", "(", "self", ",", "start_ds_idx", ",", "offset", ",", "end_ds_idx", ",", "length", ")", ":", "buffer", "=", "torch", ".", "cat", "(", "[", "self", ".", "dataset", "[", "idx", "]", "for", "idx", "in", "range", "(", "start_ds_idx",...
https://github.com/microsoft/unilm/blob/65f15af2a307ebb64cfb25adf54375b002e6fe8d/infoxlm/fairseq/fairseq/data/legacy/block_pair_dataset.py#L281-L289
mapproxy/mapproxy
45ae81b3dd6c8a1a0b473ba8c669afd0ec7ecd10
mapproxy/grid.py
python
MetaGrid._full_tile_list
(self, tiles)
return list(_create_tile_list(xs, ys, z, (maxx+1, maxy+1))), grid_size, bounds
Return a complete list of all tiles that a minimal meta tile with `tiles` contains. >>> mgrid = MetaGrid(grid=TileGrid(), meta_size=(2, 2)) >>> mgrid._full_tile_list([(0, 0, 2), (1, 1, 2)]) ([(0, 1, 2), (1, 1, 2), (0, 0, 2), (1, 0, 2)], (2, 2), ((0, 0, 2), (1, 1, 2)))
Return a complete list of all tiles that a minimal meta tile with `tiles` contains.
[ "Return", "a", "complete", "list", "of", "all", "tiles", "that", "a", "minimal", "meta", "tile", "with", "tiles", "contains", "." ]
def _full_tile_list(self, tiles): """ Return a complete list of all tiles that a minimal meta tile with `tiles` contains. >>> mgrid = MetaGrid(grid=TileGrid(), meta_size=(2, 2)) >>> mgrid._full_tile_list([(0, 0, 2), (1, 1, 2)]) ([(0, 1, 2), (1, 1, 2), (0, 0, 2), (1, 0, 2)], (2, 2), ((0, 0, 2), (1, 1, 2))) """ tile = tiles.pop() z = tile[2] minx = maxx = tile[0] miny = maxy = tile[1] for tile in tiles: x, y = tile[:2] minx = min(minx, x) maxx = max(maxx, x) miny = min(miny, y) maxy = max(maxy, y) grid_size = 1+maxx-minx, 1+maxy-miny if self.grid.flipped_y_axis: ys = range(miny, maxy+1) else: ys = range(maxy, miny-1, -1) xs = range(minx, maxx+1) bounds = (minx, miny, z), (maxx, maxy, z) return list(_create_tile_list(xs, ys, z, (maxx+1, maxy+1))), grid_size, bounds
[ "def", "_full_tile_list", "(", "self", ",", "tiles", ")", ":", "tile", "=", "tiles", ".", "pop", "(", ")", "z", "=", "tile", "[", "2", "]", "minx", "=", "maxx", "=", "tile", "[", "0", "]", "miny", "=", "maxy", "=", "tile", "[", "1", "]", "for...
https://github.com/mapproxy/mapproxy/blob/45ae81b3dd6c8a1a0b473ba8c669afd0ec7ecd10/mapproxy/grid.py#L843-L873
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/overconvergent/genus0.py
python
OverconvergentModularFormElement.prec
(self)
return self.gexp().prec()
r""" Return the series expansion precision of this overconvergent modular form. (This is not the same as the `p`-adic precision of the coefficients.) EXAMPLES:: sage: OverconvergentModularForms(5, 6, 1/3,prec=15).gen(1).prec() 15
r""" Return the series expansion precision of this overconvergent modular form. (This is not the same as the `p`-adic precision of the coefficients.)
[ "r", "Return", "the", "series", "expansion", "precision", "of", "this", "overconvergent", "modular", "form", ".", "(", "This", "is", "not", "the", "same", "as", "the", "p", "-", "adic", "precision", "of", "the", "coefficients", ".", ")" ]
def prec(self): r""" Return the series expansion precision of this overconvergent modular form. (This is not the same as the `p`-adic precision of the coefficients.) EXAMPLES:: sage: OverconvergentModularForms(5, 6, 1/3,prec=15).gen(1).prec() 15 """ return self.gexp().prec()
[ "def", "prec", "(", "self", ")", ":", "return", "self", ".", "gexp", "(", ")", ".", "prec", "(", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/overconvergent/genus0.py#L1363-L1374
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/gdata/build/lib/gdata/tlslite/utils/cipherfactory.py
python
createTripleDES
(key, IV, implList=None)
Create a new 3DES object. @type key: str @param key: A 24 byte string. @type IV: str @param IV: An 8 byte string @rtype: L{tlslite.utils.TripleDES} @return: A 3DES object.
Create a new 3DES object.
[ "Create", "a", "new", "3DES", "object", "." ]
def createTripleDES(key, IV, implList=None): """Create a new 3DES object. @type key: str @param key: A 24 byte string. @type IV: str @param IV: An 8 byte string @rtype: L{tlslite.utils.TripleDES} @return: A 3DES object. """ if implList == None: implList = ["cryptlib", "openssl", "pycrypto"] for impl in implList: if impl == "cryptlib" and cryptomath.cryptlibpyLoaded: return Cryptlib_TripleDES.new(key, 2, IV) elif impl == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_TripleDES.new(key, 2, IV) elif impl == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_TripleDES.new(key, 2, IV) raise NotImplementedError()
[ "def", "createTripleDES", "(", "key", ",", "IV", ",", "implList", "=", "None", ")", ":", "if", "implList", "==", "None", ":", "implList", "=", "[", "\"cryptlib\"", ",", "\"openssl\"", ",", "\"pycrypto\"", "]", "for", "impl", "in", "implList", ":", "if", ...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/build/lib/gdata/tlslite/utils/cipherfactory.py#L89-L111
pandera-dev/pandera
9448d0a80b8dd02910f9cc553ce00349584b107f
pandera/schemas.py
python
DataFrameSchema.coerce_dtype
(self, obj: pd.DataFrame)
return obj
Coerce dataframe to the type specified in dtype. :param obj: dataframe to coerce. :returns: dataframe with coerced dtypes
Coerce dataframe to the type specified in dtype.
[ "Coerce", "dataframe", "to", "the", "type", "specified", "in", "dtype", "." ]
def coerce_dtype(self, obj: pd.DataFrame) -> pd.DataFrame: """Coerce dataframe to the type specified in dtype. :param obj: dataframe to coerce. :returns: dataframe with coerced dtypes """ error_handler = SchemaErrorHandler(lazy=True) def _try_coercion(coerce_fn, obj): try: return coerce_fn(obj) except errors.SchemaError as exc: error_handler.collect_error("dtype_coercion_error", exc) return obj for colname, col_schema in self.columns.items(): if col_schema.regex: try: matched_columns = col_schema.get_regex_columns(obj.columns) except errors.SchemaError: matched_columns = pd.Index([]) for matched_colname in matched_columns: if col_schema.coerce or self.coerce: obj[matched_colname] = _try_coercion( col_schema.coerce_dtype, obj[matched_colname] ) elif ( (col_schema.coerce or self.coerce) and self.dtype is None and colname in obj ): obj[colname] = _try_coercion( col_schema.coerce_dtype, obj[colname] ) if self.dtype is not None: obj = _try_coercion(self._coerce_dtype, obj) if self.index is not None and (self.index.coerce or self.coerce): index_schema = copy.deepcopy(self.index) if self.coerce: # coercing at the dataframe-level should apply index coercion # for both single- and multi-indexes. index_schema._coerce = True coerced_index = _try_coercion(index_schema.coerce_dtype, obj.index) if coerced_index is not None: obj.index = coerced_index if error_handler.collected_errors: raise errors.SchemaErrors(error_handler.collected_errors, obj) return obj
[ "def", "coerce_dtype", "(", "self", ",", "obj", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "error_handler", "=", "SchemaErrorHandler", "(", "lazy", "=", "True", ")", "def", "_try_coercion", "(", "coerce_fn", ",", "obj", ")", ":"...
https://github.com/pandera-dev/pandera/blob/9448d0a80b8dd02910f9cc553ce00349584b107f/pandera/schemas.py#L362-L413
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_group.py
python
Utils.create_tmpfile_copy
(inc_file)
return tmpfile
create a temporary copy of a file
create a temporary copy of a file
[ "create", "a", "temporary", "copy", "of", "a", "file" ]
def create_tmpfile_copy(inc_file): '''create a temporary copy of a file''' tmpfile = Utils.create_tmpfile('lib_openshift-') Utils._write(tmpfile, open(inc_file).read()) # Cleanup the tmpfile atexit.register(Utils.cleanup, [tmpfile]) return tmpfile
[ "def", "create_tmpfile_copy", "(", "inc_file", ")", ":", "tmpfile", "=", "Utils", ".", "create_tmpfile", "(", "'lib_openshift-'", ")", "Utils", ".", "_write", "(", "tmpfile", ",", "open", "(", "inc_file", ")", ".", "read", "(", ")", ")", "# Cleanup the tmpfi...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_group.py#L1174-L1182
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_scale_io_volume_source.py
python
V1ScaleIOVolumeSource.to_str
(self)
return pprint.pformat(self.to_dict())
Returns the string representation of the model
Returns the string representation of the model
[ "Returns", "the", "string", "representation", "of", "the", "model" ]
def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict())
[ "def", "to_str", "(", "self", ")", ":", "return", "pprint", ".", "pformat", "(", "self", ".", "to_dict", "(", ")", ")" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_scale_io_volume_source.py#L355-L357
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/octoprint/sensor.py
python
OctoPrintTemperatureSensor.available
(self)
return self.coordinator.last_update_success and self.coordinator.data["printer"]
Return if entity is available.
Return if entity is available.
[ "Return", "if", "entity", "is", "available", "." ]
def available(self) -> bool: """Return if entity is available.""" return self.coordinator.last_update_success and self.coordinator.data["printer"]
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "coordinator", ".", "last_update_success", "and", "self", ".", "coordinator", ".", "data", "[", "\"printer\"", "]" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/octoprint/sensor.py#L245-L247
bert-nmt/bert-nmt
fcb616d28091ac23c9c16f30e6870fe90b8576d6
fairseq/models/lstm.py
python
AttentionLayer.forward
(self, input, source_hids, encoder_padding_mask)
return x, attn_scores
[]
def forward(self, input, source_hids, encoder_padding_mask): # input: bsz x input_embed_dim # source_hids: srclen x bsz x output_embed_dim # x: bsz x output_embed_dim x = self.input_proj(input) # compute attention attn_scores = (source_hids * x.unsqueeze(0)).sum(dim=2) # don't attend over padding if encoder_padding_mask is not None: attn_scores = attn_scores.float().masked_fill_( encoder_padding_mask, float('-inf') ).type_as(attn_scores) # FP16 support: cast to float and back attn_scores = F.softmax(attn_scores, dim=0) # srclen x bsz # sum weighted sources x = (attn_scores.unsqueeze(2) * source_hids).sum(dim=0) x = torch.tanh(self.output_proj(torch.cat((x, input), dim=1))) return x, attn_scores
[ "def", "forward", "(", "self", ",", "input", ",", "source_hids", ",", "encoder_padding_mask", ")", ":", "# input: bsz x input_embed_dim", "# source_hids: srclen x bsz x output_embed_dim", "# x: bsz x output_embed_dim", "x", "=", "self", ".", "input_proj", "(", "input", ")...
https://github.com/bert-nmt/bert-nmt/blob/fcb616d28091ac23c9c16f30e6870fe90b8576d6/fairseq/models/lstm.py#L283-L306
aceisace/Inkycal
552744bc5d80769c1015d48fd8b13201683ee679
inkycal/custom/functions.py
python
internet_available
()
checks if the internet is available. Attempts to connect to google.com with a timeout of 5 seconds to check if the network can be reached. Returns: - True if connection could be established. - False if the internet could not be reached. Returned output can be used to add a check for internet availability: >>> if internet_available() == True: >>> #...do something that requires internet connectivity
checks if the internet is available.
[ "checks", "if", "the", "internet", "is", "available", "." ]
def internet_available(): """checks if the internet is available. Attempts to connect to google.com with a timeout of 5 seconds to check if the network can be reached. Returns: - True if connection could be established. - False if the internet could not be reached. Returned output can be used to add a check for internet availability: >>> if internet_available() == True: >>> #...do something that requires internet connectivity """ try: urlopen('https://google.com',timeout=5) return True except URLError as err: return False
[ "def", "internet_available", "(", ")", ":", "try", ":", "urlopen", "(", "'https://google.com'", ",", "timeout", "=", "5", ")", "return", "True", "except", "URLError", "as", "err", ":", "return", "False" ]
https://github.com/aceisace/Inkycal/blob/552744bc5d80769c1015d48fd8b13201683ee679/inkycal/custom/functions.py#L234-L254
david8862/keras-YOLOv3-model-set
e9f0f94109430973525219e66eeafe8a2f51363d
tracking/model/deep_sort/kalman_filter.py
python
KalmanFilter.initiate
(self, measurement)
return mean, covariance
Create track from unassociated measurement. Parameters ---------- measurement : ndarray Bounding box coordinates (x, y, a, h) with center position (x, y), aspect ratio a, and height h. Returns ------- (ndarray, ndarray) Returns the mean vector (8 dimensional) and covariance matrix (8x8 dimensional) of the new track. Unobserved velocities are initialized to 0 mean.
Create track from unassociated measurement.
[ "Create", "track", "from", "unassociated", "measurement", "." ]
def initiate(self, measurement): """Create track from unassociated measurement. Parameters ---------- measurement : ndarray Bounding box coordinates (x, y, a, h) with center position (x, y), aspect ratio a, and height h. Returns ------- (ndarray, ndarray) Returns the mean vector (8 dimensional) and covariance matrix (8x8 dimensional) of the new track. Unobserved velocities are initialized to 0 mean. """ mean_pos = measurement mean_vel = np.zeros_like(mean_pos) mean = np.r_[mean_pos, mean_vel] std = [ 2 * self._std_weight_position * measurement[3], 2 * self._std_weight_position * measurement[3], 1e-2, 2 * self._std_weight_position * measurement[3], 10 * self._std_weight_velocity * measurement[3], 10 * self._std_weight_velocity * measurement[3], 1e-5, 10 * self._std_weight_velocity * measurement[3]] covariance = np.diag(np.square(std)) return mean, covariance
[ "def", "initiate", "(", "self", ",", "measurement", ")", ":", "mean_pos", "=", "measurement", "mean_vel", "=", "np", ".", "zeros_like", "(", "mean_pos", ")", "mean", "=", "np", ".", "r_", "[", "mean_pos", ",", "mean_vel", "]", "std", "=", "[", "2", "...
https://github.com/david8862/keras-YOLOv3-model-set/blob/e9f0f94109430973525219e66eeafe8a2f51363d/tracking/model/deep_sort/kalman_filter.py#L56-L87
allenai/allennlp
a3d71254fcc0f3615910e9c3d48874515edf53e0
allennlp/confidence_checks/task_checklists/utils.py
python
random_handle
(n: int = 6)
return "@%s" % random_string(n)
Returns a random handle of length `n`. Eg. "@randomstr23`
Returns a random handle of length `n`. Eg. "
[ "Returns", "a", "random", "handle", "of", "length", "n", ".", "Eg", "." ]
def random_handle(n: int = 6) -> str: """ Returns a random handle of length `n`. Eg. "@randomstr23` """ return "@%s" % random_string(n)
[ "def", "random_handle", "(", "n", ":", "int", "=", "6", ")", "->", "str", ":", "return", "\"@%s\"", "%", "random_string", "(", "n", ")" ]
https://github.com/allenai/allennlp/blob/a3d71254fcc0f3615910e9c3d48874515edf53e0/allennlp/confidence_checks/task_checklists/utils.py#L169-L173
ArtistScript/FastTextRank
0af1f353b4ff3180b8cac2953196d84fe012f7bc
FastTextRank/util.py
python
two_sentences_similarity
(sents_1, sents_2)
return counter / (math.log(len(sents_1) + len(sents_2)))
计算两个句子的相似性 :param sents_1: :param sents_2: :return:
计算两个句子的相似性 :param sents_1: :param sents_2: :return:
[ "计算两个句子的相似性", ":", "param", "sents_1", ":", ":", "param", "sents_2", ":", ":", "return", ":" ]
def two_sentences_similarity(sents_1, sents_2): ''' 计算两个句子的相似性 :param sents_1: :param sents_2: :return: ''' counter = 0 for sent in sents_1: if sent in sents_2: counter += 1 if counter==0: return 0 return counter / (math.log(len(sents_1) + len(sents_2)))
[ "def", "two_sentences_similarity", "(", "sents_1", ",", "sents_2", ")", ":", "counter", "=", "0", "for", "sent", "in", "sents_1", ":", "if", "sent", "in", "sents_2", ":", "counter", "+=", "1", "if", "counter", "==", "0", ":", "return", "0", "return", "...
https://github.com/ArtistScript/FastTextRank/blob/0af1f353b4ff3180b8cac2953196d84fe012f7bc/FastTextRank/util.py#L194-L207
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/bulkexports/v1/export/export_custom_job.py
python
ExportCustomJobInstance.resource_type
(self)
return self._properties['resource_type']
:returns: The type of communication – Messages, Calls, Conferences, and Participants :rtype: unicode
:returns: The type of communication – Messages, Calls, Conferences, and Participants :rtype: unicode
[ ":", "returns", ":", "The", "type", "of", "communication", "–", "Messages", "Calls", "Conferences", "and", "Participants", ":", "rtype", ":", "unicode" ]
def resource_type(self): """ :returns: The type of communication – Messages, Calls, Conferences, and Participants :rtype: unicode """ return self._properties['resource_type']
[ "def", "resource_type", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'resource_type'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/bulkexports/v1/export/export_custom_job.py#L244-L249