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
limpyd/redis-limpyd-jobs
limpyd_jobs/models.py
https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/models.py#L51-L84
def get_queue(cls, name, priority=0, **fields_if_new): """ Get, or create, and return the wanted queue. If the queue is created, fields in fields_if_new will be set for the new queue. """ queue_kwargs = {'name': name, 'priority': priority} retries = 0 whil...
[ "def", "get_queue", "(", "cls", ",", "name", ",", "priority", "=", "0", ",", "*", "*", "fields_if_new", ")", ":", "queue_kwargs", "=", "{", "'name'", ":", "name", ",", "'priority'", ":", "priority", "}", "retries", "=", "0", "while", "retries", "<", ...
Get, or create, and return the wanted queue. If the queue is created, fields in fields_if_new will be set for the new queue.
[ "Get", "or", "create", "and", "return", "the", "wanted", "queue", ".", "If", "the", "queue", "is", "created", "fields", "in", "fields_if_new", "will", "be", "set", "for", "the", "new", "queue", "." ]
python
train
34.882353
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L1177-L1179
def _to_chimera(M, N, L, q): "Converts a qubit's linear index to chimera coordinates." return (q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L)
[ "def", "_to_chimera", "(", "M", ",", "N", ",", "L", ",", "q", ")", ":", "return", "(", "q", "//", "N", "//", "L", "//", "2", ",", "(", "q", "//", "L", "//", "2", ")", "%", "N", ",", "(", "q", "//", "L", ")", "%", "2", ",", "q", "%", ...
Converts a qubit's linear index to chimera coordinates.
[ "Converts", "a", "qubit", "s", "linear", "index", "to", "chimera", "coordinates", "." ]
python
train
52.666667
sdispater/poetry
poetry/version/__init__.py
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/version/__init__.py#L28-L44
def parse( version, strict=False # type: str # type: bool ): # type:(...) -> Union[Version, LegacyVersion] """ Parse the given version string and return either a :class:`Version` object or a LegacyVersion object depending on if the given version is a valid PEP 440 version or a legacy version. ...
[ "def", "parse", "(", "version", ",", "strict", "=", "False", "# type: str # type: bool", ")", ":", "# type:(...) -> Union[Version, LegacyVersion]", "try", ":", "return", "Version", "(", "version", ")", "except", "InvalidVersion", ":", "if", "strict", ":", "raise", ...
Parse the given version string and return either a :class:`Version` object or a LegacyVersion object depending on if the given version is a valid PEP 440 version or a legacy version. If strict=True only PEP 440 versions will be accepted.
[ "Parse", "the", "given", "version", "string", "and", "return", "either", "a", ":", "class", ":", "Version", "object", "or", "a", "LegacyVersion", "object", "depending", "on", "if", "the", "given", "version", "is", "a", "valid", "PEP", "440", "version", "or...
python
train
30.117647
edeposit/edeposit.amqp.ftp
src/edeposit/amqp/ftp/settings.py
https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/settings.py#L149-L164
def get_all_constants(): """ Get list of all uppercase, non-private globals (doesn't start with ``_``). Returns: list: Uppercase names defined in `globals()` (variables from this \ module). """ return filter( lambda key: key.upper() == key and type(globals()[key]) in _...
[ "def", "get_all_constants", "(", ")", ":", "return", "filter", "(", "lambda", "key", ":", "key", ".", "upper", "(", ")", "==", "key", "and", "type", "(", "globals", "(", ")", "[", "key", "]", ")", "in", "_ALLOWED", ",", "filter", "(", "# filter _PRIV...
Get list of all uppercase, non-private globals (doesn't start with ``_``). Returns: list: Uppercase names defined in `globals()` (variables from this \ module).
[ "Get", "list", "of", "all", "uppercase", "non", "-", "private", "globals", "(", "doesn", "t", "start", "with", "_", ")", "." ]
python
train
29.4375
rflamary/POT
ot/utils.py
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L388-L413
def _get_param_names(cls): """Get parameter names for the estimator""" # fetch the constructor or the original constructor before # deprecation wrapping if any init = getattr(cls.__init__, 'deprecated_original', cls.__init__) if init is object.__init__: # No explicit...
[ "def", "_get_param_names", "(", "cls", ")", ":", "# fetch the constructor or the original constructor before", "# deprecation wrapping if any", "init", "=", "getattr", "(", "cls", ".", "__init__", ",", "'deprecated_original'", ",", "cls", ".", "__init__", ")", "if", "in...
Get parameter names for the estimator
[ "Get", "parameter", "names", "for", "the", "estimator" ]
python
train
49.115385
jreese/tasky
tasky/loop.py
https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L158-L173
def run_for_time(self, duration: float=10.0) -> None: '''Execute the tasky/asyncio event loop for `duration` seconds.''' Log.debug('running event loop for %.1f seconds', duration) try: asyncio.ensure_future(self.init()) self.loop.run_until_complete(asyncio.sleep(duration...
[ "def", "run_for_time", "(", "self", ",", "duration", ":", "float", "=", "10.0", ")", "->", "None", ":", "Log", ".", "debug", "(", "'running event loop for %.1f seconds'", ",", "duration", ")", "try", ":", "asyncio", ".", "ensure_future", "(", "self", ".", ...
Execute the tasky/asyncio event loop for `duration` seconds.
[ "Execute", "the", "tasky", "/", "asyncio", "event", "loop", "for", "duration", "seconds", "." ]
python
train
33.75
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_openflow.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_openflow.py#L12-L21
def openflow_controller_controller_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") openflow_controller = ET.SubElement(config, "openflow-controller", xmlns="urn:brocade.com:mgmt:brocade-openflow") controller_name = ET.SubElement(openflow_controller,...
[ "def", "openflow_controller_controller_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "openflow_controller", "=", "ET", ".", "SubElement", "(", "config", ",", "\"openflow-controller\"", ",", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
48.2
ocaballeror/LyricFetch
lyricfetch/run.py
https://github.com/ocaballeror/LyricFetch/blob/86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb/lyricfetch/run.py#L213-L247
def run_mp(songs): """ Concurrently calls get_lyrics to fetch the lyrics of a large list of songs. """ stats = Stats() if CONFIG['debug']: good = open('found', 'w') bad = open('notfound', 'w') logger.debug('Launching a pool of %d processes\n', CONFIG['jobcount']) chunksize =...
[ "def", "run_mp", "(", "songs", ")", ":", "stats", "=", "Stats", "(", ")", "if", "CONFIG", "[", "'debug'", "]", ":", "good", "=", "open", "(", "'found'", ",", "'w'", ")", "bad", "=", "open", "(", "'notfound'", ",", "'w'", ")", "logger", ".", "debu...
Concurrently calls get_lyrics to fetch the lyrics of a large list of songs.
[ "Concurrently", "calls", "get_lyrics", "to", "fetch", "the", "lyrics", "of", "a", "large", "list", "of", "songs", "." ]
python
train
32.085714
miguelgrinberg/python-socketio
socketio/packet.py
https://github.com/miguelgrinberg/python-socketio/blob/c0c1bf8d21e3597389b18938550a0724dd9676b7/socketio/packet.py#L165-L179
def _data_is_binary(self, data): """Check if the data contains binary components.""" if isinstance(data, six.binary_type): return True elif isinstance(data, list): return functools.reduce( lambda a, b: a or b, [self._data_is_binary(item) ...
[ "def", "_data_is_binary", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "six", ".", "binary_type", ")", ":", "return", "True", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "return", "functools", ".", "reduce", "...
Check if the data contains binary components.
[ "Check", "if", "the", "data", "contains", "binary", "components", "." ]
python
train
41.666667
a1ezzz/wasp-general
wasp_general/config.py
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L184-L192
def select_options(self, options_prefix): """ Select options from this selection, that are started with the specified prefix :param options_prefix: name prefix of options that should be selected :return: WConfigSelection """ return WConfigSelection( self.config(), self.section(), self.option_prefix() + op...
[ "def", "select_options", "(", "self", ",", "options_prefix", ")", ":", "return", "WConfigSelection", "(", "self", ".", "config", "(", ")", ",", "self", ".", "section", "(", ")", ",", "self", ".", "option_prefix", "(", ")", "+", "options_prefix", ")" ]
Select options from this selection, that are started with the specified prefix :param options_prefix: name prefix of options that should be selected :return: WConfigSelection
[ "Select", "options", "from", "this", "selection", "that", "are", "started", "with", "the", "specified", "prefix" ]
python
train
36.444444
saltstack/salt
salt/modules/zpool.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1108-L1148
def create_file_vdev(size, *vdevs): ''' Creates file based virtual devices for a zpool CLI Example: .. code-block:: bash salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...] .. note:: Depending on file size, the above command may take a while to return. ...
[ "def", "create_file_vdev", "(", "size", ",", "*", "vdevs", ")", ":", "ret", "=", "OrderedDict", "(", ")", "err", "=", "OrderedDict", "(", ")", "_mkfile_cmd", "=", "salt", ".", "utils", ".", "path", ".", "which", "(", "'mkfile'", ")", "for", "vdev", "...
Creates file based virtual devices for a zpool CLI Example: .. code-block:: bash salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...] .. note:: Depending on file size, the above command may take a while to return.
[ "Creates", "file", "based", "virtual", "devices", "for", "a", "zpool" ]
python
train
26.268293
wdecoster/NanoPlot
nanoplot/NanoPlot.py
https://github.com/wdecoster/NanoPlot/blob/d1601076731df2a07020316bd159b544f497a606/nanoplot/NanoPlot.py#L441-L488
def make_report(plots, settings): ''' Creates a fat html report based on the previously created files plots is a list of Plot objects defined by a path and title statsfile is the file to which the stats have been saved, which is parsed to a table (rather dodgy) ''' logging.info("Writing html...
[ "def", "make_report", "(", "plots", ",", "settings", ")", ":", "logging", ".", "info", "(", "\"Writing html report.\"", ")", "html_content", "=", "[", "'<body>'", "]", "# Hyperlink Table of Contents panel", "html_content", ".", "append", "(", "'<div class=\"panel pane...
Creates a fat html report based on the previously created files plots is a list of Plot objects defined by a path and title statsfile is the file to which the stats have been saved, which is parsed to a table (rather dodgy)
[ "Creates", "a", "fat", "html", "report", "based", "on", "the", "previously", "created", "files", "plots", "is", "a", "list", "of", "Plot", "objects", "defined", "by", "a", "path", "and", "title", "statsfile", "is", "the", "file", "to", "which", "the", "s...
python
train
47.541667
relwell/corenlp-xml-lib
corenlp_xml/coreference.py
https://github.com/relwell/corenlp-xml-lib/blob/9b0f8c912ba3ecedd34473f74a9f2d033a75baf9/corenlp_xml/coreference.py#L86-L98
def sentence(self): """ The sentence related to this mention :getter: returns the sentence this mention relates to :type: corenlp_xml.document.Sentence """ if self._sentence is None: sentences = self._element.xpath('sentence/text()') if len(sente...
[ "def", "sentence", "(", "self", ")", ":", "if", "self", ".", "_sentence", "is", "None", ":", "sentences", "=", "self", ".", "_element", ".", "xpath", "(", "'sentence/text()'", ")", "if", "len", "(", "sentences", ")", ">", "0", ":", "self", ".", "_sen...
The sentence related to this mention :getter: returns the sentence this mention relates to :type: corenlp_xml.document.Sentence
[ "The", "sentence", "related", "to", "this", "mention" ]
python
train
33.846154
FlaskGuys/Flask-Imagine
flask_imagine/filters/watermark.py
https://github.com/FlaskGuys/Flask-Imagine/blob/f79c6517ecb5480b63a2b3b8554edb6e2ac8be8c/flask_imagine/filters/watermark.py#L59-L79
def apply(self, resource): """ Apply filter to resource :param resource: Image.Image :return: Image.Image """ if not isinstance(resource, Image.Image): raise ValueError('Unknown resource format') resource_format = resource.format if resource.m...
[ "def", "apply", "(", "self", ",", "resource", ")", ":", "if", "not", "isinstance", "(", "resource", ",", "Image", ".", "Image", ")", ":", "raise", "ValueError", "(", "'Unknown resource format'", ")", "resource_format", "=", "resource", ".", "format", "if", ...
Apply filter to resource :param resource: Image.Image :return: Image.Image
[ "Apply", "filter", "to", "resource", ":", "param", "resource", ":", "Image", ".", "Image", ":", "return", ":", "Image", ".", "Image" ]
python
train
33.047619
honzajavorek/redis-collections
redis_collections/sortedsets.py
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sortedsets.py#L178-L186
def count_between(self, min_score=None, max_score=None): """ Returns the number of members whose score is between *min_score* and *max_score* (inclusive). """ min_score = float('-inf') if min_score is None else float(min_score) max_score = float('inf') if max_score is Non...
[ "def", "count_between", "(", "self", ",", "min_score", "=", "None", ",", "max_score", "=", "None", ")", ":", "min_score", "=", "float", "(", "'-inf'", ")", "if", "min_score", "is", "None", "else", "float", "(", "min_score", ")", "max_score", "=", "float"...
Returns the number of members whose score is between *min_score* and *max_score* (inclusive).
[ "Returns", "the", "number", "of", "members", "whose", "score", "is", "between", "*", "min_score", "*", "and", "*", "max_score", "*", "(", "inclusive", ")", "." ]
python
train
44.555556
collectiveacuity/labPack
labpack/banking/capitalone.py
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/banking/capitalone.py#L398-L465
def account_product(self, product_id): ''' a method to retrieve details about a particular account product { "error": "", "code": 200, "method": "GET", "url": "https://...", "headers": { }, "json": { ...
[ "def", "account_product", "(", "self", ",", "product_id", ")", ":", "title", "=", "'%s.account_product'", "%", "self", ".", "__class__", ".", "__name__", "# validate inputs", "input_fields", "=", "{", "'product_id'", ":", "product_id", "}", "for", "key", ",", ...
a method to retrieve details about a particular account product { "error": "", "code": 200, "method": "GET", "url": "https://...", "headers": { }, "json": { "productId": "3300", "productName": "Capital...
[ "a", "method", "to", "retrieve", "details", "about", "a", "particular", "account", "product", "{", "error", ":", "code", ":", "200", "method", ":", "GET", "url", ":", "https", ":", "//", "...", "headers", ":", "{", "}", "json", ":", "{", "productId", ...
python
train
49.794118
limpyd/redis-limpyd
limpyd/model.py
https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/model.py#L319-L329
def _set_defaults(self): """ Set default values to fields. We assume that they are not yet populated as this method is called just after creation of a new pk. """ for field_name in self._fields: if field_name in self._init_fields: continue ...
[ "def", "_set_defaults", "(", "self", ")", ":", "for", "field_name", "in", "self", ".", "_fields", ":", "if", "field_name", "in", "self", ".", "_init_fields", ":", "continue", "field", "=", "self", ".", "get_field", "(", "field_name", ")", "if", "hasattr", ...
Set default values to fields. We assume that they are not yet populated as this method is called just after creation of a new pk.
[ "Set", "default", "values", "to", "fields", ".", "We", "assume", "that", "they", "are", "not", "yet", "populated", "as", "this", "method", "is", "called", "just", "after", "creation", "of", "a", "new", "pk", "." ]
python
train
39.363636
yougov/vr.common
vr/common/models.py
https://github.com/yougov/vr.common/blob/ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4/vr/common/models.py#L738-L749
def dispatch(self, **changes): """ Patch the swarm with changes and then trigger the swarm. """ self.patch(**changes) trigger_url = self._vr._build_url(self.resource_uri, 'swarm/') resp = self._vr.session.post(trigger_url) resp.raise_for_status() try: ...
[ "def", "dispatch", "(", "self", ",", "*", "*", "changes", ")", ":", "self", ".", "patch", "(", "*", "*", "changes", ")", "trigger_url", "=", "self", ".", "_vr", ".", "_build_url", "(", "self", ".", "resource_uri", ",", "'swarm/'", ")", "resp", "=", ...
Patch the swarm with changes and then trigger the swarm.
[ "Patch", "the", "swarm", "with", "changes", "and", "then", "trigger", "the", "swarm", "." ]
python
train
32.166667
maximtrp/scikit-posthocs
scikit_posthocs/_posthocs.py
https://github.com/maximtrp/scikit-posthocs/blob/5476b09e2a325cd4e31c0b0bc6906ab5cd77fc5d/scikit_posthocs/_posthocs.py#L2388-L2490
def posthoc_dscf(a, val_col=None, group_col=None, sort=False): '''Dwass, Steel, Critchlow and Fligner all-pairs comparison test for a one-factorial layout with non-normally distributed residuals. As opposed to the all-pairs comparison procedures that depend on Kruskal ranks, the DSCF test is basically ...
[ "def", "posthoc_dscf", "(", "a", ",", "val_col", "=", "None", ",", "group_col", "=", "None", ",", "sort", "=", "False", ")", ":", "x", ",", "_val_col", ",", "_group_col", "=", "__convert_to_df", "(", "a", ",", "val_col", ",", "group_col", ")", "if", ...
Dwass, Steel, Critchlow and Fligner all-pairs comparison test for a one-factorial layout with non-normally distributed residuals. As opposed to the all-pairs comparison procedures that depend on Kruskal ranks, the DSCF test is basically an extension of the U-test as re-ranking is conducted for each pair...
[ "Dwass", "Steel", "Critchlow", "and", "Fligner", "all", "-", "pairs", "comparison", "test", "for", "a", "one", "-", "factorial", "layout", "with", "non", "-", "normally", "distributed", "residuals", ".", "As", "opposed", "to", "the", "all", "-", "pairs", "...
python
train
34.951456
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L169-L184
def ReadTag(buffer, pos): """Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple. We return the raw bytes of the tag rather than decoding them. The raw bytes can then be used to look up the proper decoder. This effectively allows us to trade some work that would be done in pure-python (decodi...
[ "def", "ReadTag", "(", "buffer", ",", "pos", ")", ":", "start", "=", "pos", "while", "six", ".", "indexbytes", "(", "buffer", ",", "pos", ")", "&", "0x80", ":", "pos", "+=", "1", "pos", "+=", "1", "return", "(", "buffer", "[", "start", ":", "pos"...
Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple. We return the raw bytes of the tag rather than decoding them. The raw bytes can then be used to look up the proper decoder. This effectively allows us to trade some work that would be done in pure-python (decoding a varint) for work that is...
[ "Read", "a", "tag", "from", "the", "buffer", "and", "return", "a", "(", "tag_bytes", "new_pos", ")", "tuple", "." ]
python
train
38.9375
log2timeline/plaso
plaso/preprocessors/linux.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/preprocessors/linux.py#L183-L221
def _ParseFileEntry(self, knowledge_base, file_entry): """Parses artifact file system data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. Rais...
[ "def", "_ParseFileEntry", "(", "self", ",", "knowledge_base", ",", "file_entry", ")", ":", "if", "file_entry", ".", "link", ":", "# Determine the timezone based on the file path.", "_", ",", "_", ",", "time_zone", "=", "file_entry", ".", "link", ".", "partition", ...
Parses artifact file system data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. Raises: errors.PreProcessFail: if the preprocessing fails.
[ "Parses", "artifact", "file", "system", "data", "for", "a", "preprocessing", "attribute", "." ]
python
train
32.641026
pymoca/pymoca
src/pymoca/backends/xml/model.py
https://github.com/pymoca/pymoca/blob/14b5eb7425e96689de6cc5c10f400895d586a978/src/pymoca/backends/xml/model.py#L70-L76
def create_function_f_c(self): """condition function""" return ca.Function( 'f_c', [self.t, self.x, self.y, self.m, self.p, self.ng, self.nu], [self.f_c], ['t', 'x', 'y', 'm', 'p', 'ng', 'nu'], ['c'], self.func_opt)
[ "def", "create_function_f_c", "(", "self", ")", ":", "return", "ca", ".", "Function", "(", "'f_c'", ",", "[", "self", ".", "t", ",", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "m", ",", "self", ".", "p", ",", "self", ".", "ng", ...
condition function
[ "condition", "function" ]
python
train
39
pyviz/imagen
imagen/colorspaces.py
https://github.com/pyviz/imagen/blob/53c5685c880f54b42795964d8db50b02e8590e88/imagen/colorspaces.py#L413-L416
def rgb_to_hsv(self,RGB): "linear rgb to hsv" gammaRGB = self._gamma_rgb(RGB) return self._ABC_to_DEF_by_fn(gammaRGB,rgb_to_hsv)
[ "def", "rgb_to_hsv", "(", "self", ",", "RGB", ")", ":", "gammaRGB", "=", "self", ".", "_gamma_rgb", "(", "RGB", ")", "return", "self", ".", "_ABC_to_DEF_by_fn", "(", "gammaRGB", ",", "rgb_to_hsv", ")" ]
linear rgb to hsv
[ "linear", "rgb", "to", "hsv" ]
python
train
37.25
tchellomello/raincloudy
raincloudy/faucet.py
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/faucet.py#L291-L306
def _set_auto_watering(self, zoneid, value): """Private method to set auto_watering program.""" if not isinstance(value, bool): return None ddata = self.preupdate() attr = 'zone{}_program_toggle'.format(zoneid) try: if not value: ddata.pop...
[ "def", "_set_auto_watering", "(", "self", ",", "zoneid", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "None", "ddata", "=", "self", ".", "preupdate", "(", ")", "attr", "=", "'zone{}_program_toggle'", "...
Private method to set auto_watering program.
[ "Private", "method", "to", "set", "auto_watering", "program", "." ]
python
train
28.75
ponty/confduino
confduino/examples/remove_libraries.py
https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/examples/remove_libraries.py#L8-L20
def gui(): """remove libraries by GUI.""" sel = psidialogs.multi_choice(libraries(), 'select libraries to remove from %s!' % libraries_dir(), title='remove boards') print('%s selected' % sel) if sel: if psidialogs.ask_yes_no('...
[ "def", "gui", "(", ")", ":", "sel", "=", "psidialogs", ".", "multi_choice", "(", "libraries", "(", ")", ",", "'select libraries to remove from %s!'", "%", "libraries_dir", "(", ")", ",", "title", "=", "'remove boards'", ")", "print", "(", "'%s selected'", "%",...
remove libraries by GUI.
[ "remove", "libraries", "by", "GUI", "." ]
python
train
36.769231
MozillaSecurity/fuzzfetch
src/fuzzfetch/fetch.py
https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L171-L186
def auto_name_prefix(self): """ Generate platform prefix for cross-platform downloads. """ # if the platform is not native, auto_name would clobber native downloads. # make a prefix to avoid this native_system = std_platform.system() native_machine = self.CPU_ALIA...
[ "def", "auto_name_prefix", "(", "self", ")", ":", "# if the platform is not native, auto_name would clobber native downloads.", "# make a prefix to avoid this", "native_system", "=", "std_platform", ".", "system", "(", ")", "native_machine", "=", "self", ".", "CPU_ALIASES", "...
Generate platform prefix for cross-platform downloads.
[ "Generate", "platform", "prefix", "for", "cross", "-", "platform", "downloads", "." ]
python
train
43.125
tritemio/PyBroMo
pybromo/storage.py
https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/storage.py#L89-L108
def set_sim_params(self, nparams, attr_params): """Store parameters in `params` in `h5file.root.parameters`. `nparams` (dict) A dict as returned by `get_params()` in `ParticlesSimulation()` The format is: keys: used as parameter name value...
[ "def", "set_sim_params", "(", "self", ",", "nparams", ",", "attr_params", ")", ":", "for", "name", ",", "value", "in", "nparams", ".", "items", "(", ")", ":", "val", "=", "value", "[", "0", "]", "if", "value", "[", "0", "]", "is", "not", "None", ...
Store parameters in `params` in `h5file.root.parameters`. `nparams` (dict) A dict as returned by `get_params()` in `ParticlesSimulation()` The format is: keys: used as parameter name values: (2-elements tuple) first element is the ...
[ "Store", "parameters", "in", "params", "in", "h5file", ".", "root", ".", "parameters", "." ]
python
valid
45.15
pyrapt/rapt
rapt/treebrd/grammars/core_grammar.py
https://github.com/pyrapt/rapt/blob/0193a07aafff83a887fdc9e5e0f25eafa5b1b205/rapt/treebrd/grammars/core_grammar.py#L132-L140
def assignment(self): """ assignment ::= relation_name assign expression | relation_name param_start attribute_list param_stop assign expression """ lhs = Group(self.relation_name + Optional(self.parenthesize(self.attribute_list))) retu...
[ "def", "assignment", "(", "self", ")", ":", "lhs", "=", "Group", "(", "self", ".", "relation_name", "+", "Optional", "(", "self", ".", "parenthesize", "(", "self", ".", "attribute_list", ")", ")", ")", "return", "Group", "(", "lhs", "+", "Keyword", "("...
assignment ::= relation_name assign expression | relation_name param_start attribute_list param_stop assign expression
[ "assignment", "::", "=", "relation_name", "assign", "expression", "|", "relation_name", "param_start", "attribute_list", "param_stop", "assign", "expression" ]
python
train
41.777778
yolothreat/utilitybelt
utilitybelt/utilitybelt.py
https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L84-L95
def is_rfc1918(ip): """Checks to see if an IP address is used for local communications within a private network as specified by RFC 1918 """ if ip_between(ip, "10.0.0.0", "10.255.255.255"): return True elif ip_between(ip, "172.16.0.0", "172.31.255.255"): return True elif ip_betwe...
[ "def", "is_rfc1918", "(", "ip", ")", ":", "if", "ip_between", "(", "ip", ",", "\"10.0.0.0\"", ",", "\"10.255.255.255\"", ")", ":", "return", "True", "elif", "ip_between", "(", "ip", ",", "\"172.16.0.0\"", ",", "\"172.31.255.255\"", ")", ":", "return", "True"...
Checks to see if an IP address is used for local communications within a private network as specified by RFC 1918
[ "Checks", "to", "see", "if", "an", "IP", "address", "is", "used", "for", "local", "communications", "within", "a", "private", "network", "as", "specified", "by", "RFC", "1918" ]
python
train
33.416667
juju/python-libjuju
juju/model.py
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1449-L1461
async def destroy_unit(self, *unit_names): """Destroy units by name. """ connection = self.connection() app_facade = client.ApplicationFacade.from_connection(connection) log.debug( 'Destroying unit%s %s', 's' if len(unit_names) == 1 else '', ...
[ "async", "def", "destroy_unit", "(", "self", ",", "*", "unit_names", ")", ":", "connection", "=", "self", ".", "connection", "(", ")", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "connection", ")", "log", ".", "debug",...
Destroy units by name.
[ "Destroy", "units", "by", "name", "." ]
python
train
30.230769
genialis/resolwe
resolwe/flow/executors/run.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/run.py#L129-L132
def _create_file(self, filename): """Ensure a new file is created and opened for writing.""" file_descriptor = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL) return os.fdopen(file_descriptor, 'w')
[ "def", "_create_file", "(", "self", ",", "filename", ")", ":", "file_descriptor", "=", "os", ".", "open", "(", "filename", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREAT", "|", "os", ".", "O_EXCL", ")", "return", "os", ".", "fdopen", "(", "file...
Ensure a new file is created and opened for writing.
[ "Ensure", "a", "new", "file", "is", "created", "and", "opened", "for", "writing", "." ]
python
train
56.5
diffeo/rejester
rejester/workers.py
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L950-L965
def stop_all_children(self): '''Kill all workers.''' # There's an unfortunate race condition if we try to log this # case: we can't depend on the logging child actually receiving # the log message before we kill it off. C'est la vie... self.stop_log_child() for pid in se...
[ "def", "stop_all_children", "(", "self", ")", ":", "# There's an unfortunate race condition if we try to log this", "# case: we can't depend on the logging child actually receiving", "# the log message before we kill it off. C'est la vie...", "self", ".", "stop_log_child", "(", ")", "fo...
Kill all workers.
[ "Kill", "all", "workers", "." ]
python
train
39.125
PmagPy/PmagPy
pmagpy/pmagplotlib.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2268-L2301
def plot_hpars(HDD, hpars, sym): """ function to plot hysteresis parameters deprecated (used in hysteresis_magic) """ plt.figure(num=HDD['hyst']) X, Y = [], [] X.append(0) Y.append(old_div(float(hpars['hysteresis_mr_moment']), float( hpars['hysteresis_ms_moment']))) X.append(...
[ "def", "plot_hpars", "(", "HDD", ",", "hpars", ",", "sym", ")", ":", "plt", ".", "figure", "(", "num", "=", "HDD", "[", "'hyst'", "]", ")", "X", ",", "Y", "=", "[", "]", ",", "[", "]", "X", ".", "append", "(", "0", ")", "Y", ".", "append", ...
function to plot hysteresis parameters deprecated (used in hysteresis_magic)
[ "function", "to", "plot", "hysteresis", "parameters", "deprecated", "(", "used", "in", "hysteresis_magic", ")" ]
python
train
39.058824
grundprinzip/pyxplorer
pyxplorer/manager.py
https://github.com/grundprinzip/pyxplorer/blob/34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2/pyxplorer/manager.py#L22-L29
def tables(self): """ :return: all tables stored in this database """ cursor = self.connection.cursor() cursor.execute("show tables in %s" % self.db) self._tables = [t.Table(r[0], con=self.connection, db=self.db) for r in cursor.fetchall()] return self._tables
[ "def", "tables", "(", "self", ")", ":", "cursor", "=", "self", ".", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "\"show tables in %s\"", "%", "self", ".", "db", ")", "self", ".", "_tables", "=", "[", "t", ".", "Table", "(", ...
:return: all tables stored in this database
[ ":", "return", ":", "all", "tables", "stored", "in", "this", "database" ]
python
train
38.625
spyder-ide/spyder
spyder/plugins/editor/widgets/editor.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/editor.py#L293-L297
def remove_and_append(self, index): """Remove previous entrances of a tab, and add it as the latest.""" while index in self: self.remove(index) self.append(index)
[ "def", "remove_and_append", "(", "self", ",", "index", ")", ":", "while", "index", "in", "self", ":", "self", ".", "remove", "(", "index", ")", "self", ".", "append", "(", "index", ")" ]
Remove previous entrances of a tab, and add it as the latest.
[ "Remove", "previous", "entrances", "of", "a", "tab", "and", "add", "it", "as", "the", "latest", "." ]
python
train
39.6
kalaspuff/tomodachi
tomodachi/transport/http.py
https://github.com/kalaspuff/tomodachi/blob/0f21e87cb43821dd6e726a8d4871fb8e17c8fe3d/tomodachi/transport/http.py#L88-L143
def handle_error(self, request: Any, status: int = 500, exc: Any = None, message: Optional[str] = None) -> web.Response: """Handle errors. Returns HTTP response with specific status code. Logs additional information. It always closes current connection.""" if self.transport is None: ...
[ "def", "handle_error", "(", "self", ",", "request", ":", "Any", ",", "status", ":", "int", "=", "500", ",", "exc", ":", "Any", "=", "None", ",", "message", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "web", ".", "Response", ":", "if...
Handle errors. Returns HTTP response with specific status code. Logs additional information. It always closes current connection.
[ "Handle", "errors", "." ]
python
train
53.035714
treycucco/bidon
bidon/db/model/model_base.py
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/model_base.py#L42-L56
def has_attr(cls, attr_name): """Check to see if an attribute is defined for the model.""" if attr_name in cls.attrs: return True if isinstance(cls.primary_key_name, str) and cls.primary_key_name == attr_name: return True if isinstance(cls.primary_key_name, tuple) and attr_name in cls.prim...
[ "def", "has_attr", "(", "cls", ",", "attr_name", ")", ":", "if", "attr_name", "in", "cls", ".", "attrs", ":", "return", "True", "if", "isinstance", "(", "cls", ".", "primary_key_name", ",", "str", ")", "and", "cls", ".", "primary_key_name", "==", "attr_n...
Check to see if an attribute is defined for the model.
[ "Check", "to", "see", "if", "an", "attribute", "is", "defined", "for", "the", "model", "." ]
python
train
29.4
FreekKalter/geoselect
geoselect.py
https://github.com/FreekKalter/geoselect/blob/2c6ab869d50215eba21dce3e1770bcf8ecdb41f3/geoselect.py#L93-L110
def build_dict(img_iterator): """ Build a dict from files from iterator. {'absolute_filename': {'EXIF field': 'exif tag value'}} Parse DateTime from filename in the same loop, added as 'TIME'. """ files_with_tags = dict() for f in img_iterator: with open(str(f.abspath()), 'rb...
[ "def", "build_dict", "(", "img_iterator", ")", ":", "files_with_tags", "=", "dict", "(", ")", "for", "f", "in", "img_iterator", ":", "with", "open", "(", "str", "(", "f", ".", "abspath", "(", ")", ")", ",", "'rb'", ")", "as", "jpg", ":", "tags", "=...
Build a dict from files from iterator. {'absolute_filename': {'EXIF field': 'exif tag value'}} Parse DateTime from filename in the same loop, added as 'TIME'.
[ "Build", "a", "dict", "from", "files", "from", "iterator", ".", "{", "absolute_filename", ":", "{", "EXIF", "field", ":", "exif", "tag", "value", "}}", "Parse", "DateTime", "from", "filename", "in", "the", "same", "loop", "added", "as", "TIME", "." ]
python
train
36.777778
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L206-L227
def has_comment(src): """Indicate whether an input line has (i.e. ends in, or is) a comment. This uses tokenize, so it can distinguish comments from # inside strings. Parameters ---------- src : string A single line input string. Returns ------- Boolean: True if sour...
[ "def", "has_comment", "(", "src", ")", ":", "readline", "=", "StringIO", "(", "src", ")", ".", "readline", "toktypes", "=", "set", "(", ")", "try", ":", "for", "t", "in", "tokenize", ".", "generate_tokens", "(", "readline", ")", ":", "toktypes", ".", ...
Indicate whether an input line has (i.e. ends in, or is) a comment. This uses tokenize, so it can distinguish comments from # inside strings. Parameters ---------- src : string A single line input string. Returns ------- Boolean: True if source has a comment.
[ "Indicate", "whether", "an", "input", "line", "has", "(", "i", ".", "e", ".", "ends", "in", "or", "is", ")", "a", "comment", ".", "This", "uses", "tokenize", "so", "it", "can", "distinguish", "comments", "from", "#", "inside", "strings", ".", "Paramete...
python
test
25.545455
bigchaindb/bigchaindb
bigchaindb/web/views/blocks.py
https://github.com/bigchaindb/bigchaindb/blob/835fdfcf598918f76139e3b88ee33dd157acaaa7/bigchaindb/web/views/blocks.py#L38-L57
def get(self): """API endpoint to get the related blocks for a transaction. Return: A ``list`` of ``block_id``s that contain the given transaction. The list may be filtered when provided a status query parameter: "valid", "invalid", "undecided". """ p...
[ "def", "get", "(", "self", ")", ":", "parser", "=", "reqparse", ".", "RequestParser", "(", ")", "parser", ".", "add_argument", "(", "'transaction_id'", ",", "type", "=", "str", ",", "required", "=", "True", ")", "args", "=", "parser", ".", "parse_args", ...
API endpoint to get the related blocks for a transaction. Return: A ``list`` of ``block_id``s that contain the given transaction. The list may be filtered when provided a status query parameter: "valid", "invalid", "undecided".
[ "API", "endpoint", "to", "get", "the", "related", "blocks", "for", "a", "transaction", "." ]
python
train
33
neherlab/treetime
treetime/gtr.py
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L399-L491
def infer(cls, nij, Ti, root_state, fixed_pi=None, pc=5.0, gap_limit=0.01, **kwargs): """ Infer a GTR model by specifying the number of transitions and time spent in each character. The basic equation that is being solved is :math:`n_{ij} = pi_i W_{ij} T_j` where :math:`n_{ij}`...
[ "def", "infer", "(", "cls", ",", "nij", ",", "Ti", ",", "root_state", ",", "fixed_pi", "=", "None", ",", "pc", "=", "5.0", ",", "gap_limit", "=", "0.01", ",", "*", "*", "kwargs", ")", ":", "from", "scipy", "import", "linalg", "as", "LA", "gtr", "...
Infer a GTR model by specifying the number of transitions and time spent in each character. The basic equation that is being solved is :math:`n_{ij} = pi_i W_{ij} T_j` where :math:`n_{ij}` are the transitions, :math:`pi_i` are the equilibrium state frequencies, :math:`W_{ij}` is the "s...
[ "Infer", "a", "GTR", "model", "by", "specifying", "the", "number", "of", "transitions", "and", "time", "spent", "in", "each", "character", ".", "The", "basic", "equation", "that", "is", "being", "solved", "is" ]
python
test
40.989247
project-rig/rig
rig/machine_control/regions.py
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/regions.py#L20-L52
def get_region_for_chip(x, y, level=3): """Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the sp...
[ "def", "get_region_for_chip", "(", "x", ",", "y", ",", "level", "=", "3", ")", ":", "shift", "=", "6", "-", "2", "*", "level", "bit", "=", "(", "(", "x", ">>", "shift", ")", "&", "3", ")", "+", "4", "*", "(", "(", "y", ">>", "shift", ")", ...
Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the specified region will ONLY select the given chip,...
[ "Get", "the", "region", "word", "for", "the", "given", "chip", "co", "-", "ordinates", "." ]
python
train
37.333333
jedie/PyHardLinkBackup
PyHardLinkBackup/phlb/filesystem_walk.py
https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/filesystem_walk.py#L85-L118
def iter_filtered_dir_entry(dir_entries, match_patterns, on_skip): """ Filter a list of DirEntryPath instances with the given pattern :param dir_entries: list of DirEntryPath instances :param match_patterns: used with Path.match() e.g.: "__pycache__/*", "*.tmp", "*.cache" :param on_skip: fu...
[ "def", "iter_filtered_dir_entry", "(", "dir_entries", ",", "match_patterns", ",", "on_skip", ")", ":", "def", "match", "(", "dir_entry_path", ",", "match_patterns", ",", "on_skip", ")", ":", "for", "match_pattern", "in", "match_patterns", ":", "if", "dir_entry_pat...
Filter a list of DirEntryPath instances with the given pattern :param dir_entries: list of DirEntryPath instances :param match_patterns: used with Path.match() e.g.: "__pycache__/*", "*.tmp", "*.cache" :param on_skip: function that will be called if 'match_patterns' hits. e.g.: def ...
[ "Filter", "a", "list", "of", "DirEntryPath", "instances", "with", "the", "given", "pattern" ]
python
train
40.529412
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1941-L1946
def newTextReaderFilename(URI): """Create an xmlTextReader structure fed with the resource at @URI """ ret = libxml2mod.xmlNewTextReaderFilename(URI) if ret is None:raise treeError('xmlNewTextReaderFilename() failed') return xmlTextReader(_obj=ret)
[ "def", "newTextReaderFilename", "(", "URI", ")", ":", "ret", "=", "libxml2mod", ".", "xmlNewTextReaderFilename", "(", "URI", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlNewTextReaderFilename() failed'", ")", "return", "xmlTextReader", "(",...
Create an xmlTextReader structure fed with the resource at @URI
[ "Create", "an", "xmlTextReader", "structure", "fed", "with", "the", "resource", "at" ]
python
train
44.333333
willemarcel/osmcha
osmcha/changeset.py
https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L311-L331
def verify_words(self): """Verify the fields source, imagery_used and comment of the changeset for some suspect words. """ if self.comment: if find_words(self.comment, self.suspect_words, self.excluded_words): self.label_suspicious('suspect_word') if ...
[ "def", "verify_words", "(", "self", ")", ":", "if", "self", ".", "comment", ":", "if", "find_words", "(", "self", ".", "comment", ",", "self", ".", "suspect_words", ",", "self", ".", "excluded_words", ")", ":", "self", ".", "label_suspicious", "(", "'sus...
Verify the fields source, imagery_used and comment of the changeset for some suspect words.
[ "Verify", "the", "fields", "source", "imagery_used", "and", "comment", "of", "the", "changeset", "for", "some", "suspect", "words", "." ]
python
valid
36.809524
amsehili/auditok
auditok/util.py
https://github.com/amsehili/auditok/blob/df6eb1d80f8cd9034be47b24869ce59b74f5f4db/auditok/util.py#L106-L119
def set_data(self, data): """ Set a new data buffer. :Parameters: `data` : a basestring object New data buffer. """ if not isinstance(data, basestring): raise ValueError("data must an instance of basestring") self._data = data ...
[ "def", "set_data", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "basestring", ")", ":", "raise", "ValueError", "(", "\"data must an instance of basestring\"", ")", "self", ".", "_data", "=", "data", "self", ".", "_current"...
Set a new data buffer. :Parameters: `data` : a basestring object New data buffer.
[ "Set", "a", "new", "data", "buffer", "." ]
python
train
23.642857
neurosynth/neurosynth
neurosynth/base/mask.py
https://github.com/neurosynth/neurosynth/blob/948ce7edce15d7df693446e76834e0c23bfe8f11/neurosynth/base/mask.py#L39-L68
def add(self, layers, above=None, below=None): """ Add one or more layers to the stack of masking layers. Args: layers: A string, NiBabel image, list, or dict. If anything other than a dict is passed, assigns sequential layer names based on the current positio...
[ "def", "add", "(", "self", ",", "layers", ",", "above", "=", "None", ",", "below", "=", "None", ")", ":", "def", "add_named_layer", "(", "name", ",", "image", ")", ":", "image", "=", "self", ".", "get_image", "(", "image", ",", "output", "=", "'vec...
Add one or more layers to the stack of masking layers. Args: layers: A string, NiBabel image, list, or dict. If anything other than a dict is passed, assigns sequential layer names based on the current position in stack; if a dict, uses key as the name ...
[ "Add", "one", "or", "more", "layers", "to", "the", "stack", "of", "masking", "layers", ".", "Args", ":", "layers", ":", "A", "string", "NiBabel", "image", "list", "or", "dict", ".", "If", "anything", "other", "than", "a", "dict", "is", "passed", "assig...
python
test
36.666667
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/table.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L693-L705
def expires(self): """Union[datetime.datetime, None]: Datetime at which the table will be deleted. Raises: ValueError: For invalid value types. """ expiration_time = self._properties.get("expirationTime") if expiration_time is not None: # expirati...
[ "def", "expires", "(", "self", ")", ":", "expiration_time", "=", "self", ".", "_properties", ".", "get", "(", "\"expirationTime\"", ")", "if", "expiration_time", "is", "not", "None", ":", "# expiration_time will be in milliseconds.", "return", "google", ".", "clou...
Union[datetime.datetime, None]: Datetime at which the table will be deleted. Raises: ValueError: For invalid value types.
[ "Union", "[", "datetime", ".", "datetime", "None", "]", ":", "Datetime", "at", "which", "the", "table", "will", "be", "deleted", "." ]
python
train
36.307692
Alignak-monitoring/alignak
alignak/scheduler.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L250-L263
def reset(self): # pylint: disable=not-context-manager """Reset scheduler:: * Remove waiting results * Clear checks and actions lists :return: None """ logger.info("Scheduling loop reset") with self.waiting_results.mutex: self.waiting_results...
[ "def", "reset", "(", "self", ")", ":", "# pylint: disable=not-context-manager", "logger", ".", "info", "(", "\"Scheduling loop reset\"", ")", "with", "self", ".", "waiting_results", ".", "mutex", ":", "self", ".", "waiting_results", ".", "queue", ".", "clear", "...
Reset scheduler:: * Remove waiting results * Clear checks and actions lists :return: None
[ "Reset", "scheduler", "::" ]
python
train
27
bitesofcode/projex
projex/xmlutil.py
https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xmlutil.py#L86-L105
def fromXml(cls, xml): """ Restores an object from XML. :param xml | <xml.etree.ElementTree.Element> :return subclass of <XmlObject> """ clsname = xml.get('class') if clsname: subcls = XmlObject.byName(clsname) if subcls is None:...
[ "def", "fromXml", "(", "cls", ",", "xml", ")", ":", "clsname", "=", "xml", ".", "get", "(", "'class'", ")", "if", "clsname", ":", "subcls", "=", "XmlObject", ".", "byName", "(", "clsname", ")", "if", "subcls", "is", "None", ":", "inst", "=", "Missi...
Restores an object from XML. :param xml | <xml.etree.ElementTree.Element> :return subclass of <XmlObject>
[ "Restores", "an", "object", "from", "XML", "." ]
python
train
24.3
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/lxml/html/html5parser.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/lxml/html/html5parser.py#L56-L64
def document_fromstring(html, guess_charset=True, parser=None): """Parse a whole document into a string.""" if not isinstance(html, _strings): raise TypeError('string required') if parser is None: parser = html_parser return parser.parse(html, useChardet=guess_charset).getroot()
[ "def", "document_fromstring", "(", "html", ",", "guess_charset", "=", "True", ",", "parser", "=", "None", ")", ":", "if", "not", "isinstance", "(", "html", ",", "_strings", ")", ":", "raise", "TypeError", "(", "'string required'", ")", "if", "parser", "is"...
Parse a whole document into a string.
[ "Parse", "a", "whole", "document", "into", "a", "string", "." ]
python
test
33.888889
gwastro/pycbc-glue
pycbc_glue/segmentdb/segmentdb_utils.py
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentdb/segmentdb_utils.py#L467-L515
def build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0): """Builds a list of segments satisfying the given criteria """ seg_result = segmentlist([]) sum_result = segmentlist([]) # Is there any way to get segment and segement summar...
[ "def", "build_segment_list_one", "(", "engine", ",", "gps_start_time", ",", "gps_end_time", ",", "ifo", ",", "segment_name", ",", "version", "=", "None", ",", "start_pad", "=", "0", ",", "end_pad", "=", "0", ")", ":", "seg_result", "=", "segmentlist", "(", ...
Builds a list of segments satisfying the given criteria
[ "Builds", "a", "list", "of", "segments", "satisfying", "the", "given", "criteria" ]
python
train
50.77551
buildbot/buildbot
pkg/buildbot_pkg.py
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/pkg/buildbot_pkg.py#L89-L114
def getVersionFromArchiveId(git_archive_id='$Format:%ct %d$'): """ Extract the tag if a source is from git archive. When source is exported via `git archive`, the git_archive_id init value is modified and placeholders are expanded to the "archived" revision: %ct: committer date, UNIX t...
[ "def", "getVersionFromArchiveId", "(", "git_archive_id", "=", "'$Format:%ct %d$'", ")", ":", "# mangle the magic string to make sure it is not replaced by git archive", "if", "not", "git_archive_id", ".", "startswith", "(", "'$For'", "'mat:'", ")", ":", "# source was modified b...
Extract the tag if a source is from git archive. When source is exported via `git archive`, the git_archive_id init value is modified and placeholders are expanded to the "archived" revision: %ct: committer date, UNIX timestamp %d: ref names, like the --decorate option of git-l...
[ "Extract", "the", "tag", "if", "a", "source", "is", "from", "git", "archive", "." ]
python
train
43.230769
mjirik/io3d
io3d/dcmtools.py
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dcmtools.py#L27-L59
def get_sitk_image_from_ndarray(data3d): """ Prepare SimpleItk Image object and rescale data to unsigned types. Simple ITK with version higher than 1.0.0 can not write signed int16. This function check the SimpleITK version and use work around with Rescale Intercept and Rescale Slope :param data3d:...
[ "def", "get_sitk_image_from_ndarray", "(", "data3d", ")", ":", "import", "SimpleITK", "as", "sitk", "rescale_intercept", "=", "None", "if", "sitk", ".", "Version", ".", "MajorVersion", "(", ")", ">", "0", ":", "if", "data3d", ".", "dtype", "==", "np", ".",...
Prepare SimpleItk Image object and rescale data to unsigned types. Simple ITK with version higher than 1.0.0 can not write signed int16. This function check the SimpleITK version and use work around with Rescale Intercept and Rescale Slope :param data3d: :return:
[ "Prepare", "SimpleItk", "Image", "object", "and", "rescale", "data", "to", "unsigned", "types", "." ]
python
train
38.69697
stephantul/somber
somber/base.py
https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/base.py#L593-L625
def load(cls, path): """ Load a SOM from a JSON file saved with this package. Parameters ---------- path : str The path to the JSON file. Returns ------- s : cls A som of the specified class. """ data = json.load(...
[ "def", "load", "(", "cls", ",", "path", ")", ":", "data", "=", "json", ".", "load", "(", "open", "(", "path", ")", ")", "weights", "=", "data", "[", "'weights'", "]", "weights", "=", "np", ".", "asarray", "(", "weights", ",", "dtype", "=", "np", ...
Load a SOM from a JSON file saved with this package. Parameters ---------- path : str The path to the JSON file. Returns ------- s : cls A som of the specified class.
[ "Load", "a", "SOM", "from", "a", "JSON", "file", "saved", "with", "this", "package", "." ]
python
train
25.757576
saltstack/salt
salt/cloud/clouds/ec2.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/ec2.py#L4597-L4662
def create_snapshot(kwargs=None, call=None, wait_to_finish=False): ''' Create a snapshot. volume_id The ID of the Volume from which to create a snapshot. description The optional description of the snapshot. CLI Exampe: .. code-block:: bash salt-cloud -f create_snaps...
[ "def", "create_snapshot", "(", "kwargs", "=", "None", ",", "call", "=", "None", ",", "wait_to_finish", "=", "False", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_snapshot function must be called with -f '", "'or ...
Create a snapshot. volume_id The ID of the Volume from which to create a snapshot. description The optional description of the snapshot. CLI Exampe: .. code-block:: bash salt-cloud -f create_snapshot my-ec2-config volume_id=vol-351d8826 salt-cloud -f create_snapshot ...
[ "Create", "a", "snapshot", "." ]
python
train
29.757576
AtsushiSakai/SimpleTkGUIKit
SimpleTkGUIKit/SimpleTkGUIKit.py
https://github.com/AtsushiSakai/SimpleTkGUIKit/blob/e7cbb06ff32afb165cdaa4fe396ca2f172c66ff0/SimpleTkGUIKit/SimpleTkGUIKit.py#L12-L34
def GetFilePathsWithDialog(fileTypes=[]): """ Multipul File Select with dialog fileTypes: you can choise file extension ex) fileTypes=[('Excel Files', '.xlsx')] """ root = tkinter.Tk() root.withdraw() filepath = filedialog.askopenfilenames( filetypes=fileTypes, p...
[ "def", "GetFilePathsWithDialog", "(", "fileTypes", "=", "[", "]", ")", ":", "root", "=", "tkinter", ".", "Tk", "(", ")", "root", ".", "withdraw", "(", ")", "filepath", "=", "filedialog", ".", "askopenfilenames", "(", "filetypes", "=", "fileTypes", ",", "...
Multipul File Select with dialog fileTypes: you can choise file extension ex) fileTypes=[('Excel Files', '.xlsx')]
[ "Multipul", "File", "Select", "with", "dialog" ]
python
train
26.73913
Pytwitcher/pytwitcherapi
src/pytwitcherapi/oauth.py
https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/oauth.py#L160-L170
def _add_bearer_token(self, *args, **kwargs): """Add a bearer token to the request uri, body or authorization header. This is overwritten to change the headers slightly. """ s = super(TwitchOAuthClient, self) uri, headers, body = s._add_bearer_token(*args, **kwargs) auth...
[ "def", "_add_bearer_token", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "s", "=", "super", "(", "TwitchOAuthClient", ",", "self", ")", "uri", ",", "headers", ",", "body", "=", "s", ".", "_add_bearer_token", "(", "*", "args", ","...
Add a bearer token to the request uri, body or authorization header. This is overwritten to change the headers slightly.
[ "Add", "a", "bearer", "token", "to", "the", "request", "uri", "body", "or", "authorization", "header", "." ]
python
train
43.727273
Antidote1911/cryptoshop
cryptoshop/_nonce_engine.py
https://github.com/Antidote1911/cryptoshop/blob/0b7ff4a6848f2733f4737606957e8042a4d6ca0b/cryptoshop/_nonce_engine.py#L45-L53
def generate_nonce_timestamp(): """ Generate unique nonce with counter, uuid and rng.""" global count rng = botan.rng().get(30) uuid4 = uuid.uuid4().bytes # 16 byte tmpnonce = (bytes(str(count).encode('utf-8'))) + uuid4 + rng nonce = tmpnonce[:41] # 41 byte (328 bit) count += 1 return ...
[ "def", "generate_nonce_timestamp", "(", ")", ":", "global", "count", "rng", "=", "botan", ".", "rng", "(", ")", ".", "get", "(", "30", ")", "uuid4", "=", "uuid", ".", "uuid4", "(", ")", ".", "bytes", "# 16 byte", "tmpnonce", "=", "(", "bytes", "(", ...
Generate unique nonce with counter, uuid and rng.
[ "Generate", "unique", "nonce", "with", "counter", "uuid", "and", "rng", "." ]
python
train
35.222222
thebigmunch/google-music
src/google_music/clients/mobileclient.py
https://github.com/thebigmunch/google-music/blob/d8a94dab462a1f063fbc1152187a73dc2f0e2a85/src/google_music/clients/mobileclient.py#L294-L302
def devices(self): """Get a listing of devices registered to the Google Music account.""" response = self._call( mc_calls.DeviceManagementInfo ) registered_devices = response.body.get('data', {}).get('items', []) return registered_devices
[ "def", "devices", "(", "self", ")", ":", "response", "=", "self", ".", "_call", "(", "mc_calls", ".", "DeviceManagementInfo", ")", "registered_devices", "=", "response", ".", "body", ".", "get", "(", "'data'", ",", "{", "}", ")", ".", "get", "(", "'ite...
Get a listing of devices registered to the Google Music account.
[ "Get", "a", "listing", "of", "devices", "registered", "to", "the", "Google", "Music", "account", "." ]
python
train
27.222222
vrtsystems/hszinc
hszinc/grid.py
https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/grid.py#L164-L175
def _assert_version(self, version): ''' Assert that the grid version is equal to or above the given value. If no version is set, set the version. ''' if self.nearest_version < version: if self._version_given: raise ValueError( '...
[ "def", "_assert_version", "(", "self", ",", "version", ")", ":", "if", "self", ".", "nearest_version", "<", "version", ":", "if", "self", ".", "_version_given", ":", "raise", "ValueError", "(", "'Data type requires version %s'", "%", "version", ")", "else", ":...
Assert that the grid version is equal to or above the given value. If no version is set, set the version.
[ "Assert", "that", "the", "grid", "version", "is", "equal", "to", "or", "above", "the", "given", "value", ".", "If", "no", "version", "is", "set", "set", "the", "version", "." ]
python
valid
36.166667
jobovy/galpy
galpy/potential/SpiralArmsPotential.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/SpiralArmsPotential.py#L570-L574
def _B(self, R): """Return numpy array from B1 up to and including Bn. (eqn. 6)""" HNn_R = self._HNn / R return HNn_R / self._sin_alpha * (0.4 * HNn_R / self._sin_alpha + 1)
[ "def", "_B", "(", "self", ",", "R", ")", ":", "HNn_R", "=", "self", ".", "_HNn", "/", "R", "return", "HNn_R", "/", "self", ".", "_sin_alpha", "*", "(", "0.4", "*", "HNn_R", "/", "self", ".", "_sin_alpha", "+", "1", ")" ]
Return numpy array from B1 up to and including Bn. (eqn. 6)
[ "Return", "numpy", "array", "from", "B1", "up", "to", "and", "including", "Bn", ".", "(", "eqn", ".", "6", ")" ]
python
train
38.8
wooster/biplist
biplist/__init__.py
https://github.com/wooster/biplist/blob/4c3d0c94132621188ca4c1fa9bda3b2d4d52ab82/biplist/__init__.py#L797-L811
def writeObjectReference(self, obj, output): """Tries to write an object reference, adding it to the references table. Does not write the actual object bytes or set the reference position. Returns a tuple of whether the object was a new reference (True if it was, False if it alr...
[ "def", "writeObjectReference", "(", "self", ",", "obj", ",", "output", ")", ":", "position", "=", "self", ".", "positionOfObjectReference", "(", "obj", ")", "if", "position", "is", "None", ":", "self", ".", "writtenReferences", "[", "obj", "]", "=", "len",...
Tries to write an object reference, adding it to the references table. Does not write the actual object bytes or set the reference position. Returns a tuple of whether the object was a new reference (True if it was, False if it already was in the reference table) and the new ...
[ "Tries", "to", "write", "an", "object", "reference", "adding", "it", "to", "the", "references", "table", ".", "Does", "not", "write", "the", "actual", "object", "bytes", "or", "set", "the", "reference", "position", ".", "Returns", "a", "tuple", "of", "whet...
python
train
53.933333
QualiSystems/cloudshell-networking-devices
cloudshell/devices/runners/configuration_runner.py
https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/configuration_runner.py#L123-L149
def orchestration_save(self, mode="shallow", custom_params=None): """Orchestration Save command :param mode: :param custom_params: json with all required action to configure or remove vlans from certain port :return Serialized OrchestrationSavedArtifact to json :rtype json ...
[ "def", "orchestration_save", "(", "self", ",", "mode", "=", "\"shallow\"", ",", "custom_params", "=", "None", ")", ":", "save_params", "=", "{", "'folder_path'", ":", "''", ",", "'configuration_type'", ":", "'running'", ",", "'return_artifact'", ":", "True", "...
Orchestration Save command :param mode: :param custom_params: json with all required action to configure or remove vlans from certain port :return Serialized OrchestrationSavedArtifact to json :rtype json
[ "Orchestration", "Save", "command" ]
python
train
47.703704
limodou/uliweb
uliweb/contrib/datadict/datadict_subcommands.py
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/datadict/datadict_subcommands.py#L82-L100
def _parse_prop(self, dd, row): """ :param dd: datadict :param _row: (tablename, row) :return: """ key = row['name'] if key.startswith('#'): deprecated = True else: deprecated = False v = dd.get(key) _value = self._g...
[ "def", "_parse_prop", "(", "self", ",", "dd", ",", "row", ")", ":", "key", "=", "row", "[", "'name'", "]", "if", "key", ".", "startswith", "(", "'#'", ")", ":", "deprecated", "=", "True", "else", ":", "deprecated", "=", "False", "v", "=", "dd", "...
:param dd: datadict :param _row: (tablename, row) :return:
[ ":", "param", "dd", ":", "datadict", ":", "param", "_row", ":", "(", "tablename", "row", ")", ":", "return", ":" ]
python
train
25.894737
SBRG/ssbio
ssbio/databases/swissmodel.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/databases/swissmodel.py#L141-L166
def organize_models(self, outdir, force_rerun=False): """Organize and rename SWISS-MODEL models to a single folder with a name containing template information. Args: outdir (str): New directory to copy renamed models to force_rerun (bool): If models should be copied again even i...
[ "def", "organize_models", "(", "self", ",", "outdir", ",", "force_rerun", "=", "False", ")", ":", "uniprot_to_swissmodel", "=", "defaultdict", "(", "list", ")", "for", "u", ",", "models", "in", "self", ".", "all_models", ".", "items", "(", ")", ":", "for...
Organize and rename SWISS-MODEL models to a single folder with a name containing template information. Args: outdir (str): New directory to copy renamed models to force_rerun (bool): If models should be copied again even if they already exist Returns: dict: Dictiona...
[ "Organize", "and", "rename", "SWISS", "-", "MODEL", "models", "to", "a", "single", "folder", "with", "a", "name", "containing", "template", "information", "." ]
python
train
50.461538
eqcorrscan/EQcorrscan
eqcorrscan/utils/catalog_to_dd.py
https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/catalog_to_dd.py#L130-L191
def readSTATION0(path, stations): """ Read a Seisan STATION0.HYP file on the path given. Outputs the information, and writes to station.dat file. :type path: str :param path: Path to the STATION0.HYP file :type stations: list :param stations: Stations to look for :returns: List of tup...
[ "def", "readSTATION0", "(", "path", ",", "stations", ")", ":", "stalist", "=", "[", "]", "f", "=", "open", "(", "path", "+", "'/STATION0.HYP'", ",", "'r'", ")", "for", "line", "in", "f", ":", "if", "line", "[", "1", ":", "6", "]", ".", "strip", ...
Read a Seisan STATION0.HYP file on the path given. Outputs the information, and writes to station.dat file. :type path: str :param path: Path to the STATION0.HYP file :type stations: list :param stations: Stations to look for :returns: List of tuples of station, lat, long, elevation :rtyp...
[ "Read", "a", "Seisan", "STATION0", ".", "HYP", "file", "on", "the", "path", "given", "." ]
python
train
34.548387
Koed00/django-q
django_q/tasks.py
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L198-L219
def fetch(task_id, wait=0, cached=Conf.CACHED): """ Return the processed task. :param task_id: the task name or uuid :type task_id: str or uuid :param wait: the number of milliseconds to wait for a result :type wait: int :param bool cached: run this against the cache backend :return: th...
[ "def", "fetch", "(", "task_id", ",", "wait", "=", "0", ",", "cached", "=", "Conf", ".", "CACHED", ")", ":", "if", "cached", ":", "return", "fetch_cached", "(", "task_id", ",", "wait", ")", "start", "=", "time", "(", ")", "while", "True", ":", "t", ...
Return the processed task. :param task_id: the task name or uuid :type task_id: str or uuid :param wait: the number of milliseconds to wait for a result :type wait: int :param bool cached: run this against the cache backend :return: the full task object :rtype: Task
[ "Return", "the", "processed", "task", "." ]
python
train
26.909091
pytroll/pyspectral
pyspectral/radiance_tb_conversion.py
https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/radiance_tb_conversion.py#L160-L170
def _getsatname(self): """ Get the satellite name used in the rsr-reader, from the platform and number """ if self.platform_name.startswith("Meteosat"): return self.platform_name else: raise NotImplementedError( 'Platform {0} not y...
[ "def", "_getsatname", "(", "self", ")", ":", "if", "self", ".", "platform_name", ".", "startswith", "(", "\"Meteosat\"", ")", ":", "return", "self", ".", "platform_name", "else", ":", "raise", "NotImplementedError", "(", "'Platform {0} not yet supported...'", ".",...
Get the satellite name used in the rsr-reader, from the platform and number
[ "Get", "the", "satellite", "name", "used", "in", "the", "rsr", "-", "reader", "from", "the", "platform", "and", "number" ]
python
train
32.181818
gwastro/pycbc
pycbc/tmpltbank/em_progenitors.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/em_progenitors.py#L232-L269
def bh_effective_spin(chi,incl): """ Determines the effective [as defined in Stone, Loeb, Berger, PRD 87, 084053 (2013)] aligned dimensionless spin parameter of a NS-BH binary with tilted BH spin. This means finding the root chi_eff of ISCO_eq_chi_first(chi_eff, PG_ISSO_solver(chi,incl)) wit...
[ "def", "bh_effective_spin", "(", "chi", ",", "incl", ")", ":", "if", "incl", "==", "0", ":", "chi_eff", "=", "chi", "else", ":", "# ISSO radius for the given BH spin magnitude and inclination", "rISSO", "=", "PG_ISSO_solver", "(", "chi", ",", "incl", ")", "# Ang...
Determines the effective [as defined in Stone, Loeb, Berger, PRD 87, 084053 (2013)] aligned dimensionless spin parameter of a NS-BH binary with tilted BH spin. This means finding the root chi_eff of ISCO_eq_chi_first(chi_eff, PG_ISSO_solver(chi,incl)) with the correct sign. Parameters -----...
[ "Determines", "the", "effective", "[", "as", "defined", "in", "Stone", "Loeb", "Berger", "PRD", "87", "084053", "(", "2013", ")", "]", "aligned", "dimensionless", "spin", "parameter", "of", "a", "NS", "-", "BH", "binary", "with", "tilted", "BH", "spin", ...
python
train
35.289474
EconForge/dolo
dolo/compiler/function_compiler_sympy.py
https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/compiler/function_compiler_sympy.py#L5-L11
def ast_to_sympy(expr): '''Converts an AST expression to a sympy expression (STUPID)''' from dolang import to_source s = to_source(expr) not_to_be_treated_as_functions = ['alpha','beta', 'gamma','zeta', 'Chi'] d = {v: sympy.Symbol(v) for v in not_to_be_treated_as_functions} return sympy.sympify(...
[ "def", "ast_to_sympy", "(", "expr", ")", ":", "from", "dolang", "import", "to_source", "s", "=", "to_source", "(", "expr", ")", "not_to_be_treated_as_functions", "=", "[", "'alpha'", ",", "'beta'", ",", "'gamma'", ",", "'zeta'", ",", "'Chi'", "]", "d", "="...
Converts an AST expression to a sympy expression (STUPID)
[ "Converts", "an", "AST", "expression", "to", "a", "sympy", "expression", "(", "STUPID", ")" ]
python
train
46.571429
yyuu/botornado
boto/mturk/connection.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/mturk/connection.py#L499-L505
def block_worker(self, worker_id, reason): """ Block a worker from working on my tasks. """ params = {'WorkerId': worker_id, 'Reason': reason} return self._process_request('BlockWorker', params)
[ "def", "block_worker", "(", "self", ",", "worker_id", ",", "reason", ")", ":", "params", "=", "{", "'WorkerId'", ":", "worker_id", ",", "'Reason'", ":", "reason", "}", "return", "self", ".", "_process_request", "(", "'BlockWorker'", ",", "params", ")" ]
Block a worker from working on my tasks.
[ "Block", "a", "worker", "from", "working", "on", "my", "tasks", "." ]
python
train
32.714286
deepmind/sonnet
sonnet/python/modules/basic.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L197-L265
def _build(self, inputs): """Connects the Linear module into the graph, with input Tensor `inputs`. If this is not the first time the module has been connected to the graph, the Tensor provided here must have the same final dimension, in order for the existing variables to be the correct size for the m...
[ "def", "_build", "(", "self", ",", "inputs", ")", ":", "input_shape", "=", "tuple", "(", "inputs", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", ")", "if", "len", "(", "input_shape", ")", "!=", "2", ":", "raise", "base", ".", "IncompatibleSha...
Connects the Linear module into the graph, with input Tensor `inputs`. If this is not the first time the module has been connected to the graph, the Tensor provided here must have the same final dimension, in order for the existing variables to be the correct size for the multiplication. The batch size...
[ "Connects", "the", "Linear", "module", "into", "the", "graph", "with", "input", "Tensor", "inputs", "." ]
python
train
41.057971
hotdoc/hotdoc
hotdoc/utils/loggable.py
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L201-L204
def register_error_code(code, exception_type, domain='core'): """Register a new error code""" Logger._error_code_to_exception[code] = (exception_type, domain) Logger._domain_codes[domain].add(code)
[ "def", "register_error_code", "(", "code", ",", "exception_type", ",", "domain", "=", "'core'", ")", ":", "Logger", ".", "_error_code_to_exception", "[", "code", "]", "=", "(", "exception_type", ",", "domain", ")", "Logger", ".", "_domain_codes", "[", "domain"...
Register a new error code
[ "Register", "a", "new", "error", "code" ]
python
train
54.5
hyperledger/indy-plenum
plenum/common/did_method.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/did_method.py#L34-L43
def get(self, didMethodName, required=True) -> DidMethod: """ :param didMethodName: name of DID Method :param required: if not found and True, throws an exception, else None :return: DID Method """ dm = self.d.get(didMethodName) if didMethodName else self.default ...
[ "def", "get", "(", "self", ",", "didMethodName", ",", "required", "=", "True", ")", "->", "DidMethod", ":", "dm", "=", "self", ".", "d", ".", "get", "(", "didMethodName", ")", "if", "didMethodName", "else", "self", ".", "default", "if", "not", "dm", ...
:param didMethodName: name of DID Method :param required: if not found and True, throws an exception, else None :return: DID Method
[ ":", "param", "didMethodName", ":", "name", "of", "DID", "Method", ":", "param", "required", ":", "if", "not", "found", "and", "True", "throws", "an", "exception", "else", "None", ":", "return", ":", "DID", "Method" ]
python
train
38.8
bugra/angel-list
angel/angel.py
https://github.com/bugra/angel-list/blob/75ac453e873727675ba18e1f45b5bc0cfda26fd7/angel/angel.py#L455-L462
def get_reviews(self, user_id): """ Get reviews for a particular user """ url = _REVIEWS_USER.format(c_api=_C_API_BEGINNING, api=_API_VERSION, user_id=user_id, at=s...
[ "def", "get_reviews", "(", "self", ",", "user_id", ")", ":", "url", "=", "_REVIEWS_USER", ".", "format", "(", "c_api", "=", "_C_API_BEGINNING", ",", "api", "=", "_API_VERSION", ",", "user_id", "=", "user_id", ",", "at", "=", "self", ".", "access_token", ...
Get reviews for a particular user
[ "Get", "reviews", "for", "a", "particular", "user" ]
python
train
44.875
SheffieldML/GPy
GPy/util/pca.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/pca.py#L41-L54
def center(self, X): """ Center `X` in PCA space. """ X = X.copy() inan = numpy.isnan(X) if self.mu is None: X_ = numpy.ma.masked_array(X, inan) self.mu = X_.mean(0).base self.sigma = X_.std(0).base reduce(lambda y,x: setitem(x[...
[ "def", "center", "(", "self", ",", "X", ")", ":", "X", "=", "X", ".", "copy", "(", ")", "inan", "=", "numpy", ".", "isnan", "(", "X", ")", "if", "self", ".", "mu", "is", "None", ":", "X_", "=", "numpy", ".", "ma", ".", "masked_array", "(", ...
Center `X` in PCA space.
[ "Center", "X", "in", "PCA", "space", "." ]
python
train
32.928571
twilio/twilio-python
twilio/rest/insights/v1/summary.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/insights/v1/summary.py#L130-L145
def fetch(self): """ Fetch a CallSummaryInstance :returns: Fetched CallSummaryInstance :rtype: twilio.rest.insights.v1.summary.CallSummaryInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, par...
[ "def", "fetch", "(", "self", ")", ":", "params", "=", "values", ".", "of", "(", "{", "}", ")", "payload", "=", "self", ".", "_version", ".", "fetch", "(", "'GET'", ",", "self", ".", "_uri", ",", "params", "=", "params", ",", ")", "return", "CallS...
Fetch a CallSummaryInstance :returns: Fetched CallSummaryInstance :rtype: twilio.rest.insights.v1.summary.CallSummaryInstance
[ "Fetch", "a", "CallSummaryInstance" ]
python
train
26.5625
gem/oq-engine
openquake/hmtk/seismicity/gcmt_catalogue.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L447-L503
def gcmt_to_simple_array(self, centroid_location=True): """ Converts the GCMT catalogue to a simple array of [ID, year, month, day, hour, minute, second, long., lat., depth, Mw, strike1, dip1, rake1, strike2, dip2, rake2, b-plunge, b-azimuth, b-eigenvalue, p-plunge, p-azimuth, p-...
[ "def", "gcmt_to_simple_array", "(", "self", ",", "centroid_location", "=", "True", ")", ":", "catalogue", "=", "np", ".", "zeros", "(", "[", "self", ".", "get_number_tensors", "(", ")", ",", "29", "]", ",", "dtype", "=", "float", ")", "for", "iloc", ",...
Converts the GCMT catalogue to a simple array of [ID, year, month, day, hour, minute, second, long., lat., depth, Mw, strike1, dip1, rake1, strike2, dip2, rake2, b-plunge, b-azimuth, b-eigenvalue, p-plunge, p-azimuth, p-eigenvalue, t-plunge, t-azimuth, t-eigenvalue, moment, f_clvd, erel]
[ "Converts", "the", "GCMT", "catalogue", "to", "a", "simple", "array", "of", "[", "ID", "year", "month", "day", "hour", "minute", "second", "long", ".", "lat", ".", "depth", "Mw", "strike1", "dip1", "rake1", "strike2", "dip2", "rake2", "b", "-", "plunge",...
python
train
60.192982
berkeley-cocosci/Wallace
examples/rogers/experiment.py
https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L168-L194
def data_check(self, participant): """Check a participants data.""" participant_id = participant.uniqueid nodes = Node.query.filter_by(participant_id=participant_id).all() if len(nodes) != self.experiment_repeats + self.practice_repeats: print("Error: Participant has {} nod...
[ "def", "data_check", "(", "self", ",", "participant", ")", ":", "participant_id", "=", "participant", ".", "uniqueid", "nodes", "=", "Node", ".", "query", ".", "filter_by", "(", "participant_id", "=", "participant_id", ")", ".", "all", "(", ")", "if", "len...
Check a participants data.
[ "Check", "a", "participants", "data", "." ]
python
train
37.518519
pkgw/pwkit
pwkit/lsqmdl.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/lsqmdl.py#L656-L660
def debug_derivative(self, guess): """returns (explicit, auto)""" from .lmmin import check_derivative return check_derivative(self.component.npar, self.data.size, self.lm_model, self.lm_deriv, guess)
[ "def", "debug_derivative", "(", "self", ",", "guess", ")", ":", "from", ".", "lmmin", "import", "check_derivative", "return", "check_derivative", "(", "self", ".", "component", ".", "npar", ",", "self", ".", "data", ".", "size", ",", "self", ".", "lm_model...
returns (explicit, auto)
[ "returns", "(", "explicit", "auto", ")" ]
python
train
50.2
pantsbuild/pants
src/python/pants/java/nailgun_io.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_io.py#L148-L156
def open(cls, sock, chunk_type, isatty, chunk_eof_type=None, buf_size=None, select_timeout=None): """Yields the write side of a pipe that will copy appropriately chunked values to a socket.""" with cls.open_multi(sock, (chunk_type,), (isatty,), ...
[ "def", "open", "(", "cls", ",", "sock", ",", "chunk_type", ",", "isatty", ",", "chunk_eof_type", "=", "None", ",", "buf_size", "=", "None", ",", "select_timeout", "=", "None", ")", ":", "with", "cls", ".", "open_multi", "(", "sock", ",", "(", "chunk_ty...
Yields the write side of a pipe that will copy appropriately chunked values to a socket.
[ "Yields", "the", "write", "side", "of", "a", "pipe", "that", "will", "copy", "appropriately", "chunked", "values", "to", "a", "socket", "." ]
python
train
47.777778
FujiMakoto/IPS-Vagrant
ips_vagrant/installer/__init__.py
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/installer/__init__.py#L17-L42
def installer(cv, ctx, site, force=False): """ Installer factory @param cv: Current version (The version of IPS we are installing) @type cv: ips_vagrant.common.version.Version @type ctx: ips_vagrant.cli.Context @param site: The IPS Site we are installing @type site: ip...
[ "def", "installer", "(", "cv", ",", "ctx", ",", "site", ",", "force", "=", "False", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "'ipsv.installer'", ")", "log", ".", "info", "(", "'Loading installer for IPS %s'", ",", "cv", ")", "iv", "=", "...
Installer factory @param cv: Current version (The version of IPS we are installing) @type cv: ips_vagrant.common.version.Version @type ctx: ips_vagrant.cli.Context @param site: The IPS Site we are installing @type site: ips_vagrant.models.sites.Site @param force: Overwri...
[ "Installer", "factory" ]
python
train
42
gem/oq-engine
openquake/calculators/views.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L382-L393
def view_portfolio_losses(token, dstore): """ The losses for the full portfolio, for each realization and loss type, extracted from the event loss table. """ oq = dstore['oqparam'] loss_dt = oq.loss_dt() data = portfolio_loss(dstore).view(loss_dt)[:, 0] rlzids = [str(r) for r in range(le...
[ "def", "view_portfolio_losses", "(", "token", ",", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "loss_dt", "=", "oq", ".", "loss_dt", "(", ")", "data", "=", "portfolio_loss", "(", "dstore", ")", ".", "view", "(", "loss_dt", ")", "[",...
The losses for the full portfolio, for each realization and loss type, extracted from the event loss table.
[ "The", "losses", "for", "the", "full", "portfolio", "for", "each", "realization", "and", "loss", "type", "extracted", "from", "the", "event", "loss", "table", "." ]
python
train
41.916667
IBMStreams/pypi.streamsx
streamsx/spl/op.py
https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/op.py#L240-L254
def output(self, stream, value): """SPL output port assignment expression. Arguments: stream(Stream): Output stream the assignment is for. value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`. Returns: ...
[ "def", "output", "(", "self", ",", "stream", ",", "value", ")", ":", "if", "stream", "not", "in", "self", ".", "outputs", ":", "raise", "ValueError", "(", "\"Stream is not an output of this operator.\"", ")", "e", "=", "self", ".", "expression", "(", "value"...
SPL output port assignment expression. Arguments: stream(Stream): Output stream the assignment is for. value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`. Returns: Expression: Output assignment ex...
[ "SPL", "output", "port", "assignment", "expression", "." ]
python
train
40.733333
koordinates/python-client
koordinates/base.py
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/base.py#L279-L296
def filter(self, **filters): """ Add a filter to this query. Appends to any previous filters set. :rtype: Query """ q = self._clone() for key, value in filters.items(): filter_key = re.split('__', key) filter_attr = filter_key[0] ...
[ "def", "filter", "(", "self", ",", "*", "*", "filters", ")", ":", "q", "=", "self", ".", "_clone", "(", ")", "for", "key", ",", "value", "in", "filters", ".", "items", "(", ")", ":", "filter_key", "=", "re", ".", "split", "(", "'__'", ",", "key...
Add a filter to this query. Appends to any previous filters set. :rtype: Query
[ "Add", "a", "filter", "to", "this", "query", ".", "Appends", "to", "any", "previous", "filters", "set", "." ]
python
train
32.888889
Erotemic/ubelt
ubelt/util_list.py
https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L324-L353
def unique_flags(items, key=None): """ Returns a list of booleans corresponding to the first instance of each unique item. Args: items (Sequence): indexable collection of items key (Callable, optional): custom normalization function. If specified returns items where `key(it...
[ "def", "unique_flags", "(", "items", ",", "key", "=", "None", ")", ":", "len_", "=", "len", "(", "items", ")", "if", "key", "is", "None", ":", "item_to_index", "=", "dict", "(", "zip", "(", "reversed", "(", "items", ")", ",", "reversed", "(", "rang...
Returns a list of booleans corresponding to the first instance of each unique item. Args: items (Sequence): indexable collection of items key (Callable, optional): custom normalization function. If specified returns items where `key(item)` is unique. Returns: List[bool...
[ "Returns", "a", "list", "of", "booleans", "corresponding", "to", "the", "first", "instance", "of", "each", "unique", "item", "." ]
python
valid
32.933333
b3j0f/schema
b3j0f/schema/registry.py
https://github.com/b3j0f/schema/blob/1c88c23337f5fef50254e65bd407112c43396dd9/b3j0f/schema/registry.py#L122-L132
def unregister(self, uuid): """Unregister a schema registered with input uuid. :raises: KeyError if uuid is not already registered. """ schema = self._schbyuuid.pop(uuid) # clean schemas by name self._schbyname[schema.name].remove(schema) if not self._schbyname[...
[ "def", "unregister", "(", "self", ",", "uuid", ")", ":", "schema", "=", "self", ".", "_schbyuuid", ".", "pop", "(", "uuid", ")", "# clean schemas by name", "self", ".", "_schbyname", "[", "schema", ".", "name", "]", ".", "remove", "(", "schema", ")", "...
Unregister a schema registered with input uuid. :raises: KeyError if uuid is not already registered.
[ "Unregister", "a", "schema", "registered", "with", "input", "uuid", "." ]
python
train
33.454545
IdentityPython/oidcendpoint
src/oidcendpoint/user_info/__init__.py
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/user_info/__init__.py#L41-L66
def filter(self, userinfo, user_info_claims=None): """ Return only those claims that are asked for. It's a best effort task; if essential claims are not present no error is flagged. :param userinfo: A dictionary containing the available info for one user :param user_info...
[ "def", "filter", "(", "self", ",", "userinfo", ",", "user_info_claims", "=", "None", ")", ":", "if", "user_info_claims", "is", "None", ":", "return", "copy", ".", "copy", "(", "userinfo", ")", "else", ":", "result", "=", "{", "}", "missing", "=", "[", ...
Return only those claims that are asked for. It's a best effort task; if essential claims are not present no error is flagged. :param userinfo: A dictionary containing the available info for one user :param user_info_claims: A dictionary specifying the asked for claims :return: ...
[ "Return", "only", "those", "claims", "that", "are", "asked", "for", ".", "It", "s", "a", "best", "effort", "task", ";", "if", "essential", "claims", "are", "not", "present", "no", "error", "is", "flagged", "." ]
python
train
35.692308
pyBookshelf/bookshelf
bookshelf/api_v1.py
https://github.com/pyBookshelf/bookshelf/blob/a6770678e735de95b194f6e6989223970db5f654/bookshelf/api_v1.py#L1498-L1506
def load_state_from_disk(): """ loads the state from a local data.json file """ if is_there_state(): with open('data.json', 'r') as f: data = json.load(f) return data else: return False
[ "def", "load_state_from_disk", "(", ")", ":", "if", "is_there_state", "(", ")", ":", "with", "open", "(", "'data.json'", ",", "'r'", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ")", "return", "data", "else", ":", "return", "False...
loads the state from a local data.json file
[ "loads", "the", "state", "from", "a", "local", "data", ".", "json", "file" ]
python
train
25.444444
saltstack/salt
salt/modules/win_pkg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L1757-L2044
def remove(name=None, pkgs=None, **kwargs): ''' Remove the passed package(s) from the system using winrepo .. versionadded:: 0.16.0 Args: name (str): The name(s) of the package(s) to be uninstalled. Can be a single package or a comma delimited list of packages, no space...
[ "def", "remove", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "saltenv", "=", "kwargs", ".", "get", "(", "'saltenv'", ",", "'base'", ")", "refresh", "=", "salt", ".", "utils", ".", "data", ".", "is_true", ...
Remove the passed package(s) from the system using winrepo .. versionadded:: 0.16.0 Args: name (str): The name(s) of the package(s) to be uninstalled. Can be a single package or a comma delimited list of packages, no spaces. pkgs (list): A list of packages ...
[ "Remove", "the", "passed", "package", "(", "s", ")", "from", "the", "system", "using", "winrepo" ]
python
train
43.9375
ibis-project/ibis
ibis/mapd/client.py
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/mapd/client.py#L485-L508
def drop_database(self, name, force=False): """ Drop an MapD database Parameters ---------- name : string Database name force : boolean, default False If False and there are any tables in this database, raises an IntegrityError """ ...
[ "def", "drop_database", "(", "self", ",", "name", ",", "force", "=", "False", ")", ":", "tables", "=", "[", "]", "if", "not", "force", "or", "self", ".", "database", "(", "name", ")", ":", "tables", "=", "self", ".", "list_tables", "(", "database", ...
Drop an MapD database Parameters ---------- name : string Database name force : boolean, default False If False and there are any tables in this database, raises an IntegrityError
[ "Drop", "an", "MapD", "database" ]
python
train
29.083333
yyuu/botornado
boto/s3/connection.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/s3/connection.py#L193-L290
def build_post_form_args(self, bucket_name, key, expires_in = 6000, acl = None, success_action_redirect = None, max_content_length = None, http_method = "http", fields=None, conditions=None): """ ...
[ "def", "build_post_form_args", "(", "self", ",", "bucket_name", ",", "key", ",", "expires_in", "=", "6000", ",", "acl", "=", "None", ",", "success_action_redirect", "=", "None", ",", "max_content_length", "=", "None", ",", "http_method", "=", "\"http\"", ",", ...
Taken from the AWS book Python examples and modified for use with boto This only returns the arguments required for the post form, not the actual form. This does not return the file input field which also needs to be added :type bucket_name: string :param bucket_name: ...
[ "Taken", "from", "the", "AWS", "book", "Python", "examples", "and", "modified", "for", "use", "with", "boto", "This", "only", "returns", "the", "arguments", "required", "for", "the", "post", "form", "not", "the", "actual", "form", ".", "This", "does", "not...
python
train
40.857143
ponty/eagexp
eagexp/partlist.py
https://github.com/ponty/eagexp/blob/1dd5108c1d8112cc87d1bda64fa6c2784ccf0ff2/eagexp/partlist.py#L90-L100
def structured_partlist(input, timeout=20, showgui=False): '''export partlist by eagle, then parse it :param input: .sch or .brd file name :param timeout: int :param showgui: Bool, True -> do not hide eagle GUI :rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value'...
[ "def", "structured_partlist", "(", "input", ",", "timeout", "=", "20", ",", "showgui", "=", "False", ")", ":", "s", "=", "raw_partlist", "(", "input", "=", "input", ",", "timeout", "=", "timeout", ",", "showgui", "=", "showgui", ")", "return", "parse_par...
export partlist by eagle, then parse it :param input: .sch or .brd file name :param timeout: int :param showgui: Bool, True -> do not hide eagle GUI :rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value':'1n'}, ..])
[ "export", "partlist", "by", "eagle", "then", "parse", "it" ]
python
train
38.909091
eandersson/amqpstorm
amqpstorm/management/exchange.py
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L14-L31
def get(self, exchange, virtual_host='/'): """Get Exchange details. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity i...
[ "def", "get", "(", "self", ",", "exchange", ",", "virtual_host", "=", "'/'", ")", ":", "virtual_host", "=", "quote", "(", "virtual_host", ",", "''", ")", "return", "self", ".", "http_client", ".", "get", "(", "API_EXCHANGE", "%", "(", "virtual_host", ","...
Get Exchange details. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
[ "Get", "Exchange", "details", "." ]
python
train
29.611111
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1202-L1210
def set_min(self, fmin): """ Updates minimum value """ if round(100000*fmin) != 100000*fmin: raise DriverError('utils.widgets.Expose.set_min: ' + 'fmin must be a multiple of 0.00001') self.fmin = fmin self.set(self.fmin)
[ "def", "set_min", "(", "self", ",", "fmin", ")", ":", "if", "round", "(", "100000", "*", "fmin", ")", "!=", "100000", "*", "fmin", ":", "raise", "DriverError", "(", "'utils.widgets.Expose.set_min: '", "+", "'fmin must be a multiple of 0.00001'", ")", "self", "...
Updates minimum value
[ "Updates", "minimum", "value" ]
python
train
33.555556
cloud-custodian/cloud-custodian
tools/c7n_salactus/c7n_salactus/cli.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L587-L641
def inspect_partitions(bucket): """Discover the partitions on a bucket via introspection. For large buckets which lack s3 inventories, salactus will attempt to process objects in parallel on the bucket by breaking the bucket into a separate keyspace partitions. It does this with a heurestic that at...
[ "def", "inspect_partitions", "(", "bucket", ")", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "\"%(asctime)s: %(name)s:%(levelname)s %(message)s\"", ")", "logging", ".", "getLogger", "(", "'botocore'", ")", "."...
Discover the partitions on a bucket via introspection. For large buckets which lack s3 inventories, salactus will attempt to process objects in parallel on the bucket by breaking the bucket into a separate keyspace partitions. It does this with a heurestic that attempts to sample the keyspace and deter...
[ "Discover", "the", "partitions", "on", "a", "bucket", "via", "introspection", "." ]
python
train
31.090909
thombashi/pytablereader
pytablereader/factory/_url.py
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/factory/_url.py#L225-L242
def _get_format_name_loader_mapping(self): """ :return: Mappings of format-name and loader class. :rtype: dict """ loader_table = self._get_common_loader_mapping() loader_table.update( { "excel": ExcelTableFileLoader, "json_lin...
[ "def", "_get_format_name_loader_mapping", "(", "self", ")", ":", "loader_table", "=", "self", ".", "_get_common_loader_mapping", "(", ")", "loader_table", ".", "update", "(", "{", "\"excel\"", ":", "ExcelTableFileLoader", ",", "\"json_lines\"", ":", "JsonLinesTableTex...
:return: Mappings of format-name and loader class. :rtype: dict
[ ":", "return", ":", "Mappings", "of", "format", "-", "name", "and", "loader", "class", ".", ":", "rtype", ":", "dict" ]
python
train
29.833333
Anaconda-Platform/anaconda-client
binstar_client/__init__.py
https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L249-L291
def user_packages( self, login=None, platform=None, package_type=None, type_=None, access=None): ''' Returns a list of packages for a given user and optionally filter by `platform`, `package_type` and `type_`. :para...
[ "def", "user_packages", "(", "self", ",", "login", "=", "None", ",", "platform", "=", "None", ",", "package_type", "=", "None", ",", "type_", "=", "None", ",", "access", "=", "None", ")", ":", "if", "login", ":", "url", "=", "'{0}/packages/{1}'", ".", ...
Returns a list of packages for a given user and optionally filter by `platform`, `package_type` and `type_`. :param login: (optional) the login name of the user or None. If login is None this method will return the packages for the authenticated user. ...
[ "Returns", "a", "list", "of", "packages", "for", "a", "given", "user", "and", "optionally", "filter", "by", "platform", "package_type", "and", "type_", "." ]
python
train
35.116279
willkg/markus
markus/main.py
https://github.com/willkg/markus/blob/0cfbe67fb7ccfa7488b0120d21ddc0cdc1f8ed33/markus/main.py#L320-L359
def timer(self, stat, tags=None): """Contextmanager for easily computing timings. :arg string stat: A period delimited alphanumeric key. :arg list-of-strings tags: Each string in the tag consists of a key and a value separated by a colon. Tags can make it easier to break down ...
[ "def", "timer", "(", "self", ",", "stat", ",", "tags", "=", "None", ")", ":", "if", "six", ".", "PY3", ":", "start_time", "=", "time", ".", "perf_counter", "(", ")", "else", ":", "start_time", "=", "time", ".", "time", "(", ")", "yield", "if", "s...
Contextmanager for easily computing timings. :arg string stat: A period delimited alphanumeric key. :arg list-of-strings tags: Each string in the tag consists of a key and a value separated by a colon. Tags can make it easier to break down metrics for analysis. For...
[ "Contextmanager", "for", "easily", "computing", "timings", "." ]
python
test
26.55