repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
Yelp/detect-secrets
detect_secrets/core/secrets_collection.py
https://github.com/Yelp/detect-secrets/blob/473923ea71f1ac2b5ea1eacc49b98f97967e3d05/detect_secrets/core/secrets_collection.py#L213-L247
def get_secret(self, filename, secret, type_=None): """Checks to see whether a secret is found in the collection. :type filename: str :param filename: the file to search in. :type secret: str :param secret: secret hash of secret to search for. :type type_: str ...
[ "def", "get_secret", "(", "self", ",", "filename", ",", "secret", ",", "type_", "=", "None", ")", ":", "if", "filename", "not", "in", "self", ".", "data", ":", "return", "None", "if", "type_", ":", "# Optimized lookup, because we know the type of secret", "# (...
Checks to see whether a secret is found in the collection. :type filename: str :param filename: the file to search in. :type secret: str :param secret: secret hash of secret to search for. :type type_: str :param type_: type of secret, if known. :rtype: Potent...
[ "Checks", "to", "see", "whether", "a", "secret", "is", "found", "in", "the", "collection", "." ]
python
train
QuantEcon/QuantEcon.py
quantecon/game_theory/repeated_game.py
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/game_theory/repeated_game.py#L178-L202
def _best_dev_gains(rpg): """ Calculate the normalized payoff gains from deviating from the current action to the best response for each player. Parameters ---------- rpg : RepeatedGame Two player repeated game. Returns ------- best_dev_gains : tuple(ndarray(float, ndim=2))...
[ "def", "_best_dev_gains", "(", "rpg", ")", ":", "sg", ",", "delta", "=", "rpg", ".", "sg", ",", "rpg", ".", "delta", "best_dev_gains", "=", "(", "(", "1", "-", "delta", ")", "/", "delta", "*", "(", "np", ".", "max", "(", "sg", ".", "payoff_arrays...
Calculate the normalized payoff gains from deviating from the current action to the best response for each player. Parameters ---------- rpg : RepeatedGame Two player repeated game. Returns ------- best_dev_gains : tuple(ndarray(float, ndim=2)) The normalized best deviation...
[ "Calculate", "the", "normalized", "payoff", "gains", "from", "deviating", "from", "the", "current", "action", "to", "the", "best", "response", "for", "each", "player", "." ]
python
train
timofurrer/w1thermsensor
w1thermsensor/cli.py
https://github.com/timofurrer/w1thermsensor/blob/8ac4fbb85e0c247dbb39e8b178cca0a975adc332/w1thermsensor/cli.py#L65-L86
def ls(types, as_json): # pylint: disable=invalid-name """List all available sensors""" sensors = W1ThermSensor.get_available_sensors(types) if as_json: data = [ {"id": i, "hwid": s.id, "type": s.type_name} for i, s in enumerate(sensors, 1) ] click.echo(json...
[ "def", "ls", "(", "types", ",", "as_json", ")", ":", "# pylint: disable=invalid-name", "sensors", "=", "W1ThermSensor", ".", "get_available_sensors", "(", "types", ")", "if", "as_json", ":", "data", "=", "[", "{", "\"id\"", ":", "i", ",", "\"hwid\"", ":", ...
List all available sensors
[ "List", "all", "available", "sensors" ]
python
train
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem_utils.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem_utils.py#L30-L46
def play_env_problem_randomly(env_problem, num_steps): """Plays the env problem by randomly sampling actions for `num_steps`.""" # Reset all environments. env_problem.reset() # Play all environments, sampling random actions each time. for _ in range(num_steps): # Sample batc...
[ "def", "play_env_problem_randomly", "(", "env_problem", ",", "num_steps", ")", ":", "# Reset all environments.", "env_problem", ".", "reset", "(", ")", "# Play all environments, sampling random actions each time.", "for", "_", "in", "range", "(", "num_steps", ")", ":", ...
Plays the env problem by randomly sampling actions for `num_steps`.
[ "Plays", "the", "env", "problem", "by", "randomly", "sampling", "actions", "for", "num_steps", "." ]
python
train
alphatwirl/alphatwirl
alphatwirl/parallel/build.py
https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/parallel/build.py#L14-L66
def build_parallel(parallel_mode, quiet=True, processes=4, user_modules=None, dispatcher_options=None): """initializes `Parallel` Parameters ---------- parallel_mode : str "multiprocessing" (default), "htcondor" or "subprocess" quiet : bool, optional if True, prog...
[ "def", "build_parallel", "(", "parallel_mode", ",", "quiet", "=", "True", ",", "processes", "=", "4", ",", "user_modules", "=", "None", ",", "dispatcher_options", "=", "None", ")", ":", "if", "user_modules", "is", "None", ":", "user_modules", "=", "[", "]"...
initializes `Parallel` Parameters ---------- parallel_mode : str "multiprocessing" (default), "htcondor" or "subprocess" quiet : bool, optional if True, progress bars will not be shown in the "multiprocessing" mode. process : int, optional The number of processes when ``para...
[ "initializes", "Parallel" ]
python
valid
EasyPost/pystalk
pystalk/client.py
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L536-L559
def using(self, tube): """Context-manager to insert jobs into a specific tube :param tube: Tube to insert to Yields out an instance of :class:`BeanstalkInsertingProxy` to insert items into that tube .. seealso:: :func:`use()` Change the default tube ...
[ "def", "using", "(", "self", ",", "tube", ")", ":", "try", ":", "current_tube", "=", "self", ".", "current_tube", "self", ".", "use", "(", "tube", ")", "yield", "BeanstalkInsertingProxy", "(", "self", ",", "tube", ")", "finally", ":", "self", ".", "use...
Context-manager to insert jobs into a specific tube :param tube: Tube to insert to Yields out an instance of :class:`BeanstalkInsertingProxy` to insert items into that tube .. seealso:: :func:`use()` Change the default tube :func:`put_job()` ...
[ "Context", "-", "manager", "to", "insert", "jobs", "into", "a", "specific", "tube" ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_speech.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_speech.py#L27-L42
def kill_speech_dispatcher(self): '''kill speech dispatcher processs''' if not 'HOME' in os.environ: return pidpath = os.path.join(os.environ['HOME'], '.speech-dispatcher', 'pid', 'speech-dispatcher.pid') if os.path.exists(pidpath): ...
[ "def", "kill_speech_dispatcher", "(", "self", ")", ":", "if", "not", "'HOME'", "in", "os", ".", "environ", ":", "return", "pidpath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'HOME'", "]", ",", "'.speech-dispatcher'", ",", "...
kill speech dispatcher processs
[ "kill", "speech", "dispatcher", "processs" ]
python
train
palantir/typedjsonrpc
contrib/multi-module-example/typedjsonrpc_example/valid.py
https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/contrib/multi-module-example/typedjsonrpc_example/valid.py#L22-L36
def histogram(data): """Returns a histogram of your data. :param data: The data to histogram :type data: list[object] :return: The histogram :rtype: dict[object, int] """ ret = {} for datum in data: if datum in ret: ret[datum] += 1 else: ret[datum...
[ "def", "histogram", "(", "data", ")", ":", "ret", "=", "{", "}", "for", "datum", "in", "data", ":", "if", "datum", "in", "ret", ":", "ret", "[", "datum", "]", "+=", "1", "else", ":", "ret", "[", "datum", "]", "=", "1", "return", "ret" ]
Returns a histogram of your data. :param data: The data to histogram :type data: list[object] :return: The histogram :rtype: dict[object, int]
[ "Returns", "a", "histogram", "of", "your", "data", "." ]
python
train
marl/jams
jams/display.py
https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L32-L61
def pprint_jobject(obj, **kwargs): '''Pretty-print a jobject. Parameters ---------- obj : jams.JObject kwargs additional parameters to `json.dumps` Returns ------- string A simplified display of `obj` contents. ''' obj_simple = {k: v for k, v in six.iteritems(...
[ "def", "pprint_jobject", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "obj_simple", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "obj", ".", "__json__", ")", "if", "v", "}", "string", "=", "json", ".", "d...
Pretty-print a jobject. Parameters ---------- obj : jams.JObject kwargs additional parameters to `json.dumps` Returns ------- string A simplified display of `obj` contents.
[ "Pretty", "-", "print", "a", "jobject", "." ]
python
valid
stanfordnlp/stanza
stanza/monitoring/trigger.py
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/monitoring/trigger.py#L124-L131
def slope(self): """ :return: the esitmated slope for points in the current window """ x = range(self.window_size) y = self.vals slope, bias = np.polyfit(x, y, 1) return slope
[ "def", "slope", "(", "self", ")", ":", "x", "=", "range", "(", "self", ".", "window_size", ")", "y", "=", "self", ".", "vals", "slope", ",", "bias", "=", "np", ".", "polyfit", "(", "x", ",", "y", ",", "1", ")", "return", "slope" ]
:return: the esitmated slope for points in the current window
[ ":", "return", ":", "the", "esitmated", "slope", "for", "points", "in", "the", "current", "window" ]
python
train
pandas-dev/pandas
pandas/io/pytables.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3407-L3429
def read_axes(self, where, **kwargs): """create and return the axes sniffed from the table: return boolean for success """ # validate the version self.validate_version(where) # infer the data kind if not self.infer_axes(): return False # cre...
[ "def", "read_axes", "(", "self", ",", "where", ",", "*", "*", "kwargs", ")", ":", "# validate the version", "self", ".", "validate_version", "(", "where", ")", "# infer the data kind", "if", "not", "self", ".", "infer_axes", "(", ")", ":", "return", "False",...
create and return the axes sniffed from the table: return boolean for success
[ "create", "and", "return", "the", "axes", "sniffed", "from", "the", "table", ":", "return", "boolean", "for", "success" ]
python
train
osrg/ryu
ryu/services/protocols/bgp/speaker.py
https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/speaker.py#L300-L357
def _data_received(self, next_bytes): """Maintains buffer of bytes received from peer and extracts bgp message from this buffer if enough data is received. Validates bgp message marker, length, type and data and constructs appropriate bgp message instance and calls handler. :Pa...
[ "def", "_data_received", "(", "self", ",", "next_bytes", ")", ":", "# Append buffer with received bytes.", "self", ".", "_recv_buff", "+=", "next_bytes", "while", "True", ":", "# If current buffer size is less then minimum bgp message size, we", "# return as we do not have a comp...
Maintains buffer of bytes received from peer and extracts bgp message from this buffer if enough data is received. Validates bgp message marker, length, type and data and constructs appropriate bgp message instance and calls handler. :Parameters: - `next_bytes`: next set of...
[ "Maintains", "buffer", "of", "bytes", "received", "from", "peer", "and", "extracts", "bgp", "message", "from", "this", "buffer", "if", "enough", "data", "is", "received", "." ]
python
train
qacafe/cdrouter.py
cdrouter/packages.py
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/packages.py#L241-L253
def create(self, resource): """Create a new package. :param resource: :class:`packages.Package <packages.Package>` object :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package """ schema = PackageSchema(exclude=('id', 'created', 'updated',...
[ "def", "create", "(", "self", ",", "resource", ")", ":", "schema", "=", "PackageSchema", "(", "exclude", "=", "(", "'id'", ",", "'created'", ",", "'updated'", ",", "'test_count'", ",", "'agent_id'", ",", "'result_id'", ")", ")", "json", "=", "self", ".",...
Create a new package. :param resource: :class:`packages.Package <packages.Package>` object :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package
[ "Create", "a", "new", "package", "." ]
python
train
saltstack/salt
salt/modules/elasticsearch.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L754-L773
def index_template_delete(name, hosts=None, profile=None): ''' Delete an index template (type) along with its data name Index template name CLI example:: salt myminion elasticsearch.index_template_delete testindex_templ user ''' es = _get_instance(hosts, profile) try: ...
[ "def", "index_template_delete", "(", "name", ",", "hosts", "=", "None", ",", "profile", "=", "None", ")", ":", "es", "=", "_get_instance", "(", "hosts", ",", "profile", ")", "try", ":", "result", "=", "es", ".", "indices", ".", "delete_template", "(", ...
Delete an index template (type) along with its data name Index template name CLI example:: salt myminion elasticsearch.index_template_delete testindex_templ user
[ "Delete", "an", "index", "template", "(", "type", ")", "along", "with", "its", "data" ]
python
train
edx/opaque-keys
opaque_keys/edx/locator.py
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L946-L955
def _to_deprecated_string(self): """ Returns an old-style location, represented as: i4x://org/course/category/name[@revision] # Revision is optional """ # pylint: disable=missing-format-attribute url = u"{0.DEPRECATED_TAG}://{0.course_key.org}/{0.course_key.course}/{0.bl...
[ "def", "_to_deprecated_string", "(", "self", ")", ":", "# pylint: disable=missing-format-attribute", "url", "=", "u\"{0.DEPRECATED_TAG}://{0.course_key.org}/{0.course_key.course}/{0.block_type}/{0.block_id}\"", ".", "format", "(", "self", ")", "if", "self", ".", "course_key", "...
Returns an old-style location, represented as: i4x://org/course/category/name[@revision] # Revision is optional
[ "Returns", "an", "old", "-", "style", "location", "represented", "as", ":", "i4x", ":", "//", "org", "/", "course", "/", "category", "/", "name", "[" ]
python
train
jaumebonet/libconfig
libconfig/config.py
https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L72-L89
def unregister_option(self, key, subkey): """Removes an option from the manager. :param str key: First identifier of the option. :param str subkey: Second identifier of the option. raise: :NotRegisteredError: If ``key`` or ``subkey`` do not define any option...
[ "def", "unregister_option", "(", "self", ",", "key", ",", "subkey", ")", ":", "if", "not", "self", ".", "open", ":", "return", "key", ",", "subkey", "=", "_lower_keys", "(", "key", ",", "subkey", ")", "_entry_must_exist", "(", "self", ".", "gc", ",", ...
Removes an option from the manager. :param str key: First identifier of the option. :param str subkey: Second identifier of the option. raise: :NotRegisteredError: If ``key`` or ``subkey`` do not define any option.
[ "Removes", "an", "option", "from", "the", "manager", "." ]
python
train
rosenbrockc/acorn
acorn/logging/decoration.py
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L818-L849
def _safe_setattr(obj, name, value): """Safely sets the attribute of the specified object. This includes not setting attributes for final objects and setting __func__ for instancemethod typed objects. Args: obj: object to set an attribute for. name (str): new attribute name. val...
[ "def", "_safe_setattr", "(", "obj", ",", "name", ",", "value", ")", ":", "okey", "=", "id", "(", "obj", ")", "if", "okey", "in", "_set_failures", "or", "okey", "in", "_final_objs", ":", "return", "False", "import", "inspect", "try", ":", "if", "inspect...
Safely sets the attribute of the specified object. This includes not setting attributes for final objects and setting __func__ for instancemethod typed objects. Args: obj: object to set an attribute for. name (str): new attribute name. value: new attribute value. Returns: ...
[ "Safely", "sets", "the", "attribute", "of", "the", "specified", "object", ".", "This", "includes", "not", "setting", "attributes", "for", "final", "objects", "and", "setting", "__func__", "for", "instancemethod", "typed", "objects", "." ]
python
train
elifesciences/elife-tools
elifetools/parseJATS.py
https://github.com/elifesciences/elife-tools/blob/4b9e38cbe485c61a4ed7cbd8970c6b318334fd86/elifetools/parseJATS.py#L2303-L2309
def body_block_paragraph_content(text): "for formatting of simple paragraphs of text only, and check if it is all whitespace" tag_content = OrderedDict() if text and text != '': tag_content["type"] = "paragraph" tag_content["text"] = clean_whitespace(text) return tag_content
[ "def", "body_block_paragraph_content", "(", "text", ")", ":", "tag_content", "=", "OrderedDict", "(", ")", "if", "text", "and", "text", "!=", "''", ":", "tag_content", "[", "\"type\"", "]", "=", "\"paragraph\"", "tag_content", "[", "\"text\"", "]", "=", "cle...
for formatting of simple paragraphs of text only, and check if it is all whitespace
[ "for", "formatting", "of", "simple", "paragraphs", "of", "text", "only", "and", "check", "if", "it", "is", "all", "whitespace" ]
python
train
tensorflow/lucid
lucid/misc/io/serialize_array.py
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/serialize_array.py#L31-L77
def _normalize_array(array, domain=(0, 1)): """Given an arbitrary rank-3 NumPy array, produce one representing an image. This ensures the resulting array has a dtype of uint8 and a domain of 0-255. Args: array: NumPy array representing the image domain: expected range of values in array, defaults ...
[ "def", "_normalize_array", "(", "array", ",", "domain", "=", "(", "0", ",", "1", ")", ")", ":", "# first copy the input so we're never mutating the user's data", "array", "=", "np", ".", "array", "(", "array", ")", "# squeeze helps both with batch=1 and B/W and PIL's mo...
Given an arbitrary rank-3 NumPy array, produce one representing an image. This ensures the resulting array has a dtype of uint8 and a domain of 0-255. Args: array: NumPy array representing the image domain: expected range of values in array, defaults to (0, 1), if explicitly set to None will use the...
[ "Given", "an", "arbitrary", "rank", "-", "3", "NumPy", "array", "produce", "one", "representing", "an", "image", "." ]
python
train
combust/mleap
python/mleap/sklearn/preprocessing/data.py
https://github.com/combust/mleap/blob/dc6b79db03ec27a0ba08b289842551e73d517ab3/python/mleap/sklearn/preprocessing/data.py#L907-L926
def transform(self, y): """ Transform features per specified math function. :param y: :return: """ if self.transform_type == 'log': return np.log(y) elif self.transform_type == 'exp': return np.exp(y) elif self.transform_type == 'sq...
[ "def", "transform", "(", "self", ",", "y", ")", ":", "if", "self", ".", "transform_type", "==", "'log'", ":", "return", "np", ".", "log", "(", "y", ")", "elif", "self", ".", "transform_type", "==", "'exp'", ":", "return", "np", ".", "exp", "(", "y"...
Transform features per specified math function. :param y: :return:
[ "Transform", "features", "per", "specified", "math", "function", ".", ":", "param", "y", ":", ":", "return", ":" ]
python
train
mabuchilab/QNET
src/qnet/printing/base.py
https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/printing/base.py#L99-L112
def _isinstance(expr, classname): """Check whether `expr` is an instance of the class with name `classname` This is like the builtin `isinstance`, but it take the `classname` a string, instead of the class directly. Useful for when we don't want to import the class for which we ...
[ "def", "_isinstance", "(", "expr", ",", "classname", ")", ":", "for", "cls", "in", "type", "(", "expr", ")", ".", "__mro__", ":", "if", "cls", ".", "__name__", "==", "classname", ":", "return", "True", "return", "False" ]
Check whether `expr` is an instance of the class with name `classname` This is like the builtin `isinstance`, but it take the `classname` a string, instead of the class directly. Useful for when we don't want to import the class for which we want to check (also, remember that pr...
[ "Check", "whether", "expr", "is", "an", "instance", "of", "the", "class", "with", "name", "classname" ]
python
train
DataONEorg/d1_python
lib_client/src/d1_client/solr_client.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/solr_client.py#L185-L192
def get_ids(self, start=0, rows=1000, **query_dict): """Retrieve a list of identifiers for documents matching the query.""" resp_dict = self._get_query(start=start, rows=rows, **query_dict) return { 'matches': resp_dict['response']['numFound'], 'start': start, ...
[ "def", "get_ids", "(", "self", ",", "start", "=", "0", ",", "rows", "=", "1000", ",", "*", "*", "query_dict", ")", ":", "resp_dict", "=", "self", ".", "_get_query", "(", "start", "=", "start", ",", "rows", "=", "rows", ",", "*", "*", "query_dict", ...
Retrieve a list of identifiers for documents matching the query.
[ "Retrieve", "a", "list", "of", "identifiers", "for", "documents", "matching", "the", "query", "." ]
python
train
learningequality/ricecooker
ricecooker/utils/tokens.py
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/tokens.py#L45-L55
def prompt_token(domain): """ Prompt user to enter content curation server authentication token. Args: domain (str): domain to authenticate user Returns: token """ token = input("\nEnter content curation server token ('q' to quit): ").lower() if token == 'q': sys.exit() else: ...
[ "def", "prompt_token", "(", "domain", ")", ":", "token", "=", "input", "(", "\"\\nEnter content curation server token ('q' to quit): \"", ")", ".", "lower", "(", ")", "if", "token", "==", "'q'", ":", "sys", ".", "exit", "(", ")", "else", ":", "return", "toke...
Prompt user to enter content curation server authentication token. Args: domain (str): domain to authenticate user Returns: token
[ "Prompt", "user", "to", "enter", "content", "curation", "server", "authentication", "token", ".", "Args", ":", "domain", "(", "str", ")", ":", "domain", "to", "authenticate", "user", "Returns", ":", "token" ]
python
train
ponty/pyscreenshot
pyscreenshot/__init__.py
https://github.com/ponty/pyscreenshot/blob/51010195cbb5361dcd4b414ff132b87244c9e1cb/pyscreenshot/__init__.py#L70-L81
def grab_to_file(filename, childprocess=None, backend=None): """Copy the contents of the screen to a file. Internal function! Use PIL.Image.save() for saving image to file. :param filename: file for saving :param childprocess: see :py:func:`grab` :param backend: see :py:func:`grab` """ if c...
[ "def", "grab_to_file", "(", "filename", ",", "childprocess", "=", "None", ",", "backend", "=", "None", ")", ":", "if", "childprocess", "is", "None", ":", "childprocess", "=", "childprocess_default_value", "(", ")", "return", "_grab", "(", "to_file", "=", "Tr...
Copy the contents of the screen to a file. Internal function! Use PIL.Image.save() for saving image to file. :param filename: file for saving :param childprocess: see :py:func:`grab` :param backend: see :py:func:`grab`
[ "Copy", "the", "contents", "of", "the", "screen", "to", "a", "file", ".", "Internal", "function!", "Use", "PIL", ".", "Image", ".", "save", "()", "for", "saving", "image", "to", "file", "." ]
python
valid
pebble/libpebble2
libpebble2/protocol/base/__init__.py
https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/protocol/base/__init__.py#L112-L141
def serialise(self, default_endianness=None): """ Serialise a message, without including any framing. :param default_endianness: The default endianness, unless overridden by the fields or class metadata. Should usually be left at ``None``. Otherwise, use ``'<'...
[ "def", "serialise", "(", "self", ",", "default_endianness", "=", "None", ")", ":", "# Figure out an endianness.", "endianness", "=", "(", "default_endianness", "or", "DEFAULT_ENDIANNESS", ")", "if", "hasattr", "(", "self", ",", "'_Meta'", ")", ":", "endianness", ...
Serialise a message, without including any framing. :param default_endianness: The default endianness, unless overridden by the fields or class metadata. Should usually be left at ``None``. Otherwise, use ``'<'`` for little endian and ``'>'`...
[ "Serialise", "a", "message", "without", "including", "any", "framing", "." ]
python
train
peterldowns/djoauth2
djoauth2/authorization.py
https://github.com/peterldowns/djoauth2/blob/151c7619d1d7a91d720397cfecf3a29fcc9747a9/djoauth2/authorization.py#L359-L416
def make_authorization_endpoint(missing_redirect_uri, authorization_endpoint_uri, authorization_template_name): """ Returns a endpoint that handles OAuth authorization requests. The template described by ``authorization_template_name`` is rendered wi...
[ "def", "make_authorization_endpoint", "(", "missing_redirect_uri", ",", "authorization_endpoint_uri", ",", "authorization_template_name", ")", ":", "@", "login_required", "@", "require_http_methods", "(", "[", "'GET'", ",", "'POST'", "]", ")", "def", "authorization_endpoi...
Returns a endpoint that handles OAuth authorization requests. The template described by ``authorization_template_name`` is rendered with a Django ``RequestContext`` with the following variables: * ``form``: a Django ``Form`` that may hold data internal to the ``djoauth2`` application. * ``client``: The :...
[ "Returns", "a", "endpoint", "that", "handles", "OAuth", "authorization", "requests", "." ]
python
train
python-openxml/python-docx
docx/image/helpers.py
https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/image/helpers.py#L43-L51
def read_long(self, base, offset=0): """ Return the int value of the four bytes at the file position defined by self._base_offset + *base* + *offset*. If *base* is None, the long is read from the current position in the stream. The endian setting of this instance is used to inter...
[ "def", "read_long", "(", "self", ",", "base", ",", "offset", "=", "0", ")", ":", "fmt", "=", "'<L'", "if", "self", ".", "_byte_order", "is", "LITTLE_ENDIAN", "else", "'>L'", "return", "self", ".", "_read_int", "(", "fmt", ",", "base", ",", "offset", ...
Return the int value of the four bytes at the file position defined by self._base_offset + *base* + *offset*. If *base* is None, the long is read from the current position in the stream. The endian setting of this instance is used to interpret the byte layout of the long.
[ "Return", "the", "int", "value", "of", "the", "four", "bytes", "at", "the", "file", "position", "defined", "by", "self", ".", "_base_offset", "+", "*", "base", "*", "+", "*", "offset", "*", ".", "If", "*", "base", "*", "is", "None", "the", "long", ...
python
train
saltstack/salt
salt/modules/file.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L112-L131
def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should...
[ "def", "_binary_replace", "(", "old", ",", "new", ")", ":", "old_isbin", "=", "not", "__utils__", "[", "'files.is_text'", "]", "(", "old", ")", "new_isbin", "=", "not", "__utils__", "[", "'files.is_text'", "]", "(", "new", ")", "if", "any", "(", "(", "...
This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined t...
[ "This", "function", "does", "NOT", "do", "any", "diffing", "it", "just", "checks", "the", "old", "and", "new", "files", "to", "see", "if", "either", "is", "binary", "and", "provides", "an", "appropriate", "string", "noting", "the", "difference", "between", ...
python
train
coinbase/coinbase-python
coinbase/wallet/client.py
https://github.com/coinbase/coinbase-python/blob/497c28158f529e8c7d0228521b4386a890baf088/coinbase/wallet/client.py#L217-L221
def get_buy_price(self, **params): """https://developers.coinbase.com/api/v2#get-buy-price""" currency_pair = params.get('currency_pair', 'BTC-USD') response = self._get('v2', 'prices', currency_pair, 'buy', params=params) return self._make_api_object(response, APIObject)
[ "def", "get_buy_price", "(", "self", ",", "*", "*", "params", ")", ":", "currency_pair", "=", "params", ".", "get", "(", "'currency_pair'", ",", "'BTC-USD'", ")", "response", "=", "self", ".", "_get", "(", "'v2'", ",", "'prices'", ",", "currency_pair", "...
https://developers.coinbase.com/api/v2#get-buy-price
[ "https", ":", "//", "developers", ".", "coinbase", ".", "com", "/", "api", "/", "v2#get", "-", "buy", "-", "price" ]
python
train
inasafe/inasafe
safe/definitions/earthquake.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/earthquake.py#L357-L369
def current_earthquake_model_name(): """Human friendly name for the currently active earthquake fatality model. :returns: Name of the current EQ fatality model as defined in users settings. """ default_earthquake_function = setting( 'earthquake_function', EARTHQUAKE_FUNCTIONS[0]['key'],...
[ "def", "current_earthquake_model_name", "(", ")", ":", "default_earthquake_function", "=", "setting", "(", "'earthquake_function'", ",", "EARTHQUAKE_FUNCTIONS", "[", "0", "]", "[", "'key'", "]", ",", "str", ")", "current_function", "=", "None", "for", "model", "in...
Human friendly name for the currently active earthquake fatality model. :returns: Name of the current EQ fatality model as defined in users settings.
[ "Human", "friendly", "name", "for", "the", "currently", "active", "earthquake", "fatality", "model", "." ]
python
train
KelSolaar/Umbra
umbra/ui/completers.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/completers.py#L91-L102
def language(self, value): """ Setter for **self.__language** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( "lan...
[ "def", "language", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "unicode", ",", "\"'{0}' attribute: '{1}' type is not 'unicode'!\"", ".", "format", "(", "\"language\"", ",", "value", ...
Setter for **self.__language** attribute. :param value: Attribute value. :type value: unicode
[ "Setter", "for", "**", "self", ".", "__language", "**", "attribute", "." ]
python
train
pavlin-policar/openTSNE
openTSNE/initialization.py
https://github.com/pavlin-policar/openTSNE/blob/28513a0d669f2f20e7b971c0c6373dc375f72771/openTSNE/initialization.py#L64-L89
def weighted_mean(X, embedding, neighbors, distances): """Initialize points onto an existing embedding by placing them in the weighted mean position of their nearest neighbors on the reference embedding. Parameters ---------- X: np.ndarray embedding: TSNEEmbedding neighbors: np.ndarray ...
[ "def", "weighted_mean", "(", "X", ",", "embedding", ",", "neighbors", ",", "distances", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "n_components", "=", "embedding", ".", "shape", "[", "1", "]", "partial_embedding", "=", "np", ".", "z...
Initialize points onto an existing embedding by placing them in the weighted mean position of their nearest neighbors on the reference embedding. Parameters ---------- X: np.ndarray embedding: TSNEEmbedding neighbors: np.ndarray distances: np.ndarray Returns ------- np.ndarray
[ "Initialize", "points", "onto", "an", "existing", "embedding", "by", "placing", "them", "in", "the", "weighted", "mean", "position", "of", "their", "nearest", "neighbors", "on", "the", "reference", "embedding", "." ]
python
train
open511/open511
open511/converter/__init__.py
https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/__init__.py#L42-L59
def open511_convert(input_doc, output_format, serialize=True, **kwargs): """ Convert an Open511 document between formats. input_doc - either an lxml open511 Element or a deserialized JSON dict output_format - short string name of a valid output format, as listed above """ try: output_fo...
[ "def", "open511_convert", "(", "input_doc", ",", "output_format", ",", "serialize", "=", "True", ",", "*", "*", "kwargs", ")", ":", "try", ":", "output_format_info", "=", "FORMATS", "[", "output_format", "]", "except", "KeyError", ":", "raise", "ValueError", ...
Convert an Open511 document between formats. input_doc - either an lxml open511 Element or a deserialized JSON dict output_format - short string name of a valid output format, as listed above
[ "Convert", "an", "Open511", "document", "between", "formats", ".", "input_doc", "-", "either", "an", "lxml", "open511", "Element", "or", "a", "deserialized", "JSON", "dict", "output_format", "-", "short", "string", "name", "of", "a", "valid", "output", "format...
python
valid
soravux/scoop
scoop/_comm/scooptcp.py
https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_comm/scooptcp.py#L294-L313
def sendFuture(self, future): """Send a Future to be executed remotely.""" try: if shared.getConst(hash(future.callable), timeout=0): # Enforce name reference passing if already shared future.callable = SharedElementEncapsu...
[ "def", "sendFuture", "(", "self", ",", "future", ")", ":", "try", ":", "if", "shared", ".", "getConst", "(", "hash", "(", "future", ".", "callable", ")", ",", "timeout", "=", "0", ")", ":", "# Enforce name reference passing if already shared\r", "future", "....
Send a Future to be executed remotely.
[ "Send", "a", "Future", "to", "be", "executed", "remotely", "." ]
python
train
eyeseast/python-tablefu
table_fu/__init__.py
https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/__init__.py#L326-L333
def get(self, column_name, default=None): """ Return the Datum for column_name, or default. """ if column_name in self.table.default_columns: index = self.table.default_columns.index(column_name) return Datum(self.cells[index], self.row_num, column_name, self.tabl...
[ "def", "get", "(", "self", ",", "column_name", ",", "default", "=", "None", ")", ":", "if", "column_name", "in", "self", ".", "table", ".", "default_columns", ":", "index", "=", "self", ".", "table", ".", "default_columns", ".", "index", "(", "column_nam...
Return the Datum for column_name, or default.
[ "Return", "the", "Datum", "for", "column_name", "or", "default", "." ]
python
train
cloudera/cm_api
python/src/cm_api/endpoints/services.py
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1150-L1174
def enable_oozie_ha(self, new_oozie_server_host_ids, new_oozie_server_role_names=None, zk_service_name=None, load_balancer_host_port=None): """ Enable high availability for Oozie. @param new_oozie_server_host_ids: List of IDs of the hosts on which new Oozie Servers ...
[ "def", "enable_oozie_ha", "(", "self", ",", "new_oozie_server_host_ids", ",", "new_oozie_server_role_names", "=", "None", ",", "zk_service_name", "=", "None", ",", "load_balancer_host_port", "=", "None", ")", ":", "args", "=", "dict", "(", "newOozieServerHostIds", "...
Enable high availability for Oozie. @param new_oozie_server_host_ids: List of IDs of the hosts on which new Oozie Servers will be added. @param new_oozie_server_role_names: List of names of the new Oozie Servers. This is an optional ...
[ "Enable", "high", "availability", "for", "Oozie", "." ]
python
train
snipsco/snipsmanagercore
snipsmanagercore/thread_handler.py
https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/thread_handler.py#L19-L30
def run(self, target, args=()): """ Run a function in a separate thread. :param target: the function to run. :param args: the parameters to pass to the function. """ run_event = threading.Event() run_event.set() thread = threading.Thread(target=target, args=args ...
[ "def", "run", "(", "self", ",", "target", ",", "args", "=", "(", ")", ")", ":", "run_event", "=", "threading", ".", "Event", "(", ")", "run_event", ".", "set", "(", ")", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "target", ",", ...
Run a function in a separate thread. :param target: the function to run. :param args: the parameters to pass to the function.
[ "Run", "a", "function", "in", "a", "separate", "thread", "." ]
python
train
serge-sans-paille/pythran
pythran/transformations/expand_imports.py
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/expand_imports.py#L63-L73
def visit_Import(self, node): """ Register imported modules and usage symbols. """ for alias in node.names: alias_name = tuple(alias.name.split('.')) self.imports.add(alias_name[0]) if alias.asname: self.symbols[alias.asname] = alias_name ...
[ "def", "visit_Import", "(", "self", ",", "node", ")", ":", "for", "alias", "in", "node", ".", "names", ":", "alias_name", "=", "tuple", "(", "alias", ".", "name", ".", "split", "(", "'.'", ")", ")", "self", ".", "imports", ".", "add", "(", "alias_n...
Register imported modules and usage symbols.
[ "Register", "imported", "modules", "and", "usage", "symbols", "." ]
python
train
klmitch/tendril
tendril/framers.py
https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L603-L650
def streamify(self, state, frame): """Prepare frame for output as a COBS-encoded stream.""" # Get the encoding table enc_tab = self._tables[1][:] # Need the special un-trailed block length and code untrail_len, untrail_code = enc_tab.pop(0) # Set up a repository to rec...
[ "def", "streamify", "(", "self", ",", "state", ",", "frame", ")", ":", "# Get the encoding table", "enc_tab", "=", "self", ".", "_tables", "[", "1", "]", "[", ":", "]", "# Need the special un-trailed block length and code", "untrail_len", ",", "untrail_code", "=",...
Prepare frame for output as a COBS-encoded stream.
[ "Prepare", "frame", "for", "output", "as", "a", "COBS", "-", "encoded", "stream", "." ]
python
train
rueckstiess/mtools
mtools/mlaunch/mlaunch.py
https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/mlaunch/mlaunch.py#L1412-L1431
def _store_parameters(self): """Store startup params and config in datadir/.mlaunch_startup.""" datapath = self.dir out_dict = { 'protocol_version': 2, 'mtools_version': __version__, 'parsed_args': self.args, 'unknown_args': self.unknown_args, ...
[ "def", "_store_parameters", "(", "self", ")", ":", "datapath", "=", "self", ".", "dir", "out_dict", "=", "{", "'protocol_version'", ":", "2", ",", "'mtools_version'", ":", "__version__", ",", "'parsed_args'", ":", "self", ".", "args", ",", "'unknown_args'", ...
Store startup params and config in datadir/.mlaunch_startup.
[ "Store", "startup", "params", "and", "config", "in", "datadir", "/", ".", "mlaunch_startup", "." ]
python
train
kubernetes-client/python
kubernetes/client/apis/core_v1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/core_v1_api.py#L9008-L9033
def delete_namespace(self, name, **kwargs): """ delete a Namespace This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespace(name, async_req=True) >>> result = thread.get() ...
[ "def", "delete_namespace", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "delete_namespace_with_http_...
delete a Namespace This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespace(name, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of t...
[ "delete", "a", "Namespace", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", ">>>", "thread", "=", "api", ".", "delete_n...
python
train
Azure/blobxfer
blobxfer/models/metadata.py
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/models/metadata.py#L92-L111
def get_md5_from_metadata(ase): # type: (blobxfer.models.azure.StorageEntity) -> str """Get MD5 from properties or metadata :param blobxfer.models.azure.StorageEntity ase: Azure Storage Entity :rtype: str or None :return: md5 """ # if encryption metadata is present, check for pre-encryption ...
[ "def", "get_md5_from_metadata", "(", "ase", ")", ":", "# type: (blobxfer.models.azure.StorageEntity) -> str", "# if encryption metadata is present, check for pre-encryption", "# md5 in blobxfer extensions", "md5", "=", "None", "if", "ase", ".", "is_encrypted", ":", "try", ":", ...
Get MD5 from properties or metadata :param blobxfer.models.azure.StorageEntity ase: Azure Storage Entity :rtype: str or None :return: md5
[ "Get", "MD5", "from", "properties", "or", "metadata", ":", "param", "blobxfer", ".", "models", ".", "azure", ".", "StorageEntity", "ase", ":", "Azure", "Storage", "Entity", ":", "rtype", ":", "str", "or", "None", ":", "return", ":", "md5" ]
python
train
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L509-L520
def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') ...
[ "def", "list_styles", "(", "self", ")", ":", "known", "=", "sorted", "(", "self", ".", "defaults", ".", "known_styles", ")", "if", "not", "known", ":", "err_exit", "(", "'No styles'", ",", "0", ")", "for", "style", "in", "known", ":", "if", "style", ...
Print available styles and exit.
[ "Print", "available", "styles", "and", "exit", "." ]
python
train
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L14112-L14137
def twovec(axdef, indexa, plndef, indexp): """ Find the transformation to the right-handed frame having a given vector as a specified axis and having a second given vector lying in a specified coordinate plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/twovec_c.html :param axdef:...
[ "def", "twovec", "(", "axdef", ",", "indexa", ",", "plndef", ",", "indexp", ")", ":", "axdef", "=", "stypes", ".", "toDoubleVector", "(", "axdef", ")", "indexa", "=", "ctypes", ".", "c_int", "(", "indexa", ")", "plndef", "=", "stypes", ".", "toDoubleVe...
Find the transformation to the right-handed frame having a given vector as a specified axis and having a second given vector lying in a specified coordinate plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/twovec_c.html :param axdef: Vector defining a principal axis. :type axdef: 3-E...
[ "Find", "the", "transformation", "to", "the", "right", "-", "handed", "frame", "having", "a", "given", "vector", "as", "a", "specified", "axis", "and", "having", "a", "second", "given", "vector", "lying", "in", "a", "specified", "coordinate", "plane", "." ]
python
train
elkan1788/ppytools
ppytools/ip2location2.py
https://github.com/elkan1788/ppytools/blob/117aeed9f669ae46e0dd6cb11c5687a5f797816c/ppytools/ip2location2.py#L111-L194
def btreeSearch(self, ip): """ " b-tree search method " param: ip """ if not ip.isdigit(): ip = self.ip2Long(ip) if len(self.__headerSip) < 1: #pass the super block self.__f.seek(8) #read the header block b = self.__f.read(...
[ "def", "btreeSearch", "(", "self", ",", "ip", ")", ":", "if", "not", "ip", ".", "isdigit", "(", ")", ":", "ip", "=", "self", ".", "ip2Long", "(", "ip", ")", "if", "len", "(", "self", ".", "__headerSip", ")", "<", "1", ":", "#pass the super block", ...
" b-tree search method " param: ip
[ "b", "-", "tree", "search", "method", "param", ":", "ip" ]
python
train
tk0miya/tk.phpautodoc
src/phply/phpparse.py
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phpparse.py#L289-L295
def p_declare_list(p): '''declare_list : STRING EQUALS static_scalar | declare_list COMMA STRING EQUALS static_scalar''' if len(p) == 4: p[0] = [ast.Directive(p[1], p[3], lineno=p.lineno(1))] else: p[0] = p[1] + [ast.Directive(p[3], p[5], lineno=p.lineno(2))]
[ "def", "p_declare_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "4", ":", "p", "[", "0", "]", "=", "[", "ast", ".", "Directive", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(",...
declare_list : STRING EQUALS static_scalar | declare_list COMMA STRING EQUALS static_scalar
[ "declare_list", ":", "STRING", "EQUALS", "static_scalar", "|", "declare_list", "COMMA", "STRING", "EQUALS", "static_scalar" ]
python
train
horazont/aioxmpp
aioxmpp/roster/service.py
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L612-L668
def set_entry(self, jid, *, name=_Sentinel, add_to_groups=frozenset(), remove_from_groups=frozenset(), timeout=None): """ Set properties of a roster entry or add a new roster entry. The roster entry is identified by its bare...
[ "def", "set_entry", "(", "self", ",", "jid", ",", "*", ",", "name", "=", "_Sentinel", ",", "add_to_groups", "=", "frozenset", "(", ")", ",", "remove_from_groups", "=", "frozenset", "(", ")", ",", "timeout", "=", "None", ")", ":", "existing", "=", "self...
Set properties of a roster entry or add a new roster entry. The roster entry is identified by its bare `jid`. If an entry already exists, all values default to those stored in the existing entry. For example, if no `name` is given, the current name of the entry is re-used, if any. ...
[ "Set", "properties", "of", "a", "roster", "entry", "or", "add", "a", "new", "roster", "entry", ".", "The", "roster", "entry", "is", "identified", "by", "its", "bare", "jid", "." ]
python
train
indico/indico-plugins
livesync/indico_livesync/uploader.py
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/livesync/indico_livesync/uploader.py#L57-L69
def run_initial(self, events): """Runs the initial batch upload :param events: an iterable containing events """ self_name = type(self).__name__ for i, batch in enumerate(grouper(events, self.INITIAL_BATCH_SIZE, skip_missing=True), 1): self.logger.debug('%s processin...
[ "def", "run_initial", "(", "self", ",", "events", ")", ":", "self_name", "=", "type", "(", "self", ")", ".", "__name__", "for", "i", ",", "batch", "in", "enumerate", "(", "grouper", "(", "events", ",", "self", ".", "INITIAL_BATCH_SIZE", ",", "skip_missin...
Runs the initial batch upload :param events: an iterable containing events
[ "Runs", "the", "initial", "batch", "upload" ]
python
train
ssato/python-anyconfig
src/anyconfig/schema.py
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/schema.py#L174-L202
def gen_schema(data, **options): """ Generate a node represents JSON schema object with type annotation added for given object node. :param data: Configuration data object (dict[-like] or namedtuple) :param options: Other keyword options such as: - ac_schema_strict: True if more strict (pr...
[ "def", "gen_schema", "(", "data", ",", "*", "*", "options", ")", ":", "if", "data", "is", "None", ":", "return", "dict", "(", "type", "=", "\"null\"", ")", "_type", "=", "type", "(", "data", ")", "if", "_type", "in", "_SIMPLE_TYPES", ":", "typemap", ...
Generate a node represents JSON schema object with type annotation added for given object node. :param data: Configuration data object (dict[-like] or namedtuple) :param options: Other keyword options such as: - ac_schema_strict: True if more strict (precise) schema is needed - ac_schema_t...
[ "Generate", "a", "node", "represents", "JSON", "schema", "object", "with", "type", "annotation", "added", "for", "given", "object", "node", "." ]
python
train
AguaClara/aguaclara
aguaclara/design/cdc.py
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/cdc.py#L61-L73
def viscosity_kinematic_chem(conc_chem, temp, en_chem): """Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin. """ if en_chem == 0: nu = viscosity_kinematic_a...
[ "def", "viscosity_kinematic_chem", "(", "conc_chem", ",", "temp", ",", "en_chem", ")", ":", "if", "en_chem", "==", "0", ":", "nu", "=", "viscosity_kinematic_alum", "(", "conc_chem", ",", "temp", ")", ".", "magnitude", "if", "en_chem", "==", "1", ":", "nu",...
Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin.
[ "Return", "the", "dynamic", "viscosity", "of", "water", "at", "a", "given", "temperature", "." ]
python
train
abarker/pdfCropMargins
src/pdfCropMargins/external_program_calls.py
https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L673-L682
def show_preview(viewer_path, pdf_file_name): """Run the PDF viewer at the path viewer_path on the file pdf_file_name.""" try: cmd = [viewer_path, pdf_file_name] run_external_subprocess_in_background(cmd) except (subprocess.CalledProcessError, OSError, IOError) as e: print("\nWarning...
[ "def", "show_preview", "(", "viewer_path", ",", "pdf_file_name", ")", ":", "try", ":", "cmd", "=", "[", "viewer_path", ",", "pdf_file_name", "]", "run_external_subprocess_in_background", "(", "cmd", ")", "except", "(", "subprocess", ".", "CalledProcessError", ",",...
Run the PDF viewer at the path viewer_path on the file pdf_file_name.
[ "Run", "the", "PDF", "viewer", "at", "the", "path", "viewer_path", "on", "the", "file", "pdf_file_name", "." ]
python
train
OSSOS/MOP
src/ossos/core/scripts/update_header.py
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/scripts/update_header.py#L48-L108
def main(): """Do the script.""" parser = argparse.ArgumentParser( description='replace image header') parser.add_argument('--extname', help='name of extension to in header') parser.add_argument('expnum', type=str, help='exposure to update') pa...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'replace image header'", ")", "parser", ".", "add_argument", "(", "'--extname'", ",", "help", "=", "'name of extension to in header'", ")", "parser", ".", "...
Do the script.
[ "Do", "the", "script", "." ]
python
train
sibirrer/lenstronomy
lenstronomy/Analysis/lens_analysis.py
https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Analysis/lens_analysis.py#L42-L66
def ellipticity_lens_light(self, kwargs_lens_light, center_x=0, center_y=0, model_bool_list=None, deltaPix=None, numPix=None): """ make sure that the window covers all the light, otherwise the moments may give to low answers. :param kwargs_lens_light: :par...
[ "def", "ellipticity_lens_light", "(", "self", ",", "kwargs_lens_light", ",", "center_x", "=", "0", ",", "center_y", "=", "0", ",", "model_bool_list", "=", "None", ",", "deltaPix", "=", "None", ",", "numPix", "=", "None", ")", ":", "if", "model_bool_list", ...
make sure that the window covers all the light, otherwise the moments may give to low answers. :param kwargs_lens_light: :param center_x: :param center_y: :param model_bool_list: :param deltaPix: :param numPix: :return:
[ "make", "sure", "that", "the", "window", "covers", "all", "the", "light", "otherwise", "the", "moments", "may", "give", "to", "low", "answers", "." ]
python
train
OzymandiasTheGreat/python-libinput
libinput/device.py
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L1735-L1762
def set_seat_logical_name(self, seat): """Change the logical seat associated with this device by removing the device and adding it to the new seat. This command is identical to physically unplugging the device, then re-plugging it as a member of the new seat. libinput will generate a :attr:`~libinput.constan...
[ "def", "set_seat_logical_name", "(", "self", ",", "seat", ")", ":", "rc", "=", "self", ".", "_libinput", ".", "libinput_device_set_seat_logical_name", "(", "self", ".", "_handle", ",", "seat", ".", "encode", "(", ")", ")", "assert", "rc", "==", "0", ",", ...
Change the logical seat associated with this device by removing the device and adding it to the new seat. This command is identical to physically unplugging the device, then re-plugging it as a member of the new seat. libinput will generate a :attr:`~libinput.constant.EventType.DEVICE_REMOVED` event and this ...
[ "Change", "the", "logical", "seat", "associated", "with", "this", "device", "by", "removing", "the", "device", "and", "adding", "it", "to", "the", "new", "seat", "." ]
python
train
althonos/pronto
pronto/term.py
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/term.py#L290-L325
def rparents(self, level=-1, intermediate=True): """Create a recursive list of children. Note that the :param:`intermediate` can be used to include every parents to the returned list, not only the most nested ones. Parameters: level (int): The depth level to continue fetchi...
[ "def", "rparents", "(", "self", ",", "level", "=", "-", "1", ",", "intermediate", "=", "True", ")", ":", "try", ":", "return", "self", ".", "_rparents", "[", "(", "level", ",", "intermediate", ")", "]", "except", "KeyError", ":", "rparents", "=", "["...
Create a recursive list of children. Note that the :param:`intermediate` can be used to include every parents to the returned list, not only the most nested ones. Parameters: level (int): The depth level to continue fetching parents from (default is -1, to get paren...
[ "Create", "a", "recursive", "list", "of", "children", "." ]
python
train
rosenbrockc/ci
pyci/config.py
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/config.py#L118-L127
def _parse_repo(self, xml): """Parses a <repo> tag to update settings on this Repository instance. :arg xml: the <repo> tag XMLElement. """ self.name = get_attrib(xml, "name", "repo") self.username = get_attrib(xml, "user", "repo") self.apikey = get_attrib(xml, "...
[ "def", "_parse_repo", "(", "self", ",", "xml", ")", ":", "self", ".", "name", "=", "get_attrib", "(", "xml", ",", "\"name\"", ",", "\"repo\"", ")", "self", ".", "username", "=", "get_attrib", "(", "xml", ",", "\"user\"", ",", "\"repo\"", ")", "self", ...
Parses a <repo> tag to update settings on this Repository instance. :arg xml: the <repo> tag XMLElement.
[ "Parses", "a", "<repo", ">", "tag", "to", "update", "settings", "on", "this", "Repository", "instance", ".", ":", "arg", "xml", ":", "the", "<repo", ">", "tag", "XMLElement", "." ]
python
train
saltstack/salt
salt/cloud/clouds/virtualbox.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/virtualbox.py#L327-L368
def destroy(name, call=None): """ This function irreversibly destroys a virtual machine on the cloud provider. Before doing so, it should fire an event on the Salt event bus. The tag for this event is `salt/cloud/<vm name>/destroying`. Once the virtual machine has been destroyed, another event is f...
[ "def", "destroy", "(", "name", ",", "call", "=", "None", ")", ":", "log", ".", "info", "(", "\"Attempting to delete instance %s\"", ",", "name", ")", "if", "not", "vb_machine_exists", "(", "name", ")", ":", "return", "\"{0} doesn't exist and can't be deleted\"", ...
This function irreversibly destroys a virtual machine on the cloud provider. Before doing so, it should fire an event on the Salt event bus. The tag for this event is `salt/cloud/<vm name>/destroying`. Once the virtual machine has been destroyed, another event is fired. The tag for that event is `salt/...
[ "This", "function", "irreversibly", "destroys", "a", "virtual", "machine", "on", "the", "cloud", "provider", ".", "Before", "doing", "so", "it", "should", "fire", "an", "event", "on", "the", "Salt", "event", "bus", "." ]
python
train
saltstack/salt
salt/modules/win_file.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L759-L799
def chgrp(path, group): ''' Change the group of a file Under Windows, this will do nothing. While a file in Windows does have a 'primary group', this rarely used attribute generally has no bearing on permissions unless intentionally configured and is only used to support Unix compatibility fea...
[ "def", "chgrp", "(", "path", ",", "group", ")", ":", "func_name", "=", "'{0}.chgrp'", ".", "format", "(", "__virtualname__", ")", "if", "__opts__", ".", "get", "(", "'fun'", ",", "''", ")", "==", "func_name", ":", "log", ".", "info", "(", "'The functio...
Change the group of a file Under Windows, this will do nothing. While a file in Windows does have a 'primary group', this rarely used attribute generally has no bearing on permissions unless intentionally configured and is only used to support Unix compatibility features (e.g. Services For Unix, N...
[ "Change", "the", "group", "of", "a", "file" ]
python
train
chrisrink10/basilisp
src/basilisp/lang/compiler/optimizer.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/optimizer.py#L31-L45
def visit_Expr(self, node: ast.Expr) -> Optional[ast.Expr]: """Eliminate no-op constant expressions which are in the tree as standalone statements.""" if isinstance( node.value, ( ast.Constant, # type: ignore ast.Name, ast....
[ "def", "visit_Expr", "(", "self", ",", "node", ":", "ast", ".", "Expr", ")", "->", "Optional", "[", "ast", ".", "Expr", "]", ":", "if", "isinstance", "(", "node", ".", "value", ",", "(", "ast", ".", "Constant", ",", "# type: ignore", "ast", ".", "N...
Eliminate no-op constant expressions which are in the tree as standalone statements.
[ "Eliminate", "no", "-", "op", "constant", "expressions", "which", "are", "in", "the", "tree", "as", "standalone", "statements", "." ]
python
test
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioFeatureExtraction.py
https://github.com/tyiannak/pyAudioAnalysis/blob/e3da991e7247492deba50648a4c7c0f41e684af4/pyAudioAnalysis/audioFeatureExtraction.py#L392-L450
def beatExtraction(st_features, win_len, PLOT=False): """ This function extracts an estimate of the beat rate for a musical signal. ARGUMENTS: - st_features: a numpy array (n_feats x numOfShortTermWindows) - win_len: window size in seconds RETURNS: - BPM: estimates o...
[ "def", "beatExtraction", "(", "st_features", ",", "win_len", ",", "PLOT", "=", "False", ")", ":", "# Features that are related to the beat tracking task:", "toWatch", "=", "[", "0", ",", "1", ",", "3", ",", "4", ",", "5", ",", "6", ",", "7", ",", "8", ",...
This function extracts an estimate of the beat rate for a musical signal. ARGUMENTS: - st_features: a numpy array (n_feats x numOfShortTermWindows) - win_len: window size in seconds RETURNS: - BPM: estimates of beats per minute - Ratio: a confidence measure
[ "This", "function", "extracts", "an", "estimate", "of", "the", "beat", "rate", "for", "a", "musical", "signal", ".", "ARGUMENTS", ":", "-", "st_features", ":", "a", "numpy", "array", "(", "n_feats", "x", "numOfShortTermWindows", ")", "-", "win_len", ":", "...
python
train
StackStorm/pybind
pybind/slxos/v17r_1_01a/routing_system/router/router_bgp/address_family/vpnv6/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/routing_system/router/router_bgp/address_family/vpnv6/__init__.py#L92-L113
def _set_vpnv6_unicast(self, v, load=False): """ Setter method for vpnv6_unicast, mapped from YANG variable /routing_system/router/router_bgp/address_family/vpnv6/vpnv6_unicast (container) If this variable is read-only (config: false) in the source YANG file, then _set_vpnv6_unicast is considered as a p...
[ "def", "_set_vpnv6_unicast", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "...
Setter method for vpnv6_unicast, mapped from YANG variable /routing_system/router/router_bgp/address_family/vpnv6/vpnv6_unicast (container) If this variable is read-only (config: false) in the source YANG file, then _set_vpnv6_unicast is considered as a private method. Backends looking to populate this vari...
[ "Setter", "method", "for", "vpnv6_unicast", "mapped", "from", "YANG", "variable", "/", "routing_system", "/", "router", "/", "router_bgp", "/", "address_family", "/", "vpnv6", "/", "vpnv6_unicast", "(", "container", ")", "If", "this", "variable", "is", "read", ...
python
train
saltstack/salt
salt/modules/junos.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L1002-L1112
def install_os(path=None, **kwargs): ''' Installs the given image on the device. After the installation is complete\ the device is rebooted, if reboot=True is given as a keyworded argument. path (required) Path where the image file is present on the proxy minion remote_path : ...
[ "def", "install_os", "(", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__proxy__", "[", "'junos.conn'", "]", "(", ")", "ret", "=", "{", "}", "ret", "[", "'out'", "]", "=", "True", "op", "=", "{", "}", "if", "'__pub_arg'",...
Installs the given image on the device. After the installation is complete\ the device is rebooted, if reboot=True is given as a keyworded argument. path (required) Path where the image file is present on the proxy minion remote_path : If the value of path is a file path on the local...
[ "Installs", "the", "given", "image", "on", "the", "device", ".", "After", "the", "installation", "is", "complete", "\\", "the", "device", "is", "rebooted", "if", "reboot", "=", "True", "is", "given", "as", "a", "keyworded", "argument", "." ]
python
train
pydata/xarray
xarray/plot/utils.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/plot/utils.py#L652-L704
def _process_cmap_cbar_kwargs(func, kwargs, data): """ Parameters ========== func : plotting function kwargs : dict, Dictionary with arguments that need to be parsed data : ndarray, Data values Returns ======= cmap_params cbar_kwargs """ cmap = kwargs.p...
[ "def", "_process_cmap_cbar_kwargs", "(", "func", ",", "kwargs", ",", "data", ")", ":", "cmap", "=", "kwargs", ".", "pop", "(", "'cmap'", ",", "None", ")", "colors", "=", "kwargs", ".", "pop", "(", "'colors'", ",", "None", ")", "cbar_kwargs", "=", "kwar...
Parameters ========== func : plotting function kwargs : dict, Dictionary with arguments that need to be parsed data : ndarray, Data values Returns ======= cmap_params cbar_kwargs
[ "Parameters", "==========", "func", ":", "plotting", "function", "kwargs", ":", "dict", "Dictionary", "with", "arguments", "that", "need", "to", "be", "parsed", "data", ":", "ndarray", "Data", "values" ]
python
train
piglei/uwsgi-sloth
uwsgi_sloth/analyzer.py
https://github.com/piglei/uwsgi-sloth/blob/2834ac5ed17d89ca5f19151c649ac610f6f37bd1/uwsgi_sloth/analyzer.py#L69-L77
def classify(self, url_path): """Classify an url""" for dict_api_url in self.user_defined_rules: api_url = dict_api_url['str'] re_api_url = dict_api_url['re'] if re_api_url.match(url_path[1:]): return api_url return self.RE_SIMPLIFY_URL.sub(r'...
[ "def", "classify", "(", "self", ",", "url_path", ")", ":", "for", "dict_api_url", "in", "self", ".", "user_defined_rules", ":", "api_url", "=", "dict_api_url", "[", "'str'", "]", "re_api_url", "=", "dict_api_url", "[", "'re'", "]", "if", "re_api_url", ".", ...
Classify an url
[ "Classify", "an", "url" ]
python
train
Kane610/axis
axis/rtsp.py
https://github.com/Kane610/axis/blob/b2b44ce595c7b722b5e13eabcab7b91f048e1808/axis/rtsp.py#L290-L294
def transport(self): """Generate transport string.""" transport = "Transport: RTP/AVP;unicast;client_port={}-{}\r\n" return transport.format( str(self.session.rtp_port), str(self.session.rtcp_port))
[ "def", "transport", "(", "self", ")", ":", "transport", "=", "\"Transport: RTP/AVP;unicast;client_port={}-{}\\r\\n\"", "return", "transport", ".", "format", "(", "str", "(", "self", ".", "session", ".", "rtp_port", ")", ",", "str", "(", "self", ".", "session", ...
Generate transport string.
[ "Generate", "transport", "string", "." ]
python
train
pytorch/vision
torchvision/transforms/functional.py
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L468-L499
def five_crop(img, size): """Crop the given PIL Image into four corners and the central crop. .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: size (sequence or int): Desired output siz...
[ "def", "five_crop", "(", "img", ",", "size", ")", ":", "if", "isinstance", "(", "size", ",", "numbers", ".", "Number", ")", ":", "size", "=", "(", "int", "(", "size", ")", ",", "int", "(", "size", ")", ")", "else", ":", "assert", "len", "(", "s...
Crop the given PIL Image into four corners and the central crop. .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: size (sequence or int): Desired output size of the crop. If size is an ...
[ "Crop", "the", "given", "PIL", "Image", "into", "four", "corners", "and", "the", "central", "crop", "." ]
python
test
simoninireland/epyc
epyc/labnotebook.py
https://github.com/simoninireland/epyc/blob/b3b61007741a0ab3de64df89070a6f30de8ec268/epyc/labnotebook.py#L175-L194
def cancelPendingResult( self, jobid ): """Cancel a particular pending result. Note that this only affects the notebook's record, not any job running in a lab. :param jobid: job id for pending result""" if jobid in self._pending.keys(): k = self._pending[jobid] d...
[ "def", "cancelPendingResult", "(", "self", ",", "jobid", ")", ":", "if", "jobid", "in", "self", ".", "_pending", ".", "keys", "(", ")", ":", "k", "=", "self", ".", "_pending", "[", "jobid", "]", "del", "self", ".", "_pending", "[", "jobid", "]", "i...
Cancel a particular pending result. Note that this only affects the notebook's record, not any job running in a lab. :param jobid: job id for pending result
[ "Cancel", "a", "particular", "pending", "result", ".", "Note", "that", "this", "only", "affects", "the", "notebook", "s", "record", "not", "any", "job", "running", "in", "a", "lab", "." ]
python
train
MAVENSDC/cdflib
cdflib/cdfread.py
https://github.com/MAVENSDC/cdflib/blob/d237c60e5db67db0f92d96054209c25c4042465c/cdflib/cdfread.py#L1726-L1741
def _convert_option(self): ''' Determines how to convert CDF byte ordering to the system byte ordering. ''' if sys.byteorder == 'little' and self._endian() == 'big-endian': # big->little order = '>' elif sys.byteorder == 'big' and self._endian() =...
[ "def", "_convert_option", "(", "self", ")", ":", "if", "sys", ".", "byteorder", "==", "'little'", "and", "self", ".", "_endian", "(", ")", "==", "'big-endian'", ":", "# big->little", "order", "=", "'>'", "elif", "sys", ".", "byteorder", "==", "'big'", "a...
Determines how to convert CDF byte ordering to the system byte ordering.
[ "Determines", "how", "to", "convert", "CDF", "byte", "ordering", "to", "the", "system", "byte", "ordering", "." ]
python
train
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L967-L1011
def create_question(participant_id): """Send a POST request to the question table. Questions store information at the participant level, not the node level. You should pass the question (string) number (int) and response (string) as arguments. """ # Get the participant. try: ppt...
[ "def", "create_question", "(", "participant_id", ")", ":", "# Get the participant.", "try", ":", "ppt", "=", "models", ".", "Participant", ".", "query", ".", "filter_by", "(", "id", "=", "participant_id", ")", ".", "one", "(", ")", "except", "NoResultFound", ...
Send a POST request to the question table. Questions store information at the participant level, not the node level. You should pass the question (string) number (int) and response (string) as arguments.
[ "Send", "a", "POST", "request", "to", "the", "question", "table", "." ]
python
train
lowandrew/OLCTools
sipprCommon/sippingmethods.py
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/sipprCommon/sippingmethods.py#L232-L264
def subsample_reads(self): """ Subsampling of reads to 20X coverage of rMLST genes (roughly). To be called after rMLST extraction and read trimming, in that order. """ logging.info('Subsampling {at} reads'.format(at=self.analysistype)) with progressbar(self.runmetadata) a...
[ "def", "subsample_reads", "(", "self", ")", ":", "logging", ".", "info", "(", "'Subsampling {at} reads'", ".", "format", "(", "at", "=", "self", ".", "analysistype", ")", ")", "with", "progressbar", "(", "self", ".", "runmetadata", ")", "as", "bar", ":", ...
Subsampling of reads to 20X coverage of rMLST genes (roughly). To be called after rMLST extraction and read trimming, in that order.
[ "Subsampling", "of", "reads", "to", "20X", "coverage", "of", "rMLST", "genes", "(", "roughly", ")", ".", "To", "be", "called", "after", "rMLST", "extraction", "and", "read", "trimming", "in", "that", "order", "." ]
python
train
LasLabs/python-five9
five9/models/base_model.py
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/base_model.py#L180-L184
def _zeep_to_dict(cls, obj): """Convert a zeep object to a dictionary.""" res = serialize_object(obj) res = cls._get_non_empty_dict(res) return res
[ "def", "_zeep_to_dict", "(", "cls", ",", "obj", ")", ":", "res", "=", "serialize_object", "(", "obj", ")", "res", "=", "cls", ".", "_get_non_empty_dict", "(", "res", ")", "return", "res" ]
Convert a zeep object to a dictionary.
[ "Convert", "a", "zeep", "object", "to", "a", "dictionary", "." ]
python
train
proycon/pynlpl
pynlpl/formats/giza.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/giza.py#L108-L126
def getalignedtarget(self, index): """Returns target range only if source index aligns to a single consecutive range of target tokens.""" targetindices = [] target = None foundindex = -1 for sourceindex, targetindex in self.alignment: if sourceindex == index: ...
[ "def", "getalignedtarget", "(", "self", ",", "index", ")", ":", "targetindices", "=", "[", "]", "target", "=", "None", "foundindex", "=", "-", "1", "for", "sourceindex", ",", "targetindex", "in", "self", ".", "alignment", ":", "if", "sourceindex", "==", ...
Returns target range only if source index aligns to a single consecutive range of target tokens.
[ "Returns", "target", "range", "only", "if", "source", "index", "aligns", "to", "a", "single", "consecutive", "range", "of", "target", "tokens", "." ]
python
train
brainiak/brainiak
brainiak/factoranalysis/tfa.py
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/factoranalysis/tfa.py#L309-L326
def get_map_offset(self): """Compute offset of prior/posterior Returns ------- map_offest : 1D array The offset to different fields in prior/posterior """ nfield = 4 self.map_offset = np.zeros(nfield).astype(int) field_size = self.K * np.a...
[ "def", "get_map_offset", "(", "self", ")", ":", "nfield", "=", "4", "self", ".", "map_offset", "=", "np", ".", "zeros", "(", "nfield", ")", ".", "astype", "(", "int", ")", "field_size", "=", "self", ".", "K", "*", "np", ".", "array", "(", "[", "s...
Compute offset of prior/posterior Returns ------- map_offest : 1D array The offset to different fields in prior/posterior
[ "Compute", "offset", "of", "prior", "/", "posterior" ]
python
train
googleapis/google-cloud-python
trace/google/cloud/trace/client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace/client.py#L103-L226
def create_span( self, name, span_id, display_name, start_time, end_time, parent_span_id=None, attributes=None, stack_trace=None, time_events=None, links=None, status=None, same_process_as_parent_span=None, c...
[ "def", "create_span", "(", "self", ",", "name", ",", "span_id", ",", "display_name", ",", "start_time", ",", "end_time", ",", "parent_span_id", "=", "None", ",", "attributes", "=", "None", ",", "stack_trace", "=", "None", ",", "time_events", "=", "None", "...
Creates a new Span. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.Client() >>> >>> name = 'projects/{project}/traces/{trace_id}/spans/{span_id}'. format('[PROJECT]', '[TRACE_ID]', '[SPAN_ID]') ...
[ "Creates", "a", "new", "Span", "." ]
python
train
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1577-L1599
def cposr(string, chars, start): """ Find the first occurrence in a string of a character belonging to a collection of characters, starting at a specified location, searching in reverse. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cposr_c.html :param string: Any character string. ...
[ "def", "cposr", "(", "string", ",", "chars", ",", "start", ")", ":", "string", "=", "stypes", ".", "stringToCharP", "(", "string", ")", "chars", "=", "stypes", ".", "stringToCharP", "(", "chars", ")", "start", "=", "ctypes", ".", "c_int", "(", "start",...
Find the first occurrence in a string of a character belonging to a collection of characters, starting at a specified location, searching in reverse. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cposr_c.html :param string: Any character string. :type string: str :param chars: A coll...
[ "Find", "the", "first", "occurrence", "in", "a", "string", "of", "a", "character", "belonging", "to", "a", "collection", "of", "characters", "starting", "at", "a", "specified", "location", "searching", "in", "reverse", "." ]
python
train
CalebBell/thermo
thermo/utils.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L3368-L3403
def calculate_derivative_P(self, P, T, zs, ws, method, order=1): r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition of a given order using a specified method. Uses SciPy's derivative function, with a delta of 0.01...
[ "def", "calculate_derivative_P", "(", "self", ",", "P", ",", "T", ",", "zs", ",", "ws", ",", "method", ",", "order", "=", "1", ")", ":", "f", "=", "lambda", "P", ":", "self", ".", "calculate", "(", "T", ",", "P", ",", "zs", ",", "ws", ",", "m...
r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition of a given order using a specified method. Uses SciPy's derivative function, with a delta of 0.01 Pa and a number of points equal to 2*order + 1. This m...
[ "r", "Method", "to", "calculate", "a", "derivative", "of", "a", "mixture", "property", "with", "respect", "to", "pressure", "at", "constant", "temperature", "and", "composition", "of", "a", "given", "order", "using", "a", "specified", "method", ".", "Uses", ...
python
valid
pandas-dev/pandas
pandas/io/formats/style.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/formats/style.py#L1217-L1243
def from_custom_template(cls, searchpath, name): """ Factory function for creating a subclass of ``Styler`` with a custom template and Jinja environment. Parameters ---------- searchpath : str or list Path or paths of directories containing the templates ...
[ "def", "from_custom_template", "(", "cls", ",", "searchpath", ",", "name", ")", ":", "loader", "=", "ChoiceLoader", "(", "[", "FileSystemLoader", "(", "searchpath", ")", ",", "cls", ".", "loader", ",", "]", ")", "class", "MyStyler", "(", "cls", ")", ":",...
Factory function for creating a subclass of ``Styler`` with a custom template and Jinja environment. Parameters ---------- searchpath : str or list Path or paths of directories containing the templates name : str Name of your custom template to use for re...
[ "Factory", "function", "for", "creating", "a", "subclass", "of", "Styler", "with", "a", "custom", "template", "and", "Jinja", "environment", "." ]
python
train
alejandroautalan/pygubu
pygubudesigner/previewer.py
https://github.com/alejandroautalan/pygubu/blob/41c8fb37ef973736ec5d68cbe1cd4ecb78712e40/pygubudesigner/previewer.py#L453-L464
def _over_resizer(self, x, y): "Returns True if mouse is over a resizer" over_resizer = False c = self.canvas ids = c.find_overlapping(x, y, x, y) if ids: o = ids[0] tags = c.gettags(o) if 'resizer' in tags: over_resizer = True...
[ "def", "_over_resizer", "(", "self", ",", "x", ",", "y", ")", ":", "over_resizer", "=", "False", "c", "=", "self", ".", "canvas", "ids", "=", "c", ".", "find_overlapping", "(", "x", ",", "y", ",", "x", ",", "y", ")", "if", "ids", ":", "o", "=",...
Returns True if mouse is over a resizer
[ "Returns", "True", "if", "mouse", "is", "over", "a", "resizer" ]
python
train
stanfordnlp/stanza
stanza/research/iterators.py
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/iterators.py#L47-L76
def gen_batches(iterable, batch_size): ''' Returns a generator object that yields batches from `iterable`. See `iter_batches` for more details and caveats. Note that `iter_batches` returns an iterator, which never supports `len()`, `gen_batches` returns an iterable which supports `len()` if and onl...
[ "def", "gen_batches", "(", "iterable", ",", "batch_size", ")", ":", "def", "batches_thunk", "(", ")", ":", "return", "iter_batches", "(", "iterable", ",", "batch_size", ")", "try", ":", "length", "=", "len", "(", "iterable", ")", "except", "TypeError", ":"...
Returns a generator object that yields batches from `iterable`. See `iter_batches` for more details and caveats. Note that `iter_batches` returns an iterator, which never supports `len()`, `gen_batches` returns an iterable which supports `len()` if and only if `iterable` does. This *may* be an iterator...
[ "Returns", "a", "generator", "object", "that", "yields", "batches", "from", "iterable", ".", "See", "iter_batches", "for", "more", "details", "and", "caveats", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/gui/controllers/library_tree.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/library_tree.py#L338-L398
def menu_item_remove_libraries_or_root_clicked(self, menu_item): """Removes library from hard drive after request second confirmation""" menu_item_text = self.get_menu_item_text(menu_item) logger.info("Delete item '{0}' pressed.".format(menu_item_text)) model, path = self.view.get_sele...
[ "def", "menu_item_remove_libraries_or_root_clicked", "(", "self", ",", "menu_item", ")", ":", "menu_item_text", "=", "self", ".", "get_menu_item_text", "(", "menu_item", ")", "logger", ".", "info", "(", "\"Delete item '{0}' pressed.\"", ".", "format", "(", "menu_item_...
Removes library from hard drive after request second confirmation
[ "Removes", "library", "from", "hard", "drive", "after", "request", "second", "confirmation" ]
python
train
ModisWorks/modis
modis/discord_modis/modules/help/on_message.py
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/help/on_message.py#L8-L59
async def on_message(message): """The on_message event handler for this module Args: message (discord.Message): Input message """ # Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.ge...
[ "async", "def", "on_message", "(", "message", ")", ":", "# Simplify message info", "server", "=", "message", ".", "server", "author", "=", "message", ".", "author", "channel", "=", "message", ".", "channel", "content", "=", "message", ".", "content", "data", ...
The on_message event handler for this module Args: message (discord.Message): Input message
[ "The", "on_message", "event", "handler", "for", "this", "module" ]
python
train
pypyr/pypyr-cli
pypyr/dsl.py
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L538-L578
def retry_loop(self, context, step_method): """Run step inside a retry loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (meth...
[ "def", "retry_loop", "(", "self", ",", "context", ",", "step_method", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "context", "[", "'retryCounter'", "]", "=", "0", "sleep", "=", "context", ".", "get_formatted_as_type", "(", "self", ".", "sle...
Run step inside a retry loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (method/function) This is the method/function that ...
[ "Run", "step", "inside", "a", "retry", "loop", "." ]
python
train
nvbn/thefuck
thefuck/rules/brew_unknown_command.py
https://github.com/nvbn/thefuck/blob/40ab4eb62db57627bff10cf029d29c94704086a2/thefuck/rules/brew_unknown_command.py#L21-L41
def _get_brew_tap_specific_commands(brew_path_prefix): """To get tap's specific commands https://github.com/Homebrew/homebrew/blob/master/Library/brew.rb#L115""" commands = [] brew_taps_path = brew_path_prefix + TAP_PATH for user in _get_directory_names_only(brew_taps_path): taps = _get_dir...
[ "def", "_get_brew_tap_specific_commands", "(", "brew_path_prefix", ")", ":", "commands", "=", "[", "]", "brew_taps_path", "=", "brew_path_prefix", "+", "TAP_PATH", "for", "user", "in", "_get_directory_names_only", "(", "brew_taps_path", ")", ":", "taps", "=", "_get_...
To get tap's specific commands https://github.com/Homebrew/homebrew/blob/master/Library/brew.rb#L115
[ "To", "get", "tap", "s", "specific", "commands", "https", ":", "//", "github", ".", "com", "/", "Homebrew", "/", "homebrew", "/", "blob", "/", "master", "/", "Library", "/", "brew", ".", "rb#L115" ]
python
train
jtwhite79/pyemu
pyemu/logger.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/logger.py#L94-L108
def warn(self,message): """write a warning to the log file. Parameters ---------- message : str the warning text """ s = str(datetime.now()) + " WARNING: " + message + '\n' if self.echo: print(s,end='') if self.filename: ...
[ "def", "warn", "(", "self", ",", "message", ")", ":", "s", "=", "str", "(", "datetime", ".", "now", "(", ")", ")", "+", "\" WARNING: \"", "+", "message", "+", "'\\n'", "if", "self", ".", "echo", ":", "print", "(", "s", ",", "end", "=", "''", ")...
write a warning to the log file. Parameters ---------- message : str the warning text
[ "write", "a", "warning", "to", "the", "log", "file", "." ]
python
train
olitheolix/qtmacs
qtmacs/extensions/qtmacsscintilla_macros.py
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L1271-L1286
def reverseCommit(self): """ Re-insert the previously deleted line. """ if self.markerPos is None: return # Remove the specified string from the same position in every line # in between the mark and the cursor (inclusive). col = min((self.markerPos[1...
[ "def", "reverseCommit", "(", "self", ")", ":", "if", "self", ".", "markerPos", "is", "None", ":", "return", "# Remove the specified string from the same position in every line", "# in between the mark and the cursor (inclusive).", "col", "=", "min", "(", "(", "self", ".",...
Re-insert the previously deleted line.
[ "Re", "-", "insert", "the", "previously", "deleted", "line", "." ]
python
train
mdiener/grace
grace/py27/slimit/parser.py
https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/slimit/parser.py#L334-L348
def p_member_expr(self, p): """member_expr : primary_expr | function_expr | member_expr LBRACKET expr RBRACKET | member_expr PERIOD identifier | NEW member_expr arguments """ if len(p) == 2: p...
[ "def", "p_member_expr", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "elif", "p", "[", "1", "]", "==", "'new'", ":", "p", "[", "0", "]", "=", "ast", ".", "NewE...
member_expr : primary_expr | function_expr | member_expr LBRACKET expr RBRACKET | member_expr PERIOD identifier | NEW member_expr arguments
[ "member_expr", ":", "primary_expr", "|", "function_expr", "|", "member_expr", "LBRACKET", "expr", "RBRACKET", "|", "member_expr", "PERIOD", "identifier", "|", "NEW", "member_expr", "arguments" ]
python
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/message.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L147-L157
def publish_time(self): """Return the time that the message was originally published. Returns: datetime: The date and time that the message was published. """ timestamp = self._message.publish_time delta = datetime.timedelta( seconds=timestamp.seconds, mi...
[ "def", "publish_time", "(", "self", ")", ":", "timestamp", "=", "self", ".", "_message", ".", "publish_time", "delta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "timestamp", ".", "seconds", ",", "microseconds", "=", "timestamp", ".", "nanos", ...
Return the time that the message was originally published. Returns: datetime: The date and time that the message was published.
[ "Return", "the", "time", "that", "the", "message", "was", "originally", "published", "." ]
python
train
mikicz/arca
arca/backend/docker.py
https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/backend/docker.py#L665-L684
def start_container(self, image, container_name: str, repo_path: Path): """ Starts a container with the image and name ``container_name`` and copies the repository into the container. :type image: docker.models.images.Image :rtype: docker.models.container.Container """ command =...
[ "def", "start_container", "(", "self", ",", "image", ",", "container_name", ":", "str", ",", "repo_path", ":", "Path", ")", ":", "command", "=", "\"bash -i\"", "if", "self", ".", "inherit_image", ":", "command", "=", "\"sh -i\"", "container", "=", "self", ...
Starts a container with the image and name ``container_name`` and copies the repository into the container. :type image: docker.models.images.Image :rtype: docker.models.container.Container
[ "Starts", "a", "container", "with", "the", "image", "and", "name", "container_name", "and", "copies", "the", "repository", "into", "the", "container", "." ]
python
train
minimind/dispatch-on-value-for-python
dispatchonvalue/dispatchonvalue.py
https://github.com/minimind/dispatch-on-value-for-python/blob/87e510ee00948854752dfca65264a3eefda365ca/dispatchonvalue/dispatchonvalue.py#L105-L119
def dispatch_strict(self, stream, *args, **kwargs): """ Dispatch to function held internally depending upon the value of stream. Matching on directories is strict. This means dictionaries will match if they are exactly the same. """ for f, pat in self.functions: ...
[ "def", "dispatch_strict", "(", "self", ",", "stream", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "f", ",", "pat", "in", "self", ".", "functions", ":", "matched", ",", "matched_stream", "=", "self", ".", "_match", "(", "stream", ",", ...
Dispatch to function held internally depending upon the value of stream. Matching on directories is strict. This means dictionaries will match if they are exactly the same.
[ "Dispatch", "to", "function", "held", "internally", "depending", "upon", "the", "value", "of", "stream", "." ]
python
train
saltstack/salt
salt/utils/minions.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L345-L353
def _check_pillar_pcre_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via pillar with PCRE ''' return self._check_cache_minions(expr, delimiter, greedy, ...
[ "def", "_check_pillar_pcre_minions", "(", "self", ",", "expr", ",", "delimiter", ",", "greedy", ")", ":", "return", "self", ".", "_check_cache_minions", "(", "expr", ",", "delimiter", ",", "greedy", ",", "'pillar'", ",", "regex_match", "=", "True", ")" ]
Return the minions found by looking via pillar with PCRE
[ "Return", "the", "minions", "found", "by", "looking", "via", "pillar", "with", "PCRE" ]
python
train
dossier/dossier.models
dossier/models/web/routes.py
https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/web/routes.py#L397-L689
def v1_highlights_post(request, response, kvlclient, tfidf, min_delay=3, task_master=None): '''Obtain highlights for a document POSTed inside a JSON object. Get our Diffeo Highlighter browser extension here: https://chrome.google.com/webstore/detail/jgfcplgdmjkdepnmbdkmgohaldaiplpo ...
[ "def", "v1_highlights_post", "(", "request", ",", "response", ",", "kvlclient", ",", "tfidf", ",", "min_delay", "=", "3", ",", "task_master", "=", "None", ")", ":", "tfidf", "=", "tfidf", "or", "None", "content_type", "=", "request", ".", "headers", ".", ...
Obtain highlights for a document POSTed inside a JSON object. Get our Diffeo Highlighter browser extension here: https://chrome.google.com/webstore/detail/jgfcplgdmjkdepnmbdkmgohaldaiplpo While you're at it, pre-register for a beta account on http://diffeo.com. `min_delay` and `task_master` are u...
[ "Obtain", "highlights", "for", "a", "document", "POSTed", "inside", "a", "JSON", "object", "." ]
python
train
sods/ods
pods/datasets.py
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1321-L1343
def movie_body_count_r_classify(data_set='movie_body_count'): """Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.""" data = movie_body_count()['Y'] import pandas as pd import numpy a...
[ "def", "movie_body_count_r_classify", "(", "data_set", "=", "'movie_body_count'", ")", ":", "data", "=", "movie_body_count", "(", ")", "[", "'Y'", "]", "import", "pandas", "as", "pd", "import", "numpy", "as", "np", "X", "=", "data", "[", "[", "'Year'", ","...
Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.
[ "Data", "set", "of", "movies", "and", "body", "count", "for", "movies", "scraped", "from", "www", ".", "MovieBodyCounts", ".", "com", "created", "by", "Simon", "Garnier", "and", "Randy", "Olson", "for", "exploring", "differences", "between", "Python", "and", ...
python
train
rchatterjee/pwmodels
src/pwmodel/models.py
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L335-L353
def _gen_next(self, history): """Generate next character sampled from the distribution of characters next. """ orig_history = history if not history: return helper.START history = history[-(self._n-1):] kv = [(k, v) for k, v in self._T.items(history) ...
[ "def", "_gen_next", "(", "self", ",", "history", ")", ":", "orig_history", "=", "history", "if", "not", "history", ":", "return", "helper", ".", "START", "history", "=", "history", "[", "-", "(", "self", ".", "_n", "-", "1", ")", ":", "]", "kv", "=...
Generate next character sampled from the distribution of characters next.
[ "Generate", "next", "character", "sampled", "from", "the", "distribution", "of", "characters", "next", "." ]
python
train
uralbash/pyramid_pages
pyramid_pages/routes.py
https://github.com/uralbash/pyramid_pages/blob/545b1ecb2e5dee5742135ba2a689b9635dd4efa1/pyramid_pages/routes.py#L31-L92
def page_factory(request): """ Page factory. Config models example: .. code-block:: python models = { '': [WebPage, CatalogResource], 'catalogue': CatalogResource, 'news': NewsResource, } """ prefix = request.matchdict['prefix'] # /{prefix}/pag...
[ "def", "page_factory", "(", "request", ")", ":", "prefix", "=", "request", ".", "matchdict", "[", "'prefix'", "]", "# /{prefix}/page1/page2/page3...", "settings", "=", "request", ".", "registry", ".", "settings", "dbsession", "=", "settings", "[", "CONFIG_DBSESSIO...
Page factory. Config models example: .. code-block:: python models = { '': [WebPage, CatalogResource], 'catalogue': CatalogResource, 'news': NewsResource, }
[ "Page", "factory", "." ]
python
train
lorien/grab
grab/deprecated.py
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L173-L185
def css_text(self, path, default=NULL, smart=False, normalize_space=True): """ Get normalized text of node which matches the css path. """ try: return get_node_text(self.css_one(path), smart=smart, normalize_space=normalize_space) exc...
[ "def", "css_text", "(", "self", ",", "path", ",", "default", "=", "NULL", ",", "smart", "=", "False", ",", "normalize_space", "=", "True", ")", ":", "try", ":", "return", "get_node_text", "(", "self", ".", "css_one", "(", "path", ")", ",", "smart", "...
Get normalized text of node which matches the css path.
[ "Get", "normalized", "text", "of", "node", "which", "matches", "the", "css", "path", "." ]
python
train
saltstack/salt
salt/modules/vsphere.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3943-L4008
def create_dvs(dvs_dict, dvs_name, service_instance=None): ''' Creates a distributed virtual switch (DVS). Note: The ``dvs_name`` param will override any name set in ``dvs_dict``. dvs_dict Dict representation of the new DVS (example in salt.states.dvs) dvs_name Name of the DVS to ...
[ "def", "create_dvs", "(", "dvs_dict", ",", "dvs_name", ",", "service_instance", "=", "None", ")", ":", "log", ".", "trace", "(", "'Creating dvs \\'%s\\' with dict = %s'", ",", "dvs_name", ",", "dvs_dict", ")", "proxy_type", "=", "get_proxy_type", "(", ")", "if",...
Creates a distributed virtual switch (DVS). Note: The ``dvs_name`` param will override any name set in ``dvs_dict``. dvs_dict Dict representation of the new DVS (example in salt.states.dvs) dvs_name Name of the DVS to be created. service_instance Service instance (vim.Service...
[ "Creates", "a", "distributed", "virtual", "switch", "(", "DVS", ")", "." ]
python
train
ionelmc/python-cogen
cogen/magic/corolets.py
https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/magic/corolets.py#L77-L142
def run_op(self, op, sched): """ Handle the operation: * if coro is in STATE_RUNNING, send or throw the given op * if coro is in STATE_NEED_INIT, call the init function and if it doesn't return a generator, set STATE_COMPLETED and set the result to whatever ...
[ "def", "run_op", "(", "self", ",", "op", ",", "sched", ")", ":", "if", "op", "is", "self", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"Running coro %s with itself. Something is fishy.\"", "%", "op", ")", "assert", "self", ".", "state", "<", ...
Handle the operation: * if coro is in STATE_RUNNING, send or throw the given op * if coro is in STATE_NEED_INIT, call the init function and if it doesn't return a generator, set STATE_COMPLETED and set the result to whatever the function returned. * if StopIterat...
[ "Handle", "the", "operation", ":", "*", "if", "coro", "is", "in", "STATE_RUNNING", "send", "or", "throw", "the", "given", "op", "*", "if", "coro", "is", "in", "STATE_NEED_INIT", "call", "the", "init", "function", "and", "if", "it", "doesn", "t", "return"...
python
train
nerdvegas/rez
src/rez/vendor/version/requirement.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/requirement.py#L196-L216
def conflicts_with(self, other): """Returns True if this requirement conflicts with another `Requirement` or `VersionedObject`.""" if isinstance(other, Requirement): if (self.name_ != other.name_) or (self.range is None) \ or (other.range is None): ...
[ "def", "conflicts_with", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Requirement", ")", ":", "if", "(", "self", ".", "name_", "!=", "other", ".", "name_", ")", "or", "(", "self", ".", "range", "is", "None", ")", "or...
Returns True if this requirement conflicts with another `Requirement` or `VersionedObject`.
[ "Returns", "True", "if", "this", "requirement", "conflicts", "with", "another", "Requirement", "or", "VersionedObject", "." ]
python
train
linuxsoftware/ls.joyous
ls/joyous/models/events.py
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L492-L504
def group(self): """ The group this event belongs to. Adding the event as a child of a group automatically assigns the event to that group. """ retval = None parent = self.get_parent() Group = get_group_model() if issubclass(parent.specific_class, Group):...
[ "def", "group", "(", "self", ")", ":", "retval", "=", "None", "parent", "=", "self", ".", "get_parent", "(", ")", "Group", "=", "get_group_model", "(", ")", "if", "issubclass", "(", "parent", ".", "specific_class", ",", "Group", ")", ":", "retval", "="...
The group this event belongs to. Adding the event as a child of a group automatically assigns the event to that group.
[ "The", "group", "this", "event", "belongs", "to", ".", "Adding", "the", "event", "as", "a", "child", "of", "a", "group", "automatically", "assigns", "the", "event", "to", "that", "group", "." ]
python
train
salsita/flask-ecstatic
flask_ecstatic.py
https://github.com/salsita/flask-ecstatic/blob/27f67f36eee3afe5855958e4187ff1268d7a5e69/flask_ecstatic.py#L19-L65
def add(app, url = None, path = None, endpoint=None, decorate=None, index='index.html', **options): """Adds static files endpoint with optional directory index.""" url = url or app.static_url_path or '' path = os.path.abspath(path or app.static_folder or '.') endpoint = endpoint or 'static_' + os.path....
[ "def", "add", "(", "app", ",", "url", "=", "None", ",", "path", "=", "None", ",", "endpoint", "=", "None", ",", "decorate", "=", "None", ",", "index", "=", "'index.html'", ",", "*", "*", "options", ")", ":", "url", "=", "url", "or", "app", ".", ...
Adds static files endpoint with optional directory index.
[ "Adds", "static", "files", "endpoint", "with", "optional", "directory", "index", "." ]
python
train