repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
gmr/queries
queries/pool.py
https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/pool.py#L314-L331
def lock(self, connection, session): """Explicitly lock the specified connection :type connection: psycopg2.extensions.connection :param connection: The connection to lock :param queries.Session session: The session to hold the lock """ cid = id(connection) try:...
[ "def", "lock", "(", "self", ",", "connection", ",", "session", ")", ":", "cid", "=", "id", "(", "connection", ")", "try", ":", "self", ".", "connection_handle", "(", "connection", ")", ".", "lock", "(", "session", ")", "except", "KeyError", ":", "raise...
Explicitly lock the specified connection :type connection: psycopg2.extensions.connection :param connection: The connection to lock :param queries.Session session: The session to hold the lock
[ "Explicitly", "lock", "the", "specified", "connection" ]
python
train
35.222222
roboogle/gtkmvc3
gtkmvco/gtkmvc3/support/metaclasses.py
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/support/metaclasses.py#L521-L543
def get_setter(cls, prop_name, # @NoSelf user_setter=None, setter_takes_name=False, user_getter=None, getter_takes_name=False): """Similar to get_getter, but for setting property values. If user_getter is specified, that it may be used to get the old value...
[ "def", "get_setter", "(", "cls", ",", "prop_name", ",", "# @NoSelf", "user_setter", "=", "None", ",", "setter_takes_name", "=", "False", ",", "user_getter", "=", "None", ",", "getter_takes_name", "=", "False", ")", ":", "if", "user_setter", ":", "if", "sette...
Similar to get_getter, but for setting property values. If user_getter is specified, that it may be used to get the old value of the property before setting it (this is the case in some derived classes' implementation). if getter_takes_name is True and user_getter is not None, than ...
[ "Similar", "to", "get_getter", "but", "for", "setting", "property", "values", ".", "If", "user_getter", "is", "specified", "that", "it", "may", "be", "used", "to", "get", "the", "old", "value", "of", "the", "property", "before", "setting", "it", "(", "this...
python
train
43.826087
BD2KGenomics/toil-scripts
src/toil_scripts/gatk_germline/germline.py
https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/gatk_germline/germline.py#L595-L680
def setup_and_run_bwakit(job, uuid, url, rg_line, config, paired_url=None): """ Downloads and runs bwakit for BAM or FASTQ files :param JobFunctionWrappingJob job: passed automatically by Toil :param str uuid: Unique sample identifier :param str url: FASTQ or BAM file URL. BAM alignment URL must ha...
[ "def", "setup_and_run_bwakit", "(", "job", ",", "uuid", ",", "url", ",", "rg_line", ",", "config", ",", "paired_url", "=", "None", ")", ":", "bwa_config", "=", "deepcopy", "(", "config", ")", "bwa_config", ".", "uuid", "=", "uuid", "bwa_config", ".", "rg...
Downloads and runs bwakit for BAM or FASTQ files :param JobFunctionWrappingJob job: passed automatically by Toil :param str uuid: Unique sample identifier :param str url: FASTQ or BAM file URL. BAM alignment URL must have .bam extension. :param Namespace config: Input parameters and shared FileStoreIDs...
[ "Downloads", "and", "runs", "bwakit", "for", "BAM", "or", "FASTQ", "files" ]
python
train
44.616279
spotify/luigi
luigi/tools/range.py
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L603-L619
def _list_existing(filesystem, glob, paths): """ Get all the paths that do in fact exist. Returns a set of all existing paths. Takes a luigi.target.FileSystem object, a str which represents a glob and a list of strings representing paths. """ globs = _constrain_glob(glob, paths) time_start ...
[ "def", "_list_existing", "(", "filesystem", ",", "glob", ",", "paths", ")", ":", "globs", "=", "_constrain_glob", "(", "glob", ",", "paths", ")", "time_start", "=", "time", ".", "time", "(", ")", "listing", "=", "[", "]", "for", "g", "in", "sorted", ...
Get all the paths that do in fact exist. Returns a set of all existing paths. Takes a luigi.target.FileSystem object, a str which represents a glob and a list of strings representing paths.
[ "Get", "all", "the", "paths", "that", "do", "in", "fact", "exist", ".", "Returns", "a", "set", "of", "all", "existing", "paths", "." ]
python
train
39.470588
mdiener/grace
grace/py27/pyjsdoc.py
https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/pyjsdoc.py#L839-L852
def get_as_list(self, tag_name): """ Return the value of a tag, making sure that it's a list. Absent tags are returned as an empty-list; single tags are returned as a one-element list. The returned list is a copy, and modifications do not affect the original object. ...
[ "def", "get_as_list", "(", "self", ",", "tag_name", ")", ":", "val", "=", "self", ".", "get", "(", "tag_name", ",", "[", "]", ")", "if", "isinstance", "(", "val", ",", "list", ")", ":", "return", "val", "[", ":", "]", "else", ":", "return", "[", ...
Return the value of a tag, making sure that it's a list. Absent tags are returned as an empty-list; single tags are returned as a one-element list. The returned list is a copy, and modifications do not affect the original object.
[ "Return", "the", "value", "of", "a", "tag", "making", "sure", "that", "it", "s", "a", "list", ".", "Absent", "tags", "are", "returned", "as", "an", "empty", "-", "list", ";", "single", "tags", "are", "returned", "as", "a", "one", "-", "element", "lis...
python
train
32.214286
projecthamster/hamster
src/hamster/lib/graphics.py
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L364-L366
def circle(self, x, y, radius): """draw circle""" self._add_instruction("arc", x, y, radius, 0, math.pi * 2)
[ "def", "circle", "(", "self", ",", "x", ",", "y", ",", "radius", ")", ":", "self", ".", "_add_instruction", "(", "\"arc\"", ",", "x", ",", "y", ",", "radius", ",", "0", ",", "math", ".", "pi", "*", "2", ")" ]
draw circle
[ "draw", "circle" ]
python
train
40.666667
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L332-L338
def persist(self): """Trigger saving the current sensorgraph to persistent storage.""" self.persisted_nodes = self.graph.dump_nodes() self.persisted_streamers = self.graph.dump_streamers() self.persisted_exists = True self.persisted_constants = self._sensor_log.dump_constants()
[ "def", "persist", "(", "self", ")", ":", "self", ".", "persisted_nodes", "=", "self", ".", "graph", ".", "dump_nodes", "(", ")", "self", ".", "persisted_streamers", "=", "self", ".", "graph", ".", "dump_streamers", "(", ")", "self", ".", "persisted_exists"...
Trigger saving the current sensorgraph to persistent storage.
[ "Trigger", "saving", "the", "current", "sensorgraph", "to", "persistent", "storage", "." ]
python
train
44.714286
project-rig/rig
rig/scripts/rig_counters.py
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/scripts/rig_counters.py#L40-L75
def monitor_counters(mc, output, counters, detailed, f): """Monitor the counters on a specified machine, taking a snap-shot every time the generator 'f' yields.""" # Print CSV header output.write("time,{}{}\n".format("x,y," if detailed else "", ",".join(counters))) ...
[ "def", "monitor_counters", "(", "mc", ",", "output", ",", "counters", ",", "detailed", ",", "f", ")", ":", "# Print CSV header", "output", ".", "write", "(", "\"time,{}{}\\n\"", ".", "format", "(", "\"x,y,\"", "if", "detailed", "else", "\"\"", ",", "\",\"", ...
Monitor the counters on a specified machine, taking a snap-shot every time the generator 'f' yields.
[ "Monitor", "the", "counters", "on", "a", "specified", "machine", "taking", "a", "snap", "-", "shot", "every", "time", "the", "generator", "f", "yields", "." ]
python
train
37.166667
knagra/farnsworth
base/views.py
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L733-L766
def recount_view(request): """ Recount number_of_messages for all threads and number_of_responses for all requests. Also set the change_date for every thread to the post_date of the latest message associated with that thread. """ requests_changed = 0 for req in Request.objects.all(): ...
[ "def", "recount_view", "(", "request", ")", ":", "requests_changed", "=", "0", "for", "req", "in", "Request", ".", "objects", ".", "all", "(", ")", ":", "recount", "=", "Response", ".", "objects", ".", "filter", "(", "request", "=", "req", ")", ".", ...
Recount number_of_messages for all threads and number_of_responses for all requests. Also set the change_date for every thread to the post_date of the latest message associated with that thread.
[ "Recount", "number_of_messages", "for", "all", "threads", "and", "number_of_responses", "for", "all", "requests", ".", "Also", "set", "the", "change_date", "for", "every", "thread", "to", "the", "post_date", "of", "the", "latest", "message", "associated", "with", ...
python
train
42.117647
Esri/ArcREST
src/arcrest/common/symbology.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/symbology.py#L74-L78
def angle(self, value): """gets/sets the angle""" if self._angle != value and \ isinstance(value, (int, float, long)): self._angle = value
[ "def", "angle", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_angle", "!=", "value", "and", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "long", ")", ")", ":", "self", ".", "_angle", "=", "value" ]
gets/sets the angle
[ "gets", "/", "sets", "the", "angle" ]
python
train
34.6
PyCQA/pylint
pylint/checkers/utils.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L383-L395
def is_func_decorator(node: astroid.node_classes.NodeNG) -> bool: """return true if the name is used in function decorator""" parent = node.parent while parent is not None: if isinstance(parent, astroid.Decorators): return True if parent.is_statement or isinstance( pa...
[ "def", "is_func_decorator", "(", "node", ":", "astroid", ".", "node_classes", ".", "NodeNG", ")", "->", "bool", ":", "parent", "=", "node", ".", "parent", "while", "parent", "is", "not", "None", ":", "if", "isinstance", "(", "parent", ",", "astroid", "."...
return true if the name is used in function decorator
[ "return", "true", "if", "the", "name", "is", "used", "in", "function", "decorator" ]
python
test
36.615385
cjdrake/pyeda
pyeda/boolalg/bfarray.py
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L956-L960
def _zeros(ftype, *dims): """Return a new farray filled with zeros.""" shape = _dims2shape(*dims) objs = [ftype.box(0) for _ in range(_volume(shape))] return farray(objs, shape, ftype)
[ "def", "_zeros", "(", "ftype", ",", "*", "dims", ")", ":", "shape", "=", "_dims2shape", "(", "*", "dims", ")", "objs", "=", "[", "ftype", ".", "box", "(", "0", ")", "for", "_", "in", "range", "(", "_volume", "(", "shape", ")", ")", "]", "return...
Return a new farray filled with zeros.
[ "Return", "a", "new", "farray", "filled", "with", "zeros", "." ]
python
train
39.2
MainRo/cyclotron-std
cyclotron_std/argparse.py
https://github.com/MainRo/cyclotron-std/blob/da4188f1c99aafc3a491803c23e01b44b52a15b1/cyclotron_std/argparse.py#L22-L65
def argparse(argv, parser, arguments): """ A command line argument parser. Parses arguments coming from the argv Observable and outputs them as Argument items in the output observable. Parameters ----------- argv : Observable An Observable of strings. parser : Observable An ...
[ "def", "argparse", "(", "argv", ",", "parser", ",", "arguments", ")", ":", "def", "add_arg", "(", "parser", ",", "arg_spec", ")", ":", "parser", ".", "add_argument", "(", "arg_spec", ".", "name", ",", "help", "=", "arg_spec", ".", "help", ")", "return"...
A command line argument parser. Parses arguments coming from the argv Observable and outputs them as Argument items in the output observable. Parameters ----------- argv : Observable An Observable of strings. parser : Observable An Observable containing one Parser item. argu...
[ "A", "command", "line", "argument", "parser", ".", "Parses", "arguments", "coming", "from", "the", "argv", "Observable", "and", "outputs", "them", "as", "Argument", "items", "in", "the", "output", "observable", "." ]
python
train
32.022727
mlperf/training
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py#L13-L33
def keep_only_positive_boxes(boxes): """ Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList) """ assert isinstance(boxes, (list, tuple)) assert isinstance(boxes[0], BoxList) assert boxes[0].has_...
[ "def", "keep_only_positive_boxes", "(", "boxes", ")", ":", "assert", "isinstance", "(", "boxes", ",", "(", "list", ",", "tuple", ")", ")", "assert", "isinstance", "(", "boxes", "[", "0", "]", ",", "BoxList", ")", "assert", "boxes", "[", "0", "]", ".", ...
Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList)
[ "Given", "a", "set", "of", "BoxList", "containing", "the", "labels", "field", "return", "a", "set", "of", "BoxList", "for", "which", "labels", ">", "0", "." ]
python
train
32.285714
Azure/azure-cosmos-python
azure/cosmos/cosmos_client.py
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2679-L2701
def __Delete(self, path, request, headers): """Azure Cosmos 'DELETE' http request. :params str url: :params str path: :params dict headers: :return: Tuple of (result, headers). :rtype: tuple of (dict, dict) """ return synchronize...
[ "def", "__Delete", "(", "self", ",", "path", ",", "request", ",", "headers", ")", ":", "return", "synchronized_request", ".", "SynchronizedRequest", "(", "self", ",", "request", ",", "self", ".", "_global_endpoint_manager", ",", "self", ".", "connection_policy",...
Azure Cosmos 'DELETE' http request. :params str url: :params str path: :params dict headers: :return: Tuple of (result, headers). :rtype: tuple of (dict, dict)
[ "Azure", "Cosmos", "DELETE", "http", "request", "." ]
python
train
43.304348
Jaymon/prom
prom/interface/sqlite.py
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/sqlite.py#L364-L378
def _set_table(self, schema, **kwargs): """ http://sqlite.org/lang_createtable.html """ query_str = [] query_str.append("CREATE TABLE {} (".format(self._normalize_table_name(schema))) query_fields = [] for field_name, field in schema.fields.items(): q...
[ "def", "_set_table", "(", "self", ",", "schema", ",", "*", "*", "kwargs", ")", ":", "query_str", "=", "[", "]", "query_str", ".", "append", "(", "\"CREATE TABLE {} (\"", ".", "format", "(", "self", ".", "_normalize_table_name", "(", "schema", ")", ")", "...
http://sqlite.org/lang_createtable.html
[ "http", ":", "//", "sqlite", ".", "org", "/", "lang_createtable", ".", "html" ]
python
train
39.533333
adamrehn/slidingwindow
slidingwindow/RectangleUtils.py
https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/RectangleUtils.py#L98-L115
def squareAspect(rect): """ Crops either the width or height, as necessary, to make a rectangle into a square. The input rectangle and return value are both a tuple of (x,y,w,h). """ # Determine which dimension needs to be cropped x,y,w,h = rect if w > h: cropX = (w - h) // 2 return cropRect(rect, 0, 0, ...
[ "def", "squareAspect", "(", "rect", ")", ":", "# Determine which dimension needs to be cropped", "x", ",", "y", ",", "w", ",", "h", "=", "rect", "if", "w", ">", "h", ":", "cropX", "=", "(", "w", "-", "h", ")", "//", "2", "return", "cropRect", "(", "r...
Crops either the width or height, as necessary, to make a rectangle into a square. The input rectangle and return value are both a tuple of (x,y,w,h).
[ "Crops", "either", "the", "width", "or", "height", "as", "necessary", "to", "make", "a", "rectangle", "into", "a", "square", ".", "The", "input", "rectangle", "and", "return", "value", "are", "both", "a", "tuple", "of", "(", "x", "y", "w", "h", ")", ...
python
train
23.944444
digidotcom/python-devicecloud
devicecloud/streams.py
https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/streams.py#L787-L797
def delete_datapoint(self, datapoint): """Delete the provided datapoint from this stream :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error """ datapoint = validate_type(datapoint, DataPoint) self._conn.delete("/ws/DataPoint/{stream_id}/{datap...
[ "def", "delete_datapoint", "(", "self", ",", "datapoint", ")", ":", "datapoint", "=", "validate_type", "(", "datapoint", ",", "DataPoint", ")", "self", ".", "_conn", ".", "delete", "(", "\"/ws/DataPoint/{stream_id}/{datapoint_id}\"", ".", "format", "(", "stream_id...
Delete the provided datapoint from this stream :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error
[ "Delete", "the", "provided", "datapoint", "from", "this", "stream" ]
python
train
38.818182
Calysto/calysto
calysto/ai/conx.py
https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L420-L428
def setLog(self, fileName, writeName=False): """ Opens a log file with name fileName. """ self.log = 1 self.logFile = fileName self._logPtr = open(fileName, "w") if writeName: self._namePtr = open(fileName + ".name", "w")
[ "def", "setLog", "(", "self", ",", "fileName", ",", "writeName", "=", "False", ")", ":", "self", ".", "log", "=", "1", "self", ".", "logFile", "=", "fileName", "self", ".", "_logPtr", "=", "open", "(", "fileName", ",", "\"w\"", ")", "if", "writeName"...
Opens a log file with name fileName.
[ "Opens", "a", "log", "file", "with", "name", "fileName", "." ]
python
train
31.222222
thautwarm/Redy
Redy/Collections/Traversal.py
https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/Collections/Traversal.py#L166-L190
def chunk(seq: ActualIterable[T]) -> ActualIterable[ActualIterable[T]]: """ >>> from Redy.Collections import Traversal, Flow >>> x = [1, 1, 2] >>> assert Flow(x)[Traversal.chunk][list].unbox == [[1, 1], [2]] >>> assert Flow([])[Traversal.chunk][list].unbox == [] """ seq = iter(seq) try: ...
[ "def", "chunk", "(", "seq", ":", "ActualIterable", "[", "T", "]", ")", "->", "ActualIterable", "[", "ActualIterable", "[", "T", "]", "]", ":", "seq", "=", "iter", "(", "seq", ")", "try", ":", "head", "=", "next", "(", "seq", ")", "except", "StopIte...
>>> from Redy.Collections import Traversal, Flow >>> x = [1, 1, 2] >>> assert Flow(x)[Traversal.chunk][list].unbox == [[1, 1], [2]] >>> assert Flow([])[Traversal.chunk][list].unbox == []
[ ">>>", "from", "Redy", ".", "Collections", "import", "Traversal", "Flow", ">>>", "x", "=", "[", "1", "1", "2", "]", ">>>", "assert", "Flow", "(", "x", ")", "[", "Traversal", ".", "chunk", "]", "[", "list", "]", ".", "unbox", "==", "[[", "1", "1",...
python
train
26.36
saltstack/salt
salt/loader.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1851-L1902
def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise Key...
[ "def", "_load", "(", "self", ",", "key", ")", ":", "# if the key doesn't have a '.' then it isn't valid for this mod dict", "if", "not", "isinstance", "(", "key", ",", "six", ".", "string_types", ")", ":", "raise", "KeyError", "(", "'The key must be a string.'", ")", ...
Load a single item if you have it
[ "Load", "a", "single", "item", "if", "you", "have", "it" ]
python
train
40.038462
PmagPy/PmagPy
programs/sundec.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/sundec.py#L23-L79
def main(): """ NAME sundec.py DESCRIPTION calculates calculates declination from sun compass measurements INPUT FORMAT GMT_offset, lat,long,year,month,day,hours,minutes,shadow_angle where GMT_offset is the hours to subtract from local time for GMT. SYNTAX sun...
[ "def", "main", "(", ")", ":", "if", "'-h'", "in", "sys", ".", "argv", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "if", "'-f'", "in", "sys", ".", "argv", ":", "ind", "=", "sys", ".", "argv", ".", "index", "("...
NAME sundec.py DESCRIPTION calculates calculates declination from sun compass measurements INPUT FORMAT GMT_offset, lat,long,year,month,day,hours,minutes,shadow_angle where GMT_offset is the hours to subtract from local time for GMT. SYNTAX sundec.py [-i][-f FILE] [< ...
[ "NAME", "sundec", ".", "py" ]
python
train
36.280702
mbedmicro/pyOCD
pyocd/utility/conversion.py
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/utility/conversion.py#L56-L61
def byte_list_to_u16le_list(byteData): """! @brief Convert a byte array into a halfword array""" data = [] for i in range(0, len(byteData), 2): data.append(byteData[i] | (byteData[i + 1] << 8)) return data
[ "def", "byte_list_to_u16le_list", "(", "byteData", ")", ":", "data", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "byteData", ")", ",", "2", ")", ":", "data", ".", "append", "(", "byteData", "[", "i", "]", "|", "(", "byteD...
! @brief Convert a byte array into a halfword array
[ "!" ]
python
train
37.333333
tjomasc/snekbol
snekbol/document.py
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L179-L186
def add_model(self, model): """ Add a model to the document """ if model.identity not in self._models.keys(): self._models[model.identity] = model else: raise ValueError("{} has already been defined".format(model.identity))
[ "def", "add_model", "(", "self", ",", "model", ")", ":", "if", "model", ".", "identity", "not", "in", "self", ".", "_models", ".", "keys", "(", ")", ":", "self", ".", "_models", "[", "model", ".", "identity", "]", "=", "model", "else", ":", "raise"...
Add a model to the document
[ "Add", "a", "model", "to", "the", "document" ]
python
train
35
qzmfranklin/easyshell
easyshell/basic_shell.py
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/basic_shell.py#L67-L84
def _do_history(self, cmd, args): """\ Display history. history Display history. history clear Clear history. history clearall Clear history for all shells. """ if args and args[0] == 'clear': readline.clear_history() ...
[ "def", "_do_history", "(", "self", ",", "cmd", ",", "args", ")", ":", "if", "args", "and", "args", "[", "0", "]", "==", "'clear'", ":", "readline", ".", "clear_history", "(", ")", "readline", ".", "write_history_file", "(", "self", ".", "history_fname", ...
\ Display history. history Display history. history clear Clear history. history clearall Clear history for all shells.
[ "\\", "Display", "history", ".", "history", "Display", "history", ".", "history", "clear", "Clear", "history", ".", "history", "clearall", "Clear", "history", "for", "all", "shells", "." ]
python
train
42.333333
turicas/rows
rows/plugins/plugin_json.py
https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_json.py#L68-L97
def export_to_json( table, filename_or_fobj=None, encoding="utf-8", indent=None, *args, **kwargs ): """Export a `rows.Table` to a JSON file or file-like object. If a file-like object is provided it MUST be open in binary mode (like in `open('myfile.json', mode='wb')`). """ # TODO: will work onl...
[ "def", "export_to_json", "(", "table", ",", "filename_or_fobj", "=", "None", ",", "encoding", "=", "\"utf-8\"", ",", "indent", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO: will work only if table.fields is OrderedDict", "fields", "=...
Export a `rows.Table` to a JSON file or file-like object. If a file-like object is provided it MUST be open in binary mode (like in `open('myfile.json', mode='wb')`).
[ "Export", "a", "rows", ".", "Table", "to", "a", "JSON", "file", "or", "file", "-", "like", "object", "." ]
python
train
33.8
AtomHash/evernode
evernode/models/base_model.py
https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/models/base_model.py#L39-L48
def delete(self): """ Easy delete for db models """ try: if self.exists() is False: return None self.db.session.delete(self) self.db.session.commit() except (Exception, BaseException) as error: # fail silently r...
[ "def", "delete", "(", "self", ")", ":", "try", ":", "if", "self", ".", "exists", "(", ")", "is", "False", ":", "return", "None", "self", ".", "db", ".", "session", ".", "delete", "(", "self", ")", "self", ".", "db", ".", "session", ".", "commit",...
Easy delete for db models
[ "Easy", "delete", "for", "db", "models" ]
python
train
32.1
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/widgets/axis.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/widgets/axis.py#L81-L89
def _view_changed(self, event=None): """Linked view transform has changed; update ticks. """ tr = self.node_transform(self._linked_view.scene) p1, p2 = tr.map(self._axis_ends()) if self.orientation in ('left', 'right'): self.axis.domain = (p1[1], p2[1]) else: ...
[ "def", "_view_changed", "(", "self", ",", "event", "=", "None", ")", ":", "tr", "=", "self", ".", "node_transform", "(", "self", ".", "_linked_view", ".", "scene", ")", "p1", ",", "p2", "=", "tr", ".", "map", "(", "self", ".", "_axis_ends", "(", ")...
Linked view transform has changed; update ticks.
[ "Linked", "view", "transform", "has", "changed", ";", "update", "ticks", "." ]
python
train
39.666667
python-diamond/Diamond
src/diamond/handler/graphite.py
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/graphite.py#L84-L105
def get_default_config(self): """ Return the default config for the handler """ config = super(GraphiteHandler, self).get_default_config() config.update({ 'host': 'localhost', 'port': 2003, 'proto': 'tcp', 'timeout': 15, ...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "GraphiteHandler", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'host'", ":", "'localhost'", ",", "'port'", ":", "2003", ",", "...
Return the default config for the handler
[ "Return", "the", "default", "config", "for", "the", "handler" ]
python
train
26.636364
ValvePython/steam
steam/core/cm.py
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/core/cm.py#L503-L509
def reset_all(self): """Reset status for all servers in the list""" self._LOG.debug("Marking all CMs as Good.") for key in self.list: self.mark_good(key)
[ "def", "reset_all", "(", "self", ")", ":", "self", ".", "_LOG", ".", "debug", "(", "\"Marking all CMs as Good.\"", ")", "for", "key", "in", "self", ".", "list", ":", "self", ".", "mark_good", "(", "key", ")" ]
Reset status for all servers in the list
[ "Reset", "status", "for", "all", "servers", "in", "the", "list" ]
python
train
26.428571
odlgroup/odl
odl/space/pspace.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/pspace.py#L1271-L1307
def imag(self, newimag): """Setter for the imaginary part. This method is invoked by ``x.imag = other``. Parameters ---------- newimag : array-like or scalar Values to be assigned to the imaginary part of this element. """ try: iter(newim...
[ "def", "imag", "(", "self", ",", "newimag", ")", ":", "try", ":", "iter", "(", "newimag", ")", "except", "TypeError", ":", "# `newimag` is not iterable, assume it can be assigned to", "# all indexed parts", "for", "part", "in", "self", ".", "parts", ":", "part", ...
Setter for the imaginary part. This method is invoked by ``x.imag = other``. Parameters ---------- newimag : array-like or scalar Values to be assigned to the imaginary part of this element.
[ "Setter", "for", "the", "imaginary", "part", "." ]
python
train
34.513514
MolSSI-BSE/basis_set_exchange
basis_set_exchange/converters/molpro.py
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/converters/molpro.py#L9-L80
def write_molpro(basis): '''Converts a basis set to Molpro format ''' # Uncontract all, and make as generally-contracted as possible basis = manip.uncontract_spdf(basis, 0, True) basis = manip.make_general(basis, False) basis = sort.sort_basis(basis, True) s = '' # Elements for which ...
[ "def", "write_molpro", "(", "basis", ")", ":", "# Uncontract all, and make as generally-contracted as possible", "basis", "=", "manip", ".", "uncontract_spdf", "(", "basis", ",", "0", ",", "True", ")", "basis", "=", "manip", ".", "make_general", "(", "basis", ",",...
Converts a basis set to Molpro format
[ "Converts", "a", "basis", "set", "to", "Molpro", "format" ]
python
train
37.333333
ubc/ubcpi
ubcpi/answer_pool.py
https://github.com/ubc/ubcpi/blob/7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e/ubcpi/answer_pool.py#L76-L88
def offer_simple(pool, answer, rationale, student_id, options): """ The simple selection algorithm. This algorithm randomly select an answer from the pool to discard and add the new one when the pool reaches the limit """ existing = pool.setdefault(answer, {}) if len(existing) >= get_max_si...
[ "def", "offer_simple", "(", "pool", ",", "answer", ",", "rationale", ",", "student_id", ",", "options", ")", ":", "existing", "=", "pool", ".", "setdefault", "(", "answer", ",", "{", "}", ")", "if", "len", "(", "existing", ")", ">=", "get_max_size", "(...
The simple selection algorithm. This algorithm randomly select an answer from the pool to discard and add the new one when the pool reaches the limit
[ "The", "simple", "selection", "algorithm", "." ]
python
train
39.923077
zhanglab/psamm
psamm/lpsolver/generic.py
https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/lpsolver/generic.py#L178-L253
def list_solvers(args=None): """Entry point for listing available solvers.""" parser = argparse.ArgumentParser( description='''List LP solver available in PSAMM. This will produce a list of all of the available LP solvers in prioritized order. Addtional requ...
[ "def", "list_solvers", "(", "args", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'''List LP solver available in PSAMM. This will produce a\n list of all of the available LP solvers in prioritized\n ...
Entry point for listing available solvers.
[ "Entry", "point", "for", "listing", "available", "solvers", "." ]
python
train
39.565789
estnltk/estnltk
estnltk/text.py
https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/text.py#L883-L893
def tag_timexes(self): """Create ``timexes`` layer. Depends on morphological analysis data in ``words`` layer and tags it automatically, if it is not present.""" if not self.is_tagged(ANALYSIS): self.tag_analysis() if not self.is_tagged(TIMEXES): if self._...
[ "def", "tag_timexes", "(", "self", ")", ":", "if", "not", "self", ".", "is_tagged", "(", "ANALYSIS", ")", ":", "self", ".", "tag_analysis", "(", ")", "if", "not", "self", ".", "is_tagged", "(", "TIMEXES", ")", ":", "if", "self", ".", "__timex_tagger", ...
Create ``timexes`` layer. Depends on morphological analysis data in ``words`` layer and tags it automatically, if it is not present.
[ "Create", "timexes", "layer", ".", "Depends", "on", "morphological", "analysis", "data", "in", "words", "layer", "and", "tags", "it", "automatically", "if", "it", "is", "not", "present", "." ]
python
train
44.181818
mlperf/training
reinforcement/tensorflow/minigo/rl_loop/example_buffer.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/example_buffer.py#L294-L329
def make_chunk_for(output_dir=LOCAL_DIR, local_dir=LOCAL_DIR, game_dir=None, model_num=1, positions=EXAMPLES_PER_GENERATION, threads=8, sampling_frac=0.02): """ Explicitly make a golden chunk for a ...
[ "def", "make_chunk_for", "(", "output_dir", "=", "LOCAL_DIR", ",", "local_dir", "=", "LOCAL_DIR", ",", "game_dir", "=", "None", ",", "model_num", "=", "1", ",", "positions", "=", "EXAMPLES_PER_GENERATION", ",", "threads", "=", "8", ",", "sampling_frac", "=", ...
Explicitly make a golden chunk for a given model `model_num` (not necessarily the most recent one). While we haven't yet got enough samples (EXAMPLES_PER_GENERATION) Add samples from the games of previous model.
[ "Explicitly", "make", "a", "golden", "chunk", "for", "a", "given", "model", "model_num", "(", "not", "necessarily", "the", "most", "recent", "one", ")", "." ]
python
train
39.777778
quasipedia/swaggery
swaggery/checker.py
https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/checker.py#L76-L80
def check_has_path(self, api): '''An API class must have a `path` attribute.''' if not hasattr(api, 'path'): msg = 'The Api class "{}" lacks a `path` attribute.' return [msg.format(api.__name__)]
[ "def", "check_has_path", "(", "self", ",", "api", ")", ":", "if", "not", "hasattr", "(", "api", ",", "'path'", ")", ":", "msg", "=", "'The Api class \"{}\" lacks a `path` attribute.'", "return", "[", "msg", ".", "format", "(", "api", ".", "__name__", ")", ...
An API class must have a `path` attribute.
[ "An", "API", "class", "must", "have", "a", "path", "attribute", "." ]
python
train
46.2
Damgaard/PyImgur
pyimgur/__init__.py
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L493-L502
def remove_from_gallery(self): """Remove this image from the gallery.""" url = self._imgur._base_url + "/3/gallery/{0}".format(self.id) self._imgur._send_request(url, needs_auth=True, method='DELETE') if isinstance(self, Image): item = self._imgur.get_image(self.id) e...
[ "def", "remove_from_gallery", "(", "self", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/gallery/{0}\"", ".", "format", "(", "self", ".", "id", ")", "self", ".", "_imgur", ".", "_send_request", "(", "url", ",", "needs_auth", "...
Remove this image from the gallery.
[ "Remove", "this", "image", "from", "the", "gallery", "." ]
python
train
42
hfaran/Tornado-JSON
tornado_json/api_doc_gen.py
https://github.com/hfaran/Tornado-JSON/blob/8d8b35ff77f13cb3ab1a606bd2083b26cc69c54f/tornado_json/api_doc_gen.py#L237-L260
def get_api_docs(routes): """ Generates GitHub Markdown formatted API documentation using provided schemas in RequestHandler methods and their docstrings. :type routes: [(url, RequestHandler), ...] :param routes: List of routes (this is ideally all possible routes of the app) :rtype: s...
[ "def", "get_api_docs", "(", "routes", ")", ":", "routes", "=", "map", "(", "_get_tuple_from_route", ",", "routes", ")", "documentation", "=", "[", "]", "for", "url", ",", "rh", ",", "methods", "in", "sorted", "(", "routes", ",", "key", "=", "lambda", "...
Generates GitHub Markdown formatted API documentation using provided schemas in RequestHandler methods and their docstrings. :type routes: [(url, RequestHandler), ...] :param routes: List of routes (this is ideally all possible routes of the app) :rtype: str :returns: generated GFM-formatt...
[ "Generates", "GitHub", "Markdown", "formatted", "API", "documentation", "using", "provided", "schemas", "in", "RequestHandler", "methods", "and", "their", "docstrings", "." ]
python
train
37.833333
iskandr/fancyimpute
fancyimpute/iterative_imputer.py
https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L952-L998
def transform(self, X): """Imputes all missing values in X. Note that this is stochastic, and that if random_state is not fixed, repeated calls, or permuted input, will yield different results. Parameters ---------- X : array-like, shape = [n_samples, n_features] ...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "'initial_imputer_'", ")", "X", ",", "Xt", ",", "mask_missing_values", "=", "self", ".", "_initial_imputation", "(", "X", ")", "if", "self", ".", "n_iter", "==", "0...
Imputes all missing values in X. Note that this is stochastic, and that if random_state is not fixed, repeated calls, or permuted input, will yield different results. Parameters ---------- X : array-like, shape = [n_samples, n_features] The input data to complete. ...
[ "Imputes", "all", "missing", "values", "in", "X", "." ]
python
train
34.765957
10gen/mongo-orchestration
mongo_orchestration/replica_sets.py
https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L245-L258
def repl_member_add(self, params): """create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False """ repl_config = self.config member_id = max([member['_id'] for member in repl_confi...
[ "def", "repl_member_add", "(", "self", ",", "params", ")", ":", "repl_config", "=", "self", ".", "config", "member_id", "=", "max", "(", "[", "member", "[", "'_id'", "]", "for", "member", "in", "repl_config", "[", "'members'", "]", "]", ")", "+", "1", ...
create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False
[ "create", "new", "mongod", "instances", "and", "add", "it", "to", "the", "replica", "set", ".", "Args", ":", "params", "-", "mongod", "params", "return", "True", "if", "operation", "success", "otherwise", "False" ]
python
train
45.571429
kytos/python-openflow
pyof/v0x04/common/flow_match.py
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L283-L301
def _get_oxm_field_int(self): """Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :class:`OxmOfbMatchField` and ...
[ "def", "_get_oxm_field_int", "(", "self", ")", ":", "if", "self", ".", "oxm_class", "==", "OxmClass", ".", "OFPXMC_OPENFLOW_BASIC", ":", "return", "OxmOfbMatchField", "(", "self", ".", "oxm_field", ")", ".", "value", "elif", "not", "isinstance", "(", "self", ...
Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :class:`OxmOfbMatchField` and the enum has no such valu...
[ "Return", "a", "valid", "integer", "value", "for", "oxm_field", "." ]
python
train
34.421053
broadinstitute/fiss
firecloud/api.py
https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/api.py#L746-L765
def get_inputs_outputs(namespace, method, snapshot_id): """Get a description of the inputs and outputs for a method. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the method ...
[ "def", "get_inputs_outputs", "(", "namespace", ",", "method", ",", "snapshot_id", ")", ":", "body", "=", "{", "\"methodNamespace\"", ":", "namespace", ",", "\"methodName\"", ":", "method", ",", "\"methodVersion\"", ":", "snapshot_id", "}", "return", "__post", "(...
Get a description of the inputs and outputs for a method. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Reposit...
[ "Get", "a", "description", "of", "the", "inputs", "and", "outputs", "for", "a", "method", "." ]
python
train
28.4
pallets/werkzeug
bench/wzbench.py
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/bench/wzbench.py#L208-L266
def compare(node1, node2): """Compares two Werkzeug hg versions.""" if not os.path.isdir("a"): print("error: comparison feature not initialized", file=sys.stderr) sys.exit(4) print("=" * 80) print("WERKZEUG INTERNAL BENCHMARK -- COMPARE MODE".center(80)) print("-" * 80) def _hg...
[ "def", "compare", "(", "node1", ",", "node2", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "\"a\"", ")", ":", "print", "(", "\"error: comparison feature not initialized\"", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", ...
Compares two Werkzeug hg versions.
[ "Compares", "two", "Werkzeug", "hg", "versions", "." ]
python
train
33.372881
MisterY/asset-allocation
asset_allocation/loader.py
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L112-L117
def load_stock_quantity(self): """ Loads quantities for all stocks """ info = StocksInfo(self.config) for stock in self.model.stocks: stock.quantity = info.load_stock_quantity(stock.symbol) info.gc_book.close()
[ "def", "load_stock_quantity", "(", "self", ")", ":", "info", "=", "StocksInfo", "(", "self", ".", "config", ")", "for", "stock", "in", "self", ".", "model", ".", "stocks", ":", "stock", ".", "quantity", "=", "info", ".", "load_stock_quantity", "(", "stoc...
Loads quantities for all stocks
[ "Loads", "quantities", "for", "all", "stocks" ]
python
train
41.5
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L472-L493
def ncdegree(polynomial): """Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial. """ degree = 0 if is_number_type(polynomial): ret...
[ "def", "ncdegree", "(", "polynomial", ")", ":", "degree", "=", "0", "if", "is_number_type", "(", "polynomial", ")", ":", "return", "degree", "polynomial", "=", "polynomial", ".", "expand", "(", ")", "for", "monomial", "in", "polynomial", ".", "as_coefficient...
Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial.
[ "Returns", "the", "degree", "of", "a", "noncommutative", "polynomial", "." ]
python
train
33.590909
romanz/trezor-agent
libagent/gpg/__init__.py
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L279-L324
def main(device_type): """Parse command-line arguments.""" epilog = ('See https://github.com/romanz/trezor-agent/blob/master/' 'doc/README-GPG.md for usage examples.') parser = argparse.ArgumentParser(epilog=epilog) agent_package = device_type.package_name() resources_map = {r.key: r ...
[ "def", "main", "(", "device_type", ")", ":", "epilog", "=", "(", "'See https://github.com/romanz/trezor-agent/blob/master/'", "'doc/README-GPG.md for usage examples.'", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "epilog", "=", "epilog", ")", "agent_packag...
Parse command-line arguments.
[ "Parse", "command", "-", "line", "arguments", "." ]
python
train
47.847826
ponty/eagexp
eagexp/image.py
https://github.com/ponty/eagexp/blob/1dd5108c1d8112cc87d1bda64fa6c2784ccf0ff2/eagexp/image.py#L15-L88
def export_image(input, output, timeout=20, palette='white', resolution=150, layers=None, command=None, mirror=False, showgui=False): ''' Exporting eagle .sch or .brd file into image file. GUI is not displayed if ``pyvirtualdisplay`` is installed. If export is blocked somehow (e.g. popup window is displ...
[ "def", "export_image", "(", "input", ",", "output", ",", "timeout", "=", "20", ",", "palette", "=", "'white'", ",", "resolution", "=", "150", ",", "layers", "=", "None", ",", "command", "=", "None", ",", "mirror", "=", "False", ",", "showgui", "=", "...
Exporting eagle .sch or .brd file into image file. GUI is not displayed if ``pyvirtualdisplay`` is installed. If export is blocked somehow (e.g. popup window is displayed) then after timeout operation is canceled with exception. Problem can be investigated by setting 'showgui' flag. Exporting generates...
[ "Exporting", "eagle", ".", "sch", "or", ".", "brd", "file", "into", "image", "file", ".", "GUI", "is", "not", "displayed", "if", "pyvirtualdisplay", "is", "installed", ".", "If", "export", "is", "blocked", "somehow", "(", "e", ".", "g", ".", "popup", "...
python
train
30.297297
agoragames/chai
chai/stub.py
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L686-L690
def call_orig(self, *args, **kwargs): ''' Calls the original function. ''' return self._orig(self._obj, *args, **kwargs)
[ "def", "call_orig", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_orig", "(", "self", ".", "_obj", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Calls the original function.
[ "Calls", "the", "original", "function", "." ]
python
train
29.6
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAIndicator/indicators.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L281-L290
def QA_indicator_RSI(DataFrame, N1=12, N2=26, N3=9): '相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;' CLOSE = DataFrame['close'] LC = REF(CLOSE, 1) RSI1 = SMA(MAX(CLOSE - LC, 0), N1) / SMA(ABS(CLOSE - LC), N1) * 100 RSI2 = SMA(MAX(CLOSE - LC, 0), N2) / SMA(ABS(CLOSE - LC), N2) * 1...
[ "def", "QA_indicator_RSI", "(", "DataFrame", ",", "N1", "=", "12", ",", "N2", "=", "26", ",", "N3", "=", "9", ")", ":", "CLOSE", "=", "DataFrame", "[", "'close'", "]", "LC", "=", "REF", "(", "CLOSE", ",", "1", ")", "RSI1", "=", "SMA", "(", "MAX...
相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;
[ "相对强弱指标RSI1", ":", "SMA", "(", "MAX", "(", "CLOSE", "-", "LC", "0", ")", "N1", "1", ")", "/", "SMA", "(", "ABS", "(", "CLOSE", "-", "LC", ")", "N1", "1", ")", "*", "100", ";" ]
python
train
47
necaris/python3-openid
openid/server/server.py
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/server/server.py#L1042-L1056
def whichEncoding(self): """How should I be encoded? @returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM. @change: 2.1.0 added the ENCODE_HTML_FORM response. """ if self.request.mode in BROWSER_REQUEST_MODES: if self.fields.getOpenIDNamespace() == OPENID...
[ "def", "whichEncoding", "(", "self", ")", ":", "if", "self", ".", "request", ".", "mode", "in", "BROWSER_REQUEST_MODES", ":", "if", "self", ".", "fields", ".", "getOpenIDNamespace", "(", ")", "==", "OPENID2_NS", "and", "len", "(", "self", ".", "encodeToURL...
How should I be encoded? @returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM. @change: 2.1.0 added the ENCODE_HTML_FORM response.
[ "How", "should", "I", "be", "encoded?" ]
python
train
34.333333
Unidata/MetPy
metpy/interpolate/one_dimension.py
https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/interpolate/one_dimension.py#L21-L51
def interpolate_nans_1d(x, y, kind='linear'): """Interpolate NaN values in y. Interpolate NaN values in the y dimension. Works with unsorted x values. Parameters ---------- x : array-like 1-dimensional array of numeric x-values y : array-like 1-dimensional array of numeric y-va...
[ "def", "interpolate_nans_1d", "(", "x", ",", "y", ",", "kind", "=", "'linear'", ")", ":", "x_sort_args", "=", "np", ".", "argsort", "(", "x", ")", "x", "=", "x", "[", "x_sort_args", "]", "y", "=", "y", "[", "x_sort_args", "]", "nans", "=", "np", ...
Interpolate NaN values in y. Interpolate NaN values in the y dimension. Works with unsorted x values. Parameters ---------- x : array-like 1-dimensional array of numeric x-values y : array-like 1-dimensional array of numeric y-values kind : string specifies the kind of ...
[ "Interpolate", "NaN", "values", "in", "y", "." ]
python
train
29.903226
bitesofcode/projexui
projexui/widgets/xdocktoolbar.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xdocktoolbar.py#L654-L664
def setMinimumPixmapSize(self, size): """ Sets the minimum pixmap size that will be displayed to the user for the dock widget. :param size | <int> """ self._minimumPixmapSize = size position = self.position() self._position = None ...
[ "def", "setMinimumPixmapSize", "(", "self", ",", "size", ")", ":", "self", ".", "_minimumPixmapSize", "=", "size", "position", "=", "self", ".", "position", "(", ")", "self", ".", "_position", "=", "None", "self", ".", "setPosition", "(", "position", ")" ]
Sets the minimum pixmap size that will be displayed to the user for the dock widget. :param size | <int>
[ "Sets", "the", "minimum", "pixmap", "size", "that", "will", "be", "displayed", "to", "the", "user", "for", "the", "dock", "widget", ".", ":", "param", "size", "|", "<int", ">" ]
python
train
31.090909
chrisjsewell/jsonextended
jsonextended/plugins.py
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L271-L315
def plugins_context(classes, category=None): """ context manager to load plugin class(es) then unload on exit Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import ppr...
[ "def", "plugins_context", "(", "classes", ",", "category", "=", "None", ")", ":", "original", "=", "{", "cat", ":", "list", "(", "_all_plugins", "[", "cat", "]", ".", "keys", "(", ")", ")", "for", "cat", "in", "_all_plugins", "}", "load_plugin_classes", ...
context manager to load plugin class(es) then unload on exit Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> class DecoderPlugin(object): ... ...
[ "context", "manager", "to", "load", "plugin", "class", "(", "es", ")", "then", "unload", "on", "exit" ]
python
train
31.266667
kytos/kytos-utils
kytos/utils/client.py
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L82-L108
def reload_napps(self, napps=None): """Reload a specific NApp or all Napps. Args: napp (list): NApp list to be reload. Raises: requests.HTTPError: When there's a server error. """ if napps is None: napps = [] api = self._config.ge...
[ "def", "reload_napps", "(", "self", ",", "napps", "=", "None", ")", ":", "if", "napps", "is", "None", ":", "napps", "=", "[", "]", "api", "=", "self", ".", "_config", ".", "get", "(", "'kytos'", ",", "'api'", ")", "endpoint", "=", "os", ".", "pat...
Reload a specific NApp or all Napps. Args: napp (list): NApp list to be reload. Raises: requests.HTTPError: When there's a server error.
[ "Reload", "a", "specific", "NApp", "or", "all", "Napps", "." ]
python
train
35.37037
marcharper/python-ternary
ternary/ternary_axes_subplot.py
https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/ternary_axes_subplot.py#L238-L259
def top_corner_label(self, label, position=None, rotation=0, offset=0.2, **kwargs): """ Sets the label on the bottom axis. Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position o...
[ "def", "top_corner_label", "(", "self", ",", "label", ",", "position", "=", "None", ",", "rotation", "=", "0", ",", "offset", "=", "0.2", ",", "*", "*", "kwargs", ")", ":", "if", "not", "position", ":", "position", "=", "(", "-", "offset", "/", "2"...
Sets the label on the bottom axis. Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 0 The angle of rotation of the label offset: float, Use...
[ "Sets", "the", "label", "on", "the", "bottom", "axis", "." ]
python
train
32.409091
saltstack/salt
salt/states/azurearm_dns.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_dns.py#L619-L683
def record_set_absent(name, zone_name, resource_group, connection_auth=None): ''' .. versionadded:: Fluorine Ensure a record set does not exist in the DNS zone. :param name: Name of the record set. :param zone_name: Name of the DNS zone. :param resource_group: The res...
[ "def", "record_set_absent", "(", "name", ",", "zone_name", ",", "resource_group", ",", "connection_auth", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{...
.. versionadded:: Fluorine Ensure a record set does not exist in the DNS zone. :param name: Name of the record set. :param zone_name: Name of the DNS zone. :param resource_group: The resource group assigned to the DNS zone. :param connection_auth: A dict with sub...
[ "..", "versionadded", "::", "Fluorine" ]
python
train
26.815385
rackerlabs/simpl
simpl/log.py
https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/log.py#L157-L163
def format(self, record): """Print out any 'extra' data provided in logs.""" if hasattr(record, 'data'): return "%s. DEBUG DATA=%s" % ( logging.Formatter.format(self, record), record.__dict__['data']) return logging.Formatter.format(self, record)
[ "def", "format", "(", "self", ",", "record", ")", ":", "if", "hasattr", "(", "record", ",", "'data'", ")", ":", "return", "\"%s. DEBUG DATA=%s\"", "%", "(", "logging", ".", "Formatter", ".", "format", "(", "self", ",", "record", ")", ",", "record", "."...
Print out any 'extra' data provided in logs.
[ "Print", "out", "any", "extra", "data", "provided", "in", "logs", "." ]
python
train
44
quantumlib/Cirq
cirq/circuits/_block_diagram_drawer.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_block_diagram_drawer.py#L179-L183
def set_col_min_width(self, x: int, min_width: int): """Sets a minimum width for blocks in the column with coordinate x.""" if x < 0: raise IndexError('x < 0') self._min_widths[x] = min_width
[ "def", "set_col_min_width", "(", "self", ",", "x", ":", "int", ",", "min_width", ":", "int", ")", ":", "if", "x", "<", "0", ":", "raise", "IndexError", "(", "'x < 0'", ")", "self", ".", "_min_widths", "[", "x", "]", "=", "min_width" ]
Sets a minimum width for blocks in the column with coordinate x.
[ "Sets", "a", "minimum", "width", "for", "blocks", "in", "the", "column", "with", "coordinate", "x", "." ]
python
train
44.6
rq/Flask-RQ2
src/flask_rq2/app.py
https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L195-L208
def init_cli(self, app): """ Initialize the Flask CLI support in case it was enabled for the app. Works with both Flask>=1.0's CLI support as well as the backport in the Flask-CLI package for Flask<1.0. """ # in case click isn't installed after all if cli...
[ "def", "init_cli", "(", "self", ",", "app", ")", ":", "# in case click isn't installed after all", "if", "click", "is", "None", ":", "raise", "RuntimeError", "(", "'Cannot import click. Is it installed?'", ")", "# only add commands if we have a click context available", "from...
Initialize the Flask CLI support in case it was enabled for the app. Works with both Flask>=1.0's CLI support as well as the backport in the Flask-CLI package for Flask<1.0.
[ "Initialize", "the", "Flask", "CLI", "support", "in", "case", "it", "was", "enabled", "for", "the", "app", "." ]
python
train
37.785714
saltstack/salt
salt/engines/slack.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/slack.py#L362-L380
def commandline_to_list(self, cmdline_str, trigger_string): ''' cmdline_str is the string of the command line trigger_string is the trigger string, to be removed ''' cmdline = salt.utils.args.shlex_split(cmdline_str[len(trigger_string):]) # Remove slack url parsing ...
[ "def", "commandline_to_list", "(", "self", ",", "cmdline_str", ",", "trigger_string", ")", ":", "cmdline", "=", "salt", ".", "utils", ".", "args", ".", "shlex_split", "(", "cmdline_str", "[", "len", "(", "trigger_string", ")", ":", "]", ")", "# Remove slack ...
cmdline_str is the string of the command line trigger_string is the trigger string, to be removed
[ "cmdline_str", "is", "the", "string", "of", "the", "command", "line", "trigger_string", "is", "the", "trigger", "string", "to", "be", "removed" ]
python
train
42.789474
marcomusy/vtkplotter
vtkplotter/vtkio.py
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L245-L256
def loadStructuredPoints(filename): """Load a ``vtkStructuredPoints`` object from file and return an ``Actor(vtkActor)`` object. .. hint:: |readStructuredPoints| |readStructuredPoints.py|_ """ reader = vtk.vtkStructuredPointsReader() reader.SetFileName(filename) reader.Update() gf = vtk.vtk...
[ "def", "loadStructuredPoints", "(", "filename", ")", ":", "reader", "=", "vtk", ".", "vtkStructuredPointsReader", "(", ")", "reader", ".", "SetFileName", "(", "filename", ")", "reader", ".", "Update", "(", ")", "gf", "=", "vtk", ".", "vtkImageDataGeometryFilte...
Load a ``vtkStructuredPoints`` object from file and return an ``Actor(vtkActor)`` object. .. hint:: |readStructuredPoints| |readStructuredPoints.py|_
[ "Load", "a", "vtkStructuredPoints", "object", "from", "file", "and", "return", "an", "Actor", "(", "vtkActor", ")", "object", "." ]
python
train
36.083333
Microsoft/nni
tools/nni_trial_tool/log_utils.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/log_utils.py#L106-L116
def write(self, buf): ''' Write buffer data into logger/stdout ''' for line in buf.rstrip().splitlines(): self.orig_stdout.write(line.rstrip() + '\n') self.orig_stdout.flush() try: self.logger.log(self.log_level, line.rstrip()) ...
[ "def", "write", "(", "self", ",", "buf", ")", ":", "for", "line", "in", "buf", ".", "rstrip", "(", ")", ".", "splitlines", "(", ")", ":", "self", ".", "orig_stdout", ".", "write", "(", "line", ".", "rstrip", "(", ")", "+", "'\\n'", ")", "self", ...
Write buffer data into logger/stdout
[ "Write", "buffer", "data", "into", "logger", "/", "stdout" ]
python
train
32.454545
inveniosoftware/invenio-oaiserver
invenio_oaiserver/utils.py
https://github.com/inveniosoftware/invenio-oaiserver/blob/eae765e32bd816ddc5612d4b281caf205518b512/invenio_oaiserver/utils.py#L66-L77
def dumps_etree(pid, record, **kwargs): """Dump MARC21 compatible record. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record: The :class:`invenio_records.api.Record` instance. :returns: A LXML Element instance. """ from dojson.contrib.to_marc21...
[ "def", "dumps_etree", "(", "pid", ",", "record", ",", "*", "*", "kwargs", ")", ":", "from", "dojson", ".", "contrib", ".", "to_marc21", "import", "to_marc21", "from", "dojson", ".", "contrib", ".", "to_marc21", ".", "utils", "import", "dumps_etree", "retur...
Dump MARC21 compatible record. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record: The :class:`invenio_records.api.Record` instance. :returns: A LXML Element instance.
[ "Dump", "MARC21", "compatible", "record", "." ]
python
train
37.666667
globality-corp/microcosm-flask
microcosm_flask/swagger/parameters/base.py
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/base.py#L53-L62
def iter_parsed_values(self, field: Field) -> Iterable[Tuple[str, Any]]: """ Walk the dictionary of parsers and emit all non-null values. """ for key, func in self.parsers.items(): value = func(field) if not value: continue yield key, ...
[ "def", "iter_parsed_values", "(", "self", ",", "field", ":", "Field", ")", "->", "Iterable", "[", "Tuple", "[", "str", ",", "Any", "]", "]", ":", "for", "key", ",", "func", "in", "self", ".", "parsers", ".", "items", "(", ")", ":", "value", "=", ...
Walk the dictionary of parsers and emit all non-null values.
[ "Walk", "the", "dictionary", "of", "parsers", "and", "emit", "all", "non", "-", "null", "values", "." ]
python
train
31.6
Azure/azure-multiapi-storage-python
azure/multiapi/storage/v2016_05_31/table/_deserialization.py
https://github.com/Azure/azure-multiapi-storage-python/blob/bd5482547f993c6eb56fd09070e15c2e9616e440/azure/multiapi/storage/v2016_05_31/table/_deserialization.py#L243-L266
def _convert_json_response_to_entities(response, property_resolver, require_encryption, key_encryption_key, key_resolver): ''' Converts the response to tables class. ''' if response is None or response.body is None: return None entities = _list() enti...
[ "def", "_convert_json_response_to_entities", "(", "response", ",", "property_resolver", ",", "require_encryption", ",", "key_encryption_key", ",", "key_resolver", ")", ":", "if", "response", "is", "None", "or", "response", ".", "body", "is", "None", ":", "return", ...
Converts the response to tables class.
[ "Converts", "the", "response", "to", "tables", "class", "." ]
python
train
35.166667
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1277-L1287
def _add_child(self, collection, set, child): """Adds 'child' to 'collection', first checking 'set' to see if it's already present.""" added = None for c in child: if c not in set: set.add(c) collection.append(c) added = 1 ...
[ "def", "_add_child", "(", "self", ",", "collection", ",", "set", ",", "child", ")", ":", "added", "=", "None", "for", "c", "in", "child", ":", "if", "c", "not", "in", "set", ":", "set", ".", "add", "(", "c", ")", "collection", ".", "append", "(",...
Adds 'child' to 'collection', first checking 'set' to see if it's already present.
[ "Adds", "child", "to", "collection", "first", "checking", "set", "to", "see", "if", "it", "s", "already", "present", "." ]
python
train
32.454545
edx/opaque-keys
opaque_keys/edx/locations.py
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L52-L59
def from_string(cls, serialized): """Deprecated. Use :meth:`locator.CourseLocator.from_string`.""" warnings.warn( "SlashSeparatedCourseKey is deprecated! Please use locator.CourseLocator", DeprecationWarning, stacklevel=2 ) return CourseLocator.from_st...
[ "def", "from_string", "(", "cls", ",", "serialized", ")", ":", "warnings", ".", "warn", "(", "\"SlashSeparatedCourseKey is deprecated! Please use locator.CourseLocator\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "return", "CourseLocator", ".", "from...
Deprecated. Use :meth:`locator.CourseLocator.from_string`.
[ "Deprecated", ".", "Use", ":", "meth", ":", "locator", ".", "CourseLocator", ".", "from_string", "." ]
python
train
41.125
inveniosoftware-contrib/invenio-classifier
invenio_classifier/find.py
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/find.py#L476-L518
def get_reference_section_beginning(fulltext): """Get start of reference section.""" sect_start = { 'start_line': None, 'end_line': None, 'title_string': None, 'marker_pattern': None, 'marker': None, 'how_found_start': None, } # Find start of refs section...
[ "def", "get_reference_section_beginning", "(", "fulltext", ")", ":", "sect_start", "=", "{", "'start_line'", ":", "None", ",", "'end_line'", ":", "None", ",", "'title_string'", ":", "None", ",", "'marker_pattern'", ":", "None", ",", "'marker'", ":", "None", ",...
Get start of reference section.
[ "Get", "start", "of", "reference", "section", "." ]
python
train
40.116279
acutesoftware/AIKIF
aikif/cls_log.py
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/cls_log.py#L98-L113
def show_time_as_short_string(self, seconds): """ converts seconds to a string in terms of seconds -> years to show complexity of algorithm """ if seconds < 60: return str(seconds) + ' seconds' elif seconds < 3600: return str(round(seconds/60, 1)...
[ "def", "show_time_as_short_string", "(", "self", ",", "seconds", ")", ":", "if", "seconds", "<", "60", ":", "return", "str", "(", "seconds", ")", "+", "' seconds'", "elif", "seconds", "<", "3600", ":", "return", "str", "(", "round", "(", "seconds", "/", ...
converts seconds to a string in terms of seconds -> years to show complexity of algorithm
[ "converts", "seconds", "to", "a", "string", "in", "terms", "of", "seconds", "-", ">", "years", "to", "show", "complexity", "of", "algorithm" ]
python
train
42.625
awslabs/sockeye
sockeye/encoder.py
https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/encoder.py#L747-L753
def get_max_seq_len(self) -> Optional[int]: """ :return: The maximum length supported by the encoder if such a restriction exists. """ max_seq_len = min((encoder.get_max_seq_len() for encoder in self.encoders if encoder.get_max_seq_len() is not None), default=N...
[ "def", "get_max_seq_len", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "max_seq_len", "=", "min", "(", "(", "encoder", ".", "get_max_seq_len", "(", ")", "for", "encoder", "in", "self", ".", "encoders", "if", "encoder", ".", "get_max_seq_len", ...
:return: The maximum length supported by the encoder if such a restriction exists.
[ ":", "return", ":", "The", "maximum", "length", "supported", "by", "the", "encoder", "if", "such", "a", "restriction", "exists", "." ]
python
train
49.285714
tducret/precisionmapper-python
precisionmapper/__init__.py
https://github.com/tducret/precisionmapper-python/blob/462dcc5bccf6edec780b8b7bc42e8c1d717db942/precisionmapper/__init__.py#L219-L230
def _css_select(soup, css_selector): """ Returns the content of the element pointed by the CSS selector, or an empty string if not found """ selection = soup.select(css_selector) if len(selection) > 0: if hasattr(selection[0], 'text'): retour = selection[0].te...
[ "def", "_css_select", "(", "soup", ",", "css_selector", ")", ":", "selection", "=", "soup", ".", "select", "(", "css_selector", ")", "if", "len", "(", "selection", ")", ">", "0", ":", "if", "hasattr", "(", "selection", "[", "0", "]", ",", "'text'", "...
Returns the content of the element pointed by the CSS selector, or an empty string if not found
[ "Returns", "the", "content", "of", "the", "element", "pointed", "by", "the", "CSS", "selector", "or", "an", "empty", "string", "if", "not", "found" ]
python
train
35.416667
skyfielders/python-skyfield
skyfield/functions.py
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/functions.py#L64-L79
def from_polar(r, theta, phi): """Convert ``(r, theta, phi)`` to Cartesian coordinates ``[x y z]``. ``r`` - vector length ``theta`` - angle above (+) or below (-) the xy-plane ``phi`` - angle around the z-axis The meaning and order of the three polar parameters is designed to match both ISO 31...
[ "def", "from_polar", "(", "r", ",", "theta", ",", "phi", ")", ":", "rxy", "=", "r", "*", "cos", "(", "theta", ")", "return", "array", "(", "(", "rxy", "*", "cos", "(", "phi", ")", ",", "rxy", "*", "sin", "(", "phi", ")", ",", "r", "*", "sin...
Convert ``(r, theta, phi)`` to Cartesian coordinates ``[x y z]``. ``r`` - vector length ``theta`` - angle above (+) or below (-) the xy-plane ``phi`` - angle around the z-axis The meaning and order of the three polar parameters is designed to match both ISO 31-11 and the traditional order used by ...
[ "Convert", "(", "r", "theta", "phi", ")", "to", "Cartesian", "coordinates", "[", "x", "y", "z", "]", "." ]
python
train
41.25
tensorflow/tensor2tensor
tensor2tensor/rl/gym_utils.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/gym_utils.py#L209-L223
def register_gym_env(class_entry_point, version="v0", kwargs=None): """Registers the class in Gym and returns the registered name and the env.""" split_on_colon = class_entry_point.split(":") assert len(split_on_colon) == 2 class_name = split_on_colon[1] # We have to add the version to conform to gym's API....
[ "def", "register_gym_env", "(", "class_entry_point", ",", "version", "=", "\"v0\"", ",", "kwargs", "=", "None", ")", ":", "split_on_colon", "=", "class_entry_point", ".", "split", "(", "\":\"", ")", "assert", "len", "(", "split_on_colon", ")", "==", "2", "cl...
Registers the class in Gym and returns the registered name and the env.
[ "Registers", "the", "class", "in", "Gym", "and", "returns", "the", "registered", "name", "and", "the", "env", "." ]
python
train
39.333333
open-homeautomation/pknx
knxip/core.py
https://github.com/open-homeautomation/pknx/blob/a8aed8271563923c447aa330ba7c1c2927286f7a/knxip/core.py#L141-L162
def to_frame(self): """Convert the object to its frame format.""" self.sanitize() res = [] res.append((1 << 7) + (1 << 4) + (self.repeat << 5) + (self.priority << 2)) res.append(self.src_addr >> 8) res.append(self.src_addr % 0x100) res.append(se...
[ "def", "to_frame", "(", "self", ")", ":", "self", ".", "sanitize", "(", ")", "res", "=", "[", "]", "res", ".", "append", "(", "(", "1", "<<", "7", ")", "+", "(", "1", "<<", "4", ")", "+", "(", "self", ".", "repeat", "<<", "5", ")", "+", "...
Convert the object to its frame format.
[ "Convert", "the", "object", "to", "its", "frame", "format", "." ]
python
train
31.090909
gem/oq-engine
openquake/risklib/riskinput.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskinput.py#L373-L418
def get_output(self, assets_by_taxo, haz, rlzi=None): """ :param assets_by_taxo: a dictionary taxonomy index -> assets on a site :param haz: an array or a dictionary of hazard on that site :param rlzi: if given, a realization index """ if isinstance(haz, numpy.ndarray): ...
[ "def", "get_output", "(", "self", ",", "assets_by_taxo", ",", "haz", ",", "rlzi", "=", "None", ")", ":", "if", "isinstance", "(", "haz", ",", "numpy", ".", "ndarray", ")", ":", "# NB: in GMF-based calculations the order in which", "# the gmfs are stored is random si...
:param assets_by_taxo: a dictionary taxonomy index -> assets on a site :param haz: an array or a dictionary of hazard on that site :param rlzi: if given, a realization index
[ ":", "param", "assets_by_taxo", ":", "a", "dictionary", "taxonomy", "index", "-", ">", "assets", "on", "a", "site", ":", "param", "haz", ":", "an", "array", "or", "a", "dictionary", "of", "hazard", "on", "that", "site", ":", "param", "rlzi", ":", "if",...
python
train
43.23913
botstory/botstory
botstory/di/injector_service.py
https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/di/injector_service.py#L175-L202
def bind(self, instance, auto=False): """ Bind deps to instance :param instance: :param auto: follow update of DI and refresh binds once we will get something new :return: """ methods = [ (m, cls.__dict__[m]) for cls in inspect.getmro(type...
[ "def", "bind", "(", "self", ",", "instance", ",", "auto", "=", "False", ")", ":", "methods", "=", "[", "(", "m", ",", "cls", ".", "__dict__", "[", "m", "]", ")", "for", "cls", "in", "inspect", ".", "getmro", "(", "type", "(", "instance", ")", "...
Bind deps to instance :param instance: :param auto: follow update of DI and refresh binds once we will get something new :return:
[ "Bind", "deps", "to", "instance" ]
python
train
32.785714
lmjohns3/downhill
downhill/base.py
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L153-L167
def _compile(self, **kwargs): '''Compile the Theano functions for evaluating and updating our model. ''' util.log('compiling evaluation function') self.f_eval = theano.function(self._inputs, self._monitor_exprs, ...
[ "def", "_compile", "(", "self", ",", "*", "*", "kwargs", ")", ":", "util", ".", "log", "(", "'compiling evaluation function'", ")", "self", ".", "f_eval", "=", "theano", ".", "function", "(", "self", ".", "_inputs", ",", "self", ".", "_monitor_exprs", ",...
Compile the Theano functions for evaluating and updating our model.
[ "Compile", "the", "Theano", "functions", "for", "evaluating", "and", "updating", "our", "model", "." ]
python
train
52.933333
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/guerilla/guerillamgmt.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L237-L250
def add_atype(self, ): """Add a atype and store it in the self.atypes :returns: None :rtype: None :raises: None """ i = self.atype_tablev.currentIndex() item = i.internalPointer() if item: atype = item.internal_data() atype.project...
[ "def", "add_atype", "(", "self", ",", ")", ":", "i", "=", "self", ".", "atype_tablev", ".", "currentIndex", "(", ")", "item", "=", "i", ".", "internalPointer", "(", ")", "if", "item", ":", "atype", "=", "item", ".", "internal_data", "(", ")", "atype"...
Add a atype and store it in the self.atypes :returns: None :rtype: None :raises: None
[ "Add", "a", "atype", "and", "store", "it", "in", "the", "self", ".", "atypes" ]
python
train
28.5
saltstack/salt
salt/cloud/clouds/azurearm.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/azurearm.py#L1795-L1808
def delete_managed_disk(call=None, kwargs=None): # pylint: disable=unused-argument ''' Delete a managed disk from a resource group. ''' compconn = get_conn(client_type='compute') try: compconn.disks.delete(kwargs['resource_group'], kwargs['blob']) except Exception as exc: log....
[ "def", "delete_managed_disk", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "# pylint: disable=unused-argument", "compconn", "=", "get_conn", "(", "client_type", "=", "'compute'", ")", "try", ":", "compconn", ".", "disks", ".", "delete", "(",...
Delete a managed disk from a resource group.
[ "Delete", "a", "managed", "disk", "from", "a", "resource", "group", "." ]
python
train
30.642857
vpelletier/pprofile
pprofile.py
https://github.com/vpelletier/pprofile/blob/51a36896727565faf23e5abccc9204e5f935fe1e/pprofile.py#L752-L756
def runctx(self, cmd, globals, locals): """Similar to profile.Profile.runctx .""" with self(): exec(cmd, globals, locals) return self
[ "def", "runctx", "(", "self", ",", "cmd", ",", "globals", ",", "locals", ")", ":", "with", "self", "(", ")", ":", "exec", "(", "cmd", ",", "globals", ",", "locals", ")", "return", "self" ]
Similar to profile.Profile.runctx .
[ "Similar", "to", "profile", ".", "Profile", ".", "runctx", "." ]
python
train
33
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L885-L896
def ovsdb_server_method(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ovsdb_server = ET.SubElement(config, "ovsdb-server", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(ovsdb_server, "name") name_key.text = kwargs.pop('...
[ "def", "ovsdb_server_method", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ovsdb_server", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ovsdb-server\"", ",", "xmlns", "=", "\"urn:broca...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
42
cnelson/python-fleet
fleet/v1/client.py
https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L97-L113
def forward_tcp(self, host, port): """Open a connection to host:port via an ssh tunnel. Args: host (str): The host to connect to. port (int): The port to connect to. Returns: A socket-like object that is connected to the provided host:port. """ ...
[ "def", "forward_tcp", "(", "self", ",", "host", ",", "port", ")", ":", "return", "self", ".", "transport", ".", "open_channel", "(", "'direct-tcpip'", ",", "(", "host", ",", "port", ")", ",", "self", ".", "transport", ".", "getpeername", "(", ")", ")" ...
Open a connection to host:port via an ssh tunnel. Args: host (str): The host to connect to. port (int): The port to connect to. Returns: A socket-like object that is connected to the provided host:port.
[ "Open", "a", "connection", "to", "host", ":", "port", "via", "an", "ssh", "tunnel", "." ]
python
train
26.411765
berkeley-cocosci/Wallace
wallace/models.py
https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/models.py#L1252-L1266
def mutate(self, info_in): """Replicate an info + mutation. To mutate an info, that info must have a method called ``_mutated_contents``. """ # check self is not failed if self.failed: raise ValueError("{} cannot mutate as it has failed.".format(self)) ...
[ "def", "mutate", "(", "self", ",", "info_in", ")", ":", "# check self is not failed", "if", "self", ".", "failed", ":", "raise", "ValueError", "(", "\"{} cannot mutate as it has failed.\"", ".", "format", "(", "self", ")", ")", "from", "transformations", "import",...
Replicate an info + mutation. To mutate an info, that info must have a method called ``_mutated_contents``.
[ "Replicate", "an", "info", "+", "mutation", "." ]
python
train
34.4
carsonyl/pypac
pypac/resolver.py
https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/resolver.py#L83-L96
def get_proxy_for_requests(self, url): """ Get proxy configuration for a given URL, in a form ready to use with the Requests library. :param str url: The URL for which to obtain proxy configuration. :returns: Proxy configuration in a form recognized by Requests, for use with the ``proxi...
[ "def", "get_proxy_for_requests", "(", "self", ",", "url", ")", ":", "proxy", "=", "self", ".", "get_proxy", "(", "url", ")", "if", "not", "proxy", ":", "raise", "ProxyConfigExhaustedError", "(", "url", ")", "return", "proxy_parameter_for_requests", "(", "proxy...
Get proxy configuration for a given URL, in a form ready to use with the Requests library. :param str url: The URL for which to obtain proxy configuration. :returns: Proxy configuration in a form recognized by Requests, for use with the ``proxies`` parameter. :rtype: dict :raises ProxyC...
[ "Get", "proxy", "configuration", "for", "a", "given", "URL", "in", "a", "form", "ready", "to", "use", "with", "the", "Requests", "library", "." ]
python
train
46.714286
trec-kba/streamcorpus-pipeline
streamcorpus_pipeline/_spinn3r_feed_storage.py
https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_spinn3r_feed_storage.py#L118-L123
def _read_varint(self): """Read exactly a varint out of the underlying file.""" buf = self._read(8) (n, l) = _DecodeVarint(buf, 0) self._unread(buf[l:]) return n
[ "def", "_read_varint", "(", "self", ")", ":", "buf", "=", "self", ".", "_read", "(", "8", ")", "(", "n", ",", "l", ")", "=", "_DecodeVarint", "(", "buf", ",", "0", ")", "self", ".", "_unread", "(", "buf", "[", "l", ":", "]", ")", "return", "n...
Read exactly a varint out of the underlying file.
[ "Read", "exactly", "a", "varint", "out", "of", "the", "underlying", "file", "." ]
python
test
32.666667
neuropsychology/NeuroKit.py
neurokit/eeg/eeg_data.py
https://github.com/neuropsychology/NeuroKit.py/blob/c9589348fbbde0fa7e986048c48f38e6b488adfe/neurokit/eeg/eeg_data.py#L23-L95
def eeg_add_channel(raw, channel, sync_index_eeg=0, sync_index_channel=0, channel_type=None, channel_name=None): """ Add a channel to a mne's Raw m/eeg file. It will basically synchronize the channel to the eeg data following a particular index and add it. Parameters ---------- raw : mne.io.Raw ...
[ "def", "eeg_add_channel", "(", "raw", ",", "channel", ",", "sync_index_eeg", "=", "0", ",", "sync_index_channel", "=", "0", ",", "channel_type", "=", "None", ",", "channel_name", "=", "None", ")", ":", "if", "channel_name", "is", "None", ":", "if", "isinst...
Add a channel to a mne's Raw m/eeg file. It will basically synchronize the channel to the eeg data following a particular index and add it. Parameters ---------- raw : mne.io.Raw Raw EEG data. channel : list or numpy.array The channel to be added. sync_index_eeg : int or list ...
[ "Add", "a", "channel", "to", "a", "mne", "s", "Raw", "m", "/", "eeg", "file", ".", "It", "will", "basically", "synchronize", "the", "channel", "to", "the", "eeg", "data", "following", "a", "particular", "index", "and", "add", "it", "." ]
python
train
31.69863
DarkEnergySurvey/ugali
ugali/utils/plotting.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L150-L158
def sparseHealpixFiles(title, infiles, field='MAGLIM',**kwargs): """ Inputs: field """ #map = ugali.utils.skymap.readSparseHealpixMaps(infiles,field) map = ugali.utils.skymap.read_partial_map(infiles,field) ax = hp.mollview(map=map, title=title, **kwargs) return ax, m...
[ "def", "sparseHealpixFiles", "(", "title", ",", "infiles", ",", "field", "=", "'MAGLIM'", ",", "*", "*", "kwargs", ")", ":", "#map = ugali.utils.skymap.readSparseHealpixMaps(infiles,field)", "map", "=", "ugali", ".", "utils", ".", "skymap", ".", "read_partial_map", ...
Inputs: field
[ "Inputs", ":", "field" ]
python
train
34.888889
thieman/dagobah
dagobah/core/core.py
https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L475-L495
def edit(self, **kwargs): """ Change this Job's name. This will affect the historical data available for this Job, e.g. past run logs will no longer be accessible. """ logger.debug('Job {0} changing name to {1}'.format(self.name, kwargs.get('name'))) if not self.state.a...
[ "def", "edit", "(", "self", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Job {0} changing name to {1}'", ".", "format", "(", "self", ".", "name", ",", "kwargs", ".", "get", "(", "'name'", ")", ")", ")", "if", "not", "self", ".", ...
Change this Job's name. This will affect the historical data available for this Job, e.g. past run logs will no longer be accessible.
[ "Change", "this", "Job", "s", "name", "." ]
python
train
39.47619
CamDavidsonPilon/lifetimes
lifetimes/fitters/beta_geo_beta_binom_fitter.py
https://github.com/CamDavidsonPilon/lifetimes/blob/f926308bc03c17c1d12fead729de43885cf13321/lifetimes/fitters/beta_geo_beta_binom_fitter.py#L248-L299
def expected_number_of_transactions_in_first_n_periods(self, n): r""" Return expected number of transactions in first n n_periods. Expected number of transactions occurring across first n transaction opportunities. Used by Fader and Hardie to assess in-sample fit. .. ma...
[ "def", "expected_number_of_transactions_in_first_n_periods", "(", "self", ",", "n", ")", ":", "params", "=", "self", ".", "_unload_params", "(", "\"alpha\"", ",", "\"beta\"", ",", "\"gamma\"", ",", "\"delta\"", ")", "alpha", ",", "beta", ",", "gamma", ",", "de...
r""" Return expected number of transactions in first n n_periods. Expected number of transactions occurring across first n transaction opportunities. Used by Fader and Hardie to assess in-sample fit. .. math:: Pr(X(n) = x| \alpha, \beta, \gamma, \delta) See (7) in Fade...
[ "r", "Return", "expected", "number", "of", "transactions", "in", "first", "n", "n_periods", "." ]
python
train
29.480769
vertexproject/synapse
synapse/lib/slabseqn.py
https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/slabseqn.py#L113-L128
def iter(self, offs): ''' Iterate over items in a sequence from a given offset. Args: offs (int): The offset to begin iterating from. Yields: (indx, valu): The index and valu of the item. ''' startkey = s_common.int64en(offs) for lkey, l...
[ "def", "iter", "(", "self", ",", "offs", ")", ":", "startkey", "=", "s_common", ".", "int64en", "(", "offs", ")", "for", "lkey", ",", "lval", "in", "self", ".", "slab", ".", "scanByRange", "(", "startkey", ",", "db", "=", "self", ".", "db", ")", ...
Iterate over items in a sequence from a given offset. Args: offs (int): The offset to begin iterating from. Yields: (indx, valu): The index and valu of the item.
[ "Iterate", "over", "items", "in", "a", "sequence", "from", "a", "given", "offset", "." ]
python
train
29.0625
goshuirc/irc
girc/client.py
https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L360-L367
def ctcp_reply(self, target, ctcp_verb, argument=None): """Send a CTCP reply to the given target.""" # we don't support complex ctcp encapsulation because we're somewhat sane atoms = [ctcp_verb] if argument is not None: atoms.append(argument) X_DELIM = '\x01' ...
[ "def", "ctcp_reply", "(", "self", ",", "target", ",", "ctcp_verb", ",", "argument", "=", "None", ")", ":", "# we don't support complex ctcp encapsulation because we're somewhat sane", "atoms", "=", "[", "ctcp_verb", "]", "if", "argument", "is", "not", "None", ":", ...
Send a CTCP reply to the given target.
[ "Send", "a", "CTCP", "reply", "to", "the", "given", "target", "." ]
python
train
48.25
justanr/Flask-Transfer
flask_transfer/transfer.py
https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L186-L219
def save(self, filehandle, destination=None, metadata=None, validate=True, catch_all_errors=False, *args, **kwargs): """Saves the filehandle to the provided destination or the attached default destination. Allows passing arbitrary positional and keyword arguments to the saving mecha...
[ "def", "save", "(", "self", ",", "filehandle", ",", "destination", "=", "None", ",", "metadata", "=", "None", ",", "validate", "=", "True", ",", "catch_all_errors", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "destination", "=", ...
Saves the filehandle to the provided destination or the attached default destination. Allows passing arbitrary positional and keyword arguments to the saving mechanism :param filehandle: werkzeug.FileStorage instance :param dest: String path, callable or writable destination to pass the...
[ "Saves", "the", "filehandle", "to", "the", "provided", "destination", "or", "the", "attached", "default", "destination", ".", "Allows", "passing", "arbitrary", "positional", "and", "keyword", "arguments", "to", "the", "saving", "mechanism" ]
python
train
45.617647
sporteasy/python-poeditor
poeditor/client.py
https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L760-L770
def remove_contributor(self, project_id, email, language): """ Removes a contributor """ self._run( url_path="contributors/remove", id=project_id, email=email, language=language ) return True
[ "def", "remove_contributor", "(", "self", ",", "project_id", ",", "email", ",", "language", ")", ":", "self", ".", "_run", "(", "url_path", "=", "\"contributors/remove\"", ",", "id", "=", "project_id", ",", "email", "=", "email", ",", "language", "=", "lan...
Removes a contributor
[ "Removes", "a", "contributor" ]
python
train
25.181818
bukun/TorCMS
torcms/script/autocrud/base_crud.py
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/base_crud.py#L31-L40
def build_dir(): ''' Build the directory used for templates. ''' tag_arr = ['add', 'edit', 'view', 'list', 'infolist'] path_arr = [os.path.join(CRUD_PATH, x) for x in tag_arr] for wpath in path_arr: if os.path.exists(wpath): continue os.makedirs(wpath)
[ "def", "build_dir", "(", ")", ":", "tag_arr", "=", "[", "'add'", ",", "'edit'", ",", "'view'", ",", "'list'", ",", "'infolist'", "]", "path_arr", "=", "[", "os", ".", "path", ".", "join", "(", "CRUD_PATH", ",", "x", ")", "for", "x", "in", "tag_arr"...
Build the directory used for templates.
[ "Build", "the", "directory", "used", "for", "templates", "." ]
python
train
29.5
bitesofcode/projexui
projexui/widgets/xviewwidget/xviewwidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewwidget.py#L65-L75
def canClose(self): """ Checks to see if the view widget can close by checking all of its \ sub-views to make sure they're ok to close. :return <bool> """ for view in self.findChildren(XView): if not view.canClose(): return False ...
[ "def", "canClose", "(", "self", ")", ":", "for", "view", "in", "self", ".", "findChildren", "(", "XView", ")", ":", "if", "not", "view", ".", "canClose", "(", ")", ":", "return", "False", "return", "True" ]
Checks to see if the view widget can close by checking all of its \ sub-views to make sure they're ok to close. :return <bool>
[ "Checks", "to", "see", "if", "the", "view", "widget", "can", "close", "by", "checking", "all", "of", "its", "\\", "sub", "-", "views", "to", "make", "sure", "they", "re", "ok", "to", "close", ".", ":", "return", "<bool", ">" ]
python
train
29.818182
sethmlarson/virtualbox-python
virtualbox/library_ext/keyboard.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library_ext/keyboard.py#L226-L272
def put_keys(self, press_keys=None, hold_keys=None, press_delay=50): """Put scancodes that represent keys defined in the sequences provided. Arguments: press_keys: Press a sequence of keys hold_keys: While pressing the sequence of keys, hold down the keys de...
[ "def", "put_keys", "(", "self", ",", "press_keys", "=", "None", ",", "hold_keys", "=", "None", ",", "press_delay", "=", "50", ")", ":", "if", "press_keys", "is", "None", ":", "press_keys", "=", "[", "]", "if", "hold_keys", "is", "None", ":", "hold_keys...
Put scancodes that represent keys defined in the sequences provided. Arguments: press_keys: Press a sequence of keys hold_keys: While pressing the sequence of keys, hold down the keys defined in hold_keys. press_delay: Number of milliseconds to delay bet...
[ "Put", "scancodes", "that", "represent", "keys", "defined", "in", "the", "sequences", "provided", "." ]
python
train
35.723404
jilljenn/tryalgo
tryalgo/dfs.py
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dfs.py#L46-L62
def dfs_tree(graph, start=0): """DFS, build DFS tree in unweighted graph :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: precedence table :complexity: `O(|V|+|E|)` """ to_visit = [start] prec = [None] * len(graph) ...
[ "def", "dfs_tree", "(", "graph", ",", "start", "=", "0", ")", ":", "to_visit", "=", "[", "start", "]", "prec", "=", "[", "None", "]", "*", "len", "(", "graph", ")", "while", "to_visit", ":", "# an empty queue equals False", "node", "=", "to_visit", "."...
DFS, build DFS tree in unweighted graph :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: precedence table :complexity: `O(|V|+|E|)`
[ "DFS", "build", "DFS", "tree", "in", "unweighted", "graph" ]
python
train
33.176471
django-salesforce/django-salesforce
salesforce/dbapi/driver.py
https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/driver.py#L218-L243
def handle_api_exceptions(self, method, *url_parts, **kwargs): """Call REST API and handle exceptions Params: method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE' url_parts: like in rest_api_url() method api_ver: like in rest_api_url() method kwargs: othe...
[ "def", "handle_api_exceptions", "(", "self", ",", "method", ",", "*", "url_parts", ",", "*", "*", "kwargs", ")", ":", "# The outer part - about error handler", "assert", "method", "in", "(", "'HEAD'", ",", "'GET'", ",", "'POST'", ",", "'PATCH'", ",", "'DELETE'...
Call REST API and handle exceptions Params: method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE' url_parts: like in rest_api_url() method api_ver: like in rest_api_url() method kwargs: other parameters passed to requests.request, but the only nota...
[ "Call", "REST", "API", "and", "handle", "exceptions", "Params", ":", "method", ":", "HEAD", "GET", "POST", "PATCH", "or", "DELETE", "url_parts", ":", "like", "in", "rest_api_url", "()", "method", "api_ver", ":", "like", "in", "rest_api_url", "()", "method", ...
python
train
49.153846
watson-developer-cloud/python-sdk
ibm_watson/assistant_v2.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/assistant_v2.py#L1240-L1255
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'message_type') and self.message_type is not None: _dict['message_type'] = self.message_type if hasattr(self, 'text') and self.text is not None: _dict['text'] =...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'message_type'", ")", "and", "self", ".", "message_type", "is", "not", "None", ":", "_dict", "[", "'message_type'", "]", "=", "self", ".", "message_ty...
Return a json dictionary representing this model.
[ "Return", "a", "json", "dictionary", "representing", "this", "model", "." ]
python
train
53.9375