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
MSchnei/pyprf_feature
pyprf_feature/analysis/find_prf_utils_np.py
https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/find_prf_utils_np.py#L8-L21
def np_lst_sq(vecMdl, aryFuncChnk): """Least squares fitting in numpy without cross-validation. Notes ----- This is just a wrapper function for np.linalg.lstsq to keep piping consistent. """ aryTmpBts, vecTmpRes = np.linalg.lstsq(vecMdl, aryFuncCh...
[ "def", "np_lst_sq", "(", "vecMdl", ",", "aryFuncChnk", ")", ":", "aryTmpBts", ",", "vecTmpRes", "=", "np", ".", "linalg", ".", "lstsq", "(", "vecMdl", ",", "aryFuncChnk", ",", "rcond", "=", "-", "1", ")", "[", ":", "2", "]", "return", "aryTmpBts", ",...
Least squares fitting in numpy without cross-validation. Notes ----- This is just a wrapper function for np.linalg.lstsq to keep piping consistent.
[ "Least", "squares", "fitting", "in", "numpy", "without", "cross", "-", "validation", "." ]
python
train
ihgazni2/elist
elist/elist.py
https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L5715-L5736
def value_interval(ol,value): ''' ol = [0, 4, 6, 8, 10, 14] value_interval(ol,-1) value_interval(ol,1) value_interval(ol,2) value_interval(ol,3) value_interval(ol,4) value_interval(ol,9) value_interval(ol,14) value_interval(ol,17) ''' s...
[ "def", "value_interval", "(", "ol", ",", "value", ")", ":", "si", ",", "ei", "=", "where", "(", "ol", ",", "value", ")", "if", "(", "si", "==", "None", ")", ":", "sv", "=", "None", "else", ":", "sv", "=", "ol", "[", "si", "]", "if", "(", "e...
ol = [0, 4, 6, 8, 10, 14] value_interval(ol,-1) value_interval(ol,1) value_interval(ol,2) value_interval(ol,3) value_interval(ol,4) value_interval(ol,9) value_interval(ol,14) value_interval(ol,17)
[ "ol", "=", "[", "0", "4", "6", "8", "10", "14", "]", "value_interval", "(", "ol", "-", "1", ")", "value_interval", "(", "ol", "1", ")", "value_interval", "(", "ol", "2", ")", "value_interval", "(", "ol", "3", ")", "value_interval", "(", "ol", "4", ...
python
valid
napalm-automation/napalm-junos
napalm_junos/junos.py
https://github.com/napalm-automation/napalm-junos/blob/78c0d161daf2abf26af5835b773f6db57c46efff/napalm_junos/junos.py#L1574-L1601
def get_probes_results(self): """Return the results of the RPM probes.""" probes_results = {} probes_results_table = junos_views.junos_rpm_probes_results_table(self.device) probes_results_table.get() probes_results_items = probes_results_table.items() for probe_result i...
[ "def", "get_probes_results", "(", "self", ")", ":", "probes_results", "=", "{", "}", "probes_results_table", "=", "junos_views", ".", "junos_rpm_probes_results_table", "(", "self", ".", "device", ")", "probes_results_table", ".", "get", "(", ")", "probes_results_ite...
Return the results of the RPM probes.
[ "Return", "the", "results", "of", "the", "RPM", "probes", "." ]
python
train
vertexproject/synapse
synapse/lib/jupyter.py
https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/jupyter.py#L241-L259
async def getTempCoreCmdr(mods=None, outp=None): ''' Get a CmdrCore instance which is backed by a temporary Cortex. Args: mods (list): A list of additional CoreModules to load in the Cortex. outp: A output helper. Will be used for the Cmdr instance. Notes: The CmdrCore returne...
[ "async", "def", "getTempCoreCmdr", "(", "mods", "=", "None", ",", "outp", "=", "None", ")", ":", "acm", "=", "genTempCoreProxy", "(", "mods", ")", "prox", "=", "await", "acm", ".", "__aenter__", "(", ")", "cmdrcore", "=", "await", "CmdrCore", ".", "ani...
Get a CmdrCore instance which is backed by a temporary Cortex. Args: mods (list): A list of additional CoreModules to load in the Cortex. outp: A output helper. Will be used for the Cmdr instance. Notes: The CmdrCore returned by this should be fini()'d to tear down the temporary Corte...
[ "Get", "a", "CmdrCore", "instance", "which", "is", "backed", "by", "a", "temporary", "Cortex", "." ]
python
train
KrishnaswamyLab/graphtools
graphtools/graphs.py
https://github.com/KrishnaswamyLab/graphtools/blob/44685352be7df2005d44722903092207967457f2/graphtools/graphs.py#L863-L947
def build_kernel(self): """Build the KNN kernel. Build a k nearest neighbors kernel, optionally with alpha decay. If `precomputed` is not `None`, the appropriate steps in the kernel building process are skipped. Must return a symmetric matrix Returns ------- ...
[ "def", "build_kernel", "(", "self", ")", ":", "if", "self", ".", "precomputed", "==", "\"affinity\"", ":", "# already done", "# TODO: should we check that precomputed matrices look okay?", "# e.g. check the diagonal", "K", "=", "self", ".", "data_nu", "elif", "self", "....
Build the KNN kernel. Build a k nearest neighbors kernel, optionally with alpha decay. If `precomputed` is not `None`, the appropriate steps in the kernel building process are skipped. Must return a symmetric matrix Returns ------- K : kernel matrix, shape=[n_sa...
[ "Build", "the", "KNN", "kernel", "." ]
python
train
django-treebeard/django-treebeard
treebeard/admin.py
https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/admin.py#L66-L87
def get_urls(self): """ Adds a url to move nodes to this admin """ urls = super(TreeAdmin, self).get_urls() if django.VERSION < (1, 10): from django.views.i18n import javascript_catalog jsi18n_url = url(r'^jsi18n/$', javascript_catalog, {'packages': ('tre...
[ "def", "get_urls", "(", "self", ")", ":", "urls", "=", "super", "(", "TreeAdmin", ",", "self", ")", ".", "get_urls", "(", ")", "if", "django", ".", "VERSION", "<", "(", "1", ",", "10", ")", ":", "from", "django", ".", "views", ".", "i18n", "impor...
Adds a url to move nodes to this admin
[ "Adds", "a", "url", "to", "move", "nodes", "to", "this", "admin" ]
python
train
odlgroup/odl
odl/contrib/tensorflow/layer.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/tensorflow/layer.py#L22-L382
def as_tensorflow_layer(odl_op, name='ODLOperator', differentiable=True): """Convert `Operator` or `Functional` to a tensorflow layer. Parameters ---------- odl_op : `Operator` or `Functional` The operator that should be wrapped as a tensorflow layer. name : str ...
[ "def", "as_tensorflow_layer", "(", "odl_op", ",", "name", "=", "'ODLOperator'", ",", "differentiable", "=", "True", ")", ":", "default_name", "=", "name", "def", "py_func", "(", "func", ",", "inp", ",", "Tout", ",", "stateful", "=", "True", ",", "name", ...
Convert `Operator` or `Functional` to a tensorflow layer. Parameters ---------- odl_op : `Operator` or `Functional` The operator that should be wrapped as a tensorflow layer. name : str Default name for tensorflow layers created. differentiable : boolean ``True`` if the laye...
[ "Convert", "Operator", "or", "Functional", "to", "a", "tensorflow", "layer", "." ]
python
train
cmorisse/ikp3db
ikp3db.py
https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1426-L1440
def set_breakpoint(self, file_name, line_number, condition=None, enabled=True): """ Create a breakpoint, register it in the class's lists and returns a tuple of (error_message, break_number) """ c_file_name = self.canonic(file_name) import linecache line = linecache.getli...
[ "def", "set_breakpoint", "(", "self", ",", "file_name", ",", "line_number", ",", "condition", "=", "None", ",", "enabled", "=", "True", ")", ":", "c_file_name", "=", "self", ".", "canonic", "(", "file_name", ")", "import", "linecache", "line", "=", "lineca...
Create a breakpoint, register it in the class's lists and returns a tuple of (error_message, break_number)
[ "Create", "a", "breakpoint", "register", "it", "in", "the", "class", "s", "lists", "and", "returns", "a", "tuple", "of", "(", "error_message", "break_number", ")" ]
python
train
confluentinc/confluent-kafka-python
examples/adminapi.py
https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/examples/adminapi.py#L51-L68
def example_delete_topics(a, topics): """ delete topics """ # Call delete_topics to asynchronously delete topics, a future is returned. # By default this operation on the broker returns immediately while # topics are deleted in the background. But here we give it some time (30s) # to propagate in t...
[ "def", "example_delete_topics", "(", "a", ",", "topics", ")", ":", "# Call delete_topics to asynchronously delete topics, a future is returned.", "# By default this operation on the broker returns immediately while", "# topics are deleted in the background. But here we give it some time (30s)", ...
delete topics
[ "delete", "topics" ]
python
train
angr/angr
angr/exploration_techniques/common.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/exploration_techniques/common.py#L5-L49
def condition_to_lambda(condition, default=False): """ Translates an integer, set, list or function into a lambda that checks if state's current basic block matches some condition. :param condition: An integer, set, list or lambda to convert to a lambda. :param default: The default return val...
[ "def", "condition_to_lambda", "(", "condition", ",", "default", "=", "False", ")", ":", "if", "condition", "is", "None", ":", "condition_function", "=", "lambda", "state", ":", "default", "static_addrs", "=", "set", "(", ")", "elif", "isinstance", "(", "cond...
Translates an integer, set, list or function into a lambda that checks if state's current basic block matches some condition. :param condition: An integer, set, list or lambda to convert to a lambda. :param default: The default return value of the lambda (in case condition is None). Default: false. ...
[ "Translates", "an", "integer", "set", "list", "or", "function", "into", "a", "lambda", "that", "checks", "if", "state", "s", "current", "basic", "block", "matches", "some", "condition", "." ]
python
train
pymupdf/PyMuPDF
fitz/fitz.py
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L4597-L4608
def _le_circle(self, annot, p1, p2, lr): """Make stream commands for circle line end symbol. "lr" denotes left (False) or right point. """ m, im, L, R, w, scol, fcol, opacity = self._le_annot_parms(annot, p1, p2) shift = 2.5 # 2*shift*width = length of square edge d =...
[ "def", "_le_circle", "(", "self", ",", "annot", ",", "p1", ",", "p2", ",", "lr", ")", ":", "m", ",", "im", ",", "L", ",", "R", ",", "w", ",", "scol", ",", "fcol", ",", "opacity", "=", "self", ".", "_le_annot_parms", "(", "annot", ",", "p1", "...
Make stream commands for circle line end symbol. "lr" denotes left (False) or right point.
[ "Make", "stream", "commands", "for", "circle", "line", "end", "symbol", ".", "lr", "denotes", "left", "(", "False", ")", "or", "right", "point", "." ]
python
train
HazyResearch/fonduer
src/fonduer/utils/visualizer.py
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/visualizer.py#L28-L50
def display_boxes(self, pdf_file, boxes, alternate_colors=False): """ Displays each of the bounding boxes passed in 'boxes' on images of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right) """ imgs = [] colors = [Color("blue...
[ "def", "display_boxes", "(", "self", ",", "pdf_file", ",", "boxes", ",", "alternate_colors", "=", "False", ")", ":", "imgs", "=", "[", "]", "colors", "=", "[", "Color", "(", "\"blue\"", ")", ",", "Color", "(", "\"red\"", ")", "]", "boxes_per_page", "="...
Displays each of the bounding boxes passed in 'boxes' on images of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right)
[ "Displays", "each", "of", "the", "bounding", "boxes", "passed", "in", "boxes", "on", "images", "of", "the", "pdf", "pointed", "to", "by", "pdf_file", "boxes", "is", "a", "list", "of", "5", "-", "tuples", "(", "page", "top", "left", "bottom", "right", "...
python
train
eerimoq/bitstruct
bitstruct.py
https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L427-L435
def pack(self, data): """See :func:`~bitstruct.pack_dict()`. """ try: return self.pack_any(data) except KeyError as e: raise Error('{} not found in data dictionary'.format(str(e)))
[ "def", "pack", "(", "self", ",", "data", ")", ":", "try", ":", "return", "self", ".", "pack_any", "(", "data", ")", "except", "KeyError", "as", "e", ":", "raise", "Error", "(", "'{} not found in data dictionary'", ".", "format", "(", "str", "(", "e", "...
See :func:`~bitstruct.pack_dict()`.
[ "See", ":", "func", ":", "~bitstruct", ".", "pack_dict", "()", "." ]
python
valid
awslabs/sockeye
sockeye/inference.py
https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/inference.py#L1804-L1846
def _decode_step(self, prev_word: mx.nd.NDArray, step: int, source_length: int, states: List[ModelState], models_output_layer_w: List[mx.nd.NDArray], models_output_layer_b: List[mx.nd.NDArray]) ...
[ "def", "_decode_step", "(", "self", ",", "prev_word", ":", "mx", ".", "nd", ".", "NDArray", ",", "step", ":", "int", ",", "source_length", ":", "int", ",", "states", ":", "List", "[", "ModelState", "]", ",", "models_output_layer_w", ":", "List", "[", "...
Returns decoder predictions (combined from all models), attention scores, and updated states. :param prev_word: Previous words of hypotheses. Shape: (batch_size * beam_size,). :param step: Beam search iteration. :param source_length: Length of the input sequence. :param states: List of ...
[ "Returns", "decoder", "predictions", "(", "combined", "from", "all", "models", ")", "attention", "scores", "and", "updated", "states", "." ]
python
train
MediaFire/mediafire-python-open-sdk
examples/mediafire-cli.py
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/examples/mediafire-cli.py#L106-L110
def do_folder_create(client, args): """Create directory""" for folder_uri in args.uris: client.create_folder(folder_uri, recursive=True) return True
[ "def", "do_folder_create", "(", "client", ",", "args", ")", ":", "for", "folder_uri", "in", "args", ".", "uris", ":", "client", ".", "create_folder", "(", "folder_uri", ",", "recursive", "=", "True", ")", "return", "True" ]
Create directory
[ "Create", "directory" ]
python
train
spyder-ide/spyder-kernels
spyder_kernels/customize/spydercustomize.py
https://github.com/spyder-ide/spyder-kernels/blob/2c5b36cdb797b8aba77bc406ca96f5e079c4aaca/spyder_kernels/customize/spydercustomize.py#L424-L433
def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" # This is useful when debugging in an active interpreter (otherwise, # the debugger will stop before reaching the target file) if self._wait_for_mainpyfile: if (self.mainpyfile != self.canon...
[ "def", "user_return", "(", "self", ",", "frame", ",", "return_value", ")", ":", "# This is useful when debugging in an active interpreter (otherwise,", "# the debugger will stop before reaching the target file)", "if", "self", ".", "_wait_for_mainpyfile", ":", "if", "(", "self"...
This function is called when a return trap is set here.
[ "This", "function", "is", "called", "when", "a", "return", "trap", "is", "set", "here", "." ]
python
train
wonambi-python/wonambi
wonambi/ioeeg/blackrock.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/blackrock.py#L373-L575
def _read_neuralev(filename, read_markers=False, trigger_bits=16, trigger_zero=True): """Read some information from NEV Parameters ---------- filename : str path to NEV file read_markers : bool whether to read markers or not (it can get really large) trigger_b...
[ "def", "_read_neuralev", "(", "filename", ",", "read_markers", "=", "False", ",", "trigger_bits", "=", "16", ",", "trigger_zero", "=", "True", ")", ":", "hdr", "=", "{", "}", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "BasicHdr"...
Read some information from NEV Parameters ---------- filename : str path to NEV file read_markers : bool whether to read markers or not (it can get really large) trigger_bits : int, optional 8 or 16, read the triggers as one or two bytes trigger_zero : bool, optional ...
[ "Read", "some", "information", "from", "NEV" ]
python
train
loli/medpy
medpy/metric/histogram.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/histogram.py#L389-L448
def relative_bin_deviation(h1, h2): # 79 us @array, 104 us @list \w 100 bins r""" Calculate the bin-wise deviation between two histograms. The relative bin deviation between two histograms :math:`H` and :math:`H'` of size :math:`m` is defined as: .. math:: d_{rbd}(H, H') = \su...
[ "def", "relative_bin_deviation", "(", "h1", ",", "h2", ")", ":", "# 79 us @array, 104 us @list \\w 100 bins", "h1", ",", "h2", "=", "__prepare_histogram", "(", "h1", ",", "h2", ")", "numerator", "=", "scipy", ".", "sqrt", "(", "scipy", ".", "square", "(", "h...
r""" Calculate the bin-wise deviation between two histograms. The relative bin deviation between two histograms :math:`H` and :math:`H'` of size :math:`m` is defined as: .. math:: d_{rbd}(H, H') = \sum_{m=1}^M \frac{ \sqrt{(H_m - H'_m)^2} ...
[ "r", "Calculate", "the", "bin", "-", "wise", "deviation", "between", "two", "histograms", ".", "The", "relative", "bin", "deviation", "between", "two", "histograms", ":", "math", ":", "H", "and", ":", "math", ":", "H", "of", "size", ":", "math", ":", "...
python
train
rsteca/sklearn-deap
evolutionary_search/cv.py
https://github.com/rsteca/sklearn-deap/blob/b7ee1722a40cc0c6550d32a2714ab220db2b7430/evolutionary_search/cv.py#L316-L318
def possible_params(self): """ Used when assuming params is a list. """ return self.params if isinstance(self.params, list) else [self.params]
[ "def", "possible_params", "(", "self", ")", ":", "return", "self", ".", "params", "if", "isinstance", "(", "self", ".", "params", ",", "list", ")", "else", "[", "self", ".", "params", "]" ]
Used when assuming params is a list.
[ "Used", "when", "assuming", "params", "is", "a", "list", "." ]
python
train
igvteam/igv-jupyter
igv/browser.py
https://github.com/igvteam/igv-jupyter/blob/f93752ce507eae893c203325764551647e28a3dc/igv/browser.py#L151-L166
def on(self, eventName, cb): """ Subscribe to an igv.js event. :param Name of the event. Currently only "locuschange" is supported. :type str :param cb - callback function taking a single argument. For the locuschange event this argument will contain a dictiona...
[ "def", "on", "(", "self", ",", "eventName", ",", "cb", ")", ":", "self", ".", "eventHandlers", "[", "eventName", "]", "=", "cb", "return", "self", ".", "_send", "(", "{", "\"id\"", ":", "self", ".", "igv_id", ",", "\"command\"", ":", "\"on\"", ",", ...
Subscribe to an igv.js event. :param Name of the event. Currently only "locuschange" is supported. :type str :param cb - callback function taking a single argument. For the locuschange event this argument will contain a dictionary of the form {chr, start, end} :type f...
[ "Subscribe", "to", "an", "igv", ".", "js", "event", "." ]
python
train
icgood/pymap
pymap/backend/mailbox.py
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/mailbox.py#L186-L202
async def find(self, seq_set: SequenceSet, selected: SelectedMailbox, requirement: FetchRequirement = FetchRequirement.METADATA) \ -> AsyncIterable[Tuple[int, MessageT]]: """Find the active message UID and message pairs in the mailbox that are contained in the given sequen...
[ "async", "def", "find", "(", "self", ",", "seq_set", ":", "SequenceSet", ",", "selected", ":", "SelectedMailbox", ",", "requirement", ":", "FetchRequirement", "=", "FetchRequirement", ".", "METADATA", ")", "->", "AsyncIterable", "[", "Tuple", "[", "int", ",", ...
Find the active message UID and message pairs in the mailbox that are contained in the given sequences set. Message sequence numbers are resolved by the selected mailbox session. Args: seq_set: The sequence set of the desired messages. selected: The selected mailbox sess...
[ "Find", "the", "active", "message", "UID", "and", "message", "pairs", "in", "the", "mailbox", "that", "are", "contained", "in", "the", "given", "sequences", "set", ".", "Message", "sequence", "numbers", "are", "resolved", "by", "the", "selected", "mailbox", ...
python
train
bpsmith/tia
tia/rlab/table.py
https://github.com/bpsmith/tia/blob/a7043b6383e557aeea8fc7112bbffd6e36a230e9/tia/rlab/table.py#L688-L694
def set_border_type(self, clazz, weight=DefaultWeight, color=None, cap=None, dashes=None, join=None, count=None, space=None): """example: set_border_type(BorderTypePartialRows) would set a border above and below each row in the range""" args = locals() args.pop('clazz') ...
[ "def", "set_border_type", "(", "self", ",", "clazz", ",", "weight", "=", "DefaultWeight", ",", "color", "=", "None", ",", "cap", "=", "None", ",", "dashes", "=", "None", ",", "join", "=", "None", ",", "count", "=", "None", ",", "space", "=", "None", ...
example: set_border_type(BorderTypePartialRows) would set a border above and below each row in the range
[ "example", ":", "set_border_type", "(", "BorderTypePartialRows", ")", "would", "set", "a", "border", "above", "and", "below", "each", "row", "in", "the", "range" ]
python
train
genesluder/python-agiletixapi
agiletixapi/utils.py
https://github.com/genesluder/python-agiletixapi/blob/a7a3907414cd5623f4542b03cb970862368a894a/agiletixapi/utils.py#L86-L94
def to_underscore(s): """Transform camel or pascal case to underscore separated string """ return re.sub( r'(?!^)([A-Z]+)', lambda m: "_{0}".format(m.group(1).lower()), re.sub(r'(?!^)([A-Z]{1}[a-z]{1})', lambda m: "_{0}".format(m.group(1).lower()), s) ).lower()
[ "def", "to_underscore", "(", "s", ")", ":", "return", "re", ".", "sub", "(", "r'(?!^)([A-Z]+)'", ",", "lambda", "m", ":", "\"_{0}\"", ".", "format", "(", "m", ".", "group", "(", "1", ")", ".", "lower", "(", ")", ")", ",", "re", ".", "sub", "(", ...
Transform camel or pascal case to underscore separated string
[ "Transform", "camel", "or", "pascal", "case", "to", "underscore", "separated", "string" ]
python
train
lingthio/Flask-User
flask_user/db_adapters/sql_db_adapter.py
https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_adapters/sql_db_adapter.py#L91-L116
def ifind_first_object(self, ObjectClass, **kwargs): """ Retrieve the first object of type ``ObjectClass``, matching the specified filters in ``**kwargs`` -- case insensitive. | If USER_IFIND_MODE is 'nocase_collation' this method maps to find_first_object(). | If USER_IFIND_MODE is 'if...
[ "def", "ifind_first_object", "(", "self", ",", "ObjectClass", ",", "*", "*", "kwargs", ")", ":", "# Call regular find() if USER_IFIND_MODE is nocase_collation", "if", "self", ".", "user_manager", ".", "USER_IFIND_MODE", "==", "'nocase_collation'", ":", "return", "self",...
Retrieve the first object of type ``ObjectClass``, matching the specified filters in ``**kwargs`` -- case insensitive. | If USER_IFIND_MODE is 'nocase_collation' this method maps to find_first_object(). | If USER_IFIND_MODE is 'ifind' this method performs a case insensitive find.
[ "Retrieve", "the", "first", "object", "of", "type", "ObjectClass", "matching", "the", "specified", "filters", "in", "**", "kwargs", "--", "case", "insensitive", "." ]
python
train
KarchinLab/probabilistic2020
prob2020/python/indel.py
https://github.com/KarchinLab/probabilistic2020/blob/5d70583b0a7c07cfe32e95f3a70e05df412acb84/prob2020/python/indel.py#L146-L181
def keep_indels(mut_df, indel_len_col=True, indel_type_col=True): """Filters out all mutations that are not indels. Requires that one of the alleles have '-' indicating either an insertion or deletion depending if found in reference allele or somatic allele columns, resp...
[ "def", "keep_indels", "(", "mut_df", ",", "indel_len_col", "=", "True", ",", "indel_type_col", "=", "True", ")", ":", "# keep only frameshifts", "mut_df", "=", "mut_df", "[", "is_indel_annotation", "(", "mut_df", ")", "]", "if", "indel_len_col", ":", "# calculat...
Filters out all mutations that are not indels. Requires that one of the alleles have '-' indicating either an insertion or deletion depending if found in reference allele or somatic allele columns, respectively. Parameters ---------- mut_df : pd.DataFrame mutation input file as a dataf...
[ "Filters", "out", "all", "mutations", "that", "are", "not", "indels", "." ]
python
train
raiden-network/raiden
raiden/network/proxies/token.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token.py#L49-L112
def approve( self, allowed_address: Address, allowance: TokenAmount, ): """ Aprove `allowed_address` to transfer up to `deposit` amount of token. Note: For channel deposit please use the channel proxy, since it does additional validations...
[ "def", "approve", "(", "self", ",", "allowed_address", ":", "Address", ",", "allowance", ":", "TokenAmount", ",", ")", ":", "# Note that given_block_identifier is not used here as there", "# are no preconditions to check before sending the transaction", "log_details", "=", "{",...
Aprove `allowed_address` to transfer up to `deposit` amount of token. Note: For channel deposit please use the channel proxy, since it does additional validations.
[ "Aprove", "allowed_address", "to", "transfer", "up", "to", "deposit", "amount", "of", "token", "." ]
python
train
pmacosta/ptrie
ptrie/ptrie.py
https://github.com/pmacosta/ptrie/blob/c176d3ee810b7b5243c7ff2bbf2f1af0b0fff2a8/ptrie/ptrie.py#L426-L508
def add_nodes(self, nodes): # noqa: D302 r""" Add nodes to tree. :param nodes: Node(s) to add with associated data. If there are several list items in the argument with the same node name the resulting node data is a list with items ...
[ "def", "add_nodes", "(", "self", ",", "nodes", ")", ":", "# noqa: D302", "self", ".", "_validate_nodes_with_data", "(", "nodes", ")", "nodes", "=", "nodes", "if", "isinstance", "(", "nodes", ",", "list", ")", "else", "[", "nodes", "]", "# Create root node (i...
r""" Add nodes to tree. :param nodes: Node(s) to add with associated data. If there are several list items in the argument with the same node name the resulting node data is a list with items corresponding to the data of each entry in th...
[ "r", "Add", "nodes", "to", "tree", "." ]
python
train
ultrabug/py3status
py3status/parse_config.py
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L180-L214
def check_child_friendly(self, name): """ Check if a module is a container and so can have children """ name = name.split()[0] if name in self.container_modules: return root = os.path.dirname(os.path.realpath(__file__)) module_path = os.path.join(root,...
[ "def", "check_child_friendly", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "split", "(", ")", "[", "0", "]", "if", "name", "in", "self", ".", "container_modules", ":", "return", "root", "=", "os", ".", "path", ".", "dirname", "(", ...
Check if a module is a container and so can have children
[ "Check", "if", "a", "module", "is", "a", "container", "and", "so", "can", "have", "children" ]
python
train
singularityhub/singularity-python
singularity/views/trees.py
https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/views/trees.py#L250-L284
def make_interactive_tree(matrix=None,labels=None): '''make interactive tree will return complete html for an interactive tree :param title: a title for the plot, if not defined, will be left out. ''' from scipy.cluster.hierarchy import ( dendrogram, linkage, to_tree ) ...
[ "def", "make_interactive_tree", "(", "matrix", "=", "None", ",", "labels", "=", "None", ")", ":", "from", "scipy", ".", "cluster", ".", "hierarchy", "import", "(", "dendrogram", ",", "linkage", ",", "to_tree", ")", "d3", "=", "None", "from", "scipy", "."...
make interactive tree will return complete html for an interactive tree :param title: a title for the plot, if not defined, will be left out.
[ "make", "interactive", "tree", "will", "return", "complete", "html", "for", "an", "interactive", "tree", ":", "param", "title", ":", "a", "title", "for", "the", "plot", "if", "not", "defined", "will", "be", "left", "out", "." ]
python
train
synw/dataswim
dataswim/data/stats.py
https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/stats.py#L8-L21
def lreg(self, xcol, ycol, name="Regression"): """ Add a column to the main dataframe populted with the model's linear regression for a column """ try: x = self.df[xcol].values.reshape(-1, 1) y = self.df[ycol] lm = linear_model.LinearRegression...
[ "def", "lreg", "(", "self", ",", "xcol", ",", "ycol", ",", "name", "=", "\"Regression\"", ")", ":", "try", ":", "x", "=", "self", ".", "df", "[", "xcol", "]", ".", "values", ".", "reshape", "(", "-", "1", ",", "1", ")", "y", "=", "self", ".",...
Add a column to the main dataframe populted with the model's linear regression for a column
[ "Add", "a", "column", "to", "the", "main", "dataframe", "populted", "with", "the", "model", "s", "linear", "regression", "for", "a", "column" ]
python
train
google/brotli
research/brotlidump.py
https://github.com/google/brotli/blob/4b2b2d4f83ffeaac7708e44409fe34896a01a278/research/brotlidump.py#L1385-L1422
def formatBitData(self, pos, width1, width2=0): """Show formatted bit data: Bytes are separated by commas whole bytes are displayed in hex >>> Layout(olleke).formatBitData(6, 2, 16) '|00h|2Eh,|00' >>> Layout(olleke).formatBitData(4, 1, 0) '1' """ r...
[ "def", "formatBitData", "(", "self", ",", "pos", ",", "width1", ",", "width2", "=", "0", ")", ":", "result", "=", "[", "]", "#make empty prefix code explicit", "if", "width1", "==", "0", ":", "result", "=", "[", "'()'", ",", "','", "]", "for", "width",...
Show formatted bit data: Bytes are separated by commas whole bytes are displayed in hex >>> Layout(olleke).formatBitData(6, 2, 16) '|00h|2Eh,|00' >>> Layout(olleke).formatBitData(4, 1, 0) '1'
[ "Show", "formatted", "bit", "data", ":", "Bytes", "are", "separated", "by", "commas", "whole", "bytes", "are", "displayed", "in", "hex", ">>>", "Layout", "(", "olleke", ")", ".", "formatBitData", "(", "6", "2", "16", ")", "|00h|2Eh", "|00", ">>>", "Layou...
python
test
jbloomlab/phydms
phydmslib/treelikelihood.py
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/treelikelihood.py#L553-L582
def paramsarray(self, value): """Set new `paramsarray` and update via `updateParams`.""" nparams = len(self._index_to_param) assert (isinstance(value, scipy.ndarray) and value.ndim == 1), ( "paramsarray must be 1-dim ndarray") assert len(value) == nparams, ("Assigning par...
[ "def", "paramsarray", "(", "self", ",", "value", ")", ":", "nparams", "=", "len", "(", "self", ".", "_index_to_param", ")", "assert", "(", "isinstance", "(", "value", ",", "scipy", ".", "ndarray", ")", "and", "value", ".", "ndim", "==", "1", ")", ","...
Set new `paramsarray` and update via `updateParams`.
[ "Set", "new", "paramsarray", "and", "update", "via", "updateParams", "." ]
python
train
learningequality/ricecooker
ricecooker/sushi_bar_client.py
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/sushi_bar_client.py#L269-L296
def execute_command_in_message(controller, cliargs, clioptions, message): """ Runs the command in message['command'], which is one of: 'start' / 'stop'. Updates the chef's initial command line args and options with args and options provided in message['args'] and message['options']. """ SUPPORTE...
[ "def", "execute_command_in_message", "(", "controller", ",", "cliargs", ",", "clioptions", ",", "message", ")", ":", "SUPPORTED_COMMANDS", "=", "[", "'start'", "]", "# , 'stop'] # TODO", "print", "(", "message", ")", "# args and options from SushiBar overrride command lin...
Runs the command in message['command'], which is one of: 'start' / 'stop'. Updates the chef's initial command line args and options with args and options provided in message['args'] and message['options'].
[ "Runs", "the", "command", "in", "message", "[", "command", "]", "which", "is", "one", "of", ":", "start", "/", "stop", ".", "Updates", "the", "chef", "s", "initial", "command", "line", "args", "and", "options", "with", "args", "and", "options", "provided...
python
train
videntity/django-djmongo
djmongo/console/utils.py
https://github.com/videntity/django-djmongo/blob/7534e0981a2bc12634cf3f1ed03353623dc57565/djmongo/console/utils.py#L131-L148
def mongodb_ensure_index(database_name, collection_name, key): """Ensure Index""" try: mongodb_client_url = getattr(settings, 'MONGODB_CLIENT', 'mongodb://localhost:27017/') mc = MongoClient(mongodb_client_url,document_class=OrderedDict) dbs = mc[databas...
[ "def", "mongodb_ensure_index", "(", "database_name", ",", "collection_name", ",", "key", ")", ":", "try", ":", "mongodb_client_url", "=", "getattr", "(", "settings", ",", "'MONGODB_CLIENT'", ",", "'mongodb://localhost:27017/'", ")", "mc", "=", "MongoClient", "(", ...
Ensure Index
[ "Ensure", "Index" ]
python
train
gbiggs/rtctree
rtctree/node.py
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/node.py#L169-L218
def iterate(self, func, args=None, filter=[]): '''Call a function on this node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node ...
[ "def", "iterate", "(", "self", ",", "func", ",", "args", "=", "None", ",", "filter", "=", "[", "]", ")", ":", "with", "self", ".", "_mutex", ":", "result", "=", "[", "]", "if", "filter", ":", "filters_passed", "=", "True", "for", "f", "in", "filt...
Call a function on this node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node in the iteration and args is the value of @ref arg...
[ "Call", "a", "function", "on", "this", "node", "and", "recursively", "all", "its", "children", "." ]
python
train
martinrusev/solid-python
solidpy/utils/wsgi.py
https://github.com/martinrusev/solid-python/blob/c5c39ad43c19e6746ea0297e0d440a2fccfb25ed/solidpy/utils/wsgi.py#L25-L45
def get_host(environ): """Return the real host for the given WSGI environment. This takes care of the `X-Forwarded-Host` header. :param environ: the WSGI environment to get the host of. """ scheme = environ.get('wsgi.url_scheme') if 'HTTP_X_FORWARDED_HOST' in environ: result = environ[...
[ "def", "get_host", "(", "environ", ")", ":", "scheme", "=", "environ", ".", "get", "(", "'wsgi.url_scheme'", ")", "if", "'HTTP_X_FORWARDED_HOST'", "in", "environ", ":", "result", "=", "environ", "[", "'HTTP_X_FORWARDED_HOST'", "]", "elif", "'HTTP_HOST'", "in", ...
Return the real host for the given WSGI environment. This takes care of the `X-Forwarded-Host` header. :param environ: the WSGI environment to get the host of.
[ "Return", "the", "real", "host", "for", "the", "given", "WSGI", "environment", ".", "This", "takes", "care", "of", "the", "X", "-", "Forwarded", "-", "Host", "header", "." ]
python
train
yyuu/botornado
boto/mturk/connection.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/mturk/connection.py#L148-L224
def create_hit(self, hit_type=None, question=None, lifetime=datetime.timedelta(days=7), max_assignments=1, title=None, description=None, keywords=None, reward=None, duration=datetime.timedelta(days=7), approval_delay=None, a...
[ "def", "create_hit", "(", "self", ",", "hit_type", "=", "None", ",", "question", "=", "None", ",", "lifetime", "=", "datetime", ".", "timedelta", "(", "days", "=", "7", ")", ",", "max_assignments", "=", "1", ",", "title", "=", "None", ",", "description...
Creates a new HIT. Returns a ResultSet See: http://docs.amazonwebservices.com/AWSMechanicalTurkRequester/2006-10-31/ApiReference_CreateHITOperation.html
[ "Creates", "a", "new", "HIT", ".", "Returns", "a", "ResultSet", "See", ":", "http", ":", "//", "docs", ".", "amazonwebservices", ".", "com", "/", "AWSMechanicalTurkRequester", "/", "2006", "-", "10", "-", "31", "/", "ApiReference_CreateHITOperation", ".", "h...
python
train
tanghaibao/goatools
goatools/cli/gosubdag_plot.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L205-L227
def _plt_gogrouped(self, goids, go2color_usr, **kws): """Plot grouped GO IDs.""" fout_img = self.get_outfile(kws['outfile'], goids) sections = read_sections(kws['sections'], exclude_ungrouped=True) # print ("KWWSSSSSSSS", kws) # kws_plt = {k:v for k, v in kws.items if k in self.k...
[ "def", "_plt_gogrouped", "(", "self", ",", "goids", ",", "go2color_usr", ",", "*", "*", "kws", ")", ":", "fout_img", "=", "self", ".", "get_outfile", "(", "kws", "[", "'outfile'", "]", ",", "goids", ")", "sections", "=", "read_sections", "(", "kws", "[...
Plot grouped GO IDs.
[ "Plot", "grouped", "GO", "IDs", "." ]
python
train
briancappello/flask-unchained
flask_unchained/string_utils.py
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/string_utils.py#L8-L23
def camel_case(string): """ Converts a string to camel case. For example:: camel_case('one_two_three') -> 'oneTwoThree' """ if not string: return string parts = snake_case(string).split('_') rv = '' while parts: part = parts.pop(0) rv += part or '_' i...
[ "def", "camel_case", "(", "string", ")", ":", "if", "not", "string", ":", "return", "string", "parts", "=", "snake_case", "(", "string", ")", ".", "split", "(", "'_'", ")", "rv", "=", "''", "while", "parts", ":", "part", "=", "parts", ".", "pop", "...
Converts a string to camel case. For example:: camel_case('one_two_three') -> 'oneTwoThree'
[ "Converts", "a", "string", "to", "camel", "case", ".", "For", "example", "::" ]
python
train
thanethomson/statik
statik/utils.py
https://github.com/thanethomson/statik/blob/56b1b5a2cb05a97afa81f428bfcefc833e935b8d/statik/utils.py#L141-L163
def copy_file_if_modified(src_path, dest_path): """Only copies the file from the source path to the destination path if it doesn't exist yet or it has been modified. Intended to provide something of an optimisation when a project has large trees of assets.""" # if the destination path is a directory, delet...
[ "def", "copy_file_if_modified", "(", "src_path", ",", "dest_path", ")", ":", "# if the destination path is a directory, delete it completely - we assume here we are", "# writing a file to the filesystem", "if", "os", ".", "path", ".", "isdir", "(", "dest_path", ")", ":", "shu...
Only copies the file from the source path to the destination path if it doesn't exist yet or it has been modified. Intended to provide something of an optimisation when a project has large trees of assets.
[ "Only", "copies", "the", "file", "from", "the", "source", "path", "to", "the", "destination", "path", "if", "it", "doesn", "t", "exist", "yet", "or", "it", "has", "been", "modified", ".", "Intended", "to", "provide", "something", "of", "an", "optimisation"...
python
train
eykd/paved
paved/docs.py
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L24-L29
def sphinx_make(*targets): """Call the Sphinx Makefile with the specified targets. `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides). """ sh('make %s' % ' '.join(targets), cwd=options.paved.docs.path)
[ "def", "sphinx_make", "(", "*", "targets", ")", ":", "sh", "(", "'make %s'", "%", "' '", ".", "join", "(", "targets", ")", ",", "cwd", "=", "options", ".", "paved", ".", "docs", ".", "path", ")" ]
Call the Sphinx Makefile with the specified targets. `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).
[ "Call", "the", "Sphinx", "Makefile", "with", "the", "specified", "targets", "." ]
python
valid
ARMmbed/icetea
icetea_lib/CliResponse.py
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/CliResponse.py#L144-L154
def verify_response_time(self, expected_below): """ Verify that response time (time span between request-response) is reasonable. :param expected_below: integer :return: Nothing :raises: ValueError if timedelta > expected time """ if self.timedelta > expected_bel...
[ "def", "verify_response_time", "(", "self", ",", "expected_below", ")", ":", "if", "self", ".", "timedelta", ">", "expected_below", ":", "raise", "ValueError", "(", "\"Response time is more (%f) than expected (%f)!\"", "%", "(", "self", ".", "timedelta", ",", "expec...
Verify that response time (time span between request-response) is reasonable. :param expected_below: integer :return: Nothing :raises: ValueError if timedelta > expected time
[ "Verify", "that", "response", "time", "(", "time", "span", "between", "request", "-", "response", ")", "is", "reasonable", "." ]
python
train
spyder-ide/conda-manager
conda_manager/api/conda_api.py
https://github.com/spyder-ide/conda-manager/blob/89a2126cbecefc92185cf979347ccac1c5ee5d9d/conda_manager/api/conda_api.py#L884-L887
def clear_lock(self, abspath=True): """Clean any conda lock in the system.""" cmd_list = ['clean', '--lock', '--json'] return self._call_and_parse(cmd_list, abspath=abspath)
[ "def", "clear_lock", "(", "self", ",", "abspath", "=", "True", ")", ":", "cmd_list", "=", "[", "'clean'", ",", "'--lock'", ",", "'--json'", "]", "return", "self", ".", "_call_and_parse", "(", "cmd_list", ",", "abspath", "=", "abspath", ")" ]
Clean any conda lock in the system.
[ "Clean", "any", "conda", "lock", "in", "the", "system", "." ]
python
train
projectatomic/atomic-reactor
atomic_reactor/rpm_util.py
https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/rpm_util.py#L36-L95
def parse_rpm_output(output, tags=None, separator=';'): """ Parse output of the rpm query. :param output: list, decoded output (str) from the rpm subprocess :param tags: list, str fields used for query output :return: list, dicts describing each rpm package """ if tags is None: tag...
[ "def", "parse_rpm_output", "(", "output", ",", "tags", "=", "None", ",", "separator", "=", "';'", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "image_component_rpm_tags", "def", "field", "(", "tag", ")", ":", "\"\"\"\n Get a field value by na...
Parse output of the rpm query. :param output: list, decoded output (str) from the rpm subprocess :param tags: list, str fields used for query output :return: list, dicts describing each rpm package
[ "Parse", "output", "of", "the", "rpm", "query", "." ]
python
train
aiortc/aioice
aioice/ice.py
https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L554-L598
def check_incoming(self, message, addr, protocol): """ Handle a succesful incoming check. """ component = protocol.local_candidate.component # find remote candidate remote_candidate = None for c in self._remote_candidates: if c.host == addr[0] and c.p...
[ "def", "check_incoming", "(", "self", ",", "message", ",", "addr", ",", "protocol", ")", ":", "component", "=", "protocol", ".", "local_candidate", ".", "component", "# find remote candidate", "remote_candidate", "=", "None", "for", "c", "in", "self", ".", "_r...
Handle a succesful incoming check.
[ "Handle", "a", "succesful", "incoming", "check", "." ]
python
train
marshmallow-code/webargs
src/webargs/falconparser.py
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/falconparser.py#L125-L128
def parse_headers(self, req, name, field): """Pull a header value from the request.""" # Use req.get_headers rather than req.headers for performance return req.get_header(name, required=False) or core.missing
[ "def", "parse_headers", "(", "self", ",", "req", ",", "name", ",", "field", ")", ":", "# Use req.get_headers rather than req.headers for performance", "return", "req", ".", "get_header", "(", "name", ",", "required", "=", "False", ")", "or", "core", ".", "missin...
Pull a header value from the request.
[ "Pull", "a", "header", "value", "from", "the", "request", "." ]
python
train
HPENetworking/PYHPEIMC
build/lib/pyhpeimc/plat/icc.py
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/plat/icc.py#L120-L148
def get_template_id(template_name, auth, url): """ Helper function takes str input of folder name and returns str numerical id of the folder. :param folder_name: str name of the folder :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC R...
[ "def", "get_template_id", "(", "template_name", ",", "auth", ",", "url", ")", ":", "object_list", "=", "get_cfg_template", "(", "auth", "=", "auth", ",", "url", "=", "url", ")", "for", "object", "in", "object_list", ":", "if", "object", "[", "'confFileName...
Helper function takes str input of folder name and returns str numerical id of the folder. :param folder_name: str name of the folder :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass ...
[ "Helper", "function", "takes", "str", "input", "of", "folder", "name", "and", "returns", "str", "numerical", "id", "of", "the", "folder", ".", ":", "param", "folder_name", ":", "str", "name", "of", "the", "folder" ]
python
train
DarkEnergySurvey/ugali
ugali/utils/projector.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/projector.py#L422-L440
def hms2dec(hms): """ Convert longitude from hours,minutes,seconds in string or 3-array format to decimal degrees. ADW: This really should be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. if isstring(hms): hour,minute,second = np.array(re....
[ "def", "hms2dec", "(", "hms", ")", ":", "DEGREE", "=", "360.", "HOUR", "=", "24.", "MINUTE", "=", "60.", "SECOND", "=", "3600.", "if", "isstring", "(", "hms", ")", ":", "hour", ",", "minute", ",", "second", "=", "np", ".", "array", "(", "re", "."...
Convert longitude from hours,minutes,seconds in string or 3-array format to decimal degrees. ADW: This really should be replaced by astropy
[ "Convert", "longitude", "from", "hours", "minutes", "seconds", "in", "string", "or", "3", "-", "array", "format", "to", "decimal", "degrees", "." ]
python
train
wbond/asn1crypto
dev/deps.py
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/deps.py#L56-L83
def _download(url, dest): """ Downloads a URL to a directory :param url: The URL to download :param dest: The path to the directory to save the file in :return: The filesystem path to the saved file """ print('Downloading %s' % url) filename = os.path.basename...
[ "def", "_download", "(", "url", ",", "dest", ")", ":", "print", "(", "'Downloading %s'", "%", "url", ")", "filename", "=", "os", ".", "path", ".", "basename", "(", "url", ")", "dest_path", "=", "os", ".", "path", ".", "join", "(", "dest", ",", "fil...
Downloads a URL to a directory :param url: The URL to download :param dest: The path to the directory to save the file in :return: The filesystem path to the saved file
[ "Downloads", "a", "URL", "to", "a", "directory" ]
python
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/tools/common.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L285-L320
def get_invocation_command_nodefault( toolset, tool, user_provided_command=[], additional_paths=[], path_last=False): """ A helper rule to get the command to invoke some tool. If 'user-provided-command' is not given, tries to find binary named 'tool' in PATH and in the passed 'additional...
[ "def", "get_invocation_command_nodefault", "(", "toolset", ",", "tool", ",", "user_provided_command", "=", "[", "]", ",", "additional_paths", "=", "[", "]", ",", "path_last", "=", "False", ")", ":", "assert", "isinstance", "(", "toolset", ",", "basestring", ")...
A helper rule to get the command to invoke some tool. If 'user-provided-command' is not given, tries to find binary named 'tool' in PATH and in the passed 'additional-path'. Otherwise, verifies that the first element of 'user-provided-command' is an existing program. This rule returns t...
[ "A", "helper", "rule", "to", "get", "the", "command", "to", "invoke", "some", "tool", ".", "If", "user", "-", "provided", "-", "command", "is", "not", "given", "tries", "to", "find", "binary", "named", "tool", "in", "PATH", "and", "in", "the", "passed"...
python
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1592-L1632
def kernels_list_cli(self, mine=False, page=1, page_size=20, search=None, csv_display=False, parent=None, competition=None, ...
[ "def", "kernels_list_cli", "(", "self", ",", "mine", "=", "False", ",", "page", "=", "1", ",", "page_size", "=", "20", ",", "search", "=", "None", ",", "csv_display", "=", "False", ",", "parent", "=", "None", ",", "competition", "=", "None", ",", "da...
client wrapper for kernels_list, see this function for arguments. Additional arguments are provided here. Parameters ========== csv_display: if True, print comma separated values instead of table
[ "client", "wrapper", "for", "kernels_list", "see", "this", "function", "for", "arguments", ".", "Additional", "arguments", "are", "provided", "here", ".", "Parameters", "==========", "csv_display", ":", "if", "True", "print", "comma", "separated", "values", "inste...
python
train
CiscoTestAutomation/yang
ncdiff/src/yang/ncdiff/netconf.py
https://github.com/CiscoTestAutomation/yang/blob/c70ec5ac5a91f276c4060009203770ece92e76b4/ncdiff/src/yang/ncdiff/netconf.py#L597-L683
def _node_add_with_peer_list(self, child_self, child_other): '''_node_add_with_peer_list Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are list nodes. Element child_self will be modified during the pro...
[ "def", "_node_add_with_peer_list", "(", "self", ",", "child_self", ",", "child_other", ")", ":", "parent_self", "=", "child_self", ".", "getparent", "(", ")", "s_node", "=", "self", ".", "device", ".", "get_schema_node", "(", "child_self", ")", "if", "child_ot...
_node_add_with_peer_list Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are list nodes. Element child_self will be modified during the process. RFC6020 section 7.8.6 is a reference of this method. ...
[ "_node_add_with_peer_list" ]
python
train
cokelaer/spectrum
doc/sphinxext/sphinx_gallery/docs_resolv.py
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/docs_resolv.py#L408-L436
def embed_code_links(app, exception): """Embed hyperlinks to documentation into example code""" if exception is not None: return # No need to waste time embedding hyperlinks when not running the examples # XXX: also at the time of writing this fixes make html-noplot # for some reason I don'...
[ "def", "embed_code_links", "(", "app", ",", "exception", ")", ":", "if", "exception", "is", "not", "None", ":", "return", "# No need to waste time embedding hyperlinks when not running the examples", "# XXX: also at the time of writing this fixes make html-noplot", "# for some reas...
Embed hyperlinks to documentation into example code
[ "Embed", "hyperlinks", "to", "documentation", "into", "example", "code" ]
python
valid
UCSBarchlab/PyRTL
pyrtl/transform.py
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L43-L48
def all_nets(transform_func): """Decorator that wraps a net transform function""" @functools.wraps(transform_func) def t_res(**kwargs): net_transform(transform_func, **kwargs) return t_res
[ "def", "all_nets", "(", "transform_func", ")", ":", "@", "functools", ".", "wraps", "(", "transform_func", ")", "def", "t_res", "(", "*", "*", "kwargs", ")", ":", "net_transform", "(", "transform_func", ",", "*", "*", "kwargs", ")", "return", "t_res" ]
Decorator that wraps a net transform function
[ "Decorator", "that", "wraps", "a", "net", "transform", "function" ]
python
train
SCIP-Interfaces/PySCIPOpt
examples/finished/ssa.py
https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/finished/ssa.py#L14-L53
def ssa(n,h,K,f,T): """ssa -- multi-stage (serial) safety stock allocation model Parameters: - n: number of stages - h[i]: inventory cost on stage i - K: number of linear segments - f: (non-linear) cost function - T[i]: production lead time on stage i Returns the mode...
[ "def", "ssa", "(", "n", ",", "h", ",", "K", ",", "f", ",", "T", ")", ":", "model", "=", "Model", "(", "\"safety stock allocation\"", ")", "# calculate endpoints for linear segments", "a", ",", "b", "=", "{", "}", ",", "{", "}", "for", "i", "in", "ran...
ssa -- multi-stage (serial) safety stock allocation model Parameters: - n: number of stages - h[i]: inventory cost on stage i - K: number of linear segments - f: (non-linear) cost function - T[i]: production lead time on stage i Returns the model with the piecewise linear...
[ "ssa", "--", "multi", "-", "stage", "(", "serial", ")", "safety", "stock", "allocation", "model", "Parameters", ":", "-", "n", ":", "number", "of", "stages", "-", "h", "[", "i", "]", ":", "inventory", "cost", "on", "stage", "i", "-", "K", ":", "num...
python
train
anchore/anchore
anchore/cli/toolbox.py
https://github.com/anchore/anchore/blob/8a4d5b9708e27856312d303aae3f04f3c72039d6/anchore/cli/toolbox.py#L144-L246
def setup_module_dev(destdir): """ Sets up a development environment suitable for working on anchore modules (queries, etc) in the specified directory. Creates a copied environment in the destination containing the module scripts, unpacked image(s) and helper scripts such that a module script that works...
[ "def", "setup_module_dev", "(", "destdir", ")", ":", "if", "not", "nav", ":", "sys", ".", "exit", "(", "1", ")", "ecode", "=", "0", "try", ":", "anchore_print", "(", "\"Anchore Module Development Environment\\n\"", ")", "helpstr", "=", "\"This tool has set up an...
Sets up a development environment suitable for working on anchore modules (queries, etc) in the specified directory. Creates a copied environment in the destination containing the module scripts, unpacked image(s) and helper scripts such that a module script that works in the environment can be copied into the ...
[ "Sets", "up", "a", "development", "environment", "suitable", "for", "working", "on", "anchore", "modules", "(", "queries", "etc", ")", "in", "the", "specified", "directory", ".", "Creates", "a", "copied", "environment", "in", "the", "destination", "containing", ...
python
train
saltstack/salt
salt/modules/gcp_addon.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gcp_addon.py#L66-L137
def route_create(credential_file=None, project_id=None, name=None, dest_range=None, next_hop_instance=None, instance_zone=None, tags=None, network=None, priority=None ...
[ "def", "route_create", "(", "credential_file", "=", "None", ",", "project_id", "=", "None", ",", "name", "=", "None", ",", "dest_range", "=", "None", ",", "next_hop_instance", "=", "None", ",", "instance_zone", "=", "None", ",", "tags", "=", "None", ",", ...
Create a route to send traffic destined to the Internet through your gateway instance credential_file : string File location of application default credential. For more information, refer: https://developers.google.com/identity/protocols/application-default-credentials project_id : string ...
[ "Create", "a", "route", "to", "send", "traffic", "destined", "to", "the", "Internet", "through", "your", "gateway", "instance" ]
python
train
lvh/txeasymail
txeasymail/html.py
https://github.com/lvh/txeasymail/blob/7b845a5238b1371824854468646d54653a426f09/txeasymail/html.py#L27-L33
def textFromHTML(html): """ Cleans and parses text from the given HTML. """ cleaner = lxml.html.clean.Cleaner(scripts=True) cleaned = cleaner.clean_html(html) return lxml.html.fromstring(cleaned).text_content()
[ "def", "textFromHTML", "(", "html", ")", ":", "cleaner", "=", "lxml", ".", "html", ".", "clean", ".", "Cleaner", "(", "scripts", "=", "True", ")", "cleaned", "=", "cleaner", ".", "clean_html", "(", "html", ")", "return", "lxml", ".", "html", ".", "fr...
Cleans and parses text from the given HTML.
[ "Cleans", "and", "parses", "text", "from", "the", "given", "HTML", "." ]
python
train
daethnir/authprogs
authprogs/authprogs.py
https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L344-L368
def find_match_command(self, rule): """Return a matching (possibly munged) command, if found in rule.""" command_string = rule['command'] command_list = command_string.split() self.logdebug('comparing "%s" to "%s"\n' % (command_list, self.original_command_list)) ...
[ "def", "find_match_command", "(", "self", ",", "rule", ")", ":", "command_string", "=", "rule", "[", "'command'", "]", "command_list", "=", "command_string", ".", "split", "(", ")", "self", ".", "logdebug", "(", "'comparing \"%s\" to \"%s\"\\n'", "%", "(", "co...
Return a matching (possibly munged) command, if found in rule.
[ "Return", "a", "matching", "(", "possibly", "munged", ")", "command", "if", "found", "in", "rule", "." ]
python
train
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py#L937-L951
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_nbr_wwn(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_fabric_trunk_info = ET.Element("show_fabric_trunk_info") config = show_fabric_trunk_info ...
[ "def", "show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_nbr_wwn", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_fabric_trunk_info", "=", "ET", ".", "Element",...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
lk-geimfari/mimesis
mimesis/providers/units.py
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/units.py#L35-L51
def prefix(self, sign: Optional[PrefixSign] = None, symbol: bool = False) -> str: """Get a random prefix for the International System of Units. :param sign: Sing of number. :param symbol: Return symbol of prefix. :return: Prefix for SI. :raises NonEnumerableError:...
[ "def", "prefix", "(", "self", ",", "sign", ":", "Optional", "[", "PrefixSign", "]", "=", "None", ",", "symbol", ":", "bool", "=", "False", ")", "->", "str", ":", "prefixes", "=", "SI_PREFIXES_SYM", "if", "symbol", "else", "SI_PREFIXES", "key", "=", "se...
Get a random prefix for the International System of Units. :param sign: Sing of number. :param symbol: Return symbol of prefix. :return: Prefix for SI. :raises NonEnumerableError: if sign is not supported. :Example: mega
[ "Get", "a", "random", "prefix", "for", "the", "International", "System", "of", "Units", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/core/states/container_state.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1749-L1767
def _check_data_port_id(self, data_port): """Checks the validity of a data port id Checks whether the id of the given data port is already used by anther data port (input, output, scoped vars) within the state. :param rafcon.core.data_port.DataPort data_port: The data port to be checke...
[ "def", "_check_data_port_id", "(", "self", ",", "data_port", ")", ":", "# First check inputs and outputs", "valid", ",", "message", "=", "super", "(", "ContainerState", ",", "self", ")", ".", "_check_data_port_id", "(", "data_port", ")", "if", "not", "valid", ":...
Checks the validity of a data port id Checks whether the id of the given data port is already used by anther data port (input, output, scoped vars) within the state. :param rafcon.core.data_port.DataPort data_port: The data port to be checked :return bool validity, str message: validit...
[ "Checks", "the", "validity", "of", "a", "data", "port", "id" ]
python
train
autokey/autokey
lib/autokey/qtapp.py
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtapp.py#L271-L279
def toggle_service(self): """ Convenience method for toggling the expansion service on or off. This is called by the global hotkey. """ self.monitoring_disabled.emit(not self.service.is_running()) if self.service.is_running(): self.pause_service() else: ...
[ "def", "toggle_service", "(", "self", ")", ":", "self", ".", "monitoring_disabled", ".", "emit", "(", "not", "self", ".", "service", ".", "is_running", "(", ")", ")", "if", "self", ".", "service", ".", "is_running", "(", ")", ":", "self", ".", "pause_s...
Convenience method for toggling the expansion service on or off. This is called by the global hotkey.
[ "Convenience", "method", "for", "toggling", "the", "expansion", "service", "on", "or", "off", ".", "This", "is", "called", "by", "the", "global", "hotkey", "." ]
python
train
meejah/txtorcon
txtorcon/onion.py
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/onion.py#L1396-L1413
def _validate_ports_low_level(ports): """ Internal helper. Validates the 'ports' argument to EphemeralOnionService or EphemeralAuthenticatedOnionService returning None on success or raising ValueError otherwise. This only accepts the "list of strings" variants; some higher-level APIs also ...
[ "def", "_validate_ports_low_level", "(", "ports", ")", ":", "if", "not", "isinstance", "(", "ports", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"'ports' must be a list of strings\"", ")", "if", "any", "(", "[", "not", "isins...
Internal helper. Validates the 'ports' argument to EphemeralOnionService or EphemeralAuthenticatedOnionService returning None on success or raising ValueError otherwise. This only accepts the "list of strings" variants; some higher-level APIs also allow lists of ints or lists of 2-tuples, but ...
[ "Internal", "helper", "." ]
python
train
angr/angr
angr/storage/paged_memory.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/storage/paged_memory.py#L207-L220
def load_mo(self, state, page_idx): """ Loads a memory object from memory. :param page_idx: the index into the page :returns: a tuple of the object """ try: key = next(self._storage.irange(maximum=page_idx, reverse=True)) except StopIteration: ...
[ "def", "load_mo", "(", "self", ",", "state", ",", "page_idx", ")", ":", "try", ":", "key", "=", "next", "(", "self", ".", "_storage", ".", "irange", "(", "maximum", "=", "page_idx", ",", "reverse", "=", "True", ")", ")", "except", "StopIteration", ":...
Loads a memory object from memory. :param page_idx: the index into the page :returns: a tuple of the object
[ "Loads", "a", "memory", "object", "from", "memory", "." ]
python
train
saltstack/salt
salt/cloud/clouds/aliyun.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L124-L144
def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locat...
[ "def", "avail_locations", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_locations function must be called with '", "'-f or --function, or with the --list-locations option'", ")", "params", "=", "{",...
Return a dict of all available VM locations on the cloud provider with relevant data
[ "Return", "a", "dict", "of", "all", "available", "VM", "locations", "on", "the", "cloud", "provider", "with", "relevant", "data" ]
python
train
Qiskit/qiskit-terra
qiskit/converters/ast_to_dag.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/ast_to_dag.py#L200-L207
def _process_if(self, node): """Process an if node.""" creg_name = node.children[0].name creg = self.dag.cregs[creg_name] cval = node.children[1].value self.condition = (creg, cval) self._process_node(node.children[2]) self.condition = None
[ "def", "_process_if", "(", "self", ",", "node", ")", ":", "creg_name", "=", "node", ".", "children", "[", "0", "]", ".", "name", "creg", "=", "self", ".", "dag", ".", "cregs", "[", "creg_name", "]", "cval", "=", "node", ".", "children", "[", "1", ...
Process an if node.
[ "Process", "an", "if", "node", "." ]
python
test
pyviz/holoviews
holoviews/core/options.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/options.py#L1581-L1617
def create_custom_trees(cls, obj, options=None): """ Returns the appropriate set of customized subtree clones for an object, suitable for merging with Store.custom_options (i.e with the ids appropriately offset). Note if an object has no integer ids a new OptionTree is built. ...
[ "def", "create_custom_trees", "(", "cls", ",", "obj", ",", "options", "=", "None", ")", ":", "clones", ",", "id_mapping", "=", "{", "}", ",", "[", "]", "obj_ids", "=", "cls", ".", "get_object_ids", "(", "obj", ")", "offset", "=", "cls", ".", "id_offs...
Returns the appropriate set of customized subtree clones for an object, suitable for merging with Store.custom_options (i.e with the ids appropriately offset). Note if an object has no integer ids a new OptionTree is built. The id_mapping return value is a list mapping the ids that ...
[ "Returns", "the", "appropriate", "set", "of", "customized", "subtree", "clones", "for", "an", "object", "suitable", "for", "merging", "with", "Store", ".", "custom_options", "(", "i", ".", "e", "with", "the", "ids", "appropriately", "offset", ")", ".", "Note...
python
train
gem/oq-engine
openquake/hazardlib/sourceconverter.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L918-L943
def mfds2multimfd(mfds): """ Convert a list of MFD nodes into a single MultiMFD node """ _, kind = mfds[0].tag.split('}') node = Node('multiMFD', dict(kind=kind, size=len(mfds))) lengths = None for field in mfd.multi_mfd.ASSOC[kind][1:]: alias = mfd.multi_mfd.ALIAS.get(field, field) ...
[ "def", "mfds2multimfd", "(", "mfds", ")", ":", "_", ",", "kind", "=", "mfds", "[", "0", "]", ".", "tag", ".", "split", "(", "'}'", ")", "node", "=", "Node", "(", "'multiMFD'", ",", "dict", "(", "kind", "=", "kind", ",", "size", "=", "len", "(",...
Convert a list of MFD nodes into a single MultiMFD node
[ "Convert", "a", "list", "of", "MFD", "nodes", "into", "a", "single", "MultiMFD", "node" ]
python
train
pypa/pipenv
pipenv/project.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L1028-L1033
def ensure_proper_casing(self): """Ensures proper casing of Pipfile packages""" pfile = self.parsed_pipfile casing_changed = self.proper_case_section(pfile.get("packages", {})) casing_changed |= self.proper_case_section(pfile.get("dev-packages", {})) return casing_changed
[ "def", "ensure_proper_casing", "(", "self", ")", ":", "pfile", "=", "self", ".", "parsed_pipfile", "casing_changed", "=", "self", ".", "proper_case_section", "(", "pfile", ".", "get", "(", "\"packages\"", ",", "{", "}", ")", ")", "casing_changed", "|=", "sel...
Ensures proper casing of Pipfile packages
[ "Ensures", "proper", "casing", "of", "Pipfile", "packages" ]
python
train
gpoulter/fablib
fablib.py
https://github.com/gpoulter/fablib/blob/5d14c4d998f79dd1aa3207063c3d06e30e3e2bf9/fablib.py#L157-L165
def watch(filenames, callback, use_sudo=False): """Call callback if any of filenames change during the context""" filenames = [filenames] if isinstance(filenames, basestring) else filenames old_md5 = {fn: md5sum(fn, use_sudo) for fn in filenames} yield for filename in filenames: if md5sum(fi...
[ "def", "watch", "(", "filenames", ",", "callback", ",", "use_sudo", "=", "False", ")", ":", "filenames", "=", "[", "filenames", "]", "if", "isinstance", "(", "filenames", ",", "basestring", ")", "else", "filenames", "old_md5", "=", "{", "fn", ":", "md5su...
Call callback if any of filenames change during the context
[ "Call", "callback", "if", "any", "of", "filenames", "change", "during", "the", "context" ]
python
train
readbeyond/aeneas
aeneas/analyzecontainer.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L98-L249
def _analyze_txt_config(self, config_string=None): """ Analyze the given container and return the corresponding job. If ``config_string`` is ``None``, try reading it from the TXT config file inside the container. :param string config_string: the configuration string :rt...
[ "def", "_analyze_txt_config", "(", "self", ",", "config_string", "=", "None", ")", ":", "self", ".", "log", "(", "u\"Analyzing container with TXT config string\"", ")", "if", "config_string", "is", "None", ":", "self", ".", "log", "(", "u\"Analyzing container with T...
Analyze the given container and return the corresponding job. If ``config_string`` is ``None``, try reading it from the TXT config file inside the container. :param string config_string: the configuration string :rtype: :class:`~aeneas.job.Job`
[ "Analyze", "the", "given", "container", "and", "return", "the", "corresponding", "job", "." ]
python
train
petl-developers/petl
petl/util/materialise.py
https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/util/materialise.py#L45-L71
def columns(table, missing=None): """ Construct a :class:`dict` mapping field names to lists of values. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]] >>> cols = etl.columns(table) >>> cols['foo'] ['a', 'b', 'b'] >>> cols...
[ "def", "columns", "(", "table", ",", "missing", "=", "None", ")", ":", "cols", "=", "OrderedDict", "(", ")", "it", "=", "iter", "(", "table", ")", "hdr", "=", "next", "(", "it", ")", "flds", "=", "list", "(", "map", "(", "text_type", ",", "hdr", ...
Construct a :class:`dict` mapping field names to lists of values. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]] >>> cols = etl.columns(table) >>> cols['foo'] ['a', 'b', 'b'] >>> cols['bar'] [1, 2, 3] See also :func:...
[ "Construct", "a", ":", "class", ":", "dict", "mapping", "field", "names", "to", "lists", "of", "values", ".", "E", ".", "g", ".", "::" ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_stochastic.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_stochastic.py#L215-L231
def next_frame_basic_stochastic(): """Basic 2-frame conv model with stochastic tower.""" hparams = basic_deterministic_params.next_frame_basic_deterministic() hparams.stochastic_model = True hparams.add_hparam("latent_channels", 1) hparams.add_hparam("latent_std_min", -5.0) hparams.add_hparam("num_iteration...
[ "def", "next_frame_basic_stochastic", "(", ")", ":", "hparams", "=", "basic_deterministic_params", ".", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "stochastic_model", "=", "True", "hparams", ".", "add_hparam", "(", "\"latent_channels\"", ",", "1", ")"...
Basic 2-frame conv model with stochastic tower.
[ "Basic", "2", "-", "frame", "conv", "model", "with", "stochastic", "tower", "." ]
python
train
Neurosim-lab/netpyne
netpyne/network/conn.py
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/network/conn.py#L310-L327
def fullConn (self, preCellsTags, postCellsTags, connParam): from .. import sim ''' Generates connections between all pre and post-syn cells ''' if sim.cfg.verbose: print('Generating set of all-to-all connections (rule: %s) ...' % (connParam['label'])) # get list of params that have a lambda function ...
[ "def", "fullConn", "(", "self", ",", "preCellsTags", ",", "postCellsTags", ",", "connParam", ")", ":", "from", ".", ".", "import", "sim", "if", "sim", ".", "cfg", ".", "verbose", ":", "print", "(", "'Generating set of all-to-all connections (rule: %s) ...'", "%"...
Generates connections between all pre and post-syn cells
[ "Generates", "connections", "between", "all", "pre", "and", "post", "-", "syn", "cells" ]
python
train
woolfson-group/isambard
isambard/optimisation/optimizer.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/optimisation/optimizer.py#L385-L404
def funnel_rebuild(psg_trm_spec): """Rebuilds a model and compares it to a reference model. Parameters ---------- psg_trm: (([float], float, int), AMPAL, specification) A tuple containing the parameters, score and generation for a model as well as a model of the ...
[ "def", "funnel_rebuild", "(", "psg_trm_spec", ")", ":", "param_score_gen", ",", "top_result_model", ",", "specification", "=", "psg_trm_spec", "params", ",", "score", ",", "gen", "=", "param_score_gen", "model", "=", "specification", "(", "*", "params", ")", "rm...
Rebuilds a model and compares it to a reference model. Parameters ---------- psg_trm: (([float], float, int), AMPAL, specification) A tuple containing the parameters, score and generation for a model as well as a model of the best scoring parameters. Returns ...
[ "Rebuilds", "a", "model", "and", "compares", "it", "to", "a", "reference", "model", "." ]
python
train
agoragames/leaderboard-python
leaderboard/leaderboard.py
https://github.com/agoragames/leaderboard-python/blob/ec309859b197a751ac0322374b36d134d8c5522f/leaderboard/leaderboard.py#L196-L224
def rank_member_if_in( self, leaderboard_name, rank_conditional, member, score, member_data=None): ''' Rank a member in the named leaderboard based on execution of the +rank_conditional+. The +rank_conditional+ is passed th...
[ "def", "rank_member_if_in", "(", "self", ",", "leaderboard_name", ",", "rank_conditional", ",", "member", ",", "score", ",", "member_data", "=", "None", ")", ":", "current_score", "=", "self", ".", "redis_connection", ".", "zscore", "(", "leaderboard_name", ",",...
Rank a member in the named leaderboard based on execution of the +rank_conditional+. The +rank_conditional+ is passed the following parameters: member: Member name. current_score: Current score for the member in the leaderboard. score: Member score. member_data: Optional...
[ "Rank", "a", "member", "in", "the", "named", "leaderboard", "based", "on", "execution", "of", "the", "+", "rank_conditional", "+", "." ]
python
train
XuShaohua/bcloud
bcloud/pcs.py
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/pcs.py#L364-L372
def get_share_url_with_dirname(uk, shareid, dirname): '''得到共享目录的链接''' return ''.join([ const.PAN_URL, 'wap/link', '?shareid=', shareid, '&uk=', uk, '&dir=', encoder.encode_uri_component(dirname), '&third=0', ])
[ "def", "get_share_url_with_dirname", "(", "uk", ",", "shareid", ",", "dirname", ")", ":", "return", "''", ".", "join", "(", "[", "const", ".", "PAN_URL", ",", "'wap/link'", ",", "'?shareid='", ",", "shareid", ",", "'&uk='", ",", "uk", ",", "'&dir='", ","...
得到共享目录的链接
[ "得到共享目录的链接" ]
python
train
google/grr
grr/server/grr_response_server/gui/api_plugins/hunt.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_plugins/hunt.py#L1320-L1343
def _Resample(self, stats, target_size): """Resamples the stats to have a specific number of data points.""" t_first = stats[0][0] t_last = stats[-1][0] interval = (t_last - t_first) / target_size result = [] current_t = t_first current_v = 0 i = 0 while i < len(stats): stat_...
[ "def", "_Resample", "(", "self", ",", "stats", ",", "target_size", ")", ":", "t_first", "=", "stats", "[", "0", "]", "[", "0", "]", "t_last", "=", "stats", "[", "-", "1", "]", "[", "0", "]", "interval", "=", "(", "t_last", "-", "t_first", ")", ...
Resamples the stats to have a specific number of data points.
[ "Resamples", "the", "stats", "to", "have", "a", "specific", "number", "of", "data", "points", "." ]
python
train
wrongwaycn/ssdb-py
ssdb/connection.py
https://github.com/wrongwaycn/ssdb-py/blob/ce7b1542f0faa06fe71a60c667fe15992af0f621/ssdb/connection.py#L171-L178
def on_connect(self, connection): """ Called when the socket connects """ self._sock = connection._sock self._buffer = SocketBuffer(self._sock, self.socket_read_size) if connection.decode_responses: self.encoding = connection.encoding
[ "def", "on_connect", "(", "self", ",", "connection", ")", ":", "self", ".", "_sock", "=", "connection", ".", "_sock", "self", ".", "_buffer", "=", "SocketBuffer", "(", "self", ".", "_sock", ",", "self", ".", "socket_read_size", ")", "if", "connection", "...
Called when the socket connects
[ "Called", "when", "the", "socket", "connects" ]
python
train
Samreay/ChainConsumer
chainconsumer/chainconsumer.py
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/chainconsumer.py#L236-L266
def remove_chain(self, chain=-1): """ Removes a chain from ChainConsumer. Calling this will require any configurations set to be redone! Parameters ---------- chain : int|str, list[str|int] The chain(s) to remove. You can pass in either the chain index, or the chain ...
[ "def", "remove_chain", "(", "self", ",", "chain", "=", "-", "1", ")", ":", "if", "isinstance", "(", "chain", ",", "str", ")", "or", "isinstance", "(", "chain", ",", "int", ")", ":", "chain", "=", "[", "chain", "]", "chain", "=", "sorted", "(", "[...
Removes a chain from ChainConsumer. Calling this will require any configurations set to be redone! Parameters ---------- chain : int|str, list[str|int] The chain(s) to remove. You can pass in either the chain index, or the chain name, to remove it. By default removes the...
[ "Removes", "a", "chain", "from", "ChainConsumer", ".", "Calling", "this", "will", "require", "any", "configurations", "set", "to", "be", "redone!" ]
python
train
ifduyue/urlfetch
urlfetch.py
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L848-L857
def get_proxies_from_environ(): """Get proxies from os.environ.""" proxies = {} http_proxy = os.getenv('http_proxy') or os.getenv('HTTP_PROXY') https_proxy = os.getenv('https_proxy') or os.getenv('HTTPS_PROXY') if http_proxy: proxies['http'] = http_proxy if https_proxy: proxies['...
[ "def", "get_proxies_from_environ", "(", ")", ":", "proxies", "=", "{", "}", "http_proxy", "=", "os", ".", "getenv", "(", "'http_proxy'", ")", "or", "os", ".", "getenv", "(", "'HTTP_PROXY'", ")", "https_proxy", "=", "os", ".", "getenv", "(", "'https_proxy'"...
Get proxies from os.environ.
[ "Get", "proxies", "from", "os", ".", "environ", "." ]
python
train
saltstack/salt
salt/modules/acme.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L107-L258
def cert(name, aliases=None, email=None, webroot=None, test_cert=False, renew=None, keysize=None, server=None, owner='root', group='root', mode='0640', certname=None, preferred_challenges=None, tls_sni_0...
[ "def", "cert", "(", "name", ",", "aliases", "=", "None", ",", "email", "=", "None", ",", "webroot", "=", "None", ",", "test_cert", "=", "False", ",", "renew", "=", "None", ",", "keysize", "=", "None", ",", "server", "=", "None", ",", "owner", "=", ...
Obtain/renew a certificate from an ACME CA, probably Let's Encrypt. :param name: Common Name of the certificate (DNS name of certificate) :param aliases: subjectAltNames (Additional DNS names on certificate) :param email: e-mail address for interaction with ACME provider :param webroot: True or a full ...
[ "Obtain", "/", "renew", "a", "certificate", "from", "an", "ACME", "CA", "probably", "Let", "s", "Encrypt", "." ]
python
train
tensorflow/probability
tensorflow_probability/__init__.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/__init__.py#L32-L65
def _ensure_tf_install(): # pylint: disable=g-statement-before-imports """Attempt to import tensorflow, and ensure its version is sufficient. Raises: ImportError: if either tensorflow is not importable or its version is inadequate. """ try: import tensorflow as tf except ImportError: # Print...
[ "def", "_ensure_tf_install", "(", ")", ":", "# pylint: disable=g-statement-before-imports", "try", ":", "import", "tensorflow", "as", "tf", "except", "ImportError", ":", "# Print more informative error message, then reraise.", "print", "(", "\"\\n\\nFailed to import TensorFlow. P...
Attempt to import tensorflow, and ensure its version is sufficient. Raises: ImportError: if either tensorflow is not importable or its version is inadequate.
[ "Attempt", "to", "import", "tensorflow", "and", "ensure", "its", "version", "is", "sufficient", "." ]
python
test
omederos/pyspinner
spinning/spinning.py
https://github.com/omederos/pyspinner/blob/4615d92e669942c48d5542a23ddf6d40b206d9d5/spinning/spinning.py#L27-L49
def unique(text): """ Return an unique text @type text: str @param text: Text written used spin syntax. @return: An unique text # Generate an unique sentence >>> unique('The {quick|fast} {brown|gray|red} fox jumped over the lazy dog.') 'The quick red fox jumped over the lazy dog' ...
[ "def", "unique", "(", "text", ")", ":", "# check if the text is correct", "correct", ",", "error", "=", "_is_correct", "(", "text", ")", "if", "not", "correct", ":", "raise", "Exception", "(", "error", ")", "s", "=", "[", "]", "_all_unique_texts", "(", "te...
Return an unique text @type text: str @param text: Text written used spin syntax. @return: An unique text # Generate an unique sentence >>> unique('The {quick|fast} {brown|gray|red} fox jumped over the lazy dog.') 'The quick red fox jumped over the lazy dog'
[ "Return", "an", "unique", "text" ]
python
train
LasLabs/python-helpscout
helpscout/apis/conversations.py
https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/apis/conversations.py#L93-L117
def create_attachment(cls, session, attachment): """Create an attachment. An attachment must be sent to the API before it can be used in a thread. Use this method to create the attachment, then use the resulting hash when creating a thread. Note that HelpScout only supports att...
[ "def", "create_attachment", "(", "cls", ",", "session", ",", "attachment", ")", ":", "return", "super", "(", "Conversations", ",", "cls", ")", ".", "create", "(", "session", ",", "attachment", ",", "endpoint_override", "=", "'/attachments.json'", ",", "out_typ...
Create an attachment. An attachment must be sent to the API before it can be used in a thread. Use this method to create the attachment, then use the resulting hash when creating a thread. Note that HelpScout only supports attachments of 10MB or lower. Args: sessio...
[ "Create", "an", "attachment", "." ]
python
train
streamlink/streamlink
src/streamlink/plugin/api/http_session.py
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/plugin/api/http_session.py#L106-L108
def xml(cls, res, *args, **kwargs): """Parses XML from a response.""" return parse_xml(res.text, *args, **kwargs)
[ "def", "xml", "(", "cls", ",", "res", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "parse_xml", "(", "res", ".", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Parses XML from a response.
[ "Parses", "XML", "from", "a", "response", "." ]
python
test
radhermit/vimball
vimball/base.py
https://github.com/radhermit/vimball/blob/3998bdb8d8c4852a388a259778f971f562f9ef37/vimball/base.py#L82-L102
def files(self): """Yields archive file information.""" # try new file header format first, then fallback on old for header in (r"(.*)\t\[\[\[1\n", r"^(\d+)\n$"): header = re.compile(header) filename = None self.fd.seek(0) line = self.readline() ...
[ "def", "files", "(", "self", ")", ":", "# try new file header format first, then fallback on old", "for", "header", "in", "(", "r\"(.*)\\t\\[\\[\\[1\\n\"", ",", "r\"^(\\d+)\\n$\"", ")", ":", "header", "=", "re", ".", "compile", "(", "header", ")", "filename", "=", ...
Yields archive file information.
[ "Yields", "archive", "file", "information", "." ]
python
train
jendrikseipp/vulture
vulture/utils.py
https://github.com/jendrikseipp/vulture/blob/fed11fb7e7ed065058a9fb1acd10052ece37f984/vulture/utils.py#L70-L86
def get_modules(paths, toplevel=True): """Take files from the command line even if they don't end with .py.""" modules = [] for path in paths: path = os.path.abspath(path) if toplevel and path.endswith('.pyc'): sys.exit('.pyc files are not supported: {0}'.format(path)) if...
[ "def", "get_modules", "(", "paths", ",", "toplevel", "=", "True", ")", ":", "modules", "=", "[", "]", "for", "path", "in", "paths", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "toplevel", "and", "path", ".", "endswi...
Take files from the command line even if they don't end with .py.
[ "Take", "files", "from", "the", "command", "line", "even", "if", "they", "don", "t", "end", "with", ".", "py", "." ]
python
train
saltstack/salt
salt/modules/boto_apigateway.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L753-L769
def delete_api_deployment(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None): ''' Deletes API deployment for a given restApiId and deploymentID CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_deployent restApiId deploymentId ''' try: ...
[ "def", "delete_api_deployment", "(", "restApiId", ",", "deploymentId", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "reg...
Deletes API deployment for a given restApiId and deploymentID CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_deployent restApiId deploymentId
[ "Deletes", "API", "deployment", "for", "a", "given", "restApiId", "and", "deploymentID" ]
python
train
mbi/django-simple-captcha
captcha/fields.py
https://github.com/mbi/django-simple-captcha/blob/e96cd8f63e41e658d103d12d6486b34195aee555/captcha/fields.py#L152-L164
def _direct_render(self, name, attrs): """Render the widget the old way - using field_template or output_format.""" context = { 'image': self.image_url(), 'name': name, 'key': self._key, 'id': u'%s_%s' % (self.id_prefix, attrs.get('id')) if self.id_prefix ...
[ "def", "_direct_render", "(", "self", ",", "name", ",", "attrs", ")", ":", "context", "=", "{", "'image'", ":", "self", ".", "image_url", "(", ")", ",", "'name'", ":", "name", ",", "'key'", ":", "self", ".", "_key", ",", "'id'", ":", "u'%s_%s'", "%...
Render the widget the old way - using field_template or output_format.
[ "Render", "the", "widget", "the", "old", "way", "-", "using", "field_template", "or", "output_format", "." ]
python
train
ethereum/web3.py
web3/iban.py
https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/iban.py#L105-L118
def fromAddress(address): """ This method should be used to create an iban object from ethereum address @method fromAddress @param {String} address @return {Iban} the IBAN object """ validate_address(address) address_as_integer = int(address, 16) ...
[ "def", "fromAddress", "(", "address", ")", ":", "validate_address", "(", "address", ")", "address_as_integer", "=", "int", "(", "address", ",", "16", ")", "address_as_base36", "=", "baseN", "(", "address_as_integer", ",", "36", ")", "padded", "=", "pad_left_he...
This method should be used to create an iban object from ethereum address @method fromAddress @param {String} address @return {Iban} the IBAN object
[ "This", "method", "should", "be", "used", "to", "create", "an", "iban", "object", "from", "ethereum", "address" ]
python
train
samjabrahams/anchorhub
anchorhub/util/stripprefix.py
https://github.com/samjabrahams/anchorhub/blob/5ade359b08297d4003a5f477389c01de9e634b54/anchorhub/util/stripprefix.py#L23-L32
def strip_prefix_from_list(list, strip): """ Goes through a list of strings and removes the specified prefix from the beginning of each string in place. :param list: a list of strings to be modified in place :param strip: a string specifying the prefix to remove from the list """ for i in r...
[ "def", "strip_prefix_from_list", "(", "list", ",", "strip", ")", ":", "for", "i", "in", "range", "(", "len", "(", "list", ")", ")", ":", "list", "[", "i", "]", "=", "strip_prefix", "(", "list", "[", "i", "]", ",", "strip", ")" ]
Goes through a list of strings and removes the specified prefix from the beginning of each string in place. :param list: a list of strings to be modified in place :param strip: a string specifying the prefix to remove from the list
[ "Goes", "through", "a", "list", "of", "strings", "and", "removes", "the", "specified", "prefix", "from", "the", "beginning", "of", "each", "string", "in", "place", "." ]
python
train
ga4gh/ga4gh-server
ga4gh/server/datarepo.py
https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datarepo.py#L947-L953
def removeBiosample(self, biosample): """ Removes the specified biosample from this repository. """ q = models.Biosample.delete().where( models.Biosample.id == biosample.getId()) q.execute()
[ "def", "removeBiosample", "(", "self", ",", "biosample", ")", ":", "q", "=", "models", ".", "Biosample", ".", "delete", "(", ")", ".", "where", "(", "models", ".", "Biosample", ".", "id", "==", "biosample", ".", "getId", "(", ")", ")", "q", ".", "e...
Removes the specified biosample from this repository.
[ "Removes", "the", "specified", "biosample", "from", "this", "repository", "." ]
python
train
patrickfuller/jgraph
python/force_directed_layout.py
https://github.com/patrickfuller/jgraph/blob/7297450f26ae8cba21914668a5aaa755de8aa14d/python/force_directed_layout.py#L10-L59
def run(edges, iterations=1000, force_strength=5.0, dampening=0.01, max_velocity=2.0, max_distance=50, is_3d=True): """Runs a force-directed-layout algorithm on the input graph. iterations - Number of FDL iterations to run in coordinate generation force_strength - Strength of Coulomb and Hooke forc...
[ "def", "run", "(", "edges", ",", "iterations", "=", "1000", ",", "force_strength", "=", "5.0", ",", "dampening", "=", "0.01", ",", "max_velocity", "=", "2.0", ",", "max_distance", "=", "50", ",", "is_3d", "=", "True", ")", ":", "# Get a list of node ids fr...
Runs a force-directed-layout algorithm on the input graph. iterations - Number of FDL iterations to run in coordinate generation force_strength - Strength of Coulomb and Hooke forces (edit this to scale the distance between nodes) dampening - Multiplier to reduce force applied to nodes...
[ "Runs", "a", "force", "-", "directed", "-", "layout", "algorithm", "on", "the", "input", "graph", "." ]
python
train
markovmodel/msmtools
msmtools/analysis/dense/correlations.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/dense/correlations.py#L55-L124
def time_correlation_direct_by_mtx_vec_prod(P, mu, obs1, obs2=None, time=1, start_values=None, return_P_k_obs=False): r"""Compute time-correlation of obs1, or time-cross-correlation with obs2. The time-correlation at time=k is computed by the matrix-vector expression: cor(k) = obs1' diag(pi) P^k obs2 ...
[ "def", "time_correlation_direct_by_mtx_vec_prod", "(", "P", ",", "mu", ",", "obs1", ",", "obs2", "=", "None", ",", "time", "=", "1", ",", "start_values", "=", "None", ",", "return_P_k_obs", "=", "False", ")", ":", "# input checks", "if", "not", "(", "type"...
r"""Compute time-correlation of obs1, or time-cross-correlation with obs2. The time-correlation at time=k is computed by the matrix-vector expression: cor(k) = obs1' diag(pi) P^k obs2 Parameters ---------- P : ndarray, shape=(n, n) or scipy.sparse matrix Transition matrix obs1 : ndarr...
[ "r", "Compute", "time", "-", "correlation", "of", "obs1", "or", "time", "-", "cross", "-", "correlation", "with", "obs2", "." ]
python
train
awslabs/aws-sam-cli
samcli/local/lambdafn/env_vars.py
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/env_vars.py#L77-L104
def resolve(self): """ Resolves the values from different sources and returns a dict of environment variables to use when running the function locally. :return dict: Dict where key is the variable name and value is the value of the variable. Both key and values are strings ...
[ "def", "resolve", "(", "self", ")", ":", "# AWS_* variables must always be passed to the function, but user has the choice to override them", "result", "=", "self", ".", "_get_aws_variables", "(", ")", "# Default value for the variable gets lowest priority", "for", "name", ",", "...
Resolves the values from different sources and returns a dict of environment variables to use when running the function locally. :return dict: Dict where key is the variable name and value is the value of the variable. Both key and values are strings
[ "Resolves", "the", "values", "from", "different", "sources", "and", "returns", "a", "dict", "of", "environment", "variables", "to", "use", "when", "running", "the", "function", "locally", "." ]
python
train
tanghaibao/jcvi
jcvi/compara/synfind.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/synfind.py#L46-L66
def get_flanker(group, query): """ >>> get_flanker([(370, 15184), (372, 15178), (373, 15176), (400, 15193)], 385) ((373, 15176), (400, 15193), True) >>> get_flanker([(124, 13639), (137, 13625)], 138) ((137, 13625), (137, 13625), False) """ group.sort() pos = bisect_left(group, (query, ...
[ "def", "get_flanker", "(", "group", ",", "query", ")", ":", "group", ".", "sort", "(", ")", "pos", "=", "bisect_left", "(", "group", ",", "(", "query", ",", "0", ")", ")", "left_flanker", "=", "group", "[", "0", "]", "if", "pos", "==", "0", "else...
>>> get_flanker([(370, 15184), (372, 15178), (373, 15176), (400, 15193)], 385) ((373, 15176), (400, 15193), True) >>> get_flanker([(124, 13639), (137, 13625)], 138) ((137, 13625), (137, 13625), False)
[ ">>>", "get_flanker", "(", "[", "(", "370", "15184", ")", "(", "372", "15178", ")", "(", "373", "15176", ")", "(", "400", "15193", ")", "]", "385", ")", "((", "373", "15176", ")", "(", "400", "15193", ")", "True", ")" ]
python
train
skylander86/uriutils
uriutils/storages.py
https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/storages.py#L421-L433
def list_dir(self): """ Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency. """ bucket = self.blob.bucket prefix = self.blob.name if not prefix.endswith('/'): prefix += '/' for blob in bucket.list_blobs(prefi...
[ "def", "list_dir", "(", "self", ")", ":", "bucket", "=", "self", ".", "blob", ".", "bucket", "prefix", "=", "self", ".", "blob", ".", "name", "if", "not", "prefix", ".", "endswith", "(", "'/'", ")", ":", "prefix", "+=", "'/'", "for", "blob", "in", ...
Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency.
[ "Non", "-", "recursive", "file", "listing", "." ]
python
train
Bystroushaak/pyDHTMLParser
src/dhtmlparser/htmlelement/html_parser.py
https://github.com/Bystroushaak/pyDHTMLParser/blob/4756f93dd048500b038ece2323fe26e46b6bfdea/src/dhtmlparser/htmlelement/html_parser.py#L354-L367
def isOpeningTag(self): """ Detect whether this tag is opening or not. Returns: bool: True if it is opening. """ if self.isTag() and \ not self.isComment() and \ not self.isEndTag() and \ not self.isNonPairTag(): return Tr...
[ "def", "isOpeningTag", "(", "self", ")", ":", "if", "self", ".", "isTag", "(", ")", "and", "not", "self", ".", "isComment", "(", ")", "and", "not", "self", ".", "isEndTag", "(", ")", "and", "not", "self", ".", "isNonPairTag", "(", ")", ":", "return...
Detect whether this tag is opening or not. Returns: bool: True if it is opening.
[ "Detect", "whether", "this", "tag", "is", "opening", "or", "not", "." ]
python
train