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
upsight/doctor
doctor/utils/__init__.py
https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L215-L237
def get_description_lines(docstring): """Extract the description from the given docstring. This grabs everything up to the first occurrence of something that looks like a parameter description. The docstring will be dedented and cleaned up using the standard Sphinx methods. :param str docstring: T...
[ "def", "get_description_lines", "(", "docstring", ")", ":", "if", "prepare_docstring", "is", "None", ":", "raise", "ImportError", "(", "'sphinx must be installed to use this function.'", ")", "if", "not", "isinstance", "(", "docstring", ",", "str", ")", ":", "return...
Extract the description from the given docstring. This grabs everything up to the first occurrence of something that looks like a parameter description. The docstring will be dedented and cleaned up using the standard Sphinx methods. :param str docstring: The source docstring. :returns: list
[ "Extract", "the", "description", "from", "the", "given", "docstring", "." ]
python
train
criteo/gourde
gourde/gourde.py
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L78-L82
def _add_routes(self): """Add some nice default routes.""" if self.app.has_static_folder: self.add_url_rule("/favicon.ico", "favicon", self.favicon) self.add_url_rule("/", "__default_redirect_to_status", self.redirect_to_status)
[ "def", "_add_routes", "(", "self", ")", ":", "if", "self", ".", "app", ".", "has_static_folder", ":", "self", ".", "add_url_rule", "(", "\"/favicon.ico\"", ",", "\"favicon\"", ",", "self", ".", "favicon", ")", "self", ".", "add_url_rule", "(", "\"/\"", ","...
Add some nice default routes.
[ "Add", "some", "nice", "default", "routes", "." ]
python
train
bspaans/python-mingus
mingus/core/progressions.py
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L38-L91
def to_chords(progression, key='C'): """Convert a list of chord functions or a string to a list of chords. Examples: >>> to_chords(['I', 'V7']) [['C', 'E', 'G'], ['G', 'B', 'D', 'F']] >>> to_chords('I7') [['C', 'E', 'G', 'B']] Any number of accidentals can be used as prefix to augment or d...
[ "def", "to_chords", "(", "progression", ",", "key", "=", "'C'", ")", ":", "if", "type", "(", "progression", ")", "==", "str", ":", "progression", "=", "[", "progression", "]", "result", "=", "[", "]", "for", "chord", "in", "progression", ":", "# strip ...
Convert a list of chord functions or a string to a list of chords. Examples: >>> to_chords(['I', 'V7']) [['C', 'E', 'G'], ['G', 'B', 'D', 'F']] >>> to_chords('I7') [['C', 'E', 'G', 'B']] Any number of accidentals can be used as prefix to augment or diminish; for example: bIV or #I. ...
[ "Convert", "a", "list", "of", "chord", "functions", "or", "a", "string", "to", "a", "list", "of", "chords", "." ]
python
train
GPflow/GPflow
gpflow/kernels.py
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/kernels.py#L627-L638
def _J(self, theta): """ Implements the order dependent family of functions defined in equations 4 to 7 in the reference paper. """ if self.order == 0: return np.pi - theta elif self.order == 1: return tf.sin(theta) + (np.pi - theta) * tf.cos(theta...
[ "def", "_J", "(", "self", ",", "theta", ")", ":", "if", "self", ".", "order", "==", "0", ":", "return", "np", ".", "pi", "-", "theta", "elif", "self", ".", "order", "==", "1", ":", "return", "tf", ".", "sin", "(", "theta", ")", "+", "(", "np"...
Implements the order dependent family of functions defined in equations 4 to 7 in the reference paper.
[ "Implements", "the", "order", "dependent", "family", "of", "functions", "defined", "in", "equations", "4", "to", "7", "in", "the", "reference", "paper", "." ]
python
train
Parquery/sphinx-icontract
sphinx_icontract/__init__.py
https://github.com/Parquery/sphinx-icontract/blob/92918f23a8ea1873112e9b7446c64cd6f12ee04b/sphinx_icontract/__init__.py#L403-L412
def _format_invariants(invariants: List[icontract._Contract]) -> List[str]: """Format invariants as reST.""" if not invariants: return [] result = [":establishes:"] # type: List[str] for invariant in invariants: result.append(" * {}".format(_format_contract(contract=invariant))) ...
[ "def", "_format_invariants", "(", "invariants", ":", "List", "[", "icontract", ".", "_Contract", "]", ")", "->", "List", "[", "str", "]", ":", "if", "not", "invariants", ":", "return", "[", "]", "result", "=", "[", "\":establishes:\"", "]", "# type: List[s...
Format invariants as reST.
[ "Format", "invariants", "as", "reST", "." ]
python
train
econ-ark/HARK
HARK/ConsumptionSaving/ConsGenIncProcessModel.py
https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L1020-L1039
def installRetirementFunc(self): ''' Installs a special pLvlNextFunc representing retirement in the correct element of self.pLvlNextFunc. Draws on the attributes T_retire and pLvlNextFuncRet. If T_retire is zero or pLvlNextFuncRet does not exist, this method does nothing. Shou...
[ "def", "installRetirementFunc", "(", "self", ")", ":", "if", "(", "not", "hasattr", "(", "self", ",", "'pLvlNextFuncRet'", ")", ")", "or", "self", ".", "T_retire", "==", "0", ":", "return", "t", "=", "self", ".", "T_retire", "self", ".", "pLvlNextFunc", ...
Installs a special pLvlNextFunc representing retirement in the correct element of self.pLvlNextFunc. Draws on the attributes T_retire and pLvlNextFuncRet. If T_retire is zero or pLvlNextFuncRet does not exist, this method does nothing. Should only be called from within the method upda...
[ "Installs", "a", "special", "pLvlNextFunc", "representing", "retirement", "in", "the", "correct", "element", "of", "self", ".", "pLvlNextFunc", ".", "Draws", "on", "the", "attributes", "T_retire", "and", "pLvlNextFuncRet", ".", "If", "T_retire", "is", "zero", "o...
python
train
saltstack/salt
salt/output/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/__init__.py#L201-L205
def out_format(data, out, opts=None, **kwargs): ''' Return the formatted outputter string for the passed data ''' return try_printout(data, out, opts, **kwargs)
[ "def", "out_format", "(", "data", ",", "out", ",", "opts", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "try_printout", "(", "data", ",", "out", ",", "opts", ",", "*", "*", "kwargs", ")" ]
Return the formatted outputter string for the passed data
[ "Return", "the", "formatted", "outputter", "string", "for", "the", "passed", "data" ]
python
train
ev3dev/ev3dev-lang-python
ev3dev2/display.py
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/display.py#L325-L333
def line(self, clear_screen=True, x1=10, y1=10, x2=50, y2=50, line_color='black', width=1): """ Draw a line from (x1, y1) to (x2, y2) """ if clear_screen: self.clear() return self.draw.line((x1, y1, x2, y2), fill=line_color, width=width)
[ "def", "line", "(", "self", ",", "clear_screen", "=", "True", ",", "x1", "=", "10", ",", "y1", "=", "10", ",", "x2", "=", "50", ",", "y2", "=", "50", ",", "line_color", "=", "'black'", ",", "width", "=", "1", ")", ":", "if", "clear_screen", ":"...
Draw a line from (x1, y1) to (x2, y2)
[ "Draw", "a", "line", "from", "(", "x1", "y1", ")", "to", "(", "x2", "y2", ")" ]
python
train
mpg-age-bioinformatics/AGEpy
AGEpy/kegg.py
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/kegg.py#L126-L147
def idsKEGG(organism): """ Uses KEGG to retrieve all ids for a given KEGG organism :param organism: an organism as listed in organismsKEGG() :returns: a Pandas dataframe of with 'gene_name' and 'KEGGid'. """ ORG=urlopen("http://rest.kegg.jp/list/"+organism).read() ORG=ORG.split("\n") ...
[ "def", "idsKEGG", "(", "organism", ")", ":", "ORG", "=", "urlopen", "(", "\"http://rest.kegg.jp/list/\"", "+", "organism", ")", ".", "read", "(", ")", "ORG", "=", "ORG", ".", "split", "(", "\"\\n\"", ")", "final", "=", "[", "]", "for", "k", "in", "OR...
Uses KEGG to retrieve all ids for a given KEGG organism :param organism: an organism as listed in organismsKEGG() :returns: a Pandas dataframe of with 'gene_name' and 'KEGGid'.
[ "Uses", "KEGG", "to", "retrieve", "all", "ids", "for", "a", "given", "KEGG", "organism" ]
python
train
OpenKMIP/PyKMIP
kmip/core/objects.py
https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/objects.py#L3599-L3619
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the RevocationReason object to a stream. Args: ostream (Stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. ...
[ "def", "write", "(", "self", ",", "ostream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "tstream", "=", "BytearrayStream", "(", ")", "self", ".", "revocation_code", ".", "write", "(", "tstream", ",", "kmip_version", "...
Write the data encoding the RevocationReason object to a stream. Args: ostream (Stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP ...
[ "Write", "the", "data", "encoding", "the", "RevocationReason", "object", "to", "a", "stream", "." ]
python
test
tensorlayer/tensorlayer
tensorlayer/logging/tl_logging.py
https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/logging/tl_logging.py#L163-L176
def log_every_n(level, msg, n, *args): """Log 'msg % args' at level 'level' once per 'n' times. Logs the 1st call, (N+1)st call, (2N+1)st call, etc. Not threadsafe. Args: level: The level at which to log. msg: The message to be logged. n: The number of times this should be called before i...
[ "def", "log_every_n", "(", "level", ",", "msg", ",", "n", ",", "*", "args", ")", ":", "count", "=", "_GetNextLogCountPerToken", "(", "_GetFileAndLine", "(", ")", ")", "log_if", "(", "level", ",", "msg", ",", "not", "(", "count", "%", "n", ")", ",", ...
Log 'msg % args' at level 'level' once per 'n' times. Logs the 1st call, (N+1)st call, (2N+1)st call, etc. Not threadsafe. Args: level: The level at which to log. msg: The message to be logged. n: The number of times this should be called before it is logged. *args: The args to be substit...
[ "Log", "msg", "%", "args", "at", "level", "level", "once", "per", "n", "times", "." ]
python
valid
ubernostrum/django-registration
src/django_registration/backends/activation/views.py
https://github.com/ubernostrum/django-registration/blob/cf10b13423669346a1f4cfaa31aae0b42856b416/src/django_registration/backends/activation/views.py#L136-L160
def validate_key(self, activation_key): """ Verify that the activation key is valid and within the permitted activation time window, returning the username if valid or raising ``ActivationError`` if not. """ try: username = signing.loads( acti...
[ "def", "validate_key", "(", "self", ",", "activation_key", ")", ":", "try", ":", "username", "=", "signing", ".", "loads", "(", "activation_key", ",", "salt", "=", "REGISTRATION_SALT", ",", "max_age", "=", "settings", ".", "ACCOUNT_ACTIVATION_DAYS", "*", "8640...
Verify that the activation key is valid and within the permitted activation time window, returning the username if valid or raising ``ActivationError`` if not.
[ "Verify", "that", "the", "activation", "key", "is", "valid", "and", "within", "the", "permitted", "activation", "time", "window", "returning", "the", "username", "if", "valid", "or", "raising", "ActivationError", "if", "not", "." ]
python
train
fabioz/PyDev.Debugger
pydevd.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd.py#L1667-L1692
def _exec(self, is_module, entry_point_fn, module_name, file, globals, locals): ''' This function should have frames tracked by unhandled exceptions (the `_exec` name is important). ''' if not is_module: pydev_imports.execfile(file, globals, locals) # execute the script ...
[ "def", "_exec", "(", "self", ",", "is_module", ",", "entry_point_fn", ",", "module_name", ",", "file", ",", "globals", ",", "locals", ")", ":", "if", "not", "is_module", ":", "pydev_imports", ".", "execfile", "(", "file", ",", "globals", ",", "locals", "...
This function should have frames tracked by unhandled exceptions (the `_exec` name is important).
[ "This", "function", "should", "have", "frames", "tracked", "by", "unhandled", "exceptions", "(", "the", "_exec", "name", "is", "important", ")", "." ]
python
train
jilljenn/tryalgo
tryalgo/rectangles_from_points.py
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/rectangles_from_points.py#L8-L29
def rectangles_from_points(S): """How many rectangles can be formed from a set of points :param S: list of points, as coordinate pairs :returns: the number of rectangles :complexity: :math:`O(n^2)` """ answ = 0 pairs = {} for j in range(len(S)): for i in range(j): px...
[ "def", "rectangles_from_points", "(", "S", ")", ":", "answ", "=", "0", "pairs", "=", "{", "}", "for", "j", "in", "range", "(", "len", "(", "S", ")", ")", ":", "for", "i", "in", "range", "(", "j", ")", ":", "px", ",", "py", "=", "S", "[", "i...
How many rectangles can be formed from a set of points :param S: list of points, as coordinate pairs :returns: the number of rectangles :complexity: :math:`O(n^2)`
[ "How", "many", "rectangles", "can", "be", "formed", "from", "a", "set", "of", "points" ]
python
train
jmgilman/Neolib
neolib/pyamf/remoting/client/__init__.py
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/client/__init__.py#L370-L390
def execute_single(self, request): """ Builds, sends and handles the response to a single request, returning the response. """ if self.logger: self.logger.debug('Executing single request: %s', request) self.removeRequest(request) body = remoting.enco...
[ "def", "execute_single", "(", "self", ",", "request", ")", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "'Executing single request: %s'", ",", "request", ")", "self", ".", "removeRequest", "(", "request", ")", "body", "=...
Builds, sends and handles the response to a single request, returning the response.
[ "Builds", "sends", "and", "handles", "the", "response", "to", "a", "single", "request", "returning", "the", "response", "." ]
python
train
scot-dev/scot
scot/connectivity.py
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L402-L418
def GDTF(self): """Generalized directed transfer function. .. math:: \mathrm{GPDC}_{ij}(f) = \\frac{\sigma_j |H_{ij}(f)|} {\sqrt{H_{i:}(f) \mathrm{diag}(\mathbf{C}) H_{i:}'(f)}} References ---------- L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear ...
[ "def", "GDTF", "(", "self", ")", ":", "H", "=", "self", ".", "H", "(", ")", "tmp", "=", "H", "/", "np", ".", "sqrt", "(", "np", ".", "einsum", "(", "'ia..., aa..., ia..., j... ->ij...'", ",", "H", ".", "conj", "(", ")", ",", "self", ".", "c", "...
Generalized directed transfer function. .. math:: \mathrm{GPDC}_{ij}(f) = \\frac{\sigma_j |H_{ij}(f)|} {\sqrt{H_{i:}(f) \mathrm{diag}(\mathbf{C}) H_{i:}'(f)}} References ---------- L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear multivariate processes: ...
[ "Generalized", "directed", "transfer", "function", "." ]
python
train
rbuffat/pyepw
pyepw/epw.py
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L3022-L3042
def dbmax05years(self, value=None): """ Corresponds to IDD Field `dbmax05years` 5-year return period values for maximum extreme dry-bulb temperature Args: value (float): value for IDD Field `dbmax05years` Unit: C if `value` is None it will not be che...
[ "def", "dbmax05years", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type f...
Corresponds to IDD Field `dbmax05years` 5-year return period values for maximum extreme dry-bulb temperature Args: value (float): value for IDD Field `dbmax05years` Unit: C if `value` is None it will not be checked against the specification an...
[ "Corresponds", "to", "IDD", "Field", "dbmax05years", "5", "-", "year", "return", "period", "values", "for", "maximum", "extreme", "dry", "-", "bulb", "temperature" ]
python
train
saltstack/salt
salt/states/ssh_known_hosts.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ssh_known_hosts.py#L194-L245
def absent(name, user=None, config=None): ''' Verifies that the specified host is not known by the given user name The host name Note that only single host names are supported. If foo.example.com and bar.example.com are the same machine and you need to exclude both, you wil...
[ "def", "absent", "(", "name", ",", "user", "=", "None", ",", "config", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "if", "not", ...
Verifies that the specified host is not known by the given user name The host name Note that only single host names are supported. If foo.example.com and bar.example.com are the same machine and you need to exclude both, you will need one Salt state for each. user The ...
[ "Verifies", "that", "the", "specified", "host", "is", "not", "known", "by", "the", "given", "user" ]
python
train
nilp0inter/cpe
cpe/cpe.py
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe.py#L410-L431
def _get_attribute_components(self, att): """ Returns the component list of input attribute. :param string att: Attribute name to get :returns: List of Component objects of the attribute in CPE Name :rtype: list :exception: ValueError - invalid attribute name """...
[ "def", "_get_attribute_components", "(", "self", ",", "att", ")", ":", "lc", "=", "[", "]", "if", "not", "CPEComponent", ".", "is_valid_attribute", "(", "att", ")", ":", "errmsg", "=", "\"Invalid attribute name '{0}' is not exist\"", ".", "format", "(", "att", ...
Returns the component list of input attribute. :param string att: Attribute name to get :returns: List of Component objects of the attribute in CPE Name :rtype: list :exception: ValueError - invalid attribute name
[ "Returns", "the", "component", "list", "of", "input", "attribute", "." ]
python
train
Neurita/boyle
boyle/files/names.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/names.py#L357-L377
def ux_file_len(filepath): """Returns the length of the file using the 'wc' GNU command Parameters ---------- filepath: str Returns ------- float """ p = subprocess.Popen(['wc', '-l', filepath], stdout=subprocess.PIPE, stderr=subprocess.PIPE) result, er...
[ "def", "ux_file_len", "(", "filepath", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "'wc'", ",", "'-l'", ",", "filepath", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "result", "...
Returns the length of the file using the 'wc' GNU command Parameters ---------- filepath: str Returns ------- float
[ "Returns", "the", "length", "of", "the", "file", "using", "the", "wc", "GNU", "command" ]
python
valid
senaite/senaite.core
bika/lims/content/analysisrequest.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/analysisrequest.py#L1595-L1616
def getPrinted(self): """ returns "0", "1" or "2" to indicate Printed state. 0 -> Never printed. 1 -> Printed after last publish 2 -> Printed but republished afterwards. """ workflow = getToolByName(self, 'portal_workflow') review_state = workflow.getI...
[ "def", "getPrinted", "(", "self", ")", ":", "workflow", "=", "getToolByName", "(", "self", ",", "'portal_workflow'", ")", "review_state", "=", "workflow", ".", "getInfoFor", "(", "self", ",", "'review_state'", ",", "''", ")", "if", "review_state", "not", "in...
returns "0", "1" or "2" to indicate Printed state. 0 -> Never printed. 1 -> Printed after last publish 2 -> Printed but republished afterwards.
[ "returns", "0", "1", "or", "2", "to", "indicate", "Printed", "state", ".", "0", "-", ">", "Never", "printed", ".", "1", "-", ">", "Printed", "after", "last", "publish", "2", "-", ">", "Printed", "but", "republished", "afterwards", "." ]
python
train
numenta/htmresearch
htmresearch/algorithms/TM.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1036-L1079
def computePhase2(self, doLearn=False): """ This is the phase 2 of learning, inference and multistep prediction. During this phase, all the cell with lateral support have their predictedState turned on and the firing segments are queued up for updates. Parameters: ------------------------------...
[ "def", "computePhase2", "(", "self", ",", "doLearn", "=", "False", ")", ":", "# Phase 2: compute predicted state for each cell", "# - if a segment has enough horizontal connections firing because of", "# bottomUpInput, it's set to be predicting, and we queue up the segment", "# for rei...
This is the phase 2 of learning, inference and multistep prediction. During this phase, all the cell with lateral support have their predictedState turned on and the firing segments are queued up for updates. Parameters: -------------------------------------------- doLearn: Boolean flag to que...
[ "This", "is", "the", "phase", "2", "of", "learning", "inference", "and", "multistep", "prediction", ".", "During", "this", "phase", "all", "the", "cell", "with", "lateral", "support", "have", "their", "predictedState", "turned", "on", "and", "the", "firing", ...
python
train
mgedmin/findimports
findimports.py
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L417-L433
def parsePathname(self, pathname): """Parse one or more source files. ``pathname`` may be a file name or a directory name. """ if os.path.isdir(pathname): for root, dirs, files in os.walk(pathname): dirs.sort() files.sort() for...
[ "def", "parsePathname", "(", "self", ",", "pathname", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "pathname", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "pathname", ")", ":", "dirs", ".", "sort", "...
Parse one or more source files. ``pathname`` may be a file name or a directory name.
[ "Parse", "one", "or", "more", "source", "files", "." ]
python
train
TheClimateCorporation/properscoring
properscoring/_brier.py
https://github.com/TheClimateCorporation/properscoring/blob/1ca13dcbc1abf53d07474b74fbe3567fd4045668/properscoring/_brier.py#L93-L190
def threshold_brier_score(observations, forecasts, threshold, issorted=False, axis=-1): """ Calculate the Brier scores of an ensemble for exceeding given thresholds. According to the threshold decomposition of CRPS, the resulting Brier scores can thus be summed along the last ...
[ "def", "threshold_brier_score", "(", "observations", ",", "forecasts", ",", "threshold", ",", "issorted", "=", "False", ",", "axis", "=", "-", "1", ")", ":", "observations", "=", "np", ".", "asarray", "(", "observations", ")", "threshold", "=", "np", ".", ...
Calculate the Brier scores of an ensemble for exceeding given thresholds. According to the threshold decomposition of CRPS, the resulting Brier scores can thus be summed along the last axis to calculate CRPS, as .. math:: CRPS(F, x) = \int_z BS(F(z), H(z - x)) dz where $F(x) = \int_{z \leq x}...
[ "Calculate", "the", "Brier", "scores", "of", "an", "ensemble", "for", "exceeding", "given", "thresholds", "." ]
python
train
Amsterdam/objectstore
objectstore/databasedumps.py
https://github.com/Amsterdam/objectstore/blob/15852e8a3f159e4e6eb018866df0a84feb2c7f68/objectstore/databasedumps.py#L94-L112
def remove_old_dumps(connection, container: str, days=None): """Remove dumps older than x days """ if not days: return if days < 20: LOG.error('A minimum of 20 backups is stored') return options = return_file_objects(connection, container) for dt, o_info in options: ...
[ "def", "remove_old_dumps", "(", "connection", ",", "container", ":", "str", ",", "days", "=", "None", ")", ":", "if", "not", "days", ":", "return", "if", "days", "<", "20", ":", "LOG", ".", "error", "(", "'A minimum of 20 backups is stored'", ")", "return"...
Remove dumps older than x days
[ "Remove", "dumps", "older", "than", "x", "days" ]
python
train
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/thread.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1985-L1999
def close_thread_handles(self): """ Closes all open handles to threads in the snapshot. """ for aThread in self.iter_threads(): try: aThread.close_handle() except Exception: try: e = sys.exc_info()[1] ...
[ "def", "close_thread_handles", "(", "self", ")", ":", "for", "aThread", "in", "self", ".", "iter_threads", "(", ")", ":", "try", ":", "aThread", ".", "close_handle", "(", ")", "except", "Exception", ":", "try", ":", "e", "=", "sys", ".", "exc_info", "(...
Closes all open handles to threads in the snapshot.
[ "Closes", "all", "open", "handles", "to", "threads", "in", "the", "snapshot", "." ]
python
train
jbloomlab/phydms
phydmslib/models.py
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2208-L2211
def mu(self, value): """Set new `mu` value.""" for k in range(self.ncats): self._models[k].updateParams({'mu':value})
[ "def", "mu", "(", "self", ",", "value", ")", ":", "for", "k", "in", "range", "(", "self", ".", "ncats", ")", ":", "self", ".", "_models", "[", "k", "]", ".", "updateParams", "(", "{", "'mu'", ":", "value", "}", ")" ]
Set new `mu` value.
[ "Set", "new", "mu", "value", "." ]
python
train
watson-developer-cloud/python-sdk
ibm_watson/discovery_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L7228-L7241
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'position') and self.position is not None: _dict['position'] = self.position if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_i...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'position'", ")", "and", "self", ".", "position", "is", "not", "None", ":", "_dict", "[", "'position'", "]", "=", "self", ".", "position", "if", "...
Return a json dictionary representing this model.
[ "Return", "a", "json", "dictionary", "representing", "this", "model", "." ]
python
train
genialis/resolwe
resolwe/flow/managers/workload_connectors/local.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/managers/workload_connectors/local.py#L21-L37
def submit(self, data, runtime_dir, argv): """Run process locally. For details, see :meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`. """ logger.debug(__( "Connector '{}' running for Data with id {} ({}).", self.__class__.__mod...
[ "def", "submit", "(", "self", ",", "data", ",", "runtime_dir", ",", "argv", ")", ":", "logger", ".", "debug", "(", "__", "(", "\"Connector '{}' running for Data with id {} ({}).\"", ",", "self", ".", "__class__", ".", "__module__", ",", "data", ".", "id", ",...
Run process locally. For details, see :meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
[ "Run", "process", "locally", "." ]
python
train
pulumi/pulumi
sdk/python/lib/pulumi/config.py
https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/config.py#L161-L175
def require_float(self, key: str) -> float: """ Returns a configuration value, as a float, by its given key. If it doesn't exist, or the configuration value is not a legal number, an error is thrown. :param str key: The requested configuration key. :return: The configuration ke...
[ "def", "require_float", "(", "self", ",", "key", ":", "str", ")", "->", "float", ":", "v", "=", "self", ".", "get_float", "(", "key", ")", "if", "v", "is", "None", ":", "raise", "ConfigMissingError", "(", "self", ".", "full_key", "(", "key", ")", "...
Returns a configuration value, as a float, by its given key. If it doesn't exist, or the configuration value is not a legal number, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's value. :rtype: float :raises ConfigMissingEr...
[ "Returns", "a", "configuration", "value", "as", "a", "float", "by", "its", "given", "key", ".", "If", "it", "doesn", "t", "exist", "or", "the", "configuration", "value", "is", "not", "a", "legal", "number", "an", "error", "is", "thrown", "." ]
python
train
jeffh/sniffer
sniffer/scent_picker.py
https://github.com/jeffh/sniffer/blob/8e4c3e77743aef08109ea0225b4a6536d4e60270/sniffer/scent_picker.py#L94-L106
def exec_from_dir(dirname=None, scent="scent.py"): """Runs the scent.py file from the given directory (cwd if None given). Returns module if loaded a scent, None otherwise. """ if dirname is None: dirname = os.getcwd() files = os.listdir(dirname) if scent not in files: return N...
[ "def", "exec_from_dir", "(", "dirname", "=", "None", ",", "scent", "=", "\"scent.py\"", ")", ":", "if", "dirname", "is", "None", ":", "dirname", "=", "os", ".", "getcwd", "(", ")", "files", "=", "os", ".", "listdir", "(", "dirname", ")", "if", "scent...
Runs the scent.py file from the given directory (cwd if None given). Returns module if loaded a scent, None otherwise.
[ "Runs", "the", "scent", ".", "py", "file", "from", "the", "given", "directory", "(", "cwd", "if", "None", "given", ")", "." ]
python
train
qacafe/cdrouter.py
cdrouter/jobs.py
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/jobs.py#L188-L204
def bulk_launch(self, jobs=None, filter=None, all=False): # pylint: disable=redefined-builtin """Bulk launch a set of jobs. :param jobs: :class:`jobs.Job <jobs.Job>` list :param filter: (optional) Filters to apply as a string list. :param all: (optional) Apply to all if bool `True`. ...
[ "def", "bulk_launch", "(", "self", ",", "jobs", "=", "None", ",", "filter", "=", "None", ",", "all", "=", "False", ")", ":", "# pylint: disable=redefined-builtin", "json", "=", "None", "if", "jobs", "is", "not", "None", ":", "schema", "=", "JobSchema", "...
Bulk launch a set of jobs. :param jobs: :class:`jobs.Job <jobs.Job>` list :param filter: (optional) Filters to apply as a string list. :param all: (optional) Apply to all if bool `True`.
[ "Bulk", "launch", "a", "set", "of", "jobs", "." ]
python
train
sourcesimian/pyPlugin
pyplugin/pluginloader.py
https://github.com/sourcesimian/pyPlugin/blob/6a7c31e40b30a418865a3b2de19291da341ddcc8/pyplugin/pluginloader.py#L93-L98
def __push_import_modules(self): """ Add custom <import_modules> to the import namespace under its own __name__. """ for module in self.__import_modules: sys.modules[module.__name__] = module
[ "def", "__push_import_modules", "(", "self", ")", ":", "for", "module", "in", "self", ".", "__import_modules", ":", "sys", ".", "modules", "[", "module", ".", "__name__", "]", "=", "module" ]
Add custom <import_modules> to the import namespace under its own __name__.
[ "Add", "custom", "<import_modules", ">", "to", "the", "import", "namespace", "under", "its", "own", "__name__", "." ]
python
train
upsight/doctor
doctor/schema.py
https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L89-L109
def resolve_remote(self, uri): """Add support to load YAML files. This will attempt to load a YAML file first, and then go back to the default behavior. :param str uri: the URI to resolve :returns: the retrieved document """ if uri.startswith('file://'): ...
[ "def", "resolve_remote", "(", "self", ",", "uri", ")", ":", "if", "uri", ".", "startswith", "(", "'file://'", ")", ":", "try", ":", "path", "=", "uri", "[", "7", ":", "]", "with", "open", "(", "path", ",", "'r'", ")", "as", "schema_file", ":", "r...
Add support to load YAML files. This will attempt to load a YAML file first, and then go back to the default behavior. :param str uri: the URI to resolve :returns: the retrieved document
[ "Add", "support", "to", "load", "YAML", "files", "." ]
python
train
BlueBrain/NeuroM
neurom/stats.py
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/stats.py#L94-L110
def fit(data, distribution='norm'): '''Calculate the parameters of a fit of a distribution to a data set Parameters: data: array of data points to be fitted Options: distribution (str): type of distribution to fit. Default 'norm'. Returns: FitResults object with fitted paramet...
[ "def", "fit", "(", "data", ",", "distribution", "=", "'norm'", ")", ":", "params", "=", "getattr", "(", "_st", ",", "distribution", ")", ".", "fit", "(", "data", ")", "return", "FitResults", "(", "params", ",", "_st", ".", "kstest", "(", "data", ",",...
Calculate the parameters of a fit of a distribution to a data set Parameters: data: array of data points to be fitted Options: distribution (str): type of distribution to fit. Default 'norm'. Returns: FitResults object with fitted parameters, errors and distribution type Note...
[ "Calculate", "the", "parameters", "of", "a", "fit", "of", "a", "distribution", "to", "a", "data", "set" ]
python
train
jart/fabulous
fabulous/rotating_cube.py
https://github.com/jart/fabulous/blob/19903cf0a980b82f5928c3bec1f28b6bdd3785bd/fabulous/rotating_cube.py#L52-L83
def line(self, x0, y0, x1, y1, c='*'): r"""Draws a line Who would have thought this would be so complicated? Thanks again Wikipedia_ <3 .. _Wikipedia: http://en.wikipedia.org/wiki/Bresenham's_line_algorithm """ steep = abs(y1 - y0) > abs(x1 - x0) if steep: ...
[ "def", "line", "(", "self", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "c", "=", "'*'", ")", ":", "steep", "=", "abs", "(", "y1", "-", "y0", ")", ">", "abs", "(", "x1", "-", "x0", ")", "if", "steep", ":", "(", "x0", ",", "y0", ")"...
r"""Draws a line Who would have thought this would be so complicated? Thanks again Wikipedia_ <3 .. _Wikipedia: http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
[ "r", "Draws", "a", "line" ]
python
train
dossier/dossier.store
dossier/store/store.py
https://github.com/dossier/dossier.store/blob/b22ffe2470bba9fcc98a30cb55b437bfa1521e7f/dossier/store/store.py#L151-L167
def get_many(self, content_id_list): '''Yield (content_id, data) tuples for ids in list. As with :meth:`get`, if a content_id in the list is missing, then it is yielded with a data value of `None`. :type content_id_list: list<str> :rtype: yields tuple(str, :class:`dossier.fc.Fe...
[ "def", "get_many", "(", "self", ",", "content_id_list", ")", ":", "content_id_keys", "=", "[", "tuplify", "(", "x", ")", "for", "x", "in", "content_id_list", "]", "for", "row", "in", "self", ".", "kvl", ".", "get", "(", "self", ".", "TABLE", ",", "*"...
Yield (content_id, data) tuples for ids in list. As with :meth:`get`, if a content_id in the list is missing, then it is yielded with a data value of `None`. :type content_id_list: list<str> :rtype: yields tuple(str, :class:`dossier.fc.FeatureCollection`)
[ "Yield", "(", "content_id", "data", ")", "tuples", "for", "ids", "in", "list", "." ]
python
test
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L115-L124
def set_terminate_listeners(stream): """Die on SIGTERM or SIGINT""" def stop(signum, frame): terminate(stream.listener) # Installs signal handlers for handling SIGINT and SIGTERM # gracefully. signal.signal(signal.SIGINT, stop) signal.signal(signal.SIGTERM, stop)
[ "def", "set_terminate_listeners", "(", "stream", ")", ":", "def", "stop", "(", "signum", ",", "frame", ")", ":", "terminate", "(", "stream", ".", "listener", ")", "# Installs signal handlers for handling SIGINT and SIGTERM", "# gracefully.", "signal", ".", "signal", ...
Die on SIGTERM or SIGINT
[ "Die", "on", "SIGTERM", "or", "SIGINT" ]
python
train
JoelBender/bacpypes
py25/bacpypes/service/object.py
https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/service/object.py#L33-L94
def do_ReadPropertyRequest(self, apdu): """Return the value of some property of one of our objects.""" if _debug: ReadWritePropertyServices._debug("do_ReadPropertyRequest %r", apdu) # extract the object identifier objId = apdu.objectIdentifier # check for wildcard if (o...
[ "def", "do_ReadPropertyRequest", "(", "self", ",", "apdu", ")", ":", "if", "_debug", ":", "ReadWritePropertyServices", ".", "_debug", "(", "\"do_ReadPropertyRequest %r\"", ",", "apdu", ")", "# extract the object identifier", "objId", "=", "apdu", ".", "objectIdentifie...
Return the value of some property of one of our objects.
[ "Return", "the", "value", "of", "some", "property", "of", "one", "of", "our", "objects", "." ]
python
train
saltstack/salt
salt/modules/postgres.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1738-L1760
def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' p...
[ "def", "user_remove", "(", "username", ",", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "runas", "=", "None", ")", ":", "return", "_role_remove", "(", ...
Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username'
[ "Removes", "a", "user", "from", "the", "Postgres", "server", "." ]
python
train
optimizely/python-sdk
optimizely/helpers/event_tag_utils.py
https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/helpers/event_tag_utils.py#L43-L123
def get_numeric_value(event_tags, logger=None): """ A smart getter of the numeric value from the event tags. Args: event_tags: A dictionary of event tags. logger: Optional logger. Returns: A float numeric metric value is returned when the provided numeric metric value is in the followi...
[ "def", "get_numeric_value", "(", "event_tags", ",", "logger", "=", "None", ")", ":", "logger_message_debug", "=", "None", "numeric_metric_value", "=", "None", "if", "event_tags", "is", "None", ":", "logger_message_debug", "=", "'Event tags is undefined.'", "elif", "...
A smart getter of the numeric value from the event tags. Args: event_tags: A dictionary of event tags. logger: Optional logger. Returns: A float numeric metric value is returned when the provided numeric metric value is in the following format: - A string (properly formatted, e.g...
[ "A", "smart", "getter", "of", "the", "numeric", "value", "from", "the", "event", "tags", "." ]
python
train
briwilcox/Concurrent-Pandas
concurrentpandas.py
https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L277-L284
def set_source_yahoo_options(self): """ Set data source to yahoo finance, specifically to download financial options data """ self.data_worker = data_worker self.worker_args = {"function": Options, "input": self.input_queue, "output": self.output_map, ...
[ "def", "set_source_yahoo_options", "(", "self", ")", ":", "self", ".", "data_worker", "=", "data_worker", "self", ".", "worker_args", "=", "{", "\"function\"", ":", "Options", ",", "\"input\"", ":", "self", ".", "input_queue", ",", "\"output\"", ":", "self", ...
Set data source to yahoo finance, specifically to download financial options data
[ "Set", "data", "source", "to", "yahoo", "finance", "specifically", "to", "download", "financial", "options", "data" ]
python
train
MillionIntegrals/vel
vel/rl/algo/policy_gradient/a2c.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/a2c.py#L41-L71
def calculate_gradient(self, batch_info, device, model, rollout): """ Calculate loss of the supplied rollout """ evaluator = model.evaluate(rollout) # Use evaluator interface to get the what we are interested in from the model advantages = evaluator.get('rollout:advantages') ret...
[ "def", "calculate_gradient", "(", "self", ",", "batch_info", ",", "device", ",", "model", ",", "rollout", ")", ":", "evaluator", "=", "model", ".", "evaluate", "(", "rollout", ")", "# Use evaluator interface to get the what we are interested in from the model", "advanta...
Calculate loss of the supplied rollout
[ "Calculate", "loss", "of", "the", "supplied", "rollout" ]
python
train
projectshift/shift-schema
shiftschema/validators/url.py
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/validators/url.py#L68-L118
def regex(self, protocols, localhost=True): """ URL Validation regex Based on regular expression by Diego Perini (@dperini) and provided under MIT License: https://gist.github.com/dperini/729294 :return: """ p = r"^" # protocol p += r"(?:(?:(?:{})...
[ "def", "regex", "(", "self", ",", "protocols", ",", "localhost", "=", "True", ")", ":", "p", "=", "r\"^\"", "# protocol", "p", "+=", "r\"(?:(?:(?:{}):)?//)\"", ".", "format", "(", "'|'", ".", "join", "(", "protocols", ")", ")", "# basic auth (optional)", "...
URL Validation regex Based on regular expression by Diego Perini (@dperini) and provided under MIT License: https://gist.github.com/dperini/729294 :return:
[ "URL", "Validation", "regex", "Based", "on", "regular", "expression", "by", "Diego", "Perini", "(" ]
python
train
mikedh/trimesh
trimesh/ray/ray_triangle.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/ray/ray_triangle.py#L143-L261
def ray_triangle_id(triangles, ray_origins, ray_directions, triangles_normal=None, tree=None, multiple_hits=True): """ Find the intersections between a group of triangles and rays Parameters ------------...
[ "def", "ray_triangle_id", "(", "triangles", ",", "ray_origins", ",", "ray_directions", ",", "triangles_normal", "=", "None", ",", "tree", "=", "None", ",", "multiple_hits", "=", "True", ")", ":", "triangles", "=", "np", ".", "asanyarray", "(", "triangles", "...
Find the intersections between a group of triangles and rays Parameters ------------- triangles : (n, 3, 3) float Triangles in space ray_origins : (m, 3) float Ray origin points ray_directions : (m, 3) float Ray direction vectors triangles_normal : (n, 3) float Normal ve...
[ "Find", "the", "intersections", "between", "a", "group", "of", "triangles", "and", "rays" ]
python
train
googleapis/google-cloud-python
storage/google/cloud/storage/blob.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L200-L213
def chunk_size(self, value): """Set the blob's default chunk size. :type value: int :param value: (Optional) The current blob's chunk size, if it is set. :raises: :class:`ValueError` if ``value`` is not ``None`` and is not a multiple of 256 KB. """ if v...
[ "def", "chunk_size", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", "and", "value", ">", "0", "and", "value", "%", "self", ".", "_CHUNK_SIZE_MULTIPLE", "!=", "0", ":", "raise", "ValueError", "(", "\"Chunk size must be a multiple of ...
Set the blob's default chunk size. :type value: int :param value: (Optional) The current blob's chunk size, if it is set. :raises: :class:`ValueError` if ``value`` is not ``None`` and is not a multiple of 256 KB.
[ "Set", "the", "blob", "s", "default", "chunk", "size", "." ]
python
train
push-things/django-th
th_twitter/my_twitter.py
https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_twitter/my_twitter.py#L204-L236
def save_data(self, trigger_id, **data): """ let's save the data :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the sa...
[ "def", "save_data", "(", "self", ",", "trigger_id", ",", "*", "*", "data", ")", ":", "status", "=", "False", "# set the title and content of the data", "title", ",", "content", "=", "super", "(", "ServiceTwitter", ",", "self", ")", ".", "save_data", "(", "tr...
let's save the data :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the save statement :rtype: boolean
[ "let", "s", "save", "the", "data" ]
python
train
markovmodel/msmtools
msmtools/flux/api.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/flux/api.py#L65-L155
def tpt(T, A, B, mu=None, qminus=None, qplus=None, rate_matrix=False): r""" Computes the A->B reactive flux using transition path theory (TPT) Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix (default) or Rate matrix (if rate_matrix=True) A : array_like ...
[ "def", "tpt", "(", "T", ",", "A", ",", "B", ",", "mu", "=", "None", ",", "qminus", "=", "None", ",", "qplus", "=", "None", ",", "rate_matrix", "=", "False", ")", ":", "import", "msmtools", ".", "analysis", "as", "msmana", "if", "len", "(", "A", ...
r""" Computes the A->B reactive flux using transition path theory (TPT) Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix (default) or Rate matrix (if rate_matrix=True) A : array_like List of integer state labels for set A B : array_like List ...
[ "r", "Computes", "the", "A", "-", ">", "B", "reactive", "flux", "using", "transition", "path", "theory", "(", "TPT", ")" ]
python
train
cjdrake/pyeda
pyeda/boolalg/expr.py
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L951-L954
def equivalent(self, other): """Return True if this expression is equivalent to other.""" f = Xor(self, self.box(other)) return f.satisfy_one() is None
[ "def", "equivalent", "(", "self", ",", "other", ")", ":", "f", "=", "Xor", "(", "self", ",", "self", ".", "box", "(", "other", ")", ")", "return", "f", ".", "satisfy_one", "(", ")", "is", "None" ]
Return True if this expression is equivalent to other.
[ "Return", "True", "if", "this", "expression", "is", "equivalent", "to", "other", "." ]
python
train
saltstack/salt
salt/modules/glanceng.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glanceng.py#L124-L137
def image_delete(auth=None, **kwargs): ''' Delete an image CLI Example: .. code-block:: bash salt '*' glanceng.image_delete name=image1 salt '*' glanceng.image_delete name=0e4febc2a5ab4f2c8f374b054162506d ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs...
[ "def", "image_delete", "(", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cloud", "=", "get_operator_cloud", "(", "auth", ")", "kwargs", "=", "_clean_kwargs", "(", "*", "*", "kwargs", ")", "return", "cloud", ".", "delete_image", "(", "*", "*...
Delete an image CLI Example: .. code-block:: bash salt '*' glanceng.image_delete name=image1 salt '*' glanceng.image_delete name=0e4febc2a5ab4f2c8f374b054162506d
[ "Delete", "an", "image" ]
python
train
thebigmunch/google-music
src/google_music/clients/mobileclient.py
https://github.com/thebigmunch/google-music/blob/d8a94dab462a1f063fbc1152187a73dc2f0e2a85/src/google_music/clients/mobileclient.py#L242-L254
def browse_stations_categories(self): """Get the categories from Browse Stations. Returns: list: Station categories that can contain subcategories. """ response = self._call( mc_calls.BrowseStationCategories ) station_categories = response.body.get('root', {}).get('subcategories', []) return stat...
[ "def", "browse_stations_categories", "(", "self", ")", ":", "response", "=", "self", ".", "_call", "(", "mc_calls", ".", "BrowseStationCategories", ")", "station_categories", "=", "response", ".", "body", ".", "get", "(", "'root'", ",", "{", "}", ")", ".", ...
Get the categories from Browse Stations. Returns: list: Station categories that can contain subcategories.
[ "Get", "the", "categories", "from", "Browse", "Stations", "." ]
python
train
HearthSim/dj-paypal
djpaypal/models/webhooks.py
https://github.com/HearthSim/dj-paypal/blob/867368f6068c2539e22d486eb7a6d2ecfb9485e0/djpaypal/models/webhooks.py#L252-L298
def webhook_handler(*event_types): """ Decorator that registers a function as a webhook handler. Usage examples: >>> # Hook a single event >>> @webhook_handler("payment.sale.completed") >>> def on_payment_received(event): >>> payment = event.get_resource() >>> print("Received payment:", payment) >>>...
[ "def", "webhook_handler", "(", "*", "event_types", ")", ":", "# First expand all wildcards and verify the event types are valid", "event_types_to_register", "=", "set", "(", ")", "for", "event_type", "in", "event_types", ":", "# Always convert to lowercase", "event_type", "="...
Decorator that registers a function as a webhook handler. Usage examples: >>> # Hook a single event >>> @webhook_handler("payment.sale.completed") >>> def on_payment_received(event): >>> payment = event.get_resource() >>> print("Received payment:", payment) >>> # Multiple events supported >>> @webhoo...
[ "Decorator", "that", "registers", "a", "function", "as", "a", "webhook", "handler", "." ]
python
valid
GiulioRossetti/dynetx
dynetx/utils/decorators.py
https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/utils/decorators.py#L62-L201
def open_file(path_arg, mode='r'): """Decorator to ensure clean opening and closing of files. Parameters ---------- path_arg : int Location of the path argument in args. Even if the argument is a named positional argument (with a default value), you must specify its index as a ...
[ "def", "open_file", "(", "path_arg", ",", "mode", "=", "'r'", ")", ":", "# Note that this decorator solves the problem when a path argument is", "# specified as a string, but it does not handle the situation when the", "# function wants to accept a default of None (and then handle it).", "...
Decorator to ensure clean opening and closing of files. Parameters ---------- path_arg : int Location of the path argument in args. Even if the argument is a named positional argument (with a default value), you must specify its index as a positional argument. mode : str ...
[ "Decorator", "to", "ensure", "clean", "opening", "and", "closing", "of", "files", "." ]
python
train
johnbywater/eventsourcing
eventsourcing/domain/model/decorators.py
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/domain/model/decorators.py#L57-L128
def mutator(arg=None): """Structures mutator functions by allowing handlers to be registered for different types of event. When the decorated function is called with an initial value and an event, it will call the handler that has been registered for that type of event. It works like singledisp...
[ "def", "mutator", "(", "arg", "=", "None", ")", ":", "domain_class", "=", "None", "def", "_mutator", "(", "func", ")", ":", "wrapped", "=", "singledispatch", "(", "func", ")", "@", "wraps", "(", "wrapped", ")", "def", "wrapper", "(", "initial", ",", ...
Structures mutator functions by allowing handlers to be registered for different types of event. When the decorated function is called with an initial value and an event, it will call the handler that has been registered for that type of event. It works like singledispatch, which it uses. The d...
[ "Structures", "mutator", "functions", "by", "allowing", "handlers", "to", "be", "registered", "for", "different", "types", "of", "event", ".", "When", "the", "decorated", "function", "is", "called", "with", "an", "initial", "value", "and", "an", "event", "it",...
python
train
linkedin/naarad
src/naarad/metrics/metric.py
https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/metric.py#L345-L356
def calculate_stats(self): """ Calculate stats with different function depending on the metric type: Data is recorded in memory for base metric type, and use calculate_base_metric_stats() Data is recorded in CSV file for other metric types, and use calculate_other_metric_stats() """ metric_type...
[ "def", "calculate_stats", "(", "self", ")", ":", "metric_type", "=", "self", ".", "metric_type", ".", "split", "(", "'-'", ")", "[", "0", "]", "if", "metric_type", "in", "naarad", ".", "naarad_imports", ".", "metric_classes", "or", "metric_type", "in", "na...
Calculate stats with different function depending on the metric type: Data is recorded in memory for base metric type, and use calculate_base_metric_stats() Data is recorded in CSV file for other metric types, and use calculate_other_metric_stats()
[ "Calculate", "stats", "with", "different", "function", "depending", "on", "the", "metric", "type", ":", "Data", "is", "recorded", "in", "memory", "for", "base", "metric", "type", "and", "use", "calculate_base_metric_stats", "()", "Data", "is", "recorded", "in", ...
python
valid
soerenwolfers/swutil
swutil/np_tools.py
https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/np_tools.py#L158-L173
def toeplitz_multiplication(a,b,v): ''' Multiply Toeplitz matrix with first row a and first column b with vector v Normal matrix multiplication would require storage and runtime O(n^2); embedding into a circulant matrix and using FFT yields O(log(n)n) ''' a = np.reshape(a,(-1)) b = np.r...
[ "def", "toeplitz_multiplication", "(", "a", ",", "b", ",", "v", ")", ":", "a", "=", "np", ".", "reshape", "(", "a", ",", "(", "-", "1", ")", ")", "b", "=", "np", ".", "reshape", "(", "b", ",", "(", "-", "1", ")", ")", "n", "=", "len", "("...
Multiply Toeplitz matrix with first row a and first column b with vector v Normal matrix multiplication would require storage and runtime O(n^2); embedding into a circulant matrix and using FFT yields O(log(n)n)
[ "Multiply", "Toeplitz", "matrix", "with", "first", "row", "a", "and", "first", "column", "b", "with", "vector", "v", "Normal", "matrix", "multiplication", "would", "require", "storage", "and", "runtime", "O", "(", "n^2", ")", ";", "embedding", "into", "a", ...
python
valid
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/ietf_netconf_notifications.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/ietf_netconf_notifications.py#L201-L210
def netconf_session_end_session_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") netconf_session_end = ET.SubElement(config, "netconf-session-end", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications") session_id = ET.SubElement(netconf_sessi...
[ "def", "netconf_session_end_session_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "netconf_session_end", "=", "ET", ".", "SubElement", "(", "config", ",", "\"netconf-session-end\"", ",", "xmln...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
python-diamond/Diamond
src/collectors/pgq/pgq.py
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/pgq/pgq.py#L62-L74
def _collect_for_instance(self, instance, connection): """Collects metrics for a named connection.""" with connection.cursor() as cursor: for queue, metrics in self.get_queue_info(instance, cursor): for name, metric in metrics.items(): self.publish('.'.joi...
[ "def", "_collect_for_instance", "(", "self", ",", "instance", ",", "connection", ")", ":", "with", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "for", "queue", ",", "metrics", "in", "self", ".", "get_queue_info", "(", "instance", ",", "curso...
Collects metrics for a named connection.
[ "Collects", "metrics", "for", "a", "named", "connection", "." ]
python
train
MillionIntegrals/vel
vel/augmentations/normalize.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/augmentations/normalize.py#L22-L24
def create(mean, std, mode='x', tags=None): """ Vel factory function """ return Normalize(mean=mean, std=std, mode=mode, tags=tags)
[ "def", "create", "(", "mean", ",", "std", ",", "mode", "=", "'x'", ",", "tags", "=", "None", ")", ":", "return", "Normalize", "(", "mean", "=", "mean", ",", "std", "=", "std", ",", "mode", "=", "mode", ",", "tags", "=", "tags", ")" ]
Vel factory function
[ "Vel", "factory", "function" ]
python
train
renatopp/liac-arff
arff.py
https://github.com/renatopp/liac-arff/blob/6771f4cdd13d0eca74d3ebbaa6290297dd0a381d/arff.py#L768-L873
def _decode(self, s, encode_nominal=False, matrix_type=DENSE): '''Do the job the ``encode``.''' # Make sure this method is idempotent self._current_line = 0 # If string, convert to a list of lines if isinstance(s, basestring): s = s.strip('\r\n ').replace('\r\n', '\...
[ "def", "_decode", "(", "self", ",", "s", ",", "encode_nominal", "=", "False", ",", "matrix_type", "=", "DENSE", ")", ":", "# Make sure this method is idempotent", "self", ".", "_current_line", "=", "0", "# If string, convert to a list of lines", "if", "isinstance", ...
Do the job the ``encode``.
[ "Do", "the", "job", "the", "encode", "." ]
python
train
uw-it-cte/uw-restclients-wheniwork
uw_wheniwork/locations.py
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/locations.py#L6-L14
def get_location(self, location_id): """ Returns location data. http://dev.wheniwork.com/#get-existing-location """ url = "/2/locations/%s" % location_id return self.location_from_json(self._get_resource(url)["location"])
[ "def", "get_location", "(", "self", ",", "location_id", ")", ":", "url", "=", "\"/2/locations/%s\"", "%", "location_id", "return", "self", ".", "location_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"location\"", "]", ")" ]
Returns location data. http://dev.wheniwork.com/#get-existing-location
[ "Returns", "location", "data", "." ]
python
valid
miquelo/resort
packages/resort/component/glassfish.py
https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/component/glassfish.py#L295-L313
def jdbc_connection_pool(self, name, res_type, ds_classname, props): """ Domain JDBC connection pool. :param str name: Resource name. :param str res_type: Resource type. :param str ds_classname: Data source class name. :param dict props: Connection pool properties. :rtype: ...
[ "def", "jdbc_connection_pool", "(", "self", ",", "name", ",", "res_type", ",", "ds_classname", ",", "props", ")", ":", "return", "JDBCConnectionPool", "(", "self", ".", "__endpoint", ",", "name", ",", "res_type", ",", "ds_classname", ",", "props", ")" ]
Domain JDBC connection pool. :param str name: Resource name. :param str res_type: Resource type. :param str ds_classname: Data source class name. :param dict props: Connection pool properties. :rtype: JDBCConnectionPool
[ "Domain", "JDBC", "connection", "pool", ".", ":", "param", "str", "name", ":", "Resource", "name", ".", ":", "param", "str", "res_type", ":", "Resource", "type", ".", ":", "param", "str", "ds_classname", ":", "Data", "source", "class", "name", ".", ":", ...
python
train
openeemeter/eeweather
eeweather/geo.py
https://github.com/openeemeter/eeweather/blob/d32b7369b26edfa3ee431c60457afeb0593123a7/eeweather/geo.py#L164-L193
def get_zcta_metadata(zcta): """ Get metadata about a ZIP Code Tabulation Area (ZCTA). Parameters ---------- zcta : str ID of ZIP Code Tabulation Area Returns ------- metadata : dict Dict of data about the ZCTA, including lat/long coordinates. """ conn = metadata_db...
[ "def", "get_zcta_metadata", "(", "zcta", ")", ":", "conn", "=", "metadata_db_connection_proxy", ".", "get_connection", "(", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "\"\"\"\n select\n *\n from\n zcta_metadat...
Get metadata about a ZIP Code Tabulation Area (ZCTA). Parameters ---------- zcta : str ID of ZIP Code Tabulation Area Returns ------- metadata : dict Dict of data about the ZCTA, including lat/long coordinates.
[ "Get", "metadata", "about", "a", "ZIP", "Code", "Tabulation", "Area", "(", "ZCTA", ")", "." ]
python
train
SiLab-Bonn/pyBAR
pybar/analysis/analysis_utils.py
https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/analysis/analysis_utils.py#L407-L462
def get_data_file_names_from_scan_base(scan_base, filter_str=['_analyzed.h5', '_interpreted.h5', '_cut.h5', '_result.h5', '_hists.h5'], sort_by_time=True, meta_data_v2=True): """ Generate a list of .h5 files which have a similar file name. Parameters ---------- scan_base : list, string List...
[ "def", "get_data_file_names_from_scan_base", "(", "scan_base", ",", "filter_str", "=", "[", "'_analyzed.h5'", ",", "'_interpreted.h5'", ",", "'_cut.h5'", ",", "'_result.h5'", ",", "'_hists.h5'", "]", ",", "sort_by_time", "=", "True", ",", "meta_data_v2", "=", "True"...
Generate a list of .h5 files which have a similar file name. Parameters ---------- scan_base : list, string List of string or string of the scan base names. The scan_base will be used to search for files containing the string. The .h5 file extension will be added automatically. filter : list, s...
[ "Generate", "a", "list", "of", ".", "h5", "files", "which", "have", "a", "similar", "file", "name", "." ]
python
train
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/setuptools/sandbox.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/sandbox.py#L70-L84
def override_temp(replacement): """ Monkey-patch tempfile.tempdir with replacement, ensuring it exists """ if not os.path.isdir(replacement): os.makedirs(replacement) saved = tempfile.tempdir tempfile.tempdir = replacement try: yield finally: tempfile.tempdir =...
[ "def", "override_temp", "(", "replacement", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "replacement", ")", ":", "os", ".", "makedirs", "(", "replacement", ")", "saved", "=", "tempfile", ".", "tempdir", "tempfile", ".", "tempdir", "=", ...
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
[ "Monkey", "-", "patch", "tempfile", ".", "tempdir", "with", "replacement", "ensuring", "it", "exists" ]
python
test
FlorianRhiem/pyGLFW
glfw/library.py
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/library.py#L17-L46
def _find_library_candidates(library_names, library_file_extensions, library_search_paths): """ Finds and returns filenames which might be the library you are looking for. """ candidates = set() for library_name in library_names: for ...
[ "def", "_find_library_candidates", "(", "library_names", ",", "library_file_extensions", ",", "library_search_paths", ")", ":", "candidates", "=", "set", "(", ")", "for", "library_name", "in", "library_names", ":", "for", "search_path", "in", "library_search_paths", "...
Finds and returns filenames which might be the library you are looking for.
[ "Finds", "and", "returns", "filenames", "which", "might", "be", "the", "library", "you", "are", "looking", "for", "." ]
python
train
ninuxorg/nodeshot
nodeshot/core/layers/models/layer.py
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/models/layer.py#L146-L155
def nodes_minimum_distance_validation(self): """ if minimum distance is specified, ensure node is not too close to other nodes; """ if self.layer and self.layer.nodes_minimum_distance: minimum_distance = self.layer.nodes_minimum_distance # TODO - lower priority: do this check only when c...
[ "def", "nodes_minimum_distance_validation", "(", "self", ")", ":", "if", "self", ".", "layer", "and", "self", ".", "layer", ".", "nodes_minimum_distance", ":", "minimum_distance", "=", "self", ".", "layer", ".", "nodes_minimum_distance", "# TODO - lower priority: do t...
if minimum distance is specified, ensure node is not too close to other nodes;
[ "if", "minimum", "distance", "is", "specified", "ensure", "node", "is", "not", "too", "close", "to", "other", "nodes", ";" ]
python
train
awslabs/aws-sam-cli
samcli/local/lambdafn/runtime.py
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/runtime.py#L118-L149
def _configure_interrupt(self, function_name, timeout, container, is_debugging): """ When a Lambda function is executing, we setup certain interrupt handlers to stop the execution. Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though, ...
[ "def", "_configure_interrupt", "(", "self", ",", "function_name", ",", "timeout", ",", "container", ",", "is_debugging", ")", ":", "def", "timer_handler", "(", ")", ":", "# NOTE: This handler runs in a separate thread. So don't try to mutate any non-thread-safe data structures"...
When a Lambda function is executing, we setup certain interrupt handlers to stop the execution. Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though, we don't enforce a timeout. But we setup a SIGINT interrupt to catch Ctrl+C and terminate the c...
[ "When", "a", "Lambda", "function", "is", "executing", "we", "setup", "certain", "interrupt", "handlers", "to", "stop", "the", "execution", ".", "Usually", "we", "setup", "a", "function", "timeout", "interrupt", "to", "kill", "the", "container", "after", "timeo...
python
train
chop-dbhi/varify-data-warehouse
vdw/samples/models.py
https://github.com/chop-dbhi/varify-data-warehouse/blob/1600ee1bc5fae6c68fd03b23624467298570cca8/vdw/samples/models.py#L234-L273
def compute_allele_frequencies(self, using=None): "Computes the allele frequencies across all samples in this cohort." if using is None: using = router.db_for_write(self.__class__) cursor = connections[using].cursor() with transition(self, 'Recomputed Allele Frequencies'): ...
[ "def", "compute_allele_frequencies", "(", "self", ",", "using", "=", "None", ")", ":", "if", "using", "is", "None", ":", "using", "=", "router", ".", "db_for_write", "(", "self", ".", "__class__", ")", "cursor", "=", "connections", "[", "using", "]", "."...
Computes the allele frequencies across all samples in this cohort.
[ "Computes", "the", "allele", "frequencies", "across", "all", "samples", "in", "this", "cohort", "." ]
python
train
dtheodor/flask-sqlalchemy-session
flask_sqlalchemy_session/__init__.py
https://github.com/dtheodor/flask-sqlalchemy-session/blob/c7ddb03e85cdd27fcdcc809b9e1c29d7738d8ebf/flask_sqlalchemy_session/__init__.py#L66-L76
def init_app(self, app): """Setup scoped sesssion creation and teardown for the passed ``app``. :param app: a :class:`~flask.Flask` application """ app.scoped_session = self @app.teardown_appcontext def remove_scoped_session(*args, **kwargs): # pylint: disab...
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "app", ".", "scoped_session", "=", "self", "@", "app", ".", "teardown_appcontext", "def", "remove_scoped_session", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=missing-docstring,u...
Setup scoped sesssion creation and teardown for the passed ``app``. :param app: a :class:`~flask.Flask` application
[ "Setup", "scoped", "sesssion", "creation", "and", "teardown", "for", "the", "passed", "app", "." ]
python
train
TUNE-Archive/freight_forwarder
freight_forwarder/container/config.py
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/config.py#L75-L94
def docker_py_dict(self): """Convert object to match valid docker-py properties. """ return { 'image': self.image, 'command': self.cmd, 'hostname': self.hostname, 'user': self.user, 'detach': self.detach, 'stdin_open': self....
[ "def", "docker_py_dict", "(", "self", ")", ":", "return", "{", "'image'", ":", "self", ".", "image", ",", "'command'", ":", "self", ".", "cmd", ",", "'hostname'", ":", "self", ".", "hostname", ",", "'user'", ":", "self", ".", "user", ",", "'detach'", ...
Convert object to match valid docker-py properties.
[ "Convert", "object", "to", "match", "valid", "docker", "-", "py", "properties", "." ]
python
train
atlassian-api/atlassian-python-api
atlassian/service_desk.py
https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/atlassian/service_desk.py#L505-L520
def add_customers(self, service_desk_id, list_of_usernames): """ Adds one or more existing customers to the given service desk. If you need to create a customer, see Create customer method. Administer project permission is required, or agents if public signups and invites are en...
[ "def", "add_customers", "(", "self", ",", "service_desk_id", ",", "list_of_usernames", ")", ":", "url", "=", "'rest/servicedeskapi/servicedesk/{}/customer'", ".", "format", "(", "service_desk_id", ")", "data", "=", "{", "'usernames'", ":", "list_of_usernames", "}", ...
Adds one or more existing customers to the given service desk. If you need to create a customer, see Create customer method. Administer project permission is required, or agents if public signups and invites are enabled for the Service Desk project. :param service_desk_id: str ...
[ "Adds", "one", "or", "more", "existing", "customers", "to", "the", "given", "service", "desk", ".", "If", "you", "need", "to", "create", "a", "customer", "see", "Create", "customer", "method", "." ]
python
train
ReFirmLabs/binwalk
src/binwalk/plugins/hilink.py
https://github.com/ReFirmLabs/binwalk/blob/a0c5315fd2bae167e5c3d8469ce95d5defc743c2/src/binwalk/plugins/hilink.py#L65-L94
def scan(self, result): ''' Validate signature results. ''' if self.enabled is True: if result.valid is True: if result.description.lower().startswith(self.SIGNATURE_DESCRIPTION) is True: # Read in the first 64 bytes of the suspected encryp...
[ "def", "scan", "(", "self", ",", "result", ")", ":", "if", "self", ".", "enabled", "is", "True", ":", "if", "result", ".", "valid", "is", "True", ":", "if", "result", ".", "description", ".", "lower", "(", ")", ".", "startswith", "(", "self", ".", ...
Validate signature results.
[ "Validate", "signature", "results", "." ]
python
train
google/grr
grr/server/grr_response_server/data_stores/common.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/data_stores/common.py#L68-L70
def MakeDestinationKey(directory, filename): """Creates a name that identifies a database file.""" return utils.SmartStr(utils.JoinPath(directory, filename)).lstrip("/")
[ "def", "MakeDestinationKey", "(", "directory", ",", "filename", ")", ":", "return", "utils", ".", "SmartStr", "(", "utils", ".", "JoinPath", "(", "directory", ",", "filename", ")", ")", ".", "lstrip", "(", "\"/\"", ")" ]
Creates a name that identifies a database file.
[ "Creates", "a", "name", "that", "identifies", "a", "database", "file", "." ]
python
train
adrn/gala
gala/potential/frame/builtin/transformations.py
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L122-L142
def constantrotating_to_static(frame_r, frame_i, w, t=None): """ Transform from a constantly rotating frame to a static, inertial frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `...
[ "def", "constantrotating_to_static", "(", "frame_r", ",", "frame_i", ",", "w", ",", "t", "=", "None", ")", ":", "return", "_constantrotating_static_helper", "(", "frame_r", "=", "frame_r", ",", "frame_i", "=", "frame_i", ",", "w", "=", "w", ",", "t", "=", ...
Transform from a constantly rotating frame to a static, inertial frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit` t : quantity_like (optional) Required i...
[ "Transform", "from", "a", "constantly", "rotating", "frame", "to", "a", "static", "inertial", "frame", "." ]
python
train
pandas-dev/pandas
pandas/core/generic.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L3185-L3199
def _slice(self, slobj, axis=0, kind=None): """ Construct a slice of this container. kind parameter is maintained for compatibility with Series slicing. """ axis = self._get_block_manager_axis(axis) result = self._constructor(self._data.get_slice(slobj, axis=axis)) ...
[ "def", "_slice", "(", "self", ",", "slobj", ",", "axis", "=", "0", ",", "kind", "=", "None", ")", ":", "axis", "=", "self", ".", "_get_block_manager_axis", "(", "axis", ")", "result", "=", "self", ".", "_constructor", "(", "self", ".", "_data", ".", ...
Construct a slice of this container. kind parameter is maintained for compatibility with Series slicing.
[ "Construct", "a", "slice", "of", "this", "container", "." ]
python
train
klen/makesite
makesite/site.py
https://github.com/klen/makesite/blob/f6f77a43a04a256189e8fffbeac1ffd63f35a10c/makesite/site.py#L38-L44
def run_check(self, template_name=None, service_dir=None): " Run checking scripts. " print_header('Check requirements', sep='-') map(lambda cmd: call("bash %s" % cmd), self._gen_scripts( 'check', template_name=template_name, service_dir=service_dir)) return True
[ "def", "run_check", "(", "self", ",", "template_name", "=", "None", ",", "service_dir", "=", "None", ")", ":", "print_header", "(", "'Check requirements'", ",", "sep", "=", "'-'", ")", "map", "(", "lambda", "cmd", ":", "call", "(", "\"bash %s\"", "%", "c...
Run checking scripts.
[ "Run", "checking", "scripts", "." ]
python
train
limodou/uliweb
uliweb/lib/werkzeug/security.py
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/security.py#L49-L65
def pbkdf2_hex(data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS, keylen=None, hashfunc=None): """Like :func:`pbkdf2_bin` but returns a hex encoded string. .. versionadded:: 0.9 :param data: the data to derive. :param salt: the salt for the derivation. :param iterations: the number o...
[ "def", "pbkdf2_hex", "(", "data", ",", "salt", ",", "iterations", "=", "DEFAULT_PBKDF2_ITERATIONS", ",", "keylen", "=", "None", ",", "hashfunc", "=", "None", ")", ":", "rv", "=", "pbkdf2_bin", "(", "data", ",", "salt", ",", "iterations", ",", "keylen", "...
Like :func:`pbkdf2_bin` but returns a hex encoded string. .. versionadded:: 0.9 :param data: the data to derive. :param salt: the salt for the derivation. :param iterations: the number of iterations. :param keylen: the length of the resulting key. If not provided the digest siz...
[ "Like", ":", "func", ":", "pbkdf2_bin", "but", "returns", "a", "hex", "encoded", "string", "." ]
python
train
VingtCinq/python-mailchimp
mailchimp3/baseapi.py
https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/baseapi.py#L27-L34
def _build_path(self, *args): """ Build path with endpoint and args :param args: Tokens in the endpoint URL :type args: :py:class:`unicode` """ return '/'.join(chain((self.endpoint,), map(str, args)))
[ "def", "_build_path", "(", "self", ",", "*", "args", ")", ":", "return", "'/'", ".", "join", "(", "chain", "(", "(", "self", ".", "endpoint", ",", ")", ",", "map", "(", "str", ",", "args", ")", ")", ")" ]
Build path with endpoint and args :param args: Tokens in the endpoint URL :type args: :py:class:`unicode`
[ "Build", "path", "with", "endpoint", "and", "args" ]
python
valid
tanghaibao/goatools
goatools/gosubdag/utils.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/utils.py#L18-L29
def get_kwargs_set(args, exp_elem2dflt): """Return user-specified keyword args in a dictionary and a set (for True/False items).""" arg_set = set() # For arguments that are True or False (present in set if True) # Add user items if True for key, val in args.items(): if exp_elem2dflt is not None...
[ "def", "get_kwargs_set", "(", "args", ",", "exp_elem2dflt", ")", ":", "arg_set", "=", "set", "(", ")", "# For arguments that are True or False (present in set if True)", "# Add user items if True", "for", "key", ",", "val", "in", "args", ".", "items", "(", ")", ":",...
Return user-specified keyword args in a dictionary and a set (for True/False items).
[ "Return", "user", "-", "specified", "keyword", "args", "in", "a", "dictionary", "and", "a", "set", "(", "for", "True", "/", "False", "items", ")", "." ]
python
train
PmagPy/PmagPy
programs/demag_gui.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L3399-L3446
def reset_backend(self, warn_user=True, reset_interps=True): """ Resets GUI data and updates GUI displays such as plots, boxes, and logger Parameters ---------- warn_user : bool which decides if a warning dialog is displayed to the user to ask about reseting ...
[ "def", "reset_backend", "(", "self", ",", "warn_user", "=", "True", ",", "reset_interps", "=", "True", ")", ":", "if", "warn_user", "and", "not", "self", ".", "data_loss_warning", "(", ")", ":", "return", "False", "# reset backend, including get_data(), get_data_i...
Resets GUI data and updates GUI displays such as plots, boxes, and logger Parameters ---------- warn_user : bool which decides if a warning dialog is displayed to the user to ask about reseting data reset_interps : bool which decides if interpretations are read in ...
[ "Resets", "GUI", "data", "and", "updates", "GUI", "displays", "such", "as", "plots", "boxes", "and", "logger" ]
python
train
allenai/allennlp
allennlp/state_machines/transition_functions/linking_coverage_transition_function.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/linking_coverage_transition_function.py#L161-L196
def _get_linked_logits_addition(checklist_state: ChecklistStatelet, action_ids: List[int], action_logits: torch.Tensor) -> torch.Tensor: """ Gets the logits of desired terminal actions yet to be produced by the decoder, and ...
[ "def", "_get_linked_logits_addition", "(", "checklist_state", ":", "ChecklistStatelet", ",", "action_ids", ":", "List", "[", "int", "]", ",", "action_logits", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "# Our basic approach here will be to ...
Gets the logits of desired terminal actions yet to be produced by the decoder, and returns them for the decoder to add to the prior action logits, biasing the model towards predicting missing linked actions.
[ "Gets", "the", "logits", "of", "desired", "terminal", "actions", "yet", "to", "be", "produced", "by", "the", "decoder", "and", "returns", "them", "for", "the", "decoder", "to", "add", "to", "the", "prior", "action", "logits", "biasing", "the", "model", "to...
python
train
django-treebeard/django-treebeard
treebeard/numconv.py
https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/numconv.py#L83-L105
def str2int(self, num): """Converts a string into an integer. If possible, the built-in python conversion will be used for speed purposes. :param num: A string that will be converted to an integer. :rtype: integer :raise ValueError: when *num* is invalid """ ...
[ "def", "str2int", "(", "self", ",", "num", ")", ":", "radix", ",", "alphabet", "=", "self", ".", "radix", ",", "self", ".", "alphabet", "if", "radix", "<=", "36", "and", "alphabet", "[", ":", "radix", "]", ".", "lower", "(", ")", "==", "BASE85", ...
Converts a string into an integer. If possible, the built-in python conversion will be used for speed purposes. :param num: A string that will be converted to an integer. :rtype: integer :raise ValueError: when *num* is invalid
[ "Converts", "a", "string", "into", "an", "integer", "." ]
python
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L255-L288
def get_func_lno(self, funcname): """The first line number of the last defined 'funcname' function.""" class FuncLineno(ast.NodeVisitor): def __init__(self): self.clss = [] def generic_visit(self, node): for child in ast.iter_child_nodes(node): ...
[ "def", "get_func_lno", "(", "self", ",", "funcname", ")", ":", "class", "FuncLineno", "(", "ast", ".", "NodeVisitor", ")", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "clss", "=", "[", "]", "def", "generic_visit", "(", "self", ",", "n...
The first line number of the last defined 'funcname' function.
[ "The", "first", "line", "number", "of", "the", "last", "defined", "funcname", "function", "." ]
python
train
johntruckenbrodt/spatialist
spatialist/envi.py
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/envi.py#L128-L137
def write(self, filename='same'): """ write object to an ENVI header file """ if filename == 'same': filename = self.filename if not filename.endswith('.hdr'): filename += '.hdr' with open(filename, 'w') as out: out.write(self.__str__()...
[ "def", "write", "(", "self", ",", "filename", "=", "'same'", ")", ":", "if", "filename", "==", "'same'", ":", "filename", "=", "self", ".", "filename", "if", "not", "filename", ".", "endswith", "(", "'.hdr'", ")", ":", "filename", "+=", "'.hdr'", "with...
write object to an ENVI header file
[ "write", "object", "to", "an", "ENVI", "header", "file" ]
python
train
agoragames/leaderboard-python
leaderboard/leaderboard.py
https://github.com/agoragames/leaderboard-python/blob/ec309859b197a751ac0322374b36d134d8c5522f/leaderboard/leaderboard.py#L319-L328
def remove_member_data_in(self, leaderboard_name, member): ''' Remove the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. ''' self.redis_connection.hdel( ...
[ "def", "remove_member_data_in", "(", "self", ",", "leaderboard_name", ",", "member", ")", ":", "self", ".", "redis_connection", ".", "hdel", "(", "self", ".", "_member_data_key", "(", "leaderboard_name", ")", ",", "member", ")" ]
Remove the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name.
[ "Remove", "the", "optional", "member", "data", "for", "a", "given", "member", "in", "the", "named", "leaderboard", "." ]
python
train
IdentityPython/pysaml2
src/saml2/s2repoze/plugins/sp.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/s2repoze/plugins/sp.py#L51-L59
def construct_came_from(environ): """ The URL that the user used when the process where interupted for single-sign-on processing. """ came_from = environ.get("PATH_INFO") qstr = environ.get("QUERY_STRING", "") if qstr: came_from += "?" + qstr return came_from
[ "def", "construct_came_from", "(", "environ", ")", ":", "came_from", "=", "environ", ".", "get", "(", "\"PATH_INFO\"", ")", "qstr", "=", "environ", ".", "get", "(", "\"QUERY_STRING\"", ",", "\"\"", ")", "if", "qstr", ":", "came_from", "+=", "\"?\"", "+", ...
The URL that the user used when the process where interupted for single-sign-on processing.
[ "The", "URL", "that", "the", "user", "used", "when", "the", "process", "where", "interupted", "for", "single", "-", "sign", "-", "on", "processing", "." ]
python
train
cokelaer/spectrum
src/spectrum/window.py
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L526-L555
def window_visu(N=51, name='hamming', **kargs): """A Window visualisation tool :param N: length of the window :param name: name of the window :param NFFT: padding used by the FFT :param mindB: the minimum frequency power in dB :param maxdB: the maximum frequency power in dB :param kargs: op...
[ "def", "window_visu", "(", "N", "=", "51", ",", "name", "=", "'hamming'", ",", "*", "*", "kargs", ")", ":", "# get the default parameters", "mindB", "=", "kargs", ".", "pop", "(", "'mindB'", ",", "-", "100", ")", "maxdB", "=", "kargs", ".", "pop", "(...
A Window visualisation tool :param N: length of the window :param name: name of the window :param NFFT: padding used by the FFT :param mindB: the minimum frequency power in dB :param maxdB: the maximum frequency power in dB :param kargs: optional arguments passed to :func:`create_window` T...
[ "A", "Window", "visualisation", "tool" ]
python
valid
pycontribs/pyrax
pyrax/cloudmonitoring.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L233-L238
def list_alarms(self, limit=None, marker=None, return_next=False): """ Returns a list of all the alarms created on this entity. """ return self._alarm_manager.list(limit=limit, marker=marker, return_next=return_next)
[ "def", "list_alarms", "(", "self", ",", "limit", "=", "None", ",", "marker", "=", "None", ",", "return_next", "=", "False", ")", ":", "return", "self", ".", "_alarm_manager", ".", "list", "(", "limit", "=", "limit", ",", "marker", "=", "marker", ",", ...
Returns a list of all the alarms created on this entity.
[ "Returns", "a", "list", "of", "all", "the", "alarms", "created", "on", "this", "entity", "." ]
python
train
census-instrumentation/opencensus-python
contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L247-L258
def _convert_hex_str_to_int(val): """Convert hexadecimal formatted ids to signed int64""" if val is None: return None hex_num = int(val, 16) # ensure it fits into 64-bit if hex_num > 0x7FFFFFFFFFFFFFFF: hex_num -= 0x10000000000000000 assert -9223372036854775808 <= hex_num <= 9...
[ "def", "_convert_hex_str_to_int", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "None", "hex_num", "=", "int", "(", "val", ",", "16", ")", "# ensure it fits into 64-bit", "if", "hex_num", ">", "0x7FFFFFFFFFFFFFFF", ":", "hex_num", "-=", "0...
Convert hexadecimal formatted ids to signed int64
[ "Convert", "hexadecimal", "formatted", "ids", "to", "signed", "int64" ]
python
train
toabctl/metaextract
metaextract/utils.py
https://github.com/toabctl/metaextract/blob/0515490b5983d888bbbaec5fdb5a0a4214743335/metaextract/utils.py#L125-L135
def from_archive(archive_filename, py_interpreter=sys.executable): """extract metadata from a given sdist archive file :param archive_filename: a sdist archive file :param py_interpreter: The full path to the used python interpreter :returns: a json blob with metadata """ with _extract_to_tempdir(...
[ "def", "from_archive", "(", "archive_filename", ",", "py_interpreter", "=", "sys", ".", "executable", ")", ":", "with", "_extract_to_tempdir", "(", "archive_filename", ")", "as", "root_dir", ":", "data", "=", "_setup_py_run_from_dir", "(", "root_dir", ",", "py_int...
extract metadata from a given sdist archive file :param archive_filename: a sdist archive file :param py_interpreter: The full path to the used python interpreter :returns: a json blob with metadata
[ "extract", "metadata", "from", "a", "given", "sdist", "archive", "file" ]
python
train
dnanexus/dx-toolkit
src/python/dxpy/utils/pretty_print.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/utils/pretty_print.py#L112-L182
def format_table(table, column_names=None, column_specs=None, max_col_width=32, report_dimensions=False): ''' Table pretty printer. Expects tables to be given as arrays of arrays. Example: print format_table([[1, "2"], [3, "456"]], column_names=['A', 'B']) ''' if len(tabl...
[ "def", "format_table", "(", "table", ",", "column_names", "=", "None", ",", "column_specs", "=", "None", ",", "max_col_width", "=", "32", ",", "report_dimensions", "=", "False", ")", ":", "if", "len", "(", "table", ")", ">", "0", ":", "col_widths", "=", ...
Table pretty printer. Expects tables to be given as arrays of arrays. Example: print format_table([[1, "2"], [3, "456"]], column_names=['A', 'B'])
[ "Table", "pretty", "printer", ".", "Expects", "tables", "to", "be", "given", "as", "arrays", "of", "arrays", "." ]
python
train
dhylands/rshell
rshell/main.py
https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L377-L383
def align_cell(fmt, elem, width): """Returns an aligned element.""" if fmt == "<": return elem + ' ' * (width - len(elem)) if fmt == ">": return ' ' * (width - len(elem)) + elem return elem
[ "def", "align_cell", "(", "fmt", ",", "elem", ",", "width", ")", ":", "if", "fmt", "==", "\"<\"", ":", "return", "elem", "+", "' '", "*", "(", "width", "-", "len", "(", "elem", ")", ")", "if", "fmt", "==", "\">\"", ":", "return", "' '", "*", "(...
Returns an aligned element.
[ "Returns", "an", "aligned", "element", "." ]
python
train
marccarre/py_sak
py_sak/functions.py
https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/functions.py#L11-L16
def log_debug(func, *args, **kwargs): ''' Wrap call of provided function with debug log statements. ''' logging.debug('Starting "%s" in thread %s...', func.__name__, current_thread()) results = func(*args, **kwargs) logging.debug('Successfully finished "%s" in thread %s.', func.__name__, current_thread(...
[ "def", "log_debug", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "debug", "(", "'Starting \"%s\" in thread %s...'", ",", "func", ".", "__name__", ",", "current_thread", "(", ")", ")", "results", "=", "func", "(", "*",...
Wrap call of provided function with debug log statements.
[ "Wrap", "call", "of", "provided", "function", "with", "debug", "log", "statements", "." ]
python
train
saltstack/salt
salt/modules/vsphere.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L2966-L3090
def set_service_policy(host, username, password, service_name, service_policy, protocol=None, port=None, host_names=None): ''' Set the service name's p...
[ "def", "set_service_policy", "(", "host", ",", "username", ",", "password", ",", "service_name", ",", "service_policy", ",", "protocol", "=", "None", ",", "port", "=", "None", ",", "host_names", "=", "None", ")", ":", "service_instance", "=", "salt", ".", ...
Set the service name's policy for a given host or list of hosts. host The location of the host. username The username used to login to the host, such as ``root``. password The password used to login to the host. service_name The name of the service for which to set th...
[ "Set", "the", "service", "name", "s", "policy", "for", "a", "given", "host", "or", "list", "of", "hosts", "." ]
python
train
rsgalloway/grit
grit/repo/version.py
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/version.py#L63-L76
def items(self, path=None): """ Returns set of items. :param path: Regex filter on item path. :return: List of Item class objects. """ items = list(self.iteritems()) if path is not None: path += '$' regex = re.compile(path) it...
[ "def", "items", "(", "self", ",", "path", "=", "None", ")", ":", "items", "=", "list", "(", "self", ".", "iteritems", "(", ")", ")", "if", "path", "is", "not", "None", ":", "path", "+=", "'$'", "regex", "=", "re", ".", "compile", "(", "path", "...
Returns set of items. :param path: Regex filter on item path. :return: List of Item class objects.
[ "Returns", "set", "of", "items", "." ]
python
train
aquatix/ns-api
ns_api.py
https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L62-L76
def load_datetime(value, dt_format): """ Create timezone-aware datetime object """ if dt_format.endswith('%z'): dt_format = dt_format[:-2] offset = value[-5:] value = value[:-5] if offset != offset.replace(':', ''): # strip : from HHMM if needed (isoformat() a...
[ "def", "load_datetime", "(", "value", ",", "dt_format", ")", ":", "if", "dt_format", ".", "endswith", "(", "'%z'", ")", ":", "dt_format", "=", "dt_format", "[", ":", "-", "2", "]", "offset", "=", "value", "[", "-", "5", ":", "]", "value", "=", "val...
Create timezone-aware datetime object
[ "Create", "timezone", "-", "aware", "datetime", "object" ]
python
train
defunkt/pystache
pystache/renderer.py
https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L369-L378
def render_name(self, template_name, *context, **kwargs): """ Render the template with the given name using the given context. See the render() docstring for more information. """ loader = self._make_loader() template = loader.load_name(template_name) return sel...
[ "def", "render_name", "(", "self", ",", "template_name", ",", "*", "context", ",", "*", "*", "kwargs", ")", ":", "loader", "=", "self", ".", "_make_loader", "(", ")", "template", "=", "loader", ".", "load_name", "(", "template_name", ")", "return", "self...
Render the template with the given name using the given context. See the render() docstring for more information.
[ "Render", "the", "template", "with", "the", "given", "name", "using", "the", "given", "context", "." ]
python
train
pyvisa/pyvisa
pyvisa/rname.py
https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/rname.py#L43-L54
def bad_syntax(cls, syntax, resource_name, ex=None): """Exception used when the resource name cannot be parsed. """ if ex: msg = "The syntax is '%s' (%s)." % (syntax, ex) else: msg = "The syntax is '%s'." % syntax msg = "Could not parse '%s'. %s" % (reso...
[ "def", "bad_syntax", "(", "cls", ",", "syntax", ",", "resource_name", ",", "ex", "=", "None", ")", ":", "if", "ex", ":", "msg", "=", "\"The syntax is '%s' (%s).\"", "%", "(", "syntax", ",", "ex", ")", "else", ":", "msg", "=", "\"The syntax is '%s'.\"", "...
Exception used when the resource name cannot be parsed.
[ "Exception", "used", "when", "the", "resource", "name", "cannot", "be", "parsed", "." ]
python
train
ray-project/ray
python/ray/node.py
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/node.py#L653-L661
def kill_raylet_monitor(self, check_alive=True): """Kill the raylet monitor. Args: check_alive (bool): Raise an exception if the process was already dead. """ self._kill_process_type( ray_constants.PROCESS_TYPE_RAYLET_MONITOR, check_alive=check_al...
[ "def", "kill_raylet_monitor", "(", "self", ",", "check_alive", "=", "True", ")", ":", "self", ".", "_kill_process_type", "(", "ray_constants", ".", "PROCESS_TYPE_RAYLET_MONITOR", ",", "check_alive", "=", "check_alive", ")" ]
Kill the raylet monitor. Args: check_alive (bool): Raise an exception if the process was already dead.
[ "Kill", "the", "raylet", "monitor", "." ]
python
train