nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
qlist_cinsn_t.pop_back
(self, *args)
return _idaapi.qlist_cinsn_t_pop_back(self, *args)
pop_back(self)
pop_back(self)
[ "pop_back", "(", "self", ")" ]
def pop_back(self, *args): """ pop_back(self) """ return _idaapi.qlist_cinsn_t_pop_back(self, *args)
[ "def", "pop_back", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "qlist_cinsn_t_pop_back", "(", "self", ",", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L34829-L34833
landlab/landlab
a5dd80b8ebfd03d1ba87ef6c4368c409485f222c
landlab/components/network_sediment_transporter/network_sediment_transporter.py
python
NetworkSedimentTransporter.run_one_step
(self, dt)
Run NetworkSedimentTransporter forward in time. When the NetworkSedimentTransporter runs forward in time the following steps occur: 1. A new set of records is created in the Parcels that corresponds to the new time 2. If parcels are on the network then: a. Active parcels are identifed based on entrainment critera. b. Effective bed slope is calculated based on inactive parcel volumes. c. Transport rate is calculated. d. Active parcels are moved based on the tranport rate. Parameters ---------- dt : float Duration of time to run the NetworkSedimentTransporter forward. Returns ------- RuntimeError if no parcels remain on the grid.
Run NetworkSedimentTransporter forward in time.
[ "Run", "NetworkSedimentTransporter", "forward", "in", "time", "." ]
def run_one_step(self, dt): """Run NetworkSedimentTransporter forward in time. When the NetworkSedimentTransporter runs forward in time the following steps occur: 1. A new set of records is created in the Parcels that corresponds to the new time 2. If parcels are on the network then: a. Active parcels are identifed based on entrainment critera. b. Effective bed slope is calculated based on inactive parcel volumes. c. Transport rate is calculated. d. Active parcels are moved based on the tranport rate. Parameters ---------- dt : float Duration of time to run the NetworkSedimentTransporter forward. Returns ------- RuntimeError if no parcels remain on the grid. """ self._time += dt self._time_idx += 1 self._create_new_parcel_time() if self._this_timesteps_parcels.any(): self._partition_active_and_storage_layers() self._adjust_node_elevation() self._update_channel_slopes() self._update_transport_time() self._move_parcel_downstream(dt) else: msg = "No more parcels on grid" raise RuntimeError(msg)
[ "def", "run_one_step", "(", "self", ",", "dt", ")", ":", "self", ".", "_time", "+=", "dt", "self", ".", "_time_idx", "+=", "1", "self", ".", "_create_new_parcel_time", "(", ")", "if", "self", ".", "_this_timesteps_parcels", ".", "any", "(", ")", ":", "...
https://github.com/landlab/landlab/blob/a5dd80b8ebfd03d1ba87ef6c4368c409485f222c/landlab/components/network_sediment_transporter/network_sediment_transporter.py#L964-L1000
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
singlestore/datadog_checks/singlestore/config_models/defaults.py
python
shared_service
(field, value)
return get_default_field_value(field, value)
[]
def shared_service(field, value): return get_default_field_value(field, value)
[ "def", "shared_service", "(", "field", ",", "value", ")", ":", "return", "get_default_field_value", "(", "field", ",", "value", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/singlestore/datadog_checks/singlestore/config_models/defaults.py#L17-L18
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
portia_examle/lib/python2.7/site-packages/pip/_vendor/distlib/database.py
python
BaseInstalledDistribution.__init__
(self, metadata, path, env=None)
Initialise an instance. :param metadata: An instance of :class:`Metadata` which describes the distribution. This will normally have been initialised from a metadata file in the ``path``. :param path: The path of the ``.dist-info`` or ``.egg-info`` directory for the distribution. :param env: This is normally the :class:`DistributionPath` instance where this distribution was found.
Initialise an instance. :param metadata: An instance of :class:`Metadata` which describes the distribution. This will normally have been initialised from a metadata file in the ``path``. :param path: The path of the ``.dist-info`` or ``.egg-info`` directory for the distribution. :param env: This is normally the :class:`DistributionPath` instance where this distribution was found.
[ "Initialise", "an", "instance", ".", ":", "param", "metadata", ":", "An", "instance", "of", ":", "class", ":", "Metadata", "which", "describes", "the", "distribution", ".", "This", "will", "normally", "have", "been", "initialised", "from", "a", "metadata", "...
def __init__(self, metadata, path, env=None): """ Initialise an instance. :param metadata: An instance of :class:`Metadata` which describes the distribution. This will normally have been initialised from a metadata file in the ``path``. :param path: The path of the ``.dist-info`` or ``.egg-info`` directory for the distribution. :param env: This is normally the :class:`DistributionPath` instance where this distribution was found. """ super(BaseInstalledDistribution, self).__init__(metadata) self.path = path self.dist_path = env
[ "def", "__init__", "(", "self", ",", "metadata", ",", "path", ",", "env", "=", "None", ")", ":", "super", "(", "BaseInstalledDistribution", ",", "self", ")", ".", "__init__", "(", "metadata", ")", "self", ".", "path", "=", "path", "self", ".", "dist_pa...
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/portia_examle/lib/python2.7/site-packages/pip/_vendor/distlib/database.py#L474-L487
psd-tools/psd-tools
00241f3aed2ca52a8012e198a0f390ff7d8edca9
src/psd_tools/api/psd_image.py
python
PSDImage.height
(self)
return self._record.header.height
Document height. :return: `int`
Document height.
[ "Document", "height", "." ]
def height(self): """ Document height. :return: `int` """ return self._record.header.height
[ "def", "height", "(", "self", ")", ":", "return", "self", ".", "_record", ".", "header", ".", "height" ]
https://github.com/psd-tools/psd-tools/blob/00241f3aed2ca52a8012e198a0f390ff7d8edca9/src/psd_tools/api/psd_image.py#L308-L314
felipecode/coiltraine
29060ab5fd2ea5531686e72c621aaaca3b23f4fb
drive/suites/corl_training_suite.py
python
CorlTraining.calculate_time_out
(self, path_distance)
return ((path_distance / 1000.0) / 5.0) * 3600.0 + 10.0
Function to return the timeout ,in milliseconds, that is calculated based on distance to goal. This is the same timeout as used on the CoRL paper.
Function to return the timeout ,in milliseconds, that is calculated based on distance to goal. This is the same timeout as used on the CoRL paper.
[ "Function", "to", "return", "the", "timeout", "in", "milliseconds", "that", "is", "calculated", "based", "on", "distance", "to", "goal", ".", "This", "is", "the", "same", "timeout", "as", "used", "on", "the", "CoRL", "paper", "." ]
def calculate_time_out(self, path_distance): """ Function to return the timeout ,in milliseconds, that is calculated based on distance to goal. This is the same timeout as used on the CoRL paper. """ return ((path_distance / 1000.0) / 5.0) * 3600.0 + 10.0
[ "def", "calculate_time_out", "(", "self", ",", "path_distance", ")", ":", "return", "(", "(", "path_distance", "/", "1000.0", ")", "/", "5.0", ")", "*", "3600.0", "+", "10.0" ]
https://github.com/felipecode/coiltraine/blob/29060ab5fd2ea5531686e72c621aaaca3b23f4fb/drive/suites/corl_training_suite.py#L36-L42
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/distutils/text_file.py
python
TextFile.__init__
(self, filename=None, file=None, **options)
Construct a new TextFile object. At least one of 'filename' (a string) and 'file' (a file-like object) must be supplied. They keyword argument options are described above and affect the values returned by 'readline()'.
Construct a new TextFile object. At least one of 'filename' (a string) and 'file' (a file-like object) must be supplied. They keyword argument options are described above and affect the values returned by 'readline()'.
[ "Construct", "a", "new", "TextFile", "object", ".", "At", "least", "one", "of", "filename", "(", "a", "string", ")", "and", "file", "(", "a", "file", "-", "like", "object", ")", "must", "be", "supplied", ".", "They", "keyword", "argument", "options", "...
def __init__ (self, filename=None, file=None, **options): """Construct a new TextFile object. At least one of 'filename' (a string) and 'file' (a file-like object) must be supplied. They keyword argument options are described above and affect the values returned by 'readline()'.""" if filename is None and file is None: raise RuntimeError, \ "you must supply either or both of 'filename' and 'file'" # set values for all options -- either from client option hash # or fallback to default_options for opt in self.default_options.keys(): if opt in options: setattr (self, opt, options[opt]) else: setattr (self, opt, self.default_options[opt]) # sanity check client option hash for opt in options.keys(): if opt not in self.default_options: raise KeyError, "invalid TextFile option '%s'" % opt if file is None: self.open (filename) else: self.filename = filename self.file = file self.current_line = 0 # assuming that file is at BOF! # 'linebuf' is a stack of lines that will be emptied before we # actually read from the file; it's only populated by an # 'unreadline()' operation self.linebuf = []
[ "def", "__init__", "(", "self", ",", "filename", "=", "None", ",", "file", "=", "None", ",", "*", "*", "options", ")", ":", "if", "filename", "is", "None", "and", "file", "is", "None", ":", "raise", "RuntimeError", ",", "\"you must supply either or both of...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/distutils/text_file.py#L78-L112
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/plat-mac/ic.py
python
_code_boolean
(data, key)
return chr(data)
[]
def _code_boolean(data, key): print 'XXXX boolean:', repr(data) return chr(data)
[ "def", "_code_boolean", "(", "data", ",", "key", ")", ":", "print", "'XXXX boolean:'", ",", "repr", "(", "data", ")", "return", "chr", "(", "data", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/plat-mac/ic.py#L99-L101
conda/conda
09cb6bdde68e551852c3844fd2b59c8ba4cafce2
conda/_vendor/tqdm/std.py
python
tqdm.reset
(self, total=None)
Resets to 0 iterations for repeated use. Consider combining with `leave=True`. Parameters ---------- total : int or float, optional. Total to use for the new bar.
Resets to 0 iterations for repeated use.
[ "Resets", "to", "0", "iterations", "for", "repeated", "use", "." ]
def reset(self, total=None): """ Resets to 0 iterations for repeated use. Consider combining with `leave=True`. Parameters ---------- total : int or float, optional. Total to use for the new bar. """ self.n = 0 if total is not None: self.total = total if self.disable: return self.last_print_n = 0 self.last_print_t = self.start_t = self._time() self._ema_dn = EMA(self.smoothing) self._ema_dt = EMA(self.smoothing) self._ema_miniters = EMA(self.smoothing) self.refresh()
[ "def", "reset", "(", "self", ",", "total", "=", "None", ")", ":", "self", ".", "n", "=", "0", "if", "total", "is", "not", "None", ":", "self", ".", "total", "=", "total", "if", "self", ".", "disable", ":", "return", "self", ".", "last_print_n", "...
https://github.com/conda/conda/blob/09cb6bdde68e551852c3844fd2b59c8ba4cafce2/conda/_vendor/tqdm/std.py#L1357-L1377
wuzheng-sjtu/FastFPN
a60a618665b11481e95bd184073a2ac09febc9d4
libs/datasets/pycocotools/coco.py
python
COCO.getCatIds
(self, catNms=[], supNms=[], catIds=[])
return ids
filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given cat ids :return: ids (int array) : integer array of cat ids
filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given cat ids :return: ids (int array) : integer array of cat ids
[ "filtering", "parameters", ".", "default", "skips", "that", "filter", ".", ":", "param", "catNms", "(", "str", "array", ")", ":", "get", "cats", "for", "given", "cat", "names", ":", "param", "supNms", "(", "str", "array", ")", ":", "get", "cats", "for"...
def getCatIds(self, catNms=[], supNms=[], catIds=[]): """ filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given cat ids :return: ids (int array) : integer array of cat ids """ catNms = catNms if type(catNms) == list else [catNms] supNms = supNms if type(supNms) == list else [supNms] catIds = catIds if type(catIds) == list else [catIds] if len(catNms) == len(supNms) == len(catIds) == 0: cats = self.dataset['categories'] else: cats = self.dataset['categories'] cats = cats if len(catNms) == 0 else [cat for cat in cats if cat['name'] in catNms] cats = cats if len(supNms) == 0 else [cat for cat in cats if cat['supercategory'] in supNms] cats = cats if len(catIds) == 0 else [cat for cat in cats if cat['id'] in catIds] ids = [cat['id'] for cat in cats] return ids
[ "def", "getCatIds", "(", "self", ",", "catNms", "=", "[", "]", ",", "supNms", "=", "[", "]", ",", "catIds", "=", "[", "]", ")", ":", "catNms", "=", "catNms", "if", "type", "(", "catNms", ")", "==", "list", "else", "[", "catNms", "]", "supNms", ...
https://github.com/wuzheng-sjtu/FastFPN/blob/a60a618665b11481e95bd184073a2ac09febc9d4/libs/datasets/pycocotools/coco.py#L152-L172
google/active-qa
bd96fab78255b8ef4f1147f78bd571abf2b919b3
px/selector/selector_keras.py
python
Selector.train
(self, questions, answers, scores)
return self.model.train_on_batch( x=[question_array, original_question_array, answer_array], y=train_labels_array_binary)
Train the model with the given data. Args: questions: A list of lists of questions. The first question is the original question and the others are generated by a Reformulator model. answers: A list of lists of answers to the questions given by the BiDAF model. scores: A list of lists of F1 scores for the answers given by the BiDAF model. Returns: A tuple containing the training loss and accuracy of the batch.
Train the model with the given data.
[ "Train", "the", "model", "with", "the", "given", "data", "." ]
def train(self, questions, answers, scores): """Train the model with the given data. Args: questions: A list of lists of questions. The first question is the original question and the others are generated by a Reformulator model. answers: A list of lists of answers to the questions given by the BiDAF model. scores: A list of lists of F1 scores for the answers given by the BiDAF model. Returns: A tuple containing the training loss and accuracy of the batch. """ (question_array, original_question_array, answer_array, train_labels) = self.encode_train(questions, answers, scores) train_labels_binary = (np.sign(train_labels) + 1) / 2 train_labels_array_binary = np.array(train_labels_binary) return self.model.train_on_batch( x=[question_array, original_question_array, answer_array], y=train_labels_array_binary)
[ "def", "train", "(", "self", ",", "questions", ",", "answers", ",", "scores", ")", ":", "(", "question_array", ",", "original_question_array", ",", "answer_array", ",", "train_labels", ")", "=", "self", ".", "encode_train", "(", "questions", ",", "answers", ...
https://github.com/google/active-qa/blob/bd96fab78255b8ef4f1147f78bd571abf2b919b3/px/selector/selector_keras.py#L231-L252
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/cffi/verifier.py
python
Verifier._load_library
(self)
[]
def _load_library(self): assert self._has_module if self.flags is not None: return self._vengine.load_library(self.flags) else: return self._vengine.load_library()
[ "def", "_load_library", "(", "self", ")", ":", "assert", "self", ".", "_has_module", "if", "self", ".", "flags", "is", "not", "None", ":", "return", "self", ".", "_vengine", ".", "load_library", "(", "self", ".", "flags", ")", "else", ":", "return", "s...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/cffi/verifier.py#L211-L216
Ecogenomics/CheckM
e79d420194f385c67d3b3710c6beadcdf710598a
checkm/fileEntity.py
python
FileEntity.getFullPath
(self)
get the full path to this entity
get the full path to this entity
[ "get", "the", "full", "path", "to", "this", "entity" ]
def getFullPath(self): """get the full path to this entity""" if self.parent == None: return "" else: return os.path.join(self.parent.getFullPath(), self.name)
[ "def", "getFullPath", "(", "self", ")", ":", "if", "self", ".", "parent", "==", "None", ":", "return", "\"\"", "else", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "parent", ".", "getFullPath", "(", ")", ",", "self", ".", "name"...
https://github.com/Ecogenomics/CheckM/blob/e79d420194f385c67d3b3710c6beadcdf710598a/checkm/fileEntity.py#L67-L72
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Tools/iobench/iobench.py
python
write_medium_chunks
(f, source)
write 4096 units at a time
write 4096 units at a time
[ "write", "4096", "units", "at", "a", "time" ]
def write_medium_chunks(f, source): """ write 4096 units at a time """ for i in xrange(0, len(source), 4096): f.write(source[i:i+4096])
[ "def", "write_medium_chunks", "(", "f", ",", "source", ")", ":", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "source", ")", ",", "4096", ")", ":", "f", ".", "write", "(", "source", "[", "i", ":", "i", "+", "4096", "]", ")" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Tools/iobench/iobench.py#L151-L154
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/inject/thirdparty/clientform/clientform.py
python
_AbstractFormParser._append_select_control
(self, attrs)
[]
def _append_select_control(self, attrs): debug("%s", attrs) controls = self._current_form[2] name = self._select.get("name") controls.append(("select", name, attrs))
[ "def", "_append_select_control", "(", "self", ",", "attrs", ")", ":", "debug", "(", "\"%s\"", ",", "attrs", ")", "controls", "=", "self", ".", "_current_form", "[", "2", "]", "name", "=", "self", ".", "_select", ".", "get", "(", "\"name\"", ")", "contr...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/clientform/clientform.py#L614-L618
numenta/nupic
b9ebedaf54f49a33de22d8d44dff7c765cdb5548
external/linux32/lib/python2.6/site-packages/matplotlib/pyparsing.py
python
ParseResults.pop
( self, index=-1 )
return ret
Removes and returns item at specified index (default=last). Will work with either numeric indices or dict-key indicies.
Removes and returns item at specified index (default=last). Will work with either numeric indices or dict-key indicies.
[ "Removes", "and", "returns", "item", "at", "specified", "index", "(", "default", "=", "last", ")", ".", "Will", "work", "with", "either", "numeric", "indices", "or", "dict", "-", "key", "indicies", "." ]
def pop( self, index=-1 ): """Removes and returns item at specified index (default=last). Will work with either numeric indices or dict-key indicies.""" ret = self[index] del self[index] return ret
[ "def", "pop", "(", "self", ",", "index", "=", "-", "1", ")", ":", "ret", "=", "self", "[", "index", "]", "del", "self", "[", "index", "]", "return", "ret" ]
https://github.com/numenta/nupic/blob/b9ebedaf54f49a33de22d8d44dff7c765cdb5548/external/linux32/lib/python2.6/site-packages/matplotlib/pyparsing.py#L355-L360
Karmenzind/fp-server
931fca8fab9d7397c52cf9e76a76b1c60e190403
src/service/tasks/spider.py
python
SpiderTasks.start_crawling
(self, key_and_spiders)
return deployed
trigger spiders :param key_and_spiders: [(key, spider_cls)] spiders to run :return: [key]
trigger spiders :param key_and_spiders: [(key, spider_cls)] spiders to run :return: [key]
[ "trigger", "spiders", ":", "param", "key_and_spiders", ":", "[", "(", "key", "spider_cls", ")", "]", "spiders", "to", "run", ":", "return", ":", "[", "key", "]" ]
async def start_crawling(self, key_and_spiders): """ trigger spiders :param key_and_spiders: [(key, spider_cls)] spiders to run :return: [key] """ deployed = [] for key, spider in key_and_spiders: await self.deploy_spider(key, spider) deployed.append(key) return deployed
[ "async", "def", "start_crawling", "(", "self", ",", "key_and_spiders", ")", ":", "deployed", "=", "[", "]", "for", "key", ",", "spider", "in", "key_and_spiders", ":", "await", "self", ".", "deploy_spider", "(", "key", ",", "spider", ")", "deployed", ".", ...
https://github.com/Karmenzind/fp-server/blob/931fca8fab9d7397c52cf9e76a76b1c60e190403/src/service/tasks/spider.py#L121-L133
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/decimal.py
python
Decimal.copy_abs
(self)
return _dec_from_triple(0, self._int, self._exp, self._is_special)
Returns a copy with the sign set to 0.
Returns a copy with the sign set to 0.
[ "Returns", "a", "copy", "with", "the", "sign", "set", "to", "0", "." ]
def copy_abs(self): """Returns a copy with the sign set to 0. """ return _dec_from_triple(0, self._int, self._exp, self._is_special)
[ "def", "copy_abs", "(", "self", ")", ":", "return", "_dec_from_triple", "(", "0", ",", "self", ".", "_int", ",", "self", ".", "_exp", ",", "self", ".", "_is_special", ")" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/decimal.py#L2887-L2889
david-abel/simple_rl
d8fe6007efb4840377f085a4e35ba89aaa2cdf6d
simple_rl/tasks/navigation/NavigationWorldMDP.py
python
NavigationWorldMDP.is_goal
(self, x, y)
return self.get_state_kind(x, y) == NavigationWorldMDP.CELL_KIND_GOAL
Checks if (x,y) cell is goal or not. Returns: (bool): True iff (x, y) is a goal location.
Checks if (x,y) cell is goal or not.
[ "Checks", "if", "(", "x", "y", ")", "cell", "is", "goal", "or", "not", "." ]
def is_goal(self, x, y): """Checks if (x,y) cell is goal or not. Returns: (bool): True iff (x, y) is a goal location. """ return self.get_state_kind(x, y) == NavigationWorldMDP.CELL_KIND_GOAL
[ "def", "is_goal", "(", "self", ",", "x", ",", "y", ")", ":", "return", "self", ".", "get_state_kind", "(", "x", ",", "y", ")", "==", "NavigationWorldMDP", ".", "CELL_KIND_GOAL" ]
https://github.com/david-abel/simple_rl/blob/d8fe6007efb4840377f085a4e35ba89aaa2cdf6d/simple_rl/tasks/navigation/NavigationWorldMDP.py#L358-L364
Ghirensics/ghiro
c9ff33b6ed16eb1cd960822b8031baf9b84a8636
api/common.py
python
api_authenticate
(api_key)
Authenticate users via API key. @param api_key: API key for authentication @return: authenticated user instance @raise: PermissionDenied if API key is not valid
Authenticate users via API key.
[ "Authenticate", "users", "via", "API", "key", "." ]
def api_authenticate(api_key): """Authenticate users via API key. @param api_key: API key for authentication @return: authenticated user instance @raise: PermissionDenied if API key is not valid """ if api_key: try: return Profile.objects.get(api_key=api_key) except ObjectDoesNotExist: raise PermissionDenied else: raise PermissionDenied
[ "def", "api_authenticate", "(", "api_key", ")", ":", "if", "api_key", ":", "try", ":", "return", "Profile", ".", "objects", ".", "get", "(", "api_key", "=", "api_key", ")", "except", "ObjectDoesNotExist", ":", "raise", "PermissionDenied", "else", ":", "raise...
https://github.com/Ghirensics/ghiro/blob/c9ff33b6ed16eb1cd960822b8031baf9b84a8636/api/common.py#L10-L22
ShichenLiu/CondenseNet
833a91d5f859df25579f70a2439dfd62f7fefb29
models/densenet.py
python
_Transition.__init__
(self, in_channels, out_channels, args)
[]
def __init__(self, in_channels, out_channels, args): super(_Transition, self).__init__() self.conv = Conv(in_channels, out_channels, kernel_size=1, groups=args.group_1x1) self.pool = nn.AvgPool2d(kernel_size=2, stride=2)
[ "def", "__init__", "(", "self", ",", "in_channels", ",", "out_channels", ",", "args", ")", ":", "super", "(", "_Transition", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "conv", "=", "Conv", "(", "in_channels", ",", "out_channels", ",", "k...
https://github.com/ShichenLiu/CondenseNet/blob/833a91d5f859df25579f70a2439dfd62f7fefb29/models/densenet.py#L48-L52
kaaedit/kaa
e6a8819a5ecba04b7db8303bd5736b5a7c9b822d
kaa/filetype/default/modebase.py
python
ModeBase.put_string
(self, wnd, s, overwrite=False)
[]
def put_string(self, wnd, s, overwrite=False): s = self.filter_string(wnd, s) if wnd.screen.selection.is_selected(): if wnd.screen.selection.is_rectangular(): if '\n' not in s: self.replace_rect(wnd, itertools.repeat(s)) else: self.replace_rect(wnd, s.split('\n')) else: sel = wnd.screen.selection.get_selrange() f, t = sel self.replace_string(wnd, f, t, s) else: if not overwrite: self.insert_string(wnd, wnd.cursor.pos, s) else: eol = wnd.document.get_line_to(wnd.cursor.pos) posto = min(wnd.cursor.pos + len(s), eol) self.replace_string(wnd, wnd.cursor.pos, posto, s)
[ "def", "put_string", "(", "self", ",", "wnd", ",", "s", ",", "overwrite", "=", "False", ")", ":", "s", "=", "self", ".", "filter_string", "(", "wnd", ",", "s", ")", "if", "wnd", ".", "screen", ".", "selection", ".", "is_selected", "(", ")", ":", ...
https://github.com/kaaedit/kaa/blob/e6a8819a5ecba04b7db8303bd5736b5a7c9b822d/kaa/filetype/default/modebase.py#L510-L530
mbj4668/pyang
97523476e7ada8609d27fd47880e1b5061073dc3
pyang/translators/schemanode.py
python
SchemaNode.rng_children
(self)
return [c for c in self.children if ":" not in c.name]
Return receiver's children that are not extensions.
Return receiver's children that are not extensions.
[ "Return", "receiver", "s", "children", "that", "are", "not", "extensions", "." ]
def rng_children(self): """Return receiver's children that are not extensions.""" return [c for c in self.children if ":" not in c.name]
[ "def", "rng_children", "(", "self", ")", ":", "return", "[", "c", "for", "c", "in", "self", ".", "children", "if", "\":\"", "not", "in", "c", ".", "name", "]" ]
https://github.com/mbj4668/pyang/blob/97523476e7ada8609d27fd47880e1b5061073dc3/pyang/translators/schemanode.py#L126-L128
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
src/outwiker/gui/searchreplacecontroller.py
python
SearchReplaceController._findPrev
(self, text, phrase)
return result
Найти предыдущее вхождение
Найти предыдущее вхождение
[ "Найти", "предыдущее", "вхождение" ]
def _findPrev(self, text, phrase): """ Найти предыдущее вхождение """ self._searcher.search(text, phrase) currpos = self.editor.GetSelectionStart() result = None for currResult in self._searcher.result: if currResult.position < currpos: result = currResult if result is None and len(self._searcher.result) > 0: result = self._searcher.result[-1] return result
[ "def", "_findPrev", "(", "self", ",", "text", ",", "phrase", ")", ":", "self", ".", "_searcher", ".", "search", "(", "text", ",", "phrase", ")", "currpos", "=", "self", ".", "editor", ".", "GetSelectionStart", "(", ")", "result", "=", "None", "for", ...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/gui/searchreplacecontroller.py#L199-L216
tensorflow/tensor2tensor
2a33b152d7835af66a6d20afe7961751047e28dd
tensor2tensor/models/research/moe_experiments.py
python
denoise_v1_m30
()
return hparams
More masking during training.
More masking during training.
[ "More", "masking", "during", "training", "." ]
def denoise_v1_m30(): """More masking during training.""" hparams = denoise_v1_m15() hparams.noising_spec_train = {"type": "mask", "prob": 0.3} return hparams
[ "def", "denoise_v1_m30", "(", ")", ":", "hparams", "=", "denoise_v1_m15", "(", ")", "hparams", ".", "noising_spec_train", "=", "{", "\"type\"", ":", "\"mask\"", ",", "\"prob\"", ":", "0.3", "}", "return", "hparams" ]
https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/models/research/moe_experiments.py#L516-L520
graalvm/mx
29c0debab406352df3af246be2f8973be5db69ae
mx.py
python
Dependency.defined_java_packages
(self)
return []
[]
def defined_java_packages(self): return []
[ "def", "defined_java_packages", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/graalvm/mx/blob/29c0debab406352df3af246be2f8973be5db69ae/mx.py#L1568-L1569
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/zj/v20190121/zj_client.py
python
ZjClient.DescribeMmsInstanceInfo
(self, request)
获取彩信实例信息 :param request: Request instance for DescribeMmsInstanceInfo. :type request: :class:`tencentcloud.zj.v20190121.models.DescribeMmsInstanceInfoRequest` :rtype: :class:`tencentcloud.zj.v20190121.models.DescribeMmsInstanceInfoResponse`
获取彩信实例信息
[ "获取彩信实例信息" ]
def DescribeMmsInstanceInfo(self, request): """获取彩信实例信息 :param request: Request instance for DescribeMmsInstanceInfo. :type request: :class:`tencentcloud.zj.v20190121.models.DescribeMmsInstanceInfoRequest` :rtype: :class:`tencentcloud.zj.v20190121.models.DescribeMmsInstanceInfoResponse` """ try: params = request._serialize() body = self.call("DescribeMmsInstanceInfo", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeMmsInstanceInfoResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DescribeMmsInstanceInfo", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DescribeMmsInstanceInfo\"", ",", "params", ")", "response", "=", "json", "...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/zj/v20190121/zj_client.py#L281-L306
jwlodek/py_cui
bc2de6a30cfc894348306531db94d7edbdbf17f3
py_cui/ui.py
python
TextBlockImplementation.get_viewport_start_pos
(self)
return self._viewport_x_start, self._viewport_y_start
Gets upper left corner position of viewport Returns ------- viewport_x_start, viewport_y_start : int Initial location of viewport relative to text
Gets upper left corner position of viewport
[ "Gets", "upper", "left", "corner", "position", "of", "viewport" ]
def get_viewport_start_pos(self) -> Tuple[int,int]: """Gets upper left corner position of viewport Returns ------- viewport_x_start, viewport_y_start : int Initial location of viewport relative to text """ return self._viewport_x_start, self._viewport_y_start
[ "def", "get_viewport_start_pos", "(", "self", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "return", "self", ".", "_viewport_x_start", ",", "self", ".", "_viewport_y_start" ]
https://github.com/jwlodek/py_cui/blob/bc2de6a30cfc894348306531db94d7edbdbf17f3/py_cui/ui.py#L1082-L1091
cournape/Bento
37de23d784407a7c98a4a15770ffc570d5f32d70
bento/core/node.py
python
Node.abspath
(self)
return val
absolute path cache into the build context, cache_node_abspath
absolute path cache into the build context, cache_node_abspath
[ "absolute", "path", "cache", "into", "the", "build", "context", "cache_node_abspath" ]
def abspath(self): """ absolute path cache into the build context, cache_node_abspath """ try: return self.cache_abspath except: pass # think twice before touching this (performance + complexity + correctness) if not self.parent: val = os.sep == '/' and os.sep or '' elif not self.parent.name: # drive letter for win32 val = (os.sep == '/' and os.sep or '') + self.name else: val = self.parent.abspath() + os.sep + self.name self.cache_abspath = val return val
[ "def", "abspath", "(", "self", ")", ":", "try", ":", "return", "self", ".", "cache_abspath", "except", ":", "pass", "# think twice before touching this (performance + complexity + correctness)", "if", "not", "self", ".", "parent", ":", "val", "=", "os", ".", "sep"...
https://github.com/cournape/Bento/blob/37de23d784407a7c98a4a15770ffc570d5f32d70/bento/core/node.py#L313-L332
aws/aws-parallelcluster
f1fe5679a01c524e7ea904c329bd6d17318c6cd9
cli/src/pcluster/schemas/cluster_schema.py
python
SchedulerPluginClusterInfrastructureSchema.make_resource
(self, data, **kwargs)
return SchedulerPluginClusterInfrastructure(**data)
Generate resource.
Generate resource.
[ "Generate", "resource", "." ]
def make_resource(self, data, **kwargs): """Generate resource.""" return SchedulerPluginClusterInfrastructure(**data)
[ "def", "make_resource", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "return", "SchedulerPluginClusterInfrastructure", "(", "*", "*", "data", ")" ]
https://github.com/aws/aws-parallelcluster/blob/f1fe5679a01c524e7ea904c329bd6d17318c6cd9/cli/src/pcluster/schemas/cluster_schema.py#L1268-L1270
GoogleCloudPlatform/webapp2
deb34447ef8927c940bed2d80c7eec75f9f01be8
webapp2.py
python
Response._get_status_message
(self)
return self.status.split(' ', 1)[1]
The response status message, as a string.
The response status message, as a string.
[ "The", "response", "status", "message", "as", "a", "string", "." ]
def _get_status_message(self): """The response status message, as a string.""" return self.status.split(' ', 1)[1]
[ "def", "_get_status_message", "(", "self", ")", ":", "return", "self", ".", "status", ".", "split", "(", "' '", ",", "1", ")", "[", "1", "]" ]
https://github.com/GoogleCloudPlatform/webapp2/blob/deb34447ef8927c940bed2d80c7eec75f9f01be8/webapp2.py#L473-L475
pypa/setuptools
9f37366aab9cd8f6baa23e6a77cfdb8daf97757e
setuptools/_distutils/command/install.py
python
install.has_headers
(self)
return self.distribution.has_headers()
Returns true if the current distribution has any headers to install.
Returns true if the current distribution has any headers to install.
[ "Returns", "true", "if", "the", "current", "distribution", "has", "any", "headers", "to", "install", "." ]
def has_headers(self): """Returns true if the current distribution has any headers to install.""" return self.distribution.has_headers()
[ "def", "has_headers", "(", "self", ")", ":", "return", "self", ".", "distribution", ".", "has_headers", "(", ")" ]
https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_distutils/command/install.py#L753-L756
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
scripts/monitoring/cron-send-logging-checks.py
python
OpenshiftLoggingStatus.run
(self)
Main function that runs the check
Main function that runs the check
[ "Main", "function", "that", "runs", "the", "check" ]
def run(self): ''' Main function that runs the check ''' self.parse_args() self.metric_sender = MetricSender(verbose=self.args.verbose, debug=self.args.debug) self.oc = OCUtil(namespace=self.get_logging_namespace(), config_file='/tmp/admin.kubeconfig', verbose=self.args.verbose) self.get_pods() logging_status = {} script_failed = 0 # everything fine try: logging_status['elasticsearch'] = self.check_elasticsearch() logging_status['fluentd'] = self.check_fluentd() logging_status['kibana'] = self.check_kibana() self.report_to_zabbix(logging_status) except: script_failed = 1 # something wrong mts = MetricSender(verbose=self.args.verbose) mts.add_metric({'openshift.master.logging.elasticsearch.script.status': script_failed}) mts.send_metrics()
[ "def", "run", "(", "self", ")", ":", "self", ".", "parse_args", "(", ")", "self", ".", "metric_sender", "=", "MetricSender", "(", "verbose", "=", "self", ".", "args", ".", "verbose", ",", "debug", "=", "self", ".", "args", ".", "debug", ")", "self", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/scripts/monitoring/cron-send-logging-checks.py#L339-L358
wanggrun/Adaptively-Connected-Neural-Networks
e27066ef52301bdafa5932f43af8feeb23647edb
tensorpack-installed/tensorpack/callbacks/param.py
python
GraphVarParam.get_value
(self)
return self.var.eval()
Evaluate the variable.
Evaluate the variable.
[ "Evaluate", "the", "variable", "." ]
def get_value(self): """ Evaluate the variable. """ return self.var.eval()
[ "def", "get_value", "(", "self", ")", ":", "return", "self", ".", "var", ".", "eval", "(", ")" ]
https://github.com/wanggrun/Adaptively-Connected-Neural-Networks/blob/e27066ef52301bdafa5932f43af8feeb23647edb/tensorpack-installed/tensorpack/callbacks/param.py#L81-L83
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/PopGen/GenePop/Controller.py
python
GenePopController.test_pop_hz_prob
( self, fname, ext, enum_test=False, dememorization=10000, batches=20, iterations=5000, )
return ( _FileIterator(hw_prob_loci_func, fname + ".P"), _FileIterator(hw_prob_pop_func, fname + ".P2"), )
Use Hardy-Weinberg test based on probability. Returns 2 iterators and a final tuple: 1. Returns a loci iterator containing: - A dictionary[pop_pos]=(P-val, SE, Fis-WC, Fis-RH, steps). Some pops have a None if the info is not available. SE might be none (for enumerations). - Result of Fisher's test (Chi2, deg freedom, prob). 2. Returns a population iterator containing: - A dictionary[locus]=(P-val, SE, Fis-WC, Fis-RH, steps). Some loci have a None if the info is not available. SE might be none (for enumerations). - Result of Fisher's test (Chi2, deg freedom, prob). 3. Final tuple (Chi2, deg freedom, prob).
Use Hardy-Weinberg test based on probability.
[ "Use", "Hardy", "-", "Weinberg", "test", "based", "on", "probability", "." ]
def test_pop_hz_prob( self, fname, ext, enum_test=False, dememorization=10000, batches=20, iterations=5000, ): """Use Hardy-Weinberg test based on probability. Returns 2 iterators and a final tuple: 1. Returns a loci iterator containing: - A dictionary[pop_pos]=(P-val, SE, Fis-WC, Fis-RH, steps). Some pops have a None if the info is not available. SE might be none (for enumerations). - Result of Fisher's test (Chi2, deg freedom, prob). 2. Returns a population iterator containing: - A dictionary[locus]=(P-val, SE, Fis-WC, Fis-RH, steps). Some loci have a None if the info is not available. SE might be none (for enumerations). - Result of Fisher's test (Chi2, deg freedom, prob). 3. Final tuple (Chi2, deg freedom, prob). """ opts = self._get_opts(dememorization, batches, iterations, enum_test) self._run_genepop([ext], [1, 3], fname, opts) def hw_prob_loci_func(self): return _hw_func(self.stream, True, True) def hw_prob_pop_func(self): return _hw_func(self.stream, False, True) shutil.copyfile(fname + ".P", fname + ".P2") return ( _FileIterator(hw_prob_loci_func, fname + ".P"), _FileIterator(hw_prob_pop_func, fname + ".P2"), )
[ "def", "test_pop_hz_prob", "(", "self", ",", "fname", ",", "ext", ",", "enum_test", "=", "False", ",", "dememorization", "=", "10000", ",", "batches", "=", "20", ",", "iterations", "=", "5000", ",", ")", ":", "opts", "=", "self", ".", "_get_opts", "(",...
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/PopGen/GenePop/Controller.py#L353-L393
optuna/optuna
2c44c1a405ba059efd53f4b9c8e849d20fb95c0a
optuna/pruners/_nop.py
python
NopPruner.prune
(self, study: "optuna.study.Study", trial: "optuna.trial.FrozenTrial")
return False
[]
def prune(self, study: "optuna.study.Study", trial: "optuna.trial.FrozenTrial") -> bool: return False
[ "def", "prune", "(", "self", ",", "study", ":", "\"optuna.study.Study\"", ",", "trial", ":", "\"optuna.trial.FrozenTrial\"", ")", "->", "bool", ":", "return", "False" ]
https://github.com/optuna/optuna/blob/2c44c1a405ba059efd53f4b9c8e849d20fb95c0a/optuna/pruners/_nop.py#L46-L48
mps-youtube/mps-youtube
4c6ee0f8f4643fc1308e637b622d0337bf9bce1b
mps_youtube/commands/search.py
python
pl_search
(term, page=0, splash=True, is_user=False)
Search for YouTube playlists. term can be query str or dict indicating user playlist search.
Search for YouTube playlists.
[ "Search", "for", "YouTube", "playlists", "." ]
def pl_search(term, page=0, splash=True, is_user=False): """ Search for YouTube playlists. term can be query str or dict indicating user playlist search. """ if not term or len(term) < 2: g.message = c.r + "Not enough input" + c.w g.content = content.generate_songlist_display() return if splash: g.content = content.logo(c.g) prog = "user: " + term if is_user else term g.message = "Searching playlists for %s" % c.y + prog + c.w screen.update() if is_user: ret = channelfromname(term) if not ret: # Error return user, channel_id = ret else: # playlist search is done with the above url and param type=playlist logging.info("playlist search for %s", prog) qs = generate_search_qs(term) qs['pageToken'] = token(page) qs['type'] = 'playlist' if 'videoCategoryId' in qs: del qs['videoCategoryId'] # Incompatable with type=playlist pldata = pafy.call_gdata('search', qs) id_list = [i.get('id', {}).get('playlistId') for i in pldata.get('items', ()) if i['id']['kind'] == 'youtube#playlist'] result_count = min(pldata['pageInfo']['totalResults'], 500) qs = {'part': 'contentDetails,snippet', 'maxResults': 50} if is_user: if page: qs['pageToken'] = token(page) qs['channelId'] = channel_id else: qs['id'] = ','.join(id_list) pldata = pafy.call_gdata('playlists', qs) playlists = get_pl_from_json(pldata)[:util.getxy().max_results] if is_user: result_count = pldata['pageInfo']['totalResults'] if playlists: g.last_search_query = (pl_search, {"term": term, "is_user": is_user}) g.browse_mode = "ytpl" g.current_page = page g.result_count = result_count g.ytpls = playlists g.message = "Playlist results for %s" % c.y + prog + c.w g.content = content.generate_playlist_display() else: g.message = "No playlists found for: %s" % c.y + prog + c.w g.current_page = 0 g.content = content.generate_songlist_display(zeromsg=g.message)
[ "def", "pl_search", "(", "term", ",", "page", "=", "0", ",", "splash", "=", "True", ",", "is_user", "=", "False", ")", ":", "if", "not", "term", "or", "len", "(", "term", ")", "<", "2", ":", "g", ".", "message", "=", "c", ".", "r", "+", "\"No...
https://github.com/mps-youtube/mps-youtube/blob/4c6ee0f8f4643fc1308e637b622d0337bf9bce1b/mps_youtube/commands/search.py#L327-L395
exodrifter/unity-python
bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d
Lib/telnetlib.py
python
Telnet._expect_with_poll
(self, expect_list, timeout=None)
return (-1, None, text)
Read until one from a list of a regular expressions matches. This method uses select.poll() to implement the timeout.
Read until one from a list of a regular expressions matches.
[ "Read", "until", "one", "from", "a", "list", "of", "a", "regular", "expressions", "matches", "." ]
def _expect_with_poll(self, expect_list, timeout=None): """Read until one from a list of a regular expressions matches. This method uses select.poll() to implement the timeout. """ re = None expect_list = expect_list[:] indices = range(len(expect_list)) for i in indices: if not hasattr(expect_list[i], "search"): if not re: import re expect_list[i] = re.compile(expect_list[i]) call_timeout = timeout if timeout is not None: from time import time time_start = time() self.process_rawq() m = None for i in indices: m = expect_list[i].search(self.cookedq) if m: e = m.end() text = self.cookedq[:e] self.cookedq = self.cookedq[e:] break if not m: poller = select.poll() poll_in_or_priority_flags = select.POLLIN | select.POLLPRI poller.register(self, poll_in_or_priority_flags) while not m and not self.eof: try: ready = poller.poll(None if timeout is None else 1000 * call_timeout) except select.error as e: if e[0] == errno.EINTR: if timeout is not None: elapsed = time() - time_start call_timeout = timeout-elapsed continue raise for fd, mode in ready: if mode & poll_in_or_priority_flags: self.fill_rawq() self.process_rawq() for i in indices: m = expect_list[i].search(self.cookedq) if m: e = m.end() text = self.cookedq[:e] self.cookedq = self.cookedq[e:] break if timeout is not None: elapsed = time() - time_start if elapsed >= timeout: break call_timeout = timeout-elapsed poller.unregister(self) if m: return (i, m, text) text = self.read_very_lazy() if not text and self.eof: raise EOFError return (-1, None, text)
[ "def", "_expect_with_poll", "(", "self", ",", "expect_list", ",", "timeout", "=", "None", ")", ":", "re", "=", "None", "expect_list", "=", "expect_list", "[", ":", "]", "indices", "=", "range", "(", "len", "(", "expect_list", ")", ")", "for", "i", "in"...
https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/telnetlib.py#L657-L719
jacobian/django-googlecharts
c542996cf9a7a097b447e1ce5a1a6b66bdad254f
googlecharts/templatetags/charts.py
python
sparkline
(data, size="100x30", color=_chart_color)
return '<img src="http://chart.apis.google.com/chart?\ cht=lc&\ chs=100x30&\ chd=e:%s&\ chco=%s&\ chls=1,1,0&\ chm=o,990000,0,%s,4&\ chxt=r,x,y&\ chxs=0,990000,11,0,_|1,990000,1,0,_|2,990000,1,0,_&\ chxl=0:|%s|1:||2:||&\ chxp=0,%s\ " alt="" />' % (encoded_data, color, len(data), data[-1], 100*(float(data[-1])/(maxvalue-minvalue)))
[]
def sparkline(data, size="100x30", color=_chart_color): maxvalue = max(data) minvalue = min(data) datarange = (minvalue, maxvalue) encoded_data = encode_extended(data,datarange) return '<img src="http://chart.apis.google.com/chart?\ cht=lc&\ chs=100x30&\ chd=e:%s&\ chco=%s&\ chls=1,1,0&\ chm=o,990000,0,%s,4&\ chxt=r,x,y&\ chxs=0,990000,11,0,_|1,990000,1,0,_|2,990000,1,0,_&\ chxl=0:|%s|1:||2:||&\ chxp=0,%s\ " alt="" />' % (encoded_data, color, len(data), data[-1], 100*(float(data[-1])/(maxvalue-minvalue)))
[ "def", "sparkline", "(", "data", ",", "size", "=", "\"100x30\"", ",", "color", "=", "_chart_color", ")", ":", "maxvalue", "=", "max", "(", "data", ")", "minvalue", "=", "min", "(", "data", ")", "datarange", "=", "(", "minvalue", ",", "maxvalue", ")", ...
https://github.com/jacobian/django-googlecharts/blob/c542996cf9a7a097b447e1ce5a1a6b66bdad254f/googlecharts/templatetags/charts.py#L42-L59
francisck/DanderSpritz_docs
86bb7caca5a957147f120b18bb5c31f299914904
Python/Core/Lib/collections.py
python
Counter.__init__
(self, iterable=None, **kwds)
Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args
Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args
[ "Create", "a", "new", "empty", "Counter", "object", ".", "And", "if", "given", "count", "elements", "from", "an", "input", "iterable", ".", "Or", "initialize", "the", "count", "from", "another", "mapping", "of", "elements", "to", "their", "counts", ".", ">...
def __init__(self, iterable=None, **kwds): """Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args """ super(Counter, self).__init__() self.update(iterable, **kwds)
[ "def", "__init__", "(", "self", ",", "iterable", "=", "None", ",", "*", "*", "kwds", ")", ":", "super", "(", "Counter", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "update", "(", "iterable", ",", "*", "*", "kwds", ")" ]
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/collections.py#L339-L351
meetbill/zabbix_manager
739e5b51facf19cc6bda2b50f29108f831cf833e
ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/Row.py
python
Row.get_cells_count
(self)
return len(self.__cells)
[]
def get_cells_count(self): return len(self.__cells)
[ "def", "get_cells_count", "(", "self", ")", ":", "return", "len", "(", "self", ".", "__cells", ")" ]
https://github.com/meetbill/zabbix_manager/blob/739e5b51facf19cc6bda2b50f29108f831cf833e/ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/Row.py#L126-L127
bigmlcom/python
35f69d2f3121f1b3dde43495cf145d4992796ad5
bigml/fusion.py
python
Fusion.dump
(self, output=None, cache_set=None)
Uses msgpack to serialize the resource object If cache_set is filled with a cache set method, the method is called
Uses msgpack to serialize the resource object If cache_set is filled with a cache set method, the method is called
[ "Uses", "msgpack", "to", "serialize", "the", "resource", "object", "If", "cache_set", "is", "filled", "with", "a", "cache", "set", "method", "the", "method", "is", "called" ]
def dump(self, output=None, cache_set=None): """Uses msgpack to serialize the resource object If cache_set is filled with a cache set method, the method is called """ self_vars = vars(self) del self_vars["api"] dump(self_vars, output=output, cache_set=cache_set)
[ "def", "dump", "(", "self", ",", "output", "=", "None", ",", "cache_set", "=", "None", ")", ":", "self_vars", "=", "vars", "(", "self", ")", "del", "self_vars", "[", "\"api\"", "]", "dump", "(", "self_vars", ",", "output", "=", "output", ",", "cache_...
https://github.com/bigmlcom/python/blob/35f69d2f3121f1b3dde43495cf145d4992796ad5/bigml/fusion.py#L492-L499
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Tools/pybench/pybench.py
python
Benchmark.print_comparison
(self, compare_to, hidenoise=0, limitnames=None)
[]
def print_comparison(self, compare_to, hidenoise=0, limitnames=None): # Check benchmark versions if compare_to.version != self.version: print ('* Benchmark versions differ: ' 'cannot compare this benchmark to "%s" !' % compare_to.name) print self.print_benchmark(hidenoise=hidenoise, limitnames=limitnames) return # Print header compare_to.print_header('Comparing with') print ('Test ' ' minimum run-time average run-time') print (' ' ' this other diff this other diff') print '-' * LINE # Print test comparisons tests = self.tests.items() tests.sort() total_min_time = other_total_min_time = 0.0 total_avg_time = other_total_avg_time = 0.0 benchmarks_compatible = self.compatible(compare_to) tests_compatible = 1 for name, test in tests: if (limitnames is not None and limitnames.search(name) is None): continue (min_time, avg_time, total_time, op_avg, min_overhead) = test.stat() total_min_time = total_min_time + min_time total_avg_time = total_avg_time + avg_time try: other = compare_to.tests[name] except KeyError: other = None if other is None: # Other benchmark doesn't include the given test min_diff, avg_diff = 'n/a', 'n/a' other_min_time = 0.0 other_avg_time = 0.0 tests_compatible = 0 else: (other_min_time, other_avg_time, other_total_time, other_op_avg, other_min_overhead) = other.stat() other_total_min_time = other_total_min_time + other_min_time other_total_avg_time = other_total_avg_time + other_avg_time if (benchmarks_compatible and test.compatible(other)): # Both benchmark and tests are comparable min_diff = ((min_time * self.warp) / (other_min_time * other.warp) - 1.0) avg_diff = ((avg_time * self.warp) / (other_avg_time * other.warp) - 1.0) if hidenoise and abs(min_diff) < 10.0: min_diff = '' else: min_diff = '%+5.1f%%' % (min_diff * PERCENT) if hidenoise and abs(avg_diff) < 10.0: avg_diff = '' else: avg_diff = '%+5.1f%%' % (avg_diff * PERCENT) else: # Benchmark or tests are not comparable min_diff, avg_diff = 'n/a', 'n/a' tests_compatible = 0 print '%30s: %5.0fms %5.0fms %7s %5.0fms %5.0fms %7s' % \ (name, min_time * MILLI_SECONDS, other_min_time * MILLI_SECONDS * compare_to.warp / self.warp, min_diff, avg_time * MILLI_SECONDS, other_avg_time * MILLI_SECONDS * compare_to.warp / self.warp, avg_diff) print '-' * LINE # Summarise test results if not benchmarks_compatible or not tests_compatible: min_diff, avg_diff = 'n/a', 'n/a' else: if other_total_min_time != 0.0: min_diff = '%+5.1f%%' % ( ((total_min_time * self.warp) / (other_total_min_time * compare_to.warp) - 1.0) * PERCENT) else: min_diff = 'n/a' if other_total_avg_time != 0.0: avg_diff = '%+5.1f%%' % ( ((total_avg_time * self.warp) / (other_total_avg_time * compare_to.warp) - 1.0) * PERCENT) else: avg_diff = 'n/a' print ('Totals: ' ' %5.0fms %5.0fms %7s %5.0fms %5.0fms %7s' % (total_min_time * MILLI_SECONDS, (other_total_min_time * compare_to.warp/self.warp * MILLI_SECONDS), min_diff, total_avg_time * MILLI_SECONDS, (other_total_avg_time * compare_to.warp/self.warp * MILLI_SECONDS), avg_diff )) print print '(this=%s, other=%s)' % (self.name, compare_to.name) print
[ "def", "print_comparison", "(", "self", ",", "compare_to", ",", "hidenoise", "=", "0", ",", "limitnames", "=", "None", ")", ":", "# Check benchmark versions", "if", "compare_to", ".", "version", "!=", "self", ".", "version", ":", "print", "(", "'* Benchmark ve...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Tools/pybench/pybench.py#L634-L749
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/number_field/class_group.py
python
SClassGroup.S
(self)
return self._S
r""" Return the set (or rather tuple) of primes used to define this class group. EXAMPLES:: sage: K.<a> = QuadraticField(-14) sage: I = K.ideal(2,a) sage: S = (I,) sage: CS = K.S_class_group(S);CS S-class group of order 2 with structure C2 of Number Field in a with defining polynomial x^2 + 14 with a = 3.741657386773942?*I sage: T = tuple([]) sage: CT = K.S_class_group(T);CT S-class group of order 4 with structure C4 of Number Field in a with defining polynomial x^2 + 14 with a = 3.741657386773942?*I sage: CS.S() (Fractional ideal (2, a),) sage: CT.S() ()
r""" Return the set (or rather tuple) of primes used to define this class group.
[ "r", "Return", "the", "set", "(", "or", "rather", "tuple", ")", "of", "primes", "used", "to", "define", "this", "class", "group", "." ]
def S(self): r""" Return the set (or rather tuple) of primes used to define this class group. EXAMPLES:: sage: K.<a> = QuadraticField(-14) sage: I = K.ideal(2,a) sage: S = (I,) sage: CS = K.S_class_group(S);CS S-class group of order 2 with structure C2 of Number Field in a with defining polynomial x^2 + 14 with a = 3.741657386773942?*I sage: T = tuple([]) sage: CT = K.S_class_group(T);CT S-class group of order 4 with structure C4 of Number Field in a with defining polynomial x^2 + 14 with a = 3.741657386773942?*I sage: CS.S() (Fractional ideal (2, a),) sage: CT.S() () """ return self._S
[ "def", "S", "(", "self", ")", ":", "return", "self", ".", "_S" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/number_field/class_group.py#L665-L684
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py
python
ParserElement.setWhitespaceChars
( self, chars )
return self
Overrides the default whitespace chars
Overrides the default whitespace chars
[ "Overrides", "the", "default", "whitespace", "chars" ]
def setWhitespaceChars( self, chars ): """ Overrides the default whitespace chars """ self.skipWhitespace = True self.whiteChars = chars self.copyDefaultWhiteChars = False return self
[ "def", "setWhitespaceChars", "(", "self", ",", "chars", ")", ":", "self", ".", "skipWhitespace", "=", "True", "self", ".", "whiteChars", "=", "chars", "self", ".", "copyDefaultWhiteChars", "=", "False", "return", "self" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py#L2020-L2027
NervanaSystems/ngraph-python
ac032c83c7152b615a9ad129d54d350f9d6a2986
ngraph/frontends/cntk/cntk_importer/ops_compound.py
python
OpsCompound.MaxPooling
(self, cntk_op, inputs)
return self._block_op_import(cntk_op, inputs, self._pooling_op)
Import MaxPooling operation block. Arguments: cntk_op: CNTK block to be imported. inputs: List of inputs to this node. Returns: A ngraph Op.
Import MaxPooling operation block.
[ "Import", "MaxPooling", "operation", "block", "." ]
def MaxPooling(self, cntk_op, inputs): """ Import MaxPooling operation block. Arguments: cntk_op: CNTK block to be imported. inputs: List of inputs to this node. Returns: A ngraph Op. """ return self._block_op_import(cntk_op, inputs, self._pooling_op)
[ "def", "MaxPooling", "(", "self", ",", "cntk_op", ",", "inputs", ")", ":", "return", "self", ".", "_block_op_import", "(", "cntk_op", ",", "inputs", ",", "self", ".", "_pooling_op", ")" ]
https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/frontends/cntk/cntk_importer/ops_compound.py#L458-L469
opendatacube/datacube-core
b062184be61c140a168de94510bc3661748f112e
datacube/drivers/postgres/_fields.py
python
DateDocField.day
(self)
return NativeField( '{}_day'.format(self.name), 'Day of {}'.format(self.description), self.alchemy_column, alchemy_expression=cast(func.date_trunc('day', self.alchemy_expression), postgres.TIMESTAMP) )
Get field truncated to the day
Get field truncated to the day
[ "Get", "field", "truncated", "to", "the", "day" ]
def day(self): """Get field truncated to the day""" return NativeField( '{}_day'.format(self.name), 'Day of {}'.format(self.description), self.alchemy_column, alchemy_expression=cast(func.date_trunc('day', self.alchemy_expression), postgres.TIMESTAMP) )
[ "def", "day", "(", "self", ")", ":", "return", "NativeField", "(", "'{}_day'", ".", "format", "(", "self", ".", "name", ")", ",", "'Day of {}'", ".", "format", "(", "self", ".", "description", ")", ",", "self", ".", "alchemy_column", ",", "alchemy_expres...
https://github.com/opendatacube/datacube-core/blob/b062184be61c140a168de94510bc3661748f112e/datacube/drivers/postgres/_fields.py#L278-L285
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_vendor/html5lib/_trie/py.py
python
Trie.__iter__
(self)
return iter(self._data)
[]
def __iter__(self): return iter(self._data)
[ "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "_data", ")" ]
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/html5lib/_trie/py.py#L25-L26
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/posixpath.py
python
basename
(p)
return p[i:]
Returns the final component of a pathname
Returns the final component of a pathname
[ "Returns", "the", "final", "component", "of", "a", "pathname" ]
def basename(p): """Returns the final component of a pathname""" p = os.fspath(p) sep = _get_sep(p) i = p.rfind(sep) + 1 return p[i:]
[ "def", "basename", "(", "p", ")", ":", "p", "=", "os", ".", "fspath", "(", "p", ")", "sep", "=", "_get_sep", "(", "p", ")", "i", "=", "p", ".", "rfind", "(", "sep", ")", "+", "1", "return", "p", "[", "i", ":", "]" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/posixpath.py#L142-L147
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
stock2/ctp/__init__.py
python
TraderApi.OnRspQryInvestor
(self, pInvestor, pRspInfo, nRequestID, bIsLast)
请求查询投资者响应
请求查询投资者响应
[ "请求查询投资者响应" ]
def OnRspQryInvestor(self, pInvestor, pRspInfo, nRequestID, bIsLast): """请求查询投资者响应"""
[ "def", "OnRspQryInvestor", "(", "self", ",", "pInvestor", ",", "pRspInfo", ",", "nRequestID", ",", "bIsLast", ")", ":" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/stock2/ctp/__init__.py#L292-L293
achael/eht-imaging
bbd3aeb06bef52bf89fa1c06de71e5509a5b0015
ehtim/parloop.py
python
Parloop.prog_msg
(self, i, n, i_last=0)
Print a progress bar
Print a progress bar
[ "Print", "a", "progress", "bar" ]
def prog_msg(self, i, n, i_last=0): """Print a progress bar """ # complete_percent_last = int(100*float(i_last)/float(n)) complete_percent = int(100*float(i)/float(n)) ndigit = str(len(str(n))) bar_width = 30 progress = int(bar_width * complete_percent/float(100)) barparams = (i, n, ("-"*progress) + (" " * (bar_width-progress)), complete_percent) printstr = "\rProcessed %0"+ndigit+"i/%i : [%s]%i%%" sys.stdout.write(printstr % barparams) sys.stdout.flush()
[ "def", "prog_msg", "(", "self", ",", "i", ",", "n", ",", "i_last", "=", "0", ")", ":", "# complete_percent_last = int(100*float(i_last)/float(n))", "complete_percent", "=", "int", "(", "100", "*", "float", "(", "i", ")", "/", "float", "(", "n", ")", ")", ...
https://github.com/achael/eht-imaging/blob/bbd3aeb06bef52bf89fa1c06de71e5509a5b0015/ehtim/parloop.py#L111-L125
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/reformer/modeling_reformer.py
python
ReformerOnlyLMHead.__init__
(self, config)
[]
def __init__(self, config): super().__init__() # Reformer is using Rev Nets, thus last layer outputs are concatenated and # Layer Norm is done over 2 * hidden_size self.seq_len_dim = 1 self.chunk_size_lm_head = config.chunk_size_lm_head self.decoder = nn.Linear(2 * config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) self.decoder.bias = self.bias
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "# Reformer is using Rev Nets, thus last layer outputs are concatenated and", "# Layer Norm is done over 2 * hidden_size", "self", ".", "seq_len_dim", "=", "1", "self", ...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/reformer/modeling_reformer.py#L1742-L1750
brendano/tweetmotif
1b0b1e3a941745cd5a26eba01f554688b7c4b27e
everything_else/djfrontend/django-1.0.2/core/cache/backends/base.py
python
BaseCache.add
(self, key, value, timeout=None)
Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Returns True if the value was stored, False otherwise.
Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
[ "Set", "a", "value", "in", "the", "cache", "if", "the", "key", "does", "not", "already", "exist", ".", "If", "timeout", "is", "given", "that", "timeout", "will", "be", "used", "for", "the", "key", ";", "otherwise", "the", "default", "cache", "timeout", ...
def add(self, key, value, timeout=None): """ Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Returns True if the value was stored, False otherwise. """ raise NotImplementedError
[ "def", "add", "(", "self", ",", "key", ",", "value", ",", "timeout", "=", "None", ")", ":", "raise", "NotImplementedError" ]
https://github.com/brendano/tweetmotif/blob/1b0b1e3a941745cd5a26eba01f554688b7c4b27e/everything_else/djfrontend/django-1.0.2/core/cache/backends/base.py#L17-L25
kirthevasank/nasbot
3c745dc986be30e3721087c8fa768099032a0802
gp/gp_core.py
python
GPFitter._tuning_objective
(self, gp_hyperparams)
return ret
This function computes the tuning objective (such as the marginal likelihood) which is to be maximised in fit_gp.
This function computes the tuning objective (such as the marginal likelihood) which is to be maximised in fit_gp.
[ "This", "function", "computes", "the", "tuning", "objective", "(", "such", "as", "the", "marginal", "likelihood", ")", "which", "is", "to", "be", "maximised", "in", "fit_gp", "." ]
def _tuning_objective(self, gp_hyperparams): """ This function computes the tuning objective (such as the marginal likelihood) which is to be maximised in fit_gp. """ built_gp = self.build_gp(gp_hyperparams) if self.options.hp_tune_criterion in ['ml', 'marginal_likelihood']: ret = built_gp.compute_log_marginal_likelihood() elif self.options.hp_tune_criterion in ['cv', 'cross_validation']: raise NotImplementedError('Yet to implement cross validation based hp-tuning.') else: raise ValueError('hp_tune_criterion should be either ml or cv') return ret
[ "def", "_tuning_objective", "(", "self", ",", "gp_hyperparams", ")", ":", "built_gp", "=", "self", ".", "build_gp", "(", "gp_hyperparams", ")", "if", "self", ".", "options", ".", "hp_tune_criterion", "in", "[", "'ml'", ",", "'marginal_likelihood'", "]", ":", ...
https://github.com/kirthevasank/nasbot/blob/3c745dc986be30e3721087c8fa768099032a0802/gp/gp_core.py#L350-L360
paramiko/paramiko
88f35a537428e430f7f26eee8026715e357b55d6
paramiko/sftp_si.py
python
SFTPServerInterface.session_ended
(self)
The SFTP server session has just ended, either cleanly or via an exception. This method is meant to be overridden to perform any necessary cleanup before this `.SFTPServerInterface` object is destroyed.
The SFTP server session has just ended, either cleanly or via an exception. This method is meant to be overridden to perform any necessary cleanup before this `.SFTPServerInterface` object is destroyed.
[ "The", "SFTP", "server", "session", "has", "just", "ended", "either", "cleanly", "or", "via", "an", "exception", ".", "This", "method", "is", "meant", "to", "be", "overridden", "to", "perform", "any", "necessary", "cleanup", "before", "this", ".", "SFTPServe...
def session_ended(self): """ The SFTP server session has just ended, either cleanly or via an exception. This method is meant to be overridden to perform any necessary cleanup before this `.SFTPServerInterface` object is destroyed. """ pass
[ "def", "session_ended", "(", "self", ")", ":", "pass" ]
https://github.com/paramiko/paramiko/blob/88f35a537428e430f7f26eee8026715e357b55d6/paramiko/sftp_si.py#L61-L68
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/tvdbapiv2/models/episode.py
python
Episode.to_dict
(self)
return result
Returns the model properties as a dict
Returns the model properties as a dict
[ "Returns", "the", "model", "properties", "as", "a", "dict" ]
def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() else: result[attr] = value return result
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "attr", ",", "_", "in", "iteritems", "(", "self", ".", "swagger_types", ")", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "isinstance", "(", "value", ","...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/tvdbapiv2/models/episode.py#L774-L792
scikit-hep/awkward-0.x
dd885bef15814f588b58944d2505296df4aaae0e
awkward0/array/virtual.py
python
VirtualArray._reduce
(self, ufunc, identity, dtype)
return self._util_reduce(self.array, ufunc, identity, dtype)
[]
def _reduce(self, ufunc, identity, dtype): return self._util_reduce(self.array, ufunc, identity, dtype)
[ "def", "_reduce", "(", "self", ",", "ufunc", ",", "identity", ",", "dtype", ")", ":", "return", "self", ".", "_util_reduce", "(", "self", ".", "array", ",", "ufunc", ",", "identity", ",", "dtype", ")" ]
https://github.com/scikit-hep/awkward-0.x/blob/dd885bef15814f588b58944d2505296df4aaae0e/awkward0/array/virtual.py#L451-L452
GoogleCloudPlatform/datastore-ndb-python
cf4cab3f1f69cd04e1a9229871be466b53729f3f
ndb/model.py
python
Model._reset_kind_map
(cls)
Clear the kind map. Useful for testing.
Clear the kind map. Useful for testing.
[ "Clear", "the", "kind", "map", ".", "Useful", "for", "testing", "." ]
def _reset_kind_map(cls): """Clear the kind map. Useful for testing.""" # Preserve "system" kinds, like __namespace__ keep = {} for name, value in cls._kind_map.iteritems(): if name.startswith('__') and name.endswith('__'): keep[name] = value cls._kind_map.clear() cls._kind_map.update(keep)
[ "def", "_reset_kind_map", "(", "cls", ")", ":", "# Preserve \"system\" kinds, like __namespace__", "keep", "=", "{", "}", "for", "name", ",", "value", "in", "cls", ".", "_kind_map", ".", "iteritems", "(", ")", ":", "if", "name", ".", "startswith", "(", "'__'...
https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3074-L3082
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/rsk.py
python
RuleSuperRSK.to_pairs
(self, obj1=None, obj2=None, check=True)
return zip(obj1, obj2)
r""" Given a valid input for the super RSK algorithm, such as two `n`-tuples ``obj1`` `= [a_1, a_2, \ldots, a_n]` and ``obj2`` `= [b_1, b_2, \ldots, b_n]` forming a restricted super biword (i.e., entries with even and odd parity and no repetition of corresponding pairs with mixed parity entries) return the array `[(a_1, b_1), (a_2, b_2), \ldots, (a_n, b_n)]`. INPUT: - ``obj1, obj2`` -- anything representing a restricted super biword (see the doc of :meth:`forward_rule` for the encodings accepted) - ``check`` -- (default: ``True``) whether to check that ``obj1`` and ``obj2`` actually define a valid restricted super biword EXAMPLES:: sage: from sage.combinat.rsk import RuleSuperRSK sage: list(RuleSuperRSK().to_pairs([2, '1p', 1],[1, 1, '1p'])) [(2, 1), (1', 1), (1, 1')] sage: list(RuleSuperRSK().to_pairs([1, '1p', '2p'])) [(1', 1), (1, 1'), (2', 2')] sage: list(RuleSuperRSK().to_pairs([1, 1], ['1p', '1p'])) Traceback (most recent call last): ... ValueError: invalid restricted superbiword
r""" Given a valid input for the super RSK algorithm, such as two `n`-tuples ``obj1`` `= [a_1, a_2, \ldots, a_n]` and ``obj2`` `= [b_1, b_2, \ldots, b_n]` forming a restricted super biword (i.e., entries with even and odd parity and no repetition of corresponding pairs with mixed parity entries) return the array `[(a_1, b_1), (a_2, b_2), \ldots, (a_n, b_n)]`.
[ "r", "Given", "a", "valid", "input", "for", "the", "super", "RSK", "algorithm", "such", "as", "two", "n", "-", "tuples", "obj1", "=", "[", "a_1", "a_2", "\\", "ldots", "a_n", "]", "and", "obj2", "=", "[", "b_1", "b_2", "\\", "ldots", "b_n", "]", ...
def to_pairs(self, obj1=None, obj2=None, check=True): r""" Given a valid input for the super RSK algorithm, such as two `n`-tuples ``obj1`` `= [a_1, a_2, \ldots, a_n]` and ``obj2`` `= [b_1, b_2, \ldots, b_n]` forming a restricted super biword (i.e., entries with even and odd parity and no repetition of corresponding pairs with mixed parity entries) return the array `[(a_1, b_1), (a_2, b_2), \ldots, (a_n, b_n)]`. INPUT: - ``obj1, obj2`` -- anything representing a restricted super biword (see the doc of :meth:`forward_rule` for the encodings accepted) - ``check`` -- (default: ``True``) whether to check that ``obj1`` and ``obj2`` actually define a valid restricted super biword EXAMPLES:: sage: from sage.combinat.rsk import RuleSuperRSK sage: list(RuleSuperRSK().to_pairs([2, '1p', 1],[1, 1, '1p'])) [(2, 1), (1', 1), (1, 1')] sage: list(RuleSuperRSK().to_pairs([1, '1p', '2p'])) [(1', 1), (1, 1'), (2', 2')] sage: list(RuleSuperRSK().to_pairs([1, 1], ['1p', '1p'])) Traceback (most recent call last): ... ValueError: invalid restricted superbiword """ from sage.combinat.shifted_primed_tableau import PrimedEntry # Initializing itr for itr = None case itr = None if obj2 is None: try: itr = obj1._rsk_iter() except AttributeError: # set recording list (obj1) to default value [1', 1, 2', 2, ...] obj2, obj1 = obj1, [] a = ZZ.one() / ZZ(2) for i in range(len(obj2)): obj1.append(a) a = a + ZZ.one() / ZZ(2) else: if check: if len(obj1) != len(obj2): raise ValueError("the two arrays must be the same length") mixed_parity = [] # Check it is a restricted superbiword: that is, # the entries can have even or odd parity, but repetition of # the pairs of corresponding entries of obj1 # and obj2 with mixed-parity is not allowed for t, b in zip(obj1, obj2): if PrimedEntry(t).is_primed() != PrimedEntry(b).is_primed(): if (t, b) in mixed_parity: raise ValueError("invalid restricted superbiword") else: mixed_parity.append((t, b)) # Since the _rsk_iter() gives unprimed entries # We will create obj1 and obj2 from it. if itr: obj1, obj2 = [], [] for i, j in itr: obj1.append(i) obj2.append(j) # Converting entries of obj1 and obj2 to PrimedEntry for i in range(len(obj1)): obj1[i] = PrimedEntry(obj1[i]) obj2[i] = PrimedEntry(obj2[i]) return zip(obj1, obj2)
[ "def", "to_pairs", "(", "self", ",", "obj1", "=", "None", ",", "obj2", "=", "None", ",", "check", "=", "True", ")", ":", "from", "sage", ".", "combinat", ".", "shifted_primed_tableau", "import", "PrimedEntry", "# Initializing itr for itr = None case", "itr", "...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/rsk.py#L2012-L2082
SHI-Labs/Decoupled-Classification-Refinement
16202b48eb9cbf79a9b130a98e8c209d4f24693e
faster_rcnn/core/metric.py
python
RCNNLogLossMetric.update
(self, labels, preds)
[]
def update(self, labels, preds): pred = preds[self.pred.index('rcnn_cls_prob')] if self.ohem or self.e2e: label = preds[self.pred.index('rcnn_label')] else: label = labels[self.label.index('rcnn_label')] last_dim = pred.shape[-1] pred = pred.asnumpy().reshape(-1, last_dim) label = label.asnumpy().reshape(-1,).astype('int32') # filter with keep_inds keep_inds = np.where(label != -1)[0] label = label[keep_inds] cls = pred[keep_inds, label] cls += 1e-14 cls_loss = -1 * np.log(cls) cls_loss = np.sum(cls_loss) self.sum_metric += cls_loss self.num_inst += label.shape[0]
[ "def", "update", "(", "self", ",", "labels", ",", "preds", ")", ":", "pred", "=", "preds", "[", "self", ".", "pred", ".", "index", "(", "'rcnn_cls_prob'", ")", "]", "if", "self", ".", "ohem", "or", "self", ".", "e2e", ":", "label", "=", "preds", ...
https://github.com/SHI-Labs/Decoupled-Classification-Refinement/blob/16202b48eb9cbf79a9b130a98e8c209d4f24693e/faster_rcnn/core/metric.py#L121-L141
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/Toggl-Time-Tracking/alp/request/bs4/element.py
python
Tag.clear
(self, decompose=False)
Extract all children. If decompose is True, decompose instead.
Extract all children. If decompose is True, decompose instead.
[ "Extract", "all", "children", ".", "If", "decompose", "is", "True", "decompose", "instead", "." ]
def clear(self, decompose=False): """ Extract all children. If decompose is True, decompose instead. """ if decompose: for element in self.contents[:]: if isinstance(element, Tag): element.decompose() else: element.extract() else: for element in self.contents[:]: element.extract()
[ "def", "clear", "(", "self", ",", "decompose", "=", "False", ")", ":", "if", "decompose", ":", "for", "element", "in", "self", ".", "contents", "[", ":", "]", ":", "if", "isinstance", "(", "element", ",", "Tag", ")", ":", "element", ".", "decompose",...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/Toggl-Time-Tracking/alp/request/bs4/element.py#L840-L852
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/api/search/search.py
python
Cursor.__init__
(self, web_safe_string=None, per_result=False)
Initializer. Args: web_safe_string: The cursor string returned from the search service to be interpreted by the search service to get the next set of results. per_result: A bool when true will return a cursor per ScoredDocument in SearchResults, otherwise will return a single cursor for the whole SearchResults. If using offset this is ignored, as the user is responsible for calculating a next offset if any. Raises: ValueError: if the web_safe_string is not of required format.
Initializer.
[ "Initializer", "." ]
def __init__(self, web_safe_string=None, per_result=False): """Initializer. Args: web_safe_string: The cursor string returned from the search service to be interpreted by the search service to get the next set of results. per_result: A bool when true will return a cursor per ScoredDocument in SearchResults, otherwise will return a single cursor for the whole SearchResults. If using offset this is ignored, as the user is responsible for calculating a next offset if any. Raises: ValueError: if the web_safe_string is not of required format. """ self._web_safe_string = _CheckCursor(_ConvertToUnicode(web_safe_string)) self._per_result = per_result if self._web_safe_string: parts = self._web_safe_string.split(':', 1) if len(parts) != 2 or parts[0] not in ['True', 'False']: raise ValueError('invalid format for web_safe_string, got %s' % self._web_safe_string) self._internal_cursor = parts[1] self._per_result = (parts[0] == 'True')
[ "def", "__init__", "(", "self", ",", "web_safe_string", "=", "None", ",", "per_result", "=", "False", ")", ":", "self", ".", "_web_safe_string", "=", "_CheckCursor", "(", "_ConvertToUnicode", "(", "web_safe_string", ")", ")", "self", ".", "_per_result", "=", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/search/search.py#L2468-L2491
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/utils/schedule.py
python
clean_proc_dir
(opts)
Loop through jid files in the minion proc directory (default /var/cache/salt/minion/proc) and remove any that refer to processes that no longer exist
Loop through jid files in the minion proc directory (default /var/cache/salt/minion/proc) and remove any that refer to processes that no longer exist
[ "Loop", "through", "jid", "files", "in", "the", "minion", "proc", "directory", "(", "default", "/", "var", "/", "cache", "/", "salt", "/", "minion", "/", "proc", ")", "and", "remove", "any", "that", "refer", "to", "processes", "that", "no", "longer", "...
def clean_proc_dir(opts): """ Loop through jid files in the minion proc directory (default /var/cache/salt/minion/proc) and remove any that refer to processes that no longer exist """ for basefilename in os.listdir(salt.minion.get_proc_dir(opts["cachedir"])): fn_ = os.path.join(salt.minion.get_proc_dir(opts["cachedir"]), basefilename) with salt.utils.files.fopen(fn_, "rb") as fp_: job = None try: job = salt.payload.load(fp_) except Exception: # pylint: disable=broad-except # It's corrupted # Windows cannot delete an open file if salt.utils.platform.is_windows(): fp_.close() try: os.unlink(fn_) continue except OSError: continue log.debug( "schedule.clean_proc_dir: checking job %s for process existence", job ) if job is not None and "pid" in job: if salt.utils.process.os_is_running(job["pid"]): log.debug( "schedule.clean_proc_dir: Cleaning proc dir, pid %s " "still exists.", job["pid"], ) else: # Windows cannot delete an open file if salt.utils.platform.is_windows(): fp_.close() # Maybe the file is already gone try: os.unlink(fn_) except OSError: pass
[ "def", "clean_proc_dir", "(", "opts", ")", ":", "for", "basefilename", "in", "os", ".", "listdir", "(", "salt", ".", "minion", ".", "get_proc_dir", "(", "opts", "[", "\"cachedir\"", "]", ")", ")", ":", "fn_", "=", "os", ".", "path", ".", "join", "(",...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/utils/schedule.py#L1839-L1880
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/locale.py
python
_parse_localename
(localename)
Parses the locale code for localename and returns the result as tuple (language code, encoding). The localename is normalized and passed through the locale alias engine. A ValueError is raised in case the locale name cannot be parsed. The language code corresponds to RFC 1766. code and encoding can be None in case the values cannot be determined or are unknown to this implementation.
Parses the locale code for localename and returns the result as tuple (language code, encoding).
[ "Parses", "the", "locale", "code", "for", "localename", "and", "returns", "the", "result", "as", "tuple", "(", "language", "code", "encoding", ")", "." ]
def _parse_localename(localename): """ Parses the locale code for localename and returns the result as tuple (language code, encoding). The localename is normalized and passed through the locale alias engine. A ValueError is raised in case the locale name cannot be parsed. The language code corresponds to RFC 1766. code and encoding can be None in case the values cannot be determined or are unknown to this implementation. """ code = normalize(localename) if '@' in code: # Deal with locale modifiers code, modifier = code.split('@') if modifier == 'euro' and '.' not in code: # Assume Latin-9 for @euro locales. This is bogus, # since some systems may use other encodings for these # locales. Also, we ignore other modifiers. return code, 'iso-8859-15' if '.' in code: return tuple(code.split('.')[:2]) elif code == 'C': return None, None raise ValueError, 'unknown locale: %s' % localename
[ "def", "_parse_localename", "(", "localename", ")", ":", "code", "=", "normalize", "(", "localename", ")", "if", "'@'", "in", "code", ":", "# Deal with locale modifiers", "code", ",", "modifier", "=", "code", ".", "split", "(", "'@'", ")", "if", "modifier", ...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/locale.py#L400-L428
XuezheMax/flowseq
8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b
flownmt/nnet/attention.py
python
PositionwiseFeedForward.__init__
(self, features, hidden_features, dropout=0.0)
[]
def __init__(self, features, hidden_features, dropout=0.0): super(PositionwiseFeedForward, self).__init__() self.linear1 = nn.Linear(features, hidden_features) self.dropout = dropout self.linear2 = nn.Linear(hidden_features, features) self.layer_norm = LayerNorm(features)
[ "def", "__init__", "(", "self", ",", "features", ",", "hidden_features", ",", "dropout", "=", "0.0", ")", ":", "super", "(", "PositionwiseFeedForward", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "linear1", "=", "nn", ".", "Linear", "(", ...
https://github.com/XuezheMax/flowseq/blob/8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b/flownmt/nnet/attention.py#L236-L241
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/jc-weather/requests/packages/urllib3/filepost.py
python
encode_multipart_formdata
(fields, boundary=None)
return body.getvalue(), content_type
Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, value) or (key, value, MIME type) field tuples. The key is treated as the field name, and the value as the body of the form-data bytes. If the value is a tuple of two elements, then the first element is treated as the filename of the form-data section and a suitable MIME type is guessed based on the filename. If the value is a tuple of three elements, then the third element is treated as an explicit MIME type of the form-data section. Field names and filenames must be unicode. :param boundary: If not specified, then a random boundary will be generated using :func:`mimetools.choose_boundary`.
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
[ "Encode", "a", "dictionary", "of", "fields", "using", "the", "multipart", "/", "form", "-", "data", "MIME", "format", "." ]
def encode_multipart_formdata(fields, boundary=None): """ Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, value) or (key, value, MIME type) field tuples. The key is treated as the field name, and the value as the body of the form-data bytes. If the value is a tuple of two elements, then the first element is treated as the filename of the form-data section and a suitable MIME type is guessed based on the filename. If the value is a tuple of three elements, then the third element is treated as an explicit MIME type of the form-data section. Field names and filenames must be unicode. :param boundary: If not specified, then a random boundary will be generated using :func:`mimetools.choose_boundary`. """ body = BytesIO() if boundary is None: boundary = choose_boundary() for fieldname, value in iter_fields(fields): body.write(b('--%s\r\n' % (boundary))) if isinstance(value, tuple): if len(value) == 3: filename, data, content_type = value else: filename, data = value content_type = get_content_type(filename) writer(body).write('Content-Disposition: form-data; name="%s"; ' 'filename="%s"\r\n' % (fieldname, filename)) body.write(b('Content-Type: %s\r\n\r\n' % (content_type,))) else: data = value writer(body).write('Content-Disposition: form-data; name="%s"\r\n' % (fieldname)) body.write(b'\r\n') if isinstance(data, int): data = str(data) # Backwards compatibility if isinstance(data, six.text_type): writer(body).write(data) else: body.write(data) body.write(b'\r\n') body.write(b('--%s--\r\n' % (boundary))) content_type = b('multipart/form-data; boundary=%s' % boundary) return body.getvalue(), content_type
[ "def", "encode_multipart_formdata", "(", "fields", ",", "boundary", "=", "None", ")", ":", "body", "=", "BytesIO", "(", ")", "if", "boundary", "is", "None", ":", "boundary", "=", "choose_boundary", "(", ")", "for", "fieldname", ",", "value", "in", "iter_fi...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/jc-weather/requests/packages/urllib3/filepost.py#L42-L98
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/distlib/_backport/tarfile.py
python
ExFileObject.read
(self, size=None)
return buf
Read at most size bytes from the file. If size is not present or None, read all data until EOF is reached.
Read at most size bytes from the file. If size is not present or None, read all data until EOF is reached.
[ "Read", "at", "most", "size", "bytes", "from", "the", "file", ".", "If", "size", "is", "not", "present", "or", "None", "read", "all", "data", "until", "EOF", "is", "reached", "." ]
def read(self, size=None): """Read at most size bytes from the file. If size is not present or None, read all data until EOF is reached. """ if self.closed: raise ValueError("I/O operation on closed file") buf = b"" if self.buffer: if size is None: buf = self.buffer self.buffer = b"" else: buf = self.buffer[:size] self.buffer = self.buffer[size:] if size is None: buf += self.fileobj.read() else: buf += self.fileobj.read(size - len(buf)) self.position += len(buf) return buf
[ "def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "\"I/O operation on closed file\"", ")", "buf", "=", "b\"\"", "if", "self", ".", "buffer", ":", "if", "size", "is", "None", ":...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/distlib/_backport/tarfile.py#L810-L832
tanghaibao/jcvi
5e720870c0928996f8b77a38208106ff0447ccb6
jcvi/apps/phylo.py
python
draw
(args)
%prog draw --input newicktrees [options] Draw phylogenetic trees into single or combined plots. Input trees should be one of the following: 1. single Newick format tree file 2. a dir containing *ONLY* the tree files to be drawn Newick format: http://evolution.genetics.washington.edu/phylip/newicktree.html This function wraps on jcvi.graphics.tree This function is better used for trees generated by jcvi.apps.phylo (rooted if possible). For drawing general Newick trees from external sources invoke jcvi.graphics.tree directly, which also gives more drawing options.
%prog draw --input newicktrees [options]
[ "%prog", "draw", "--", "input", "newicktrees", "[", "options", "]" ]
def draw(args): """ %prog draw --input newicktrees [options] Draw phylogenetic trees into single or combined plots. Input trees should be one of the following: 1. single Newick format tree file 2. a dir containing *ONLY* the tree files to be drawn Newick format: http://evolution.genetics.washington.edu/phylip/newicktree.html This function wraps on jcvi.graphics.tree This function is better used for trees generated by jcvi.apps.phylo (rooted if possible). For drawing general Newick trees from external sources invoke jcvi.graphics.tree directly, which also gives more drawing options. """ trunc_name_options = ["headn", "oheadn", "tailn", "otailn"] p = OptionParser(draw.__doc__) p.add_option( "--input", help="path to single input tree file or a dir " "containing ONLY the input tree files", ) p.add_option( "--combine", type="string", default="1x1", help="combine multiple trees into one plot in nrowxncol", ) p.add_option( "--trunc_name", default=None, help="Options are: {0}. " "truncate first n chars, retains only first n chars, " "truncate last n chars, retain only last chars. " "n=1~99.".format(trunc_name_options), ) p.add_option( "--SH", default=None, help="path to a file containing SH test p-values in format:" "tree_file_name<tab>p-values " "This file can be generated with jcvi.apps.phylo build", ) p.add_option( "--scutoff", default=50, type="int", help="cutoff for displaying node support, 0-100", ) p.add_option( "--barcode", default=None, help="path to seq/taxon name barcode mapping file: " "barcode<tab>new_name " "This option is downstream of `--trunc_name`", ) p.add_option( "--leafcolorfile", default=None, help="path to a mapping file containing font colors " "for the OTUs: leafname<tab>color", ) p.set_outdir() opts, args, iopts = p.set_image_options(figsize="8x6") input = opts.input outdir = opts.outdir combine = opts.combine.split("x") trunc_name = opts.trunc_name SH = opts.SH mkdir(outdir) if not input: sys.exit(not p.print_help()) elif op.isfile(input): trees_file = input treenames = [op.basename(input)] elif op.isdir(input): trees_file = op.join(outdir, "alltrees.dnd") treenames = [] for f in sorted(os.listdir(input)): sh("cat {0}/{1} >> {2}".format(input, f, trees_file), log=False) treenames.append(f) else: sys.exit(not p.print_help()) trees = OrderedDict() tree = "" i = 0 for row in LineFile(trees_file, comment="#", load=True).lines: if i == len(treenames): break if not len(row): continue if ";" in row: # sanity check if row.index(";") != len(row) - 1: ts = row.split(";") for ii in range(len(ts) - 1): ts[ii] += ";" else: ts = [row] for t in ts: if ";" in t: tree += t if tree: trees[treenames[i]] = tree tree = "" i += 1 else: tree += t else: tree += row logging.debug("A total of {0} trees imported.".format(len(trees))) sh("rm {0}".format(op.join(outdir, "alltrees.dnd"))) _draw_trees( trees, nrow=int(combine[0]), ncol=int(combine[1]), rmargin=0.3, iopts=iopts, outdir=outdir, shfile=SH, trunc_name=trunc_name, scutoff=opts.scutoff, barcodefile=opts.barcode, leafcolorfile=opts.leafcolorfile, )
[ "def", "draw", "(", "args", ")", ":", "trunc_name_options", "=", "[", "\"headn\"", ",", "\"oheadn\"", ",", "\"tailn\"", ",", "\"otailn\"", "]", "p", "=", "OptionParser", "(", "draw", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--input\"", ",", "...
https://github.com/tanghaibao/jcvi/blob/5e720870c0928996f8b77a38208106ff0447ccb6/jcvi/apps/phylo.py#L1069-L1200
donnemartin/saws
bddc553237e692cbe220d94144592843b25e4a92
saws/resources.py
python
AwsResources.__init__
(self, log_exception)
Initializes AwsResources. Args: * log_exception: A callable log_exception from SawsLogger. Returns: None.
Initializes AwsResources.
[ "Initializes", "AwsResources", "." ]
def __init__(self, log_exception): """Initializes AwsResources. Args: * log_exception: A callable log_exception from SawsLogger. Returns: None. """ # TODO: Use a file version instead of a new file self._set_resources_path('data/RESOURCES_v2.txt') self.log_exception = log_exception self.resource_lists = self._create_resource_lists() self.resources_headers_map = None self.resources_options_map = None self.resource_headers = self._get_resource_headers() self.resource_options = self._get_resource_options() self.data_util = DataUtil() self.header_to_type_map = self.data_util.create_header_to_type_map( headers=self.resource_headers, data_type=self.ResourceType)
[ "def", "__init__", "(", "self", ",", "log_exception", ")", ":", "# TODO: Use a file version instead of a new file", "self", ".", "_set_resources_path", "(", "'data/RESOURCES_v2.txt'", ")", "self", ".", "log_exception", "=", "log_exception", "self", ".", "resource_lists", ...
https://github.com/donnemartin/saws/blob/bddc553237e692cbe220d94144592843b25e4a92/saws/resources.py#L72-L93
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/mail/imap4.py
python
IMAP4Server.opt_datetime
(self, line)
Optional date-time string
Optional date-time string
[ "Optional", "date", "-", "time", "string" ]
def opt_datetime(self, line): """ Optional date-time string """ if line.startswith('"'): try: spam, date, rest = line.split('"',2) except IndexError: raise IllegalClientResponse("Malformed date-time") return (date, rest[1:]) else: return (None, line)
[ "def", "opt_datetime", "(", "self", ",", "line", ")", ":", "if", "line", ".", "startswith", "(", "'\"'", ")", ":", "try", ":", "spam", ",", "date", ",", "rest", "=", "line", ".", "split", "(", "'\"'", ",", "2", ")", "except", "IndexError", ":", "...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/mail/imap4.py#L850-L861
google/apitools
31cad2d904f356872d2965687e84b2d87ee2cdd3
apitools/base/protorpclite/messages.py
python
find_definition
(name, relative_to=None, importer=__import__)
Find definition by name in module-space. The find algorthm will look for definitions by name relative to a message definition or by fully qualfied name. If no definition is found relative to the relative_to parameter it will do the same search against the container of relative_to. If relative_to is a nested Message, it will search its message_definition(). If that message has no message_definition() it will search its module. If relative_to is a module, it will attempt to look for the containing module and search relative to it. If the module is a top-level module, it will look for the a message using a fully qualified name. If no message is found then, the search fails and DefinitionNotFoundError is raised. For example, when looking for any definition 'foo.bar.ADefinition' relative to an actual message definition abc.xyz.SomeMessage: find_definition('foo.bar.ADefinition', SomeMessage) It is like looking for the following fully qualified names: abc.xyz.SomeMessage. foo.bar.ADefinition abc.xyz. foo.bar.ADefinition abc. foo.bar.ADefinition foo.bar.ADefinition When resolving the name relative to Message definitions and modules, the algorithm searches any Messages or sub-modules found in its path. Non-Message values are not searched. A name that begins with '.' is considered to be a fully qualified name. The name is always searched for from the topmost package. For example, assume two message types: abc.xyz.SomeMessage xyz.SomeMessage Searching for '.xyz.SomeMessage' relative to 'abc' will resolve to 'xyz.SomeMessage' and not 'abc.xyz.SomeMessage'. For this kind of name, the relative_to parameter is effectively ignored and always set to None. For more information about package name resolution, please see: http://code.google.com/apis/protocolbuffers/docs/proto.html#packages Args: name: Name of definition to find. May be fully qualified or relative name. relative_to: Search for definition relative to message definition or module. None will cause a fully qualified name search. importer: Import function to use for resolving modules. Returns: Enum or Message class definition associated with name. Raises: DefinitionNotFoundError if no definition is found in any search path.
Find definition by name in module-space.
[ "Find", "definition", "by", "name", "in", "module", "-", "space", "." ]
def find_definition(name, relative_to=None, importer=__import__): """Find definition by name in module-space. The find algorthm will look for definitions by name relative to a message definition or by fully qualfied name. If no definition is found relative to the relative_to parameter it will do the same search against the container of relative_to. If relative_to is a nested Message, it will search its message_definition(). If that message has no message_definition() it will search its module. If relative_to is a module, it will attempt to look for the containing module and search relative to it. If the module is a top-level module, it will look for the a message using a fully qualified name. If no message is found then, the search fails and DefinitionNotFoundError is raised. For example, when looking for any definition 'foo.bar.ADefinition' relative to an actual message definition abc.xyz.SomeMessage: find_definition('foo.bar.ADefinition', SomeMessage) It is like looking for the following fully qualified names: abc.xyz.SomeMessage. foo.bar.ADefinition abc.xyz. foo.bar.ADefinition abc. foo.bar.ADefinition foo.bar.ADefinition When resolving the name relative to Message definitions and modules, the algorithm searches any Messages or sub-modules found in its path. Non-Message values are not searched. A name that begins with '.' is considered to be a fully qualified name. The name is always searched for from the topmost package. For example, assume two message types: abc.xyz.SomeMessage xyz.SomeMessage Searching for '.xyz.SomeMessage' relative to 'abc' will resolve to 'xyz.SomeMessage' and not 'abc.xyz.SomeMessage'. For this kind of name, the relative_to parameter is effectively ignored and always set to None. For more information about package name resolution, please see: http://code.google.com/apis/protocolbuffers/docs/proto.html#packages Args: name: Name of definition to find. May be fully qualified or relative name. relative_to: Search for definition relative to message definition or module. None will cause a fully qualified name search. importer: Import function to use for resolving modules. Returns: Enum or Message class definition associated with name. Raises: DefinitionNotFoundError if no definition is found in any search path. """ # Check parameters. if not (relative_to is None or isinstance(relative_to, types.ModuleType) or isinstance(relative_to, type) and issubclass(relative_to, Message)): raise TypeError( 'relative_to must be None, Message definition or module.' ' Found: %s' % relative_to) name_path = name.split('.') # Handle absolute path reference. if not name_path[0]: relative_to = None name_path = name_path[1:] def search_path(): """Performs a single iteration searching the path from relative_to. This is the function that searches up the path from a relative object. fully.qualified.object . relative.or.nested.Definition ----------------------------> ^ | this part of search --+ Returns: Message or Enum at the end of name_path, else None. """ next_part = relative_to for node in name_path: # Look for attribute first. attribute = getattr(next_part, node, None) if attribute is not None: next_part = attribute else: # If module, look for sub-module. if (next_part is None or isinstance(next_part, types.ModuleType)): if next_part is None: module_name = node else: module_name = '%s.%s' % (next_part.__name__, node) try: fromitem = module_name.split('.')[-1] next_part = importer(module_name, '', '', [str(fromitem)]) except ImportError: return None else: return None if not isinstance(next_part, types.ModuleType): if not (isinstance(next_part, type) and issubclass(next_part, (Message, Enum))): return None return next_part while True: found = search_path() if isinstance(found, type) and issubclass(found, (Enum, Message)): return found else: # Find next relative_to to search against. # # fully.qualified.object . relative.or.nested.Definition # <--------------------- # ^ # | # does this part of search if relative_to is None: # Fully qualified search was done. Nothing found. Fail. raise DefinitionNotFoundError( 'Could not find definition for %s' % name) else: if isinstance(relative_to, types.ModuleType): # Find parent module. module_path = relative_to.__name__.split('.')[:-1] if not module_path: relative_to = None else: # Should not raise ImportError. If it does... # weird and unexpected. Propagate. relative_to = importer( '.'.join(module_path), '', '', [module_path[-1]]) elif (isinstance(relative_to, type) and issubclass(relative_to, Message)): parent = relative_to.message_definition() if parent is None: last_module_name = relative_to.__module__.split( '.')[-1] relative_to = importer( relative_to.__module__, '', '', [last_module_name]) else: relative_to = parent
[ "def", "find_definition", "(", "name", ",", "relative_to", "=", "None", ",", "importer", "=", "__import__", ")", ":", "# Check parameters.", "if", "not", "(", "relative_to", "is", "None", "or", "isinstance", "(", "relative_to", ",", "types", ".", "ModuleType",...
https://github.com/google/apitools/blob/31cad2d904f356872d2965687e84b2d87ee2cdd3/apitools/base/protorpclite/messages.py#L1847-L2005
timkpaine/pyEX
254acd2b0cf7cb7183100106f4ecc11d1860c46a
pyEX/stocks/iex.py
python
iexDeep
(symbol=None, token="", version="stable", format="json")
return _get("deep", token=token, version=version, format=format)
DEEP is used to receive real-time depth of book quotations direct from IEX. The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side, and do not indicate the size or number of individual orders at any price level. Non-displayed orders and non-displayed portions of reserve orders are not represented in DEEP. DEEP also provides last trade price and size information. Trades resulting from either displayed or non-displayed orders matching on IEX will be reported. Routed executions will not be reported. https://iexcloud.io/docs/api/#deep Args: symbol (str): Ticker to request token (str): Access token version (str): API version format (str): return format, defaults to json Returns: dict: result
DEEP is used to receive real-time depth of book quotations direct from IEX. The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side, and do not indicate the size or number of individual orders at any price level. Non-displayed orders and non-displayed portions of reserve orders are not represented in DEEP.
[ "DEEP", "is", "used", "to", "receive", "real", "-", "time", "depth", "of", "book", "quotations", "direct", "from", "IEX", ".", "The", "depth", "of", "book", "quotations", "received", "via", "DEEP", "provide", "an", "aggregated", "size", "of", "resting", "d...
def iexDeep(symbol=None, token="", version="stable", format="json"): """DEEP is used to receive real-time depth of book quotations direct from IEX. The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side, and do not indicate the size or number of individual orders at any price level. Non-displayed orders and non-displayed portions of reserve orders are not represented in DEEP. DEEP also provides last trade price and size information. Trades resulting from either displayed or non-displayed orders matching on IEX will be reported. Routed executions will not be reported. https://iexcloud.io/docs/api/#deep Args: symbol (str): Ticker to request token (str): Access token version (str): API version format (str): return format, defaults to json Returns: dict: result """ _raiseIfNotStr(symbol) if symbol: return _get( "deep?symbols=" + _quoteSymbols(symbol), token=token, version=version, format=format, ) return _get("deep", token=token, version=version, format=format)
[ "def", "iexDeep", "(", "symbol", "=", "None", ",", "token", "=", "\"\"", ",", "version", "=", "\"stable\"", ",", "format", "=", "\"json\"", ")", ":", "_raiseIfNotStr", "(", "symbol", ")", "if", "symbol", ":", "return", "_get", "(", "\"deep?symbols=\"", "...
https://github.com/timkpaine/pyEX/blob/254acd2b0cf7cb7183100106f4ecc11d1860c46a/pyEX/stocks/iex.py#L152-L179
MTG/DeepConvSep
65112086378287b2a33cd09e87983d5004f95b89
examples/dsd100/trainCNN.py
python
build_ca
(input_var=None, batch_size=32,time_context=30,feat_size=513)
return l_out
Builds a network with lasagne Parameters ---------- input_var : Theano tensor The input for the network batch_size : int, optional The number of examples in a batch time_context : int, optional The time context modeled by the network. feat_size : int, optional The feature size modeled by the network (last dimension of the feature vector) Yields ------ l_out : Theano tensor The output of the network
Builds a network with lasagne Parameters ---------- input_var : Theano tensor The input for the network batch_size : int, optional The number of examples in a batch time_context : int, optional The time context modeled by the network. feat_size : int, optional The feature size modeled by the network (last dimension of the feature vector) Yields ------ l_out : Theano tensor The output of the network
[ "Builds", "a", "network", "with", "lasagne", "Parameters", "----------", "input_var", ":", "Theano", "tensor", "The", "input", "for", "the", "network", "batch_size", ":", "int", "optional", "The", "number", "of", "examples", "in", "a", "batch", "time_context", ...
def build_ca(input_var=None, batch_size=32,time_context=30,feat_size=513): """ Builds a network with lasagne Parameters ---------- input_var : Theano tensor The input for the network batch_size : int, optional The number of examples in a batch time_context : int, optional The time context modeled by the network. feat_size : int, optional The feature size modeled by the network (last dimension of the feature vector) Yields ------ l_out : Theano tensor The output of the network """ input_shape=(batch_size,1,time_context,feat_size) #input layer l_in_1 = lasagne.layers.InputLayer(shape=input_shape, input_var=input_var) #vertical convolution layer l_conv1 = lasagne.layers.Conv2DLayer(l_in_1, num_filters=50, filter_size=(1,feat_size),stride=(1,1), pad='valid', nonlinearity=None) l_conv1b= lasagne.layers.BiasLayer(l_conv1) #horizontal convolution layer l_conv2 = lasagne.layers.Conv2DLayer(l_conv1b, num_filters=50, filter_size=(int(time_context/2),1),stride=(1,1), pad='valid', nonlinearity=None) l_conv2b= lasagne.layers.BiasLayer(l_conv2) #bottlneck layer l_fc=lasagne.layers.DenseLayer(l_conv2b,128) #build output for source1 l_fc11=lasagne.layers.DenseLayer(l_fc,l_conv2.output_shape[1]*l_conv2.output_shape[2]*l_conv2.output_shape[3]) l_reshape1 = lasagne.layers.ReshapeLayer(l_fc11,(batch_size,l_conv2.output_shape[1],l_conv2.output_shape[2], l_conv2.output_shape[3])) l_inverse11=lasagne.layers.InverseLayer(l_reshape1, l_conv2) l_inverse41=lasagne.layers.InverseLayer(l_inverse11, l_conv1) #build output for source2 l_fc12=lasagne.layers.DenseLayer(l_fc,l_conv2.output_shape[1]*l_conv2.output_shape[2]*l_conv2.output_shape[3]) l_reshape2 = lasagne.layers.ReshapeLayer(l_fc12,(batch_size,l_conv2.output_shape[1],l_conv2.output_shape[2], l_conv2.output_shape[3])) l_inverse12=lasagne.layers.InverseLayer(l_reshape2, l_conv2) l_inverse42=lasagne.layers.InverseLayer(l_inverse12, l_conv1) #build output for source3 l_fc13=lasagne.layers.DenseLayer(l_fc,l_conv2.output_shape[1]*l_conv2.output_shape[2]*l_conv2.output_shape[3]) l_reshape3 = lasagne.layers.ReshapeLayer(l_fc13,(batch_size,l_conv2.output_shape[1],l_conv2.output_shape[2], l_conv2.output_shape[3])) l_inverse13=lasagne.layers.InverseLayer(l_reshape3, l_conv2) l_inverse43=lasagne.layers.InverseLayer(l_inverse13, l_conv1) #build output for source4 l_fc14=lasagne.layers.DenseLayer(l_fc,l_conv2.output_shape[1]*l_conv2.output_shape[2]*l_conv2.output_shape[3]) l_reshape4 = lasagne.layers.ReshapeLayer(l_fc12,(batch_size,l_conv2.output_shape[1],l_conv2.output_shape[2], l_conv2.output_shape[3])) l_inverse14=lasagne.layers.InverseLayer(l_reshape4, l_conv2) l_inverse44=lasagne.layers.InverseLayer(l_inverse14, l_conv1) #build final output l_merge=lasagne.layers.ConcatLayer([l_inverse41,l_inverse42,l_inverse43,l_inverse44],axis=1) l_out = lasagne.layers.NonlinearityLayer(lasagne.layers.BiasLayer(l_merge), nonlinearity=lasagne.nonlinearities.rectify) return l_out
[ "def", "build_ca", "(", "input_var", "=", "None", ",", "batch_size", "=", "32", ",", "time_context", "=", "30", ",", "feat_size", "=", "513", ")", ":", "input_shape", "=", "(", "batch_size", ",", "1", ",", "time_context", ",", "feat_size", ")", "#input l...
https://github.com/MTG/DeepConvSep/blob/65112086378287b2a33cd09e87983d5004f95b89/examples/dsd100/trainCNN.py#L66-L130
Calamari-OCR/calamari
9dbdb3a66e3729fabff4119d11851b08f3c6eb66
calamari_ocr/thirdparty/ctcwordbeamsearch/PrefixTree.py
python
PrefixTree.getNextWords
(self, text)
return words
get all words of which given text is a prefix (including the text itself, it is a word)
get all words of which given text is a prefix (including the text itself, it is a word)
[ "get", "all", "words", "of", "which", "given", "text", "is", "a", "prefix", "(", "including", "the", "text", "itself", "it", "is", "a", "word", ")" ]
def getNextWords(self, text): "get all words of which given text is a prefix (including the text itself, it is a word)" words = [] node = self.getNode(text) if node: nodes = [node] prefixes = [text] while len(nodes) > 0: # put all children into list for k, v in nodes[0].children.items(): nodes.append(v) prefixes.append(prefixes[0] + k) # is current node a word if nodes[0].isWord: words.append(prefixes[0]) # remove current node del nodes[0] del prefixes[0] return words
[ "def", "getNextWords", "(", "self", ",", "text", ")", ":", "words", "=", "[", "]", "node", "=", "self", ".", "getNode", "(", "text", ")", "if", "node", ":", "nodes", "=", "[", "node", "]", "prefixes", "=", "[", "text", "]", "while", "len", "(", ...
https://github.com/Calamari-OCR/calamari/blob/9dbdb3a66e3729fabff4119d11851b08f3c6eb66/calamari_ocr/thirdparty/ctcwordbeamsearch/PrefixTree.py#L66-L87
HacTF/poc--exp
52f4082ee40a6e60b23c56390cf081112b37c533
CVE-2018-20250/acefile.py
python
AceCRC32.__str__
(self)
return "0x%08x" % self.sum
String representation of object is hex value of checksum.
String representation of object is hex value of checksum.
[ "String", "representation", "of", "object", "is", "hex", "value", "of", "checksum", "." ]
def __str__(self): """ String representation of object is hex value of checksum. """ return "0x%08x" % self.sum
[ "def", "__str__", "(", "self", ")", ":", "return", "\"0x%08x\"", "%", "self", ".", "sum" ]
https://github.com/HacTF/poc--exp/blob/52f4082ee40a6e60b23c56390cf081112b37c533/CVE-2018-20250/acefile.py#L909-L913
xiaocong/uiautomator
ddef372b5bd3811f196290a1f75b636c6be9da2b
uiautomator/__init__.py
python
AutomatorDevice.orientation
(self)
return self.__orientation[self.info["displayRotation"]][1]
orienting the devie to left/right or natural. left/l: rotation=90 , displayRotation=1 right/r: rotation=270, displayRotation=3 natural/n: rotation=0 , displayRotation=0 upsidedown/u: rotation=180, displayRotation=2
orienting the devie to left/right or natural. left/l: rotation=90 , displayRotation=1 right/r: rotation=270, displayRotation=3 natural/n: rotation=0 , displayRotation=0 upsidedown/u: rotation=180, displayRotation=2
[ "orienting", "the", "devie", "to", "left", "/", "right", "or", "natural", ".", "left", "/", "l", ":", "rotation", "=", "90", "displayRotation", "=", "1", "right", "/", "r", ":", "rotation", "=", "270", "displayRotation", "=", "3", "natural", "/", "n", ...
def orientation(self): ''' orienting the devie to left/right or natural. left/l: rotation=90 , displayRotation=1 right/r: rotation=270, displayRotation=3 natural/n: rotation=0 , displayRotation=0 upsidedown/u: rotation=180, displayRotation=2 ''' return self.__orientation[self.info["displayRotation"]][1]
[ "def", "orientation", "(", "self", ")", ":", "return", "self", ".", "__orientation", "[", "self", ".", "info", "[", "\"displayRotation\"", "]", "]", "[", "1", "]" ]
https://github.com/xiaocong/uiautomator/blob/ddef372b5bd3811f196290a1f75b636c6be9da2b/uiautomator/__init__.py#L649-L657
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/ui/gui/tabs/exploit/utils.py
python
TextDialogConsumer.handle_message
(self, msg)
[]
def handle_message(self, msg): # This yield True is required by MessageConsumer yield True if msg.get_type() == 'console': # Handling new lines text = msg.get_msg() if msg.get_new_line(): text += '\n' self.add_message(text)
[ "def", "handle_message", "(", "self", ",", "msg", ")", ":", "# This yield True is required by MessageConsumer", "yield", "True", "if", "msg", ".", "get_type", "(", ")", "==", "'console'", ":", "# Handling new lines", "text", "=", "msg", ".", "get_msg", "(", ")",...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/ui/gui/tabs/exploit/utils.py#L44-L54
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/numpy/ma/core.py
python
doc_note
(initialdoc, note)
return newdoc % (initialdoc, note)
Adds a Notes section to an existing docstring.
Adds a Notes section to an existing docstring.
[ "Adds", "a", "Notes", "section", "to", "an", "existing", "docstring", "." ]
def doc_note(initialdoc, note): """ Adds a Notes section to an existing docstring. """ if initialdoc is None: return if note is None: return initialdoc newdoc = """ %s Notes ----- %s """ return newdoc % (initialdoc, note)
[ "def", "doc_note", "(", "initialdoc", ",", "note", ")", ":", "if", "initialdoc", "is", "None", ":", "return", "if", "note", "is", "None", ":", "return", "initialdoc", "newdoc", "=", "\"\"\"\n %s\n\n Notes\n -----\n %s\n \"\"\"", "return", "newdoc", ...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/numpy/ma/core.py#L92-L107
yandex/yandex-tank
b41bcc04396c4ed46fc8b28a261197320854fd33
yandextank/plugins/Autostop/criterions.py
python
QuantileCriterion.get_type_string
()
return 'quantile'
[]
def get_type_string(): return 'quantile'
[ "def", "get_type_string", "(", ")", ":", "return", "'quantile'" ]
https://github.com/yandex/yandex-tank/blob/b41bcc04396c4ed46fc8b28a261197320854fd33/yandextank/plugins/Autostop/criterions.py#L305-L306
secdev/scapy
65089071da1acf54622df0b4fa7fc7673d47d3cd
scapy/layers/tls/handshake.py
python
TLSHelloRequest.tls_session_update
(self, msg_str)
return
Message should not be added to the list of handshake messages that will be hashed in the finished and certificate verify messages.
Message should not be added to the list of handshake messages that will be hashed in the finished and certificate verify messages.
[ "Message", "should", "not", "be", "added", "to", "the", "list", "of", "handshake", "messages", "that", "will", "be", "hashed", "in", "the", "finished", "and", "certificate", "verify", "messages", "." ]
def tls_session_update(self, msg_str): """ Message should not be added to the list of handshake messages that will be hashed in the finished and certificate verify messages. """ return
[ "def", "tls_session_update", "(", "self", ",", "msg_str", ")", ":", "return" ]
https://github.com/secdev/scapy/blob/65089071da1acf54622df0b4fa7fc7673d47d3cd/scapy/layers/tls/handshake.py#L131-L136
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_image.py
python
OpenShiftCLI._list_pods
(self, node=None, selector=None, pod_selector=None)
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
perform oadm list pods node: the node in which to list pods selector: the label selector filter if provided pod_selector: the pod selector filter if provided
perform oadm list pods
[ "perform", "oadm", "list", "pods" ]
def _list_pods(self, node=None, selector=None, pod_selector=None): ''' perform oadm list pods node: the node in which to list pods selector: the label selector filter if provided pod_selector: the pod selector filter if provided ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) if pod_selector: cmd.append('--pod-selector={}'.format(pod_selector)) cmd.extend(['--list-pods', '-o', 'json']) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
[ "def", "_list_pods", "(", "self", ",", "node", "=", "None", ",", "selector", "=", "None", ",", "pod_selector", "=", "None", ")", ":", "cmd", "=", "[", "'manage-node'", "]", "if", "node", ":", "cmd", ".", "extend", "(", "node", ")", "else", ":", "cm...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_image.py#L1033-L1051
ipython/ipython
c0abea7a6dfe52c1f74c9d0387d4accadba7cc14
IPython/core/completer.py
python
cursor_to_position
(text:str, line:int, column:int)
return sum(len(l) + 1 for l in lines[:line]) + column
Convert the (line,column) position of the cursor in text to an offset in a string. Parameters ---------- text : str The text in which to calculate the cursor offset line : int Line of the cursor; 0-indexed column : int Column of the cursor 0-indexed Returns ------- Position of the cursor in ``text``, 0-indexed. See Also -------- position_to_cursor : reciprocal of this function
Convert the (line,column) position of the cursor in text to an offset in a string.
[ "Convert", "the", "(", "line", "column", ")", "position", "of", "the", "cursor", "in", "text", "to", "an", "offset", "in", "a", "string", "." ]
def cursor_to_position(text:str, line:int, column:int)->int: """ Convert the (line,column) position of the cursor in text to an offset in a string. Parameters ---------- text : str The text in which to calculate the cursor offset line : int Line of the cursor; 0-indexed column : int Column of the cursor 0-indexed Returns ------- Position of the cursor in ``text``, 0-indexed. See Also -------- position_to_cursor : reciprocal of this function """ lines = text.split('\n') assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines))) return sum(len(l) + 1 for l in lines[:line]) + column
[ "def", "cursor_to_position", "(", "text", ":", "str", ",", "line", ":", "int", ",", "column", ":", "int", ")", "->", "int", ":", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "assert", "line", "<=", "len", "(", "lines", ")", ",", "'{} <= {...
https://github.com/ipython/ipython/blob/c0abea7a6dfe52c1f74c9d0387d4accadba7cc14/IPython/core/completer.py#L855-L881
arc90/git-sweep
d7522b4de1dbc85570ec36b82bc155a4fa371b5e
src/gitsweep/entrypoints.py
python
test
()
Run git-sweep's test suite.
Run git-sweep's test suite.
[ "Run", "git", "-", "sweep", "s", "test", "suite", "." ]
def test(): """ Run git-sweep's test suite. """ import nose import sys nose.main(argv=['nose'] + sys.argv[1:])
[ "def", "test", "(", ")", ":", "import", "nose", "import", "sys", "nose", ".", "main", "(", "argv", "=", "[", "'nose'", "]", "+", "sys", ".", "argv", "[", "1", ":", "]", ")" ]
https://github.com/arc90/git-sweep/blob/d7522b4de1dbc85570ec36b82bc155a4fa371b5e/src/gitsweep/entrypoints.py#L12-L20
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/geometry/polygon.py
python
RegularPolygon.__new__
(self, c, r, n, rot=0, **kwargs)
return obj
[]
def __new__(self, c, r, n, rot=0, **kwargs): r, n, rot = map(sympify, (r, n, rot)) c = Point(c) if not isinstance(r, Expr): raise GeometryError("r must be an Expr object, not %s" % r) if n.is_Number: as_int(n) # let an error raise if necessary if n < 3: raise GeometryError("n must be a >= 3, not %s" % n) obj = GeometryEntity.__new__(self, c, r, n, **kwargs) obj._n = n obj._center = c obj._radius = r obj._rot = rot return obj
[ "def", "__new__", "(", "self", ",", "c", ",", "r", ",", "n", ",", "rot", "=", "0", ",", "*", "*", "kwargs", ")", ":", "r", ",", "n", ",", "rot", "=", "map", "(", "sympify", ",", "(", "r", ",", "n", ",", "rot", ")", ")", "c", "=", "Point...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/geometry/polygon.py#L1048-L1063
runawayhorse001/LearningApacheSpark
67f3879dce17553195f094f5728b94a01badcf24
pyspark/mllib/clustering.py
python
LDAModel.load
(cls, sc, path)
return LDAModel(model)
Load the LDAModel from disk. :param sc: SparkContext. :param path: Path to where the model is stored.
Load the LDAModel from disk.
[ "Load", "the", "LDAModel", "from", "disk", "." ]
def load(cls, sc, path): """Load the LDAModel from disk. :param sc: SparkContext. :param path: Path to where the model is stored. """ if not isinstance(sc, SparkContext): raise TypeError("sc should be a SparkContext, got type %s" % type(sc)) if not isinstance(path, basestring): raise TypeError("path should be a basestring, got type %s" % type(path)) model = callMLlibFunc("loadLDAModel", sc, path) return LDAModel(model)
[ "def", "load", "(", "cls", ",", "sc", ",", "path", ")", ":", "if", "not", "isinstance", "(", "sc", ",", "SparkContext", ")", ":", "raise", "TypeError", "(", "\"sc should be a SparkContext, got type %s\"", "%", "type", "(", "sc", ")", ")", "if", "not", "i...
https://github.com/runawayhorse001/LearningApacheSpark/blob/67f3879dce17553195f094f5728b94a01badcf24/pyspark/mllib/clustering.py#L977-L990
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idc.py
python
ArmForceBLJump
(ea)
return Eval("ArmForceBLJump(0x%x)"%ea)
Some ARM compilers in Thumb mode use BL (branch-and-link) instead of B (branch) for long jumps, since BL has more range. By default, IDA tries to determine if BL is a jump or a call. You can override IDA's decision using commands in Edit/Other menu (Force BL call/Force BL jump) or the following two functions. Force BL instruction to be a jump @param ea: address of the BL instruction @return: 1-ok, 0-failed
Some ARM compilers in Thumb mode use BL (branch-and-link) instead of B (branch) for long jumps, since BL has more range. By default, IDA tries to determine if BL is a jump or a call. You can override IDA's decision using commands in Edit/Other menu (Force BL call/Force BL jump) or the following two functions.
[ "Some", "ARM", "compilers", "in", "Thumb", "mode", "use", "BL", "(", "branch", "-", "and", "-", "link", ")", "instead", "of", "B", "(", "branch", ")", "for", "long", "jumps", "since", "BL", "has", "more", "range", ".", "By", "default", "IDA", "tries"...
def ArmForceBLJump(ea): """ Some ARM compilers in Thumb mode use BL (branch-and-link) instead of B (branch) for long jumps, since BL has more range. By default, IDA tries to determine if BL is a jump or a call. You can override IDA's decision using commands in Edit/Other menu (Force BL call/Force BL jump) or the following two functions. Force BL instruction to be a jump @param ea: address of the BL instruction @return: 1-ok, 0-failed """ return Eval("ArmForceBLJump(0x%x)"%ea)
[ "def", "ArmForceBLJump", "(", "ea", ")", ":", "return", "Eval", "(", "\"ArmForceBLJump(0x%x)\"", "%", "ea", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idc.py#L8378-L8392
balajiln/mondrianforest
eac11fe085160daf56f4e8c6226d0400b78c3908
src/mondrianforest_utils.py
python
compute_dirichlet_normalizer
(cnt, alpha=0.0, prior_term=None)
return op
cnt is np.array, alpha is concentration of Dirichlet prior => alpha/K is the mass for each component of a K-dimensional Dirichlet
cnt is np.array, alpha is concentration of Dirichlet prior => alpha/K is the mass for each component of a K-dimensional Dirichlet
[ "cnt", "is", "np", ".", "array", "alpha", "is", "concentration", "of", "Dirichlet", "prior", "=", ">", "alpha", "/", "K", "is", "the", "mass", "for", "each", "component", "of", "a", "K", "-", "dimensional", "Dirichlet" ]
def compute_dirichlet_normalizer(cnt, alpha=0.0, prior_term=None): """ cnt is np.array, alpha is concentration of Dirichlet prior => alpha/K is the mass for each component of a K-dimensional Dirichlet """ try: assert(len(cnt.shape) == 1) except AssertionError: print 'cnt should be a 1-dimensional np array' raise AssertionError n_class = float(len(cnt)) if prior_term is None: #print 'recomputing prior_term' prior_term = gammaln(alpha) - n_class * gammaln(alpha / n_class) op = np.sum(gammaln(cnt + alpha / n_class)) - gammaln(np.sum(cnt) + alpha) \ + prior_term return op
[ "def", "compute_dirichlet_normalizer", "(", "cnt", ",", "alpha", "=", "0.0", ",", "prior_term", "=", "None", ")", ":", "try", ":", "assert", "(", "len", "(", "cnt", ".", "shape", ")", "==", "1", ")", "except", "AssertionError", ":", "print", "'cnt should...
https://github.com/balajiln/mondrianforest/blob/eac11fe085160daf56f4e8c6226d0400b78c3908/src/mondrianforest_utils.py#L709-L724
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/more_itertools/more.py
python
unique_to_each
(*iterables)
return [list(filter(uniques.__contains__, it)) for it in pool]
Return the elements from each of the input iterables that aren't in the other input iterables. For example, suppose you have a set of packages, each with a set of dependencies:: {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}} If you remove one package, which dependencies can also be removed? If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for ``pkg_2``, and ``D`` is only needed for ``pkg_3``:: >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'}) [['A'], ['C'], ['D']] If there are duplicates in one input iterable that aren't in the others they will be duplicated in the output. Input order is preserved:: >>> unique_to_each("mississippi", "missouri") [['p', 'p'], ['o', 'u', 'r']] It is assumed that the elements of each iterable are hashable.
Return the elements from each of the input iterables that aren't in the other input iterables.
[ "Return", "the", "elements", "from", "each", "of", "the", "input", "iterables", "that", "aren", "t", "in", "the", "other", "input", "iterables", "." ]
def unique_to_each(*iterables): """Return the elements from each of the input iterables that aren't in the other input iterables. For example, suppose you have a set of packages, each with a set of dependencies:: {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}} If you remove one package, which dependencies can also be removed? If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for ``pkg_2``, and ``D`` is only needed for ``pkg_3``:: >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'}) [['A'], ['C'], ['D']] If there are duplicates in one input iterable that aren't in the others they will be duplicated in the output. Input order is preserved:: >>> unique_to_each("mississippi", "missouri") [['p', 'p'], ['o', 'u', 'r']] It is assumed that the elements of each iterable are hashable. """ pool = [list(it) for it in iterables] counts = Counter(chain.from_iterable(map(set, pool))) uniques = {element for element in counts if counts[element] == 1} return [list(filter(uniques.__contains__, it)) for it in pool]
[ "def", "unique_to_each", "(", "*", "iterables", ")", ":", "pool", "=", "[", "list", "(", "it", ")", "for", "it", "in", "iterables", "]", "counts", "=", "Counter", "(", "chain", ".", "from_iterable", "(", "map", "(", "set", ",", "pool", ")", ")", ")...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/more_itertools/more.py#L707-L737
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_vendor/html5lib/treewalkers/base.py
python
TreeWalker.emptyTag
(self, namespace, name, attrs, hasChildren=False)
Generates an EmptyTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :arg hasChildren: whether or not to yield a SerializationError because this tag shouldn't have children :returns: EmptyTag token
Generates an EmptyTag token
[ "Generates", "an", "EmptyTag", "token" ]
def emptyTag(self, namespace, name, attrs, hasChildren=False): """Generates an EmptyTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :arg hasChildren: whether or not to yield a SerializationError because this tag shouldn't have children :returns: EmptyTag token """ yield {"type": "EmptyTag", "name": name, "namespace": namespace, "data": attrs} if hasChildren: yield self.error("Void element has children")
[ "def", "emptyTag", "(", "self", ",", "namespace", ",", "name", ",", "attrs", ",", "hasChildren", "=", "False", ")", ":", "yield", "{", "\"type\"", ":", "\"EmptyTag\"", ",", "\"name\"", ":", "name", ",", "\"namespace\"", ":", "namespace", ",", "\"data\"", ...
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/html5lib/treewalkers/base.py#L48-L67
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/sqli/thirdparty/bottle/bottle.py
python
makelist
(data)
[]
def makelist(data): # This is just to handy if isinstance(data, (tuple, list, set, dict)): return list(data) elif data: return [data] else: return []
[ "def", "makelist", "(", "data", ")", ":", "# This is just to handy", "if", "isinstance", "(", "data", ",", "(", "tuple", ",", "list", ",", "set", ",", "dict", ")", ")", ":", "return", "list", "(", "data", ")", "elif", "data", ":", "return", "[", "dat...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/sqli/thirdparty/bottle/bottle.py#L144-L147
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/knutson_tao_puzzles.py
python
PuzzleFilling.copy
(self)
return PP
r""" Return copy of ``self``. EXAMPLES:: sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, PuzzleFilling sage: piece = DeltaPiece('0','1','0') sage: P = PuzzleFilling('0101','0101'); P {} sage: PP = P.copy() sage: P.add_piece(piece); P {(1, 4): 1/0\0} sage: PP {}
r""" Return copy of ``self``.
[ "r", "Return", "copy", "of", "self", "." ]
def copy(self): r""" Return copy of ``self``. EXAMPLES:: sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, PuzzleFilling sage: piece = DeltaPiece('0','1','0') sage: P = PuzzleFilling('0101','0101'); P {} sage: PP = P.copy() sage: P.add_piece(piece); P {(1, 4): 1/0\0} sage: PP {} """ PP = PuzzleFilling(self._nw_labels, self._ne_labels) PP._squares = self._squares.copy() PP._kink_coordinates = self._kink_coordinates PP._n = self._n return PP
[ "def", "copy", "(", "self", ")", ":", "PP", "=", "PuzzleFilling", "(", "self", ".", "_nw_labels", ",", "self", ".", "_ne_labels", ")", "PP", ".", "_squares", "=", "self", ".", "_squares", ".", "copy", "(", ")", "PP", ".", "_kink_coordinates", "=", "s...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/knutson_tao_puzzles.py#L1262-L1283
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/setuptools/command/easy_install.py
python
is_sh
(executable)
return magic == '#!'
Determine if the specified executable is a .sh (contains a #! line)
Determine if the specified executable is a .sh (contains a #! line)
[ "Determine", "if", "the", "specified", "executable", "is", "a", ".", "sh", "(", "contains", "a", "#!", "line", ")" ]
def is_sh(executable): """Determine if the specified executable is a .sh (contains a #! line)""" try: with io.open(executable, encoding='latin-1') as fp: magic = fp.read(2) except (OSError, IOError): return executable return magic == '#!'
[ "def", "is_sh", "(", "executable", ")", ":", "try", ":", "with", "io", ".", "open", "(", "executable", ",", "encoding", "=", "'latin-1'", ")", "as", "fp", ":", "magic", "=", "fp", ".", "read", "(", "2", ")", "except", "(", "OSError", ",", "IOError"...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/setuptools/command/easy_install.py#L1916-L1923
OSInside/kiwi
9618cf33f510ddf302ad1d4e0df35f75b00eb152
kiwi/bootloader/install/grub2.py
python
BootLoaderInstallGrub2.install_required
(self)
return True
Check if grub2 has to be installed Take architecture and firmware setup into account to check if bootloader code in a boot record is required :return: True or False :rtype: bool
Check if grub2 has to be installed
[ "Check", "if", "grub2", "has", "to", "be", "installed" ]
def install_required(self): """ Check if grub2 has to be installed Take architecture and firmware setup into account to check if bootloader code in a boot record is required :return: True or False :rtype: bool """ if 'ppc64' in self.arch and self.firmware.opal_mode(): # OPAL doesn't need a grub2 stage1, just a config file. # The machine will be setup to kexec grub2 in user space log.info( 'No grub boot code installation in opal mode on %s', self.arch ) return False elif 'arm' in self.arch or self.arch == 'aarch64': # On arm grub2 is used for EFI setup only, no install # of grub2 boot code makes sense log.info( 'No grub boot code installation on %s', self.arch ) return False elif self.arch == 'riscv64': # On riscv grub2 is used for EFI setup only, no install # of grub2 boot code makes sense log.info( 'No grub boot code installation on %s', self.arch ) return False return True
[ "def", "install_required", "(", "self", ")", ":", "if", "'ppc64'", "in", "self", ".", "arch", "and", "self", ".", "firmware", ".", "opal_mode", "(", ")", ":", "# OPAL doesn't need a grub2 stage1, just a config file.", "# The machine will be setup to kexec grub2 in user sp...
https://github.com/OSInside/kiwi/blob/9618cf33f510ddf302ad1d4e0df35f75b00eb152/kiwi/bootloader/install/grub2.py#L95-L127
dropbox/PyHive
b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0
TCLIService/TCLIService.py
python
Client.recv_GetOperationStatus
(self)
[]
def recv_GetOperationStatus(self): iprot = self._iprot (fname, mtype, rseqid) = iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(iprot) iprot.readMessageEnd() raise x result = GetOperationStatus_result() result.read(iprot) iprot.readMessageEnd() if result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, "GetOperationStatus failed: unknown result")
[ "def", "recv_GetOperationStatus", "(", "self", ")", ":", "iprot", "=", "self", ".", "_iprot", "(", "fname", ",", "mtype", ",", "rseqid", ")", "=", "iprot", ".", "readMessageBegin", "(", ")", "if", "mtype", "==", "TMessageType", ".", "EXCEPTION", ":", "x"...
https://github.com/dropbox/PyHive/blob/b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0/TCLIService/TCLIService.py#L600-L613
hannes-brt/hebel
1e2c3a9309c2646103901b26a55be4e312dd5005
hebel/pycuda_ops/cublas.py
python
cublasDtrsv
(handle, uplo, trans, diag, n, A, lda, x, incx)
Solve real triangular system with one right-hand side.
Solve real triangular system with one right-hand side.
[ "Solve", "real", "triangular", "system", "with", "one", "right", "-", "hand", "side", "." ]
def cublasDtrsv(handle, uplo, trans, diag, n, A, lda, x, incx): """ Solve real triangular system with one right-hand side. """ status = _libcublas.cublasDtrsv_v2(handle, _CUBLAS_FILL_MODE[uplo], _CUBLAS_OP[trans], _CUBLAS_DIAG[diag], n, int(A), lda, int(x), incx) cublasCheckStatus(status)
[ "def", "cublasDtrsv", "(", "handle", ",", "uplo", ",", "trans", ",", "diag", ",", "n", ",", "A", ",", "lda", ",", "x", ",", "incx", ")", ":", "status", "=", "_libcublas", ".", "cublasDtrsv_v2", "(", "handle", ",", "_CUBLAS_FILL_MODE", "[", "uplo", "]...
https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L3490-L3501
python-babel/babel
cc36c84a83dd447bf48a6af3eb03c97bf299e8cb
scripts/import_cldr.py
python
_import_type_text
(dest, elem, type=None)
Conditionally import the element's inner text(s) into the `dest` dict. The condition being, namely, that the element isn't a draft/alternate version of a pre-existing element. :param dest: Destination dict :param elem: XML element. :param type: Override type. (By default, the `type` attr of the element.) :return:
Conditionally import the element's inner text(s) into the `dest` dict.
[ "Conditionally", "import", "the", "element", "s", "inner", "text", "(", "s", ")", "into", "the", "dest", "dict", "." ]
def _import_type_text(dest, elem, type=None): """ Conditionally import the element's inner text(s) into the `dest` dict. The condition being, namely, that the element isn't a draft/alternate version of a pre-existing element. :param dest: Destination dict :param elem: XML element. :param type: Override type. (By default, the `type` attr of the element.) :return: """ if type is None: type = elem.attrib['type'] if _should_skip_elem(elem, type, dest): return dest[type] = _text(elem)
[ "def", "_import_type_text", "(", "dest", ",", "elem", ",", "type", "=", "None", ")", ":", "if", "type", "is", "None", ":", "type", "=", "elem", ".", "attrib", "[", "'type'", "]", "if", "_should_skip_elem", "(", "elem", ",", "type", ",", "dest", ")", ...
https://github.com/python-babel/babel/blob/cc36c84a83dd447bf48a6af3eb03c97bf299e8cb/scripts/import_cldr.py#L483-L499
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/vacuum/__init__.py
python
_BaseVacuum.fan_speed
(self)
return None
Return the fan speed of the vacuum cleaner.
Return the fan speed of the vacuum cleaner.
[ "Return", "the", "fan", "speed", "of", "the", "vacuum", "cleaner", "." ]
def fan_speed(self): """Return the fan speed of the vacuum cleaner.""" return None
[ "def", "fan_speed", "(", "self", ")", ":", "return", "None" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/vacuum/__init__.py#L169-L171
wagtail/wagtail
ba8207a5d82c8a1de8f5f9693a7cd07421762999
wagtail/core/models/__init__.py
python
UserPagePermissionsProxy.for_page
(self, page)
return PagePermissionTester(self, page)
Return a PagePermissionTester object that can be used to query whether this user has permission to perform specific tasks on the given page
Return a PagePermissionTester object that can be used to query whether this user has permission to perform specific tasks on the given page
[ "Return", "a", "PagePermissionTester", "object", "that", "can", "be", "used", "to", "query", "whether", "this", "user", "has", "permission", "to", "perform", "specific", "tasks", "on", "the", "given", "page" ]
def for_page(self, page): """Return a PagePermissionTester object that can be used to query whether this user has permission to perform specific tasks on the given page""" return PagePermissionTester(self, page)
[ "def", "for_page", "(", "self", ",", "page", ")", ":", "return", "PagePermissionTester", "(", "self", ",", "page", ")" ]
https://github.com/wagtail/wagtail/blob/ba8207a5d82c8a1de8f5f9693a7cd07421762999/wagtail/core/models/__init__.py#L2398-L2401
inguma/bokken
6109dd0025093a11631cb88cf48cb5c5ed5e617d
lib/web/http.py
python
urlencode
(query, doseq=0)
return urllib.urlencode(query, doseq=doseq)
Same as urllib.urlencode, but supports unicode strings. >>> urlencode({'text':'foo bar'}) 'text=foo+bar' >>> urlencode({'x': [1, 2]}, doseq=True) 'x=1&x=2'
Same as urllib.urlencode, but supports unicode strings. >>> urlencode({'text':'foo bar'}) 'text=foo+bar' >>> urlencode({'x': [1, 2]}, doseq=True) 'x=1&x=2'
[ "Same", "as", "urllib", ".", "urlencode", "but", "supports", "unicode", "strings", ".", ">>>", "urlencode", "(", "{", "text", ":", "foo", "bar", "}", ")", "text", "=", "foo", "+", "bar", ">>>", "urlencode", "(", "{", "x", ":", "[", "1", "2", "]", ...
def urlencode(query, doseq=0): """ Same as urllib.urlencode, but supports unicode strings. >>> urlencode({'text':'foo bar'}) 'text=foo+bar' >>> urlencode({'x': [1, 2]}, doseq=True) 'x=1&x=2' """ def convert(value, doseq=False): if doseq and isinstance(value, list): return [convert(v) for v in value] else: return utils.safestr(value) query = dict([(k, convert(v, doseq)) for k, v in query.items()]) return urllib.urlencode(query, doseq=doseq)
[ "def", "urlencode", "(", "query", ",", "doseq", "=", "0", ")", ":", "def", "convert", "(", "value", ",", "doseq", "=", "False", ")", ":", "if", "doseq", "and", "isinstance", "(", "value", ",", "list", ")", ":", "return", "[", "convert", "(", "v", ...
https://github.com/inguma/bokken/blob/6109dd0025093a11631cb88cf48cb5c5ed5e617d/lib/web/http.py#L87-L103
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/IPython/utils/localinterfaces.py
python
public_ips
()
return PUBLIC_IPS
return the IP addresses for this machine that are visible to other machines
return the IP addresses for this machine that are visible to other machines
[ "return", "the", "IP", "addresses", "for", "this", "machine", "that", "are", "visible", "to", "other", "machines" ]
def public_ips(): """return the IP addresses for this machine that are visible to other machines""" return PUBLIC_IPS
[ "def", "public_ips", "(", ")", ":", "return", "PUBLIC_IPS" ]
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/IPython/utils/localinterfaces.py#L261-L263