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
saltstack/salt
salt/modules/boto_elasticache.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elasticache.py#L427-L468
def create_subnet_group(name, description, subnet_ids=None, subnet_names=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an ElastiCache subnet group CLI example to create an ElastiCache subnet group:: salt myminion boto_elasticache.create_subne...
[ "def", "create_subnet_group", "(", "name", ",", "description", ",", "subnet_ids", "=", "None", ",", "subnet_names", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "...
Create an ElastiCache subnet group CLI example to create an ElastiCache subnet group:: salt myminion boto_elasticache.create_subnet_group my-subnet-group \ "group description" subnet_ids='[subnet-12345678, subnet-87654321]' \ region=us-east-1
[ "Create", "an", "ElastiCache", "subnet", "group" ]
python
train
43.071429
juju/charm-helpers
charmhelpers/contrib/hardening/templating.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/templating.py#L55-L73
def render_and_write(template_dir, path, context): """Renders the specified template into the file. :param template_dir: the directory to load the template from :param path: the path to write the templated contents to :param context: the parameters to pass to the rendering engine """ env = Envi...
[ "def", "render_and_write", "(", "template_dir", ",", "path", ",", "context", ")", ":", "env", "=", "Environment", "(", "loader", "=", "FileSystemLoader", "(", "template_dir", ")", ")", "template_file", "=", "os", ".", "path", ".", "basename", "(", "path", ...
Renders the specified template into the file. :param template_dir: the directory to load the template from :param path: the path to write the templated contents to :param context: the parameters to pass to the rendering engine
[ "Renders", "the", "specified", "template", "into", "the", "file", "." ]
python
train
41.684211
StackStorm/pybind
pybind/nos/v7_2_0/rbridge_id/router/router_bgp/address_family/l2vpn/evpn/neighbor/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/rbridge_id/router/router_bgp/address_family/l2vpn/evpn/neighbor/__init__.py#L162-L183
def _set_evpn_neighbor_ipv6(self, v, load=False): """ Setter method for evpn_neighbor_ipv6, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/l2vpn/evpn/neighbor/evpn_neighbor_ipv6 (list) If this variable is read-only (config: false) in the source YANG file, then _set_evpn_neighbor_...
[ "def", "_set_evpn_neighbor_ipv6", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ","...
Setter method for evpn_neighbor_ipv6, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/l2vpn/evpn/neighbor/evpn_neighbor_ipv6 (list) If this variable is read-only (config: false) in the source YANG file, then _set_evpn_neighbor_ipv6 is considered as a private method. Backends looking t...
[ "Setter", "method", "for", "evpn_neighbor_ipv6", "mapped", "from", "YANG", "variable", "/", "rbridge_id", "/", "router", "/", "router_bgp", "/", "address_family", "/", "l2vpn", "/", "evpn", "/", "neighbor", "/", "evpn_neighbor_ipv6", "(", "list", ")", "If", "t...
python
train
139.227273
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/lib/pretty.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/pretty.py#L212-L229
def breakable(self, sep=' '): """ Add a breakable separator to the output. This does not mean that it will automatically break here. If no breaking on this position takes place the `sep` is inserted which default to one space. """ width = len(sep) group = self.g...
[ "def", "breakable", "(", "self", ",", "sep", "=", "' '", ")", ":", "width", "=", "len", "(", "sep", ")", "group", "=", "self", ".", "group_stack", "[", "-", "1", "]", "if", "group", ".", "want_break", ":", "self", ".", "flush", "(", ")", "self", ...
Add a breakable separator to the output. This does not mean that it will automatically break here. If no breaking on this position takes place the `sep` is inserted which default to one space.
[ "Add", "a", "breakable", "separator", "to", "the", "output", ".", "This", "does", "not", "mean", "that", "it", "will", "automatically", "break", "here", ".", "If", "no", "breaking", "on", "this", "position", "takes", "place", "the", "sep", "is", "inserted"...
python
test
39.111111
Diaoul/subliminal
subliminal/cli.py
https://github.com/Diaoul/subliminal/blob/a952dfb2032eb0fd6eb1eb89f04080923c11c4cf/subliminal/cli.py#L264-L271
def cache(ctx, clear_subliminal): """Cache management.""" if clear_subliminal: for file in glob.glob(os.path.join(ctx.parent.params['cache_dir'], cache_file) + '*'): os.remove(file) click.echo('Subliminal\'s cache cleared.') else: click.echo('Nothing done.')
[ "def", "cache", "(", "ctx", ",", "clear_subliminal", ")", ":", "if", "clear_subliminal", ":", "for", "file", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "ctx", ".", "parent", ".", "params", "[", "'cache_dir'", "]", ",", "cach...
Cache management.
[ "Cache", "management", "." ]
python
train
37.375
steveYeah/PyBomb
pybomb/clients/base_client.py
https://github.com/steveYeah/PyBomb/blob/54045d74e642f8a1c4366c24bd6a330ae3da6257/pybomb/clients/base_client.py#L102-L114
def _validate_filter_fields(self, filter_by): """ :param filter_by: dict :raises: pybomb.exceptions.InvalidFilterFieldException """ for filter_field in filter_by: if ( filter_field not in self.RESPONSE_FIELD_MAP or not self.RESPONSE_FIE...
[ "def", "_validate_filter_fields", "(", "self", ",", "filter_by", ")", ":", "for", "filter_field", "in", "filter_by", ":", "if", "(", "filter_field", "not", "in", "self", ".", "RESPONSE_FIELD_MAP", "or", "not", "self", ".", "RESPONSE_FIELD_MAP", "[", "filter_fiel...
:param filter_by: dict :raises: pybomb.exceptions.InvalidFilterFieldException
[ ":", "param", "filter_by", ":", "dict", ":", "raises", ":", "pybomb", ".", "exceptions", ".", "InvalidFilterFieldException" ]
python
train
38.307692
mental32/spotify.py
spotify/models/playlist.py
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/playlist.py#L114-L134
async def get_all_tracks(self) -> List[PlaylistTrack]: """Get all playlist tracks from the playlist. Returns ------- tracks : List[PlaylistTrack] The playlists tracks. """ if isinstance(self._tracks, PartialTracks): return await self._tracks.build...
[ "async", "def", "get_all_tracks", "(", "self", ")", "->", "List", "[", "PlaylistTrack", "]", ":", "if", "isinstance", "(", "self", ".", "_tracks", ",", "PartialTracks", ")", ":", "return", "await", "self", ".", "_tracks", ".", "build", "(", ")", "_tracks...
Get all playlist tracks from the playlist. Returns ------- tracks : List[PlaylistTrack] The playlists tracks.
[ "Get", "all", "playlist", "tracks", "from", "the", "playlist", "." ]
python
test
33.380952
aws/sagemaker-python-sdk
src/sagemaker/session.py
https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/session.py#L118-L169
def upload_data(self, path, bucket=None, key_prefix='data'): """Upload local file or directory to S3. If a single file is specified for upload, the resulting S3 object key is ``{key_prefix}/{filename}`` (filename does not include the local path, if any specified). If a directory is spe...
[ "def", "upload_data", "(", "self", ",", "path", ",", "bucket", "=", "None", ",", "key_prefix", "=", "'data'", ")", ":", "# Generate a tuple for each file that we want to upload of the form (local_path, s3_key).", "files", "=", "[", "]", "key_suffix", "=", "None", "if"...
Upload local file or directory to S3. If a single file is specified for upload, the resulting S3 object key is ``{key_prefix}/{filename}`` (filename does not include the local path, if any specified). If a directory is specified for upload, the API uploads all content, recursively, pre...
[ "Upload", "local", "file", "or", "directory", "to", "S3", "." ]
python
train
52.519231
vaexio/vaex
packages/vaex-core/vaex/__init__.py
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/__init__.py#L77-L98
def app(*args, **kwargs): """Create a vaex app, the QApplication mainloop must be started. In ipython notebook/jupyter do the following: >>> import vaex.ui.main # this causes the qt api level to be set properly >>> import vaex Next cell: >>> %gui qt Next cell: >>> app = vaex.app() ...
[ "def", "app", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "vaex", ".", "ui", ".", "main", "return", "vaex", ".", "ui", ".", "main", ".", "VaexApp", "(", ")" ]
Create a vaex app, the QApplication mainloop must be started. In ipython notebook/jupyter do the following: >>> import vaex.ui.main # this causes the qt api level to be set properly >>> import vaex Next cell: >>> %gui qt Next cell: >>> app = vaex.app() From now on, you can run the...
[ "Create", "a", "vaex", "app", "the", "QApplication", "mainloop", "must", "be", "started", "." ]
python
test
19.227273
uw-it-aca/uw-restclients-sws
uw_sws/term.py
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/term.py#L251-L259
def get_next_non_summer_term(term): """ Return the Term object for the quarter after as the given term (skip the summer quarter) """ next_term = get_term_after(term) if next_term.is_summer_quarter(): return get_next_autumn_term(next_term) return next_term
[ "def", "get_next_non_summer_term", "(", "term", ")", ":", "next_term", "=", "get_term_after", "(", "term", ")", "if", "next_term", ".", "is_summer_quarter", "(", ")", ":", "return", "get_next_autumn_term", "(", "next_term", ")", "return", "next_term" ]
Return the Term object for the quarter after as the given term (skip the summer quarter)
[ "Return", "the", "Term", "object", "for", "the", "quarter", "after", "as", "the", "given", "term", "(", "skip", "the", "summer", "quarter", ")" ]
python
train
31.444444
coleifer/walrus
walrus/models.py
https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/models.py#L369-L373
def make_key(self, *parts): """Generate a namespaced key for the given path.""" separator = getattr(self.model_class, 'index_separator', '.') parts = map(decode, parts) return '%s%s' % (self._base_key, separator.join(map(str, parts)))
[ "def", "make_key", "(", "self", ",", "*", "parts", ")", ":", "separator", "=", "getattr", "(", "self", ".", "model_class", ",", "'index_separator'", ",", "'.'", ")", "parts", "=", "map", "(", "decode", ",", "parts", ")", "return", "'%s%s'", "%", "(", ...
Generate a namespaced key for the given path.
[ "Generate", "a", "namespaced", "key", "for", "the", "given", "path", "." ]
python
train
52.4
iotile/coretools
iotilecore/iotile/core/hw/auth/auth_provider.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/auth/auth_provider.py#L72-L82
def DeriveReportKey(cls, root_key, report_id, sent_timestamp): """Derive a standard one time use report signing key. The standard method is HMAC-SHA256(root_key, MAGIC_NUMBER || report_id || sent_timestamp) where MAGIC_NUMBER is 0x00000002 and all integers are in little endian. """ ...
[ "def", "DeriveReportKey", "(", "cls", ",", "root_key", ",", "report_id", ",", "sent_timestamp", ")", ":", "signed_data", "=", "struct", ".", "pack", "(", "\"<LLL\"", ",", "AuthProvider", ".", "ReportKeyMagic", ",", "report_id", ",", "sent_timestamp", ")", "hma...
Derive a standard one time use report signing key. The standard method is HMAC-SHA256(root_key, MAGIC_NUMBER || report_id || sent_timestamp) where MAGIC_NUMBER is 0x00000002 and all integers are in little endian.
[ "Derive", "a", "standard", "one", "time", "use", "report", "signing", "key", "." ]
python
train
47.090909
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py#L95-L104
def print_latex(o): """A function to generate the latex representation of sympy expressions.""" if can_print_latex(o): s = latex(o, mode='plain') s = s.replace('\\dag','\\dagger') s = s.strip('$') return '$$%s$$' % s # Fallback to the string printer return None
[ "def", "print_latex", "(", "o", ")", ":", "if", "can_print_latex", "(", "o", ")", ":", "s", "=", "latex", "(", "o", ",", "mode", "=", "'plain'", ")", "s", "=", "s", ".", "replace", "(", "'\\\\dag'", ",", "'\\\\dagger'", ")", "s", "=", "s", ".", ...
A function to generate the latex representation of sympy expressions.
[ "A", "function", "to", "generate", "the", "latex", "representation", "of", "sympy", "expressions", "." ]
python
test
30.4
KelSolaar/Umbra
umbra/ui/delegates.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/delegates.py#L130-L144
def style(self, value): """ Setter for **self.__style** attribute. :param value: Attribute value. :type value: Style """ if value is not None: assert type(value) is Style, "'{0}' attribute: '{1}' type is not 'Style'!".format("style", value) style...
[ "def", "style", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "Style", ",", "\"'{0}' attribute: '{1}' type is not 'Style'!\"", ".", "format", "(", "\"style\"", ",", "value", ")", "s...
Setter for **self.__style** attribute. :param value: Attribute value. :type value: Style
[ "Setter", "for", "**", "self", ".", "__style", "**", "attribute", "." ]
python
train
30.733333
pudo-attic/scrapekit
scrapekit/http.py
https://github.com/pudo-attic/scrapekit/blob/cfd258120922fcd571430cdf00ba50f3cf18dc15/scrapekit/http.py#L29-L38
def xml(self): """ Create an ``lxml``-based XML DOM from the response. The tree will not have a root, so all queries need to be relative (i.e. start with a dot). """ try: from lxml import etree return etree.fromstring(self.content) except ImportErr...
[ "def", "xml", "(", "self", ")", ":", "try", ":", "from", "lxml", "import", "etree", "return", "etree", ".", "fromstring", "(", "self", ".", "content", ")", "except", "ImportError", "as", "ie", ":", "raise", "DependencyException", "(", "ie", ")" ]
Create an ``lxml``-based XML DOM from the response. The tree will not have a root, so all queries need to be relative (i.e. start with a dot).
[ "Create", "an", "lxml", "-", "based", "XML", "DOM", "from", "the", "response", ".", "The", "tree", "will", "not", "have", "a", "root", "so", "all", "queries", "need", "to", "be", "relative", "(", "i", ".", "e", ".", "start", "with", "a", "dot", ")"...
python
train
36.2
williballenthin/python-evtx
Evtx/BinaryParser.py
https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/BinaryParser.py#L480-L495
def unpack_wstring(self, offset, length): """ Returns a string from the relative offset with the given length, where each character is a wchar (2 bytes) Arguments: - `offset`: The relative offset from the start of the block. - `length`: The length of the string. T...
[ "def", "unpack_wstring", "(", "self", ",", "offset", ",", "length", ")", ":", "start", "=", "self", ".", "_offset", "+", "offset", "end", "=", "self", ".", "_offset", "+", "offset", "+", "2", "*", "length", "try", ":", "return", "bytes", "(", "self",...
Returns a string from the relative offset with the given length, where each character is a wchar (2 bytes) Arguments: - `offset`: The relative offset from the start of the block. - `length`: The length of the string. Throws: - `UnicodeDecodeError`
[ "Returns", "a", "string", "from", "the", "relative", "offset", "with", "the", "given", "length", "where", "each", "character", "is", "a", "wchar", "(", "2", "bytes", ")", "Arguments", ":", "-", "offset", ":", "The", "relative", "offset", "from", "the", "...
python
train
39.5
rigetti/quantumflow
tools/benchmark.py
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/tools/benchmark.py#L31-L45
def benchmark(N, gates): """Create and run a circuit with N qubits and given number of gates""" qubits = list(range(0, N)) ket = qf.zero_state(N) for n in range(0, N): ket = qf.H(n).run(ket) for _ in range(0, (gates-N)//3): qubit0, qubit1 = random.sample(qubits, 2) ket = qf...
[ "def", "benchmark", "(", "N", ",", "gates", ")", ":", "qubits", "=", "list", "(", "range", "(", "0", ",", "N", ")", ")", "ket", "=", "qf", ".", "zero_state", "(", "N", ")", "for", "n", "in", "range", "(", "0", ",", "N", ")", ":", "ket", "="...
Create and run a circuit with N qubits and given number of gates
[ "Create", "and", "run", "a", "circuit", "with", "N", "qubits", "and", "given", "number", "of", "gates" ]
python
train
29
BlueBrain/NeuroM
neurom/check/neuron_checks.py
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L54-L65
def has_axon(neuron, treefun=_read_neurite_type): '''Check if a neuron has an axon Arguments: neuron(Neuron): The neuron object to test treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result ''' return CheckResult...
[ "def", "has_axon", "(", "neuron", ",", "treefun", "=", "_read_neurite_type", ")", ":", "return", "CheckResult", "(", "NeuriteType", ".", "axon", "in", "(", "treefun", "(", "n", ")", "for", "n", "in", "neuron", ".", "neurites", ")", ")" ]
Check if a neuron has an axon Arguments: neuron(Neuron): The neuron object to test treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result
[ "Check", "if", "a", "neuron", "has", "an", "axon" ]
python
train
30.666667
hyperledger/indy-sdk
wrappers/python/indy/pool.py
https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/wrappers/python/indy/pool.py#L113-L130
async def list_pools() -> None: """ Lists names of created pool ledgers :return: Error code """ logger = logging.getLogger(__name__) logger.debug("list_pools: >>> ") if not hasattr(list_pools, "cb"): logger.debug("list_pools: Creating callback") list_pools.cb = create_cb(CF...
[ "async", "def", "list_pools", "(", ")", "->", "None", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "\"list_pools: >>> \"", ")", "if", "not", "hasattr", "(", "list_pools", ",", "\"cb\"", ")", ":", "lo...
Lists names of created pool ledgers :return: Error code
[ "Lists", "names", "of", "created", "pool", "ledgers", ":", "return", ":", "Error", "code" ]
python
train
29.277778
echinopsii/net.echinopsii.ariane.community.cli.python3
ariane_clip3/directory.py
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L4476-L4552
def save(self): """ :return: save this team on Ariane server (create or update) """ LOGGER.debug("Team.save") post_payload = {} consolidated_osi_id = [] consolidated_app_id = [] if self.id is not None: post_payload['teamID'] = self.id ...
[ "def", "save", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"Team.save\"", ")", "post_payload", "=", "{", "}", "consolidated_osi_id", "=", "[", "]", "consolidated_app_id", "=", "[", "]", "if", "self", ".", "id", "is", "not", "None", ":", "post...
:return: save this team on Ariane server (create or update)
[ ":", "return", ":", "save", "this", "team", "on", "Ariane", "server", "(", "create", "or", "update", ")" ]
python
train
38.207792
pkkid/python-plexapi
plexapi/settings.py
https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/settings.py#L42-L44
def all(self): """ Returns a list of all :class:`~plexapi.settings.Setting` objects available. """ return list(v for id, v in sorted(self._settings.items()))
[ "def", "all", "(", "self", ")", ":", "return", "list", "(", "v", "for", "id", ",", "v", "in", "sorted", "(", "self", ".", "_settings", ".", "items", "(", ")", ")", ")" ]
Returns a list of all :class:`~plexapi.settings.Setting` objects available.
[ "Returns", "a", "list", "of", "all", ":", "class", ":", "~plexapi", ".", "settings", ".", "Setting", "objects", "available", "." ]
python
train
57
bcbio/bcbio-nextgen
bcbio/variation/split.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/split.py#L12-L25
def split_vcf(in_file, ref_file, config, out_dir=None): """Split a VCF file into separate files by chromosome. """ if out_dir is None: out_dir = os.path.join(os.path.dirname(in_file), "split") out_files = [] with open(ref.fasta_idx(ref_file, config)) as in_handle: for line in in_hand...
[ "def", "split_vcf", "(", "in_file", ",", "ref_file", ",", "config", ",", "out_dir", "=", "None", ")", ":", "if", "out_dir", "is", "None", ":", "out_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "in_file", "...
Split a VCF file into separate files by chromosome.
[ "Split", "a", "VCF", "file", "into", "separate", "files", "by", "chromosome", "." ]
python
train
45.785714
rueckstiess/mtools
mtools/util/profile_collection.py
https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/util/profile_collection.py#L117-L131
def _calculate_bounds(self): """Calculate beginning and end of log events.""" # get start datetime first = self.coll_handle.find_one(None, sort=[("ts", ASCENDING)]) last = self.coll_handle.find_one(None, sort=[("ts", DESCENDING)]) self._start = first['ts'] if self._start...
[ "def", "_calculate_bounds", "(", "self", ")", ":", "# get start datetime", "first", "=", "self", ".", "coll_handle", ".", "find_one", "(", "None", ",", "sort", "=", "[", "(", "\"ts\"", ",", "ASCENDING", ")", "]", ")", "last", "=", "self", ".", "coll_hand...
Calculate beginning and end of log events.
[ "Calculate", "beginning", "and", "end", "of", "log", "events", "." ]
python
train
35.466667
oasis-open/cti-stix-validator
stix2validator/codes.py
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/codes.py#L22-L41
def get_code(results): """Determines the exit status code to be returned from a script by inspecting the results returned from validating file(s). Status codes are binary OR'd together, so exit codes can communicate multiple error conditions. """ status = EXIT_SUCCESS for file_result in re...
[ "def", "get_code", "(", "results", ")", ":", "status", "=", "EXIT_SUCCESS", "for", "file_result", "in", "results", ":", "error", "=", "any", "(", "object_result", ".", "errors", "for", "object_result", "in", "file_result", ".", "object_results", ")", "fatal", ...
Determines the exit status code to be returned from a script by inspecting the results returned from validating file(s). Status codes are binary OR'd together, so exit codes can communicate multiple error conditions.
[ "Determines", "the", "exit", "status", "code", "to", "be", "returned", "from", "a", "script", "by", "inspecting", "the", "results", "returned", "from", "validating", "file", "(", "s", ")", ".", "Status", "codes", "are", "binary", "OR", "d", "together", "so...
python
train
28.7
openvax/isovar
isovar/variant_sequences.py
https://github.com/openvax/isovar/blob/b39b684920e3f6b344851d6598a1a1c67bce913b/isovar/variant_sequences.py#L200-L242
def trim_by_coverage(self, min_reads): """ Given the min number of reads overlapping each nucleotide of a variant sequence, trim this sequence by getting rid of positions which are overlapped by fewer reads than specified. """ read_count_array = self.coverage() lo...
[ "def", "trim_by_coverage", "(", "self", ",", "min_reads", ")", ":", "read_count_array", "=", "self", ".", "coverage", "(", ")", "logger", ".", "info", "(", "\"Coverage: %s (len=%d)\"", "%", "(", "read_count_array", ",", "len", "(", "read_count_array", ")", ")"...
Given the min number of reads overlapping each nucleotide of a variant sequence, trim this sequence by getting rid of positions which are overlapped by fewer reads than specified.
[ "Given", "the", "min", "number", "of", "reads", "overlapping", "each", "nucleotide", "of", "a", "variant", "sequence", "trim", "this", "sequence", "by", "getting", "rid", "of", "positions", "which", "are", "overlapped", "by", "fewer", "reads", "than", "specifi...
python
train
50.55814
RudolfCardinal/pythonlib
cardinal_pythonlib/json/serialize.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L626-L633
def json_encode(obj: Instance, **kwargs) -> str: """ Encodes an object to JSON using our custom encoder. The ``**kwargs`` can be used to pass things like ``'indent'``, for formatting. """ return json.dumps(obj, cls=JsonClassEncoder, **kwargs)
[ "def", "json_encode", "(", "obj", ":", "Instance", ",", "*", "*", "kwargs", ")", "->", "str", ":", "return", "json", ".", "dumps", "(", "obj", ",", "cls", "=", "JsonClassEncoder", ",", "*", "*", "kwargs", ")" ]
Encodes an object to JSON using our custom encoder. The ``**kwargs`` can be used to pass things like ``'indent'``, for formatting.
[ "Encodes", "an", "object", "to", "JSON", "using", "our", "custom", "encoder", "." ]
python
train
32.5
Holzhaus/python-cmuclmtk
cmuclmtk/__init__.py
https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L329-L358
def idngram2stats(input_file, output_file, n=3, fof_size=50, verbosity=2, ascii_input=False): """ Lists the frequency-of-frequencies for each of the 2-grams, ... , n-grams, which can enable the user to choose appropriate cut-offs, and to specify appropriate memory requirements with the spec_num parameter in...
[ "def", "idngram2stats", "(", "input_file", ",", "output_file", ",", "n", "=", "3", ",", "fof_size", "=", "50", ",", "verbosity", "=", "2", ",", "ascii_input", "=", "False", ")", ":", "cmd", "=", "[", "'idngram2stats'", "]", "if", "n", ":", "cmd", "."...
Lists the frequency-of-frequencies for each of the 2-grams, ... , n-grams, which can enable the user to choose appropriate cut-offs, and to specify appropriate memory requirements with the spec_num parameter in idngram2lm.
[ "Lists", "the", "frequency", "-", "of", "-", "frequencies", "for", "each", "of", "the", "2", "-", "grams", "...", "n", "-", "grams", "which", "can", "enable", "the", "user", "to", "choose", "appropriate", "cut", "-", "offs", "and", "to", "specify", "ap...
python
train
38.3
marshallward/f90nml
f90nml/namelist.py
https://github.com/marshallward/f90nml/blob/4932cabc5221afc844ee6a5b4a05ceb8bd4a2711/f90nml/namelist.py#L408-L417
def patch(self, nml_patch): """Update the namelist from another partial or full namelist. This is different from the intrinsic `update()` method, which replaces a namelist section. Rather, it updates the values within a section. """ for sec in nml_patch: if sec not ...
[ "def", "patch", "(", "self", ",", "nml_patch", ")", ":", "for", "sec", "in", "nml_patch", ":", "if", "sec", "not", "in", "self", ":", "self", "[", "sec", "]", "=", "Namelist", "(", ")", "self", "[", "sec", "]", ".", "update", "(", "nml_patch", "[...
Update the namelist from another partial or full namelist. This is different from the intrinsic `update()` method, which replaces a namelist section. Rather, it updates the values within a section.
[ "Update", "the", "namelist", "from", "another", "partial", "or", "full", "namelist", "." ]
python
train
40.3
Jajcus/pyxmpp2
pyxmpp2/expdict.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/expdict.py#L138-L163
def _expire_item(self, key): """Do the expiration of a dictionary item. Remove the item if it has expired by now. :Parameters: - `key`: key to the object. :Types: - `key`: any hashable value """ (timeout, callback) = self._timeouts[key] n...
[ "def", "_expire_item", "(", "self", ",", "key", ")", ":", "(", "timeout", ",", "callback", ")", "=", "self", ".", "_timeouts", "[", "key", "]", "now", "=", "time", ".", "time", "(", ")", "if", "timeout", "<=", "now", ":", "item", "=", "dict", "."...
Do the expiration of a dictionary item. Remove the item if it has expired by now. :Parameters: - `key`: key to the object. :Types: - `key`: any hashable value
[ "Do", "the", "expiration", "of", "a", "dictionary", "item", "." ]
python
valid
28.461538
BDNYC/astrodbkit
astrodbkit/astrodb.py
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L685-L782
def _compare_records(self, table, duplicate, options=['r', 'c', 'k', 'sql']): """ Compares similar records and prompts the user to make decisions about keeping, updating, or modifying records in question. Parameters ---------- table: str The name of the table whose r...
[ "def", "_compare_records", "(", "self", ",", "table", ",", "duplicate", ",", "options", "=", "[", "'r'", ",", "'c'", ",", "'k'", ",", "'sql'", "]", ")", ":", "# print the old and new records suspected of being duplicates", "verbose", "=", "True", "if", "duplicat...
Compares similar records and prompts the user to make decisions about keeping, updating, or modifying records in question. Parameters ---------- table: str The name of the table whose records are being compared. duplicate: sequence The ids of the potentially dupl...
[ "Compares", "similar", "records", "and", "prompts", "the", "user", "to", "make", "decisions", "about", "keeping", "updating", "or", "modifying", "records", "in", "question", "." ]
python
train
48.530612
zhmcclient/python-zhmcclient
zhmcclient/_storage_group.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_storage_group.py#L315-L325
def virtual_storage_resources(self): """ :class:`~zhmcclient.VirtualStorageResourceManager`: Access to the :term:`virtual storage resources <Virtual Storage Resource>` in this storage group. """ # We do here some lazy loading. if not self._virtual_storage_resource...
[ "def", "virtual_storage_resources", "(", "self", ")", ":", "# We do here some lazy loading.", "if", "not", "self", ".", "_virtual_storage_resources", ":", "self", ".", "_virtual_storage_resources", "=", "VirtualStorageResourceManager", "(", "self", ")", "return", "self", ...
:class:`~zhmcclient.VirtualStorageResourceManager`: Access to the :term:`virtual storage resources <Virtual Storage Resource>` in this storage group.
[ ":", "class", ":", "~zhmcclient", ".", "VirtualStorageResourceManager", ":", "Access", "to", "the", ":", "term", ":", "virtual", "storage", "resources", "<Virtual", "Storage", "Resource", ">", "in", "this", "storage", "group", "." ]
python
train
41.727273
adubkov/py-cloudwatch
pycloudwatch/sender.py
https://github.com/adubkov/py-cloudwatch/blob/755bac7c153f75c4f0aa73ce14ca333cc4affb36/pycloudwatch/sender.py#L14-L23
def put(self, metrics): """ Put metrics to cloudwatch. Metric shoult be instance or list of instances of CloudWatchMetric """ if type(metrics) == list: for metric in metrics: self.c.put_metric_data(**metric) else: self.c.put_metric_...
[ "def", "put", "(", "self", ",", "metrics", ")", ":", "if", "type", "(", "metrics", ")", "==", "list", ":", "for", "metric", "in", "metrics", ":", "self", ".", "c", ".", "put_metric_data", "(", "*", "*", "metric", ")", "else", ":", "self", ".", "c...
Put metrics to cloudwatch. Metric shoult be instance or list of instances of CloudWatchMetric
[ "Put", "metrics", "to", "cloudwatch", ".", "Metric", "shoult", "be", "instance", "or", "list", "of", "instances", "of", "CloudWatchMetric" ]
python
valid
32.6
tcalmant/python-javaobj
javaobj/core.py
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1357-L1382
def write_enum(self, obj): """ Writes an Enum value :param obj: A JavaEnum object """ # FIXME: the output doesn't have the same references as the real # serializable form self._writeStruct(">B", 1, (self.TC_ENUM,)) try: idx = self.references....
[ "def", "write_enum", "(", "self", ",", "obj", ")", ":", "# FIXME: the output doesn't have the same references as the real", "# serializable form", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_ENUM", ",", ")", ")", "try", ":", ...
Writes an Enum value :param obj: A JavaEnum object
[ "Writes", "an", "Enum", "value" ]
python
train
27.923077
arista-eosplus/pyeapi
pyeapi/api/interfaces.py
https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/api/interfaces.py#L766-L788
def set_lacp_fallback(self, name, mode=None): """Configures the Port-Channel lacp_fallback Args: name(str): The Port-Channel interface name mode(str): The Port-Channel LACP fallback setting Valid values are 'disabled', 'static', 'individual': * ...
[ "def", "set_lacp_fallback", "(", "self", ",", "name", ",", "mode", "=", "None", ")", ":", "if", "mode", "not", "in", "[", "'disabled'", ",", "'static'", ",", "'individual'", "]", ":", "return", "False", "disable", "=", "True", "if", "mode", "==", "'dis...
Configures the Port-Channel lacp_fallback Args: name(str): The Port-Channel interface name mode(str): The Port-Channel LACP fallback setting Valid values are 'disabled', 'static', 'individual': * static - Fallback to static LAG mode * i...
[ "Configures", "the", "Port", "-", "Channel", "lacp_fallback" ]
python
train
40.086957
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1321-L1345
def _new_convolution(self, use_bias): """Returns new convolution. Args: use_bias: Use bias in convolutions. If False, clean_dict removes bias entries from initializers, partitioners and regularizers passed to the constructor of the convolution. """ def clean_dict(input_dict): ...
[ "def", "_new_convolution", "(", "self", ",", "use_bias", ")", ":", "def", "clean_dict", "(", "input_dict", ")", ":", "if", "input_dict", "and", "not", "use_bias", ":", "cleaned_dict", "=", "input_dict", ".", "copy", "(", ")", "cleaned_dict", ".", "pop", "(...
Returns new convolution. Args: use_bias: Use bias in convolutions. If False, clean_dict removes bias entries from initializers, partitioners and regularizers passed to the constructor of the convolution.
[ "Returns", "new", "convolution", "." ]
python
train
34.76
rackerlabs/fastfood
fastfood/utils.py
https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/utils.py#L49-L60
def ruby_lines(text): """Tidy up lines from a file, honor # comments. Does not honor ruby block comments (yet). """ if isinstance(text, basestring): text = text.splitlines() elif not isinstance(text, list): raise TypeError("text should be a list or a string, not %s" ...
[ "def", "ruby_lines", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "basestring", ")", ":", "text", "=", "text", ".", "splitlines", "(", ")", "elif", "not", "isinstance", "(", "text", ",", "list", ")", ":", "raise", "TypeError", "(", "\...
Tidy up lines from a file, honor # comments. Does not honor ruby block comments (yet).
[ "Tidy", "up", "lines", "from", "a", "file", "honor", "#", "comments", "." ]
python
train
35.5
guaix-ucm/pyemir
emirdrp/instrument/dtu_configuration.py
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/instrument/dtu_configuration.py#L172-L197
def closeto(self, other, abserror): """Check that all the members are equal within provided absolute error. Parameters ---------- other : DtuConfiguration object DTU configuration instance to be compared with self. abserror : float Absolute maximum allowe...
[ "def", "closeto", "(", "self", ",", "other", ",", "abserror", ")", ":", "result", "=", "(", "abs", "(", "self", ".", "xdtu", "-", "other", ".", "xdtu", ")", "<=", "abserror", ")", "and", "(", "abs", "(", "self", ".", "ydtu", "-", "other", ".", ...
Check that all the members are equal within provided absolute error. Parameters ---------- other : DtuConfiguration object DTU configuration instance to be compared with self. abserror : float Absolute maximum allowed error. Returns ------- ...
[ "Check", "that", "all", "the", "members", "are", "equal", "within", "provided", "absolute", "error", "." ]
python
train
33.5
ManiacalLabs/BiblioPixel
bibliopixel/layout/layout.py
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/layout.py#L186-L188
def setRGB(self, pixel, r, g, b): """Set single pixel using individual RGB values instead of tuple""" self._set_base(pixel, (r, g, b))
[ "def", "setRGB", "(", "self", ",", "pixel", ",", "r", ",", "g", ",", "b", ")", ":", "self", ".", "_set_base", "(", "pixel", ",", "(", "r", ",", "g", ",", "b", ")", ")" ]
Set single pixel using individual RGB values instead of tuple
[ "Set", "single", "pixel", "using", "individual", "RGB", "values", "instead", "of", "tuple" ]
python
valid
49.333333
dpkp/kafka-python
kafka/protocol/parser.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/protocol/parser.py#L47-L72
def send_request(self, request, correlation_id=None): """Encode and queue a kafka api request for sending. Arguments: request (object): An un-encoded kafka request. correlation_id (int, optional): Optionally specify an ID to correlate requests with responses. If ...
[ "def", "send_request", "(", "self", ",", "request", ",", "correlation_id", "=", "None", ")", ":", "log", ".", "debug", "(", "'Sending request %s'", ",", "request", ")", "if", "correlation_id", "is", "None", ":", "correlation_id", "=", "self", ".", "_next_cor...
Encode and queue a kafka api request for sending. Arguments: request (object): An un-encoded kafka request. correlation_id (int, optional): Optionally specify an ID to correlate requests with responses. If not provided, an ID will be generated automatical...
[ "Encode", "and", "queue", "a", "kafka", "api", "request", "for", "sending", "." ]
python
train
40.653846
DeVilhena-Paulo/KdQuery
kdquery.py
https://github.com/DeVilhena-Paulo/KdQuery/blob/76e3791e25b2db2168c1007fe1b92c3f8ec20005/kdquery.py#L13-L16
def interval_condition(value, inf, sup, dist): """Checks if value belongs to the interval [inf - dist, sup + dist]. """ return (value > inf - dist and value < sup + dist)
[ "def", "interval_condition", "(", "value", ",", "inf", ",", "sup", ",", "dist", ")", ":", "return", "(", "value", ">", "inf", "-", "dist", "and", "value", "<", "sup", "+", "dist", ")" ]
Checks if value belongs to the interval [inf - dist, sup + dist].
[ "Checks", "if", "value", "belongs", "to", "the", "interval", "[", "inf", "-", "dist", "sup", "+", "dist", "]", "." ]
python
train
44.75
saschpe/rapport
rapport/plugin.py
https://github.com/saschpe/rapport/blob/ccceb8f84bd7e8add88ab5e137cdab6424aa4683/rapport/plugin.py#L94-L101
def _get_plugin_dirs(): """Return a list of directories where plugins may be located. """ plugin_dirs = [ os.path.expanduser(os.path.join(USER_CONFIG_DIR, "plugins")), os.path.join("rapport", "plugins") # Local dev tree ] return plugin_dirs
[ "def", "_get_plugin_dirs", "(", ")", ":", "plugin_dirs", "=", "[", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "USER_CONFIG_DIR", ",", "\"plugins\"", ")", ")", ",", "os", ".", "path", ".", "join", "(", "\"rapport\"",...
Return a list of directories where plugins may be located.
[ "Return", "a", "list", "of", "directories", "where", "plugins", "may", "be", "located", "." ]
python
train
33.75
lekhakpadmanabh/Summarizer
smrzr/core.py
https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/core.py#L39-L47
def _normalize(sentences): '''returns tf-idf matrix (unigrams+bigrams)''' tfidf = TfidfVectorizer(tokenizer=_tokenize, stop_words='english', decode_error='ignore', ngram_range=(1,2)) return tfidf.fit_transform(senten...
[ "def", "_normalize", "(", "sentences", ")", ":", "tfidf", "=", "TfidfVectorizer", "(", "tokenizer", "=", "_tokenize", ",", "stop_words", "=", "'english'", ",", "decode_error", "=", "'ignore'", ",", "ngram_range", "=", "(", "1", ",", "2", ")", ")", "return"...
returns tf-idf matrix (unigrams+bigrams)
[ "returns", "tf", "-", "idf", "matrix", "(", "unigrams", "+", "bigrams", ")" ]
python
train
35.111111
ungarj/mapchete
mapchete/io/vector.py
https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/vector.py#L131-L163
def segmentize_geometry(geometry, segmentize_value): """ Segmentize Polygon outer ring by segmentize value. Just Polygon geometry type supported. Parameters ---------- geometry : ``shapely.geometry`` segmentize_value: float Returns ------- geometry : ``shapely.geometry`` "...
[ "def", "segmentize_geometry", "(", "geometry", ",", "segmentize_value", ")", ":", "if", "geometry", ".", "geom_type", "!=", "\"Polygon\"", ":", "raise", "TypeError", "(", "\"segmentize geometry type must be Polygon\"", ")", "return", "Polygon", "(", "LinearRing", "(",...
Segmentize Polygon outer ring by segmentize value. Just Polygon geometry type supported. Parameters ---------- geometry : ``shapely.geometry`` segmentize_value: float Returns ------- geometry : ``shapely.geometry``
[ "Segmentize", "Polygon", "outer", "ring", "by", "segmentize", "value", "." ]
python
valid
28.636364
wummel/linkchecker
linkcheck/logger/html.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/html.py#L210-L214
def write_real (self, url_data): """Write url_data.url.""" self.writeln("<tr><td>"+self.part("realurl")+u"</td><td>"+ u'<a target="top" href="'+url_data.url+ u'">'+cgi.escape(url_data.url)+u"</a></td></tr>")
[ "def", "write_real", "(", "self", ",", "url_data", ")", ":", "self", ".", "writeln", "(", "\"<tr><td>\"", "+", "self", ".", "part", "(", "\"realurl\"", ")", "+", "u\"</td><td>\"", "+", "u'<a target=\"top\" href=\"'", "+", "url_data", ".", "url", "+", "u'\">'...
Write url_data.url.
[ "Write", "url_data", ".", "url", "." ]
python
train
52.2
twisted/mantissa
xmantissa/websharing.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websharing.py#L119-L125
def cloneURL(self, scheme, netloc, pathsegs, querysegs, fragment): """ Override the base implementation to pass along the share ID our constructor was passed. """ return self.__class__( self._shareID, scheme, netloc, pathsegs, querysegs, fragment)
[ "def", "cloneURL", "(", "self", ",", "scheme", ",", "netloc", ",", "pathsegs", ",", "querysegs", ",", "fragment", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "_shareID", ",", "scheme", ",", "netloc", ",", "pathsegs", ",", "querysegs",...
Override the base implementation to pass along the share ID our constructor was passed.
[ "Override", "the", "base", "implementation", "to", "pass", "along", "the", "share", "ID", "our", "constructor", "was", "passed", "." ]
python
train
41.857143
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/core/application.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/application.py#L237-L282
def init_profile_dir(self): """initialize the profile dir""" try: # location explicitly specified: location = self.config.ProfileDir.location except AttributeError: # location not specified, find by profile name try: p = ProfileDir....
[ "def", "init_profile_dir", "(", "self", ")", ":", "try", ":", "# location explicitly specified:", "location", "=", "self", ".", "config", ".", "ProfileDir", ".", "location", "except", "AttributeError", ":", "# location not specified, find by profile name", "try", ":", ...
initialize the profile dir
[ "initialize", "the", "profile", "dir" ]
python
test
45.521739
inveniosoftware/dcxml
dcxml/xmlutils.py
https://github.com/inveniosoftware/dcxml/blob/9fed6123ec0f3f2e2f645ff91653a7e86a39138d/dcxml/xmlutils.py#L36-L44
def etree_to_string(root, pretty_print=True, xml_declaration=True, encoding='utf-8'): """Dump XML etree as a string.""" return etree.tostring( root, pretty_print=pretty_print, xml_declaration=xml_declaration, encoding=encoding, ).decode('utf-8')
[ "def", "etree_to_string", "(", "root", ",", "pretty_print", "=", "True", ",", "xml_declaration", "=", "True", ",", "encoding", "=", "'utf-8'", ")", ":", "return", "etree", ".", "tostring", "(", "root", ",", "pretty_print", "=", "pretty_print", ",", "xml_decl...
Dump XML etree as a string.
[ "Dump", "XML", "etree", "as", "a", "string", "." ]
python
train
33.444444
tgsmith61591/pmdarima
pmdarima/decorators.py
https://github.com/tgsmith61591/pmdarima/blob/a133de78ba5bd68da9785b061f519ba28cd514cc/pmdarima/decorators.py#L9-L43
def deprecated(use_instead, notes=None): """Mark functions as deprecated. This decorator will result in a warning being emitted when the decorated function is used. Parameters ---------- use_instead : str The name of the function to use instead. notes : str, optional (default=None...
[ "def", "deprecated", "(", "use_instead", ",", "notes", "=", "None", ")", ":", "if", "notes", "is", "None", ":", "notes", "=", "\"\"", "else", ":", "notes", "=", "\" \"", "+", "notes", "def", "wrapped_func", "(", "func", ")", ":", "@", "functools", "....
Mark functions as deprecated. This decorator will result in a warning being emitted when the decorated function is used. Parameters ---------- use_instead : str The name of the function to use instead. notes : str, optional (default=None) Additional notes to add to the warning...
[ "Mark", "functions", "as", "deprecated", "." ]
python
train
31.142857
bitesofcode/projexui
projexui/widgets/xtreewidget/xtreewidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1160-L1211
def lockToColumn(self, index): """ Sets the column that the tree view will lock to. If None is supplied, then locking will be removed. :param index | <int> || None """ self._lockColumn = index if index is None: self.__...
[ "def", "lockToColumn", "(", "self", ",", "index", ")", ":", "self", ".", "_lockColumn", "=", "index", "if", "index", "is", "None", ":", "self", ".", "__destroyLockedView", "(", ")", "return", "else", ":", "if", "not", "self", ".", "_lockedView", ":", "...
Sets the column that the tree view will lock to. If None is supplied, then locking will be removed. :param index | <int> || None
[ "Sets", "the", "column", "that", "the", "tree", "view", "will", "lock", "to", ".", "If", "None", "is", "supplied", "then", "locking", "will", "be", "removed", ".", ":", "param", "index", "|", "<int", ">", "||", "None" ]
python
train
43.538462
mushkevych/scheduler
synergy/system/time_trigger_factory.py
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/system/time_trigger_factory.py#L10-L33
def parse_time_trigger_string(trigger_frequency): """ :param trigger_frequency: human-readable and editable string in one of two formats: - 'at Day_of_Week-HH:MM, ..., Day_of_Week-HH:MM' - 'every NNN' :return: return tuple (parsed_trigger_frequency, timer_klass) """ # replace multiple spac...
[ "def", "parse_time_trigger_string", "(", "trigger_frequency", ")", ":", "# replace multiple spaces with one", "trigger_frequency", "=", "' '", ".", "join", "(", "trigger_frequency", ".", "split", "(", ")", ")", "if", "trigger_frequency", ".", "startswith", "(", "TRIGG...
:param trigger_frequency: human-readable and editable string in one of two formats: - 'at Day_of_Week-HH:MM, ..., Day_of_Week-HH:MM' - 'every NNN' :return: return tuple (parsed_trigger_frequency, timer_klass)
[ ":", "param", "trigger_frequency", ":", "human", "-", "readable", "and", "editable", "string", "in", "one", "of", "two", "formats", ":", "-", "at", "Day_of_Week", "-", "HH", ":", "MM", "...", "Day_of_Week", "-", "HH", ":", "MM", "-", "every", "NNN", ":...
python
train
44.333333
projectshift/shift-boiler
boiler/user/event_handlers.py
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/event_handlers.py#L14-L17
def user_save_event(user): """ Handle persist event for user entities """ msg = 'User ({}){} updated/saved'.format(user.id, user.email) current_app.logger.info(msg)
[ "def", "user_save_event", "(", "user", ")", ":", "msg", "=", "'User ({}){} updated/saved'", ".", "format", "(", "user", ".", "id", ",", "user", ".", "email", ")", "current_app", ".", "logger", ".", "info", "(", "msg", ")" ]
Handle persist event for user entities
[ "Handle", "persist", "event", "for", "user", "entities" ]
python
train
43.25
armstrong/armstrong.core.arm_sections
armstrong/core/arm_sections/utils.py
https://github.com/armstrong/armstrong.core.arm_sections/blob/39c999c93771da909359e53b35afefe4846f77cb/armstrong/core/arm_sections/utils.py#L30-L34
def get_section_relations(Section): """Find every relationship between section and the item model.""" all_rels = (Section._meta.get_all_related_objects() + Section._meta.get_all_related_many_to_many_objects()) return filter_item_rels(all_rels)
[ "def", "get_section_relations", "(", "Section", ")", ":", "all_rels", "=", "(", "Section", ".", "_meta", ".", "get_all_related_objects", "(", ")", "+", "Section", ".", "_meta", ".", "get_all_related_many_to_many_objects", "(", ")", ")", "return", "filter_item_rels...
Find every relationship between section and the item model.
[ "Find", "every", "relationship", "between", "section", "and", "the", "item", "model", "." ]
python
train
53.4
cqparts/cqparts
src/cqparts_fasteners/utils/evaluator.py
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/evaluator.py#L40-L48
def start_point(self): """ Start vertex of effect :return: vertex (as vector) :rtype: :class:`cadquery.Vector` """ edge = self.result.wire().val().Edges()[0] return edge.Vertices()[0].Center()
[ "def", "start_point", "(", "self", ")", ":", "edge", "=", "self", ".", "result", ".", "wire", "(", ")", ".", "val", "(", ")", ".", "Edges", "(", ")", "[", "0", "]", "return", "edge", ".", "Vertices", "(", ")", "[", "0", "]", ".", "Center", "(...
Start vertex of effect :return: vertex (as vector) :rtype: :class:`cadquery.Vector`
[ "Start", "vertex", "of", "effect" ]
python
train
26.777778
mushkevych/scheduler
synergy/system/time_helper.py
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/system/time_helper.py#L85-L89
def month_to_year(timeperiod): """:param timeperiod: as string in YYYYMM0000 format :return string in YYYY000000 format""" t = datetime.strptime(timeperiod, SYNERGY_MONTHLY_PATTERN) return t.strftime(SYNERGY_YEARLY_PATTERN)
[ "def", "month_to_year", "(", "timeperiod", ")", ":", "t", "=", "datetime", ".", "strptime", "(", "timeperiod", ",", "SYNERGY_MONTHLY_PATTERN", ")", "return", "t", ".", "strftime", "(", "SYNERGY_YEARLY_PATTERN", ")" ]
:param timeperiod: as string in YYYYMM0000 format :return string in YYYY000000 format
[ ":", "param", "timeperiod", ":", "as", "string", "in", "YYYYMM0000", "format", ":", "return", "string", "in", "YYYY000000", "format" ]
python
train
47
jealous/stockstats
stockstats.py
https://github.com/jealous/stockstats/blob/a479a504ea1906955feeb8519c34ef40eb48ec9b/stockstats.py#L343-L362
def _get_wr(cls, df, n_days): """ Williams Overbought/Oversold Index WMS=[(Hn—Ct)/(Hn—Ln)] ×100 Ct - the close price Hn - N days high Ln - N days low :param df: data :param n_days: N days :return: None """ n_days = int(n_days)...
[ "def", "_get_wr", "(", "cls", ",", "df", ",", "n_days", ")", ":", "n_days", "=", "int", "(", "n_days", ")", "ln", "=", "df", "[", "'low'", "]", ".", "rolling", "(", "min_periods", "=", "1", ",", "window", "=", "n_days", ",", "center", "=", "False...
Williams Overbought/Oversold Index WMS=[(Hn—Ct)/(Hn—Ln)] ×100 Ct - the close price Hn - N days high Ln - N days low :param df: data :param n_days: N days :return: None
[ "Williams", "Overbought", "/", "Oversold", "Index", "WMS", "=", "[", "(", "Hn—Ct", ")", "/", "(", "Hn—Ln", ")", "]", "×100", "Ct", "-", "the", "close", "price", "Hn", "-", "N", "days", "high", "Ln", "-", "N", "days", "low", ":", "param", "df", ":...
python
train
32.15
sernst/cauldron
cauldron/runner/__init__.py
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L15-L33
def add_library_path(path: str) -> bool: """ Adds the path to the Python system path if not already added and the path exists. :param path: The path to add to the system paths :return: Whether or not the path was added. Only returns False if the path was not added because it...
[ "def", "add_library_path", "(", "path", ":", "str", ")", "->", "bool", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "False", "if", "path", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "app...
Adds the path to the Python system path if not already added and the path exists. :param path: The path to add to the system paths :return: Whether or not the path was added. Only returns False if the path was not added because it doesn't exist
[ "Adds", "the", "path", "to", "the", "Python", "system", "path", "if", "not", "already", "added", "and", "the", "path", "exists", "." ]
python
train
24
RJT1990/pyflux
pyflux/families/poisson.py
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/poisson.py#L342-L366
def second_order_score(y, mean, scale, shape, skewness): """ GAS Poisson Update term potentially using second-order information - native Python function Parameters ---------- y : float datapoint for the time series mean : float location parameter for the...
[ "def", "second_order_score", "(", "y", ",", "mean", ",", "scale", ",", "shape", ",", "skewness", ")", ":", "return", "(", "y", "-", "mean", ")", "/", "float", "(", "mean", ")" ]
GAS Poisson Update term potentially using second-order information - native Python function Parameters ---------- y : float datapoint for the time series mean : float location parameter for the Poisson distribution scale : float scale parame...
[ "GAS", "Poisson", "Update", "term", "potentially", "using", "second", "-", "order", "information", "-", "native", "Python", "function" ]
python
train
28.12
DiamondLightSource/python-procrunner
procrunner/__init__.py
https://github.com/DiamondLightSource/python-procrunner/blob/e11c446f97f28abceb507d21403259757f08be0a/procrunner/__init__.py#L173-L202
def get_output(self): """ Retrieve the stored data in full. This call may block if the reading thread has not yet terminated. """ self._closing = True if not self.has_finished(): if self._debug: # Main thread overtook stream reading thread. ...
[ "def", "get_output", "(", "self", ")", ":", "self", ".", "_closing", "=", "True", "if", "not", "self", ".", "has_finished", "(", ")", ":", "if", "self", ".", "_debug", ":", "# Main thread overtook stream reading thread.", "underrun_debug_timer", "=", "timeit", ...
Retrieve the stored data in full. This call may block if the reading thread has not yet terminated.
[ "Retrieve", "the", "stored", "data", "in", "full", ".", "This", "call", "may", "block", "if", "the", "reading", "thread", "has", "not", "yet", "terminated", "." ]
python
train
39.133333
DerMitch/fritzbox-smarthome
fritzhome/__main__.py
https://github.com/DerMitch/fritzbox-smarthome/blob/84cbd7c1b33e6256add041b0395ff5fccc01f103/fritzhome/__main__.py#L223-L238
def logs(context, format): """Show system logs since last reboot""" fritz = context.obj fritz.login() messages = fritz.get_logs() if format == "plain": for msg in messages: merged = "{} {} {}".format(msg.date, msg.time, msg.message.encode("UTF-8")) click.echo(merged)...
[ "def", "logs", "(", "context", ",", "format", ")", ":", "fritz", "=", "context", ".", "obj", "fritz", ".", "login", "(", ")", "messages", "=", "fritz", ".", "get_logs", "(", ")", "if", "format", "==", "\"plain\"", ":", "for", "msg", "in", "messages",...
Show system logs since last reboot
[ "Show", "system", "logs", "since", "last", "reboot" ]
python
train
28.8125
ThreatConnect-Inc/tcex
tcex/tcex_logger.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_logger.py#L60-L72
def log_to_api(self): """Best effort API logger. Send logs to the ThreatConnect API and do nothing if the attempt fails. """ if self.entries: try: headers = {'Content-Type': 'application/json'} self.session.post('/v2/logs/app', headers=headers...
[ "def", "log_to_api", "(", "self", ")", ":", "if", "self", ".", "entries", ":", "try", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "self", ".", "session", ".", "post", "(", "'/v2/logs/app'", ",", "headers", "=", "headers", ...
Best effort API logger. Send logs to the ThreatConnect API and do nothing if the attempt fails.
[ "Best", "effort", "API", "logger", "." ]
python
train
36.692308
mardix/Mocha
mocha/contrib/auth/decorators.py
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/decorators.py#L203-L217
def accepts_moderator_roles(func): """ Decorator that accepts only moderator roles :param func: :return: """ if inspect.isclass(func): apply_function_to_members(func, accepts_moderator_roles) return func else: @functools.wraps(func) def decorator(*args, **kwar...
[ "def", "accepts_moderator_roles", "(", "func", ")", ":", "if", "inspect", ".", "isclass", "(", "func", ")", ":", "apply_function_to_members", "(", "func", ",", "accepts_moderator_roles", ")", "return", "func", "else", ":", "@", "functools", ".", "wraps", "(", ...
Decorator that accepts only moderator roles :param func: :return:
[ "Decorator", "that", "accepts", "only", "moderator", "roles", ":", "param", "func", ":", ":", "return", ":" ]
python
train
27.333333
ConsenSys/mythril-classic
mythril/mythril/mythril_leveldb.py
https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/mythril/mythril_leveldb.py#L41-L49
def contract_hash_to_address(self, contract_hash): """ Returns address of the corresponding hash by searching the leveldb :param contract_hash: Hash to be searched """ if not re.match(r"0x[a-fA-F0-9]{64}", contract_hash): raise CriticalError("Invalid address hash. Exp...
[ "def", "contract_hash_to_address", "(", "self", ",", "contract_hash", ")", ":", "if", "not", "re", ".", "match", "(", "r\"0x[a-fA-F0-9]{64}\"", ",", "contract_hash", ")", ":", "raise", "CriticalError", "(", "\"Invalid address hash. Expected format is '0x...'.\"", ")", ...
Returns address of the corresponding hash by searching the leveldb :param contract_hash: Hash to be searched
[ "Returns", "address", "of", "the", "corresponding", "hash", "by", "searching", "the", "leveldb", ":", "param", "contract_hash", ":", "Hash", "to", "be", "searched" ]
python
train
45.222222
aiortc/aiortc
aiortc/contrib/media.py
https://github.com/aiortc/aiortc/blob/60ed036abf4575bd63985724b4493d569e6da29b/aiortc/contrib/media.py#L329-L335
async def start(self): """ Start recording. """ for track, context in self.__tracks.items(): if context.task is None: context.task = asyncio.ensure_future(self.__run_track(track, context))
[ "async", "def", "start", "(", "self", ")", ":", "for", "track", ",", "context", "in", "self", ".", "__tracks", ".", "items", "(", ")", ":", "if", "context", ".", "task", "is", "None", ":", "context", ".", "task", "=", "asyncio", ".", "ensure_future",...
Start recording.
[ "Start", "recording", "." ]
python
train
34.571429
tensorflow/tensor2tensor
tensor2tensor/rl/rl_utils.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L806-L809
def set_initial_state(self, initial_state, initial_frames): """Sets the state that will be used on next reset.""" self.env.set_initial_state(initial_state, initial_frames) self._initial_frames = initial_frames
[ "def", "set_initial_state", "(", "self", ",", "initial_state", ",", "initial_frames", ")", ":", "self", ".", "env", ".", "set_initial_state", "(", "initial_state", ",", "initial_frames", ")", "self", ".", "_initial_frames", "=", "initial_frames" ]
Sets the state that will be used on next reset.
[ "Sets", "the", "state", "that", "will", "be", "used", "on", "next", "reset", "." ]
python
train
54.5
aestrivex/bctpy
bct/utils/visualization.py
https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/utils/visualization.py#L402-L473
def reorderMAT(m, H=5000, cost='line'): ''' This function reorders the connectivity matrix in order to place more edges closer to the diagonal. This often helps in displaying community structure, clusters, etc. Parameters ---------- MAT : NxN np.ndarray connection matrix H : int...
[ "def", "reorderMAT", "(", "m", ",", "H", "=", "5000", ",", "cost", "=", "'line'", ")", ":", "from", "scipy", "import", "linalg", ",", "stats", "m", "=", "m", ".", "copy", "(", ")", "n", "=", "len", "(", "m", ")", "np", ".", "fill_diagonal", "("...
This function reorders the connectivity matrix in order to place more edges closer to the diagonal. This often helps in displaying community structure, clusters, etc. Parameters ---------- MAT : NxN np.ndarray connection matrix H : int number of reordering attempts cost : st...
[ "This", "function", "reorders", "the", "connectivity", "matrix", "in", "order", "to", "place", "more", "edges", "closer", "to", "the", "diagonal", ".", "This", "often", "helps", "in", "displaying", "community", "structure", "clusters", "etc", "." ]
python
train
29.861111
T-002/pycast
pycast/methods/exponentialsmoothing.py
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/exponentialsmoothing.py#L347-L393
def execute(self, timeSeries): """Creates a new TimeSeries containing the smoothed values. :param TimeSeries timeSeries: TimeSeries containing hte data. :return: TimeSeries object containing the exponentially smoothed TimeSeries, including the forecasted values. :rtype: ...
[ "def", "execute", "(", "self", ",", "timeSeries", ")", ":", "# determine the number of values to forecast, if necessary", "self", ".", "_calculate_values_to_forecast", "(", "timeSeries", ")", "seasonLength", "=", "self", ".", "get_parameter", "(", "\"seasonLength\"", ")",...
Creates a new TimeSeries containing the smoothed values. :param TimeSeries timeSeries: TimeSeries containing hte data. :return: TimeSeries object containing the exponentially smoothed TimeSeries, including the forecasted values. :rtype: TimeSeries :note: Currently t...
[ "Creates", "a", "new", "TimeSeries", "containing", "the", "smoothed", "values", "." ]
python
train
40.957447
blockstack/blockstack-core
blockstack/lib/rpc.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L740-L760
def GET_zonefile(self, path_info, zonefile_hash): """ Get a raw zonefile Reply the zonefile as application/octet-stream Reply 404 if not found """ if not check_string(zonefile_hash, pattern=OP_ZONEFILE_HASH_PATTERN): return self._reply_json({'error': 'Invalid ...
[ "def", "GET_zonefile", "(", "self", ",", "path_info", ",", "zonefile_hash", ")", ":", "if", "not", "check_string", "(", "zonefile_hash", ",", "pattern", "=", "OP_ZONEFILE_HASH_PATTERN", ")", ":", "return", "self", ".", "_reply_json", "(", "{", "'error'", ":", ...
Get a raw zonefile Reply the zonefile as application/octet-stream Reply 404 if not found
[ "Get", "a", "raw", "zonefile", "Reply", "the", "zonefile", "as", "application", "/", "octet", "-", "stream", "Reply", "404", "if", "not", "found" ]
python
train
49.571429
anrosent/LT-code
lt/encode/__init__.py
https://github.com/anrosent/LT-code/blob/e13a4c927effc90f9d41ab3884f9fcbd95b9450d/lt/encode/__init__.py#L17-L43
def encoder(f, blocksize, seed=None, c=sampler.DEFAULT_C, delta=sampler.DEFAULT_DELTA): """Generates an infinite sequence of blocks to transmit to the receiver """ # Generate seed if not provided if seed is None: seed = randint(0, 1 << 31 - 1) # get file blocks filesize, blocks = _...
[ "def", "encoder", "(", "f", ",", "blocksize", ",", "seed", "=", "None", ",", "c", "=", "sampler", ".", "DEFAULT_C", ",", "delta", "=", "sampler", ".", "DEFAULT_DELTA", ")", ":", "# Generate seed if not provided", "if", "seed", "is", "None", ":", "seed", ...
Generates an infinite sequence of blocks to transmit to the receiver
[ "Generates", "an", "infinite", "sequence", "of", "blocks", "to", "transmit", "to", "the", "receiver" ]
python
train
30.962963
PmagPy/PmagPy
dialogs/grid_frame2.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame2.py#L765-L837
def make_grid(self, incl_pmag=True): """ return grid """ if incl_pmag and self.grid_type in self.er_magic.incl_pmag_data: incl_pmag = True else: incl_pmag = False er_header = self.grid_headers[self.grid_type]['er'][0] if incl_pmag: ...
[ "def", "make_grid", "(", "self", ",", "incl_pmag", "=", "True", ")", ":", "if", "incl_pmag", "and", "self", ".", "grid_type", "in", "self", ".", "er_magic", ".", "incl_pmag_data", ":", "incl_pmag", "=", "True", "else", ":", "incl_pmag", "=", "False", "er...
return grid
[ "return", "grid" ]
python
train
41.082192
ArchiveTeam/wpull
wpull/version.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/version.py#L23-L32
def get_version_tuple(string): '''Return a version tuple from a string.''' match = re.match(r'(\d+)\.(\d+)\.?(\d*)([abc]?)(\d*)', string) major = int(match.group(1)) minor = int(match.group(2)) patch = int(match.group(3) or 0) level = RELEASE_LEVEL_MAP.get(match.group(4), 'final') serial = i...
[ "def", "get_version_tuple", "(", "string", ")", ":", "match", "=", "re", ".", "match", "(", "r'(\\d+)\\.(\\d+)\\.?(\\d*)([abc]?)(\\d*)'", ",", "string", ")", "major", "=", "int", "(", "match", ".", "group", "(", "1", ")", ")", "minor", "=", "int", "(", "...
Return a version tuple from a string.
[ "Return", "a", "version", "tuple", "from", "a", "string", "." ]
python
train
38.1
google/grr
grr/server/grr_response_server/client_index.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/client_index.py#L510-L519
def AddClient(self, client): """Adds a client to the index. Args: client: A Client object record. """ keywords = self.AnalyzeClient(client) keywords.add(self._NormalizeKeyword(client.client_id)) data_store.REL_DB.AddClientKeywords(client.client_id, keywords)
[ "def", "AddClient", "(", "self", ",", "client", ")", ":", "keywords", "=", "self", ".", "AnalyzeClient", "(", "client", ")", "keywords", ".", "add", "(", "self", ".", "_NormalizeKeyword", "(", "client", ".", "client_id", ")", ")", "data_store", ".", "REL...
Adds a client to the index. Args: client: A Client object record.
[ "Adds", "a", "client", "to", "the", "index", "." ]
python
train
28.1
yunojuno/elasticsearch-django
elasticsearch_django/index.py
https://github.com/yunojuno/elasticsearch-django/blob/e8d98d32bcd77f1bedb8f1a22b6523ca44ffd489/elasticsearch_django/index.py#L10-L14
def create_index(index): """Create an index and apply mapping if appropriate.""" logger.info("Creating search index: '%s'", index) client = get_client() return client.indices.create(index=index, body=get_index_mapping(index))
[ "def", "create_index", "(", "index", ")", ":", "logger", ".", "info", "(", "\"Creating search index: '%s'\"", ",", "index", ")", "client", "=", "get_client", "(", ")", "return", "client", ".", "indices", ".", "create", "(", "index", "=", "index", ",", "bod...
Create an index and apply mapping if appropriate.
[ "Create", "an", "index", "and", "apply", "mapping", "if", "appropriate", "." ]
python
train
47.4
cuihantao/andes
andes/utils/math.py
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L107-L115
def sort(m, reverse=False): """Return sorted m (default: ascending order)""" ty = type(m) if ty == matrix: m = list(m) m = sorted(m, reverse=reverse) if ty == matrix: m = matrix(m) return m
[ "def", "sort", "(", "m", ",", "reverse", "=", "False", ")", ":", "ty", "=", "type", "(", "m", ")", "if", "ty", "==", "matrix", ":", "m", "=", "list", "(", "m", ")", "m", "=", "sorted", "(", "m", ",", "reverse", "=", "reverse", ")", "if", "t...
Return sorted m (default: ascending order)
[ "Return", "sorted", "m", "(", "default", ":", "ascending", "order", ")" ]
python
train
24.555556
saltstack/salt
salt/modules/virt.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2966-L2994
def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :par...
[ "def", "create_xml_path", "(", "path", ",", "*", "*", "kwargs", ")", ":", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "path", ",", "'r'", ")", "as", "fp_", ":", "return", "create_xml_str", "(", "salt", ".", "utils", "...
Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding...
[ "Start", "a", "transient", "domain", "based", "on", "the", "XML", "-", "file", "path", "passed", "to", "the", "function" ]
python
train
29.793103
vtkiorg/vtki
vtki/pointset.py
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2426-L2430
def dimensions(self, dims): """Sets the dataset dimensions. Pass a length three tuple of integers""" nx, ny, nz = dims[0], dims[1], dims[2] self.SetDimensions(nx, ny, nz) self.Modified()
[ "def", "dimensions", "(", "self", ",", "dims", ")", ":", "nx", ",", "ny", ",", "nz", "=", "dims", "[", "0", "]", ",", "dims", "[", "1", "]", ",", "dims", "[", "2", "]", "self", ".", "SetDimensions", "(", "nx", ",", "ny", ",", "nz", ")", "se...
Sets the dataset dimensions. Pass a length three tuple of integers
[ "Sets", "the", "dataset", "dimensions", ".", "Pass", "a", "length", "three", "tuple", "of", "integers" ]
python
train
42.8
opengridcc/opengrid
opengrid/datasets/datasets.py
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/datasets/datasets.py#L27-L40
def add(self, path): """ Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str """ name_with_ext = os.path.split(path)[1] # spli...
[ "def", "add", "(", "self", ",", "path", ")", ":", "name_with_ext", "=", "os", ".", "path", ".", "split", "(", "path", ")", "[", "1", "]", "# split directory and filename", "name", "=", "name_with_ext", ".", "split", "(", "'.'", ")", "[", "0", "]", "#...
Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str
[ "Add", "the", "path", "of", "a", "data", "set", "to", "the", "list", "of", "available", "sets" ]
python
train
30.928571
rm-hull/luma.core
luma/core/sprite_system.py
https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/sprite_system.py#L132-L162
def animate(self, seq_name): """ Returns a generator which "executes" an animation sequence for the given ``seq_name``, inasmuch as the next frame for the given animation is yielded when requested. :param seq_name: The name of a previously defined animation sequence. :ty...
[ "def", "animate", "(", "self", ",", "seq_name", ")", ":", "while", "True", ":", "index", "=", "0", "anim", "=", "getattr", "(", "self", ".", "animations", ",", "seq_name", ")", "speed", "=", "anim", ".", "speed", "if", "hasattr", "(", "anim", ",", ...
Returns a generator which "executes" an animation sequence for the given ``seq_name``, inasmuch as the next frame for the given animation is yielded when requested. :param seq_name: The name of a previously defined animation sequence. :type seq_name: str :returns: A generator th...
[ "Returns", "a", "generator", "which", "executes", "an", "animation", "sequence", "for", "the", "given", "seq_name", "inasmuch", "as", "the", "next", "frame", "for", "the", "given", "animation", "is", "yielded", "when", "requested", "." ]
python
train
35.548387
pandas-dev/pandas
pandas/core/indexing.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L914-L933
def _multi_take(self, tup): """ Create the indexers for the passed tuple of keys, and execute the take operation. This allows the take operation to be executed all at once - rather than once for each dimension - improving efficiency. Parameters ---------- tup : t...
[ "def", "_multi_take", "(", "self", ",", "tup", ")", ":", "# GH 836", "o", "=", "self", ".", "obj", "d", "=", "{", "axis", ":", "self", ".", "_get_listlike_indexer", "(", "key", ",", "axis", ")", "for", "(", "key", ",", "axis", ")", "in", "zip", "...
Create the indexers for the passed tuple of keys, and execute the take operation. This allows the take operation to be executed all at once - rather than once for each dimension - improving efficiency. Parameters ---------- tup : tuple Tuple of indexers, one per axis...
[ "Create", "the", "indexers", "for", "the", "passed", "tuple", "of", "keys", "and", "execute", "the", "take", "operation", ".", "This", "allows", "the", "take", "operation", "to", "be", "executed", "all", "at", "once", "-", "rather", "than", "once", "for", ...
python
train
33.6
calston/tensor
tensor/outputs/riemann.py
https://github.com/calston/tensor/blob/7c0c99708b5dbff97f3895f705e11996b608549d/tensor/outputs/riemann.py#L145-L160
def emptyQueue(self): """Remove all or self.queueDepth events from the queue """ if self.events: if self.queueDepth and (len(self.events) > self.queueDepth): # Remove maximum of self.queueDepth items from queue events = self.events[:self.queueDepth] ...
[ "def", "emptyQueue", "(", "self", ")", ":", "if", "self", ".", "events", ":", "if", "self", ".", "queueDepth", "and", "(", "len", "(", "self", ".", "events", ")", ">", "self", ".", "queueDepth", ")", ":", "# Remove maximum of self.queueDepth items from queue...
Remove all or self.queueDepth events from the queue
[ "Remove", "all", "or", "self", ".", "queueDepth", "events", "from", "the", "queue" ]
python
test
40.3125
hendrix/hendrix
hendrix/ux.py
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/ux.py#L100-L118
def logReload(options): """ encompasses all the logic for reloading observer. """ event_handler = Reload(options) observer = Observer() observer.schedule(event_handler, path='.', recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterr...
[ "def", "logReload", "(", "options", ")", ":", "event_handler", "=", "Reload", "(", "options", ")", "observer", "=", "Observer", "(", ")", "observer", ".", "schedule", "(", "event_handler", ",", "path", "=", "'.'", ",", "recursive", "=", "True", ")", "obs...
encompasses all the logic for reloading observer.
[ "encompasses", "all", "the", "logic", "for", "reloading", "observer", "." ]
python
train
25.947368
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L10549-L10565
def attitude_target_send(self, time_boot_ms, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust, force_mavlink1=False): ''' Reports the current commanded attitude of the vehicle as specified by the autopilot. This should match the commands sent in ...
[ "def", "attitude_target_send", "(", "self", ",", "time_boot_ms", ",", "type_mask", ",", "q", ",", "body_roll_rate", ",", "body_pitch_rate", ",", "body_yaw_rate", ",", "thrust", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", ...
Reports the current commanded attitude of the vehicle as specified by the autopilot. This should match the commands sent in a SET_ATTITUDE_TARGET message if the vehicle is being controlled this way. time_boot_ms : Timestamp in milliseconds si...
[ "Reports", "the", "current", "commanded", "attitude", "of", "the", "vehicle", "as", "specified", "by", "the", "autopilot", ".", "This", "should", "match", "the", "commands", "sent", "in", "a", "SET_ATTITUDE_TARGET", "message", "if", "the", "vehicle", "is", "be...
python
train
86.705882
Dallinger/Dallinger
dallinger/command_line.py
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L796-L808
def verify(): """Verify that app is compatible with Dallinger.""" verbose = True log( "Verifying current directory as a Dallinger experiment...", delay=0, verbose=verbose, ) ok = verify_package(verbose=verbose) if ok: log("✓ Everything looks good!", delay=0, verbo...
[ "def", "verify", "(", ")", ":", "verbose", "=", "True", "log", "(", "\"Verifying current directory as a Dallinger experiment...\"", ",", "delay", "=", "0", ",", "verbose", "=", "verbose", ",", ")", "ok", "=", "verify_package", "(", "verbose", "=", "verbose", "...
Verify that app is compatible with Dallinger.
[ "Verify", "that", "app", "is", "compatible", "with", "Dallinger", "." ]
python
train
30.615385
Shinichi-Nakagawa/pitchpx
pitchpx/game/boxscore.py
https://github.com/Shinichi-Nakagawa/pitchpx/blob/5747402a0b3416f5e910b479e100df858f0b6440/pitchpx/game/boxscore.py#L145-L156
def _get_batting_order_starting_flg(cls, batter): """ get batting order and starting member flg :param batter: Beautifulsoup object(batter element) :return: batting order(1-9), starting member flg(True or False) """ bo = batter.get('bo', None) if not bo or len(bo)...
[ "def", "_get_batting_order_starting_flg", "(", "cls", ",", "batter", ")", ":", "bo", "=", "batter", ".", "get", "(", "'bo'", ",", "None", ")", "if", "not", "bo", "or", "len", "(", "bo", ")", "!=", "3", ":", "return", "False", ",", "False", "batting_o...
get batting order and starting member flg :param batter: Beautifulsoup object(batter element) :return: batting order(1-9), starting member flg(True or False)
[ "get", "batting", "order", "and", "starting", "member", "flg", ":", "param", "batter", ":", "Beautifulsoup", "object", "(", "batter", "element", ")", ":", "return", ":", "batting", "order", "(", "1", "-", "9", ")", "starting", "member", "flg", "(", "True...
python
train
39.25
weso/CWR-DataApi
cwr/parser/decoder/file.py
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/parser/decoder/file.py#L287-L310
def decode(self, data): """ Parses the file, creating a CWRFile from it. It requires a dictionary with two values: - filename, containing the filename - contents, containing the file contents :param data: dictionary with the data to parse :return: a CWRFile inst...
[ "def", "decode", "(", "self", ",", "data", ")", ":", "file_name", "=", "self", ".", "_filename_decoder", ".", "decode", "(", "data", "[", "'filename'", "]", ")", "file_data", "=", "data", "[", "'contents'", "]", "i", "=", "0", "max_size", "=", "len", ...
Parses the file, creating a CWRFile from it. It requires a dictionary with two values: - filename, containing the filename - contents, containing the file contents :param data: dictionary with the data to parse :return: a CWRFile instance
[ "Parses", "the", "file", "creating", "a", "CWRFile", "from", "it", "." ]
python
train
30.291667
dw/mitogen
mitogen/core.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/core.py#L1622-L1631
def on_receive(self, broker): """Handle the next complete message on the stream. Raise :class:`StreamError` on failure.""" _vv and IOLOG.debug('%r.on_receive()', self) buf = self.receive_side.read() if not buf: return self.on_disconnect(broker) self._interna...
[ "def", "on_receive", "(", "self", ",", "broker", ")", ":", "_vv", "and", "IOLOG", ".", "debug", "(", "'%r.on_receive()'", ",", "self", ")", "buf", "=", "self", ".", "receive_side", ".", "read", "(", ")", "if", "not", "buf", ":", "return", "self", "."...
Handle the next complete message on the stream. Raise :class:`StreamError` on failure.
[ "Handle", "the", "next", "complete", "message", "on", "the", "stream", ".", "Raise", ":", "class", ":", "StreamError", "on", "failure", "." ]
python
train
33.3
ambitioninc/django-manager-utils
manager_utils/manager_utils.py
https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L599-L664
def upsert(manager, defaults=None, updates=None, **kwargs): """ Performs an update on an object or an insert if the object does not exist. :type defaults: dict :param defaults: These values are set when the object is created, but are irrelevant when the object already exists. This field sho...
[ "def", "upsert", "(", "manager", ",", "defaults", "=", "None", ",", "updates", "=", "None", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "defaults", "or", "{", "}", "# Override any defaults with updates", "defaults", ".", "update", "(", "updates", "...
Performs an update on an object or an insert if the object does not exist. :type defaults: dict :param defaults: These values are set when the object is created, but are irrelevant when the object already exists. This field should only be used when values only need to be set during crea...
[ "Performs", "an", "update", "on", "an", "object", "or", "an", "insert", "if", "the", "object", "does", "not", "exist", "." ]
python
train
39.666667
autokey/autokey
lib/autokey/qtui/configwindow.py
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/configwindow.py#L146-L163
def _set_platform_specific_keyboard_shortcuts(self): """ QtDesigner does not support QKeySequence::StandardKey enum based default keyboard shortcuts. This means that all default key combinations ("Save", "Quit", etc) have to be defined in code. """ self.action_new_phrase.setShort...
[ "def", "_set_platform_specific_keyboard_shortcuts", "(", "self", ")", ":", "self", ".", "action_new_phrase", ".", "setShortcuts", "(", "QKeySequence", ".", "New", ")", "self", ".", "action_save", ".", "setShortcuts", "(", "QKeySequence", ".", "Save", ")", "self", ...
QtDesigner does not support QKeySequence::StandardKey enum based default keyboard shortcuts. This means that all default key combinations ("Save", "Quit", etc) have to be defined in code.
[ "QtDesigner", "does", "not", "support", "QKeySequence", "::", "StandardKey", "enum", "based", "default", "keyboard", "shortcuts", ".", "This", "means", "that", "all", "default", "key", "combinations", "(", "Save", "Quit", "etc", ")", "have", "to", "be", "defin...
python
train
52.777778
spulec/moto
moto/cloudwatch/models.py
https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/cloudwatch/models.py#L23-L48
def daterange(start, stop, step=timedelta(days=1), inclusive=False): """ This method will iterate from `start` to `stop` datetimes with a timedelta step of `step` (supports iteration forwards or backwards in time) :param start: start datetime :param stop: end datetime :param step: step size as ...
[ "def", "daterange", "(", "start", ",", "stop", ",", "step", "=", "timedelta", "(", "days", "=", "1", ")", ",", "inclusive", "=", "False", ")", ":", "# inclusive=False to behave like range by default", "total_step_secs", "=", "step", ".", "total_seconds", "(", ...
This method will iterate from `start` to `stop` datetimes with a timedelta step of `step` (supports iteration forwards or backwards in time) :param start: start datetime :param stop: end datetime :param step: step size as a timedelta :param inclusive: if True, last item returned will be as step clo...
[ "This", "method", "will", "iterate", "from", "start", "to", "stop", "datetimes", "with", "a", "timedelta", "step", "of", "step", "(", "supports", "iteration", "forwards", "or", "backwards", "in", "time", ")" ]
python
train
31.576923
ternaris/marv
marv/cli.py
https://github.com/ternaris/marv/blob/c221354d912ff869bbdb4f714a86a70be30d823e/marv/cli.py#L463-L471
def marvcli_tag(ctx, add, remove, datasets): """Add or remove tags to datasets""" if not any([add, remove]) or not datasets: click.echo(ctx.get_help()) ctx.exit(1) app = create_app() setids = parse_setids(datasets) app.site.tag(setids, add, remove)
[ "def", "marvcli_tag", "(", "ctx", ",", "add", ",", "remove", ",", "datasets", ")", ":", "if", "not", "any", "(", "[", "add", ",", "remove", "]", ")", "or", "not", "datasets", ":", "click", ".", "echo", "(", "ctx", ".", "get_help", "(", ")", ")", ...
Add or remove tags to datasets
[ "Add", "or", "remove", "tags", "to", "datasets" ]
python
train
30.777778
elliterate/capybara.py
capybara/queries/text_query.py
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/text_query.py#L68-L84
def resolve_for(self, node): """ Resolves this query relative to the given node. Args: node (node.Base): The node to be evaluated. Returns: int: The number of matches found. """ self.node = node self.actual_text = normalize_text( ...
[ "def", "resolve_for", "(", "self", ",", "node", ")", ":", "self", ".", "node", "=", "node", "self", ".", "actual_text", "=", "normalize_text", "(", "node", ".", "visible_text", "if", "self", ".", "query_type", "==", "\"visible\"", "else", "node", ".", "a...
Resolves this query relative to the given node. Args: node (node.Base): The node to be evaluated. Returns: int: The number of matches found.
[ "Resolves", "this", "query", "relative", "to", "the", "given", "node", "." ]
python
test
28.235294
llazzaro/analyzerdam
analyzerdam/sqlDAM.py
https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L167-L174
def write_ticks(self, ticks): ''' write ticks ''' if self.first: Base.metadata.create_all(self.engine, checkfirst=True) self.first=False session=self.getWriteSession() session.add_all([self.__tickToSql(tick) for tick in ticks])
[ "def", "write_ticks", "(", "self", ",", "ticks", ")", ":", "if", "self", ".", "first", ":", "Base", ".", "metadata", ".", "create_all", "(", "self", ".", "engine", ",", "checkfirst", "=", "True", ")", "self", ".", "first", "=", "False", "session", "=...
write ticks
[ "write", "ticks" ]
python
train
35.5
sarugaku/vistir
src/vistir/compat.py
https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/compat.py#L205-L216
def is_bytes(string): """Check if a string is a bytes instance :param Union[str, bytes] string: A string that may be string or bytes like :return: Whether the provided string is a bytes type or not :rtype: bool """ if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)): # noqa ...
[ "def", "is_bytes", "(", "string", ")", ":", "if", "six", ".", "PY3", "and", "isinstance", "(", "string", ",", "(", "bytes", ",", "memoryview", ",", "bytearray", ")", ")", ":", "# noqa", "return", "True", "elif", "six", ".", "PY2", "and", "isinstance", ...
Check if a string is a bytes instance :param Union[str, bytes] string: A string that may be string or bytes like :return: Whether the provided string is a bytes type or not :rtype: bool
[ "Check", "if", "a", "string", "is", "a", "bytes", "instance" ]
python
train
35.833333
PGower/PyCanvas
pycanvas/apis/communication_channels.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/communication_channels.py#L37-L81
def create_communication_channel(self, user_id, communication_channel_type, communication_channel_address, communication_channel_token=None, skip_confirmation=None): """ Create a communication channel. Creates a new communication channel for the specified user. """ path = ...
[ "def", "create_communication_channel", "(", "self", ",", "user_id", ",", "communication_channel_type", ",", "communication_channel_address", ",", "communication_channel_token", "=", "None", ",", "skip_confirmation", "=", "None", ")", ":", "path", "=", "{", "}", "data"...
Create a communication channel. Creates a new communication channel for the specified user.
[ "Create", "a", "communication", "channel", ".", "Creates", "a", "new", "communication", "channel", "for", "the", "specified", "user", "." ]
python
train
51.8
dagwieers/vmguestlib
vmguestlib.py
https://github.com/dagwieers/vmguestlib/blob/2ba9333a745628cf9e6b4c767427a5bd997a71ad/vmguestlib.py#L442-L447
def GetMemZippedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemZippedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
[ "def", "GetMemZippedMB", "(", "self", ")", ":", "counter", "=", "c_uint", "(", ")", "ret", "=", "vmGuestLib", ".", "VMGuestLib_GetMemZippedMB", "(", "self", ".", "handle", ".", "value", ",", "byref", "(", "counter", ")", ")", "if", "ret", "!=", "VMGUESTL...
Undocumented.
[ "Undocumented", "." ]
python
train
44.166667
GoogleCloudPlatform/datastore-ndb-python
ndb/blobstore.py
https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L293-L298
def delete_multi_async(blob_keys, **options): """Async version of delete_multi().""" if isinstance(blob_keys, (basestring, BlobKey)): raise TypeError('Expected a list, got %r' % (blob_key,)) rpc = blobstore.create_rpc(**options) yield blobstore.delete_async(blob_keys, rpc=rpc)
[ "def", "delete_multi_async", "(", "blob_keys", ",", "*", "*", "options", ")", ":", "if", "isinstance", "(", "blob_keys", ",", "(", "basestring", ",", "BlobKey", ")", ")", ":", "raise", "TypeError", "(", "'Expected a list, got %r'", "%", "(", "blob_key", ",",...
Async version of delete_multi().
[ "Async", "version", "of", "delete_multi", "()", "." ]
python
train
47.333333
Kane610/deconz
pydeconz/sensor.py
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/sensor.py#L1012-L1047
def create_sensor(sensor_id, sensor, async_set_state_callback): """Simplify creating sensor by not needing to know type.""" if sensor['type'] in CONSUMPTION: return Consumption(sensor_id, sensor) if sensor['type'] in CARBONMONOXIDE: return CarbonMonoxide(sensor_id, sensor) if sensor['typ...
[ "def", "create_sensor", "(", "sensor_id", ",", "sensor", ",", "async_set_state_callback", ")", ":", "if", "sensor", "[", "'type'", "]", "in", "CONSUMPTION", ":", "return", "Consumption", "(", "sensor_id", ",", "sensor", ")", "if", "sensor", "[", "'type'", "]...
Simplify creating sensor by not needing to know type.
[ "Simplify", "creating", "sensor", "by", "not", "needing", "to", "know", "type", "." ]
python
train
40.888889
iLampard/x-utils
xutils/date_utils/misc.py
https://github.com/iLampard/x-utils/blob/291d92832ee0e0c89bc22e10ecf2f44445e0d300/xutils/date_utils/misc.py#L8-L22
def is_within_hour_range(ref_time, start_time, end_time): """ :param ref_time: datetime/string, 需要判断的时间变量 :param start_time: string, 时间区间上限 :param end_time: string, 时间下限 :return: 判断某个时间是否在限定的时间范围内 """ str_ref_time = ref_time.strftime('%Y%m%d') start_time_ = mktime(strptime(str_ref_time +...
[ "def", "is_within_hour_range", "(", "ref_time", ",", "start_time", ",", "end_time", ")", ":", "str_ref_time", "=", "ref_time", ".", "strftime", "(", "'%Y%m%d'", ")", "start_time_", "=", "mktime", "(", "strptime", "(", "str_ref_time", "+", "'-'", "+", "start_ti...
:param ref_time: datetime/string, 需要判断的时间变量 :param start_time: string, 时间区间上限 :param end_time: string, 时间下限 :return: 判断某个时间是否在限定的时间范围内
[ ":", "param", "ref_time", ":", "datetime", "/", "string", "需要判断的时间变量", ":", "param", "start_time", ":", "string", "时间区间上限", ":", "param", "end_time", ":", "string", "时间下限", ":", "return", ":", "判断某个时间是否在限定的时间范围内" ]
python
train
37.533333
raphaelm/python-sepaxml
sepaxml/transfer.py
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/transfer.py#L207-L260
def _add_non_batch(self, TX_nodes, PmtInf_nodes): """ Method to add a transaction as non batch, will fold the transaction together with the payment info node and append to the main xml. """ PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtInfIdNode']) PmtInf_nodes['PmtI...
[ "def", "_add_non_batch", "(", "self", ",", "TX_nodes", ",", "PmtInf_nodes", ")", ":", "PmtInf_nodes", "[", "'PmtInfNode'", "]", ".", "append", "(", "PmtInf_nodes", "[", "'PmtInfIdNode'", "]", ")", "PmtInf_nodes", "[", "'PmtInfNode'", "]", ".", "append", "(", ...
Method to add a transaction as non batch, will fold the transaction together with the payment info node and append to the main xml.
[ "Method", "to", "add", "a", "transaction", "as", "non", "batch", "will", "fold", "the", "transaction", "together", "with", "the", "payment", "info", "node", "and", "append", "to", "the", "main", "xml", "." ]
python
train
52.592593
frnmst/md-toc
md_toc/__main__.py
https://github.com/frnmst/md-toc/blob/86d2002ecf52fa9e1e5316a31f7eb7d549cb0830/md_toc/__main__.py#L28-L41
def main(args=None): """Call the CLI interface and wait for the result.""" retcode = 0 try: ci = CliInterface() args = ci.parser.parse_args() result = args.func(args) if result is not None: print(result) retcode = 0 except Exception: retcode = ...
[ "def", "main", "(", "args", "=", "None", ")", ":", "retcode", "=", "0", "try", ":", "ci", "=", "CliInterface", "(", ")", "args", "=", "ci", ".", "parser", ".", "parse_args", "(", ")", "result", "=", "args", ".", "func", "(", "args", ")", "if", ...
Call the CLI interface and wait for the result.
[ "Call", "the", "CLI", "interface", "and", "wait", "for", "the", "result", "." ]
python
train
25.714286
kmmbvnr/django-any
django_any/models.py
https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L182-L194
def any_email_field(field, **kwargs): """ Return random value for EmailField >>> result = any_field(models.EmailField()) >>> type(result) <type 'str'> >>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None True """ retu...
[ "def", "any_email_field", "(", "field", ",", "*", "*", "kwargs", ")", ":", "return", "\"%s@%s.%s\"", "%", "(", "xunit", ".", "any_string", "(", "max_length", "=", "10", ")", ",", "xunit", ".", "any_string", "(", "max_length", "=", "10", ")", ",", "xuni...
Return random value for EmailField >>> result = any_field(models.EmailField()) >>> type(result) <type 'str'> >>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None True
[ "Return", "random", "value", "for", "EmailField", ">>>", "result", "=", "any_field", "(", "models", ".", "EmailField", "()", ")", ">>>", "type", "(", "result", ")", "<type", "str", ">", ">>>", "re", ".", "match", "(", "r", "(", "?", ":", "^|", "\\", ...
python
test
37.538462