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
HDI-Project/BTB
btb/tuning/gp.py
https://github.com/HDI-Project/BTB/blob/7f489ebc5591bd0886652ef743098c022d7f7460/btb/tuning/gp.py#L97-L115
def fit(self, X, y): """ Train a gaussian process like normal, then compute a "Probability Of Uniform selection" (POU) value. """ # first, train a gaussian process like normal super(GPEiVelocity, self).fit(X, y) # probability of uniform self.POU = 0 ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "# first, train a gaussian process like normal", "super", "(", "GPEiVelocity", ",", "self", ")", ".", "fit", "(", "X", ",", "y", ")", "# probability of uniform", "self", ".", "POU", "=", "0", "if", ...
Train a gaussian process like normal, then compute a "Probability Of Uniform selection" (POU) value.
[ "Train", "a", "gaussian", "process", "like", "normal", "then", "compute", "a", "Probability", "Of", "Uniform", "selection", "(", "POU", ")", "value", "." ]
python
train
40.315789
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/device_directory/apis/default_api.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/apis/default_api.py#L535-L559
def device_log_list(self, **kwargs): # noqa: E501 """DEPRECATED: List all device events. # noqa: E501 DEPRECATED: List all device events. Use `/v3/device-events/` instead. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, plea...
[ "def", "device_log_list", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ".", "device_log_list_with_htt...
DEPRECATED: List all device events. # noqa: E501 DEPRECATED: List all device events. Use `/v3/device-events/` instead. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.device_log_...
[ "DEPRECATED", ":", "List", "all", "device", "events", ".", "#", "noqa", ":", "E501" ]
python
train
162.64
Miserlou/Zappa
zappa/cli.py
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2443-L2455
def remove_local_zip(self): """ Remove our local zip file. """ if self.stage_config.get('delete_local_zip', True): try: if os.path.isfile(self.zip_path): os.remove(self.zip_path) if self.handler_path and os.path.isfile(self...
[ "def", "remove_local_zip", "(", "self", ")", ":", "if", "self", ".", "stage_config", ".", "get", "(", "'delete_local_zip'", ",", "True", ")", ":", "try", ":", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "zip_path", ")", ":", "os", ".", ...
Remove our local zip file.
[ "Remove", "our", "local", "zip", "file", "." ]
python
train
35
Clinical-Genomics/trailblazer
trailblazer/store/api.py
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/store/api.py#L26-L33
def find_analysis(self, family, started_at, status): """Find a single analysis.""" query = self.Analysis.query.filter_by( family=family, started_at=started_at, status=status, ) return query.first()
[ "def", "find_analysis", "(", "self", ",", "family", ",", "started_at", ",", "status", ")", ":", "query", "=", "self", ".", "Analysis", ".", "query", ".", "filter_by", "(", "family", "=", "family", ",", "started_at", "=", "started_at", ",", "status", "=",...
Find a single analysis.
[ "Find", "a", "single", "analysis", "." ]
python
train
32.25
chaoss/grimoirelab-perceval
perceval/backends/core/slack.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/slack.py#L98-L158
def fetch_items(self, category, **kwargs): """Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] latest = kwargs['latest'] logger.info("F...
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "latest", "=", "kwargs", "[", "'latest'", "]", "logger", ".", "info", "(", "\"Fetching messages of '%s' channel from %s\...
Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
[ "Fetch", "the", "messages" ]
python
test
33.213115
BerkeleyAutomation/perception
perception/kinect2_sensor.py
https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/kinect2_sensor.py#L168-L213
def start(self): """Starts the Kinect v2 sensor stream. Raises ------ IOError If the Kinect v2 is not detected. """ # open packet pipeline if self._packet_pipeline_mode == Kinect2PacketPipelineMode.OPENGL: self._pipeline = lf2.OpenGLPacket...
[ "def", "start", "(", "self", ")", ":", "# open packet pipeline", "if", "self", ".", "_packet_pipeline_mode", "==", "Kinect2PacketPipelineMode", ".", "OPENGL", ":", "self", ".", "_pipeline", "=", "lf2", ".", "OpenGLPacketPipeline", "(", ")", "elif", "self", ".", ...
Starts the Kinect v2 sensor stream. Raises ------ IOError If the Kinect v2 is not detected.
[ "Starts", "the", "Kinect", "v2", "sensor", "stream", "." ]
python
train
40.847826
vals/umis
umis/umis.py
https://github.com/vals/umis/blob/e8adb8486d9e9134ab8a6cad9811a7e74dcc4a2c/umis/umis.py#L334-L348
def _extract_readnum(read_dict): """Extract read numbers from old-style fastqs. Handles read 1 and 2 specifications where naming is readname/1 readname/2 """ pat = re.compile(r"(?P<readnum>/\d+)$") parts = pat.split(read_dict["name"]) if len(parts) == 3: name, readnum, endofline = p...
[ "def", "_extract_readnum", "(", "read_dict", ")", ":", "pat", "=", "re", ".", "compile", "(", "r\"(?P<readnum>/\\d+)$\"", ")", "parts", "=", "pat", ".", "split", "(", "read_dict", "[", "\"name\"", "]", ")", "if", "len", "(", "parts", ")", "==", "3", ":...
Extract read numbers from old-style fastqs. Handles read 1 and 2 specifications where naming is readname/1 readname/2
[ "Extract", "read", "numbers", "from", "old", "-", "style", "fastqs", "." ]
python
train
29.8
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_aaa.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_aaa.py#L161-L169
def service_password_encryption(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") service = ET.SubElement(config, "service", xmlns="urn:brocade.com:mgmt:brocade-aaa") password_encryption = ET.SubElement(service, "password-encryption") callback = k...
[ "def", "service_password_encryption", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "service", "=", "ET", ".", "SubElement", "(", "config", ",", "\"service\"", ",", "xmlns", "=", "\"urn:brocade...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
42.333333
pyapi-gitlab/pyapi-gitlab
gitlab/base.py
https://github.com/pyapi-gitlab/pyapi-gitlab/blob/f74b6fb5c13cecae9524997847e928905cc60acf/gitlab/base.py#L55-L74
def get(self, uri, default_response=None, **kwargs): """ Call GET on the Gitlab server >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False) >>> gitlab.login(user='root', password='5iveL!fe') >>> gitlab.get('/users/5') :param uri: String with the URI for ...
[ "def", "get", "(", "self", ",", "uri", ",", "default_response", "=", "None", ",", "*", "*", "kwargs", ")", ":", "url", "=", "self", ".", "api_url", "+", "uri", "response", "=", "requests", ".", "get", "(", "url", ",", "params", "=", "kwargs", ",", ...
Call GET on the Gitlab server >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False) >>> gitlab.login(user='root', password='5iveL!fe') >>> gitlab.get('/users/5') :param uri: String with the URI for the endpoint to GET from :param default_response: Return value if...
[ "Call", "GET", "on", "the", "Gitlab", "server" ]
python
train
44.65
tango-controls/pytango
tango/tango_object.py
https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/tango_object.py#L476-L501
def get_devices(self): """ Helper that retuns a dict of devices for this server. :return: Returns a tuple of two elements: - dict<tango class name : list of device names> - dict<device names : tango class name> :rtype: tuple<dict, dict> ""...
[ "def", "get_devices", "(", "self", ")", ":", "if", "self", ".", "__util", "is", "None", ":", "import", "tango", "db", "=", "tango", ".", "Database", "(", ")", "else", ":", "db", "=", "self", ".", "__util", ".", "get_database", "(", ")", "server", "...
Helper that retuns a dict of devices for this server. :return: Returns a tuple of two elements: - dict<tango class name : list of device names> - dict<device names : tango class name> :rtype: tuple<dict, dict>
[ "Helper", "that", "retuns", "a", "dict", "of", "devices", "for", "this", "server", "." ]
python
train
36.076923
uber/doubles
doubles/target.py
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L64-L74
def _determine_doubled_obj_type(self): """Returns the type (class) of the target object. :return: The type (class) of the target. :rtype: type, classobj """ if isclass(self.doubled_obj) or ismodule(self.doubled_obj): return self.doubled_obj return self.doub...
[ "def", "_determine_doubled_obj_type", "(", "self", ")", ":", "if", "isclass", "(", "self", ".", "doubled_obj", ")", "or", "ismodule", "(", "self", ".", "doubled_obj", ")", ":", "return", "self", ".", "doubled_obj", "return", "self", ".", "doubled_obj", ".", ...
Returns the type (class) of the target object. :return: The type (class) of the target. :rtype: type, classobj
[ "Returns", "the", "type", "(", "class", ")", "of", "the", "target", "object", "." ]
python
train
29.727273
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#L630-L654
def set_active_current(self, settings): ''' Sets the amperage of each motor for when it is activated by driver. Values are initialized from the `robot_config.high_current` values, and can then be changed through this method by other parts of the API. For example, `Pipette` setti...
[ "def", "set_active_current", "(", "self", ",", "settings", ")", ":", "self", ".", "_active_current_settings", "[", "'now'", "]", ".", "update", "(", "settings", ")", "# if an axis specified in the `settings` is currently active,", "# reset it's current to the new active-curre...
Sets the amperage of each motor for when it is activated by driver. Values are initialized from the `robot_config.high_current` values, and can then be changed through this method by other parts of the API. For example, `Pipette` setting the active-current of it's pipette, depending on ...
[ "Sets", "the", "amperage", "of", "each", "motor", "for", "when", "it", "is", "activated", "by", "driver", ".", "Values", "are", "initialized", "from", "the", "robot_config", ".", "high_current", "values", "and", "can", "then", "be", "changed", "through", "th...
python
train
45.92
CloudGenix/sdk-python
cloudgenix/__init__.py
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L755-L890
def rest_call(self, url, method, data=None, sensitive=False, timeout=None, content_json=True, retry=None, max_retry=None, retry_sleep=None): """ Generic REST call worker function **Parameters:** - **url:** URL for the REST call - **method:** METHOD for the...
[ "def", "rest_call", "(", "self", ",", "url", ",", "method", ",", "data", "=", "None", ",", "sensitive", "=", "False", ",", "timeout", "=", "None", ",", "content_json", "=", "True", ",", "retry", "=", "None", ",", "max_retry", "=", "None", ",", "retry...
Generic REST call worker function **Parameters:** - **url:** URL for the REST call - **method:** METHOD for the REST call - **data:** Optional DATA for the call (for POST/PUT/etc.) - **sensitive:** Flag if content request/response should be hidden from logging functions...
[ "Generic", "REST", "call", "worker", "function" ]
python
train
47.154412
Apstra/aeon-venos
pylib/aeon/nxos/autoload/install_os.py
https://github.com/Apstra/aeon-venos/blob/4d4f73d5904831ddc78c30922a8a226c90cf7d90/pylib/aeon/nxos/autoload/install_os.py#L56-L76
def copy_from(self, location, timeout=10 * 60): """ This method will fetch the image; the fetch will happen from the device-side using the 'copy' command. Note that the NXAPI appears to be single-threaded, so the code needs to wait until this operation has completed before attem...
[ "def", "copy_from", "(", "self", ",", "location", ",", "timeout", "=", "10", "*", "60", ")", ":", "cmd", "=", "'copy {location} {dir}: vrf {vrf_name}'", ".", "format", "(", "location", "=", "location", ",", "dir", "=", "self", ".", "DESTDIR", ",", "vrf_nam...
This method will fetch the image; the fetch will happen from the device-side using the 'copy' command. Note that the NXAPI appears to be single-threaded, so the code needs to wait until this operation has completed before attempting another API call. Therefore the :timeout: value is se...
[ "This", "method", "will", "fetch", "the", "image", ";", "the", "fetch", "will", "happen", "from", "the", "device", "-", "side", "using", "the", "copy", "command", ".", "Note", "that", "the", "NXAPI", "appears", "to", "be", "single", "-", "threaded", "so"...
python
train
39.761905
koszullab/metaTOR
metator/metator.py
https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/metator.py#L97-L111
def main(): """This module just acts as an entry point to the bulk of the pipeline. All argument parsing is delegated to metator.sh """ metator_args = sys.argv[1:] entry_point = pkg_resources.resource_filename("metator", "bin/metator.sh") try: metator_process = subprocess.Popen((entry_...
[ "def", "main", "(", ")", ":", "metator_args", "=", "sys", ".", "argv", "[", "1", ":", "]", "entry_point", "=", "pkg_resources", ".", "resource_filename", "(", "\"metator\"", ",", "\"bin/metator.sh\"", ")", "try", ":", "metator_process", "=", "subprocess", "....
This module just acts as an entry point to the bulk of the pipeline. All argument parsing is delegated to metator.sh
[ "This", "module", "just", "acts", "as", "an", "entry", "point", "to", "the", "bulk", "of", "the", "pipeline", ".", "All", "argument", "parsing", "is", "delegated", "to", "metator", ".", "sh" ]
python
train
35.466667
noahbenson/neuropythy
neuropythy/geometry/mesh.py
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/geometry/mesh.py#L3912-L3932
def close_path_traces(*args): ''' close_path_traces(pt1, pt2...) yields the path-trace formed by joining the list of path traces at their intersection points in the order given. Note that the direction in which each individual path trace's coordinates are specified is ultimately ignored by this func...
[ "def", "close_path_traces", "(", "*", "args", ")", ":", "pts", "=", "[", "x", "for", "x", "in", "args", "if", "is_path_trace", "(", "x", ")", "]", "if", "len", "(", "pts", ")", "==", "0", ":", "if", "len", "(", "args", ")", "==", "1", "and", ...
close_path_traces(pt1, pt2...) yields the path-trace formed by joining the list of path traces at their intersection points in the order given. Note that the direction in which each individual path trace's coordinates are specified is ultimately ignored by this function--the only ordering that matters...
[ "close_path_traces", "(", "pt1", "pt2", "...", ")", "yields", "the", "path", "-", "trace", "formed", "by", "joining", "the", "list", "of", "path", "traces", "at", "their", "intersection", "points", "in", "the", "order", "given", ".", "Note", "that", "the",...
python
train
57.047619
materialsproject/pymatgen
pymatgen/analysis/eos.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/eos.py#L311-L318
def _func(self, volume, params): """ Pourier-Tarantola equation from PRB 70, 224107 """ e0, b0, b1, v0 = tuple(params) eta = (volume / v0) ** (1. / 3.) squiggle = -3.*np.log(eta) return e0 + b0 * v0 * squiggle ** 2 / 6. * (3. + squiggle * (b1 - 2))
[ "def", "_func", "(", "self", ",", "volume", ",", "params", ")", ":", "e0", ",", "b0", ",", "b1", ",", "v0", "=", "tuple", "(", "params", ")", "eta", "=", "(", "volume", "/", "v0", ")", "**", "(", "1.", "/", "3.", ")", "squiggle", "=", "-", ...
Pourier-Tarantola equation from PRB 70, 224107
[ "Pourier", "-", "Tarantola", "equation", "from", "PRB", "70", "224107" ]
python
train
37.125
sosy-lab/benchexec
benchexec/cgroups.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/cgroups.py#L312-L318
def get_all_tasks(self, subsystem): """ Return a generator of all PIDs currently in this cgroup for the given subsystem. """ with open(os.path.join(self.per_subsystem[subsystem], 'tasks'), 'r') as tasksFile: for line in tasksFile: yield int(line)
[ "def", "get_all_tasks", "(", "self", ",", "subsystem", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "per_subsystem", "[", "subsystem", "]", ",", "'tasks'", ")", ",", "'r'", ")", "as", "tasksFile", ":", "for", "line...
Return a generator of all PIDs currently in this cgroup for the given subsystem.
[ "Return", "a", "generator", "of", "all", "PIDs", "currently", "in", "this", "cgroup", "for", "the", "given", "subsystem", "." ]
python
train
42.857143
twisted/txaws
txaws/route53/client.py
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/route53/client.py#L60-L73
def get_route53_client(agent, region, cooperator=None): """ Get a non-registration Route53 client. """ if cooperator is None: cooperator = task return region.get_client( _Route53Client, agent=agent, creds=region.creds, region=REGION_US_EAST_1, endpoint...
[ "def", "get_route53_client", "(", "agent", ",", "region", ",", "cooperator", "=", "None", ")", ":", "if", "cooperator", "is", "None", ":", "cooperator", "=", "task", "return", "region", ".", "get_client", "(", "_Route53Client", ",", "agent", "=", "agent", ...
Get a non-registration Route53 client.
[ "Get", "a", "non", "-", "registration", "Route53", "client", "." ]
python
train
27.214286
Diviyan-Kalainathan/CausalDiscoveryToolbox
cdt/causality/graph/CGNN.py
https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CGNN.py#L127-L145
def run(self, data, train_epochs=1000, test_epochs=1000, verbose=None, idx=0, lr=0.01, **kwargs): """Run the CGNN on a given graph.""" verbose = SETTINGS.get_default(verbose=verbose) optim = th.optim.Adam(self.parameters(), lr=lr) self.score.zero_() with trange(train_...
[ "def", "run", "(", "self", ",", "data", ",", "train_epochs", "=", "1000", ",", "test_epochs", "=", "1000", ",", "verbose", "=", "None", ",", "idx", "=", "0", ",", "lr", "=", "0.01", ",", "*", "*", "kwargs", ")", ":", "verbose", "=", "SETTINGS", "...
Run the CGNN on a given graph.
[ "Run", "the", "CGNN", "on", "a", "given", "graph", "." ]
python
valid
43.684211
petl-developers/petlx
petlx/bio/gff3.py
https://github.com/petl-developers/petlx/blob/54039e30388c7da12407d6b5c3cb865b00436004/petlx/bio/gff3.py#L17-L33
def gff3_parse_attributes(attributes_string): """ Parse a string of GFF3 attributes ('key=value' pairs delimited by ';') and return a dictionary. """ attributes = dict() fields = attributes_string.split(';') for f in fields: if '=' in f: key, value = f.split('=')...
[ "def", "gff3_parse_attributes", "(", "attributes_string", ")", ":", "attributes", "=", "dict", "(", ")", "fields", "=", "attributes_string", ".", "split", "(", "';'", ")", "for", "f", "in", "fields", ":", "if", "'='", "in", "f", ":", "key", ",", "value",...
Parse a string of GFF3 attributes ('key=value' pairs delimited by ';') and return a dictionary.
[ "Parse", "a", "string", "of", "GFF3", "attributes", "(", "key", "=", "value", "pairs", "delimited", "by", ";", ")", "and", "return", "a", "dictionary", "." ]
python
train
31.294118
KnowledgeLinks/rdfframework
rdfframework/connections/connmanager.py
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L135-L149
def get(self, conn_name, default=None, **kwargs): """ returns the specified connection args: conn_name: the name of the connection """ if isinstance(conn_name, RdfwConnections): return conn_name try: return self.conns[conn_name] excep...
[ "def", "get", "(", "self", ",", "conn_name", ",", "default", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "conn_name", ",", "RdfwConnections", ")", ":", "return", "conn_name", "try", ":", "return", "self", ".", "conns", "[",...
returns the specified connection args: conn_name: the name of the connection
[ "returns", "the", "specified", "connection" ]
python
train
31.333333
jonashaag/django-addanother
django_addanother/widgets.py
https://github.com/jonashaag/django-addanother/blob/83dc0c8cc7665cc481dd58da0b9a746972264046/django_addanother/widgets.py#L28-L31
def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs
[ "def", "build_attrs", "(", "self", ",", "extra_attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "attrs", "=", "self", ".", "widget", ".", "build_attrs", "(", "extra_attrs", "=", "None", ",", "*", "*", "kwargs", ")", "return", "sel...
Helper function for building an attribute dictionary.
[ "Helper", "function", "for", "building", "an", "attribute", "dictionary", "." ]
python
test
52.5
tensorflow/tensor2tensor
tensor2tensor/data_generators/mnist.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/mnist.py#L69-L83
def _extract_mnist_labels(filename, num_labels): """Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A int64 numpy array of shape [num_labels] """ with gzip.open(filename) as bytestream: ...
[ "def", "_extract_mnist_labels", "(", "filename", ",", "num_labels", ")", ":", "with", "gzip", ".", "open", "(", "filename", ")", "as", "bytestream", ":", "bytestream", ".", "read", "(", "8", ")", "buf", "=", "bytestream", ".", "read", "(", "num_labels", ...
Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A int64 numpy array of shape [num_labels]
[ "Extract", "labels", "from", "an", "MNIST", "file", "into", "integers", "." ]
python
train
29.533333
DataDog/integrations-core
tokumx/datadog_checks/tokumx/vendor/pymongo/cursor.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/cursor.py#L1033-L1080
def _refresh(self): """Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error on the query. """ if l...
[ "def", "_refresh", "(", "self", ")", ":", "if", "len", "(", "self", ".", "__data", ")", "or", "self", ".", "__killed", ":", "return", "len", "(", "self", ".", "__data", ")", "if", "self", ".", "__id", "is", "None", ":", "# Query", "self", ".", "_...
Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error on the query.
[ "Refreshes", "the", "cursor", "with", "more", "data", "from", "Mongo", "." ]
python
train
44.020833
saltstack/salt
salt/cloud/clouds/msazure.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L901-L1016
def destroy(name, conn=None, call=None, kwargs=None): ''' Destroy a VM CLI Examples: .. code-block:: bash salt-cloud -d myminion salt-cloud -a destroy myminion service_name=myservice ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action ...
[ "def", "destroy", "(", "name", ",", "conn", "=", "None", ",", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "call", "==", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The destroy action must be called with -d, --destroy, '", "'-a ...
Destroy a VM CLI Examples: .. code-block:: bash salt-cloud -d myminion salt-cloud -a destroy myminion service_name=myservice
[ "Destroy", "a", "VM" ]
python
train
33.637931
uchicago-cs/deepdish
deepdish/image.py
https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/image.py#L135-L157
def load(path, dtype=np.float64): """ Loads an image from file. Parameters ---------- path : str Path to image file. dtype : np.dtype Defaults to ``np.float64``, which means the image will be returned as a float with values between 0 and 1. If ``np.uint8`` is specified, ...
[ "def", "load", "(", "path", ",", "dtype", "=", "np", ".", "float64", ")", ":", "_import_skimage", "(", ")", "import", "skimage", ".", "io", "im", "=", "skimage", ".", "io", ".", "imread", "(", "path", ")", "if", "dtype", "==", "np", ".", "uint8", ...
Loads an image from file. Parameters ---------- path : str Path to image file. dtype : np.dtype Defaults to ``np.float64``, which means the image will be returned as a float with values between 0 and 1. If ``np.uint8`` is specified, the values will be between 0 and 255 a...
[ "Loads", "an", "image", "from", "file", "." ]
python
train
29.130435
CITGuru/PyInquirer
PyInquirer/color_print.py
https://github.com/CITGuru/PyInquirer/blob/10d53723b36ebc7bba311457ec4afd9747a5c777/PyInquirer/color_print.py#L10-L27
def _print_token_factory(col): """Internal helper to provide color names.""" def _helper(msg): style = style_from_dict({ Token.Color: col, }) tokens = [ (Token.Color, msg) ] print_tokens(tokens, style=style) def _helper_no_terminal(msg): ...
[ "def", "_print_token_factory", "(", "col", ")", ":", "def", "_helper", "(", "msg", ")", ":", "style", "=", "style_from_dict", "(", "{", "Token", ".", "Color", ":", "col", ",", "}", ")", "tokens", "=", "[", "(", "Token", ".", "Color", ",", "msg", ")...
Internal helper to provide color names.
[ "Internal", "helper", "to", "provide", "color", "names", "." ]
python
test
25.333333
datalib/StatsCounter
statscounter/_stats.py
https://github.com/datalib/StatsCounter/blob/5386c967808bbe451025af1d550f060cd7f86669/statscounter/_stats.py#L154-L200
def median_grouped(data, interval=1): """"Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 >>> median_grouped([52, 52, 53, 54]) 52.5 This calculates the median as the 50th percentile, and should be used when your data is...
[ "def", "median_grouped", "(", "data", ",", "interval", "=", "1", ")", ":", "data", "=", "sorted", "(", "data", ")", "n", "=", "len", "(", "data", ")", "if", "n", "==", "0", ":", "raise", "StatisticsError", "(", "\"no median for empty data\"", ")", "eli...
Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 >>> median_grouped([52, 52, 53, 54]) 52.5 This calculates the median as the 50th percentile, and should be used when your data is continuous and grouped. In the above example,...
[ "Return", "the", "50th", "percentile", "(", "median", ")", "of", "grouped", "continuous", "data", "." ]
python
train
38.212766
saltstack/salt
salt/cache/etcd_cache.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/etcd_cache.py#L90-L119
def _init_client(): '''Setup client and init datastore. ''' global client, path_prefix if client is not None: return etcd_kwargs = { 'host': __opts__.get('etcd.host', '127.0.0.1'), 'port': __opts__.get('etcd.port', 2379), 'protocol': __opts__.get('etcd.pr...
[ "def", "_init_client", "(", ")", ":", "global", "client", ",", "path_prefix", "if", "client", "is", "not", "None", ":", "return", "etcd_kwargs", "=", "{", "'host'", ":", "__opts__", ".", "get", "(", "'etcd.host'", ",", "'127.0.0.1'", ")", ",", "'port'", ...
Setup client and init datastore.
[ "Setup", "client", "and", "init", "datastore", "." ]
python
train
42.566667
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L907-L916
def imagetransformer_ae_imagenet(): """For 64x64 ImageNet. ~56M trainable variables.""" hparams = imagetransformer_ae_cifar() hparams.max_length = int(64 * 64 * 3) hparams.img_len = 64 hparams.num_heads = 4 # Heads are expensive on TPUs. # Reduce architecture from 32x32 CIFAR-10 in order to fit in memory. ...
[ "def", "imagetransformer_ae_imagenet", "(", ")", ":", "hparams", "=", "imagetransformer_ae_cifar", "(", ")", "hparams", ".", "max_length", "=", "int", "(", "64", "*", "64", "*", "3", ")", "hparams", ".", "img_len", "=", "64", "hparams", ".", "num_heads", "...
For 64x64 ImageNet. ~56M trainable variables.
[ "For", "64x64", "ImageNet", ".", "~56M", "trainable", "variables", "." ]
python
train
39.3
saltstack/salt
salt/states/zk_concurrency.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zk_concurrency.py#L115-L155
def unlock(name, zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example) identifier=None, max_concurrency=1, ephemeral_lease=False, profile=None, scheme=None, username=None, password=None,...
[ "def", "unlock", "(", "name", ",", "zk_hosts", "=", "None", ",", "# in case you need to unlock without having run lock (failed execution for example)", "identifier", "=", "None", ",", "max_concurrency", "=", "1", ",", "ephemeral_lease", "=", "False", ",", "profile", "="...
Remove lease from semaphore.
[ "Remove", "lease", "from", "semaphore", "." ]
python
train
33.609756
codelv/enaml-native
src/enamlnative/core/eventloop/ioloop.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/ioloop.py#L679-L692
def handle_callback_exception(self, callback): """This method is called whenever a callback run by the `IOLoop` throws an exception. By default simply logs the exception as an error. Subclasses may override this method to customize reporting of exceptions. The exception itself...
[ "def", "handle_callback_exception", "(", "self", ",", "callback", ")", ":", "if", "self", ".", "_error_handler", ":", "self", ".", "_error_handler", "(", "callback", ")", "else", ":", "app_log", ".", "error", "(", "\"Exception in callback %r\"", ",", "callback",...
This method is called whenever a callback run by the `IOLoop` throws an exception. By default simply logs the exception as an error. Subclasses may override this method to customize reporting of exceptions. The exception itself is not passed explicitly, but is available in `sy...
[ "This", "method", "is", "called", "whenever", "a", "callback", "run", "by", "the", "IOLoop", "throws", "an", "exception", "." ]
python
train
39.714286
spacetelescope/stsci.tools
lib/stsci/tools/fileutil.py
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L308-L343
def verifyWriteMode(files): """ Checks whether files are writable. It is up to the calling routine to raise an Exception, if desired. This function returns True, if all files are writable and False, if any are not writable. In addition, for all files found to not be writable, it will print out...
[ "def", "verifyWriteMode", "(", "files", ")", ":", "# Start by insuring that input is a list of filenames,", "# if only a single filename has been given as input,", "# convert it to a list with len == 1.", "if", "not", "isinstance", "(", "files", ",", "list", ")", ":", "files", ...
Checks whether files are writable. It is up to the calling routine to raise an Exception, if desired. This function returns True, if all files are writable and False, if any are not writable. In addition, for all files found to not be writable, it will print out the list of names of affected files.
[ "Checks", "whether", "files", "are", "writable", ".", "It", "is", "up", "to", "the", "calling", "routine", "to", "raise", "an", "Exception", "if", "desired", "." ]
python
train
29.611111
fermiPy/fermipy
fermipy/castro.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/castro.py#L1162-L1200
def create_from_tables(cls, norm_type='eflux', tab_s="SCANDATA", tab_e="EBOUNDS"): """Create a CastroData object from two tables Parameters ---------- norm_type : str Type of normalization to use. Valid options are: ...
[ "def", "create_from_tables", "(", "cls", ",", "norm_type", "=", "'eflux'", ",", "tab_s", "=", "\"SCANDATA\"", ",", "tab_e", "=", "\"EBOUNDS\"", ")", ":", "if", "norm_type", "in", "[", "'flux'", ",", "'eflux'", ",", "'dnde'", "]", ":", "norm_vals", "=", "...
Create a CastroData object from two tables Parameters ---------- norm_type : str Type of normalization to use. Valid options are: * norm : Normalization w.r.t. to test source * flux : Flux of the test source ( ph cm^-2 s^-1 ) * eflux: Energy Flu...
[ "Create", "a", "CastroData", "object", "from", "two", "tables" ]
python
train
35.179487
python-openxml/python-docx
docx/opc/pkgreader.py
https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/opc/pkgreader.py#L49-L58
def iter_srels(self): """ Generate a 2-tuple `(source_uri, srel)` for each of the relationships in the package. """ for srel in self._pkg_srels: yield (PACKAGE_URI, srel) for spart in self._sparts: for srel in spart.srels: yield (sp...
[ "def", "iter_srels", "(", "self", ")", ":", "for", "srel", "in", "self", ".", "_pkg_srels", ":", "yield", "(", "PACKAGE_URI", ",", "srel", ")", "for", "spart", "in", "self", ".", "_sparts", ":", "for", "srel", "in", "spart", ".", "srels", ":", "yield...
Generate a 2-tuple `(source_uri, srel)` for each of the relationships in the package.
[ "Generate", "a", "2", "-", "tuple", "(", "source_uri", "srel", ")", "for", "each", "of", "the", "relationships", "in", "the", "package", "." ]
python
train
33
Nachtfeuer/pipeline
spline/components/tasks.py
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/components/tasks.py#L230-L249
def process_shell(self, creator, entry, config): """Processing a shell entry.""" self.logger.info("Processing Bash code: start") output = [] shell = creator(entry, config) for line in shell.process(): output.append(line) self.logger.info(" | %s", line) ...
[ "def", "process_shell", "(", "self", ",", "creator", ",", "entry", ",", "config", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Processing Bash code: start\"", ")", "output", "=", "[", "]", "shell", "=", "creator", "(", "entry", ",", "config", ")...
Processing a shell entry.
[ "Processing", "a", "shell", "entry", "." ]
python
train
35.15
gwpy/gwpy
gwpy/cli/timeseries.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/cli/timeseries.py#L35-L47
def get_ylabel(self): """Text for y-axis label, check if channel defines it """ units = self.units if len(units) == 1 and str(units[0]) == '': # dimensionless return '' if len(units) == 1 and self.usetex: return units[0].to_string('latex') elif l...
[ "def", "get_ylabel", "(", "self", ")", ":", "units", "=", "self", ".", "units", "if", "len", "(", "units", ")", "==", "1", "and", "str", "(", "units", "[", "0", "]", ")", "==", "''", ":", "# dimensionless", "return", "''", "if", "len", "(", "unit...
Text for y-axis label, check if channel defines it
[ "Text", "for", "y", "-", "axis", "label", "check", "if", "channel", "defines", "it" ]
python
train
36.923077
jfear/sramongo
sramongo/services/entrez.py
https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L118-L171
def elink(db: str, dbfrom: str, ids=False, webenv=False, query_key=False, api_key=False, email=False, **kwargs) -> Optional[ElinkResult]: """Get document summaries using the Entrez ESearch API. Parameters ---------- db : str Entez database to get ids from. dbfrom : str Ent...
[ "def", "elink", "(", "db", ":", "str", ",", "dbfrom", ":", "str", ",", "ids", "=", "False", ",", "webenv", "=", "False", ",", "query_key", "=", "False", ",", "api_key", "=", "False", ",", "email", "=", "False", ",", "*", "*", "kwargs", ")", "->",...
Get document summaries using the Entrez ESearch API. Parameters ---------- db : str Entez database to get ids from. dbfrom : str Entez database the provided ids are from. ids : list or str List of IDs to submit to the server. webenv : str An Entrez WebEnv to use ...
[ "Get", "document", "summaries", "using", "the", "Entrez", "ESearch", "API", "." ]
python
train
30.722222
Genida/django-appsettings
src/appsettings/settings.py
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L522-L531
def run_validators(self, value): """Run the validators on the setting value.""" errors = [] for validator in self.validators: try: validator(value) except ValidationError as error: errors.extend(error.messages) if errors: ...
[ "def", "run_validators", "(", "self", ",", "value", ")", ":", "errors", "=", "[", "]", "for", "validator", "in", "self", ".", "validators", ":", "try", ":", "validator", "(", "value", ")", "except", "ValidationError", "as", "error", ":", "errors", ".", ...
Run the validators on the setting value.
[ "Run", "the", "validators", "on", "the", "setting", "value", "." ]
python
train
34.2
aloetesting/aloe_webdriver
aloe_webdriver/util.py
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L142-L154
def _select(self): """Fetch the elements from the browser.""" for element in self.browser.find_elements_by_xpath(self.xpath): if self.filter_displayed: if not element.is_displayed(): continue if self.filter_enabled: if not ele...
[ "def", "_select", "(", "self", ")", ":", "for", "element", "in", "self", ".", "browser", ".", "find_elements_by_xpath", "(", "self", ".", "xpath", ")", ":", "if", "self", ".", "filter_displayed", ":", "if", "not", "element", ".", "is_displayed", "(", ")"...
Fetch the elements from the browser.
[ "Fetch", "the", "elements", "from", "the", "browser", "." ]
python
train
29.384615
PmagPy/PmagPy
programs/vgpmap_magic2.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/vgpmap_magic2.py#L13-L251
def main(): """ NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a pmag_results table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 9...
[ "def", "main", "(", ")", ":", "dir_path", "=", "'.'", "res", ",", "ages", "=", "'c'", ",", "0", "plot", "=", "0", "proj", "=", "'ortho'", "results_file", "=", "'pmag_results.txt'", "ell", ",", "flip", "=", "0", ",", "0", "lat_0", ",", "lon_0", "=",...
NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a pmag_results table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 90., 0. -f FILE p...
[ "NAME", "vgpmap_magic", ".", "py" ]
python
train
34.179916
neon-jungle/wagtailmodelchooser
wagtailmodelchooser/views.py
https://github.com/neon-jungle/wagtailmodelchooser/blob/8dd1e33dd61418a726ff3acf67a956626c8b7ba1/wagtailmodelchooser/views.py#L15-L39
def instance_from_str(instance_str): """ Given an instance string in the form "app.Model:pk", returns a tuple of ``(model, instance)``. If the pk part is empty, ``instance`` will be ``None``. Raises ``ValueError`` on invalid model strings or missing instances. """ match = instance_str_re.mat...
[ "def", "instance_from_str", "(", "instance_str", ")", ":", "match", "=", "instance_str_re", ".", "match", "(", "instance_str", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "\"Invalid instance string\"", ")", "model_string", "=", "match", ".", "gro...
Given an instance string in the form "app.Model:pk", returns a tuple of ``(model, instance)``. If the pk part is empty, ``instance`` will be ``None``. Raises ``ValueError`` on invalid model strings or missing instances.
[ "Given", "an", "instance", "string", "in", "the", "form", "app", ".", "Model", ":", "pk", "returns", "a", "tuple", "of", "(", "model", "instance", ")", ".", "If", "the", "pk", "part", "is", "empty", "instance", "will", "be", "None", ".", "Raises", "V...
python
valid
31.4
allenai/allennlp
allennlp/common/params.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L396-L404
def assert_empty(self, class_name: str): """ Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `calling`...
[ "def", "assert_empty", "(", "self", ",", "class_name", ":", "str", ")", ":", "if", "self", ".", "params", ":", "raise", "ConfigurationError", "(", "\"Extra parameters passed to {}: {}\"", ".", "format", "(", "class_name", ",", "self", ".", "params", ")", ")" ]
Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `calling` class, the one that got extra parameters (if there a...
[ "Raises", "a", "ConfigurationError", "if", "self", ".", "params", "is", "not", "empty", ".", "We", "take", "class_name", "as", "an", "argument", "so", "that", "the", "error", "message", "gives", "some", "idea", "of", "where", "an", "error", "happened", "if...
python
train
58.111111
csparpa/pyowm
pyowm/uvindexapi30/uvindex.py
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/uvindexapi30/uvindex.py#L123-L143
def to_XML(self, xml_declaration=True, xmlns=True): """ Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefix...
[ "def", "to_XML", "(", "self", ",", "xml_declaration", "=", "True", ",", "xmlns", "=", "True", ")", ":", "root_node", "=", "self", ".", "_to_DOM", "(", ")", "if", "xmlns", ":", "xmlutils", ".", "annotate_with_XMLNS", "(", "root_node", ",", "UVINDEX_XMLNS_PR...
Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefixes. :param XML_declaration: if ``True`` (default) prints a lead...
[ "Dumps", "object", "fields", "to", "an", "XML", "-", "formatted", "string", ".", "The", "xml_declaration", "switch", "enables", "printing", "of", "a", "leading", "standard", "XML", "line", "containing", "XML", "version", "and", "encoding", ".", "The", "xmlns",...
python
train
42.47619
viniciuschiele/flask-io
flask_io/io.py
https://github.com/viniciuschiele/flask-io/blob/4e559419b3d8e6859f83fa16557b00542d5f3aa7/flask_io/io.py#L334-L369
def __make_response(self, data, default_renderer=None): """ Creates a Flask response object from the specified data. The appropriated encoder is taken based on the request header Accept. If there is not data to be serialized the response status code is 204. :param data: The Pyth...
[ "def", "__make_response", "(", "self", ",", "data", ",", "default_renderer", "=", "None", ")", ":", "status", "=", "headers", "=", "None", "if", "isinstance", "(", "data", ",", "tuple", ")", ":", "data", ",", "status", ",", "headers", "=", "unpack", "(...
Creates a Flask response object from the specified data. The appropriated encoder is taken based on the request header Accept. If there is not data to be serialized the response status code is 204. :param data: The Python object to be serialized. :return: A Flask response object.
[ "Creates", "a", "Flask", "response", "object", "from", "the", "specified", "data", ".", "The", "appropriated", "encoder", "is", "taken", "based", "on", "the", "request", "header", "Accept", ".", "If", "there", "is", "not", "data", "to", "be", "serialized", ...
python
train
34.416667
materialsproject/pymatgen
pymatgen/io/vasp/inputs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/inputs.py#L1620-L1632
def element(self): """ Attempt to return the atomic symbol based on the VRHFIN keyword. """ element = self.keywords["VRHFIN"].split(":")[0].strip() try: return Element(element).symbol except ValueError: # VASP incorrectly gives the element symbol f...
[ "def", "element", "(", "self", ")", ":", "element", "=", "self", ".", "keywords", "[", "\"VRHFIN\"", "]", ".", "split", "(", "\":\"", ")", "[", "0", "]", ".", "strip", "(", ")", "try", ":", "return", "Element", "(", "element", ")", ".", "symbol", ...
Attempt to return the atomic symbol based on the VRHFIN keyword.
[ "Attempt", "to", "return", "the", "atomic", "symbol", "based", "on", "the", "VRHFIN", "keyword", "." ]
python
train
39
OpenHumans/open-humans-api
ohapi/utils_fs.py
https://github.com/OpenHumans/open-humans-api/blob/ca2a28cf5d55cfdae13dd222ba58c25565bdb86e/ohapi/utils_fs.py#L176-L206
def load_metadata_csv(input_filepath): """ Return dict of metadata. Format is either dict (filenames are keys) or dict-of-dicts (project member IDs as top level keys, then filenames as keys). :param input_filepath: This field is the filepath of the csv file. """ with open(input_filepath) a...
[ "def", "load_metadata_csv", "(", "input_filepath", ")", ":", "with", "open", "(", "input_filepath", ")", "as", "f", ":", "csv_in", "=", "csv", ".", "reader", "(", "f", ")", "header", "=", "next", "(", "csv_in", ")", "if", "'tags'", "in", "header", ":",...
Return dict of metadata. Format is either dict (filenames are keys) or dict-of-dicts (project member IDs as top level keys, then filenames as keys). :param input_filepath: This field is the filepath of the csv file.
[ "Return", "dict", "of", "metadata", "." ]
python
train
43.967742
thefab/tornadis
tornadis/pool.py
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/pool.py#L180-L195
def preconnect(self, size=-1): """(pre)Connects some or all redis clients inside the pool. Args: size (int): number of redis clients to build and to connect (-1 means all clients if pool max_size > -1) Raises: ClientError: when size == -1 and pool max_si...
[ "def", "preconnect", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "size", "==", "-", "1", "and", "self", ".", "max_size", "==", "-", "1", ":", "raise", "ClientError", "(", "\"size=-1 not allowed with pool max_size=-1\"", ")", "limit", "=", "m...
(pre)Connects some or all redis clients inside the pool. Args: size (int): number of redis clients to build and to connect (-1 means all clients if pool max_size > -1) Raises: ClientError: when size == -1 and pool max_size == -1
[ "(", "pre", ")", "Connects", "some", "or", "all", "redis", "clients", "inside", "the", "pool", "." ]
python
train
41.9375
VisTrails/tej
tej/submission.py
https://github.com/VisTrails/tej/blob/b8dedaeb6bdeb650b46cfe6d85e5aa9284fc7f0b/tej/submission.py#L52-L62
def escape_queue(s): """Escapes the path to a queue, e.g. preserves ~ at the begining. """ if isinstance(s, PosixPath): s = unicode_(s) elif isinstance(s, bytes): s = s.decode('utf-8') if s.startswith('~/'): return '~/' + shell_escape(s[2:]) else: return shell_esc...
[ "def", "escape_queue", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "PosixPath", ")", ":", "s", "=", "unicode_", "(", "s", ")", "elif", "isinstance", "(", "s", ",", "bytes", ")", ":", "s", "=", "s", ".", "decode", "(", "'utf-8'", ")", ...
Escapes the path to a queue, e.g. preserves ~ at the begining.
[ "Escapes", "the", "path", "to", "a", "queue", "e", ".", "g", ".", "preserves", "~", "at", "the", "begining", "." ]
python
train
28.727273
IdentityPython/pysaml2
src/saml2/s2repoze/plugins/sp.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/s2repoze/plugins/sp.py#L51-L59
def construct_came_from(environ): """ The URL that the user used when the process where interupted for single-sign-on processing. """ came_from = environ.get("PATH_INFO") qstr = environ.get("QUERY_STRING", "") if qstr: came_from += "?" + qstr return came_from
[ "def", "construct_came_from", "(", "environ", ")", ":", "came_from", "=", "environ", ".", "get", "(", "\"PATH_INFO\"", ")", "qstr", "=", "environ", ".", "get", "(", "\"QUERY_STRING\"", ",", "\"\"", ")", "if", "qstr", ":", "came_from", "+=", "\"?\"", "+", ...
The URL that the user used when the process where interupted for single-sign-on processing.
[ "The", "URL", "that", "the", "user", "used", "when", "the", "process", "where", "interupted", "for", "single", "-", "sign", "-", "on", "processing", "." ]
python
train
31.555556
petl-developers/petl
petl/io/csv.py
https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/io/csv.py#L115-L131
def appendcsv(table, source=None, encoding=None, errors='strict', write_header=False, **csvargs): """ Append data rows to an existing CSV file. As :func:`petl.io.csv.tocsv` but the file is opened in append mode and the table header is not written by default. Note that no attempt is ma...
[ "def", "appendcsv", "(", "table", ",", "source", "=", "None", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ",", "write_header", "=", "False", ",", "*", "*", "csvargs", ")", ":", "source", "=", "write_source_from_arg", "(", "source", ")",...
Append data rows to an existing CSV file. As :func:`petl.io.csv.tocsv` but the file is opened in append mode and the table header is not written by default. Note that no attempt is made to check that the fields or row lengths are consistent with the existing data, the data rows from the table are simpl...
[ "Append", "data", "rows", "to", "an", "existing", "CSV", "file", ".", "As", ":", "func", ":", "petl", ".", "io", ".", "csv", ".", "tocsv", "but", "the", "file", "is", "opened", "in", "append", "mode", "and", "the", "table", "header", "is", "not", "...
python
train
40.176471
hyperledger/indy-sdk
wrappers/python/indy/did.py
https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/wrappers/python/indy/did.py#L245-L275
async def get_key_metadata(wallet_handle: int, verkey: str) -> str: """ Retrieves the meta information for the giving key in the wallet. :param wallet_handle: Wallet handle (created by open_wallet). :param verkey: The key (verkey, key id) to retrieve metadata. :return: me...
[ "async", "def", "get_key_metadata", "(", "wallet_handle", ":", "int", ",", "verkey", ":", "str", ")", "->", "str", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "\"get_key_metadata: >>> wallet_handle: %r, ver...
Retrieves the meta information for the giving key in the wallet. :param wallet_handle: Wallet handle (created by open_wallet). :param verkey: The key (verkey, key id) to retrieve metadata. :return: metadata: The meta information stored with the key; Can be null if no metadata was saved for this key.
[ "Retrieves", "the", "meta", "information", "for", "the", "giving", "key", "in", "the", "wallet", "." ]
python
train
36.870968
lmcinnes/umap
umap/rp_tree.py
https://github.com/lmcinnes/umap/blob/bbb01c03ba49f7bff8f77fd662d00e50d6686c77/umap/rp_tree.py#L596-L605
def max_sparse_hyperplane_size(tree): """Determine the most number on non zeros in a hyperplane entry""" if tree.is_leaf: return 0 else: return max( tree.hyperplane.shape[1], max_sparse_hyperplane_size(tree.left_child), max_sparse_hyperplane_size(tree.righ...
[ "def", "max_sparse_hyperplane_size", "(", "tree", ")", ":", "if", "tree", ".", "is_leaf", ":", "return", "0", "else", ":", "return", "max", "(", "tree", ".", "hyperplane", ".", "shape", "[", "1", "]", ",", "max_sparse_hyperplane_size", "(", "tree", ".", ...
Determine the most number on non zeros in a hyperplane entry
[ "Determine", "the", "most", "number", "on", "non", "zeros", "in", "a", "hyperplane", "entry" ]
python
train
33
Erotemic/ubelt
ubelt/util_hash.py
https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L381-L447
def _register_numpy_extensions(self): """ Numpy extensions are builtin """ # system checks import numpy as np numpy_floating_types = (np.float16, np.float32, np.float64) if hasattr(np, 'float128'): # nocover numpy_floating_types = numpy_floating_types...
[ "def", "_register_numpy_extensions", "(", "self", ")", ":", "# system checks", "import", "numpy", "as", "np", "numpy_floating_types", "=", "(", "np", ".", "float16", ",", "np", ".", "float32", ",", "np", ".", "float64", ")", "if", "hasattr", "(", "np", ","...
Numpy extensions are builtin
[ "Numpy", "extensions", "are", "builtin" ]
python
valid
41.537313
tonioo/sievelib
sievelib/parser.py
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L124-L138
def __reset_parser(self): """Reset parser's internal variables Restore the parser to an initial state. Useful when creating a new parser or reusing an existing one. """ self.result = [] self.hash_comments = [] self.__cstate = None self.__curcommand = Non...
[ "def", "__reset_parser", "(", "self", ")", ":", "self", ".", "result", "=", "[", "]", "self", ".", "hash_comments", "=", "[", "]", "self", ".", "__cstate", "=", "None", "self", ".", "__curcommand", "=", "None", "self", ".", "__curstringlist", "=", "Non...
Reset parser's internal variables Restore the parser to an initial state. Useful when creating a new parser or reusing an existing one.
[ "Reset", "parser", "s", "internal", "variables" ]
python
train
30.2
aouyar/PyMunin
pymunin/plugins/phpopcstats.py
https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pymunin/plugins/phpopcstats.py#L148-L177
def retrieveVals(self): """Retrieve values for graphs.""" opcinfo = OPCinfo(self._host, self._port, self._user, self._password, self._monpath, self._ssl) stats = opcinfo.getAllStats() if self.hasGraph('php_opc_memory') and stats: mem = stat...
[ "def", "retrieveVals", "(", "self", ")", ":", "opcinfo", "=", "OPCinfo", "(", "self", ".", "_host", ",", "self", ".", "_port", ",", "self", ".", "_user", ",", "self", ".", "_password", ",", "self", ".", "_monpath", ",", "self", ".", "_ssl", ")", "s...
Retrieve values for graphs.
[ "Retrieve", "values", "for", "graphs", "." ]
python
train
50.433333
sentinel-hub/eo-learn
features/eolearn/features/interpolation.py
https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/features/eolearn/features/interpolation.py#L182-L209
def _copy_old_features(new_eopatch, old_eopatch, copy_features): """ Copy features from old EOPatch :param new_eopatch: New EOPatch container where the old features will be copied to :type new_eopatch: EOPatch :param old_eopatch: Old EOPatch container where the old features are located ...
[ "def", "_copy_old_features", "(", "new_eopatch", ",", "old_eopatch", ",", "copy_features", ")", ":", "if", "copy_features", ":", "existing_features", "=", "set", "(", "new_eopatch", ".", "get_feature_list", "(", ")", ")", "for", "copy_feature_type", ",", "copy_fea...
Copy features from old EOPatch :param new_eopatch: New EOPatch container where the old features will be copied to :type new_eopatch: EOPatch :param old_eopatch: Old EOPatch container where the old features are located :type old_eopatch: EOPatch :param copy_features: List of tupl...
[ "Copy", "features", "from", "old", "EOPatch" ]
python
train
52.5
swans-one/django-kittens
settings.py
https://github.com/swans-one/django-kittens/blob/31e1ff54737c8ba3e99880dbff285a730ddac851/settings.py#L6-L33
def configure_settings(): """ Configures settings for manage.py and for run_tests.py. """ if not settings.configured: db_config = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_kittens_db.sqlite3', } settings.configure( TEST_RUNNER=...
[ "def", "configure_settings", "(", ")", ":", "if", "not", "settings", ".", "configured", ":", "db_config", "=", "{", "'ENGINE'", ":", "'django.db.backends.sqlite3'", ",", "'NAME'", ":", "'django_kittens_db.sqlite3'", ",", "}", "settings", ".", "configure", "(", "...
Configures settings for manage.py and for run_tests.py.
[ "Configures", "settings", "for", "manage", ".", "py", "and", "for", "run_tests", ".", "py", "." ]
python
train
31.5
santosjorge/cufflinks
cufflinks/colors.py
https://github.com/santosjorge/cufflinks/blob/ca1cbf93998dc793d0b1f8ac30fe1f2bd105f63a/cufflinks/colors.py#L198-L281
def color_table(color, N=1, sort=False, sort_values=False, inline=False, as_html=False): """ Generates a colour table Parameters: ----------- color : string | list | dict Color representation in rgba|rgb|hex If a list of colors is passed then these ...
[ "def", "color_table", "(", "color", ",", "N", "=", "1", ",", "sort", "=", "False", ",", "sort_values", "=", "False", ",", "inline", "=", "False", ",", "as_html", "=", "False", ")", ":", "if", "isinstance", "(", "color", ",", "list", ")", ":", "c_",...
Generates a colour table Parameters: ----------- color : string | list | dict Color representation in rgba|rgb|hex If a list of colors is passed then these are displayed in a table N : int number of colou...
[ "Generates", "a", "colour", "table" ]
python
train
34.27381
sveetch/boussole
boussole/conf/model.py
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/model.py#L77-L96
def update(self, settings): """ Update object attributes from given settings Args: settings (dict): Dictionnary of elements to update settings. Returns: dict: Dictionnary of all current saved settings. """ settings = self.clean(settings) ...
[ "def", "update", "(", "self", ",", "settings", ")", ":", "settings", "=", "self", ".", "clean", "(", "settings", ")", "# Update internal dict", "self", ".", "_settings", ".", "update", "(", "settings", ")", "# Push every setting items as class object attributes", ...
Update object attributes from given settings Args: settings (dict): Dictionnary of elements to update settings. Returns: dict: Dictionnary of all current saved settings.
[ "Update", "object", "attributes", "from", "given", "settings" ]
python
train
24.75
numenta/htmresearch
htmresearch/frameworks/union_temporal_pooling/activation/excite_functions/excite_functions_all.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/union_temporal_pooling/activation/excite_functions/excite_functions_all.py#L70-L82
def plot(self): """ plot the activation function """ plt.ion() plt.show() x = numpy.linspace(0, 15, 100) y = numpy.zeros(x.shape) y = self.excite(y, x) plt.plot(x, y) plt.xlabel('Input') plt.ylabel('Persistence') plt.title('Sigmoid Activation Function')
[ "def", "plot", "(", "self", ")", ":", "plt", ".", "ion", "(", ")", "plt", ".", "show", "(", ")", "x", "=", "numpy", ".", "linspace", "(", "0", ",", "15", ",", "100", ")", "y", "=", "numpy", ".", "zeros", "(", "x", ".", "shape", ")", "y", ...
plot the activation function
[ "plot", "the", "activation", "function" ]
python
train
22.230769
RJT1990/pyflux
pyflux/gas/gasrank.py
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gas/gasrank.py#L294-L335
def _model_abilities_two_components(self,beta): """ Creates the structure of the model - store abilities Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- theta : np.array ...
[ "def", "_model_abilities_two_components", "(", "self", ",", "beta", ")", ":", "parm", "=", "np", ".", "array", "(", "[", "self", ".", "latent_variables", ".", "z_list", "[", "k", "]", ".", "prior", ".", "transform", "(", "beta", "[", "k", "]", ")", "...
Creates the structure of the model - store abilities Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- theta : np.array Contains the predicted values for the time series ...
[ "Creates", "the", "structure", "of", "the", "model", "-", "store", "abilities" ]
python
train
69.833333
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/core/ultratb.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/ultratb.py#L138-L211
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. ...
[ "def", "findsource", "(", "object", ")", ":", "file", "=", "getsourcefile", "(", "object", ")", "or", "getfile", "(", "object", ")", "# If the object is a frame, then trying to get the globals dict from its", "# module won't work. Instead, the frame object itself has the globals"...
Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if th...
[ "Return", "the", "entire", "source", "file", "and", "starting", "line", "number", "for", "an", "object", "." ]
python
test
38.445946
twitterdev/tweet_parser
tweet_parser/getter_methods/tweet_entities.py
https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_entities.py#L215-L245
def get_hashtags(tweet): """ Get a list of hashtags in the Tweet Note that in the case of a quote-tweet, this does not return the hashtags in the quoted status. Args: tweet (Tweet or dict): A Tweet object or dictionary Returns: list (a list of strings): list of all of the hasht...
[ "def", "get_hashtags", "(", "tweet", ")", ":", "entities", "=", "get_entities", "(", "tweet", ")", "hashtags", "=", "entities", ".", "get", "(", "\"hashtags\"", ")", "hashtags", "=", "[", "tag", "[", "\"text\"", "]", "for", "tag", "in", "hashtags", "]", ...
Get a list of hashtags in the Tweet Note that in the case of a quote-tweet, this does not return the hashtags in the quoted status. Args: tweet (Tweet or dict): A Tweet object or dictionary Returns: list (a list of strings): list of all of the hashtags in the Tweet Example: ...
[ "Get", "a", "list", "of", "hashtags", "in", "the", "Tweet", "Note", "that", "in", "the", "case", "of", "a", "quote", "-", "tweet", "this", "does", "not", "return", "the", "hashtags", "in", "the", "quoted", "status", "." ]
python
train
36.225806
programa-stic/barf-project
barf/arch/x86/translator.py
https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/arch/x86/translator.py#L261-L322
def resolve_memory_access(self, tb, x86_mem_operand): """Return operand memory access translation. """ size = self.__get_memory_access_size(x86_mem_operand) addr = None if x86_mem_operand.base: addr = ReilRegisterOperand(x86_mem_operand.base, size) if x86_m...
[ "def", "resolve_memory_access", "(", "self", ",", "tb", ",", "x86_mem_operand", ")", ":", "size", "=", "self", ".", "__get_memory_access_size", "(", "x86_mem_operand", ")", "addr", "=", "None", "if", "x86_mem_operand", ".", "base", ":", "addr", "=", "ReilRegis...
Return operand memory access translation.
[ "Return", "operand", "memory", "access", "translation", "." ]
python
train
29.419355
abseil/abseil-py
absl/logging/__init__.py
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L389-L411
def _seconds_have_elapsed(token, num_seconds): """Tests if 'num_seconds' have passed since 'token' was requested. Not strictly thread-safe - may log with the wrong frequency if called concurrently from multiple threads. Accuracy depends on resolution of 'timeit.default_timer()'. Always returns True on the f...
[ "def", "_seconds_have_elapsed", "(", "token", ",", "num_seconds", ")", ":", "now", "=", "timeit", ".", "default_timer", "(", ")", "then", "=", "_log_timer_per_token", ".", "get", "(", "token", ",", "None", ")", "if", "then", "is", "None", "or", "(", "now...
Tests if 'num_seconds' have passed since 'token' was requested. Not strictly thread-safe - may log with the wrong frequency if called concurrently from multiple threads. Accuracy depends on resolution of 'timeit.default_timer()'. Always returns True on the first call for a given 'token'. Args: token: T...
[ "Tests", "if", "num_seconds", "have", "passed", "since", "token", "was", "requested", "." ]
python
train
32.26087
jasonrbriggs/stomp.py
stomp/utils.py
https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/utils.py#L103-L122
def parse_headers(lines, offset=0): """ Parse the headers in a STOMP response :param list(str) lines: the lines received in the message response :param int offset: the starting line number :rtype: dict(str,str) """ headers = {} for header_line in lines[offset:]: header_match = ...
[ "def", "parse_headers", "(", "lines", ",", "offset", "=", "0", ")", ":", "headers", "=", "{", "}", "for", "header_line", "in", "lines", "[", "offset", ":", "]", ":", "header_match", "=", "HEADER_LINE_RE", ".", "match", "(", "header_line", ")", "if", "h...
Parse the headers in a STOMP response :param list(str) lines: the lines received in the message response :param int offset: the starting line number :rtype: dict(str,str)
[ "Parse", "the", "headers", "in", "a", "STOMP", "response" ]
python
train
33.3
ejeschke/ginga
ginga/rv/plugins/ColorMapPicker.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ColorMapPicker.py#L168-L215
def rebuild_cmaps(self): """Builds a color RGB image containing color bars of all the possible color maps and their labels. """ self.logger.info("building color maps image") ht, wd, sep = self._cmht, self._cmwd, self._cmsep viewer = self.p_view # put the canvas i...
[ "def", "rebuild_cmaps", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"building color maps image\"", ")", "ht", ",", "wd", ",", "sep", "=", "self", ".", "_cmht", ",", "self", ".", "_cmwd", ",", "self", ".", "_cmsep", "viewer", "=", ...
Builds a color RGB image containing color bars of all the possible color maps and their labels.
[ "Builds", "a", "color", "RGB", "image", "containing", "color", "bars", "of", "all", "the", "possible", "color", "maps", "and", "their", "labels", "." ]
python
train
36.333333
jtpaasch/simplygithub
simplygithub/branches.py
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/branches.py#L72-L95
def create_branch(profile, name, branch_off): """Create a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name ...
[ "def", "create_branch", "(", "profile", ",", "name", ",", "branch_off", ")", ":", "branch_off_sha", "=", "get_branch_sha", "(", "profile", ",", "branch_off", ")", "ref", "=", "\"heads/\"", "+", "name", "data", "=", "refs", ".", "create_ref", "(", "profile", ...
Create a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name The name of the new branch. branch_...
[ "Create", "a", "branch", "." ]
python
train
26.875
assamite/creamas
creamas/ds.py
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/ds.py#L262-L280
def get_slave_managers(self, as_coro=False): """Return all slave environment manager addresses. :param bool as_coro: If ``True`` returns awaitable coroutine, otherwise runs the calls to the slave managers asynchoronously in the event loop. This method returns the addres...
[ "def", "get_slave_managers", "(", "self", ",", "as_coro", "=", "False", ")", ":", "async", "def", "slave_task", "(", "addr", ")", ":", "r_manager", "=", "await", "self", ".", "env", ".", "connect", "(", "addr", ")", "return", "await", "r_manager", ".", ...
Return all slave environment manager addresses. :param bool as_coro: If ``True`` returns awaitable coroutine, otherwise runs the calls to the slave managers asynchoronously in the event loop. This method returns the addresses of the true slave environment managers, i.e....
[ "Return", "all", "slave", "environment", "manager", "addresses", "." ]
python
train
44.789474
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L965-L1025
def _do_submit_problems(self): """Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread. """ try: while True: # Pull as many problems as we can, block on the first one, #...
[ "def", "_do_submit_problems", "(", "self", ")", ":", "try", ":", "while", "True", ":", "# Pull as many problems as we can, block on the first one,", "# but once we have one problem, switch to non-blocking then", "# submit without blocking again.", "# `None` task is used to signal thread ...
Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread.
[ "Pull", "problems", "from", "the", "submission", "queue", "and", "submit", "them", "." ]
python
train
43.262295
optimizely/python-sdk
optimizely/optimizely.py
https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/optimizely.py#L112-L134
def _validate_user_inputs(self, attributes=None, event_tags=None): """ Helper method to validate user inputs. Args: attributes: Dict representing user attributes. event_tags: Dict representing metadata associated with an event. Returns: Boolean True if inputs are valid. False otherwise. ...
[ "def", "_validate_user_inputs", "(", "self", ",", "attributes", "=", "None", ",", "event_tags", "=", "None", ")", ":", "if", "attributes", "and", "not", "validator", ".", "are_attributes_valid", "(", "attributes", ")", ":", "self", ".", "logger", ".", "error...
Helper method to validate user inputs. Args: attributes: Dict representing user attributes. event_tags: Dict representing metadata associated with an event. Returns: Boolean True if inputs are valid. False otherwise.
[ "Helper", "method", "to", "validate", "user", "inputs", "." ]
python
train
38.173913
tensorflow/datasets
tensorflow_datasets/core/features/feature.py
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/feature.py#L654-L657
def _assert_keys_match(keys1, keys2): """Ensure the two list of keys matches.""" if set(keys1) != set(keys2): raise ValueError('{} {}'.format(list(keys1), list(keys2)))
[ "def", "_assert_keys_match", "(", "keys1", ",", "keys2", ")", ":", "if", "set", "(", "keys1", ")", "!=", "set", "(", "keys2", ")", ":", "raise", "ValueError", "(", "'{} {}'", ".", "format", "(", "list", "(", "keys1", ")", ",", "list", "(", "keys2", ...
Ensure the two list of keys matches.
[ "Ensure", "the", "two", "list", "of", "keys", "matches", "." ]
python
train
43.25
Jammy2211/PyAutoLens
autolens/data/array/grids.py
https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L1034-L1067
def relocated_grid_from_grid_jit(grid, border_grid): """ Relocate the coordinates of a grid to its border if they are outside the border. This is performed as \ follows: 1) Use the mean value of the grid's y and x coordinates to determine the origin of the grid. 2) Compute the radial di...
[ "def", "relocated_grid_from_grid_jit", "(", "grid", ",", "border_grid", ")", ":", "border_origin", "=", "np", ".", "zeros", "(", "2", ")", "border_origin", "[", "0", "]", "=", "np", ".", "mean", "(", "border_grid", "[", ":", ",", "0", "]", ")", "border...
Relocate the coordinates of a grid to its border if they are outside the border. This is performed as \ follows: 1) Use the mean value of the grid's y and x coordinates to determine the origin of the grid. 2) Compute the radial distance of every grid coordinate from the origin. 3) For e...
[ "Relocate", "the", "coordinates", "of", "a", "grid", "to", "its", "border", "if", "they", "are", "outside", "the", "border", ".", "This", "is", "performed", "as", "\\", "follows", ":" ]
python
valid
56.411765
trailofbits/manticore
manticore/native/cpu/x86.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1013-L1059
def AAA(cpu): """ ASCII adjust after addition. Adjusts the sum of two unpacked BCD values to create an unpacked BCD result. The AL register is the implied source and destination operand for this instruction. The AAA instruction is only useful when it follows an ADD instr...
[ "def", "AAA", "(", "cpu", ")", ":", "cpu", ".", "AF", "=", "Operators", ".", "OR", "(", "cpu", ".", "AL", "&", "0x0F", ">", "9", ",", "cpu", ".", "AF", ")", "cpu", ".", "CF", "=", "cpu", ".", "AF", "cpu", ".", "AH", "=", "Operators", ".", ...
ASCII adjust after addition. Adjusts the sum of two unpacked BCD values to create an unpacked BCD result. The AL register is the implied source and destination operand for this instruction. The AAA instruction is only useful when it follows an ADD instruction that adds (binary addition)...
[ "ASCII", "adjust", "after", "addition", "." ]
python
valid
39.510638
pyQode/pyqode.core
pyqode/core/managers/panels.py
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/panels.py#L212-L232
def _update(self, rect, delta_y, force_update_margins=False): """ Updates panels """ helper = TextHelper(self.editor) if not self: return for zones_id, zone in self._panels.items(): if zones_id == Panel.Position.TOP or \ zones_id == Panel.Position.B...
[ "def", "_update", "(", "self", ",", "rect", ",", "delta_y", ",", "force_update_margins", "=", "False", ")", ":", "helper", "=", "TextHelper", "(", "self", ".", "editor", ")", "if", "not", "self", ":", "return", "for", "zones_id", ",", "zone", "in", "se...
Updates panels
[ "Updates", "panels" ]
python
train
45.761905
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py#L215-L227
def embedManifestDllCheck(target, source, env): """Function run by embedManifestDllCheckAction to check for existence of manifest and other conditions, and embed the manifest by calling embedManifestDllAction if so.""" if env.get('WINDOWS_EMBED_MANIFEST', 0): manifestSrc = target[0].get_abspath() + ...
[ "def", "embedManifestDllCheck", "(", "target", ",", "source", ",", "env", ")", ":", "if", "env", ".", "get", "(", "'WINDOWS_EMBED_MANIFEST'", ",", "0", ")", ":", "manifestSrc", "=", "target", "[", "0", "]", ".", "get_abspath", "(", ")", "+", "'.manifest'...
Function run by embedManifestDllCheckAction to check for existence of manifest and other conditions, and embed the manifest by calling embedManifestDllAction if so.
[ "Function", "run", "by", "embedManifestDllCheckAction", "to", "check", "for", "existence", "of", "manifest", "and", "other", "conditions", "and", "embed", "the", "manifest", "by", "calling", "embedManifestDllAction", "if", "so", "." ]
python
train
52.307692
Celeo/Preston
preston/preston.py
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L173-L201
def authenticate(self, code: str) -> 'Preston': """Authenticates using the code from the EVE SSO. A new Preston object is returned; this object is not modified. The intended usage is: auth = preston.authenticate('some_code_here') Args: code: SSO code ...
[ "def", "authenticate", "(", "self", ",", "code", ":", "str", ")", "->", "'Preston'", ":", "headers", "=", "self", ".", "_get_authorization_headers", "(", ")", "data", "=", "{", "'grant_type'", ":", "'authorization_code'", ",", "'code'", ":", "code", "}", "...
Authenticates using the code from the EVE SSO. A new Preston object is returned; this object is not modified. The intended usage is: auth = preston.authenticate('some_code_here') Args: code: SSO code Returns: new Preston, authenticated
[ "Authenticates", "using", "the", "code", "from", "the", "EVE", "SSO", "." ]
python
train
35.896552
WoLpH/python-statsd
statsd/timer.py
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L50-L65
def send(self, subname, delta): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The time delta (time.time() - time.time()) to report :type delta: float...
[ "def", "send", "(", "self", ",", "subname", ",", "delta", ")", ":", "ms", "=", "delta", "*", "1000", "if", "ms", ">", "self", ".", "min_send_threshold", ":", "name", "=", "self", ".", "_get_name", "(", "self", ".", "name", ",", "subname", ")", "sel...
Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The time delta (time.time() - time.time()) to report :type delta: float
[ "Send", "the", "data", "to", "statsd", "via", "self", ".", "connection" ]
python
train
37.625
dereneaton/ipyrad
ipyrad/analysis/twiist.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/twiist.py#L129-L155
def run_tree_inference(self, nexus, idx): """ Write nexus to tmpfile, runs phyml tree inference, and parses and returns the resulting tree. """ ## create a tmpdir for this test tmpdir = tempfile.tempdir tmpfile = os.path.join(tempfile.NamedTemporaryFile( ...
[ "def", "run_tree_inference", "(", "self", ",", "nexus", ",", "idx", ")", ":", "## create a tmpdir for this test", "tmpdir", "=", "tempfile", ".", "tempdir", "tmpfile", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "NamedTemporaryFile", "(", "delet...
Write nexus to tmpfile, runs phyml tree inference, and parses and returns the resulting tree.
[ "Write", "nexus", "to", "tmpfile", "runs", "phyml", "tree", "inference", "and", "parses", "and", "returns", "the", "resulting", "tree", "." ]
python
valid
29.148148
pandas-dev/pandas
pandas/core/generic.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L3065-L3081
def get(self, key, default=None): """ Get item from object for given key (DataFrame column, Panel slice, etc.). Returns default value if not found. Parameters ---------- key : object Returns ------- value : same type as items contained in object ...
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", "[", "key", "]", "except", "(", "KeyError", ",", "ValueError", ",", "IndexError", ")", ":", "return", "default" ]
Get item from object for given key (DataFrame column, Panel slice, etc.). Returns default value if not found. Parameters ---------- key : object Returns ------- value : same type as items contained in object
[ "Get", "item", "from", "object", "for", "given", "key", "(", "DataFrame", "column", "Panel", "slice", "etc", ".", ")", ".", "Returns", "default", "value", "if", "not", "found", "." ]
python
train
25.588235
andreasjansson/head-in-the-clouds
headintheclouds/dependencies/PyDbLite/PyDbLite_SQL.py
https://github.com/andreasjansson/head-in-the-clouds/blob/32c1d00d01036834dc94368e7f38b0afd3f7a82f/headintheclouds/dependencies/PyDbLite/PyDbLite_SQL.py#L59-L70
def open(self): """Open an existing database""" if self._table_exists(): self.mode = "open" # get table info self._get_table_info() self.types = dict([ (f[0],self.conv_func[f[1].upper()]) for f in self.fields if f[1].upper() in self...
[ "def", "open", "(", "self", ")", ":", "if", "self", ".", "_table_exists", "(", ")", ":", "self", ".", "mode", "=", "\"open\"", "# get table info\r", "self", ".", "_get_table_info", "(", ")", "self", ".", "types", "=", "dict", "(", "[", "(", "f", "[",...
Open an existing database
[ "Open", "an", "existing", "database" ]
python
train
38
biocommons/biocommons.seqrepo
biocommons/seqrepo/fastadir/fabgz.py
https://github.com/biocommons/biocommons.seqrepo/blob/fb6d88682cb73ee6971cfa47d4dcd90a9c649167/biocommons/seqrepo/fastadir/fabgz.py#L32-L38
def _get_bgzip_version(exe): """return bgzip version as string""" p = subprocess.Popen([exe, "-h"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output = p.communicate() version_line = output[0].splitlines()[1] version = re.match(r"(?:Version:|bgzip \(htslib\))\s+(\d+\....
[ "def", "_get_bgzip_version", "(", "exe", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "exe", ",", "\"-h\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "universal_newlines", "=", ...
return bgzip version as string
[ "return", "bgzip", "version", "as", "string" ]
python
train
52.857143
lisael/fastidious
fastidious/parser_base.py
https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L74-L77
def p_debug(self, message): "Format and print debug messages" print("{}{} `{}`".format(self._debug_indent * " ", message, repr(self.p_suffix(10))))
[ "def", "p_debug", "(", "self", ",", "message", ")", ":", "print", "(", "\"{}{} `{}`\"", ".", "format", "(", "self", ".", "_debug_indent", "*", "\" \"", ",", "message", ",", "repr", "(", "self", ".", "p_suffix", "(", "10", ")", ")", ")", ")" ]
Format and print debug messages
[ "Format", "and", "print", "debug", "messages" ]
python
train
48.25
ramses-tech/nefertari
nefertari/view.py
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L160-L167
def set_override_rendered(self): """ Set self.request.override_renderer if needed. """ if '' in self.request.accept: self.request.override_renderer = self._default_renderer elif 'application/json' in self.request.accept: self.request.override_renderer = 'nefertari_json' ...
[ "def", "set_override_rendered", "(", "self", ")", ":", "if", "''", "in", "self", ".", "request", ".", "accept", ":", "self", ".", "request", ".", "override_renderer", "=", "self", ".", "_default_renderer", "elif", "'application/json'", "in", "self", ".", "re...
Set self.request.override_renderer if needed.
[ "Set", "self", ".", "request", ".", "override_renderer", "if", "needed", "." ]
python
train
51.875
Kozea/wdb
client/wdb/__init__.py
https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L946-L953
def breaks(self, frame, no_remove=False): """Return True if there's a breakpoint at frame""" for breakpoint in set(self.breakpoints): if breakpoint.breaks(frame): if breakpoint.temporary and not no_remove: self.breakpoints.remove(breakpoint) ...
[ "def", "breaks", "(", "self", ",", "frame", ",", "no_remove", "=", "False", ")", ":", "for", "breakpoint", "in", "set", "(", "self", ".", "breakpoints", ")", ":", "if", "breakpoint", ".", "breaks", "(", "frame", ")", ":", "if", "breakpoint", ".", "te...
Return True if there's a breakpoint at frame
[ "Return", "True", "if", "there", "s", "a", "breakpoint", "at", "frame" ]
python
train
43.375
wdecoster/nanoget
nanoget/extraction_functions.py
https://github.com/wdecoster/nanoget/blob/fb7306220e261849b96785fab02dd2f35a0e3b60/nanoget/extraction_functions.py#L290-L297
def process_fastq_plain(fastq, **kwargs): """Combine metrics extracted from a fastq file.""" logging.info("Nanoget: Starting to collect statistics from plain fastq file.") inputfastq = handle_compressed_input(fastq) return ut.reduce_memory_usage(pd.DataFrame( data=[res for res in extract_from_fa...
[ "def", "process_fastq_plain", "(", "fastq", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "info", "(", "\"Nanoget: Starting to collect statistics from plain fastq file.\"", ")", "inputfastq", "=", "handle_compressed_input", "(", "fastq", ")", "return", "ut", ".",...
Combine metrics extracted from a fastq file.
[ "Combine", "metrics", "extracted", "from", "a", "fastq", "file", "." ]
python
train
48.75
nion-software/nionswift
nion/swift/model/HardwareSource.py
https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/swift/model/HardwareSource.py#L1226-L1232
def pause(self) -> None: """Pause recording. Thread safe and UI safe.""" with self.__state_lock: if self.__state == DataChannelBuffer.State.started: self.__state = DataChannelBuffer.State.paused
[ "def", "pause", "(", "self", ")", "->", "None", ":", "with", "self", ".", "__state_lock", ":", "if", "self", ".", "__state", "==", "DataChannelBuffer", ".", "State", ".", "started", ":", "self", ".", "__state", "=", "DataChannelBuffer", ".", "State", "."...
Pause recording. Thread safe and UI safe.
[ "Pause", "recording", "." ]
python
train
34.428571
pantsbuild/pants
src/python/pants/goal/products.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/products.py#L100-L113
def get_product_target_mappings_for_targets(self, targets): """Gets the product-target associations for the given targets, preserving the input order. :API: public :param targets: The targets to lookup products for. :returns: The ordered (product, target) tuples. """ product_target_mappings = ...
[ "def", "get_product_target_mappings_for_targets", "(", "self", ",", "targets", ")", ":", "product_target_mappings", "=", "[", "]", "for", "target", "in", "targets", ":", "for", "product", "in", "self", ".", "_products_by_target", "[", "target", "]", ":", "produc...
Gets the product-target associations for the given targets, preserving the input order. :API: public :param targets: The targets to lookup products for. :returns: The ordered (product, target) tuples.
[ "Gets", "the", "product", "-", "target", "associations", "for", "the", "given", "targets", "preserving", "the", "input", "order", "." ]
python
train
34.642857
VIVelev/PyDojoML
dojo/metrics/classification.py
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/metrics/classification.py#L145-L166
def precision(y, y_pred): """Precision score precision = true_positives / (true_positives + false_positives) Parameters: ----------- y : vector, shape (n_samples,) The target labels. y_pred : vector, shape (n_samples,) The predicted labels. Returns: -------- preci...
[ "def", "precision", "(", "y", ",", "y_pred", ")", ":", "tp", "=", "true_positives", "(", "y", ",", "y_pred", ")", "fp", "=", "false_positives", "(", "y", ",", "y_pred", ")", "return", "tp", "/", "(", "tp", "+", "fp", ")" ]
Precision score precision = true_positives / (true_positives + false_positives) Parameters: ----------- y : vector, shape (n_samples,) The target labels. y_pred : vector, shape (n_samples,) The predicted labels. Returns: -------- precision : float
[ "Precision", "score" ]
python
train
19.227273
tensorflow/tensor2tensor
tensor2tensor/utils/yellowfin.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L308-L349
def _prepare_variables(self): """Prepare Variables for YellowFin. Returns: Grad**2, Norm, Norm**2, Mean(Norm**2) ops """ self._moving_averager = tf.train.ExponentialMovingAverage( decay=self._beta, zero_debias=self._zero_debias) # assert self._grad is not None and len(self._grad) > 0 ...
[ "def", "_prepare_variables", "(", "self", ")", ":", "self", ".", "_moving_averager", "=", "tf", ".", "train", ".", "ExponentialMovingAverage", "(", "decay", "=", "self", ".", "_beta", ",", "zero_debias", "=", "self", ".", "_zero_debias", ")", "# assert self._g...
Prepare Variables for YellowFin. Returns: Grad**2, Norm, Norm**2, Mean(Norm**2) ops
[ "Prepare", "Variables", "for", "YellowFin", "." ]
python
train
35.095238
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/user.py
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/user.py#L34-L42
def get_user_brief(): """Retrieve brief for current user (if any).""" client = get_user_api() with catch_raise_api_exception(): data, _, headers = client.user_self_with_http_info() ratelimits.maybe_rate_limit(client, headers) return data.authenticated, data.slug, data.email, data.name
[ "def", "get_user_brief", "(", ")", ":", "client", "=", "get_user_api", "(", ")", "with", "catch_raise_api_exception", "(", ")", ":", "data", ",", "_", ",", "headers", "=", "client", ".", "user_self_with_http_info", "(", ")", "ratelimits", ".", "maybe_rate_limi...
Retrieve brief for current user (if any).
[ "Retrieve", "brief", "for", "current", "user", "(", "if", "any", ")", "." ]
python
train
34.111111
matthewdeanmartin/jiggle_version
jiggle_version/central_module_finder.py
https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/central_module_finder.py#L171-L198
def remove_likely_non_central(self, candidates): # type: (List[str]) -> List[str] """ Stuff that is likely to be in find_packages(exclude...) :param candidates: :return: """ if len(candidates) > 1: for unlikely in [ "test", "te...
[ "def", "remove_likely_non_central", "(", "self", ",", "candidates", ")", ":", "# type: (List[str]) -> List[str]", "if", "len", "(", "candidates", ")", ">", "1", ":", "for", "unlikely", "in", "[", "\"test\"", ",", "\"tests\"", ",", "\"example\"", ",", "\"examples...
Stuff that is likely to be in find_packages(exclude...) :param candidates: :return:
[ "Stuff", "that", "is", "likely", "to", "be", "in", "find_packages", "(", "exclude", "...", ")", ":", "param", "candidates", ":", ":", "return", ":" ]
python
train
35.821429
PSPC-SPAC-buyandsell/von_anchor
von_anchor/anchor/holderprover.py
https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/holderprover.py#L720-L771
async def get_cred_infos_by_filter(self, filt: dict = None) -> str: """ Return cred-info (json list) from wallet by input filter for schema identifier and/or credential definition identifier components; return info of all credentials for no filter. Raise WalletState if the walle...
[ "async", "def", "get_cred_infos_by_filter", "(", "self", ",", "filt", ":", "dict", "=", "None", ")", "->", "str", ":", "LOGGER", ".", "debug", "(", "'HolderProver.get_cred_infos_by_filter >>> filt: %s'", ",", "filt", ")", "if", "not", "self", ".", "wallet", "....
Return cred-info (json list) from wallet by input filter for schema identifier and/or credential definition identifier components; return info of all credentials for no filter. Raise WalletState if the wallet is closed. :param filt: indy-sdk filter for credentials; i.e., :: ...
[ "Return", "cred", "-", "info", "(", "json", "list", ")", "from", "wallet", "by", "input", "filter", "for", "schema", "identifier", "and", "/", "or", "credential", "definition", "identifier", "components", ";", "return", "info", "of", "all", "credentials", "f...
python
train
35.865385
lawsie/guizero
guizero/ButtonGroup.py
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L290-L310
def update_command(self, command, args=None): """ Updates the callback command which is called when the ButtonGroup changes. Setting to `None` stops the callback. :param callback command: The callback function to call. :param callback args: A li...
[ "def", "update_command", "(", "self", ",", "command", ",", "args", "=", "None", ")", ":", "if", "command", "is", "None", ":", "self", ".", "_command", "=", "lambda", ":", "None", "else", ":", "if", "args", "is", "None", ":", "self", ".", "_command", ...
Updates the callback command which is called when the ButtonGroup changes. Setting to `None` stops the callback. :param callback command: The callback function to call. :param callback args: A list of arguments to pass to the widgets `command`, defaults to ...
[ "Updates", "the", "callback", "command", "which", "is", "called", "when", "the", "ButtonGroup", "changes", "." ]
python
train
29.857143
OpenKMIP/PyKMIP
kmip/core/messages/payloads/revoke.py
https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/messages/payloads/revoke.py#L172-L193
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the RevokeResponsePayload object and decode it into its constituent parts. Args: istream (Stream): A data stream containing encoded object data, supporting a read meth...
[ "def", "read", "(", "self", ",", "istream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "RevokeResponsePayload", ",", "self", ")", ".", "read", "(", "istream", ",", "kmip_version", "=", "kmip_version", ")...
Read the data encoding the RevokeResponsePayload object and decode it into its constituent parts. Args: istream (Stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enume...
[ "Read", "the", "data", "encoding", "the", "RevokeResponsePayload", "object", "and", "decode", "it", "into", "its", "constituent", "parts", ".", "Args", ":", "istream", "(", "Stream", ")", ":", "A", "data", "stream", "containing", "encoded", "object", "data", ...
python
test
41.227273
jwhitlock/drf-cached-instances
drf_cached_instances/models.py
https://github.com/jwhitlock/drf-cached-instances/blob/ec4e8a6e1e83eeea6ec0b924b2eaa40a38d5963a/drf_cached_instances/models.py#L95-L100
def pks(self): """Lazy-load the primary keys.""" if self._primary_keys is None: self._primary_keys = list( self.queryset.values_list('pk', flat=True)) return self._primary_keys
[ "def", "pks", "(", "self", ")", ":", "if", "self", ".", "_primary_keys", "is", "None", ":", "self", ".", "_primary_keys", "=", "list", "(", "self", ".", "queryset", ".", "values_list", "(", "'pk'", ",", "flat", "=", "True", ")", ")", "return", "self"...
Lazy-load the primary keys.
[ "Lazy", "-", "load", "the", "primary", "keys", "." ]
python
train
37.166667
EventTeam/beliefs
src/beliefs/cells/lists.py
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L84-L91
def is_entailed_by(self, other): """ Other is more specific than self. Other is bounded within self. """ other = self.coerce(other) to_i = self.to_i return to_i(other.low) >= to_i(self.low) and \ to_i(other.high) <= to_i(self.high)
[ "def", "is_entailed_by", "(", "self", ",", "other", ")", ":", "other", "=", "self", ".", "coerce", "(", "other", ")", "to_i", "=", "self", ".", "to_i", "return", "to_i", "(", "other", ".", "low", ")", ">=", "to_i", "(", "self", ".", "low", ")", "...
Other is more specific than self. Other is bounded within self.
[ "Other", "is", "more", "specific", "than", "self", ".", "Other", "is", "bounded", "within", "self", "." ]
python
train
36.25
mpapi/lazylights
lazylights.py
https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L319-L339
def run(self): """ Process all outgoing packets, until `stop()` is called. Intended to run in its own thread. """ while True: to_send = self._queue.get() if to_send is _SHUTDOWN: break # If we get a gateway object, connect to i...
[ "def", "run", "(", "self", ")", ":", "while", "True", ":", "to_send", "=", "self", ".", "_queue", ".", "get", "(", ")", "if", "to_send", "is", "_SHUTDOWN", ":", "break", "# If we get a gateway object, connect to it. Otherwise, assume", "# it's a bytestring and send ...
Process all outgoing packets, until `stop()` is called. Intended to run in its own thread.
[ "Process", "all", "outgoing", "packets", "until", "stop", "()", "is", "called", ".", "Intended", "to", "run", "in", "its", "own", "thread", "." ]
python
train
37.857143