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
rm-hull/luma.emulator
luma/emulator/render.py
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/render.py#L51-L65
def led_matrix(self, surface): """ Transforms the input surface into an LED matrix (1 pixel = 1 LED) """ scale = self._led_on.get_width() w, h = self._input_size pix = self._pygame.PixelArray(surface) img = self._pygame.Surface((w * scale, h * scale)) for...
[ "def", "led_matrix", "(", "self", ",", "surface", ")", ":", "scale", "=", "self", ".", "_led_on", ".", "get_width", "(", ")", "w", ",", "h", "=", "self", ".", "_input_size", "pix", "=", "self", ".", "_pygame", ".", "PixelArray", "(", "surface", ")", ...
Transforms the input surface into an LED matrix (1 pixel = 1 LED)
[ "Transforms", "the", "input", "surface", "into", "an", "LED", "matrix", "(", "1", "pixel", "=", "1", "LED", ")" ]
python
train
inasafe/inasafe
safe/gui/tools/batch/batch_dialog.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L798-L801
def on_output_directory_chooser_clicked(self): """Auto connect slot activated when tbOutputDiris clicked.""" title = self.tr('Set the output directory for pdf report files') self.choose_directory(self.output_directory, title)
[ "def", "on_output_directory_chooser_clicked", "(", "self", ")", ":", "title", "=", "self", ".", "tr", "(", "'Set the output directory for pdf report files'", ")", "self", ".", "choose_directory", "(", "self", ".", "output_directory", ",", "title", ")" ]
Auto connect slot activated when tbOutputDiris clicked.
[ "Auto", "connect", "slot", "activated", "when", "tbOutputDiris", "clicked", "." ]
python
train
robertpeteuil/multi-cloud-control
mcc/uimode.py
https://github.com/robertpeteuil/multi-cloud-control/blob/f1565af1c0b6ed465ff312d3ccc592ba0609f4a2/mcc/uimode.py#L40-L62
def ui_main(fmt_table, node_dict): """Create the base UI in command mode.""" cmd_funct = {"quit": False, "run": node_cmd, "stop": node_cmd, "connect": node_cmd, "details": node_cmd, "update": True} ui_print("\033[?25l") # ...
[ "def", "ui_main", "(", "fmt_table", ",", "node_dict", ")", ":", "cmd_funct", "=", "{", "\"quit\"", ":", "False", ",", "\"run\"", ":", "node_cmd", ",", "\"stop\"", ":", "node_cmd", ",", "\"connect\"", ":", "node_cmd", ",", "\"details\"", ":", "node_cmd", ",...
Create the base UI in command mode.
[ "Create", "the", "base", "UI", "in", "command", "mode", "." ]
python
train
proycon/pynlpl
pynlpl/formats/folia.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L5783-L5798
def correctwords(self, originalwords, newwords, **kwargs): """Generic correction method for words. You most likely want to use the helper functions :meth:`Sentence.splitword` , :meth:`Sentence.mergewords`, :meth:`deleteword`, :meth:`insertword` instead""" for w in originalwords: i...
[ "def", "correctwords", "(", "self", ",", "originalwords", ",", "newwords", ",", "*", "*", "kwargs", ")", ":", "for", "w", "in", "originalwords", ":", "if", "not", "isinstance", "(", "w", ",", "Word", ")", ":", "raise", "Exception", "(", "\"Original word ...
Generic correction method for words. You most likely want to use the helper functions :meth:`Sentence.splitword` , :meth:`Sentence.mergewords`, :meth:`deleteword`, :meth:`insertword` instead
[ "Generic", "correction", "method", "for", "words", ".", "You", "most", "likely", "want", "to", "use", "the", "helper", "functions", ":", "meth", ":", "Sentence", ".", "splitword", ":", "meth", ":", "Sentence", ".", "mergewords", ":", "meth", ":", "deletewo...
python
train
pypyr/pypyr-cli
pypyr/steps/env.py
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/env.py#L46-L85
def env_get(context): """Get $ENVs into the pypyr context. Context is a dictionary or dictionary-like. context is mandatory. context['env']['get'] must exist. It's a dictionary. Values are the names of the $ENVs to write to the pypyr context. Keys are the pypyr context item to which to write the $...
[ "def", "env_get", "(", "context", ")", ":", "get", "=", "context", "[", "'env'", "]", ".", "get", "(", "'get'", ",", "None", ")", "exists", "=", "False", "if", "get", ":", "logger", ".", "debug", "(", "\"start\"", ")", "for", "k", ",", "v", "in",...
Get $ENVs into the pypyr context. Context is a dictionary or dictionary-like. context is mandatory. context['env']['get'] must exist. It's a dictionary. Values are the names of the $ENVs to write to the pypyr context. Keys are the pypyr context item to which to write the $ENV values. For example,...
[ "Get", "$ENVs", "into", "the", "pypyr", "context", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py#L1147-L1178
def install(self, install_options, global_options=()): """Install everything in this set (after having downloaded and unpacked the packages)""" to_install = [r for r in self.requirements.values() if not r.satisfied_by] if to_install: logger.notify('Installing c...
[ "def", "install", "(", "self", ",", "install_options", ",", "global_options", "=", "(", ")", ")", ":", "to_install", "=", "[", "r", "for", "r", "in", "self", ".", "requirements", ".", "values", "(", ")", "if", "not", "r", ".", "satisfied_by", "]", "i...
Install everything in this set (after having downloaded and unpacked the packages)
[ "Install", "everything", "in", "this", "set", "(", "after", "having", "downloaded", "and", "unpacked", "the", "packages", ")" ]
python
test
ligyxy/DictMySQL
dictmysql.py
https://github.com/ligyxy/DictMySQL/blob/f40d649193ccf58d1c7933189be1042b37afbe31/dictmysql.py#L49-L68
def _backtick_columns(cols): """ Quote the column names """ def bt(s): b = '' if s == '*' or not s else '`' return [_ for _ in [b + (s or '') + b] if _] formatted = [] for c in cols: if c[0] == '#': formatted.append(c[1...
[ "def", "_backtick_columns", "(", "cols", ")", ":", "def", "bt", "(", "s", ")", ":", "b", "=", "''", "if", "s", "==", "'*'", "or", "not", "s", "else", "'`'", "return", "[", "_", "for", "_", "in", "[", "b", "+", "(", "s", "or", "''", ")", "+"...
Quote the column names
[ "Quote", "the", "column", "names" ]
python
train
knipknap/SpiffWorkflow
SpiffWorkflow/util/event.py
https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/util/event.py#L161-L201
def emit(self, *args, **kwargs): """ Emits the signal, passing the given arguments to the callbacks. If one of the callbacks returns a value other than None, no further callbacks are invoked and the return value of the callback is returned to the caller of emit(). :type ...
[ "def", "emit", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "hard_subscribers", "is", "not", "None", ":", "for", "callback", ",", "user_args", ",", "user_kwargs", "in", "self", ".", "hard_subscribers", ":", "kwar...
Emits the signal, passing the given arguments to the callbacks. If one of the callbacks returns a value other than None, no further callbacks are invoked and the return value of the callback is returned to the caller of emit(). :type args: tuple :param args: Optional arguments ...
[ "Emits", "the", "signal", "passing", "the", "given", "arguments", "to", "the", "callbacks", ".", "If", "one", "of", "the", "callbacks", "returns", "a", "value", "other", "than", "None", "no", "further", "callbacks", "are", "invoked", "and", "the", "return", ...
python
valid
ungarj/mapchete
mapchete/formats/base.py
https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/base.py#L318-L336
def output_is_valid(self, process_data): """ Check whether process output is allowed with output driver. Parameters ---------- process_data : raw process output Returns ------- True or False """ if self.METADATA["data_type"] == "raster": ...
[ "def", "output_is_valid", "(", "self", ",", "process_data", ")", ":", "if", "self", ".", "METADATA", "[", "\"data_type\"", "]", "==", "\"raster\"", ":", "return", "(", "is_numpy_or_masked_array", "(", "process_data", ")", "or", "is_numpy_or_masked_array_with_tags", ...
Check whether process output is allowed with output driver. Parameters ---------- process_data : raw process output Returns ------- True or False
[ "Check", "whether", "process", "output", "is", "allowed", "with", "output", "driver", "." ]
python
valid
kajala/django-jutil
jutil/request.py
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/request.py#L8-L36
def get_geo_ip(ip: str, exceptions: bool=False, timeout: int=10) -> dict: """ Returns geo IP info or empty dict if geoip query fails at http://ipstack.com. requires settings.IPSTACK_TOKEN set as valid access token to the API. Example replies: {'country_name': 'United States', 'country_code': 'US', ...
[ "def", "get_geo_ip", "(", "ip", ":", "str", ",", "exceptions", ":", "bool", "=", "False", ",", "timeout", ":", "int", "=", "10", ")", "->", "dict", ":", "import", "requests", "import", "traceback", "try", ":", "res", "=", "requests", ".", "get", "(",...
Returns geo IP info or empty dict if geoip query fails at http://ipstack.com. requires settings.IPSTACK_TOKEN set as valid access token to the API. Example replies: {'country_name': 'United States', 'country_code': 'US', 'region_code': 'TX', 'region_name': 'Texas', 'ip': '76.184.236.184', 'latitude': 33.15...
[ "Returns", "geo", "IP", "info", "or", "empty", "dict", "if", "geoip", "query", "fails", "at", "http", ":", "//", "ipstack", ".", "com", ".", "requires", "settings", ".", "IPSTACK_TOKEN", "set", "as", "valid", "access", "token", "to", "the", "API", "." ]
python
train
numenta/nupic
src/nupic/data/generators/data_generator.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L59-L67
def setSeed(self, seed): """Set the random seed and the numpy seed Parameters: -------------------------------------------------------------------- seed: random seed """ rand.seed(seed) np.random.seed(seed)
[ "def", "setSeed", "(", "self", ",", "seed", ")", ":", "rand", ".", "seed", "(", "seed", ")", "np", ".", "random", ".", "seed", "(", "seed", ")" ]
Set the random seed and the numpy seed Parameters: -------------------------------------------------------------------- seed: random seed
[ "Set", "the", "random", "seed", "and", "the", "numpy", "seed", "Parameters", ":", "--------------------------------------------------------------------", "seed", ":", "random", "seed" ]
python
valid
ensime/ensime-vim
ensime_shared/client.py
https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L433-L436
def doc_uri(self, args, range=None): """Request doc of whatever at cursor.""" self.log.debug('doc_uri: in') self.send_at_position("DocUri", False, "point")
[ "def", "doc_uri", "(", "self", ",", "args", ",", "range", "=", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "'doc_uri: in'", ")", "self", ".", "send_at_position", "(", "\"DocUri\"", ",", "False", ",", "\"point\"", ")" ]
Request doc of whatever at cursor.
[ "Request", "doc", "of", "whatever", "at", "cursor", "." ]
python
train
jtwhite79/pyemu
pyemu/utils/helpers.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/helpers.py#L1832-L1842
def setup_hfb_pars(self): """setup non-mult parameters for hfb (yuck!) """ if self.m.hfb6 is None: self.logger.lraise("couldn't find hfb pak") tpl_file,df = pyemu.gw_utils.write_hfb_template(self.m) self.in_files.append(os.path.split(tpl_file.replace(".tpl",""))[-1]...
[ "def", "setup_hfb_pars", "(", "self", ")", ":", "if", "self", ".", "m", ".", "hfb6", "is", "None", ":", "self", ".", "logger", ".", "lraise", "(", "\"couldn't find hfb pak\"", ")", "tpl_file", ",", "df", "=", "pyemu", ".", "gw_utils", ".", "write_hfb_tem...
setup non-mult parameters for hfb (yuck!)
[ "setup", "non", "-", "mult", "parameters", "for", "hfb", "(", "yuck!", ")" ]
python
train
scivision/lowtran
lowtran/scenarios.py
https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/scenarios.py#L50-L85
def horizrad(infn: Path, outfn: Path, c1: dict) -> xarray.Dataset: """ read CSV, simulate, write, plot """ if infn is not None: infn = Path(infn).expanduser() if infn.suffix == '.h5': TR = xarray.open_dataset(infn) return TR c1.update({'model': 0, # 0: user...
[ "def", "horizrad", "(", "infn", ":", "Path", ",", "outfn", ":", "Path", ",", "c1", ":", "dict", ")", "->", "xarray", ".", "Dataset", ":", "if", "infn", "is", "not", "None", ":", "infn", "=", "Path", "(", "infn", ")", ".", "expanduser", "(", ")", ...
read CSV, simulate, write, plot
[ "read", "CSV", "simulate", "write", "plot" ]
python
train
wavefrontHQ/python-client
wavefront_api_client/api/dashboard_api.py
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/dashboard_api.py#L1003-L1024
def get_dashboard_version(self, id, version, **kwargs): # noqa: E501 """Get a specific version of a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thre...
[ "def", "get_dashboard_version", "(", "self", ",", "id", ",", "version", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "sel...
Get a specific version of a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_dashboard_version(id, version, async_req=True) >>> result = ...
[ "Get", "a", "specific", "version", "of", "a", "specific", "dashboard", "#", "noqa", ":", "E501" ]
python
train
luckydonald/pytgbot
pytgbot/api_types/receivable/updates.py
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L149-L176
def to_array(self): """ Serializes this Update to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Update, self).to_array() array['update_id'] = int(self.update_id) # type int if self.message is not None: ...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "Update", ",", "self", ")", ".", "to_array", "(", ")", "array", "[", "'update_id'", "]", "=", "int", "(", "self", ".", "update_id", ")", "# type int", "if", "self", ".", "message",...
Serializes this Update to a dictionary. :return: dictionary representation of this object. :rtype: dict
[ "Serializes", "this", "Update", "to", "a", "dictionary", "." ]
python
train
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/mmax2.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/mmax2.py#L270-L338
def add_annotation_layer(self, annotation_file, layer_name): """ adds all markables from the given annotation layer to the discourse graph. """ assert os.path.isfile(annotation_file), \ "Annotation file doesn't exist: {}".format(annotation_file) tree = etree.p...
[ "def", "add_annotation_layer", "(", "self", ",", "annotation_file", ",", "layer_name", ")", ":", "assert", "os", ".", "path", ".", "isfile", "(", "annotation_file", ")", ",", "\"Annotation file doesn't exist: {}\"", ".", "format", "(", "annotation_file", ")", "tre...
adds all markables from the given annotation layer to the discourse graph.
[ "adds", "all", "markables", "from", "the", "given", "annotation", "layer", "to", "the", "discourse", "graph", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L140-L152
def log_params(params, name="params"): """Dumps the params with `logging.error`.""" for i, param in enumerate(params): if not param: # Empty tuple. continue if not isinstance(param, (list, tuple)): logging.error( "%s[%d] : (%s) = [%s]", name, i, param.shape, onp.array(param)) ...
[ "def", "log_params", "(", "params", ",", "name", "=", "\"params\"", ")", ":", "for", "i", ",", "param", "in", "enumerate", "(", "params", ")", ":", "if", "not", "param", ":", "# Empty tuple.", "continue", "if", "not", "isinstance", "(", "param", ",", "...
Dumps the params with `logging.error`.
[ "Dumps", "the", "params", "with", "logging", ".", "error", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py#L513-L527
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_time_since_last_change(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interf...
[ "def", "fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_time_since_last_change", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "fcoe_get_interface", "=", "ET", ".", "Element", "(", "\"fcoe_get_interface...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
base4sistemas/satcomum
satcomum/br.py
https://github.com/base4sistemas/satcomum/blob/b42bec06cb0fb0ad2f6b1a2644a1e8fc8403f2c3/satcomum/br.py#L252-L271
def is_cnpjcpf(numero, estrito=False): """Uma versão conveniente para usar em testes condicionais. Apenas retorna verdadeiro ou falso, conforme o argumento é validado. :param bool estrito: Padrão ``False``, indica se apenas os dígitos do número deverão ser considerados. Se verdadeiro, potenciais ca...
[ "def", "is_cnpjcpf", "(", "numero", ",", "estrito", "=", "False", ")", ":", "_numero", "=", "digitos", "(", "numero", ")", "if", "not", "estrito", "else", "numero", "try", ":", "cnpj", "(", "_numero", ")", "return", "True", "except", "NumeroCNPJError", "...
Uma versão conveniente para usar em testes condicionais. Apenas retorna verdadeiro ou falso, conforme o argumento é validado. :param bool estrito: Padrão ``False``, indica se apenas os dígitos do número deverão ser considerados. Se verdadeiro, potenciais caracteres que formam a máscara serão re...
[ "Uma", "versão", "conveniente", "para", "usar", "em", "testes", "condicionais", ".", "Apenas", "retorna", "verdadeiro", "ou", "falso", "conforme", "o", "argumento", "é", "validado", "." ]
python
train
hubo1016/vlcp
vlcp/event/future.py
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/future.py#L89-L98
def set_result(self, result): ''' Set the result to Future object, wake up all the waiters :param result: result to set ''' if hasattr(self, '_result'): raise ValueError('Cannot set the result twice') self._result = result self._scheduler.emer...
[ "def", "set_result", "(", "self", ",", "result", ")", ":", "if", "hasattr", "(", "self", ",", "'_result'", ")", ":", "raise", "ValueError", "(", "'Cannot set the result twice'", ")", "self", ".", "_result", "=", "result", "self", ".", "_scheduler", ".", "e...
Set the result to Future object, wake up all the waiters :param result: result to set
[ "Set", "the", "result", "to", "Future", "object", "wake", "up", "all", "the", "waiters", ":", "param", "result", ":", "result", "to", "set" ]
python
train
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3432-L3445
def should_generate_summaries(): """Is this an appropriate context to generate summaries. Returns: a boolean """ name_scope = tf.contrib.framework.get_name_scope() if name_scope and "while/" in name_scope: # Summaries don't work well within tf.while_loop() return False if tf.get_variable_scope(...
[ "def", "should_generate_summaries", "(", ")", ":", "name_scope", "=", "tf", ".", "contrib", ".", "framework", ".", "get_name_scope", "(", ")", "if", "name_scope", "and", "\"while/\"", "in", "name_scope", ":", "# Summaries don't work well within tf.while_loop()", "retu...
Is this an appropriate context to generate summaries. Returns: a boolean
[ "Is", "this", "an", "appropriate", "context", "to", "generate", "summaries", "." ]
python
train
scheibler/khard
khard/actions.py
https://github.com/scheibler/khard/blob/0f69430c2680f1ff5f073a977a3c5b753b96cc17/khard/actions.py#L30-L43
def get_action(cls, alias): """Find the name of the action for the supplied alias. If no action is asociated with the given alias, None is returned. :param alias: the alias to look up :type alias: str :rturns: the name of the corresponding action or None :rtype: str or ...
[ "def", "get_action", "(", "cls", ",", "alias", ")", ":", "for", "action", ",", "alias_list", "in", "cls", ".", "action_map", ".", "items", "(", ")", ":", "if", "alias", "in", "alias_list", ":", "return", "action", "return", "None" ]
Find the name of the action for the supplied alias. If no action is asociated with the given alias, None is returned. :param alias: the alias to look up :type alias: str :rturns: the name of the corresponding action or None :rtype: str or NoneType
[ "Find", "the", "name", "of", "the", "action", "for", "the", "supplied", "alias", ".", "If", "no", "action", "is", "asociated", "with", "the", "given", "alias", "None", "is", "returned", "." ]
python
test
robinandeer/puzzle
puzzle/plugins/gemini/mixins/case.py
https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/gemini/mixins/case.py#L48-L68
def case(self, case_id=None): """Return a Case object If no case_id is given return one case Args: case_id (str): A case id Returns: case(Case): A Case object """ cases = self.cases() if case_id: for case ...
[ "def", "case", "(", "self", ",", "case_id", "=", "None", ")", ":", "cases", "=", "self", ".", "cases", "(", ")", "if", "case_id", ":", "for", "case", "in", "cases", ":", "if", "case", ".", "case_id", "==", "case_id", ":", "return", "case", "else", ...
Return a Case object If no case_id is given return one case Args: case_id (str): A case id Returns: case(Case): A Case object
[ "Return", "a", "Case", "object" ]
python
train
TUNE-Archive/freight_forwarder
freight_forwarder/container/config.py
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/config.py#L329-L340
def hostname(self, hostname): """ hostname setter """ if not isinstance(hostname, six.string_types): raise TypeError("hostname must be a string. {0} was passed.".format(type(hostname))) # if a host name is passed and its not valid raise else set hostname empty strings are ...
[ "def", "hostname", "(", "self", ",", "hostname", ")", ":", "if", "not", "isinstance", "(", "hostname", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "\"hostname must be a string. {0} was passed.\"", ".", "format", "(", "type", "(", "ho...
hostname setter
[ "hostname", "setter" ]
python
train
cloud-custodian/cloud-custodian
tools/c7n_traildb/c7n_traildb/trailes.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_traildb/c7n_traildb/trailes.py#L105-L114
def fetch_events(cursor, config, account_name): """Generator that returns the events""" query = config['indexer'].get('query', 'select * from events where user_agent glob \'*CloudCustodian*\'') for event in cursor.execute(query): event['account'] = account_name event['_index'] = con...
[ "def", "fetch_events", "(", "cursor", ",", "config", ",", "account_name", ")", ":", "query", "=", "config", "[", "'indexer'", "]", ".", "get", "(", "'query'", ",", "'select * from events where user_agent glob \\'*CloudCustodian*\\''", ")", "for", "event", "in", "c...
Generator that returns the events
[ "Generator", "that", "returns", "the", "events" ]
python
train
watson-developer-cloud/python-sdk
ibm_watson/compare_comply_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/compare_comply_v1.py#L1225-L1276
def _from_dict(cls, _dict): """Initialize a BodyCells object from a json dictionary.""" args = {} if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' ...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'cell_id'", "in", "_dict", ":", "args", "[", "'cell_id'", "]", "=", "_dict", ".", "get", "(", "'cell_id'", ")", "if", "'location'", "in", "_dict", ":", "args", "...
Initialize a BodyCells object from a json dictionary.
[ "Initialize", "a", "BodyCells", "object", "from", "a", "json", "dictionary", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L927-L1037
def universal_transformer_with_lstm_as_transition_function( layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer which uses a lstm as transition function. It's kind of like having a lstm, filliped vertically next to the Universal Transformer that controls the flo...
[ "def", "universal_transformer_with_lstm_as_transition_function", "(", "layer_inputs", ",", "step", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", "=", "None", ")", ":", "state", ",", "unused_inputs", ",", "memory", "=", "tf", ".", "uns...
Universal Transformer which uses a lstm as transition function. It's kind of like having a lstm, filliped vertically next to the Universal Transformer that controls the flow of the information in depth, over different steps of the Universal Transformer. Args: layer_inputs: - state: state - in...
[ "Universal", "Transformer", "which", "uses", "a", "lstm", "as", "transition", "function", "." ]
python
train
ultrabug/py3status
py3status/parse_config.py
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L460-L475
def separator(self, separator=",", end_token=None): """ Read through tokens till the required separator is found. We ignore newlines. If an end token is supplied raise a ParseEnd exception if it is found. """ while True: token = self.next() t_val...
[ "def", "separator", "(", "self", ",", "separator", "=", "\",\"", ",", "end_token", "=", "None", ")", ":", "while", "True", ":", "token", "=", "self", ".", "next", "(", ")", "t_value", "=", "token", "[", "\"value\"", "]", "if", "end_token", "and", "t_...
Read through tokens till the required separator is found. We ignore newlines. If an end token is supplied raise a ParseEnd exception if it is found.
[ "Read", "through", "tokens", "till", "the", "required", "separator", "is", "found", ".", "We", "ignore", "newlines", ".", "If", "an", "end", "token", "is", "supplied", "raise", "a", "ParseEnd", "exception", "if", "it", "is", "found", "." ]
python
train
jmatt/threepio
threepio/__init__.py
https://github.com/jmatt/threepio/blob/91e2835c85c1618fcc4a1357dbb398353e662d1a/threepio/__init__.py#L32-L93
def initialize(logger_name=LOGGER_NAME, log_filename=LOG_FILENAME, app_logging_level=APP_LOGGING_LEVEL, dep_logging_level=DEP_LOGGING_LEVEL, format=None, logger_class=None, handlers=[], global_logger=True): """ ...
[ "def", "initialize", "(", "logger_name", "=", "LOGGER_NAME", ",", "log_filename", "=", "LOG_FILENAME", ",", "app_logging_level", "=", "APP_LOGGING_LEVEL", ",", "dep_logging_level", "=", "DEP_LOGGING_LEVEL", ",", "format", "=", "None", ",", "logger_class", "=", "None...
Constructs and initializes a `logging.Logger` object. Returns :class:`logging.Logger` object. :param logger_name: name of the new logger. :param log_filename: The log file location :class:`str` or None. :param app_logging_level: The logging level to use for the application. :param dep_logging_leve...
[ "Constructs", "and", "initializes", "a", "logging", ".", "Logger", "object", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/__init__.py#L10317-L10340
def _set_preprovision(self, v, load=False): """ Setter method for preprovision, mapped from YANG variable /preprovision (container) If this variable is read-only (config: false) in the source YANG file, then _set_preprovision is considered as a private method. Backends looking to populate this varia...
[ "def", "_set_preprovision", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "b...
Setter method for preprovision, mapped from YANG variable /preprovision (container) If this variable is read-only (config: false) in the source YANG file, then _set_preprovision is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_preprovisi...
[ "Setter", "method", "for", "preprovision", "mapped", "from", "YANG", "variable", "/", "preprovision", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", "file", "then...
python
train
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAMarket/QATTSBroker.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QATTSBroker.py#L255-L292
def send_order(self, code, price, amount, towards, order_model, market=None): """下单 Arguments: code {[type]} -- [description] price {[type]} -- [description] amount {[type]} -- [description] towards {[type]} -- [description] order_model {[typ...
[ "def", "send_order", "(", "self", ",", "code", ",", "price", ",", "amount", ",", "towards", ",", "order_model", ",", "market", "=", "None", ")", ":", "towards", "=", "0", "if", "towards", "==", "ORDER_DIRECTION", ".", "BUY", "else", "1", "if", "order_m...
下单 Arguments: code {[type]} -- [description] price {[type]} -- [description] amount {[type]} -- [description] towards {[type]} -- [description] order_model {[type]} -- [description] market:市场,SZ 深交所,SH 上交所 Returns: [ty...
[ "下单" ]
python
train
mrstephenneal/dirutility
dirutility/compare.py
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/compare.py#L6-L13
def unique(list1, list2): """ Get unique items in list1 that are not in list2 :return: Unique items only in list 1 """ set2 = set(list2) list1_unique = [x for x in tqdm(list1, desc='Unique', total=len(list1)) if x not in set2] return list1_unique
[ "def", "unique", "(", "list1", ",", "list2", ")", ":", "set2", "=", "set", "(", "list2", ")", "list1_unique", "=", "[", "x", "for", "x", "in", "tqdm", "(", "list1", ",", "desc", "=", "'Unique'", ",", "total", "=", "len", "(", "list1", ")", ")", ...
Get unique items in list1 that are not in list2 :return: Unique items only in list 1
[ "Get", "unique", "items", "in", "list1", "that", "are", "not", "in", "list2", ":", "return", ":", "Unique", "items", "only", "in", "list", "1" ]
python
train
sods/ods
pods/datasets.py
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L373-L413
def to_arff(dataset, **kwargs): """Take a pods data set and write it as an ARFF file""" pods_data = dataset(**kwargs) vals = list(kwargs.values()) for i, v in enumerate(vals): if isinstance(v, list): vals[i] = '|'.join(v) else: vals[i] = str(v) args = '_'.join...
[ "def", "to_arff", "(", "dataset", ",", "*", "*", "kwargs", ")", ":", "pods_data", "=", "dataset", "(", "*", "*", "kwargs", ")", "vals", "=", "list", "(", "kwargs", ".", "values", "(", ")", ")", "for", "i", ",", "v", "in", "enumerate", "(", "vals"...
Take a pods data set and write it as an ARFF file
[ "Take", "a", "pods", "data", "set", "and", "write", "it", "as", "an", "ARFF", "file" ]
python
train
openthread/openthread
tools/harness-thci/OpenThread.py
https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-thci/OpenThread.py#L362-L376
def __setAddressfilterMode(self, mode): """set address filter mode Returns: True: successful to set address filter mode. False: fail to set address filter mode. """ print 'call setAddressFilterMode() ' + mode try: cmd = 'macfilter addr ' + mo...
[ "def", "__setAddressfilterMode", "(", "self", ",", "mode", ")", ":", "print", "'call setAddressFilterMode() '", "+", "mode", "try", ":", "cmd", "=", "'macfilter addr '", "+", "mode", "if", "self", ".", "__sendCommand", "(", "cmd", ")", "[", "0", "]", "==", ...
set address filter mode Returns: True: successful to set address filter mode. False: fail to set address filter mode.
[ "set", "address", "filter", "mode" ]
python
train
OLC-Bioinformatics/sipprverse
cgecore/utility.py
https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/cgecore/utility.py#L471-L484
def file_unzipper(directory): """ This function will unzip all files in the runroot directory and subdirectories """ debug.log("Unzipping directory (%s)..."%directory) #FINDING AND UNZIPPING ZIPPED FILES for root, dirs, files in os.walk(directory, topdown=False): if root != "": orig_dir...
[ "def", "file_unzipper", "(", "directory", ")", ":", "debug", ".", "log", "(", "\"Unzipping directory (%s)...\"", "%", "directory", ")", "#FINDING AND UNZIPPING ZIPPED FILES", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "directory", ",...
This function will unzip all files in the runroot directory and subdirectories
[ "This", "function", "will", "unzip", "all", "files", "in", "the", "runroot", "directory", "and", "subdirectories" ]
python
train
rigetti/quantumflow
quantumflow/visualization.py
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L47-L216
def circuit_to_latex(circ: Circuit, qubits: Qubits = None, document: bool = True) -> str: """ Create an image of a quantum circuit in LaTeX. Can currently draw X, Y, Z, H, T, S, T_H, S_H, RX, RY, RZ, TX, TY, TZ, TH, CNOT, CZ, SWAP, ISWAP, CCNOT, CSWAP, XX, YY, ...
[ "def", "circuit_to_latex", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", "=", "None", ",", "document", ":", "bool", "=", "True", ")", "->", "str", ":", "if", "qubits", "is", "None", ":", "qubits", "=", "circ", ".", "qubits", "N", "=", ...
Create an image of a quantum circuit in LaTeX. Can currently draw X, Y, Z, H, T, S, T_H, S_H, RX, RY, RZ, TX, TY, TZ, TH, CNOT, CZ, SWAP, ISWAP, CCNOT, CSWAP, XX, YY, ZZ, CAN, P0 and P1 gates, and the RESET operation. Args: circ: A quantum Circuit qubits: Optional qubit list ...
[ "Create", "an", "image", "of", "a", "quantum", "circuit", "in", "LaTeX", "." ]
python
train
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L703-L728
def file_contents_safe(self, sentry_unit, file_name, max_wait=60, fatal=False): """Get file contents from a sentry unit. Wrap amulet file_contents with retry logic to address races where a file checks as existing, but no longer exists by the time file_contents is call...
[ "def", "file_contents_safe", "(", "self", ",", "sentry_unit", ",", "file_name", ",", "max_wait", "=", "60", ",", "fatal", "=", "False", ")", ":", "unit_name", "=", "sentry_unit", ".", "info", "[", "'unit_name'", "]", "file_contents", "=", "False", "tries", ...
Get file contents from a sentry unit. Wrap amulet file_contents with retry logic to address races where a file checks as existing, but no longer exists by the time file_contents is called. Return None if file not found. Optionally raise if fatal is True.
[ "Get", "file", "contents", "from", "a", "sentry", "unit", ".", "Wrap", "amulet", "file_contents", "with", "retry", "logic", "to", "address", "races", "where", "a", "file", "checks", "as", "existing", "but", "no", "longer", "exists", "by", "the", "time", "f...
python
train
FactoryBoy/factory_boy
factory/django.py
https://github.com/FactoryBoy/factory_boy/blob/edaa7c7f5a14065b229927903bd7989cc93cd069/factory/django.py#L54-L66
def _lazy_load_get_model(): """Lazy loading of get_model. get_model loads django.conf.settings, which may fail if the settings haven't been configured yet. """ if django is None: def _get_model(app, model): raise import_failure else: from django import apps as django...
[ "def", "_lazy_load_get_model", "(", ")", ":", "if", "django", "is", "None", ":", "def", "_get_model", "(", "app", ",", "model", ")", ":", "raise", "import_failure", "else", ":", "from", "django", "import", "apps", "as", "django_apps", "_get_model", "=", "d...
Lazy loading of get_model. get_model loads django.conf.settings, which may fail if the settings haven't been configured yet.
[ "Lazy", "loading", "of", "get_model", "." ]
python
train
carta/ldap_tools
src/ldap_tools/key.py
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/key.py#L66-L75
def install(self): # pragma: no cover """Install/download ssh keys from LDAP for consumption by SSH.""" keys = self.get_keys_from_ldap() for user, ssh_keys in keys.items(): user_dir = API.__authorized_keys_path(user) if not os.path.isdir(user_dir): os.mak...
[ "def", "install", "(", "self", ")", ":", "# pragma: no cover", "keys", "=", "self", ".", "get_keys_from_ldap", "(", ")", "for", "user", ",", "ssh_keys", "in", "keys", ".", "items", "(", ")", ":", "user_dir", "=", "API", ".", "__authorized_keys_path", "(", ...
Install/download ssh keys from LDAP for consumption by SSH.
[ "Install", "/", "download", "ssh", "keys", "from", "LDAP", "for", "consumption", "by", "SSH", "." ]
python
train
pip-services3-python/pip-services3-components-python
pip_services3_components/build/Factory.py
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/build/Factory.py#L37-L50
def register(self, locator, factory): """ Registers a component using a factory method. :param locator: a locator to identify component to be created. :param factory: a factory function that receives a locator and returns a created component. """ if locator == None: ...
[ "def", "register", "(", "self", ",", "locator", ",", "factory", ")", ":", "if", "locator", "==", "None", ":", "raise", "Exception", "(", "\"Locator cannot be null\"", ")", "if", "factory", "==", "None", ":", "raise", "Exception", "(", "\"Factory cannot be null...
Registers a component using a factory method. :param locator: a locator to identify component to be created. :param factory: a factory function that receives a locator and returns a created component.
[ "Registers", "a", "component", "using", "a", "factory", "method", "." ]
python
train
lowandrew/OLCTools
metagenomefilter/automateCLARK.py
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/metagenomefilter/automateCLARK.py#L62-L78
def clean_sequences(self): """Removes reads/contigs that contain plasmids, and masks phage sequences.""" logging.info('Removing plasmids and masking phages') plasmid_db = os.path.join(self.reffilepath, 'plasmidfinder', 'plasmid_database.fa') phage_db = os.path.join(self.reffilepath, 'pro...
[ "def", "clean_sequences", "(", "self", ")", ":", "logging", ".", "info", "(", "'Removing plasmids and masking phages'", ")", "plasmid_db", "=", "os", ".", "path", ".", "join", "(", "self", ".", "reffilepath", ",", "'plasmidfinder'", ",", "'plasmid_database.fa'", ...
Removes reads/contigs that contain plasmids, and masks phage sequences.
[ "Removes", "reads", "/", "contigs", "that", "contain", "plasmids", "and", "masks", "phage", "sequences", "." ]
python
train
codelv/enaml-native
src/enamlnative/widgets/web_view.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/widgets/web_view.py#L105-L115
def _update_proxy(self, change): """ An observer which sends the state change to the proxy. """ if change['type'] == 'event': name = 'do_'+change['name'] if hasattr(self.proxy, name): handler = getattr(self.proxy, name) handler() e...
[ "def", "_update_proxy", "(", "self", ",", "change", ")", ":", "if", "change", "[", "'type'", "]", "==", "'event'", ":", "name", "=", "'do_'", "+", "change", "[", "'name'", "]", "if", "hasattr", "(", "self", ".", "proxy", ",", "name", ")", ":", "han...
An observer which sends the state change to the proxy.
[ "An", "observer", "which", "sends", "the", "state", "change", "to", "the", "proxy", "." ]
python
train
tyarkoni/pliers
pliers/graph.py
https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L237-L298
def draw(self, filename, color=True): ''' Render a plot of the graph via pygraphviz. Args: filename (str): Path to save the generated image to. color (bool): If True, will color graph nodes based on their type, otherwise will draw a black-and-white graph. ...
[ "def", "draw", "(", "self", ",", "filename", ",", "color", "=", "True", ")", ":", "verify_dependencies", "(", "[", "'pgv'", "]", ")", "if", "not", "hasattr", "(", "self", ",", "'_results'", ")", ":", "raise", "RuntimeError", "(", "\"Graph cannot be drawn b...
Render a plot of the graph via pygraphviz. Args: filename (str): Path to save the generated image to. color (bool): If True, will color graph nodes based on their type, otherwise will draw a black-and-white graph.
[ "Render", "a", "plot", "of", "the", "graph", "via", "pygraphviz", "." ]
python
train
ForensicArtifacts/artifacts
tools/stats.py
https://github.com/ForensicArtifacts/artifacts/blob/044a63bfb4448af33d085c69066c80f9505ae7ca/tools/stats.py#L81-L112
def BuildStats(self): """Builds the statistics.""" artifact_reader = reader.YamlArtifactsReader() self.label_counts = {} self.os_counts = {} self.path_count = 0 self.reg_key_count = 0 self.source_type_counts = {} self.total_count = 0 for artifact_definition in artifact_reader.ReadDi...
[ "def", "BuildStats", "(", "self", ")", ":", "artifact_reader", "=", "reader", ".", "YamlArtifactsReader", "(", ")", "self", ".", "label_counts", "=", "{", "}", "self", ".", "os_counts", "=", "{", "}", "self", ".", "path_count", "=", "0", "self", ".", "...
Builds the statistics.
[ "Builds", "the", "statistics", "." ]
python
train
pypa/pipenv
pipenv/vendor/pathlib2/__init__.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1138-L1161
def match(self, path_pattern): """ Return True if this path matches the given pattern. """ cf = self._flavour.casefold path_pattern = cf(path_pattern) drv, root, pat_parts = self._flavour.parse_parts((path_pattern,)) if not pat_parts: raise ValueError(...
[ "def", "match", "(", "self", ",", "path_pattern", ")", ":", "cf", "=", "self", ".", "_flavour", ".", "casefold", "path_pattern", "=", "cf", "(", "path_pattern", ")", "drv", ",", "root", ",", "pat_parts", "=", "self", ".", "_flavour", ".", "parse_parts", ...
Return True if this path matches the given pattern.
[ "Return", "True", "if", "this", "path", "matches", "the", "given", "pattern", "." ]
python
train
pyviz/holoviews
holoviews/core/dimension.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/dimension.py#L1444-L1456
def regroup(self, group): """Deprecated method to apply new group to items. Equivalent functionality possible using: ViewableTree(tree.relabel(group='Group').values()) """ if util.config.future_deprecations: self.param.warning('%s.regroup is deprecated, use rela...
[ "def", "regroup", "(", "self", ",", "group", ")", ":", "if", "util", ".", "config", ".", "future_deprecations", ":", "self", ".", "param", ".", "warning", "(", "'%s.regroup is deprecated, use relabel '", "'method with a group argument instead.'", "%", "type", "(", ...
Deprecated method to apply new group to items. Equivalent functionality possible using: ViewableTree(tree.relabel(group='Group').values())
[ "Deprecated", "method", "to", "apply", "new", "group", "to", "items", "." ]
python
train
textX/textX
examples/StateMachine/state_machine.py
https://github.com/textX/textX/blob/5796ac38116ad86584392dbecdbf923ede746361/examples/StateMachine/state_machine.py#L46-L62
def interpret(self): """ Main interpreter loop. """ self.print_menu() while True: try: event = input() if event == 'q': return event = int(event) event = self.model.events[event-1] ...
[ "def", "interpret", "(", "self", ")", ":", "self", ".", "print_menu", "(", ")", "while", "True", ":", "try", ":", "event", "=", "input", "(", ")", "if", "event", "==", "'q'", ":", "return", "event", "=", "int", "(", "event", ")", "event", "=", "s...
Main interpreter loop.
[ "Main", "interpreter", "loop", "." ]
python
train
orbingol/NURBS-Python
geomdl/_tessellate.py
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_tessellate.py#L179-L214
def make_quad_mesh(points, size_u, size_v): """ Generates a mesh of quadrilateral elements. :param points: list of points :type points: list, tuple :param size_u: number of points on the u-direction (column) :type size_u: int :param size_v: number of points on the v-direction (row) :type si...
[ "def", "make_quad_mesh", "(", "points", ",", "size_u", ",", "size_v", ")", ":", "# Numbering", "vertex_idx", "=", "0", "quad_idx", "=", "0", "# Generate vertices", "vertices", "=", "[", "]", "for", "pt", "in", "points", ":", "vrt", "=", "Vertex", "(", "*...
Generates a mesh of quadrilateral elements. :param points: list of points :type points: list, tuple :param size_u: number of points on the u-direction (column) :type size_u: int :param size_v: number of points on the v-direction (row) :type size_v: int :return: a tuple containing lists of v...
[ "Generates", "a", "mesh", "of", "quadrilateral", "elements", "." ]
python
train
annoviko/pyclustering
pyclustering/utils/__init__.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/utils/__init__.py#L1202-L1213
def list_math_subtraction(a, b): """! @brief Calculates subtraction of two lists. @details Each element from list 'a' is subtracted by element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematical subtraction. @param[in] b (list): List of elements tha...
[ "def", "list_math_subtraction", "(", "a", ",", "b", ")", ":", "return", "[", "a", "[", "i", "]", "-", "b", "[", "i", "]", "for", "i", "in", "range", "(", "len", "(", "a", ")", ")", "]" ]
! @brief Calculates subtraction of two lists. @details Each element from list 'a' is subtracted by element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematical subtraction. @param[in] b (list): List of elements that supports mathematical subtraction. ...
[ "!" ]
python
valid
saltstack/salt
salt/spm/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/__init__.py#L1093-L1112
def _render(self, data, formula_def): ''' Render a [pre|post]_local_state or [pre|post]_tgt_state script ''' # FORMULA can contain a renderer option renderer = formula_def.get('renderer', self.opts.get('renderer', 'jinja|yaml')) rend = salt.loader.render(self.opts, {}) ...
[ "def", "_render", "(", "self", ",", "data", ",", "formula_def", ")", ":", "# FORMULA can contain a renderer option", "renderer", "=", "formula_def", ".", "get", "(", "'renderer'", ",", "self", ".", "opts", ".", "get", "(", "'renderer'", ",", "'jinja|yaml'", ")...
Render a [pre|post]_local_state or [pre|post]_tgt_state script
[ "Render", "a", "[", "pre|post", "]", "_local_state", "or", "[", "pre|post", "]", "_tgt_state", "script" ]
python
train
abseil/abseil-py
absl/logging/__init__.py
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L569-L611
def find_log_dir_and_names(program_name=None, log_dir=None): """Computes the directory and filename prefix for log file. Args: program_name: str|None, the filename part of the path to the program that is running without its extension. e.g: if your program is called 'usr/bin/foobar.py' this met...
[ "def", "find_log_dir_and_names", "(", "program_name", "=", "None", ",", "log_dir", "=", "None", ")", ":", "if", "not", "program_name", ":", "# Strip the extension (foobar.par becomes foobar, and", "# fubar.py becomes fubar). We do this so that the log", "# file names are similar ...
Computes the directory and filename prefix for log file. Args: program_name: str|None, the filename part of the path to the program that is running without its extension. e.g: if your program is called 'usr/bin/foobar.py' this method should probably be called with program_name='foobar' H...
[ "Computes", "the", "directory", "and", "filename", "prefix", "for", "log", "file", "." ]
python
train
FactoryBoy/factory_boy
factory/builder.py
https://github.com/FactoryBoy/factory_boy/blob/edaa7c7f5a14065b229927903bd7989cc93cd069/factory/builder.py#L70-L94
def update(self, values): """Add new declarations to this set/ Args: values (dict(name, declaration)): the declarations to ingest. """ for k, v in values.items(): root, sub = self.split(k) if sub is None: self.declarations[root] = v ...
[ "def", "update", "(", "self", ",", "values", ")", ":", "for", "k", ",", "v", "in", "values", ".", "items", "(", ")", ":", "root", ",", "sub", "=", "self", ".", "split", "(", "k", ")", "if", "sub", "is", "None", ":", "self", ".", "declarations",...
Add new declarations to this set/ Args: values (dict(name, declaration)): the declarations to ingest.
[ "Add", "new", "declarations", "to", "this", "set", "/" ]
python
train
dbrattli/OSlash
oslash/abc/monoid.py
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/abc/monoid.py#L48-L60
def concat(cls, xs): """mconcat :: [m] -> m Fold a list using the monoid. For most types, the default definition for mconcat will be used, but the function is included in the class definition so that an optimized version can be provided for specific types. """ d...
[ "def", "concat", "(", "cls", ",", "xs", ")", ":", "def", "reducer", "(", "a", ",", "b", ")", ":", "return", "a", ".", "append", "(", "b", ")", "return", "reduce", "(", "reducer", ",", "xs", ",", "cls", ".", "empty", "(", ")", ")" ]
mconcat :: [m] -> m Fold a list using the monoid. For most types, the default definition for mconcat will be used, but the function is included in the class definition so that an optimized version can be provided for specific types.
[ "mconcat", "::", "[", "m", "]", "-", ">", "m" ]
python
train
google/tangent
tangent/ast.py
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/ast.py#L83-L90
def copy_node(node): """Copy a node but keep its annotations intact.""" if not isinstance(node, gast.AST): return [copy_node(n) for n in node] new_node = copy.deepcopy(node) setattr(new_node, anno.ANNOTATION_FIELD, getattr(node, anno.ANNOTATION_FIELD, {}).copy()) return new_node
[ "def", "copy_node", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "gast", ".", "AST", ")", ":", "return", "[", "copy_node", "(", "n", ")", "for", "n", "in", "node", "]", "new_node", "=", "copy", ".", "deepcopy", "(", "node", ...
Copy a node but keep its annotations intact.
[ "Copy", "a", "node", "but", "keep", "its", "annotations", "intact", "." ]
python
train
rocioar/flake8-django
flake8_django/checkers/model_form.py
https://github.com/rocioar/flake8-django/blob/917f196e2518412bda6e841c1ed3de312004fc67/flake8_django/checkers/model_form.py#L39-L68
def run(self, node): """ Captures the use of exclude in ModelForm Meta """ if not self.checker_applies(node): return issues = [] for body in node.body: if not isinstance(body, ast.ClassDef): continue for element in body...
[ "def", "run", "(", "self", ",", "node", ")", ":", "if", "not", "self", ".", "checker_applies", "(", "node", ")", ":", "return", "issues", "=", "[", "]", "for", "body", "in", "node", ".", "body", ":", "if", "not", "isinstance", "(", "body", ",", "...
Captures the use of exclude in ModelForm Meta
[ "Captures", "the", "use", "of", "exclude", "in", "ModelForm", "Meta" ]
python
train
ioos/compliance-checker
compliance_checker/cf/cf.py
https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cf/cf.py#L1802-L1850
def check_dimensionless_vertical_coordinate(self, ds): ''' Check the validity of dimensionless coordinates under CF CF §4.3.2 The units attribute is not required for dimensionless coordinates. The standard_name attribute associates a coordinate with its definition from ...
[ "def", "check_dimensionless_vertical_coordinate", "(", "self", ",", "ds", ")", ":", "ret_val", "=", "[", "]", "z_variables", "=", "cfutil", ".", "get_z_variables", "(", "ds", ")", "deprecated_units", "=", "[", "'level'", ",", "'layer'", ",", "'sigma_level'", "...
Check the validity of dimensionless coordinates under CF CF §4.3.2 The units attribute is not required for dimensionless coordinates. The standard_name attribute associates a coordinate with its definition from Appendix D, Dimensionless Vertical Coordinates. The definition prov...
[ "Check", "the", "validity", "of", "dimensionless", "coordinates", "under", "CF" ]
python
train
dnanexus/dx-toolkit
src/python/dxpy/utils/resolver.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/utils/resolver.py#L615-L718
def _check_resolution_needed(path, project, folderpath, entity_name, expected_classes=None, describe=True, enclose_in_list=False): """ :param path: Path to the object that required resolution; propagated from command-line :type path: string :param project: T...
[ "def", "_check_resolution_needed", "(", "path", ",", "project", ",", "folderpath", ",", "entity_name", ",", "expected_classes", "=", "None", ",", "describe", "=", "True", ",", "enclose_in_list", "=", "False", ")", ":", "if", "entity_name", "is", "None", ":", ...
:param path: Path to the object that required resolution; propagated from command-line :type path: string :param project: The potential project the entity belongs to :type project: string :param folderpath: Path to the entity :type folderpath: string :param entity_name: The name...
[ ":", "param", "path", ":", "Path", "to", "the", "object", "that", "required", "resolution", ";", "propagated", "from", "command", "-", "line", ":", "type", "path", ":", "string", ":", "param", "project", ":", "The", "potential", "project", "the", "entity",...
python
train
kislyuk/ensure
ensure/main.py
https://github.com/kislyuk/ensure/blob/0a562a4b469ffbaf71c75dc4d394e94334c831f0/ensure/main.py#L282-L287
def does_not_contain(self, element): """ Ensures :attr:`subject` does not contain *element*. """ self._run(unittest_case.assertNotIn, (element, self._subject)) return ChainInspector(self._subject)
[ "def", "does_not_contain", "(", "self", ",", "element", ")", ":", "self", ".", "_run", "(", "unittest_case", ".", "assertNotIn", ",", "(", "element", ",", "self", ".", "_subject", ")", ")", "return", "ChainInspector", "(", "self", ".", "_subject", ")" ]
Ensures :attr:`subject` does not contain *element*.
[ "Ensures", ":", "attr", ":", "subject", "does", "not", "contain", "*", "element", "*", "." ]
python
train
dhermes/bezier
src/bezier/curve.py
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curve.py#L443-L538
def reduce_(self): r"""Return a degree-reduced version of the current curve. .. _pseudo-inverse: https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n - 1}` ...
[ "def", "reduce_", "(", "self", ")", ":", "new_nodes", "=", "_curve_helpers", ".", "reduce_pseudo_inverse", "(", "self", ".", "_nodes", ")", "return", "Curve", "(", "new_nodes", ",", "self", ".", "_degree", "-", "1", ",", "_copy", "=", "False", ")" ]
r"""Return a degree-reduced version of the current curve. .. _pseudo-inverse: https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n - 1}` that correspond to ...
[ "r", "Return", "a", "degree", "-", "reduced", "version", "of", "the", "current", "curve", "." ]
python
train
project-rig/rig
rig/place_and_route/place/breadth_first.py
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/breadth_first.py#L8-L39
def breadth_first_vertex_order(vertices_resources, nets): """A generator which iterates over a set of vertices in a breadth-first order in terms of connectivity. For use as a vertex ordering for the sequential placer. """ # Special case: no vertices, just stop immediately if len(vertices_resour...
[ "def", "breadth_first_vertex_order", "(", "vertices_resources", ",", "nets", ")", ":", "# Special case: no vertices, just stop immediately", "if", "len", "(", "vertices_resources", ")", "==", "0", ":", "return", "# Enumerate the set of nets attached to each vertex", "vertex_nei...
A generator which iterates over a set of vertices in a breadth-first order in terms of connectivity. For use as a vertex ordering for the sequential placer.
[ "A", "generator", "which", "iterates", "over", "a", "set", "of", "vertices", "in", "a", "breadth", "-", "first", "order", "in", "terms", "of", "connectivity", "." ]
python
train
sparklingpandas/sparklingpandas
sparklingpandas/groupby.py
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/groupby.py#L119-L126
def groups(self): """Returns dict {group name -> group labels}.""" self._prep_pandas_groupby() def extract_group_labels(frame): return (frame[0], frame[1].index.values) return self._mergedRDD.map(extract_group_labels).collectAsMap()
[ "def", "groups", "(", "self", ")", ":", "self", ".", "_prep_pandas_groupby", "(", ")", "def", "extract_group_labels", "(", "frame", ")", ":", "return", "(", "frame", "[", "0", "]", ",", "frame", "[", "1", "]", ".", "index", ".", "values", ")", "retur...
Returns dict {group name -> group labels}.
[ "Returns", "dict", "{", "group", "name", "-", ">", "group", "labels", "}", "." ]
python
train
chrisspen/weka
weka/arff.py
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L370-L383
def parse(cls, s, schema_only=False): """ Parse an ARFF File already loaded into a string. """ a = cls() a.state = 'comment' a.lineno = 1 for l in s.splitlines(): a.parseline(l) a.lineno += 1 if schema_only and a.state == 'data'...
[ "def", "parse", "(", "cls", ",", "s", ",", "schema_only", "=", "False", ")", ":", "a", "=", "cls", "(", ")", "a", ".", "state", "=", "'comment'", "a", ".", "lineno", "=", "1", "for", "l", "in", "s", ".", "splitlines", "(", ")", ":", "a", ".",...
Parse an ARFF File already loaded into a string.
[ "Parse", "an", "ARFF", "File", "already", "loaded", "into", "a", "string", "." ]
python
train
adamreeve/npTDMS
nptdms/tdms.py
https://github.com/adamreeve/npTDMS/blob/d7d6632d4ebc2e78ed941477c2f1c56bd7493d74/nptdms/tdms.py#L208-L226
def as_dataframe(self, time_index=False, absolute_time=False): """ Converts the TDMS file to a DataFrame :param time_index: Whether to include a time index for the dataframe. :param absolute_time: If time_index is true, whether the time index values are absolute times or rel...
[ "def", "as_dataframe", "(", "self", ",", "time_index", "=", "False", ",", "absolute_time", "=", "False", ")", ":", "import", "pandas", "as", "pd", "dataframe_dict", "=", "OrderedDict", "(", ")", "for", "key", ",", "value", "in", "self", ".", "objects", "...
Converts the TDMS file to a DataFrame :param time_index: Whether to include a time index for the dataframe. :param absolute_time: If time_index is true, whether the time index values are absolute times or relative to the start time. :return: The full TDMS file data. :rtype: ...
[ "Converts", "the", "TDMS", "file", "to", "a", "DataFrame" ]
python
train
zetaops/pyoko
pyoko/manage.py
https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/manage.py#L884-L893
def _print_fields(self, fields): """Print the fields, padding the names as necessary to align them.""" # Prepare a formatting string that aligns the names and types based on the longest ones longest_name = max(fields, key=lambda f: len(f[1]))[1] longest_type = max(fields, key=lambda f: l...
[ "def", "_print_fields", "(", "self", ",", "fields", ")", ":", "# Prepare a formatting string that aligns the names and types based on the longest ones", "longest_name", "=", "max", "(", "fields", ",", "key", "=", "lambda", "f", ":", "len", "(", "f", "[", "1", "]", ...
Print the fields, padding the names as necessary to align them.
[ "Print", "the", "fields", "padding", "the", "names", "as", "necessary", "to", "align", "them", "." ]
python
train
pandas-dev/pandas
pandas/core/arrays/categorical.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1088-L1124
def remove_unused_categories(self, inplace=False): """ Remove categories which are not used. Parameters ---------- inplace : bool, default False Whether or not to drop unused categories inplace or return a copy of this categorical with unused categories dro...
[ "def", "remove_unused_categories", "(", "self", ",", "inplace", "=", "False", ")", ":", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "'inplace'", ")", "cat", "=", "self", "if", "inplace", "else", "self", ".", "copy", "(", ")", "idx", ",", ...
Remove categories which are not used. Parameters ---------- inplace : bool, default False Whether or not to drop unused categories inplace or return a copy of this categorical with unused categories dropped. Returns ------- cat : Categorical with u...
[ "Remove", "categories", "which", "are", "not", "used", "." ]
python
train
sixty-north/asq
asq/queryables.py
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L417-L476
def select_many_with_correspondence( self, collection_selector=identity, result_selector=KeyedElement): '''Projects each element of a sequence to an intermediate new sequence, and flattens the resulting sequence, into one sequence and uses a selector function ...
[ "def", "select_many_with_correspondence", "(", "self", ",", "collection_selector", "=", "identity", ",", "result_selector", "=", "KeyedElement", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call \"", "\"select_many_...
Projects each element of a sequence to an intermediate new sequence, and flattens the resulting sequence, into one sequence and uses a selector function to incorporate the corresponding source for each item in the result sequence. Note: This method uses deferred execution. Args...
[ "Projects", "each", "element", "of", "a", "sequence", "to", "an", "intermediate", "new", "sequence", "and", "flattens", "the", "resulting", "sequence", "into", "one", "sequence", "and", "uses", "a", "selector", "function", "to", "incorporate", "the", "correspond...
python
train
weluse/django-nose-selenium
noseselenium/plugins.py
https://github.com/weluse/django-nose-selenium/blob/19a09b9455545f70271f884649323a38812793e6/noseselenium/plugins.py#L81-L89
def _patch_static_handler(handler): """Patch in support for static files serving if supported and enabled. """ if django.VERSION[:2] < (1, 3): return from django.contrib.staticfiles.handlers import StaticFilesHandler return StaticFilesHandler(handler)
[ "def", "_patch_static_handler", "(", "handler", ")", ":", "if", "django", ".", "VERSION", "[", ":", "2", "]", "<", "(", "1", ",", "3", ")", ":", "return", "from", "django", ".", "contrib", ".", "staticfiles", ".", "handlers", "import", "StaticFilesHandle...
Patch in support for static files serving if supported and enabled.
[ "Patch", "in", "support", "for", "static", "files", "serving", "if", "supported", "and", "enabled", "." ]
python
train
kodexlab/reliure
reliure/web.py
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/web.py#L248-L257
def options(self): """ Engine options discover HTTP entry point """ #configure engine with an empty dict to ensure default selection/options self.engine.configure({}) conf = self.engine.as_dict() conf["returns"] = [oname for oname in six.iterkeys(self._outputs)] #...
[ "def", "options", "(", "self", ")", ":", "#configure engine with an empty dict to ensure default selection/options", "self", ".", "engine", ".", "configure", "(", "{", "}", ")", "conf", "=", "self", ".", "engine", ".", "as_dict", "(", ")", "conf", "[", "\"return...
Engine options discover HTTP entry point
[ "Engine", "options", "discover", "HTTP", "entry", "point" ]
python
train
yunojuno/python-env-utils
env_utils/utils.py
https://github.com/yunojuno/python-env-utils/blob/7f3b5635f93322759856644901221955908e7e99/env_utils/utils.py#L146-L149
def get_list(key, *default, **kwargs): """Return env var as a list.""" separator = kwargs.get('separator', ' ') return get_env(key, *default, coerce=lambda x: x.split(separator))
[ "def", "get_list", "(", "key", ",", "*", "default", ",", "*", "*", "kwargs", ")", ":", "separator", "=", "kwargs", ".", "get", "(", "'separator'", ",", "' '", ")", "return", "get_env", "(", "key", ",", "*", "default", ",", "coerce", "=", "lambda", ...
Return env var as a list.
[ "Return", "env", "var", "as", "a", "list", "." ]
python
train
BlockHub/blockhubdpostools
dpostools/dbtools.py
https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/dbtools.py#L519-L654
def tbw(self, delegate_address, blacklist=None, share_fees=False, compound_interest=False): """This function doesn't work yet. Instead use legacy.trueshare() for a functional tbw script""" if not blacklist: blacklist = [] delegate_public_key = self.account_details(address=delegate_a...
[ "def", "tbw", "(", "self", ",", "delegate_address", ",", "blacklist", "=", "None", ",", "share_fees", "=", "False", ",", "compound_interest", "=", "False", ")", ":", "if", "not", "blacklist", ":", "blacklist", "=", "[", "]", "delegate_public_key", "=", "se...
This function doesn't work yet. Instead use legacy.trueshare() for a functional tbw script
[ "This", "function", "doesn", "t", "work", "yet", ".", "Instead", "use", "legacy", ".", "trueshare", "()", "for", "a", "functional", "tbw", "script" ]
python
valid
collectiveacuity/jsonModel
jsonmodel/validators.py
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1368-L1385
def _ingest_boolean(self, input_boolean, path_to_root): ''' a helper method for ingesting a boolean :return: valid_boolean ''' valid_boolean = False try: valid_boolean = self._validate_boolean(input_boolean, path_to_root) except: ru...
[ "def", "_ingest_boolean", "(", "self", ",", "input_boolean", ",", "path_to_root", ")", ":", "valid_boolean", "=", "False", "try", ":", "valid_boolean", "=", "self", ".", "_validate_boolean", "(", "input_boolean", ",", "path_to_root", ")", "except", ":", "rules_p...
a helper method for ingesting a boolean :return: valid_boolean
[ "a", "helper", "method", "for", "ingesting", "a", "boolean" ]
python
train
open-homeautomation/pknx
knxip/ip.py
https://github.com/open-homeautomation/pknx/blob/a8aed8271563923c447aa330ba7c1c2927286f7a/knxip/ip.py#L182-L193
def init_group_write(self, dst_addr=1, data=None, dptsize=0): """Initialize the CEMI frame for a group write operation.""" self.init_group(dst_addr) # unnumbered data packet, group write self.tpci_apci = 0x00 * 256 + 0x80 self.dptsize = dptsize if data is None: ...
[ "def", "init_group_write", "(", "self", ",", "dst_addr", "=", "1", ",", "data", "=", "None", ",", "dptsize", "=", "0", ")", ":", "self", ".", "init_group", "(", "dst_addr", ")", "# unnumbered data packet, group write", "self", ".", "tpci_apci", "=", "0x00", ...
Initialize the CEMI frame for a group write operation.
[ "Initialize", "the", "CEMI", "frame", "for", "a", "group", "write", "operation", "." ]
python
train
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L3077-L3110
def get_metric_values_response(self): """ Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object, as a string in the format needed for the "Get Metrics" operation response. Returns: "MetricsR...
[ "def", "get_metric_values_response", "(", "self", ")", ":", "mv_list", "=", "self", ".", "get_metric_values", "(", ")", "resp_lines", "=", "[", "]", "for", "mv", "in", "mv_list", ":", "group_name", "=", "mv", "[", "0", "]", "resp_lines", ".", "append", "...
Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object, as a string in the format needed for the "Get Metrics" operation response. Returns: "MetricsResponse" string as described for the "Get Metrics" ...
[ "Get", "the", "faked", "metrics", "for", "all", "metric", "groups", "and", "all", "resources", "that", "have", "been", "prepared", "on", "the", "manager", "object", "of", "this", "context", "object", "as", "a", "string", "in", "the", "format", "needed", "f...
python
train
deepmind/sonnet
sonnet/python/modules/sequential.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/sequential.py#L79-L107
def _build(self, *args): """Connects the Sequential module into the graph. Args: *args: A tuple of inputs, to be unpacked as the arguments to the first layer. Returns: The output value of the last layer. """ net = args if not self._layers: # If the sequential is pa...
[ "def", "_build", "(", "self", ",", "*", "args", ")", ":", "net", "=", "args", "if", "not", "self", ".", "_layers", ":", "# If the sequential is passed a single arg, this will end up being", "# wrapped in an extra layer of tuple by *args. Normally we internally", "# handle thi...
Connects the Sequential module into the graph. Args: *args: A tuple of inputs, to be unpacked as the arguments to the first layer. Returns: The output value of the last layer.
[ "Connects", "the", "Sequential", "module", "into", "the", "graph", "." ]
python
train
chaoss/grimoirelab-perceval
perceval/backends/core/git.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/git.py#L1204-L1223
def _update_ref(self, ref, delete=False): """Update a reference.""" cmd = ['git', 'update-ref'] if delete: cmd.extend(['-d', ref.refname]) action = 'deleted' else: cmd.extend([ref.refname, ref.hash]) action = 'updated to %s' % ref.hash ...
[ "def", "_update_ref", "(", "self", ",", "ref", ",", "delete", "=", "False", ")", ":", "cmd", "=", "[", "'git'", ",", "'update-ref'", "]", "if", "delete", ":", "cmd", ".", "extend", "(", "[", "'-d'", ",", "ref", ".", "refname", "]", ")", "action", ...
Update a reference.
[ "Update", "a", "reference", "." ]
python
test
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/werkzeug/wrappers.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/werkzeug/wrappers.py#L1078-L1167
def get_wsgi_headers(self, environ): """This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary. For example the loc...
[ "def", "get_wsgi_headers", "(", "self", ",", "environ", ")", ":", "headers", "=", "Headers", "(", "self", ".", "headers", ")", "location", "=", "None", "content_location", "=", "None", "content_length", "=", "None", "status", "=", "self", ".", "status_code",...
This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary. For example the location header (if present) is joined with the roo...
[ "This", "is", "automatically", "called", "right", "before", "the", "response", "is", "started", "and", "returns", "headers", "modified", "for", "the", "given", "environment", ".", "It", "returns", "a", "copy", "of", "the", "headers", "from", "the", "response",...
python
test
openwisp/netdiff
netdiff/parsers/olsr.py
https://github.com/openwisp/netdiff/blob/f7fda2ed78ad815b8c56eae27dfd193172fb23f5/netdiff/parsers/olsr.py#L11-L18
def to_python(self, data): """ Adds support for txtinfo format """ try: return super(OlsrParser, self).to_python(data) except ConversionException as e: return self._txtinfo_to_jsoninfo(e.data)
[ "def", "to_python", "(", "self", ",", "data", ")", ":", "try", ":", "return", "super", "(", "OlsrParser", ",", "self", ")", ".", "to_python", "(", "data", ")", "except", "ConversionException", "as", "e", ":", "return", "self", ".", "_txtinfo_to_jsoninfo", ...
Adds support for txtinfo format
[ "Adds", "support", "for", "txtinfo", "format" ]
python
train
ewels/MultiQC
multiqc/modules/rseqc/gene_body_coverage.py
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rseqc/gene_body_coverage.py#L15-L106
def parse_reports(self): """ Find RSeQC gene_body_coverage reports and parse their data """ # Set up vars self.gene_body_cov_hist_counts = dict() self.gene_body_cov_hist_percent = dict() # TODO - Do separate parsing step to find skewness values # and add these to the general stats table? ...
[ "def", "parse_reports", "(", "self", ")", ":", "# Set up vars", "self", ".", "gene_body_cov_hist_counts", "=", "dict", "(", ")", "self", ".", "gene_body_cov_hist_percent", "=", "dict", "(", ")", "# TODO - Do separate parsing step to find skewness values", "# and add these...
Find RSeQC gene_body_coverage reports and parse their data
[ "Find", "RSeQC", "gene_body_coverage", "reports", "and", "parse", "their", "data" ]
python
train
pmacosta/peng
peng/functions.py
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L804-L1051
def pprint_vector(vector, limit=False, width=None, indent=0, eng=False, frac_length=3): r""" Format a list of numbers (vector) or a Numpy vector for printing. If the argument **vector** is :code:`None` the string :code:`'None'` is returned :param vector: Vector to pretty print or None :type v...
[ "def", "pprint_vector", "(", "vector", ",", "limit", "=", "False", ",", "width", "=", "None", ",", "indent", "=", "0", ",", "eng", "=", "False", ",", "frac_length", "=", "3", ")", ":", "# pylint: disable=R0912,R0913", "num_digits", "=", "12", "approx", "...
r""" Format a list of numbers (vector) or a Numpy vector for printing. If the argument **vector** is :code:`None` the string :code:`'None'` is returned :param vector: Vector to pretty print or None :type vector: list of integers or floats, Numpy vector or None :param limit: Flag that indicat...
[ "r", "Format", "a", "list", "of", "numbers", "(", "vector", ")", "or", "a", "Numpy", "vector", "for", "printing", "." ]
python
test
yatiml/yatiml
yatiml/helpers.py
https://github.com/yatiml/yatiml/blob/4f55c058b72388350f0af3076ac3ea9bc1c142b0/yatiml/helpers.py#L321-L425
def seq_attribute_to_map(self, attribute: str, key_attribute: str, value_attribute: Optional[str] = None, strict: Optional[bool] = True) -> None: """Converts a sequence attribute to a map. ...
[ "def", "seq_attribute_to_map", "(", "self", ",", "attribute", ":", "str", ",", "key_attribute", ":", "str", ",", "value_attribute", ":", "Optional", "[", "str", "]", "=", "None", ",", "strict", ":", "Optional", "[", "bool", "]", "=", "True", ")", "->", ...
Converts a sequence attribute to a map. This function takes an attribute of this Node that is \ a sequence of mappings and turns it into a mapping of mappings. \ It assumes that each of the mappings in the original sequence \ has an attribute containing a unique value, which it will use...
[ "Converts", "a", "sequence", "attribute", "to", "a", "map", "." ]
python
train
hyperledger/indy-plenum
plenum/server/replica.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L1333-L1348
def processCommit(self, commit: Commit, sender: str) -> None: """ Validate and process the COMMIT specified. If validation is successful, return the message to the node. :param commit: an incoming COMMIT message :param sender: name of the node that sent the COMMIT """ ...
[ "def", "processCommit", "(", "self", ",", "commit", ":", "Commit", ",", "sender", ":", "str", ")", "->", "None", ":", "self", ".", "logger", ".", "debug", "(", "\"{} received COMMIT{} from {}\"", ".", "format", "(", "self", ",", "(", "commit", ".", "view...
Validate and process the COMMIT specified. If validation is successful, return the message to the node. :param commit: an incoming COMMIT message :param sender: name of the node that sent the COMMIT
[ "Validate", "and", "process", "the", "COMMIT", "specified", ".", "If", "validation", "is", "successful", "return", "the", "message", "to", "the", "node", "." ]
python
train
Alignak-monitoring/alignak
alignak/external_command.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/external_command.py#L2436-L2450
def disable_svc_check(self, service): """Disable checks for a service Format of the line that triggers function call:: DISABLE_SVC_CHECK;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service :return: None ...
[ "def", "disable_svc_check", "(", "self", ",", "service", ")", ":", "if", "service", ".", "active_checks_enabled", ":", "service", ".", "disable_active_checks", "(", "self", ".", "daemon", ".", "checks", ")", "service", ".", "modified_attributes", "|=", "DICT_MOD...
Disable checks for a service Format of the line that triggers function call:: DISABLE_SVC_CHECK;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service :return: None
[ "Disable", "checks", "for", "a", "service", "Format", "of", "the", "line", "that", "triggers", "function", "call", "::" ]
python
train
learningequality/iceqube
src/iceqube/storage/backends/inmem.py
https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/storage/backends/inmem.py#L304-L312
def _ns_query(self, session): """ Return a SQLAlchemy query that is already namespaced by the app and namespace given to this backend during initialization. Returns: a SQLAlchemy query object """ return session.query(ORMJob).filter(ORMJob.app == self.app, ...
[ "def", "_ns_query", "(", "self", ",", "session", ")", ":", "return", "session", ".", "query", "(", "ORMJob", ")", ".", "filter", "(", "ORMJob", ".", "app", "==", "self", ".", "app", ",", "ORMJob", ".", "namespace", "==", "self", ".", "namespace", ")"...
Return a SQLAlchemy query that is already namespaced by the app and namespace given to this backend during initialization. Returns: a SQLAlchemy query object
[ "Return", "a", "SQLAlchemy", "query", "that", "is", "already", "namespaced", "by", "the", "app", "and", "namespace", "given", "to", "this", "backend", "during", "initialization", ".", "Returns", ":", "a", "SQLAlchemy", "query", "object" ]
python
train
saltstack/salt
salt/modules/win_system.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L788-L846
def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``exampl...
[ "def", "_join_domain", "(", "domain", ",", "username", "=", "None", ",", "password", "=", "None", ",", "account_ou", "=", "None", ",", "account_exists", "=", "False", ")", ":", "NETSETUP_JOIN_DOMAIN", "=", "0x1", "# pylint: disable=invalid-name", "NETSETUP_ACCOUNT...
Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified ...
[ "Helper", "function", "to", "join", "the", "domain", "." ]
python
train
ThreatConnect-Inc/tcex
tcex/tcex_vault.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_vault.py#L23-L31
def create(self, key, value, lease='1h'): """Create key/value pair in Vault. Args: key (string): The data key. value (string): The data value. lease (string): The least time. """ return self._client.write(key, value, lease=lease)
[ "def", "create", "(", "self", ",", "key", ",", "value", ",", "lease", "=", "'1h'", ")", ":", "return", "self", ".", "_client", ".", "write", "(", "key", ",", "value", ",", "lease", "=", "lease", ")" ]
Create key/value pair in Vault. Args: key (string): The data key. value (string): The data value. lease (string): The least time.
[ "Create", "key", "/", "value", "pair", "in", "Vault", "." ]
python
train
Nachtfeuer/pipeline
spline/components/config.py
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/components/config.py#L29-L46
def schema(): """Provide schema for shell configuration.""" return Schema({ 'script': And(Or(type(' '), type(u' ')), len), Optional('title', default=''): str, Optional('model', default={}): {Optional(And(str, len)): object}, Optional('env', default={}): {O...
[ "def", "schema", "(", ")", ":", "return", "Schema", "(", "{", "'script'", ":", "And", "(", "Or", "(", "type", "(", "' '", ")", ",", "type", "(", "u' '", ")", ")", ",", "len", ")", ",", "Optional", "(", "'title'", ",", "default", "=", "''", ")",...
Provide schema for shell configuration.
[ "Provide", "schema", "for", "shell", "configuration", "." ]
python
train
wummel/dosage
dosagelib/scraper.py
https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/dosagelib/scraper.py#L198-L211
def getPrevUrl(self, url, data): """Find previous URL.""" prevUrl = None if self.prevSearch: try: prevUrl = self.fetchUrl(url, data, self.prevSearch) except ValueError as msg: # assume there is no previous URL, but print a warning ...
[ "def", "getPrevUrl", "(", "self", ",", "url", ",", "data", ")", ":", "prevUrl", "=", "None", "if", "self", ".", "prevSearch", ":", "try", ":", "prevUrl", "=", "self", ".", "fetchUrl", "(", "url", ",", "data", ",", "self", ".", "prevSearch", ")", "e...
Find previous URL.
[ "Find", "previous", "URL", "." ]
python
train
chrisspen/dtree
dtree.py
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L145-L154
def normpdf(x, mu, sigma): """ Describes the relative likelihood that a real-valued random variable X will take on a given value. http://en.wikipedia.org/wiki/Probability_density_function """ u = (x-mu)/abs(sigma) y = (1/(math.sqrt(2*pi)*abs(sigma)))*math.exp(-u*u/2) return y
[ "def", "normpdf", "(", "x", ",", "mu", ",", "sigma", ")", ":", "u", "=", "(", "x", "-", "mu", ")", "/", "abs", "(", "sigma", ")", "y", "=", "(", "1", "/", "(", "math", ".", "sqrt", "(", "2", "*", "pi", ")", "*", "abs", "(", "sigma", ")"...
Describes the relative likelihood that a real-valued random variable X will take on a given value. http://en.wikipedia.org/wiki/Probability_density_function
[ "Describes", "the", "relative", "likelihood", "that", "a", "real", "-", "valued", "random", "variable", "X", "will", "take", "on", "a", "given", "value", ".", "http", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Probability_density_fun...
python
train
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L72-L104
def _new_alloc_handle(stype, shape, ctx, delay_alloc, dtype, aux_types, aux_shapes=None): """Return a new handle with specified storage type, shape, dtype and context. Empty handle is only used to hold results Returns ------- handle A new empty ndarray handle """ hdl = NDArrayHandl...
[ "def", "_new_alloc_handle", "(", "stype", ",", "shape", ",", "ctx", ",", "delay_alloc", ",", "dtype", ",", "aux_types", ",", "aux_shapes", "=", "None", ")", ":", "hdl", "=", "NDArrayHandle", "(", ")", "for", "aux_t", "in", "aux_types", ":", "if", "np", ...
Return a new handle with specified storage type, shape, dtype and context. Empty handle is only used to hold results Returns ------- handle A new empty ndarray handle
[ "Return", "a", "new", "handle", "with", "specified", "storage", "type", "shape", "dtype", "and", "context", "." ]
python
train
ARMmbed/icetea
examples/sample_cloud.py
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/examples/sample_cloud.py#L24-L30
def create(host, port, result_converter=None, testcase_converter=None, args=None): """ Function which is called by Icetea to create an instance of the cloud client. This function must exists. This function myust not return None. Either return an instance of Client or raise. """ return SampleClie...
[ "def", "create", "(", "host", ",", "port", ",", "result_converter", "=", "None", ",", "testcase_converter", "=", "None", ",", "args", "=", "None", ")", ":", "return", "SampleClient", "(", "host", ",", "port", ",", "result_converter", ",", "testcase_converter...
Function which is called by Icetea to create an instance of the cloud client. This function must exists. This function myust not return None. Either return an instance of Client or raise.
[ "Function", "which", "is", "called", "by", "Icetea", "to", "create", "an", "instance", "of", "the", "cloud", "client", ".", "This", "function", "must", "exists", ".", "This", "function", "myust", "not", "return", "None", ".", "Either", "return", "an", "ins...
python
train
trailofbits/protofuzz
protofuzz/gen.py
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/gen.py#L130-L152
def make_dependent(self, source, target, action): ''' Create a dependency between path 'source' and path 'target' via the callable 'action'. >>> permuter._generators [IterValueGenerator(one), IterValueGenerator(two)] >>> permuter.make_dependent('one', 'two', lambda x: x ...
[ "def", "make_dependent", "(", "self", ",", "source", ",", "target", ",", "action", ")", ":", "if", "not", "self", ".", "_generators", ":", "return", "src_permuter", ",", "src", "=", "self", ".", "_resolve_child", "(", "source", ")", "dest", "=", "self", ...
Create a dependency between path 'source' and path 'target' via the callable 'action'. >>> permuter._generators [IterValueGenerator(one), IterValueGenerator(two)] >>> permuter.make_dependent('one', 'two', lambda x: x + 1) Going forward, 'two' will only contain values that are (...
[ "Create", "a", "dependency", "between", "path", "source", "and", "path", "target", "via", "the", "callable", "action", "." ]
python
train
readbeyond/aeneas
aeneas/validator.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L259-L276
def check_file_encoding(self, input_file_path): """ Check whether the given file is UTF-8 encoded. :param string input_file_path: the path of the file to be checked :rtype: :class:`~aeneas.validator.ValidatorResult` """ self.log([u"Checking encoding of file '%s'", input_...
[ "def", "check_file_encoding", "(", "self", ",", "input_file_path", ")", ":", "self", ".", "log", "(", "[", "u\"Checking encoding of file '%s'\"", ",", "input_file_path", "]", ")", "self", ".", "result", "=", "ValidatorResult", "(", ")", "if", "self", ".", "_ar...
Check whether the given file is UTF-8 encoded. :param string input_file_path: the path of the file to be checked :rtype: :class:`~aeneas.validator.ValidatorResult`
[ "Check", "whether", "the", "given", "file", "is", "UTF", "-", "8", "encoded", "." ]
python
train
jtwhite79/pyemu
pyemu/mat/mat_handler.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/mat/mat_handler.py#L18-L64
def save_coo(x, row_names, col_names, filename, chunk=None): """write a PEST-compatible binary file. The data format is [int,int,float] for i,j,value. It is autodetected during the read with Matrix.from_binary(). Parameters ---------- x : numpy.sparse coo sparse matrix row_names ...
[ "def", "save_coo", "(", "x", ",", "row_names", ",", "col_names", ",", "filename", ",", "chunk", "=", "None", ")", ":", "f", "=", "open", "(", "filename", ",", "'wb'", ")", "# print(\"counting nnz\")", "# write the header", "header", "=", "np", ".", "array"...
write a PEST-compatible binary file. The data format is [int,int,float] for i,j,value. It is autodetected during the read with Matrix.from_binary(). Parameters ---------- x : numpy.sparse coo sparse matrix row_names : list list of row_names col_names : list list of...
[ "write", "a", "PEST", "-", "compatible", "binary", "file", ".", "The", "data", "format", "is", "[", "int", "int", "float", "]", "for", "i", "j", "value", ".", "It", "is", "autodetected", "during", "the", "read", "with", "Matrix", ".", "from_binary", "(...
python
train
gem/oq-engine
openquake/calculators/base.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L568-L586
def load_riskmodel(self): # to be called before read_exposure # NB: this is called even if there is no risk model """ Read the risk model and set the attribute .riskmodel. The riskmodel can be empty for hazard calculations. Save the loss ratios (if any) in the datastore. ...
[ "def", "load_riskmodel", "(", "self", ")", ":", "# to be called before read_exposure", "# NB: this is called even if there is no risk model", "logging", ".", "info", "(", "'Reading the risk model if present'", ")", "self", ".", "riskmodel", "=", "readinput", ".", "get_risk_mo...
Read the risk model and set the attribute .riskmodel. The riskmodel can be empty for hazard calculations. Save the loss ratios (if any) in the datastore.
[ "Read", "the", "risk", "model", "and", "set", "the", "attribute", ".", "riskmodel", ".", "The", "riskmodel", "can", "be", "empty", "for", "hazard", "calculations", ".", "Save", "the", "loss", "ratios", "(", "if", "any", ")", "in", "the", "datastore", "."...
python
train
bmcfee/pumpp
pumpp/base.py
https://github.com/bmcfee/pumpp/blob/06a17b888271dd1f6cd41bddb22b0eb04d494056/pumpp/base.py#L52-L84
def register(self, field, shape, dtype): '''Register a field as a tensor with specified shape and type. A `Tensor` of the given shape and type will be registered in this object's `fields` dict. Parameters ---------- field : str The name of the field ...
[ "def", "register", "(", "self", ",", "field", ",", "shape", ",", "dtype", ")", ":", "if", "not", "isinstance", "(", "dtype", ",", "type", ")", ":", "raise", "ParameterError", "(", "'dtype={} must be a type'", ".", "format", "(", "dtype", ")", ")", "if", ...
Register a field as a tensor with specified shape and type. A `Tensor` of the given shape and type will be registered in this object's `fields` dict. Parameters ---------- field : str The name of the field shape : iterable of `int` or `None` The...
[ "Register", "a", "field", "as", "a", "tensor", "with", "specified", "shape", "and", "type", "." ]
python
train
django-auth-ldap/django-auth-ldap
django_auth_ldap/backend.py
https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L591-L632
def _get_or_create_user(self, force_populate=False): """ Loads the User model object from the database or creates it if it doesn't exist. Also populates the fields, subject to AUTH_LDAP_ALWAYS_UPDATE_USER. """ save_user = False username = self.backend.ldap_to_dja...
[ "def", "_get_or_create_user", "(", "self", ",", "force_populate", "=", "False", ")", ":", "save_user", "=", "False", "username", "=", "self", ".", "backend", ".", "ldap_to_django_username", "(", "self", ".", "_username", ")", "self", ".", "_user", ",", "buil...
Loads the User model object from the database or creates it if it doesn't exist. Also populates the fields, subject to AUTH_LDAP_ALWAYS_UPDATE_USER.
[ "Loads", "the", "User", "model", "object", "from", "the", "database", "or", "creates", "it", "if", "it", "doesn", "t", "exist", ".", "Also", "populates", "the", "fields", "subject", "to", "AUTH_LDAP_ALWAYS_UPDATE_USER", "." ]
python
train
tonyfischetti/sake
sakelib/build.py
https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L115-L129
def write_shas_to_shastore(sha_dict): """ Writes a sha1 dictionary stored in memory to the .shastore file """ if sys.version_info[0] < 3: fn_open = open else: fn_open = io.open with fn_open(".shastore", "w") as fh: fh.write("---\n") fh.write('sake version: {}\...
[ "def", "write_shas_to_shastore", "(", "sha_dict", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "fn_open", "=", "open", "else", ":", "fn_open", "=", "io", ".", "open", "with", "fn_open", "(", "\".shastore\"", ",", "\"w\"", "...
Writes a sha1 dictionary stored in memory to the .shastore file
[ "Writes", "a", "sha1", "dictionary", "stored", "in", "memory", "to", "the", ".", "shastore", "file" ]
python
valid
mlperf/training
object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/voc/voc_eval.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/voc/voc_eval.py#L68-L157
def calc_detection_voc_prec_rec(gt_boxlists, pred_boxlists, iou_thresh=0.5): """Calculate precision and recall based on evaluation code of PASCAL VOC. This function calculates precision and recall of predicted bounding boxes obtained from a dataset which has :math:`N` images. The code is based on th...
[ "def", "calc_detection_voc_prec_rec", "(", "gt_boxlists", ",", "pred_boxlists", ",", "iou_thresh", "=", "0.5", ")", ":", "n_pos", "=", "defaultdict", "(", "int", ")", "score", "=", "defaultdict", "(", "list", ")", "match", "=", "defaultdict", "(", "list", ")...
Calculate precision and recall based on evaluation code of PASCAL VOC. This function calculates precision and recall of predicted bounding boxes obtained from a dataset which has :math:`N` images. The code is based on the evaluation code used in PASCAL VOC Challenge.
[ "Calculate", "precision", "and", "recall", "based", "on", "evaluation", "code", "of", "PASCAL", "VOC", ".", "This", "function", "calculates", "precision", "and", "recall", "of", "predicted", "bounding", "boxes", "obtained", "from", "a", "dataset", "which", "has"...
python
train
pytroll/satpy
satpy/scene.py
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/scene.py#L1036-L1097
def resample(self, destination=None, datasets=None, generate=True, unload=True, resampler=None, reduce_data=True, **resample_kwargs): """Resample datasets and return a new scene. Args: destination (AreaDefinition, GridDefinition): area definition to ...
[ "def", "resample", "(", "self", ",", "destination", "=", "None", ",", "datasets", "=", "None", ",", "generate", "=", "True", ",", "unload", "=", "True", ",", "resampler", "=", "None", ",", "reduce_data", "=", "True", ",", "*", "*", "resample_kwargs", "...
Resample datasets and return a new scene. Args: destination (AreaDefinition, GridDefinition): area definition to resample to. If not specified then the area returned by `Scene.max_area()` will be used. datasets (list): Limit datasets to resample to these ...
[ "Resample", "datasets", "and", "return", "a", "new", "scene", "." ]
python
train