repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
johnbywater/eventsourcing
eventsourcing/domain/model/array.py
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/domain/model/array.py#L372-L397
def calc_parent(self, i, j, h): """ Returns get_big_array and end of span of parent sequence that contains given child. """ N = self.repo.array_size c_i = i c_j = j c_h = h # Calculate the number of the sequence in its row (sequences # with same he...
[ "def", "calc_parent", "(", "self", ",", "i", ",", "j", ",", "h", ")", ":", "N", "=", "self", ".", "repo", ".", "array_size", "c_i", "=", "i", "c_j", "=", "j", "c_h", "=", "h", "# Calculate the number of the sequence in its row (sequences", "# with same heigh...
Returns get_big_array and end of span of parent sequence that contains given child.
[ "Returns", "get_big_array", "and", "end", "of", "span", "of", "parent", "sequence", "that", "contains", "given", "child", "." ]
python
train
40.884615
tomprince/nomenclature
nomenclature/syscalls.py
https://github.com/tomprince/nomenclature/blob/81af4a590034f75211f028d485c0d83fceda5af2/nomenclature/syscalls.py#L27-L38
def setns(fd, nstype): """ Reassociate thread with a namespace :param fd int: The file descriptor referreing to one of the namespace entries in a :directory::`/proc/<pid>/ns/` directory. :param nstype int: The type of namespace the calling thread should be reasscoiated with. """ ...
[ "def", "setns", "(", "fd", ",", "nstype", ")", ":", "res", "=", "lib", ".", "setns", "(", "fd", ",", "nstype", ")", "if", "res", "!=", "0", ":", "_check_error", "(", "ffi", ".", "errno", ")" ]
Reassociate thread with a namespace :param fd int: The file descriptor referreing to one of the namespace entries in a :directory::`/proc/<pid>/ns/` directory. :param nstype int: The type of namespace the calling thread should be reasscoiated with.
[ "Reassociate", "thread", "with", "a", "namespace" ]
python
train
32.166667
iotile/coretools
iotilebuild/iotile/build/config/site_scons/autobuild.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L233-L259
def autobuild_trub_script(file_name, slot_assignments=None, os_info=None, sensor_graph=None, app_info=None, use_safeupdate=False): """Build a trub script that loads given firmware into the given slots. slot_assignments should be a list of tuples in the following form: ("slot X" or...
[ "def", "autobuild_trub_script", "(", "file_name", ",", "slot_assignments", "=", "None", ",", "os_info", "=", "None", ",", "sensor_graph", "=", "None", ",", "app_info", "=", "None", ",", "use_safeupdate", "=", "False", ")", ":", "build_update_script", "(", "fil...
Build a trub script that loads given firmware into the given slots. slot_assignments should be a list of tuples in the following form: ("slot X" or "controller", firmware_image_name) The output of this autobuild action will be a trub script in build/output/<file_name> that assigns the given firmware t...
[ "Build", "a", "trub", "script", "that", "loads", "given", "firmware", "into", "the", "given", "slots", "." ]
python
train
55.703704
Tanganelli/CoAPthon3
coapthon/layers/requestlayer.py
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/requestlayer.py#L46-L72
def _handle_get(self, transaction): """ Handle GET requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ path = str("/" +...
[ "def", "_handle_get", "(", "self", ",", "transaction", ")", ":", "path", "=", "str", "(", "\"/\"", "+", "transaction", ".", "request", ".", "uri_path", ")", "transaction", ".", "response", "=", "Response", "(", ")", "transaction", ".", "response", ".", "...
Handle GET requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request
[ "Handle", "GET", "requests" ]
python
train
40.222222
amorison/loam
loam/cli.py
https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L248-L292
def zsh_complete(self, path, cmd, *cmds, sourceable=False): """Write zsh compdef script. Args: path (path-like): desired path of the compdef script. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. ...
[ "def", "zsh_complete", "(", "self", ",", "path", ",", "cmd", ",", "*", "cmds", ",", "sourceable", "=", "False", ")", ":", "grouping", "=", "internal", ".", "zsh_version", "(", ")", ">=", "(", "5", ",", "4", ")", "path", "=", "pathlib", ".", "Path",...
Write zsh compdef script. Args: path (path-like): desired path of the compdef script. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. sourceable (bool): if True, the generated file will contain an ...
[ "Write", "zsh", "compdef", "script", "." ]
python
test
46
kiwiz/gkeepapi
gkeepapi/node.py
https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1464-L1476
def add(self, text, checked=False, sort=None): """Add a new sub item to the list. This item must already be attached to a list. Args: text (str): The text. checked (bool): Whether this item is checked. sort (int): Item id for sorting. """ if self.pare...
[ "def", "add", "(", "self", ",", "text", ",", "checked", "=", "False", ",", "sort", "=", "None", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "raise", "exception", ".", "InvalidException", "(", "'Item has no parent'", ")", "node", "=", "sel...
Add a new sub item to the list. This item must already be attached to a list. Args: text (str): The text. checked (bool): Whether this item is checked. sort (int): Item id for sorting.
[ "Add", "a", "new", "sub", "item", "to", "the", "list", ".", "This", "item", "must", "already", "be", "attached", "to", "a", "list", "." ]
python
train
37.230769
edibledinos/pwnypack
pwnypack/codec.py
https://github.com/edibledinos/pwnypack/blob/e0a5a8e6ef3f4f1f7e1b91ee379711f4a49cb0e6/pwnypack/codec.py#L79-L172
def find_xor_mask(data, alphabet=None, max_depth=3, min_depth=0, iv=None): """ Produce a series of bytestrings that when XORed together end up being equal to ``data`` and only contain characters from the giving ``alphabet``. The initial state (or previous state) can be given as ``iv``. Argument...
[ "def", "find_xor_mask", "(", "data", ",", "alphabet", "=", "None", ",", "max_depth", "=", "3", ",", "min_depth", "=", "0", ",", "iv", "=", "None", ")", ":", "if", "alphabet", "is", "None", ":", "alphabet", "=", "set", "(", "i", "for", "i", "in", ...
Produce a series of bytestrings that when XORed together end up being equal to ``data`` and only contain characters from the giving ``alphabet``. The initial state (or previous state) can be given as ``iv``. Arguments: data (bytes): The data to recreate as a series of XOR operations. al...
[ "Produce", "a", "series", "of", "bytestrings", "that", "when", "XORed", "together", "end", "up", "being", "equal", "to", "data", "and", "only", "contain", "characters", "from", "the", "giving", "alphabet", ".", "The", "initial", "state", "(", "or", "previous...
python
train
36.670213
hyperledger/sawtooth-core
cli/sawtooth_cli/admin_command/config.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/cli/sawtooth_cli/admin_command/config.py#L36-L68
def _get_dir(toml_config_setting, sawtooth_home_dir, windows_dir, default_dir): """Determines the directory path based on configuration. Arguments: toml_config_setting (str): The name of the config setting related to the directory which will appear in path.toml. sawtooth_home_dir (s...
[ "def", "_get_dir", "(", "toml_config_setting", ",", "sawtooth_home_dir", ",", "windows_dir", ",", "default_dir", ")", ":", "conf_file", "=", "os", ".", "path", ".", "join", "(", "_get_config_dir", "(", ")", ",", "'path.toml'", ")", "if", "os", ".", "path", ...
Determines the directory path based on configuration. Arguments: toml_config_setting (str): The name of the config setting related to the directory which will appear in path.toml. sawtooth_home_dir (str): The directory under the SAWTOOTH_HOME environment variable. For examp...
[ "Determines", "the", "directory", "path", "based", "on", "configuration", "." ]
python
train
38.666667
cuihantao/andes
andes/utils/math.py
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L118-L120
def sort_idx(m, reverse=False): """Return the indices of m in sorted order (default: ascending order)""" return sorted(range(len(m)), key=lambda k: m[k], reverse=reverse)
[ "def", "sort_idx", "(", "m", ",", "reverse", "=", "False", ")", ":", "return", "sorted", "(", "range", "(", "len", "(", "m", ")", ")", ",", "key", "=", "lambda", "k", ":", "m", "[", "k", "]", ",", "reverse", "=", "reverse", ")" ]
Return the indices of m in sorted order (default: ascending order)
[ "Return", "the", "indices", "of", "m", "in", "sorted", "order", "(", "default", ":", "ascending", "order", ")" ]
python
train
58.666667
ravenac95/lxc4u
lxc4u/overlayutils.py
https://github.com/ravenac95/lxc4u/blob/4b5a9c8e25af97e5637db2f4c0c67d319ab0ed32/lxc4u/overlayutils.py#L62-L67
def meta(self): """Data for loading later""" mount_points = [] for overlay in self.overlays: mount_points.append(overlay.mount_point) return [self.end_dir, self.start_dir, mount_points]
[ "def", "meta", "(", "self", ")", ":", "mount_points", "=", "[", "]", "for", "overlay", "in", "self", ".", "overlays", ":", "mount_points", ".", "append", "(", "overlay", ".", "mount_point", ")", "return", "[", "self", ".", "end_dir", ",", "self", ".", ...
Data for loading later
[ "Data", "for", "loading", "later" ]
python
train
37.333333
google/grr
grr/server/grr_response_server/gui/archive_generator.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/archive_generator.py#L216-L233
def _WriteFileChunk(self, chunk): """Yields binary chunks, respecting archive file headers and footers. Args: chunk: the StreamedFileChunk to be written """ if chunk.chunk_index == 0: # Make sure size of the original file is passed. It's required # when output_writer is StreamingTarWr...
[ "def", "_WriteFileChunk", "(", "self", ",", "chunk", ")", ":", "if", "chunk", ".", "chunk_index", "==", "0", ":", "# Make sure size of the original file is passed. It's required", "# when output_writer is StreamingTarWriter.", "st", "=", "os", ".", "stat_result", "(", "...
Yields binary chunks, respecting archive file headers and footers. Args: chunk: the StreamedFileChunk to be written
[ "Yields", "binary", "chunks", "respecting", "archive", "file", "headers", "and", "footers", "." ]
python
train
41.722222
secdev/scapy
scapy/layers/radius.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/radius.py#L250-L258
def dispatch_hook(cls, _pkt=None, *args, **kargs): """ Returns the right RadiusAttribute class for the given data. """ if _pkt: attr_type = orb(_pkt[0]) return cls.registered_attributes.get(attr_type, cls) return cls
[ "def", "dispatch_hook", "(", "cls", ",", "_pkt", "=", "None", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "if", "_pkt", ":", "attr_type", "=", "orb", "(", "_pkt", "[", "0", "]", ")", "return", "cls", ".", "registered_attributes", ".", "get"...
Returns the right RadiusAttribute class for the given data.
[ "Returns", "the", "right", "RadiusAttribute", "class", "for", "the", "given", "data", "." ]
python
train
30.333333
project-rig/rig
rig/machine_control/machine_controller.py
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/machine_controller.py#L1531-L1587
def count_cores_in_state(self, state, app_id): """Count the number of cores in a given state. .. warning:: In current implementations of SARK, signals (which are used to determine the state of cores) are highly likely to arrive but this is not guaranteed (especially ...
[ "def", "count_cores_in_state", "(", "self", ",", "state", ",", "app_id", ")", ":", "if", "(", "isinstance", "(", "state", ",", "collections", ".", "Iterable", ")", "and", "not", "isinstance", "(", "state", ",", "str", ")", ")", ":", "# If the state is iter...
Count the number of cores in a given state. .. warning:: In current implementations of SARK, signals (which are used to determine the state of cores) are highly likely to arrive but this is not guaranteed (especially when the system's network is heavily utilised)...
[ "Count", "the", "number", "of", "cores", "in", "a", "given", "state", "." ]
python
train
43.947368
daknuett/py_register_machine2
core/memory.py
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/memory.py#L51-L61
def program(self, prog, offset = 0): """ .. _program: Write the content of the iterable ``prog`` starting with the optional offset ``offset`` to the device. Invokes program_word_. """ for addr, word in enumerate(prog): self.program_word(offset + addr, word)
[ "def", "program", "(", "self", ",", "prog", ",", "offset", "=", "0", ")", ":", "for", "addr", ",", "word", "in", "enumerate", "(", "prog", ")", ":", "self", ".", "program_word", "(", "offset", "+", "addr", ",", "word", ")" ]
.. _program: Write the content of the iterable ``prog`` starting with the optional offset ``offset`` to the device. Invokes program_word_.
[ "..", "_program", ":" ]
python
train
24.181818
soasme/rio
rio/setup.py
https://github.com/soasme/rio/blob/f722eb0ff4b0382bceaff77737f0b87cb78429e7/rio/setup.py#L19-L49
def configure_app(app): """Configure Flask/Celery application. * Rio will find environment variable `RIO_SETTINGS` first:: $ export RIO_SETTINGS=/path/to/settings.cfg $ rio worker * If `RIO_SETTINGS` is missing, Rio will try to load configuration module in `rio.settings` according t...
[ "def", "configure_app", "(", "app", ")", ":", "app", ".", "config_from_object", "(", "'rio.settings.default'", ")", "if", "environ", ".", "get", "(", "'RIO_SETTINGS'", ")", ":", "app", ".", "config_from_envvar", "(", "'RIO_SETTINGS'", ")", "return", "config_map"...
Configure Flask/Celery application. * Rio will find environment variable `RIO_SETTINGS` first:: $ export RIO_SETTINGS=/path/to/settings.cfg $ rio worker * If `RIO_SETTINGS` is missing, Rio will try to load configuration module in `rio.settings` according to another environment var...
[ "Configure", "Flask", "/", "Celery", "application", "." ]
python
train
28.645161
Alignak-monitoring/alignak
alignak/objects/satellitelink.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/satellitelink.py#L744-L751
def get_daemon_stats(self, details=False): """Send a HTTP request to the satellite (GET /get_daemon_stats) :return: Daemon statistics :rtype: dict """ logger.debug("Get daemon statistics for %s, %s %s", self.name, self.alive, self.reachable) return self.con.get('stats%s'...
[ "def", "get_daemon_stats", "(", "self", ",", "details", "=", "False", ")", ":", "logger", ".", "debug", "(", "\"Get daemon statistics for %s, %s %s\"", ",", "self", ".", "name", ",", "self", ".", "alive", ",", "self", ".", "reachable", ")", "return", "self",...
Send a HTTP request to the satellite (GET /get_daemon_stats) :return: Daemon statistics :rtype: dict
[ "Send", "a", "HTTP", "request", "to", "the", "satellite", "(", "GET", "/", "get_daemon_stats", ")" ]
python
train
43.75
rtlee9/serveit
serveit/log_utils.py
https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/log_utils.py#L8-L12
def get_logger(name): """Get a logger with the specified name.""" logger = logging.getLogger(name) logger.setLevel(getenv('LOGLEVEL', 'INFO')) return logger
[ "def", "get_logger", "(", "name", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "logger", ".", "setLevel", "(", "getenv", "(", "'LOGLEVEL'", ",", "'INFO'", ")", ")", "return", "logger" ]
Get a logger with the specified name.
[ "Get", "a", "logger", "with", "the", "specified", "name", "." ]
python
train
33.6
toumorokoshi/transmute-core
transmute_core/swagger/__init__.py
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/__init__.py#L53-L57
def add_func(self, transmute_func, transmute_context): """ add a transmute function's swagger definition to the spec """ swagger_path = transmute_func.get_swagger_path(transmute_context) for p in transmute_func.paths: self.add_path(p, swagger_path)
[ "def", "add_func", "(", "self", ",", "transmute_func", ",", "transmute_context", ")", ":", "swagger_path", "=", "transmute_func", ".", "get_swagger_path", "(", "transmute_context", ")", "for", "p", "in", "transmute_func", ".", "paths", ":", "self", ".", "add_pat...
add a transmute function's swagger definition to the spec
[ "add", "a", "transmute", "function", "s", "swagger", "definition", "to", "the", "spec" ]
python
train
56
gbowerman/azurerm
azurerm/container.py
https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/container.py#L36-L72
def create_container_instance_group(access_token, subscription_id, resource_group, container_group_name, container_list, location, ostype='Linux', port=80, iptype='public'): '''Create a new container group with a list of containers specifified ...
[ "def", "create_container_instance_group", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "container_group_name", ",", "container_list", ",", "location", ",", "ostype", "=", "'Linux'", ",", "port", "=", "80", ",", "iptype", "=", "'public'", ...
Create a new container group with a list of containers specifified by container_list. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of cont...
[ "Create", "a", "new", "container", "group", "with", "a", "list", "of", "containers", "specifified", "by", "container_list", "." ]
python
train
48.945946
googlefonts/glyphsLib
Lib/glyphsLib/builder/user_data.py
https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/builder/user_data.py#L115-L125
def to_glyphs_family_user_data_from_ufo(self, ufo): """Set the GSFont userData from the UFO family-wide lib data.""" target_user_data = self.font.userData try: for key, value in ufo.lib[FONT_USER_DATA_KEY].items(): # Existing values taken from the designspace lib take precedence ...
[ "def", "to_glyphs_family_user_data_from_ufo", "(", "self", ",", "ufo", ")", ":", "target_user_data", "=", "self", ".", "font", ".", "userData", "try", ":", "for", "key", ",", "value", "in", "ufo", ".", "lib", "[", "FONT_USER_DATA_KEY", "]", ".", "items", "...
Set the GSFont userData from the UFO family-wide lib data.
[ "Set", "the", "GSFont", "userData", "from", "the", "UFO", "family", "-", "wide", "lib", "data", "." ]
python
train
42.818182
tensorflow/tensorboard
tensorboard/plugins/graph/graph_util.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/graph/graph_util.py#L27-L87
def _safe_copy_proto_list_values(dst_proto_list, src_proto_list, get_key): """Safely merge values from `src_proto_list` into `dst_proto_list`. Each element in `dst_proto_list` must be mapped by `get_key` to a key value that is unique within that list; likewise for `src_proto_list`. If an element of `src_proto_...
[ "def", "_safe_copy_proto_list_values", "(", "dst_proto_list", ",", "src_proto_list", ",", "get_key", ")", ":", "def", "_assert_proto_container_unique_keys", "(", "proto_list", ",", "get_key", ")", ":", "\"\"\"Asserts proto_list to only contains unique keys.\n\n Args:\n pr...
Safely merge values from `src_proto_list` into `dst_proto_list`. Each element in `dst_proto_list` must be mapped by `get_key` to a key value that is unique within that list; likewise for `src_proto_list`. If an element of `src_proto_list` has the same key as an existing element in `dst_proto_list`, then the el...
[ "Safely", "merge", "values", "from", "src_proto_list", "into", "dst_proto_list", "." ]
python
train
37.606557
delfick/aws_syncr
aws_syncr/amazon/iam.py
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/amazon/iam.py#L128-L156
def modify_attached_policies(self, role_name, new_policies): """Make sure this role has just the new policies""" parts = role_name.split('/', 1) if len(parts) == 2: prefix, name = parts prefix = "/{0}/".format(prefix) else: prefix = "/" nam...
[ "def", "modify_attached_policies", "(", "self", ",", "role_name", ",", "new_policies", ")", ":", "parts", "=", "role_name", ".", "split", "(", "'/'", ",", "1", ")", "if", "len", "(", "parts", ")", "==", "2", ":", "prefix", ",", "name", "=", "parts", ...
Make sure this role has just the new policies
[ "Make", "sure", "this", "role", "has", "just", "the", "new", "policies" ]
python
train
53
LogicalDash/LiSE
ELiDE/ELiDE/card.py
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/card.py#L805-L810
def on_touch_down(self, touch): """Tell my parent if I've been touched""" if self.parent is None: return if self.collide_point(*touch.pos): self.parent.bar_touched(self, touch)
[ "def", "on_touch_down", "(", "self", ",", "touch", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "return", "if", "self", ".", "collide_point", "(", "*", "touch", ".", "pos", ")", ":", "self", ".", "parent", ".", "bar_touched", "(", "self"...
Tell my parent if I've been touched
[ "Tell", "my", "parent", "if", "I", "ve", "been", "touched" ]
python
train
36.5
hydpy-dev/hydpy
hydpy/models/lstream/lstream_model.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lstream/lstream_model.py#L243-L342
def calc_av_uv_v1(self): """Calculate the flown through area and the wetted perimeter of both forelands. Note that the each foreland lies between the main channel and one outer embankment and that water flowing exactly above the a foreland is contributing to |AV|. The theoretical surface seperatin...
[ "def", "calc_av_uv_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "der", "=", "self", ".", "parameters", ".", "derived", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", ...
Calculate the flown through area and the wetted perimeter of both forelands. Note that the each foreland lies between the main channel and one outer embankment and that water flowing exactly above the a foreland is contributing to |AV|. The theoretical surface seperating water above the main chann...
[ "Calculate", "the", "flown", "through", "area", "and", "the", "wetted", "perimeter", "of", "both", "forelands", "." ]
python
train
32.26
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v20/ardupilotmega.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v20/ardupilotmega.py#L11046-L11054
def gopro_set_response_send(self, cmd_id, status, force_mavlink1=False): ''' Response from a GOPRO_COMMAND set request cmd_id : Command ID (uint8_t) status : Status (uint8_t) ''' retur...
[ "def", "gopro_set_response_send", "(", "self", ",", "cmd_id", ",", "status", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "gopro_set_response_encode", "(", "cmd_id", ",", "status", ")", ",", "force_mavlink1", ...
Response from a GOPRO_COMMAND set request cmd_id : Command ID (uint8_t) status : Status (uint8_t)
[ "Response", "from", "a", "GOPRO_COMMAND", "set", "request" ]
python
train
44.666667
rigetti/grove
grove/tomography/process_tomography.py
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/process_tomography.py#L203-L216
def avg_gate_fidelity(self, reference_unitary): """ Compute the average gate fidelity of the estimated process with respect to a unitary process. See `Chow et al., 2012, <https://doi.org/10.1103/PhysRevLett.109.060501>`_ :param (qutip.Qobj|matrix-like) reference_unitary: A unitary oper...
[ "def", "avg_gate_fidelity", "(", "self", ",", "reference_unitary", ")", ":", "process_fidelity", "=", "self", ".", "process_fidelity", "(", "reference_unitary", ")", "dimension", "=", "self", ".", "pauli_basis", ".", "ops", "[", "0", "]", ".", "shape", "[", ...
Compute the average gate fidelity of the estimated process with respect to a unitary process. See `Chow et al., 2012, <https://doi.org/10.1103/PhysRevLett.109.060501>`_ :param (qutip.Qobj|matrix-like) reference_unitary: A unitary operator that induces a process as `rho -> other*rho*other.dag(...
[ "Compute", "the", "average", "gate", "fidelity", "of", "the", "estimated", "process", "with", "respect", "to", "a", "unitary", "process", ".", "See", "Chow", "et", "al", ".", "2012", "<https", ":", "//", "doi", ".", "org", "/", "10", ".", "1103", "/", ...
python
train
56.428571
guaix-ucm/pyemir
emirdrp/processing/bardetect.py
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/bardetect.py#L110-L120
def simple_prot(x, start): """Find the first peak to the right of start""" # start must b >= 1 for i in range(start,len(x)-1): a,b,c = x[i-1], x[i], x[i+1] if b - a > 0 and b -c >= 0: return i else: return None
[ "def", "simple_prot", "(", "x", ",", "start", ")", ":", "# start must b >= 1", "for", "i", "in", "range", "(", "start", ",", "len", "(", "x", ")", "-", "1", ")", ":", "a", ",", "b", ",", "c", "=", "x", "[", "i", "-", "1", "]", ",", "x", "["...
Find the first peak to the right of start
[ "Find", "the", "first", "peak", "to", "the", "right", "of", "start" ]
python
train
23.181818
QuantEcon/QuantEcon.py
quantecon/quad.py
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/quad.py#L685-L730
def _qnwcheb1(n, a, b): """ Compute univariate Guass-Checbychev quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) ...
[ "def", "_qnwcheb1", "(", "n", ",", "a", ",", "b", ")", ":", "nodes", "=", "(", "b", "+", "a", ")", "/", "2", "-", "(", "b", "-", "a", ")", "/", "2", "*", "np", ".", "cos", "(", "np", ".", "pi", "/", "n", "*", "np", ".", "linspace", "(...
Compute univariate Guass-Checbychev quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) An n element array of nodes no...
[ "Compute", "univariate", "Guass", "-", "Checbychev", "quadrature", "nodes", "and", "weights" ]
python
train
23.586957
CulturePlex/django-zotero
django_zotero/signals.py
https://github.com/CulturePlex/django-zotero/blob/de31583a80a2bd2459c118fb5aa767a2842e0b00/django_zotero/signals.py#L51-L68
def check_field_multiplicity(tag, previous_tags): """ Check the multiplicity of a 'field' for an object. """ fail = False #If the field is single if not tag.field.multiple: #If the tag is being created... if not tag.id: #... and the new field was already included in t...
[ "def", "check_field_multiplicity", "(", "tag", ",", "previous_tags", ")", ":", "fail", "=", "False", "#If the field is single", "if", "not", "tag", ".", "field", ".", "multiple", ":", "#If the tag is being created...", "if", "not", "tag", ".", "id", ":", "#... a...
Check the multiplicity of a 'field' for an object.
[ "Check", "the", "multiplicity", "of", "a", "field", "for", "an", "object", "." ]
python
train
36
kgori/treeCl
treeCl/collection.py
https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/collection.py#L137-L139
def records(self): """ Returns a list of records in SORT_KEY order """ return [self._records[i] for i in range(len(self._records))]
[ "def", "records", "(", "self", ")", ":", "return", "[", "self", ".", "_records", "[", "i", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_records", ")", ")", "]" ]
Returns a list of records in SORT_KEY order
[ "Returns", "a", "list", "of", "records", "in", "SORT_KEY", "order" ]
python
train
48.333333
isislovecruft/python-gnupg
pretty_bad_protocol/_parsers.py
https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L476-L610
def _get_options_group(group=None): """Get a specific group of options which are allowed.""" #: These expect a hexidecimal keyid as their argument, and can be parsed #: with :func:`_is_hex`. hex_options = frozenset(['--check-sigs', '--default-key', ...
[ "def", "_get_options_group", "(", "group", "=", "None", ")", ":", "#: These expect a hexidecimal keyid as their argument, and can be parsed", "#: with :func:`_is_hex`.", "hex_options", "=", "frozenset", "(", "[", "'--check-sigs'", ",", "'--default-key'", ",", "'--default-recipi...
Get a specific group of options which are allowed.
[ "Get", "a", "specific", "group", "of", "options", "which", "are", "allowed", "." ]
python
train
47.2
contentful/contentful-management.py
contentful_management/webhook.py
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/webhook.py#L94-L114
def to_json(self): """ Returns the JSON representation of the webhook. """ result = super(Webhook, self).to_json() result.update({ 'name': self.name, 'url': self.url, 'topics': self.topics, 'httpBasicUsername': self.http_basic_user...
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "super", "(", "Webhook", ",", "self", ")", ".", "to_json", "(", ")", "result", ".", "update", "(", "{", "'name'", ":", "self", ".", "name", ",", "'url'", ":", "self", ".", "url", ",", "'topi...
Returns the JSON representation of the webhook.
[ "Returns", "the", "JSON", "representation", "of", "the", "webhook", "." ]
python
train
26.380952
pkgw/pwkit
pwkit/lsqmdl.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/lsqmdl.py#L126-L143
def set_data(self, data, invsigma=None): """Set the data to be modeled. Returns *self*. """ self.data = np.array(data, dtype=np.float, ndmin=1) if invsigma is None: self.invsigma = np.ones(self.data.shape) else: i = np.array(invsigma, dtype=np.f...
[ "def", "set_data", "(", "self", ",", "data", ",", "invsigma", "=", "None", ")", ":", "self", ".", "data", "=", "np", ".", "array", "(", "data", ",", "dtype", "=", "np", ".", "float", ",", "ndmin", "=", "1", ")", "if", "invsigma", "is", "None", ...
Set the data to be modeled. Returns *self*.
[ "Set", "the", "data", "to", "be", "modeled", "." ]
python
train
31.111111
ValvePython/steam
steam/webapi.py
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/webapi.py#L444-L468
def get(interface, method, version=1, apihost=DEFAULT_PARAMS['apihost'], https=DEFAULT_PARAMS['https'], caller=None, session=None, params=None): """Send GET request to an API endpoint .. versionadded:: 0.8.3 :param interface: interface name :type interface: str :param method: metho...
[ "def", "get", "(", "interface", ",", "method", ",", "version", "=", "1", ",", "apihost", "=", "DEFAULT_PARAMS", "[", "'apihost'", "]", ",", "https", "=", "DEFAULT_PARAMS", "[", "'https'", "]", ",", "caller", "=", "None", ",", "session", "=", "None", ",...
Send GET request to an API endpoint .. versionadded:: 0.8.3 :param interface: interface name :type interface: str :param method: method name :type method: str :param version: method version :type version: int :param apihost: API hostname :type apihost: str :param https: whether...
[ "Send", "GET", "request", "to", "an", "API", "endpoint" ]
python
train
34.76
troeger/opensubmit
web/opensubmit/models/userprofile.py
https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/models/userprofile.py#L124-L144
def move_user_data(primary, secondary): ''' Moves all submissions and other data linked to the secondary user into the primary user. Nothing is deleted here, we just modify foreign user keys. ''' # Update all submission authorships of the secondary to the primary submissions = Submission...
[ "def", "move_user_data", "(", "primary", ",", "secondary", ")", ":", "# Update all submission authorships of the secondary to the primary", "submissions", "=", "Submission", ".", "objects", ".", "filter", "(", "authors__id", "=", "secondary", ".", "pk", ")", "for", "s...
Moves all submissions and other data linked to the secondary user into the primary user. Nothing is deleted here, we just modify foreign user keys.
[ "Moves", "all", "submissions", "and", "other", "data", "linked", "to", "the", "secondary", "user", "into", "the", "primary", "user", ".", "Nothing", "is", "deleted", "here", "we", "just", "modify", "foreign", "user", "keys", "." ]
python
train
40.428571
jciskey/pygraph
pygraph/predefined_graphs.py
https://github.com/jciskey/pygraph/blob/037bb2f32503fecb60d62921f9766d54109f15e2/pygraph/predefined_graphs.py#L217-L233
def build_chvatal_graph(): """Makes a new Chvatal graph. Ref: http://mathworld.wolfram.com/ChvatalGraph.html""" # The easiest way to build the Chvatal graph is to start # with C12 and add the additional 12 edges graph = build_cycle_graph(12) edge_tpls = [ (1,7), (1,9), (2,5), (2,11),...
[ "def", "build_chvatal_graph", "(", ")", ":", "# The easiest way to build the Chvatal graph is to start", "# with C12 and add the additional 12 edges", "graph", "=", "build_cycle_graph", "(", "12", ")", "edge_tpls", "=", "[", "(", "1", ",", "7", ")", ",", "(", "1", ","...
Makes a new Chvatal graph. Ref: http://mathworld.wolfram.com/ChvatalGraph.html
[ "Makes", "a", "new", "Chvatal", "graph", ".", "Ref", ":", "http", ":", "//", "mathworld", ".", "wolfram", ".", "com", "/", "ChvatalGraph", ".", "html" ]
python
train
27.176471
SKA-ScienceDataProcessor/integration-prototype
sip/execution_control/docker_api/sip_docker_swarm/docker_swarm_client.py
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/docker_api/sip_docker_swarm/docker_swarm_client.py#L352-L365
def get_container_list(self) -> list: """Get list of containers. Returns: list, all the ids of containers """ # Initialising empty list containers = [] containers_list = self._client.containers.list() for c_list in containers_list: conta...
[ "def", "get_container_list", "(", "self", ")", "->", "list", ":", "# Initialising empty list", "containers", "=", "[", "]", "containers_list", "=", "self", ".", "_client", ".", "containers", ".", "list", "(", ")", "for", "c_list", "in", "containers_list", ":",...
Get list of containers. Returns: list, all the ids of containers
[ "Get", "list", "of", "containers", "." ]
python
train
25.857143
saltstack/salt
salt/key.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L352-L359
def gen_signature(self, privkey, pubkey, sig_path): ''' Generate master public-key-signature ''' return salt.crypt.gen_signature(privkey, pubkey, sig_path, self.passphr...
[ "def", "gen_signature", "(", "self", ",", "privkey", ",", "pubkey", ",", "sig_path", ")", ":", "return", "salt", ".", "crypt", ".", "gen_signature", "(", "privkey", ",", "pubkey", ",", "sig_path", ",", "self", ".", "passphrase", ")" ]
Generate master public-key-signature
[ "Generate", "master", "public", "-", "key", "-", "signature" ]
python
train
39.625
redapple/parslepy
parslepy/base.py
https://github.com/redapple/parslepy/blob/a8bc4c0592824459629018c8f4c6ae3dad6cc3cc/parslepy/base.py#L338-L429
def _compile(self, parselet_node, level=0): """ Build part of the abstract Parsley extraction tree Arguments: parselet_node (dict) -- part of the Parsley tree to compile (can be the root dict/node) level (int) -- current recursion depth (...
[ "def", "_compile", "(", "self", ",", "parselet_node", ",", "level", "=", "0", ")", ":", "if", "self", ".", "DEBUG", ":", "debug_offset", "=", "\"\"", ".", "join", "(", "[", "\" \"", "for", "x", "in", "range", "(", "level", ")", "]", ")", "if", ...
Build part of the abstract Parsley extraction tree Arguments: parselet_node (dict) -- part of the Parsley tree to compile (can be the root dict/node) level (int) -- current recursion depth (used for debug)
[ "Build", "part", "of", "the", "abstract", "Parsley", "extraction", "tree" ]
python
valid
37.586957
danilobellini/audiolazy
audiolazy/lazy_analysis.py
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L722-L802
def overlap_add(blk_sig, size=None, hop=None, wnd=None, normalize=True): """ Overlap-add algorithm using Numpy arrays. Parameters ---------- blk_sig : An iterable of blocks (sequences), such as the ``Stream.blocks`` result. size : Block size for each ``blk_sig`` element, in samples. hop : Num...
[ "def", "overlap_add", "(", "blk_sig", ",", "size", "=", "None", ",", "hop", "=", "None", ",", "wnd", "=", "None", ",", "normalize", "=", "True", ")", ":", "import", "numpy", "as", "np", "# Finds the size from data, if needed", "if", "size", "is", "None", ...
Overlap-add algorithm using Numpy arrays. Parameters ---------- blk_sig : An iterable of blocks (sequences), such as the ``Stream.blocks`` result. size : Block size for each ``blk_sig`` element, in samples. hop : Number of samples for two adjacent blocks (defaults to the size). wnd : Window...
[ "Overlap", "-", "add", "algorithm", "using", "Numpy", "arrays", "." ]
python
train
30.283951
chrisjrn/registrasion
registrasion/controllers/credit_note.py
https://github.com/chrisjrn/registrasion/blob/461d5846c6f9f3b7099322a94f5d9911564448e4/registrasion/controllers/credit_note.py#L60-L83
def cancellation_fee(self, percentage): ''' Generates an invoice with a cancellation fee, and applies credit to the invoice. percentage (Decimal): The percentage of the credit note to turn into a cancellation fee. Must be 0 <= percentage <= 100. ''' # Local import to fi...
[ "def", "cancellation_fee", "(", "self", ",", "percentage", ")", ":", "# Local import to fix import cycles. Can we do better?", "from", ".", "invoice", "import", "InvoiceController", "assert", "(", "percentage", ">=", "0", "and", "percentage", "<=", "100", ")", "cancel...
Generates an invoice with a cancellation fee, and applies credit to the invoice. percentage (Decimal): The percentage of the credit note to turn into a cancellation fee. Must be 0 <= percentage <= 100.
[ "Generates", "an", "invoice", "with", "a", "cancellation", "fee", "and", "applies", "credit", "to", "the", "invoice", "." ]
python
test
34.75
gbowerman/azurerm
azurerm/acs.py
https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/acs.py#L64-L81
def delete_container_service(access_token, subscription_id, resource_group, service_name): '''Delete a named container. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. se...
[ "def", "delete_container_service", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "service_name", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", ...
Delete a named container. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. service_name (str): Name of container service. Returns: HTTP response.
[ "Delete", "a", "named", "container", "." ]
python
train
41.611111
user-cont/conu
conu/backend/docker/image.py
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/docker/image.py#L342-L355
def tag_image(self, repository=None, tag=None): """ Apply additional tags to the image or even add a new name :param repository: str, see constructor :param tag: str, see constructor :return: instance of DockerImage """ if not (repository or tag): rai...
[ "def", "tag_image", "(", "self", ",", "repository", "=", "None", ",", "tag", "=", "None", ")", ":", "if", "not", "(", "repository", "or", "tag", ")", ":", "raise", "ValueError", "(", "\"You need to specify either repository or tag.\"", ")", "r", "=", "reposi...
Apply additional tags to the image or even add a new name :param repository: str, see constructor :param tag: str, see constructor :return: instance of DockerImage
[ "Apply", "additional", "tags", "to", "the", "image", "or", "even", "add", "a", "new", "name" ]
python
train
39.357143
BD2KGenomics/protect
src/protect/mutation_calling/somaticsniper.py
https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/mutation_calling/somaticsniper.py#L126-L165
def run_somaticsniper_full(job, tumor_bam, normal_bam, univ_options, somaticsniper_options): """ Run SomaticSniper on the DNA bams. :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq :param dict normal_bam: Dict of bam and bai for normal DNA-Seq :param dict univ_options: Dict of universal...
[ "def", "run_somaticsniper_full", "(", "job", ",", "tumor_bam", ",", "normal_bam", ",", "univ_options", ",", "somaticsniper_options", ")", ":", "work_dir", "=", "os", ".", "getcwd", "(", ")", "input_files", "=", "{", "'tumor.bam'", ":", "tumor_bam", "[", "'tumo...
Run SomaticSniper on the DNA bams. :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq :param dict normal_bam: Dict of bam and bai for normal DNA-Seq :param dict univ_options: Dict of universal options used by almost all tools :param dict somaticsniper_options: Options specific to SomaticSnipe...
[ "Run", "SomaticSniper", "on", "the", "DNA", "bams", "." ]
python
train
49.075
gatkin/declxml
declxml.py
https://github.com/gatkin/declxml/blob/3a2324b43aee943e82a04587fbb68932c6f392ba/declxml.py#L1613-L1625
def _xml_namespace_strip(root): # type: (ET.Element) -> None """Strip the XML namespace prefix from all element tags under the given root Element.""" if '}' not in root.tag: return # Nothing to do, no namespace present for element in root.iter(): if '}' in element.tag: elem...
[ "def", "_xml_namespace_strip", "(", "root", ")", ":", "# type: (ET.Element) -> None", "if", "'}'", "not", "in", "root", ".", "tag", ":", "return", "# Nothing to do, no namespace present", "for", "element", "in", "root", ".", "iter", "(", ")", ":", "if", "'}'", ...
Strip the XML namespace prefix from all element tags under the given root Element.
[ "Strip", "the", "XML", "namespace", "prefix", "from", "all", "element", "tags", "under", "the", "given", "root", "Element", "." ]
python
train
40.615385
clalancette/pycdlib
pycdlib/rockridge.py
https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/rockridge.py#L566-L599
def parse(self, rrstr): # type: (bytes) -> None ''' Parse a Rock Ridge Extensions Reference record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing. ''' if self._initialized: raise pycdlibe...
[ "def", "parse", "(", "self", ",", "rrstr", ")", ":", "# type: (bytes) -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'ER record already initialized!'", ")", "(", "su_len", ",", "su_entry_version_unused...
Parse a Rock Ridge Extensions Reference record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing.
[ "Parse", "a", "Rock", "Ridge", "Extensions", "Reference", "record", "out", "of", "a", "string", "." ]
python
train
39.411765
persephone-tools/persephone
persephone/experiment.py
https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/experiment.py#L18-L22
def get_exp_dir_num(parent_dir: str) -> int: """ Gets the number of the current experiment directory.""" return max([int(fn.split(".")[0]) for fn in os.listdir(parent_dir) if fn.split(".")[0].isdigit()] + [-1])
[ "def", "get_exp_dir_num", "(", "parent_dir", ":", "str", ")", "->", "int", ":", "return", "max", "(", "[", "int", "(", "fn", ".", "split", "(", "\".\"", ")", "[", "0", "]", ")", "for", "fn", "in", "os", ".", "listdir", "(", "parent_dir", ")", "if...
Gets the number of the current experiment directory.
[ "Gets", "the", "number", "of", "the", "current", "experiment", "directory", "." ]
python
train
50
SeleniumHQ/selenium
py/selenium/webdriver/common/action_chains.py
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L149-L166
def double_click(self, on_element=None): """ Double-clicks an element. :Args: - on_element: The element to double-click. If None, clicks on current mouse position. """ if on_element: self.move_to_element(on_element) if self._driver.w3c: ...
[ "def", "double_click", "(", "self", ",", "on_element", "=", "None", ")", ":", "if", "on_element", ":", "self", ".", "move_to_element", "(", "on_element", ")", "if", "self", ".", "_driver", ".", "w3c", ":", "self", ".", "w3c_actions", ".", "pointer_action",...
Double-clicks an element. :Args: - on_element: The element to double-click. If None, clicks on current mouse position.
[ "Double", "-", "clicks", "an", "element", "." ]
python
train
33.277778
ashleysommer/sanicpluginsframework
spf/plugin.py
https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L85-L105
def listener(self, event, *args, **kwargs): """Create a listener from a decorated function. :param event: Event to listen to. :type event: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :param kwargs: captures the keyword argume...
[ "def", "listener", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", "and", "callable", "(", "args", "[", "0", "]", ")", ":", "# pragma: no cover", "raise", "RuntimeError", "("...
Create a listener from a decorated function. :param event: Event to listen to. :type event: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :param kwargs: captures the keyword arguments passed in :type kwargs: dict(Any) :...
[ "Create", "a", "listener", "from", "a", "decorated", "function", ".", ":", "param", "event", ":", "Event", "to", "listen", "to", ".", ":", "type", "event", ":", "str", ":", "param", "args", ":", "captures", "all", "of", "the", "positional", "arguments", ...
python
train
40.095238
trolldbois/ctypeslib
ctypeslib/codegen/cursorhandler.py
https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L159-L178
def FUNCTION_DECL(self, cursor): """Handles function declaration""" # FIXME to UT name = self.get_unique_name(cursor) if self.is_registered(name): return self.get_registered(name) returns = self.parse_cursor_type(cursor.type.get_result()) attributes = [] ...
[ "def", "FUNCTION_DECL", "(", "self", ",", "cursor", ")", ":", "# FIXME to UT", "name", "=", "self", ".", "get_unique_name", "(", "cursor", ")", "if", "self", ".", "is_registered", "(", "name", ")", ":", "return", "self", ".", "get_registered", "(", "name",...
Handles function declaration
[ "Handles", "function", "declaration" ]
python
train
38.05
edx/opaque-keys
opaque_keys/edx/django/models.py
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/django/models.py#L58-L65
def _strip_object(key): """ Strips branch and version info if the given key supports those attributes. """ if hasattr(key, 'version_agnostic') and hasattr(key, 'for_branch'): return key.for_branch(None).version_agnostic() else: return key
[ "def", "_strip_object", "(", "key", ")", ":", "if", "hasattr", "(", "key", ",", "'version_agnostic'", ")", "and", "hasattr", "(", "key", ",", "'for_branch'", ")", ":", "return", "key", ".", "for_branch", "(", "None", ")", ".", "version_agnostic", "(", ")...
Strips branch and version info if the given key supports those attributes.
[ "Strips", "branch", "and", "version", "info", "if", "the", "given", "key", "supports", "those", "attributes", "." ]
python
train
33.375
saltstack/salt
salt/modules/boto_iam.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1933-L1953
def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, pro...
[ "def", "list_policy_versions", "(", "policy_name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ...
List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy
[ "List", "versions", "of", "a", "policy", "." ]
python
train
34.714286
TankerHQ/python-cli-ui
cli_ui/__init__.py
https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L187-L206
def process_tokens( tokens: Sequence[Token], *, end: str = "\n", sep: str = " " ) -> Tuple[str, str]: """ Returns two strings from a list of tokens. One containing ASCII escape codes, the other only the 'normal' characters """ # Flatten the list of tokens in case some of them are of # class...
[ "def", "process_tokens", "(", "tokens", ":", "Sequence", "[", "Token", "]", ",", "*", ",", "end", ":", "str", "=", "\"\\n\"", ",", "sep", ":", "str", "=", "\" \"", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "# Flatten the list of tokens in c...
Returns two strings from a list of tokens. One containing ASCII escape codes, the other only the 'normal' characters
[ "Returns", "two", "strings", "from", "a", "list", "of", "tokens", ".", "One", "containing", "ASCII", "escape", "codes", "the", "other", "only", "the", "normal", "characters" ]
python
train
36.5
pantsbuild/pants
src/python/pants/backend/jvm/tasks/ivy_resolve.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/ivy_resolve.py#L88-L117
def execute(self): """Resolves the specified confs for the configured targets and returns an iterator over tuples of (conf, jar path). """ if JvmResolveSubsystem.global_instance().get_options().resolver != 'ivy': return compile_classpath = self.context.products.get_data('compile_classpath', ...
[ "def", "execute", "(", "self", ")", ":", "if", "JvmResolveSubsystem", ".", "global_instance", "(", ")", ".", "get_options", "(", ")", ".", "resolver", "!=", "'ivy'", ":", "return", "compile_classpath", "=", "self", ".", "context", ".", "products", ".", "ge...
Resolves the specified confs for the configured targets and returns an iterator over tuples of (conf, jar path).
[ "Resolves", "the", "specified", "confs", "for", "the", "configured", "targets", "and", "returns", "an", "iterator", "over", "tuples", "of", "(", "conf", "jar", "path", ")", "." ]
python
train
43.333333
Parsl/parsl
parsl/executors/low_latency/executor.py
https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/low_latency/executor.py#L118-L142
def _start_local_queue_process(self): """ TODO: docstring """ comm_q = Queue(maxsize=10) self.queue_proc = Process(target=interchange.starter, args=(comm_q,), kwargs={"client_ports": (self.outgoing_q.port, ...
[ "def", "_start_local_queue_process", "(", "self", ")", ":", "comm_q", "=", "Queue", "(", "maxsize", "=", "10", ")", "self", ".", "queue_proc", "=", "Process", "(", "target", "=", "interchange", ".", "starter", ",", "args", "=", "(", "comm_q", ",", ")", ...
TODO: docstring
[ "TODO", ":", "docstring" ]
python
valid
45.36
learningequality/ricecooker
ricecooker/utils/paths.py
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/paths.py#L48-L57
def build_path(levels): """ make a linear directory structure from a list of path levels names levels = ["chefdir", "trees", "test"] builds ./chefdir/trees/test/ """ path = os.path.join(*levels) if not dir_exists(path): os.makedirs(path) return path
[ "def", "build_path", "(", "levels", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "*", "levels", ")", "if", "not", "dir_exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "return", "path" ]
make a linear directory structure from a list of path levels names levels = ["chefdir", "trees", "test"] builds ./chefdir/trees/test/
[ "make", "a", "linear", "directory", "structure", "from", "a", "list", "of", "path", "levels", "names", "levels", "=", "[", "chefdir", "trees", "test", "]", "builds", ".", "/", "chefdir", "/", "trees", "/", "test", "/" ]
python
train
28
Josef-Friedrich/phrydy
phrydy/utils.py
https://github.com/Josef-Friedrich/phrydy/blob/aa13755155977b4776e49f79984f9968ac1d74dc/phrydy/utils.py#L42-L58
def displayable_path(path, separator=u'; '): """Attempts to decode a bytestring path to a unicode object for the purpose of displaying it to the user. If the `path` argument is a list or a tuple, the elements are joined with `separator`. """ if isinstance(path, (list, tuple)): return separat...
[ "def", "displayable_path", "(", "path", ",", "separator", "=", "u'; '", ")", ":", "if", "isinstance", "(", "path", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "separator", ".", "join", "(", "displayable_path", "(", "p", ")", "for", "p", ...
Attempts to decode a bytestring path to a unicode object for the purpose of displaying it to the user. If the `path` argument is a list or a tuple, the elements are joined with `separator`.
[ "Attempts", "to", "decode", "a", "bytestring", "path", "to", "a", "unicode", "object", "for", "the", "purpose", "of", "displaying", "it", "to", "the", "user", ".", "If", "the", "path", "argument", "is", "a", "list", "or", "a", "tuple", "the", "elements",...
python
train
40.941176
mitsei/dlkit
dlkit/services/assessment.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/assessment.py#L3010-L3016
def remove_item(self, *args, **kwargs): """Pass through to provider methods.""" try: self._get_provider_session('assessment_basic_authoring_session').remove_item(*args, **kwargs) except InvalidArgument: self._get_sub_package_provider_session( 'assessment_a...
[ "def", "remove_item", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "_get_provider_session", "(", "'assessment_basic_authoring_session'", ")", ".", "remove_item", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
Pass through to provider methods.
[ "Pass", "through", "to", "provider", "methods", "." ]
python
train
56
tdegeus/cppmat
cppmat/__init__.py
https://github.com/tdegeus/cppmat/blob/0d5031d08ce621a4d3e9c396779d99fd5203aa00/cppmat/__init__.py#L109-L157
def find_eigen(hint=None): r''' Try to find the Eigen library. If successful the include directory is returned. ''' # search with pkgconfig # --------------------- try: import pkgconfig if pkgconfig.installed('eigen3','>3.0.0'): return pkgconfig.parse('eigen3')['include_dirs'][0] except: ...
[ "def", "find_eigen", "(", "hint", "=", "None", ")", ":", "# search with pkgconfig", "# ---------------------", "try", ":", "import", "pkgconfig", "if", "pkgconfig", ".", "installed", "(", "'eigen3'", ",", "'>3.0.0'", ")", ":", "return", "pkgconfig", ".", "parse"...
r''' Try to find the Eigen library. If successful the include directory is returned.
[ "r", "Try", "to", "find", "the", "Eigen", "library", ".", "If", "successful", "the", "include", "directory", "is", "returned", "." ]
python
train
25.857143
sleepyfran/itunespy
itunespy/__init__.py
https://github.com/sleepyfran/itunespy/blob/0e7e931b135b5e0daae49ba68e9167ff4ac73eb5/itunespy/__init__.py#L302-L349
def _url_lookup_builder(id=None, artist_amg_id=None, upc=None, country='US', media='music', entity=None, attribute=None, limit=50): """ Builds the URL to perform the lookup based on the provided data :param id: String. iTunes ID of the artist, album, track, ebook or software :par...
[ "def", "_url_lookup_builder", "(", "id", "=", "None", ",", "artist_amg_id", "=", "None", ",", "upc", "=", "None", ",", "country", "=", "'US'", ",", "media", "=", "'music'", ",", "entity", "=", "None", ",", "attribute", "=", "None", ",", "limit", "=", ...
Builds the URL to perform the lookup based on the provided data :param id: String. iTunes ID of the artist, album, track, ebook or software :param artist_amg_id: String. All Music Guide ID of the artist :param upc: String. UPCs/EANs :param country: String. The two-letter country code for the store you w...
[ "Builds", "the", "URL", "to", "perform", "the", "lookup", "based", "on", "the", "provided", "data", ":", "param", "id", ":", "String", ".", "iTunes", "ID", "of", "the", "artist", "album", "track", "ebook", "or", "software", ":", "param", "artist_amg_id", ...
python
train
42.541667
inasafe/inasafe
safe/gui/tools/help/options_help.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/options_help.py#L19-L32
def options_help(): """Help message for options dialog. .. versionadded:: 3.2.1 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) return me...
[ "def", "options_help", "(", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "message", ".", "add", "(", "m", ".", "Brand", "(", ")", ")", "message", ".", "add", "(", "heading", "(", ")", ")", "message", ".", "add", "(", "content", "(", ...
Help message for options dialog. .. versionadded:: 3.2.1 :returns: A message object containing helpful information. :rtype: messaging.message.Message
[ "Help", "message", "for", "options", "dialog", "." ]
python
train
22.285714
apache/airflow
airflow/models/dagrun.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/dagrun.py#L232-L239
def get_previous_scheduled_dagrun(self, session=None): """The previous, SCHEDULED DagRun, if there is one""" dag = self.get_dag() return session.query(DagRun).filter( DagRun.dag_id == self.dag_id, DagRun.execution_date == dag.previous_schedule(self.execution_date) ...
[ "def", "get_previous_scheduled_dagrun", "(", "self", ",", "session", "=", "None", ")", ":", "dag", "=", "self", ".", "get_dag", "(", ")", "return", "session", ".", "query", "(", "DagRun", ")", ".", "filter", "(", "DagRun", ".", "dag_id", "==", "self", ...
The previous, SCHEDULED DagRun, if there is one
[ "The", "previous", "SCHEDULED", "DagRun", "if", "there", "is", "one" ]
python
test
40.5
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/core/debugger.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/debugger.py#L153-L162
def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): """Make new_fn have old_fn's doc string. This is particularly useful for the do_... commands that hook into the help system. Adapted from from a comp.lang.python posting by Duncan Booth.""" def wrapper(*args, **kw): return new_fn(...
[ "def", "decorate_fn_with_doc", "(", "new_fn", ",", "old_fn", ",", "additional_text", "=", "\"\"", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "return", "new_fn", "(", "*", "args", ",", "*", "*", "kw", ")", "if", "ol...
Make new_fn have old_fn's doc string. This is particularly useful for the do_... commands that hook into the help system. Adapted from from a comp.lang.python posting by Duncan Booth.
[ "Make", "new_fn", "have", "old_fn", "s", "doc", "string", ".", "This", "is", "particularly", "useful", "for", "the", "do_", "...", "commands", "that", "hook", "into", "the", "help", "system", ".", "Adapted", "from", "from", "a", "comp", ".", "lang", ".",...
python
test
42.4
raiden-network/raiden-contracts
raiden_contracts/deploy/contract_deployer.py
https://github.com/raiden-network/raiden-contracts/blob/a7e72a9477f2204b03f3706360ea8d9c0a8e7063/raiden_contracts/deploy/contract_deployer.py#L243-L287
def _register_token_network_without_limits( self, token_registry_abi: Dict, token_registry_address: str, token_address: str, channel_participant_deposit_limit: Optional[int], token_network_deposit_limit: Optional[int], ): """Register to...
[ "def", "_register_token_network_without_limits", "(", "self", ",", "token_registry_abi", ":", "Dict", ",", "token_registry_address", ":", "str", ",", "token_address", ":", "str", ",", "channel_participant_deposit_limit", ":", "Optional", "[", "int", "]", ",", "token_n...
Register token with a TokenNetworkRegistry contract with a contracts-version that doesn't require deposit limits in the TokenNetwork constructor.
[ "Register", "token", "with", "a", "TokenNetworkRegistry", "contract" ]
python
train
39.888889
sprockets/sprockets.clients.statsd
sprockets/clients/statsd/__init__.py
https://github.com/sprockets/sprockets.clients.statsd/blob/34daf6972ebdc5ed1e8fde2ff85b3443b9c04d2c/sprockets/clients/statsd/__init__.py#L166-L181
def _send(key, value, metric_type): """Send the specified value to the statsd daemon via UDP without a direct socket connection. :param str value: The properly formatted statsd counter value """ if STATSD_PREFIX: key = '.'.join([STATSD_PREFIX, key]) try: STATSD_SOCKET.sendto('{...
[ "def", "_send", "(", "key", ",", "value", ",", "metric_type", ")", ":", "if", "STATSD_PREFIX", ":", "key", "=", "'.'", ".", "join", "(", "[", "STATSD_PREFIX", ",", "key", "]", ")", "try", ":", "STATSD_SOCKET", ".", "sendto", "(", "'{0}:{1}|{2}'", ".", ...
Send the specified value to the statsd daemon via UDP without a direct socket connection. :param str value: The properly formatted statsd counter value
[ "Send", "the", "specified", "value", "to", "the", "statsd", "daemon", "via", "UDP", "without", "a", "direct", "socket", "connection", "." ]
python
train
35.25
mikedh/trimesh
trimesh/sample.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/sample.py#L13-L69
def sample_surface(mesh, count): """ Sample the surface of a mesh, returning the specified number of points For individual triangle sampling uses this method: http://mathworld.wolfram.com/TrianglePointPicking.html Parameters --------- mesh: Trimesh object count: number of points to...
[ "def", "sample_surface", "(", "mesh", ",", "count", ")", ":", "# len(mesh.faces) float, array of the areas", "# of each face of the mesh", "area", "=", "mesh", ".", "area_faces", "# total area (float)", "area_sum", "=", "np", ".", "sum", "(", "area", ")", "# cumulativ...
Sample the surface of a mesh, returning the specified number of points For individual triangle sampling uses this method: http://mathworld.wolfram.com/TrianglePointPicking.html Parameters --------- mesh: Trimesh object count: number of points to return Returns --------- sample...
[ "Sample", "the", "surface", "of", "a", "mesh", "returning", "the", "specified", "number", "of", "points" ]
python
train
34.77193
mitsei/dlkit
dlkit/records/assessment/basic/simple_records.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/basic/simple_records.py#L636-L640
def _init_metadata(self): """stub""" TextAnswerFormRecord._init_metadata(self) FilesAnswerFormRecord._init_metadata(self) super(AnswerTextAndFilesMixin, self)._init_metadata()
[ "def", "_init_metadata", "(", "self", ")", ":", "TextAnswerFormRecord", ".", "_init_metadata", "(", "self", ")", "FilesAnswerFormRecord", ".", "_init_metadata", "(", "self", ")", "super", "(", "AnswerTextAndFilesMixin", ",", "self", ")", ".", "_init_metadata", "("...
stub
[ "stub" ]
python
train
40.6
Qiskit/qiskit-terra
qiskit/extensions/standard/rzz.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/rzz.py#L49-L51
def rzz(self, theta, qubit1, qubit2): """Apply RZZ to circuit.""" return self.append(RZZGate(theta), [qubit1, qubit2], [])
[ "def", "rzz", "(", "self", ",", "theta", ",", "qubit1", ",", "qubit2", ")", ":", "return", "self", ".", "append", "(", "RZZGate", "(", "theta", ")", ",", "[", "qubit1", ",", "qubit2", "]", ",", "[", "]", ")" ]
Apply RZZ to circuit.
[ "Apply", "RZZ", "to", "circuit", "." ]
python
test
42.666667
hsolbrig/pyjsg
pyjsg/parser_impl/jsg_arrayexpr_parser.py
https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/parser_impl/jsg_arrayexpr_parser.py#L61-L68
def visitArrayExpr(self, ctx: jsgParser.ArrayExprContext): """ arrayExpr: OBRACKET valueType (BAR valueType)* ebnfSuffix? CBRACKET; """ from pyjsg.parser_impl.jsg_ebnf_parser import JSGEbnf from pyjsg.parser_impl.jsg_valuetype_parser import JSGValueType self._types = [JSGValueType(self....
[ "def", "visitArrayExpr", "(", "self", ",", "ctx", ":", "jsgParser", ".", "ArrayExprContext", ")", ":", "from", "pyjsg", ".", "parser_impl", ".", "jsg_ebnf_parser", "import", "JSGEbnf", "from", "pyjsg", ".", "parser_impl", ".", "jsg_valuetype_parser", "import", "...
arrayExpr: OBRACKET valueType (BAR valueType)* ebnfSuffix? CBRACKET;
[ "arrayExpr", ":", "OBRACKET", "valueType", "(", "BAR", "valueType", ")", "*", "ebnfSuffix?", "CBRACKET", ";" ]
python
train
56
a1ezzz/wasp-general
wasp_general/network/primitives.py
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/primitives.py#L269-L287
def first_address(self, skip_network_address=True): """ Return the first IP address of this network :param skip_network_address: this flag specifies whether this function returns address of the network \ or returns address that follows address of the network (address, that a host could have) :return: WIPV4Addr...
[ "def", "first_address", "(", "self", ",", "skip_network_address", "=", "True", ")", ":", "bin_address", "=", "self", ".", "__address", ".", "bin_address", "(", ")", "bin_address_length", "=", "len", "(", "bin_address", ")", "if", "self", ".", "__mask", ">", ...
Return the first IP address of this network :param skip_network_address: this flag specifies whether this function returns address of the network \ or returns address that follows address of the network (address, that a host could have) :return: WIPV4Address
[ "Return", "the", "first", "IP", "address", "of", "this", "network" ]
python
train
35.210526
carpedm20/fbchat
fbchat/_client.py
https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3333-L3363
def onNicknameChange( self, mid=None, author_id=None, changed_for=None, new_nickname=None, thread_id=None, thread_type=ThreadType.USER, ts=None, metadata=None, msg=None, ): """ Called when the client is listening, and so...
[ "def", "onNicknameChange", "(", "self", ",", "mid", "=", "None", ",", "author_id", "=", "None", ",", "changed_for", "=", "None", ",", "new_nickname", "=", "None", ",", "thread_id", "=", "None", ",", "thread_type", "=", "ThreadType", ".", "USER", ",", "ts...
Called when the client is listening, and somebody changes the nickname of a person :param mid: The action ID :param author_id: The ID of the person who changed the nickname :param changed_for: The ID of the person whom got their nickname changed :param new_nickname: The new nickname ...
[ "Called", "when", "the", "client", "is", "listening", "and", "somebody", "changes", "the", "nickname", "of", "a", "person" ]
python
train
37.193548
ChristianKuehnel/btlewrap
btlewrap/pygatt.py
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/pygatt.py#L9-L27
def wrap_exception(func: Callable) -> Callable: """Decorator to wrap pygatt exceptions into BluetoothBackendException.""" try: # only do the wrapping if pygatt is installed. # otherwise it's pointless anyway from pygatt.backends.bgapi.exceptions import BGAPIError from pygatt.exce...
[ "def", "wrap_exception", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "try", ":", "# only do the wrapping if pygatt is installed.", "# otherwise it's pointless anyway", "from", "pygatt", ".", "backends", ".", "bgapi", ".", "exceptions", "import", "BGAPIErro...
Decorator to wrap pygatt exceptions into BluetoothBackendException.
[ "Decorator", "to", "wrap", "pygatt", "exceptions", "into", "BluetoothBackendException", "." ]
python
train
37.210526
MSchnei/pyprf_feature
pyprf_feature/analysis/utils_hrf.py
https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/utils_hrf.py#L203-L263
def create_boxcar(aryCnd, aryOns, aryDrt, varTr, varNumVol, aryExclCnd=None, varTmpOvsmpl=1000.): """ Creation of condition time courses in temporally upsampled space. Parameters ---------- aryCnd : np.array 1D array with condition identifiers (every condition has its own...
[ "def", "create_boxcar", "(", "aryCnd", ",", "aryOns", ",", "aryDrt", ",", "varTr", ",", "varNumVol", ",", "aryExclCnd", "=", "None", ",", "varTmpOvsmpl", "=", "1000.", ")", ":", "if", "aryExclCnd", "is", "not", "None", ":", "for", "cond", "in", "aryExclC...
Creation of condition time courses in temporally upsampled space. Parameters ---------- aryCnd : np.array 1D array with condition identifiers (every condition has its own int) aryOns : np.array, same len as aryCnd 1D array with condition onset times in seconds. aryDrt : np.array, s...
[ "Creation", "of", "condition", "time", "courses", "in", "temporally", "upsampled", "space", "." ]
python
train
35.836066
pkkid/python-plexapi
plexapi/myplex.py
https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L600-L611
def _loadData(self, data): """ Load attribute values from Plex XML response. """ self._data = data self.id = utils.cast(int, data.attrib.get('id')) self.serverId = utils.cast(int, data.attrib.get('serverId')) self.machineIdentifier = data.attrib.get('machineIdentifier') s...
[ "def", "_loadData", "(", "self", ",", "data", ")", ":", "self", ".", "_data", "=", "data", "self", ".", "id", "=", "utils", ".", "cast", "(", "int", ",", "data", ".", "attrib", ".", "get", "(", "'id'", ")", ")", "self", ".", "serverId", "=", "u...
Load attribute values from Plex XML response.
[ "Load", "attribute", "values", "from", "Plex", "XML", "response", "." ]
python
train
58.666667
UpCloudLtd/upcloud-python-api
upcloud_api/server.py
https://github.com/UpCloudLtd/upcloud-python-api/blob/954b0ad7c4b932b2be31a95d88975f6b0eeac8ed/upcloud_api/server.py#L457-L473
def ensure_started(self): """ Start a server and waits (blocking wait) until it is fully started. """ # server is either starting or stopping (or error) if self.state in ['maintenance', 'error']: self._wait_for_state_change(['stopped', 'started']) if self.sta...
[ "def", "ensure_started", "(", "self", ")", ":", "# server is either starting or stopping (or error)", "if", "self", ".", "state", "in", "[", "'maintenance'", ",", "'error'", "]", ":", "self", ".", "_wait_for_state_change", "(", "[", "'stopped'", ",", "'started'", ...
Start a server and waits (blocking wait) until it is fully started.
[ "Start", "a", "server", "and", "waits", "(", "blocking", "wait", ")", "until", "it", "is", "fully", "started", "." ]
python
train
34.823529
timothydmorton/VESPA
vespa/statutils.py
https://github.com/timothydmorton/VESPA/blob/0446b54d48009f3655cfd1a3957ceea21d3adcaa/vespa/statutils.py#L8-L19
def kdeconf(kde,conf=0.683,xmin=None,xmax=None,npts=500, shortest=True,conftol=0.001,return_max=False): """ Returns desired confidence interval for provided KDE object """ if xmin is None: xmin = kde.dataset.min() if xmax is None: xmax = kde.dataset.max() x = np.linsp...
[ "def", "kdeconf", "(", "kde", ",", "conf", "=", "0.683", ",", "xmin", "=", "None", ",", "xmax", "=", "None", ",", "npts", "=", "500", ",", "shortest", "=", "True", ",", "conftol", "=", "0.001", ",", "return_max", "=", "False", ")", ":", "if", "xm...
Returns desired confidence interval for provided KDE object
[ "Returns", "desired", "confidence", "interval", "for", "provided", "KDE", "object" ]
python
train
37.916667
etalab/cada
cada/csv.py
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/csv.py#L60-L74
def from_row(row): '''Create an advice from a CSV row''' subject = (row[5][0].upper() + row[5][1:]) if row[5] else row[5] return Advice.objects.create( id=row[0], administration=cleanup(row[1]), type=row[2], session=datetime.strptime(row[4], '%d/%m/%Y'), subject=clean...
[ "def", "from_row", "(", "row", ")", ":", "subject", "=", "(", "row", "[", "5", "]", "[", "0", "]", ".", "upper", "(", ")", "+", "row", "[", "5", "]", "[", "1", ":", "]", ")", "if", "row", "[", "5", "]", "else", "row", "[", "5", "]", "re...
Create an advice from a CSV row
[ "Create", "an", "advice", "from", "a", "CSV", "row" ]
python
train
39.266667
earlzo/hfut
hfut/shortcut.py
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L47-L57
def get_class_students(self, xqdm, kcdm, jxbh): """ 教学班查询, 查询指定教学班的所有学生 @structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号 """ return self.query(GetClassStudents(xqdm, kcdm, jxbh))
[ "def", "get_class_students", "(", "self", ",", "xqdm", ",", "kcdm", ",", "jxbh", ")", ":", "return", "self", ".", "query", "(", "GetClassStudents", "(", "xqdm", ",", "kcdm", ",", "jxbh", ")", ")" ]
教学班查询, 查询指定教学班的所有学生 @structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号
[ "教学班查询", "查询指定教学班的所有学生" ]
python
train
27.909091
rosenbrockc/fortpy
fortpy/debug.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/debug.py#L43-L51
def increase_indent(func): """Decorator for makin """ def wrapper(*args, **kwargs): global _debug_indent _debug_indent += 1 result = func(*args, **kwargs) _debug_indent -= 1 return result return wrapper
[ "def", "increase_indent", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "_debug_indent", "_debug_indent", "+=", "1", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "_de...
Decorator for makin
[ "Decorator", "for", "makin" ]
python
train
27.333333
Opentrons/opentrons
api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L1068-L1148
def move(self, target, home_flagged_axes=False): ''' Move to the `target` Smoothieware coordinate, along any of the size axes, XYZABC. target: dict dict setting the coordinate that Smoothieware will be at when `move()` returns. `target` keys are the axis in upper...
[ "def", "move", "(", "self", ",", "target", ",", "home_flagged_axes", "=", "False", ")", ":", "from", "numpy", "import", "isclose", "self", ".", "run_flag", ".", "wait", "(", ")", "def", "valid_movement", "(", "coords", ",", "axis", ")", ":", "return", ...
Move to the `target` Smoothieware coordinate, along any of the size axes, XYZABC. target: dict dict setting the coordinate that Smoothieware will be at when `move()` returns. `target` keys are the axis in upper-case, and the values are the coordinate in millimeters (...
[ "Move", "to", "the", "target", "Smoothieware", "coordinate", "along", "any", "of", "the", "size", "axes", "XYZABC", "." ]
python
train
40.901235
LordSputnik/mutagen
mutagen/ogg.py
https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/ogg.py#L394-L443
def find_last(fileobj, serial): """Find the last page of the stream 'serial'. If the file is not multiplexed this function is fast. If it is, it must read the whole the stream. This finds the last page in the actual file object, or the last page in the stream (with eos set), wh...
[ "def", "find_last", "(", "fileobj", ",", "serial", ")", ":", "# For non-muxed streams, look at the last page.", "try", ":", "fileobj", ".", "seek", "(", "-", "256", "*", "256", ",", "2", ")", "except", "IOError", ":", "# The file is less than 64k in length.", "fil...
Find the last page of the stream 'serial'. If the file is not multiplexed this function is fast. If it is, it must read the whole the stream. This finds the last page in the actual file object, or the last page in the stream (with eos set), whichever comes first.
[ "Find", "the", "last", "page", "of", "the", "stream", "serial", "." ]
python
test
30.28
Terrance/SkPy
skpy/main.py
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/main.py#L120-L129
def setMood(self, mood): """ Update the activity message for the current user. Args: mood (str): new mood message """ self.conn("POST", "{0}/users/{1}/profile/partial".format(SkypeConnection.API_USER, self.userId), auth=SkypeConnection.Auth.SkypeTok...
[ "def", "setMood", "(", "self", ",", "mood", ")", ":", "self", ".", "conn", "(", "\"POST\"", ",", "\"{0}/users/{1}/profile/partial\"", ".", "format", "(", "SkypeConnection", ".", "API_USER", ",", "self", ".", "userId", ")", ",", "auth", "=", "SkypeConnection"...
Update the activity message for the current user. Args: mood (str): new mood message
[ "Update", "the", "activity", "message", "for", "the", "current", "user", "." ]
python
test
42.4
pytroll/satpy
satpy/writers/__init__.py
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/writers/__init__.py#L111-L142
def configs_for_writer(writer=None, ppp_config_dir=None): """Generator of writer configuration files for one or more writers Args: writer (Optional[str]): Yield configs only for this writer ppp_config_dir (Optional[str]): Additional configuration directory to search for writer confi...
[ "def", "configs_for_writer", "(", "writer", "=", "None", ",", "ppp_config_dir", "=", "None", ")", ":", "search_paths", "=", "(", "ppp_config_dir", ",", ")", "if", "ppp_config_dir", "else", "tuple", "(", ")", "if", "writer", "is", "not", "None", ":", "if", ...
Generator of writer configuration files for one or more writers Args: writer (Optional[str]): Yield configs only for this writer ppp_config_dir (Optional[str]): Additional configuration directory to search for writer configuration files. Returns: Generator of lists of configuration...
[ "Generator", "of", "writer", "configuration", "files", "for", "one", "or", "more", "writers" ]
python
train
37.90625
sampottinger/pycotracer
pycotracer/mongo_aggregator.py
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L132-L147
def update_expenditure_entry(database, entry): """Update a record of a expenditure report in the provided database. @param db: The MongoDB database to operate on. The expenditures collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert i...
[ "def", "update_expenditure_entry", "(", "database", ",", "entry", ")", ":", "entry", "=", "clean_entry", "(", "entry", ")", "database", ".", "expenditures", ".", "update", "(", "{", "'recordID'", ":", "entry", "[", "'recordID'", "]", "}", ",", "{", "'$set'...
Update a record of a expenditure report in the provided database. @param db: The MongoDB database to operate on. The expenditures collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert into the database, updating the entry with the ...
[ "Update", "a", "record", "of", "a", "expenditure", "report", "in", "the", "provided", "database", "." ]
python
train
35.875
richardliaw/track
track/convenience.py
https://github.com/richardliaw/track/blob/7ac42ea34e5c1d7bb92fd813e938835a06a63fc7/track/convenience.py#L10-L31
def absl_flags(): """ Extracts absl-py flags that the user has specified and outputs their key-value mapping. By default, extracts only those flags in the current __package__ and mainfile. Useful to put into a trial's param_map. """ # TODO: need same thing for argparse flags_dict =...
[ "def", "absl_flags", "(", ")", ":", "# TODO: need same thing for argparse", "flags_dict", "=", "flags", ".", "FLAGS", ".", "flags_by_module_dict", "(", ")", "# only include parameters from modules the user probably cares about", "def", "_relevant_module", "(", "module_name", ...
Extracts absl-py flags that the user has specified and outputs their key-value mapping. By default, extracts only those flags in the current __package__ and mainfile. Useful to put into a trial's param_map.
[ "Extracts", "absl", "-", "py", "flags", "that", "the", "user", "has", "specified", "and", "outputs", "their", "key", "-", "value", "mapping", "." ]
python
train
33.954545
spyder-ide/spyder
spyder/plugins/onlinehelp/widgets.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/onlinehelp/widgets.py#L80-L84
def initialize(self): """Start pydoc server""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() self.start_server()
[ "def", "initialize", "(", "self", ")", ":", "QApplication", ".", "setOverrideCursor", "(", "QCursor", "(", "Qt", ".", "WaitCursor", ")", ")", "QApplication", ".", "processEvents", "(", ")", "self", ".", "start_server", "(", ")" ]
Start pydoc server
[ "Start", "pydoc", "server" ]
python
train
36.4
aws/aws-encryption-sdk-python
decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/key_providers/counting.py
https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/key_providers/counting.py#L80-L99
def _decrypt_data_key( self, encrypted_data_key: EncryptedDataKey, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text] ) -> DataKey: """Decrypt an encrypted data key and return the plaintext. :param data_key: Encrypted data key :type data_key: aws_encryption_sdk.structur...
[ "def", "_decrypt_data_key", "(", "self", ",", "encrypted_data_key", ":", "EncryptedDataKey", ",", "algorithm", ":", "AlgorithmSuite", ",", "encryption_context", ":", "Dict", "[", "Text", ",", "Text", "]", ")", "->", "DataKey", ":", "if", "encrypted_data_key", "....
Decrypt an encrypted data key and return the plaintext. :param data_key: Encrypted data key :type data_key: aws_encryption_sdk.structures.EncryptedDataKey :param algorithm: Algorithm object which directs how this Master Key will encrypt the data key :type algorithm: aws_encryption_sdk.i...
[ "Decrypt", "an", "encrypted", "data", "key", "and", "return", "the", "plaintext", "." ]
python
train
53.55
pandas-dev/pandas
pandas/io/json/normalize.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/json/normalize.py#L99-L286
def json_normalize(data, record_path=None, meta=None, meta_prefix=None, record_prefix=None, errors='raise', sep='.'): """ Normalize semi-structured JSON data into a flat table. Parameters ---------- data : dict or list of d...
[ "def", "json_normalize", "(", "data", ",", "record_path", "=", "None", ",", "meta", "=", "None", ",", "meta_prefix", "=", "None", ",", "record_prefix", "=", "None", ",", "errors", "=", "'raise'", ",", "sep", "=", "'.'", ")", ":", "def", "_pull_field", ...
Normalize semi-structured JSON data into a flat table. Parameters ---------- data : dict or list of dicts Unserialized JSON objects record_path : string or list of strings, default None Path in each object to list of records. If not passed, data will be assumed to be an array of...
[ "Normalize", "semi", "-", "structured", "JSON", "data", "into", "a", "flat", "table", "." ]
python
train
35.553191
nuagenetworks/bambou
bambou/nurest_connection.py
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L427-L440
def start(self): """ Make an HTTP request with a specific method """ # TODO : Use Timeout here and _ignore_request_idle from .nurest_session import NURESTSession session = NURESTSession.get_current_session() if self.async: thread = threading.Thread(target=self._make...
[ "def", "start", "(", "self", ")", ":", "# TODO : Use Timeout here and _ignore_request_idle", "from", ".", "nurest_session", "import", "NURESTSession", "session", "=", "NURESTSession", ".", "get_current_session", "(", ")", "if", "self", ".", "async", ":", "thread", "...
Make an HTTP request with a specific method
[ "Make", "an", "HTTP", "request", "with", "a", "specific", "method" ]
python
train
35.714286
bretth/woven
woven/webservers.py
https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L84-L97
def _ls_sites(path): """ List only sites in the domain_sites() to ensure we co-exist with other projects """ with cd(path): sites = run('ls').split('\n') doms = [d.name for d in domain_sites()] dom_sites = [] for s in sites: ds = s.split('-')[0] d...
[ "def", "_ls_sites", "(", "path", ")", ":", "with", "cd", "(", "path", ")", ":", "sites", "=", "run", "(", "'ls'", ")", ".", "split", "(", "'\\n'", ")", "doms", "=", "[", "d", ".", "name", "for", "d", "in", "domain_sites", "(", ")", "]", "dom_si...
List only sites in the domain_sites() to ensure we co-exist with other projects
[ "List", "only", "sites", "in", "the", "domain_sites", "()", "to", "ensure", "we", "co", "-", "exist", "with", "other", "projects" ]
python
train
31.214286
decryptus/sonicprobe
sonicprobe/libs/daemonize.py
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/daemonize.py#L186-L234
def daemonize(): """ Daemonize the program, ie. make it run in the "background", detach it from its controlling terminal and from its controlling process group session. NOTES: - This function also umask(0) and chdir("/") - stdin, stdout, and stderr are redirected from/to /dev/null ...
[ "def", "daemonize", "(", ")", ":", "try", ":", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", ">", "0", ":", "os", ".", "_exit", "(", "0", ")", "# pylint: disable-msg=W0212", "except", "OSError", ",", "e", ":", "log", ".", "exception", "(", ...
Daemonize the program, ie. make it run in the "background", detach it from its controlling terminal and from its controlling process group session. NOTES: - This function also umask(0) and chdir("/") - stdin, stdout, and stderr are redirected from/to /dev/null SEE ALSO: http://...
[ "Daemonize", "the", "program", "ie", ".", "make", "it", "run", "in", "the", "background", "detach", "it", "from", "its", "controlling", "terminal", "and", "from", "its", "controlling", "process", "group", "session", "." ]
python
train
29.204082
twilio/twilio-python
twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py#L92-L106
def get_instance(self, payload): """ Build an instance of WorkflowRealTimeStatisticsInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance :rtype: twilio...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "WorkflowRealTimeStatisticsInstance", "(", "self", ".", "_version", ",", "payload", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspace_sid'", "]", ",", "workflow_sid", "="...
Build an instance of WorkflowRealTimeStatisticsInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_...
[ "Build", "an", "instance", "of", "WorkflowRealTimeStatisticsInstance" ]
python
train
43.066667
raiden-network/raiden
raiden/transfer/node.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L1183-L1232
def is_transaction_invalidated(transaction, state_change): """ True if the `transaction` is made invalid by `state_change`. Some transactions will fail due to race conditions. The races are: - Another transaction which has the same side effect is executed before. - Another transaction which *invalidat...
[ "def", "is_transaction_invalidated", "(", "transaction", ",", "state_change", ")", ":", "# Most transactions cannot be invalidated by others. These are:", "#", "# - close transactions", "# - settle transactions", "# - batch unlocks", "#", "# Deposits and withdraws are invalidated by the ...
True if the `transaction` is made invalid by `state_change`. Some transactions will fail due to race conditions. The races are: - Another transaction which has the same side effect is executed before. - Another transaction which *invalidates* the state of the smart contract required by the local trans...
[ "True", "if", "the", "transaction", "is", "made", "invalid", "by", "state_change", "." ]
python
train
41.66
awslabs/serverless-application-model
samtranslator/model/sam_resources.py
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L186-L246
def _construct_role(self, managed_policy_map): """Constructs a Lambda execution role based on this SAM function's Policies property. :returns: the generated IAM Role :rtype: model.iam.IAMRole """ execution_role = IAMRole(self.logical_id + 'Role', attributes=self.get_passthrough_...
[ "def", "_construct_role", "(", "self", ",", "managed_policy_map", ")", ":", "execution_role", "=", "IAMRole", "(", "self", ".", "logical_id", "+", "'Role'", ",", "attributes", "=", "self", ".", "get_passthrough_resource_attributes", "(", ")", ")", "execution_role"...
Constructs a Lambda execution role based on this SAM function's Policies property. :returns: the generated IAM Role :rtype: model.iam.IAMRole
[ "Constructs", "a", "Lambda", "execution", "role", "based", "on", "this", "SAM", "function", "s", "Policies", "property", "." ]
python
train
50.590164
mattja/nsim
nsim/nsim.py
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1594-L1636
def _tosubs(self, ixlist): """Maps a list of integer indices to sub-indices. ixlist can contain repeated indices and does not need to be sorted. Returns pair (ss, ms) where ss is a list of subsim numbers and ms is a list of lists of subindices m (one list for each subsim in ss). ...
[ "def", "_tosubs", "(", "self", ",", "ixlist", ")", ":", "n", "=", "len", "(", "ixlist", ")", "N", "=", "self", ".", "_n", "ss", "=", "[", "]", "ms", "=", "[", "]", "if", "n", "==", "0", ":", "return", "ss", ",", "ms", "j", "=", "0", "# th...
Maps a list of integer indices to sub-indices. ixlist can contain repeated indices and does not need to be sorted. Returns pair (ss, ms) where ss is a list of subsim numbers and ms is a list of lists of subindices m (one list for each subsim in ss).
[ "Maps", "a", "list", "of", "integer", "indices", "to", "sub", "-", "indices", ".", "ixlist", "can", "contain", "repeated", "indices", "and", "does", "not", "need", "to", "be", "sorted", ".", "Returns", "pair", "(", "ss", "ms", ")", "where", "ss", "is",...
python
train
36.488372
romanorac/discomll
discomll/classification/naivebayes.py
https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/classification/naivebayes.py#L17-L57
def map_fit(interface, state, label, inp): """ Function counts occurrences of feature values for every row in given data chunk. For continuous features it returns number of values and it calculates mean and variance for every feature. For discrete features it counts occurrences of labels and values for ...
[ "def", "map_fit", "(", "interface", ",", "state", ",", "label", ",", "inp", ")", ":", "import", "numpy", "as", "np", "combiner", "=", "{", "}", "# combiner used for joining of intermediate pairs", "out", "=", "interface", ".", "output", "(", "0", ")", "# all...
Function counts occurrences of feature values for every row in given data chunk. For continuous features it returns number of values and it calculates mean and variance for every feature. For discrete features it counts occurrences of labels and values for every feature. It returns occurrences of pairs: lab...
[ "Function", "counts", "occurrences", "of", "feature", "values", "for", "every", "row", "in", "given", "data", "chunk", ".", "For", "continuous", "features", "it", "returns", "number", "of", "values", "and", "it", "calculates", "mean", "and", "variance", "for",...
python
train
52.780488
brandonxiang/geojson-python-utils
geojson_utils/merger.py
https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/merger.py#L22-L55
def simplify_other(major, minor, dist): """ Simplify the point featurecollection of poi with another point features accoording by distance. Attention: point featurecollection only Keyword arguments: major -- major geojson minor -- minor geojson dist -- distance return a geoj...
[ "def", "simplify_other", "(", "major", ",", "minor", ",", "dist", ")", ":", "result", "=", "deepcopy", "(", "major", ")", "if", "major", "[", "'type'", "]", "==", "'FeatureCollection'", "and", "minor", "[", "'type'", "]", "==", "'FeatureCollection'", ":", ...
Simplify the point featurecollection of poi with another point features accoording by distance. Attention: point featurecollection only Keyword arguments: major -- major geojson minor -- minor geojson dist -- distance return a geojson featurecollection with two parts of featurecolle...
[ "Simplify", "the", "point", "featurecollection", "of", "poi", "with", "another", "point", "features", "accoording", "by", "distance", ".", "Attention", ":", "point", "featurecollection", "only" ]
python
train
38.676471
airspeed-velocity/asv
asv/feed.py
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/feed.py#L201-L217
def _get_id(owner, date, content): """ Generate an unique Atom id for the given content """ h = hashlib.sha256() # Hash still contains the original project url, keep as is h.update("github.com/spacetelescope/asv".encode('utf-8')) for x in content: if x is None: h.update("...
[ "def", "_get_id", "(", "owner", ",", "date", ",", "content", ")", ":", "h", "=", "hashlib", ".", "sha256", "(", ")", "# Hash still contains the original project url, keep as is", "h", ".", "update", "(", "\"github.com/spacetelescope/asv\"", ".", "encode", "(", "'u...
Generate an unique Atom id for the given content
[ "Generate", "an", "unique", "Atom", "id", "for", "the", "given", "content" ]
python
train
33.411765
ChrisCummins/labm8
fs.py
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/fs.py#L281-L301
def lsfiles(root=".", **kwargs): """ Return only files from a directory listing. Arguments: root (str): Path to directory. Can be relative or absolute. **kwargs: Any additional arguments to be passed to ls(). Returns: list of str: A list of file paths. Raises: O...
[ "def", "lsfiles", "(", "root", "=", "\".\"", ",", "*", "*", "kwargs", ")", ":", "paths", "=", "ls", "(", "root", "=", "root", ",", "*", "*", "kwargs", ")", "if", "isfile", "(", "root", ")", ":", "return", "paths", "return", "[", "_path", "for", ...
Return only files from a directory listing. Arguments: root (str): Path to directory. Can be relative or absolute. **kwargs: Any additional arguments to be passed to ls(). Returns: list of str: A list of file paths. Raises: OSError: If root directory does not exist.
[ "Return", "only", "files", "from", "a", "directory", "listing", "." ]
python
train
23.52381
alevinval/scheduling
scheduling/scheduler.py
https://github.com/alevinval/scheduling/blob/127239712c0b73b929ca19b4b5c2855eebb7fcf0/scheduling/scheduler.py#L41-L46
def run(self): """ Run the schedule """ self.main_task.thread.start() self.main_task.thread.join()
[ "def", "run", "(", "self", ")", ":", "self", ".", "main_task", ".", "thread", ".", "start", "(", ")", "self", ".", "main_task", ".", "thread", ".", "join", "(", ")" ]
Run the schedule
[ "Run", "the", "schedule" ]
python
train
22.166667