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
wbond/oscrypto
oscrypto/_openssl/asymmetric.py
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/asymmetric.py#L729-L755
def _load_key(private_object): """ Loads a private key into a PrivateKey object :param private_object: An asn1crypto.keys.PrivateKeyInfo object :return: A PrivateKey object """ if libcrypto_version_info < (1,) and private_object.algorithm == 'dsa' and private_object.hash_algo ...
[ "def", "_load_key", "(", "private_object", ")", ":", "if", "libcrypto_version_info", "<", "(", "1", ",", ")", "and", "private_object", ".", "algorithm", "==", "'dsa'", "and", "private_object", ".", "hash_algo", "==", "'sha2'", ":", "raise", "AsymmetricKeyError",...
Loads a private key into a PrivateKey object :param private_object: An asn1crypto.keys.PrivateKeyInfo object :return: A PrivateKey object
[ "Loads", "a", "private", "key", "into", "a", "PrivateKey", "object" ]
python
valid
allenai/allennlp
allennlp/tools/drop_eval.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L150-L164
def answer_json_to_strings(answer: Dict[str, Any]) -> Tuple[Tuple[str, ...], str]: """ Takes an answer JSON blob from the DROP data release and converts it into strings used for evaluation. """ if "number" in answer and answer["number"]: return tuple([str(answer["number"])]), "number" el...
[ "def", "answer_json_to_strings", "(", "answer", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "Tuple", "[", "str", ",", "...", "]", ",", "str", "]", ":", "if", "\"number\"", "in", "answer", "and", "answer", "[", "\"number\"", "]"...
Takes an answer JSON blob from the DROP data release and converts it into strings used for evaluation.
[ "Takes", "an", "answer", "JSON", "blob", "from", "the", "DROP", "data", "release", "and", "converts", "it", "into", "strings", "used", "for", "evaluation", "." ]
python
train
sdispater/backpack
backpack/collections/base_collection.py
https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L145-L155
def diff(self, items): """ Diff the collections with the given items :param items: The items to diff with :type items: mixed :return: A Collection instance :rtype: Collection """ return self.__class__([i for i in self.items if i not in items])
[ "def", "diff", "(", "self", ",", "items", ")", ":", "return", "self", ".", "__class__", "(", "[", "i", "for", "i", "in", "self", ".", "items", "if", "i", "not", "in", "items", "]", ")" ]
Diff the collections with the given items :param items: The items to diff with :type items: mixed :return: A Collection instance :rtype: Collection
[ "Diff", "the", "collections", "with", "the", "given", "items" ]
python
train
pyroscope/pyrocore
src/pyrocore/torrent/formatting.py
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L41-L47
def fmt_sz(intval): """ Format a byte sized value. """ try: return fmt.human_size(intval) except (ValueError, TypeError): return "N/A".rjust(len(fmt.human_size(0)))
[ "def", "fmt_sz", "(", "intval", ")", ":", "try", ":", "return", "fmt", ".", "human_size", "(", "intval", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "\"N/A\"", ".", "rjust", "(", "len", "(", "fmt", ".", "human_size", "(", ...
Format a byte sized value.
[ "Format", "a", "byte", "sized", "value", "." ]
python
train
mattjj/pylds
pylds/laplace.py
https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/laplace.py#L53-L65
def hessian_local_log_likelihood(self, x): """ return d^2/dxt^2 log p(y | x) for each time bin Optionally override this in base classes """ T, D = self.T, self.D_latent assert x.shape == (T, D) hfun = hessian(self.local_log_likelihood) H_diag = np.zeros((...
[ "def", "hessian_local_log_likelihood", "(", "self", ",", "x", ")", ":", "T", ",", "D", "=", "self", ".", "T", ",", "self", ".", "D_latent", "assert", "x", ".", "shape", "==", "(", "T", ",", "D", ")", "hfun", "=", "hessian", "(", "self", ".", "loc...
return d^2/dxt^2 log p(y | x) for each time bin Optionally override this in base classes
[ "return", "d^2", "/", "dxt^2", "log", "p", "(", "y", "|", "x", ")", "for", "each", "time", "bin", "Optionally", "override", "this", "in", "base", "classes" ]
python
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/random_layer.py
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/random_layer.py#L296-L326
def _compute_centers(self, X, sparse, rs): """Generate RBF centers""" # use supplied centers if present centers = self._get_user_components('centers') # use points taken uniformly from the bounding # hyperrectangle if (centers is None): n_features = X.shape[...
[ "def", "_compute_centers", "(", "self", ",", "X", ",", "sparse", ",", "rs", ")", ":", "# use supplied centers if present", "centers", "=", "self", ".", "_get_user_components", "(", "'centers'", ")", "# use points taken uniformly from the bounding", "# hyperrectangle", "...
Generate RBF centers
[ "Generate", "RBF", "centers" ]
python
train
Nic30/hwtGraph
hwtGraph/elk/fromHwt/resolveSharedConnections.py
https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/fromHwt/resolveSharedConnections.py#L6-L84
def portTryReduce(root: LNode, port: LPort): """ Check if majority of children is connected to same port if it is the case reduce children and connect this port instead children :note: use reduceUselessAssignments, extractSplits, flattenTrees before this function to maximize it's effect """...
[ "def", "portTryReduce", "(", "root", ":", "LNode", ",", "port", ":", "LPort", ")", ":", "if", "not", "port", ".", "children", ":", "return", "for", "p", "in", "port", ".", "children", ":", "portTryReduce", "(", "root", ",", "p", ")", "target_nodes", ...
Check if majority of children is connected to same port if it is the case reduce children and connect this port instead children :note: use reduceUselessAssignments, extractSplits, flattenTrees before this function to maximize it's effect
[ "Check", "if", "majority", "of", "children", "is", "connected", "to", "same", "port", "if", "it", "is", "the", "case", "reduce", "children", "and", "connect", "this", "port", "instead", "children" ]
python
train
quantumlib/Cirq
cirq/sim/sampler.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/sampler.py#L25-L42
def run( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType' = None, repetitions: int = 1, ) -> study.TrialResult: """Samples from the given Circuit or Schedule. Args: program: The...
[ "def", "run", "(", "self", ",", "program", ":", "Union", "[", "circuits", ".", "Circuit", ",", "schedules", ".", "Schedule", "]", ",", "param_resolver", ":", "'study.ParamResolverOrSimilarType'", "=", "None", ",", "repetitions", ":", "int", "=", "1", ",", ...
Samples from the given Circuit or Schedule. Args: program: The circuit or schedule to simulate. param_resolver: Parameters to run with the program. repetitions: The number of repetitions to simulate. Returns: TrialResult for a run.
[ "Samples", "from", "the", "given", "Circuit", "or", "Schedule", "." ]
python
train
n1analytics/python-paillier
phe/command_line.py
https://github.com/n1analytics/python-paillier/blob/955f8c0bfa9623be15b75462b121d28acf70f04b/phe/command_line.py#L139-L165
def decrypt(private, ciphertext, output): """Decrypt ciphertext with private key. Requires PRIVATE key file and the CIPHERTEXT encrypted with the corresponding public key. """ privatekeydata = json.load(private) assert 'pub' in privatekeydata pub = load_public_key(privatekeydata['pub']) ...
[ "def", "decrypt", "(", "private", ",", "ciphertext", ",", "output", ")", ":", "privatekeydata", "=", "json", ".", "load", "(", "private", ")", "assert", "'pub'", "in", "privatekeydata", "pub", "=", "load_public_key", "(", "privatekeydata", "[", "'pub'", "]",...
Decrypt ciphertext with private key. Requires PRIVATE key file and the CIPHERTEXT encrypted with the corresponding public key.
[ "Decrypt", "ciphertext", "with", "private", "key", "." ]
python
train
raphaelvallat/pingouin
pingouin/pandas.py
https://github.com/raphaelvallat/pingouin/blob/58b19fa4fffbfe09d58b456e3926a148249e4d9b/pingouin/pandas.py#L18-L22
def _anova(self, dv=None, between=None, detailed=False, export_filename=None): """Return one-way and two-way ANOVA.""" aov = anova(data=self, dv=dv, between=between, detailed=detailed, export_filename=export_filename) return aov
[ "def", "_anova", "(", "self", ",", "dv", "=", "None", ",", "between", "=", "None", ",", "detailed", "=", "False", ",", "export_filename", "=", "None", ")", ":", "aov", "=", "anova", "(", "data", "=", "self", ",", "dv", "=", "dv", ",", "between", ...
Return one-way and two-way ANOVA.
[ "Return", "one", "-", "way", "and", "two", "-", "way", "ANOVA", "." ]
python
train
alimanfoo/csvvalidator
csvvalidator.py
https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L293-L324
def add_record_predicate(self, record_predicate, code=RECORD_PREDICATE_FALSE, message=MESSAGES[RECORD_PREDICATE_FALSE], modulus=1): """ Add a record predicate function. N.B., everything you can do with record predicates can...
[ "def", "add_record_predicate", "(", "self", ",", "record_predicate", ",", "code", "=", "RECORD_PREDICATE_FALSE", ",", "message", "=", "MESSAGES", "[", "RECORD_PREDICATE_FALSE", "]", ",", "modulus", "=", "1", ")", ":", "assert", "callable", "(", "record_predicate",...
Add a record predicate function. N.B., everything you can do with record predicates can also be done with record check functions, whether you use one or the other is a matter of style. Arguments --------- `record_predicate` - a function that accepts a single argument (...
[ "Add", "a", "record", "predicate", "function", "." ]
python
valid
kmerkmer/pymer
pymer/markov.py
https://github.com/kmerkmer/pymer/blob/c22802436b3756a2e92829c9b234bde6217b683a/pymer/markov.py#L80-L92
def P(self): """Sparse [k-1]x[k-1] transition frequency matrix""" if self._P is not None: return self._P sparse_P = sparse.lil_matrix((self.n, self.n)) alpha_size = len(self.alphabet) bitmask = (self.n-1) # Mask w/ all bits set hi within (k-1)mer range. for f...
[ "def", "P", "(", "self", ")", ":", "if", "self", ".", "_P", "is", "not", "None", ":", "return", "self", ".", "_P", "sparse_P", "=", "sparse", ".", "lil_matrix", "(", "(", "self", ".", "n", ",", "self", ".", "n", ")", ")", "alpha_size", "=", "le...
Sparse [k-1]x[k-1] transition frequency matrix
[ "Sparse", "[", "k", "-", "1", "]", "x", "[", "k", "-", "1", "]", "transition", "frequency", "matrix" ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe.py#L245-L258
def fcoe_fcoe_map_fcoe_map_cee_map_fcoe_map_cee_map_leaf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe") fcoe_map = ET.SubElement(fcoe, "fcoe-map") fcoe_map_name_key ...
[ "def", "fcoe_fcoe_map_fcoe_map_cee_map_fcoe_map_cee_map_leaf", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "fcoe", "=", "ET", ".", "SubElement", "(", "config", ",", "\"fcoe\"", ",", "xmlns", "=...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
CivicSpleen/ambry
ambry/orm/partition.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L790-L796
def analysis(self): """Return an AnalysisPartition proxy, which wraps this partition to provide acess to dataframes, shapely shapes and other analysis services""" if isinstance(self, PartitionProxy): return AnalysisPartition(self._obj) else: return AnalysisPartiti...
[ "def", "analysis", "(", "self", ")", ":", "if", "isinstance", "(", "self", ",", "PartitionProxy", ")", ":", "return", "AnalysisPartition", "(", "self", ".", "_obj", ")", "else", ":", "return", "AnalysisPartition", "(", "self", ")" ]
Return an AnalysisPartition proxy, which wraps this partition to provide acess to dataframes, shapely shapes and other analysis services
[ "Return", "an", "AnalysisPartition", "proxy", "which", "wraps", "this", "partition", "to", "provide", "acess", "to", "dataframes", "shapely", "shapes", "and", "other", "analysis", "services" ]
python
train
django-fluent/django-fluent-contents
fluent_contents/cache.py
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/cache.py#L7-L22
def get_rendering_cache_key(placeholder_name, contentitem): """ Return a cache key for the content item output. .. seealso:: The :func:`ContentItem.clear_cache() <fluent_contents.models.ContentItem.clear_cache>` function can be used to remove the cache keys of a retrieved object. """ ...
[ "def", "get_rendering_cache_key", "(", "placeholder_name", ",", "contentitem", ")", ":", "if", "not", "contentitem", ".", "pk", ":", "return", "None", "return", "\"contentitem.@{0}.{1}.{2}\"", ".", "format", "(", "placeholder_name", ",", "contentitem", ".", "plugin"...
Return a cache key for the content item output. .. seealso:: The :func:`ContentItem.clear_cache() <fluent_contents.models.ContentItem.clear_cache>` function can be used to remove the cache keys of a retrieved object.
[ "Return", "a", "cache", "key", "for", "the", "content", "item", "output", "." ]
python
train
brunobord/meuhdb
meuhdb/core.py
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L171-L175
def insert(self, value): "Insert value in the keystore. Return the UUID key." key = str(uuid4()) self.set(key, value) return key
[ "def", "insert", "(", "self", ",", "value", ")", ":", "key", "=", "str", "(", "uuid4", "(", ")", ")", "self", ".", "set", "(", "key", ",", "value", ")", "return", "key" ]
Insert value in the keystore. Return the UUID key.
[ "Insert", "value", "in", "the", "keystore", ".", "Return", "the", "UUID", "key", "." ]
python
train
alixedi/palal
palal/survey.py
https://github.com/alixedi/palal/blob/325359f66ac48a9f96efea0489aec353f8a40837/palal/survey.py#L28-L31
def _stdin_(p): """Takes input from user. Works for Python 2 and 3.""" _v = sys.version[0] return input(p) if _v is '3' else raw_input(p)
[ "def", "_stdin_", "(", "p", ")", ":", "_v", "=", "sys", ".", "version", "[", "0", "]", "return", "input", "(", "p", ")", "if", "_v", "is", "'3'", "else", "raw_input", "(", "p", ")" ]
Takes input from user. Works for Python 2 and 3.
[ "Takes", "input", "from", "user", ".", "Works", "for", "Python", "2", "and", "3", "." ]
python
train
chaimleib/intervaltree
intervaltree/intervaltree.py
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L622-L643
def split_overlaps(self): """ Finds all intervals with overlapping ranges and splits them along the range boundaries. Completes in worst-case O(n^2*log n) time (many interval boundaries are inside many intervals), best-case O(n*log n) time (small number of overlaps << n ...
[ "def", "split_overlaps", "(", "self", ")", ":", "if", "not", "self", ":", "return", "if", "len", "(", "self", ".", "boundary_table", ")", "==", "2", ":", "return", "bounds", "=", "sorted", "(", "self", ".", "boundary_table", ")", "# get bound locations", ...
Finds all intervals with overlapping ranges and splits them along the range boundaries. Completes in worst-case O(n^2*log n) time (many interval boundaries are inside many intervals), best-case O(n*log n) time (small number of overlaps << n per interval).
[ "Finds", "all", "intervals", "with", "overlapping", "ranges", "and", "splits", "them", "along", "the", "range", "boundaries", "." ]
python
train
spacetelescope/stsci.tools
lib/stsci/tools/minmatch.py
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/minmatch.py#L204-L210
def getallkeys(self, key, failobj=None): """Returns a list of the full key names (not the items) for all the matching values for key. The list will contain a single entry for unambiguous matches and multiple entries for ambiguous matches.""" if self.mmkeys is None: self._mmInit(...
[ "def", "getallkeys", "(", "self", ",", "key", ",", "failobj", "=", "None", ")", ":", "if", "self", ".", "mmkeys", "is", "None", ":", "self", ".", "_mmInit", "(", ")", "return", "self", ".", "mmkeys", ".", "get", "(", "key", ",", "failobj", ")" ]
Returns a list of the full key names (not the items) for all the matching values for key. The list will contain a single entry for unambiguous matches and multiple entries for ambiguous matches.
[ "Returns", "a", "list", "of", "the", "full", "key", "names", "(", "not", "the", "items", ")", "for", "all", "the", "matching", "values", "for", "key", ".", "The", "list", "will", "contain", "a", "single", "entry", "for", "unambiguous", "matches", "and", ...
python
train
onnx/onnxmltools
onnxmltools/convert/libsvm/_parse.py
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/libsvm/_parse.py#L11-L36
def _parse_libsvm_simple_model(scope, model, inputs): ''' This function handles all non-pipeline models. :param scope: Scope object :param model: A libsvm object (e.g., OneHotEncoder and LogisticRegression) :param inputs: A list of variables :return: A list of output variables which will be pas...
[ "def", "_parse_libsvm_simple_model", "(", "scope", ",", "model", ",", "inputs", ")", ":", "if", "model", ".", "get_svm_type", "(", ")", "in", "(", "0", ",", "1", ")", ":", "label_variable", "=", "scope", ".", "declare_local_variable", "(", "'label'", ",", ...
This function handles all non-pipeline models. :param scope: Scope object :param model: A libsvm object (e.g., OneHotEncoder and LogisticRegression) :param inputs: A list of variables :return: A list of output variables which will be passed to next stage
[ "This", "function", "handles", "all", "non", "-", "pipeline", "models", "." ]
python
train
pybluez/pybluez
macos/_lightbluecommon.py
https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/macos/_lightbluecommon.py#L73-L89
def _isbtaddr(address): """ Returns whether the given address is a valid bluetooth address. For example, "00:0e:6d:7b:a2:0a" is a valid address. Returns False if the argument is None or is not a string. """ # Define validity regex. Accept either ":" or "-" as separators. global _validbtaddr...
[ "def", "_isbtaddr", "(", "address", ")", ":", "# Define validity regex. Accept either \":\" or \"-\" as separators.", "global", "_validbtaddr", "if", "_validbtaddr", "is", "None", ":", "import", "re", "_validbtaddr", "=", "re", ".", "compile", "(", "\"((\\d|[a-f]){2}(:|-)...
Returns whether the given address is a valid bluetooth address. For example, "00:0e:6d:7b:a2:0a" is a valid address. Returns False if the argument is None or is not a string.
[ "Returns", "whether", "the", "given", "address", "is", "a", "valid", "bluetooth", "address", ".", "For", "example", "00", ":", "0e", ":", "6d", ":", "7b", ":", "a2", ":", "0a", "is", "a", "valid", "address", "." ]
python
train
tensorflow/hub
tensorflow_hub/feature_column.py
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/feature_column.py#L33-L80
def text_embedding_column(key, module_spec, trainable=False): """Uses a Module to construct a dense representation from a text feature. This feature column can be used on an input feature whose values are strings of arbitrary size. The result of this feature column is the result of passing its `input` throu...
[ "def", "text_embedding_column", "(", "key", ",", "module_spec", ",", "trainable", "=", "False", ")", ":", "module_spec", "=", "module", ".", "as_module_spec", "(", "module_spec", ")", "_check_module_is_text_embedding", "(", "module_spec", ")", "return", "_TextEmbedd...
Uses a Module to construct a dense representation from a text feature. This feature column can be used on an input feature whose values are strings of arbitrary size. The result of this feature column is the result of passing its `input` through the module `m` instantiated from `module_spec`, as per `result...
[ "Uses", "a", "Module", "to", "construct", "a", "dense", "representation", "from", "a", "text", "feature", "." ]
python
train
xflows/rdm
rdm/db/converters.py
https://github.com/xflows/rdm/blob/d984e2a0297e5fa8d799953bbd0dba79b05d403d/rdm/db/converters.py#L51-L64
def mode(self, predicate, args, recall=1, head=False): ''' Emits mode declarations in Aleph-like format. :param predicate: predicate name :param args: predicate arguments with input/output specification, e.g.: >>> [('+', 'train'), ('-', 'car')] :param r...
[ "def", "mode", "(", "self", ",", "predicate", ",", "args", ",", "recall", "=", "1", ",", "head", "=", "False", ")", ":", "return", "':- mode%s(%s, %s(%s)).'", "%", "(", "'h'", "if", "head", "else", "'b'", ",", "str", "(", "recall", ")", ",", "predica...
Emits mode declarations in Aleph-like format. :param predicate: predicate name :param args: predicate arguments with input/output specification, e.g.: >>> [('+', 'train'), ('-', 'car')] :param recall: recall setting (see `Aleph manual <http://www.cs.ox.ac.uk/activities...
[ "Emits", "mode", "declarations", "in", "Aleph", "-", "like", "format", "." ]
python
train
CI-WATER/mapkit
mapkit/RasterConverter.py
https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L1097-L1107
def isNumber(self, value): """ Validate whether a value is a number or not """ try: str(value) float(value) return True except ValueError: return False
[ "def", "isNumber", "(", "self", ",", "value", ")", ":", "try", ":", "str", "(", "value", ")", "float", "(", "value", ")", "return", "True", "except", "ValueError", ":", "return", "False" ]
Validate whether a value is a number or not
[ "Validate", "whether", "a", "value", "is", "a", "number", "or", "not" ]
python
train
kensho-technologies/graphql-compiler
graphql_compiler/compiler/common.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/common.py#L23-L53
def compile_graphql_to_match(schema, graphql_string, type_equivalence_hints=None): """Compile the GraphQL input using the schema into a MATCH query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query to ...
[ "def", "compile_graphql_to_match", "(", "schema", ",", "graphql_string", ",", "type_equivalence_hints", "=", "None", ")", ":", "lowering_func", "=", "ir_lowering_match", ".", "lower_ir", "query_emitter_func", "=", "emit_match", ".", "emit_code_from_ir", "return", "_comp...
Compile the GraphQL input using the schema into a MATCH query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query to compile to MATCH, as a string type_equivalence_hints: optional dict of GraphQL int...
[ "Compile", "the", "GraphQL", "input", "using", "the", "schema", "into", "a", "MATCH", "query", "and", "associated", "metadata", "." ]
python
train
jeffh/rpi_courses
rpi_courses/scheduler.py
https://github.com/jeffh/rpi_courses/blob/c97176f73f866f112c785910ebf3ff8a790e8e9a/rpi_courses/scheduler.py#L128-L134
def create_variables(self, courses): """Internal use. Creates all variables in the problem instance for the given courses. If given a dict of {course: sections}, will use the provided sections. """ has_sections = isinstance(courses, dict) for course in courses: self.p...
[ "def", "create_variables", "(", "self", ",", "courses", ")", ":", "has_sections", "=", "isinstance", "(", "courses", ",", "dict", ")", "for", "course", "in", "courses", ":", "self", ".", "p", ".", "add_variable", "(", "course", ",", "courses", ".", "get"...
Internal use. Creates all variables in the problem instance for the given courses. If given a dict of {course: sections}, will use the provided sections.
[ "Internal", "use", ".", "Creates", "all", "variables", "in", "the", "problem", "instance", "for", "the", "given", "courses", ".", "If", "given", "a", "dict", "of", "{", "course", ":", "sections", "}", "will", "use", "the", "provided", "sections", "." ]
python
train
melizalab/arf
arf.py
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L204-L238
def check_file_version(file): """Check the ARF version attribute of file for compatibility. Raises DeprecationWarning for backwards-incompatible files, FutureWarning for (potentially) forwards-incompatible files, and UserWarning for files that may not have been created by an ARF library. Returns t...
[ "def", "check_file_version", "(", "file", ")", ":", "from", "distutils", ".", "version", "import", "StrictVersion", "as", "Version", "try", ":", "ver", "=", "file", ".", "attrs", ".", "get", "(", "'arf_version'", ",", "None", ")", "if", "ver", "is", "Non...
Check the ARF version attribute of file for compatibility. Raises DeprecationWarning for backwards-incompatible files, FutureWarning for (potentially) forwards-incompatible files, and UserWarning for files that may not have been created by an ARF library. Returns the version for the file
[ "Check", "the", "ARF", "version", "attribute", "of", "file", "for", "compatibility", "." ]
python
train
nderkach/airbnb-python
airbnb/api.py
https://github.com/nderkach/airbnb-python/blob/0b3ed69518e41383eca93ae11b24247f3cc69a27/airbnb/api.py#L186-L201
def get_calendar(self, listing_id, starting_month=datetime.datetime.now().month, starting_year=datetime.datetime.now().year, calendar_months=12): """ Get availability calendar for a given listing """ params = { 'year': str(starting_year), 'listing_id': str(listing...
[ "def", "get_calendar", "(", "self", ",", "listing_id", ",", "starting_month", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "month", ",", "starting_year", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "year", ",", "calendar_...
Get availability calendar for a given listing
[ "Get", "availability", "calendar", "for", "a", "given", "listing" ]
python
train
zencoder/zencoder-py
zencoder/core.py
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L329-L350
def create(self, input=None, live_stream=False, outputs=None, options=None): """ Creates a transcoding job. Here are some examples:: job.create('s3://zencodertesting/test.mov') job.create(live_stream=True) job.create(input='http://example.com/input.mov', ...
[ "def", "create", "(", "self", ",", "input", "=", "None", ",", "live_stream", "=", "False", ",", "outputs", "=", "None", ",", "options", "=", "None", ")", ":", "data", "=", "{", "\"input\"", ":", "input", ",", "\"test\"", ":", "self", ".", "test", "...
Creates a transcoding job. Here are some examples:: job.create('s3://zencodertesting/test.mov') job.create(live_stream=True) job.create(input='http://example.com/input.mov', outputs=({'label': 'test output'},)) https://app.zencoder.com/docs/api/jobs/c...
[ "Creates", "a", "transcoding", "job", ".", "Here", "are", "some", "examples", "::" ]
python
train
mushkevych/scheduler
launch.py
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/launch.py#L139-L145
def install_virtualenv_p3(root, python_version): """ Install virtual environment for Python 3.3+; removing the old one if it exists """ import venv builder = venv.EnvBuilder(system_site_packages=False, clear=True, symlinks=False, upgrade=False) builder.create(root) ret_code = subprocess.call([VE_SCR...
[ "def", "install_virtualenv_p3", "(", "root", ",", "python_version", ")", ":", "import", "venv", "builder", "=", "venv", ".", "EnvBuilder", "(", "system_site_packages", "=", "False", ",", "clear", "=", "True", ",", "symlinks", "=", "False", ",", "upgrade", "=...
Install virtual environment for Python 3.3+; removing the old one if it exists
[ "Install", "virtual", "environment", "for", "Python", "3", ".", "3", "+", ";", "removing", "the", "old", "one", "if", "it", "exists" ]
python
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L473-L476
def _context_menu_make(self, pos): """Reimplement the IPython context menu""" menu = super(ShellWidget, self)._context_menu_make(pos) return self.ipyclient.add_actions_to_context_menu(menu)
[ "def", "_context_menu_make", "(", "self", ",", "pos", ")", ":", "menu", "=", "super", "(", "ShellWidget", ",", "self", ")", ".", "_context_menu_make", "(", "pos", ")", "return", "self", ".", "ipyclient", ".", "add_actions_to_context_menu", "(", "menu", ")" ]
Reimplement the IPython context menu
[ "Reimplement", "the", "IPython", "context", "menu" ]
python
train
bcbio/bcbio-nextgen
bcbio/rnaseq/bcbiornaseq.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/bcbiornaseq.py#L49-L65
def rmarkdown_draft(filename, template, package): """ create a draft rmarkdown file from an installed template """ if file_exists(filename): return filename draft_template = Template( 'rmarkdown::draft("$filename", template="$template", package="$package", edit=FALSE)' ) draf...
[ "def", "rmarkdown_draft", "(", "filename", ",", "template", ",", "package", ")", ":", "if", "file_exists", "(", "filename", ")", ":", "return", "filename", "draft_template", "=", "Template", "(", "'rmarkdown::draft(\"$filename\", template=\"$template\", package=\"$package...
create a draft rmarkdown file from an installed template
[ "create", "a", "draft", "rmarkdown", "file", "from", "an", "installed", "template" ]
python
train
Azure/Azure-MachineLearning-ClientLibrary-Python
azureml/services.py
https://github.com/Azure/Azure-MachineLearning-ClientLibrary-Python/blob/d1211b289747671898eb063013e0dc53d3c80acd/azureml/services.py#L896-L945
def publish(func_or_workspace_id, workspace_id_or_token = None, workspace_token_or_none = None, files=(), endpoint=None): '''publishes a callable function or decorates a function to be published. Returns a callable, iterable object. Calling the object will invoke the published service. Iterating the object will...
[ "def", "publish", "(", "func_or_workspace_id", ",", "workspace_id_or_token", "=", "None", ",", "workspace_token_or_none", "=", "None", ",", "files", "=", "(", ")", ",", "endpoint", "=", "None", ")", ":", "if", "not", "callable", "(", "func_or_workspace_id", ")...
publishes a callable function or decorates a function to be published. Returns a callable, iterable object. Calling the object will invoke the published service. Iterating the object will give the API URL, API key, and API help url. To define a function which will be published to Azure you can simply decorate ...
[ "publishes", "a", "callable", "function", "or", "decorates", "a", "function", "to", "be", "published", "." ]
python
test
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine3d.py#L382-L435
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given rotation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Anoth...
[ "def", "transform", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ")", ":", "# unpack zoom range", "rotation_x", ",", "rotation_y", ",", "rotation_z", "=", "self", ".", "rotation", "# Rotation about X axis", "theta_x", "=", "math", ".", "pi", ...
Transform an image using an Affine transform with the given rotation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ...
[ "Transform", "an", "image", "using", "an", "Affine", "transform", "with", "the", "given", "rotation", "parameters", ".", "Return", "the", "transform", "if", "X", "=", "None", "." ]
python
train
zenotech/SysScribe
sysscribe/__init__.py
https://github.com/zenotech/SysScribe/blob/8cabfc9718e7ccc6d217fbcfc158dd255b28c9b1/sysscribe/__init__.py#L58-L72
def netdevs(): ''' RX and TX bytes for each of the network devices ''' with open('/proc/net/dev') as f: net_dump = f.readlines() device_data={} data = namedtuple('data',['rx','tx']) for line in net_dump[2:]: line = line.split(':') if line[0].strip() != 'lo': ...
[ "def", "netdevs", "(", ")", ":", "with", "open", "(", "'/proc/net/dev'", ")", "as", "f", ":", "net_dump", "=", "f", ".", "readlines", "(", ")", "device_data", "=", "{", "}", "data", "=", "namedtuple", "(", "'data'", ",", "[", "'rx'", ",", "'tx'", "...
RX and TX bytes for each of the network devices
[ "RX", "and", "TX", "bytes", "for", "each", "of", "the", "network", "devices" ]
python
train
woolfson-group/isambard
isambard/ampal/analyse_protein.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/analyse_protein.py#L264-L289
def cc_to_local_params(pitch, radius, oligo): """Returns local parameters for an oligomeric assembly. Parameters ---------- pitch : float Pitch of assembly radius : float Radius of assembly oligo : int Oligomeric state of assembly Returns ------- pitchloc : ...
[ "def", "cc_to_local_params", "(", "pitch", ",", "radius", ",", "oligo", ")", ":", "rloc", "=", "numpy", ".", "sin", "(", "numpy", ".", "pi", "/", "oligo", ")", "*", "radius", "alpha", "=", "numpy", ".", "arctan", "(", "(", "2", "*", "numpy", ".", ...
Returns local parameters for an oligomeric assembly. Parameters ---------- pitch : float Pitch of assembly radius : float Radius of assembly oligo : int Oligomeric state of assembly Returns ------- pitchloc : float Local pitch of assembly (between 2 adja...
[ "Returns", "local", "parameters", "for", "an", "oligomeric", "assembly", "." ]
python
train
KnightConan/sspdatatables
src/sspdatatables/utils/decorator.py
https://github.com/KnightConan/sspdatatables/blob/1179a11358734e5e472e5eee703e8d34fa49e9bf/src/sspdatatables/utils/decorator.py#L41-L59
def generate_error_json_response(error_dict, error_response_context=None): """ Intends to build an error json response. If the error_response_context is None, then we generate this response using data tables format :param error_dict: str/dict: contains the error message(s) :param error_response_con...
[ "def", "generate_error_json_response", "(", "error_dict", ",", "error_response_context", "=", "None", ")", ":", "response", "=", "error_dict", "if", "isinstance", "(", "error_dict", ",", "str", ")", ":", "response", "=", "{", "\"error\"", ":", "response", "}", ...
Intends to build an error json response. If the error_response_context is None, then we generate this response using data tables format :param error_dict: str/dict: contains the error message(s) :param error_response_context: None/dict: context dictionary to render, if error occurs :return: JsonR...
[ "Intends", "to", "build", "an", "error", "json", "response", ".", "If", "the", "error_response_context", "is", "None", "then", "we", "generate", "this", "response", "using", "data", "tables", "format" ]
python
train
ibis-project/ibis
ibis/client.py
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/client.py#L164-L186
def execute(self, expr, params=None, limit='default', **kwargs): """ Compile and execute Ibis expression using this backend client interface, returning results in-memory in the appropriate object type Parameters ---------- expr : Expr limit : int, default None ...
[ "def", "execute", "(", "self", ",", "expr", ",", "params", "=", "None", ",", "limit", "=", "'default'", ",", "*", "*", "kwargs", ")", ":", "query_ast", "=", "self", ".", "_build_ast_ensure_limit", "(", "expr", ",", "limit", ",", "params", "=", "params"...
Compile and execute Ibis expression using this backend client interface, returning results in-memory in the appropriate object type Parameters ---------- expr : Expr limit : int, default None For expressions yielding result yets; retrieve at most this number of ...
[ "Compile", "and", "execute", "Ibis", "expression", "using", "this", "backend", "client", "interface", "returning", "results", "in", "-", "memory", "in", "the", "appropriate", "object", "type" ]
python
train
aio-libs/aiohttp
aiohttp/multipart.py
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/multipart.py#L407-L413
async def json(self, *, encoding: Optional[str]=None) -> Any: """Like read(), but assumes that body parts contains JSON data.""" data = await self.read(decode=True) if not data: return None encoding = encoding or self.get_charset(default='utf-8') return json.loads(dat...
[ "async", "def", "json", "(", "self", ",", "*", ",", "encoding", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Any", ":", "data", "=", "await", "self", ".", "read", "(", "decode", "=", "True", ")", "if", "not", "data", ":", "return", ...
Like read(), but assumes that body parts contains JSON data.
[ "Like", "read", "()", "but", "assumes", "that", "body", "parts", "contains", "JSON", "data", "." ]
python
train
jeffh/describe
describe/spec/runners.py
https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/runners.py#L110-L118
def _execute_example_group(self): "Handles the execution of Example Group" for example in self.example: runner = self.__class__(example, self.formatter) runner.is_root_runner = False successes, failures, skipped = runner.run(self.context) self.num_successe...
[ "def", "_execute_example_group", "(", "self", ")", ":", "for", "example", "in", "self", ".", "example", ":", "runner", "=", "self", ".", "__class__", "(", "example", ",", "self", ".", "formatter", ")", "runner", ".", "is_root_runner", "=", "False", "succes...
Handles the execution of Example Group
[ "Handles", "the", "execution", "of", "Example", "Group" ]
python
train
theonion/django-bulbs
bulbs/videos/models.py
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/videos/models.py#L118-L136
def get_hub_url(self): """gets a canonical path to the detail page of the video on the hub :return: the path to the consumer ui detail page of the video :rtype: str """ url = getattr(settings, "VIDEOHUB_VIDEO_URL", self.DEFAULT_VIDEOHUB_VIDEO_URL) # slugify needs ascii ...
[ "def", "get_hub_url", "(", "self", ")", ":", "url", "=", "getattr", "(", "settings", ",", "\"VIDEOHUB_VIDEO_URL\"", ",", "self", ".", "DEFAULT_VIDEOHUB_VIDEO_URL", ")", "# slugify needs ascii", "ascii_title", "=", "\"\"", "if", "isinstance", "(", "self", ".", "t...
gets a canonical path to the detail page of the video on the hub :return: the path to the consumer ui detail page of the video :rtype: str
[ "gets", "a", "canonical", "path", "to", "the", "detail", "page", "of", "the", "video", "on", "the", "hub" ]
python
train
Gandi/gandi.cli
gandi/cli/commands/webacc.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/webacc.py#L154-L185
def create(gandi, name, datacenter, backend, port, vhost, algorithm, ssl_enable, zone_alter, ssl, private_key, poll_cert): """ Create a webaccelerator """ try: gandi.datacenter.is_opened(datacenter, 'iaas') except DatacenterLimited as exc: gandi.echo('/!\ Datacenter %s will be clo...
[ "def", "create", "(", "gandi", ",", "name", ",", "datacenter", ",", "backend", ",", "port", ",", "vhost", ",", "algorithm", ",", "ssl_enable", ",", "zone_alter", ",", "ssl", ",", "private_key", ",", "poll_cert", ")", ":", "try", ":", "gandi", ".", "dat...
Create a webaccelerator
[ "Create", "a", "webaccelerator" ]
python
train
joke2k/django-faker
django_faker/templatetags/fakers.py
https://github.com/joke2k/django-faker/blob/345e3eebcf636e2566d9890ae7b35788ebdb5173/django_faker/templatetags/fakers.py#L96-L108
def do_fake_filter( formatter, arg=None ): """ call a faker format uses: {{ 'randomElement'|fake:mylist }} {% if 'boolean'|fake:30 %} .. {% endif %} {% for word in 'words'|fake:times %}{{ word }}\n{% endfor %} """ args = [] if not arg is None: args.append(arg) retur...
[ "def", "do_fake_filter", "(", "formatter", ",", "arg", "=", "None", ")", ":", "args", "=", "[", "]", "if", "not", "arg", "is", "None", ":", "args", ".", "append", "(", "arg", ")", "return", "Faker", ".", "getGenerator", "(", ")", ".", "format", "("...
call a faker format uses: {{ 'randomElement'|fake:mylist }} {% if 'boolean'|fake:30 %} .. {% endif %} {% for word in 'words'|fake:times %}{{ word }}\n{% endfor %}
[ "call", "a", "faker", "format", "uses", ":" ]
python
train
locationlabs/mockredis
mockredis/client.py
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L424-L446
def msetnx(self, *args, **kwargs): """ Sets key/values based on a mapping if none of the keys are already set. Mapping can be supplied as a single dictionary argument or as kwargs. Returns a boolean indicating if the operation was successful. """ if args: if l...
[ "def", "msetnx", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", ":", "if", "len", "(", "args", ")", "!=", "1", "or", "not", "isinstance", "(", "args", "[", "0", "]", ",", "dict", ")", ":", "raise", "RedisError",...
Sets key/values based on a mapping if none of the keys are already set. Mapping can be supplied as a single dictionary argument or as kwargs. Returns a boolean indicating if the operation was successful.
[ "Sets", "key", "/", "values", "based", "on", "a", "mapping", "if", "none", "of", "the", "keys", "are", "already", "set", ".", "Mapping", "can", "be", "supplied", "as", "a", "single", "dictionary", "argument", "or", "as", "kwargs", ".", "Returns", "a", ...
python
train
push-things/django-th
django_th/publish.py
https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/publish.py#L26-L35
def update_trigger(self, service): """ update the date when occurs the trigger :param service: service object to update """ now = arrow.utcnow().to(settings.TIME_ZONE).format('YYYY-MM-DD HH:mm:ssZZ') TriggerService.objects.filter(id=service.id).update(date_trigger...
[ "def", "update_trigger", "(", "self", ",", "service", ")", ":", "now", "=", "arrow", ".", "utcnow", "(", ")", ".", "to", "(", "settings", ".", "TIME_ZONE", ")", ".", "format", "(", "'YYYY-MM-DD HH:mm:ssZZ'", ")", "TriggerService", ".", "objects", ".", "f...
update the date when occurs the trigger :param service: service object to update
[ "update", "the", "date", "when", "occurs", "the", "trigger", ":", "param", "service", ":", "service", "object", "to", "update" ]
python
train
pikepdf/pikepdf
src/pikepdf/_methods.py
https://github.com/pikepdf/pikepdf/blob/07154f4dec007e2e9c0c6a8c07b964fd06bc5f77/src/pikepdf/_methods.py#L76-L83
def _single_page_pdf(page): """Construct a single page PDF from the provided page in memory""" pdf = Pdf.new() pdf.pages.append(page) bio = BytesIO() pdf.save(bio) bio.seek(0) return bio.read()
[ "def", "_single_page_pdf", "(", "page", ")", ":", "pdf", "=", "Pdf", ".", "new", "(", ")", "pdf", ".", "pages", ".", "append", "(", "page", ")", "bio", "=", "BytesIO", "(", ")", "pdf", ".", "save", "(", "bio", ")", "bio", ".", "seek", "(", "0",...
Construct a single page PDF from the provided page in memory
[ "Construct", "a", "single", "page", "PDF", "from", "the", "provided", "page", "in", "memory" ]
python
train
senaite/senaite.core
bika/lims/workflow/worksheet/guards.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/workflow/worksheet/guards.py#L26-L57
def guard_submit(obj): """Returns if 'submit' transition can be applied to the worksheet passed in. By default, the target state for the 'submit' transition for a worksheet is 'to_be_verified', so this guard returns true if all the analyses assigned to the worksheet have already been submitted. Those an...
[ "def", "guard_submit", "(", "obj", ")", ":", "analyses", "=", "obj", ".", "getAnalyses", "(", ")", "if", "not", "analyses", ":", "# An empty worksheet cannot be submitted", "return", "False", "can_submit", "=", "False", "for", "analysis", "in", "obj", ".", "ge...
Returns if 'submit' transition can be applied to the worksheet passed in. By default, the target state for the 'submit' transition for a worksheet is 'to_be_verified', so this guard returns true if all the analyses assigned to the worksheet have already been submitted. Those analyses that are in a non-v...
[ "Returns", "if", "submit", "transition", "can", "be", "applied", "to", "the", "worksheet", "passed", "in", ".", "By", "default", "the", "target", "state", "for", "the", "submit", "transition", "for", "a", "worksheet", "is", "to_be_verified", "so", "this", "g...
python
train
allenai/allennlp
scripts/convert_openie_to_conll.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L186-L196
def parse_element(raw_element: str) -> List[Element]: """ Parse a raw element into text and indices (integers). """ elements = [regex.match("^(([a-zA-Z]+)\(([^;]+),List\(([^;]*)\)\))$", elem.lstrip().rstrip()) for elem in raw_element.split(';')...
[ "def", "parse_element", "(", "raw_element", ":", "str", ")", "->", "List", "[", "Element", "]", ":", "elements", "=", "[", "regex", ".", "match", "(", "\"^(([a-zA-Z]+)\\(([^;]+),List\\(([^;]*)\\)\\))$\"", ",", "elem", ".", "lstrip", "(", ")", ".", "rstrip", ...
Parse a raw element into text and indices (integers).
[ "Parse", "a", "raw", "element", "into", "text", "and", "indices", "(", "integers", ")", "." ]
python
train
NeuralEnsemble/lazyarray
lazyarray.py
https://github.com/NeuralEnsemble/lazyarray/blob/391a4cef3be85309c36adac0c17824de3d82f5be/lazyarray.py#L540-L549
def _build_ufunc(func): """Return a ufunc that works with lazy arrays""" def larray_compatible_ufunc(x): if isinstance(x, larray): y = deepcopy(x) y.apply(func) return y else: return func(x) return larray_compatible_ufunc
[ "def", "_build_ufunc", "(", "func", ")", ":", "def", "larray_compatible_ufunc", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "larray", ")", ":", "y", "=", "deepcopy", "(", "x", ")", "y", ".", "apply", "(", "func", ")", "return", "y", "els...
Return a ufunc that works with lazy arrays
[ "Return", "a", "ufunc", "that", "works", "with", "lazy", "arrays" ]
python
train
mk-fg/txu1
txu1/api_v1.py
https://github.com/mk-fg/txu1/blob/0326e9105f3cf9efa17a3d2ed1dd5606e0ad57d6/txu1/api_v1.py#L61-L64
def force_bytes(bytes_or_unicode, encoding='utf-8', errors='backslashreplace'): 'Convert passed string type to bytes, if necessary.' if isinstance(bytes_or_unicode, bytes): return bytes_or_unicode return bytes_or_unicode.encode(encoding, errors)
[ "def", "force_bytes", "(", "bytes_or_unicode", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'backslashreplace'", ")", ":", "if", "isinstance", "(", "bytes_or_unicode", ",", "bytes", ")", ":", "return", "bytes_or_unicode", "return", "bytes_or_unicode", "."...
Convert passed string type to bytes, if necessary.
[ "Convert", "passed", "string", "type", "to", "bytes", "if", "necessary", "." ]
python
train
LionelAuroux/pyrser
pyrser/type_system/symbol.py
https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/symbol.py#L39-L49
def get_scope_list(self) -> list: """ Return the list of all contained scope from global to local """ # by default only return scoped name lstparent = [self] p = self.get_parent() while p is not None: lstparent.append(p) p = p.get_parent() ...
[ "def", "get_scope_list", "(", "self", ")", "->", "list", ":", "# by default only return scoped name", "lstparent", "=", "[", "self", "]", "p", "=", "self", ".", "get_parent", "(", ")", "while", "p", "is", "not", "None", ":", "lstparent", ".", "append", "("...
Return the list of all contained scope from global to local
[ "Return", "the", "list", "of", "all", "contained", "scope", "from", "global", "to", "local" ]
python
test
senaite/senaite.core
bika/lims/workflow/analysis/events.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/workflow/analysis/events.py#L85-L114
def after_submit(analysis): """Method triggered after a 'submit' transition for the analysis passed in is performed. Promotes the submit transition to the Worksheet to which the analysis belongs to. Note that for the worksheet there is already a guard that assures the transition to the worksheet will on...
[ "def", "after_submit", "(", "analysis", ")", ":", "# Mark this analysis as ISubmitted", "alsoProvides", "(", "analysis", ",", "ISubmitted", ")", "# Promote to analyses this analysis depends on", "promote_to_dependencies", "(", "analysis", ",", "\"submit\"", ")", "# TODO: REFL...
Method triggered after a 'submit' transition for the analysis passed in is performed. Promotes the submit transition to the Worksheet to which the analysis belongs to. Note that for the worksheet there is already a guard that assures the transition to the worksheet will only be performed if all analyses...
[ "Method", "triggered", "after", "a", "submit", "transition", "for", "the", "analysis", "passed", "in", "is", "performed", ".", "Promotes", "the", "submit", "transition", "to", "the", "Worksheet", "to", "which", "the", "analysis", "belongs", "to", ".", "Note", ...
python
train
RetailMeNotSandbox/acky
acky/s3.py
https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/s3.py#L60-L73
def create(self, url): """Create a bucket, directory, or empty file.""" bucket, obj_key = _parse_url(url) if not bucket: raise InvalidURL(url, "You must specify a bucket and (optional) path") if obj_key: target = "/".join((bucket, ob...
[ "def", "create", "(", "self", ",", "url", ")", ":", "bucket", ",", "obj_key", "=", "_parse_url", "(", "url", ")", "if", "not", "bucket", ":", "raise", "InvalidURL", "(", "url", ",", "\"You must specify a bucket and (optional) path\"", ")", "if", "obj_key", "...
Create a bucket, directory, or empty file.
[ "Create", "a", "bucket", "directory", "or", "empty", "file", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/__init__.py#L97-L123
def _set_mep_id(self, v, load=False): """ Setter method for mep_id, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/mep_id (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_mep_id is considered as a private method. Backends ...
[ "def", "_set_mep_id", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "parent", "=", "getattr", "(", "self", ",", "\"_parent\"", ",", "None", ")", "if", "parent", "is", "not", "None", "and", "load", "is", "False", ":", "raise", "Attribute...
Setter method for mep_id, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/mep_id (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_mep_id is considered as a private method. Backends looking to populate this variable should do so...
[ "Setter", "method", "for", "mep_id", "mapped", "from", "YANG", "variable", "/", "protocol", "/", "cfm", "/", "domain_name", "/", "ma_name", "/", "cfm_ma_sub_commands", "/", "mep", "/", "mep_id", "(", "uint32", ")", "If", "this", "variable", "is", "read", "...
python
train
xi/ldif3
ldif3.py
https://github.com/xi/ldif3/blob/debc4222bb48492de0d3edcc3c71fdae5bc612a4/ldif3.py#L116-L124
def _needs_base64_encoding(self, attr_type, attr_value): """Return True if attr_value has to be base-64 encoded. This is the case because of special chars or because attr_type is in self._base64_attrs """ return attr_type.lower() in self._base64_attrs or \ isinstance...
[ "def", "_needs_base64_encoding", "(", "self", ",", "attr_type", ",", "attr_value", ")", ":", "return", "attr_type", ".", "lower", "(", ")", "in", "self", ".", "_base64_attrs", "or", "isinstance", "(", "attr_value", ",", "bytes", ")", "or", "UNSAFE_STRING_RE", ...
Return True if attr_value has to be base-64 encoded. This is the case because of special chars or because attr_type is in self._base64_attrs
[ "Return", "True", "if", "attr_value", "has", "to", "be", "base", "-", "64", "encoded", "." ]
python
train
ejeschke/ginga
ginga/ImageView.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L353-L384
def set_window_size(self, width, height): """Report the size of the window to display the image. **Callbacks** Will call any callbacks registered for the ``'configure'`` event. Callbacks should have a method signature of:: (viewer, width, height, ...) .. note:: ...
[ "def", "set_window_size", "(", "self", ",", "width", ",", "height", ")", ":", "self", ".", "_imgwin_wd", "=", "int", "(", "width", ")", "self", ".", "_imgwin_ht", "=", "int", "(", "height", ")", "self", ".", "_ctr_x", "=", "width", "//", "2", "self",...
Report the size of the window to display the image. **Callbacks** Will call any callbacks registered for the ``'configure'`` event. Callbacks should have a method signature of:: (viewer, width, height, ...) .. note:: This is called by the subclass with ``widt...
[ "Report", "the", "size", "of", "the", "window", "to", "display", "the", "image", "." ]
python
train
airspeed-velocity/asv
asv/extern/asizeof.py
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1031-L1037
def kwds(self): '''Return all attributes as keywords dict. ''' # no dict(refs=self.refs, ..., kind=self.kind) in Python 2.0 return _kwds(base=self.base, item=self.item, leng=self.leng, refs=self.refs, both=self.both, kind=self.kind, type=self.ty...
[ "def", "kwds", "(", "self", ")", ":", "# no dict(refs=self.refs, ..., kind=self.kind) in Python 2.0", "return", "_kwds", "(", "base", "=", "self", ".", "base", ",", "item", "=", "self", ".", "item", ",", "leng", "=", "self", ".", "leng", ",", "refs", "=", ...
Return all attributes as keywords dict.
[ "Return", "all", "attributes", "as", "keywords", "dict", "." ]
python
train
pybel/pybel
src/pybel/struct/grouping/provenance.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/grouping/provenance.py#L15-L32
def get_subgraphs_by_citation(graph): """Stratify the graph based on citations. :type graph: pybel.BELGraph :rtype: dict[tuple[str,str],pybel.BELGraph] """ rv = defaultdict(graph.fresh_copy) for u, v, key, data in graph.edges(keys=True, data=True): if CITATION not in data: ...
[ "def", "get_subgraphs_by_citation", "(", "graph", ")", ":", "rv", "=", "defaultdict", "(", "graph", ".", "fresh_copy", ")", "for", "u", ",", "v", ",", "key", ",", "data", "in", "graph", ".", "edges", "(", "keys", "=", "True", ",", "data", "=", "True"...
Stratify the graph based on citations. :type graph: pybel.BELGraph :rtype: dict[tuple[str,str],pybel.BELGraph]
[ "Stratify", "the", "graph", "based", "on", "citations", "." ]
python
train
Yelp/kafka-utils
kafka_utils/kafka_check/commands/replication_factor.py
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_check/commands/replication_factor.py#L78-L107
def _prepare_output(topics_with_wrong_rf, verbose): """Returns dict with 'raw' and 'message' keys filled.""" out = {} topics_count = len(topics_with_wrong_rf) out['raw'] = { 'topics_with_wrong_replication_factor_count': topics_count, } if topics_count == 0: out['message'] = 'All...
[ "def", "_prepare_output", "(", "topics_with_wrong_rf", ",", "verbose", ")", ":", "out", "=", "{", "}", "topics_count", "=", "len", "(", "topics_with_wrong_rf", ")", "out", "[", "'raw'", "]", "=", "{", "'topics_with_wrong_replication_factor_count'", ":", "topics_co...
Returns dict with 'raw' and 'message' keys filled.
[ "Returns", "dict", "with", "raw", "and", "message", "keys", "filled", "." ]
python
train
mlperf/training
translation/tensorflow/transformer/utils/tokenizer.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L372-L391
def _split_token_to_subtokens(token, subtoken_dict, max_subtoken_length): """Splits a token into subtokens defined in the subtoken dict.""" ret = [] start = 0 token_len = len(token) while start < token_len: # Find the longest subtoken, so iterate backwards. for end in xrange(min(token_len, start + max...
[ "def", "_split_token_to_subtokens", "(", "token", ",", "subtoken_dict", ",", "max_subtoken_length", ")", ":", "ret", "=", "[", "]", "start", "=", "0", "token_len", "=", "len", "(", "token", ")", "while", "start", "<", "token_len", ":", "# Find the longest subt...
Splits a token into subtokens defined in the subtoken dict.
[ "Splits", "a", "token", "into", "subtokens", "defined", "in", "the", "subtoken", "dict", "." ]
python
train
hubo1016/namedstruct
namedstruct/namedstruct.py
https://github.com/hubo1016/namedstruct/blob/5039026e0df4ce23003d212358918dbe1a6e1d76/namedstruct/namedstruct.py#L366-L373
def _create_embedded_indices(self): ''' Create indices for all the embedded structs. For parser internal use. ''' try: self._target._embedded_indices.update(((k,(self,v)) for k,v in getattr(self._parser.typedef, 'inline_names', {}).items())) except AttributeError: ...
[ "def", "_create_embedded_indices", "(", "self", ")", ":", "try", ":", "self", ".", "_target", ".", "_embedded_indices", ".", "update", "(", "(", "(", "k", ",", "(", "self", ",", "v", ")", ")", "for", "k", ",", "v", "in", "getattr", "(", "self", "."...
Create indices for all the embedded structs. For parser internal use.
[ "Create", "indices", "for", "all", "the", "embedded", "structs", ".", "For", "parser", "internal", "use", "." ]
python
train
BlueBrain/NeuroM
neurom/morphmath.py
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/morphmath.py#L387-L419
def principal_direction_extent(points): '''Calculate the extent of a set of 3D points. The extent is defined as the maximum distance between the projections on the principal directions of the covariance matrix of the points. Parameter: points : a 2D numpy array of points Returns: ext...
[ "def", "principal_direction_extent", "(", "points", ")", ":", "# center the points around 0.0", "points", "=", "np", ".", "copy", "(", "points", ")", "points", "-=", "np", ".", "mean", "(", "points", ",", "axis", "=", "0", ")", "# principal components", "_", ...
Calculate the extent of a set of 3D points. The extent is defined as the maximum distance between the projections on the principal directions of the covariance matrix of the points. Parameter: points : a 2D numpy array of points Returns: extents : the extents for each of the eigenvectors...
[ "Calculate", "the", "extent", "of", "a", "set", "of", "3D", "points", "." ]
python
train
hydpy-dev/hydpy
hydpy/models/hbranch/hbranch_model.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/hbranch/hbranch_model.py#L11-L94
def calc_outputs_v1(self): """Performs the actual interpolation or extrapolation. Required control parameters: |XPoints| |YPoints| Required derived parameter: |NmbPoints| |NmbBranches| Required flux sequence: |Input| Calculated flux sequence: |Outputs| Ex...
[ "def", "calc_outputs_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "der", "=", "self", ".", "parameters", ".", "derived", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".",...
Performs the actual interpolation or extrapolation. Required control parameters: |XPoints| |YPoints| Required derived parameter: |NmbPoints| |NmbBranches| Required flux sequence: |Input| Calculated flux sequence: |Outputs| Examples: As a simple examp...
[ "Performs", "the", "actual", "interpolation", "or", "extrapolation", "." ]
python
train
ManiacalLabs/BiblioPixel
bibliopixel/layout/matrix.py
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix.py#L299-L307
def fillRoundRect(self, x, y, w, h, r, color=None, aa=False): """ Draw a rounded rectangle with top-left corner at (x, y), width w, height h, and corner radius r :param aa: if True, use Bresenham's algorithm for line drawing; otherwise use Xiaolin Wu's algorithm """ ...
[ "def", "fillRoundRect", "(", "self", ",", "x", ",", "y", ",", "w", ",", "h", ",", "r", ",", "color", "=", "None", ",", "aa", "=", "False", ")", ":", "md", ".", "fill_round_rect", "(", "self", ".", "set", ",", "x", ",", "y", ",", "w", ",", "...
Draw a rounded rectangle with top-left corner at (x, y), width w, height h, and corner radius r :param aa: if True, use Bresenham's algorithm for line drawing; otherwise use Xiaolin Wu's algorithm
[ "Draw", "a", "rounded", "rectangle", "with", "top", "-", "left", "corner", "at", "(", "x", "y", ")", "width", "w", "height", "h", "and", "corner", "radius", "r" ]
python
valid
MinchinWeb/colourettu
colourettu/_colour.py
https://github.com/MinchinWeb/colourettu/blob/f0b2f6b1d44055f3ccee62ac2759829f1e16a252/colourettu/_colour.py#L288-L377
def contrast(colour1, colour2): r"""Determines the contrast between two colours. Args: colour1 (colourettu.Colour): a colour colour2 (colourettu.Colour): a second colour Contrast the difference in (perceived) brightness between colours. Values vary between 1:1 (a given colour on itself...
[ "def", "contrast", "(", "colour1", ",", "colour2", ")", ":", "colour_for_type", "=", "Colour", "(", ")", "if", "type", "(", "colour1", ")", "is", "type", "(", "colour_for_type", ")", ":", "mycolour1", "=", "colour1", "else", ":", "try", ":", "mycolour1",...
r"""Determines the contrast between two colours. Args: colour1 (colourettu.Colour): a colour colour2 (colourettu.Colour): a second colour Contrast the difference in (perceived) brightness between colours. Values vary between 1:1 (a given colour on itself) and 21:1 (white on black). ...
[ "r", "Determines", "the", "contrast", "between", "two", "colours", "." ]
python
train
pyrogram/pyrogram
pyrogram/client/methods/bots/set_game_score.py
https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/methods/bots/set_game_score.py#L27-L92
def set_game_score( self, user_id: Union[int, str], score: int, force: bool = None, disable_edit_message: bool = None, chat_id: Union[int, str] = None, message_id: int = None ): # inline_message_id: str = None): TODO Add inline_message_id """U...
[ "def", "set_game_score", "(", "self", ",", "user_id", ":", "Union", "[", "int", ",", "str", "]", ",", "score", ":", "int", ",", "force", ":", "bool", "=", "None", ",", "disable_edit_message", ":", "bool", "=", "None", ",", "chat_id", ":", "Union", "[...
Use this method to set the score of the specified user in a game. Args: user_id (``int`` | ``str``): Unique identifier (int) or username (str) of the target chat. For your personal cloud (Saved Messages) you can simply use "me" or "self". For a contac...
[ "Use", "this", "method", "to", "set", "the", "score", "of", "the", "specified", "user", "in", "a", "game", "." ]
python
train
oscarbranson/latools
latools/helpers/helpers.py
https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/helpers/helpers.py#L220-L237
def bool_2_indices(a): """ Convert boolean array into a 2D array of (start, stop) pairs. """ if any(a): lims = [] lims.append(np.where(a[:-1] != a[1:])[0]) if a[0]: lims.append([0]) if a[-1]: lims.append([len(a) - 1]) lims = np.concatenate...
[ "def", "bool_2_indices", "(", "a", ")", ":", "if", "any", "(", "a", ")", ":", "lims", "=", "[", "]", "lims", ".", "append", "(", "np", ".", "where", "(", "a", "[", ":", "-", "1", "]", "!=", "a", "[", "1", ":", "]", ")", "[", "0", "]", "...
Convert boolean array into a 2D array of (start, stop) pairs.
[ "Convert", "boolean", "array", "into", "a", "2D", "array", "of", "(", "start", "stop", ")", "pairs", "." ]
python
test
volafiled/python-volapi
volapi/handler.py
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L194-L199
def _handle_changed_config(self, change): """Handle configuration changes""" key, value = change.get("key"), change.get("value") self.room.config.update({key: value}) self.conn.enqueue_data("config", self.room.config)
[ "def", "_handle_changed_config", "(", "self", ",", "change", ")", ":", "key", ",", "value", "=", "change", ".", "get", "(", "\"key\"", ")", ",", "change", ".", "get", "(", "\"value\"", ")", "self", ".", "room", ".", "config", ".", "update", "(", "{",...
Handle configuration changes
[ "Handle", "configuration", "changes" ]
python
train
MartijnBraam/pyElectronics
electronics/devices/hmc5883l.py
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/hmc5883l.py#L128-L150
def gauss(self): """ Get the magnetometer values as gauss for each axis as a tuple (x,y,z) :example: >>> sensor = HMC5883L(gw) >>> sensor.gauss() (16.56, 21.2888, 26.017599999999998) """ raw = self.raw() factors = { 1370: 0.73, ...
[ "def", "gauss", "(", "self", ")", ":", "raw", "=", "self", ".", "raw", "(", ")", "factors", "=", "{", "1370", ":", "0.73", ",", "1090", ":", "0.92", ",", "820", ":", "1.22", ",", "660", ":", "1.52", ",", "440", ":", "2.27", ",", "390", ":", ...
Get the magnetometer values as gauss for each axis as a tuple (x,y,z) :example: >>> sensor = HMC5883L(gw) >>> sensor.gauss() (16.56, 21.2888, 26.017599999999998)
[ "Get", "the", "magnetometer", "values", "as", "gauss", "for", "each", "axis", "as", "a", "tuple", "(", "x", "y", "z", ")" ]
python
train
kstaniek/condoor
condoor/actions.py
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L154-L161
def a_expected_prompt(ctx): """Update driver, config mode and hostname when received an expected prompt.""" prompt = ctx.ctrl.match.group(0) ctx.device.update_driver(prompt) ctx.device.update_config_mode() ctx.device.update_hostname() ctx.finished = True return True
[ "def", "a_expected_prompt", "(", "ctx", ")", ":", "prompt", "=", "ctx", ".", "ctrl", ".", "match", ".", "group", "(", "0", ")", "ctx", ".", "device", ".", "update_driver", "(", "prompt", ")", "ctx", ".", "device", ".", "update_config_mode", "(", ")", ...
Update driver, config mode and hostname when received an expected prompt.
[ "Update", "driver", "config", "mode", "and", "hostname", "when", "received", "an", "expected", "prompt", "." ]
python
train
klahnakoski/pyLibrary
pyLibrary/env/flask_wrappers.py
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/env/flask_wrappers.py#L68-L114
def dockerflow(flask_app, backend_check): """ ADD ROUTING TO HANDLE DOCKERFLOW APP REQUIREMENTS (see https://github.com/mozilla-services/Dockerflow#containerized-app-requirements) :param flask_app: THE (Flask) APP :param backend_check: METHOD THAT WILL CHECK THE BACKEND IS WORKING AND RAISE AN EXCEP...
[ "def", "dockerflow", "(", "flask_app", ",", "backend_check", ")", ":", "global", "VERSION_JSON", "try", ":", "VERSION_JSON", "=", "File", "(", "\"version.json\"", ")", ".", "read_bytes", "(", ")", "@", "cors_wrapper", "def", "version", "(", ")", ":", "return...
ADD ROUTING TO HANDLE DOCKERFLOW APP REQUIREMENTS (see https://github.com/mozilla-services/Dockerflow#containerized-app-requirements) :param flask_app: THE (Flask) APP :param backend_check: METHOD THAT WILL CHECK THE BACKEND IS WORKING AND RAISE AN EXCEPTION IF NOT :return:
[ "ADD", "ROUTING", "TO", "HANDLE", "DOCKERFLOW", "APP", "REQUIREMENTS", "(", "see", "https", ":", "//", "github", ".", "com", "/", "mozilla", "-", "services", "/", "Dockerflow#containerized", "-", "app", "-", "requirements", ")", ":", "param", "flask_app", ":...
python
train
mitsei/dlkit
dlkit/json_/learning/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/sessions.py#L1732-L1753
def get_objective_bank_ids_by_objective(self, objective_id): """Gets the list of ``ObjectiveBank`` ``Ids`` mapped to an ``Objective``. arg: objective_id (osid.id.Id): ``Id`` of an ``Objective`` return: (osid.id.IdList) - list of objective bank ``Ids`` raise: NotFound - ``objective_...
[ "def", "get_objective_bank_ids_by_objective", "(", "self", ",", "objective_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinSession.get_bin_ids_by_resource", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'LEARNING'", ",", "local", "=", "...
Gets the list of ``ObjectiveBank`` ``Ids`` mapped to an ``Objective``. arg: objective_id (osid.id.Id): ``Id`` of an ``Objective`` return: (osid.id.IdList) - list of objective bank ``Ids`` raise: NotFound - ``objective_id`` is not found raise: NullArgument - ``objective_id`` is ``n...
[ "Gets", "the", "list", "of", "ObjectiveBank", "Ids", "mapped", "to", "an", "Objective", "." ]
python
train
xtrementl/focus
focus/parser/parser.py
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/parser.py#L324-L338
def _rule_value(self): """ Parses the production rule:: value : TERM (',' TERM)* Returns list of string terms. """ terms = [self._get_token()] # consume additional terms if available while self._lookahead_token() == ',': self._get_to...
[ "def", "_rule_value", "(", "self", ")", ":", "terms", "=", "[", "self", ".", "_get_token", "(", ")", "]", "# consume additional terms if available", "while", "self", ".", "_lookahead_token", "(", ")", "==", "','", ":", "self", ".", "_get_token", "(", ")", ...
Parses the production rule:: value : TERM (',' TERM)* Returns list of string terms.
[ "Parses", "the", "production", "rule", "::", "value", ":", "TERM", "(", "TERM", ")", "*" ]
python
train
sony/nnabla
python/src/nnabla/experimental/graph_converters/batch_normalization_folded.py
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/experimental/graph_converters/batch_normalization_folded.py#L41-L94
def convert(self, vroot, entry_variables): """ All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. """ self.graph_info ...
[ "def", "convert", "(", "self", ",", "vroot", ",", "entry_variables", ")", ":", "self", ".", "graph_info", "=", "GraphInfo", "(", "vroot", ")", "self", ".", "entry_variables", "=", "entry_variables", "with", "nn", ".", "parameter_scope", "(", "self", ".", "...
All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
[ "All", "functions", "are", "replaced", "with", "the", "same", "new", "function", "." ]
python
train
datacamp/pythonwhat
pythonwhat/checks/has_funcs.py
https://github.com/datacamp/pythonwhat/blob/ffbf7f8436a51f77c22f3bed75ba3bc37a5c666f/pythonwhat/checks/has_funcs.py#L537-L575
def has_output(state, text, pattern=True, no_output_msg=None): """Search student output for a pattern. Among the student and solution process, the student submission and solution code as a string, the ``Ex()`` state also contains the output that a student generated with his or her submission. With ``h...
[ "def", "has_output", "(", "state", ",", "text", ",", "pattern", "=", "True", ",", "no_output_msg", "=", "None", ")", ":", "if", "not", "no_output_msg", ":", "no_output_msg", "=", "\"You did not output the correct things.\"", "_msg", "=", "state", ".", "build_mes...
Search student output for a pattern. Among the student and solution process, the student submission and solution code as a string, the ``Ex()`` state also contains the output that a student generated with his or her submission. With ``has_output()``, you can access this output and match it against a regul...
[ "Search", "student", "output", "for", "a", "pattern", "." ]
python
test
FNNDSC/pfmisc
pfmisc/C_snode.py
https://github.com/FNNDSC/pfmisc/blob/960b4d6135fcc50bed0a8e55db2ab1ddad9b99d8/pfmisc/C_snode.py#L1108-L1114
def treeNode_metaSet(self, astr_path, **kwargs): """ Sets the metaData_print bit on node at <astr_path>. """ self.cdnode(astr_path) self.snode_current.metaData_print(self.b_printMetaData) return {'status': True}
[ "def", "treeNode_metaSet", "(", "self", ",", "astr_path", ",", "*", "*", "kwargs", ")", ":", "self", ".", "cdnode", "(", "astr_path", ")", "self", ".", "snode_current", ".", "metaData_print", "(", "self", ".", "b_printMetaData", ")", "return", "{", "'statu...
Sets the metaData_print bit on node at <astr_path>.
[ "Sets", "the", "metaData_print", "bit", "on", "node", "at", "<astr_path", ">", "." ]
python
train
snipsco/snipsmanagercore
snipsmanagercore/intent_parser.py
https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L136-L169
def parse_instant_time(slot): """ Parse a slot into an InstantTime object. Sample response: { "entity": "snips/datetime", "range": { "end": 36, "start": 28 }, "rawValue": "tomorrow", "slotName": "weatherForecastStartDate...
[ "def", "parse_instant_time", "(", "slot", ")", ":", "date", "=", "IntentParser", ".", "get_dict_value", "(", "slot", ",", "[", "'value'", ",", "'value'", "]", ")", "if", "not", "date", ":", "return", "None", "date", "=", "parse", "(", "date", ")", "if"...
Parse a slot into an InstantTime object. Sample response: { "entity": "snips/datetime", "range": { "end": 36, "start": 28 }, "rawValue": "tomorrow", "slotName": "weatherForecastStartDatetime", "value": { "g...
[ "Parse", "a", "slot", "into", "an", "InstantTime", "object", "." ]
python
train
OCA/vertical-hotel
hotel/models/hotel.py
https://github.com/OCA/vertical-hotel/blob/a01442e92b5ea1fda7fb9e6180b3211e8749a35a/hotel/models/hotel.py#L247-L256
def isroom_change(self): ''' Based on isroom, status will be updated. ---------------------------------------- @param self: object pointer ''' if self.isroom is False: self.status = 'occupied' if self.isroom is True: self.status = 'availabl...
[ "def", "isroom_change", "(", "self", ")", ":", "if", "self", ".", "isroom", "is", "False", ":", "self", ".", "status", "=", "'occupied'", "if", "self", ".", "isroom", "is", "True", ":", "self", ".", "status", "=", "'available'" ]
Based on isroom, status will be updated. ---------------------------------------- @param self: object pointer
[ "Based", "on", "isroom", "status", "will", "be", "updated", ".", "----------------------------------------" ]
python
train
aliyun/aliyun-odps-python-sdk
odps/df/expr/collections.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/collections.py#L922-L955
def pivot(expr, rows, columns, values=None): """ Produce ‘pivot’ table based on 3 columns of this DataFrame. Uses unique values from rows / columns and fills with values. :param expr: collection :param rows: use to make new collection's grouped rows :param columns: use to make new collection's ...
[ "def", "pivot", "(", "expr", ",", "rows", ",", "columns", ",", "values", "=", "None", ")", ":", "rows", "=", "[", "expr", ".", "_get_field", "(", "r", ")", "for", "r", "in", "utils", ".", "to_list", "(", "rows", ")", "]", "columns", "=", "[", "...
Produce ‘pivot’ table based on 3 columns of this DataFrame. Uses unique values from rows / columns and fills with values. :param expr: collection :param rows: use to make new collection's grouped rows :param columns: use to make new collection's columns :param values: values to use for populating n...
[ "Produce", "‘pivot’", "table", "based", "on", "3", "columns", "of", "this", "DataFrame", ".", "Uses", "unique", "values", "from", "rows", "/", "columns", "and", "fills", "with", "values", "." ]
python
train
llazzaro/django-scheduler
schedule/models/events.py
https://github.com/llazzaro/django-scheduler/blob/0530b74a5fc0b1125645002deaa4da2337ed0f17/schedule/models/events.py#L513-L521
def create_relation(self, event, content_object, distinction=''): """ Creates a relation between event and content_object. See EventRelation for help on distinction. """ return EventRelation.objects.create( event=event, distinction=distinction, ...
[ "def", "create_relation", "(", "self", ",", "event", ",", "content_object", ",", "distinction", "=", "''", ")", ":", "return", "EventRelation", ".", "objects", ".", "create", "(", "event", "=", "event", ",", "distinction", "=", "distinction", ",", "content_o...
Creates a relation between event and content_object. See EventRelation for help on distinction.
[ "Creates", "a", "relation", "between", "event", "and", "content_object", ".", "See", "EventRelation", "for", "help", "on", "distinction", "." ]
python
train
debrouwere/google-analytics
googleanalytics/query.py
https://github.com/debrouwere/google-analytics/blob/7d585c2f6f5ca191e975e6e3eaf7d5e2424fa11c/googleanalytics/query.py#L469-L484
def description(self): """ A list of the metrics this query will ask for. """ if 'metrics' in self.raw: metrics = self.raw['metrics'] head = metrics[0:-1] or metrics[0:1] text = ", ".join(head) if len(metrics) > 1: tail = m...
[ "def", "description", "(", "self", ")", ":", "if", "'metrics'", "in", "self", ".", "raw", ":", "metrics", "=", "self", ".", "raw", "[", "'metrics'", "]", "head", "=", "metrics", "[", "0", ":", "-", "1", "]", "or", "metrics", "[", "0", ":", "1", ...
A list of the metrics this query will ask for.
[ "A", "list", "of", "the", "metrics", "this", "query", "will", "ask", "for", "." ]
python
train
timothydmorton/isochrones
isochrones/starmodel_old.py
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L254-L325
def lnlike(self, p): """Log-likelihood of model at given parameters :param p: mass, log10(age), feh, [distance, A_V (extinction)]. Final two should only be provided if ``self.fit_for_distance`` is ``True``; that is, apparent magnitudes are provided. ...
[ "def", "lnlike", "(", "self", ",", "p", ")", ":", "if", "not", "self", ".", "_props_cleaned", ":", "self", ".", "_clean_props", "(", ")", "if", "not", "self", ".", "use_emcee", ":", "fit_for_distance", "=", "True", "mass", ",", "age", ",", "feh", ","...
Log-likelihood of model at given parameters :param p: mass, log10(age), feh, [distance, A_V (extinction)]. Final two should only be provided if ``self.fit_for_distance`` is ``True``; that is, apparent magnitudes are provided. :return: ...
[ "Log", "-", "likelihood", "of", "model", "at", "given", "parameters" ]
python
train
pkgw/pwkit
pwkit/synphot.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/synphot.py#L464-L471
def register_pivot_wavelength(self, telescope, band, wlen): """Register precomputed pivot wavelengths.""" if (telescope, band) in self._pivot_wavelengths: raise AlreadyDefinedError('pivot wavelength for %s/%s already ' 'defined', telescope, band) ...
[ "def", "register_pivot_wavelength", "(", "self", ",", "telescope", ",", "band", ",", "wlen", ")", ":", "if", "(", "telescope", ",", "band", ")", "in", "self", ".", "_pivot_wavelengths", ":", "raise", "AlreadyDefinedError", "(", "'pivot wavelength for %s/%s already...
Register precomputed pivot wavelengths.
[ "Register", "precomputed", "pivot", "wavelengths", "." ]
python
train
bwohlberg/sporco
sporco/admm/ccmod.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/ccmod.py#L288-L297
def uinit(self, ushape): """Return initialiser for working variable U""" if self.opt['Y0'] is None: return np.zeros(ushape, dtype=self.dtype) else: # If initial Y is non-zero, initial U is chosen so that # the relevant dual optimality criterion (see (3.10) in...
[ "def", "uinit", "(", "self", ",", "ushape", ")", ":", "if", "self", ".", "opt", "[", "'Y0'", "]", "is", "None", ":", "return", "np", ".", "zeros", "(", "ushape", ",", "dtype", "=", "self", ".", "dtype", ")", "else", ":", "# If initial Y is non-zero, ...
Return initialiser for working variable U
[ "Return", "initialiser", "for", "working", "variable", "U" ]
python
train
mopidy/mopidy-gmusic
mopidy_gmusic/translator.py
https://github.com/mopidy/mopidy-gmusic/blob/bbfe876d2a7e4f0f4f9308193bb988936bdfd5c3/mopidy_gmusic/translator.py#L24-L30
def artist_to_ref(artist): """Convert a mopidy artist to a mopidy ref.""" if artist.name: name = artist.name else: name = 'Unknown artist' return Ref.directory(uri=artist.uri, name=name)
[ "def", "artist_to_ref", "(", "artist", ")", ":", "if", "artist", ".", "name", ":", "name", "=", "artist", ".", "name", "else", ":", "name", "=", "'Unknown artist'", "return", "Ref", ".", "directory", "(", "uri", "=", "artist", ".", "uri", ",", "name", ...
Convert a mopidy artist to a mopidy ref.
[ "Convert", "a", "mopidy", "artist", "to", "a", "mopidy", "ref", "." ]
python
train
elliterate/capybara.py
capybara/window.py
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/window.py#L58-L63
def current(self): """ bool: Whether this window is the window in which commands are being executed. """ try: return self.driver.current_window_handle == self.handle except self.driver.no_such_window_error: return False
[ "def", "current", "(", "self", ")", ":", "try", ":", "return", "self", ".", "driver", ".", "current_window_handle", "==", "self", ".", "handle", "except", "self", ".", "driver", ".", "no_such_window_error", ":", "return", "False" ]
bool: Whether this window is the window in which commands are being executed.
[ "bool", ":", "Whether", "this", "window", "is", "the", "window", "in", "which", "commands", "are", "being", "executed", "." ]
python
test
scott-griffiths/bitstring
bitstring.py
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2161-L2164
def _set(self, pos): """Set bit at pos to 1.""" assert 0 <= pos < self.len self._datastore.setbit(pos)
[ "def", "_set", "(", "self", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<", "self", ".", "len", "self", ".", "_datastore", ".", "setbit", "(", "pos", ")" ]
Set bit at pos to 1.
[ "Set", "bit", "at", "pos", "to", "1", "." ]
python
train
hazelcast/hazelcast-python-client
hazelcast/proxy/queue.py
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L229-L241
def remove_all(self, items): """ Removes all of the elements of the specified collection from this queue. :param items: (Collection), the specified collection. :return: (bool), ``true`` if the call changed this queue, ``false`` otherwise. """ check_not_none(items, "Value...
[ "def", "remove_all", "(", "self", ",", "items", ")", ":", "check_not_none", "(", "items", ",", "\"Value can't be None\"", ")", "data_items", "=", "[", "]", "for", "item", "in", "items", ":", "check_not_none", "(", "item", ",", "\"Value can't be None\"", ")", ...
Removes all of the elements of the specified collection from this queue. :param items: (Collection), the specified collection. :return: (bool), ``true`` if the call changed this queue, ``false`` otherwise.
[ "Removes", "all", "of", "the", "elements", "of", "the", "specified", "collection", "from", "this", "queue", "." ]
python
train
noobermin/lspreader
lspreader/lspreader.py
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/lspreader.py#L65-L152
def get_header(file,**kw): '''gets the header for the .p4 file, note that this Advanced the file position to the end of the header. Returns the size of the header, and the size of the header, if the header keyword is true. ''' if type(file) == str: #if called with a file...
[ "def", "get_header", "(", "file", ",", "*", "*", "kw", ")", ":", "if", "type", "(", "file", ")", "==", "str", ":", "#if called with a filename, recall with opened file.", "if", "test", "(", "kw", ",", "\"gzip\"", ")", "and", "kw", "[", "'gzip'", "]", "==...
gets the header for the .p4 file, note that this Advanced the file position to the end of the header. Returns the size of the header, and the size of the header, if the header keyword is true.
[ "gets", "the", "header", "for", "the", ".", "p4", "file", "note", "that", "this", "Advanced", "the", "file", "position", "to", "the", "end", "of", "the", "header", ".", "Returns", "the", "size", "of", "the", "header", "and", "the", "size", "of", "the",...
python
train
alexhayes/django-toolkit
django_toolkit/email.py
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/email.py#L24-L37
def attach_related(self, filename=None, content=None, mimetype=None): """ Attaches a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass it is inserted directly into the...
[ "def", "attach_related", "(", "self", ",", "filename", "=", "None", ",", "content", "=", "None", ",", "mimetype", "=", "None", ")", ":", "if", "isinstance", "(", "filename", ",", "MIMEBase", ")", ":", "assert", "content", "==", "mimetype", "==", "None", ...
Attaches a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass it is inserted directly into the resulting message attachments.
[ "Attaches", "a", "file", "with", "the", "given", "filename", "and", "content", ".", "The", "filename", "can", "be", "omitted", "and", "the", "mimetype", "is", "guessed", "if", "not", "provided", "." ]
python
train
mdavidsaver/p4p
src/p4p/client/thread.py
https://github.com/mdavidsaver/p4p/blob/c5e45eac01edfdad9cc2857bc283c7f2695802b8/src/p4p/client/thread.py#L207-L218
def close(self): """Force close all Channels and cancel all Operations """ if self._Q is not None: for T in self._T: self._Q.interrupt() for n, T in enumerate(self._T): _log.debug('Join Context worker %d', n) T.join() ...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_Q", "is", "not", "None", ":", "for", "T", "in", "self", ".", "_T", ":", "self", ".", "_Q", ".", "interrupt", "(", ")", "for", "n", ",", "T", "in", "enumerate", "(", "self", ".", "_T"...
Force close all Channels and cancel all Operations
[ "Force", "close", "all", "Channels", "and", "cancel", "all", "Operations" ]
python
train
awslabs/aws-cfn-template-flip
cfn_clean/__init__.py
https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_clean/__init__.py#L96-L112
def clean(source): """ Clean up the source: * Replace use of Fn::Join with Fn::Sub """ if isinstance(source, dict): for key, value in source.items(): if key == "Fn::Join": return convert_join(value) else: source[key] = clean(value) ...
[ "def", "clean", "(", "source", ")", ":", "if", "isinstance", "(", "source", ",", "dict", ")", ":", "for", "key", ",", "value", "in", "source", ".", "items", "(", ")", ":", "if", "key", "==", "\"Fn::Join\"", ":", "return", "convert_join", "(", "value"...
Clean up the source: * Replace use of Fn::Join with Fn::Sub
[ "Clean", "up", "the", "source", ":", "*", "Replace", "use", "of", "Fn", "::", "Join", "with", "Fn", "::", "Sub" ]
python
train
chaoss/grimoirelab-perceval
perceval/backends/core/askbot.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/askbot.py#L393-L462
def parse_answers(html_question): """Parse the answers of a given HTML question. The method parses the answers related with a given HTML question, as well as all the comments related to the answer. :param html_question: raw HTML question element :returns: a list with the answe...
[ "def", "parse_answers", "(", "html_question", ")", ":", "def", "parse_answer_container", "(", "update_info", ")", ":", "\"\"\"Parse the answer info container of a given HTML question.\n\n The method parses the information available in the answer information\n container....
Parse the answers of a given HTML question. The method parses the answers related with a given HTML question, as well as all the comments related to the answer. :param html_question: raw HTML question element :returns: a list with the answers
[ "Parse", "the", "answers", "of", "a", "given", "HTML", "question", "." ]
python
test
mesowx/MesoPy
MesoPy.py
https://github.com/mesowx/MesoPy/blob/cd1e837e108ed7a110d81cf789f19afcdd52145b/MesoPy.py#L754-L827
def metadata(self, **kwargs): r""" Returns the metadata for a station or stations. Users must specify at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'gacc', or 'subgacc') to obtain observation data. Other parameters may als...
[ "def", "metadata", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_geo_param", "(", "kwargs", ")", "kwargs", "[", "'token'", "]", "=", "self", ".", "token", "return", "self", ".", "_get_response", "(", "'stations/metadata'", ",", "kw...
r""" Returns the metadata for a station or stations. Users must specify at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'gacc', or 'subgacc') to obtain observation data. Other parameters may also be included. See below for optional ...
[ "r", "Returns", "the", "metadata", "for", "a", "station", "or", "stations", ".", "Users", "must", "specify", "at", "least", "one", "geographic", "search", "parameter", "(", "stid", "state", "country", "county", "radius", "bbox", "cwa", "nwsfirezone", "gacc", ...
python
train
digidotcom/python-devicecloud
devicecloud/streams.py
https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/streams.py#L799-L824
def delete_datapoints_in_time_range(self, start_dt=None, end_dt=None): """Delete datapoints from this stream between the provided start and end times If neither a start or end time is specified, all data points in the stream will be deleted. :param start_dt: The datetime after which da...
[ "def", "delete_datapoints_in_time_range", "(", "self", ",", "start_dt", "=", "None", ",", "end_dt", "=", "None", ")", ":", "start_dt", "=", "to_none_or_dt", "(", "validate_type", "(", "start_dt", ",", "datetime", ".", "datetime", ",", "type", "(", "None", ")...
Delete datapoints from this stream between the provided start and end times If neither a start or end time is specified, all data points in the stream will be deleted. :param start_dt: The datetime after which data points should be deleted or None if all data points from the beginn...
[ "Delete", "datapoints", "from", "this", "stream", "between", "the", "provided", "start", "and", "end", "times" ]
python
train
django-fluent/django-fluent-blogs
fluent_blogs/models/query.py
https://github.com/django-fluent/django-fluent-blogs/blob/86b148549a010eaca9a2ea987fe43be250e06c50/fluent_blogs/models/query.py#L187-L195
def get_category_for_slug(slug, language_code=None): """ Find the category for a given slug """ Category = get_category_model() if issubclass(Category, TranslatableModel): return Category.objects.active_translations(language_code, slug=slug).get() else: return Category.objects.ge...
[ "def", "get_category_for_slug", "(", "slug", ",", "language_code", "=", "None", ")", ":", "Category", "=", "get_category_model", "(", ")", "if", "issubclass", "(", "Category", ",", "TranslatableModel", ")", ":", "return", "Category", ".", "objects", ".", "acti...
Find the category for a given slug
[ "Find", "the", "category", "for", "a", "given", "slug" ]
python
train
saltstack/salt
salt/modules/iosconfig.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iosconfig.py#L308-L355
def merge_diff(initial_config=None, initial_path=None, merge_config=None, merge_path=None, saltenv='base'): ''' Return the merge diff, as text, after merging the merge config into the initial config. initial_config The initial configur...
[ "def", "merge_diff", "(", "initial_config", "=", "None", ",", "initial_path", "=", "None", ",", "merge_config", "=", "None", ",", "merge_path", "=", "None", ",", "saltenv", "=", "'base'", ")", ":", "if", "initial_path", ":", "initial_config", "=", "__salt__"...
Return the merge diff, as text, after merging the merge config into the initial config. initial_config The initial configuration sent as text. This argument is ignored when ``initial_path`` is set. initial_path Absolute or remote path from where to load the initial configuration ...
[ "Return", "the", "merge", "diff", "as", "text", "after", "merging", "the", "merge", "config", "into", "the", "initial", "config", "." ]
python
train
clinicedc/edc-notification
edc_notification/site_notifications.py
https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/site_notifications.py#L47-L56
def get(self, name): """Returns a Notification by name. """ if not self.loaded: raise RegistryNotLoaded(self) if not self._registry.get(name): raise NotificationNotRegistered( f"Notification not registered. Got '{name}'." ) retu...
[ "def", "get", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "loaded", ":", "raise", "RegistryNotLoaded", "(", "self", ")", "if", "not", "self", ".", "_registry", ".", "get", "(", "name", ")", ":", "raise", "NotificationNotRegistered", "...
Returns a Notification by name.
[ "Returns", "a", "Notification", "by", "name", "." ]
python
train
kensho-technologies/graphql-compiler
graphql_compiler/compiler/compiler_frontend.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/compiler_frontend.py#L741-L863
def _compile_root_ast_to_ir(schema, ast, type_equivalence_hints=None): """Compile a full GraphQL abstract syntax tree (AST) to intermediate representation. Args: schema: GraphQL schema object, obtained from the graphql library ast: the root GraphQL AST node for the query, obtained from the grap...
[ "def", "_compile_root_ast_to_ir", "(", "schema", ",", "ast", ",", "type_equivalence_hints", "=", "None", ")", ":", "if", "len", "(", "ast", ".", "selection_set", ".", "selections", ")", "!=", "1", ":", "raise", "GraphQLCompilationError", "(", "u'Cannot process A...
Compile a full GraphQL abstract syntax tree (AST) to intermediate representation. Args: schema: GraphQL schema object, obtained from the graphql library ast: the root GraphQL AST node for the query, obtained from the graphql library, and already validated against the schema for type-co...
[ "Compile", "a", "full", "GraphQL", "abstract", "syntax", "tree", "(", "AST", ")", "to", "intermediate", "representation", "." ]
python
train
aiven/pghoard
pghoard/restore.py
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/restore.py#L201-L238
def get_basebackup(self, arg): """Download a basebackup from an object store""" if not arg.tablespace_dir: tablespace_mapping = {} else: try: tablespace_mapping = dict(v.split("=", 1) for v in arg.tablespace_dir) except ValueError: ...
[ "def", "get_basebackup", "(", "self", ",", "arg", ")", ":", "if", "not", "arg", ".", "tablespace_dir", ":", "tablespace_mapping", "=", "{", "}", "else", ":", "try", ":", "tablespace_mapping", "=", "dict", "(", "v", ".", "split", "(", "\"=\"", ",", "1",...
Download a basebackup from an object store
[ "Download", "a", "basebackup", "from", "an", "object", "store" ]
python
train