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
jupyter-widgets/jupyterlab-sidecar
setupbase.py
https://github.com/jupyter-widgets/jupyterlab-sidecar/blob/8889d09f1a0933e2cbee06d4874f720b075b29e8/setupbase.py#L502-L540
def _get_data_files(data_specs, existing): """Expand data file specs into valid data files metadata. Parameters ---------- data_specs: list of tuples See [createcmdclass] for description. existing: list of tuples The existing distribution data_files metadata. Returns ------...
[ "def", "_get_data_files", "(", "data_specs", ",", "existing", ")", ":", "# Extract the existing data files into a staging object.", "file_data", "=", "defaultdict", "(", "list", ")", "for", "(", "path", ",", "files", ")", "in", "existing", "or", "[", "]", ":", "...
Expand data file specs into valid data files metadata. Parameters ---------- data_specs: list of tuples See [createcmdclass] for description. existing: list of tuples The existing distribution data_files metadata. Returns ------- A valid list of data_files items.
[ "Expand", "data", "file", "specs", "into", "valid", "data", "files", "metadata", "." ]
python
test
flask-restful/flask-restful
flask_restful/__init__.py
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L271-L341
def handle_error(self, e): """Error handler for the API transforms a raised exception into a Flask response, with the appropriate HTTP status code and body. :param e: the raised Exception object :type e: Exception """ got_request_exception.send(current_app._get_current_...
[ "def", "handle_error", "(", "self", ",", "e", ")", ":", "got_request_exception", ".", "send", "(", "current_app", ".", "_get_current_object", "(", ")", ",", "exception", "=", "e", ")", "if", "not", "isinstance", "(", "e", ",", "HTTPException", ")", "and", ...
Error handler for the API transforms a raised exception into a Flask response, with the appropriate HTTP status code and body. :param e: the raised Exception object :type e: Exception
[ "Error", "handler", "for", "the", "API", "transforms", "a", "raised", "exception", "into", "a", "Flask", "response", "with", "the", "appropriate", "HTTP", "status", "code", "and", "body", "." ]
python
train
data-8/datascience
datascience/tables.py
https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/tables.py#L2854-L2859
def _collected_label(collect, label): """Label of a collected column.""" if not collect.__name__.startswith('<'): return label + ' ' + collect.__name__ else: return label
[ "def", "_collected_label", "(", "collect", ",", "label", ")", ":", "if", "not", "collect", ".", "__name__", ".", "startswith", "(", "'<'", ")", ":", "return", "label", "+", "' '", "+", "collect", ".", "__name__", "else", ":", "return", "label" ]
Label of a collected column.
[ "Label", "of", "a", "collected", "column", "." ]
python
train
randomsync/robotframework-mqttlibrary
src/MQTTLibrary/MQTTKeywords.py
https://github.com/randomsync/robotframework-mqttlibrary/blob/14f20038ccdbb576cc1057ec6736e3685138f59e/src/MQTTLibrary/MQTTKeywords.py#L28-L75
def connect(self, broker, port=1883, client_id="", clean_session=True): """ Connect to an MQTT broker. This is a pre-requisite step for publish and subscribe keywords. `broker` MQTT broker host `port` broker port (default 1883) `client_id` if not specified, a random id is gene...
[ "def", "connect", "(", "self", ",", "broker", ",", "port", "=", "1883", ",", "client_id", "=", "\"\"", ",", "clean_session", "=", "True", ")", ":", "logger", ".", "info", "(", "'Connecting to %s at port %s'", "%", "(", "broker", ",", "port", ")", ")", ...
Connect to an MQTT broker. This is a pre-requisite step for publish and subscribe keywords. `broker` MQTT broker host `port` broker port (default 1883) `client_id` if not specified, a random id is generated `clean_session` specifies the clean session flag for the connection ...
[ "Connect", "to", "an", "MQTT", "broker", ".", "This", "is", "a", "pre", "-", "requisite", "step", "for", "publish", "and", "subscribe", "keywords", "." ]
python
train
alpacahq/pylivetrader
examples/q01/algo.py
https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/examples/q01/algo.py#L291-L304
def my_record_vars(context, data): """ Record variables at the end of each day. """ # Record our variables. record(leverage=context.account.leverage) record(positions=len(context.portfolio.positions)) if 0 < len(context.age): MaxAge = context.age[max( list(context.age.ke...
[ "def", "my_record_vars", "(", "context", ",", "data", ")", ":", "# Record our variables.", "record", "(", "leverage", "=", "context", ".", "account", ".", "leverage", ")", "record", "(", "positions", "=", "len", "(", "context", ".", "portfolio", ".", "positi...
Record variables at the end of each day.
[ "Record", "variables", "at", "the", "end", "of", "each", "day", "." ]
python
train
pandas-dev/pandas
pandas/core/generic.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L9877-L9891
def _check_percentile(self, q): """ Validate percentiles (used by describe and quantile). """ msg = ("percentiles should all be in the interval [0, 1]. " "Try {0} instead.") q = np.asarray(q) if q.ndim == 0: if not 0 <= q <= 1: ...
[ "def", "_check_percentile", "(", "self", ",", "q", ")", ":", "msg", "=", "(", "\"percentiles should all be in the interval [0, 1]. \"", "\"Try {0} instead.\"", ")", "q", "=", "np", ".", "asarray", "(", "q", ")", "if", "q", ".", "ndim", "==", "0", ":", "if", ...
Validate percentiles (used by describe and quantile).
[ "Validate", "percentiles", "(", "used", "by", "describe", "and", "quantile", ")", "." ]
python
train
bbitmaster/ale_python_interface
ale_python_interface/ale_python_interface.py
https://github.com/bbitmaster/ale_python_interface/blob/253062be8e07fb738ea25982387b20af3712b615/ale_python_interface/ale_python_interface.py#L75-L88
def getScreen(self,screen_data=None): """This function fills screen_data with the RAW Pixel data screen_data MUST be a numpy array of uint8/int8. This could be initialized like so: screen_data = np.array(w*h,dtype=np.uint8) Notice, it must be width*height in size also If it is No...
[ "def", "getScreen", "(", "self", ",", "screen_data", "=", "None", ")", ":", "if", "(", "screen_data", "is", "None", ")", ":", "width", "=", "ale_lib", ".", "getScreenWidth", "(", "self", ".", "obj", ")", "height", "=", "ale_lib", ".", "getScreenWidth", ...
This function fills screen_data with the RAW Pixel data screen_data MUST be a numpy array of uint8/int8. This could be initialized like so: screen_data = np.array(w*h,dtype=np.uint8) Notice, it must be width*height in size also If it is None, then this function will initialize it ...
[ "This", "function", "fills", "screen_data", "with", "the", "RAW", "Pixel", "data", "screen_data", "MUST", "be", "a", "numpy", "array", "of", "uint8", "/", "int8", ".", "This", "could", "be", "initialized", "like", "so", ":", "screen_data", "=", "np", ".", ...
python
train
pysathq/pysat
examples/rc2.py
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L895-L935
def process_sums(self): """ Process cardinality sums participating in a new core. Whenever necessary, some of the sum assumptions are removed or split (depending on the value of ``self.minw``). Deleted sums are marked as garbage and are dealt with in :...
[ "def", "process_sums", "(", "self", ")", ":", "for", "l", "in", "self", ".", "core_sums", ":", "if", "self", ".", "wght", "[", "l", "]", "==", "self", ".", "minw", ":", "# marking variable as being a part of the core", "# so that next time it is not used as an ass...
Process cardinality sums participating in a new core. Whenever necessary, some of the sum assumptions are removed or split (depending on the value of ``self.minw``). Deleted sums are marked as garbage and are dealt with in :func:`filter_assumps`. In some case...
[ "Process", "cardinality", "sums", "participating", "in", "a", "new", "core", ".", "Whenever", "necessary", "some", "of", "the", "sum", "assumptions", "are", "removed", "or", "split", "(", "depending", "on", "the", "value", "of", "self", ".", "minw", ")", "...
python
train
janpipek/physt
physt/examples/__init__.py
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/examples/__init__.py#L25-L34
def normal_h2(size: int = 10000) -> Histogram2D: """A simple 2D histogram with normal distribution. Parameters ---------- size : Number of points """ data1 = np.random.normal(0, 1, (size,)) data2 = np.random.normal(0, 1, (size,)) return h2(data1, data2, name="normal", axis_names=tuple("...
[ "def", "normal_h2", "(", "size", ":", "int", "=", "10000", ")", "->", "Histogram2D", ":", "data1", "=", "np", ".", "random", ".", "normal", "(", "0", ",", "1", ",", "(", "size", ",", ")", ")", "data2", "=", "np", ".", "random", ".", "normal", "...
A simple 2D histogram with normal distribution. Parameters ---------- size : Number of points
[ "A", "simple", "2D", "histogram", "with", "normal", "distribution", "." ]
python
train
batiste/django-page-cms
pages/utils.py
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/utils.py#L63-L113
def _placeholders_recursif(nodelist, plist, blist): """Recursively search into a template node list for PlaceholderNode node.""" # I needed to do this lazy import to compile the documentation from django.template.loader_tags import BlockNode if len(blist): block = blist[-1] else: ...
[ "def", "_placeholders_recursif", "(", "nodelist", ",", "plist", ",", "blist", ")", ":", "# I needed to do this lazy import to compile the documentation", "from", "django", ".", "template", ".", "loader_tags", "import", "BlockNode", "if", "len", "(", "blist", ")", ":",...
Recursively search into a template node list for PlaceholderNode node.
[ "Recursively", "search", "into", "a", "template", "node", "list", "for", "PlaceholderNode", "node", "." ]
python
train
adrianliaw/PyCuber
pycuber/solver/cfop/pll.py
https://github.com/adrianliaw/PyCuber/blob/e44b5ba48c831b964ce73d046fb813222771853f/pycuber/solver/cfop/pll.py#L32-L43
def recognise(self): """ Recognise the PLL case of Cube. """ result = "" for side in "LFRB": for square in self.cube.get_face(side)[0]: for _side in "LFRB": if square.colour == self.cube[_side].colour: result...
[ "def", "recognise", "(", "self", ")", ":", "result", "=", "\"\"", "for", "side", "in", "\"LFRB\"", ":", "for", "square", "in", "self", ".", "cube", ".", "get_face", "(", "side", ")", "[", "0", "]", ":", "for", "_side", "in", "\"LFRB\"", ":", "if", ...
Recognise the PLL case of Cube.
[ "Recognise", "the", "PLL", "case", "of", "Cube", "." ]
python
train
rollbar/pyrollbar
rollbar/contrib/django/middleware.py
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/contrib/django/middleware.py#L236-L246
def _ensure_log_handler(self): """ If there's no log configuration, set up a default handler. """ if log.handlers: return handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(m...
[ "def", "_ensure_log_handler", "(", "self", ")", ":", "if", "log", ".", "handlers", ":", "return", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s...
If there's no log configuration, set up a default handler.
[ "If", "there", "s", "no", "log", "configuration", "set", "up", "a", "default", "handler", "." ]
python
test
CamDavidsonPilon/lifelines
lifelines/utils/concordance.py
https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/utils/concordance.py#L203-L228
def _naive_concordance_summary_statistics(event_times, predicted_event_times, event_observed): """ Fallback, simpler method to compute concordance. Assumes the data has been verified by lifelines.utils.concordance_index first. """ num_pairs = 0.0 num_correct = 0.0 num_tied = 0.0 for a,...
[ "def", "_naive_concordance_summary_statistics", "(", "event_times", ",", "predicted_event_times", ",", "event_observed", ")", ":", "num_pairs", "=", "0.0", "num_correct", "=", "0.0", "num_tied", "=", "0.0", "for", "a", ",", "time_a", "in", "enumerate", "(", "event...
Fallback, simpler method to compute concordance. Assumes the data has been verified by lifelines.utils.concordance_index first.
[ "Fallback", "simpler", "method", "to", "compute", "concordance", "." ]
python
train
KelSolaar/Foundations
foundations/cache.py
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/cache.py#L103-L123
def get_content(self, key): """ Gets given content from the cache. Usage:: >>> cache = Cache() >>> cache.add_content(John="Doe", Luke="Skywalker") True >>> cache.get_content("Luke") 'Skywalker' :param key: Content to retrieve...
[ "def", "get_content", "(", "self", ",", "key", ")", ":", "LOGGER", ".", "debug", "(", "\"> Retrieving '{0}' content from the cache.\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "key", ")", ")", "return", "self", ".", "get", "(", ...
Gets given content from the cache. Usage:: >>> cache = Cache() >>> cache.add_content(John="Doe", Luke="Skywalker") True >>> cache.get_content("Luke") 'Skywalker' :param key: Content to retrieve. :type key: object :return: Con...
[ "Gets", "given", "content", "from", "the", "cache", "." ]
python
train
vingd/encrypted-pickle-python
encryptedpickle/encryptedpickle.py
https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L490-L505
def _unserialize_data(self, data, options): '''Unserialize data''' serialization_algorithm_id = options['serialization_algorithm_id'] if serialization_algorithm_id not in self.serialization_algorithms: raise Exception('Unknown serialization algorithm id: %d' ...
[ "def", "_unserialize_data", "(", "self", ",", "data", ",", "options", ")", ":", "serialization_algorithm_id", "=", "options", "[", "'serialization_algorithm_id'", "]", "if", "serialization_algorithm_id", "not", "in", "self", ".", "serialization_algorithms", ":", "rais...
Unserialize data
[ "Unserialize", "data" ]
python
valid
esheldon/fitsio
fitsio/hdu/table.py
https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/hdu/table.py#L1258-L1279
def _fix_range(self, num, isslice=True): """ Ensure the input is within range. If el=True, then don't treat as a slice element """ nrows = self._info['nrows'] if isslice: # include the end if num < 0: num = nrows + (1+num) ...
[ "def", "_fix_range", "(", "self", ",", "num", ",", "isslice", "=", "True", ")", ":", "nrows", "=", "self", ".", "_info", "[", "'nrows'", "]", "if", "isslice", ":", "# include the end", "if", "num", "<", "0", ":", "num", "=", "nrows", "+", "(", "1",...
Ensure the input is within range. If el=True, then don't treat as a slice element
[ "Ensure", "the", "input", "is", "within", "range", "." ]
python
train
jtwhite79/pyemu
pyemu/utils/gw_utils.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/gw_utils.py#L2379-L2447
def write_hfb_template(m): """write a template file for an hfb (yuck!) Parameters ---------- m : flopy.modflow.Modflow instance with an HFB file Returns ------- (tpl_filename, df) : (str, pandas.DataFrame) the name of the template file and a dataframe with useful info. ...
[ "def", "write_hfb_template", "(", "m", ")", ":", "assert", "m", ".", "hfb6", "is", "not", "None", "hfb_file", "=", "os", ".", "path", ".", "join", "(", "m", ".", "model_ws", ",", "m", ".", "hfb6", ".", "file_name", "[", "0", "]", ")", "assert", "...
write a template file for an hfb (yuck!) Parameters ---------- m : flopy.modflow.Modflow instance with an HFB file Returns ------- (tpl_filename, df) : (str, pandas.DataFrame) the name of the template file and a dataframe with useful info.
[ "write", "a", "template", "file", "for", "an", "hfb", "(", "yuck!", ")" ]
python
train
PMBio/limix-backup
limix/mtSet/core/splitter_bed.py
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/splitter_bed.py#L41-L77
def splitGenoSlidingWindow(pos,out_file,size=5e4,step=None): """ split into windows using a slide criterion Args: size: window size step: moving step (default: 0.5*size) Returns: wnd_i: number of windows nSnps: vector of per-window number of SNPs ...
[ "def", "splitGenoSlidingWindow", "(", "pos", ",", "out_file", ",", "size", "=", "5e4", ",", "step", "=", "None", ")", ":", "if", "step", "is", "None", ":", "step", "=", "0.5", "*", "size", "chroms", "=", "SP", ".", "unique", "(", "pos", "[", ":", ...
split into windows using a slide criterion Args: size: window size step: moving step (default: 0.5*size) Returns: wnd_i: number of windows nSnps: vector of per-window number of SNPs
[ "split", "into", "windows", "using", "a", "slide", "criterion", "Args", ":", "size", ":", "window", "size", "step", ":", "moving", "step", "(", "default", ":", "0", ".", "5", "*", "size", ")", "Returns", ":", "wnd_i", ":", "number", "of", "windows", ...
python
train
ghackebeil/PyORAM
src/pyoram/util/virtual_heap.py
https://github.com/ghackebeil/PyORAM/blob/b8832c1b753c0b2148ef7a143c5f5dd3bbbb61e7/src/pyoram/util/virtual_heap.py#L379-L417
def write_as_dot(self, f, data=None, max_levels=None): "Write the tree in the dot language format to f." assert (max_levels is None) or (max_levels >= 0) def visit_node(n, levels): lbl = "{" if data is None: if self.k <= max_k_labeled: ...
[ "def", "write_as_dot", "(", "self", ",", "f", ",", "data", "=", "None", ",", "max_levels", "=", "None", ")", ":", "assert", "(", "max_levels", "is", "None", ")", "or", "(", "max_levels", ">=", "0", ")", "def", "visit_node", "(", "n", ",", "levels", ...
Write the tree in the dot language format to f.
[ "Write", "the", "tree", "in", "the", "dot", "language", "format", "to", "f", "." ]
python
train
mitsei/dlkit
dlkit/json_/grading/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/objects.py#L491-L504
def get_numeric_score_increment(self): """Gets the incremental step. return: (decimal) - the increment raise: IllegalState - ``is_based_on_grades()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if self.is_based_on_grades(): r...
[ "def", "get_numeric_score_increment", "(", "self", ")", ":", "if", "self", ".", "is_based_on_grades", "(", ")", ":", "raise", "errors", ".", "IllegalState", "(", "'This GradeSystem is based on grades'", ")", "if", "self", ".", "_my_map", "[", "'numericScoreIncrement...
Gets the incremental step. return: (decimal) - the increment raise: IllegalState - ``is_based_on_grades()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
[ "Gets", "the", "incremental", "step", "." ]
python
train
kylejusticemagnuson/pyti
pyti/commodity_channel_index.py
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/commodity_channel_index.py#L10-L22
def commodity_channel_index(close_data, high_data, low_data, period): """ Commodity Channel Index. Formula: CCI = (TP - SMA(TP)) / (0.015 * Mean Deviation) """ catch_errors.check_for_input_len_diff(close_data, high_data, low_data) catch_errors.check_for_period_error(close_data, period) ...
[ "def", "commodity_channel_index", "(", "close_data", ",", "high_data", ",", "low_data", ",", "period", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "high_data", ",", "low_data", ")", "catch_errors", ".", "check_for_period_error", ...
Commodity Channel Index. Formula: CCI = (TP - SMA(TP)) / (0.015 * Mean Deviation)
[ "Commodity", "Channel", "Index", "." ]
python
train
aws/sagemaker-python-sdk
src/sagemaker/tuner.py
https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/tuner.py#L559-L581
def identical_dataset_and_algorithm_tuner(self, additional_parents=None): """Creates a new ``HyperparameterTuner`` by copying the request fields from the provided parent to the new instance of ``HyperparameterTuner``. Followed by addition of warm start configuration with the type as "IdenticalDa...
[ "def", "identical_dataset_and_algorithm_tuner", "(", "self", ",", "additional_parents", "=", "None", ")", ":", "return", "self", ".", "_create_warm_start_tuner", "(", "additional_parents", "=", "additional_parents", ",", "warm_start_type", "=", "WarmStartTypes", ".", "I...
Creates a new ``HyperparameterTuner`` by copying the request fields from the provided parent to the new instance of ``HyperparameterTuner``. Followed by addition of warm start configuration with the type as "IdenticalDataAndAlgorithm" and parents as the union of provided list of ``additional_parents`` a...
[ "Creates", "a", "new", "HyperparameterTuner", "by", "copying", "the", "request", "fields", "from", "the", "provided", "parent", "to", "the", "new", "instance", "of", "HyperparameterTuner", ".", "Followed", "by", "addition", "of", "warm", "start", "configuration", ...
python
train
cartologic/cartoview
pavement.py
https://github.com/cartologic/cartoview/blob/8eea73a7e363ac806dbfca3ca61f7e9d2c839b6b/pavement.py#L139-L157
def _robust_rmtree(path, logger=None, max_retries=5): """Try to delete paths robustly . Retries several times (with increasing delays) if an OSError occurs. If the final attempt fails, the Exception is propagated to the caller. Taken from https://github.com/hashdist/hashdist/pull/116 """ for i...
[ "def", "_robust_rmtree", "(", "path", ",", "logger", "=", "None", ",", "max_retries", "=", "5", ")", ":", "for", "i", "in", "range", "(", "max_retries", ")", ":", "try", ":", "shutil", ".", "rmtree", "(", "path", ")", "return", "except", "OSError", "...
Try to delete paths robustly . Retries several times (with increasing delays) if an OSError occurs. If the final attempt fails, the Exception is propagated to the caller. Taken from https://github.com/hashdist/hashdist/pull/116
[ "Try", "to", "delete", "paths", "robustly", ".", "Retries", "several", "times", "(", "with", "increasing", "delays", ")", "if", "an", "OSError", "occurs", ".", "If", "the", "final", "attempt", "fails", "the", "Exception", "is", "propagated", "to", "the", "...
python
train
edx/XBlock
xblock/runtime.py
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L738-L749
def _aside_from_xml(self, node, block_def_id, block_usage_id, id_generator): """ Create an aside from the xml and attach it to the given block """ id_generator = id_generator or self.id_generator aside_type = node.tag aside_class = self.load_aside_type(aside_type) ...
[ "def", "_aside_from_xml", "(", "self", ",", "node", ",", "block_def_id", ",", "block_usage_id", ",", "id_generator", ")", ":", "id_generator", "=", "id_generator", "or", "self", ".", "id_generator", "aside_type", "=", "node", ".", "tag", "aside_class", "=", "s...
Create an aside from the xml and attach it to the given block
[ "Create", "an", "aside", "from", "the", "xml", "and", "attach", "it", "to", "the", "given", "block" ]
python
train
wavycloud/pyboto3
pyboto3/opsworks.py
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/opsworks.py#L3431-L3623
def update_layer(LayerId=None, Name=None, Shortname=None, Attributes=None, CloudWatchLogsConfiguration=None, CustomInstanceProfileArn=None, CustomJson=None, CustomSecurityGroupIds=None, Packages=None, VolumeConfigurations=None, EnableAutoHealing=None, AutoAssignElasticIps=None, AutoAssignPublicIps=None, CustomRecipes=N...
[ "def", "update_layer", "(", "LayerId", "=", "None", ",", "Name", "=", "None", ",", "Shortname", "=", "None", ",", "Attributes", "=", "None", ",", "CloudWatchLogsConfiguration", "=", "None", ",", "CustomInstanceProfileArn", "=", "None", ",", "CustomJson", "=", ...
Updates a specified layer. See also: AWS API Documentation :example: response = client.update_layer( LayerId='string', Name='string', Shortname='string', Attributes={ 'string': 'string' }, CloudWatchLogsConfiguration={ 'Enabled': ...
[ "Updates", "a", "specified", "layer", ".", "See", "also", ":", "AWS", "API", "Documentation", ":", "example", ":", "response", "=", "client", ".", "update_layer", "(", "LayerId", "=", "string", "Name", "=", "string", "Shortname", "=", "string", "Attributes",...
python
train
etingof/pysnmpcrypto
pysnmpcrypto/aes.py
https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/aes.py#L27-L39
def _cryptography_cipher(key, iv): """Build a cryptography AES Cipher object. :param bytes key: Encryption key :param bytes iv: Initialization vector :returns: AES Cipher instance :rtype: cryptography.hazmat.primitives.ciphers.Cipher """ return Cipher( algorithm=algorithms.AES(key),...
[ "def", "_cryptography_cipher", "(", "key", ",", "iv", ")", ":", "return", "Cipher", "(", "algorithm", "=", "algorithms", ".", "AES", "(", "key", ")", ",", "mode", "=", "modes", ".", "CFB", "(", "iv", ")", ",", "backend", "=", "default_backend", "(", ...
Build a cryptography AES Cipher object. :param bytes key: Encryption key :param bytes iv: Initialization vector :returns: AES Cipher instance :rtype: cryptography.hazmat.primitives.ciphers.Cipher
[ "Build", "a", "cryptography", "AES", "Cipher", "object", "." ]
python
train
rackerlabs/fastfood
fastfood/utils.py
https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/utils.py#L49-L60
def ruby_lines(text): """Tidy up lines from a file, honor # comments. Does not honor ruby block comments (yet). """ if isinstance(text, basestring): text = text.splitlines() elif not isinstance(text, list): raise TypeError("text should be a list or a string, not %s" ...
[ "def", "ruby_lines", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "basestring", ")", ":", "text", "=", "text", ".", "splitlines", "(", ")", "elif", "not", "isinstance", "(", "text", ",", "list", ")", ":", "raise", "TypeError", "(", "\...
Tidy up lines from a file, honor # comments. Does not honor ruby block comments (yet).
[ "Tidy", "up", "lines", "from", "a", "file", "honor", "#", "comments", "." ]
python
train
defunkt/pystache
pystache/parser.py
https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/parser.py#L21-L41
def parse(template, delimiters=None): """ Parse a unicode template string and return a ParsedTemplate instance. Arguments: template: a unicode template string. delimiters: a 2-tuple of delimiters. Defaults to the package default. Examples: >>> parsed = parse(u"Hey {{#who}}{{name}}!...
[ "def", "parse", "(", "template", ",", "delimiters", "=", "None", ")", ":", "if", "type", "(", "template", ")", "is", "not", "unicode", ":", "raise", "Exception", "(", "\"Template is not unicode: %s\"", "%", "type", "(", "template", ")", ")", "parser", "=",...
Parse a unicode template string and return a ParsedTemplate instance. Arguments: template: a unicode template string. delimiters: a 2-tuple of delimiters. Defaults to the package default. Examples: >>> parsed = parse(u"Hey {{#who}}{{name}}!{{/who}}") >>> print str(parsed).replace('u', ...
[ "Parse", "a", "unicode", "template", "string", "and", "return", "a", "ParsedTemplate", "instance", "." ]
python
train
vaexio/vaex
packages/vaex-core/vaex/ext/jprops.py
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/ext/jprops.py#L33-L53
def store_properties(fh, props, comment=None, timestamp=True): """ Writes properties to the file in Java properties format. :param fh: a writable file-like object :param props: a mapping (dict) or iterable of key/value pairs :param comment: comment to write to the beginning of the file :param tim...
[ "def", "store_properties", "(", "fh", ",", "props", ",", "comment", "=", "None", ",", "timestamp", "=", "True", ")", ":", "if", "comment", "is", "not", "None", ":", "write_comment", "(", "fh", ",", "comment", ")", "if", "timestamp", ":", "write_comment",...
Writes properties to the file in Java properties format. :param fh: a writable file-like object :param props: a mapping (dict) or iterable of key/value pairs :param comment: comment to write to the beginning of the file :param timestamp: boolean indicating whether to write a timestamp comment
[ "Writes", "properties", "to", "the", "file", "in", "Java", "properties", "format", "." ]
python
test
aio-libs/aiohttp
aiohttp/web_urldispatcher.py
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_urldispatcher.py#L1036-L1059
def add_static(self, prefix: str, path: PathLike, *, name: Optional[str]=None, expect_handler: Optional[_ExpectHandler]=None, chunk_size: int=256 * 1024, show_index: bool=False, follow_symlinks: bool=False, append_version: bo...
[ "def", "add_static", "(", "self", ",", "prefix", ":", "str", ",", "path", ":", "PathLike", ",", "*", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ",", "expect_handler", ":", "Optional", "[", "_ExpectHandler", "]", "=", "None", ",", "ch...
Add static files view. prefix - url prefix path - folder with files
[ "Add", "static", "files", "view", "." ]
python
train
ulf1/oxyba
oxyba/rand_imancon.py
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/rand_imancon.py#L2-L59
def rand_imancon(X, rho): """Iman-Conover Method to generate random ordinal variables (Implementation adopted from Ekstrom, 2005) x : ndarray <obs x cols> matrix with "cols" ordinal variables that are uncorrelated. rho : ndarray Spearman Rank Correlation Matrix Links ...
[ "def", "rand_imancon", "(", "X", ",", "rho", ")", ":", "import", "numpy", "as", "np", "import", "scipy", ".", "stats", "as", "sstat", "import", "scipy", ".", "special", "as", "sspec", "# data prep", "n", ",", "d", "=", "X", ".", "shape", "# Ordering", ...
Iman-Conover Method to generate random ordinal variables (Implementation adopted from Ekstrom, 2005) x : ndarray <obs x cols> matrix with "cols" ordinal variables that are uncorrelated. rho : ndarray Spearman Rank Correlation Matrix Links * Iman, R.L., Conover, W.J., 1...
[ "Iman", "-", "Conover", "Method", "to", "generate", "random", "ordinal", "variables", "(", "Implementation", "adopted", "from", "Ekstrom", "2005", ")" ]
python
train
iqbal-lab-org/cluster_vcf_records
cluster_vcf_records/vcf_record_cluster.py
https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record_cluster.py#L140-L156
def make_simple_merged_vcf_with_no_combinations(self, ref_seq): '''Does a simple merging of all variants in this cluster. Assumes one ALT in each variant. Uses the ALT for each variant, making one new vcf_record that has all the variants put together''' if len(self) <= 1: ...
[ "def", "make_simple_merged_vcf_with_no_combinations", "(", "self", ",", "ref_seq", ")", ":", "if", "len", "(", "self", ")", "<=", "1", ":", "return", "merged_vcf_record", "=", "self", ".", "vcf_records", "[", "0", "]", "for", "i", "in", "range", "(", "1", ...
Does a simple merging of all variants in this cluster. Assumes one ALT in each variant. Uses the ALT for each variant, making one new vcf_record that has all the variants put together
[ "Does", "a", "simple", "merging", "of", "all", "variants", "in", "this", "cluster", ".", "Assumes", "one", "ALT", "in", "each", "variant", ".", "Uses", "the", "ALT", "for", "each", "variant", "making", "one", "new", "vcf_record", "that", "has", "all", "t...
python
train
GNS3/gns3-server
gns3server/compute/virtualbox/virtualbox_vm.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L627-L647
def set_vmname(self, vmname): """ Renames the VirtualBox VM. :param vmname: VirtualBox VM name """ if vmname == self._vmname: return if self.linked_clone: if self.status == "started": raise VirtualBoxError("You can't change the n...
[ "def", "set_vmname", "(", "self", ",", "vmname", ")", ":", "if", "vmname", "==", "self", ".", "_vmname", ":", "return", "if", "self", ".", "linked_clone", ":", "if", "self", ".", "status", "==", "\"started\"", ":", "raise", "VirtualBoxError", "(", "\"You...
Renames the VirtualBox VM. :param vmname: VirtualBox VM name
[ "Renames", "the", "VirtualBox", "VM", "." ]
python
train
apache/incubator-mxnet
python/mxnet/profiler.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L70-L86
def profiler_set_config(mode='symbolic', filename='profile.json'): """Set up the configure of profiler (Deprecated). Parameters ---------- mode : string, optional Indicates whether to enable the profiler, can be 'symbolic', or 'all'. Defaults to `symbolic`. filename : string, option...
[ "def", "profiler_set_config", "(", "mode", "=", "'symbolic'", ",", "filename", "=", "'profile.json'", ")", ":", "warnings", ".", "warn", "(", "'profiler.profiler_set_config() is deprecated. '", "'Please use profiler.set_config() instead'", ")", "keys", "=", "c_str_array", ...
Set up the configure of profiler (Deprecated). Parameters ---------- mode : string, optional Indicates whether to enable the profiler, can be 'symbolic', or 'all'. Defaults to `symbolic`. filename : string, optional The name of output trace file. Defaults to 'profile.json'.
[ "Set", "up", "the", "configure", "of", "profiler", "(", "Deprecated", ")", "." ]
python
train
sorgerlab/indra
indra/tools/assemble_corpus.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L962-L1039
def filter_by_db_refs(stmts_in, namespace, values, policy, **kwargs): """Filter to Statements whose agents are grounded to a matching entry. Statements are filtered so that the db_refs entry (of the given namespace) of their Agent/Concept arguments take a value in the given list of values. Parameters ...
[ "def", "filter_by_db_refs", "(", "stmts_in", ",", "namespace", ",", "values", ",", "policy", ",", "*", "*", "kwargs", ")", ":", "invert", "=", "kwargs", ".", "get", "(", "'invert'", ",", "False", ")", "match_suffix", "=", "kwargs", ".", "get", "(", "'m...
Filter to Statements whose agents are grounded to a matching entry. Statements are filtered so that the db_refs entry (of the given namespace) of their Agent/Concept arguments take a value in the given list of values. Parameters ---------- stmts_in : list[indra.statements.Statement] A list...
[ "Filter", "to", "Statements", "whose", "agents", "are", "grounded", "to", "a", "matching", "entry", "." ]
python
train
edx/edx-django-extensions
edx_management_commands/management_commands/management/commands/manage_user.py
https://github.com/edx/edx-django-extensions/blob/35bbf7f95453c0e2c07acf3539722a92e7b6f548/edx_management_commands/management_commands/management/commands/manage_user.py#L26-L38
def _maybe_update(self, user, attribute, new_value): """ DRY helper. If the specified attribute of the user differs from the specified value, it will be updated. """ old_value = getattr(user, attribute) if new_value != old_value: self.stderr.write( ...
[ "def", "_maybe_update", "(", "self", ",", "user", ",", "attribute", ",", "new_value", ")", ":", "old_value", "=", "getattr", "(", "user", ",", "attribute", ")", "if", "new_value", "!=", "old_value", ":", "self", ".", "stderr", ".", "write", "(", "_", "...
DRY helper. If the specified attribute of the user differs from the specified value, it will be updated.
[ "DRY", "helper", ".", "If", "the", "specified", "attribute", "of", "the", "user", "differs", "from", "the", "specified", "value", "it", "will", "be", "updated", "." ]
python
train
pdkit/pdkit
pdkit/tremor_processor.py
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/tremor_processor.py#L192-L217
def approximate_entropy(self, x, m=None, r=None): """ As in tsfresh \ `approximate_entropy <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\ feature_calculators.py#L1601>`_ Implements a `vectorized approximate entropy algorithm <https://en.wikipedi...
[ "def", "approximate_entropy", "(", "self", ",", "x", ",", "m", "=", "None", ",", "r", "=", "None", ")", ":", "if", "m", "is", "None", "or", "r", "is", "None", ":", "m", "=", "2", "r", "=", "0.3", "entropy", "=", "feature_calculators", ".", "appro...
As in tsfresh \ `approximate_entropy <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\ feature_calculators.py#L1601>`_ Implements a `vectorized approximate entropy algorithm <https://en.wikipedia.org/wiki/Approximate_entropy>`_ For short time-series this ...
[ "As", "in", "tsfresh", "\\", "approximate_entropy", "<https", ":", "//", "github", ".", "com", "/", "blue", "-", "yonder", "/", "tsfresh", "/", "blob", "/", "master", "/", "tsfresh", "/", "feature_extraction", "/", "\\", "feature_calculators", ".", "py#L1601...
python
train
oscarbranson/latools
latools/D_obj.py
https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/D_obj.py#L593-L606
def ablation_times(self): """ Function for calculating the ablation time for each ablation. Returns ------- dict of times for each ablation. """ ats = {} for n in np.arange(self.n) + 1: t = self.Time[self.ns == n] ats[n...
[ "def", "ablation_times", "(", "self", ")", ":", "ats", "=", "{", "}", "for", "n", "in", "np", ".", "arange", "(", "self", ".", "n", ")", "+", "1", ":", "t", "=", "self", ".", "Time", "[", "self", ".", "ns", "==", "n", "]", "ats", "[", "n", ...
Function for calculating the ablation time for each ablation. Returns ------- dict of times for each ablation.
[ "Function", "for", "calculating", "the", "ablation", "time", "for", "each", "ablation", "." ]
python
test
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L193-L204
def __replace_base_variables(text, req_len, idx): """ Replace i and n in text with index+1 and req_len. :param text: base text to modify :param req_len: amount of required resources :param idx: index of resource we are working on :return: modified string """ ...
[ "def", "__replace_base_variables", "(", "text", ",", "req_len", ",", "idx", ")", ":", "return", "text", ".", "replace", "(", "\"{i}\"", ",", "str", "(", "idx", "+", "1", ")", ")", ".", "replace", "(", "\"{n}\"", ",", "str", "(", "req_len", ")", ")" ]
Replace i and n in text with index+1 and req_len. :param text: base text to modify :param req_len: amount of required resources :param idx: index of resource we are working on :return: modified string
[ "Replace", "i", "and", "n", "in", "text", "with", "index", "+", "1", "and", "req_len", "." ]
python
train
AltSchool/dynamic-rest
dynamic_rest/viewsets.py
https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L178-L205
def _extract_object_params(self, name): """ Extract object params, return as dict """ params = self.request.query_params.lists() params_map = {} prefix = name[:-1] offset = len(prefix) for name, value in params: if name.startswith(prefix): ...
[ "def", "_extract_object_params", "(", "self", ",", "name", ")", ":", "params", "=", "self", ".", "request", ".", "query_params", ".", "lists", "(", ")", "params_map", "=", "{", "}", "prefix", "=", "name", "[", ":", "-", "1", "]", "offset", "=", "len"...
Extract object params, return as dict
[ "Extract", "object", "params", "return", "as", "dict" ]
python
train
fedora-python/pyp2rpm
pyp2rpm/dependency_parser.py
https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/dependency_parser.py#L47-L72
def deps_from_pyp_format(requires, runtime=True): """Parses dependencies extracted from setup.py. Args: requires: list of dependencies as written in setup.py of the package. runtime: are the dependencies runtime (True) or build time (False)? Returns: List of semi-SPECFILE dependencie...
[ "def", "deps_from_pyp_format", "(", "requires", ",", "runtime", "=", "True", ")", ":", "parsed", "=", "[", "]", "logger", ".", "debug", "(", "\"Dependencies from setup.py: {0} runtime: {1}.\"", ".", "format", "(", "requires", ",", "runtime", ")", ")", "for", "...
Parses dependencies extracted from setup.py. Args: requires: list of dependencies as written in setup.py of the package. runtime: are the dependencies runtime (True) or build time (False)? Returns: List of semi-SPECFILE dependencies (see dependency_to_rpm for format).
[ "Parses", "dependencies", "extracted", "from", "setup", ".", "py", ".", "Args", ":", "requires", ":", "list", "of", "dependencies", "as", "written", "in", "setup", ".", "py", "of", "the", "package", ".", "runtime", ":", "are", "the", "dependencies", "runti...
python
train
textmagic/textmagic-rest-python
textmagic/rest/models/user.py
https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/user.py#L61-L75
def update(self, **kwargs): """ Update an current User via a PUT request. Returns True if success. :Example: client.user.update(firstName="John", lastName="Doe", company="TextMagic") :param str firstName: User first name. Required. :param str lastName: User la...
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "response", ",", "instance", "=", "self", ".", "request", "(", "\"PUT\"", ",", "self", ".", "uri", ",", "data", "=", "kwargs", ")", "return", "response", ".", "status", "==", "201" ]
Update an current User via a PUT request. Returns True if success. :Example: client.user.update(firstName="John", lastName="Doe", company="TextMagic") :param str firstName: User first name. Required. :param str lastName: User last name. Required. :param str company: ...
[ "Update", "an", "current", "User", "via", "a", "PUT", "request", ".", "Returns", "True", "if", "success", "." ]
python
train
IntegralDefense/critsapi
critsapi/critsdbapi.py
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L134-L171
def add_embedded_campaign(self, id, collection, campaign, confidence, analyst, date, description): """ Adds an embedded campaign to the TLO. Args: id: the CRITs object id of the TLO collection: The db collection. See main class documentation...
[ "def", "add_embedded_campaign", "(", "self", ",", "id", ",", "collection", ",", "campaign", ",", "confidence", ",", "analyst", ",", "date", ",", "description", ")", ":", "if", "type", "(", "id", ")", "is", "not", "ObjectId", ":", "id", "=", "ObjectId", ...
Adds an embedded campaign to the TLO. Args: id: the CRITs object id of the TLO collection: The db collection. See main class documentation. campaign: The campaign to assign. confidence: The campaign confidence analyst: The analyst making the assignmen...
[ "Adds", "an", "embedded", "campaign", "to", "the", "TLO", "." ]
python
train
log2timeline/dfvfs
dfvfs/volume/volume_system.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/volume/volume_system.py#L59-L74
def _AddAttribute(self, attribute): """Adds an attribute. Args: attribute (VolumeAttribute): a volume attribute. Raises: KeyError: if volume attribute is already set for the corresponding volume attribute identifier. """ if attribute.identifier in self._attributes: rais...
[ "def", "_AddAttribute", "(", "self", ",", "attribute", ")", ":", "if", "attribute", ".", "identifier", "in", "self", ".", "_attributes", ":", "raise", "KeyError", "(", "(", "'Volume attribute object already set for volume attribute '", "'identifier: {0:s}.'", ")", "."...
Adds an attribute. Args: attribute (VolumeAttribute): a volume attribute. Raises: KeyError: if volume attribute is already set for the corresponding volume attribute identifier.
[ "Adds", "an", "attribute", "." ]
python
train
secdev/scapy
scapy/arch/windows/__init__.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/arch/windows/__init__.py#L174-L183
def _exec_cmd(command): """Call a CMD command and return the output and returncode""" proc = sp.Popen(command, stdout=sp.PIPE, shell=True) if six.PY2: res = proc.communicate()[0] else: res = proc.communicate(timeout=5)[0] return res, proc.retur...
[ "def", "_exec_cmd", "(", "command", ")", ":", "proc", "=", "sp", ".", "Popen", "(", "command", ",", "stdout", "=", "sp", ".", "PIPE", ",", "shell", "=", "True", ")", "if", "six", ".", "PY2", ":", "res", "=", "proc", ".", "communicate", "(", ")", ...
Call a CMD command and return the output and returncode
[ "Call", "a", "CMD", "command", "and", "return", "the", "output", "and", "returncode" ]
python
train
fchauvel/MAD
mad/parsing.py
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L243-L253
def p_operation_list(p): """ operation_list : define_operation operation_list | define_operation """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_operation_list'")
[ "def", "p_operation_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "p", "[", "2", "]", "elif", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "p...
operation_list : define_operation operation_list | define_operation
[ "operation_list", ":", "define_operation", "operation_list", "|", "define_operation" ]
python
train
samstav/requests-chef
requests_chef/mixlib_auth.py
https://github.com/samstav/requests-chef/blob/a0bf013b925abd0cf76eeaf6300cf32659632773/requests_chef/mixlib_auth.py#L38-L48
def digester(data): """Create SHA-1 hash, get digest, b64 encode, split every 60 char.""" if not isinstance(data, six.binary_type): data = data.encode('utf_8') hashof = hashlib.sha1(data).digest() encoded_hash = base64.b64encode(hashof) if not isinstance(encoded_hash, six.string_types): ...
[ "def", "digester", "(", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "six", ".", "binary_type", ")", ":", "data", "=", "data", ".", "encode", "(", "'utf_8'", ")", "hashof", "=", "hashlib", ".", "sha1", "(", "data", ")", ".", "dige...
Create SHA-1 hash, get digest, b64 encode, split every 60 char.
[ "Create", "SHA", "-", "1", "hash", "get", "digest", "b64", "encode", "split", "every", "60", "char", "." ]
python
train
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L516-L532
def get_requests(self): """ Creates tile structure and returns list of files for download. :return: List of download requests and list of empty folders that need to be created :rtype: (list(download.DownloadRequest), list(str)) """ self.download_list = [] for dat...
[ "def", "get_requests", "(", "self", ")", ":", "self", ".", "download_list", "=", "[", "]", "for", "data_name", "in", "[", "band", "for", "band", "in", "self", ".", "bands", "if", "self", ".", "_band_exists", "(", "band", ")", "]", "+", "self", ".", ...
Creates tile structure and returns list of files for download. :return: List of download requests and list of empty folders that need to be created :rtype: (list(download.DownloadRequest), list(str))
[ "Creates", "tile", "structure", "and", "returns", "list", "of", "files", "for", "download", "." ]
python
train
ZELLMECHANIK-DRESDEN/dclab
dclab/isoelastics/__init__.py
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/isoelastics/__init__.py#L33-L41
def _add(self, isoel, col1, col2, method, meta): """Convenience method for population self._data""" self._data[method][col1][col2]["isoelastics"] = isoel self._data[method][col1][col2]["meta"] = meta # Use advanced slicing to flip the data columns isoel_flip = [iso[:, [1, 0, 2]]...
[ "def", "_add", "(", "self", ",", "isoel", ",", "col1", ",", "col2", ",", "method", ",", "meta", ")", ":", "self", ".", "_data", "[", "method", "]", "[", "col1", "]", "[", "col2", "]", "[", "\"isoelastics\"", "]", "=", "isoel", "self", ".", "_data...
Convenience method for population self._data
[ "Convenience", "method", "for", "population", "self", ".", "_data" ]
python
train
mozilla/funfactory
funfactory/cmd.py
https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/cmd.py#L225-L230
def dir_path(dir): """with dir_path(path) to change into a directory.""" old_dir = os.getcwd() os.chdir(dir) yield os.chdir(old_dir)
[ "def", "dir_path", "(", "dir", ")", ":", "old_dir", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "dir", ")", "yield", "os", ".", "chdir", "(", "old_dir", ")" ]
with dir_path(path) to change into a directory.
[ "with", "dir_path", "(", "path", ")", "to", "change", "into", "a", "directory", "." ]
python
train
rikrd/inspire
inspirespeech/htk.py
https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/htk.py#L223-L242
def load_mlf(filename, utf8_normalization=None): """Load an HTK Master Label File. :param filename: The filename of the MLF file. :param utf8_normalization: None """ with codecs.open(filename, 'r', 'string_escape') as f: data = f.read().decode('utf8') if utf8_normalization: ...
[ "def", "load_mlf", "(", "filename", ",", "utf8_normalization", "=", "None", ")", ":", "with", "codecs", ".", "open", "(", "filename", ",", "'r'", ",", "'string_escape'", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", ".", "decode", "("...
Load an HTK Master Label File. :param filename: The filename of the MLF file. :param utf8_normalization: None
[ "Load", "an", "HTK", "Master", "Label", "File", "." ]
python
train
openspending/ckanext-budgets
ckanext/budgets/plugin.py
https://github.com/openspending/ckanext-budgets/blob/07dde5a4fdec6b36ceb812b70f0c31cdecb40cfc/ckanext/budgets/plugin.py#L263-L282
def before_create(self, context, resource): """ When triggered the resource which can either be uploaded or linked to will be parsed and analysed to see if it possibly is a budget data package resource (checking if all required headers and any of the recommended headers exist in ...
[ "def", "before_create", "(", "self", ",", "context", ",", "resource", ")", ":", "# If the resource is being uploaded we load the uploaded file", "# If not we load the provided url", "if", "resource", ".", "get", "(", "'upload'", ",", "''", ")", "==", "''", ":", "self"...
When triggered the resource which can either be uploaded or linked to will be parsed and analysed to see if it possibly is a budget data package resource (checking if all required headers and any of the recommended headers exist in the csv). The budget data package specific fields are t...
[ "When", "triggered", "the", "resource", "which", "can", "either", "be", "uploaded", "or", "linked", "to", "will", "be", "parsed", "and", "analysed", "to", "see", "if", "it", "possibly", "is", "a", "budget", "data", "package", "resource", "(", "checking", "...
python
train
CyberReboot/vent
vent/menus/add.py
https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/add.py#L18-L69
def create(self): """ Create widgets for AddForm """ self.add_handlers({'^T': self.quit, '^Q': self.quit}) self.add(npyscreen.Textfield, value='Add a plugin from a Git repository or an image from a ' 'Docker registry.', editable=False, ...
[ "def", "create", "(", "self", ")", ":", "self", ".", "add_handlers", "(", "{", "'^T'", ":", "self", ".", "quit", ",", "'^Q'", ":", "self", ".", "quit", "}", ")", "self", ".", "add", "(", "npyscreen", ".", "Textfield", ",", "value", "=", "'Add a plu...
Create widgets for AddForm
[ "Create", "widgets", "for", "AddForm" ]
python
train
gangverk/flask-swagger
flask_swagger.py
https://github.com/gangverk/flask-swagger/blob/fa4eb7d4cbebfd30d4033626160881b77ad2b156/flask_swagger.py#L20-L37
def _find_from_file(full_doc, from_file_keyword): """ Finds a line in <full_doc> like <from_file_keyword> <colon> <path> and return path """ path = None for line in full_doc.splitlines(): if from_file_keyword in line: parts = line.strip().split(':') if ...
[ "def", "_find_from_file", "(", "full_doc", ",", "from_file_keyword", ")", ":", "path", "=", "None", "for", "line", "in", "full_doc", ".", "splitlines", "(", ")", ":", "if", "from_file_keyword", "in", "line", ":", "parts", "=", "line", ".", "strip", "(", ...
Finds a line in <full_doc> like <from_file_keyword> <colon> <path> and return path
[ "Finds", "a", "line", "in", "<full_doc", ">", "like" ]
python
train
gem/oq-engine
openquake/calculators/base.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L931-L956
def save_gmf_data(dstore, sitecol, gmfs, imts, events=()): """ :param dstore: a :class:`openquake.baselib.datastore.DataStore` instance :param sitecol: a :class:`openquake.hazardlib.site.SiteCollection` instance :param gmfs: an array of shape (N, E, M) :param imts: a list of IMT strings :param e...
[ "def", "save_gmf_data", "(", "dstore", ",", "sitecol", ",", "gmfs", ",", "imts", ",", "events", "=", "(", ")", ")", ":", "if", "len", "(", "events", ")", "==", "0", ":", "E", "=", "gmfs", ".", "shape", "[", "1", "]", "events", "=", "numpy", "."...
:param dstore: a :class:`openquake.baselib.datastore.DataStore` instance :param sitecol: a :class:`openquake.hazardlib.site.SiteCollection` instance :param gmfs: an array of shape (N, E, M) :param imts: a list of IMT strings :param events: E event IDs or the empty tuple
[ ":", "param", "dstore", ":", "a", ":", "class", ":", "openquake", ".", "baselib", ".", "datastore", ".", "DataStore", "instance", ":", "param", "sitecol", ":", "a", ":", "class", ":", "openquake", ".", "hazardlib", ".", "site", ".", "SiteCollection", "in...
python
train
quantopian/empyrical
empyrical/stats.py
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L963-L992
def _aligned_series(*many_series): """ Return a new list of series containing the data in the input series, but with their indices aligned. NaNs will be filled in for missing values. Parameters ---------- *many_series The series to align. Returns ------- aligned_series : it...
[ "def", "_aligned_series", "(", "*", "many_series", ")", ":", "head", "=", "many_series", "[", "0", "]", "tail", "=", "many_series", "[", "1", ":", "]", "n", "=", "len", "(", "head", ")", "if", "(", "isinstance", "(", "head", ",", "np", ".", "ndarra...
Return a new list of series containing the data in the input series, but with their indices aligned. NaNs will be filled in for missing values. Parameters ---------- *many_series The series to align. Returns ------- aligned_series : iterable[array-like] A new list of series...
[ "Return", "a", "new", "list", "of", "series", "containing", "the", "data", "in", "the", "input", "series", "but", "with", "their", "indices", "aligned", ".", "NaNs", "will", "be", "filled", "in", "for", "missing", "values", "." ]
python
train
marshmallow-code/marshmallow
src/marshmallow/schema.py
https://github.com/marshmallow-code/marshmallow/blob/a6b6c4151f1fbf16f3774d4052ca2bddf6903750/src/marshmallow/schema.py#L986-L1008
def _bind_field(self, field_name, field_obj): """Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name). Also set field load_only and dump_only values if field_name was specified in ``class Meta``. """ try: if field_nam...
[ "def", "_bind_field", "(", "self", ",", "field_name", ",", "field_obj", ")", ":", "try", ":", "if", "field_name", "in", "self", ".", "load_only", ":", "field_obj", ".", "load_only", "=", "True", "if", "field_name", "in", "self", ".", "dump_only", ":", "f...
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name). Also set field load_only and dump_only values if field_name was specified in ``class Meta``.
[ "Bind", "field", "to", "the", "schema", "setting", "any", "necessary", "attributes", "on", "the", "field", "(", "e", ".", "g", ".", "parent", "and", "name", ")", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/overlay_policy_map_state/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/overlay_policy_map_state/__init__.py#L141-L164
def _set_active_on(self, v, load=False): """ Setter method for active_on, mapped from YANG variable /overlay_policy_map_state/active_on (container) If this variable is read-only (config: false) in the source YANG file, then _set_active_on is considered as a private method. Backends looking to popula...
[ "def", "_set_active_on", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base...
Setter method for active_on, mapped from YANG variable /overlay_policy_map_state/active_on (container) If this variable is read-only (config: false) in the source YANG file, then _set_active_on is considered as a private method. Backends looking to populate this variable should do so via calling thisObj...
[ "Setter", "method", "for", "active_on", "mapped", "from", "YANG", "variable", "/", "overlay_policy_map_state", "/", "active_on", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "sourc...
python
train
happyleavesaoc/python-orvibo
orvibo/s20.py
https://github.com/happyleavesaoc/python-orvibo/blob/27210dfe0c44a9e4f2ef4edf2dac221977d7f5c9/orvibo/s20.py#L167-L188
def _discover_mac(self): """ Discovers MAC address of device. Discovery is done by sending a UDP broadcast. All configured devices reply. The response contains the MAC address in both needed formats. Discovery of multiple switches must be done synchronously. :returns: ...
[ "def", "_discover_mac", "(", "self", ")", ":", "mac", "=", "None", "mac_reversed", "=", "None", "cmd", "=", "MAGIC", "+", "DISCOVERY", "resp", "=", "self", ".", "_udp_transact", "(", "cmd", ",", "self", ".", "_discovery_resp", ",", "broadcast", "=", "Tru...
Discovers MAC address of device. Discovery is done by sending a UDP broadcast. All configured devices reply. The response contains the MAC address in both needed formats. Discovery of multiple switches must be done synchronously. :returns: Tuple of MAC address and reversed MAC...
[ "Discovers", "MAC", "address", "of", "device", "." ]
python
train
trentm/cmdln
examples/svn.py
https://github.com/trentm/cmdln/blob/55e980cf52c9b03e62d2349a7e62c9101d08ae10/examples/svn.py#L518-L549
def do_log(self, subcmd, opts, *args): """Show the log messages for a set of revision(s) and/or file(s). usage: 1. log [PATH] 2. log URL [PATH...] 1. Print the log messages for a local PATH (default: '.'). The default revision range is BASE:1. ...
[ "def", "do_log", "(", "self", ",", "subcmd", ",", "opts", ",", "*", "args", ")", ":", "print", "\"'svn %s' opts: %s\"", "%", "(", "subcmd", ",", "opts", ")", "print", "\"'svn %s' args: %s\"", "%", "(", "subcmd", ",", "args", ")" ]
Show the log messages for a set of revision(s) and/or file(s). usage: 1. log [PATH] 2. log URL [PATH...] 1. Print the log messages for a local PATH (default: '.'). The default revision range is BASE:1. 2. Print the log messages for the PATHs ...
[ "Show", "the", "log", "messages", "for", "a", "set", "of", "revision", "(", "s", ")", "and", "/", "or", "file", "(", "s", ")", "." ]
python
train
rytilahti/python-songpal
songpal/device.py
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L304-L307
async def set_custom_eq(self, target: str, value: str) -> None: """Set custom EQ settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["audio"]["setCustomEqualizerSettings"](params)
[ "async", "def", "set_custom_eq", "(", "self", ",", "target", ":", "str", ",", "value", ":", "str", ")", "->", "None", ":", "params", "=", "{", "\"settings\"", ":", "[", "{", "\"target\"", ":", "target", ",", "\"value\"", ":", "value", "}", "]", "}", ...
Set custom EQ settings.
[ "Set", "custom", "EQ", "settings", "." ]
python
train
silver-castle/mach9
mach9/response.py
https://github.com/silver-castle/mach9/blob/7a623aab3c70d89d36ade6901b6307e115400c5e/mach9/response.py#L376-L394
def redirect(to, headers=None, status=302, content_type='text/html; charset=utf-8'): '''Abort execution and cause a 302 redirect (by default). :param to: path or fully qualified URL to redirect to :param headers: optional dict of headers to include in the new request :param status: status ...
[ "def", "redirect", "(", "to", ",", "headers", "=", "None", ",", "status", "=", "302", ",", "content_type", "=", "'text/html; charset=utf-8'", ")", ":", "headers", "=", "headers", "or", "{", "}", "# According to RFC 7231, a relative URI is now permitted.", "headers",...
Abort execution and cause a 302 redirect (by default). :param to: path or fully qualified URL to redirect to :param headers: optional dict of headers to include in the new request :param status: status code (int) of the new request, defaults to 302 :param content_type: the content type (string) of the ...
[ "Abort", "execution", "and", "cause", "a", "302", "redirect", "(", "by", "default", ")", "." ]
python
train
jonathansick/paperweight
paperweight/texutils.py
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/texutils.py#L57-L61
def iter_tex_documents(base_dir="."): """Iterate through all .tex documents in the current directory.""" for path, dirlist, filelist in os.walk(base_dir): for name in fnmatch.filter(filelist, "*.tex"): yield os.path.join(path, name)
[ "def", "iter_tex_documents", "(", "base_dir", "=", "\".\"", ")", ":", "for", "path", ",", "dirlist", ",", "filelist", "in", "os", ".", "walk", "(", "base_dir", ")", ":", "for", "name", "in", "fnmatch", ".", "filter", "(", "filelist", ",", "\"*.tex\"", ...
Iterate through all .tex documents in the current directory.
[ "Iterate", "through", "all", ".", "tex", "documents", "in", "the", "current", "directory", "." ]
python
train
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/lxml/html/diff.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/lxml/html/diff.py#L71-L77
def tokenize_annotated(doc, annotation): """Tokenize a document and add an annotation attribute to each token """ tokens = tokenize(doc, include_hrefs=False) for tok in tokens: tok.annotation = annotation return tokens
[ "def", "tokenize_annotated", "(", "doc", ",", "annotation", ")", ":", "tokens", "=", "tokenize", "(", "doc", ",", "include_hrefs", "=", "False", ")", "for", "tok", "in", "tokens", ":", "tok", ".", "annotation", "=", "annotation", "return", "tokens" ]
Tokenize a document and add an annotation attribute to each token
[ "Tokenize", "a", "document", "and", "add", "an", "annotation", "attribute", "to", "each", "token" ]
python
test
RobotStudio/bors
bors/api/adapter/api.py
https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/adapter/api.py#L34-L53
def call(self, callname, arguments=None): """Executed on each scheduled iteration""" # See if a method override exists action = getattr(self.api, callname, None) if action is None: try: action = self.api.ENDPOINT_OVERRIDES.get(callname, None) excep...
[ "def", "call", "(", "self", ",", "callname", ",", "arguments", "=", "None", ")", ":", "# See if a method override exists", "action", "=", "getattr", "(", "self", ".", "api", ",", "callname", ",", "None", ")", "if", "action", "is", "None", ":", "try", ":"...
Executed on each scheduled iteration
[ "Executed", "on", "each", "scheduled", "iteration" ]
python
train
PmagPy/PmagPy
pmagpy/builder2.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/builder2.py#L1193-L1207
def validate_data(self): """ Validate specimen, sample, site, and location data. """ warnings = {} spec_warnings, samp_warnings, site_warnings, loc_warnings = {}, {}, {}, {} if self.specimens: spec_warnings = self.validate_items(self.specimens, 'specimen') ...
[ "def", "validate_data", "(", "self", ")", ":", "warnings", "=", "{", "}", "spec_warnings", ",", "samp_warnings", ",", "site_warnings", ",", "loc_warnings", "=", "{", "}", ",", "{", "}", ",", "{", "}", ",", "{", "}", "if", "self", ".", "specimens", ":...
Validate specimen, sample, site, and location data.
[ "Validate", "specimen", "sample", "site", "and", "location", "data", "." ]
python
train
chrisrink10/basilisp
src/basilisp/lang/compiler/optimizer.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/optimizer.py#L75-L86
def visit_While(self, node: ast.While) -> Optional[ast.AST]: """Eliminate dead code from while bodies.""" new_node = self.generic_visit(node) assert isinstance(new_node, ast.While) return ast.copy_location( ast.While( test=new_node.test, body=_...
[ "def", "visit_While", "(", "self", ",", "node", ":", "ast", ".", "While", ")", "->", "Optional", "[", "ast", ".", "AST", "]", ":", "new_node", "=", "self", ".", "generic_visit", "(", "node", ")", "assert", "isinstance", "(", "new_node", ",", "ast", "...
Eliminate dead code from while bodies.
[ "Eliminate", "dead", "code", "from", "while", "bodies", "." ]
python
test
duniter/duniter-python-api
duniterpy/api/client.py
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/client.py#L277-L285
def connect_ws(self, path: str) -> _WSRequestContextManager: """ Connect to a websocket in order to use API parameters :param path: the url path :return: """ client = API(self.endpoint.conn_handler(self.session, self.proxy)) return client.connect_ws(path)
[ "def", "connect_ws", "(", "self", ",", "path", ":", "str", ")", "->", "_WSRequestContextManager", ":", "client", "=", "API", "(", "self", ".", "endpoint", ".", "conn_handler", "(", "self", ".", "session", ",", "self", ".", "proxy", ")", ")", "return", ...
Connect to a websocket in order to use API parameters :param path: the url path :return:
[ "Connect", "to", "a", "websocket", "in", "order", "to", "use", "API", "parameters" ]
python
train
bootphon/h5features
h5features/convert2h5features.py
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/convert2h5features.py#L50-L56
def main(): """Main function of the converter command-line tool, ``convert2h5features --help`` for a more complete doc.""" args = parse_args() converter = h5f.Converter(args.output, args.group, args.chunk) for infile in args.file: converter.convert(infile)
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "converter", "=", "h5f", ".", "Converter", "(", "args", ".", "output", ",", "args", ".", "group", ",", "args", ".", "chunk", ")", "for", "infile", "in", "args", ".", "file", ":", ...
Main function of the converter command-line tool, ``convert2h5features --help`` for a more complete doc.
[ "Main", "function", "of", "the", "converter", "command", "-", "line", "tool", "convert2h5features", "--", "help", "for", "a", "more", "complete", "doc", "." ]
python
train
openstax/cnx-publishing
cnxpublishing/db.py
https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L1187-L1202
def remove_role_requests(cursor, uuid_, roles): """Given a ``uuid`` and list of dicts containing the ``uid`` (user identifiers) and ``role`` for removal of the identified users' role acceptance entries. """ if not isinstance(roles, (list, set, tuple,)): raise TypeError("``roles`` is an inval...
[ "def", "remove_role_requests", "(", "cursor", ",", "uuid_", ",", "roles", ")", ":", "if", "not", "isinstance", "(", "roles", ",", "(", "list", ",", "set", ",", "tuple", ",", ")", ")", ":", "raise", "TypeError", "(", "\"``roles`` is an invalid type: {}\"", ...
Given a ``uuid`` and list of dicts containing the ``uid`` (user identifiers) and ``role`` for removal of the identified users' role acceptance entries.
[ "Given", "a", "uuid", "and", "list", "of", "dicts", "containing", "the", "uid", "(", "user", "identifiers", ")", "and", "role", "for", "removal", "of", "the", "identified", "users", "role", "acceptance", "entries", "." ]
python
valid
bukun/TorCMS
torcms/handlers/post_handler.py
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L622-L647
def _delete(self, *args, **kwargs): ''' delete the post. ''' _ = kwargs uid = args[0] current_infor = MPost.get_by_uid(uid) if MPost.delete(uid): tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid']) MCategory.update_count(c...
[ "def", "_delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_", "=", "kwargs", "uid", "=", "args", "[", "0", "]", "current_infor", "=", "MPost", ".", "get_by_uid", "(", "uid", ")", "if", "MPost", ".", "delete", "(", "uid"...
delete the post.
[ "delete", "the", "post", "." ]
python
train
PmagPy/PmagPy
programs/demag_gui.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L6166-L6175
def update_GUI_with_new_interpretation(self): """ update statistics boxes and figures with a new interpretatiom when selecting new temperature bound """ self.update_fit_bounds_and_statistics() self.draw_interpretations() self.calculate_high_levels_data() ...
[ "def", "update_GUI_with_new_interpretation", "(", "self", ")", ":", "self", ".", "update_fit_bounds_and_statistics", "(", ")", "self", ".", "draw_interpretations", "(", ")", "self", ".", "calculate_high_levels_data", "(", ")", "self", ".", "plot_high_levels_data", "("...
update statistics boxes and figures with a new interpretatiom when selecting new temperature bound
[ "update", "statistics", "boxes", "and", "figures", "with", "a", "new", "interpretatiom", "when", "selecting", "new", "temperature", "bound" ]
python
train
useblocks/sphinxcontrib-needs
sphinxcontrib/needs/filter_common.py
https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/filter_common.py#L68-L117
def procces_filters(all_needs, current_needlist): """ Filters all needs with given configuration :param current_needlist: needlist object, which stores all filters :param all_needs: List of all needs inside document :return: list of needs, which passed the filters """ if current_needlist[...
[ "def", "procces_filters", "(", "all_needs", ",", "current_needlist", ")", ":", "if", "current_needlist", "[", "\"sort_by\"", "]", "is", "not", "None", ":", "if", "current_needlist", "[", "\"sort_by\"", "]", "==", "\"id\"", ":", "all_needs", "=", "sorted", "(",...
Filters all needs with given configuration :param current_needlist: needlist object, which stores all filters :param all_needs: List of all needs inside document :return: list of needs, which passed the filters
[ "Filters", "all", "needs", "with", "given", "configuration" ]
python
train
sergiocorreia/panflute
panflute/io.py
https://github.com/sergiocorreia/panflute/blob/65c2d570c26a190deb600cab5e2ad8a828a3302e/panflute/io.py#L96-L165
def dump(doc, output_stream=None): """ Dump a :class:`.Doc` object into a JSON-encoded text string. The output will be sent to :data:`sys.stdout` unless an alternative text stream is given. To dump to :data:`sys.stdout` just do: >>> import panflute as pf >>> doc = pf.Doc(Para(Str(...
[ "def", "dump", "(", "doc", ",", "output_stream", "=", "None", ")", ":", "assert", "type", "(", "doc", ")", "==", "Doc", ",", "\"panflute.dump needs input of type panflute.Doc\"", "if", "output_stream", "is", "None", ":", "sys", ".", "stdout", "=", "codecs", ...
Dump a :class:`.Doc` object into a JSON-encoded text string. The output will be sent to :data:`sys.stdout` unless an alternative text stream is given. To dump to :data:`sys.stdout` just do: >>> import panflute as pf >>> doc = pf.Doc(Para(Str('a'))) # Create sample document >>> pf...
[ "Dump", "a", ":", "class", ":", ".", "Doc", "object", "into", "a", "JSON", "-", "encoded", "text", "string", "." ]
python
train
Alignak-monitoring/alignak
alignak/objects/escalation.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/escalation.py#L349-L366
def linkify_es_by_h(self, hosts): """Add each escalation object into host.escalation attribute :param hosts: host list, used to look for a specific host :type hosts: alignak.objects.host.Hosts :return: None """ for escal in self: # If no host, no hope of havi...
[ "def", "linkify_es_by_h", "(", "self", ",", "hosts", ")", ":", "for", "escal", "in", "self", ":", "# If no host, no hope of having a service", "if", "(", "not", "hasattr", "(", "escal", ",", "'host_name'", ")", "or", "escal", ".", "host_name", ".", "strip", ...
Add each escalation object into host.escalation attribute :param hosts: host list, used to look for a specific host :type hosts: alignak.objects.host.Hosts :return: None
[ "Add", "each", "escalation", "object", "into", "host", ".", "escalation", "attribute" ]
python
train
aaren/notedown
notedown/notedown.py
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L648-L679
def get_caption_comments(content): """Retrieve an id and a caption from a code cell. If the code cell content begins with a commented block that looks like ## fig:id # multi-line or single-line # caption then the 'fig:id' and the caption will be returned. The '#' are stripped. """...
[ "def", "get_caption_comments", "(", "content", ")", ":", "if", "not", "content", ".", "startswith", "(", "'## fig:'", ")", ":", "return", "None", ",", "None", "content", "=", "content", ".", "splitlines", "(", ")", "id", "=", "content", "[", "0", "]", ...
Retrieve an id and a caption from a code cell. If the code cell content begins with a commented block that looks like ## fig:id # multi-line or single-line # caption then the 'fig:id' and the caption will be returned. The '#' are stripped.
[ "Retrieve", "an", "id", "and", "a", "caption", "from", "a", "code", "cell", "." ]
python
train
edx/bok-choy
bok_choy/promise.py
https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/promise.py#L111-L136
def _check_fulfilled(self): """ Return tuple `(is_fulfilled, result)` where `is_fulfilled` is a boolean indicating whether the promise has been fulfilled and `result` is the value to pass to the `with` block. """ is_fulfilled = False result = None start_ti...
[ "def", "_check_fulfilled", "(", "self", ")", ":", "is_fulfilled", "=", "False", "result", "=", "None", "start_time", "=", "time", ".", "time", "(", ")", "# Check whether the promise has been fulfilled until we run out of time or attempts", "while", "self", ".", "_has_ti...
Return tuple `(is_fulfilled, result)` where `is_fulfilled` is a boolean indicating whether the promise has been fulfilled and `result` is the value to pass to the `with` block.
[ "Return", "tuple", "(", "is_fulfilled", "result", ")", "where", "is_fulfilled", "is", "a", "boolean", "indicating", "whether", "the", "promise", "has", "been", "fulfilled", "and", "result", "is", "the", "value", "to", "pass", "to", "the", "with", "block", "....
python
train
seleniumbase/SeleniumBase
seleniumbase/fixtures/page_utils.py
https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/page_utils.py#L25-L32
def is_xpath_selector(selector): """ A basic method to determine if a selector is an xpath selector. """ if (selector.startswith('/') or selector.startswith('./') or ( selector.startswith('('))): return True return False
[ "def", "is_xpath_selector", "(", "selector", ")", ":", "if", "(", "selector", ".", "startswith", "(", "'/'", ")", "or", "selector", ".", "startswith", "(", "'./'", ")", "or", "(", "selector", ".", "startswith", "(", "'('", ")", ")", ")", ":", "return",...
A basic method to determine if a selector is an xpath selector.
[ "A", "basic", "method", "to", "determine", "if", "a", "selector", "is", "an", "xpath", "selector", "." ]
python
train
quantopian/pyfolio
pyfolio/plotting.py
https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L346-L400
def plot_long_short_holdings(returns, positions, legend_loc='upper left', ax=None, **kwargs): """ Plots total amount of stocks with an active position, breaking out short and long into transparent filled regions. Parameters ---------- returns : pd.Series Dai...
[ "def", "plot_long_short_holdings", "(", "returns", ",", "positions", ",", "legend_loc", "=", "'upper left'", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "positions", ...
Plots total amount of stocks with an active position, breaking out short and long into transparent filled regions. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. positions : pd.DataFram...
[ "Plots", "total", "amount", "of", "stocks", "with", "an", "active", "position", "breaking", "out", "short", "and", "long", "into", "transparent", "filled", "regions", "." ]
python
valid
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L662-L676
def overlay_gateway_access_lists_mac_in_cg_mac_acl_in_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, ...
[ "def", "overlay_gateway_access_lists_mac_in_cg_mac_acl_in_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "overlay_gateway", "=", "ET", ".", "SubElement", "(", "config", ",", "\"overlay-gateway\""...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
Element-34/py.saunter
saunter/matchers.py
https://github.com/Element-34/py.saunter/blob/bdc8480b1453e082872c80d3382d42565b8ed9c0/saunter/matchers.py#L398-L412
def verify_visible(self, locator, msg=None): """ Soft assert for whether and element is present and visible in the current window/frame :params locator: the locator of the element to search for :params msg: (Optional) msg explaining the difference """ try: se...
[ "def", "verify_visible", "(", "self", ",", "locator", ",", "msg", "=", "None", ")", ":", "try", ":", "self", ".", "assert_visible", "(", "locator", ",", "msg", ")", "except", "AssertionError", ",", "e", ":", "if", "msg", ":", "m", "=", "\"%s:\\n%s\"", ...
Soft assert for whether and element is present and visible in the current window/frame :params locator: the locator of the element to search for :params msg: (Optional) msg explaining the difference
[ "Soft", "assert", "for", "whether", "and", "element", "is", "present", "and", "visible", "in", "the", "current", "window", "/", "frame" ]
python
train
sdispater/orator
orator/schema/blueprint.py
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/blueprint.py#L443-L454
def unsigned_integer(self, column, auto_increment=False): """ Create a new unisgned integer column on the table. :param column: The column :type column: str :type auto_increment: bool :rtype: Fluent """ return self.integer(column, auto_increment, True)
[ "def", "unsigned_integer", "(", "self", ",", "column", ",", "auto_increment", "=", "False", ")", ":", "return", "self", ".", "integer", "(", "column", ",", "auto_increment", ",", "True", ")" ]
Create a new unisgned integer column on the table. :param column: The column :type column: str :type auto_increment: bool :rtype: Fluent
[ "Create", "a", "new", "unisgned", "integer", "column", "on", "the", "table", "." ]
python
train
SKA-ScienceDataProcessor/integration-prototype
sip/execution_control/configuration_db/sip_config_db/_events/pubsub.py
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/configuration_db/sip_config_db/_events/pubsub.py#L169-L188
def _get_event_id(object_type: str) -> str: """Return an event key for the event on the object type. This must be a unique event id for the object. Args: object_type (str): Type of object Returns: str, event id """ key = _keys.event_counter(object_type) DB.watch(key, pipe...
[ "def", "_get_event_id", "(", "object_type", ":", "str", ")", "->", "str", ":", "key", "=", "_keys", ".", "event_counter", "(", "object_type", ")", "DB", ".", "watch", "(", "key", ",", "pipeline", "=", "True", ")", "count", "=", "DB", ".", "get_value", ...
Return an event key for the event on the object type. This must be a unique event id for the object. Args: object_type (str): Type of object Returns: str, event id
[ "Return", "an", "event", "key", "for", "the", "event", "on", "the", "object", "type", "." ]
python
train
saltstack/salt
salt/modules/mysql.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1116-L1166
def db_create(name, character_set=None, collate=None, **connection_args): ''' Adds a databases to the MySQL server. name The name of the database to manage character_set The character set, if left empty the MySQL default will be used collate The collation, if left empty th...
[ "def", "db_create", "(", "name", ",", "character_set", "=", "None", ",", "collate", "=", "None", ",", "*", "*", "connection_args", ")", ":", "# check if db exists", "if", "db_exists", "(", "name", ",", "*", "*", "connection_args", ")", ":", "log", ".", "...
Adds a databases to the MySQL server. name The name of the database to manage character_set The character set, if left empty the MySQL default will be used collate The collation, if left empty the MySQL default will be used CLI Example: .. code-block:: bash salt...
[ "Adds", "a", "databases", "to", "the", "MySQL", "server", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/variation/population.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L348-L356
def get_gemini_files(data): """Enumerate available gemini data files in a standard installation. """ try: from gemini import annotations, config except ImportError: return {} return {"base": config.read_gemini_config()["annotation_dir"], "files": annotations.get_anno_file...
[ "def", "get_gemini_files", "(", "data", ")", ":", "try", ":", "from", "gemini", "import", "annotations", ",", "config", "except", "ImportError", ":", "return", "{", "}", "return", "{", "\"base\"", ":", "config", ".", "read_gemini_config", "(", ")", "[", "\...
Enumerate available gemini data files in a standard installation.
[ "Enumerate", "available", "gemini", "data", "files", "in", "a", "standard", "installation", "." ]
python
train
OpenHydrology/floodestimation
floodestimation/analysis.py
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L310-L322
def _qmed_from_area(self): """ Return QMED estimate based on catchment area. TODO: add source of method :return: QMED in m³/s :rtype: float """ try: return 1.172 * self.catchment.descriptors.dtm_area ** self._area_exponent() # Area in km² ex...
[ "def", "_qmed_from_area", "(", "self", ")", ":", "try", ":", "return", "1.172", "*", "self", ".", "catchment", ".", "descriptors", ".", "dtm_area", "**", "self", ".", "_area_exponent", "(", ")", "# Area in km²", "except", "(", "TypeError", ",", "KeyError", ...
Return QMED estimate based on catchment area. TODO: add source of method :return: QMED in m³/s :rtype: float
[ "Return", "QMED", "estimate", "based", "on", "catchment", "area", "." ]
python
train
pteichman/cobe
cobe/brain.py
https://github.com/pteichman/cobe/blob/b0dc2a707035035b9a689105c8f833894fb59eb7/cobe/brain.py#L154-L165
def _to_graph(self, contexts): """This is an iterator that returns each edge of our graph with its two nodes""" prev = None for context in contexts: if prev is None: prev = context continue yield prev[0], context[1], context[0] ...
[ "def", "_to_graph", "(", "self", ",", "contexts", ")", ":", "prev", "=", "None", "for", "context", "in", "contexts", ":", "if", "prev", "is", "None", ":", "prev", "=", "context", "continue", "yield", "prev", "[", "0", "]", ",", "context", "[", "1", ...
This is an iterator that returns each edge of our graph with its two nodes
[ "This", "is", "an", "iterator", "that", "returns", "each", "edge", "of", "our", "graph", "with", "its", "two", "nodes" ]
python
train
joshspeagle/dynesty
dynesty/sampler.py
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampler.py#L761-L861
def run_nested(self, maxiter=None, maxcall=None, dlogz=None, logl_max=np.inf, add_live=True, print_progress=True, print_func=None, save_bounds=True): """ **A wrapper that executes the main nested sampling loop.** Iteratively replace the worst live point with...
[ "def", "run_nested", "(", "self", ",", "maxiter", "=", "None", ",", "maxcall", "=", "None", ",", "dlogz", "=", "None", ",", "logl_max", "=", "np", ".", "inf", ",", "add_live", "=", "True", ",", "print_progress", "=", "True", ",", "print_func", "=", "...
**A wrapper that executes the main nested sampling loop.** Iteratively replace the worst live point with a sample drawn uniformly from the prior until the provided stopping criteria are reached. Parameters ---------- maxiter : int, optional Maximum number of ...
[ "**", "A", "wrapper", "that", "executes", "the", "main", "nested", "sampling", "loop", ".", "**", "Iteratively", "replace", "the", "worst", "live", "point", "with", "a", "sample", "drawn", "uniformly", "from", "the", "prior", "until", "the", "provided", "sto...
python
train
fhamborg/news-please
newsplease/crawler/spiders/recursive_sitemap_crawler.py
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/crawler/spiders/recursive_sitemap_crawler.py#L41-L57
def parse(self, response): """ Checks any given response on being an article and if positiv, passes the response to the pipeline. :param obj response: The scrapy response """ if not self.helper.parse_crawler.content_type(response): return for request...
[ "def", "parse", "(", "self", ",", "response", ")", ":", "if", "not", "self", ".", "helper", ".", "parse_crawler", ".", "content_type", "(", "response", ")", ":", "return", "for", "request", "in", "self", ".", "helper", ".", "parse_crawler", ".", "recursi...
Checks any given response on being an article and if positiv, passes the response to the pipeline. :param obj response: The scrapy response
[ "Checks", "any", "given", "response", "on", "being", "an", "article", "and", "if", "positiv", "passes", "the", "response", "to", "the", "pipeline", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L394-L559
def decode_from_file(estimator, filename, hparams, decode_hp, decode_to_file=None, checkpoint_path=None): """Compute predictions on entries in filename and write them out.""" if not decode_hp.batch_size: dec...
[ "def", "decode_from_file", "(", "estimator", ",", "filename", ",", "hparams", ",", "decode_hp", ",", "decode_to_file", "=", "None", ",", "checkpoint_path", "=", "None", ")", ":", "if", "not", "decode_hp", ".", "batch_size", ":", "decode_hp", ".", "batch_size",...
Compute predictions on entries in filename and write them out.
[ "Compute", "predictions", "on", "entries", "in", "filename", "and", "write", "them", "out", "." ]
python
train
jhuapl-boss/intern
intern/remote/boss/remote.py
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L384-L398
def delete_group_maintainer(self, grp_name, user): """ Delete the given user to the named group. Both group and user must already exist for this to succeed. Args: name (string): Name of group. user (string): User to add to group. Raises: req...
[ "def", "delete_group_maintainer", "(", "self", ",", "grp_name", ",", "user", ")", ":", "self", ".", "project_service", ".", "set_auth", "(", "self", ".", "_token_project", ")", "self", ".", "project_service", ".", "delete_group_maintainer", "(", "grp_name", ",",...
Delete the given user to the named group. Both group and user must already exist for this to succeed. Args: name (string): Name of group. user (string): User to add to group. Raises: requests.HTTPError on failure.
[ "Delete", "the", "given", "user", "to", "the", "named", "group", "." ]
python
train
ethereum/eth-abi
eth_abi/registry.py
https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/registry.py#L270-L279
def is_base_tuple(type_str): """ A predicate that matches a tuple type with no array dimension list. """ try: abi_type = grammar.parse(type_str) except exceptions.ParseError: return False return isinstance(abi_type, grammar.TupleType) and abi_type.arrlist is None
[ "def", "is_base_tuple", "(", "type_str", ")", ":", "try", ":", "abi_type", "=", "grammar", ".", "parse", "(", "type_str", ")", "except", "exceptions", ".", "ParseError", ":", "return", "False", "return", "isinstance", "(", "abi_type", ",", "grammar", ".", ...
A predicate that matches a tuple type with no array dimension list.
[ "A", "predicate", "that", "matches", "a", "tuple", "type", "with", "no", "array", "dimension", "list", "." ]
python
train
BD2KGenomics/toil-lib
src/toil_lib/tools/aligners.py
https://github.com/BD2KGenomics/toil-lib/blob/022a615fc3dc98fc1aaa7bfd232409962ca44fbd/src/toil_lib/tools/aligners.py#L9-L82
def run_star(job, r1_id, r2_id, star_index_url, wiggle=False, sort=True): """ Performs alignment of fastqs to bam via STAR --limitBAMsortRAM step added to deal with memory explosion when sorting certain samples. The value was chosen to complement the recommended amount of memory to have when running ST...
[ "def", "run_star", "(", "job", ",", "r1_id", ",", "r2_id", ",", "star_index_url", ",", "wiggle", "=", "False", ",", "sort", "=", "True", ")", ":", "work_dir", "=", "job", ".", "fileStore", ".", "getLocalTempDir", "(", ")", "download_url", "(", "job", "...
Performs alignment of fastqs to bam via STAR --limitBAMsortRAM step added to deal with memory explosion when sorting certain samples. The value was chosen to complement the recommended amount of memory to have when running STAR (60G) :param JobFunctionWrappingJob job: passed automatically by Toil :par...
[ "Performs", "alignment", "of", "fastqs", "to", "bam", "via", "STAR" ]
python
test
pschmitt/python-opsview
opsview/opsview.py
https://github.com/pschmitt/python-opsview/blob/720acc06c491db32d18c79d20f04cae16e57a7fb/opsview/opsview.py#L142-L148
def user_info(self, verbose=False): ''' Get information about the currently authenticated user http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information ''' url = '{}/{}'.format(self.rest_url, 'user') return self.__auth_req_get(url, verbose=verbose)
[ "def", "user_info", "(", "self", ",", "verbose", "=", "False", ")", ":", "url", "=", "'{}/{}'", ".", "format", "(", "self", ".", "rest_url", ",", "'user'", ")", "return", "self", ".", "__auth_req_get", "(", "url", ",", "verbose", "=", "verbose", ")" ]
Get information about the currently authenticated user http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information
[ "Get", "information", "about", "the", "currently", "authenticated", "user", "http", ":", "//", "docs", ".", "opsview", ".", "com", "/", "doku", ".", "php?id", "=", "opsview4", ".", "6", ":", "restapi#user_information" ]
python
train
jonathf/chaospy
chaospy/distributions/evaluation/bound.py
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/evaluation/bound.py#L32-L75
def evaluate_bound( distribution, x_data, parameters=None, cache=None, ): """ Evaluate lower and upper bounds. Args: distribution (Dist): Distribution to evaluate. x_data (numpy.ndarray): Locations for where evaluate bounds at. Relevan...
[ "def", "evaluate_bound", "(", "distribution", ",", "x_data", ",", "parameters", "=", "None", ",", "cache", "=", "None", ",", ")", ":", "assert", "len", "(", "x_data", ")", "==", "len", "(", "distribution", ")", "assert", "len", "(", "x_data", ".", "sha...
Evaluate lower and upper bounds. Args: distribution (Dist): Distribution to evaluate. x_data (numpy.ndarray): Locations for where evaluate bounds at. Relevant in the case of multivariate distributions where the bounds are affected by the output of oth...
[ "Evaluate", "lower", "and", "upper", "bounds", "." ]
python
train
SALib/SALib
src/SALib/sample/morris/__init__.py
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/__init__.py#L129-L166
def _sample_groups(problem, N, num_levels=4): """Generate trajectories for groups Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories, where :math:`g` is the number of groups and :math:`k` is the number of factors Arguments --------- problem : dict The problem definiti...
[ "def", "_sample_groups", "(", "problem", ",", "N", ",", "num_levels", "=", "4", ")", ":", "if", "len", "(", "problem", "[", "'groups'", "]", ")", "!=", "problem", "[", "'num_vars'", "]", ":", "raise", "ValueError", "(", "\"Groups do not match to number of va...
Generate trajectories for groups Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories, where :math:`g` is the number of groups and :math:`k` is the number of factors Arguments --------- problem : dict The problem definition N : int The number of trajectories to ...
[ "Generate", "trajectories", "for", "groups" ]
python
train
square/pylink
pylink/jlink.py
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3510-L3542
def breakpoint_set(self, addr, thumb=False, arm=False): """Sets a breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. Args: ...
[ "def", "breakpoint_set", "(", "self", ",", "addr", ",", "thumb", "=", "False", ",", "arm", "=", "False", ")", ":", "flags", "=", "enums", ".", "JLinkBreakpoint", ".", "ANY", "if", "thumb", ":", "flags", "=", "flags", "|", "enums", ".", "JLinkBreakpoint...
Sets a breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. Args: self (JLink): the ``JLink`` instance addr (int): t...
[ "Sets", "a", "breakpoint", "at", "the", "specified", "address", "." ]
python
train
lrq3000/pyFileFixity
pyFileFixity/lib/reedsolomon/reedsolo.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/reedsolomon/reedsolo.py#L316-L330
def gf_poly_mul(p, q): '''Multiply two polynomials, inside Galois Field (but the procedure is generic). Optimized function by precomputation of log.''' # Pre-allocate the result array r = bytearray(len(p) + len(q) - 1) # Precompute the logarithm of p lp = [gf_log[p[i]] for i in xrange(len(p))] #...
[ "def", "gf_poly_mul", "(", "p", ",", "q", ")", ":", "# Pre-allocate the result array", "r", "=", "bytearray", "(", "len", "(", "p", ")", "+", "len", "(", "q", ")", "-", "1", ")", "# Precompute the logarithm of p", "lp", "=", "[", "gf_log", "[", "p", "[...
Multiply two polynomials, inside Galois Field (but the procedure is generic). Optimized function by precomputation of log.
[ "Multiply", "two", "polynomials", "inside", "Galois", "Field", "(", "but", "the", "procedure", "is", "generic", ")", ".", "Optimized", "function", "by", "precomputation", "of", "log", "." ]
python
train
fumitoh/modelx
modelx/core/spacecontainer.py
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L94-L121
def import_module(self, module=None, recursive=False, **params): """Create a child space from an module. Args: module: a module object or name of the module object. recursive: Not yet implemented. **params: arguments to pass to ``new_space`` Returns: ...
[ "def", "import_module", "(", "self", ",", "module", "=", "None", ",", "recursive", "=", "False", ",", "*", "*", "params", ")", ":", "if", "module", "is", "None", ":", "if", "\"module_\"", "in", "params", ":", "warnings", ".", "warn", "(", "\"Parameter ...
Create a child space from an module. Args: module: a module object or name of the module object. recursive: Not yet implemented. **params: arguments to pass to ``new_space`` Returns: The new child space created from the module.
[ "Create", "a", "child", "space", "from", "an", "module", "." ]
python
valid
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/table.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L1907-L1922
def _rows_page_start(iterator, page, response): """Grab total rows when :class:`~google.cloud.iterator.Page` starts. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type page: :class:`~google.api_core.page_iterator.Page` :pa...
[ "def", "_rows_page_start", "(", "iterator", ",", "page", ",", "response", ")", ":", "total_rows", "=", "response", ".", "get", "(", "\"totalRows\"", ")", "if", "total_rows", "is", "not", "None", ":", "total_rows", "=", "int", "(", "total_rows", ")", "itera...
Grab total rows when :class:`~google.cloud.iterator.Page` starts. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type page: :class:`~google.api_core.page_iterator.Page` :param page: The page that was just created. :type re...
[ "Grab", "total", "rows", "when", ":", "class", ":", "~google", ".", "cloud", ".", "iterator", ".", "Page", "starts", "." ]
python
train