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
balloob/pychromecast
pychromecast/socket_client.py
https://github.com/balloob/pychromecast/blob/831b09c4fed185a7bffe0ea330b7849d5f4e36b6/pychromecast/socket_client.py#L745-L762
def _ensure_channel_connected(self, destination_id): """ Ensure we opened a channel to destination_id. """ if destination_id not in self._open_channels: self._open_channels.append(destination_id) self.send_message( destination_id, NS_CONNECTION, {...
[ "def", "_ensure_channel_connected", "(", "self", ",", "destination_id", ")", ":", "if", "destination_id", "not", "in", "self", ".", "_open_channels", ":", "self", ".", "_open_channels", ".", "append", "(", "destination_id", ")", "self", ".", "send_message", "(",...
Ensure we opened a channel to destination_id.
[ "Ensure", "we", "opened", "a", "channel", "to", "destination_id", "." ]
python
train
42.777778
brainiak/brainiak
brainiak/fcma/classifier.py
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/fcma/classifier.py#L184-L220
def _normalize_correlation_data(self, corr_data, norm_unit): """Normalize the correlation data if necessary. Fisher-transform and then z-score the data for every norm_unit samples if norm_unit > 1. Parameters ---------- corr_data: the correlation data ...
[ "def", "_normalize_correlation_data", "(", "self", ",", "corr_data", ",", "norm_unit", ")", ":", "# normalize if necessary", "if", "norm_unit", ">", "1", ":", "num_samples", "=", "len", "(", "corr_data", ")", "[", "_", ",", "d2", ",", "d3", "]", "=", "corr...
Normalize the correlation data if necessary. Fisher-transform and then z-score the data for every norm_unit samples if norm_unit > 1. Parameters ---------- corr_data: the correlation data in shape [num_samples, num_processed_voxels, num_voxels] norm_...
[ "Normalize", "the", "correlation", "data", "if", "necessary", "." ]
python
train
39.108108
praekelt/jmbo-gallery
gallery/models.py
https://github.com/praekelt/jmbo-gallery/blob/064e005913d79e456ba014b50205c7916df4714a/gallery/models.py#L64-L69
def youtube_id(self): """Extract and return Youtube video id""" m = re.search(r'/embed/([A-Za-z0-9\-=_]*)', self.embed) if m: return m.group(1) return ''
[ "def", "youtube_id", "(", "self", ")", ":", "m", "=", "re", ".", "search", "(", "r'/embed/([A-Za-z0-9\\-=_]*)'", ",", "self", ".", "embed", ")", "if", "m", ":", "return", "m", ".", "group", "(", "1", ")", "return", "''" ]
Extract and return Youtube video id
[ "Extract", "and", "return", "Youtube", "video", "id" ]
python
train
32
MacHu-GWU/angora-project
angora/dataIO/pk.py
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/pk.py#L363-L379
def obj2str(obj, pk_protocol=pk_protocol): """Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1L...
[ "def", "obj2str", "(", "obj", ",", "pk_protocol", "=", "pk_protocol", ")", ":", "return", "base64", ".", "b64encode", "(", "pickle", ".", "dumps", "(", "obj", ",", "protocol", "=", "pk_protocol", ")", ")", ".", "decode", "(", "\"utf-8\"", ")" ]
Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1Lg==' **中文文档** 将可Pickle化的Python对象转化为utf-8...
[ "Convert", "arbitrary", "object", "to", "utf", "-", "8", "string", "using", "base64encode", "algorithm", "." ]
python
train
27.294118
google/dotty
efilter/parsers/common/tokenizer.py
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/common/tokenizer.py#L259-L266
def _parse_next_token(self): """Will parse patterns until it gets to the next token or EOF.""" while self._position < self.limit: token = self._next_pattern() if token: return token return None
[ "def", "_parse_next_token", "(", "self", ")", ":", "while", "self", ".", "_position", "<", "self", ".", "limit", ":", "token", "=", "self", ".", "_next_pattern", "(", ")", "if", "token", ":", "return", "token", "return", "None" ]
Will parse patterns until it gets to the next token or EOF.
[ "Will", "parse", "patterns", "until", "it", "gets", "to", "the", "next", "token", "or", "EOF", "." ]
python
train
31.375
twilio/twilio-python
twilio/rest/api/v2010/account/queue/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/queue/__init__.py#L347-L361
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: QueueContext for this QueueInstance :rtype: twilio.rest.api.v2010.account.queue.QueueContext ...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "QueueContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "si...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: QueueContext for this QueueInstance :rtype: twilio.rest.api.v2010.account.queue.QueueContext
[ "Generate", "an", "instance", "context", "for", "the", "instance", "the", "context", "is", "capable", "of", "performing", "various", "actions", ".", "All", "instance", "actions", "are", "proxied", "to", "the", "context" ]
python
train
37.666667
santoshphilip/eppy
eppy/modeleditor.py
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/modeleditor.py#L713-L755
def newidfobject(self, key, aname='', defaultvalues=True, **kwargs): """ Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", ...
[ "def", "newidfobject", "(", "self", ",", "key", ",", "aname", "=", "''", ",", "defaultvalues", "=", "True", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "newrawobject", "(", "self", ".", "model", ",", "self", ".", "idd_info", ",", "key", ",", "bl...
Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", Name='Interior Ceiling_class', Outside_Layer='LW Concrete', ...
[ "Add", "a", "new", "idfobject", "to", "the", "model", ".", "If", "you", "don", "t", "specify", "a", "value", "for", "a", "field", "the", "default", "value", "will", "be", "set", "." ]
python
train
34.697674
moonlitesolutions/SolrClient
SolrClient/solrresp.py
https://github.com/moonlitesolutions/SolrClient/blob/19c5280c9f8e97ee104d22ae883c4ccfd7c4f43b/SolrClient/solrresp.py#L222-L231
def get_field_values_as_list(self,field): ''' :param str field: The name of the field for which to pull in values. Will parse the query results (must be ungrouped) and return all values of 'field' as a list. Note that these are not unique values. Example:: >>> r.get_field_values_as...
[ "def", "get_field_values_as_list", "(", "self", ",", "field", ")", ":", "return", "[", "doc", "[", "field", "]", "for", "doc", "in", "self", ".", "docs", "if", "field", "in", "doc", "]" ]
:param str field: The name of the field for which to pull in values. Will parse the query results (must be ungrouped) and return all values of 'field' as a list. Note that these are not unique values. Example:: >>> r.get_field_values_as_list('product_name_exact') ['Mauris risus risus l...
[ ":", "param", "str", "field", ":", "The", "name", "of", "the", "field", "for", "which", "to", "pull", "in", "values", ".", "Will", "parse", "the", "query", "results", "(", "must", "be", "ungrouped", ")", "and", "return", "all", "values", "of", "field",...
python
train
77.1
mbj4668/pyang
pyang/__init__.py
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/__init__.py#L138-L141
def del_module(self, module): """Remove a module from the context""" rev = util.get_latest_revision(module) del self.modules[(module.arg, rev)]
[ "def", "del_module", "(", "self", ",", "module", ")", ":", "rev", "=", "util", ".", "get_latest_revision", "(", "module", ")", "del", "self", ".", "modules", "[", "(", "module", ".", "arg", ",", "rev", ")", "]" ]
Remove a module from the context
[ "Remove", "a", "module", "from", "the", "context" ]
python
train
41
googleapis/google-auth-library-python
google/oauth2/id_token.py
https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/oauth2/id_token.py#L144-L159
def verify_firebase_token(id_token, request, audience=None): """Verifies an ID Token issued by Firebase Authentication. Args: id_token (Union[str, bytes]): The encoded token. request (google.auth.transport.Request): The object used to make HTTP requests. audience (str): The ...
[ "def", "verify_firebase_token", "(", "id_token", ",", "request", ",", "audience", "=", "None", ")", ":", "return", "verify_token", "(", "id_token", ",", "request", ",", "audience", "=", "audience", ",", "certs_url", "=", "_GOOGLE_APIS_CERTS_URL", ")" ]
Verifies an ID Token issued by Firebase Authentication. Args: id_token (Union[str, bytes]): The encoded token. request (google.auth.transport.Request): The object used to make HTTP requests. audience (str): The audience that this token is intended for. This is typica...
[ "Verifies", "an", "ID", "Token", "issued", "by", "Firebase", "Authentication", "." ]
python
train
39.625
softlayer/softlayer-python
SoftLayer/managers/load_balancer.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L27-L41
def get_lb_pkgs(self): """Retrieves the local load balancer packages. :returns: A dictionary containing the load balancer packages """ _filter = {'items': {'description': utils.query_filter('*Load Balancer*')}} packages = self.prod_pkg.getItems(id=...
[ "def", "get_lb_pkgs", "(", "self", ")", ":", "_filter", "=", "{", "'items'", ":", "{", "'description'", ":", "utils", ".", "query_filter", "(", "'*Load Balancer*'", ")", "}", "}", "packages", "=", "self", ".", "prod_pkg", ".", "getItems", "(", "id", "=",...
Retrieves the local load balancer packages. :returns: A dictionary containing the load balancer packages
[ "Retrieves", "the", "local", "load", "balancer", "packages", "." ]
python
train
33.066667
koordinates/python-client
koordinates/publishing.py
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/publishing.py#L56-L60
def cancel(self): """ Cancel a pending publish task """ target_url = self._client.get_url('PUBLISH', 'DELETE', 'single', {'id': self.id}) r = self._client.request('DELETE', target_url) logger.info("cancel(): %s", r.status_code)
[ "def", "cancel", "(", "self", ")", ":", "target_url", "=", "self", ".", "_client", ".", "get_url", "(", "'PUBLISH'", ",", "'DELETE'", ",", "'single'", ",", "{", "'id'", ":", "self", ".", "id", "}", ")", "r", "=", "self", ".", "_client", ".", "reque...
Cancel a pending publish task
[ "Cancel", "a", "pending", "publish", "task" ]
python
train
51
SmokinCaterpillar/pypet
examples/example_06_parameter_presetting.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_06_parameter_presetting.py#L56-L72
def diff_roessler(value_array, a, c): """The Roessler attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param a: Constant attractor parameter :param c: Constant attractor parameter :return: 3d array of the Roessler system evaluated at `value_...
[ "def", "diff_roessler", "(", "value_array", ",", "a", ",", "c", ")", ":", "b", "=", "a", "diff_array", "=", "np", ".", "zeros", "(", "3", ")", "diff_array", "[", "0", "]", "=", "-", "value_array", "[", "1", "]", "-", "value_array", "[", "2", "]",...
The Roessler attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param a: Constant attractor parameter :param c: Constant attractor parameter :return: 3d array of the Roessler system evaluated at `value_array`
[ "The", "Roessler", "attractor", "differential", "equation" ]
python
test
32.352941
ajdavis/mongo-mockup-db
mockupdb/__init__.py
https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1793-L1804
def mock_server_receive(sock, length): """Receive `length` bytes from a socket object.""" msg = b'' while length: chunk = sock.recv(length) if chunk == b'': raise socket.error(errno.ECONNRESET, 'closed') length -= len(chunk) msg += chunk return msg
[ "def", "mock_server_receive", "(", "sock", ",", "length", ")", ":", "msg", "=", "b''", "while", "length", ":", "chunk", "=", "sock", ".", "recv", "(", "length", ")", "if", "chunk", "==", "b''", ":", "raise", "socket", ".", "error", "(", "errno", ".",...
Receive `length` bytes from a socket object.
[ "Receive", "length", "bytes", "from", "a", "socket", "object", "." ]
python
train
24.916667
IntegralDefense/critsapi
critsapi/critsdbapi.py
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L68-L74
def connect(self): """ Starts the mongodb connection. Must be called before anything else will work. """ self.client = MongoClient(self.mongo_uri) self.db = self.client[self.db_name]
[ "def", "connect", "(", "self", ")", ":", "self", ".", "client", "=", "MongoClient", "(", "self", ".", "mongo_uri", ")", "self", ".", "db", "=", "self", ".", "client", "[", "self", ".", "db_name", "]" ]
Starts the mongodb connection. Must be called before anything else will work.
[ "Starts", "the", "mongodb", "connection", ".", "Must", "be", "called", "before", "anything", "else", "will", "work", "." ]
python
train
32
luckydonald/pytgbot
pytgbot/api_types/receivable/passport.py
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/passport.py#L186-L197
def to_array(self): """ Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(PassportFile, self).to_array() array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str a...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "PassportFile", ",", "self", ")", ".", "to_array", "(", ")", "array", "[", "'file_id'", "]", "=", "u", "(", "self", ".", "file_id", ")", "# py2: type unicode, py3: type str", "array", ...
Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict
[ "Serializes", "this", "PassportFile", "to", "a", "dictionary", "." ]
python
train
36.833333
minhhoit/yacms
yacms/core/models.py
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L451-L468
def _get_next_or_previous_by_order(self, is_next, **kwargs): """ Retrieves next or previous object by order. We implement our own version instead of Django's so we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method. """ ...
[ "def", "_get_next_or_previous_by_order", "(", "self", ",", "is_next", ",", "*", "*", "kwargs", ")", ":", "lookup", "=", "self", ".", "with_respect_to", "(", ")", "lookup", "[", "\"_order\"", "]", "=", "self", ".", "_order", "+", "(", "1", "if", "is_next"...
Retrieves next or previous object by order. We implement our own version instead of Django's so we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method.
[ "Retrieves", "next", "or", "previous", "object", "by", "order", ".", "We", "implement", "our", "own", "version", "instead", "of", "Django", "s", "so", "we", "can", "hook", "into", "the", "published", "manager", "concrete", "subclasses", "and", "our", "custom...
python
train
41.277778
saltstack/salt
salt/modules/pkgutil.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkgutil.py#L77-L99
def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613 ''' List all available package upgrades on this system CLI Example: .. code-block:: bash salt '*' pkgutil.list_upgrades ''' if salt.utils.data.is_true(refresh): refresh_db() upgrades = {} lines = __sal...
[ "def", "list_upgrades", "(", "refresh", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "if", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "refresh", ")", ":", "refresh_db", "(", ")", "upgrades", "=", "{", "}", "li...
List all available package upgrades on this system CLI Example: .. code-block:: bash salt '*' pkgutil.list_upgrades
[ "List", "all", "available", "package", "upgrades", "on", "this", "system" ]
python
train
26.217391
ANTsX/ANTsPy
ants/utils/ndimage_to_list.py
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/ndimage_to_list.py#L67-L113
def ndimage_to_list(image): """ Split a n dimensional ANTsImage into a list of n-1 dimensional ANTsImages Arguments --------- image : ANTsImage n-dimensional image to split Returns ------- list of ANTsImage types Example ------- >>> import ants >>> image = ...
[ "def", "ndimage_to_list", "(", "image", ")", ":", "inpixeltype", "=", "image", ".", "pixeltype", "dimension", "=", "image", ".", "dimension", "components", "=", "1", "imageShape", "=", "image", ".", "shape", "nSections", "=", "imageShape", "[", "dimension", ...
Split a n dimensional ANTsImage into a list of n-1 dimensional ANTsImages Arguments --------- image : ANTsImage n-dimensional image to split Returns ------- list of ANTsImage types Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16'...
[ "Split", "a", "n", "dimensional", "ANTsImage", "into", "a", "list", "of", "n", "-", "1", "dimensional", "ANTsImages" ]
python
train
31.446809
edeposit/edeposit.amqp.serializers
src/edeposit/amqp/serializers/serializers.py
https://github.com/edeposit/edeposit.amqp.serializers/blob/44409db650b16658e778255e420da9f14ef9f197/src/edeposit/amqp/serializers/serializers.py#L178-L209
def iiOfAny(instance, classes): """ Returns true, if `instance` is instance of any (iiOfAny) of the `classes`. This function doesn't use :py:func:`isinstance` check, it just compares the `class` names. This can be generaly dangerous, but it is really useful when you are comparing class seriali...
[ "def", "iiOfAny", "(", "instance", ",", "classes", ")", ":", "if", "type", "(", "classes", ")", "not", "in", "[", "list", ",", "tuple", "]", ":", "classes", "=", "[", "classes", "]", "return", "any", "(", "type", "(", "instance", ")", ".", "__name_...
Returns true, if `instance` is instance of any (iiOfAny) of the `classes`. This function doesn't use :py:func:`isinstance` check, it just compares the `class` names. This can be generaly dangerous, but it is really useful when you are comparing class serialized in one module and deserialized in anothe...
[ "Returns", "true", "if", "instance", "is", "instance", "of", "any", "(", "iiOfAny", ")", "of", "the", "classes", "." ]
python
train
34.65625
JukeboxPipeline/jukebox-core
src/jukeboxcore/main.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/main.py#L13-L22
def init_environment(): """Set environment variables that are important for the pipeline. :returns: None :rtype: None :raises: None """ os.environ['DJANGO_SETTINGS_MODULE'] = 'jukeboxcore.djsettings' pluginpath = os.pathsep.join((os.environ.get('JUKEBOX_PLUGIN_PATH', ''), constants.BUILTIN_...
[ "def", "init_environment", "(", ")", ":", "os", ".", "environ", "[", "'DJANGO_SETTINGS_MODULE'", "]", "=", "'jukeboxcore.djsettings'", "pluginpath", "=", "os", ".", "pathsep", ".", "join", "(", "(", "os", ".", "environ", ".", "get", "(", "'JUKEBOX_PLUGIN_PATH'...
Set environment variables that are important for the pipeline. :returns: None :rtype: None :raises: None
[ "Set", "environment", "variables", "that", "are", "important", "for", "the", "pipeline", "." ]
python
train
37.5
basilfx/flask-daapserver
daapserver/provider.py
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L96-L118
def create_session(self, user_agent, remote_address, client_version): """ Create a new session. :param str user_agent: Client user agent :param str remote_addr: Remote address of client :param str client_version: Remote client version :return: The new session id ...
[ "def", "create_session", "(", "self", ",", "user_agent", ",", "remote_address", ",", "client_version", ")", ":", "self", ".", "session_counter", "+=", "1", "self", ".", "sessions", "[", "self", ".", "session_counter", "]", "=", "session", "=", "self", ".", ...
Create a new session. :param str user_agent: Client user agent :param str remote_addr: Remote address of client :param str client_version: Remote client version :return: The new session id :rtype: int
[ "Create", "a", "new", "session", "." ]
python
train
32.086957
noxdafox/vminspect
vminspect/filesystem.py
https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/filesystem.py#L142-L144
def checksum(self, path, hashtype='sha1'): """Returns the checksum of the given path.""" return self._handler.checksum(hashtype, posix_path(path))
[ "def", "checksum", "(", "self", ",", "path", ",", "hashtype", "=", "'sha1'", ")", ":", "return", "self", ".", "_handler", ".", "checksum", "(", "hashtype", ",", "posix_path", "(", "path", ")", ")" ]
Returns the checksum of the given path.
[ "Returns", "the", "checksum", "of", "the", "given", "path", "." ]
python
train
53.333333
tensorflow/tensorboard
tensorboard/util/tensor_util.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/util/tensor_util.py#L280-L480
def make_tensor_proto(values, dtype=None, shape=None, verify_shape=False): """Create a TensorProto. Args: values: Values to put in the TensorProto. dtype: Optional tensor_pb2 DataType value. shape: List of integers representing the dimensions of tensor. verify_shape: B...
[ "def", "make_tensor_proto", "(", "values", ",", "dtype", "=", "None", ",", "shape", "=", "None", ",", "verify_shape", "=", "False", ")", ":", "if", "isinstance", "(", "values", ",", "tensor_pb2", ".", "TensorProto", ")", ":", "return", "values", "if", "d...
Create a TensorProto. Args: values: Values to put in the TensorProto. dtype: Optional tensor_pb2 DataType value. shape: List of integers representing the dimensions of tensor. verify_shape: Boolean that enables verification of a shape of values. Returns: A `TensorPr...
[ "Create", "a", "TensorProto", "." ]
python
train
39.641791
singularityhub/singularity-cli
spython/main/execute.py
https://github.com/singularityhub/singularity-cli/blob/cb36b4504812ca87e29c6a40b222a545d1865799/spython/main/execute.py#L15-L92
def execute(self, image = None, command = None, app = None, writable = False, contain = False, bind = None, stream = False, nv = False, return_result=False): ''' execute: send a command to a container ...
[ "def", "execute", "(", "self", ",", "image", "=", "None", ",", "command", "=", "None", ",", "app", "=", "None", ",", "writable", "=", "False", ",", "contain", "=", "False", ",", "bind", "=", "None", ",", "stream", "=", "False", ",", "nv", "=", "F...
execute: send a command to a container Parameters ========== image: full path to singularity image command: command to send to container app: if not None, execute a command in context of an app writable: This option makes the file system accessible as read/write ...
[ "execute", ":", "send", "a", "command", "to", "a", "container", "Parameters", "==========" ]
python
train
31.320513
novopl/peltak
src/peltak/commands/__init__.py
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/commands/__init__.py#L57-L92
def pretend_option(fn): # type: (FunctionType) -> FunctionType """ Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'pretend' if the command n...
[ "def", "pretend_option", "(", "fn", ")", ":", "# type: (FunctionType) -> FunctionType", "def", "set_pretend", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=missing-docstring", "# type: (click.Context, str, Any) -> None", "from", "peltak", ".", "core...
Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'pretend' if the command needs it. To get the current value you can do: >>> from peltak.comm...
[ "Decorator", "to", "add", "a", "--", "pretend", "option", "to", "any", "click", "command", "." ]
python
train
34.611111
nerdvegas/rez
src/rez/bind/_utils.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/bind/_utils.py#L45-L54
def check_version(version, range_=None): """Check that the found software version is within supplied range. Args: version: Version of the package as a Version object. range_: Allowable version range as a VersionRange object. """ if range_ and version not in range_: raise RezBind...
[ "def", "check_version", "(", "version", ",", "range_", "=", "None", ")", ":", "if", "range_", "and", "version", "not", "in", "range_", ":", "raise", "RezBindError", "(", "\"found version %s is not within range %s\"", "%", "(", "str", "(", "version", ")", ",", ...
Check that the found software version is within supplied range. Args: version: Version of the package as a Version object. range_: Allowable version range as a VersionRange object.
[ "Check", "that", "the", "found", "software", "version", "is", "within", "supplied", "range", "." ]
python
train
41.6
dims/etcd3-gateway
etcd3gw/client.py
https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L165-L183
def put(self, key, value, lease=None): """Put puts the given key into the key-value store. A put request increments the revision of the key-value store and generates one event in the event history. :param key: :param value: :param lease: :return: boolean ...
[ "def", "put", "(", "self", ",", "key", ",", "value", ",", "lease", "=", "None", ")", ":", "payload", "=", "{", "\"key\"", ":", "_encode", "(", "key", ")", ",", "\"value\"", ":", "_encode", "(", "value", ")", "}", "if", "lease", ":", "payload", "[...
Put puts the given key into the key-value store. A put request increments the revision of the key-value store and generates one event in the event history. :param key: :param value: :param lease: :return: boolean
[ "Put", "puts", "the", "given", "key", "into", "the", "key", "-", "value", "store", "." ]
python
train
28.421053
gwpy/gwpy
gwpy/timeseries/timeseries.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/timeseries/timeseries.py#L1005-L1133
def filter(self, *filt, **kwargs): """Filter this `TimeSeries` with an IIR or FIR filter Parameters ---------- *filt : filter arguments 1, 2, 3, or 4 arguments defining the filter to be applied, - an ``Nx1`` `~numpy.ndarray` of FIR coefficients ...
[ "def", "filter", "(", "self", ",", "*", "filt", ",", "*", "*", "kwargs", ")", ":", "# parse keyword arguments", "filtfilt", "=", "kwargs", ".", "pop", "(", "'filtfilt'", ",", "False", ")", "# parse filter", "form", ",", "filt", "=", "filter_design", ".", ...
Filter this `TimeSeries` with an IIR or FIR filter Parameters ---------- *filt : filter arguments 1, 2, 3, or 4 arguments defining the filter to be applied, - an ``Nx1`` `~numpy.ndarray` of FIR coefficients - an ``Nx6`` `~numpy.ndarray` of SOS coeffi...
[ "Filter", "this", "TimeSeries", "with", "an", "IIR", "or", "FIR", "filter" ]
python
train
34.031008
wummel/linkchecker
third_party/dnspython/dns/zone.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/zone.py#L161-L179
def find_node(self, name, create=False): """Find a node in the zone, possibly creating it. @param name: the name of the node to find @type name: dns.name.Name object or string @param create: should the node be created if it doesn't exist? @type create: bool @raises KeyEr...
[ "def", "find_node", "(", "self", ",", "name", ",", "create", "=", "False", ")", ":", "name", "=", "self", ".", "_validate_name", "(", "name", ")", "node", "=", "self", ".", "nodes", ".", "get", "(", "name", ")", "if", "node", "is", "None", ":", "...
Find a node in the zone, possibly creating it. @param name: the name of the node to find @type name: dns.name.Name object or string @param create: should the node be created if it doesn't exist? @type create: bool @raises KeyError: the name is not known and create was not specif...
[ "Find", "a", "node", "in", "the", "zone", "possibly", "creating", "it", "." ]
python
train
34.894737
aliyun/aliyun-odps-python-sdk
odps/df/expr/collections.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/collections.py#L435-L540
def apply(expr, func, axis=0, names=None, types=None, reduce=False, resources=None, keep_nulls=False, args=(), **kwargs): """ Apply a function to a row when axis=1 or column when axis=0. :param expr: :param func: function to apply :param axis: row when axis=1 else column :param names:...
[ "def", "apply", "(", "expr", ",", "func", ",", "axis", "=", "0", ",", "names", "=", "None", ",", "types", "=", "None", ",", "reduce", "=", "False", ",", "resources", "=", "None", ",", "keep_nulls", "=", "False", ",", "args", "=", "(", ")", ",", ...
Apply a function to a row when axis=1 or column when axis=0. :param expr: :param func: function to apply :param axis: row when axis=1 else column :param names: output names :param types: output types :param reduce: if True will return a sequence else return a collection :param resources: re...
[ "Apply", "a", "function", "to", "a", "row", "when", "axis", "=", "1", "or", "column", "when", "axis", "=", "0", "." ]
python
train
37.886792
Accelize/pycosio
pycosio/_core/functions_os_path.py
https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os_path.py#L108-L124
def isdir(path): """ Return True if path is an existing directory. Equivalent to "os.path.isdir". Args: path (path-like object): Path or URL. Returns: bool: True if directory exists. """ system = get_instance(path) # User may use directory path without trailing '/' ...
[ "def", "isdir", "(", "path", ")", ":", "system", "=", "get_instance", "(", "path", ")", "# User may use directory path without trailing '/'", "# like on standard file systems", "return", "system", ".", "isdir", "(", "system", ".", "ensure_dir_path", "(", "path", ")", ...
Return True if path is an existing directory. Equivalent to "os.path.isdir". Args: path (path-like object): Path or URL. Returns: bool: True if directory exists.
[ "Return", "True", "if", "path", "is", "an", "existing", "directory", "." ]
python
train
23
tnkteja/myhelp
virtualEnvironment/lib/python2.7/site-packages/coverage/config.py
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/config.py#L148-L154
def from_args(self, **kwargs): """Read config values from `kwargs`.""" for k, v in iitems(kwargs): if v is not None: if k in self.MUST_BE_LIST and isinstance(v, string_class): v = [v] setattr(self, k, v)
[ "def", "from_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "k", ",", "v", "in", "iitems", "(", "kwargs", ")", ":", "if", "v", "is", "not", "None", ":", "if", "k", "in", "self", ".", "MUST_BE_LIST", "and", "isinstance", "(", "v", ...
Read config values from `kwargs`.
[ "Read", "config", "values", "from", "kwargs", "." ]
python
test
39.571429
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/session.py
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/session.py#L22-L131
def get_session(user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> requests.Session """Set up and return Session object that is set up with retrying. Requires either global user agent to be set or appropriate user ag...
[ "def", "get_session", "(", "user_agent", "=", "None", ",", "user_agent_config_yaml", "=", "None", ",", "user_agent_lookup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (Optional[str], Optional[str], Optional[str], Any) -> requests.Session", "s", "=", "reque...
Set up and return Session object that is set up with retrying. Requires either global user agent to be set or appropriate user agent parameter(s) to be completed. Args: user_agent (Optional[str]): User agent string. HDXPythonUtilities/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): ...
[ "Set", "up", "and", "return", "Session", "object", "that", "is", "set", "up", "with", "retrying", ".", "Requires", "either", "global", "user", "agent", "to", "be", "set", "or", "appropriate", "user", "agent", "parameter", "(", "s", ")", "to", "be", "comp...
python
train
49.745455
saltstack/salt
salt/returners/couchbase_return.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L211-L235
def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.tex...
[ "def", "save_load", "(", "jid", ",", "clear_load", ",", "minion", "=", "None", ")", ":", "cb_", "=", "_get_connection", "(", ")", "try", ":", "jid_doc", "=", "cb_", ".", "get", "(", "six", ".", "text_type", "(", "jid", ")", ")", "except", "couchbase"...
Save the load to the specified jid
[ "Save", "the", "load", "to", "the", "specified", "jid" ]
python
train
33.4
materialsproject/pymatgen
pymatgen/analysis/wulff.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/wulff.py#L255-L269
def _get_cross_pt_dual_simp(self, dual_simp): """ |normal| = 1, e_surf is plane's distance to (0, 0, 0), plane function: normal[0]x + normal[1]y + normal[2]z = e_surf from self: normal_e_m to get the plane functions dual_simp: (i, j, k) simplices from...
[ "def", "_get_cross_pt_dual_simp", "(", "self", ",", "dual_simp", ")", ":", "matrix_surfs", "=", "[", "self", ".", "facets", "[", "dual_simp", "[", "i", "]", "]", ".", "normal", "for", "i", "in", "range", "(", "3", ")", "]", "matrix_e", "=", "[", "sel...
|normal| = 1, e_surf is plane's distance to (0, 0, 0), plane function: normal[0]x + normal[1]y + normal[2]z = e_surf from self: normal_e_m to get the plane functions dual_simp: (i, j, k) simplices from the dual convex hull i, j, k: plane index(same or...
[ "|normal|", "=", "1", "e_surf", "is", "plane", "s", "distance", "to", "(", "0", "0", "0", ")", "plane", "function", ":", "normal", "[", "0", "]", "x", "+", "normal", "[", "1", "]", "y", "+", "normal", "[", "2", "]", "z", "=", "e_surf" ]
python
train
42.6
ArabellaTech/django-basic-cms
basic_cms/templatetags/pages_tags.py
https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/templatetags/pages_tags.py#L460-L465
def do_videoplaceholder(parser, token): """ Method that parse the imageplaceholder template tag. """ name, params = parse_placeholder(parser, token) return VideoPlaceholderNode(name, **params)
[ "def", "do_videoplaceholder", "(", "parser", ",", "token", ")", ":", "name", ",", "params", "=", "parse_placeholder", "(", "parser", ",", "token", ")", "return", "VideoPlaceholderNode", "(", "name", ",", "*", "*", "params", ")" ]
Method that parse the imageplaceholder template tag.
[ "Method", "that", "parse", "the", "imageplaceholder", "template", "tag", "." ]
python
train
34.5
aaugustin/websockets
src/websockets/framing.py
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/framing.py#L243-L265
def check(frame) -> None: """ Check that this frame contains acceptable values. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this frame contains incorrect values. """ # The first parameter is called `frame` rather than `self`, # but it's the ins...
[ "def", "check", "(", "frame", ")", "->", "None", ":", "# The first parameter is called `frame` rather than `self`,", "# but it's the instance of class to which this method is bound.", "if", "frame", ".", "rsv1", "or", "frame", ".", "rsv2", "or", "frame", ".", "rsv3", ":",...
Check that this frame contains acceptable values. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this frame contains incorrect values.
[ "Check", "that", "this", "frame", "contains", "acceptable", "values", "." ]
python
train
37.782609
Workiva/furious
furious/context/context.py
https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L335-L345
def result(self): """Return the context result object pulled from the persistence_engine if it has been set. """ if not self._result: if not self._persistence_engine: return None self._result = self._persistence_engine.get_context_result(self) ...
[ "def", "result", "(", "self", ")", ":", "if", "not", "self", ".", "_result", ":", "if", "not", "self", ".", "_persistence_engine", ":", "return", "None", "self", ".", "_result", "=", "self", ".", "_persistence_engine", ".", "get_context_result", "(", "self...
Return the context result object pulled from the persistence_engine if it has been set.
[ "Return", "the", "context", "result", "object", "pulled", "from", "the", "persistence_engine", "if", "it", "has", "been", "set", "." ]
python
train
30.454545
condereis/realtime-stock
rtstock/utils.py
https://github.com/condereis/realtime-stock/blob/5b3110d0bc2fd3e8354ab2edb5cfe6cafd6f2a94/rtstock/utils.py#L173-L196
def download_historical(tickers_list, output_folder): """Download historical data from Yahoo Finance. Downloads full historical data from Yahoo Finance as CSV. The following fields are available: Adj Close, Close, High, Low, Open and Volume. Files will be saved to output_folder as <ticker>.csv. :p...
[ "def", "download_historical", "(", "tickers_list", ",", "output_folder", ")", ":", "__validate_list", "(", "tickers_list", ")", "for", "ticker", "in", "tickers_list", ":", "file_name", "=", "os", ".", "path", ".", "join", "(", "output_folder", ",", "ticker", "...
Download historical data from Yahoo Finance. Downloads full historical data from Yahoo Finance as CSV. The following fields are available: Adj Close, Close, High, Low, Open and Volume. Files will be saved to output_folder as <ticker>.csv. :param tickers_list: List of tickers that will be returned. ...
[ "Download", "historical", "data", "from", "Yahoo", "Finance", "." ]
python
train
43.708333
google/prettytensor
prettytensor/pretty_tensor_class.py
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_class.py#L1282-L1306
def attach_template(self, _template, _key, **unbound_var_values): """Attaches the template to this with the _key is supplied with this layer. Note: names were chosen to avoid conflicts. Args: _template: The template to construct. _key: The key that this layer should replace. **unbound_va...
[ "def", "attach_template", "(", "self", ",", "_template", ",", "_key", ",", "*", "*", "unbound_var_values", ")", ":", "if", "_key", "in", "unbound_var_values", ":", "raise", "ValueError", "(", "'%s specified twice.'", "%", "_key", ")", "unbound_var_values", "[", ...
Attaches the template to this with the _key is supplied with this layer. Note: names were chosen to avoid conflicts. Args: _template: The template to construct. _key: The key that this layer should replace. **unbound_var_values: The values for the unbound_vars. Returns: A new layer...
[ "Attaches", "the", "template", "to", "this", "with", "the", "_key", "is", "supplied", "with", "this", "layer", "." ]
python
train
38.96
python-cmd2/cmd2
cmd2/cmd2.py
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2037-L2069
def onecmd(self, statement: Union[Statement, str]) -> bool: """ This executes the actual do_* method for a command. If the command provided doesn't exist, then it executes default() instead. :param statement: intended to be a Statement instance parsed command from the input stream, alternative...
[ "def", "onecmd", "(", "self", ",", "statement", ":", "Union", "[", "Statement", ",", "str", "]", ")", "->", "bool", ":", "# For backwards compatibility with cmd, allow a str to be passed in", "if", "not", "isinstance", "(", "statement", ",", "Statement", ")", ":",...
This executes the actual do_* method for a command. If the command provided doesn't exist, then it executes default() instead. :param statement: intended to be a Statement instance parsed command from the input stream, alternative acceptance of a str is present only for backw...
[ "This", "executes", "the", "actual", "do_", "*", "method", "for", "a", "command", "." ]
python
train
40.484848
scanny/python-pptx
pptx/chart/axis.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/axis.py#L114-L122
def major_tick_mark(self): """ Read/write :ref:`XlTickMark` value specifying the type of major tick mark to display on this axis. """ majorTickMark = self._element.majorTickMark if majorTickMark is None: return XL_TICK_MARK.CROSS return majorTickMark.v...
[ "def", "major_tick_mark", "(", "self", ")", ":", "majorTickMark", "=", "self", ".", "_element", ".", "majorTickMark", "if", "majorTickMark", "is", "None", ":", "return", "XL_TICK_MARK", ".", "CROSS", "return", "majorTickMark", ".", "val" ]
Read/write :ref:`XlTickMark` value specifying the type of major tick mark to display on this axis.
[ "Read", "/", "write", ":", "ref", ":", "XlTickMark", "value", "specifying", "the", "type", "of", "major", "tick", "mark", "to", "display", "on", "this", "axis", "." ]
python
train
34.888889
sprockets/sprockets.mixins.metrics
examples/statsd.py
https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/examples/statsd.py#L34-L48
def make_application(): """ Create a application configured to send metrics. Metrics will be sent to localhost:8125 namespaced with ``webapps``. Run netcat or a similar listener then run this example. HTTP GETs will result in a metric like:: webapps.SimpleHandler.GET.204:255.24497032165527...
[ "def", "make_application", "(", ")", ":", "settings", "=", "{", "}", "application", "=", "web", ".", "Application", "(", "[", "web", ".", "url", "(", "'/'", ",", "SimpleHandler", ")", "]", ",", "*", "*", "settings", ")", "statsd", ".", "install", "("...
Create a application configured to send metrics. Metrics will be sent to localhost:8125 namespaced with ``webapps``. Run netcat or a similar listener then run this example. HTTP GETs will result in a metric like:: webapps.SimpleHandler.GET.204:255.24497032165527|ms
[ "Create", "a", "application", "configured", "to", "send", "metrics", "." ]
python
train
33.066667
openstack/networking-arista
networking_arista/ml2/security_groups/switch_helper.py
https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/security_groups/switch_helper.py#L370-L387
def _parse_binding_config(self, binding_config): """Parse configured interface -> ACL bindings Bindings are returned as a set of (intf, name, direction) tuples: set([(intf1, acl_name, direction), (intf2, acl_name, direction), ..., ]) """ parsed_...
[ "def", "_parse_binding_config", "(", "self", ",", "binding_config", ")", ":", "parsed_bindings", "=", "set", "(", ")", "for", "acl", "in", "binding_config", "[", "'aclList'", "]", ":", "for", "intf", "in", "acl", "[", "'configuredIngressIntfs'", "]", ":", "p...
Parse configured interface -> ACL bindings Bindings are returned as a set of (intf, name, direction) tuples: set([(intf1, acl_name, direction), (intf2, acl_name, direction), ..., ])
[ "Parse", "configured", "interface", "-", ">", "ACL", "bindings" ]
python
train
42.333333
google/grr
grr/server/grr_response_server/flows/general/administrative.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/flows/general/administrative.py#L56-L114
def WriteAllCrashDetails(client_id, crash_details, flow_session_id=None, hunt_session_id=None, token=None): """Updates the last crash attribute of the client.""" # AFF4. if data_store.AFF4Enabled(): with aff4.F...
[ "def", "WriteAllCrashDetails", "(", "client_id", ",", "crash_details", ",", "flow_session_id", "=", "None", ",", "hunt_session_id", "=", "None", ",", "token", "=", "None", ")", ":", "# AFF4.", "if", "data_store", ".", "AFF4Enabled", "(", ")", ":", "with", "a...
Updates the last crash attribute of the client.
[ "Updates", "the", "last", "crash", "attribute", "of", "the", "client", "." ]
python
train
35.084746
hanguokai/youku
youku/youku_searches.py
https://github.com/hanguokai/youku/blob/b2df060c7dccfad990bcfa289fff68bb77d1e69b/youku/youku_searches.py#L70-L95
def search_shows_by_keyword(self, keyword, unite=0, source_site=None, category=None, release_year=None, area=None, orderby='view-count', paid=None, hasvideotype=None, page=1, count=20): ...
[ "def", "search_shows_by_keyword", "(", "self", ",", "keyword", ",", "unite", "=", "0", ",", "source_site", "=", "None", ",", "category", "=", "None", ",", "release_year", "=", "None", ",", "area", "=", "None", ",", "orderby", "=", "'view-count'", ",", "p...
doc: http://open.youku.com/docs/doc?id=82
[ "doc", ":", "http", ":", "//", "open", ".", "youku", ".", "com", "/", "docs", "/", "doc?id", "=", "82" ]
python
train
38
algofairness/BlackBoxAuditing
python2_source/BlackBoxAuditing/measurements.py
https://github.com/algofairness/BlackBoxAuditing/blob/b06c4faed5591cd7088475b2a203127bc5820483/python2_source/BlackBoxAuditing/measurements.py#L1-L12
def accuracy(conf_matrix): """ Given a confusion matrix, returns the accuracy. Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml """ total, correct = 0.0, 0.0 for true_response, guess_dict in conf_matrix.items(): for guess, count in guess_dict.items(): if t...
[ "def", "accuracy", "(", "conf_matrix", ")", ":", "total", ",", "correct", "=", "0.0", ",", "0.0", "for", "true_response", ",", "guess_dict", "in", "conf_matrix", ".", "items", "(", ")", ":", "for", "guess", ",", "count", "in", "guess_dict", ".", "items",...
Given a confusion matrix, returns the accuracy. Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml
[ "Given", "a", "confusion", "matrix", "returns", "the", "accuracy", ".", "Accuracy", "Definition", ":", "http", ":", "//", "research", ".", "ics", ".", "aalto", ".", "fi", "/", "events", "/", "eyechallenge2005", "/", "evaluation", ".", "shtml" ]
python
test
33.333333
adafruit/Adafruit_Python_BluefruitLE
Adafruit_BluefruitLE/interfaces/provider.py
https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/interfaces/provider.py#L125-L143
def find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC): """Return the first device that advertises the specified service UUIDs or has the specified name. Will wait up to timeout_sec seconds for the device to be found, and if the timeout is zero then it will not wait at all a...
[ "def", "find_device", "(", "self", ",", "service_uuids", "=", "[", "]", ",", "name", "=", "None", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "start", "=", "time", ".", "time", "(", ")", "while", "True", ":", "# Call find_devices and grab the first res...
Return the first device that advertises the specified service UUIDs or has the specified name. Will wait up to timeout_sec seconds for the device to be found, and if the timeout is zero then it will not wait at all and immediately return a result. When no device is found a value of None is ...
[ "Return", "the", "first", "device", "that", "advertises", "the", "specified", "service", "UUIDs", "or", "has", "the", "specified", "name", ".", "Will", "wait", "up", "to", "timeout_sec", "seconds", "for", "the", "device", "to", "be", "found", "and", "if", ...
python
valid
49.052632
trailofbits/manticore
manticore/core/smtlib/solver.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L242-L256
def _reset(self, constraints=None): """Auxiliary method to reset the smtlib external solver to initial defaults""" if self._proc is None: self._start_proc() else: if self.support_reset: self._send("(reset)") for cfg in self._init: ...
[ "def", "_reset", "(", "self", ",", "constraints", "=", "None", ")", ":", "if", "self", ".", "_proc", "is", "None", ":", "self", ".", "_start_proc", "(", ")", "else", ":", "if", "self", ".", "support_reset", ":", "self", ".", "_send", "(", "\"(reset)\...
Auxiliary method to reset the smtlib external solver to initial defaults
[ "Auxiliary", "method", "to", "reset", "the", "smtlib", "external", "solver", "to", "initial", "defaults" ]
python
valid
32.8
manahl/arctic
arctic/store/bson_store.py
https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/store/bson_store.py#L112-L117
def update_one(self, filter, update, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one """ self._arctic_lib.check_quota() return self._collection.update_one(filter, update, **kwargs)
[ "def", "update_one", "(", "self", ",", "filter", ",", "update", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_arctic_lib", ".", "check_quota", "(", ")", "return", "self", ".", "_collection", ".", "update_one", "(", "filter", ",", "update", ",", "*"...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one
[ "See", "http", ":", "//", "api", ".", "mongodb", ".", "com", "/", "python", "/", "current", "/", "api", "/", "pymongo", "/", "collection", ".", "html#pymongo", ".", "collection", ".", "Collection", ".", "update_one" ]
python
train
48.833333
klen/graphite-beacon
graphite_beacon/alerts.py
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L259-L285
def load(self): """Load data from Graphite.""" LOGGER.debug('%s: start checking: %s', self.name, self.query) if self.waiting: self.notify('warning', 'Process takes too much time', target='waiting', ntype='common') else: self.waiting = True try: ...
[ "def", "load", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'%s: start checking: %s'", ",", "self", ".", "name", ",", "self", ".", "query", ")", "if", "self", ".", "waiting", ":", "self", ".", "notify", "(", "'warning'", ",", "'Process takes too ...
Load data from Graphite.
[ "Load", "data", "from", "Graphite", "." ]
python
train
53.851852
PBR/MQ2
MQ2/__init__.py
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/__init__.py#L140-L161
def write_matrix(outputfile, matrix): """ Write down the provided matrix in the specified outputfile. :arg outputfile, name of the outputfile in which the QTLs found are written. :arg matrix, the list of lists of data to write. """ try: stream = open(outputfile, 'w') for row...
[ "def", "write_matrix", "(", "outputfile", ",", "matrix", ")", ":", "try", ":", "stream", "=", "open", "(", "outputfile", ",", "'w'", ")", "for", "row", "in", "matrix", ":", "if", "isinstance", "(", "row", ",", "list", ")", "or", "isinstance", "(", "r...
Write down the provided matrix in the specified outputfile. :arg outputfile, name of the outputfile in which the QTLs found are written. :arg matrix, the list of lists of data to write.
[ "Write", "down", "the", "provided", "matrix", "in", "the", "specified", "outputfile", ".", ":", "arg", "outputfile", "name", "of", "the", "outputfile", "in", "which", "the", "QTLs", "found", "are", "written", ".", ":", "arg", "matrix", "the", "list", "of",...
python
train
36.454545
decryptus/sonicprobe
sonicprobe/libs/urisup.py
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/urisup.py#L278-L311
def host_type(host): """ Correctly classify correct RFC 3986 compliant hostnames, but do not try hard to validate compliance anyway... NOTE: indeed we allow a small deviation from the RFC 3986: IPv4 addresses are allowed to contain bytes represented in hexadecimal or octal notation when begining...
[ "def", "host_type", "(", "host", ")", ":", "if", "not", "host", ":", "return", "HOST_REG_NAME", "elif", "host", "[", "0", "]", "==", "'['", ":", "return", "HOST_IP_LITERAL", "elif", "__valid_IPv4address", "(", "host", ")", ":", "return", "HOST_IPV4_ADDRESS",...
Correctly classify correct RFC 3986 compliant hostnames, but do not try hard to validate compliance anyway... NOTE: indeed we allow a small deviation from the RFC 3986: IPv4 addresses are allowed to contain bytes represented in hexadecimal or octal notation when begining respectively with '0x'/'0X' and ...
[ "Correctly", "classify", "correct", "RFC", "3986", "compliant", "hostnames", "but", "do", "not", "try", "hard", "to", "validate", "compliance", "anyway", "...", "NOTE", ":", "indeed", "we", "allow", "a", "small", "deviation", "from", "the", "RFC", "3986", ":...
python
train
30.117647
mongodb/mongo-python-driver
pymongo/change_stream.py
https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/change_stream.py#L226-L283
def try_next(self): """Advance the cursor without blocking indefinitely. This method returns the next change document without waiting indefinitely for the next change. For example:: with db.collection.watch() as stream: while stream.alive: change...
[ "def", "try_next", "(", "self", ")", ":", "# Attempt to get the next change with at most one getMore and at most", "# one resume attempt.", "try", ":", "change", "=", "self", ".", "_cursor", ".", "_try_next", "(", "True", ")", "except", "ConnectionFailure", ":", "self",...
Advance the cursor without blocking indefinitely. This method returns the next change document without waiting indefinitely for the next change. For example:: with db.collection.watch() as stream: while stream.alive: change = stream.try_next() ...
[ "Advance", "the", "cursor", "without", "blocking", "indefinitely", "." ]
python
train
38.293103
dictatorlib/dictator
dictator/__init__.py
https://github.com/dictatorlib/dictator/blob/b77b1709b6fff174f13b0f0c5dbe740b4c07d712/dictator/__init__.py#L208-L235
def get(self, key, default=None): """Return the value at key ``key``, or default value ``default`` which is None by default. >>> dc = Dictator() >>> dc['l0'] = [1, 2, 3, 4] >>> dc.get('l0') ['1', '2', '3', '4'] >>> dc['l0'] ['1', '2', '3', '4'] >>...
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "value", "=", "self", ".", "__getitem__", "(", "key", ")", "except", "KeyError", ":", "value", "=", "None", "# Py3 Redis compatibiility", "if", "isinstance", "(", ...
Return the value at key ``key``, or default value ``default`` which is None by default. >>> dc = Dictator() >>> dc['l0'] = [1, 2, 3, 4] >>> dc.get('l0') ['1', '2', '3', '4'] >>> dc['l0'] ['1', '2', '3', '4'] >>> dc.clear() :param key: key of valu...
[ "Return", "the", "value", "at", "key", "key", "or", "default", "value", "default", "which", "is", "None", "by", "default", "." ]
python
train
28.071429
andrea-cuttone/geoplotlib
geoplotlib/colors.py
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/colors.py#L25-L62
def to_color(self, value, maxvalue, scale, minvalue=0.0): """ convert continuous values into colors using matplotlib colorscales :param value: value to be converted :param maxvalue: max value in the colorscale :param scale: lin, log, sqrt :param minvalue: minimum of the i...
[ "def", "to_color", "(", "self", ",", "value", ",", "maxvalue", ",", "scale", ",", "minvalue", "=", "0.0", ")", ":", "if", "scale", "==", "'lin'", ":", "if", "minvalue", ">=", "maxvalue", ":", "raise", "Exception", "(", "'minvalue must be less than maxvalue'"...
convert continuous values into colors using matplotlib colorscales :param value: value to be converted :param maxvalue: max value in the colorscale :param scale: lin, log, sqrt :param minvalue: minimum of the input values in linear scale (default is 0) :return: the color correspo...
[ "convert", "continuous", "values", "into", "colors", "using", "matplotlib", "colorscales", ":", "param", "value", ":", "value", "to", "be", "converted", ":", "param", "maxvalue", ":", "max", "value", "in", "the", "colorscale", ":", "param", "scale", ":", "li...
python
train
38.526316
Fantomas42/django-blog-zinnia
zinnia/xmlrpc/metaweblog.py
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/xmlrpc/metaweblog.py#L82-L89
def author_structure(user): """ An author structure. """ return {'user_id': user.pk, 'user_login': user.get_username(), 'display_name': user.__str__(), 'user_email': user.email}
[ "def", "author_structure", "(", "user", ")", ":", "return", "{", "'user_id'", ":", "user", ".", "pk", ",", "'user_login'", ":", "user", ".", "get_username", "(", ")", ",", "'display_name'", ":", "user", ".", "__str__", "(", ")", ",", "'user_email'", ":",...
An author structure.
[ "An", "author", "structure", "." ]
python
train
27.75
databio/pypiper
pypiper/ngstk.py
https://github.com/databio/pypiper/blob/00e6c2b94033c4187d47ff14c5580bbfc2ff097f/pypiper/ngstk.py#L129-L142
def check_command(self, command): """ Check if command can be called. """ # Use `command` to see if command is callable, store exit code code = os.system("command -v {0} >/dev/null 2>&1 || {{ exit 1; }}".format(command)) # If exit code is not 0, report which command fai...
[ "def", "check_command", "(", "self", ",", "command", ")", ":", "# Use `command` to see if command is callable, store exit code", "code", "=", "os", ".", "system", "(", "\"command -v {0} >/dev/null 2>&1 || {{ exit 1; }}\"", ".", "format", "(", "command", ")", ")", "# If ex...
Check if command can be called.
[ "Check", "if", "command", "can", "be", "called", "." ]
python
train
35.428571
GPflow/GPflow
gpflow/training/monitor.py
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/training/monitor.py#L435-L441
def print_summary(self) -> None: """ Prints the tasks' timing summary. """ print("Tasks execution time summary:") for mon_task in self._monitor_tasks: print("%s:\t%.4f (sec)" % (mon_task.task_name, mon_task.total_time))
[ "def", "print_summary", "(", "self", ")", "->", "None", ":", "print", "(", "\"Tasks execution time summary:\"", ")", "for", "mon_task", "in", "self", ".", "_monitor_tasks", ":", "print", "(", "\"%s:\\t%.4f (sec)\"", "%", "(", "mon_task", ".", "task_name", ",", ...
Prints the tasks' timing summary.
[ "Prints", "the", "tasks", "timing", "summary", "." ]
python
train
37.857143
google/grr
grr/proto/setup.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/proto/setup.py#L53-L63
def compile_protos(): """Builds necessary assets from sources.""" # If there's no makefile, we're likely installing from an sdist, # so there's no need to compile the protos (they should be already # compiled). if not os.path.exists(os.path.join(THIS_DIRECTORY, "makefile.py")): return # Only compile pr...
[ "def", "compile_protos", "(", ")", ":", "# If there's no makefile, we're likely installing from an sdist,", "# so there's no need to compile the protos (they should be already", "# compiled).", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join"...
Builds necessary assets from sources.
[ "Builds", "necessary", "assets", "from", "sources", "." ]
python
train
39.909091
neurodata/ndio
ndio/remote/resources.py
https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/remote/resources.py#L240-L264
def delete_token(self, token_name, project_name, dataset_name): """ Delete a token with the given parameters. Arguments: project_name (str): Project name dataset_name (str): Dataset name project is based on ...
[ "def", "delete_token", "(", "self", ",", "token_name", ",", "project_name", ",", "dataset_name", ")", ":", "url", "=", "self", ".", "url", "(", ")", "+", "\"/nd/resource/dataset/{}\"", ".", "format", "(", "dataset_name", ")", "+", "\"/project/{}\"", ".", "fo...
Delete a token with the given parameters. Arguments: project_name (str): Project name dataset_name (str): Dataset name project is based on token_name (str): Token name channel_name (str): Channel name project is based on Returns: bool: True if ...
[ "Delete", "a", "token", "with", "the", "given", "parameters", ".", "Arguments", ":", "project_name", "(", "str", ")", ":", "Project", "name", "dataset_name", "(", "str", ")", ":", "Dataset", "name", "project", "is", "based", "on", "token_name", "(", "str",...
python
test
37.88
openshift/openshift-restclient-python
openshift/dynamic/client.py
https://github.com/openshift/openshift-restclient-python/blob/5d86bf5ba4e723bcc4d33ad47077aca01edca0f6/openshift/dynamic/client.py#L179-L217
def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None): """ Stream events for a resource from the Kubernetes API :param resource: The API resource object that will be used to query the API :param namespace: The...
[ "def", "watch", "(", "self", ",", "resource", ",", "namespace", "=", "None", ",", "name", "=", "None", ",", "label_selector", "=", "None", ",", "field_selector", "=", "None", ",", "resource_version", "=", "None", ",", "timeout", "=", "None", ")", ":", ...
Stream events for a resource from the Kubernetes API :param resource: The API resource object that will be used to query the API :param namespace: The namespace to query :param name: The name of the resource instance to query :param label_selector: The label selector with which to filte...
[ "Stream", "events", "for", "a", "resource", "from", "the", "Kubernetes", "API" ]
python
train
47.179487
slackapi/python-slackclient
slack/rtm/client.py
https://github.com/slackapi/python-slackclient/blob/901341c0284fd81e6d2719d6a0502308760d83e4/slack/rtm/client.py#L309-L357
async def _connect_and_read(self): """Retreives and connects to Slack's RTM API. Makes an authenticated call to Slack's RTM API to retrieve a websocket URL. Then connects to the message server and reads event messages as they come in. If 'auto_reconnect' is specified we ...
[ "async", "def", "_connect_and_read", "(", "self", ")", ":", "while", "not", "self", ".", "_stopped", ":", "try", ":", "self", ".", "_connection_attempts", "+=", "1", "async", "with", "aiohttp", ".", "ClientSession", "(", "loop", "=", "self", ".", "_event_l...
Retreives and connects to Slack's RTM API. Makes an authenticated call to Slack's RTM API to retrieve a websocket URL. Then connects to the message server and reads event messages as they come in. If 'auto_reconnect' is specified we retrieve a new url and reconnect any time the...
[ "Retreives", "and", "connects", "to", "Slack", "s", "RTM", "API", "." ]
python
train
44.326531
odlgroup/odl
odl/operator/pspace_ops.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L389-L435
def adjoint(self): """Adjoint of this operator. The adjoint is given by taking the transpose of the matrix and the adjoint of each component operator. In weighted product spaces, the adjoint needs to take the weightings into account. This is currently not supported. Re...
[ "def", "adjoint", "(", "self", ")", ":", "# Lazy import to improve `import odl` time", "import", "scipy", ".", "sparse", "adjoint_ops", "=", "[", "op", ".", "adjoint", "for", "op", "in", "self", ".", "ops", ".", "data", "]", "data", "=", "np", ".", "empty"...
Adjoint of this operator. The adjoint is given by taking the transpose of the matrix and the adjoint of each component operator. In weighted product spaces, the adjoint needs to take the weightings into account. This is currently not supported. Returns ------- ...
[ "Adjoint", "of", "this", "operator", "." ]
python
train
32.829787
christophertbrown/bioscripts
ctbBio/rRNA_copies.py
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/rRNA_copies.py#L102-L160
def copies(mapping, s2bins, rna, min_rna = 800, mismatches = 0): """ 1. determine bin coverage 2. determine rRNA gene coverage 3. compare """ cov = {} # cov[scaffold] = [bases, length] s2bins, bins2s = parse_s2bins(s2bins) rna_cov = parse_rna(rna, s2bins, min_rna) s2bins, bins2s = fi...
[ "def", "copies", "(", "mapping", ",", "s2bins", ",", "rna", ",", "min_rna", "=", "800", ",", "mismatches", "=", "0", ")", ":", "cov", "=", "{", "}", "# cov[scaffold] = [bases, length]", "s2bins", ",", "bins2s", "=", "parse_s2bins", "(", "s2bins", ")", "r...
1. determine bin coverage 2. determine rRNA gene coverage 3. compare
[ "1", ".", "determine", "bin", "coverage", "2", ".", "determine", "rRNA", "gene", "coverage", "3", ".", "compare" ]
python
train
38.949153
hobson/pug-dj
pug/dj/explore.py
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L421-L461
def index_with_dupes(values_list, unique_together=2, model_number_i=0, serial_number_i=1, verbosity=1): '''Create dict from values_list with first N values as a compound key. Default N (number of columns assumbed to be "unique_together") is 2. >>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == (...
[ "def", "index_with_dupes", "(", "values_list", ",", "unique_together", "=", "2", ",", "model_number_i", "=", "0", ",", "serial_number_i", "=", "1", ",", "verbosity", "=", "1", ")", ":", "try", ":", "N", "=", "values_list", ".", "count", "(", ")", "except...
Create dict from values_list with first N values as a compound key. Default N (number of columns assumbed to be "unique_together") is 2. >>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == ({(1, 2): (1, 2, 3), (2, 1): (2, 1, 3), (5, 6): (5, 6, 7)}, {(5, 6): [(5, 6, 7), (5, 6, 8)]}) True
[ "Create", "dict", "from", "values_list", "with", "first", "N", "values", "as", "a", "compound", "key", "." ]
python
train
49.463415
mixcloud/django-experiments
experiments/templatetags/experiments.py
https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/templatetags/experiments.py#L80-L101
def experiment(parser, token): """ Split Testing experiment tag has the following syntax : {% experiment <experiment_name> <alternative> %} experiment content goes here {% endexperiment %} If the alternative name is neither 'test' nor 'control' an exception is raised during render...
[ "def", "experiment", "(", "parser", ",", "token", ")", ":", "try", ":", "token_contents", "=", "token", ".", "split_contents", "(", ")", "experiment_name", ",", "alternative", ",", "weight", ",", "user_variable", "=", "_parse_token_contents", "(", "token_content...
Split Testing experiment tag has the following syntax : {% experiment <experiment_name> <alternative> %} experiment content goes here {% endexperiment %} If the alternative name is neither 'test' nor 'control' an exception is raised during rendering.
[ "Split", "Testing", "experiment", "tag", "has", "the", "following", "syntax", ":", "{", "%", "experiment", "<experiment_name", ">", "<alternative", ">", "%", "}", "experiment", "content", "goes", "here", "{", "%", "endexperiment", "%", "}", "If", "the", "alt...
python
train
37.727273
MisterWil/abodepy
abodepy/devices/alarm.py
https://github.com/MisterWil/abodepy/blob/6f84bb428fd1da98855f55083cd427bebbcc57ae/abodepy/devices/alarm.py#L33-L60
def set_mode(self, mode): """Set Abode alarm mode.""" if not mode: raise AbodeException(ERROR.MISSING_ALARM_MODE) elif mode.lower() not in CONST.ALL_MODES: raise AbodeException(ERROR.INVALID_ALARM_MODE, CONST.ALL_MODES) mode = mode.lower() response = sel...
[ "def", "set_mode", "(", "self", ",", "mode", ")", ":", "if", "not", "mode", ":", "raise", "AbodeException", "(", "ERROR", ".", "MISSING_ALARM_MODE", ")", "elif", "mode", ".", "lower", "(", ")", "not", "in", "CONST", ".", "ALL_MODES", ":", "raise", "Abo...
Set Abode alarm mode.
[ "Set", "Abode", "alarm", "mode", "." ]
python
train
32.714286
cozy/python_cozy_management
cozy_management/ssl.py
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L120-L155
def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE): ''' Sign certificate with acme_tiny for let's encrypt ''' private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name) certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name) certificate_request_path = '{}/...
[ "def", "acme_sign_certificate", "(", "common_name", ",", "size", "=", "DEFAULT_KEY_SIZE", ")", ":", "private_key_path", "=", "'{}/{}.key'", ".", "format", "(", "CERTIFICATES_PATH", ",", "common_name", ")", "certificate_path", "=", "'{}/{}.crt'", ".", "format", "(", ...
Sign certificate with acme_tiny for let's encrypt
[ "Sign", "certificate", "with", "acme_tiny", "for", "let", "s", "encrypt" ]
python
train
39.75
timeyyy/apptools
peasoup/pidutil.py
https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/pidutil.py#L66-L75
def move_active_window(x, y): """ Moves the active window to a given position given the window_id and absolute co ordinates, --sync option auto passed in, will wait until actually moved before giving control back to us will do nothing if the window is maximized """ window_id = get_window_id() ...
[ "def", "move_active_window", "(", "x", ",", "y", ")", ":", "window_id", "=", "get_window_id", "(", ")", "cmd", "=", "[", "'xdotool'", ",", "'windowmove'", ",", "window_id", ",", "str", "(", "x", ")", ",", "str", "(", "y", ")", "]", "subprocess", ".",...
Moves the active window to a given position given the window_id and absolute co ordinates, --sync option auto passed in, will wait until actually moved before giving control back to us will do nothing if the window is maximized
[ "Moves", "the", "active", "window", "to", "a", "given", "position", "given", "the", "window_id", "and", "absolute", "co", "ordinates", "--", "sync", "option", "auto", "passed", "in", "will", "wait", "until", "actually", "moved", "before", "giving", "control", ...
python
train
46.1
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L285-L287
def _eq(self, other): """Compare two nodes for equality.""" return (self.type, self.children) == (other.type, other.children)
[ "def", "_eq", "(", "self", ",", "other", ")", ":", "return", "(", "self", ".", "type", ",", "self", ".", "children", ")", "==", "(", "other", ".", "type", ",", "other", ".", "children", ")" ]
Compare two nodes for equality.
[ "Compare", "two", "nodes", "for", "equality", "." ]
python
train
46.333333
Qiskit/qiskit-terra
qiskit/quantum_info/operators/channel/transformations.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L75-L86
def _to_chi(rep, data, input_dim, output_dim): """Transform a QuantumChannel to the Chi representation.""" if rep == 'Chi': return data # Check valid n-qubit input _check_nqubit_dim(input_dim, output_dim) if rep == 'Operator': return _from_operator('Chi', data, input_dim, output_dim)...
[ "def", "_to_chi", "(", "rep", ",", "data", ",", "input_dim", ",", "output_dim", ")", ":", "if", "rep", "==", "'Chi'", ":", "return", "data", "# Check valid n-qubit input", "_check_nqubit_dim", "(", "input_dim", ",", "output_dim", ")", "if", "rep", "==", "'Op...
Transform a QuantumChannel to the Chi representation.
[ "Transform", "a", "QuantumChannel", "to", "the", "Chi", "representation", "." ]
python
test
40
Grunny/zap-cli
zapcli/commands/session.py
https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/session.py#L34-L37
def save_session(zap_helper, file_path): """Save the session.""" console.debug('Saving the session to "{0}"'.format(file_path)) zap_helper.zap.core.save_session(file_path, overwrite='true')
[ "def", "save_session", "(", "zap_helper", ",", "file_path", ")", ":", "console", ".", "debug", "(", "'Saving the session to \"{0}\"'", ".", "format", "(", "file_path", ")", ")", "zap_helper", ".", "zap", ".", "core", ".", "save_session", "(", "file_path", ",",...
Save the session.
[ "Save", "the", "session", "." ]
python
train
49.5
Cognexa/cxflow
cxflow/utils/download.py
https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/download.py#L9-L25
def sanitize_url(url: str) -> str: """ Sanitize the given url so that it can be used as a valid filename. :param url: url to create filename from :raise ValueError: when the given url can not be sanitized :return: created filename """ for part in reversed(url.split('/')): filename ...
[ "def", "sanitize_url", "(", "url", ":", "str", ")", "->", "str", ":", "for", "part", "in", "reversed", "(", "url", ".", "split", "(", "'/'", ")", ")", ":", "filename", "=", "re", ".", "sub", "(", "r'[^a-zA-Z0-9_.\\-]'", ",", "''", ",", "part", ")",...
Sanitize the given url so that it can be used as a valid filename. :param url: url to create filename from :raise ValueError: when the given url can not be sanitized :return: created filename
[ "Sanitize", "the", "given", "url", "so", "that", "it", "can", "be", "used", "as", "a", "valid", "filename", "." ]
python
train
29.941176
kakwa/ldapcherry
ldapcherry/cli.py
https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/cli.py#L19-L102
def start(configfile=None, daemonize=False, environment=None, fastcgi=False, scgi=False, pidfile=None, cgi=False, debug=False): """Subscribe all engine plugins and start the engine.""" sys.path = [''] + sys.path # monkey patching cherrypy to disable config interpolation def new_as_d...
[ "def", "start", "(", "configfile", "=", "None", ",", "daemonize", "=", "False", ",", "environment", "=", "None", ",", "fastcgi", "=", "False", ",", "scgi", "=", "False", ",", "pidfile", "=", "None", ",", "cgi", "=", "False", ",", "debug", "=", "False...
Subscribe all engine plugins and start the engine.
[ "Subscribe", "all", "engine", "plugins", "and", "start", "the", "engine", "." ]
python
train
37.595238
sernst/cauldron
cauldron/session/writing/components/definitions.py
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/components/definitions.py#L61-L84
def combine_lists_reducer( key: str, merged_list: list, component: COMPONENT ) -> list: """ Reducer function to combine the lists for the specified key into a single, flat list :param key: The key on the COMPONENT instances to operate upon :param merged_list: ...
[ "def", "combine_lists_reducer", "(", "key", ":", "str", ",", "merged_list", ":", "list", ",", "component", ":", "COMPONENT", ")", "->", "list", ":", "merged_list", ".", "extend", "(", "getattr", "(", "component", ",", "key", ")", ")", "return", "merged_lis...
Reducer function to combine the lists for the specified key into a single, flat list :param key: The key on the COMPONENT instances to operate upon :param merged_list: The accumulated list of values populated by previous calls to this reducer function :param component: T...
[ "Reducer", "function", "to", "combine", "the", "lists", "for", "the", "specified", "key", "into", "a", "single", "flat", "list" ]
python
train
28.25
ray-project/ray
python/ray/experimental/state.py
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/state.py#L598-L687
def chrome_tracing_object_transfer_dump(self, filename=None): """Return a list of transfer events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing ...
[ "def", "chrome_tracing_object_transfer_dump", "(", "self", ",", "filename", "=", "None", ")", ":", "client_id_to_address", "=", "{", "}", "for", "client_info", "in", "ray", ".", "global_state", ".", "client_table", "(", ")", ":", "client_id_to_address", "[", "cl...
Return a list of transfer events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing in the Chrome web browser and load the dumped file. Make sure to ...
[ "Return", "a", "list", "of", "transfer", "events", "that", "can", "viewed", "as", "a", "timeline", "." ]
python
train
44.577778
sbg/sevenbridges-python
sevenbridges/meta/resource.py
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/meta/resource.py#L143-L158
def get(cls, id, api=None): """ Fetches the resource from the server. :param id: Resource identifier :param api: sevenbridges Api instance. :return: Resource object. """ id = Transform.to_resource(id) api = api if api else cls._API if 'get' in cls....
[ "def", "get", "(", "cls", ",", "id", ",", "api", "=", "None", ")", ":", "id", "=", "Transform", ".", "to_resource", "(", "id", ")", "api", "=", "api", "if", "api", "else", "cls", ".", "_API", "if", "'get'", "in", "cls", ".", "_URL", ":", "extra...
Fetches the resource from the server. :param id: Resource identifier :param api: sevenbridges Api instance. :return: Resource object.
[ "Fetches", "the", "resource", "from", "the", "server", ".", ":", "param", "id", ":", "Resource", "identifier", ":", "param", "api", ":", "sevenbridges", "Api", "instance", ".", ":", "return", ":", "Resource", "object", "." ]
python
train
39.875
bwengals/ccsnmultivar
ccsnmultivar/designmatrix.py
https://github.com/bwengals/ccsnmultivar/blob/dbadf52e728e0ce922cbc147864e693c2c2d305c/ccsnmultivar/designmatrix.py#L97-L203
def make_encoder(self,formula_dict,inter_list,param_dict): """ make the encoder function """ X_dict = {} Xcol_dict = {} encoder_dict = {} # first, replace param_dict[key] = values, with param_dict[key] = dmatrix for key in formula_dict: encodin...
[ "def", "make_encoder", "(", "self", ",", "formula_dict", ",", "inter_list", ",", "param_dict", ")", ":", "X_dict", "=", "{", "}", "Xcol_dict", "=", "{", "}", "encoder_dict", "=", "{", "}", "# first, replace param_dict[key] = values, with param_dict[key] = dmatrix", ...
make the encoder function
[ "make", "the", "encoder", "function" ]
python
train
46.345794
fastai/fastai
fastai/text/learner.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L269-L284
def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, pad_idx:int=1) -> nn.Module: "Create a text classifier from `arch` and it...
[ "def", "get_text_classifier", "(", "arch", ":", "Callable", ",", "vocab_sz", ":", "int", ",", "n_class", ":", "int", ",", "bptt", ":", "int", "=", "70", ",", "max_len", ":", "int", "=", "20", "*", "70", ",", "config", ":", "dict", "=", "None", ",",...
Create a text classifier from `arch` and its `config`, maybe `pretrained`.
[ "Create", "a", "text", "classifier", "from", "arch", "and", "its", "config", "maybe", "pretrained", "." ]
python
train
60.8125
SkyLothar/requests-aliyun
aliyunauth/sign_ver_1_0.py
https://github.com/SkyLothar/requests-aliyun/blob/43f6646dcf7f09691ae997b09d365ad9e76386cf/aliyunauth/sign_ver_1_0.py#L82-L100
def sign(self, method, params): """Calculate signature with the SIG_METHOD(HMAC-SHA1) Returns a base64 encoeded string of the hex signature :param method: the http verb :param params: the params needs calculate """ query_str = utils.percent_encode(params.items(), True) ...
[ "def", "sign", "(", "self", ",", "method", ",", "params", ")", ":", "query_str", "=", "utils", ".", "percent_encode", "(", "params", ".", "items", "(", ")", ",", "True", ")", "str_to_sign", "=", "\"{0}&%2F&{1}\"", ".", "format", "(", "method", ",", "ut...
Calculate signature with the SIG_METHOD(HMAC-SHA1) Returns a base64 encoeded string of the hex signature :param method: the http verb :param params: the params needs calculate
[ "Calculate", "signature", "with", "the", "SIG_METHOD", "(", "HMAC", "-", "SHA1", ")", "Returns", "a", "base64", "encoeded", "string", "of", "the", "hex", "signature" ]
python
train
31.842105
freelancer/freelancer-sdk-python
freelancersdk/resources/projects/projects.py
https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L255-L275
def get_bids(session, project_ids=[], bid_ids=[], limit=10, offset=0): """ Get the list of bids """ get_bids_data = {} if bid_ids: get_bids_data['bids[]'] = bid_ids if project_ids: get_bids_data['projects[]'] = project_ids get_bids_data['limit'] = limit get_bids_data['off...
[ "def", "get_bids", "(", "session", ",", "project_ids", "=", "[", "]", ",", "bid_ids", "=", "[", "]", ",", "limit", "=", "10", ",", "offset", "=", "0", ")", ":", "get_bids_data", "=", "{", "}", "if", "bid_ids", ":", "get_bids_data", "[", "'bids[]'", ...
Get the list of bids
[ "Get", "the", "list", "of", "bids" ]
python
valid
33.761905
etesync/radicale_storage_etesync
radicale_storage_etesync/__init__.py
https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L505-L536
def acquire_lock(cls, mode, user=None): """Set a context manager to lock the whole storage. ``mode`` must either be "r" for shared access or "w" for exclusive access. ``user`` is the name of the logged in user or empty. """ if not user: return with...
[ "def", "acquire_lock", "(", "cls", ",", "mode", ",", "user", "=", "None", ")", ":", "if", "not", "user", ":", "return", "with", "EteSyncCache", ".", "lock", ":", "cls", ".", "user", "=", "user", "cls", ".", "etesync", "=", "cls", ".", "_get_etesync_f...
Set a context manager to lock the whole storage. ``mode`` must either be "r" for shared access or "w" for exclusive access. ``user`` is the name of the logged in user or empty.
[ "Set", "a", "context", "manager", "to", "lock", "the", "whole", "storage", "." ]
python
train
32.5
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L472-L532
def get_next_invalid_time_from_t(self, timestamp): # pylint: disable=too-many-branches """ Get the next invalid time :param timestamp: timestamp in seconds (of course) :type timestamp: int or float :return: timestamp of next invalid time :rtype: int or float ...
[ "def", "get_next_invalid_time_from_t", "(", "self", ",", "timestamp", ")", ":", "# pylint: disable=too-many-branches", "timestamp", "=", "int", "(", "timestamp", ")", "original_t", "=", "timestamp", "dr_mins", "=", "[", "]", "for", "daterange", "in", "self", ".", ...
Get the next invalid time :param timestamp: timestamp in seconds (of course) :type timestamp: int or float :return: timestamp of next invalid time :rtype: int or float
[ "Get", "the", "next", "invalid", "time" ]
python
train
37.04918
CivicSpleen/ambry
ambry/etl/pipeline.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L2097-L2104
def _subset(self, subset): """Return a new pipeline with a subset of the sections""" pl = Pipeline(bundle=self.bundle) for group_name, pl_segment in iteritems(self): if group_name not in subset: continue pl[group_name] = pl_segment return pl
[ "def", "_subset", "(", "self", ",", "subset", ")", ":", "pl", "=", "Pipeline", "(", "bundle", "=", "self", ".", "bundle", ")", "for", "group_name", ",", "pl_segment", "in", "iteritems", "(", "self", ")", ":", "if", "group_name", "not", "in", "subset", ...
Return a new pipeline with a subset of the sections
[ "Return", "a", "new", "pipeline", "with", "a", "subset", "of", "the", "sections" ]
python
train
38.25
chemlab/chemlab
chemlab/mviewer/representations/ballandstick.py
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/representations/ballandstick.py#L279-L310
def hide(self, selections): '''Hide objects in this representation. BallAndStickRepresentation support selections of atoms and bonds. To hide the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import Selection represent...
[ "def", "hide", "(", "self", ",", "selections", ")", ":", "if", "'atoms'", "in", "selections", ":", "self", ".", "hidden_state", "[", "'atoms'", "]", "=", "selections", "[", "'atoms'", "]", "self", ".", "on_atom_hidden_changed", "(", ")", "if", "'bonds'", ...
Hide objects in this representation. BallAndStickRepresentation support selections of atoms and bonds. To hide the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import Selection representation.hide({'atoms': Selection([0], sys...
[ "Hide", "objects", "in", "this", "representation", ".", "BallAndStickRepresentation", "support", "selections", "of", "atoms", "and", "bonds", "." ]
python
train
37.96875
titusjan/argos
argos/repo/rtiplugins/ncdf.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/ncdf.py#L70-L84
def variableMissingValue(ncVar): """ Returns the missingData given a NetCDF variable Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. """ attributes = ncVarAttributes(ncVar) if not attribute...
[ "def", "variableMissingValue", "(", "ncVar", ")", ":", "attributes", "=", "ncVarAttributes", "(", "ncVar", ")", "if", "not", "attributes", ":", "return", "None", "# a premature optimization :-)", "for", "key", "in", "(", "'missing_value'", ",", "'MissingValue'", "...
Returns the missingData given a NetCDF variable Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found.
[ "Returns", "the", "missingData", "given", "a", "NetCDF", "variable" ]
python
train
38.8
denisenkom/pytds
src/pytds/tds.py
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L577-L594
def process_cancel(self): """ Process the incoming token stream until it finds an end token DONE with the cancel flag set. At that point the connection should be ready to handle a new query. In case when no cancel request is pending this function does nothing. """ ...
[ "def", "process_cancel", "(", "self", ")", ":", "self", ".", "log_response_message", "(", "'got CANCEL message'", ")", "# silly cases, nothing to do", "if", "not", "self", ".", "in_cancel", ":", "return", "while", "True", ":", "token_id", "=", "self", ".", "get_...
Process the incoming token stream until it finds an end token DONE with the cancel flag set. At that point the connection should be ready to handle a new query. In case when no cancel request is pending this function does nothing.
[ "Process", "the", "incoming", "token", "stream", "until", "it", "finds", "an", "end", "token", "DONE", "with", "the", "cancel", "flag", "set", ".", "At", "that", "point", "the", "connection", "should", "be", "ready", "to", "handle", "a", "new", "query", ...
python
train
33.444444
CTPUG/wafer
wafer/kv/utils.py
https://github.com/CTPUG/wafer/blob/a20af3c399267f76373dc342f4d542a9bc457c35/wafer/kv/utils.py#L5-L16
def deserialize_by_field(value, field): """ Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them """ if isinstance(field, forms.DateTimeField): value = parse_datetime(value) elif isinstance(field, forms.DateField): value ...
[ "def", "deserialize_by_field", "(", "value", ",", "field", ")", ":", "if", "isinstance", "(", "field", ",", "forms", ".", "DateTimeField", ")", ":", "value", "=", "parse_datetime", "(", "value", ")", "elif", "isinstance", "(", "field", ",", "forms", ".", ...
Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them
[ "Some", "types", "get", "serialized", "to", "JSON", "as", "strings", ".", "If", "we", "know", "what", "they", "are", "supposed", "to", "be", "we", "can", "deserialize", "them" ]
python
train
35.333333
penguinmenac3/starttf
starttf/data/autorecords.py
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/data/autorecords.py#L264-L300
def write_data(hyper_params, mode, sequence, num_threads): """ Write a tf record containing a feature dict and a label dict. :param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}} :param mode: The mode sp...
[ "def", "write_data", "(", "hyper_params", ",", "mode", ",", "sequence", ",", "num_threads", ")", ":", "if", "not", "isinstance", "(", "sequence", ",", "Sequence", ")", "and", "not", "(", "callable", "(", "getattr", "(", "sequence", ",", "\"__getitem__\"", ...
Write a tf record containing a feature dict and a label dict. :param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}} :param mode: The mode specifies the purpose of the data. Typically it is either "train" or "validation". :param sequence: A tf.keras.uti...
[ "Write", "a", "tf", "record", "containing", "a", "feature", "dict", "and", "a", "label", "dict", "." ]
python
train
48.756757
ambitioninc/rabbitmq-admin
rabbitmq_admin/base.py
https://github.com/ambitioninc/rabbitmq-admin/blob/ff65054115f19991da153f0e4f4e45e526545fea/rabbitmq_admin/base.py#L62-L73
def _api_put(self, url, **kwargs): """ A convenience wrapper for _put. Adds headers, auth and base url by default """ kwargs['url'] = self.url + url kwargs['auth'] = self.auth headers = deepcopy(self.headers) headers.update(kwargs.get('headers', {})) ...
[ "def", "_api_put", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'url'", "]", "=", "self", ".", "url", "+", "url", "kwargs", "[", "'auth'", "]", "=", "self", ".", "auth", "headers", "=", "deepcopy", "(", "self", ".",...
A convenience wrapper for _put. Adds headers, auth and base url by default
[ "A", "convenience", "wrapper", "for", "_put", ".", "Adds", "headers", "auth", "and", "base", "url", "by", "default" ]
python
train
30.666667
Rapptz/discord.py
discord/voice_client.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/voice_client.py#L415-L446
def send_audio_packet(self, data, *, encode=True): """Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool ...
[ "def", "send_audio_packet", "(", "self", ",", "data", ",", "*", ",", "encode", "=", "True", ")", ":", "self", ".", "checked_add", "(", "'sequence'", ",", "1", ",", "65535", ")", "if", "encode", ":", "encoded_data", "=", "self", ".", "encoder", ".", "...
Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool Indicates if ``data`` should be encoded into Opus. ...
[ "Sends", "an", "audio", "packet", "composed", "of", "the", "data", "." ]
python
train
33.28125
TimBest/django-multi-form-view
multi_form_view/base.py
https://github.com/TimBest/django-multi-form-view/blob/d7f0a341881a5a36e4d567ca9bc29d233de01720/multi_form_view/base.py#L127-L135
def get_objects(self): """ Returns dictionary with the instance objects for each form. Keys should match the corresponding form. """ objects = {} for key in six.iterkeys(self.form_classes): objects[key] = None return objects
[ "def", "get_objects", "(", "self", ")", ":", "objects", "=", "{", "}", "for", "key", "in", "six", ".", "iterkeys", "(", "self", ".", "form_classes", ")", ":", "objects", "[", "key", "]", "=", "None", "return", "objects" ]
Returns dictionary with the instance objects for each form. Keys should match the corresponding form.
[ "Returns", "dictionary", "with", "the", "instance", "objects", "for", "each", "form", ".", "Keys", "should", "match", "the", "corresponding", "form", "." ]
python
train
31.555556
Parisson/TimeSide
timeside/core/processor.py
https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/processor.py#L230-L267
def process(self, frames, eod): """Returns an iterator over tuples of the form (buffer, eod) where buffer is a fixed-sized block of data, and eod indicates whether this is the last block. In case padding is deactivated the last block may be smaller than the buffer size. "...
[ "def", "process", "(", "self", ",", "frames", ",", "eod", ")", ":", "src_index", "=", "0", "remaining", "=", "len", "(", "frames", ")", "while", "remaining", ":", "space", "=", "self", ".", "buffer_size", "-", "self", ".", "len", "copylen", "=", "rem...
Returns an iterator over tuples of the form (buffer, eod) where buffer is a fixed-sized block of data, and eod indicates whether this is the last block. In case padding is deactivated the last block may be smaller than the buffer size.
[ "Returns", "an", "iterator", "over", "tuples", "of", "the", "form", "(", "buffer", "eod", ")", "where", "buffer", "is", "a", "fixed", "-", "sized", "block", "of", "data", "and", "eod", "indicates", "whether", "this", "is", "the", "last", "block", ".", ...
python
train
33.5
spotify/luigi
luigi/tools/range.py
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L316-L321
def parameters_to_datetime(self, p): """ Given a dictionary of parameters, will extract the ranged task parameter value """ dt = p[self._param_name] return datetime(dt.year, dt.month, dt.day)
[ "def", "parameters_to_datetime", "(", "self", ",", "p", ")", ":", "dt", "=", "p", "[", "self", ".", "_param_name", "]", "return", "datetime", "(", "dt", ".", "year", ",", "dt", ".", "month", ",", "dt", ".", "day", ")" ]
Given a dictionary of parameters, will extract the ranged task parameter value
[ "Given", "a", "dictionary", "of", "parameters", "will", "extract", "the", "ranged", "task", "parameter", "value" ]
python
train
37.666667
jaredLunde/redis_structures
redis_structures/__init__.py
https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L412-L415
def mget(self, *keys): """ -> #list of values at the specified @keys """ keys = list(map(self.get_key, keys)) return list(map(self._loads, self._client.mget(*keys)))
[ "def", "mget", "(", "self", ",", "*", "keys", ")", ":", "keys", "=", "list", "(", "map", "(", "self", ".", "get_key", ",", "keys", ")", ")", "return", "list", "(", "map", "(", "self", ".", "_loads", ",", "self", ".", "_client", ".", "mget", "("...
-> #list of values at the specified @keys
[ "-", ">", "#list", "of", "values", "at", "the", "specified" ]
python
train
46.5
danielperna84/pyhomematic
pyhomematic/_hm.py
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L873-L878
def deleteMetadata(self, remote, address, key): """Delete metadata of device""" try: return self.proxies["%s-%s" % (self._interface_id, remote)].deleteMetadata(address, key) except Exception as err: LOG.debug("ServerThread.deleteMetadata: Exception: %s" % str(err))
[ "def", "deleteMetadata", "(", "self", ",", "remote", ",", "address", ",", "key", ")", ":", "try", ":", "return", "self", ".", "proxies", "[", "\"%s-%s\"", "%", "(", "self", ".", "_interface_id", ",", "remote", ")", "]", ".", "deleteMetadata", "(", "add...
Delete metadata of device
[ "Delete", "metadata", "of", "device" ]
python
train
51.333333
ArchiveTeam/wpull
wpull/scraper/util.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/util.py#L19-L35
def parse_refresh(text): '''Parses text for HTTP Refresh URL. Returns: str, None ''' match = re.search(r'url\s*=(.+)', text, re.IGNORECASE) if match: url = match.group(1) if url.startswith('"'): url = url.strip('"') elif url.startswith("'"): ...
[ "def", "parse_refresh", "(", "text", ")", ":", "match", "=", "re", ".", "search", "(", "r'url\\s*=(.+)'", ",", "text", ",", "re", ".", "IGNORECASE", ")", "if", "match", ":", "url", "=", "match", ".", "group", "(", "1", ")", "if", "url", ".", "start...
Parses text for HTTP Refresh URL. Returns: str, None
[ "Parses", "text", "for", "HTTP", "Refresh", "URL", "." ]
python
train
21.294118
nwilming/ocupy
ocupy/parallel.py
https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L216-L221
def from_dict(self, description): """Configures the task store to be the task_store described in description""" assert(self.ident == description['ident']) self.partitions = description['partitions'] self.indices = description['indices']
[ "def", "from_dict", "(", "self", ",", "description", ")", ":", "assert", "(", "self", ".", "ident", "==", "description", "[", "'ident'", "]", ")", "self", ".", "partitions", "=", "description", "[", "'partitions'", "]", "self", ".", "indices", "=", "desc...
Configures the task store to be the task_store described in description
[ "Configures", "the", "task", "store", "to", "be", "the", "task_store", "described", "in", "description" ]
python
train
46.5