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
ioos/pyoos
pyoos/collectors/ioos/swe_sos.py
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/ioos/swe_sos.py#L50-L87
def metadata_plus_exceptions( self, output_format=None, feature_name_callback=None, **kwargs ): """ Gets SensorML objects for all procedures in your filtered features. Return two dictionaries for service responses keyed by 'feature': responses: values are SOS DescribeSen...
[ "def", "metadata_plus_exceptions", "(", "self", ",", "output_format", "=", "None", ",", "feature_name_callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "feature_name_callback", "or", "str", "if", "output_format", "is", "None", ":", "o...
Gets SensorML objects for all procedures in your filtered features. Return two dictionaries for service responses keyed by 'feature': responses: values are SOS DescribeSensor response text response_failures: values are exception text content furnished from ServiceException, ExceptionRep...
[ "Gets", "SensorML", "objects", "for", "all", "procedures", "in", "your", "filtered", "features", "." ]
python
train
woolfson-group/isambard
isambard/ampal/protein.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/protein.py#L1289-L1324
def side_chain(self): """List of the side-chain atoms (R-group). Notes ----- Returns empty list for glycine. Returns ------- side_chain_atoms: list(`Atoms`) """ side_chain_atoms = [] if self.mol_code != 'GLY': covalent_bond_gr...
[ "def", "side_chain", "(", "self", ")", ":", "side_chain_atoms", "=", "[", "]", "if", "self", ".", "mol_code", "!=", "'GLY'", ":", "covalent_bond_graph", "=", "generate_covalent_bond_graph", "(", "find_covalent_bonds", "(", "self", ")", ")", "try", ":", "subgra...
List of the side-chain atoms (R-group). Notes ----- Returns empty list for glycine. Returns ------- side_chain_atoms: list(`Atoms`)
[ "List", "of", "the", "side", "-", "chain", "atoms", "(", "R", "-", "group", ")", "." ]
python
train
aestrivex/bctpy
bct/utils/other.py
https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/utils/other.py#L6-L33
def threshold_absolute(W, thr, copy=True): ''' This function thresholds the connectivity matrix by absolute weight magnitude. All weights below the given threshold, and all weights on the main diagonal (self-self connections) are set to 0. If copy is not set, this function will *modify W in place.*...
[ "def", "threshold_absolute", "(", "W", ",", "thr", ",", "copy", "=", "True", ")", ":", "if", "copy", ":", "W", "=", "W", ".", "copy", "(", ")", "np", ".", "fill_diagonal", "(", "W", ",", "0", ")", "# clear diagonal", "W", "[", "W", "<", "thr", ...
This function thresholds the connectivity matrix by absolute weight magnitude. All weights below the given threshold, and all weights on the main diagonal (self-self connections) are set to 0. If copy is not set, this function will *modify W in place.* Parameters ---------- W : np.ndarray ...
[ "This", "function", "thresholds", "the", "connectivity", "matrix", "by", "absolute", "weight", "magnitude", ".", "All", "weights", "below", "the", "given", "threshold", "and", "all", "weights", "on", "the", "main", "diagonal", "(", "self", "-", "self", "connec...
python
train
kwikteam/phy
phy/plot/panzoom.py
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/panzoom.py#L198-L210
def _constrain_pan(self): """Constrain bounding box.""" if self.xmin is not None and self.xmax is not None: p0 = self.xmin + 1. / self._zoom[0] p1 = self.xmax - 1. / self._zoom[0] p0, p1 = min(p0, p1), max(p0, p1) self._pan[0] = np.clip(self._pan[0], p0, p...
[ "def", "_constrain_pan", "(", "self", ")", ":", "if", "self", ".", "xmin", "is", "not", "None", "and", "self", ".", "xmax", "is", "not", "None", ":", "p0", "=", "self", ".", "xmin", "+", "1.", "/", "self", ".", "_zoom", "[", "0", "]", "p1", "="...
Constrain bounding box.
[ "Constrain", "bounding", "box", "." ]
python
train
limix/limix-core
limix_core/mean/linear.py
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/linear.py#L219-L251
def removeFixedEffect(self, index=None): """ set sample and trait designs F: NxK sample design A: LxP sample design REML: REML for this term? index: index of which fixed effect to replace. If None, remove last term. """ if self._n_terms==0: ...
[ "def", "removeFixedEffect", "(", "self", ",", "index", "=", "None", ")", ":", "if", "self", ".", "_n_terms", "==", "0", ":", "pass", "if", "index", "is", "None", "or", "index", "==", "(", "self", ".", "_n_terms", "-", "1", ")", ":", "self", ".", ...
set sample and trait designs F: NxK sample design A: LxP sample design REML: REML for this term? index: index of which fixed effect to replace. If None, remove last term.
[ "set", "sample", "and", "trait", "designs", "F", ":", "NxK", "sample", "design", "A", ":", "LxP", "sample", "design", "REML", ":", "REML", "for", "this", "term?", "index", ":", "index", "of", "which", "fixed", "effect", "to", "replace", ".", "If", "Non...
python
train
ScatterHQ/machinist
machinist/_fsm.py
https://github.com/ScatterHQ/machinist/blob/1d1c017ac03be8e737d50af0dfabf31722ddc621/machinist/_fsm.py#L193-L209
def addTransitions(self, state, transitions): """ Create a new L{TransitionTable} with all the same transitions as this L{TransitionTable} plus a number of new transitions. @param state: The state for which the new transitions are defined. @param transitions: A L{dict} mapping i...
[ "def", "addTransitions", "(", "self", ",", "state", ",", "transitions", ")", ":", "table", "=", "self", ".", "_copy", "(", ")", "state", "=", "table", ".", "table", ".", "setdefault", "(", "state", ",", "{", "}", ")", "for", "(", "input", ",", "(",...
Create a new L{TransitionTable} with all the same transitions as this L{TransitionTable} plus a number of new transitions. @param state: The state for which the new transitions are defined. @param transitions: A L{dict} mapping inputs to output, nextState pairs. Each item from this...
[ "Create", "a", "new", "L", "{", "TransitionTable", "}", "with", "all", "the", "same", "transitions", "as", "this", "L", "{", "TransitionTable", "}", "plus", "a", "number", "of", "new", "transitions", "." ]
python
train
dropbox/stone
stone/backends/obj_c_types.py
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/backends/obj_c_types.py#L582-L599
def _generate_union_cstor_funcs(self, union): """Emits standard union constructor.""" for field in union.all_fields: enum_field_name = fmt_enum_name(field.name, union) func_args = [] if is_void_type( field.data_type) else fmt_func_args_from_fields([field]) ...
[ "def", "_generate_union_cstor_funcs", "(", "self", ",", "union", ")", ":", "for", "field", "in", "union", ".", "all_fields", ":", "enum_field_name", "=", "fmt_enum_name", "(", "field", ".", "name", ",", "union", ")", "func_args", "=", "[", "]", "if", "is_v...
Emits standard union constructor.
[ "Emits", "standard", "union", "constructor", "." ]
python
train
regardscitoyens/anpy
anpy/dossier_like_senapy.py
https://github.com/regardscitoyens/anpy/blob/72eff17c992e054edade7bc16eda1eca96e69225/anpy/dossier_like_senapy.py#L21-L27
def find_promulgation_date(line): """ >>> find_promulgation_date("Loi nº 2010-383 du 16 avril 2010 autorisant l'approbation de l'accord entre...") '2010-04-16' """ line = line.split(' du ')[1] return format_date(re.search(r"(\d\d? \w\w\w+ \d\d\d\d)", line).group(1))
[ "def", "find_promulgation_date", "(", "line", ")", ":", "line", "=", "line", ".", "split", "(", "' du '", ")", "[", "1", "]", "return", "format_date", "(", "re", ".", "search", "(", "r\"(\\d\\d? \\w\\w\\w+ \\d\\d\\d\\d)\"", ",", "line", ")", ".", "group", ...
>>> find_promulgation_date("Loi nº 2010-383 du 16 avril 2010 autorisant l'approbation de l'accord entre...") '2010-04-16'
[ ">>>", "find_promulgation_date", "(", "Loi", "nº", "2010", "-", "383", "du", "16", "avril", "2010", "autorisant", "l", "approbation", "de", "l", "accord", "entre", "...", ")", "2010", "-", "04", "-", "16" ]
python
train
baverman/covador
covador/types.py
https://github.com/baverman/covador/blob/1597759f7ba77004efef1b27bf804539663b5488/covador/types.py#L693-L697
def pipe(p1, p2): """Joins two pipes""" if isinstance(p1, Pipeable) or isinstance(p2, Pipeable): return p1 | p2 return Pipe([p1, p2])
[ "def", "pipe", "(", "p1", ",", "p2", ")", ":", "if", "isinstance", "(", "p1", ",", "Pipeable", ")", "or", "isinstance", "(", "p2", ",", "Pipeable", ")", ":", "return", "p1", "|", "p2", "return", "Pipe", "(", "[", "p1", ",", "p2", "]", ")" ]
Joins two pipes
[ "Joins", "two", "pipes" ]
python
train
daler/metaseq
metaseq/minibrowser.py
https://github.com/daler/metaseq/blob/fa875d1f72317aa7ef95cb128b739956b16eef9f/metaseq/minibrowser.py#L101-L106
def make_fig(self): """ Figure constructor, called before `self.plot()` """ self.fig = plt.figure(figsize=(8, 4)) self._all_figures.append(self.fig)
[ "def", "make_fig", "(", "self", ")", ":", "self", ".", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "8", ",", "4", ")", ")", "self", ".", "_all_figures", ".", "append", "(", "self", ".", "fig", ")" ]
Figure constructor, called before `self.plot()`
[ "Figure", "constructor", "called", "before", "self", ".", "plot", "()" ]
python
train
evhub/coconut
coconut/compiler/matching.py
https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/matching.py#L580-L596
def match_trailer(self, tokens, item): """Matches typedefs and as patterns.""" internal_assert(len(tokens) > 1 and len(tokens) % 2 == 1, "invalid trailer match tokens", tokens) match, trailers = tokens[0], tokens[1:] for i in range(0, len(trailers), 2): op, arg = trailers[i],...
[ "def", "match_trailer", "(", "self", ",", "tokens", ",", "item", ")", ":", "internal_assert", "(", "len", "(", "tokens", ")", ">", "1", "and", "len", "(", "tokens", ")", "%", "2", "==", "1", ",", "\"invalid trailer match tokens\"", ",", "tokens", ")", ...
Matches typedefs and as patterns.
[ "Matches", "typedefs", "and", "as", "patterns", "." ]
python
train
facelessuser/backrefs
backrefs/uniprops/__init__.py
https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/backrefs/uniprops/__init__.py#L154-L165
def get_hangul_syllable_type_property(value, is_bytes=False): """Get `HANGUL SYLLABLE TYPE` property.""" obj = unidata.ascii_hangul_syllable_type if is_bytes else unidata.unicode_hangul_syllable_type if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['hanguls...
[ "def", "get_hangul_syllable_type_property", "(", "value", ",", "is_bytes", "=", "False", ")", ":", "obj", "=", "unidata", ".", "ascii_hangul_syllable_type", "if", "is_bytes", "else", "unidata", ".", "unicode_hangul_syllable_type", "if", "value", ".", "startswith", "...
Get `HANGUL SYLLABLE TYPE` property.
[ "Get", "HANGUL", "SYLLABLE", "TYPE", "property", "." ]
python
train
Dirguis/ipfn
ipfn/ipfn.py
https://github.com/Dirguis/ipfn/blob/0a896ea395664515c5a424b69043937aad1d5567/ipfn/ipfn.py#L60-L134
def ipfn_np(self, m, aggregates, dimensions, weight_col='total'): """ Runs the ipfn method from a matrix m, aggregates/marginals and the dimension(s) preserved. For example: from ipfn import ipfn import numpy as np m = np.array([[8., 4., 6., 7.], [3., 6., 5., 2.], [9., 11...
[ "def", "ipfn_np", "(", "self", ",", "m", ",", "aggregates", ",", "dimensions", ",", "weight_col", "=", "'total'", ")", ":", "steps", "=", "len", "(", "aggregates", ")", "dim", "=", "len", "(", "m", ".", "shape", ")", "product_elem", "=", "[", "]", ...
Runs the ipfn method from a matrix m, aggregates/marginals and the dimension(s) preserved. For example: from ipfn import ipfn import numpy as np m = np.array([[8., 4., 6., 7.], [3., 6., 5., 2.], [9., 11., 3., 1.]], ) xip = np.array([20., 18., 22.]) xpj = np.array([18., 16...
[ "Runs", "the", "ipfn", "method", "from", "a", "matrix", "m", "aggregates", "/", "marginals", "and", "the", "dimension", "(", "s", ")", "preserved", ".", "For", "example", ":", "from", "ipfn", "import", "ipfn", "import", "numpy", "as", "np", "m", "=", "...
python
valid
kronenthaler/mod-pbxproj
pbxproj/pbxextensions/ProjectFiles.py
https://github.com/kronenthaler/mod-pbxproj/blob/8de3cbdd3210480ddbb1fa0f50a4f4ea87de6e71/pbxproj/pbxextensions/ProjectFiles.py#L266-L278
def get_files_by_path(self, path, tree=TreeType.SOURCE_ROOT): """ Gets the files under the given tree type that match the given path. :param path: Path to the file relative to the tree root :param tree: Tree type to look for the path. By default the SOURCE_ROOT :return: List of a...
[ "def", "get_files_by_path", "(", "self", ",", "path", ",", "tree", "=", "TreeType", ".", "SOURCE_ROOT", ")", ":", "files", "=", "[", "]", "for", "file_ref", "in", "self", ".", "objects", ".", "get_objects_in_section", "(", "u'PBXFileReference'", ")", ":", ...
Gets the files under the given tree type that match the given path. :param path: Path to the file relative to the tree root :param tree: Tree type to look for the path. By default the SOURCE_ROOT :return: List of all PBXFileReference that match the path and tree criteria.
[ "Gets", "the", "files", "under", "the", "given", "tree", "type", "that", "match", "the", "given", "path", ".", ":", "param", "path", ":", "Path", "to", "the", "file", "relative", "to", "the", "tree", "root", ":", "param", "tree", ":", "Tree", "type", ...
python
train
PyCQA/astroid
astroid/brain/brain_attrs.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_attrs.py#L18-L28
def is_decorated_with_attrs(node, decorator_names=ATTRS_NAMES): """Return True if a decorated node has an attr decorator applied.""" if not node.decorators: return False for decorator_attribute in node.decorators.nodes: if isinstance(decorator_attribute, astroid.Call): # decorator with ...
[ "def", "is_decorated_with_attrs", "(", "node", ",", "decorator_names", "=", "ATTRS_NAMES", ")", ":", "if", "not", "node", ".", "decorators", ":", "return", "False", "for", "decorator_attribute", "in", "node", ".", "decorators", ".", "nodes", ":", "if", "isinst...
Return True if a decorated node has an attr decorator applied.
[ "Return", "True", "if", "a", "decorated", "node", "has", "an", "attr", "decorator", "applied", "." ]
python
train
LCAV/pylocus
pylocus/algorithms.py
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L146-L167
def reconstruct_cdm(dm, absolute_angles, all_points, W=None): """ Reconstruct point set from angle and distance measurements, using coordinate difference matrices. """ from pylocus.point_set import dmi_from_V, sdm_from_dmi, get_V from pylocus.mds import signedMDS N = all_points.shape[0] V = ge...
[ "def", "reconstruct_cdm", "(", "dm", ",", "absolute_angles", ",", "all_points", ",", "W", "=", "None", ")", ":", "from", "pylocus", ".", "point_set", "import", "dmi_from_V", ",", "sdm_from_dmi", ",", "get_V", "from", "pylocus", ".", "mds", "import", "signedM...
Reconstruct point set from angle and distance measurements, using coordinate difference matrices.
[ "Reconstruct", "point", "set", "from", "angle", "and", "distance", "measurements", "using", "coordinate", "difference", "matrices", "." ]
python
train
numenta/nupic
src/nupic/engine/__init__.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/engine/__init__.py#L449-L454
def getInputNames(self): """ Returns list of input names in spec. """ inputs = self.getSpec().inputs return [inputs.getByIndex(i)[0] for i in xrange(inputs.getCount())]
[ "def", "getInputNames", "(", "self", ")", ":", "inputs", "=", "self", ".", "getSpec", "(", ")", ".", "inputs", "return", "[", "inputs", ".", "getByIndex", "(", "i", ")", "[", "0", "]", "for", "i", "in", "xrange", "(", "inputs", ".", "getCount", "("...
Returns list of input names in spec.
[ "Returns", "list", "of", "input", "names", "in", "spec", "." ]
python
valid
PGower/PyCanvas
pycanvas/apis/feature_flags.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/feature_flags.py#L340-L362
def remove_feature_flag_users(self, user_id, feature): """ Remove feature flag. Remove feature flag for a given Account, Course, or User. (Note that the flag must be defined on the Account, Course, or User directly.) The object will then inherit the feature flags from a ...
[ "def", "remove_feature_flag_users", "(", "self", ",", "user_id", ",", "feature", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"user_id\"", "]", "=", "user_i...
Remove feature flag. Remove feature flag for a given Account, Course, or User. (Note that the flag must be defined on the Account, Course, or User directly.) The object will then inherit the feature flags from a higher account, if any exist. If this flag was 'on' or 'off', then ...
[ "Remove", "feature", "flag", ".", "Remove", "feature", "flag", "for", "a", "given", "Account", "Course", "or", "User", ".", "(", "Note", "that", "the", "flag", "must", "be", "defined", "on", "the", "Account", "Course", "or", "User", "directly", ".", ")",...
python
train
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L384-L391
def get_cmd_output_from_stdin(stdint_content_binary: bytes, *args, encoding: str = SYS_ENCODING) -> str: """ Returns text output of a command, passing binary data in via stdin. """ p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr ...
[ "def", "get_cmd_output_from_stdin", "(", "stdint_content_binary", ":", "bytes", ",", "*", "args", ",", "encoding", ":", "str", "=", "SYS_ENCODING", ")", "->", "str", ":", "p", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdin", "=", "subprocess", "...
Returns text output of a command, passing binary data in via stdin.
[ "Returns", "text", "output", "of", "a", "command", "passing", "binary", "data", "in", "via", "stdin", "." ]
python
train
jbittel/django-mama-cas
mama_cas/models.py
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/models.py#L207-L218
def request_sign_out(self, user): """ Send a single logout request to each service accessed by a specified user. This is called at logout when single logout is enabled. If requests-futures is installed, asynchronous requests will be sent. Otherwise, synchronous requests ...
[ "def", "request_sign_out", "(", "self", ",", "user", ")", ":", "session", "=", "Session", "(", ")", "for", "ticket", "in", "self", ".", "filter", "(", "user", "=", "user", ",", "consumed__gte", "=", "user", ".", "last_login", ")", ":", "ticket", ".", ...
Send a single logout request to each service accessed by a specified user. This is called at logout when single logout is enabled. If requests-futures is installed, asynchronous requests will be sent. Otherwise, synchronous requests will be sent.
[ "Send", "a", "single", "logout", "request", "to", "each", "service", "accessed", "by", "a", "specified", "user", ".", "This", "is", "called", "at", "logout", "when", "single", "logout", "is", "enabled", "." ]
python
train
JukeboxPipeline/jukebox-core
src/jukeboxcore/launcher.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/launcher.py#L185-L198
def compile_ui(self, namespace, unknown): """Compile qt designer files :param namespace: namespace containing arguments from the launch parser :type namespace: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None ...
[ "def", "compile_ui", "(", "self", ",", "namespace", ",", "unknown", ")", ":", "uifiles", "=", "namespace", ".", "uifile", "for", "f", "in", "uifiles", ":", "qtcompile", ".", "compile_ui", "(", "f", ".", "name", ")" ]
Compile qt designer files :param namespace: namespace containing arguments from the launch parser :type namespace: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None :raises: None
[ "Compile", "qt", "designer", "files" ]
python
train
googleapis/google-cloud-python
bigquery/samples/get_model.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/samples/get_model.py#L16-L34
def get_model(client, model_id): """Sample ID: go/samples-tracker/1510""" # [START bigquery_get_model] from google.cloud import bigquery # TODO(developer): Construct a BigQuery client object. # client = bigquery.Client() # TODO(developer): Set model_id to the ID of the model to fetch. # m...
[ "def", "get_model", "(", "client", ",", "model_id", ")", ":", "# [START bigquery_get_model]", "from", "google", ".", "cloud", "import", "bigquery", "# TODO(developer): Construct a BigQuery client object.", "# client = bigquery.Client()", "# TODO(developer): Set model_id to the ID o...
Sample ID: go/samples-tracker/1510
[ "Sample", "ID", ":", "go", "/", "samples", "-", "tracker", "/", "1510" ]
python
train
praekeltfoundation/seed-control-interface-service
services/tasks.py
https://github.com/praekeltfoundation/seed-control-interface-service/blob/0c8ec58ae61e72d4443e6c9a4d8b7dd12dd8a86e/services/tasks.py#L81-L88
def run(self): """ Queues all services to be polled. Should be run via beat. """ services = Service.objects.all() for service in services: poll_service.apply_async(kwargs={"service_id": str(service.id)}) return "Queued <%s> Service(s) for Polling" % services.c...
[ "def", "run", "(", "self", ")", ":", "services", "=", "Service", ".", "objects", ".", "all", "(", ")", "for", "service", "in", "services", ":", "poll_service", ".", "apply_async", "(", "kwargs", "=", "{", "\"service_id\"", ":", "str", "(", "service", "...
Queues all services to be polled. Should be run via beat.
[ "Queues", "all", "services", "to", "be", "polled", ".", "Should", "be", "run", "via", "beat", "." ]
python
train
tBaxter/tango-happenings
build/lib/happenings/models.py
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L238-L249
def get_top_assets(self): """ Gets images and videos to populate top assets. Map is built separately. """ images = self.get_all_images()[0:14] video = [] if supports_video: video = self.eventvideo_set.all()[0:10] return list(chain(images, vid...
[ "def", "get_top_assets", "(", "self", ")", ":", "images", "=", "self", ".", "get_all_images", "(", ")", "[", "0", ":", "14", "]", "video", "=", "[", "]", "if", "supports_video", ":", "video", "=", "self", ".", "eventvideo_set", ".", "all", "(", ")", ...
Gets images and videos to populate top assets. Map is built separately.
[ "Gets", "images", "and", "videos", "to", "populate", "top", "assets", "." ]
python
valid
tuomas2/automate
src/automate/statusobject.py
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/statusobject.py#L223-L236
def get_status_display(self, **kwargs): """ Define how status is displayed in UIs (add units etc.). """ if 'value' in kwargs: value = kwargs['value'] else: value = self.status if self.show_stdev_seconds: stdev = self.stdev(self.sho...
[ "def", "get_status_display", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'value'", "in", "kwargs", ":", "value", "=", "kwargs", "[", "'value'", "]", "else", ":", "value", "=", "self", ".", "status", "if", "self", ".", "show_stdev_seconds", "...
Define how status is displayed in UIs (add units etc.).
[ "Define", "how", "status", "is", "displayed", "in", "UIs", "(", "add", "units", "etc", ".", ")", "." ]
python
train
newville/wxmplot
examples/floatcontrol.py
https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/floatcontrol.py#L14-L25
def set_float(val): """ utility to set a floating value, useful for converting from strings """ out = None if not val in (None, ''): try: out = float(val) except ValueError: return None if numpy.isnan(out): out = default return out
[ "def", "set_float", "(", "val", ")", ":", "out", "=", "None", "if", "not", "val", "in", "(", "None", ",", "''", ")", ":", "try", ":", "out", "=", "float", "(", "val", ")", "except", "ValueError", ":", "return", "None", "if", "numpy", ".", "isnan"...
utility to set a floating value, useful for converting from strings
[ "utility", "to", "set", "a", "floating", "value", "useful", "for", "converting", "from", "strings" ]
python
train
gwpy/gwpy
gwpy/types/series.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/types/series.py#L864-L871
def update(self, other, inplace=True): """Update this series by appending new data from an other and dropping the same amount of data off the start. This is a convenience method that just calls `~Series.append` with `resize=False`. """ return self.append(other, inplace=i...
[ "def", "update", "(", "self", ",", "other", ",", "inplace", "=", "True", ")", ":", "return", "self", ".", "append", "(", "other", ",", "inplace", "=", "inplace", ",", "resize", "=", "False", ")" ]
Update this series by appending new data from an other and dropping the same amount of data off the start. This is a convenience method that just calls `~Series.append` with `resize=False`.
[ "Update", "this", "series", "by", "appending", "new", "data", "from", "an", "other", "and", "dropping", "the", "same", "amount", "of", "data", "off", "the", "start", "." ]
python
train
CiscoDevNet/webexteamssdk
webexteamssdk/utils.py
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L89-L97
def validate_base_url(base_url): """Verify that base_url specifies a protocol and network location.""" parsed_url = urllib.parse.urlparse(base_url) if parsed_url.scheme and parsed_url.netloc: return parsed_url.geturl() else: error_message = "base_url must contain a valid scheme (protocol...
[ "def", "validate_base_url", "(", "base_url", ")", ":", "parsed_url", "=", "urllib", ".", "parse", ".", "urlparse", "(", "base_url", ")", "if", "parsed_url", ".", "scheme", "and", "parsed_url", ".", "netloc", ":", "return", "parsed_url", ".", "geturl", "(", ...
Verify that base_url specifies a protocol and network location.
[ "Verify", "that", "base_url", "specifies", "a", "protocol", "and", "network", "location", "." ]
python
test
improbable-research/keanu
keanu-python/keanu/vertex/generated.py
https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/keanu-python/keanu/vertex/generated.py#L585-L591
def Exponential(rate: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ One to one constructor for mapping some shape of rate to matching shaped exponential. :param rate: the rate of the Exponential with either the same shape as specified for this vertex or scalar """ re...
[ "def", "Exponential", "(", "rate", ":", "vertex_constructor_param_types", ",", "label", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Vertex", ":", "return", "Double", "(", "context", ".", "jvm_view", "(", ")", ".", "ExponentialVertex", ",", "...
One to one constructor for mapping some shape of rate to matching shaped exponential. :param rate: the rate of the Exponential with either the same shape as specified for this vertex or scalar
[ "One", "to", "one", "constructor", "for", "mapping", "some", "shape", "of", "rate", "to", "matching", "shaped", "exponential", ".", ":", "param", "rate", ":", "the", "rate", "of", "the", "Exponential", "with", "either", "the", "same", "shape", "as", "speci...
python
train
O365/python-o365
O365/message.py
https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/message.py#L801-L878
def save_draft(self, target_folder=OutlookWellKnowFolderNames.DRAFTS): """ Save this message as a draft on the cloud :param target_folder: name of the drafts folder :return: Success / Failure :rtype: bool """ if self.object_id: # update message. Attachments ...
[ "def", "save_draft", "(", "self", ",", "target_folder", "=", "OutlookWellKnowFolderNames", ".", "DRAFTS", ")", ":", "if", "self", ".", "object_id", ":", "# update message. Attachments are NOT included nor saved.", "if", "not", "self", ".", "__is_draft", ":", "raise", ...
Save this message as a draft on the cloud :param target_folder: name of the drafts folder :return: Success / Failure :rtype: bool
[ "Save", "this", "message", "as", "a", "draft", "on", "the", "cloud" ]
python
train
wilson-eft/wilson
wilson/translate/wet.py
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/translate/wet.py#L1352-L1368
def Fierz_to_Bern_chrom(C, dd, parameters): """From Fierz to chromomagnetic Bern basis for Class V. dd should be of the form 'sb', 'ds' etc.""" e = sqrt(4 * pi * parameters['alpha_e']) gs = sqrt(4 * pi * parameters['alpha_s']) if dd == 'sb' or dd == 'db': mq = parameters['m_b'] elif dd =...
[ "def", "Fierz_to_Bern_chrom", "(", "C", ",", "dd", ",", "parameters", ")", ":", "e", "=", "sqrt", "(", "4", "*", "pi", "*", "parameters", "[", "'alpha_e'", "]", ")", "gs", "=", "sqrt", "(", "4", "*", "pi", "*", "parameters", "[", "'alpha_s'", "]", ...
From Fierz to chromomagnetic Bern basis for Class V. dd should be of the form 'sb', 'ds' etc.
[ "From", "Fierz", "to", "chromomagnetic", "Bern", "basis", "for", "Class", "V", ".", "dd", "should", "be", "of", "the", "form", "sb", "ds", "etc", "." ]
python
train
wummel/linkchecker
third_party/dnspython/dns/rdata.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/rdata.py#L184-L190
def validate(self): """Check that the current contents of the rdata's fields are valid. If you change an rdata by assigning to its fields, it is a good idea to call validate() when you are done making changes. """ dns.rdata.from_text(self.rdclass, self.rdtype, self.to_te...
[ "def", "validate", "(", "self", ")", ":", "dns", ".", "rdata", ".", "from_text", "(", "self", ".", "rdclass", ",", "self", ".", "rdtype", ",", "self", ".", "to_text", "(", ")", ")" ]
Check that the current contents of the rdata's fields are valid. If you change an rdata by assigning to its fields, it is a good idea to call validate() when you are done making changes.
[ "Check", "that", "the", "current", "contents", "of", "the", "rdata", "s", "fields", "are", "valid", ".", "If", "you", "change", "an", "rdata", "by", "assigning", "to", "its", "fields", "it", "is", "a", "good", "idea", "to", "call", "validate", "()", "w...
python
train
toastdriven/alligator
alligator/backends/beanstalk_backend.py
https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/backends/beanstalk_backend.py#L34-L53
def len(self, queue_name): """ Returns the length of the queue. :param queue_name: The name of the queue. Usually handled by the ``Gator`` instance. :type queue_name: string :returns: The length of the queue :rtype: integer """ try: ...
[ "def", "len", "(", "self", ",", "queue_name", ")", ":", "try", ":", "stats", "=", "self", ".", "conn", ".", "stats_tube", "(", "queue_name", ")", "except", "beanstalkc", ".", "CommandFailed", "as", "err", ":", "if", "err", "[", "1", "]", "==", "'NOT_...
Returns the length of the queue. :param queue_name: The name of the queue. Usually handled by the ``Gator`` instance. :type queue_name: string :returns: The length of the queue :rtype: integer
[ "Returns", "the", "length", "of", "the", "queue", "." ]
python
train
teddychoi/BynamoDB
bynamodb/model.py
https://github.com/teddychoi/BynamoDB/blob/9b143d0554c89fb8edbfb99db5542e48bd126b39/bynamodb/model.py#L167-L205
def update_item(cls, hash_key, range_key=None, attributes_to_set=None, attributes_to_add=None): """Update item attributes. Currently SET and ADD actions are supported.""" primary_key = cls._encode_key(hash_key, range_key) value_names = {} encoded_values = {} dynamizer = Dynamize...
[ "def", "update_item", "(", "cls", ",", "hash_key", ",", "range_key", "=", "None", ",", "attributes_to_set", "=", "None", ",", "attributes_to_add", "=", "None", ")", ":", "primary_key", "=", "cls", ".", "_encode_key", "(", "hash_key", ",", "range_key", ")", ...
Update item attributes. Currently SET and ADD actions are supported.
[ "Update", "item", "attributes", ".", "Currently", "SET", "and", "ADD", "actions", "are", "supported", "." ]
python
train
scott-griffiths/bitstring
bitstring.py
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3365-L3388
def insert(self, bs, pos=None): """Insert bs at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. Raises ValueError if pos < 0 or pos > self.len. """ bs = Bits(bs) if not bs.len: return self if bs is self...
[ "def", "insert", "(", "self", ",", "bs", ",", "pos", "=", "None", ")", ":", "bs", "=", "Bits", "(", "bs", ")", "if", "not", "bs", ".", "len", ":", "return", "self", "if", "bs", "is", "self", ":", "bs", "=", "self", ".", "__copy__", "(", ")", ...
Insert bs at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. Raises ValueError if pos < 0 or pos > self.len.
[ "Insert", "bs", "at", "bit", "position", "pos", "." ]
python
train
openvax/pyensembl
pyensembl/download_cache.py
https://github.com/openvax/pyensembl/blob/4b995fb72e848206d6fbf11950cf30964cd9b3aa/pyensembl/download_cache.py#L243-L276
def download_or_copy_if_necessary( self, path_or_url, download_if_missing=False, overwrite=False): """ Download a remote file or copy Get the local path to a possibly remote file. Download if file is missing from the cache directory and ...
[ "def", "download_or_copy_if_necessary", "(", "self", ",", "path_or_url", ",", "download_if_missing", "=", "False", ",", "overwrite", "=", "False", ")", ":", "assert", "path_or_url", ",", "\"Expected non-empty string for path_or_url\"", "if", "self", ".", "is_url_format"...
Download a remote file or copy Get the local path to a possibly remote file. Download if file is missing from the cache directory and `download_if_missing` is True. Download even if local file exists if both `download_if_missing` and `overwrite` are True. If the file is on the ...
[ "Download", "a", "remote", "file", "or", "copy", "Get", "the", "local", "path", "to", "a", "possibly", "remote", "file", "." ]
python
train
tanghaibao/goatools
goatools/statsdescribe.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/statsdescribe.py#L37-L40
def getstr_data(self, name, vals): """Return stats data string in markdown style.""" fld2val = self.get_fld2val(name, vals) return self.fmt.format(**fld2val)
[ "def", "getstr_data", "(", "self", ",", "name", ",", "vals", ")", ":", "fld2val", "=", "self", ".", "get_fld2val", "(", "name", ",", "vals", ")", "return", "self", ".", "fmt", ".", "format", "(", "*", "*", "fld2val", ")" ]
Return stats data string in markdown style.
[ "Return", "stats", "data", "string", "in", "markdown", "style", "." ]
python
train
IntegralDefense/critsapi
critsapi/critsapi.py
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L723-L761
def source_add_update(self, crits_id, crits_type, source, action_type='add', method='', reference='', date=None): """ date must be in the format "%Y-%m-%d %H:%M:%S.%f" """ type_trans = self._type_translation(crits_type) submit_u...
[ "def", "source_add_update", "(", "self", ",", "crits_id", ",", "crits_type", ",", "source", ",", "action_type", "=", "'add'", ",", "method", "=", "''", ",", "reference", "=", "''", ",", "date", "=", "None", ")", ":", "type_trans", "=", "self", ".", "_t...
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
[ "date", "must", "be", "in", "the", "format", "%Y", "-", "%m", "-", "%d", "%H", ":", "%M", ":", "%S", ".", "%f" ]
python
train
cmbruns/pyopenvr
src/openvr/__init__.py
https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L3749-L3756
def getBoundsColor(self, nNumOutputColors, flCollisionBoundsFadeDistance): """Get the current chaperone bounds draw color and brightness""" fn = self.function_table.getBoundsColor pOutputColorArray = HmdColor_t() pOutputCameraColor = HmdColor_t() fn(byref(pOutputColorArray), nNu...
[ "def", "getBoundsColor", "(", "self", ",", "nNumOutputColors", ",", "flCollisionBoundsFadeDistance", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getBoundsColor", "pOutputColorArray", "=", "HmdColor_t", "(", ")", "pOutputCameraColor", "=", "HmdColor_t", ...
Get the current chaperone bounds draw color and brightness
[ "Get", "the", "current", "chaperone", "bounds", "draw", "color", "and", "brightness" ]
python
train
portfors-lab/sparkle
sparkle/gui/stim/auto_parameters_editor.py
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/auto_parameters_editor.py#L98-L104
def closeEvent(self, event): """Emits a signal to update start values on components""" self.visibilityChanged.emit(0) model = self.paramList.model() model.hintRequested.disconnect() model.rowsInserted.disconnect() model.rowsRemoved.disconnect()
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "self", ".", "visibilityChanged", ".", "emit", "(", "0", ")", "model", "=", "self", ".", "paramList", ".", "model", "(", ")", "model", ".", "hintRequested", ".", "disconnect", "(", ")", "model",...
Emits a signal to update start values on components
[ "Emits", "a", "signal", "to", "update", "start", "values", "on", "components" ]
python
train
MacHu-GWU/angora-project
angora/visual/timeseries.py
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/visual/timeseries.py#L136-L179
def plot_one_month(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """时间跨度为一月。 major tick = every days """ plt.close("all") fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(x, y) days = DayLocator(range(365)) daysFmt = DateFormatter("%Y-%m-...
[ "def", "plot_one_month", "(", "x", ",", "y", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "title", "=", "None", ",", "ylim", "=", "None", ")", ":", "plt", ".", "close", "(", "\"all\"", ")", "fig", "=", "plt", ".", "figure", "(", ...
时间跨度为一月。 major tick = every days
[ "时间跨度为一月。", "major", "tick", "=", "every", "days" ]
python
train
apache/incubator-heron
heronpy/api/cloudpickle.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/cloudpickle.py#L604-L657
def save_file(self, obj): # pylint: disable=too-many-branches """Save a file""" try: import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute except ImportError: import io as pystringIO # pylint: disable=reimported if not hasattr(obj, 'name') or not hasattr(obj,...
[ "def", "save_file", "(", "self", ",", "obj", ")", ":", "# pylint: disable=too-many-branches", "try", ":", "import", "StringIO", "as", "pystringIO", "#we can't use cStringIO as it lacks the name attribute", "except", "ImportError", ":", "import", "io", "as", "pystringIO", ...
Save a file
[ "Save", "a", "file" ]
python
valid
mirukan/pydecensooru
pydecensooru/main.py
https://github.com/mirukan/pydecensooru/blob/2a2bec93c40ed2d3e359ee203eceabf42ef1755d/pydecensooru/main.py#L27-L32
def decensor_iter(posts_info: Iterable[dict], site_url: str = DEFAULT_SITE ) -> Generator[dict, None, None]: """Apply decensoring on an iterable of posts info dicts from Danbooru API. Any censored post is automatically decensored if needed.""" for info in posts_info: yield decensor(...
[ "def", "decensor_iter", "(", "posts_info", ":", "Iterable", "[", "dict", "]", ",", "site_url", ":", "str", "=", "DEFAULT_SITE", ")", "->", "Generator", "[", "dict", ",", "None", ",", "None", "]", ":", "for", "info", "in", "posts_info", ":", "yield", "d...
Apply decensoring on an iterable of posts info dicts from Danbooru API. Any censored post is automatically decensored if needed.
[ "Apply", "decensoring", "on", "an", "iterable", "of", "posts", "info", "dicts", "from", "Danbooru", "API", ".", "Any", "censored", "post", "is", "automatically", "decensored", "if", "needed", "." ]
python
train
contentful-labs/contentful.py
contentful/cda/errors.py
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/errors.py#L23-L33
def api_exception(http_code): """Convenience decorator to associate HTTP status codes with :class:`.ApiError` subclasses. :param http_code: (int) HTTP status code. :return: wrapper function. """ def wrapper(*args): code = args[0] ErrorMapping.mapping[http_code] = code return...
[ "def", "api_exception", "(", "http_code", ")", ":", "def", "wrapper", "(", "*", "args", ")", ":", "code", "=", "args", "[", "0", "]", "ErrorMapping", ".", "mapping", "[", "http_code", "]", "=", "code", "return", "code", "return", "wrapper" ]
Convenience decorator to associate HTTP status codes with :class:`.ApiError` subclasses. :param http_code: (int) HTTP status code. :return: wrapper function.
[ "Convenience", "decorator", "to", "associate", "HTTP", "status", "codes", "with", ":", "class", ":", ".", "ApiError", "subclasses", "." ]
python
train
opentok/Opentok-Python-SDK
opentok/opentok.py
https://github.com/opentok/Opentok-Python-SDK/blob/ffc6714e76be0d29e6b56aff8cbf7509b71a8b2c/opentok/opentok.py#L490-L495
def list_archives(self, offset=None, count=None, session_id=None): """ New method to get archive list, it's alternative to 'get_archives()', both methods exist to have backwards compatible """ return self.get_archives(offset, count, session_id)
[ "def", "list_archives", "(", "self", ",", "offset", "=", "None", ",", "count", "=", "None", ",", "session_id", "=", "None", ")", ":", "return", "self", ".", "get_archives", "(", "offset", ",", "count", ",", "session_id", ")" ]
New method to get archive list, it's alternative to 'get_archives()', both methods exist to have backwards compatible
[ "New", "method", "to", "get", "archive", "list", "it", "s", "alternative", "to", "get_archives", "()", "both", "methods", "exist", "to", "have", "backwards", "compatible" ]
python
train
Equitable/trump
trump/orm.py
https://github.com/Equitable/trump/blob/a2802692bc642fa32096374159eea7ceca2947b4/trump/orm.py#L1270-L1286
def describe(self): """ describes a Symbol, returns a string """ lines = [] lines.append("Symbol = {}".format(self.name)) if len(self.tags): tgs = ", ".join(x.tag for x in self.tags) lines.append(" tagged = {}".format(tgs)) if len(self.aliases): ...
[ "def", "describe", "(", "self", ")", ":", "lines", "=", "[", "]", "lines", ".", "append", "(", "\"Symbol = {}\"", ".", "format", "(", "self", ".", "name", ")", ")", "if", "len", "(", "self", ".", "tags", ")", ":", "tgs", "=", "\", \"", ".", "join...
describes a Symbol, returns a string
[ "describes", "a", "Symbol", "returns", "a", "string" ]
python
train
nfcpy/nfcpy
src/nfc/tag/tt3.py
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3.py#L644-L665
def write_to_ndef_service(self, data, *blocks): """Write block data to an NDEF compatible tag. This is a convinience method to write block data to a tag that has system code 0x12FC (NDEF). For other tags this method simply does nothing. The *data* to write must be a string or by...
[ "def", "write_to_ndef_service", "(", "self", ",", "data", ",", "*", "blocks", ")", ":", "if", "self", ".", "sys", "==", "0x12FC", ":", "sc_list", "=", "[", "ServiceCode", "(", "0", ",", "0b001001", ")", "]", "bc_list", "=", "[", "BlockCode", "(", "n"...
Write block data to an NDEF compatible tag. This is a convinience method to write block data to a tag that has system code 0x12FC (NDEF). For other tags this method simply does nothing. The *data* to write must be a string or bytearray with length equal ``16 * len(blocks)``. All ...
[ "Write", "block", "data", "to", "an", "NDEF", "compatible", "tag", "." ]
python
train
HazyResearch/pdftotree
pdftotree/utils/display_utils.py
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/display_utils.py#L65-L74
def pdf_to_img(pdf_file, page_num, page_width, page_height): """ Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object """ img = Image(filename="{}[{}]".format(pdf_file, page_num - 1)) i...
[ "def", "pdf_to_img", "(", "pdf_file", ",", "page_num", ",", "page_width", ",", "page_height", ")", ":", "img", "=", "Image", "(", "filename", "=", "\"{}[{}]\"", ".", "format", "(", "pdf_file", ",", "page_num", "-", "1", ")", ")", "img", ".", "resize", ...
Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object
[ "Converts", "pdf", "file", "into", "image", ":", "param", "pdf_file", ":", "path", "to", "the", "pdf", "file", ":", "param", "page_num", ":", "page", "number", "to", "convert", "(", "index", "starting", "at", "1", ")", ":", "return", ":", "wand", "imag...
python
train
brutasse/graphite-api
graphite_api/functions.py
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L4146-L4175
def randomWalkFunction(requestContext, name, step=60): """ Short Alias: randomWalk() Returns a random walk starting at 0. This is great for testing when there is no real data in whisper. Example:: &target=randomWalk("The.time.series") This would create a series named "The.time.series...
[ "def", "randomWalkFunction", "(", "requestContext", ",", "name", ",", "step", "=", "60", ")", ":", "delta", "=", "timedelta", "(", "seconds", "=", "step", ")", "when", "=", "requestContext", "[", "\"startTime\"", "]", "values", "=", "[", "]", "current", ...
Short Alias: randomWalk() Returns a random walk starting at 0. This is great for testing when there is no real data in whisper. Example:: &target=randomWalk("The.time.series") This would create a series named "The.time.series" that contains points where x(t) == x(t-1)+random()-0.5, and x...
[ "Short", "Alias", ":", "randomWalk", "()" ]
python
train
hasgeek/coaster
coaster/sqlalchemy/mixins.py
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L536-L545
def permissions(self, actor, inherited=None): """ Permissions for this model, plus permissions inherited from the parent. """ if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(s...
[ "def", "permissions", "(", "self", ",", "actor", ",", "inherited", "=", "None", ")", ":", "if", "inherited", "is", "not", "None", ":", "return", "inherited", "|", "super", "(", "BaseScopedNameMixin", ",", "self", ")", ".", "permissions", "(", "actor", ")...
Permissions for this model, plus permissions inherited from the parent.
[ "Permissions", "for", "this", "model", "plus", "permissions", "inherited", "from", "the", "parent", "." ]
python
train
wndhydrnt/python-oauth2
oauth2/store/memory.py
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memory.py#L69-L82
def fetch_by_code(self, code): """ Returns an AuthorizationCode. :param code: The authorization code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`AuthCodeNotFound` if no data could be retrieved for given code. ""...
[ "def", "fetch_by_code", "(", "self", ",", "code", ")", ":", "if", "code", "not", "in", "self", ".", "auth_codes", ":", "raise", "AuthCodeNotFound", "return", "self", ".", "auth_codes", "[", "code", "]" ]
Returns an AuthorizationCode. :param code: The authorization code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`AuthCodeNotFound` if no data could be retrieved for given code.
[ "Returns", "an", "AuthorizationCode", "." ]
python
train
scanny/python-pptx
pptx/chart/xmlwriter.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/xmlwriter.py#L1661-L1673
def yVal(self): """ Return the ``<c:yVal>`` element for this series as an oxml element. This element contains the Y values for this series. """ xml = self._yVal_tmpl.format(**{ 'nsdecls': ' %s' % nsdecls('c'), 'numRef_xml': self.numRef_xml( ...
[ "def", "yVal", "(", "self", ")", ":", "xml", "=", "self", ".", "_yVal_tmpl", ".", "format", "(", "*", "*", "{", "'nsdecls'", ":", "' %s'", "%", "nsdecls", "(", "'c'", ")", ",", "'numRef_xml'", ":", "self", ".", "numRef_xml", "(", "self", ".", "_ser...
Return the ``<c:yVal>`` element for this series as an oxml element. This element contains the Y values for this series.
[ "Return", "the", "<c", ":", "yVal", ">", "element", "for", "this", "series", "as", "an", "oxml", "element", ".", "This", "element", "contains", "the", "Y", "values", "for", "this", "series", "." ]
python
train
helixyte/everest
everest/views/base.py
https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/views/base.py#L540-L560
def create_307_response(self): """ Creates a 307 "Temporary Redirect" response including a HTTP Warning header with code 299 that contains the user message received during processing the request. """ request = get_current_request() msg_mb = UserMessageMember(self....
[ "def", "create_307_response", "(", "self", ")", ":", "request", "=", "get_current_request", "(", ")", "msg_mb", "=", "UserMessageMember", "(", "self", ".", "message", ")", "coll", "=", "request", ".", "root", "[", "'_messages'", "]", "coll", ".", "add", "(...
Creates a 307 "Temporary Redirect" response including a HTTP Warning header with code 299 that contains the user message received during processing the request.
[ "Creates", "a", "307", "Temporary", "Redirect", "response", "including", "a", "HTTP", "Warning", "header", "with", "code", "299", "that", "contains", "the", "user", "message", "received", "during", "processing", "the", "request", "." ]
python
train
SpriteLink/NIPAP
nipap-www/nipapwww/controllers/prefix.py
https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap-www/nipapwww/controllers/prefix.py#L34-L47
def add(self): """ Add a prefix. """ # pass prefix to template - if we have any if 'prefix' in request.params: c.prefix = request.params['prefix'] else: c.prefix = '' c.search_opt_parent = "all" c.search_opt_child = "none" return...
[ "def", "add", "(", "self", ")", ":", "# pass prefix to template - if we have any", "if", "'prefix'", "in", "request", ".", "params", ":", "c", ".", "prefix", "=", "request", ".", "params", "[", "'prefix'", "]", "else", ":", "c", ".", "prefix", "=", "''", ...
Add a prefix.
[ "Add", "a", "prefix", "." ]
python
train
fboender/ansible-cmdb
src/ansiblecmdb/ansible.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/src/ansiblecmdb/ansible.py#L155-L189
def _parse_hostvar_dir(self, inventory_path): """ Parse host_vars dir, if it exists. """ # inventory_path could point to a `hosts` file, or to a dir. So we # construct the location to the `host_vars` differently. if os.path.isdir(inventory_path): path = os.pat...
[ "def", "_parse_hostvar_dir", "(", "self", ",", "inventory_path", ")", ":", "# inventory_path could point to a `hosts` file, or to a dir. So we", "# construct the location to the `host_vars` differently.", "if", "os", ".", "path", ".", "isdir", "(", "inventory_path", ")", ":", ...
Parse host_vars dir, if it exists.
[ "Parse", "host_vars", "dir", "if", "it", "exists", "." ]
python
train
bitshares/uptick
uptick/account.py
https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/account.py#L198-L220
def cloneaccount(ctx, account_name, account): """ Clone an account This copies the owner and active permissions as well as the options (e.g. votes, memo key) """ from bitsharesbase import transactions, operations account = Account(account) op = { "fee": {"amount": 0, "asset...
[ "def", "cloneaccount", "(", "ctx", ",", "account_name", ",", "account", ")", ":", "from", "bitsharesbase", "import", "transactions", ",", "operations", "account", "=", "Account", "(", "account", ")", "op", "=", "{", "\"fee\"", ":", "{", "\"amount\"", ":", ...
Clone an account This copies the owner and active permissions as well as the options (e.g. votes, memo key)
[ "Clone", "an", "account" ]
python
train
oscarbranson/latools
latools/helpers/helpers.py
https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/helpers/helpers.py#L187-L218
def collate_data(in_dir, extension='.csv', out_dir=None): """ Copy all csvs in nested directroy to single directory. Function to copy all csvs from a directory, and place them in a new directory. Parameters ---------- in_dir : str Input directory containing csv files in subfolders ...
[ "def", "collate_data", "(", "in_dir", ",", "extension", "=", "'.csv'", ",", "out_dir", "=", "None", ")", ":", "if", "out_dir", "is", "None", ":", "out_dir", "=", "'./'", "+", "re", ".", "search", "(", "'^\\.(.*)'", ",", "extension", ")", ".", "groups",...
Copy all csvs in nested directroy to single directory. Function to copy all csvs from a directory, and place them in a new directory. Parameters ---------- in_dir : str Input directory containing csv files in subfolders extension : str The extension that identifies your data fi...
[ "Copy", "all", "csvs", "in", "nested", "directroy", "to", "single", "directory", "." ]
python
test
aisthesis/pynance
pynance/opt/price.py
https://github.com/aisthesis/pynance/blob/9eb0d78b60fe2a324ed328d026fedb6dbe8f7f41/pynance/opt/price.py#L150-L182
def exps(self, opttype, strike): """ Prices for given strike on all available dates. Parameters ---------- opttype : str ('call' or 'put') strike : numeric Returns ---------- df : :class:`pandas.DataFrame` eq : float Price of ...
[ "def", "exps", "(", "self", ",", "opttype", ",", "strike", ")", ":", "_relevant", "=", "_relevant_rows", "(", "self", ".", "data", ",", "(", "strike", ",", "slice", "(", "None", ")", ",", "opttype", ",", ")", ",", "\"No key for {} {}\"", ".", "format",...
Prices for given strike on all available dates. Parameters ---------- opttype : str ('call' or 'put') strike : numeric Returns ---------- df : :class:`pandas.DataFrame` eq : float Price of underlying. qt : :class:`datetime.datetime` ...
[ "Prices", "for", "given", "strike", "on", "all", "available", "dates", "." ]
python
train
bakwc/PySyncObj
pysyncobj/syncobj.py
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/syncobj.py#L1298-L1373
def replicated(*decArgs, **decKwargs): """Replicated decorator. Use it to mark your class members that modifies a class state. Function will be called asynchronously. Function accepts flowing additional parameters (optional): 'callback': callback(result, failReason), failReason - `FAIL_REASON <#pysy...
[ "def", "replicated", "(", "*", "decArgs", ",", "*", "*", "decKwargs", ")", ":", "def", "replicatedImpl", "(", "func", ")", ":", "def", "newFunc", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "...
Replicated decorator. Use it to mark your class members that modifies a class state. Function will be called asynchronously. Function accepts flowing additional parameters (optional): 'callback': callback(result, failReason), failReason - `FAIL_REASON <#pysyncobj.FAIL_REASON>`_. 'sync': True - t...
[ "Replicated", "decorator", ".", "Use", "it", "to", "mark", "your", "class", "members", "that", "modifies", "a", "class", "state", ".", "Function", "will", "be", "called", "asynchronously", ".", "Function", "accepts", "flowing", "additional", "parameters", "(", ...
python
test
dshean/pygeotools
pygeotools/lib/timelib.py
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L488-L494
def dt2jd(dt): """Convert datetime to julian date """ a = (14 - dt.month)//12 y = dt.year + 4800 - a m = dt.month + 12*a - 3 return dt.day + ((153*m + 2)//5) + 365*y + y//4 - y//100 + y//400 - 32045
[ "def", "dt2jd", "(", "dt", ")", ":", "a", "=", "(", "14", "-", "dt", ".", "month", ")", "//", "12", "y", "=", "dt", ".", "year", "+", "4800", "-", "a", "m", "=", "dt", ".", "month", "+", "12", "*", "a", "-", "3", "return", "dt", ".", "d...
Convert datetime to julian date
[ "Convert", "datetime", "to", "julian", "date" ]
python
train
lsst-sqre/lsst-projectmeta-kit
lsstprojectmeta/jsonld.py
https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/jsonld.py#L46-L60
def _encode_datetime(self, dt): """Encode a datetime in the format '%Y-%m-%dT%H:%M:%SZ'. The datetime can be naieve (doesn't have timezone info) or aware (it does have a tzinfo attribute set). Regardless, the datetime is transformed into UTC. """ if dt.tzinfo is None: ...
[ "def", "_encode_datetime", "(", "self", ",", "dt", ")", ":", "if", "dt", ".", "tzinfo", "is", "None", ":", "# Force it to be a UTC datetime", "dt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "datetime", ".", "timezone", ".", "utc", ")", "# Convert to U...
Encode a datetime in the format '%Y-%m-%dT%H:%M:%SZ'. The datetime can be naieve (doesn't have timezone info) or aware (it does have a tzinfo attribute set). Regardless, the datetime is transformed into UTC.
[ "Encode", "a", "datetime", "in", "the", "format", "%Y", "-", "%m", "-", "%dT%H", ":", "%M", ":", "%SZ", "." ]
python
valid
Microsoft/knack
knack/deprecation.py
https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/deprecation.py#L53-L62
def ensure_new_style_deprecation(cli_ctx, kwargs, object_type): """ Helper method to make the previous string-based deprecate_info kwarg work with the new style. """ deprecate_info = kwargs.get('deprecate_info', None) if isinstance(deprecate_info, Deprecated): deprecate_i...
[ "def", "ensure_new_style_deprecation", "(", "cli_ctx", ",", "kwargs", ",", "object_type", ")", ":", "deprecate_info", "=", "kwargs", ".", "get", "(", "'deprecate_info'", ",", "None", ")", "if", "isinstance", "(", "deprecate_info", ",", "Deprecated", ")", ":", ...
Helper method to make the previous string-based deprecate_info kwarg work with the new style.
[ "Helper", "method", "to", "make", "the", "previous", "string", "-", "based", "deprecate_info", "kwarg", "work", "with", "the", "new", "style", "." ]
python
train
indranilsinharoy/pyzos
pyzos/zos.py
https://github.com/indranilsinharoy/pyzos/blob/da6bf3296b0154ccee44ad9a4286055ae031ecc7/pyzos/zos.py#L396-L414
def zSetSurfaceData(self, surfNum, radius=None, thick=None, material=None, semidia=None, conic=None, comment=None): """Sets surface data""" if self.pMode == 0: # Sequential mode surf = self.pLDE.GetSurfaceAt(surfNum) if radius is not None: ...
[ "def", "zSetSurfaceData", "(", "self", ",", "surfNum", ",", "radius", "=", "None", ",", "thick", "=", "None", ",", "material", "=", "None", ",", "semidia", "=", "None", ",", "conic", "=", "None", ",", "comment", "=", "None", ")", ":", "if", "self", ...
Sets surface data
[ "Sets", "surface", "data" ]
python
train
theislab/scanpy
scanpy/plotting/_tools/scatterplots.py
https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/plotting/_tools/scatterplots.py#L651-L736
def _get_color_values(adata, value_to_plot, groups=None, palette=None, use_raw=False, gene_symbols=None, layer=None): """ Returns the value or color associated to each data point. For categorical data, the return value is list of colors taken from the category palette or from the g...
[ "def", "_get_color_values", "(", "adata", ",", "value_to_plot", ",", "groups", "=", "None", ",", "palette", "=", "None", ",", "use_raw", "=", "False", ",", "gene_symbols", "=", "None", ",", "layer", "=", "None", ")", ":", "###", "# when plotting, the color o...
Returns the value or color associated to each data point. For categorical data, the return value is list of colors taken from the category palette or from the given `palette` value. For non-categorical data, the values are returned
[ "Returns", "the", "value", "or", "color", "associated", "to", "each", "data", "point", ".", "For", "categorical", "data", "the", "return", "value", "is", "list", "of", "colors", "taken", "from", "the", "category", "palette", "or", "from", "the", "given", "...
python
train
ahmontero/dop
dop/client.py
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L724-L742
def domain_records(self, domain_id): """ This method returns all of your current domain records. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve records. """ json = s...
[ "def", "domain_records", "(", "self", ",", "domain_id", ")", ":", "json", "=", "self", ".", "request", "(", "'/domains/%s/records'", "%", "domain_id", ",", "method", "=", "'GET'", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "if", "statu...
This method returns all of your current domain records. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve records.
[ "This", "method", "returns", "all", "of", "your", "current", "domain", "records", "." ]
python
train
waqasbhatti/astrobase
astrobase/cpserver/checkplotlist.py
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/cpserver/checkplotlist.py#L169-L203
def checkplot_infokey_worker(task): '''This gets the required keys from the requested file. Parameters ---------- task : tuple Task is a two element tuple:: - task[0] is the dict to work on - task[1] is a list of lists of str indicating all the key address to extrac...
[ "def", "checkplot_infokey_worker", "(", "task", ")", ":", "cpf", ",", "keys", "=", "task", "cpd", "=", "_read_checkplot_picklefile", "(", "cpf", ")", "resultkeys", "=", "[", "]", "for", "k", "in", "keys", ":", "try", ":", "resultkeys", ".", "append", "("...
This gets the required keys from the requested file. Parameters ---------- task : tuple Task is a two element tuple:: - task[0] is the dict to work on - task[1] is a list of lists of str indicating all the key address to extract items from the dict for Returns ...
[ "This", "gets", "the", "required", "keys", "from", "the", "requested", "file", "." ]
python
valid
knipknap/SpiffWorkflow
SpiffWorkflow/bpmn/serializer/Packager.py
https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/Packager.py#L240-L256
def pre_parse_and_validate_signavio(self, bpmn, filename): """ This is the Signavio specific editor hook for pre-parsing and validation. A subclass can override this method to provide additional parseing or validation. It should call the parent method first. :param bpmn...
[ "def", "pre_parse_and_validate_signavio", "(", "self", ",", "bpmn", ",", "filename", ")", ":", "self", ".", "_check_for_disconnected_boundary_events_signavio", "(", "bpmn", ",", "filename", ")", "self", ".", "_fix_call_activities_signavio", "(", "bpmn", ",", "filename...
This is the Signavio specific editor hook for pre-parsing and validation. A subclass can override this method to provide additional parseing or validation. It should call the parent method first. :param bpmn: an lxml tree of the bpmn content :param filename: the source file na...
[ "This", "is", "the", "Signavio", "specific", "editor", "hook", "for", "pre", "-", "parsing", "and", "validation", "." ]
python
valid
saltstack/salt
salt/modules/mac_user.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L437-L456
def list_groups(name): ''' Return a list of groups the named user belongs to. name The name of the user for which to list groups. Starting in Salt 2016.11.0, all groups for the user, including groups beginning with an underscore will be listed. .. versionchanged:: 2016.11....
[ "def", "list_groups", "(", "name", ")", ":", "groups", "=", "[", "group", "for", "group", "in", "salt", ".", "utils", ".", "user", ".", "get_group_list", "(", "name", ")", "]", "return", "groups" ]
Return a list of groups the named user belongs to. name The name of the user for which to list groups. Starting in Salt 2016.11.0, all groups for the user, including groups beginning with an underscore will be listed. .. versionchanged:: 2016.11.0 CLI Example: .. code-bl...
[ "Return", "a", "list", "of", "groups", "the", "named", "user", "belongs", "to", "." ]
python
train
jasonrbriggs/proton
python/proton/xmlutils.py
https://github.com/jasonrbriggs/proton/blob/e734734750797ef0caaa1680379e07b86d7a53e3/python/proton/xmlutils.py#L42-L49
def parseelement(elem): ''' Convert the content of an element into more ElementTree structures. We do this because sometimes we want to set xml as the content of an element. ''' xml = '<%(tag)s>%(content)s</%(tag)s>' % {'tag' : elem.tag, 'content' : elem.text} et = etree.fromstring(xml) repl...
[ "def", "parseelement", "(", "elem", ")", ":", "xml", "=", "'<%(tag)s>%(content)s</%(tag)s>'", "%", "{", "'tag'", ":", "elem", ".", "tag", ",", "'content'", ":", "elem", ".", "text", "}", "et", "=", "etree", ".", "fromstring", "(", "xml", ")", "replaceele...
Convert the content of an element into more ElementTree structures. We do this because sometimes we want to set xml as the content of an element.
[ "Convert", "the", "content", "of", "an", "element", "into", "more", "ElementTree", "structures", ".", "We", "do", "this", "because", "sometimes", "we", "want", "to", "set", "xml", "as", "the", "content", "of", "an", "element", "." ]
python
train
raphaelgyory/django-rest-messaging
rest_messaging/models.py
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L191-L194
def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """ h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, sent_at__gte=h24).count()
[ "def", "return_daily_messages_count", "(", "self", ",", "sender", ")", ":", "h24", "=", "now", "(", ")", "-", "timedelta", "(", "days", "=", "1", ")", "return", "Message", ".", "objects", ".", "filter", "(", "sender", "=", "sender", ",", "sent_at__gte", ...
Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits
[ "Returns", "the", "number", "of", "messages", "sent", "in", "the", "last", "24", "hours", "so", "we", "can", "ensure", "the", "user", "does", "not", "exceed", "his", "messaging", "limits" ]
python
train
liamw9534/bt-manager
bt_manager/codecs.py
https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/codecs.py#L159-L181
def encode(self, fd, mtu, data): """ Encode the supplied data (byte array) and write to the media transport file descriptor encapsulated as RTP packets. The encoder will calculate the required number of SBC frames and encapsulate as RTP to fit the MTU size. :par...
[ "def", "encode", "(", "self", ",", "fd", ",", "mtu", ",", "data", ")", ":", "self", ".", "codec", ".", "rtp_sbc_encode_to_fd", "(", "self", ".", "config", ",", "ffi", ".", "new", "(", "'char[]'", ",", "data", ")", ",", "len", "(", "data", ")", ",...
Encode the supplied data (byte array) and write to the media transport file descriptor encapsulated as RTP packets. The encoder will calculate the required number of SBC frames and encapsulate as RTP to fit the MTU size. :param int fd: Media transport file descriptor :p...
[ "Encode", "the", "supplied", "data", "(", "byte", "array", ")", "and", "write", "to", "the", "media", "transport", "file", "descriptor", "encapsulated", "as", "RTP", "packets", ".", "The", "encoder", "will", "calculate", "the", "required", "number", "of", "S...
python
train
pkkid/python-plexapi
plexapi/server.py
https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/server.py#L174-L179
def settings(self): """ Returns a list of all server settings. """ if not self._settings: data = self.query(Settings.key) self._settings = Settings(self, data) return self._settings
[ "def", "settings", "(", "self", ")", ":", "if", "not", "self", ".", "_settings", ":", "data", "=", "self", ".", "query", "(", "Settings", ".", "key", ")", "self", ".", "_settings", "=", "Settings", "(", "self", ",", "data", ")", "return", "self", "...
Returns a list of all server settings.
[ "Returns", "a", "list", "of", "all", "server", "settings", "." ]
python
train
google/grr
api_client/python/grr_api_client/client.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/api_client/python/grr_api_client/client.py#L242-L247
def Get(self): """Fetch client's data and return a proper Client object.""" args = client_pb2.ApiGetClientArgs(client_id=self.client_id) result = self._context.SendRequest("GetClient", args) return Client(data=result, context=self._context)
[ "def", "Get", "(", "self", ")", ":", "args", "=", "client_pb2", ".", "ApiGetClientArgs", "(", "client_id", "=", "self", ".", "client_id", ")", "result", "=", "self", ".", "_context", ".", "SendRequest", "(", "\"GetClient\"", ",", "args", ")", "return", "...
Fetch client's data and return a proper Client object.
[ "Fetch", "client", "s", "data", "and", "return", "a", "proper", "Client", "object", "." ]
python
train
aio-libs/aioftp
ftpbench.py
https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/ftpbench.py#L248-L269
def stor(ftp=None): """Same as ftplib's storbinary() but just sends dummy data instead of reading it from a real file. """ if ftp is None: ftp = connect() quit = True else: quit = False ftp.voidcmd('TYPE I') with contextlib.closing(ftp.transfercmd("STOR " + TESTFN)) a...
[ "def", "stor", "(", "ftp", "=", "None", ")", ":", "if", "ftp", "is", "None", ":", "ftp", "=", "connect", "(", ")", "quit", "=", "True", "else", ":", "quit", "=", "False", "ftp", ".", "voidcmd", "(", "'TYPE I'", ")", "with", "contextlib", ".", "cl...
Same as ftplib's storbinary() but just sends dummy data instead of reading it from a real file.
[ "Same", "as", "ftplib", "s", "storbinary", "()", "but", "just", "sends", "dummy", "data", "instead", "of", "reading", "it", "from", "a", "real", "file", "." ]
python
valid
benjamin-hodgson/asynqp
src/asynqp/__init__.py
https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/__init__.py#L90-L112
def connect_and_open_channel(host='localhost', port=5672, username='guest', password='guest', virtual_host='/', on_connection_close=None, *, loop=None, **kwargs): """ ...
[ "def", "connect_and_open_channel", "(", "host", "=", "'localhost'", ",", "port", "=", "5672", ",", "username", "=", "'guest'", ",", "password", "=", "'guest'", ",", "virtual_host", "=", "'/'", ",", "on_connection_close", "=", "None", ",", "*", ",", "loop", ...
Connect to an AMQP server and open a channel on the connection. This function is a :ref:`coroutine <coroutine>`. Parameters of this function are the same as :func:`connect`. :return: a tuple of ``(connection, channel)``. Equivalent to:: connection = yield from connect(host, port, username, p...
[ "Connect", "to", "an", "AMQP", "server", "and", "open", "a", "channel", "on", "the", "connection", ".", "This", "function", "is", "a", ":", "ref", ":", "coroutine", "<coroutine", ">", "." ]
python
train
DEIB-GECO/PyGMQL
gmql/ml/dataset/parser/parser.py
https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/dataset/parser/parser.py#L59-L70
def parse_schema(schema_file): """ parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe :param schema_file: the path to the schema file :return: the columns of the schema file """ e = xml.etree.Elem...
[ "def", "parse_schema", "(", "schema_file", ")", ":", "e", "=", "xml", ".", "etree", ".", "ElementTree", ".", "parse", "(", "schema_file", ")", "root", "=", "e", ".", "getroot", "(", ")", "cols", "=", "[", "]", "for", "elem", "in", "root", ".", "fin...
parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe :param schema_file: the path to the schema file :return: the columns of the schema file
[ "parses", "the", "schema", "file", "and", "returns", "the", "columns", "that", "are", "later", "going", "to", "represent", "the", "columns", "of", "the", "genometric", "space", "dataframe", ":", "param", "schema_file", ":", "the", "path", "to", "the", "schem...
python
train
Gandi/gandi.cli
gandi/cli/modules/paas.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/paas.py#L362-L366
def list_names(cls): """Retrieve paas id and names.""" ret = dict([(item['id'], item['name']) for item in cls.list({'items_per_page': 500})]) return ret
[ "def", "list_names", "(", "cls", ")", ":", "ret", "=", "dict", "(", "[", "(", "item", "[", "'id'", "]", ",", "item", "[", "'name'", "]", ")", "for", "item", "in", "cls", ".", "list", "(", "{", "'items_per_page'", ":", "500", "}", ")", "]", ")",...
Retrieve paas id and names.
[ "Retrieve", "paas", "id", "and", "names", "." ]
python
train
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L360-L370
def selected_urls(self): """ Gets the list of selected items file path (url) """ urls = [] debug('gettings urls') for proxy_index in self.tree_view.selectedIndexes(): finfo = self.tree_view.fileInfo(proxy_index) urls.append(finfo.canonicalFilePath(...
[ "def", "selected_urls", "(", "self", ")", ":", "urls", "=", "[", "]", "debug", "(", "'gettings urls'", ")", "for", "proxy_index", "in", "self", ".", "tree_view", ".", "selectedIndexes", "(", ")", ":", "finfo", "=", "self", ".", "tree_view", ".", "fileInf...
Gets the list of selected items file path (url)
[ "Gets", "the", "list", "of", "selected", "items", "file", "path", "(", "url", ")" ]
python
train
edx/edx-enterprise
enterprise/admin/utils.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/utils.py#L141-L173
def validate_email_to_link(email, raw_email=None, message_template=None, ignore_existing=False): """ Validate email to be linked to Enterprise Customer. Performs two checks: * Checks that email is valid * Checks that it is not already linked to any Enterprise Customer Arguments: ...
[ "def", "validate_email_to_link", "(", "email", ",", "raw_email", "=", "None", ",", "message_template", "=", "None", ",", "ignore_existing", "=", "False", ")", ":", "raw_email", "=", "raw_email", "if", "raw_email", "is", "not", "None", "else", "email", "message...
Validate email to be linked to Enterprise Customer. Performs two checks: * Checks that email is valid * Checks that it is not already linked to any Enterprise Customer Arguments: email (str): user email to link raw_email (str): raw value as it was passed by user - used in error...
[ "Validate", "email", "to", "be", "linked", "to", "Enterprise", "Customer", "." ]
python
valid
DataBiosphere/toil
src/toil/utils/toilStats.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/utils/toilStats.py#L410-L418
def computeColumnWidths(job_types, worker, job, options): """ Return a ColumnWidths() object with the correct max widths. """ cw = ColumnWidths() for t in job_types: updateColumnWidths(t, cw, options) updateColumnWidths(worker, cw, options) updateColumnWidths(job, cw, options) return...
[ "def", "computeColumnWidths", "(", "job_types", ",", "worker", ",", "job", ",", "options", ")", ":", "cw", "=", "ColumnWidths", "(", ")", "for", "t", "in", "job_types", ":", "updateColumnWidths", "(", "t", ",", "cw", ",", "options", ")", "updateColumnWidth...
Return a ColumnWidths() object with the correct max widths.
[ "Return", "a", "ColumnWidths", "()", "object", "with", "the", "correct", "max", "widths", "." ]
python
train
Dentosal/python-sc2
sc2/bot_ai.py
https://github.com/Dentosal/python-sc2/blob/608bd25f04e89d39cef68b40101d8e9a8a7f1634/sc2/bot_ai.py#L468-L472
def get_terrain_height(self, pos: Union[Point2, Point3, Unit]) -> int: """ Returns terrain height at a position. Caution: terrain height is not anywhere near a unit's z-coordinate. """ assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self._game_info.te...
[ "def", "get_terrain_height", "(", "self", ",", "pos", ":", "Union", "[", "Point2", ",", "Point3", ",", "Unit", "]", ")", "->", "int", ":", "assert", "isinstance", "(", "pos", ",", "(", "Point2", ",", "Point3", ",", "Unit", ")", ")", "pos", "=", "po...
Returns terrain height at a position. Caution: terrain height is not anywhere near a unit's z-coordinate.
[ "Returns", "terrain", "height", "at", "a", "position", ".", "Caution", ":", "terrain", "height", "is", "not", "anywhere", "near", "a", "unit", "s", "z", "-", "coordinate", "." ]
python
train
saltstack/salt
salt/runners/cloud.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/cloud.py#L129-L137
def destroy(instances, opts=None): ''' Destroy the named vm(s) ''' client = _get_client() if isinstance(opts, dict): client.opts.update(opts) info = client.destroy(instances) return info
[ "def", "destroy", "(", "instances", ",", "opts", "=", "None", ")", ":", "client", "=", "_get_client", "(", ")", "if", "isinstance", "(", "opts", ",", "dict", ")", ":", "client", ".", "opts", ".", "update", "(", "opts", ")", "info", "=", "client", "...
Destroy the named vm(s)
[ "Destroy", "the", "named", "vm", "(", "s", ")" ]
python
train
dwavesystems/penaltymodel
penaltymodel_cache/penaltymodel/cache/database_manager.py
https://github.com/dwavesystems/penaltymodel/blob/b9d343233aea8df0f59cea45a07f12d0b3b8d9b3/penaltymodel_cache/penaltymodel/cache/database_manager.py#L316-L337
def _serialize_linear_biases(linear, nodelist): """Serializes the linear biases. Args: linear: a interable object where linear[v] is the bias associated with v. nodelist (list): an ordered iterable containing the nodes. Returns: str: base 64 encoded string of little end...
[ "def", "_serialize_linear_biases", "(", "linear", ",", "nodelist", ")", ":", "linear_bytes", "=", "struct", ".", "pack", "(", "'<'", "+", "'d'", "*", "len", "(", "linear", ")", ",", "*", "[", "linear", "[", "i", "]", "for", "i", "in", "nodelist", "]"...
Serializes the linear biases. Args: linear: a interable object where linear[v] is the bias associated with v. nodelist (list): an ordered iterable containing the nodes. Returns: str: base 64 encoded string of little endian 8 byte floats, one for each of the bias...
[ "Serializes", "the", "linear", "biases", "." ]
python
train
fumitoh/modelx
modelx/core/node.py
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/node.py#L63-L80
def tuplize_key(obj, key, remove_extra=False): """Args""" paramlen = len(obj.formula.parameters) if isinstance(key, str): key = (key,) elif not isinstance(key, Sequence): key = (key,) if not remove_extra: return key else: arglen = len(key) if arglen: ...
[ "def", "tuplize_key", "(", "obj", ",", "key", ",", "remove_extra", "=", "False", ")", ":", "paramlen", "=", "len", "(", "obj", ".", "formula", ".", "parameters", ")", "if", "isinstance", "(", "key", ",", "str", ")", ":", "key", "=", "(", "key", ","...
Args
[ "Args" ]
python
valid
coin-or/GiMPy
src/gimpy/tree.py
https://github.com/coin-or/GiMPy/blob/51853122a50eb6019d06bbdedbfc396a833b5a22/src/gimpy/tree.py#L281-L296
def del_node(self, n): ''' API: del_node(self, n) Description: Removes node n from tree. Pre: Node n should be present in the tree. Input: n: Node name. ''' parent = self.get_node_attr(n, 'parent') if self.get_node_attr(...
[ "def", "del_node", "(", "self", ",", "n", ")", ":", "parent", "=", "self", ".", "get_node_attr", "(", "n", ",", "'parent'", ")", "if", "self", ".", "get_node_attr", "(", "n", ",", "'direction'", ")", "==", "'R'", ":", "self", ".", "set_node_attr", "(...
API: del_node(self, n) Description: Removes node n from tree. Pre: Node n should be present in the tree. Input: n: Node name.
[ "API", ":", "del_node", "(", "self", "n", ")", "Description", ":", "Removes", "node", "n", "from", "tree", ".", "Pre", ":", "Node", "n", "should", "be", "present", "in", "the", "tree", ".", "Input", ":", "n", ":", "Node", "name", "." ]
python
train
raiden-network/raiden
raiden/network/proxies/utils.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/utils.py#L45-L70
def get_onchain_locksroots( chain: 'BlockChainService', canonical_identifier: CanonicalIdentifier, participant1: Address, participant2: Address, block_identifier: BlockSpecification, ) -> Tuple[Locksroot, Locksroot]: """Return the locksroot for `participant1` and `participant...
[ "def", "get_onchain_locksroots", "(", "chain", ":", "'BlockChainService'", ",", "canonical_identifier", ":", "CanonicalIdentifier", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", ")", ...
Return the locksroot for `participant1` and `participant2` at `block_identifier`.
[ "Return", "the", "locksroot", "for", "participant1", "and", "participant2", "at", "block_identifier", "." ]
python
train
openvax/datacache
datacache/download.py
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/download.py#L159-L214
def fetch_file( download_url, filename=None, decompress=False, subdir=None, force=False, timeout=None, use_wget_if_available=False): """ Download a remote file and store it locally in a cache directory. Don't download it again if it's already present (...
[ "def", "fetch_file", "(", "download_url", ",", "filename", "=", "None", ",", "decompress", "=", "False", ",", "subdir", "=", "None", ",", "force", "=", "False", ",", "timeout", "=", "None", ",", "use_wget_if_available", "=", "False", ")", ":", "filename", ...
Download a remote file and store it locally in a cache directory. Don't download it again if it's already present (unless `force` is True.) Parameters ---------- download_url : str Remote URL of file to download. filename : str, optional Local filename, used as cache key. If omitte...
[ "Download", "a", "remote", "file", "and", "store", "it", "locally", "in", "a", "cache", "directory", ".", "Don", "t", "download", "it", "again", "if", "it", "s", "already", "present", "(", "unless", "force", "is", "True", ".", ")" ]
python
train
rduplain/jeni-python
jeni.py
https://github.com/rduplain/jeni-python/blob/feca12ce5e4f0438ae5d7bec59d61826063594f1/jeni.py#L300-L326
def partial(__fn, *a, **kw): """Wrap a note for injection of a partially applied function. This allows for annotated functions to be injected for composition:: from jeni import annotate @annotate('foo', bar=annotate.maybe('bar')) def foobar(foo, bar=None): ...
[ "def", "partial", "(", "__fn", ",", "*", "a", ",", "*", "*", "kw", ")", ":", "return", "(", "PARTIAL", ",", "(", "__fn", ",", "a", ",", "tuple", "(", "kw", ".", "items", "(", ")", ")", ")", ")" ]
Wrap a note for injection of a partially applied function. This allows for annotated functions to be injected for composition:: from jeni import annotate @annotate('foo', bar=annotate.maybe('bar')) def foobar(foo, bar=None): return @annotate('f...
[ "Wrap", "a", "note", "for", "injection", "of", "a", "partially", "applied", "function", "." ]
python
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/main.py
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/main.py#L43-L68
def init(): """Initialize the pipeline in maya so everything works Init environment and load plugins. This also creates the initial Jukebox Menu entry. :returns: None :rtype: None :raises: None """ main.init_environment() pluginpath = os.pathsep.join((os.environ.get('JUKEBOX_PLUGIN...
[ "def", "init", "(", ")", ":", "main", ".", "init_environment", "(", ")", "pluginpath", "=", "os", ".", "pathsep", ".", "join", "(", "(", "os", ".", "environ", ".", "get", "(", "'JUKEBOX_PLUGIN_PATH'", ",", "''", ")", ",", "BUILTIN_PLUGIN_PATH", ")", ")...
Initialize the pipeline in maya so everything works Init environment and load plugins. This also creates the initial Jukebox Menu entry. :returns: None :rtype: None :raises: None
[ "Initialize", "the", "pipeline", "in", "maya", "so", "everything", "works" ]
python
train
cakebread/yolk
yolk/yolklib.py
https://github.com/cakebread/yolk/blob/ee8c9f529a542d9c5eff4fe69b9c7906c802e4d8/yolk/yolklib.py#L107-L128
def get_packages(self, show): """ Return list of Distributions filtered by active status or all @param show: Type of package(s) to show; active, non-active or all @type show: string: "active", "non-active", "all" @returns: list of pkg_resources Distribution objects """ ...
[ "def", "get_packages", "(", "self", ",", "show", ")", ":", "if", "show", "==", "'nonactive'", "or", "show", "==", "\"all\"", ":", "all_packages", "=", "[", "]", "for", "package", "in", "self", ".", "environment", ":", "#There may be multiple versions of same p...
Return list of Distributions filtered by active status or all @param show: Type of package(s) to show; active, non-active or all @type show: string: "active", "non-active", "all" @returns: list of pkg_resources Distribution objects
[ "Return", "list", "of", "Distributions", "filtered", "by", "active", "status", "or", "all" ]
python
train
abe-winter/pg13-py
pg13/pgmock_dbapi2.py
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pgmock_dbapi2.py#L134-L140
def open_only(f): "decorator" @functools.wraps(f) def f2(self, *args, **kwargs): if self.closed: raise NotSupportedError('connection is closed') return f(self, *args, **kwargs) return f2
[ "def", "open_only", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "f2", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "closed", ":", "raise", "NotSupportedError", "(", "'connection ...
decorator
[ "decorator" ]
python
train
caseyjlaw/rtpipe
rtpipe/RT.py
https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/RT.py#L1027-L1036
def correct_dmdt(d, dmind, dtind, blrange): """ Dedisperses and resamples data *in place*. Drops edges, since it assumes that data is read with overlapping chunks in time. """ data = numpyview(data_mem, 'complex64', datashape(d)) data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d)) ...
[ "def", "correct_dmdt", "(", "d", ",", "dmind", ",", "dtind", ",", "blrange", ")", ":", "data", "=", "numpyview", "(", "data_mem", ",", "'complex64'", ",", "datashape", "(", "d", ")", ")", "data_resamp", "=", "numpyview", "(", "data_resamp_mem", ",", "'co...
Dedisperses and resamples data *in place*. Drops edges, since it assumes that data is read with overlapping chunks in time.
[ "Dedisperses", "and", "resamples", "data", "*", "in", "place", "*", ".", "Drops", "edges", "since", "it", "assumes", "that", "data", "is", "read", "with", "overlapping", "chunks", "in", "time", "." ]
python
train
jazzband/django-model-utils
model_utils/managers.py
https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/managers.py#L327-L400
def join(self, qs=None): ''' Join one queryset together with another using a temporary table. If no queryset is used, it will use the current queryset and join that to itself. `Join` either uses the current queryset and effectively does a self-join to create a new limite...
[ "def", "join", "(", "self", ",", "qs", "=", "None", ")", ":", "to_field", "=", "'id'", "if", "qs", ":", "fk", "=", "[", "fk", "for", "fk", "in", "qs", ".", "model", ".", "_meta", ".", "fields", "if", "getattr", "(", "fk", ",", "'related_model'", ...
Join one queryset together with another using a temporary table. If no queryset is used, it will use the current queryset and join that to itself. `Join` either uses the current queryset and effectively does a self-join to create a new limited queryset OR it uses a querset given by the ...
[ "Join", "one", "queryset", "together", "with", "another", "using", "a", "temporary", "table", ".", "If", "no", "queryset", "is", "used", "it", "will", "use", "the", "current", "queryset", "and", "join", "that", "to", "itself", "." ]
python
train
fabioz/PyDev.Debugger
third_party/pep8/pycodestyle.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L791-L806
def whitespace_around_comma(logical_line): r"""Avoid extraneous whitespace after a comma or a colon. Note: these checks are disabled by default Okay: a = (1, 2) E241: a = (1, 2) E242: a = (1,\t2) """ line = logical_line for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line): fou...
[ "def", "whitespace_around_comma", "(", "logical_line", ")", ":", "line", "=", "logical_line", "for", "m", "in", "WHITESPACE_AFTER_COMMA_REGEX", ".", "finditer", "(", "line", ")", ":", "found", "=", "m", ".", "start", "(", ")", "+", "1", "if", "'\\t'", "in"...
r"""Avoid extraneous whitespace after a comma or a colon. Note: these checks are disabled by default Okay: a = (1, 2) E241: a = (1, 2) E242: a = (1,\t2)
[ "r", "Avoid", "extraneous", "whitespace", "after", "a", "comma", "or", "a", "colon", "." ]
python
train
consbio/restle
restle/fields.py
https://github.com/consbio/restle/blob/60d100da034c612d4910f4f79eaa57a76eb3dcc6/restle/fields.py#L145-L157
def to_python(self, value, resource): """Dictionary to Python object""" if isinstance(value, dict): d = { self.aliases.get(k, k): self.to_python(v, resource) if isinstance(v, (dict, list)) else v for k, v in six.iteritems(value) } retu...
[ "def", "to_python", "(", "self", ",", "value", ",", "resource", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "d", "=", "{", "self", ".", "aliases", ".", "get", "(", "k", ",", "k", ")", ":", "self", ".", "to_python", "(", "...
Dictionary to Python object
[ "Dictionary", "to", "Python", "object" ]
python
train
richardchien/nonebot
nonebot/command/argfilter/validators.py
https://github.com/richardchien/nonebot/blob/13ed9e4e87d9824b61592520aabda6d2737c8848/nonebot/command/argfilter/validators.py#L72-L84
def ensure_true(bool_func: Callable[[Any], bool], message=None) -> Filter_T: """ Validate any object to ensure the result of applying a boolean function to it is True. """ def validate(value): if bool_func(value) is not True: _raise_failure(message) retur...
[ "def", "ensure_true", "(", "bool_func", ":", "Callable", "[", "[", "Any", "]", ",", "bool", "]", ",", "message", "=", "None", ")", "->", "Filter_T", ":", "def", "validate", "(", "value", ")", ":", "if", "bool_func", "(", "value", ")", "is", "not", ...
Validate any object to ensure the result of applying a boolean function to it is True.
[ "Validate", "any", "object", "to", "ensure", "the", "result", "of", "applying", "a", "boolean", "function", "to", "it", "is", "True", "." ]
python
train
a1ezzz/wasp-general
wasp_general/signals/signals.py
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/signals/signals.py#L126-L138
def __watchers_callbacks_exec(self, signal_name): """ Generate callback for a queue :param signal_name: name of a signal that callback is generated for :type signal_name: str :rtype: callable """ def callback_fn(): for watcher in self.__watchers_callbacks[signal_name]: if watcher is not None: ...
[ "def", "__watchers_callbacks_exec", "(", "self", ",", "signal_name", ")", ":", "def", "callback_fn", "(", ")", ":", "for", "watcher", "in", "self", ".", "__watchers_callbacks", "[", "signal_name", "]", ":", "if", "watcher", "is", "not", "None", ":", "watcher...
Generate callback for a queue :param signal_name: name of a signal that callback is generated for :type signal_name: str :rtype: callable
[ "Generate", "callback", "for", "a", "queue" ]
python
train
pyca/pyopenssl
src/OpenSSL/crypto.py
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1102-L1115
def set_version(self, version): """ Set the version number of the certificate. Note that the version value is zero-based, eg. a value of 0 is V1. :param version: The version number of the certificate. :type version: :py:class:`int` :return: ``None`` """ ...
[ "def", "set_version", "(", "self", ",", "version", ")", ":", "if", "not", "isinstance", "(", "version", ",", "int", ")", ":", "raise", "TypeError", "(", "\"version must be an integer\"", ")", "_lib", ".", "X509_set_version", "(", "self", ".", "_x509", ",", ...
Set the version number of the certificate. Note that the version value is zero-based, eg. a value of 0 is V1. :param version: The version number of the certificate. :type version: :py:class:`int` :return: ``None``
[ "Set", "the", "version", "number", "of", "the", "certificate", ".", "Note", "that", "the", "version", "value", "is", "zero", "-", "based", "eg", ".", "a", "value", "of", "0", "is", "V1", "." ]
python
test
juju/charm-helpers
charmhelpers/contrib/saltstack/__init__.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/saltstack/__init__.py#L88-L104
def install_salt_support(from_ppa=True): """Installs the salt-minion helper for machine state. By default the salt-minion package is installed from the saltstack PPA. If from_ppa is False you must ensure that the salt-minion package is available in the apt cache. """ if from_ppa: subpro...
[ "def", "install_salt_support", "(", "from_ppa", "=", "True", ")", ":", "if", "from_ppa", ":", "subprocess", ".", "check_call", "(", "[", "'/usr/bin/add-apt-repository'", ",", "'--yes'", ",", "'ppa:saltstack/salt'", ",", "]", ")", "subprocess", ".", "check_call", ...
Installs the salt-minion helper for machine state. By default the salt-minion package is installed from the saltstack PPA. If from_ppa is False you must ensure that the salt-minion package is available in the apt cache.
[ "Installs", "the", "salt", "-", "minion", "helper", "for", "machine", "state", "." ]
python
train
mfitzp/biocyc
biocyc/biocyc.py
https://github.com/mfitzp/biocyc/blob/2fe81971687e4dcf1fcf869af0e7b3549be535b1/biocyc/biocyc.py#L338-L379
def get_from_cache(self, org_id, id): ''' Get an object from the cache Use all cache folders available (primary first, then secondary in order) and look for the ID in the dir if found unpickle and return the object, else return False FIXME: Check for expiry of o...
[ "def", "get_from_cache", "(", "self", ",", "org_id", ",", "id", ")", ":", "current_time", "=", "datetime", ".", "now", "(", ")", "# Check memory cache first", "if", "id", "in", "self", ".", "memory_cache", "[", "org_id", "]", ":", "obj", "=", "self", "."...
Get an object from the cache Use all cache folders available (primary first, then secondary in order) and look for the ID in the dir if found unpickle and return the object, else return False FIXME: Check for expiry of object! Return false is expired (will auto-refetch and over...
[ "Get", "an", "object", "from", "the", "cache", "Use", "all", "cache", "folders", "available", "(", "primary", "first", "then", "secondary", "in", "order", ")", "and", "look", "for", "the", "ID", "in", "the", "dir", "if", "found", "unpickle", "and", "retu...
python
train