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
tomguluson92/PRNet_PyTorch
2d30e244855a043eec071baf78e8edbab9c11c78
face3d/morphable_model/load.py
python
load_pncc_code
(path = 'pncc_code.mat')
return pncc_code
load pncc code of BFM PNCC code: Defined in 'Face Alignment Across Large Poses: A 3D Solution Xiangyu' download at http://www.cbsr.ia.ac.cn/users/xiangyuzhu/projects/3DDFA/main.htm. Args: path: path to data. Returns: pncc_code: [nver, 3]
load pncc code of BFM PNCC code: Defined in 'Face Alignment Across Large Poses: A 3D Solution Xiangyu' download at http://www.cbsr.ia.ac.cn/users/xiangyuzhu/projects/3DDFA/main.htm. Args: path: path to data. Returns: pncc_code: [nver, 3]
[ "load", "pncc", "code", "of", "BFM", "PNCC", "code", ":", "Defined", "in", "Face", "Alignment", "Across", "Large", "Poses", ":", "A", "3D", "Solution", "Xiangyu", "download", "at", "http", ":", "//", "www", ".", "cbsr", ".", "ia", ".", "ac", ".", "cn...
def load_pncc_code(path = 'pncc_code.mat'): ''' load pncc code of BFM PNCC code: Defined in 'Face Alignment Across Large Poses: A 3D Solution Xiangyu' download at http://www.cbsr.ia.ac.cn/users/xiangyuzhu/projects/3DDFA/main.htm. Args: path: path to data. Returns: pncc_code: [nver, 3] ''' C = sio.loadmat(path) pncc_code = C['vertex_code'].T return pncc_code
[ "def", "load_pncc_code", "(", "path", "=", "'pncc_code.mat'", ")", ":", "C", "=", "sio", ".", "loadmat", "(", "path", ")", "pncc_code", "=", "C", "[", "'vertex_code'", "]", ".", "T", "return", "pncc_code" ]
https://github.com/tomguluson92/PRNet_PyTorch/blob/2d30e244855a043eec071baf78e8edbab9c11c78/face3d/morphable_model/load.py#L89-L100
nucleic/enaml
65c2a2a2d765e88f2e1103046680571894bb41ed
enaml/qt/qt_window.py
python
finalize_close
(d)
Finalize the closing of the declaration object. This is performed as a deferred call so that the window may fully close before the declaration is potentially destroyed.
Finalize the closing of the declaration object.
[ "Finalize", "the", "closing", "of", "the", "declaration", "object", "." ]
def finalize_close(d): """ Finalize the closing of the declaration object. This is performed as a deferred call so that the window may fully close before the declaration is potentially destroyed. """ d.visible = False d.closed() if d.destroy_on_close: d.destroy()
[ "def", "finalize_close", "(", "d", ")", ":", "d", ".", "visible", "=", "False", "d", ".", "closed", "(", ")", "if", "d", ".", "destroy_on_close", ":", "d", ".", "destroy", "(", ")" ]
https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/qt/qt_window.py#L33-L43
tribe29/checkmk
6260f2512e159e311f426e16b84b19d0b8e9ad0c
buildscripts/infrastructure/build-nodes/aws/inventory/ec2.py
python
Ec2Inventory.to_safe
(self, word)
return re.sub(regex + "]", "_", word)
Converts 'bad' characters in a string to underscores so they can be used as Ansible groups
Converts 'bad' characters in a string to underscores so they can be used as Ansible groups
[ "Converts", "bad", "characters", "in", "a", "string", "to", "underscores", "so", "they", "can", "be", "used", "as", "Ansible", "groups" ]
def to_safe(self, word): ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' regex = r"[^A-Za-z0-9\_" if not self.replace_dash_in_groups: regex += r"\-" return re.sub(regex + "]", "_", word)
[ "def", "to_safe", "(", "self", ",", "word", ")", ":", "regex", "=", "r\"[^A-Za-z0-9\\_\"", "if", "not", "self", ".", "replace_dash_in_groups", ":", "regex", "+=", "r\"\\-\"", "return", "re", ".", "sub", "(", "regex", "+", "\"]\"", ",", "\"_\"", ",", "wor...
https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/buildscripts/infrastructure/build-nodes/aws/inventory/ec2.py#L1692-L1697
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/scripts/findnocoding.py
python
get_declaration
(line)
return b''
[]
def get_declaration(line): match = decl_re.match(line) if match: return match.group(1) return b''
[ "def", "get_declaration", "(", "line", ")", ":", "match", "=", "decl_re", ".", "match", "(", "line", ")", "if", "match", ":", "return", "match", ".", "group", "(", "1", ")", "return", "b''" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/scripts/findnocoding.py#L38-L42
dropbox/hydra
101b274e5ac89e1fa196ff6aeb4e1cfc66717341
copy_state_db.py
python
_mongo_dict_to_str
(d)
return "%s:%d/%s/%s" % (d['host'], d['port'], d['db'], d['collection'])
[]
def _mongo_dict_to_str(d): if 'id_source' in d: return d['id_source']['shard_name'] return "%s:%d/%s/%s" % (d['host'], d['port'], d['db'], d['collection'])
[ "def", "_mongo_dict_to_str", "(", "d", ")", ":", "if", "'id_source'", "in", "d", ":", "return", "d", "[", "'id_source'", "]", "[", "'shard_name'", "]", "return", "\"%s:%d/%s/%s\"", "%", "(", "d", "[", "'host'", "]", ",", "d", "[", "'port'", "]", ",", ...
https://github.com/dropbox/hydra/blob/101b274e5ac89e1fa196ff6aeb4e1cfc66717341/copy_state_db.py#L21-L25
apple/coremltools
141a83af482fcbdd5179807c9eaff9a7999c2c49
coremltools/converters/onnx/_operators_nd.py
python
_convert_randomuniform
(builder, node, graph, err)
convert to CoreML Random Uniform Static Layer: https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L4526
convert to CoreML Random Uniform Static Layer: https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L4526
[ "convert", "to", "CoreML", "Random", "Uniform", "Static", "Layer", ":", "https", ":", "//", "github", ".", "com", "/", "apple", "/", "coremltools", "/", "blob", "/", "655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492", "/", "mlmodel", "/", "format", "/", "NeuralNetwork",...
def _convert_randomuniform(builder, node, graph, err): """ convert to CoreML Random Uniform Static Layer: https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L4526 """ add_random(builder, node, graph, err, builder.random_uniform_static)
[ "def", "_convert_randomuniform", "(", "builder", ",", "node", ",", "graph", ",", "err", ")", ":", "add_random", "(", "builder", ",", "node", ",", "graph", ",", "err", ",", "builder", ".", "random_uniform_static", ")" ]
https://github.com/apple/coremltools/blob/141a83af482fcbdd5179807c9eaff9a7999c2c49/coremltools/converters/onnx/_operators_nd.py#L1733-L1738
haiwen/seahub
e92fcd44e3e46260597d8faa9347cb8222b8b10d
seahub/two_factor/middleware.py
python
IsVerified.__init__
(self, user)
[]
def __init__(self, user): self.user = user
[ "def", "__init__", "(", "self", ",", "user", ")", ":", "self", ".", "user", "=", "user" ]
https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/seahub/two_factor/middleware.py#L18-L19
googlearchive/simian
fb9c43946ff7ba29be417068d6447cfc0adfe9ef
src/simian/mac/munki/handlers/__init__.py
python
StrHeaderDateToDatetime
(str_header_dt)
Converts a string header date to a datetime object. Args: str_header_dt: str date from header, i.e. If-Modified-Since. Returns: datetime.datetime object, or None if there's a parsing error.
Converts a string header date to a datetime object.
[ "Converts", "a", "string", "header", "date", "to", "a", "datetime", "object", "." ]
def StrHeaderDateToDatetime(str_header_dt): """Converts a string header date to a datetime object. Args: str_header_dt: str date from header, i.e. If-Modified-Since. Returns: datetime.datetime object, or None if there's a parsing error. """ if not str_header_dt: return try: # NOTE(user): strptime is a py2.5+ feature. return datetime.datetime.strptime(str_header_dt, HEADER_DATE_FORMAT) except ValueError: logging.exception( 'Error parsing If-Modified-Since date: %s', str_header_dt)
[ "def", "StrHeaderDateToDatetime", "(", "str_header_dt", ")", ":", "if", "not", "str_header_dt", ":", "return", "try", ":", "# NOTE(user): strptime is a py2.5+ feature.", "return", "datetime", ".", "datetime", ".", "strptime", "(", "str_header_dt", ",", "HEADER_DATE_FORM...
https://github.com/googlearchive/simian/blob/fb9c43946ff7ba29be417068d6447cfc0adfe9ef/src/simian/mac/munki/handlers/__init__.py#L48-L63
opencobra/cobrapy
0b9ea70cb0ffe78568d445ce3361ad10ec6b02a2
src/cobra/io/sbml.py
python
_sbase_notes_dict
(sbase, notes)
Set SBase notes based on dictionary. Parameters ---------- sbase : libsbml.SBase SBML object to set notes on notes : notes object notes information from cobra object
Set SBase notes based on dictionary.
[ "Set", "SBase", "notes", "based", "on", "dictionary", "." ]
def _sbase_notes_dict(sbase, notes): """Set SBase notes based on dictionary. Parameters ---------- sbase : libsbml.SBase SBML object to set notes on notes : notes object notes information from cobra object """ if notes and len(notes) > 0: tokens = ( ['<html xmlns = "http://www.w3.org/1999/xhtml" >'] + ["<p>{}: {}</p>".format(k, v) for (k, v) in notes.items()] + ["</html>"] ) _check( sbase.setNotes("\n".join(tokens)), "Setting notes on sbase: {}".format(sbase), )
[ "def", "_sbase_notes_dict", "(", "sbase", ",", "notes", ")", ":", "if", "notes", "and", "len", "(", "notes", ")", ">", "0", ":", "tokens", "=", "(", "[", "'<html xmlns = \"http://www.w3.org/1999/xhtml\" >'", "]", "+", "[", "\"<p>{}: {}</p>\"", ".", "format", ...
https://github.com/opencobra/cobrapy/blob/0b9ea70cb0ffe78568d445ce3361ad10ec6b02a2/src/cobra/io/sbml.py#L1421-L1440
eoyilmaz/stalker
a35c041b79d953d00dc2a09cf8206956ca269bef
stalker/models/task.py
python
Task._validate_children
(self, key, child)
return child
validates the given child
validates the given child
[ "validates", "the", "given", "child" ]
def _validate_children(self, key, child): """validates the given child """ # just empty the resources list # do it without a flush from stalker.db.session import DBSession with DBSession.no_autoflush: self.resources = [] # if this is the first ever child we receive # set total_scheduled_seconds to child's total_logged_seconds # and set schedule_seconds to child's schedule_seconds if self.is_leaf: # remove info from parent old_schedule_seconds = self.schedule_seconds self._total_logged_seconds = child.total_logged_seconds self._schedule_seconds = child.schedule_seconds # got a parent ? if self.parent: # update schedule_seconds self.parent._schedule_seconds -= old_schedule_seconds self.parent._schedule_seconds += child.schedule_seconds # it was a leaf but now a parent, so set the start to max and # end to min import pytz self._start = datetime.datetime.max.replace(tzinfo=pytz.utc) self._end = datetime.datetime.min.replace(tzinfo=pytz.utc) # extend start and end dates self._expand_dates(self, child.start, child.end) return child
[ "def", "_validate_children", "(", "self", ",", "key", ",", "child", ")", ":", "# just empty the resources list", "# do it without a flush", "from", "stalker", ".", "db", ".", "session", "import", "DBSession", "with", "DBSession", ".", "no_autoflush", ":", "self", ...
https://github.com/eoyilmaz/stalker/blob/a35c041b79d953d00dc2a09cf8206956ca269bef/stalker/models/task.py#L1517-L1549
memray/seq2seq-keyphrase
9145c63ebdc4c3bc431f8091dc52547a46804012
emolga/dataset/build_dataset.py
python
filter_unk
(X, min_freq=5)
return word2idx, id2word
[]
def filter_unk(X, min_freq=5): voc = dict() for l in X: for w in l: if w not in voc: voc[w] = 1 else: voc[w] += 1 word2idx = dict() word2idx['<eol>'] = 0 id2word = dict() id2word[0] = '<eol>' at = 1 for w in voc: if voc[w] > min_freq: word2idx[w] = at id2word[at] = w at += 1 word2idx['<unk>'] = at id2word[at] = '<unk>' return word2idx, id2word
[ "def", "filter_unk", "(", "X", ",", "min_freq", "=", "5", ")", ":", "voc", "=", "dict", "(", ")", "for", "l", "in", "X", ":", "for", "w", "in", "l", ":", "if", "w", "not", "in", "voc", ":", "voc", "[", "w", "]", "=", "1", "else", ":", "vo...
https://github.com/memray/seq2seq-keyphrase/blob/9145c63ebdc4c3bc431f8091dc52547a46804012/emolga/dataset/build_dataset.py#L123-L146
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/calendar.py
python
Calendar.monthdatescalendar
(self, year, month)
return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values.
Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values.
[ "Return", "a", "matrix", "(", "list", "of", "lists", ")", "representing", "a", "month", "s", "calendar", ".", "Each", "row", "represents", "a", "week", ";", "week", "entries", "are", "datetime", ".", "date", "values", "." ]
def monthdatescalendar(self, year, month): """ Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values. """ dates = list(self.itermonthdates(year, month)) return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
[ "def", "monthdatescalendar", "(", "self", ",", "year", ",", "month", ")", ":", "dates", "=", "list", "(", "self", ".", "itermonthdates", "(", "year", ",", "month", ")", ")", "return", "[", "dates", "[", "i", ":", "i", "+", "7", "]", "for", "i", "...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/calendar.py#L228-L234
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/algebras/free_algebra_element.py
python
FreeAlgebraElement.to_pbw_basis
(self)
return self.parent().pbw_element(self)
Return ``self`` in the Poincaré-Birkhoff-Witt (PBW) basis. EXAMPLES:: sage: F.<x,y,z> = FreeAlgebra(ZZ, 3) sage: p = x^2*y + 3*y*x + 2 sage: p.to_pbw_basis() 2*PBW[1] + 3*PBW[y]*PBW[x] + PBW[x^2*y] + 2*PBW[x*y]*PBW[x] + PBW[y]*PBW[x]^2
Return ``self`` in the Poincaré-Birkhoff-Witt (PBW) basis.
[ "Return", "self", "in", "the", "Poincaré", "-", "Birkhoff", "-", "Witt", "(", "PBW", ")", "basis", "." ]
def to_pbw_basis(self): """ Return ``self`` in the Poincaré-Birkhoff-Witt (PBW) basis. EXAMPLES:: sage: F.<x,y,z> = FreeAlgebra(ZZ, 3) sage: p = x^2*y + 3*y*x + 2 sage: p.to_pbw_basis() 2*PBW[1] + 3*PBW[y]*PBW[x] + PBW[x^2*y] + 2*PBW[x*y]*PBW[x] + PBW[y]*PBW[x]^2 """ return self.parent().pbw_element(self)
[ "def", "to_pbw_basis", "(", "self", ")", ":", "return", "self", ".", "parent", "(", ")", ".", "pbw_element", "(", "self", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/algebras/free_algebra_element.py#L256-L268
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/alarm/backends/onealert.py
python
OneAlertBackend.send
(self, ev)
[]
def send(self, ev): api_key = self.conf.get('api_key') if not api_key: return for user in ev['users']: resp = requests.post( 'http://api.110monitor.com/alert/api/event', headers={'Content-Type': 'application/json'}, timeout=10, data=json.dumps({ "app": user.get('onealert') or api_key, "eventId": ev['id'], "eventType": 'trigger' if ev['status'] in ('PROBLEM', 'EVENT') else 'resolve', "alarmName": ev.get('expr') or ev.get('title', '-'), "entityName": ev['title'], "entityId": ev['title'], "priority": 1, "alarmContent": ev['text'], }), ) if not resp.ok: raise Exception(resp.json())
[ "def", "send", "(", "self", ",", "ev", ")", ":", "api_key", "=", "self", ".", "conf", ".", "get", "(", "'api_key'", ")", "if", "not", "api_key", ":", "return", "for", "user", "in", "ev", "[", "'users'", "]", ":", "resp", "=", "requests", ".", "po...
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/alarm/backends/onealert.py#L15-L38
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/contrib/mps.py
python
matmul
(lhs, rhs, transa=False, transb=False)
return te.extern( (m, n), [lhs, rhs], lambda ins, outs: tvm.tir.call_packed( "tvm.contrib.mps.matmul", ins[0], ins[1], outs[0], transa, transb ), name="C", )
Create an extern op that compute matrix mult of A and rhs with CrhsLAS This function serves as an example on how to calle external libraries. Parameters ---------- lhs : Tensor The left matrix operand rhs : Tensor The right matrix operand transa : bool Whether transpose lhs transb : bool Whether transpose rhs Returns ------- C : Tensor The result tensor.
Create an extern op that compute matrix mult of A and rhs with CrhsLAS
[ "Create", "an", "extern", "op", "that", "compute", "matrix", "mult", "of", "A", "and", "rhs", "with", "CrhsLAS" ]
def matmul(lhs, rhs, transa=False, transb=False): """Create an extern op that compute matrix mult of A and rhs with CrhsLAS This function serves as an example on how to calle external libraries. Parameters ---------- lhs : Tensor The left matrix operand rhs : Tensor The right matrix operand transa : bool Whether transpose lhs transb : bool Whether transpose rhs Returns ------- C : Tensor The result tensor. """ m = lhs.shape[0] if transa is False else lhs.shape[1] n = rhs.shape[1] if transb is False else rhs.shape[0] if transa: m = b if transb: n = c return te.extern( (m, n), [lhs, rhs], lambda ins, outs: tvm.tir.call_packed( "tvm.contrib.mps.matmul", ins[0], ins[1], outs[0], transa, transb ), name="C", )
[ "def", "matmul", "(", "lhs", ",", "rhs", ",", "transa", "=", "False", ",", "transb", "=", "False", ")", ":", "m", "=", "lhs", ".", "shape", "[", "0", "]", "if", "transa", "is", "False", "else", "lhs", ".", "shape", "[", "1", "]", "n", "=", "r...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/contrib/mps.py#L25-L59
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/logging/handlers.py
python
RotatingFileHandler.__init__
(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False)
Open the specified file and use it as the stream for logging. By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at a predetermined size. Rollover occurs whenever the current log file is nearly maxBytes in length. If backupCount is >= 1, the system will successively create new files with the same pathname as the base file, but with extensions ".1", ".2" etc. appended to it. For example, with a backupCount of 5 and a base file name of "app.log", you would get "app.log", "app.log.1", "app.log.2", ... through to "app.log.5". The file being written to is always "app.log" - when it gets filled up, it is closed and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. exist, then they are renamed to "app.log.2", "app.log.3" etc. respectively. If maxBytes is zero, rollover never occurs.
Open the specified file and use it as the stream for logging.
[ "Open", "the", "specified", "file", "and", "use", "it", "as", "the", "stream", "for", "logging", "." ]
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False): """ Open the specified file and use it as the stream for logging. By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at a predetermined size. Rollover occurs whenever the current log file is nearly maxBytes in length. If backupCount is >= 1, the system will successively create new files with the same pathname as the base file, but with extensions ".1", ".2" etc. appended to it. For example, with a backupCount of 5 and a base file name of "app.log", you would get "app.log", "app.log.1", "app.log.2", ... through to "app.log.5". The file being written to is always "app.log" - when it gets filled up, it is closed and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. exist, then they are renamed to "app.log.2", "app.log.3" etc. respectively. If maxBytes is zero, rollover never occurs. """ # If rotation/rollover is wanted, it doesn't make sense to use another # mode. If for example 'w' were specified, then if there were multiple # runs of the calling application, the logs from previous runs would be # lost if the 'w' is respected, because the log file would be truncated # on each run. if maxBytes > 0: mode = 'a' BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) self.maxBytes = maxBytes self.backupCount = backupCount
[ "def", "__init__", "(", "self", ",", "filename", ",", "mode", "=", "'a'", ",", "maxBytes", "=", "0", ",", "backupCount", "=", "0", ",", "encoding", "=", "None", ",", "delay", "=", "False", ")", ":", "# If rotation/rollover is wanted, it doesn't make sense to u...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/logging/handlers.py#L122-L152
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/distlib/manifest.py
python
Manifest.sorted
(self, wantdirs=False)
return [os.path.join(*path_tuple) for path_tuple in sorted(os.path.split(path) for path in result)]
Return sorted files in directory order
Return sorted files in directory order
[ "Return", "sorted", "files", "in", "directory", "order" ]
def sorted(self, wantdirs=False): """ Return sorted files in directory order """ def add_dir(dirs, d): dirs.add(d) logger.debug('add_dir added %s', d) if d != self.base: parent, _ = os.path.split(d) assert parent not in ('', '/') add_dir(dirs, parent) result = set(self.files) # make a copy! if wantdirs: dirs = set() for f in result: add_dir(dirs, os.path.dirname(f)) result |= dirs return [os.path.join(*path_tuple) for path_tuple in sorted(os.path.split(path) for path in result)]
[ "def", "sorted", "(", "self", ",", "wantdirs", "=", "False", ")", ":", "def", "add_dir", "(", "dirs", ",", "d", ")", ":", "dirs", ".", "add", "(", "d", ")", "logger", ".", "debug", "(", "'add_dir added %s'", ",", "d", ")", "if", "d", "!=", "self"...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/distlib/manifest.py#L103-L123
kindredresearch/SenseAct
e7acbeb7918d0069ea82f0bab09ecb99807fdc9b
senseact/devices/camera/camera_communicator.py
python
CameraCommunicator._actuator_handler
(self)
There's no actuator available for cameras.
There's no actuator available for cameras.
[ "There", "s", "no", "actuator", "available", "for", "cameras", "." ]
def _actuator_handler(self): """There's no actuator available for cameras.""" raise RuntimeError("Camera Communicator does not have an actuator handler.")
[ "def", "_actuator_handler", "(", "self", ")", ":", "raise", "RuntimeError", "(", "\"Camera Communicator does not have an actuator handler.\"", ")" ]
https://github.com/kindredresearch/SenseAct/blob/e7acbeb7918d0069ea82f0bab09ecb99807fdc9b/senseact/devices/camera/camera_communicator.py#L92-L94
glitchdotcom/WebPutty
4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7
ziplibs/werkzeug/urls.py
python
_safe_urlsplit
(s)
return rv
the urllib.urlsplit cache breaks if it contains unicode and we cannot control that. So we force type cast that thing back to what we think it is.
the urllib.urlsplit cache breaks if it contains unicode and we cannot control that. So we force type cast that thing back to what we think it is.
[ "the", "urllib", ".", "urlsplit", "cache", "breaks", "if", "it", "contains", "unicode", "and", "we", "cannot", "control", "that", ".", "So", "we", "force", "type", "cast", "that", "thing", "back", "to", "what", "we", "think", "it", "is", "." ]
def _safe_urlsplit(s): """the urllib.urlsplit cache breaks if it contains unicode and we cannot control that. So we force type cast that thing back to what we think it is. """ rv = urlparse.urlsplit(s) if type(rv[1]) is not type(s): try: return tuple(map(type(s), rv)) except UnicodeError: # oh well, we most likely will break later again, but # let's just say it worked out well to that point. pass return rv
[ "def", "_safe_urlsplit", "(", "s", ")", ":", "rv", "=", "urlparse", ".", "urlsplit", "(", "s", ")", "if", "type", "(", "rv", "[", "1", "]", ")", "is", "not", "type", "(", "s", ")", ":", "try", ":", "return", "tuple", "(", "map", "(", "type", ...
https://github.com/glitchdotcom/WebPutty/blob/4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7/ziplibs/werkzeug/urls.py#L43-L56
CJWorkbench/cjworkbench
e0b878d8ff819817fa049a4126efcbfcec0b50e6
cjwstate/rendercache/io.py
python
clear_cached_render_result_for_step
(step: Step)
Delete a CachedRenderResult, if it exists. This deletes the Parquet file from disk, _then_ empties relevant database fields and saves them (and only them).
Delete a CachedRenderResult, if it exists.
[ "Delete", "a", "CachedRenderResult", "if", "it", "exists", "." ]
def clear_cached_render_result_for_step(step: Step) -> None: """Delete a CachedRenderResult, if it exists. This deletes the Parquet file from disk, _then_ empties relevant database fields and saves them (and only them). """ delete_parquet_files_for_step(step.workflow_id, step.id) step.cached_render_result_delta_id = None step.cached_render_result_errors = [] step.cached_render_result_json = b"null" step.cached_render_result_status = None step.cached_render_result_columns = None step.cached_render_result_nrows = None step.save(update_fields=STEP_FIELDS)
[ "def", "clear_cached_render_result_for_step", "(", "step", ":", "Step", ")", "->", "None", ":", "delete_parquet_files_for_step", "(", "step", ".", "workflow_id", ",", "step", ".", "id", ")", "step", ".", "cached_render_result_delta_id", "=", "None", "step", ".", ...
https://github.com/CJWorkbench/cjworkbench/blob/e0b878d8ff819817fa049a4126efcbfcec0b50e6/cjwstate/rendercache/io.py#L254-L269
awslabs/autogluon
7309118f2ab1c9519f25acf61a283a95af95842b
core/src/autogluon/core/scheduler/seq_scheduler.py
python
LocalSequentialScheduler.get_best_reward
(self)
return self.searcher.get_best_reward()
Get the best reward from the finished jobs.
Get the best reward from the finished jobs.
[ "Get", "the", "best", "reward", "from", "the", "finished", "jobs", "." ]
def get_best_reward(self): """Get the best reward from the finished jobs. """ return self.searcher.get_best_reward()
[ "def", "get_best_reward", "(", "self", ")", ":", "return", "self", ".", "searcher", ".", "get_best_reward", "(", ")" ]
https://github.com/awslabs/autogluon/blob/7309118f2ab1c9519f25acf61a283a95af95842b/core/src/autogluon/core/scheduler/seq_scheduler.py#L288-L291
sbraz/pymediainfo
2e5891b457632dc6fcb71f422906c5a6beb175e7
pymediainfo/__init__.py
python
MediaInfo.menu_tracks
(self)
return self._tracks("Menu")
:return: All :class:`Track`\\s of type ``Menu``. :rtype: list of :class:`Track`\\s
:return: All :class:`Track`\\s of type ``Menu``. :rtype: list of :class:`Track`\\s
[ ":", "return", ":", "All", ":", "class", ":", "Track", "\\\\", "s", "of", "type", "Menu", ".", ":", "rtype", ":", "list", "of", ":", "class", ":", "Track", "\\\\", "s" ]
def menu_tracks(self) -> List[Track]: """ :return: All :class:`Track`\\s of type ``Menu``. :rtype: list of :class:`Track`\\s """ return self._tracks("Menu")
[ "def", "menu_tracks", "(", "self", ")", "->", "List", "[", "Track", "]", ":", "return", "self", ".", "_tracks", "(", "\"Menu\"", ")" ]
https://github.com/sbraz/pymediainfo/blob/2e5891b457632dc6fcb71f422906c5a6beb175e7/pymediainfo/__init__.py#L228-L233
albertz/music-player
d23586f5bf657cbaea8147223be7814d117ae73d
mac/pyobjc-framework-Cocoa/Examples/AppKit/WebServicesTool/WSTConnectionWindowControllerClass.py
python
WSTConnectionWindowController.createToolbarItems
(self)
Creates all of the toolbar items that can be made available in the toolbar. The actual set of available toolbar items is determined by other mechanisms (user defaults, for example).
Creates all of the toolbar items that can be made available in the toolbar. The actual set of available toolbar items is determined by other mechanisms (user defaults, for example).
[ "Creates", "all", "of", "the", "toolbar", "items", "that", "can", "be", "made", "available", "in", "the", "toolbar", ".", "The", "actual", "set", "of", "available", "toolbar", "items", "is", "determined", "by", "other", "mechanisms", "(", "user", "defaults",...
def createToolbarItems(self): """ Creates all of the toolbar items that can be made available in the toolbar. The actual set of available toolbar items is determined by other mechanisms (user defaults, for example). """ addToolbarItem(self, kWSTReloadContentsToolbarItemIdentifier, "Reload", "Reload", "Reload Contents", None, "reloadVisibleData:", NSImage.imageNamed_("Reload"), None) addToolbarItem(self, kWSTPreferencesToolbarItemIdentifier, "Preferences", "Preferences", "Show Preferences", None, "orderFrontPreferences:", NSImage.imageNamed_("Preferences"), None) addToolbarItem(self, kWSTUrlTextFieldToolbarItemIdentifier, "URL", "URL", "Server URL", None, None, self.urlTextField, None) self._toolbarDefaultItemIdentifiers = [ kWSTReloadContentsToolbarItemIdentifier, kWSTUrlTextFieldToolbarItemIdentifier, NSToolbarSeparatorItemIdentifier, NSToolbarCustomizeToolbarItemIdentifier, ] self._toolbarAllowedItemIdentifiers = [ kWSTReloadContentsToolbarItemIdentifier, kWSTUrlTextFieldToolbarItemIdentifier, NSToolbarSeparatorItemIdentifier, NSToolbarSpaceItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier, NSToolbarPrintItemIdentifier, kWSTPreferencesToolbarItemIdentifier, NSToolbarCustomizeToolbarItemIdentifier, ]
[ "def", "createToolbarItems", "(", "self", ")", ":", "addToolbarItem", "(", "self", ",", "kWSTReloadContentsToolbarItemIdentifier", ",", "\"Reload\"", ",", "\"Reload\"", ",", "\"Reload Contents\"", ",", "None", ",", "\"reloadVisibleData:\"", ",", "NSImage", ".", "image...
https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/mac/pyobjc-framework-Cocoa/Examples/AppKit/WebServicesTool/WSTConnectionWindowControllerClass.py#L202-L233
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/helpers/config_entry_oauth2_flow.py
python
AbstractOAuth2Implementation.name
(self)
Name of the implementation.
Name of the implementation.
[ "Name", "of", "the", "implementation", "." ]
def name(self) -> str: """Name of the implementation."""
[ "def", "name", "(", "self", ")", "->", "str", ":" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/helpers/config_entry_oauth2_flow.py#L49-L50
nosmokingbandit/Watcher3
0217e75158b563bdefc8e01c3be7620008cf3977
lib/sqlalchemy/interfaces.py
python
ConnectionProxy.execute
(self, conn, execute, clauseelement, *multiparams, **params)
return execute(clauseelement, *multiparams, **params)
Intercept high level execute() events.
Intercept high level execute() events.
[ "Intercept", "high", "level", "execute", "()", "events", "." ]
def execute(self, conn, execute, clauseelement, *multiparams, **params): """Intercept high level execute() events.""" return execute(clauseelement, *multiparams, **params)
[ "def", "execute", "(", "self", ",", "conn", ",", "execute", ",", "clauseelement", ",", "*", "multiparams", ",", "*", "*", "params", ")", ":", "return", "execute", "(", "clauseelement", ",", "*", "multiparams", ",", "*", "*", "params", ")" ]
https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/lib/sqlalchemy/interfaces.py#L253-L256
amimo/dcc
114326ab5a082a42c7728a375726489e4709ca29
androguard/gui/sourcewindow.py
python
SourceWindow.keyPressEvent
(self, event)
Keyboard shortcuts
Keyboard shortcuts
[ "Keyboard", "shortcuts" ]
def keyPressEvent(self, event): """Keyboard shortcuts""" key = event.key() if key == QtCore.Qt.Key_X: self.actionXref() elif key == QtCore.Qt.Key_G: self.actionGoto() elif key == QtCore.Qt.Key_X: self.actionXref() elif key == QtCore.Qt.Key_I: self.actionInfo() elif key == QtCore.Qt.Key_R: self.reload_java_sources()
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "key", "=", "event", ".", "key", "(", ")", "if", "key", "==", "QtCore", ".", "Qt", ".", "Key_X", ":", "self", ".", "actionXref", "(", ")", "elif", "key", "==", "QtCore", ".", "Qt", ".",...
https://github.com/amimo/dcc/blob/114326ab5a082a42c7728a375726489e4709ca29/androguard/gui/sourcewindow.py#L384-L396
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/werkzeug/wrappers.py
python
ResponseStreamMixin.stream
(self)
return ResponseStream(self)
The response iterable as write-only stream.
The response iterable as write-only stream.
[ "The", "response", "iterable", "as", "write", "-", "only", "stream", "." ]
def stream(self): """The response iterable as write-only stream.""" return ResponseStream(self)
[ "def", "stream", "(", "self", ")", ":", "return", "ResponseStream", "(", "self", ")" ]
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/werkzeug/wrappers.py#L1558-L1560
crossbario/crossbar
ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64
crossbar/common/checkconfig.py
python
check_transport_auth_tls
(config)
Check a WAMP-TLS configuration item.
Check a WAMP-TLS configuration item.
[ "Check", "a", "WAMP", "-", "TLS", "configuration", "item", "." ]
def check_transport_auth_tls(config): """ Check a WAMP-TLS configuration item. """ if 'type' not in config: raise InvalidConfigException("missing mandatory attribute 'type' in WAMP-TLS configuration") if config['type'] not in ['static', 'dynamic', 'function']: raise InvalidConfigException( "invalid type '{}' in WAMP-TLS configuration - must be one of 'static', 'dynamic', 'function'".format( config['type'])) if config['type'] == 'static': # FIXME pass elif config['type'] == 'dynamic': if 'authenticator' not in config: raise InvalidConfigException( "missing mandatory attribute 'authenticator' in dynamic WAMP-TLS configuration") check_or_raise_uri( config['authenticator'], "invalid authenticator URI '{}' in dynamic WAMP-TLS configuration".format(config['authenticator'])) elif config['type'] == 'function': if 'create' not in config: raise InvalidConfigException("missing mandatory attribute 'create' in function WAMP-TLS configuration") else: raise InvalidConfigException('logic error')
[ "def", "check_transport_auth_tls", "(", "config", ")", ":", "if", "'type'", "not", "in", "config", ":", "raise", "InvalidConfigException", "(", "\"missing mandatory attribute 'type' in WAMP-TLS configuration\"", ")", "if", "config", "[", "'type'", "]", "not", "in", "[...
https://github.com/crossbario/crossbar/blob/ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64/crossbar/common/checkconfig.py#L476-L505
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/logging/handlers.py
python
BufferingHandler.shouldFlush
(self, record)
return (len(self.buffer) >= self.capacity)
Should the handler flush its buffer? Returns true if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies.
Should the handler flush its buffer?
[ "Should", "the", "handler", "flush", "its", "buffer?" ]
def shouldFlush(self, record): """ Should the handler flush its buffer? Returns true if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies. """ return (len(self.buffer) >= self.capacity)
[ "def", "shouldFlush", "(", "self", ",", "record", ")", ":", "return", "(", "len", "(", "self", ".", "buffer", ")", ">=", "self", ".", "capacity", ")" ]
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/logging/handlers.py#L1126-L1133
aneisch/home-assistant-config
86e381fde9609cb8871c439c433c12989e4e225d
custom_components/alexa_media/alexa_entity.py
python
get_entity_data
( login_obj: AlexaLogin, entity_ids: List[Text] )
return entities
Get and process the entity data into a more usable format.
Get and process the entity data into a more usable format.
[ "Get", "and", "process", "the", "entity", "data", "into", "a", "more", "usable", "format", "." ]
async def get_entity_data( login_obj: AlexaLogin, entity_ids: List[Text] ) -> AlexaEntityData: """Get and process the entity data into a more usable format.""" entities = {} if entity_ids: raw = await AlexaAPI.get_entity_state(login_obj, entity_ids=entity_ids) device_states = raw.get("deviceStates", []) if isinstance(raw, dict) else None if device_states: for device_state in device_states: entity_id = device_state.get("entity", {}).get("entityId") if entity_id: entities[entity_id] = [] cap_states = device_state.get("capabilityStates", []) for cap_state in cap_states: entities[entity_id].append(json.loads(cap_state)) return entities
[ "async", "def", "get_entity_data", "(", "login_obj", ":", "AlexaLogin", ",", "entity_ids", ":", "List", "[", "Text", "]", ")", "->", "AlexaEntityData", ":", "entities", "=", "{", "}", "if", "entity_ids", ":", "raw", "=", "await", "AlexaAPI", ".", "get_enti...
https://github.com/aneisch/home-assistant-config/blob/86e381fde9609cb8871c439c433c12989e4e225d/custom_components/alexa_media/alexa_entity.py#L205-L222
tanghaibao/goatools
647e9dd833695f688cd16c2f9ea18f1692e5c6bc
goatools/go_enrichment.py
python
GOEnrichmentRecord.get_pvalue
(self)
return getattr(self, "p_uncorrected")
Returns pval for 1st method, if it exists. Else returns uncorrected pval.
Returns pval for 1st method, if it exists. Else returns uncorrected pval.
[ "Returns", "pval", "for", "1st", "method", "if", "it", "exists", ".", "Else", "returns", "uncorrected", "pval", "." ]
def get_pvalue(self): """Returns pval for 1st method, if it exists. Else returns uncorrected pval.""" if self.method_flds: return getattr(self, "p_{m}".format(m=self.get_method_name())) return getattr(self, "p_uncorrected")
[ "def", "get_pvalue", "(", "self", ")", ":", "if", "self", ".", "method_flds", ":", "return", "getattr", "(", "self", ",", "\"p_{m}\"", ".", "format", "(", "m", "=", "self", ".", "get_method_name", "(", ")", ")", ")", "return", "getattr", "(", "self", ...
https://github.com/tanghaibao/goatools/blob/647e9dd833695f688cd16c2f9ea18f1692e5c6bc/goatools/go_enrichment.py#L90-L94
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/pip/_internal/req/req_install.py
python
InstallRequirement.populate_link
(self, finder, upgrade, require_hashes)
Ensure that if a link can be found for this, that it is found. Note that self.link may still be None - if Upgrade is False and the requirement is already installed. If require_hashes is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than the files downloaded from the index server and thus throw false hash mismatches. Furthermore, cached wheels at present have undeterministic contents due to file modification times.
Ensure that if a link can be found for this, that it is found.
[ "Ensure", "that", "if", "a", "link", "can", "be", "found", "for", "this", "that", "it", "is", "found", "." ]
def populate_link(self, finder, upgrade, require_hashes): """Ensure that if a link can be found for this, that it is found. Note that self.link may still be None - if Upgrade is False and the requirement is already installed. If require_hashes is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than the files downloaded from the index server and thus throw false hash mismatches. Furthermore, cached wheels at present have undeterministic contents due to file modification times. """ if self.link is None: self.link = finder.find_requirement(self, upgrade) if self._wheel_cache is not None and not require_hashes: old_link = self.link self.link = self._wheel_cache.get(self.link, self.name) if old_link != self.link: logger.debug('Using cached wheel link: %s', self.link)
[ "def", "populate_link", "(", "self", ",", "finder", ",", "upgrade", ",", "require_hashes", ")", ":", "if", "self", ".", "link", "is", "None", ":", "self", ".", "link", "=", "finder", ".", "find_requirement", "(", "self", ",", "upgrade", ")", "if", "sel...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/pip/_internal/req/req_install.py#L295-L313
radlab/sparrow
afb8efadeb88524f1394d1abe4ea66c6fd2ac744
deploy/third_party/boto-2.1.1/boto/storage_uri.py
python
BucketStorageUri.clone_replace_name
(self, new_name)
return BucketStorageUri(self.scheme, self.bucket_name, new_name, self.debug)
Instantiate a BucketStorageUri from the current BucketStorageUri, but replacing the object_name. @type new_name: string @param new_name: new object name
Instantiate a BucketStorageUri from the current BucketStorageUri, but replacing the object_name.
[ "Instantiate", "a", "BucketStorageUri", "from", "the", "current", "BucketStorageUri", "but", "replacing", "the", "object_name", "." ]
def clone_replace_name(self, new_name): """Instantiate a BucketStorageUri from the current BucketStorageUri, but replacing the object_name. @type new_name: string @param new_name: new object name """ if not self.bucket_name: raise InvalidUriError('clone_replace_name() on bucket-less URI %s' % self.uri) return BucketStorageUri(self.scheme, self.bucket_name, new_name, self.debug)
[ "def", "clone_replace_name", "(", "self", ",", "new_name", ")", ":", "if", "not", "self", ".", "bucket_name", ":", "raise", "InvalidUriError", "(", "'clone_replace_name() on bucket-less URI %s'", "%", "self", ".", "uri", ")", "return", "BucketStorageUri", "(", "se...
https://github.com/radlab/sparrow/blob/afb8efadeb88524f1394d1abe4ea66c6fd2ac744/deploy/third_party/boto-2.1.1/boto/storage_uri.py#L212-L223
missionpinball/mpf
8e6b74cff4ba06d2fec9445742559c1068b88582
mpf/platforms/rpi/rpi.py
python
RaspberryPiHardwarePlatform.configure_switch
(self, number: str, config: SwitchConfig, platform_config: dict)
return RpiSwitch(config, number, self)
Configure a switch with pull up.
Configure a switch with pull up.
[ "Configure", "a", "switch", "with", "pull", "up", "." ]
def configure_switch(self, number: str, config: SwitchConfig, platform_config: dict) -> "SwitchPlatformInterface": """Configure a switch with pull up.""" # set input self.send_command(self.pi.set_mode(int(number), apigpio.INPUT)) # configure pull up self.send_command(self.pi.set_pull_up_down(int(number), apigpio.PUD_UP)) if config.debounce: # configure debounce to 2ms self.send_command(self.pi.set_glitch_filter(int(number), 2000)) else: # configure debounce to 100us self.send_command(self.pi.set_glitch_filter(int(number), 100)) # add callback self.send_command(self.pi.add_callback(int(number), apigpio.EITHER_EDGE, self._switch_changed)) return RpiSwitch(config, number, self)
[ "def", "configure_switch", "(", "self", ",", "number", ":", "str", ",", "config", ":", "SwitchConfig", ",", "platform_config", ":", "dict", ")", "->", "\"SwitchPlatformInterface\"", ":", "# set input", "self", ".", "send_command", "(", "self", ".", "pi", ".", ...
https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/platforms/rpi/rpi.py#L229-L246
wiseman/mavelous
eef41c096cc282bb3acd33a747146a88d2bd1eee
modules/kml.py
python
mavlink_packet
(m)
handle an incoming mavlink packet
handle an incoming mavlink packet
[ "handle", "an", "incoming", "mavlink", "packet" ]
def mavlink_packet(m): """handle an incoming mavlink packet""" global g_module_context state = g_module_context.mmap_state
[ "def", "mavlink_packet", "(", "m", ")", ":", "global", "g_module_context", "state", "=", "g_module_context", ".", "mmap_state" ]
https://github.com/wiseman/mavelous/blob/eef41c096cc282bb3acd33a747146a88d2bd1eee/modules/kml.py#L85-L88
inasafe/inasafe
355eb2ce63f516b9c26af0c86a24f99e53f63f87
safe/gui/tools/wizard/step_fc05_functions2.py
python
StepFcFunctions2.on_tblFunctions2_itemSelectionChanged
(self)
Choose selected hazard x exposure constraints combination. .. note:: This is an automatic Qt slot executed when the category selection changes.
Choose selected hazard x exposure constraints combination.
[ "Choose", "selected", "hazard", "x", "exposure", "constraints", "combination", "." ]
def on_tblFunctions2_itemSelectionChanged(self): """Choose selected hazard x exposure constraints combination. .. note:: This is an automatic Qt slot executed when the category selection changes. """ functions = self.selected_functions_2() if not functions: self.lblAvailableFunctions2.clear() else: text = self.tr('Available functions:') + ' ' + ', '.join( [f['name'] for f in functions]) self.lblAvailableFunctions2.setText(text) self.parent.pbnNext.setEnabled(True) # Put a dot to the selected cell - note there is no way # to center an icon without using a custom ItemDelegate selection = self.tblFunctions2.selectedItems() selItem = (len(selection) == 1) and selection[0] or None for row in range(self.tblFunctions2.rowCount()): for column in range(self.tblFunctions2.columnCount()): item = self.tblFunctions2.item(row, column) item.setText((item == selItem) and '•' or '')
[ "def", "on_tblFunctions2_itemSelectionChanged", "(", "self", ")", ":", "functions", "=", "self", ".", "selected_functions_2", "(", ")", "if", "not", "functions", ":", "self", ".", "lblAvailableFunctions2", ".", "clear", "(", ")", "else", ":", "text", "=", "sel...
https://github.com/inasafe/inasafe/blob/355eb2ce63f516b9c26af0c86a24f99e53f63f87/safe/gui/tools/wizard/step_fc05_functions2.py#L100-L122
polychromatic/polychromatic
106bc3fdfda650a732341bf45e0d20fd281cc521
pylib/controller/editor.py
python
VisualEffectEditor._show_file_error
(self)
Alias to the _show_file_error() function from the Effects tab.
Alias to the _show_file_error() function from the Effects tab.
[ "Alias", "to", "the", "_show_file_error", "()", "function", "from", "the", "Effects", "tab", "." ]
def _show_file_error(self): """ Alias to the _show_file_error() function from the Effects tab. """ self.appdata.tab_effects._show_file_error() self.closeEvent()
[ "def", "_show_file_error", "(", "self", ")", ":", "self", ".", "appdata", ".", "tab_effects", ".", "_show_file_error", "(", ")", "self", ".", "closeEvent", "(", ")" ]
https://github.com/polychromatic/polychromatic/blob/106bc3fdfda650a732341bf45e0d20fd281cc521/pylib/controller/editor.py#L872-L877
wanggrun/Adaptively-Connected-Neural-Networks
e27066ef52301bdafa5932f43af8feeb23647edb
tensorpack-installed/build/lib/tensorpack/dataflow/base.py
python
RNGDataFlow.reset_state
(self)
Reset the RNG
Reset the RNG
[ "Reset", "the", "RNG" ]
def reset_state(self): """ Reset the RNG """ self.rng = get_rng(self)
[ "def", "reset_state", "(", "self", ")", ":", "self", ".", "rng", "=", "get_rng", "(", "self", ")" ]
https://github.com/wanggrun/Adaptively-Connected-Neural-Networks/blob/e27066ef52301bdafa5932f43af8feeb23647edb/tensorpack-installed/build/lib/tensorpack/dataflow/base.py#L80-L82
unode/firefox_decrypt
a3daadc09603a6cf8c4b7e49a59776340bc885e7
firefox_decrypt.py
python
ask_section
(sections: ConfigParser)
return final_choice
Prompt the user which profile should be used for decryption
Prompt the user which profile should be used for decryption
[ "Prompt", "the", "user", "which", "profile", "should", "be", "used", "for", "decryption" ]
def ask_section(sections: ConfigParser): """ Prompt the user which profile should be used for decryption """ # Do not ask for choice if user already gave one choice = "ASK" while choice not in sections: sys.stderr.write("Select the Mozilla profile you wish to decrypt\n") print_sections(sections) try: choice = input() except EOFError: LOG.error("Could not read Choice, got EOF") raise Exit(Exit.READ_GOT_EOF) try: final_choice = sections[choice] except KeyError: LOG.error("Profile No. %s does not exist!", choice) raise Exit(Exit.NO_SUCH_PROFILE) LOG.debug("Profile selection matched %s", final_choice) return final_choice
[ "def", "ask_section", "(", "sections", ":", "ConfigParser", ")", ":", "# Do not ask for choice if user already gave one", "choice", "=", "\"ASK\"", "while", "choice", "not", "in", "sections", ":", "sys", ".", "stderr", ".", "write", "(", "\"Select the Mozilla profile ...
https://github.com/unode/firefox_decrypt/blob/a3daadc09603a6cf8c4b7e49a59776340bc885e7/firefox_decrypt.py#L783-L806
tensorlayer/tensorlayer
cb4eb896dd063e650ef22533ed6fa6056a71cad5
examples/reinforcement_learning/tutorial_wrappers.py
python
FireResetEnv.__init__
(self, env)
Take action on reset for environments that are fixed until firing.
Take action on reset for environments that are fixed until firing.
[ "Take", "action", "on", "reset", "for", "environments", "that", "are", "fixed", "until", "firing", "." ]
def __init__(self, env): """Take action on reset for environments that are fixed until firing.""" super(FireResetEnv, self).__init__(env) assert env.unwrapped.get_action_meanings()[1] == 'FIRE' assert len(env.unwrapped.get_action_meanings()) >= 3
[ "def", "__init__", "(", "self", ",", "env", ")", ":", "super", "(", "FireResetEnv", ",", "self", ")", ".", "__init__", "(", "env", ")", "assert", "env", ".", "unwrapped", ".", "get_action_meanings", "(", ")", "[", "1", "]", "==", "'FIRE'", "assert", ...
https://github.com/tensorlayer/tensorlayer/blob/cb4eb896dd063e650ef22533ed6fa6056a71cad5/examples/reinforcement_learning/tutorial_wrappers.py#L138-L142
TensorVision/TensorVision
d971ed2b7d8fe1c0caf407eb7bdaebc0838e5801
tensorvision/utils.py
python
cfg
()
return None
General configuration values.
General configuration values.
[ "General", "configuration", "values", "." ]
def cfg(): """General configuration values.""" return None
[ "def", "cfg", "(", ")", ":", "return", "None" ]
https://github.com/TensorVision/TensorVision/blob/d971ed2b7d8fe1c0caf407eb7bdaebc0838e5801/tensorvision/utils.py#L301-L303
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/scrapy/scrapy/xlib/pydispatch/saferef.py
python
BoundMethodWeakref.calculateKey
( cls, target )
return (id(target.im_self),id(target.im_func))
Calculate the reference key for this reference Currently this is a two-tuple of the id()'s of the target object and the target function respectively.
Calculate the reference key for this reference
[ "Calculate", "the", "reference", "key", "for", "this", "reference" ]
def calculateKey( cls, target ): """Calculate the reference key for this reference Currently this is a two-tuple of the id()'s of the target object and the target function respectively. """ return (id(target.im_self),id(target.im_func))
[ "def", "calculateKey", "(", "cls", ",", "target", ")", ":", "return", "(", "id", "(", "target", ".", "im_self", ")", ",", "id", "(", "target", ".", "im_func", ")", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/scrapy/scrapy/xlib/pydispatch/saferef.py#L125-L131
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/ext/mapreduce/input_readers.py
python
_GoogleCloudStorageInputReader.split_input
(cls, mapper_spec)
return readers
Returns a list of input readers. An equal number of input files are assigned to each shard (+/- 1). If there are fewer files than shards, fewer than the requested number of shards will be used. Input files are currently never split (although for some formats could be and may be split in a future implementation). Args: mapper_spec: an instance of model.MapperSpec. Returns: A list of InputReaders. None when no input data can be found.
Returns a list of input readers.
[ "Returns", "a", "list", "of", "input", "readers", "." ]
def split_input(cls, mapper_spec): """Returns a list of input readers. An equal number of input files are assigned to each shard (+/- 1). If there are fewer files than shards, fewer than the requested number of shards will be used. Input files are currently never split (although for some formats could be and may be split in a future implementation). Args: mapper_spec: an instance of model.MapperSpec. Returns: A list of InputReaders. None when no input data can be found. """ reader_spec = cls.get_params(mapper_spec, allow_old=False) bucket = reader_spec[cls.BUCKET_NAME_PARAM] filenames = reader_spec[cls.OBJECT_NAMES_PARAM] delimiter = reader_spec.get(cls.DELIMITER_PARAM) account_id = reader_spec.get(cls._ACCOUNT_ID_PARAM) buffer_size = reader_spec.get(cls.BUFFER_SIZE_PARAM) fail_on_missing_input = reader_spec.get(cls.FAIL_ON_MISSING_INPUT) all_filenames = [] for filename in filenames: if filename.endswith("*"): all_filenames.extend( [file_stat.filename for file_stat in cloudstorage.listbucket( "/" + bucket + "/" + filename[:-1], delimiter=delimiter, _account_id=account_id)]) else: all_filenames.append("/%s/%s" % (bucket, filename)) readers = [] for shard in range(0, mapper_spec.shard_count): shard_filenames = all_filenames[shard::mapper_spec.shard_count] if shard_filenames: reader = cls( shard_filenames, buffer_size=buffer_size, _account_id=account_id, delimiter=delimiter) reader._fail_on_missing_input = fail_on_missing_input readers.append(reader) return readers
[ "def", "split_input", "(", "cls", ",", "mapper_spec", ")", ":", "reader_spec", "=", "cls", ".", "get_params", "(", "mapper_spec", ",", "allow_old", "=", "False", ")", "bucket", "=", "reader_spec", "[", "cls", ".", "BUCKET_NAME_PARAM", "]", "filenames", "=", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/ext/mapreduce/input_readers.py#L2380-L2423
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
python/dgl/_deprecate/runtime/ir/program.py
python
set_current_prog
(program)
Set the current program.
Set the current program.
[ "Set", "the", "current", "program", "." ]
def set_current_prog(program): """Set the current program.""" CURRENT_PROG.set_prog(program)
[ "def", "set_current_prog", "(", "program", ")", ":", "CURRENT_PROG", ".", "set_prog", "(", "program", ")" ]
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/python/dgl/_deprecate/runtime/ir/program.py#L69-L71
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/cmdoptions.py
python
_merge_hash
(option, opt_str, value, parser)
Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.
Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.
[ "Given", "a", "value", "spelled", "algo", ":", "digest", "append", "the", "digest", "to", "a", "list", "pointed", "to", "in", "a", "dict", "by", "the", "algo", "name", "." ]
def _merge_hash(option, opt_str, value, parser): """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} try: algo, digest = value.split(':', 1) except ValueError: parser.error('Arguments to %s must be a hash name ' 'followed by a value, like --hash=sha256:abcde...' % opt_str) if algo not in STRONG_HASHES: parser.error('Allowed hash algorithms for %s are %s.' % (opt_str, ', '.join(STRONG_HASHES))) parser.values.hashes.setdefault(algo, []).append(digest)
[ "def", "_merge_hash", "(", "option", ",", "opt_str", ",", "value", ",", "parser", ")", ":", "if", "not", "parser", ".", "values", ".", "hashes", ":", "parser", ".", "values", ".", "hashes", "=", "{", "}", "try", ":", "algo", ",", "digest", "=", "va...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/cmdoptions.py#L542-L556
golemhq/golem
84f51478b169cdeab73fc7e2a22a64d0a2a29263
golem/execution_runner/execution_runner.py
python
ExecutionRunner._select_environments
(self, project_envs)
return envs
Define the environments to use for the test. The test can have a list of environments set from 2 places: - using the -e|--environments CLI argument - suite `environments` variable If both of these are empty try using the first env if there are any envs defined for the project. Otherwise just return [''] meaning: no envs will be used.
Define the environments to use for the test.
[ "Define", "the", "environments", "to", "use", "for", "the", "test", "." ]
def _select_environments(self, project_envs): """Define the environments to use for the test. The test can have a list of environments set from 2 places: - using the -e|--environments CLI argument - suite `environments` variable If both of these are empty try using the first env if there are any envs defined for the project. Otherwise just return [''] meaning: no envs will be used. """ if self.cli_args.envs: # use the environments passed through command line envs = self.cli_args.envs elif self.suite.envs: # use the environments defined in the suite envs = self.suite.envs elif project_envs: # if there are available envs, use the first by default envs = [sorted(project_envs)[0]] else: envs = [] return envs
[ "def", "_select_environments", "(", "self", ",", "project_envs", ")", ":", "if", "self", ".", "cli_args", ".", "envs", ":", "# use the environments passed through command line", "envs", "=", "self", ".", "cli_args", ".", "envs", "elif", "self", ".", "suite", "."...
https://github.com/golemhq/golem/blob/84f51478b169cdeab73fc7e2a22a64d0a2a29263/golem/execution_runner/execution_runner.py#L142-L164
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/template/context.py
python
RequestContext.new
(self, values=None)
return new_context
[]
def new(self, values=None): new_context = super(RequestContext, self).new(values) # This is for backwards-compatibility: RequestContexts created via # Context.new don't include values from context processors. if hasattr(new_context, '_processors_index'): del new_context._processors_index return new_context
[ "def", "new", "(", "self", ",", "values", "=", "None", ")", ":", "new_context", "=", "super", "(", "RequestContext", ",", "self", ")", ".", "new", "(", "values", ")", "# This is for backwards-compatibility: RequestContexts created via", "# Context.new don't include va...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/template/context.py#L273-L279
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/homematic/cover.py
python
setup_platform
( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, )
Set up the platform.
Set up the platform.
[ "Set", "up", "the", "platform", "." ]
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the platform.""" if discovery_info is None: return devices: list[HMCover] = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: if conf[ATTR_DEVICE_TYPE] in HM_GARAGE: devices.append(HMGarage(conf)) else: devices.append(HMCover(conf)) add_entities(devices, True)
[ "def", "setup_platform", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "ConfigType", ",", "add_entities", ":", "AddEntitiesCallback", ",", "discovery_info", ":", "DiscoveryInfoType", "|", "None", "=", "None", ",", ")", "->", "None", ":", "if", "discov...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/homematic/cover.py#L20-L37
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_volume.py
python
Utils.create_tmp_file_from_contents
(rname, data, ftype='yaml')
return tmp
create a file in tmp with name and contents
create a file in tmp with name and contents
[ "create", "a", "file", "in", "tmp", "with", "name", "and", "contents" ]
def create_tmp_file_from_contents(rname, data, ftype='yaml'): ''' create a file in tmp with name and contents''' tmp = Utils.create_tmpfile(prefix=rname) if ftype == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripDumper'): Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper)) else: Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False)) elif ftype == 'json': Utils._write(tmp, json.dumps(data)) else: Utils._write(tmp, data) # Register cleanup when module is done atexit.register(Utils.cleanup, [tmp]) return tmp
[ "def", "create_tmp_file_from_contents", "(", "rname", ",", "data", ",", "ftype", "=", "'yaml'", ")", ":", "tmp", "=", "Utils", ".", "create_tmpfile", "(", "prefix", "=", "rname", ")", "if", "ftype", "==", "'yaml'", ":", "# AUDIT:no-member makes sense here due to...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_volume.py#L1215-L1235
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_component_status.py
python
V1ComponentStatus.kind
(self)
return self._kind
Gets the kind of this V1ComponentStatus. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1ComponentStatus. # noqa: E501 :rtype: str
Gets the kind of this V1ComponentStatus. # noqa: E501
[ "Gets", "the", "kind", "of", "this", "V1ComponentStatus", ".", "#", "noqa", ":", "E501" ]
def kind(self): """Gets the kind of this V1ComponentStatus. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1ComponentStatus. # noqa: E501 :rtype: str """ return self._kind
[ "def", "kind", "(", "self", ")", ":", "return", "self", ".", "_kind" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_component_status.py#L117-L125
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/resample.py
python
Resampler.interpolate
(self, method='linear', axis=0, limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast=None, **kwargs)
return result.interpolate(method=method, axis=axis, limit=limit, inplace=inplace, limit_direction=limit_direction, limit_area=limit_area, downcast=downcast, **kwargs)
Interpolate values according to different methods. .. versionadded:: 0.18.1
Interpolate values according to different methods.
[ "Interpolate", "values", "according", "to", "different", "methods", "." ]
def interpolate(self, method='linear', axis=0, limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast=None, **kwargs): """ Interpolate values according to different methods. .. versionadded:: 0.18.1 """ result = self._upsample(None) return result.interpolate(method=method, axis=axis, limit=limit, inplace=inplace, limit_direction=limit_direction, limit_area=limit_area, downcast=downcast, **kwargs)
[ "def", "interpolate", "(", "self", ",", "method", "=", "'linear'", ",", "axis", "=", "0", ",", "limit", "=", "None", ",", "inplace", "=", "False", ",", "limit_direction", "=", "'forward'", ",", "limit_area", "=", "None", ",", "downcast", "=", "None", "...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/resample.py#L763-L776
viewflow/viewflow
2389bd379a2ab22cc277585df7c09514e273541d
viewflow/nodes/switch.py
python
Switch.Default
(self, node)
return result
Last node to activate if no one other succeed.
Last node to activate if no one other succeed.
[ "Last", "node", "to", "activate", "if", "no", "one", "other", "succeed", "." ]
def Default(self, node): """Last node to activate if no one other succeed.""" result = copy(self) result._activate_next.append((node, None)) return result
[ "def", "Default", "(", "self", ",", "node", ")", ":", "result", "=", "copy", "(", "self", ")", "result", ".", "_activate_next", ".", "append", "(", "(", "node", ",", "None", ")", ")", "return", "result" ]
https://github.com/viewflow/viewflow/blob/2389bd379a2ab22cc277585df7c09514e273541d/viewflow/nodes/switch.py#L95-L99
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
TensorFlow/Detection/SSD/models/research/object_detection/exporter.py
python
profile_inference_graph
(graph)
Profiles the inference graph. Prints model parameters and computation FLOPs given an inference graph. BatchNorms are excluded from the parameter count due to the fact that BatchNorms are usually folded. BatchNorm, Initializer, Regularizer and BiasAdd are not considered in FLOP count. Args: graph: the inference graph.
Profiles the inference graph.
[ "Profiles", "the", "inference", "graph", "." ]
def profile_inference_graph(graph): """Profiles the inference graph. Prints model parameters and computation FLOPs given an inference graph. BatchNorms are excluded from the parameter count due to the fact that BatchNorms are usually folded. BatchNorm, Initializer, Regularizer and BiasAdd are not considered in FLOP count. Args: graph: the inference graph. """ tfprof_vars_option = ( tf.contrib.tfprof.model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS) tfprof_flops_option = tf.contrib.tfprof.model_analyzer.FLOAT_OPS_OPTIONS # Batchnorm is usually folded during inference. tfprof_vars_option['trim_name_regexes'] = ['.*BatchNorm.*'] # Initializer and Regularizer are only used in training. tfprof_flops_option['trim_name_regexes'] = [ '.*BatchNorm.*', '.*Initializer.*', '.*Regularizer.*', '.*BiasAdd.*' ] tf.contrib.tfprof.model_analyzer.print_model_analysis( graph, tfprof_options=tfprof_vars_option) tf.contrib.tfprof.model_analyzer.print_model_analysis( graph, tfprof_options=tfprof_flops_option)
[ "def", "profile_inference_graph", "(", "graph", ")", ":", "tfprof_vars_option", "=", "(", "tf", ".", "contrib", ".", "tfprof", ".", "model_analyzer", ".", "TRAINABLE_VARS_PARAMS_STAT_OPTIONS", ")", "tfprof_flops_option", "=", "tf", ".", "contrib", ".", "tfprof", "...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow/Detection/SSD/models/research/object_detection/exporter.py#L460-L488
hhatto/autopep8
577774fa57619ea87682c0999d9e91cd1cdb7425
autopep8.py
python
_get_indentword
(source)
return indent_word
Return indentation type.
Return indentation type.
[ "Return", "indentation", "type", "." ]
def _get_indentword(source): """Return indentation type.""" indent_word = ' ' # Default in case source has no indentation try: for t in generate_tokens(source): if t[0] == token.INDENT: indent_word = t[1] break except (SyntaxError, tokenize.TokenError): pass return indent_word
[ "def", "_get_indentword", "(", "source", ")", ":", "indent_word", "=", "' '", "# Default in case source has no indentation", "try", ":", "for", "t", "in", "generate_tokens", "(", "source", ")", ":", "if", "t", "[", "0", "]", "==", "token", ".", "INDENT", ...
https://github.com/hhatto/autopep8/blob/577774fa57619ea87682c0999d9e91cd1cdb7425/autopep8.py#L1831-L1841
gem/oq-engine
1bdb88f3914e390abcbd285600bfd39477aae47c
openquake/commonlib/hazard_writers.py
python
gen_gmfs
(gmf_set)
Generate GMF nodes from a gmf_set :param gmf_set: a sequence of GMF objects with attributes imt, sa_period, sa_damping, event_id and containing a list of GMF nodes with attributes gmv and location. The nodes are sorted by lon/lat.
Generate GMF nodes from a gmf_set :param gmf_set: a sequence of GMF objects with attributes imt, sa_period, sa_damping, event_id and containing a list of GMF nodes with attributes gmv and location. The nodes are sorted by lon/lat.
[ "Generate", "GMF", "nodes", "from", "a", "gmf_set", ":", "param", "gmf_set", ":", "a", "sequence", "of", "GMF", "objects", "with", "attributes", "imt", "sa_period", "sa_damping", "event_id", "and", "containing", "a", "list", "of", "GMF", "nodes", "with", "at...
def gen_gmfs(gmf_set): """ Generate GMF nodes from a gmf_set :param gmf_set: a sequence of GMF objects with attributes imt, sa_period, sa_damping, event_id and containing a list of GMF nodes with attributes gmv and location. The nodes are sorted by lon/lat. """ for gmf in gmf_set: gmf_node = Node('gmf') gmf_node['IMT'] = gmf.imt if gmf.imt == 'SA': gmf_node['saPeriod'] = str(gmf.sa_period) gmf_node['saDamping'] = str(gmf.sa_damping) gmf_node['ruptureId'] = gmf.event_id sorted_nodes = sorted(gmf) gmf_node.nodes = ( Node('node', dict(gmv=n.gmv, lon=n.location.x, lat=n.location.y)) for n in sorted_nodes) yield gmf_node
[ "def", "gen_gmfs", "(", "gmf_set", ")", ":", "for", "gmf", "in", "gmf_set", ":", "gmf_node", "=", "Node", "(", "'gmf'", ")", "gmf_node", "[", "'IMT'", "]", "=", "gmf", ".", "imt", "if", "gmf", ".", "imt", "==", "'SA'", ":", "gmf_node", "[", "'saPer...
https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/commonlib/hazard_writers.py#L218-L237
Digital-Sapphire/PyUpdater
d408f54a38ab63ab5f4bcf6471ac1a546357b29f
pyupdater/core/package_handler/__init__.py
python
PackageHandler.process_packages
(self, report_errors=False)
Gets a list of updates to process. Adds the name of an update to the version file if not already present. Processes all packages. Updates the version file meta-data. Then writes version file back to disk.
Gets a list of updates to process. Adds the name of an update to the version file if not already present. Processes all packages. Updates the version file meta-data. Then writes version file back to disk.
[ "Gets", "a", "list", "of", "updates", "to", "process", ".", "Adds", "the", "name", "of", "an", "update", "to", "the", "version", "file", "if", "not", "already", "present", ".", "Processes", "all", "packages", ".", "Updates", "the", "version", "file", "me...
def process_packages(self, report_errors=False): """Gets a list of updates to process. Adds the name of an update to the version file if not already present. Processes all packages. Updates the version file meta-data. Then writes version file back to disk. """ if self.patch_support: log.info("Patch support enabled") else: log.info("Patch support disabled") # Getting a list of meta data from all packages in the # pyu-data/new directory. Also create a patch manifest # to create patches. pkg_manifest, patch_manifest = self._get_package_list(report_errors) patches = PackageHandler._make_patches(patch_manifest) PackageHandler._cleanup(patch_manifest) PackageHandler._add_patches_to_packages( pkg_manifest, patches, self.patch_support ) PackageHandler._update_version_file(self.version_data, pkg_manifest) self._write_json_to_file(self.version_data) self._write_config_to_file(self.config) self._move_packages(pkg_manifest)
[ "def", "process_packages", "(", "self", ",", "report_errors", "=", "False", ")", ":", "if", "self", ".", "patch_support", ":", "log", ".", "info", "(", "\"Patch support enabled\"", ")", "else", ":", "log", ".", "info", "(", "\"Patch support disabled\"", ")", ...
https://github.com/Digital-Sapphire/PyUpdater/blob/d408f54a38ab63ab5f4bcf6471ac1a546357b29f/pyupdater/core/package_handler/__init__.py#L93-L118
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/mutagen/apev2.py
python
_APEValue._validate
(self, value)
Returns validated value or raises TypeError/ValueErrr
Returns validated value or raises TypeError/ValueErrr
[ "Returns", "validated", "value", "or", "raises", "TypeError", "/", "ValueErrr" ]
def _validate(self, value): """Returns validated value or raises TypeError/ValueErrr""" raise NotImplementedError
[ "def", "_validate", "(", "self", ",", "value", ")", ":", "raise", "NotImplementedError" ]
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/mutagen/apev2.py#L572-L575
scikit-learn/scikit-learn
1d1aadd0711b87d2a11c80aad15df6f8cf156712
sklearn/covariance/_shrunk_covariance.py
python
ledoit_wolf
(X, *, assume_centered=False, block_size=1000)
return shrunk_cov, shrinkage
Estimates the shrunk Ledoit-Wolf covariance matrix. Read more in the :ref:`User Guide <shrunk_covariance>`. Parameters ---------- X : array-like of shape (n_samples, n_features) Data from which to compute the covariance estimate assume_centered : bool, default=False If True, data will not be centered before computation. Useful to work with data whose mean is significantly equal to zero but is not exactly zero. If False, data will be centered before computation. block_size : int, default=1000 Size of blocks into which the covariance matrix will be split. This is purely a memory optimization and does not affect results. Returns ------- shrunk_cov : ndarray of shape (n_features, n_features) Shrunk covariance. shrinkage : float Coefficient in the convex combination used for the computation of the shrunk estimate. Notes ----- The regularized (shrunk) covariance is: (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features) where mu = trace(cov) / n_features
Estimates the shrunk Ledoit-Wolf covariance matrix.
[ "Estimates", "the", "shrunk", "Ledoit", "-", "Wolf", "covariance", "matrix", "." ]
def ledoit_wolf(X, *, assume_centered=False, block_size=1000): """Estimates the shrunk Ledoit-Wolf covariance matrix. Read more in the :ref:`User Guide <shrunk_covariance>`. Parameters ---------- X : array-like of shape (n_samples, n_features) Data from which to compute the covariance estimate assume_centered : bool, default=False If True, data will not be centered before computation. Useful to work with data whose mean is significantly equal to zero but is not exactly zero. If False, data will be centered before computation. block_size : int, default=1000 Size of blocks into which the covariance matrix will be split. This is purely a memory optimization and does not affect results. Returns ------- shrunk_cov : ndarray of shape (n_features, n_features) Shrunk covariance. shrinkage : float Coefficient in the convex combination used for the computation of the shrunk estimate. Notes ----- The regularized (shrunk) covariance is: (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features) where mu = trace(cov) / n_features """ X = check_array(X) # for only one feature, the result is the same whatever the shrinkage if len(X.shape) == 2 and X.shape[1] == 1: if not assume_centered: X = X - X.mean() return np.atleast_2d((X ** 2).mean()), 0.0 if X.ndim == 1: X = np.reshape(X, (1, -1)) warnings.warn( "Only one sample available. You may want to reshape your data array" ) n_features = X.size else: _, n_features = X.shape # get Ledoit-Wolf shrinkage shrinkage = ledoit_wolf_shrinkage( X, assume_centered=assume_centered, block_size=block_size ) emp_cov = empirical_covariance(X, assume_centered=assume_centered) mu = np.sum(np.trace(emp_cov)) / n_features shrunk_cov = (1.0 - shrinkage) * emp_cov shrunk_cov.flat[:: n_features + 1] += shrinkage * mu return shrunk_cov, shrinkage
[ "def", "ledoit_wolf", "(", "X", ",", "*", ",", "assume_centered", "=", "False", ",", "block_size", "=", "1000", ")", ":", "X", "=", "check_array", "(", "X", ")", "# for only one feature, the result is the same whatever the shrinkage", "if", "len", "(", "X", ".",...
https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/covariance/_shrunk_covariance.py#L283-L344
boostorg/build
aaa95bba19a7acb07badb1929737c67583b14ba0
src/build/feature.py
python
free_features
()
return __free_features
Returns all free features.
Returns all free features.
[ "Returns", "all", "free", "features", "." ]
def free_features (): """ Returns all free features. """ return __free_features
[ "def", "free_features", "(", ")", ":", "return", "__free_features" ]
https://github.com/boostorg/build/blob/aaa95bba19a7acb07badb1929737c67583b14ba0/src/build/feature.py#L564-L567
gkrizek/bash-lambda-layer
703b0ade8174022d44779d823172ab7ac33a5505
bin/botocore/config.py
python
Config.merge
(self, other_config)
return Config(**config_options)
Merges the config object with another config object This will merge in all non-default values from the provided config and return a new config object :type other_config: botocore.config.Config :param other config: Another config object to merge with. The values in the provided config object will take precedence in the merging :returns: A config object built from the merged values of both config objects.
Merges the config object with another config object
[ "Merges", "the", "config", "object", "with", "another", "config", "object" ]
def merge(self, other_config): """Merges the config object with another config object This will merge in all non-default values from the provided config and return a new config object :type other_config: botocore.config.Config :param other config: Another config object to merge with. The values in the provided config object will take precedence in the merging :returns: A config object built from the merged values of both config objects. """ # Make a copy of the current attributes in the config object. config_options = copy.copy(self._user_provided_options) # Merge in the user provided options from the other config config_options.update(other_config._user_provided_options) # Return a new config object with the merged properties. return Config(**config_options)
[ "def", "merge", "(", "self", ",", "other_config", ")", ":", "# Make a copy of the current attributes in the config object.", "config_options", "=", "copy", ".", "copy", "(", "self", ".", "_user_provided_options", ")", "# Merge in the user provided options from the other config"...
https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/botocore/config.py#L211-L231
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/lib2to3/fixer_base.py
python
BaseFix.warning
(self, node, reason)
Used for warning the user about possible uncertainty in the translation. First argument is the top-level node for the code in question. Optional second argument is why it can't be converted.
Used for warning the user about possible uncertainty in the translation.
[ "Used", "for", "warning", "the", "user", "about", "possible", "uncertainty", "in", "the", "translation", "." ]
def warning(self, node, reason): """Used for warning the user about possible uncertainty in the translation. First argument is the top-level node for the code in question. Optional second argument is why it can't be converted. """ lineno = node.get_lineno() self.log_message("Line %d: %s" % (lineno, reason))
[ "def", "warning", "(", "self", ",", "node", ",", "reason", ")", ":", "lineno", "=", "node", ".", "get_lineno", "(", ")", "self", ".", "log_message", "(", "\"Line %d: %s\"", "%", "(", "lineno", ",", "reason", ")", ")" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/lib2to3/fixer_base.py#L140-L148
criteo/biggraphite
1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30
biggraphite/glob_utils.py
python
CharNotIn.__init__
(self, values)
Initializes the CharNotIn.
Initializes the CharNotIn.
[ "Initializes", "the", "CharNotIn", "." ]
def __init__(self, values): """Initializes the CharNotIn.""" super(CharNotIn, self).__init__(values) self.negated = True
[ "def", "__init__", "(", "self", ",", "values", ")", ":", "super", "(", "CharNotIn", ",", "self", ")", ".", "__init__", "(", "values", ")", "self", ".", "negated", "=", "True" ]
https://github.com/criteo/biggraphite/blob/1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30/biggraphite/glob_utils.py#L419-L422
morganstanley/treadmill
f18267c665baf6def4374d21170198f63ff1cde4
lib/python/treadmill/cli/admin/master.py
python
monitor_group
(parent)
App monitor CLI group
App monitor CLI group
[ "App", "monitor", "CLI", "group" ]
def monitor_group(parent): """App monitor CLI group""" formatter = cli.make_formatter('app-monitor') @parent.group() def monitor(): """Manage app monitors configuration. """ @monitor.command() @click.option('-n', '--count', type=int, help='Instance count') @click.option('-p', '--policy', type=click.Choice(['fifo', 'lifo']), help='Instance scale policy: fifo (remove oldest first), ' 'lifo (remove newest first)') @click.argument('app') @cli.admin.ON_EXCEPTIONS def configure(app, count, policy): """Create, get or modify an app monitor configuration""" zkclient = context.GLOBAL.zk.conn options = {} if count is not None: options['count'] = count if policy is not None: options['policy'] = policy existing = masterapi.get_appmonitor(zkclient, app) # reconfigure if any of the parameters is specified if options: if count is None and existing is not None: count = existing.get('count') if policy is None and existing is not None: policy = existing.get('policy') data = masterapi.update_appmonitor(zkclient, app, count, policy) else: data = existing cli.out(formatter(data)) @monitor.command() @click.argument('app') @cli.admin.ON_EXCEPTIONS def delete(app): """Deletes app monitor""" masterapi.delete_appmonitor(context.GLOBAL.zk.conn, app) @monitor.command(name='list') def _list(): """List all configured monitors""" zkclient = context.GLOBAL.zk.conn suspended_monitors = masterapi.get_suspended_appmonitors(zkclient) monitors = [ masterapi.get_appmonitor( zkclient, app, suspended_monitors=suspended_monitors, ) for app in masterapi.appmonitors(zkclient) ] cli.out(formatter(monitors)) del delete del configure del _list
[ "def", "monitor_group", "(", "parent", ")", ":", "formatter", "=", "cli", ".", "make_formatter", "(", "'app-monitor'", ")", "@", "parent", ".", "group", "(", ")", "def", "monitor", "(", ")", ":", "\"\"\"Manage app monitors configuration.\n \"\"\"", "@", "...
https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/cli/admin/master.py#L220-L287
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/chardet/charsetprober.py
python
CharSetProber.filter_international_words
(buf)
return filtered
We define three types of bytes: alphabet: english alphabets [a-zA-Z] international: international characters [\x80-\xFF] marker: everything else [^a-zA-Z\x80-\xFF] The input buffer can be thought to contain a series of words delimited by markers. This function works to filter all words that contain at least one international character. All contiguous sequences of markers are replaced by a single space ascii character. This filter applies to all scripts which do not use English characters.
We define three types of bytes: alphabet: english alphabets [a-zA-Z] international: international characters [\x80-\xFF] marker: everything else [^a-zA-Z\x80-\xFF]
[ "We", "define", "three", "types", "of", "bytes", ":", "alphabet", ":", "english", "alphabets", "[", "a", "-", "zA", "-", "Z", "]", "international", ":", "international", "characters", "[", "\\", "x80", "-", "\\", "xFF", "]", "marker", ":", "everything", ...
def filter_international_words(buf): """ We define three types of bytes: alphabet: english alphabets [a-zA-Z] international: international characters [\x80-\xFF] marker: everything else [^a-zA-Z\x80-\xFF] The input buffer can be thought to contain a series of words delimited by markers. This function works to filter all words that contain at least one international character. All contiguous sequences of markers are replaced by a single space ascii character. This filter applies to all scripts which do not use English characters. """ filtered = bytearray() # This regex expression filters out only words that have at-least one # international character. The word may include one marker character at # the end. words = re.findall(b'[a-zA-Z]*[\x80-\xFF]+[a-zA-Z]*[^a-zA-Z\x80-\xFF]?', buf) for word in words: filtered.extend(word[:-1]) # If the last character in the word is a marker, replace it with a # space as markers shouldn't affect our analysis (they are used # similarly across all languages and may thus have similar # frequencies). last_char = word[-1:] if not last_char.isalpha() and last_char < b'\x80': last_char = b' ' filtered.extend(last_char) return filtered
[ "def", "filter_international_words", "(", "buf", ")", ":", "filtered", "=", "bytearray", "(", ")", "# This regex expression filters out only words that have at-least one", "# international character. The word may include one marker character at", "# the end.", "words", "=", "re", "...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/chardet/charsetprober.py#L67-L101
Kozea/cairocffi
2473d1bb82a52ca781edec595a95951509db2969
cairocffi/context.py
python
Context.get_dash
(self)
return list(dashes), offset[0]
Return the current dash pattern. :returns: A ``(dashes, offset)`` tuple of a list and a float. :obj:`dashes` is a list of floats, empty if no dashing is in effect.
Return the current dash pattern.
[ "Return", "the", "current", "dash", "pattern", "." ]
def get_dash(self): """Return the current dash pattern. :returns: A ``(dashes, offset)`` tuple of a list and a float. :obj:`dashes` is a list of floats, empty if no dashing is in effect. """ dashes = ffi.new('double[]', cairo.cairo_get_dash_count(self._pointer)) offset = ffi.new('double *') cairo.cairo_get_dash(self._pointer, dashes, offset) self._check_status() return list(dashes), offset[0]
[ "def", "get_dash", "(", "self", ")", ":", "dashes", "=", "ffi", ".", "new", "(", "'double[]'", ",", "cairo", ".", "cairo_get_dash_count", "(", "self", ".", "_pointer", ")", ")", "offset", "=", "ffi", ".", "new", "(", "'double *'", ")", "cairo", ".", ...
https://github.com/Kozea/cairocffi/blob/2473d1bb82a52ca781edec595a95951509db2969/cairocffi/context.py#L472-L485
Unidata/MetPy
1153590f397ae23adfea66c4adb0a206872fa0ad
examples/gridding/Natural_Neighbor_Verification.py
python
draw_polygon_with_info
(ax, polygon, off_x=0, off_y=0)
Draw one of the natural neighbor polygons with some information.
Draw one of the natural neighbor polygons with some information.
[ "Draw", "one", "of", "the", "natural", "neighbor", "polygons", "with", "some", "information", "." ]
def draw_polygon_with_info(ax, polygon, off_x=0, off_y=0): """Draw one of the natural neighbor polygons with some information.""" pts = np.array(polygon)[ConvexHull(polygon).vertices] for i, pt in enumerate(pts): ax.plot([pt[0], pts[(i + 1) % len(pts)][0]], [pt[1], pts[(i + 1) % len(pts)][1]], 'k-') avex, avey = np.mean(pts, axis=0) ax.annotate(f'area: {geometry.area(pts):.3f}', xy=(avex + off_x, avey + off_y), fontsize=12)
[ "def", "draw_polygon_with_info", "(", "ax", ",", "polygon", ",", "off_x", "=", "0", ",", "off_y", "=", "0", ")", ":", "pts", "=", "np", ".", "array", "(", "polygon", ")", "[", "ConvexHull", "(", "polygon", ")", ".", "vertices", "]", "for", "i", ","...
https://github.com/Unidata/MetPy/blob/1153590f397ae23adfea66c4adb0a206872fa0ad/examples/gridding/Natural_Neighbor_Verification.py#L197-L206
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/importlib/metadata.py
python
PackagePath.locate
(self)
return self.dist.locate_file(self)
Return a path-like object for this path
Return a path-like object for this path
[ "Return", "a", "path", "-", "like", "object", "for", "this", "path" ]
def locate(self): """Return a path-like object for this path""" return self.dist.locate_file(self)
[ "def", "locate", "(", "self", ")", ":", "return", "self", ".", "dist", ".", "locate_file", "(", "self", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/importlib/metadata.py#L130-L132
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/volatility/conf.py
python
ConfObject.__init__
(self)
This is a singleton object kept in the class
This is a singleton object kept in the class
[ "This", "is", "a", "singleton", "object", "kept", "in", "the", "class" ]
def __init__(self): """ This is a singleton object kept in the class """ if not ConfObject.initialised: self.optparser.add_option("-h", "--help", action = "store_true", default = False, help = "list all available options and their default values. Default values may be set in the configuration file (" + default_config + ")") ConfObject.initialised = True
[ "def", "__init__", "(", "self", ")", ":", "if", "not", "ConfObject", ".", "initialised", ":", "self", ".", "optparser", ".", "add_option", "(", "\"-h\"", ",", "\"--help\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", ...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/volatility/conf.py#L157-L163
UCL-INGI/INGInious
60f10cb4c375ce207471043e76bd813220b95399
inginious/frontend/user_manager.py
python
UserManager.session_api_key
(self)
return self.get_user_api_key(self.session_username())
Returns the API key for the current user. Created on first demand.
Returns the API key for the current user. Created on first demand.
[ "Returns", "the", "API", "key", "for", "the", "current", "user", ".", "Created", "on", "first", "demand", "." ]
def session_api_key(self): """ Returns the API key for the current user. Created on first demand. """ return self.get_user_api_key(self.session_username())
[ "def", "session_api_key", "(", "self", ")", ":", "return", "self", ".", "get_user_api_key", "(", "self", ".", "session_username", "(", ")", ")" ]
https://github.com/UCL-INGI/INGInious/blob/60f10cb4c375ce207471043e76bd813220b95399/inginious/frontend/user_manager.py#L181-L183
wechatpy/wechatpy
5f693a7e90156786c2540ad3c941d12cdf6d88ef
wechatpy/client/api/merchant/express.py
python
MerchantExpress.update
(self, template_id, delivery_template)
return self._post( "merchant/express/update", data={"template_id": template_id, "delivery_template": delivery_template}, )
[]
def update(self, template_id, delivery_template): return self._post( "merchant/express/update", data={"template_id": template_id, "delivery_template": delivery_template}, )
[ "def", "update", "(", "self", ",", "template_id", ",", "delivery_template", ")", ":", "return", "self", ".", "_post", "(", "\"merchant/express/update\"", ",", "data", "=", "{", "\"template_id\"", ":", "template_id", ",", "\"delivery_template\"", ":", "delivery_tem...
https://github.com/wechatpy/wechatpy/blob/5f693a7e90156786c2540ad3c941d12cdf6d88ef/wechatpy/client/api/merchant/express.py#L16-L20
ncoudray/DeepPATH
62bf7e7f74a80889f1e07890b8fe814f076f780d
DeepPATH_code/01_training/xClasses/inception/data/build_imagenet_data.py
python
_process_dataset
(name, directory, num_shards, synset_to_human, image_to_bboxes)
Process a complete data set and save it as a TFRecord. Args: name: string, unique identifier specifying the data set. directory: string, root path to the data set. num_shards: integer number of shards for this data set. synset_to_human: dict of synset to human labels, e.g., 'n02119022' --> 'red fox, Vulpes vulpes' image_to_bboxes: dictionary mapping image file names to a list of bounding boxes. This list contains 0+ bounding boxes.
Process a complete data set and save it as a TFRecord.
[ "Process", "a", "complete", "data", "set", "and", "save", "it", "as", "a", "TFRecord", "." ]
def _process_dataset(name, directory, num_shards, synset_to_human, image_to_bboxes): """Process a complete data set and save it as a TFRecord. Args: name: string, unique identifier specifying the data set. directory: string, root path to the data set. num_shards: integer number of shards for this data set. synset_to_human: dict of synset to human labels, e.g., 'n02119022' --> 'red fox, Vulpes vulpes' image_to_bboxes: dictionary mapping image file names to a list of bounding boxes. This list contains 0+ bounding boxes. """ filenames, synsets, labels = _find_image_files(directory, FLAGS.labels_file) humans = _find_human_readable_labels(synsets, synset_to_human) bboxes = _find_image_bounding_boxes(filenames, image_to_bboxes) _process_image_files(name, filenames, synsets, labels, humans, bboxes, num_shards)
[ "def", "_process_dataset", "(", "name", ",", "directory", ",", "num_shards", ",", "synset_to_human", ",", "image_to_bboxes", ")", ":", "filenames", ",", "synsets", ",", "labels", "=", "_find_image_files", "(", "directory", ",", "FLAGS", ".", "labels_file", ")", ...
https://github.com/ncoudray/DeepPATH/blob/62bf7e7f74a80889f1e07890b8fe814f076f780d/DeepPATH_code/01_training/xClasses/inception/data/build_imagenet_data.py#L583-L600
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/evaluate/owrocanalysis.py
python
roc_curve_threshold_average
(curves, thresh_samples)
return ((fpr_samples.mean(axis=0), fpr_samples.std(axis=0)), (tpr_samples.mean(axis=0), fpr_samples.std(axis=0)))
[]
def roc_curve_threshold_average(curves, thresh_samples): if not curves: raise ValueError("No curves") fpr_samples, tpr_samples = [], [] for fpr, tpr, thresh in curves: ind = np.searchsorted(thresh[::-1], thresh_samples, side="left") ind = ind[::-1] ind = np.clip(ind, 0, len(thresh) - 1) fpr_samples.append(fpr[ind]) tpr_samples.append(tpr[ind]) fpr_samples = np.array(fpr_samples) tpr_samples = np.array(tpr_samples) return ((fpr_samples.mean(axis=0), fpr_samples.std(axis=0)), (tpr_samples.mean(axis=0), fpr_samples.std(axis=0)))
[ "def", "roc_curve_threshold_average", "(", "curves", ",", "thresh_samples", ")", ":", "if", "not", "curves", ":", "raise", "ValueError", "(", "\"No curves\"", ")", "fpr_samples", ",", "tpr_samples", "=", "[", "]", ",", "[", "]", "for", "fpr", ",", "tpr", "...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/evaluate/owrocanalysis.py#L849-L864
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py
python
TaskQueueCumulativeStatisticsInstance.tasks_deleted
(self)
return self._properties['tasks_deleted']
:returns: The total number of Tasks deleted in the TaskQueue :rtype: unicode
:returns: The total number of Tasks deleted in the TaskQueue :rtype: unicode
[ ":", "returns", ":", "The", "total", "number", "of", "Tasks", "deleted", "in", "the", "TaskQueue", ":", "rtype", ":", "unicode" ]
def tasks_deleted(self): """ :returns: The total number of Tasks deleted in the TaskQueue :rtype: unicode """ return self._properties['tasks_deleted']
[ "def", "tasks_deleted", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'tasks_deleted'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py#L374-L379
cantools/cantools
8d86d61bc010f328cf414150331fecfd4b6f4dc3
cantools/database/can/signal.py
python
NamedSignalValue.value
(self)
return self._value
The integer value that gets mapped
The integer value that gets mapped
[ "The", "integer", "value", "that", "gets", "mapped" ]
def value(self) -> int: """The integer value that gets mapped """ return self._value
[ "def", "value", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_value" ]
https://github.com/cantools/cantools/blob/8d86d61bc010f328cf414150331fecfd4b6f4dc3/cantools/database/can/signal.py#L110-L114
eth-brownie/brownie
754bda9f0a294b2beb86453d5eca4ff769a877c8
brownie/utils/docopt.py
python
BranchPattern.fix_repeating_arguments
(self)
return self
Fix elements that should accumulate/increment values.
Fix elements that should accumulate/increment values.
[ "Fix", "elements", "that", "should", "accumulate", "/", "increment", "values", "." ]
def fix_repeating_arguments(self) -> "BranchPattern": """Fix elements that should accumulate/increment values.""" either = [list(child.children) for child in transform(self).children] for case in either: for e in [child for child in case if case.count(child) > 1]: if type(e) is Argument or type(e) is Option and e.argcount: if e.value is None: e.value = [] elif type(e.value) is not list: e.value = e.value.split() if type(e) is Command or type(e) is Option and e.argcount == 0: e.value = 0 return self
[ "def", "fix_repeating_arguments", "(", "self", ")", "->", "\"BranchPattern\"", ":", "either", "=", "[", "list", "(", "child", ".", "children", ")", "for", "child", "in", "transform", "(", "self", ")", ".", "children", "]", "for", "case", "in", "either", ...
https://github.com/eth-brownie/brownie/blob/754bda9f0a294b2beb86453d5eca4ff769a877c8/brownie/utils/docopt.py#L241-L253
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/_strptime.py
python
_strptime
(data_string, format="%a %b %d %H:%M:%S %Y")
return (year, month, day, hour, minute, second, weekday, julian, tz, tzname, gmtoff), fraction
Return a 2-tuple consisting of a time struct and an int containing the number of microseconds based on the input string and the format string.
Return a 2-tuple consisting of a time struct and an int containing the number of microseconds based on the input string and the format string.
[ "Return", "a", "2", "-", "tuple", "consisting", "of", "a", "time", "struct", "and", "an", "int", "containing", "the", "number", "of", "microseconds", "based", "on", "the", "input", "string", "and", "the", "format", "string", "." ]
def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a 2-tuple consisting of a time struct and an int containing the number of microseconds based on the input string and the format string.""" for index, arg in enumerate([data_string, format]): if not isinstance(arg, str): msg = "strptime() argument {} must be str, not {}" raise TypeError(msg.format(index, type(arg))) global _TimeRE_cache, _regex_cache with _cache_lock: locale_time = _TimeRE_cache.locale_time if (_getlang() != locale_time.lang or time.tzname != locale_time.tzname or time.daylight != locale_time.daylight): _TimeRE_cache = TimeRE() _regex_cache.clear() locale_time = _TimeRE_cache.locale_time if len(_regex_cache) > _CACHE_MAX_SIZE: _regex_cache.clear() format_regex = _regex_cache.get(format) if not format_regex: try: format_regex = _TimeRE_cache.compile(format) # KeyError raised when a bad format is found; can be specified as # \\, in which case it was a stray % but with a space after it except KeyError as err: bad_directive = err.args[0] if bad_directive == "\\": bad_directive = "%" del err raise ValueError("'%s' is a bad directive in format '%s'" % (bad_directive, format)) from None # IndexError only occurs when the format string is "%" except IndexError: raise ValueError("stray %% in format '%s'" % format) from None _regex_cache[format] = format_regex found = format_regex.match(data_string) if not found: raise ValueError("time data %r does not match format %r" % (data_string, format)) if len(data_string) != found.end(): raise ValueError("unconverted data remains: %s" % data_string[found.end():]) year = None month = day = 1 hour = minute = second = fraction = 0 tz = -1 tzoffset = None # Default to -1 to signify that values not known; not critical to have, # though week_of_year = -1 week_of_year_start = -1 # weekday and julian defaulted to None so as to signal need to calculate # values weekday = julian = None found_dict = found.groupdict() for group_key in found_dict.keys(): # Directives not explicitly handled below: # c, x, X # handled by making out of other directives # U, W # worthless without day of the week if group_key == 'y': year = int(found_dict['y']) # Open Group specification for strptime() states that a %y #value in the range of [00, 68] is in the century 2000, while #[69,99] is in the century 1900 if year <= 68: year += 2000 else: year += 1900 elif group_key == 'Y': year = int(found_dict['Y']) elif group_key == 'm': month = int(found_dict['m']) elif group_key == 'B': month = locale_time.f_month.index(found_dict['B'].lower()) elif group_key == 'b': month = locale_time.a_month.index(found_dict['b'].lower()) elif group_key == 'd': day = int(found_dict['d']) elif group_key == 'H': hour = int(found_dict['H']) elif group_key == 'I': hour = int(found_dict['I']) ampm = found_dict.get('p', '').lower() # If there was no AM/PM indicator, we'll treat this like AM if ampm in ('', locale_time.am_pm[0]): # We're in AM so the hour is correct unless we're # looking at 12 midnight. # 12 midnight == 12 AM == hour 0 if hour == 12: hour = 0 elif ampm == locale_time.am_pm[1]: # We're in PM so we need to add 12 to the hour unless # we're looking at 12 noon. # 12 noon == 12 PM == hour 12 if hour != 12: hour += 12 elif group_key == 'M': minute = int(found_dict['M']) elif group_key == 'S': second = int(found_dict['S']) elif group_key == 'f': s = found_dict['f'] # Pad to always return microseconds. s += "0" * (6 - len(s)) fraction = int(s) elif group_key == 'A': weekday = locale_time.f_weekday.index(found_dict['A'].lower()) elif group_key == 'a': weekday = locale_time.a_weekday.index(found_dict['a'].lower()) elif group_key == 'w': weekday = int(found_dict['w']) if weekday == 0: weekday = 6 else: weekday -= 1 elif group_key == 'j': julian = int(found_dict['j']) elif group_key in ('U', 'W'): week_of_year = int(found_dict[group_key]) if group_key == 'U': # U starts week on Sunday. week_of_year_start = 6 else: # W starts week on Monday. week_of_year_start = 0 elif group_key == 'z': z = found_dict['z'] tzoffset = int(z[1:3]) * 60 + int(z[3:5]) if z.startswith("-"): tzoffset = -tzoffset elif group_key == 'Z': # Since -1 is default value only need to worry about setting tz if # it can be something other than -1. found_zone = found_dict['Z'].lower() for value, tz_values in enumerate(locale_time.timezone): if found_zone in tz_values: # Deal with bad locale setup where timezone names are the # same and yet time.daylight is true; too ambiguous to # be able to tell what timezone has daylight savings if (time.tzname[0] == time.tzname[1] and time.daylight and found_zone not in ("utc", "gmt")): break else: tz = value break leap_year_fix = False if year is None and month == 2 and day == 29: year = 1904 # 1904 is first leap year of 20th century leap_year_fix = True elif year is None: year = 1900 # If we know the week of the year and what day of that week, we can figure # out the Julian day of the year. if julian is None and week_of_year != -1 and weekday is not None: week_starts_Mon = True if week_of_year_start == 0 else False julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, week_starts_Mon) # Cannot pre-calculate datetime_date() since can change in Julian # calculation and thus could have different value for the day of the week # calculation. if julian is None: # Need to add 1 to result since first day of the year is 1, not 0. julian = datetime_date(year, month, day).toordinal() - \ datetime_date(year, 1, 1).toordinal() + 1 else: # Assume that if they bothered to include Julian day it will # be accurate. datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal()) year = datetime_result.year month = datetime_result.month day = datetime_result.day if weekday is None: weekday = datetime_date(year, month, day).weekday() # Add timezone info tzname = found_dict.get("Z") if tzoffset is not None: gmtoff = tzoffset * 60 else: gmtoff = None if leap_year_fix: # the caller didn't supply a year but asked for Feb 29th. We couldn't # use the default of 1900 for computations. We set it back to ensure # that February 29th is smaller than March 1st. year = 1900 return (year, month, day, hour, minute, second, weekday, julian, tz, tzname, gmtoff), fraction
[ "def", "_strptime", "(", "data_string", ",", "format", "=", "\"%a %b %d %H:%M:%S %Y\"", ")", ":", "for", "index", ",", "arg", "in", "enumerate", "(", "[", "data_string", ",", "format", "]", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "str", ")"...
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/_strptime.py#L302-L496
vyos/vyos-1x
6e8a8934a7d4e1b21d7c828e372303683b499b56
python/vyos/migrator.py
python
Migrator.save_json_record
(self, component_versions: dict)
Write component versions to a json file
Write component versions to a json file
[ "Write", "component", "versions", "to", "a", "json", "file" ]
def save_json_record(self, component_versions: dict): """ Write component versions to a json file """ mask = os.umask(0o113) version_file = vyos.defaults.component_version_json try: with open(version_file, 'w') as f: f.write(json.dumps(component_versions, indent=2, sort_keys=True)) except OSError: pass finally: os.umask(mask)
[ "def", "save_json_record", "(", "self", ",", "component_versions", ":", "dict", ")", ":", "mask", "=", "os", ".", "umask", "(", "0o113", ")", "version_file", "=", "vyos", ".", "defaults", ".", "component_version_json", "try", ":", "with", "open", "(", "ver...
https://github.com/vyos/vyos-1x/blob/6e8a8934a7d4e1b21d7c828e372303683b499b56/python/vyos/migrator.py#L169-L181
p4-team/ctf
05ab90cd04ea26f0fca860579939617f57961a1a
2017-02-25-bkp/sponge/hash.py
python
Hasher.hash
(self, s)
return self.squeeze() + self.squeeze()
Hash an input of any length of bytes. Return a 160-bit digest.
Hash an input of any length of bytes. Return a 160-bit digest.
[ "Hash", "an", "input", "of", "any", "length", "of", "bytes", ".", "Return", "a", "160", "-", "bit", "digest", "." ]
def hash(self, s): """Hash an input of any length of bytes. Return a 160-bit digest.""" self.reset() blocks = len(s) // 10 for i in range(blocks): self.ingest(s[10*i:10*(i+1)]) self.final_ingest(s[blocks*10:]) return self.squeeze() + self.squeeze()
[ "def", "hash", "(", "self", ",", "s", ")", ":", "self", ".", "reset", "(", ")", "blocks", "=", "len", "(", "s", ")", "//", "10", "for", "i", "in", "range", "(", "blocks", ")", ":", "self", ".", "ingest", "(", "s", "[", "10", "*", "i", ":", ...
https://github.com/p4-team/ctf/blob/05ab90cd04ea26f0fca860579939617f57961a1a/2017-02-25-bkp/sponge/hash.py#L41-L49
runawayhorse001/LearningApacheSpark
67f3879dce17553195f094f5728b94a01badcf24
pyspark/sql/functions.py
python
unix_timestamp
(timestamp=None, format='yyyy-MM-dd HH:mm:ss')
return Column(sc._jvm.functions.unix_timestamp(_to_java_column(timestamp), format))
Convert time string with given pattern ('yyyy-MM-dd HH:mm:ss', by default) to Unix time stamp (in seconds), using the default timezone and the default locale, return null if fail. if `timestamp` is None, then it returns current timestamp. >>> spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") >>> time_df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> time_df.select(unix_timestamp('dt', 'yyyy-MM-dd').alias('unix_time')).collect() [Row(unix_time=1428476400)] >>> spark.conf.unset("spark.sql.session.timeZone")
Convert time string with given pattern ('yyyy-MM-dd HH:mm:ss', by default) to Unix time stamp (in seconds), using the default timezone and the default locale, return null if fail.
[ "Convert", "time", "string", "with", "given", "pattern", "(", "yyyy", "-", "MM", "-", "dd", "HH", ":", "mm", ":", "ss", "by", "default", ")", "to", "Unix", "time", "stamp", "(", "in", "seconds", ")", "using", "the", "default", "timezone", "and", "the...
def unix_timestamp(timestamp=None, format='yyyy-MM-dd HH:mm:ss'): """ Convert time string with given pattern ('yyyy-MM-dd HH:mm:ss', by default) to Unix time stamp (in seconds), using the default timezone and the default locale, return null if fail. if `timestamp` is None, then it returns current timestamp. >>> spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") >>> time_df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> time_df.select(unix_timestamp('dt', 'yyyy-MM-dd').alias('unix_time')).collect() [Row(unix_time=1428476400)] >>> spark.conf.unset("spark.sql.session.timeZone") """ sc = SparkContext._active_spark_context if timestamp is None: return Column(sc._jvm.functions.unix_timestamp()) return Column(sc._jvm.functions.unix_timestamp(_to_java_column(timestamp), format))
[ "def", "unix_timestamp", "(", "timestamp", "=", "None", ",", "format", "=", "'yyyy-MM-dd HH:mm:ss'", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "if", "timestamp", "is", "None", ":", "return", "Column", "(", "sc", ".", "_jvm", ".", "fu...
https://github.com/runawayhorse001/LearningApacheSpark/blob/67f3879dce17553195f094f5728b94a01badcf24/pyspark/sql/functions.py#L1236-L1253
saymedia/remoteobjects
d250e9a0e53c53744cb16c5fb2dc136df3785c1f
examples/twitter.py
python
Status.get_status
(cls, id, http=None)
return cls.get(urljoin(Twitter.endpoint, "/statuses/show/%d.json" % int(id)), http=http)
[]
def get_status(cls, id, http=None): return cls.get(urljoin(Twitter.endpoint, "/statuses/show/%d.json" % int(id)), http=http)
[ "def", "get_status", "(", "cls", ",", "id", ",", "http", "=", "None", ")", ":", "return", "cls", ".", "get", "(", "urljoin", "(", "Twitter", ".", "endpoint", ",", "\"/statuses/show/%d.json\"", "%", "int", "(", "id", ")", ")", ",", "http", "=", "http"...
https://github.com/saymedia/remoteobjects/blob/d250e9a0e53c53744cb16c5fb2dc136df3785c1f/examples/twitter.py#L129-L130
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/distutils/text_file.py
python
TextFile.open
(self, filename)
Open a new file named 'filename'. This overrides both the 'filename' and 'file' arguments to the constructor.
Open a new file named 'filename'. This overrides both the 'filename' and 'file' arguments to the constructor.
[ "Open", "a", "new", "file", "named", "filename", ".", "This", "overrides", "both", "the", "filename", "and", "file", "arguments", "to", "the", "constructor", "." ]
def open (self, filename): """Open a new file named 'filename'. This overrides both the 'filename' and 'file' arguments to the constructor.""" self.filename = filename self.file = open (self.filename, 'r') self.current_line = 0
[ "def", "open", "(", "self", ",", "filename", ")", ":", "self", ".", "filename", "=", "filename", "self", ".", "file", "=", "open", "(", "self", ".", "filename", ",", "'r'", ")", "self", ".", "current_line", "=", "0" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/distutils/text_file.py#L115-L121
neubig/nn4nlp-code
970d91a51664b3d91a9822b61cd76abea20218cb
14-semparsing/ucca/ucca/core.py
python
Passage.layer
(self, ID)
return self._layers[ID]
Returns the :class:Layer object whose ID is given. :param ID: ID of the Layer requested. :raise KeyError: if no Layer with this ID is present
Returns the :class:Layer object whose ID is given.
[ "Returns", "the", ":", "class", ":", "Layer", "object", "whose", "ID", "is", "given", "." ]
def layer(self, ID): """Returns the :class:Layer object whose ID is given. :param ID: ID of the Layer requested. :raise KeyError: if no Layer with this ID is present """ return self._layers[ID]
[ "def", "layer", "(", "self", ",", "ID", ")", ":", "return", "self", ".", "_layers", "[", "ID", "]" ]
https://github.com/neubig/nn4nlp-code/blob/970d91a51664b3d91a9822b61cd76abea20218cb/14-semparsing/ucca/ucca/core.py#L829-L837
InQuest/ThreatIngestor
28d41bc991aad994d3bb8218d6f79779b889ab4d
threatingestor/sources/__init__.py
python
Source.__init__
(self, name, *args, **kwargs)
Override this constructor in child classes. The first argument must always be ``name``. Other argumentss should be url, auth, etc, whatever is needed to set up the object.
Override this constructor in child classes.
[ "Override", "this", "constructor", "in", "child", "classes", "." ]
def __init__(self, name, *args, **kwargs): """Override this constructor in child classes. The first argument must always be ``name``. Other argumentss should be url, auth, etc, whatever is needed to set up the object. """ raise NotImplementedError()
[ "def", "__init__", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/InQuest/ThreatIngestor/blob/28d41bc991aad994d3bb8218d6f79779b889ab4d/threatingestor/sources/__init__.py#L24-L32
emedvedev/attention-ocr
2ef51cba4770b86fccd34bae4e77d8f3eda3e797
aocr/model/cnn.py
python
tf_create_attention_map
(incoming)
return tf.reshape(incoming, (-1, np.prod(shape[1:3]), shape[3]))
flatten hight and width into one dimention of size attn_length :param incoming: 3D Tensor [batch_size x cur_h x cur_w x num_channels] :return: attention_map: 3D Tensor [batch_size x attn_length x attn_size].
flatten hight and width into one dimention of size attn_length :param incoming: 3D Tensor [batch_size x cur_h x cur_w x num_channels] :return: attention_map: 3D Tensor [batch_size x attn_length x attn_size].
[ "flatten", "hight", "and", "width", "into", "one", "dimention", "of", "size", "attn_length", ":", "param", "incoming", ":", "3D", "Tensor", "[", "batch_size", "x", "cur_h", "x", "cur_w", "x", "num_channels", "]", ":", "return", ":", "attention_map", ":", "...
def tf_create_attention_map(incoming): ''' flatten hight and width into one dimention of size attn_length :param incoming: 3D Tensor [batch_size x cur_h x cur_w x num_channels] :return: attention_map: 3D Tensor [batch_size x attn_length x attn_size]. ''' shape = incoming.get_shape().as_list() return tf.reshape(incoming, (-1, np.prod(shape[1:3]), shape[3]))
[ "def", "tf_create_attention_map", "(", "incoming", ")", ":", "shape", "=", "incoming", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "return", "tf", ".", "reshape", "(", "incoming", ",", "(", "-", "1", ",", "np", ".", "prod", "(", "shape", "[...
https://github.com/emedvedev/attention-ocr/blob/2ef51cba4770b86fccd34bae4e77d8f3eda3e797/aocr/model/cnn.py#L108-L115
bethesirius/ChosunTruck
889644385ce57f971ec2921f006fbb0a167e6f1e
linux/tensorbox/pymouse/x11.py
python
PyMouseEvent.run
(self)
[]
def run(self): try: if self.capture and self.capture_move: capturing = X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask elif self.capture: capturing = X.ButtonPressMask | X.ButtonReleaseMask elif self.capture_move: capturing = X.PointerMotionMask else: capturing = False if capturing: self.display2.screen().root.grab_pointer(True, capturing, X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime) self.display.screen().root.grab_pointer(True, capturing, X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime) self.display2.record_enable_context(self.ctx, self.handler) self.display2.record_free_context(self.ctx) except KeyboardInterrupt: self.stop()
[ "def", "run", "(", "self", ")", ":", "try", ":", "if", "self", ".", "capture", "and", "self", ".", "capture_move", ":", "capturing", "=", "X", ".", "ButtonPressMask", "|", "X", ".", "ButtonReleaseMask", "|", "X", ".", "PointerMotionMask", "elif", "self",...
https://github.com/bethesirius/ChosunTruck/blob/889644385ce57f971ec2921f006fbb0a167e6f1e/linux/tensorbox/pymouse/x11.py#L168-L194
zzzeek/sqlalchemy
fc5c54fcd4d868c2a4c7ac19668d72f506fe821e
lib/sqlalchemy/orm/attributes.py
python
CollectionAttributeImpl.set_committed_value
(self, state, dict_, value)
return user_data
Set an attribute value on the given instance and 'commit' it.
Set an attribute value on the given instance and 'commit' it.
[ "Set", "an", "attribute", "value", "on", "the", "given", "instance", "and", "commit", "it", "." ]
def set_committed_value(self, state, dict_, value): """Set an attribute value on the given instance and 'commit' it.""" collection, user_data = self._initialize_collection(state) if value: collection.append_multiple_without_event(value) state.dict[self.key] = user_data state._commit(dict_, [self.key]) if self.key in state._pending_mutations: # pending items exist. issue a modified event, # add/remove new items. state._modified_event(dict_, self, user_data, True) pending = state._pending_mutations.pop(self.key) added = pending.added_items removed = pending.deleted_items for item in added: collection.append_without_event(item) for item in removed: collection.remove_without_event(item) return user_data
[ "def", "set_committed_value", "(", "self", ",", "state", ",", "dict_", ",", "value", ")", ":", "collection", ",", "user_data", "=", "self", ".", "_initialize_collection", "(", "state", ")", "if", "value", ":", "collection", ".", "append_multiple_without_event", ...
https://github.com/zzzeek/sqlalchemy/blob/fc5c54fcd4d868c2a4c7ac19668d72f506fe821e/lib/sqlalchemy/orm/attributes.py#L1608-L1633
tensorflow/tensor2tensor
2a33b152d7835af66a6d20afe7961751047e28dd
tensor2tensor/models/research/transformer_vae_flow_prior_ops.py
python
generic_loss
(top_out, targets, model_hparams, vocab_size, weights_fn)
return common_layers.padded_cross_entropy( logits, targets, model_hparams.label_smoothing, cutoff=cutoff, weights_fn=weights_fn, reduce_sum=False)
Compute loss numerator and denominator for one shard of output.
Compute loss numerator and denominator for one shard of output.
[ "Compute", "loss", "numerator", "and", "denominator", "for", "one", "shard", "of", "output", "." ]
def generic_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Compute loss numerator and denominator for one shard of output.""" del vocab_size # unused arg logits = top_out logits = common_attention.maybe_upcast(logits, hparams=model_hparams) cutoff = getattr(model_hparams, "video_modality_loss_cutoff", 0.0) return common_layers.padded_cross_entropy( logits, targets, model_hparams.label_smoothing, cutoff=cutoff, weights_fn=weights_fn, reduce_sum=False)
[ "def", "generic_loss", "(", "top_out", ",", "targets", ",", "model_hparams", ",", "vocab_size", ",", "weights_fn", ")", ":", "del", "vocab_size", "# unused arg", "logits", "=", "top_out", "logits", "=", "common_attention", ".", "maybe_upcast", "(", "logits", ","...
https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/models/research/transformer_vae_flow_prior_ops.py#L353-L365
openstack/tempest
fe0ac89a5a1c43fa908a76759cd99eea3b1f9853
tempest/lib/services/compute/keypairs_client.py
python
KeyPairsClient.list_keypairs
(self, **params)
return rest_client.ResponseBody(resp, body)
Lists keypairs that are associated with the account. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-keypairs
Lists keypairs that are associated with the account.
[ "Lists", "keypairs", "that", "are", "associated", "with", "the", "account", "." ]
def list_keypairs(self, **params): """Lists keypairs that are associated with the account. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-keypairs """ url = 'os-keypairs' if params: url += '?%s' % urllib.urlencode(params) resp, body = self.get(url) body = json.loads(body) schema = self.get_schema(self.schema_versions_info) self.validate_response(schema.list_keypairs, resp, body) return rest_client.ResponseBody(resp, body)
[ "def", "list_keypairs", "(", "self", ",", "*", "*", "params", ")", ":", "url", "=", "'os-keypairs'", "if", "params", ":", "url", "+=", "'?%s'", "%", "urllib", ".", "urlencode", "(", "params", ")", "resp", ",", "body", "=", "self", ".", "get", "(", ...
https://github.com/openstack/tempest/blob/fe0ac89a5a1c43fa908a76759cd99eea3b1f9853/tempest/lib/services/compute/keypairs_client.py#L31-L45
selfteaching/selfteaching-python-camp
9982ee964b984595e7d664b07c389cddaf158f1e
exercises/1901050024/d09/mymodule/stats_word.py
python
stats_text_en
(en,count1)
1. 英文词频统计:使用正则表达式过滤英文字符,使用Counter统计并排序。 2. 参数类型检查,不为字符串抛出异常。
1. 英文词频统计:使用正则表达式过滤英文字符,使用Counter统计并排序。 2. 参数类型检查,不为字符串抛出异常。
[ "1", ".", "英文词频统计:使用正则表达式过滤英文字符,使用Counter统计并排序。", "2", ".", "参数类型检查,不为字符串抛出异常。" ]
def stats_text_en(en,count1): ''' 1. 英文词频统计:使用正则表达式过滤英文字符,使用Counter统计并排序。 2. 参数类型检查,不为字符串抛出异常。 ''' if type(en) == str : text_en = re.sub("[^A-Za-z]", " ", en.strip()) enList = text_en.split( ) count1 = int(input('请输入获取的英文单词数量:')) return collections.Counter(enList).most_common(count1) else: raise ValueError ('type of argumengt is not str')
[ "def", "stats_text_en", "(", "en", ",", "count1", ")", ":", "if", "type", "(", "en", ")", "==", "str", ":", "text_en", "=", "re", ".", "sub", "(", "\"[^A-Za-z]\"", ",", "\" \"", ",", "en", ".", "strip", "(", ")", ")", "enList", "=", "text_en", "....
https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/exercises/1901050024/d09/mymodule/stats_word.py#L4-L14
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/asyncio/futures.py
python
Future.done
(self)
return self._state != _PENDING
Return True if the future is done. Done means either that a result / exception are available, or that the future was cancelled.
Return True if the future is done.
[ "Return", "True", "if", "the", "future", "is", "done", "." ]
def done(self): """Return True if the future is done. Done means either that a result / exception are available, or that the future was cancelled. """ return self._state != _PENDING
[ "def", "done", "(", "self", ")", ":", "return", "self", ".", "_state", "!=", "_PENDING" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/asyncio/futures.py#L157-L163
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/analyses/decompiler/utils.py
python
insert_node
(parent, insert_idx, node, node_idx, label=None, insert_location=None)
[]
def insert_node(parent, insert_idx, node, node_idx, label=None, insert_location=None): if isinstance(parent, SequenceNode): parent.nodes.insert(insert_idx, node) elif isinstance(parent, CodeNode): # Make a new sequence node seq = SequenceNode(parent.addr, nodes=[parent.node, node]) parent.node = seq elif isinstance(parent, MultiNode): parent.nodes.insert(insert_idx, node) elif isinstance(parent, ConditionNode): if node_idx == 0: # true node if not isinstance(parent.true_node, (SequenceNode, MultiNode)): parent.true_node = SequenceNode(parent.true_node.addr, nodes=[parent.true_node]) insert_node(parent.true_node, insert_idx - node_idx, node, 0) else: # false node if not isinstance(parent.false_node, (SequenceNode, MultiNode)): parent.false_node = SequenceNode(parent.false_node.addr, nodes=[parent.false_node]) insert_node(parent.false_node, insert_idx - node_idx, node, 0) elif isinstance(parent, CascadingConditionNode): cond, child_node = parent.condition_and_nodes[node_idx] if not isinstance(child_node, SequenceNode): child_node = SequenceNode(child_node.addr, nodes=[child_node]) parent.condition_and_nodes[node_idx] = (cond, child_node) insert_node(child_node, insert_idx - node_idx, node, 0) elif isinstance(parent, SwitchCaseNode): # note that this case will be hit only when the parent node is not a container, such as SequenceNode or # MultiNode. we always need to create a new SequenceNode and replace the original node in place. if label == 'switch_expr': raise TypeError("You cannot insert a node after an expression.") if label == 'case': # node_idx is the case number if insert_location == 'after': new_nodes = [ parent.cases[node_idx], node ] elif insert_location == 'before': new_nodes = [ node, parent.cases[node_idx] ] else: raise TypeError("Unsupported 'insert_location' value %r." % insert_location) seq = SequenceNode(new_nodes[0].addr, nodes=new_nodes) parent.cases[node_idx] = seq elif label == 'default': if insert_location == 'after': new_nodes = [ parent.default_node, node ] elif insert_location == 'before': new_nodes = [ node, parent.default_node ] else: raise TypeError("Unsupported 'insert_location' value %r." % insert_location) seq = SequenceNode(new_nodes[0].addr, nodes=new_nodes) parent.default_node = seq else: raise NotImplementedError()
[ "def", "insert_node", "(", "parent", ",", "insert_idx", ",", "node", ",", "node_idx", ",", "label", "=", "None", ",", "insert_location", "=", "None", ")", ":", "if", "isinstance", "(", "parent", ",", "SequenceNode", ")", ":", "parent", ".", "nodes", ".",...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/analyses/decompiler/utils.py#L148-L200
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/data/kb/vuln_templates/base_template.py
python
BaseTemplate.get_options
(self)
return ol
In this case we provide a sample implementation since most vulnerabilities will have this template. If the specific vulnerability needs other params then it should override this implementation.
In this case we provide a sample implementation since most vulnerabilities will have this template. If the specific vulnerability needs other params then it should override this implementation.
[ "In", "this", "case", "we", "provide", "a", "sample", "implementation", "since", "most", "vulnerabilities", "will", "have", "this", "template", ".", "If", "the", "specific", "vulnerability", "needs", "other", "params", "then", "it", "should", "override", "this",...
def get_options(self): """ In this case we provide a sample implementation since most vulnerabilities will have this template. If the specific vulnerability needs other params then it should override this implementation. """ ol = OptionList() d = 'Vulnerability name (eg. SQL Injection)' o = opt_factory('name', self.name, d, 'string') ol.add(o) d = 'URL (without query string parameters)' o = opt_factory('url', self.url, d, 'url') ol.add(o) d = 'Query string or postdata parameters in url-encoded form' h = 'If the HTTP method is GET, the data will be sent in the ' \ 'query-string otherwise it will be sent using the HTTP request\'s' \ ' body. If the vulnerability requires the request to be sent using'\ ' multipart-forms, the exploit will convert this url-encoded data' \ ' into that format.\n\n'\ 'Enter the original parameter value, not the one which triggers'\ ' the vulnerability. Correct input looks like "id=2" not like'\ ' "id=2;cat /etc/passwd".' o = opt_factory('data', self.data, d, 'string', help=h) ol.add(o) d = 'HTTP method' o = opt_factory('method', self.method, d, 'string') ol.add(o) d = 'Vulnerable parameter (needs to be one of the entered in the data'\ ' field).' o = opt_factory('vulnerable_parameter', self.vulnerable_parameter, d, 'string') ol.add(o) return ol
[ "def", "get_options", "(", "self", ")", ":", "ol", "=", "OptionList", "(", ")", "d", "=", "'Vulnerability name (eg. SQL Injection)'", "o", "=", "opt_factory", "(", "'name'", ",", "self", ".", "name", ",", "d", ",", "'string'", ")", "ol", ".", "add", "(",...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/data/kb/vuln_templates/base_template.py#L53-L91
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/api/images/__init__.py
python
Image.crop
(self, left_x, top_y, right_x, bottom_y)
Crop the image. The four arguments are the scaling numbers to describe the bounding box which will crop the image. The upper left point of the bounding box will be at (left_x*image_width, top_y*image_height) the lower right point will be at (right_x*image_width, bottom_y*image_height). Args: left_x: float value between 0.0 and 1.0 (inclusive). top_y: float value between 0.0 and 1.0 (inclusive). right_x: float value between 0.0 and 1.0 (inclusive). bottom_y: float value between 0.0 and 1.0 (inclusive). Raises: TypeError if the args are not of type 'float'. BadRequestError when there is something wrong with the given bounding box or if MAX_TRANSFORMS_PER_REQUEST transforms have already been requested for this image.
Crop the image.
[ "Crop", "the", "image", "." ]
def crop(self, left_x, top_y, right_x, bottom_y): """Crop the image. The four arguments are the scaling numbers to describe the bounding box which will crop the image. The upper left point of the bounding box will be at (left_x*image_width, top_y*image_height) the lower right point will be at (right_x*image_width, bottom_y*image_height). Args: left_x: float value between 0.0 and 1.0 (inclusive). top_y: float value between 0.0 and 1.0 (inclusive). right_x: float value between 0.0 and 1.0 (inclusive). bottom_y: float value between 0.0 and 1.0 (inclusive). Raises: TypeError if the args are not of type 'float'. BadRequestError when there is something wrong with the given bounding box or if MAX_TRANSFORMS_PER_REQUEST transforms have already been requested for this image. """ self._validate_crop_arg(left_x, "left_x") self._validate_crop_arg(top_y, "top_y") self._validate_crop_arg(right_x, "right_x") self._validate_crop_arg(bottom_y, "bottom_y") if left_x >= right_x: raise BadRequestError("left_x must be less than right_x") if top_y >= bottom_y: raise BadRequestError("top_y must be less than bottom_y") self._check_transform_limits() transform = images_service_pb.Transform() transform.set_crop_left_x(left_x) transform.set_crop_top_y(top_y) transform.set_crop_right_x(right_x) transform.set_crop_bottom_y(bottom_y) self._transforms.append(transform)
[ "def", "crop", "(", "self", ",", "left_x", ",", "top_y", ",", "right_x", ",", "bottom_y", ")", ":", "self", ".", "_validate_crop_arg", "(", "left_x", ",", "\"left_x\"", ")", "self", ".", "_validate_crop_arg", "(", "top_y", ",", "\"top_y\"", ")", "self", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/images/__init__.py#L667-L705
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/imputil.py
python
ImportManager._reload_hook
(self, module)
Python calls this hook to reload a module.
Python calls this hook to reload a module.
[ "Python", "calls", "this", "hook", "to", "reload", "a", "module", "." ]
def _reload_hook(self, module): "Python calls this hook to reload a module." # reloading of a module may or may not be possible (depending on the # importer), but at least we can validate that it's ours to reload importer = module.__dict__.get('__importer__') if not importer: ### oops. now what... pass # okay. it is using the imputil system, and we must delegate it, but # we don't know what to do (yet) ### we should blast the module dict and do another get_code(). need to ### flesh this out and add proper docco... raise SystemError, "reload not yet implemented"
[ "def", "_reload_hook", "(", "self", ",", "module", ")", ":", "# reloading of a module may or may not be possible (depending on the", "# importer), but at least we can validate that it's ours to reload", "importer", "=", "module", ".", "__dict__", ".", "get", "(", "'__importer__'"...
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/imputil.py#L200-L214
phonopy/phonopy
816586d0ba8177482ecf40e52f20cbdee2260d51
phonopy/api_qha.py
python
PhonopyQHA.get_bulk_modulus_temperature
(self)
return self.bulk_modulus_temperature
Return bulk moduli at temperatures.
Return bulk moduli at temperatures.
[ "Return", "bulk", "moduli", "at", "temperatures", "." ]
def get_bulk_modulus_temperature(self): """Return bulk moduli at temperatures.""" warnings.warn( "PhonopyQHA.get_bulk_modulus_temperature() is deprecated." "Use bulk_modulus_temperature attribute.", DeprecationWarning, ) return self.bulk_modulus_temperature
[ "def", "get_bulk_modulus_temperature", "(", "self", ")", ":", "warnings", ".", "warn", "(", "\"PhonopyQHA.get_bulk_modulus_temperature() is deprecated.\"", "\"Use bulk_modulus_temperature attribute.\"", ",", "DeprecationWarning", ",", ")", "return", "self", ".", "bulk_modulus_t...
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/api_qha.py#L443-L450
simons-public/protonfixes
24ecb378bc4e99bfe698090661d255dcbb5b677f
protonfixes/gamefixes/390710.py
python
main
()
Installs d3dxof
Installs d3dxof
[ "Installs", "d3dxof" ]
def main(): """ Installs d3dxof """ # https://github.com/ValveSoftware/Proton/issues/970#issuecomment-420421289 util.protontricks('d3dxof')
[ "def", "main", "(", ")", ":", "# https://github.com/ValveSoftware/Proton/issues/970#issuecomment-420421289", "util", ".", "protontricks", "(", "'d3dxof'", ")" ]
https://github.com/simons-public/protonfixes/blob/24ecb378bc4e99bfe698090661d255dcbb5b677f/protonfixes/gamefixes/390710.py#L7-L12
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/pdb2pqr/contrib/numpy-1.1.0/numpy/ma/core.py
python
_minimum_operation.__init__
(self)
minimum(a, b) or minimum(a) In one argument case, returns the scalar minimum.
minimum(a, b) or minimum(a) In one argument case, returns the scalar minimum.
[ "minimum", "(", "a", "b", ")", "or", "minimum", "(", "a", ")", "In", "one", "argument", "case", "returns", "the", "scalar", "minimum", "." ]
def __init__ (self): """minimum(a, b) or minimum(a) In one argument case, returns the scalar minimum. """ self.ufunc = umath.minimum self.afunc = amin self.compare = less self.fill_value_func = minimum_fill_value
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ufunc", "=", "umath", ".", "minimum", "self", ".", "afunc", "=", "amin", "self", ".", "compare", "=", "less", "self", ".", "fill_value_func", "=", "minimum_fill_value" ]
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/contrib/numpy-1.1.0/numpy/ma/core.py#L2745-L2752
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/middleware/transaction.py
python
TransactionMiddleware.process_response
(self, request, response)
return response
Commits and leaves transaction management.
Commits and leaves transaction management.
[ "Commits", "and", "leaves", "transaction", "management", "." ]
def process_response(self, request, response): """Commits and leaves transaction management.""" if transaction.is_managed(): if transaction.is_dirty(): transaction.commit() transaction.leave_transaction_management() return response
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "transaction", ".", "is_managed", "(", ")", ":", "if", "transaction", ".", "is_dirty", "(", ")", ":", "transaction", ".", "commit", "(", ")", "transaction", ".", "le...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/middleware/transaction.py#L21-L27
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/sqlalchemy/orm/util.py
python
AliasedInsp.class_
(self)
return self.mapper.class_
Return the mapped class ultimately represented by this :class:`.AliasedInsp`.
Return the mapped class ultimately represented by this :class:`.AliasedInsp`.
[ "Return", "the", "mapped", "class", "ultimately", "represented", "by", "this", ":", "class", ":", ".", "AliasedInsp", "." ]
def class_(self): """Return the mapped class ultimately represented by this :class:`.AliasedInsp`.""" return self.mapper.class_
[ "def", "class_", "(", "self", ")", ":", "return", "self", ".", "mapper", ".", "class_" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/sqlalchemy/orm/util.py#L490-L493
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/net/proto2/python/internal/wire_format.py
python
_VarUInt64ByteSizeNoTag
(uint64)
return 10
Returns the number of bytes required to serialize a single varint using boundary value comparisons. (unrolled loop optimization -WPierce) uint64 must be unsigned.
Returns the number of bytes required to serialize a single varint using boundary value comparisons. (unrolled loop optimization -WPierce) uint64 must be unsigned.
[ "Returns", "the", "number", "of", "bytes", "required", "to", "serialize", "a", "single", "varint", "using", "boundary", "value", "comparisons", ".", "(", "unrolled", "loop", "optimization", "-", "WPierce", ")", "uint64", "must", "be", "unsigned", "." ]
def _VarUInt64ByteSizeNoTag(uint64): """Returns the number of bytes required to serialize a single varint using boundary value comparisons. (unrolled loop optimization -WPierce) uint64 must be unsigned. """ if uint64 <= 0x7f: return 1 if uint64 <= 0x3fff: return 2 if uint64 <= 0x1fffff: return 3 if uint64 <= 0xfffffff: return 4 if uint64 <= 0x7ffffffff: return 5 if uint64 <= 0x3ffffffffff: return 6 if uint64 <= 0x1ffffffffffff: return 7 if uint64 <= 0xffffffffffffff: return 8 if uint64 <= 0x7fffffffffffffff: return 9 if uint64 > UINT64_MAX: raise message.EncodeError('Value out of range: %d' % uint64) return 10
[ "def", "_VarUInt64ByteSizeNoTag", "(", "uint64", ")", ":", "if", "uint64", "<=", "0x7f", ":", "return", "1", "if", "uint64", "<=", "0x3fff", ":", "return", "2", "if", "uint64", "<=", "0x1fffff", ":", "return", "3", "if", "uint64", "<=", "0xfffffff", ":",...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/net/proto2/python/internal/wire_format.py#L221-L237