repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
thiagopbueno/rddl2tf
rddl2tf/compiler.py
https://github.com/thiagopbueno/rddl2tf/blob/f7c03d3a74d2663807c1e23e04eeed2e85166b71/rddl2tf/compiler.py#L441-L461
def reward_scope(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor], next_state: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]: '''Returns the complete reward fluent scope for the current `state`, `action` fluents, and `next_sta...
[ "def", "reward_scope", "(", "self", ",", "state", ":", "Sequence", "[", "tf", ".", "Tensor", "]", ",", "action", ":", "Sequence", "[", "tf", ".", "Tensor", "]", ",", "next_state", ":", "Sequence", "[", "tf", ".", "Tensor", "]", ")", "->", "Dict", "...
Returns the complete reward fluent scope for the current `state`, `action` fluents, and `next_state` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. next_state (Sequence[tf.Tensor]): The next st...
[ "Returns", "the", "complete", "reward", "fluent", "scope", "for", "the", "current", "state", "action", "fluents", "and", "next_state", "fluents", "." ]
python
train
Azure/blobxfer
blobxfer/operations/upload.py
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/upload.py#L260-L281
def _check_for_uploads_from_md5(self): # type: (Uploader) -> None """Check queue for a file to upload :param Uploader self: this """ cv = self._md5_offload.done_cv while not self.termination_check_md5: result = None cv.acquire() while T...
[ "def", "_check_for_uploads_from_md5", "(", "self", ")", ":", "# type: (Uploader) -> None", "cv", "=", "self", ".", "_md5_offload", ".", "done_cv", "while", "not", "self", ".", "termination_check_md5", ":", "result", "=", "None", "cv", ".", "acquire", "(", ")", ...
Check queue for a file to upload :param Uploader self: this
[ "Check", "queue", "for", "a", "file", "to", "upload", ":", "param", "Uploader", "self", ":", "this" ]
python
train
fermiPy/fermipy
fermipy/hpx_utils.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/hpx_utils.py#L559-L571
def create_from_hdu(cls, hdu, ebins=None): """ Creates an HPX object from a FITS header. hdu : The FITS hdu ebins : Energy bin edges [optional] """ convname = HPX.identify_HPX_convention(hdu.header) conv = HPX_FITS_CONVENTIONS[convname] try: pixel...
[ "def", "create_from_hdu", "(", "cls", ",", "hdu", ",", "ebins", "=", "None", ")", ":", "convname", "=", "HPX", ".", "identify_HPX_convention", "(", "hdu", ".", "header", ")", "conv", "=", "HPX_FITS_CONVENTIONS", "[", "convname", "]", "try", ":", "pixels", ...
Creates an HPX object from a FITS header. hdu : The FITS hdu ebins : Energy bin edges [optional]
[ "Creates", "an", "HPX", "object", "from", "a", "FITS", "header", "." ]
python
train
fbcotter/py3nvml
py3nvml/py3nvml.py
https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/py3nvml.py#L2128-L2154
def nvmlDeviceGetMultiGpuBoard(handle): r""" /** * Retrieves whether the device is on a Multi-GPU Board * Devices that are on multi-GPU boards will set \a multiGpuBool to a non-zero value. * * For Fermi &tm; or newer fully supported devices. * * @param device ...
[ "def", "nvmlDeviceGetMultiGpuBoard", "(", "handle", ")", ":", "c_multiGpu", "=", "c_uint", "(", ")", "fn", "=", "_nvmlGetFunctionPointer", "(", "\"nvmlDeviceGetMultiGpuBoard\"", ")", "ret", "=", "fn", "(", "handle", ",", "byref", "(", "c_multiGpu", ")", ")", "...
r""" /** * Retrieves whether the device is on a Multi-GPU Board * Devices that are on multi-GPU boards will set \a multiGpuBool to a non-zero value. * * For Fermi &tm; or newer fully supported devices. * * @param device The identifier of the target device ...
[ "r", "/", "**", "*", "Retrieves", "whether", "the", "device", "is", "on", "a", "Multi", "-", "GPU", "Board", "*", "Devices", "that", "are", "on", "multi", "-", "GPU", "boards", "will", "set", "\\", "a", "multiGpuBool", "to", "a", "non", "-", "zero", ...
python
train
dwavesystems/dimod
dimod/higherorder/polynomial.py
https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/higherorder/polynomial.py#L461-L491
def to_binary(self, copy=False): """Return a binary polynomial over `{0, 1}` variables. Args: copy (optional, default=False): If True, the returned polynomial is always a copy. Otherwise, if the polynomial is binary-valued already it returns itself. ...
[ "def", "to_binary", "(", "self", ",", "copy", "=", "False", ")", ":", "if", "self", ".", "vartype", "is", "Vartype", ".", "BINARY", ":", "if", "copy", ":", "return", "self", ".", "copy", "(", ")", "else", ":", "return", "self", "new", "=", "BinaryP...
Return a binary polynomial over `{0, 1}` variables. Args: copy (optional, default=False): If True, the returned polynomial is always a copy. Otherwise, if the polynomial is binary-valued already it returns itself. Returns: :obj:`.BinaryPolynomial...
[ "Return", "a", "binary", "polynomial", "over", "{", "0", "1", "}", "variables", "." ]
python
train
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L1845-L1942
def to_sql(self, conn, table_name, dbapi_module=None, use_python_type_specifiers=False, use_exact_column_names=True): """ Convert an SFrame to a single table in a SQL database. This function does not attempt to create the table or check if a table named `table_name` exists i...
[ "def", "to_sql", "(", "self", ",", "conn", ",", "table_name", ",", "dbapi_module", "=", "None", ",", "use_python_type_specifiers", "=", "False", ",", "use_exact_column_names", "=", "True", ")", ":", "mod_info", "=", "_get_global_dbapi_info", "(", "dbapi_module", ...
Convert an SFrame to a single table in a SQL database. This function does not attempt to create the table or check if a table named `table_name` exists in the database. It simply assumes that `table_name` exists in the database and appends to it. `to_sql` can be thought of as a conveni...
[ "Convert", "an", "SFrame", "to", "a", "single", "table", "in", "a", "SQL", "database", "." ]
python
train
not-na/peng3d
peng3d/gui/__init__.py
https://github.com/not-na/peng3d/blob/1151be665b26cc8a479f6307086ba919e4d32d85/peng3d/gui/__init__.py#L68-L84
def changeSubMenu(self,submenu): """ Changes the submenu that is displayed. :raises ValueError: if the name was not previously registered """ if submenu not in self.submenus: raise ValueError("Submenu %s does not exist!"%submenu) elif submenu == self....
[ "def", "changeSubMenu", "(", "self", ",", "submenu", ")", ":", "if", "submenu", "not", "in", "self", ".", "submenus", ":", "raise", "ValueError", "(", "\"Submenu %s does not exist!\"", "%", "submenu", ")", "elif", "submenu", "==", "self", ".", "activeSubMenu",...
Changes the submenu that is displayed. :raises ValueError: if the name was not previously registered
[ "Changes", "the", "submenu", "that", "is", "displayed", ".", ":", "raises", "ValueError", ":", "if", "the", "name", "was", "not", "previously", "registered" ]
python
test
elastic/elasticsearch-py
elasticsearch/transport.py
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/transport.py#L258-L350
def perform_request(self, method, url, headers=None, params=None, body=None): """ Perform the actual request. Retrieve a connection from the connection pool, pass all the information to it's perform_request method and return the data. If an exception was raised, mark the connect...
[ "def", "perform_request", "(", "self", ",", "method", ",", "url", ",", "headers", "=", "None", ",", "params", "=", "None", ",", "body", "=", "None", ")", ":", "if", "body", "is", "not", "None", ":", "body", "=", "self", ".", "serializer", ".", "dum...
Perform the actual request. Retrieve a connection from the connection pool, pass all the information to it's perform_request method and return the data. If an exception was raised, mark the connection as failed and retry (up to `max_retries` times). If the operation was succesf...
[ "Perform", "the", "actual", "request", ".", "Retrieve", "a", "connection", "from", "the", "connection", "pool", "pass", "all", "the", "information", "to", "it", "s", "perform_request", "method", "and", "return", "the", "data", "." ]
python
train
threeML/astromodels
astromodels/core/parameter.py
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L325-L346
def in_unit_of(self, unit, as_quantity=False): """ Return the current value transformed to the new units :param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit instance, like "1 / (erg cm**2 s)" :param as_quantity: if True, the me...
[ "def", "in_unit_of", "(", "self", ",", "unit", ",", "as_quantity", "=", "False", ")", ":", "new_unit", "=", "u", ".", "Unit", "(", "unit", ")", "new_quantity", "=", "self", ".", "as_quantity", ".", "to", "(", "new_unit", ")", "if", "as_quantity", ":", ...
Return the current value transformed to the new units :param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit instance, like "1 / (erg cm**2 s)" :param as_quantity: if True, the method return an astropy.Quantity, if False just a floating point num...
[ "Return", "the", "current", "value", "transformed", "to", "the", "new", "units" ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/psutil/_common.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_common.py#L106-L119
def isfile_strict(path): """Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: st = os.stat(path) except OSError: err = sys.exc_info()[1] if err.errno in (errno.EPERM, er...
[ "def", "isfile_strict", "(", "path", ")", ":", "try", ":", "st", "=", "os", ".", "stat", "(", "path", ")", "except", "OSError", ":", "err", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "err", ".", "errno", "in", "(", "errno", "."...
Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html
[ "Same", "as", "os", ".", "path", ".", "isfile", "()", "but", "does", "not", "swallow", "EACCES", "/", "EPERM", "exceptions", "see", ":", "http", ":", "//", "mail", ".", "python", ".", "org", "/", "pipermail", "/", "python", "-", "dev", "/", "2012", ...
python
test
pjmark/NIMPA
niftypet/nimpa/prc/imio.py
https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L130-L187
def array2nii(im, A, fnii, descrip='', trnsp=(), flip=(), storage_as=[]): '''Store the numpy array 'im' to a NIfTI file 'fnii'. ---- Arguments: 'im': image to be stored in NIfTI 'A': affine transformation 'fnii': output NIfTI file name. 'descrip': the descri...
[ "def", "array2nii", "(", "im", ",", "A", ",", "fnii", ",", "descrip", "=", "''", ",", "trnsp", "=", "(", ")", ",", "flip", "=", "(", ")", ",", "storage_as", "=", "[", "]", ")", ":", "if", "not", "len", "(", "trnsp", ")", "in", "[", "0", ","...
Store the numpy array 'im' to a NIfTI file 'fnii'. ---- Arguments: 'im': image to be stored in NIfTI 'A': affine transformation 'fnii': output NIfTI file name. 'descrip': the description given to the file 'trsnp': transpose/permute the dimensions. ...
[ "Store", "the", "numpy", "array", "im", "to", "a", "NIfTI", "file", "fnii", ".", "----", "Arguments", ":", "im", ":", "image", "to", "be", "stored", "in", "NIfTI", "A", ":", "affine", "transformation", "fnii", ":", "output", "NIfTI", "file", "name", "....
python
train
mschwager/cohesion
lib/cohesion/parser.py
https://github.com/mschwager/cohesion/blob/b242ad59770940f3a0904931f27755ede009f491/lib/cohesion/parser.py#L32-L36
def get_attribute_name_id(attr): """ Return the attribute name identifier """ return attr.value.id if isinstance(attr.value, ast.Name) else None
[ "def", "get_attribute_name_id", "(", "attr", ")", ":", "return", "attr", ".", "value", ".", "id", "if", "isinstance", "(", "attr", ".", "value", ",", "ast", ".", "Name", ")", "else", "None" ]
Return the attribute name identifier
[ "Return", "the", "attribute", "name", "identifier" ]
python
train
bwesterb/mirte
src/mirteFile.py
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L95-L109
def load_mirteFile(path, m, logger=None): """ Loads the mirte-file at <path> into the manager <m>. """ l = logging.getLogger('load_mirteFile') if logger is None else logger had = set() for name, path, d in walk_mirteFiles(path, logger): if os.path.realpath(path) in m.loaded_mirteFiles: ...
[ "def", "load_mirteFile", "(", "path", ",", "m", ",", "logger", "=", "None", ")", ":", "l", "=", "logging", ".", "getLogger", "(", "'load_mirteFile'", ")", "if", "logger", "is", "None", "else", "logger", "had", "=", "set", "(", ")", "for", "name", ","...
Loads the mirte-file at <path> into the manager <m>.
[ "Loads", "the", "mirte", "-", "file", "at", "<path", ">", "into", "the", "manager", "<m", ">", "." ]
python
train
OCR-D/core
ocrd_validators/ocrd_validators/page_validator.py
https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/page_validator.py#L100-L114
def get_text(node, strategy): """ Get the most confident text results, either those with @index = 1 or the first text results or empty string. """ textEquivs = node.get_TextEquiv() if not textEquivs: log.debug("No text results on %s %s", node, node.id) return '' # elif strategy ...
[ "def", "get_text", "(", "node", ",", "strategy", ")", ":", "textEquivs", "=", "node", ".", "get_TextEquiv", "(", ")", "if", "not", "textEquivs", ":", "log", ".", "debug", "(", "\"No text results on %s %s\"", ",", "node", ",", "node", ".", "id", ")", "ret...
Get the most confident text results, either those with @index = 1 or the first text results or empty string.
[ "Get", "the", "most", "confident", "text", "results", "either", "those", "with" ]
python
train
HttpRunner/HttpRunner
httprunner/logger.py
https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/logger.py#L21-L46
def setup_logger(log_level, log_file=None): """setup root logger with ColoredFormatter.""" level = getattr(logging, log_level.upper(), None) if not level: color_print("Invalid log level: %s" % log_level, "RED") sys.exit(1) # hide traceback when log level is INFO/WARNING/ERROR/CRITICAL ...
[ "def", "setup_logger", "(", "log_level", ",", "log_file", "=", "None", ")", ":", "level", "=", "getattr", "(", "logging", ",", "log_level", ".", "upper", "(", ")", ",", "None", ")", "if", "not", "level", ":", "color_print", "(", "\"Invalid log level: %s\""...
setup root logger with ColoredFormatter.
[ "setup", "root", "logger", "with", "ColoredFormatter", "." ]
python
train
saltstack/salt
salt/modules/debian_ip.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1453-L1463
def _read_temp(data): ''' Return what would be written to disk ''' tout = StringIO() tout.write(data) tout.seek(0) output = tout.readlines() tout.close() return output
[ "def", "_read_temp", "(", "data", ")", ":", "tout", "=", "StringIO", "(", ")", "tout", ".", "write", "(", "data", ")", "tout", ".", "seek", "(", "0", ")", "output", "=", "tout", ".", "readlines", "(", ")", "tout", ".", "close", "(", ")", "return"...
Return what would be written to disk
[ "Return", "what", "would", "be", "written", "to", "disk" ]
python
train
weld-project/weld
python/numpy/weldnumpy/weldnumpy.py
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/numpy/weldnumpy/weldnumpy.py#L44-L53
def get_supported_binary_ops(): ''' Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol. ''' binary_ops = {} binary_ops[np.add.__name__] = '+' binary_ops[np.subtract.__name__] = '-' binary_ops[np.multiply.__name__] = '*' binary_ops[np.divide.__name_...
[ "def", "get_supported_binary_ops", "(", ")", ":", "binary_ops", "=", "{", "}", "binary_ops", "[", "np", ".", "add", ".", "__name__", "]", "=", "'+'", "binary_ops", "[", "np", ".", "subtract", ".", "__name__", "]", "=", "'-'", "binary_ops", "[", "np", "...
Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol.
[ "Returns", "a", "dictionary", "of", "the", "Weld", "supported", "binary", "ops", "with", "values", "being", "their", "Weld", "symbol", "." ]
python
train
ecederstrand/exchangelib
exchangelib/folders.py
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/folders.py#L1594-L1602
def folder_cls_from_folder_name(cls, folder_name, locale): """Returns the folder class that matches a localized folder name. locale is a string, e.g. 'da_DK' """ for folder_cls in cls.WELLKNOWN_FOLDERS + NON_DELETEABLE_FOLDERS: if folder_name.lower() in folder_cls.localized_...
[ "def", "folder_cls_from_folder_name", "(", "cls", ",", "folder_name", ",", "locale", ")", ":", "for", "folder_cls", "in", "cls", ".", "WELLKNOWN_FOLDERS", "+", "NON_DELETEABLE_FOLDERS", ":", "if", "folder_name", ".", "lower", "(", ")", "in", "folder_cls", ".", ...
Returns the folder class that matches a localized folder name. locale is a string, e.g. 'da_DK'
[ "Returns", "the", "folder", "class", "that", "matches", "a", "localized", "folder", "name", "." ]
python
train
noxdafox/pebble
pebble/common.py
https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/common.py#L177-L183
def send_result(pipe, data): """Send result handling pickling and communication errors.""" try: pipe.send(data) except (pickle.PicklingError, TypeError) as error: error.traceback = format_exc() pipe.send(RemoteException(error, error.traceback))
[ "def", "send_result", "(", "pipe", ",", "data", ")", ":", "try", ":", "pipe", ".", "send", "(", "data", ")", "except", "(", "pickle", ".", "PicklingError", ",", "TypeError", ")", "as", "error", ":", "error", ".", "traceback", "=", "format_exc", "(", ...
Send result handling pickling and communication errors.
[ "Send", "result", "handling", "pickling", "and", "communication", "errors", "." ]
python
train
codenerix/django-codenerix
codenerix/templatetags/codenerix_common.py
https://github.com/codenerix/django-codenerix/blob/1f5527b352141caaee902b37b2648791a06bd57d/codenerix/templatetags/codenerix_common.py#L241-L262
def objectatrib(instance, atrib): ''' this filter is going to be useful to execute an object method or get an object attribute dynamically. this method is going to take into account the atrib param can contains underscores ''' atrib = atrib.replace("__", ".") atribs = [] atribs = atrib.s...
[ "def", "objectatrib", "(", "instance", ",", "atrib", ")", ":", "atrib", "=", "atrib", ".", "replace", "(", "\"__\"", ",", "\".\"", ")", "atribs", "=", "[", "]", "atribs", "=", "atrib", ".", "split", "(", "\".\"", ")", "obj", "=", "instance", "for", ...
this filter is going to be useful to execute an object method or get an object attribute dynamically. this method is going to take into account the atrib param can contains underscores
[ "this", "filter", "is", "going", "to", "be", "useful", "to", "execute", "an", "object", "method", "or", "get", "an", "object", "attribute", "dynamically", ".", "this", "method", "is", "going", "to", "take", "into", "account", "the", "atrib", "param", "can"...
python
train
projectshift/shift-schema
shiftschema/validators/email.py
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/validators/email.py#L26-L43
def validate(self, value, model=None, context=None): """ Validate Perform value validation and return result :param value: value to check :param model: parent model being validated :param context: object or None, validation context :re...
[ "def", "validate", "(", "self", ",", "value", ",", "model", "=", "None", ",", "context", "=", "None", ")", ":", "regex", "=", "self", ".", "regex", "(", ")", "match", "=", "regex", ".", "match", "(", "value", ")", "if", "not", "match", ":", "retu...
Validate Perform value validation and return result :param value: value to check :param model: parent model being validated :param context: object or None, validation context :return: shiftschema.results.SimpleResult
[ "Validate", "Perform", "value", "validation", "and", "return", "result" ]
python
train
cggh/scikit-allel
allel/model/ndarray.py
https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/model/ndarray.py#L2510-L2520
def distinct_counts(self): """Return counts for each distinct haplotype.""" # hash the haplotypes k = [hash(self.values[:, i].tobytes()) for i in range(self.shape[1])] # count and sort # noinspection PyArgumentList counts = sorted(collections.Counter(k).values(), revers...
[ "def", "distinct_counts", "(", "self", ")", ":", "# hash the haplotypes", "k", "=", "[", "hash", "(", "self", ".", "values", "[", ":", ",", "i", "]", ".", "tobytes", "(", ")", ")", "for", "i", "in", "range", "(", "self", ".", "shape", "[", "1", "...
Return counts for each distinct haplotype.
[ "Return", "counts", "for", "each", "distinct", "haplotype", "." ]
python
train
gwpy/gwpy
gwpy/timeseries/timeseries.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/timeseries/timeseries.py#L968-L1003
def zpk(self, zeros, poles, gain, analog=True, **kwargs): """Filter this `TimeSeries` by applying a zero-pole-gain filter Parameters ---------- zeros : `array-like` list of zero frequencies (in Hertz) poles : `array-like` list of pole frequencies (in Her...
[ "def", "zpk", "(", "self", ",", "zeros", ",", "poles", ",", "gain", ",", "analog", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "filter", "(", "zeros", ",", "poles", ",", "gain", ",", "analog", "=", "analog", ",", "*", ...
Filter this `TimeSeries` by applying a zero-pole-gain filter Parameters ---------- zeros : `array-like` list of zero frequencies (in Hertz) poles : `array-like` list of pole frequencies (in Hertz) gain : `float` DC gain of filter an...
[ "Filter", "this", "TimeSeries", "by", "applying", "a", "zero", "-", "pole", "-", "gain", "filter" ]
python
train
portfors-lab/sparkle
sparkle/gui/stim/stim_detail.py
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/stim_detail.py#L24-L36
def setDoc(self, doc): """Presents the documentation :param doc: documentation for StimulusModel. i.e. returned from :meth:`componentDoc<sparkle.stim.stimulus_model.StimulusModel.componentDoc>` or :meth:`templateDoc<sparkle.stim.stimulus_model.StimulusModel.templateDoc>` """ ...
[ "def", "setDoc", "(", "self", ",", "doc", ")", ":", "self", ".", "ui", ".", "overAtten", ".", "setNum", "(", "doc", "[", "'overloaded_attenuation'", "]", ")", "# also set composite stim type", "# self.ui.traceType.setText(doc['testtype'])", "self", ".", "ui", ".",...
Presents the documentation :param doc: documentation for StimulusModel. i.e. returned from :meth:`componentDoc<sparkle.stim.stimulus_model.StimulusModel.componentDoc>` or :meth:`templateDoc<sparkle.stim.stimulus_model.StimulusModel.templateDoc>`
[ "Presents", "the", "documentation" ]
python
train
nvdv/vprof
vprof/flame_graph.py
https://github.com/nvdv/vprof/blob/4c3ff78f8920ab10cb9c00b14143452aa09ff6bb/vprof/flame_graph.py#L75-L79
def _fill_sample_count(self, node): """Counts and fills sample counts inside call tree.""" node['sampleCount'] += sum( self._fill_sample_count(child) for child in node['children']) return node['sampleCount']
[ "def", "_fill_sample_count", "(", "self", ",", "node", ")", ":", "node", "[", "'sampleCount'", "]", "+=", "sum", "(", "self", ".", "_fill_sample_count", "(", "child", ")", "for", "child", "in", "node", "[", "'children'", "]", ")", "return", "node", "[", ...
Counts and fills sample counts inside call tree.
[ "Counts", "and", "fills", "sample", "counts", "inside", "call", "tree", "." ]
python
test
glottobank/python-newick
src/newick.py
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L360-L371
def loads(s, strip_comments=False, **kw): """ Load a list of trees from a Newick formatted string. :param s: Newick formatted string. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.create`. ...
[ "def", "loads", "(", "s", ",", "strip_comments", "=", "False", ",", "*", "*", "kw", ")", ":", "kw", "[", "'strip_comments'", "]", "=", "strip_comments", "return", "[", "parse_node", "(", "ss", ".", "strip", "(", ")", ",", "*", "*", "kw", ")", "for"...
Load a list of trees from a Newick formatted string. :param s: Newick formatted string. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.create`. :return: List of Node objects.
[ "Load", "a", "list", "of", "trees", "from", "a", "Newick", "formatted", "string", "." ]
python
test
swistakm/graceful
src/graceful/authentication.py
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L288-L314
def process_resource(self, req, resp, resource, uri_kwargs=None): """Process resource after routing to it. This is basic falcon middleware handler. Args: req (falcon.Request): request object resp (falcon.Response): response object resource (object): resource...
[ "def", "process_resource", "(", "self", ",", "req", ",", "resp", ",", "resource", ",", "uri_kwargs", "=", "None", ")", ":", "if", "'user'", "in", "req", ".", "context", ":", "return", "identifier", "=", "self", ".", "identify", "(", "req", ",", "resp",...
Process resource after routing to it. This is basic falcon middleware handler. Args: req (falcon.Request): request object resp (falcon.Response): response object resource (object): resource object matched by falcon router uri_kwargs (dict): additional ke...
[ "Process", "resource", "after", "routing", "to", "it", "." ]
python
train
qiniu/python-sdk
qiniu/services/compute/qcos_api.py
https://github.com/qiniu/python-sdk/blob/a69fbef4e3e6ea1ebe09f4610a5b18bb2c17de59/qiniu/services/compute/qcos_api.py#L128-L142
def start_stack(self, stack): """启动服务组 启动服务组中的所有停止状态的服务。 Args: - stack: 服务所属的服务组名称 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息 ...
[ "def", "start_stack", "(", "self", ",", "stack", ")", ":", "url", "=", "'{0}/v3/stacks/{1}/start'", ".", "format", "(", "self", ".", "host", ",", "stack", ")", "return", "self", ".", "__post", "(", "url", ")" ]
启动服务组 启动服务组中的所有停止状态的服务。 Args: - stack: 服务所属的服务组名称 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
[ "启动服务组" ]
python
train
mrstephenneal/pdfconduit
pdf/gui/config/images.py
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/gui/config/images.py#L25-L29
def remove(image): """Remove an image to the GUI img library.""" path = os.path.join(IMG_DIR, image) if os.path.isfile(path): os.remove(path)
[ "def", "remove", "(", "image", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "IMG_DIR", ",", "image", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "os", ".", "remove", "(", "path", ")" ]
Remove an image to the GUI img library.
[ "Remove", "an", "image", "to", "the", "GUI", "img", "library", "." ]
python
train
sveetch/boussole
boussole/watcher.py
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/watcher.py#L236-L252
def on_deleted(self, event): """ Called when a file or directory is deleted. Todo: May be bugged with inspector and sass compiler since the does not exists anymore. Args: event: Watchdog event, ``watchdog.events.DirDeletedEvent`` or `...
[ "def", "on_deleted", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "_event_error", ":", "self", ".", "logger", ".", "info", "(", "u\"Change detected from deletion of: %s\"", ",", "event", ".", "src_path", ")", "# Never try to compile the deleted s...
Called when a file or directory is deleted. Todo: May be bugged with inspector and sass compiler since the does not exists anymore. Args: event: Watchdog event, ``watchdog.events.DirDeletedEvent`` or ``watchdog.events.FileDeletedEvent``.
[ "Called", "when", "a", "file", "or", "directory", "is", "deleted", "." ]
python
train
silver-castle/mach9
mach9/static.py
https://github.com/silver-castle/mach9/blob/7a623aab3c70d89d36ade6901b6307e115400c5e/mach9/static.py#L19-L104
def register(app, uri, file_or_directory, pattern, use_modified_since, use_content_range): # TODO: Though mach9 is not a file server, I feel like we should at least # make a good effort here. Modified-since is nice, but we could # also look into etags, expires, and caching """ ...
[ "def", "register", "(", "app", ",", "uri", ",", "file_or_directory", ",", "pattern", ",", "use_modified_since", ",", "use_content_range", ")", ":", "# TODO: Though mach9 is not a file server, I feel like we should at least", "# make a good effort here. Modified-since is nice...
Register a static directory handler with Mach9 by adding a route to the router and registering a handler. :param app: Mach9 :param file_or_directory: File or directory path to serve from :param uri: URL to serve from :param pattern: regular expression used to match files in the URL :param use_m...
[ "Register", "a", "static", "directory", "handler", "with", "Mach9", "by", "adding", "a", "route", "to", "the", "router", "and", "registering", "a", "handler", "." ]
python
train
radical-cybertools/radical.entk
setup.py
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/setup.py#L155-L174
def visit((prefix, strip, found), dirname, names): """ Visit directory, create distutil tuple Add distutil tuple for each directory using this format: (destination, [dirname/file1, dirname/file2, ...]) distutil will copy later file1, file2, ... info destination. """ files = [] # Iterate ...
[ "def", "visit", "(", "(", "prefix", ",", "strip", ",", "found", ")", ",", "dirname", ",", "names", ")", ":", "files", "=", "[", "]", "# Iterate over a copy of names, modify names", "for", "name", "in", "names", "[", ":", "]", ":", "path", "=", "os", "....
Visit directory, create distutil tuple Add distutil tuple for each directory using this format: (destination, [dirname/file1, dirname/file2, ...]) distutil will copy later file1, file2, ... info destination.
[ "Visit", "directory", "create", "distutil", "tuple", "Add", "distutil", "tuple", "for", "each", "directory", "using", "this", "format", ":", "(", "destination", "[", "dirname", "/", "file1", "dirname", "/", "file2", "...", "]", ")", "distutil", "will", "copy...
python
train
scott-griffiths/bitstring
bitstring.py
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1784-L1802
def _readsie(self, pos): """Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ codenum, pos = self._readui...
[ "def", "_readsie", "(", "self", ",", "pos", ")", ":", "codenum", ",", "pos", "=", "self", ".", "_readuie", "(", "pos", ")", "if", "not", "codenum", ":", "return", "0", ",", "pos", "try", ":", "if", "self", "[", "pos", "]", ":", "return", "-", "...
Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code.
[ "Return", "interpretation", "of", "next", "bits", "as", "a", "signed", "interleaved", "exponential", "-", "Golomb", "code", "." ]
python
train
blazelibs/blazeutils
blazeutils/rst.py
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/rst.py#L182-L190
def rst2html(rst_src, **kwargs): """ Convert a reStructuredText string into a unicode HTML fragment. For `kwargs`, see `default_rst_opts` and http://docutils.sourceforge.net/docs/user/config.html """ pub = rst2pub(rst_src, settings_overrides=kwargs, writer_name='html') return pu...
[ "def", "rst2html", "(", "rst_src", ",", "*", "*", "kwargs", ")", ":", "pub", "=", "rst2pub", "(", "rst_src", ",", "settings_overrides", "=", "kwargs", ",", "writer_name", "=", "'html'", ")", "return", "pub", ".", "writer", ".", "parts", "[", "'body'", ...
Convert a reStructuredText string into a unicode HTML fragment. For `kwargs`, see `default_rst_opts` and http://docutils.sourceforge.net/docs/user/config.html
[ "Convert", "a", "reStructuredText", "string", "into", "a", "unicode", "HTML", "fragment", "." ]
python
train
mlperf/training
object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/coco/coco_eval.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/coco/coco_eval.py#L189-L302
def evaluate_box_proposals( predictions, dataset, thresholds=None, area="all", limit=None ): """Evaluate detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results. """ # Record ma...
[ "def", "evaluate_box_proposals", "(", "predictions", ",", "dataset", ",", "thresholds", "=", "None", ",", "area", "=", "\"all\"", ",", "limit", "=", "None", ")", ":", "# Record max overlap value for each gt box", "# Return vector of overlap values", "areas", "=", "{",...
Evaluate detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results.
[ "Evaluate", "detection", "proposal", "recall", "metrics", ".", "This", "function", "is", "a", "much", "faster", "alternative", "to", "the", "official", "COCO", "API", "recall", "evaluation", "code", ".", "However", "it", "produces", "slightly", "different", "res...
python
train
totalgood/nlpia
src/nlpia/loaders.py
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L820-L858
def download_unzip(names=None, normalize_filenames=False, verbose=True): r""" Download CSV or HTML tables listed in `names`, unzip and to DATA_PATH/`names`.csv .txt etc TODO: move to web or data_utils or futils Also normalizes file name extensions (.bin.gz -> .w2v.bin.gz). Uses table in data_info.csv (...
[ "def", "download_unzip", "(", "names", "=", "None", ",", "normalize_filenames", "=", "False", ",", "verbose", "=", "True", ")", ":", "names", "=", "[", "names", "]", "if", "isinstance", "(", "names", ",", "(", "str", ",", "basestring", ")", ")", "else"...
r""" Download CSV or HTML tables listed in `names`, unzip and to DATA_PATH/`names`.csv .txt etc TODO: move to web or data_utils or futils Also normalizes file name extensions (.bin.gz -> .w2v.bin.gz). Uses table in data_info.csv (internal DATA_INFO) to determine URL or file path from dataset name. Also...
[ "r", "Download", "CSV", "or", "HTML", "tables", "listed", "in", "names", "unzip", "and", "to", "DATA_PATH", "/", "names", ".", "csv", ".", "txt", "etc" ]
python
train
cloudendpoints/endpoints-python
endpoints/users_id_token.py
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L750-L794
def get_verified_jwt( providers, audiences, check_authorization_header=True, check_query_arg=True, request=None, cache=memcache): """ This function will extract, verify, and parse a JWT token from the Authorization header or access_token query argument. The JWT is assumed to contain an issuer and a...
[ "def", "get_verified_jwt", "(", "providers", ",", "audiences", ",", "check_authorization_header", "=", "True", ",", "check_query_arg", "=", "True", ",", "request", "=", "None", ",", "cache", "=", "memcache", ")", ":", "if", "not", "(", "check_authorization_heade...
This function will extract, verify, and parse a JWT token from the Authorization header or access_token query argument. The JWT is assumed to contain an issuer and audience claim, as well as issued-at and expiration timestamps. The signature will be cryptographically verified, the claims and timestamps will be...
[ "This", "function", "will", "extract", "verify", "and", "parse", "a", "JWT", "token", "from", "the", "Authorization", "header", "or", "access_token", "query", "argument", "." ]
python
train
dwavesystems/dwave_networkx
dwave_networkx/drawing/chimera_layout.py
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/chimera_layout.py#L122-L203
def chimera_node_placer_2d(m, n, t, scale=1., center=None, dim=2): """Generates a function that converts Chimera indices to x, y coordinates for a plot. Parameters ---------- m : int Number of rows in the Chimera lattice. n : int Number of columns in the Chimera lattice. t...
[ "def", "chimera_node_placer_2d", "(", "m", ",", "n", ",", "t", ",", "scale", "=", "1.", ",", "center", "=", "None", ",", "dim", "=", "2", ")", ":", "import", "numpy", "as", "np", "tile_center", "=", "t", "//", "2", "tile_length", "=", "t", "+", "...
Generates a function that converts Chimera indices to x, y coordinates for a plot. Parameters ---------- m : int Number of rows in the Chimera lattice. n : int Number of columns in the Chimera lattice. t : int Size of the shore within each Chimera tile. scale : fl...
[ "Generates", "a", "function", "that", "converts", "Chimera", "indices", "to", "x", "y", "coordinates", "for", "a", "plot", "." ]
python
train
oasis-open/cti-stix-validator
stix2validator/validator.py
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L309-L339
def get_json_files(files, recursive=False): """Return a list of files to validate from `files`. If a member of `files` is a directory, its children with a ``.json`` extension will be added to the return value. Args: files: A list of file paths and/or directory paths. recursive: If ``tru...
[ "def", "get_json_files", "(", "files", ",", "recursive", "=", "False", ")", ":", "json_files", "=", "[", "]", "if", "not", "files", ":", "return", "json_files", "for", "fn", "in", "files", ":", "if", "os", ".", "path", ".", "isdir", "(", "fn", ")", ...
Return a list of files to validate from `files`. If a member of `files` is a directory, its children with a ``.json`` extension will be added to the return value. Args: files: A list of file paths and/or directory paths. recursive: If ``true``, this will descend into any subdirectories ...
[ "Return", "a", "list", "of", "files", "to", "validate", "from", "files", ".", "If", "a", "member", "of", "files", "is", "a", "directory", "its", "children", "with", "a", ".", "json", "extension", "will", "be", "added", "to", "the", "return", "value", "...
python
train
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L178-L265
def make(self): """ reads through the definitions and generates an python class for each definition """ log.setLevel(self.log_level) created = [] self.set_class_dict() start = datetime.datetime.now() log.info(" # of classes to create: %s" % len(self.class_dict)) ...
[ "def", "make", "(", "self", ")", ":", "log", ".", "setLevel", "(", "self", ".", "log_level", ")", "created", "=", "[", "]", "self", ".", "set_class_dict", "(", ")", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "log", ".", "info"...
reads through the definitions and generates an python class for each definition
[ "reads", "through", "the", "definitions", "and", "generates", "an", "python", "class", "for", "each", "definition" ]
python
train
dnanexus/dx-toolkit
src/python/dxpy/bindings/dxanalysis.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/dxanalysis.py#L148-L165
def get_output_ref(self, field, index=None, metadata=None): ''' :param field: Output field name of this analysis :type field: string :param index: If the referenced field is an array, optionally specify an index (starting from 0) to indicate a particular member of the array :type...
[ "def", "get_output_ref", "(", "self", ",", "field", ",", "index", "=", "None", ",", "metadata", "=", "None", ")", ":", "link", "=", "{", "\"$dnanexus_link\"", ":", "{", "\"analysis\"", ":", "self", ".", "_dxid", ",", "\"field\"", ":", "field", "}", "}"...
:param field: Output field name of this analysis :type field: string :param index: If the referenced field is an array, optionally specify an index (starting from 0) to indicate a particular member of the array :type index: int :param metadata: If the referenced field is of a data object...
[ ":", "param", "field", ":", "Output", "field", "name", "of", "this", "analysis", ":", "type", "field", ":", "string", ":", "param", "index", ":", "If", "the", "referenced", "field", "is", "an", "array", "optionally", "specify", "an", "index", "(", "start...
python
train
JarryShaw/PyPCAPKit
src/protocols/internet/hip.py
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/hip.py#L1523-L1555
def _read_para_echo_response_signed(self, code, cbit, clen, *, desc, length, version): """Read HIP ECHO_RESPONSE_SIGNED parameter. Structure of HIP ECHO_RESPONSE_SIGNED parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 ...
[ "def", "_read_para_echo_response_signed", "(", "self", ",", "code", ",", "cbit", ",", "clen", ",", "*", ",", "desc", ",", "length", ",", "version", ")", ":", "_data", "=", "self", ".", "_read_fileng", "(", "clen", ")", "echo_response_signed", "=", "dict", ...
Read HIP ECHO_RESPONSE_SIGNED parameter. Structure of HIP ECHO_RESPONSE_SIGNED parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
[ "Read", "HIP", "ECHO_RESPONSE_SIGNED", "parameter", "." ]
python
train
diux-dev/ncluster
ncluster/aws_util.py
https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L369-L398
def ssh_to_task(task) -> paramiko.SSHClient: """Create ssh connection to task's machine returns Paramiko SSH client connected to host. """ username = task.ssh_username hostname = task.public_ip ssh_key_fn = get_keypair_fn() print(f"ssh -i {ssh_key_fn} {username}@{hostname}") pkey = paramiko.RSAKey.fr...
[ "def", "ssh_to_task", "(", "task", ")", "->", "paramiko", ".", "SSHClient", ":", "username", "=", "task", ".", "ssh_username", "hostname", "=", "task", ".", "public_ip", "ssh_key_fn", "=", "get_keypair_fn", "(", ")", "print", "(", "f\"ssh -i {ssh_key_fn} {userna...
Create ssh connection to task's machine returns Paramiko SSH client connected to host.
[ "Create", "ssh", "connection", "to", "task", "s", "machine" ]
python
train
LogicalDash/LiSE
ELiDE/ELiDE/board/arrow.py
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/arrow.py#L366-L392
def add_widget(self, wid, index=0, canvas=None): """Put the :class:`Pawn` at a point along my length proportionate to how close it is to finishing its travel through me. Only :class:`Pawn` should ever be added as a child of :class:`Arrow`. """ super().add_widget(wid, index, can...
[ "def", "add_widget", "(", "self", ",", "wid", ",", "index", "=", "0", ",", "canvas", "=", "None", ")", ":", "super", "(", ")", ".", "add_widget", "(", "wid", ",", "index", ",", "canvas", ")", "if", "not", "hasattr", "(", "wid", ",", "'group'", ")...
Put the :class:`Pawn` at a point along my length proportionate to how close it is to finishing its travel through me. Only :class:`Pawn` should ever be added as a child of :class:`Arrow`.
[ "Put", "the", ":", "class", ":", "Pawn", "at", "a", "point", "along", "my", "length", "proportionate", "to", "how", "close", "it", "is", "to", "finishing", "its", "travel", "through", "me", "." ]
python
train
honzajavorek/redis-collections
redis_collections/sortedsets.py
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sortedsets.py#L538-L587
def update(self, other): """ Update the collection with items from *other*. Accepts other :class:`GeoDB` instances, dictionaries mapping places to ``{'latitude': latitude, 'longitude': longitude}`` dicts, or sequences of ``(place, latitude, longitude)`` tuples. """ ...
[ "def", "update", "(", "self", ",", "other", ")", ":", "# other is another Sorted Set", "def", "update_sortedset_trans", "(", "pipe", ")", ":", "items", "=", "other", ".", "_data", "(", "pipe", "=", "pipe", ")", "if", "use_redis", "else", "other", ".", "_da...
Update the collection with items from *other*. Accepts other :class:`GeoDB` instances, dictionaries mapping places to ``{'latitude': latitude, 'longitude': longitude}`` dicts, or sequences of ``(place, latitude, longitude)`` tuples.
[ "Update", "the", "collection", "with", "items", "from", "*", "other", "*", ".", "Accepts", "other", ":", "class", ":", "GeoDB", "instances", "dictionaries", "mapping", "places", "to", "{", "latitude", ":", "latitude", "longitude", ":", "longitude", "}", "dic...
python
train
trendmicro/flask-ini
flask_ini.py
https://github.com/trendmicro/flask-ini/blob/a1e4baa598c9a01021a1333d9c15e4d99c8334dd/flask_ini.py#L12-L16
def read(self, *args, **kwargs): '''Overridden read() method to call parse_flask_section() at the end''' ret = configparser.SafeConfigParser.read(self, *args, **kwargs) self.parse_flask_section() return ret
[ "def", "read", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "configparser", ".", "SafeConfigParser", ".", "read", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "parse_flask_section", "(", ...
Overridden read() method to call parse_flask_section() at the end
[ "Overridden", "read", "()", "method", "to", "call", "parse_flask_section", "()", "at", "the", "end" ]
python
train
chrisrink10/basilisp
src/basilisp/lang/runtime.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/runtime.py#L881-L893
def update(m, k, f, *args): """Updates the value for key k in associative data structure m with the return value from calling f(old_v, *args). If m is None, use an empty map. If k is not in m, old_v will be None.""" if m is None: return lmap.Map.empty().assoc(k, f(None, *args)) if isinstance...
[ "def", "update", "(", "m", ",", "k", ",", "f", ",", "*", "args", ")", ":", "if", "m", "is", "None", ":", "return", "lmap", ".", "Map", ".", "empty", "(", ")", ".", "assoc", "(", "k", ",", "f", "(", "None", ",", "*", "args", ")", ")", "if"...
Updates the value for key k in associative data structure m with the return value from calling f(old_v, *args). If m is None, use an empty map. If k is not in m, old_v will be None.
[ "Updates", "the", "value", "for", "key", "k", "in", "associative", "data", "structure", "m", "with", "the", "return", "value", "from", "calling", "f", "(", "old_v", "*", "args", ")", ".", "If", "m", "is", "None", "use", "an", "empty", "map", ".", "If...
python
test
dask/dask-ml
dask_ml/model_selection/_incremental.py
https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_incremental.py#L569-L578
def fit(self, X, y, **fit_params): """Find the best parameters for a particular model. Parameters ---------- X, y : array-like **fit_params Additional partial fit keyword arguments for the estimator. """ return default_client().sync(self._fit, X, y, *...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "*", "*", "fit_params", ")", ":", "return", "default_client", "(", ")", ".", "sync", "(", "self", ".", "_fit", ",", "X", ",", "y", ",", "*", "*", "fit_params", ")" ]
Find the best parameters for a particular model. Parameters ---------- X, y : array-like **fit_params Additional partial fit keyword arguments for the estimator.
[ "Find", "the", "best", "parameters", "for", "a", "particular", "model", "." ]
python
train
rwl/pylon
pylon/opf.py
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/opf.py#L294-L309
def _power_mismatch_dc(self, buses, generators, B, Pbusinj, base_mva): """ Returns the power mismatch constraint (B*Va + Pg = Pd). """ nb, ng = len(buses), len(generators) # Negative bus-generator incidence matrix. gen_bus = array([g.bus._i for g in generators]) neg_Cg = ...
[ "def", "_power_mismatch_dc", "(", "self", ",", "buses", ",", "generators", ",", "B", ",", "Pbusinj", ",", "base_mva", ")", ":", "nb", ",", "ng", "=", "len", "(", "buses", ")", ",", "len", "(", "generators", ")", "# Negative bus-generator incidence matrix.", ...
Returns the power mismatch constraint (B*Va + Pg = Pd).
[ "Returns", "the", "power", "mismatch", "constraint", "(", "B", "*", "Va", "+", "Pg", "=", "Pd", ")", "." ]
python
train
Yelp/kafka-utils
kafka_utils/util/protocol.py
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/protocol.py#L27-L46
def encode_offset_commit_request_kafka(cls, group, payloads): """ Encode an OffsetCommitRequest struct Arguments: group: string, the consumer group you are committing offsets for payloads: list of OffsetCommitRequestPayload """ return kafka.protocol.commit...
[ "def", "encode_offset_commit_request_kafka", "(", "cls", ",", "group", ",", "payloads", ")", ":", "return", "kafka", ".", "protocol", ".", "commit", ".", "OffsetCommitRequest", "[", "2", "]", "(", "consumer_group", "=", "group", ",", "consumer_group_generation_id"...
Encode an OffsetCommitRequest struct Arguments: group: string, the consumer group you are committing offsets for payloads: list of OffsetCommitRequestPayload
[ "Encode", "an", "OffsetCommitRequest", "struct", "Arguments", ":", "group", ":", "string", "the", "consumer", "group", "you", "are", "committing", "offsets", "for", "payloads", ":", "list", "of", "OffsetCommitRequestPayload" ]
python
train
yt-project/unyt
unyt/array.py
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1738-L1772
def copy(self, order="C"): """ Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, '...
[ "def", "copy", "(", "self", ",", "order", "=", "\"C\"", ")", ":", "return", "type", "(", "self", ")", "(", "np", ".", "copy", "(", "np", ".", "asarray", "(", "self", ")", ")", ",", "self", ".", "units", ")" ]
Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a`...
[ "Return", "a", "copy", "of", "the", "array", "." ]
python
train
edeposit/edeposit.amqp.ftp
src/edeposit/amqp/ftp/settings.py
https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/settings.py#L121-L133
def conf_merger(user_dict, variable): """ Merge global configuration with user's personal configuration. Global configuration has always higher priority. """ if variable not in globals().keys(): raise NameError("Unknown variable '%s'." % variable) if variable not in user_dict: ...
[ "def", "conf_merger", "(", "user_dict", ",", "variable", ")", ":", "if", "variable", "not", "in", "globals", "(", ")", ".", "keys", "(", ")", ":", "raise", "NameError", "(", "\"Unknown variable '%s'.\"", "%", "variable", ")", "if", "variable", "not", "in",...
Merge global configuration with user's personal configuration. Global configuration has always higher priority.
[ "Merge", "global", "configuration", "with", "user", "s", "personal", "configuration", "." ]
python
train
jobovy/galpy
galpy/orbit/OrbitTop.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L372-L394
def y(self,*args,**kwargs): """ NAME: y PURPOSE: return y INPUT: t - (optional) time at which to get y ro= (Object-wide default) physical scale for distances to use to convert use_physical= use to override Object-wide default for usi...
[ "def", "y", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thiso", "=", "self", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "len", "(", "thiso", ".", "shape", ")", "==", "2", ":", "thiso", "=", "thiso", ...
NAME: y PURPOSE: return y INPUT: t - (optional) time at which to get y ro= (Object-wide default) physical scale for distances to use to convert use_physical= use to override Object-wide default for using a physical scale for output OUTPUT: ...
[ "NAME", ":", "y", "PURPOSE", ":", "return", "y", "INPUT", ":", "t", "-", "(", "optional", ")", "time", "at", "which", "to", "get", "y", "ro", "=", "(", "Object", "-", "wide", "default", ")", "physical", "scale", "for", "distances", "to", "use", "to...
python
train
mfitzp/padua
padua/normalization.py
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/normalization.py#L4-L22
def subtract_column_median(df, prefix='Intensity '): """ Apply column-wise normalisation to expression columns. Default is median transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return: """ df = df.copy() ...
[ "def", "subtract_column_median", "(", "df", ",", "prefix", "=", "'Intensity '", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "df", ".", "replace", "(", "[", "np", ".", "inf", ",", "-", "np", ".", "inf", "]", ",", "np", ".", "nan", ",", "in...
Apply column-wise normalisation to expression columns. Default is median transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return:
[ "Apply", "column", "-", "wise", "normalisation", "to", "expression", "columns", "." ]
python
train
Jajcus/pyxmpp2
pyxmpp2/ext/disco.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L501-L517
def add_item(self,jid,node=None,name=None,action=None): """Add a new item to the `DiscoItems` object. :Parameters: - `jid`: item JID. - `node`: item node name. - `name`: item name. - `action`: action for a "disco push". :Types: - `jid`...
[ "def", "add_item", "(", "self", ",", "jid", ",", "node", "=", "None", ",", "name", "=", "None", ",", "action", "=", "None", ")", ":", "return", "DiscoItem", "(", "self", ",", "jid", ",", "node", ",", "name", ",", "action", ")" ]
Add a new item to the `DiscoItems` object. :Parameters: - `jid`: item JID. - `node`: item node name. - `name`: item name. - `action`: action for a "disco push". :Types: - `jid`: `pyxmpp.JID` - `node`: `unicode` - `name`...
[ "Add", "a", "new", "item", "to", "the", "DiscoItems", "object", "." ]
python
valid
wavycloud/pyboto3
pyboto3/elasticbeanstalk.py
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/elasticbeanstalk.py#L585-L755
def create_environment(ApplicationName=None, EnvironmentName=None, GroupName=None, Description=None, CNAMEPrefix=None, Tier=None, Tags=None, VersionLabel=None, TemplateName=None, SolutionStackName=None, PlatformArn=None, OptionSettings=None, OptionsToRemove=None): """ Launches an environment for the specified a...
[ "def", "create_environment", "(", "ApplicationName", "=", "None", ",", "EnvironmentName", "=", "None", ",", "GroupName", "=", "None", ",", "Description", "=", "None", ",", "CNAMEPrefix", "=", "None", ",", "Tier", "=", "None", ",", "Tags", "=", "None", ",",...
Launches an environment for the specified application using the specified configuration. See also: AWS API Documentation Examples The following operation creates a new environment for version v1 of a java application named my-app: Expected Output: :example: response = client.create_environ...
[ "Launches", "an", "environment", "for", "the", "specified", "application", "using", "the", "specified", "configuration", ".", "See", "also", ":", "AWS", "API", "Documentation", "Examples", "The", "following", "operation", "creates", "a", "new", "environment", "for...
python
train
juju/juju-bundlelib
jujubundlelib/validation.py
https://github.com/juju/juju-bundlelib/blob/c2efa614f53675ed9526027776448bfbb0454ca6/jujubundlelib/validation.py#L37-L62
def validate(bundle): """Validate a bundle object and all of its components. The bundle must be passed as a YAML decoded object. Return a list of bundle errors, or an empty list if the bundle is valid. """ errors = [] add_error = errors.append # Check that the bundle sections are well for...
[ "def", "validate", "(", "bundle", ")", ":", "errors", "=", "[", "]", "add_error", "=", "errors", ".", "append", "# Check that the bundle sections are well formed.", "series", ",", "services", ",", "machines", ",", "relations", "=", "_validate_sections", "(", "bund...
Validate a bundle object and all of its components. The bundle must be passed as a YAML decoded object. Return a list of bundle errors, or an empty list if the bundle is valid.
[ "Validate", "a", "bundle", "object", "and", "all", "of", "its", "components", "." ]
python
train
stevearc/dql
dql/cli.py
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L254-L260
def save_config(self): """ Save the conf file """ if not os.path.exists(self._conf_dir): os.makedirs(self._conf_dir) conf_file = os.path.join(self._conf_dir, "dql.json") with open(conf_file, "w") as ofile: json.dump(self.conf, ofile, indent=2)
[ "def", "save_config", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_conf_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_conf_dir", ")", "conf_file", "=", "os", ".", "path", ".", "join", "(", ...
Save the conf file
[ "Save", "the", "conf", "file" ]
python
train
mitsei/dlkit
dlkit/json_/hierarchy/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/hierarchy/sessions.py#L978-L1001
def can_create_hierarchy_with_record_types(self, hierarchy_record_types): """Tests if this user can create a single ``Hierarchy`` using the desired record types. While ``HierarchyManager.getHierarchyRecordTypes()`` can be used to examine which records are supported, this method tests which ...
[ "def", "can_create_hierarchy_with_record_types", "(", "self", ",", "hierarchy_record_types", ")", ":", "# Implemented from template for", "# osid.resource.BinAdminSession.can_create_bin_with_record_types", "# NOTE: It is expected that real authentication hints will be", "# handled in a service...
Tests if this user can create a single ``Hierarchy`` using the desired record types. While ``HierarchyManager.getHierarchyRecordTypes()`` can be used to examine which records are supported, this method tests which record(s) are required for creating a specific ``Hierarchy``. Providing a...
[ "Tests", "if", "this", "user", "can", "create", "a", "single", "Hierarchy", "using", "the", "desired", "record", "types", "." ]
python
train
bitesofcode/projexui
projexui/widgets/xwalkthroughwidget/xwalkthrough.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xwalkthroughwidget/xwalkthrough.py#L133-L145
def fromXml(xml): """ Creates a new slide from XML. :return <XWalkthroughSlide> """ slide = XWalkthroughSlide(**xml.attrib) # create the items for xgraphic in xml: slide.addItem(XWalkthroughItem.fromXml(xgraphic)) ...
[ "def", "fromXml", "(", "xml", ")", ":", "slide", "=", "XWalkthroughSlide", "(", "*", "*", "xml", ".", "attrib", ")", "# create the items\r", "for", "xgraphic", "in", "xml", ":", "slide", ".", "addItem", "(", "XWalkthroughItem", ".", "fromXml", "(", "xgraph...
Creates a new slide from XML. :return <XWalkthroughSlide>
[ "Creates", "a", "new", "slide", "from", "XML", ".", ":", "return", "<XWalkthroughSlide", ">" ]
python
train
zhmcclient/python-zhmcclient
zhmcclient/_hba.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_hba.py#L302-L331
def reassign_port(self, port): """ Reassign this HBA to a new underlying :term:`FCP port`. This method performs the HMC operation "Reassign Storage Adapter Port". Authorization requirements: * Object-access permission to the Partition containing this HBA. * Object-acce...
[ "def", "reassign_port", "(", "self", ",", "port", ")", ":", "body", "=", "{", "'adapter-port-uri'", ":", "port", ".", "uri", "}", "self", ".", "manager", ".", "session", ".", "post", "(", "self", ".", "_uri", "+", "'/operations/reassign-storage-adapter-port'...
Reassign this HBA to a new underlying :term:`FCP port`. This method performs the HMC operation "Reassign Storage Adapter Port". Authorization requirements: * Object-access permission to the Partition containing this HBA. * Object-access permission to the Adapter with the new Port. ...
[ "Reassign", "this", "HBA", "to", "a", "new", "underlying", ":", "term", ":", "FCP", "port", "." ]
python
train
reiinakano/xcessiv
xcessiv/functions.py
https://github.com/reiinakano/xcessiv/blob/a48dff7d370c84eb5c243bde87164c1f5fd096d5/xcessiv/functions.py#L16-L28
def hash_file(path, block_size=65536): """Returns SHA256 checksum of a file Args: path (string): Absolute file path of file to hash block_size (int, optional): Number of bytes to read per block """ sha256 = hashlib.sha256() with open(path, 'rb') as f: for block in iter(lamb...
[ "def", "hash_file", "(", "path", ",", "block_size", "=", "65536", ")", ":", "sha256", "=", "hashlib", ".", "sha256", "(", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "for", "block", "in", "iter", "(", "lambda", ":", "f", "...
Returns SHA256 checksum of a file Args: path (string): Absolute file path of file to hash block_size (int, optional): Number of bytes to read per block
[ "Returns", "SHA256", "checksum", "of", "a", "file" ]
python
train
saulpw/visidata
visidata/vdtui.py
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2258-L2263
def getMaxWidth(self, rows): 'Return the maximum length of any cell in column or its header.' w = 0 if len(rows) > 0: w = max(max(len(self.getDisplayValue(r)) for r in rows), len(self.name))+2 return max(w, len(self.name))
[ "def", "getMaxWidth", "(", "self", ",", "rows", ")", ":", "w", "=", "0", "if", "len", "(", "rows", ")", ">", "0", ":", "w", "=", "max", "(", "max", "(", "len", "(", "self", ".", "getDisplayValue", "(", "r", ")", ")", "for", "r", "in", "rows",...
Return the maximum length of any cell in column or its header.
[ "Return", "the", "maximum", "length", "of", "any", "cell", "in", "column", "or", "its", "header", "." ]
python
train
django-userena-ce/django-userena-ce
userena/decorators.py
https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/userena/decorators.py#L9-L29
def secure_required(view_func): """ Decorator to switch an url from http to https. If a view is accessed through http and this decorator is applied to that view, than it will return a permanent redirect to the secure (https) version of the same view. The decorator also must check that ``USEREN...
[ "def", "secure_required", "(", "view_func", ")", ":", "def", "_wrapped_view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "request", ".", "is_secure", "(", ")", ":", "if", "getattr", "(", "settings", ",", "'USERENA...
Decorator to switch an url from http to https. If a view is accessed through http and this decorator is applied to that view, than it will return a permanent redirect to the secure (https) version of the same view. The decorator also must check that ``USERENA_USE_HTTPS`` is enabled. If disabled, i...
[ "Decorator", "to", "switch", "an", "url", "from", "http", "to", "https", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/mpls_state/rsvp/sessions/psbs/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/mpls_state/rsvp/sessions/psbs/__init__.py#L254-L277
def _set_session_type(self, v, load=False): """ Setter method for session_type, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/session_type (session-type) If this variable is read-only (config: false) in the source YANG file, then _set_session_type is considered as a private method. Backen...
[ "def", "_set_session_type", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "b...
Setter method for session_type, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/session_type (session-type) If this variable is read-only (config: false) in the source YANG file, then _set_session_type is considered as a private method. Backends looking to populate this variable should do so vi...
[ "Setter", "method", "for", "session_type", "mapped", "from", "YANG", "variable", "/", "mpls_state", "/", "rsvp", "/", "sessions", "/", "psbs", "/", "session_type", "(", "session", "-", "type", ")", "If", "this", "variable", "is", "read", "-", "only", "(", ...
python
train
MrYsLab/PyMata
PyMata/pymata_command_handler.py
https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_command_handler.py#L704-L730
def i2c_reply(self, data): """ This method receives replies to i2c_read requests. It stores the data for each i2c device address in a dictionary called i2c_map. The data is retrieved via a call to i2c_get_read_data() in pymata.py It a callback was specified in pymata.i2c_read, th...
[ "def", "i2c_reply", "(", "self", ",", "data", ")", ":", "reply_data", "=", "[", "]", "address", "=", "(", "data", "[", "0", "]", "&", "0x7f", ")", "+", "(", "data", "[", "1", "]", "<<", "7", ")", "register", "=", "data", "[", "2", "]", "&", ...
This method receives replies to i2c_read requests. It stores the data for each i2c device address in a dictionary called i2c_map. The data is retrieved via a call to i2c_get_read_data() in pymata.py It a callback was specified in pymata.i2c_read, the raw data is sent through the callback ...
[ "This", "method", "receives", "replies", "to", "i2c_read", "requests", ".", "It", "stores", "the", "data", "for", "each", "i2c", "device", "address", "in", "a", "dictionary", "called", "i2c_map", ".", "The", "data", "is", "retrieved", "via", "a", "call", "...
python
valid
SatelliteQE/nailgun
nailgun/entities.py
https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L7346-L7351
def update_payload(self, fields=None): """Convert ``sync_date`` to a string if datetime object provided.""" data = super(SyncPlan, self).update_payload(fields) if isinstance(data.get('sync_date'), datetime): data['sync_date'] = data['sync_date'].strftime('%Y-%m-%d %H:%M:%S') ...
[ "def", "update_payload", "(", "self", ",", "fields", "=", "None", ")", ":", "data", "=", "super", "(", "SyncPlan", ",", "self", ")", ".", "update_payload", "(", "fields", ")", "if", "isinstance", "(", "data", ".", "get", "(", "'sync_date'", ")", ",", ...
Convert ``sync_date`` to a string if datetime object provided.
[ "Convert", "sync_date", "to", "a", "string", "if", "datetime", "object", "provided", "." ]
python
train
cuihantao/andes
andes/models/base.py
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L417-L455
def get_field(self, field, idx=None, astype=None): """ Return `self.field` for the elements labeled by `idx` :param astype: type cast of the return value :param field: field name of this model :param idx: element indices, will be the whole list if not specified :return: ...
[ "def", "get_field", "(", "self", ",", "field", ",", "idx", "=", "None", ",", "astype", "=", "None", ")", ":", "assert", "astype", "in", "(", "None", ",", "list", ",", "matrix", ")", "ret", "=", "None", "if", "idx", "is", "None", ":", "idx", "=", ...
Return `self.field` for the elements labeled by `idx` :param astype: type cast of the return value :param field: field name of this model :param idx: element indices, will be the whole list if not specified :return: field values
[ "Return", "self", ".", "field", "for", "the", "elements", "labeled", "by", "idx" ]
python
train
sods/paramz
paramz/core/index_operations.py
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/index_operations.py#L145-L159
def properties_dict_for(self, index): """ Return a dictionary, containing properties as keys and indices as index Thus, the indices for each constraint, which is contained will be collected as one dictionary Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] ...
[ "def", "properties_dict_for", "(", "self", ",", "index", ")", ":", "props", "=", "self", ".", "properties_for", "(", "index", ")", "prop_index", "=", "extract_properties_to_index", "(", "index", ",", "props", ")", "return", "prop_index" ]
Return a dictionary, containing properties as keys and indices as index Thus, the indices for each constraint, which is contained will be collected as one dictionary Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] >>> properties_dict_for([2,3,5]) {'one':[2,3], '...
[ "Return", "a", "dictionary", "containing", "properties", "as", "keys", "and", "indices", "as", "index", "Thus", "the", "indices", "for", "each", "constraint", "which", "is", "contained", "will", "be", "collected", "as", "one", "dictionary" ]
python
train
airspeed-velocity/asv
asv/plugins/virtualenv.py
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/plugins/virtualenv.py#L124-L140
def _setup(self): """ Setup the environment on disk using virtualenv. Then, all of the requirements are installed into it using `pip install`. """ log.info("Creating virtualenv for {0}".format(self.name)) util.check_call([ sys.executable, "...
[ "def", "_setup", "(", "self", ")", ":", "log", ".", "info", "(", "\"Creating virtualenv for {0}\"", ".", "format", "(", "self", ".", "name", ")", ")", "util", ".", "check_call", "(", "[", "sys", ".", "executable", ",", "\"-mvirtualenv\"", ",", "'--no-site-...
Setup the environment on disk using virtualenv. Then, all of the requirements are installed into it using `pip install`.
[ "Setup", "the", "environment", "on", "disk", "using", "virtualenv", ".", "Then", "all", "of", "the", "requirements", "are", "installed", "into", "it", "using", "pip", "install", "." ]
python
train
RedHatInsights/insights-core
insights/client/mount.py
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/mount.py#L112-L118
def _get_fs(thin_pathname): """ Returns the file system type (xfs, ext4) of a given device """ cmd = ['lsblk', '-o', 'FSTYPE', '-n', thin_pathname] fs_return = util.subp(cmd) return fs_return.stdout.strip()
[ "def", "_get_fs", "(", "thin_pathname", ")", ":", "cmd", "=", "[", "'lsblk'", ",", "'-o'", ",", "'FSTYPE'", ",", "'-n'", ",", "thin_pathname", "]", "fs_return", "=", "util", ".", "subp", "(", "cmd", ")", "return", "fs_return", ".", "stdout", ".", "stri...
Returns the file system type (xfs, ext4) of a given device
[ "Returns", "the", "file", "system", "type", "(", "xfs", "ext4", ")", "of", "a", "given", "device" ]
python
train
jreese/aiosqlite
aiosqlite/core.py
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L169-L173
async def _connect(self) -> "Connection": """Connect to the actual sqlite database.""" if self._connection is None: self._connection = await self._execute(self._connector) return self
[ "async", "def", "_connect", "(", "self", ")", "->", "\"Connection\"", ":", "if", "self", ".", "_connection", "is", "None", ":", "self", ".", "_connection", "=", "await", "self", ".", "_execute", "(", "self", ".", "_connector", ")", "return", "self" ]
Connect to the actual sqlite database.
[ "Connect", "to", "the", "actual", "sqlite", "database", "." ]
python
train
schapman1974/tinymongo
tinymongo/tinymongo.py
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L441-L469
def find(self, filter=None, sort=None, skip=None, limit=None, *args, **kwargs): """ Finds all matching results :param query: dictionary representing the mongo query :return: cursor containing the search results """ if self.table is None: self.bui...
[ "def", "find", "(", "self", ",", "filter", "=", "None", ",", "sort", "=", "None", ",", "skip", "=", "None", ",", "limit", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ...
Finds all matching results :param query: dictionary representing the mongo query :return: cursor containing the search results
[ "Finds", "all", "matching", "results" ]
python
train
tanghaibao/jcvi
jcvi/apps/base.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L921-L931
def need_update(a, b): """ Check if file a is newer than file b and decide whether or not to update file b. Can generalize to two lists. """ a = listify(a) b = listify(b) return any((not op.exists(x)) for x in b) or \ all((os.stat(x).st_size == 0 for x in b)) or \ any(...
[ "def", "need_update", "(", "a", ",", "b", ")", ":", "a", "=", "listify", "(", "a", ")", "b", "=", "listify", "(", "b", ")", "return", "any", "(", "(", "not", "op", ".", "exists", "(", "x", ")", ")", "for", "x", "in", "b", ")", "or", "all", ...
Check if file a is newer than file b and decide whether or not to update file b. Can generalize to two lists.
[ "Check", "if", "file", "a", "is", "newer", "than", "file", "b", "and", "decide", "whether", "or", "not", "to", "update", "file", "b", ".", "Can", "generalize", "to", "two", "lists", "." ]
python
train
saltstack/salt
salt/states/libcloud_storage.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_storage.py#L175-L195
def file_present(container, name, path, profile, overwrite_existing=False): ''' Ensures a object is downloaded locally. :param container: Container name :type container: ``str`` :param name: Object name in cloud :type name: ``str`` :param path: Local path to file :type path: ``str`...
[ "def", "file_present", "(", "container", ",", "name", ",", "path", ",", "profile", ",", "overwrite_existing", "=", "False", ")", ":", "result", "=", "__salt__", "[", "'libcloud_storage.download_object'", "]", "(", "path", ",", "container", ",", "name", ",", ...
Ensures a object is downloaded locally. :param container: Container name :type container: ``str`` :param name: Object name in cloud :type name: ``str`` :param path: Local path to file :type path: ``str`` :param profile: The profile key :type profile: ``str`` :param overwrite...
[ "Ensures", "a", "object", "is", "downloaded", "locally", "." ]
python
train
base4sistemas/satcfe
satcfe/base.py
https://github.com/base4sistemas/satcfe/blob/cb8e8815f4133d3e3d94cf526fa86767b4521ed9/satcfe/base.py#L326-L347
def cancelar_ultima_venda(self, chave_cfe, dados_cancelamento): """Função ``CancelarUltimaVenda`` conforme ER SAT, item 6.1.4. Envia o CF-e de cancelamento para o equipamento SAT, que o enviará para autorização e cancelamento do CF-e pela SEFAZ. :param chave_cfe: String contendo a chave...
[ "def", "cancelar_ultima_venda", "(", "self", ",", "chave_cfe", ",", "dados_cancelamento", ")", ":", "cfe_canc", "=", "dados_cancelamento", "if", "isinstance", "(", "dados_cancelamento", ",", "basestring", ")", "else", "dados_cancelamento", ".", "documento", "(", ")"...
Função ``CancelarUltimaVenda`` conforme ER SAT, item 6.1.4. Envia o CF-e de cancelamento para o equipamento SAT, que o enviará para autorização e cancelamento do CF-e pela SEFAZ. :param chave_cfe: String contendo a chave do CF-e a ser cancelado, prefixada com o literal ``CFe``. ...
[ "Função", "CancelarUltimaVenda", "conforme", "ER", "SAT", "item", "6", ".", "1", ".", "4", ".", "Envia", "o", "CF", "-", "e", "de", "cancelamento", "para", "o", "equipamento", "SAT", "que", "o", "enviará", "para", "autorização", "e", "cancelamento", "do", ...
python
train
ejeschke/ginga
ginga/rv/Control.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L2609-L2614
def motion_cb(self, viewer, button, data_x, data_y): """Motion event in the channel viewer window. Show the pointing information under the cursor. """ self.showxy(viewer, data_x, data_y) return True
[ "def", "motion_cb", "(", "self", ",", "viewer", ",", "button", ",", "data_x", ",", "data_y", ")", ":", "self", ".", "showxy", "(", "viewer", ",", "data_x", ",", "data_y", ")", "return", "True" ]
Motion event in the channel viewer window. Show the pointing information under the cursor.
[ "Motion", "event", "in", "the", "channel", "viewer", "window", ".", "Show", "the", "pointing", "information", "under", "the", "cursor", "." ]
python
train
boriel/zxbasic
arch/zx48k/backend/__array.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__array.py#L189-L243
def _astore16(ins): ''' Stores 2º operand content into address of 1st operand. store16 a, x => *(&a) = x Use '*' for indirect store on 1st operand. ''' output = _addr(ins.quad[1]) op = ins.quad[2] indirect = op[0] == '*' if indirect: op = op[1:] immediate = op[0] == '#' ...
[ "def", "_astore16", "(", "ins", ")", ":", "output", "=", "_addr", "(", "ins", ".", "quad", "[", "1", "]", ")", "op", "=", "ins", ".", "quad", "[", "2", "]", "indirect", "=", "op", "[", "0", "]", "==", "'*'", "if", "indirect", ":", "op", "=", ...
Stores 2º operand content into address of 1st operand. store16 a, x => *(&a) = x Use '*' for indirect store on 1st operand.
[ "Stores", "2º", "operand", "content", "into", "address", "of", "1st", "operand", ".", "store16", "a", "x", "=", ">", "*", "(", "&a", ")", "=", "x", "Use", "*", "for", "indirect", "store", "on", "1st", "operand", "." ]
python
train
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L192-L207
def get_availabilities_for_duration(duration, availabilities): """ Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows. """ duration_availabilities = [] start_time = '10:00' while start_time != '17:00': if start_time in av...
[ "def", "get_availabilities_for_duration", "(", "duration", ",", "availabilities", ")", ":", "duration_availabilities", "=", "[", "]", "start_time", "=", "'10:00'", "while", "start_time", "!=", "'17:00'", ":", "if", "start_time", "in", "availabilities", ":", "if", ...
Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows.
[ "Helper", "function", "to", "return", "the", "windows", "of", "availability", "of", "the", "given", "duration", "when", "provided", "a", "set", "of", "30", "minute", "windows", "." ]
python
train
spotify/luigi
luigi/contrib/hadoop.py
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L989-L1004
def _map_input(self, input_stream): """ Iterate over input and call the mapper for each item. If the job has a parser defined, the return values from the parser will be passed as arguments to the mapper. If the input is coded output from a previous run, the arguments wil...
[ "def", "_map_input", "(", "self", ",", "input_stream", ")", ":", "for", "record", "in", "self", ".", "reader", "(", "input_stream", ")", ":", "for", "output", "in", "self", ".", "mapper", "(", "*", "record", ")", ":", "yield", "output", "if", "self", ...
Iterate over input and call the mapper for each item. If the job has a parser defined, the return values from the parser will be passed as arguments to the mapper. If the input is coded output from a previous run, the arguments will be splitted in key and value.
[ "Iterate", "over", "input", "and", "call", "the", "mapper", "for", "each", "item", ".", "If", "the", "job", "has", "a", "parser", "defined", "the", "return", "values", "from", "the", "parser", "will", "be", "passed", "as", "arguments", "to", "the", "mapp...
python
train
juju/charm-helpers
charmhelpers/core/hookenv.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L676-L688
def relation_to_role_and_interface(relation_name): """ Given the name of a relation, return the role and the name of the interface that relation uses (where role is one of ``provides``, ``requires``, or ``peers``). :returns: A tuple containing ``(role, interface)``, or ``(None, None)``. """ _me...
[ "def", "relation_to_role_and_interface", "(", "relation_name", ")", ":", "_metadata", "=", "metadata", "(", ")", "for", "role", "in", "(", "'provides'", ",", "'requires'", ",", "'peers'", ")", ":", "interface", "=", "_metadata", ".", "get", "(", "role", ",",...
Given the name of a relation, return the role and the name of the interface that relation uses (where role is one of ``provides``, ``requires``, or ``peers``). :returns: A tuple containing ``(role, interface)``, or ``(None, None)``.
[ "Given", "the", "name", "of", "a", "relation", "return", "the", "role", "and", "the", "name", "of", "the", "interface", "that", "relation", "uses", "(", "where", "role", "is", "one", "of", "provides", "requires", "or", "peers", ")", "." ]
python
train
chemlab/chemlab
chemlab/libs/cirpy.py
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/cirpy.py#L33-L39
def resolve(input, representation, resolvers=None, **kwargs): """ Resolve input to the specified output representation """ resultdict = query(input, representation, resolvers, **kwargs) result = resultdict[0]['value'] if resultdict else None if result and len(result) == 1: result = result[0] ...
[ "def", "resolve", "(", "input", ",", "representation", ",", "resolvers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "resultdict", "=", "query", "(", "input", ",", "representation", ",", "resolvers", ",", "*", "*", "kwargs", ")", "result", "=", "re...
Resolve input to the specified output representation
[ "Resolve", "input", "to", "the", "specified", "output", "representation" ]
python
train
tchellomello/python-arlo
pyarlo/base_station.py
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L408-L418
def get_cameras_signal_strength(self): """Return a list of signal strength of all cameras.""" signal_strength = {} if not self.camera_properties: return None for camera in self.camera_properties: serialnum = camera.get('serialNumber') cam_strength = c...
[ "def", "get_cameras_signal_strength", "(", "self", ")", ":", "signal_strength", "=", "{", "}", "if", "not", "self", ".", "camera_properties", ":", "return", "None", "for", "camera", "in", "self", ".", "camera_properties", ":", "serialnum", "=", "camera", ".", ...
Return a list of signal strength of all cameras.
[ "Return", "a", "list", "of", "signal", "strength", "of", "all", "cameras", "." ]
python
train
rsmuc/health_monitoring_plugins
health_monitoring_plugins/newtecmodem.py
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/newtecmodem.py#L74-L79
def process_alarms(self, snmp_data): "Build list with active alarms" self.active_alarms = [] for i in range(0, len(self.models[self.modem_type]['alarms'])): if bool(int(snmp_data[i])) == True: self.active_alarms.append(self.models[self.modem_type]['alarms'][i])
[ "def", "process_alarms", "(", "self", ",", "snmp_data", ")", ":", "self", ".", "active_alarms", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "models", "[", "self", ".", "modem_type", "]", "[", "'alarms'", "]", "...
Build list with active alarms
[ "Build", "list", "with", "active", "alarms" ]
python
train
jazzband/django-axes
axes/attempts.py
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/attempts.py#L76-L86
def reset_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> int: """ Reset all user attempts that match the given request and credentials. """ attempts = filter_user_attempts(request, credentials) count, _ = attempts.delete() log.info('AXES: Reset %s access attempts from dat...
[ "def", "reset_user_attempts", "(", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "int", ":", "attempts", "=", "filter_user_attempts", "(", "request", ",", "credentials", ")", "count", ",", "_", "=", "attempts", "...
Reset all user attempts that match the given request and credentials.
[ "Reset", "all", "user", "attempts", "that", "match", "the", "given", "request", "and", "credentials", "." ]
python
train
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1994-L1999
def schemaNewMemParserCtxt(buffer, size): """Create an XML Schemas parse context for that memory buffer expected to contain an XML Schemas file. """ ret = libxml2mod.xmlSchemaNewMemParserCtxt(buffer, size) if ret is None:raise parserError('xmlSchemaNewMemParserCtxt() failed') return SchemaParserC...
[ "def", "schemaNewMemParserCtxt", "(", "buffer", ",", "size", ")", ":", "ret", "=", "libxml2mod", ".", "xmlSchemaNewMemParserCtxt", "(", "buffer", ",", "size", ")", "if", "ret", "is", "None", ":", "raise", "parserError", "(", "'xmlSchemaNewMemParserCtxt() failed'",...
Create an XML Schemas parse context for that memory buffer expected to contain an XML Schemas file.
[ "Create", "an", "XML", "Schemas", "parse", "context", "for", "that", "memory", "buffer", "expected", "to", "contain", "an", "XML", "Schemas", "file", "." ]
python
train
opencobra/cobrapy
cobra/core/reaction.py
https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L107-L111
def reverse_id(self): """Generate the id of reverse_variable from the reaction's id.""" return '_'.join((self.id, 'reverse', hashlib.md5( self.id.encode('utf-8')).hexdigest()[0:5]))
[ "def", "reverse_id", "(", "self", ")", ":", "return", "'_'", ".", "join", "(", "(", "self", ".", "id", ",", "'reverse'", ",", "hashlib", ".", "md5", "(", "self", ".", "id", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "[",...
Generate the id of reverse_variable from the reaction's id.
[ "Generate", "the", "id", "of", "reverse_variable", "from", "the", "reaction", "s", "id", "." ]
python
valid
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L413-L485
def list_instances( self, parent, page_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists information about instances in a project. Example: >>> f...
[ "def", "list_instances", "(", "self", ",", "parent", ",", "page_token", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "meth...
Lists information about instances in a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> ...
[ "Lists", "information", "about", "instances", "in", "a", "project", "." ]
python
train
DataDog/integrations-core
haproxy/datadog_checks/haproxy/haproxy.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/haproxy/datadog_checks/haproxy/haproxy.py#L193-L217
def _fetch_socket_data(self, parsed_url): ''' Hit a given stats socket and return the stats lines ''' self.log.debug("Fetching haproxy stats from socket: %s" % parsed_url.geturl()) if parsed_url.scheme == 'tcp': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s...
[ "def", "_fetch_socket_data", "(", "self", ",", "parsed_url", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Fetching haproxy stats from socket: %s\"", "%", "parsed_url", ".", "geturl", "(", ")", ")", "if", "parsed_url", ".", "scheme", "==", "'tcp'", ":", ...
Hit a given stats socket and return the stats lines
[ "Hit", "a", "given", "stats", "socket", "and", "return", "the", "stats", "lines" ]
python
train
benley/butcher
butcher/gitrepo.py
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/gitrepo.py#L147-L158
def sethead(self, ref): """Set head to a git ref.""" log.debug('[%s] Setting to ref %s', self.name, ref) try: ref = self.repo.rev_parse(ref) except gitdb.exc.BadObject: # Probably means we don't have it cached yet. # So maybe we can fetch it. ...
[ "def", "sethead", "(", "self", ",", "ref", ")", ":", "log", ".", "debug", "(", "'[%s] Setting to ref %s'", ",", "self", ".", "name", ",", "ref", ")", "try", ":", "ref", "=", "self", ".", "repo", ".", "rev_parse", "(", "ref", ")", "except", "gitdb", ...
Set head to a git ref.
[ "Set", "head", "to", "a", "git", "ref", "." ]
python
train
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L870-L878
def transitions_for(self, roles=None, actor=None, anchors=[]): """ For use on :class:`~coaster.sqlalchemy.mixins.RoleMixin` classes: returns currently available transitions for the specified roles or actor as a dictionary of name: :class:`StateTransitionWrapper`. """ prox...
[ "def", "transitions_for", "(", "self", ",", "roles", "=", "None", ",", "actor", "=", "None", ",", "anchors", "=", "[", "]", ")", ":", "proxy", "=", "self", ".", "obj", ".", "access_for", "(", "roles", ",", "actor", ",", "anchors", ")", "return", "{...
For use on :class:`~coaster.sqlalchemy.mixins.RoleMixin` classes: returns currently available transitions for the specified roles or actor as a dictionary of name: :class:`StateTransitionWrapper`.
[ "For", "use", "on", ":", "class", ":", "~coaster", ".", "sqlalchemy", ".", "mixins", ".", "RoleMixin", "classes", ":", "returns", "currently", "available", "transitions", "for", "the", "specified", "roles", "or", "actor", "as", "a", "dictionary", "of", "name...
python
train
cisco-sas/kitty
kitty/model/low_level/container.py
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/model/low_level/container.py#L709-L717
def get_rendered_fields(self, ctx=None): ''' :param ctx: rendering context in which the method was called :return: ordered list of the fields that will be rendered ''' times = self._min_times if self._mutating() and self._in_repeat_stage(): times += (self._cur...
[ "def", "get_rendered_fields", "(", "self", ",", "ctx", "=", "None", ")", ":", "times", "=", "self", ".", "_min_times", "if", "self", ".", "_mutating", "(", ")", "and", "self", ".", "_in_repeat_stage", "(", ")", ":", "times", "+=", "(", "self", ".", "...
:param ctx: rendering context in which the method was called :return: ordered list of the fields that will be rendered
[ ":", "param", "ctx", ":", "rendering", "context", "in", "which", "the", "method", "was", "called", ":", "return", ":", "ordered", "list", "of", "the", "fields", "that", "will", "be", "rendered" ]
python
train
mozilla/treeherder
treeherder/client/thclient/perfherder.py
https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/client/thclient/perfherder.py#L16-L26
def all_valid_time_intervals(): ''' Helper method to return all possible valid time intervals for data stored by Perfherder ''' return [PerformanceTimeInterval.DAY, PerformanceTimeInterval.WEEK, PerformanceTimeInterval.TWO_WEEKS, Pe...
[ "def", "all_valid_time_intervals", "(", ")", ":", "return", "[", "PerformanceTimeInterval", ".", "DAY", ",", "PerformanceTimeInterval", ".", "WEEK", ",", "PerformanceTimeInterval", ".", "TWO_WEEKS", ",", "PerformanceTimeInterval", ".", "SIXTY_DAYS", ",", "PerformanceTim...
Helper method to return all possible valid time intervals for data stored by Perfherder
[ "Helper", "method", "to", "return", "all", "possible", "valid", "time", "intervals", "for", "data", "stored", "by", "Perfherder" ]
python
train
googleapis/google-cloud-python
datastore/google/cloud/datastore/batch.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/batch.py#L159-L200
def put(self, entity): """Remember an entity's state to be saved during :meth:`commit`. .. note:: Any existing properties for the entity will be replaced by those currently set on this instance. Already-stored properties which do not correspond to keys set on this inst...
[ "def", "put", "(", "self", ",", "entity", ")", ":", "if", "self", ".", "_status", "!=", "self", ".", "_IN_PROGRESS", ":", "raise", "ValueError", "(", "\"Batch must be in progress to put()\"", ")", "if", "entity", ".", "key", "is", "None", ":", "raise", "Va...
Remember an entity's state to be saved during :meth:`commit`. .. note:: Any existing properties for the entity will be replaced by those currently set on this instance. Already-stored properties which do not correspond to keys set on this instance will be removed from ...
[ "Remember", "an", "entity", "s", "state", "to", "be", "saved", "during", ":", "meth", ":", "commit", "." ]
python
train
XuShaohua/bcloud
bcloud/IconWindow.py
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/IconWindow.py#L758-L782
def on_drag_data_received(self, widget, context, x, y, data, info, time): '''拖放结束''' if not data: return bx, by = self.iconview.convert_widget_to_bin_window_coords(x, y) selected = Gtk.TreeView.get_path_at_pos(self.iconview, bx, by) if not selected: return...
[ "def", "on_drag_data_received", "(", "self", ",", "widget", ",", "context", ",", "x", ",", "y", ",", "data", ",", "info", ",", "time", ")", ":", "if", "not", "data", ":", "return", "bx", ",", "by", "=", "self", ".", "iconview", ".", "convert_widget_t...
拖放结束
[ "拖放结束" ]
python
train
obulpathi/cdn-fastly-python
fastly/__init__.py
https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/fastly/__init__.py#L436-L439
def check_domain(self, service_id, version_number, name): """Checks the status of a domain's DNS record. Returns an array of 3 items. The first is the details for the domain. The second is the current CNAME of the domain. The third is a boolean indicating whether or not it has been properly setup to use Fastly.""" ...
[ "def", "check_domain", "(", "self", ",", "service_id", ",", "version_number", ",", "name", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s/version/%d/domain/%s/check\"", "%", "(", "service_id", ",", "version_number", ",", "name", ")", ")", ...
Checks the status of a domain's DNS record. Returns an array of 3 items. The first is the details for the domain. The second is the current CNAME of the domain. The third is a boolean indicating whether or not it has been properly setup to use Fastly.
[ "Checks", "the", "status", "of", "a", "domain", "s", "DNS", "record", ".", "Returns", "an", "array", "of", "3", "items", ".", "The", "first", "is", "the", "details", "for", "the", "domain", ".", "The", "second", "is", "the", "current", "CNAME", "of", ...
python
train
timster/peewee-validates
peewee_validates.py
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L886-L935
def convert_field(self, name, field): """ Convert a single field from a Peewee model field to a validator field. :param name: Name of the field as defined on this validator. :param name: Peewee field instance. :return: Validator field. """ if PEEWEE3: ...
[ "def", "convert_field", "(", "self", ",", "name", ",", "field", ")", ":", "if", "PEEWEE3", ":", "field_type", "=", "field", ".", "field_type", ".", "lower", "(", ")", "else", ":", "field_type", "=", "field", ".", "db_field", "pwv_field", "=", "ModelValid...
Convert a single field from a Peewee model field to a validator field. :param name: Name of the field as defined on this validator. :param name: Peewee field instance. :return: Validator field.
[ "Convert", "a", "single", "field", "from", "a", "Peewee", "model", "field", "to", "a", "validator", "field", "." ]
python
train
saltstack/salt
salt/modules/opkg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1329-L1346
def get_repo(repo, **kwargs): # pylint: disable=unused-argument ''' Display a repo from the ``/etc/opkg/*.conf`` CLI Examples: .. code-block:: bash salt '*' pkg.get_repo repo ''' repos = list_repos() if repos: for source in six.itervalues(repos): for sub in s...
[ "def", "get_repo", "(", "repo", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "repos", "=", "list_repos", "(", ")", "if", "repos", ":", "for", "source", "in", "six", ".", "itervalues", "(", "repos", ")", ":", "for", "sub", "in",...
Display a repo from the ``/etc/opkg/*.conf`` CLI Examples: .. code-block:: bash salt '*' pkg.get_repo repo
[ "Display", "a", "repo", "from", "the", "/", "etc", "/", "opkg", "/", "*", ".", "conf" ]
python
train
apache/airflow
airflow/contrib/hooks/sagemaker_hook.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sagemaker_hook.py#L519-L572
def describe_training_job_with_log(self, job_name, positions, stream_names, instance_count, state, last_description, last_describe_job_call): """ Return the training job info associated with job_name and print CloudWatch logs ...
[ "def", "describe_training_job_with_log", "(", "self", ",", "job_name", ",", "positions", ",", "stream_names", ",", "instance_count", ",", "state", ",", "last_description", ",", "last_describe_job_call", ")", ":", "log_group", "=", "'/aws/sagemaker/TrainingJobs'", "if", ...
Return the training job info associated with job_name and print CloudWatch logs
[ "Return", "the", "training", "job", "info", "associated", "with", "job_name", "and", "print", "CloudWatch", "logs" ]
python
test
thunlp/THULAC-Python
thulac/__init__.py
https://github.com/thunlp/THULAC-Python/blob/3f1f126cd92c3d2aebdf4ab4850de3c9428a3b66/thulac/__init__.py#L208-L227
def __cutRaw(self, oiraw, maxLength): '''现将句子按句子完结符号切分,如果切分完后一个句子长度超过限定值 ,再对该句子进行切分''' vec = [] m = re.findall(u".*?[。?!;;!?]", oiraw) num, l, last = 0, 0, 0 for i in range(len(m)): if(num + len(m[i]) >= maxLength): vec.append("".join(m[last:i]...
[ "def", "__cutRaw", "(", "self", ",", "oiraw", ",", "maxLength", ")", ":", "vec", "=", "[", "]", "m", "=", "re", ".", "findall", "(", "u\".*?[。?!;;!?]\", oiraw)", "", "", "", "num", ",", "l", ",", "last", "=", "0", ",", "0", ",", "0", "for", "i"...
现将句子按句子完结符号切分,如果切分完后一个句子长度超过限定值 ,再对该句子进行切分
[ "现将句子按句子完结符号切分,如果切分完后一个句子长度超过限定值", ",再对该句子进行切分" ]
python
train