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
utek/pyseaweed
pyseaweed/utils.py
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/utils.py#L95-L119
def post_file(self, url, filename, file_stream, *args, **kwargs): """Uploads file to provided url. Returns contents as text Args: **url**: address where to upload file **filename**: Name of the uploaded file **file_stream**: file like object to upload ...
[ "def", "post_file", "(", "self", ",", "url", ",", "filename", ",", "file_stream", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "self", ".", "_conn", ".", "post", "(", "url", ",", "files", "=", "{", "filename", ":", "file_stream"...
Uploads file to provided url. Returns contents as text Args: **url**: address where to upload file **filename**: Name of the uploaded file **file_stream**: file like object to upload .. versionadded:: 0.3.2 **additional_headers**: (opt...
[ "Uploads", "file", "to", "provided", "url", "." ]
python
train
PolyJIT/benchbuild
benchbuild/utils/actions.py
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/actions.py#L93-L104
def prepend_status(func): """Prepends the output of `func` with the status.""" @ft.wraps(func) def wrapper(self, *args, **kwargs): """Wrapper stub.""" res = func(self, *args, **kwargs) if self.status is not StepResult.UNSET: res = "[{status}]".format(status=self.status.n...
[ "def", "prepend_status", "(", "func", ")", ":", "@", "ft", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper stub.\"\"\"", "res", "=", "func", "(", "self", ",", "*", "...
Prepends the output of `func` with the status.
[ "Prepends", "the", "output", "of", "func", "with", "the", "status", "." ]
python
train
aio-libs/aiohttp
aiohttp/web_protocol.py
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_protocol.py#L316-L324
def keep_alive(self, val: bool) -> None: """Set keep-alive connection mode. :param bool val: new state. """ self._keepalive = val if self._keepalive_handle: self._keepalive_handle.cancel() self._keepalive_handle = None
[ "def", "keep_alive", "(", "self", ",", "val", ":", "bool", ")", "->", "None", ":", "self", ".", "_keepalive", "=", "val", "if", "self", ".", "_keepalive_handle", ":", "self", ".", "_keepalive_handle", ".", "cancel", "(", ")", "self", ".", "_keepalive_han...
Set keep-alive connection mode. :param bool val: new state.
[ "Set", "keep", "-", "alive", "connection", "mode", "." ]
python
train
FutunnOpen/futuquant
futuquant/quote/open_quote_context.py
https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/quote/open_quote_context.py#L796-L845
def get_plate_list(self, market, plate_class): """ 获取板块集合下的子板块列表 :param market: 市场标识,注意这里不区分沪,深,输入沪或者深都会返回沪深市场的子板块(这个是和客户端保持一致的)参见Market :param plate_class: 板块分类,参见Plate :return: ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下 ret != RET_OK 返回错误字符串 ...
[ "def", "get_plate_list", "(", "self", ",", "market", ",", "plate_class", ")", ":", "param_table", "=", "{", "'market'", ":", "market", ",", "'plate_class'", ":", "plate_class", "}", "for", "x", "in", "param_table", ":", "param", "=", "param_table", "[", "x...
获取板块集合下的子板块列表 :param market: 市场标识,注意这里不区分沪,深,输入沪或者深都会返回沪深市场的子板块(这个是和客户端保持一致的)参见Market :param plate_class: 板块分类,参见Plate :return: ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下 ret != RET_OK 返回错误字符串 ===================== =========== ================...
[ "获取板块集合下的子板块列表" ]
python
train
thomasdelaet/python-velbus
velbus/messages/module_subtype.py
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/module_subtype.py#L50-L59
def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['sub_1'] = self.sub_address_1 json_dict['sub_2'] = self.sub_address_2 json_dict['sub_3'] = self.sub_address_3 json_dict['sub_4'] = self.sub_address_4 return json.dum...
[ "def", "to_json", "(", "self", ")", ":", "json_dict", "=", "self", ".", "to_json_basic", "(", ")", "json_dict", "[", "'sub_1'", "]", "=", "self", ".", "sub_address_1", "json_dict", "[", "'sub_2'", "]", "=", "self", ".", "sub_address_2", "json_dict", "[", ...
:return: str
[ ":", "return", ":", "str" ]
python
train
rocky/python3-trepan
trepan/processor/cmdproc.py
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/cmdproc.py#L107-L112
def run_hooks(obj, hooks, *args): """Run each function in `hooks' with args""" for hook in hooks: if hook(obj, *args): return True pass return False
[ "def", "run_hooks", "(", "obj", ",", "hooks", ",", "*", "args", ")", ":", "for", "hook", "in", "hooks", ":", "if", "hook", "(", "obj", ",", "*", "args", ")", ":", "return", "True", "pass", "return", "False" ]
Run each function in `hooks' with args
[ "Run", "each", "function", "in", "hooks", "with", "args" ]
python
test
pyviz/imagen
imagen/__init__.py
https://github.com/pyviz/imagen/blob/53c5685c880f54b42795964d8db50b02e8590e88/imagen/__init__.py#L1122-L1132
def _setup_xy(self, p): """ Produce pattern coordinate matrices from the bounds and density (or rows and cols), and transforms them according to x, y, and orientation. """ self.debug("bounds=%s, xdensity=%s, ydensity=%s, x=%s, y=%s, orientation=%s",p.bounds, p.xdensity, p...
[ "def", "_setup_xy", "(", "self", ",", "p", ")", ":", "self", ".", "debug", "(", "\"bounds=%s, xdensity=%s, ydensity=%s, x=%s, y=%s, orientation=%s\"", ",", "p", ".", "bounds", ",", "p", ".", "xdensity", ",", "p", ".", "ydensity", ",", "p", ".", "x", ",", "...
Produce pattern coordinate matrices from the bounds and density (or rows and cols), and transforms them according to x, y, and orientation.
[ "Produce", "pattern", "coordinate", "matrices", "from", "the", "bounds", "and", "density", "(", "or", "rows", "and", "cols", ")", "and", "transforms", "them", "according", "to", "x", "y", "and", "orientation", "." ]
python
train
ensime/ensime-vim
ensime_shared/ensime.py
https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ensime.py#L60-L65
def get_setting(self, key, default): """Returns the value of a Vim variable ``g:ensime_{key}`` if it is set, and ``default`` otherwise. """ gkey = "ensime_{}".format(key) return self._vim.vars.get(gkey, default)
[ "def", "get_setting", "(", "self", ",", "key", ",", "default", ")", ":", "gkey", "=", "\"ensime_{}\"", ".", "format", "(", "key", ")", "return", "self", ".", "_vim", ".", "vars", ".", "get", "(", "gkey", ",", "default", ")" ]
Returns the value of a Vim variable ``g:ensime_{key}`` if it is set, and ``default`` otherwise.
[ "Returns", "the", "value", "of", "a", "Vim", "variable", "g", ":", "ensime_", "{", "key", "}", "if", "it", "is", "set", "and", "default", "otherwise", "." ]
python
train
pazz/alot
alot/helper.py
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/helper.py#L258-L296
def call_cmd(cmdlist, stdin=None): """ get a shell commands output, error message and return value and immediately return. .. warning:: This returns with the first screen content for interactive commands. :param cmdlist: shellcommand to call, already splitted into a list accepted ...
[ "def", "call_cmd", "(", "cmdlist", ",", "stdin", "=", "None", ")", ":", "termenc", "=", "urwid", ".", "util", ".", "detected_encoding", "if", "isinstance", "(", "stdin", ",", "str", ")", ":", "stdin", "=", "stdin", ".", "encode", "(", "termenc", ")", ...
get a shell commands output, error message and return value and immediately return. .. warning:: This returns with the first screen content for interactive commands. :param cmdlist: shellcommand to call, already splitted into a list accepted by :meth:`subprocess.Popen` :ty...
[ "get", "a", "shell", "commands", "output", "error", "message", "and", "return", "value", "and", "immediately", "return", "." ]
python
train
ghukill/pyfc4
pyfc4/models.py
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/models.py#L1785-L1826
def _prep_binary_content(self): ''' Sets delivery method of either payload or header Favors Content-Location header if set Args: None Returns: None: sets attributes in self.binary and headers ''' # nothing present if not self.data and not self.location and 'Content-Location' not in self.resour...
[ "def", "_prep_binary_content", "(", "self", ")", ":", "# nothing present", "if", "not", "self", ".", "data", "and", "not", "self", ".", "location", "and", "'Content-Location'", "not", "in", "self", ".", "resource", ".", "headers", ".", "keys", "(", ")", ":...
Sets delivery method of either payload or header Favors Content-Location header if set Args: None Returns: None: sets attributes in self.binary and headers
[ "Sets", "delivery", "method", "of", "either", "payload", "or", "header", "Favors", "Content", "-", "Location", "header", "if", "set" ]
python
train
blakev/python-syncthing
syncthing/__init__.py
https://github.com/blakev/python-syncthing/blob/a7f4930f86f7543cd96990277945467896fb523d/syncthing/__init__.py#L106-L125
def parse_datetime(s, **kwargs): """ Converts a time-string into a valid :py:class:`~datetime.datetime.DateTime` object. Args: s (str): string to be formatted. ``**kwargs`` is passed directly to :func:`.dateutil_parser`. Returns: :py:class:`~datetime.datetime.D...
[ "def", "parse_datetime", "(", "s", ",", "*", "*", "kwargs", ")", ":", "if", "not", "s", ":", "return", "None", "try", ":", "ret", "=", "dateutil_parser", "(", "s", ",", "*", "*", "kwargs", ")", "except", "(", "OverflowError", ",", "TypeError", ",", ...
Converts a time-string into a valid :py:class:`~datetime.datetime.DateTime` object. Args: s (str): string to be formatted. ``**kwargs`` is passed directly to :func:`.dateutil_parser`. Returns: :py:class:`~datetime.datetime.DateTime`
[ "Converts", "a", "time", "-", "string", "into", "a", "valid", ":", "py", ":", "class", ":", "~datetime", ".", "datetime", ".", "DateTime", "object", "." ]
python
train
ChrisCummins/labm8
cache.py
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/cache.py#L203-L210
def write(self): """ Write contents of cache to disk. """ io.debug("Storing cache '{0}'".format(self.path)) with open(self.path, "w") as file: json.dump(self._data, file, sort_keys=True, indent=2, separators=(',', ': '))
[ "def", "write", "(", "self", ")", ":", "io", ".", "debug", "(", "\"Storing cache '{0}'\"", ".", "format", "(", "self", ".", "path", ")", ")", "with", "open", "(", "self", ".", "path", ",", "\"w\"", ")", "as", "file", ":", "json", ".", "dump", "(", ...
Write contents of cache to disk.
[ "Write", "contents", "of", "cache", "to", "disk", "." ]
python
train
coleifer/irc
irc.py
https://github.com/coleifer/irc/blob/f9d2bd6369aafe6cb0916c9406270ca8ecea2080/irc.py#L199-L209
def handle_registered(self, server): """\ When the connection to the server is registered, send all pending data. """ if not self._registered: self.logger.info('Registered') self._registered = True for data in self._out_buffer: ...
[ "def", "handle_registered", "(", "self", ",", "server", ")", ":", "if", "not", "self", ".", "_registered", ":", "self", ".", "logger", ".", "info", "(", "'Registered'", ")", "self", ".", "_registered", "=", "True", "for", "data", "in", "self", ".", "_o...
\ When the connection to the server is registered, send all pending data.
[ "\\", "When", "the", "connection", "to", "the", "server", "is", "registered", "send", "all", "pending", "data", "." ]
python
test
vladsaveliev/TargQC
targqc/utilz/jsontemplate/_jsontemplate.py
https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L843-L849
def _StrftimeGm(value, unused_context, args): """Convert a timestamp in seconds to a string based on the format string. Returns GM time. """ time_tuple = time.gmtime(value) return _StrftimeHelper(args, time_tuple)
[ "def", "_StrftimeGm", "(", "value", ",", "unused_context", ",", "args", ")", ":", "time_tuple", "=", "time", ".", "gmtime", "(", "value", ")", "return", "_StrftimeHelper", "(", "args", ",", "time_tuple", ")" ]
Convert a timestamp in seconds to a string based on the format string. Returns GM time.
[ "Convert", "a", "timestamp", "in", "seconds", "to", "a", "string", "based", "on", "the", "format", "string", "." ]
python
train
tanghaibao/goatools
goatools/obo_parser.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L94-L99
def _init_obo_version(self, line): """Save obo version and release.""" if line[0:14] == "format-version": self.format_version = line[16:-1] if line[0:12] == "data-version": self.data_version = line[14:-1]
[ "def", "_init_obo_version", "(", "self", ",", "line", ")", ":", "if", "line", "[", "0", ":", "14", "]", "==", "\"format-version\"", ":", "self", ".", "format_version", "=", "line", "[", "16", ":", "-", "1", "]", "if", "line", "[", "0", ":", "12", ...
Save obo version and release.
[ "Save", "obo", "version", "and", "release", "." ]
python
train
Telefonica/toolium
toolium/utils.py
https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/utils.py#L80-L97
def save_webdriver_logs(self, test_name): """Get webdriver logs and write them to log files :param test_name: test that has generated these logs """ try: log_types = self.driver_wrapper.driver.log_types except Exception: # geckodriver does not implement l...
[ "def", "save_webdriver_logs", "(", "self", ",", "test_name", ")", ":", "try", ":", "log_types", "=", "self", ".", "driver_wrapper", ".", "driver", ".", "log_types", "except", "Exception", ":", "# geckodriver does not implement log_types, but it implements get_log for clie...
Get webdriver logs and write them to log files :param test_name: test that has generated these logs
[ "Get", "webdriver", "logs", "and", "write", "them", "to", "log", "files" ]
python
train
tanghaibao/goatools
goatools/cli/find_enrichment.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/find_enrichment.py#L392-L407
def _init_objaartall(self): """Get background database info for making ASCII art.""" kws = { 'sortgo':lambda nt: [nt.NS, nt.dcnt], # fmtgo=('{p_fdr_bh:8.2e} {GO} ' # Formatting for GO terms in grouped GO list 'fmtgo':('{hdr1usr01:2} {NS} {GO} {s_fdr_bh:8} ...
[ "def", "_init_objaartall", "(", "self", ")", ":", "kws", "=", "{", "'sortgo'", ":", "lambda", "nt", ":", "[", "nt", ".", "NS", ",", "nt", ".", "dcnt", "]", ",", "# fmtgo=('{p_fdr_bh:8.2e} {GO} '", "# Formatting for GO terms in grouped GO list", "'fmtgo'", ":", ...
Get background database info for making ASCII art.
[ "Get", "background", "database", "info", "for", "making", "ASCII", "art", "." ]
python
train
tritemio/PyBroMo
pybromo/timestamps.py
https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/timestamps.py#L68-L84
def populations_diff_coeff(particles, populations): """Diffusion coefficients of the two specified populations. """ D_counts = particles.diffusion_coeff_counts if len(D_counts) == 1: pop_sizes = [pop.stop - pop.start for pop in populations] assert D_counts[0][1] >= sum(pop_sizes) ...
[ "def", "populations_diff_coeff", "(", "particles", ",", "populations", ")", ":", "D_counts", "=", "particles", ".", "diffusion_coeff_counts", "if", "len", "(", "D_counts", ")", "==", "1", ":", "pop_sizes", "=", "[", "pop", ".", "stop", "-", "pop", ".", "st...
Diffusion coefficients of the two specified populations.
[ "Diffusion", "coefficients", "of", "the", "two", "specified", "populations", "." ]
python
valid
mrtazz/notifo.py
notifo/notifo.py
https://github.com/mrtazz/notifo.py/blob/26079db3b40c26661155af20a9f16a0eca06dbde/notifo/notifo.py#L25-L31
def subscribe_user(self, user): """ method to subscribe a user to a service """ url = self.root_url + "subscribe_user" values = {} values["username"] = user return self._query(url, values)
[ "def", "subscribe_user", "(", "self", ",", "user", ")", ":", "url", "=", "self", ".", "root_url", "+", "\"subscribe_user\"", "values", "=", "{", "}", "values", "[", "\"username\"", "]", "=", "user", "return", "self", ".", "_query", "(", "url", ",", "va...
method to subscribe a user to a service
[ "method", "to", "subscribe", "a", "user", "to", "a", "service" ]
python
test
pmbarrett314/curses-menu
cursesmenu/items/command_item.py
https://github.com/pmbarrett314/curses-menu/blob/c76fc00ab9d518eab275e55434fc2941f49c6b30/cursesmenu/items/command_item.py#L27-L36
def action(self): """ This class overrides this method """ commandline = "{0} {1}".format(self.command, " ".join(self.arguments)) try: completed_process = subprocess.run(commandline, shell=True) self.exit_status = completed_process.returncode excep...
[ "def", "action", "(", "self", ")", ":", "commandline", "=", "\"{0} {1}\"", ".", "format", "(", "self", ".", "command", ",", "\" \"", ".", "join", "(", "self", ".", "arguments", ")", ")", "try", ":", "completed_process", "=", "subprocess", ".", "run", "...
This class overrides this method
[ "This", "class", "overrides", "this", "method" ]
python
test
jtwhite79/pyemu
pyemu/sc.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/sc.py#L155-L178
def map_forecast_estimate(self): """ get the prior and posterior forecast (prediction) expectations. Returns ------- pandas.DataFrame : pandas.DataFrame dataframe with prior and posterior forecast expected values """ assert self.forecasts is not None ...
[ "def", "map_forecast_estimate", "(", "self", ")", ":", "assert", "self", ".", "forecasts", "is", "not", "None", "islog", "=", "self", ".", "pst", ".", "parameter_data", ".", "partrans", "==", "\"log\"", "par_map", "=", "self", ".", "map_parameter_estimate", ...
get the prior and posterior forecast (prediction) expectations. Returns ------- pandas.DataFrame : pandas.DataFrame dataframe with prior and posterior forecast expected values
[ "get", "the", "prior", "and", "posterior", "forecast", "(", "prediction", ")", "expectations", "." ]
python
train
Atomistica/atomistica
src/python/atomistica/mdcore_io.py
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/mdcore_io.py#L39-L161
def read_atoms(fn, cycfn=None, pos_only=False, conv=1.0): """ Read atom information from an atoms.dat file (i.e., tblmd, MDCORE input file) """ f = paropen(fn, "r") l = f.readline().lstrip() while len(l) > 0 and ( l[0] == '#' or l[0] == '<' ): l = f.readline().lstrip() n_atoms = in...
[ "def", "read_atoms", "(", "fn", ",", "cycfn", "=", "None", ",", "pos_only", "=", "False", ",", "conv", "=", "1.0", ")", ":", "f", "=", "paropen", "(", "fn", ",", "\"r\"", ")", "l", "=", "f", ".", "readline", "(", ")", ".", "lstrip", "(", ")", ...
Read atom information from an atoms.dat file (i.e., tblmd, MDCORE input file)
[ "Read", "atom", "information", "from", "an", "atoms", ".", "dat", "file", "(", "i", ".", "e", ".", "tblmd", "MDCORE", "input", "file", ")" ]
python
train
adafruit/Adafruit_Python_GPIO
Adafruit_GPIO/FT232H.py
https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L829-L843
def readRaw8(self): """Read an 8-bit value on the bus (without register).""" self._idle() self._transaction_start() self._i2c_start() self._i2c_write_bytes([self._address_byte(False)]) self._i2c_stop() self._i2c_idle() self._i2c_start() self._i2c_w...
[ "def", "readRaw8", "(", "self", ")", ":", "self", ".", "_idle", "(", ")", "self", ".", "_transaction_start", "(", ")", "self", ".", "_i2c_start", "(", ")", "self", ".", "_i2c_write_bytes", "(", "[", "self", ".", "_address_byte", "(", "False", ")", "]",...
Read an 8-bit value on the bus (without register).
[ "Read", "an", "8", "-", "bit", "value", "on", "the", "bus", "(", "without", "register", ")", "." ]
python
valid
MrMinimal64/timezonefinder
timezonefinder/timezonefinder.py
https://github.com/MrMinimal64/timezonefinder/blob/96cc43afb3bae57ffd002ab4cf104fe15eda2257/timezonefinder/timezonefinder.py#L491-L528
def certain_timezone_at(self, *, lng, lat): """ this function looks up in which polygon the point certainly is included this is much slower than 'timezone_at'! :param lng: longitude of the point in degree :param lat: latitude in degree :return: the timezone name of the po...
[ "def", "certain_timezone_at", "(", "self", ",", "*", ",", "lng", ",", "lat", ")", ":", "lng", ",", "lat", "=", "rectify_coordinates", "(", "lng", ",", "lat", ")", "shortcut_id_x", ",", "shortcut_id_y", "=", "coord2shortcut", "(", "lng", ",", "lat", ")", ...
this function looks up in which polygon the point certainly is included this is much slower than 'timezone_at'! :param lng: longitude of the point in degree :param lat: latitude in degree :return: the timezone name of the polygon the point is included in or None
[ "this", "function", "looks", "up", "in", "which", "polygon", "the", "point", "certainly", "is", "included", "this", "is", "much", "slower", "than", "timezone_at", "!", ":", "param", "lng", ":", "longitude", "of", "the", "point", "in", "degree", ":", "param...
python
train
kensho-technologies/graphql-compiler
graphql_compiler/compiler/ir_sanity_checks.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/ir_sanity_checks.py#L13-L36
def sanity_check_ir_blocks_from_frontend(ir_blocks, query_metadata_table): """Assert that IR blocks originating from the frontend do not have nonsensical structure. Args: ir_blocks: list of BasicBlocks representing the IR to sanity-check Raises: AssertionError, if the IR has unexpected str...
[ "def", "sanity_check_ir_blocks_from_frontend", "(", "ir_blocks", ",", "query_metadata_table", ")", ":", "if", "not", "ir_blocks", ":", "raise", "AssertionError", "(", "u'Received no ir_blocks: {}'", ".", "format", "(", "ir_blocks", ")", ")", "_sanity_check_fold_scope_loca...
Assert that IR blocks originating from the frontend do not have nonsensical structure. Args: ir_blocks: list of BasicBlocks representing the IR to sanity-check Raises: AssertionError, if the IR has unexpected structure. If the IR produced by the front-end cannot be successfully and cor...
[ "Assert", "that", "IR", "blocks", "originating", "from", "the", "frontend", "do", "not", "have", "nonsensical", "structure", "." ]
python
train
h2oai/h2o-3
h2o-py/h2o/utils/typechecks.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/utils/typechecks.py#L373-L376
def check(self, var): """Return True if the variable matches this type, and False otherwise.""" if self._class is None: self._init() return self._class and self._checker(var, self._class)
[ "def", "check", "(", "self", ",", "var", ")", ":", "if", "self", ".", "_class", "is", "None", ":", "self", ".", "_init", "(", ")", "return", "self", ".", "_class", "and", "self", ".", "_checker", "(", "var", ",", "self", ".", "_class", ")" ]
Return True if the variable matches this type, and False otherwise.
[ "Return", "True", "if", "the", "variable", "matches", "this", "type", "and", "False", "otherwise", "." ]
python
test
swimlane/swimlane-python
swimlane/core/fields/list.py
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/list.py#L88-L142
def _validate_item(self, item): """Validate char/word count""" if not isinstance(item, six.string_types): raise ValidationError( self._record, "Text list field items must be strings, not '{}'".format(item.__class__) ) words = item.split(' ...
[ "def", "_validate_item", "(", "self", ",", "item", ")", ":", "if", "not", "isinstance", "(", "item", ",", "six", ".", "string_types", ")", ":", "raise", "ValidationError", "(", "self", ".", "_record", ",", "\"Text list field items must be strings, not '{}'\"", "...
Validate char/word count
[ "Validate", "char", "/", "word", "count" ]
python
train
a2liu/mr-clean
mr_clean/_utils/io.py
https://github.com/a2liu/mr-clean/blob/0ee4ee5639f834dec4b59b94442fa84373f3c176/mr_clean/_utils/io.py#L38-L44
def get_info(df, verbose = None,max_cols = None, memory_usage = None, null_counts = None): """ Returns the .info() output of a dataframe """ assert type(df) is pd.DataFrame buffer = io.StringIO() df.info(verbose, buffer, max_cols, memory_usage, null_counts) return buffer.getvalue()
[ "def", "get_info", "(", "df", ",", "verbose", "=", "None", ",", "max_cols", "=", "None", ",", "memory_usage", "=", "None", ",", "null_counts", "=", "None", ")", ":", "assert", "type", "(", "df", ")", "is", "pd", ".", "DataFrame", "buffer", "=", "io",...
Returns the .info() output of a dataframe
[ "Returns", "the", ".", "info", "()", "output", "of", "a", "dataframe" ]
python
train
saltstack/salt
salt/modules/dracr.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1081-L1110
def get_slotname(slot, host=None, admin_username=None, admin_password=None): ''' Get the name of a slot number in the chassis. slot The number of the slot for which to obtain the name. host The chassis host. admin_username The username used to access the chassis. admi...
[ "def", "get_slotname", "(", "slot", ",", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ")", ":", "slots", "=", "list_slotnames", "(", "host", "=", "host", ",", "admin_username", "=", "admin_username", ",", "ad...
Get the name of a slot number in the chassis. slot The number of the slot for which to obtain the name. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. cod...
[ "Get", "the", "name", "of", "a", "slot", "number", "in", "the", "chassis", "." ]
python
train
dslackw/slpkg
slpkg/sbo/network.py
https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/sbo/network.py#L338-L349
def fill_pager(self, page): """Fix pager spaces """ tty_size = os.popen("stty size", "r").read().split() rows = int(tty_size[0]) - 1 lines = sum(1 for line in page.splitlines()) diff = rows - lines fill = "\n" * diff if diff > 0: return fill ...
[ "def", "fill_pager", "(", "self", ",", "page", ")", ":", "tty_size", "=", "os", ".", "popen", "(", "\"stty size\"", ",", "\"r\"", ")", ".", "read", "(", ")", ".", "split", "(", ")", "rows", "=", "int", "(", "tty_size", "[", "0", "]", ")", "-", ...
Fix pager spaces
[ "Fix", "pager", "spaces" ]
python
train
exekias/droplet
droplet/samba/module.py
https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/samba/module.py#L42-L82
def install(self): """ Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain """ domain_settings = DomainSettings.get() with root(): if os.path.exists(self.SMBCONF_FILE): os.remove(self.SMBCONF_FILE) ...
[ "def", "install", "(", "self", ")", ":", "domain_settings", "=", "DomainSettings", ".", "get", "(", ")", "with", "root", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "SMBCONF_FILE", ")", ":", "os", ".", "remove", "(", "s...
Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain
[ "Installation", "procedure", "it", "writes", "basic", "smb", ".", "conf", "and", "uses", "samba", "-", "tool", "to", "provision", "the", "domain" ]
python
train
jic-dtool/dtool-info
dtool_info/dataset.py
https://github.com/jic-dtool/dtool-info/blob/3c6c7755f4c142e548bbfdf3b38230612fd4060a/dtool_info/dataset.py#L342-L394
def verify(full, dataset_uri): """Verify the integrity of a dataset. """ dataset = dtoolcore.DataSet.from_uri(dataset_uri) all_okay = True generated_manifest = dataset.generate_manifest() generated_identifiers = set(generated_manifest["items"].keys()) manifest_identifiers = set(dataset.iden...
[ "def", "verify", "(", "full", ",", "dataset_uri", ")", ":", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "dataset_uri", ")", "all_okay", "=", "True", "generated_manifest", "=", "dataset", ".", "generate_manifest", "(", ")", "generated_ide...
Verify the integrity of a dataset.
[ "Verify", "the", "integrity", "of", "a", "dataset", "." ]
python
train
openpermissions/perch
perch/user.py
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L255-L257
def is_reseller(self): """is the user a reseller""" return self.role == self.roles.reseller.value and self.state == State.approved
[ "def", "is_reseller", "(", "self", ")", ":", "return", "self", ".", "role", "==", "self", ".", "roles", ".", "reseller", ".", "value", "and", "self", ".", "state", "==", "State", ".", "approved" ]
is the user a reseller
[ "is", "the", "user", "a", "reseller" ]
python
train
humangeo/rawes
rawes/thrift_connection.py
https://github.com/humangeo/rawes/blob/b860100cbb4115a1c884133c83eae448ded6b2d3/rawes/thrift_connection.py#L94-L101
def _dict_to_map_str_str(self, d): """ Thrift requires the params and headers dict values to only contain str values. """ return dict(map( lambda (k, v): (k, str(v).lower() if isinstance(v, bool) else str(v)), d.iteritems() ))
[ "def", "_dict_to_map_str_str", "(", "self", ",", "d", ")", ":", "return", "dict", "(", "map", "(", "lambda", "(", "k", ",", "v", ")", ":", "(", "k", ",", "str", "(", "v", ")", ".", "lower", "(", ")", "if", "isinstance", "(", "v", ",", "bool", ...
Thrift requires the params and headers dict values to only contain str values.
[ "Thrift", "requires", "the", "params", "and", "headers", "dict", "values", "to", "only", "contain", "str", "values", "." ]
python
train
cackharot/suds-py3
suds/reader.py
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/reader.py#L83-L100
def download(self, url): """ Download the docuemnt. @param url: A document url. @type url: str. @return: A file pointer to the docuemnt. @rtype: file-like """ store = DocumentStore() fp = store.open(url) if fp is None: fp = self...
[ "def", "download", "(", "self", ",", "url", ")", ":", "store", "=", "DocumentStore", "(", ")", "fp", "=", "store", ".", "open", "(", "url", ")", "if", "fp", "is", "None", ":", "fp", "=", "self", ".", "options", ".", "transport", ".", "open", "(",...
Download the docuemnt. @param url: A document url. @type url: str. @return: A file pointer to the docuemnt. @rtype: file-like
[ "Download", "the", "docuemnt", "." ]
python
train
aestrivex/bctpy
bct/algorithms/reference.py
https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/reference.py#L545-L601
def makefractalCIJ(mx_lvl, E, sz_cl, seed=None): ''' This function generates a directed network with a hierarchical modular organization. All modules are fully connected and connection density decays as 1/(E^n), with n = index of hierarchical level. Parameters ---------- mx_lvl : int ...
[ "def", "makefractalCIJ", "(", "mx_lvl", ",", "E", ",", "sz_cl", ",", "seed", "=", "None", ")", ":", "rng", "=", "get_rng", "(", "seed", ")", "# make a stupid little template", "t", "=", "np", ".", "ones", "(", "(", "2", ",", "2", ")", ")", "*", "2"...
This function generates a directed network with a hierarchical modular organization. All modules are fully connected and connection density decays as 1/(E^n), with n = index of hierarchical level. Parameters ---------- mx_lvl : int number of hierarchical levels, N = 2^mx_lvl E : int ...
[ "This", "function", "generates", "a", "directed", "network", "with", "a", "hierarchical", "modular", "organization", ".", "All", "modules", "are", "fully", "connected", "and", "connection", "density", "decays", "as", "1", "/", "(", "E^n", ")", "with", "n", "...
python
train
spacetelescope/stsci.tools
lib/stsci/tools/validate.py
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/validate.py#L1265-L1331
def is_mixed_list(value, *args): """ Check that the value is a list. Allow specifying the type of each member. Work on lists of specific lengths. You specify each member as a positional argument specifying type Each type should be one of the following strings : 'integer', 'float', 'ip_ad...
[ "def", "is_mixed_list", "(", "value", ",", "*", "args", ")", ":", "try", ":", "length", "=", "len", "(", "value", ")", "except", "TypeError", ":", "raise", "VdtTypeError", "(", "value", ")", "if", "length", "<", "len", "(", "args", ")", ":", "raise",...
Check that the value is a list. Allow specifying the type of each member. Work on lists of specific lengths. You specify each member as a positional argument specifying type Each type should be one of the following strings : 'integer', 'float', 'ip_addr', 'string', 'boolean' So you can spec...
[ "Check", "that", "the", "value", "is", "a", "list", ".", "Allow", "specifying", "the", "type", "of", "each", "member", ".", "Work", "on", "lists", "of", "specific", "lengths", "." ]
python
train
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Screen/SSPILScreen.py
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Screen/SSPILScreen.py#L210-L291
def write(self, text="", xy=(0,0), align="left", font=None, fontName=None, fontSize = 10, fill = 1, spacing = 0, screenCenter = False): """! \~english Print one line text or multi-line text on the screen @param text: Text to be drawn. eg. "Hello World!" or "Hello/nWorld!" @param...
[ "def", "write", "(", "self", ",", "text", "=", "\"\"", ",", "xy", "=", "(", "0", ",", "0", ")", ",", "align", "=", "\"left\"", ",", "font", "=", "None", ",", "fontName", "=", "None", ",", "fontSize", "=", "10", ",", "fill", "=", "1", ",", "sp...
! \~english Print one line text or multi-line text on the screen @param text: Text to be drawn. eg. "Hello World!" or "Hello/nWorld!" @param xy: Top left corner of the text. defaule: (0,0) @param align: "left", "center" or "right". defaule: "left" @param fontName: Name o...
[ "!", "\\", "~english", "Print", "one", "line", "text", "or", "multi", "-", "line", "text", "on", "the", "screen", "@param", "text", ":", "Text", "to", "be", "drawn", ".", "eg", ".", "Hello", "World!", "or", "Hello", "/", "nWorld!", "@param", "xy", ":...
python
train
peterdemin/pip-compile-multi
pipcompilemulti/discover.py
https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/discover.py#L46-L62
def order_by_refs(envs): """ Return topologicaly sorted list of environments. I.e. all referenced environments are placed before their references. """ topology = { env['name']: set(env['refs']) for env in envs } by_name = { env['name']: env for env in envs ...
[ "def", "order_by_refs", "(", "envs", ")", ":", "topology", "=", "{", "env", "[", "'name'", "]", ":", "set", "(", "env", "[", "'refs'", "]", ")", "for", "env", "in", "envs", "}", "by_name", "=", "{", "env", "[", "'name'", "]", ":", "env", "for", ...
Return topologicaly sorted list of environments. I.e. all referenced environments are placed before their references.
[ "Return", "topologicaly", "sorted", "list", "of", "environments", ".", "I", ".", "e", ".", "all", "referenced", "environments", "are", "placed", "before", "their", "references", "." ]
python
train
robertpeteuil/multi-cloud-control
mcc/uimode.py
https://github.com/robertpeteuil/multi-cloud-control/blob/f1565af1c0b6ed465ff312d3ccc592ba0609f4a2/mcc/uimode.py#L129-L143
def node_validate(node_dict, node_num, cmd_name): """Validate that command can be performed on target node.""" # cmd: [required-state, action-to-displayed, error-statement] req_lu = {"run": ["stopped", "Already Running"], "stop": ["running", "Already Stopped"], "connect": ["runni...
[ "def", "node_validate", "(", "node_dict", ",", "node_num", ",", "cmd_name", ")", ":", "# cmd: [required-state, action-to-displayed, error-statement]", "req_lu", "=", "{", "\"run\"", ":", "[", "\"stopped\"", ",", "\"Already Running\"", "]", ",", "\"stop\"", ":", "[", ...
Validate that command can be performed on target node.
[ "Validate", "that", "command", "can", "be", "performed", "on", "target", "node", "." ]
python
train
Kozea/cairocffi
cairocffi/context.py
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1839-L1850
def get_font_options(self): """Retrieves font rendering options set via :meth:`set_font_options`. Note that the returned options do not include any options derived from the underlying surface; they are literally the options passed to :meth:`set_font_options`. :return: A new :cla...
[ "def", "get_font_options", "(", "self", ")", ":", "font_options", "=", "FontOptions", "(", ")", "cairo", ".", "cairo_get_font_options", "(", "self", ".", "_pointer", ",", "font_options", ".", "_pointer", ")", "return", "font_options" ]
Retrieves font rendering options set via :meth:`set_font_options`. Note that the returned options do not include any options derived from the underlying surface; they are literally the options passed to :meth:`set_font_options`. :return: A new :class:`FontOptions` object.
[ "Retrieves", "font", "rendering", "options", "set", "via", ":", "meth", ":", "set_font_options", ".", "Note", "that", "the", "returned", "options", "do", "not", "include", "any", "options", "derived", "from", "the", "underlying", "surface", ";", "they", "are",...
python
train
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_net_command_factory_xml.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_net_command_factory_xml.py#L179-L211
def make_thread_stack_str(self, frame, frame_id_to_lineno=None): ''' :param frame_id_to_lineno: If available, the line number for the frame will be gotten from this dict, otherwise frame.f_lineno will be used (needed for unhandled exceptions as the place where we repo...
[ "def", "make_thread_stack_str", "(", "self", ",", "frame", ",", "frame_id_to_lineno", "=", "None", ")", ":", "if", "frame_id_to_lineno", "is", "None", ":", "frame_id_to_lineno", "=", "{", "}", "make_valid_xml_value", "=", "pydevd_xml", ".", "make_valid_xml_value", ...
:param frame_id_to_lineno: If available, the line number for the frame will be gotten from this dict, otherwise frame.f_lineno will be used (needed for unhandled exceptions as the place where we report may be different from the place where it's raised).
[ ":", "param", "frame_id_to_lineno", ":", "If", "available", "the", "line", "number", "for", "the", "frame", "will", "be", "gotten", "from", "this", "dict", "otherwise", "frame", ".", "f_lineno", "will", "be", "used", "(", "needed", "for", "unhandled", "excep...
python
train
googlefonts/fontbakery
Lib/fontbakery/checkrunner.py
https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/checkrunner.py#L1363-L1415
def _load_profile_imports(self, symbol_table): """ profile_imports is a list of module names or tuples of (module_name, names to import) in the form of ('.', names) it behaces like: from . import name1, name2, name3 or similarly import .name1, .name2, .name3 i.e. "name" in names becomes...
[ "def", "_load_profile_imports", "(", "self", ",", "symbol_table", ")", ":", "results", "=", "[", "]", "if", "'profile_imports'", "not", "in", "symbol_table", ":", "return", "results", "package", "=", "self", ".", "_get_package", "(", "symbol_table", ")", "prof...
profile_imports is a list of module names or tuples of (module_name, names to import) in the form of ('.', names) it behaces like: from . import name1, name2, name3 or similarly import .name1, .name2, .name3 i.e. "name" in names becomes ".name"
[ "profile_imports", "is", "a", "list", "of", "module", "names", "or", "tuples", "of", "(", "module_name", "names", "to", "import", ")", "in", "the", "form", "of", "(", ".", "names", ")", "it", "behaces", "like", ":", "from", ".", "import", "name1", "nam...
python
train
marshmallow-code/marshmallow
src/marshmallow/schema.py
https://github.com/marshmallow-code/marshmallow/blob/a6b6c4151f1fbf16f3774d4052ca2bddf6903750/src/marshmallow/schema.py#L561-L577
def dumps(self, obj, many=None, *args, **kwargs): """Same as :meth:`dump`, except return a JSON-encoded string. :param obj: The object to serialize. :param bool many: Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used. :return: A ``json`...
[ "def", "dumps", "(", "self", ",", "obj", ",", "many", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "serialized", "=", "self", ".", "dump", "(", "obj", ",", "many", "=", "many", ")", "return", "self", ".", "opts", ".", "rend...
Same as :meth:`dump`, except return a JSON-encoded string. :param obj: The object to serialize. :param bool many: Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used. :return: A ``json`` string :rtype: str .. versionadded:: 1.0.0...
[ "Same", "as", ":", "meth", ":", "dump", "except", "return", "a", "JSON", "-", "encoded", "string", "." ]
python
train
ixc/python-edtf
edtf/jdutil.py
https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/jdutil.py#L274-L298
def datetime_to_jd(date): """ Convert a `datetime.datetime` object to Julian Day. Parameters ---------- date : `datetime.datetime` instance Returns ------- jd : float Julian day. Examples -------- >>> d = datetime.datetime(1985,2,17,6) >>> d datetime.date...
[ "def", "datetime_to_jd", "(", "date", ")", ":", "days", "=", "date", ".", "day", "+", "hmsm_to_days", "(", "date", ".", "hour", ",", "date", ".", "minute", ",", "date", ".", "second", ",", "date", ".", "microsecond", ")", "return", "date_to_jd", "(", ...
Convert a `datetime.datetime` object to Julian Day. Parameters ---------- date : `datetime.datetime` instance Returns ------- jd : float Julian day. Examples -------- >>> d = datetime.datetime(1985,2,17,6) >>> d datetime.datetime(1985, 2, 17, 6, 0) >>> jdutil...
[ "Convert", "a", "datetime", ".", "datetime", "object", "to", "Julian", "Day", "." ]
python
train
Microsoft/ApplicationInsights-Python
applicationinsights/channel/contracts/StackFrame.py
https://github.com/Microsoft/ApplicationInsights-Python/blob/8452ab7126f9bb6964637d4aa1258c2af17563d6/applicationinsights/channel/contracts/StackFrame.py#L73-L82
def assembly(self, value): """The assembly property. Args: value (string). the property value. """ if value == self._defaults['assembly'] and 'assembly' in self._values: del self._values['assembly'] else: self._values['assembly'] = val...
[ "def", "assembly", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'assembly'", "]", "and", "'assembly'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'assembly'", "]", "else", ":", ...
The assembly property. Args: value (string). the property value.
[ "The", "assembly", "property", ".", "Args", ":", "value", "(", "string", ")", ".", "the", "property", "value", "." ]
python
train
mattupstate/flask-security
flask_security/views.py
https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L102-L139
def register(): """View function which handles a registration request.""" if _security.confirmable or request.is_json: form_class = _security.confirm_register_form else: form_class = _security.register_form if request.is_json: form_data = MultiDict(request.get_json()) else:...
[ "def", "register", "(", ")", ":", "if", "_security", ".", "confirmable", "or", "request", ".", "is_json", ":", "form_class", "=", "_security", ".", "confirm_register_form", "else", ":", "form_class", "=", "_security", ".", "register_form", "if", "request", "."...
View function which handles a registration request.
[ "View", "function", "which", "handles", "a", "registration", "request", "." ]
python
train
tradenity/python-sdk
tradenity/resources/cancel_operation.py
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/cancel_operation.py#L344-L364
def delete_cancel_operation_by_id(cls, cancel_operation_id, **kwargs): """Delete CancelOperation Delete an instance of CancelOperation by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = ap...
[ "def", "delete_cancel_operation_by_id", "(", "cls", ",", "cancel_operation_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_dele...
Delete CancelOperation Delete an instance of CancelOperation by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_cancel_operation_by_id(cancel_operation_id, async=True) >>> resul...
[ "Delete", "CancelOperation" ]
python
train
croscon/fleaker
fleaker/peewee/mixins/event.py
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L485-L515
def parse_meta(self, meta): """Parses the meta field in the message, copies it's keys into a new dict and replaces the values, which should be attribute paths relative to the passed in object, with the current value at the end of that path. This function will run recursively when it enco...
[ "def", "parse_meta", "(", "self", ",", "meta", ")", ":", "res", "=", "{", "}", "for", "key", ",", "val", "in", "meta", ".", "items", "(", ")", ":", "if", "not", "val", ":", "continue", "elif", "isinstance", "(", "val", ",", "dict", ")", ":", "r...
Parses the meta field in the message, copies it's keys into a new dict and replaces the values, which should be attribute paths relative to the passed in object, with the current value at the end of that path. This function will run recursively when it encounters other dicts inside the m...
[ "Parses", "the", "meta", "field", "in", "the", "message", "copies", "it", "s", "keys", "into", "a", "new", "dict", "and", "replaces", "the", "values", "which", "should", "be", "attribute", "paths", "relative", "to", "the", "passed", "in", "object", "with",...
python
train
CZ-NIC/yangson
yangson/instance.py
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L1043-L1064
def _key_values(self, sn: "SequenceNode") -> Union[EntryKeys, EntryValue]: """Parse leaf-list value or list keys.""" try: keys = self.up_to("/") except EndOfInput: keys = self.remaining() if not keys: raise UnexpectedInput(self, "entry value or keys") ...
[ "def", "_key_values", "(", "self", ",", "sn", ":", "\"SequenceNode\"", ")", "->", "Union", "[", "EntryKeys", ",", "EntryValue", "]", ":", "try", ":", "keys", "=", "self", ".", "up_to", "(", "\"/\"", ")", "except", "EndOfInput", ":", "keys", "=", "self"...
Parse leaf-list value or list keys.
[ "Parse", "leaf", "-", "list", "value", "or", "list", "keys", "." ]
python
train
fjwCode/cerium
cerium/androiddriver.py
https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L198-L202
def get_cpu_info(self) -> str: '''Show device CPU information.''' output, _ = self._execute( '-s', self.device_sn, 'shell', 'cat', '/proc/cpuinfo') return output
[ "def", "get_cpu_info", "(", "self", ")", "->", "str", ":", "output", ",", "_", "=", "self", ".", "_execute", "(", "'-s'", ",", "self", ".", "device_sn", ",", "'shell'", ",", "'cat'", ",", "'/proc/cpuinfo'", ")", "return", "output" ]
Show device CPU information.
[ "Show", "device", "CPU", "information", "." ]
python
train
abe-winter/pg13-py
pg13/weval.py
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/weval.py#L81-L91
def wherex_to_rowlist(scope_, fromx, wherex): """return a RowList with the rows included from scope by the fromx and wherex. When the scope has more than one name in it, the output will be a list of composite row (i.e. a row whose field types are themselves RowType). """ single, multi = classify_wherex(scop...
[ "def", "wherex_to_rowlist", "(", "scope_", ",", "fromx", ",", "wherex", ")", ":", "single", ",", "multi", "=", "classify_wherex", "(", "scope_", ",", "fromx", ",", "wherex", ")", "single_rowlists", "=", "{", "tablename", ":", "table_to_rowlist", "(", "scope_...
return a RowList with the rows included from scope by the fromx and wherex. When the scope has more than one name in it, the output will be a list of composite row (i.e. a row whose field types are themselves RowType).
[ "return", "a", "RowList", "with", "the", "rows", "included", "from", "scope", "by", "the", "fromx", "and", "wherex", ".", "When", "the", "scope", "has", "more", "than", "one", "name", "in", "it", "the", "output", "will", "be", "a", "list", "of", "compo...
python
train
aio-libs/aiomysql
aiomysql/connection.py
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/connection.py#L1320-L1340
async def send_data(self): """Send data packets from the local file to the server""" self.connection._ensure_alive() conn = self.connection try: await self._open_file() with self._file_object: chunk_size = MAX_PACKET_LEN while True...
[ "async", "def", "send_data", "(", "self", ")", ":", "self", ".", "connection", ".", "_ensure_alive", "(", ")", "conn", "=", "self", ".", "connection", "try", ":", "await", "self", ".", "_open_file", "(", ")", "with", "self", ".", "_file_object", ":", "...
Send data packets from the local file to the server
[ "Send", "data", "packets", "from", "the", "local", "file", "to", "the", "server" ]
python
train
Julian/Compares
compares.py
https://github.com/Julian/Compares/blob/4a848240b3bca69238fef832bdbe37059ee2ae6c/compares.py#L10-L63
def via(fields): """ Define the fields (attributes) to use for instance comparison and repr. Creates ``__eq__``\ , ``__ne__`` and ``__repr__`` methods for the decorated class, along with a private ``_contents`` property which simply returns the fields provided with associated values on the inst...
[ "def", "via", "(", "fields", ")", ":", "def", "add_methods", "(", "cls", ")", ":", "nothing", "=", "object", "(", ")", "if", "getattr", "(", "cls", ",", "\"fields\"", ",", "nothing", ")", "is", "nothing", ":", "cls", ".", "fields", "=", "tuple", "(...
Define the fields (attributes) to use for instance comparison and repr. Creates ``__eq__``\ , ``__ne__`` and ``__repr__`` methods for the decorated class, along with a private ``_contents`` property which simply returns the fields provided with associated values on the instance, and a ``fields`` attrib...
[ "Define", "the", "fields", "(", "attributes", ")", "to", "use", "for", "instance", "comparison", "and", "repr", "." ]
python
train
kennethreitz/requests-html
requests_html.py
https://github.com/kennethreitz/requests-html/blob/b59a9f2fb9333d7d467154a0fd82978efdb9d23b/requests_html.py#L767-L775
def run(self, *coros): """ Pass in all the coroutines you want to run, it will wrap each one in a task, run it and wait for the result. Return a list with all results, this is returned in the same order coros are passed in. """ tasks = [ asyncio.ensure_future(coro()) ...
[ "def", "run", "(", "self", ",", "*", "coros", ")", ":", "tasks", "=", "[", "asyncio", ".", "ensure_future", "(", "coro", "(", ")", ")", "for", "coro", "in", "coros", "]", "done", ",", "_", "=", "self", ".", "loop", ".", "run_until_complete", "(", ...
Pass in all the coroutines you want to run, it will wrap each one in a task, run it and wait for the result. Return a list with all results, this is returned in the same order coros are passed in.
[ "Pass", "in", "all", "the", "coroutines", "you", "want", "to", "run", "it", "will", "wrap", "each", "one", "in", "a", "task", "run", "it", "and", "wait", "for", "the", "result", ".", "Return", "a", "list", "with", "all", "results", "this", "is", "ret...
python
train
chaoss/grimoirelab-perceval
perceval/backends/core/mediawiki.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/mediawiki.py#L250-L364
def __fetch_pre1_27(self, from_date=None): """Fetch the pages from the backend url. The method retrieves, from a MediaWiki url, the wiki pages. :returns: a generator of pages """ def fetch_incremental_changes(namespaces_contents): # Use recent changes API t...
[ "def", "__fetch_pre1_27", "(", "self", ",", "from_date", "=", "None", ")", ":", "def", "fetch_incremental_changes", "(", "namespaces_contents", ")", ":", "# Use recent changes API to get the pages from date", "npages", "=", "0", "# number of pages processed", "tpages", "=...
Fetch the pages from the backend url. The method retrieves, from a MediaWiki url, the wiki pages. :returns: a generator of pages
[ "Fetch", "the", "pages", "from", "the", "backend", "url", "." ]
python
test
scanny/python-pptx
pptx/chart/xmlwriter.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/xmlwriter.py#L1647-L1658
def xVal_xml(self): """ Return the ``<c:xVal>`` element for this series as unicode text. This element contains the X values for this series. """ return self._xVal_tmpl.format(**{ 'nsdecls': '', 'numRef_xml': self.numRef_xml( self._series...
[ "def", "xVal_xml", "(", "self", ")", ":", "return", "self", ".", "_xVal_tmpl", ".", "format", "(", "*", "*", "{", "'nsdecls'", ":", "''", ",", "'numRef_xml'", ":", "self", ".", "numRef_xml", "(", "self", ".", "_series", ".", "x_values_ref", ",", "self"...
Return the ``<c:xVal>`` element for this series as unicode text. This element contains the X values for this series.
[ "Return", "the", "<c", ":", "xVal", ">", "element", "for", "this", "series", "as", "unicode", "text", ".", "This", "element", "contains", "the", "X", "values", "for", "this", "series", "." ]
python
train
sephii/taxi-zebra
taxi_zebra/commands.py
https://github.com/sephii/taxi-zebra/blob/36affa22d4167e7ce5a8c7c6eaf5adc4cbfcfb5d/taxi_zebra/commands.py#L55-L79
def balance(ctx): """ Show Zebra balance. Like the hours balance, vacation left, etc. """ backend = plugins_registry.get_backends_by_class(ZebraBackend)[0] timesheet_collection = get_timesheet_collection_for_context(ctx, None) hours_to_be_pushed = timesheet_collection.get_hours(pushed=Fals...
[ "def", "balance", "(", "ctx", ")", ":", "backend", "=", "plugins_registry", ".", "get_backends_by_class", "(", "ZebraBackend", ")", "[", "0", "]", "timesheet_collection", "=", "get_timesheet_collection_for_context", "(", "ctx", ",", "None", ")", "hours_to_be_pushed"...
Show Zebra balance. Like the hours balance, vacation left, etc.
[ "Show", "Zebra", "balance", "." ]
python
valid
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L143-L170
def found_check(): """ Temporarily enables spiceypy default behavior which raises exceptions for false found flags for certain spice functions. All spice functions executed within the context manager will check the found flag return parameter and the found flag will be removed from the return for ...
[ "def", "found_check", "(", ")", ":", "current_catch_state", "=", "config", ".", "catch_false_founds", "config", ".", "catch_false_founds", "=", "True", "yield", "config", ".", "catch_false_founds", "=", "current_catch_state" ]
Temporarily enables spiceypy default behavior which raises exceptions for false found flags for certain spice functions. All spice functions executed within the context manager will check the found flag return parameter and the found flag will be removed from the return for the given function. For E...
[ "Temporarily", "enables", "spiceypy", "default", "behavior", "which", "raises", "exceptions", "for", "false", "found", "flags", "for", "certain", "spice", "functions", ".", "All", "spice", "functions", "executed", "within", "the", "context", "manager", "will", "ch...
python
train
ctuning/ck
ck/kernel.py
https://github.com/ctuning/ck/blob/7e009814e975f8742790d3106340088a46223714/ck/kernel.py#L1597-L1629
def dump_json(i): """ Input: { dict - dictionary (skip_indent) - if 'yes', skip indent (sort_keys) - if 'yes', sort keys } Output: { return - return code = 0, if successful > 0, ...
[ "def", "dump_json", "(", "i", ")", ":", "d", "=", "i", "[", "'dict'", "]", "si", "=", "i", ".", "get", "(", "'skip_indent'", ",", "''", ")", "sk", "=", "False", "if", "i", ".", "get", "(", "'sort_keys'", ",", "''", ")", "==", "'yes'", ":", "s...
Input: { dict - dictionary (skip_indent) - if 'yes', skip indent (sort_keys) - if 'yes', sort keys } Output: { return - return code = 0, if successful > 0, if error string...
[ "Input", ":", "{", "dict", "-", "dictionary", "(", "skip_indent", ")", "-", "if", "yes", "skip", "indent", "(", "sort_keys", ")", "-", "if", "yes", "sort", "keys", "}" ]
python
train
tornadoweb/tornado
tornado/auth.py
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/auth.py#L605-L659
async def oauth2_request( self, url: str, access_token: str = None, post_args: Dict[str, Any] = None, **args: Any ) -> Any: """Fetches the given URL auth an OAuth2 access token. If the request is a POST, ``post_args`` should be provided. Query string ...
[ "async", "def", "oauth2_request", "(", "self", ",", "url", ":", "str", ",", "access_token", ":", "str", "=", "None", ",", "post_args", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "*", "*", "args", ":", "Any", ")", "->", "Any", ":"...
Fetches the given URL auth an OAuth2 access token. If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as keyword arguments. Example usage: ..testcode:: class MainHandler(tornado.web.RequestHandler, ...
[ "Fetches", "the", "given", "URL", "auth", "an", "OAuth2", "access", "token", "." ]
python
train
Fizzadar/pyinfra
pyinfra/api/util.py
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/util.py#L227-L233
def underscore(name): ''' Transform CamelCase -> snake_case. ''' s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
[ "def", "underscore", "(", "name", ")", ":", "s1", "=", "re", ".", "sub", "(", "'(.)([A-Z][a-z]+)'", ",", "r'\\1_\\2'", ",", "name", ")", "return", "re", ".", "sub", "(", "'([a-z0-9])([A-Z])'", ",", "r'\\1_\\2'", ",", "s1", ")", ".", "lower", "(", ")" ]
Transform CamelCase -> snake_case.
[ "Transform", "CamelCase", "-", ">", "snake_case", "." ]
python
train
adafruit/Adafruit_Python_LED_Backpack
Adafruit_LED_Backpack/HT16K33.py
https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/HT16K33.py#L69-L75
def set_brightness(self, brightness): """Set brightness of entire display to specified value (16 levels, from 0 to 15). """ if brightness < 0 or brightness > 15: raise ValueError('Brightness must be a value of 0 to 15.') self._device.writeList(HT16K33_CMD_BRIGHTNESS |...
[ "def", "set_brightness", "(", "self", ",", "brightness", ")", ":", "if", "brightness", "<", "0", "or", "brightness", ">", "15", ":", "raise", "ValueError", "(", "'Brightness must be a value of 0 to 15.'", ")", "self", ".", "_device", ".", "writeList", "(", "HT...
Set brightness of entire display to specified value (16 levels, from 0 to 15).
[ "Set", "brightness", "of", "entire", "display", "to", "specified", "value", "(", "16", "levels", "from", "0", "to", "15", ")", "." ]
python
train
HewlettPackard/python-hpOneView
hpOneView/resources/servers/server_hardware.py
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/servers/server_hardware.py#L89-L105
def remove(self, force=False, timeout=-1): """ Removes the rackserver with the specified URI. Note: This operation is only supported on appliances that support rack-mounted servers. Args: force (bool): If set to true, the operation completes despite any probl...
[ "def", "remove", "(", "self", ",", "force", "=", "False", ",", "timeout", "=", "-", "1", ")", ":", "return", "self", ".", "delete", "(", "force", "=", "force", ",", "timeout", "=", "timeout", ")" ]
Removes the rackserver with the specified URI. Note: This operation is only supported on appliances that support rack-mounted servers. Args: force (bool): If set to true, the operation completes despite any problems with network connectivity or errors on the ...
[ "Removes", "the", "rackserver", "with", "the", "specified", "URI", ".", "Note", ":", "This", "operation", "is", "only", "supported", "on", "appliances", "that", "support", "rack", "-", "mounted", "servers", "." ]
python
train
saltstack/salt
salt/utils/cloud.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cloud.py#L3184-L3208
def _salt_cloud_force_ascii(exc): ''' Helper method to try its best to convert any Unicode text into ASCII without stack tracing since salt internally does not handle Unicode strings This method is not supposed to be used directly. Once `py:module: salt.utils.cloud` is imported this method register...
[ "def", "_salt_cloud_force_ascii", "(", "exc", ")", ":", "if", "not", "isinstance", "(", "exc", ",", "(", "UnicodeEncodeError", ",", "UnicodeTranslateError", ")", ")", ":", "raise", "TypeError", "(", "'Can\\'t handle {0}'", ".", "format", "(", "exc", ")", ")", ...
Helper method to try its best to convert any Unicode text into ASCII without stack tracing since salt internally does not handle Unicode strings This method is not supposed to be used directly. Once `py:module: salt.utils.cloud` is imported this method register's with python's codecs module for proper ...
[ "Helper", "method", "to", "try", "its", "best", "to", "convert", "any", "Unicode", "text", "into", "ASCII", "without", "stack", "tracing", "since", "salt", "internally", "does", "not", "handle", "Unicode", "strings" ]
python
train
openstack/proliantutils
proliantutils/redfish/redfish.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/redfish.py#L493-L499
def _is_boot_mode_uefi(self): """Checks if the system is in uefi boot mode. :return: 'True' if the boot mode is uefi else 'False' """ boot_mode = self.get_current_boot_mode() return (boot_mode == BOOT_MODE_MAP.get(sys_cons.BIOS_BOOT_MODE_UEFI))
[ "def", "_is_boot_mode_uefi", "(", "self", ")", ":", "boot_mode", "=", "self", ".", "get_current_boot_mode", "(", ")", "return", "(", "boot_mode", "==", "BOOT_MODE_MAP", ".", "get", "(", "sys_cons", ".", "BIOS_BOOT_MODE_UEFI", ")", ")" ]
Checks if the system is in uefi boot mode. :return: 'True' if the boot mode is uefi else 'False'
[ "Checks", "if", "the", "system", "is", "in", "uefi", "boot", "mode", "." ]
python
train
dsandersAzure/python_cowbull_game
python_cowbull_game/v2_deprecated/GameController.py
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/v2_deprecated/GameController.py#L266-L274
def _start_again(self, message=None): """Simple method to form a start again message and give the answer in readable form.""" logging.debug("Start again message delivered: {}".format(message)) the_answer = self._game.answer_str return "{0} The correct answer was {1}. Please start a new ...
[ "def", "_start_again", "(", "self", ",", "message", "=", "None", ")", ":", "logging", ".", "debug", "(", "\"Start again message delivered: {}\"", ".", "format", "(", "message", ")", ")", "the_answer", "=", "self", ".", "_game", ".", "answer_str", "return", "...
Simple method to form a start again message and give the answer in readable form.
[ "Simple", "method", "to", "form", "a", "start", "again", "message", "and", "give", "the", "answer", "in", "readable", "form", "." ]
python
valid
samuelcolvin/watchgod
watchgod/main.py
https://github.com/samuelcolvin/watchgod/blob/15c72be2fca0afe2a081e4076f9353e5cdd8e42f/watchgod/main.py#L169-L189
async def arun_process(path: Union[Path, str], target: Callable, *, args: Tuple[Any]=(), kwargs: Dict[str, Any]=None, callback: Callable[[Set[Tuple[Change, str]]], Awaitable]=None, watcher_cls: Type[AllWatcher]=PythonWatcher, ...
[ "async", "def", "arun_process", "(", "path", ":", "Union", "[", "Path", ",", "str", "]", ",", "target", ":", "Callable", ",", "*", ",", "args", ":", "Tuple", "[", "Any", "]", "=", "(", ")", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]...
Run a function in a subprocess using multiprocessing.Process, restart it whenever files change in path.
[ "Run", "a", "function", "in", "a", "subprocess", "using", "multiprocessing", ".", "Process", "restart", "it", "whenever", "files", "change", "in", "path", "." ]
python
train
gagneurlab/concise
concise/legacy/concise.py
https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1331-L1340
def from_dict(cls, obj_dict): """ Load the object from a dictionary (produced with :py:func:`ConciseCV.to_dict`) Returns: ConciseCV: Loaded ConciseCV object. """ default_model = Concise() cvdc = ConciseCV(default_model) cvdc._from_dict(obj_dict) ...
[ "def", "from_dict", "(", "cls", ",", "obj_dict", ")", ":", "default_model", "=", "Concise", "(", ")", "cvdc", "=", "ConciseCV", "(", "default_model", ")", "cvdc", ".", "_from_dict", "(", "obj_dict", ")", "return", "cvdc" ]
Load the object from a dictionary (produced with :py:func:`ConciseCV.to_dict`) Returns: ConciseCV: Loaded ConciseCV object.
[ "Load", "the", "object", "from", "a", "dictionary", "(", "produced", "with", ":", "py", ":", "func", ":", "ConciseCV", ".", "to_dict", ")", "Returns", ":", "ConciseCV", ":", "Loaded", "ConciseCV", "object", "." ]
python
train
O365/python-o365
O365/connection.py
https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/connection.py#L548-L635
def _internal_request(self, request_obj, url, method, **kwargs): """ Internal handling of requests. Handles Exceptions. :param request_obj: a requests session. :param str url: url to send request to :param str method: type of request (get/put/post/patch/delete) :param kwargs: ex...
[ "def", "_internal_request", "(", "self", ",", "request_obj", ",", "url", ",", "method", ",", "*", "*", "kwargs", ")", ":", "method", "=", "method", ".", "lower", "(", ")", "if", "method", "not", "in", "self", ".", "_allowed_methods", ":", "raise", "Val...
Internal handling of requests. Handles Exceptions. :param request_obj: a requests session. :param str url: url to send request to :param str method: type of request (get/put/post/patch/delete) :param kwargs: extra params to send to the request api :return: Response of the reques...
[ "Internal", "handling", "of", "requests", ".", "Handles", "Exceptions", "." ]
python
train
huge-success/sanic
sanic/app.py
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L567-L583
def exception(self, *exceptions): """Decorate a function to be registered as a handler for exceptions :param exceptions: exceptions :return: decorated function """ def response(handler): for exception in exceptions: if isinstance(exception, (tuple, l...
[ "def", "exception", "(", "self", ",", "*", "exceptions", ")", ":", "def", "response", "(", "handler", ")", ":", "for", "exception", "in", "exceptions", ":", "if", "isinstance", "(", "exception", ",", "(", "tuple", ",", "list", ")", ")", ":", "for", "...
Decorate a function to be registered as a handler for exceptions :param exceptions: exceptions :return: decorated function
[ "Decorate", "a", "function", "to", "be", "registered", "as", "a", "handler", "for", "exceptions" ]
python
train
xenon-middleware/pyxenon
xenon/oop.py
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L104-L115
def request_name(self): """Generate the name of the request.""" if self.static and not self.uses_request: return 'Empty' if not self.uses_request: return None if isinstance(self.uses_request, str): return self.uses_request return to_camel_ca...
[ "def", "request_name", "(", "self", ")", ":", "if", "self", ".", "static", "and", "not", "self", ".", "uses_request", ":", "return", "'Empty'", "if", "not", "self", ".", "uses_request", ":", "return", "None", "if", "isinstance", "(", "self", ".", "uses_r...
Generate the name of the request.
[ "Generate", "the", "name", "of", "the", "request", "." ]
python
train
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L146-L157
def serialize(self, method="urlencoded", lev=0, **kwargs): """ Convert this instance to another representation. Which representation is given by the choice of serialization method. :param method: A serialization method. Presently 'urlencoded', 'json', 'jwt' and 'dic...
[ "def", "serialize", "(", "self", ",", "method", "=", "\"urlencoded\"", ",", "lev", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "getattr", "(", "self", ",", "\"to_%s\"", "%", "method", ")", "(", "lev", "=", "lev", ",", "*", "*", "kwargs",...
Convert this instance to another representation. Which representation is given by the choice of serialization method. :param method: A serialization method. Presently 'urlencoded', 'json', 'jwt' and 'dict' is supported. :param lev: :param kwargs: Extra key word arg...
[ "Convert", "this", "instance", "to", "another", "representation", ".", "Which", "representation", "is", "given", "by", "the", "choice", "of", "serialization", "method", ".", ":", "param", "method", ":", "A", "serialization", "method", ".", "Presently", "urlencod...
python
train
secdev/scapy
scapy/layers/tls/handshake.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/tls/handshake.py#L280-L298
def tls_session_update(self, msg_str): """ Either for parsing or building, we store the client_random along with the raw string representing this handshake message. """ super(TLSClientHello, self).tls_session_update(msg_str) self.tls_session.advertised_tls_version = self...
[ "def", "tls_session_update", "(", "self", ",", "msg_str", ")", ":", "super", "(", "TLSClientHello", ",", "self", ")", ".", "tls_session_update", "(", "msg_str", ")", "self", ".", "tls_session", ".", "advertised_tls_version", "=", "self", ".", "version", "self"...
Either for parsing or building, we store the client_random along with the raw string representing this handshake message.
[ "Either", "for", "parsing", "or", "building", "we", "store", "the", "client_random", "along", "with", "the", "raw", "string", "representing", "this", "handshake", "message", "." ]
python
train
hydpy-dev/hydpy
hydpy/auxs/statstools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/statstools.py#L18-L135
def prepare_arrays(sim=None, obs=None, node=None, skip_nan=False): """Prepare and return two |numpy| arrays based on the given arguments. Note that many functions provided by module |statstools| apply function |prepare_arrays| internally (e.g. |nse|). But you can also apply it manually, as shown in th...
[ "def", "prepare_arrays", "(", "sim", "=", "None", ",", "obs", "=", "None", ",", "node", "=", "None", ",", "skip_nan", "=", "False", ")", ":", "if", "node", ":", "if", "sim", "is", "not", "None", ":", "raise", "ValueError", "(", "'Values are passed to b...
Prepare and return two |numpy| arrays based on the given arguments. Note that many functions provided by module |statstools| apply function |prepare_arrays| internally (e.g. |nse|). But you can also apply it manually, as shown in the following examples. Function |prepare_arrays| can extract time seri...
[ "Prepare", "and", "return", "two", "|numpy|", "arrays", "based", "on", "the", "given", "arguments", "." ]
python
train
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/pympler/refgraph.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/refgraph.py#L222-L252
def split(self): """ Split the graph into sub-graphs. Only connected objects belong to the same graph. `split` yields copies of the Graph object. Shallow copies are used that only replicate the meta-information, but share the same object list ``self.objects``. >>> from p...
[ "def", "split", "(", "self", ")", ":", "self", ".", "_annotate_groups", "(", ")", "index", "=", "0", "for", "group", "in", "range", "(", "self", ".", "_max_group", ")", ":", "subgraph", "=", "copy", "(", "self", ")", "subgraph", ".", "metadata", "=",...
Split the graph into sub-graphs. Only connected objects belong to the same graph. `split` yields copies of the Graph object. Shallow copies are used that only replicate the meta-information, but share the same object list ``self.objects``. >>> from pympler.refgraph import ReferenceGraph...
[ "Split", "the", "graph", "into", "sub", "-", "graphs", ".", "Only", "connected", "objects", "belong", "to", "the", "same", "graph", ".", "split", "yields", "copies", "of", "the", "Graph", "object", ".", "Shallow", "copies", "are", "used", "that", "only", ...
python
train
treycucco/bidon
bidon/util/transform.py
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L102-L104
def obj(extract=None, child_transform=None, transform=None): """Returns a partial of get_obj that only needs a source argument.""" return lambda source: get_obj(source, extract, child_transform, transform)
[ "def", "obj", "(", "extract", "=", "None", ",", "child_transform", "=", "None", ",", "transform", "=", "None", ")", ":", "return", "lambda", "source", ":", "get_obj", "(", "source", ",", "extract", ",", "child_transform", ",", "transform", ")" ]
Returns a partial of get_obj that only needs a source argument.
[ "Returns", "a", "partial", "of", "get_obj", "that", "only", "needs", "a", "source", "argument", "." ]
python
train
tango-controls/pytango
tango/utils.py
https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/utils.py#L1094-L1099
def copy_doc(klass, fnname): """Copies documentation string of a method from the super class into the rewritten method of the given class""" base_meth, base_func = __get_meth_func(klass.__base__, fnname) meth, func = __get_meth_func(klass, fnname) func.__doc__ = base_func.__doc__
[ "def", "copy_doc", "(", "klass", ",", "fnname", ")", ":", "base_meth", ",", "base_func", "=", "__get_meth_func", "(", "klass", ".", "__base__", ",", "fnname", ")", "meth", ",", "func", "=", "__get_meth_func", "(", "klass", ",", "fnname", ")", "func", "."...
Copies documentation string of a method from the super class into the rewritten method of the given class
[ "Copies", "documentation", "string", "of", "a", "method", "from", "the", "super", "class", "into", "the", "rewritten", "method", "of", "the", "given", "class" ]
python
train
dingusdk/PythonIhcSdk
ihcsdk/ihccurlconnection.py
https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccurlconnection.py#L21-L58
def soap_action(self, service, action, payloadbody): """Do a soap request """ payload = self.soapenvelope.format(body=payloadbody).encode('utf-8') headers = ['SOAPAction: ' + action, 'Content-Type: application/soap+xml; charset=UTF-8', 'Content-Length: ' + s...
[ "def", "soap_action", "(", "self", ",", "service", ",", "action", ",", "payloadbody", ")", ":", "payload", "=", "self", ".", "soapenvelope", ".", "format", "(", "body", "=", "payloadbody", ")", ".", "encode", "(", "'utf-8'", ")", "headers", "=", "[", "...
Do a soap request
[ "Do", "a", "soap", "request" ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L1085-L1094
def imagetransformer_b12l_4h_b128_h512_uncond_dr01_im(): """TPU related imagenet model.""" hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_w...
[ "def", "imagetransformer_b12l_4h_b128_h512_uncond_dr01_im", "(", ")", ":", "hparams", "=", "imagetransformer_b12l_4h_b256_uncond_dr03_tpu", "(", ")", "update_hparams_for_tpu", "(", "hparams", ")", "hparams", ".", "batch_size", "=", "4", "hparams", ".", "optimizer", "=", ...
TPU related imagenet model.
[ "TPU", "related", "imagenet", "model", "." ]
python
train
mitsei/dlkit
dlkit/json_/grading/default_mdata.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/default_mdata.py#L11-L107
def get_grade_mdata(): """Return default mdata map for Grade""" return { 'output_score': { 'element_label': { 'text': 'output score', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'forma...
[ "def", "get_grade_mdata", "(", ")", ":", "return", "{", "'output_score'", ":", "{", "'element_label'", ":", "{", "'text'", ":", "'output score'", ",", "'languageTypeId'", ":", "str", "(", "DEFAULT_LANGUAGE_TYPE", ")", ",", "'scriptTypeId'", ":", "str", "(", "D...
Return default mdata map for Grade
[ "Return", "default", "mdata", "map", "for", "Grade" ]
python
train
vint21h/django-po2xls
po2xls/utils.py
https://github.com/vint21h/django-po2xls/blob/e76d26cfae6d9e5ca95ff053d05a00f875875019/po2xls/utils.py#L78-L93
def strings(self): """ Write strings sheet. """ sheet = self.result.add_sheet("strings") self.header(sheet, "strings") n_row = 1 # row number for entry in self.po: row = sheet.row(n_row) row.write(0, entry.msgid) row.write(1...
[ "def", "strings", "(", "self", ")", ":", "sheet", "=", "self", ".", "result", ".", "add_sheet", "(", "\"strings\"", ")", "self", ".", "header", "(", "sheet", ",", "\"strings\"", ")", "n_row", "=", "1", "# row number", "for", "entry", "in", "self", ".",...
Write strings sheet.
[ "Write", "strings", "sheet", "." ]
python
train
polysquare/polysquare-generic-file-linter
polysquarelinter/spelling.py
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L681-L754
def _find_spellcheckable_chunks(contents, comment_system): """Given some contents for a file, find chunks that can be spellchecked. This applies the following rules: 1. If the comment system comments individual lines, that whole line can be spellchecked from the poi...
[ "def", "_find_spellcheckable_chunks", "(", "contents", ",", "comment_system", ")", ":", "state", "=", "InTextParser", "(", ")", "comment_system_transitions", "=", "CommentSystemTransitions", "(", "comment_system", ")", "chunks", "=", "[", "]", "for", "line_index", "...
Given some contents for a file, find chunks that can be spellchecked. This applies the following rules: 1. If the comment system comments individual lines, that whole line can be spellchecked from the point of the comment 2. If a comment-start marker or triple quote is found, keep going u...
[ "Given", "some", "contents", "for", "a", "file", "find", "chunks", "that", "can", "be", "spellchecked", "." ]
python
train
treycucco/pyebnf
pyebnf/primitive.py
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/primitive.py#L87-L97
def add_ignored(self, ignored): """Add ignored text to the node. This will add the length of the ignored text to the node's consumed property. """ if ignored: if self.ignored: self.ignored = ignored + self.ignored else: self.ignored = ignored self.consumed += len(ignored...
[ "def", "add_ignored", "(", "self", ",", "ignored", ")", ":", "if", "ignored", ":", "if", "self", ".", "ignored", ":", "self", ".", "ignored", "=", "ignored", "+", "self", ".", "ignored", "else", ":", "self", ".", "ignored", "=", "ignored", "self", "....
Add ignored text to the node. This will add the length of the ignored text to the node's consumed property.
[ "Add", "ignored", "text", "to", "the", "node", ".", "This", "will", "add", "the", "length", "of", "the", "ignored", "text", "to", "the", "node", "s", "consumed", "property", "." ]
python
test
LogicalDash/LiSE
LiSE/LiSE/character.py
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/character.py#L2028-L2040
def thing2place(self, name): """Unset a Thing's location, and thus turn it into a Place.""" self.engine._set_thing_loc( self.name, name, None ) if (self.name, name) in self.engine._node_objs: thing = self.engine._node_objs[self.name, name] place = Plac...
[ "def", "thing2place", "(", "self", ",", "name", ")", ":", "self", ".", "engine", ".", "_set_thing_loc", "(", "self", ".", "name", ",", "name", ",", "None", ")", "if", "(", "self", ".", "name", ",", "name", ")", "in", "self", ".", "engine", ".", "...
Unset a Thing's location, and thus turn it into a Place.
[ "Unset", "a", "Thing", "s", "location", "and", "thus", "turn", "it", "into", "a", "Place", "." ]
python
train
GPflow/GPflow
gpflow/conditionals.py
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/conditionals.py#L412-L437
def _expand_independent_outputs(fvar, full_cov, full_output_cov): """ Reshapes fvar to the correct shape, specified by `full_cov` and `full_output_cov`. :param fvar: has shape N x P (full_cov = False) or P x N x N (full_cov = True). :return: 1. full_cov: True and full_output_cov: True fvar N...
[ "def", "_expand_independent_outputs", "(", "fvar", ",", "full_cov", ",", "full_output_cov", ")", ":", "if", "full_cov", "and", "full_output_cov", ":", "fvar", "=", "tf", ".", "matrix_diag", "(", "tf", ".", "transpose", "(", "fvar", ")", ")", "# N x N x P x P",...
Reshapes fvar to the correct shape, specified by `full_cov` and `full_output_cov`. :param fvar: has shape N x P (full_cov = False) or P x N x N (full_cov = True). :return: 1. full_cov: True and full_output_cov: True fvar N x P x N x P 2. full_cov: True and full_output_cov: False fvar P x ...
[ "Reshapes", "fvar", "to", "the", "correct", "shape", "specified", "by", "full_cov", "and", "full_output_cov", "." ]
python
train
biocore/deblur
deblur/workflow.py
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L196-L232
def build_index_sortmerna(ref_fp, working_dir): """Build a SortMeRNA index for all reference databases. Parameters ---------- ref_fp: tuple filepaths to FASTA reference databases working_dir: string working directory path where to store the indexed database Returns ------- ...
[ "def", "build_index_sortmerna", "(", "ref_fp", ",", "working_dir", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'build_index_sortmerna files %s to'", "' dir %s'", "%", "(", "ref_fp", ",", "working_dir", ...
Build a SortMeRNA index for all reference databases. Parameters ---------- ref_fp: tuple filepaths to FASTA reference databases working_dir: string working directory path where to store the indexed database Returns ------- all_db: tuple filepaths to SortMeRNA indexe...
[ "Build", "a", "SortMeRNA", "index", "for", "all", "reference", "databases", "." ]
python
train
materialsproject/pymatgen
pymatgen/util/coord.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/util/coord.py#L64-L79
def is_coord_subset(subset, superset, atol=1e-8): """ Tests if all coords in subset are contained in superset. Doesn't use periodic boundary conditions Args: subset, superset: List of coords Returns: True if all of subset is in superset. """ c1 = np.array(subset) c2 = n...
[ "def", "is_coord_subset", "(", "subset", ",", "superset", ",", "atol", "=", "1e-8", ")", ":", "c1", "=", "np", ".", "array", "(", "subset", ")", "c2", "=", "np", ".", "array", "(", "superset", ")", "is_close", "=", "np", ".", "all", "(", "np", "....
Tests if all coords in subset are contained in superset. Doesn't use periodic boundary conditions Args: subset, superset: List of coords Returns: True if all of subset is in superset.
[ "Tests", "if", "all", "coords", "in", "subset", "are", "contained", "in", "superset", ".", "Doesn", "t", "use", "periodic", "boundary", "conditions" ]
python
train
transitland/mapzen-gtfs
mzgtfs/trip.py
https://github.com/transitland/mapzen-gtfs/blob/d445f1588ed10713eea9a1ca2878eef792121eca/mzgtfs/trip.py#L37-L42
def stop_sequence(self): """Return the sorted StopTimes for this trip.""" return sorted( self.stop_times(), key=lambda x:int(x.get('stop_sequence')) )
[ "def", "stop_sequence", "(", "self", ")", ":", "return", "sorted", "(", "self", ".", "stop_times", "(", ")", ",", "key", "=", "lambda", "x", ":", "int", "(", "x", ".", "get", "(", "'stop_sequence'", ")", ")", ")" ]
Return the sorted StopTimes for this trip.
[ "Return", "the", "sorted", "StopTimes", "for", "this", "trip", "." ]
python
train
pyca/pyopenssl
src/OpenSSL/SSL.py
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/SSL.py#L1389-L1402
def set_tlsext_use_srtp(self, profiles): """ Enable support for negotiating SRTP keying material. :param bytes profiles: A colon delimited list of protection profile names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``. :return: None """ if not is...
[ "def", "set_tlsext_use_srtp", "(", "self", ",", "profiles", ")", ":", "if", "not", "isinstance", "(", "profiles", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"profiles must be a byte string.\"", ")", "_openssl_assert", "(", "_lib", ".", "SSL_CTX_set_tlsex...
Enable support for negotiating SRTP keying material. :param bytes profiles: A colon delimited list of protection profile names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``. :return: None
[ "Enable", "support", "for", "negotiating", "SRTP", "keying", "material", "." ]
python
test
blockstack/blockstack-core
blockstack/lib/nameset/db.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1680-L1687
def namedb_get_history( cur, history_id, offset=None, count=None, reverse=False ): """ Get all of the history for a name or namespace. Returns a dict keyed by block heights, paired to lists of changes (see namedb_history_extract) """ # get history in increasing order by block_id and then vtxindex ...
[ "def", "namedb_get_history", "(", "cur", ",", "history_id", ",", "offset", "=", "None", ",", "count", "=", "None", ",", "reverse", "=", "False", ")", ":", "# get history in increasing order by block_id and then vtxindex", "history_rows", "=", "namedb_get_history_rows", ...
Get all of the history for a name or namespace. Returns a dict keyed by block heights, paired to lists of changes (see namedb_history_extract)
[ "Get", "all", "of", "the", "history", "for", "a", "name", "or", "namespace", ".", "Returns", "a", "dict", "keyed", "by", "block", "heights", "paired", "to", "lists", "of", "changes", "(", "see", "namedb_history_extract", ")" ]
python
train
rushter/heamy
heamy/dataset.py
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/dataset.py#L331-L334
def to_csr(self): """Convert Dataset to scipy's Compressed Sparse Row matrix.""" self._X_train = csr_matrix(self._X_train) self._X_test = csr_matrix(self._X_test)
[ "def", "to_csr", "(", "self", ")", ":", "self", ".", "_X_train", "=", "csr_matrix", "(", "self", ".", "_X_train", ")", "self", ".", "_X_test", "=", "csr_matrix", "(", "self", ".", "_X_test", ")" ]
Convert Dataset to scipy's Compressed Sparse Row matrix.
[ "Convert", "Dataset", "to", "scipy", "s", "Compressed", "Sparse", "Row", "matrix", "." ]
python
train
twilio/twilio-python
twilio/rest/api/v2010/account/sip/credential_list/credential.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/sip/credential_list/credential.py#L439-L448
def update(self, password=values.unset): """ Update the CredentialInstance :param unicode password: The password will not be returned in the response :returns: Updated CredentialInstance :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance ...
[ "def", "update", "(", "self", ",", "password", "=", "values", ".", "unset", ")", ":", "return", "self", ".", "_proxy", ".", "update", "(", "password", "=", "password", ",", ")" ]
Update the CredentialInstance :param unicode password: The password will not be returned in the response :returns: Updated CredentialInstance :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance
[ "Update", "the", "CredentialInstance" ]
python
train
JamesPHoughton/pysd
pysd/py_backend/xmile/SMILE2Py.py
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/xmile/SMILE2Py.py#L239-L259
def parse(self, text, element, context='eqn'): """ context : <string> 'eqn', 'defn' If context is set to equation, lone identifiers will be parsed as calls to elements If context is set to definition, lone identifiers will be cleaned and returned. """ ...
[ "def", "parse", "(", "self", ",", "text", ",", "element", ",", "context", "=", "'eqn'", ")", ":", "# Remove the inline comments from `text` before parsing the grammar", "# http://docs.oasis-open.org/xmile/xmile/v1.0/csprd01/xmile-v1.0-csprd01.html#_Toc398039973", "text", "=", "re...
context : <string> 'eqn', 'defn' If context is set to equation, lone identifiers will be parsed as calls to elements If context is set to definition, lone identifiers will be cleaned and returned.
[ "context", ":", "<string", ">", "eqn", "defn", "If", "context", "is", "set", "to", "equation", "lone", "identifiers", "will", "be", "parsed", "as", "calls", "to", "elements", "If", "context", "is", "set", "to", "definition", "lone", "identifiers", "will", ...
python
train
mfcloud/python-zvm-sdk
sample/simple/sample.py
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L39-L54
def describe_guest(userid): """ Get the basic information of virtual machine. Input parameters: :userid: USERID of the guest, last 8 if length > 8 """ # Check if the guest exists. guest_list_info = client.send_request('guest_list') userid_1 = (unicode(userid, "utf-8") if sys.version[0] =...
[ "def", "describe_guest", "(", "userid", ")", ":", "# Check if the guest exists.", "guest_list_info", "=", "client", ".", "send_request", "(", "'guest_list'", ")", "userid_1", "=", "(", "unicode", "(", "userid", ",", "\"utf-8\"", ")", "if", "sys", ".", "version",...
Get the basic information of virtual machine. Input parameters: :userid: USERID of the guest, last 8 if length > 8
[ "Get", "the", "basic", "information", "of", "virtual", "machine", "." ]
python
train
xtrementl/focus
focus/daemon.py
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L54-L62
def pid_exists(pid): """ Determines if a system process identifer exists in process table. """ try: os.kill(pid, 0) except OSError as exc: return exc.errno == errno.EPERM else: return True
[ "def", "pid_exists", "(", "pid", ")", ":", "try", ":", "os", ".", "kill", "(", "pid", ",", "0", ")", "except", "OSError", "as", "exc", ":", "return", "exc", ".", "errno", "==", "errno", ".", "EPERM", "else", ":", "return", "True" ]
Determines if a system process identifer exists in process table.
[ "Determines", "if", "a", "system", "process", "identifer", "exists", "in", "process", "table", "." ]
python
train
apache/spark
python/pyspark/mllib/linalg/__init__.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/linalg/__init__.py#L874-L886
def dense(*elements): """ Create a dense vector of 64-bit floats from a Python list or numbers. >>> Vectors.dense([1, 2, 3]) DenseVector([1.0, 2.0, 3.0]) >>> Vectors.dense(1.0, 2.0) DenseVector([1.0, 2.0]) """ if len(elements) == 1 and not isinstance(elem...
[ "def", "dense", "(", "*", "elements", ")", ":", "if", "len", "(", "elements", ")", "==", "1", "and", "not", "isinstance", "(", "elements", "[", "0", "]", ",", "(", "float", ",", "int", ",", "long", ")", ")", ":", "# it's list, numpy.array or other iter...
Create a dense vector of 64-bit floats from a Python list or numbers. >>> Vectors.dense([1, 2, 3]) DenseVector([1.0, 2.0, 3.0]) >>> Vectors.dense(1.0, 2.0) DenseVector([1.0, 2.0])
[ "Create", "a", "dense", "vector", "of", "64", "-", "bit", "floats", "from", "a", "Python", "list", "or", "numbers", "." ]
python
train
saltstack/salt
salt/loader.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L373-L383
def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': co...
[ "def", "returners", "(", "opts", ",", "functions", ",", "whitelist", "=", "None", ",", "context", "=", "None", ",", "proxy", "=", "None", ")", ":", "return", "LazyLoader", "(", "_module_dirs", "(", "opts", ",", "'returners'", ",", "'returner'", ")", ",",...
Returns the returner modules
[ "Returns", "the", "returner", "modules" ]
python
train
pdkit/pdkit
pdkit/utils.py
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/utils.py#L345-L363
def autocorrelation(signal): """ The `correlation <https://en.wikipedia.org/wiki/Autocorrelation#Estimation>`_ of a signal with a delayed copy of itself. :param signal: A 1-dimensional array or list (the signal). :type signal: array :return: The autocorrelated signal. :rtyp...
[ "def", "autocorrelation", "(", "signal", ")", ":", "signal", "=", "np", ".", "array", "(", "signal", ")", "n", "=", "len", "(", "signal", ")", "variance", "=", "signal", ".", "var", "(", ")", "signal", "-=", "signal", ".", "mean", "(", ")", "r", ...
The `correlation <https://en.wikipedia.org/wiki/Autocorrelation#Estimation>`_ of a signal with a delayed copy of itself. :param signal: A 1-dimensional array or list (the signal). :type signal: array :return: The autocorrelated signal. :rtype: numpy.ndarray
[ "The", "correlation", "<https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Autocorrelation#Estimation", ">", "_", "of", "a", "signal", "with", "a", "delayed", "copy", "of", "itself", "." ]
python
train
quantumlib/Cirq
cirq/google/programs.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/programs.py#L147-L168
def schedule_to_proto_dicts(schedule: Schedule) -> Iterable[Dict]: """Convert a schedule into an iterable of proto dictionaries. Args: schedule: The schedule to convert to a proto dict. Must contain only gates that can be cast to xmon gates. Yields: A proto dictionary correspon...
[ "def", "schedule_to_proto_dicts", "(", "schedule", ":", "Schedule", ")", "->", "Iterable", "[", "Dict", "]", ":", "last_time_picos", "=", "None", "# type: Optional[int]", "for", "so", "in", "schedule", ".", "scheduled_operations", ":", "op", "=", "gate_to_proto_di...
Convert a schedule into an iterable of proto dictionaries. Args: schedule: The schedule to convert to a proto dict. Must contain only gates that can be cast to xmon gates. Yields: A proto dictionary corresponding to an Operation proto.
[ "Convert", "a", "schedule", "into", "an", "iterable", "of", "proto", "dictionaries", "." ]
python
train