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
pandas-dev/pandas
5ba7d714014ae8feaccc0dd4a98890828cf2832d
pandas/core/internals/managers.py
python
SingleBlockManager.internal_values
(self)
return self._block.values
The array that Series._values returns
The array that Series._values returns
[ "The", "array", "that", "Series", ".", "_values", "returns" ]
def internal_values(self): """The array that Series._values returns""" return self._block.values
[ "def", "internal_values", "(", "self", ")", ":", "return", "self", ".", "_block", ".", "values" ]
https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/core/internals/managers.py#L1848-L1850
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/foundation/whatsthis_utilities.py
python
refix_whatsthis_text_and_links
( )
return
[public]
[public]
[ "[", "public", "]" ]
def refix_whatsthis_text_and_links( ): #bruce 060319 part of fixing bug 1421 """ [public] """ win = env.mainwindow() fix_QAction_whatsthis(win.editUndoAction) fix_QAction_whatsthis(win.editRedoAction) return
[ "def", "refix_whatsthis_text_and_links", "(", ")", ":", "#bruce 060319 part of fixing bug 1421", "win", "=", "env", ".", "mainwindow", "(", ")", "fix_QAction_whatsthis", "(", "win", ".", "editUndoAction", ")", "fix_QAction_whatsthis", "(", "win", ".", "editRedoAction", ...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/foundation/whatsthis_utilities.py#L190-L197
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/mailbox.py
python
_ProxyFile._read
(self, size, read_method)
return result
Read size bytes using read_method.
Read size bytes using read_method.
[ "Read", "size", "bytes", "using", "read_method", "." ]
def _read(self, size, read_method): """Read size bytes using read_method.""" if size is None: size = -1 self._file.seek(self._pos) result = read_method(size) self._pos = self._file.tell() return result
[ "def", "_read", "(", "self", ",", "size", ",", "read_method", ")", ":", "if", "size", "is", "None", ":", "size", "=", "-", "1", "self", ".", "_file", ".", "seek", "(", "self", ".", "_pos", ")", "result", "=", "read_method", "(", "size", ")", "sel...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/mailbox.py#L1912-L1919
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
pytorch/pytorchcv/models/resnet.py
python
resnetbc26b
(**kwargs)
return get_resnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="resnetbc26b", **kwargs)
ResNet-BC-26b model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model (bottleneck compressed). Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location for keeping the model parameters.
ResNet-BC-26b model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model (bottleneck compressed).
[ "ResNet", "-", "BC", "-", "26b", "model", "from", "Deep", "Residual", "Learning", "for", "Image", "Recognition", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1512", ".", "03385", ".", "It", "s", "an", "experimental", "model", "(", "bottle...
def resnetbc26b(**kwargs): """ ResNet-BC-26b model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model (bottleneck compressed). Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location for keeping the model parameters. """ return get_resnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="resnetbc26b", **kwargs)
[ "def", "resnetbc26b", "(", "*", "*", "kwargs", ")", ":", "return", "get_resnet", "(", "blocks", "=", "26", ",", "bottleneck", "=", "True", ",", "conv1_stride", "=", "False", ",", "model_name", "=", "\"resnetbc26b\"", ",", "*", "*", "kwargs", ")" ]
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/pytorch/pytorchcv/models/resnet.py#L540-L552
bhoov/exbert
d27b6236aa51b185f7d3fed904f25cabe3baeb1a
server/transformers/src/transformers/tokenization_gpt2.py
python
GPT2Tokenizer._convert_token_to_id
(self, token)
return self.encoder.get(token, self.encoder.get(self.unk_token))
Converts a token (str) in an id using the vocab.
Converts a token (str) in an id using the vocab.
[ "Converts", "a", "token", "(", "str", ")", "in", "an", "id", "using", "the", "vocab", "." ]
def _convert_token_to_id(self, token): """ Converts a token (str) in an id using the vocab. """ return self.encoder.get(token, self.encoder.get(self.unk_token))
[ "def", "_convert_token_to_id", "(", "self", ",", "token", ")", ":", "return", "self", ".", "encoder", ".", "get", "(", "token", ",", "self", ".", "encoder", ".", "get", "(", "self", ".", "unk_token", ")", ")" ]
https://github.com/bhoov/exbert/blob/d27b6236aa51b185f7d3fed904f25cabe3baeb1a/server/transformers/src/transformers/tokenization_gpt2.py#L225-L227
CarlosGS/Cyclone-PCB-Factory
2d3136de424a94ea3579a24caf167e540daf0cad
Software/PythonScripts/Replath/pyRepRap/reprap/snap.py
python
_breakHDB1
(HDB1)
return NDB
Decode Header Byte 1 (HDB1)
Decode Header Byte 1 (HDB1)
[ "Decode", "Header", "Byte", "1", "(", "HDB1", ")" ]
def _breakHDB1(HDB1): """Decode Header Byte 1 (HDB1)""" NDB = HDB1 & 0xF return NDB
[ "def", "_breakHDB1", "(", "HDB1", ")", ":", "NDB", "=", "HDB1", "&", "0xF", "return", "NDB" ]
https://github.com/CarlosGS/Cyclone-PCB-Factory/blob/2d3136de424a94ea3579a24caf167e540daf0cad/Software/PythonScripts/Replath/pyRepRap/reprap/snap.py#L331-L334
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/numpy/lib/npyio.py
python
mafromtxt
(fname, **kwargs)
return genfromtxt(fname, **kwargs)
Load ASCII data stored in a text file and return a masked array. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function to load ASCII data.
Load ASCII data stored in a text file and return a masked array.
[ "Load", "ASCII", "data", "stored", "in", "a", "text", "file", "and", "return", "a", "masked", "array", "." ]
def mafromtxt(fname, **kwargs): """ Load ASCII data stored in a text file and return a masked array. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function to load ASCII data. """ kwargs['usemask'] = True return genfromtxt(fname, **kwargs)
[ "def", "mafromtxt", "(", "fname", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'usemask'", "]", "=", "True", "return", "genfromtxt", "(", "fname", ",", "*", "*", "kwargs", ")" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/numpy/lib/npyio.py#L1911-L1925
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/core/config.py
python
get
(key)
Fetch a config value @param key is the config key value
Fetch a config value
[ "Fetch", "a", "config", "value" ]
def get(key): """Fetch a config value @param key is the config key value """ if CONFIG: if key in CONFIG.opts: return CONFIG.opts[key]['value'] elif key in CONFIG._opts: return CONFIG._opts[key]['value']
[ "def", "get", "(", "key", ")", ":", "if", "CONFIG", ":", "if", "key", "in", "CONFIG", ".", "opts", ":", "return", "CONFIG", ".", "opts", "[", "key", "]", "[", "'value'", "]", "elif", "key", "in", "CONFIG", ".", "_opts", ":", "return", "CONFIG", "...
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/core/config.py#L83-L91
python-diamond/Diamond
7000e16cfdf4508ed9291fc4b3800592557b2431
src/collectors/sidekiq/sidekiq.py
python
SidekiqCollector.__publish
(self, port, db, queue, queue_length)
:param port: Redis port :param db: Redis db index to report :param queue: Queue name to report :param queue_length: Queue length to report :return:
:param port: Redis port :param db: Redis db index to report :param queue: Queue name to report :param queue_length: Queue length to report :return:
[ ":", "param", "port", ":", "Redis", "port", ":", "param", "db", ":", "Redis", "db", "index", "to", "report", ":", "param", "queue", ":", "Queue", "name", "to", "report", ":", "param", "queue_length", ":", "Queue", "length", "to", "report", ":", "return...
def __publish(self, port, db, queue, queue_length): """ :param port: Redis port :param db: Redis db index to report :param queue: Queue name to report :param queue_length: Queue length to report :return: """ metric_name_segaments = ['queue'] cluster = self.config['cluster_prefix'] if cluster: metric_name_segaments.append(cluster) metric_name_segaments.append(port) metric_name_segaments.append(str(db)) metric_name_segaments.append(queue) self.publish_gauge( name='.'.join(metric_name_segaments), value=queue_length )
[ "def", "__publish", "(", "self", ",", "port", ",", "db", ",", "queue", ",", "queue_length", ")", ":", "metric_name_segaments", "=", "[", "'queue'", "]", "cluster", "=", "self", ".", "config", "[", "'cluster_prefix'", "]", "if", "cluster", ":", "metric_name...
https://github.com/python-diamond/Diamond/blob/7000e16cfdf4508ed9291fc4b3800592557b2431/src/collectors/sidekiq/sidekiq.py#L153-L170
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/heapq.py
python
merge
(*iterables)
Merge multiple sorted inputs into a single sorted output. Similar to sorted(itertools.chain(*iterables)) but returns a generator, does not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest). >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
Merge multiple sorted inputs into a single sorted output. Similar to sorted(itertools.chain(*iterables)) but returns a generator, does not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest). >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
[ "Merge", "multiple", "sorted", "inputs", "into", "a", "single", "sorted", "output", ".", "Similar", "to", "sorted", "(", "itertools", ".", "chain", "(", "*", "iterables", "))", "but", "returns", "a", "generator", "does", "not", "pull", "the", "data", "into...
def merge(*iterables): """Merge multiple sorted inputs into a single sorted output. Similar to sorted(itertools.chain(*iterables)) but returns a generator, does not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest). >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] """ _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration h = [] h_append = h.append for itnum, it in enumerate(map(iter, iterables)): try: next = it.next h_append([next(), itnum, next]) except _StopIteration: pass heapify(h) while 1: try: while 1: v, itnum, next = s = h[0] yield v s[0] = next() _heapreplace(h, s) except _StopIteration: _heappop(h) except IndexError: return
[ "def", "merge", "(", "*", "iterables", ")", ":", "_heappop", ",", "_heapreplace", ",", "_StopIteration", "=", "heappop", ",", "heapreplace", ",", "StopIteration", "h", "=", "[", "]", "h_append", "=", "h", ".", "append", "for", "itnum", ",", "it", "in", ...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/heapq.py#L178-L211
GetStream/stream-python
142b5b43c0a60a96c36f25b6fc5a224dd2e418cc
stream/client.py
python
StreamClient.track_impressions
(self, impressions)
Creates a list of impressions ;param impressions: Slice of impressions to create. eg. [ { "content_list": ["1", "2", "3"], "features": [ {"group": "topic", "value": "js"}, {"group": "user", "value": "tommaso"}, ], "user_data": {"id": "tommaso", "alias": "tommaso"}, }, { "content_list": ["2", "3", "5"], "features": [{"group": "topic", "value": "js"}], "user_data": {"id": "486892", "alias": "Julian"}, }, ]
Creates a list of impressions
[ "Creates", "a", "list", "of", "impressions" ]
def track_impressions(self, impressions): """ Creates a list of impressions ;param impressions: Slice of impressions to create. eg. [ { "content_list": ["1", "2", "3"], "features": [ {"group": "topic", "value": "js"}, {"group": "user", "value": "tommaso"}, ], "user_data": {"id": "tommaso", "alias": "tommaso"}, }, { "content_list": ["2", "3", "5"], "features": [{"group": "topic", "value": "js"}], "user_data": {"id": "486892", "alias": "Julian"}, }, ] """ auth_token = self.create_jwt_token("*", "*", feed_id="*") self.post("impression/", auth_token, data=impressions, service_name="analytics")
[ "def", "track_impressions", "(", "self", ",", "impressions", ")", ":", "auth_token", "=", "self", ".", "create_jwt_token", "(", "\"*\"", ",", "\"*\"", ",", "feed_id", "=", "\"*\"", ")", "self", ".", "post", "(", "\"impression/\"", ",", "auth_token", ",", "...
https://github.com/GetStream/stream-python/blob/142b5b43c0a60a96c36f25b6fc5a224dd2e418cc/stream/client.py#L527-L552
vlachoudis/bCNC
67126b4894dabf6579baf47af8d0f9b7de35e6e3
bCNC/lib/tkExtra.py
python
ProgressBar.autoText
(self, tmsg)
[]
def autoText(self, tmsg): completed = self.done - self.low if self.low != 0: low = "%d - "%(self.low) else: low = "" self.msg = "Current: %d [%s%d] Completed: %d%% %s" % \ (self.now, low, self.high, int((100*completed)/self.length), tmsg) self.setText(self.msg)
[ "def", "autoText", "(", "self", ",", "tmsg", ")", ":", "completed", "=", "self", ".", "done", "-", "self", ".", "low", "if", "self", ".", "low", "!=", "0", ":", "low", "=", "\"%d - \"", "%", "(", "self", ".", "low", ")", "else", ":", "low", "="...
https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/lib/tkExtra.py#L673-L683
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/distlib/_backport/shutil.py
python
_get_uid
(name)
return None
Returns an uid, given a user name.
Returns an uid, given a user name.
[ "Returns", "an", "uid", "given", "a", "user", "name", "." ]
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "def", "_get_uid", "(", "name", ")", ":", "if", "getpwnam", "is", "None", "or", "name", "is", "None", ":", "return", "None", "try", ":", "result", "=", "getpwnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result", "i...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/distlib/_backport/shutil.py#L361-L371
ARM-DOE/pyart
72affe5b669f1996cd3cc39ec7d8dd29b838bd48
pyart/util/circular_stats.py
python
mean_of_two_angles_deg
(angle1, angle2)
return np.rad2deg( mean_of_two_angles(np.deg2rad(angle1), np.deg2rad(angle2)))
Compute the element by element mean of two sets of angles in degrees. Parameters ---------- angle1 : array First set of angles in degrees. angle2 : array Second set of angles in degrees. Returns ------- mean : array Elements by element angular mean of the two sets of angles in degrees.
Compute the element by element mean of two sets of angles in degrees.
[ "Compute", "the", "element", "by", "element", "mean", "of", "two", "sets", "of", "angles", "in", "degrees", "." ]
def mean_of_two_angles_deg(angle1, angle2): """ Compute the element by element mean of two sets of angles in degrees. Parameters ---------- angle1 : array First set of angles in degrees. angle2 : array Second set of angles in degrees. Returns ------- mean : array Elements by element angular mean of the two sets of angles in degrees. """ return np.rad2deg( mean_of_two_angles(np.deg2rad(angle1), np.deg2rad(angle2)))
[ "def", "mean_of_two_angles_deg", "(", "angle1", ",", "angle2", ")", ":", "return", "np", ".", "rad2deg", "(", "mean_of_two_angles", "(", "np", ".", "deg2rad", "(", "angle1", ")", ",", "np", ".", "deg2rad", "(", "angle2", ")", ")", ")" ]
https://github.com/ARM-DOE/pyart/blob/72affe5b669f1996cd3cc39ec7d8dd29b838bd48/pyart/util/circular_stats.py#L38-L56
debian-calibre/calibre
020fc81d3936a64b2ac51459ecb796666ab6a051
src/calibre/gui2/dialogs/quickview.py
python
Quickview.book_was_changed
(self, mi)
Called when book information is changed in the library view. Make that book info current. This means that prev and next in edit metadata will move the current book and change quickview
Called when book information is changed in the library view. Make that book info current. This means that prev and next in edit metadata will move the current book and change quickview
[ "Called", "when", "book", "information", "is", "changed", "in", "the", "library", "view", ".", "Make", "that", "book", "info", "current", ".", "This", "means", "that", "prev", "and", "next", "in", "edit", "metadata", "will", "move", "the", "current", "book...
def book_was_changed(self, mi): ''' Called when book information is changed in the library view. Make that book info current. This means that prev and next in edit metadata will move the current book and change quickview ''' if self.is_closed or self.current_column is None or not self.follow_library_view: return # There is an ordering problem when libraries are changed. The library # view is changed, triggering a book_was_changed signal. Unfortunately # this happens before the library_changed actions are run, meaning we # still have the old database. To avoid the problem we just ignore the # operation if we get an exception. The "close" will come # eventually. try: self.refresh(self.view.model().index(self.db.row(mi.id), self.current_column)) except: pass
[ "def", "book_was_changed", "(", "self", ",", "mi", ")", ":", "if", "self", ".", "is_closed", "or", "self", ".", "current_column", "is", "None", "or", "not", "self", ".", "follow_library_view", ":", "return", "# There is an ordering problem when libraries are changed...
https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/gui2/dialogs/quickview.py#L462-L479
windelbouwman/ppci
915c069e0667042c085ec42c78e9e3c9a5295324
ppci/ir.py
python
SubRoutine.add_parameter
(self, parameter)
Add an argument to this function
Add an argument to this function
[ "Add", "an", "argument", "to", "this", "function" ]
def add_parameter(self, parameter): """ Add an argument to this function """ assert isinstance(parameter, Parameter) parameter.num = len(self.arguments) self.arguments.append(parameter)
[ "def", "add_parameter", "(", "self", ",", "parameter", ")", ":", "assert", "isinstance", "(", "parameter", ",", "Parameter", ")", "parameter", ".", "num", "=", "len", "(", "self", ".", "arguments", ")", "self", ".", "arguments", ".", "append", "(", "para...
https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/ir.py#L487-L491
stellargraph/stellargraph
3c2c8c18ab4c5c16660f350d8e23d7dc39e738de
stellargraph/interpretability/saliency_maps/integrated_gradients.py
python
IntegratedGradients.__init__
(self, model, generator)
Args: model (Keras model object): The differentiable graph model object. For a dense model, the model.input should contain two tensors: - features: The placeholder of the feature matrix. - adj: The placeholder of the adjacency matrix. For a sparse model, the model.input should contain three tensors: - features: The placeholder of the feature matrix. - adj_index: The placeholder of the adjacency matrix. - adj_values: The placeholder of the adjacency matrix. The model.output (Keras tensor) is the tensor of model prediction output. This is typically the logit or softmax output.
Args: model (Keras model object): The differentiable graph model object. For a dense model, the model.input should contain two tensors: - features: The placeholder of the feature matrix. - adj: The placeholder of the adjacency matrix. For a sparse model, the model.input should contain three tensors: - features: The placeholder of the feature matrix. - adj_index: The placeholder of the adjacency matrix. - adj_values: The placeholder of the adjacency matrix. The model.output (Keras tensor) is the tensor of model prediction output. This is typically the logit or softmax output.
[ "Args", ":", "model", "(", "Keras", "model", "object", ")", ":", "The", "differentiable", "graph", "model", "object", ".", "For", "a", "dense", "model", "the", "model", ".", "input", "should", "contain", "two", "tensors", ":", "-", "features", ":", "The"...
def __init__(self, model, generator): """ Args: model (Keras model object): The differentiable graph model object. For a dense model, the model.input should contain two tensors: - features: The placeholder of the feature matrix. - adj: The placeholder of the adjacency matrix. For a sparse model, the model.input should contain three tensors: - features: The placeholder of the feature matrix. - adj_index: The placeholder of the adjacency matrix. - adj_values: The placeholder of the adjacency matrix. The model.output (Keras tensor) is the tensor of model prediction output. This is typically the logit or softmax output. """ # Set sparse flag from the generator self._is_sparse = generator.use_sparse if self._is_sparse: if not isinstance(generator, SparseFullBatchSequence): raise TypeError( "The generator supplied has to be an object of SparseFullBatchSequence for sparse adjacency matrix." ) if len(model.input) != 4: raise RuntimeError( "Keras model for sparse adjacency is expected to have four inputs" ) self._adj = generator.A_values self._adj_inds = generator.A_indices else: if not isinstance(generator, FullBatchSequence): raise TypeError( "The generator supplied has to be an object of FullBatchSequence for dense adjacency matrix." ) if len(model.input) != 3: raise RuntimeError( "Keras model for dense adjacency is expected to have three inputs" ) self._adj = generator.A_dense # Extract features from generator self._features = generator.features self._model = model
[ "def", "__init__", "(", "self", ",", "model", ",", "generator", ")", ":", "# Set sparse flag from the generator", "self", ".", "_is_sparse", "=", "generator", ".", "use_sparse", "if", "self", ".", "_is_sparse", ":", "if", "not", "isinstance", "(", "generator", ...
https://github.com/stellargraph/stellargraph/blob/3c2c8c18ab4c5c16660f350d8e23d7dc39e738de/stellargraph/interpretability/saliency_maps/integrated_gradients.py#L42-L85
bokeh/bokeh
a00e59da76beb7b9f83613533cfd3aced1df5f06
bokeh/model/util.py
python
visit_immediate_value_references
(value: Unknown, visitor: Callable[[Model], None])
Visit all references to another Model without recursing into any of the child Model; may visit the same Model more than once if it's referenced more than once. Does not visit the passed-in value.
Visit all references to another Model without recursing into any of the child Model; may visit the same Model more than once if it's referenced more than once. Does not visit the passed-in value.
[ "Visit", "all", "references", "to", "another", "Model", "without", "recursing", "into", "any", "of", "the", "child", "Model", ";", "may", "visit", "the", "same", "Model", "more", "than", "once", "if", "it", "s", "referenced", "more", "than", "once", ".", ...
def visit_immediate_value_references(value: Unknown, visitor: Callable[[Model], None]) -> None: ''' Visit all references to another Model without recursing into any of the child Model; may visit the same Model more than once if it's referenced more than once. Does not visit the passed-in value. ''' if isinstance(value, HasProps): for attr in value.properties_with_refs(): child = getattr(value, attr) visit_value_and_its_immediate_references(child, visitor) else: visit_value_and_its_immediate_references(value, visitor)
[ "def", "visit_immediate_value_references", "(", "value", ":", "Unknown", ",", "visitor", ":", "Callable", "[", "[", "Model", "]", ",", "None", "]", ")", "->", "None", ":", "if", "isinstance", "(", "value", ",", "HasProps", ")", ":", "for", "attr", "in", ...
https://github.com/bokeh/bokeh/blob/a00e59da76beb7b9f83613533cfd3aced1df5f06/bokeh/model/util.py#L197-L208
QCoDeS/Qcodes
3cda2cef44812e2aa4672781f2423bf5f816f9f9
qcodes/instrument_drivers/tektronix/AWG5014.py
python
Tektronix_AWG5014.stop
(self)
This command stops the output of a waveform or a sequence.
This command stops the output of a waveform or a sequence.
[ "This", "command", "stops", "the", "output", "of", "a", "waveform", "or", "a", "sequence", "." ]
def stop(self) -> None: """This command stops the output of a waveform or a sequence.""" self.write('AWGControl:STOP')
[ "def", "stop", "(", "self", ")", "->", "None", ":", "self", ".", "write", "(", "'AWGControl:STOP'", ")" ]
https://github.com/QCoDeS/Qcodes/blob/3cda2cef44812e2aa4672781f2423bf5f816f9f9/qcodes/instrument_drivers/tektronix/AWG5014.py#L472-L474
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
example/ctp/futures/ApiStruct.py
python
ExchangeMarginRate.__init__
(self, BrokerID='', InstrumentID='', HedgeFlag=HF_Speculation, LongMarginRatioByMoney=0.0, LongMarginRatioByVolume=0.0, ShortMarginRatioByMoney=0.0, ShortMarginRatioByVolume=0.0)
[]
def __init__(self, BrokerID='', InstrumentID='', HedgeFlag=HF_Speculation, LongMarginRatioByMoney=0.0, LongMarginRatioByVolume=0.0, ShortMarginRatioByMoney=0.0, ShortMarginRatioByVolume=0.0): self.BrokerID = '' #经纪公司代码, char[11] self.InstrumentID = '' #合约代码, char[31] self.HedgeFlag = '' #投机套保标志, char self.LongMarginRatioByMoney = 'Ratio' #多头保证金率, double self.LongMarginRatioByVolume = 'Money' #多头保证金费, double self.ShortMarginRatioByMoney = 'Ratio' #空头保证金率, double self.ShortMarginRatioByVolume = 'Money'
[ "def", "__init__", "(", "self", ",", "BrokerID", "=", "''", ",", "InstrumentID", "=", "''", ",", "HedgeFlag", "=", "HF_Speculation", ",", "LongMarginRatioByMoney", "=", "0.0", ",", "LongMarginRatioByVolume", "=", "0.0", ",", "ShortMarginRatioByMoney", "=", "0.0"...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/ctp/futures/ApiStruct.py#L2428-L2435
electricitymap/electricitymap-contrib
3099e873e1da4c95c7c86f7b14a4e2ac13094cc8
parsers/US_HI.py
python
fetch_production
(zone_key='US-HI-OA', session=None, target_datetime: datetime.datetime = None, logger: logging.Logger = logging.getLogger(__name__))
return data
Requests the last known production mix (in MW) of a given country.
Requests the last known production mix (in MW) of a given country.
[ "Requests", "the", "last", "known", "production", "mix", "(", "in", "MW", ")", "of", "a", "given", "country", "." ]
def fetch_production(zone_key='US-HI-OA', session=None, target_datetime: datetime.datetime = None, logger: logging.Logger = logging.getLogger(__name__)) -> dict: """Requests the last known production mix (in MW) of a given country.""" r = session or requests.session() if target_datetime is None: request_dt = arrow.now("Pacific/Honolulu") res = r.get(BASE_URL + 'limit=1').json() raw_data = res[0] # the first entry returned by the API always has a UTC datetime, but any additional entries are in HST (local time) raw_data['dateTime'] = arrow.get(raw_data['dateTime']).to(tz="Pacific/Honolulu").datetime else: request_dt = arrow.get(target_datetime).to(tz="Pacific/Honolulu") raw_data = get_historical_prod(r, request_dt) if raw_data is None: return None energy_dt = arrow.get(raw_data['dateTime'], tzinfo='Pacific/Honolulu') if validate_prod_timestamp(logger, energy_dt, request_dt) is False: return None production = { 'biomass': float(raw_data['Waste2Energy'] + raw_data['BioFuel']), 'coal': float(raw_data['Coal']), 'oil': float(raw_data['Fossil_Fuel']), 'solar': float(raw_data['Solar']), 'wind': float(raw_data['WindFarm']) } data = { 'zoneKey': zone_key, 'production': production, 'datetime': energy_dt.datetime, 'storage': {}, 'source': 'islandpulse.org' } return data
[ "def", "fetch_production", "(", "zone_key", "=", "'US-HI-OA'", ",", "session", "=", "None", ",", "target_datetime", ":", "datetime", ".", "datetime", "=", "None", ",", "logger", ":", "logging", ".", "Logger", "=", "logging", ".", "getLogger", "(", "__name__"...
https://github.com/electricitymap/electricitymap-contrib/blob/3099e873e1da4c95c7c86f7b14a4e2ac13094cc8/parsers/US_HI.py#L50-L87
Calysto/calysto_scheme
15bf81987870bcae1264e5a0a06feb9a8ee12b8b
calysto_scheme/scheme.py
python
b_cont2_78_d
(k)
[]
def b_cont2_78_d(k): GLOBALS['value1_reg'] = binding_docstring(value1_reg) GLOBALS['k_reg'] = k GLOBALS['pc'] = apply_cont2
[ "def", "b_cont2_78_d", "(", "k", ")", ":", "GLOBALS", "[", "'value1_reg'", "]", "=", "binding_docstring", "(", "value1_reg", ")", "GLOBALS", "[", "'k_reg'", "]", "=", "k", "GLOBALS", "[", "'pc'", "]", "=", "apply_cont2" ]
https://github.com/Calysto/calysto_scheme/blob/15bf81987870bcae1264e5a0a06feb9a8ee12b8b/calysto_scheme/scheme.py#L2910-L2913
ktbyers/pynet
f01ca44afe1db1e64828fc93028f67410174719e
netmiko/load_bgp_config_part3.py
python
check_bgp
(net_connect, cmd='show run | inc router bgp')
return 'bgp' in output
Check whether BGP is currently configured on device. Return boolean
Check whether BGP is currently configured on device. Return boolean
[ "Check", "whether", "BGP", "is", "currently", "configured", "on", "device", ".", "Return", "boolean" ]
def check_bgp(net_connect, cmd='show run | inc router bgp'): """Check whether BGP is currently configured on device. Return boolean""" output = net_connect.send_command_expect(cmd) return 'bgp' in output
[ "def", "check_bgp", "(", "net_connect", ",", "cmd", "=", "'show run | inc router bgp'", ")", ":", "output", "=", "net_connect", ".", "send_command_expect", "(", "cmd", ")", "return", "'bgp'", "in", "output" ]
https://github.com/ktbyers/pynet/blob/f01ca44afe1db1e64828fc93028f67410174719e/netmiko/load_bgp_config_part3.py#L9-L12
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/inject/plugins/dbms/postgresql/takeover.py
python
Takeover.udfSetRemotePath
(self)
[]
def udfSetRemotePath(self): # On Windows if Backend.isOs(OS.WINDOWS): # The DLL can be in any folder where postgres user has # read/write/execute access is valid # NOTE: by not specifing any path, it will save into the # data directory, on PostgreSQL 8.3 it is # C:\Program Files\PostgreSQL\8.3\data. self.udfRemoteFile = "%s.%s" % (self.udfSharedLibName, self.udfSharedLibExt) # On Linux else: # The SO can be in any folder where postgres user has # read/write/execute access is valid self.udfRemoteFile = "/tmp/%s.%s" % (self.udfSharedLibName, self.udfSharedLibExt)
[ "def", "udfSetRemotePath", "(", "self", ")", ":", "# On Windows", "if", "Backend", ".", "isOs", "(", "OS", ".", "WINDOWS", ")", ":", "# The DLL can be in any folder where postgres user has", "# read/write/execute access is valid", "# NOTE: by not specifing any path, it will sav...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/inject/plugins/dbms/postgresql/takeover.py#L27-L41
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/python-openid-2.2.5/openid/extensions/ax.py
python
FetchResponse.__init__
(self, request=None, update_url=None)
@param request: When supplied, I will use namespace aliases that match those in this request. I will also check to make sure I do not respond with attributes that were not requested. @type request: L{FetchRequest} @param update_url: By default, C{update_url} is taken from the request. But if you do not supply the request, you may set the C{update_url} here. @type update_url: str
@param request: When supplied, I will use namespace aliases that match those in this request. I will also check to make sure I do not respond with attributes that were not requested.
[ "@param", "request", ":", "When", "supplied", "I", "will", "use", "namespace", "aliases", "that", "match", "those", "in", "this", "request", ".", "I", "will", "also", "check", "to", "make", "sure", "I", "do", "not", "respond", "with", "attributes", "that",...
def __init__(self, request=None, update_url=None): """ @param request: When supplied, I will use namespace aliases that match those in this request. I will also check to make sure I do not respond with attributes that were not requested. @type request: L{FetchRequest} @param update_url: By default, C{update_url} is taken from the request. But if you do not supply the request, you may set the C{update_url} here. @type update_url: str """ AXKeyValueMessage.__init__(self) self.update_url = update_url self.request = request
[ "def", "__init__", "(", "self", ",", "request", "=", "None", ",", "update_url", "=", "None", ")", ":", "AXKeyValueMessage", ".", "__init__", "(", "self", ")", "self", ".", "update_url", "=", "update_url", "self", ".", "request", "=", "request" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/python-openid-2.2.5/openid/extensions/ax.py#L597-L614
projecthamster/hamster
19d160090de30e756bdc3122ff935bdaa86e2843
waflib/Logs.py
python
log_handler.emit
(self, record)
Delegates the functionality to :py:meth:`waflib.Log.log_handler.emit_override`
Delegates the functionality to :py:meth:`waflib.Log.log_handler.emit_override`
[ "Delegates", "the", "functionality", "to", ":", "py", ":", "meth", ":", "waflib", ".", "Log", ".", "log_handler", ".", "emit_override" ]
def emit(self, record): """ Delegates the functionality to :py:meth:`waflib.Log.log_handler.emit_override` """ # default implementation try: try: self.stream = record.stream except AttributeError: if record.levelno >= logging.WARNING: record.stream = self.stream = sys.stderr else: record.stream = self.stream = sys.stdout self.emit_override(record) self.flush() except (KeyboardInterrupt, SystemExit): raise except: # from the python library -_- self.handleError(record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "# default implementation", "try", ":", "try", ":", "self", ".", "stream", "=", "record", ".", "stream", "except", "AttributeError", ":", "if", "record", ".", "levelno", ">=", "logging", ".", "WARNING", ...
https://github.com/projecthamster/hamster/blob/19d160090de30e756bdc3122ff935bdaa86e2843/waflib/Logs.py#L159-L177
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/packaging/version.py
python
_legacy_cmpkey
(version: str)
return epoch, tuple(parts)
[]
def _legacy_cmpkey(version: str) -> LegacyCmpKey: # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch # greater than or equal to 0. This will effectively put the LegacyVersion, # which uses the defacto standard originally implemented by setuptools, # as before all PEP 440 versions. epoch = -1 # This scheme is taken from pkg_resources.parse_version setuptools prior to # it's adoption of the packaging library. parts: List[str] = [] for part in _parse_version_parts(version.lower()): if part.startswith("*"): # remove "-" before a prerelease tag if part < "*final": while parts and parts[-1] == "*final-": parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1] == "00000000": parts.pop() parts.append(part) return epoch, tuple(parts)
[ "def", "_legacy_cmpkey", "(", "version", ":", "str", ")", "->", "LegacyCmpKey", ":", "# We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch", "# greater than or equal to 0. This will effectively put the LegacyVersion,", "# which uses the defacto standard originally imple...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/packaging/version.py#L196-L220
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/lib2to3/pgen2/driver.py
python
Driver.parse_stream_raw
(self, stream, debug=False)
return self.parse_tokens(tokens, debug)
Parse a stream and return the syntax tree.
Parse a stream and return the syntax tree.
[ "Parse", "a", "stream", "and", "return", "the", "syntax", "tree", "." ]
def parse_stream_raw(self, stream, debug=False): """Parse a stream and return the syntax tree.""" tokens = tokenize.generate_tokens(stream.readline) return self.parse_tokens(tokens, debug)
[ "def", "parse_stream_raw", "(", "self", ",", "stream", ",", "debug", "=", "False", ")", ":", "tokens", "=", "tokenize", ".", "generate_tokens", "(", "stream", ".", "readline", ")", "return", "self", ".", "parse_tokens", "(", "tokens", ",", "debug", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/lib2to3/pgen2/driver.py#L86-L89
timknip/pyswf
3740cc80d7650156831e728ea0d408819e5671eb
swf/movie.py
python
SWF.parse
(self, data)
Parses the SWF. The @data parameter can be a file object or a SWFStream
Parses the SWF. The
[ "Parses", "the", "SWF", ".", "The" ]
def parse(self, data): """ Parses the SWF. The @data parameter can be a file object or a SWFStream """ self._data = data = data if isinstance(data, SWFStream) else SWFStream(data) self._header = SWFHeader(self._data) if self._header.compressed: temp = BytesIO() if self._header.compressed_zlib: import zlib data = data.f.read() zip = zlib.decompressobj() temp.write(zip.decompress(data)) else: import pylzma data.readUI32() #consume compressed length data = data.f.read() temp.write(pylzma.decompress(data)) temp.seek(0) data = SWFStream(temp) self._header._frame_size = data.readRECT() self._header._frame_rate = data.readFIXED8() self._header._frame_count = data.readUI16() self.parse_tags(data)
[ "def", "parse", "(", "self", ",", "data", ")", ":", "self", ".", "_data", "=", "data", "=", "data", "if", "isinstance", "(", "data", ",", "SWFStream", ")", "else", "SWFStream", "(", "data", ")", "self", ".", "_header", "=", "SWFHeader", "(", "self", ...
https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/movie.py#L137-L162
pypa/pip
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
src/pip/_vendor/pkg_resources/__init__.py
python
ResourceManager.resource_filename
(self, package_or_requirement, resource_name)
return get_provider(package_or_requirement).get_resource_filename( self, resource_name )
Return a true filesystem path for specified resource
Return a true filesystem path for specified resource
[ "Return", "a", "true", "filesystem", "path", "for", "specified", "resource" ]
def resource_filename(self, package_or_requirement, resource_name): """Return a true filesystem path for specified resource""" return get_provider(package_or_requirement).get_resource_filename( self, resource_name )
[ "def", "resource_filename", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "get_resource_filename", "(", "self", ",", "resource_name", ")" ]
https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/pkg_resources/__init__.py#L1142-L1146
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/zope/interface/interfaces.py
python
IDeclaration.__iter__
()
Return an iterator for the interfaces in the specification
Return an iterator for the interfaces in the specification
[ "Return", "an", "iterator", "for", "the", "interfaces", "in", "the", "specification" ]
def __iter__(): """Return an iterator for the interfaces in the specification """
[ "def", "__iter__", "(", ")", ":" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/zope/interface/interfaces.py#L317-L319
modflowpy/flopy
eecd1ad193c5972093c9712e5c4b7a83284f0688
flopy/modpath/mp7particlegroup.py
python
ParticleGroupLRCTemplate.write
(self, fp=None, ws=".")
return
Parameters ---------- fp : fileobject Fileobject that is open with write access ws : str Workspace for particle data Returns -------
[]
def write(self, fp=None, ws="."): """ Parameters ---------- fp : fileobject Fileobject that is open with write access ws : str Workspace for particle data Returns ------- """ # validate that a valid file object was passed if not hasattr(fp, "write"): raise ValueError( "{}: cannot write data for template without passing a valid " "file object ({}) open for writing".format(self.name, fp) ) # call base class write method to write common data _Modpath7ParticleGroup.write(self, fp, ws) # open external file if required if self.external: fpth = os.path.join(ws, self.filename) f = open(fpth, "w") else: f = fp # item 1 f.write(f"{self.inputstyle}\n") # items 2, 3, 4 or 5, and 6 self.particledata.write(f) # close the external file if self.external: f.close() return
[ "def", "write", "(", "self", ",", "fp", "=", "None", ",", "ws", "=", "\".\"", ")", ":", "# validate that a valid file object was passed", "if", "not", "hasattr", "(", "fp", ",", "\"write\"", ")", ":", "raise", "ValueError", "(", "\"{}: cannot write data for temp...
https://github.com/modflowpy/flopy/blob/eecd1ad193c5972093c9712e5c4b7a83284f0688/flopy/modpath/mp7particlegroup.py#L377-L418
accel-brain/accel-brain-code
86f489dc9be001a3bae6d053f48d6b57c0bedb95
Algorithm-Wars/algowars/noisesampler/volatility_conditional_noise_sampler.py
python
VolatilityConditionalNoiseSampler.__init__
( self, extractable_historical_data, ticker_list, start_date, end_date, batch_size=20, seq_len=10, channel=3, target_features_list=None, diff_mode=False, log_mode=False, lstm_mode=True, ctx=mx.gpu() )
Init. Args: extractable_historical_data: is-a `ExtractableHistoricalData`. ticker_list: `list` of tickers. start_date: `str` of start date. end_date: `str` of end date. batch_size: Batch size. seq_len: The length of sequneces. channel: Channel. target_features_list: `list` of target feature list. diff_mode: `bool`. If `True`, this class outputs difference sequences. log_mode: `bool`. If `True`, this class outputs logarithmic rates of change. lstm_mode: `bool`. If `True`, this class converts data for LSTM model. ctx: `mx.gpu()` or `mx.cpu()`.
Init.
[ "Init", "." ]
def __init__( self, extractable_historical_data, ticker_list, start_date, end_date, batch_size=20, seq_len=10, channel=3, target_features_list=None, diff_mode=False, log_mode=False, lstm_mode=True, ctx=mx.gpu() ): ''' Init. Args: extractable_historical_data: is-a `ExtractableHistoricalData`. ticker_list: `list` of tickers. start_date: `str` of start date. end_date: `str` of end date. batch_size: Batch size. seq_len: The length of sequneces. channel: Channel. target_features_list: `list` of target feature list. diff_mode: `bool`. If `True`, this class outputs difference sequences. log_mode: `bool`. If `True`, this class outputs logarithmic rates of change. lstm_mode: `bool`. If `True`, this class converts data for LSTM model. ctx: `mx.gpu()` or `mx.cpu()`. ''' if isinstance(extractable_historical_data, ExtractableHistoricalData) is False: raise TypeError() self.__extractable_historical_data = extractable_historical_data self.__batch_size = batch_size self.__seq_len = seq_len self.__channel = channel self.__ticker_list = ticker_list self.__start_date = start_date self.__end_date = end_date if target_features_list is not None: self.__target_features_list = target_features_list self.__dim = len(self.__target_features_list) if lstm_mode is True and len(target_features_list) > 1: raise ValueError() self.__lstm_mode = lstm_mode self.__diff_mode = diff_mode self.__normlized_flag = False self.__log_mode = log_mode self.setup_data() self.__ctx = ctx
[ "def", "__init__", "(", "self", ",", "extractable_historical_data", ",", "ticker_list", ",", "start_date", ",", "end_date", ",", "batch_size", "=", "20", ",", "seq_len", "=", "10", ",", "channel", "=", "3", ",", "target_features_list", "=", "None", ",", "dif...
https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Algorithm-Wars/algowars/noisesampler/volatility_conditional_noise_sampler.py#L38-L93
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/ma/extras.py
python
notmasked_edges
(a, axis=None)
return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]), tuple([idx[i].max(axis).compressed() for i in range(a.ndim)]), ]
Find the indices of the first and last unmasked values along an axis. If all values are masked, return None. Otherwise, return a list of two tuples, corresponding to the indices of the first and last unmasked values respectively. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flattened version of the array. Returns ------- edges : ndarray or list An array of start and end indexes if there are any masked data in the array. If there are no masked data in the array, `edges` is a list of the first and last index. See Also -------- flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous, clump_masked, clump_unmasked Examples -------- >>> a = np.arange(9).reshape((3, 3)) >>> m = np.zeros_like(a) >>> m[1:, 1:] = 1 >>> am = np.ma.array(a, mask=m) >>> np.array(am[~am.mask]) array([0, 1, 2, 3, 6]) >>> np.ma.notmasked_edges(ma) array([0, 6])
Find the indices of the first and last unmasked values along an axis.
[ "Find", "the", "indices", "of", "the", "first", "and", "last", "unmasked", "values", "along", "an", "axis", "." ]
def notmasked_edges(a, axis=None): """ Find the indices of the first and last unmasked values along an axis. If all values are masked, return None. Otherwise, return a list of two tuples, corresponding to the indices of the first and last unmasked values respectively. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flattened version of the array. Returns ------- edges : ndarray or list An array of start and end indexes if there are any masked data in the array. If there are no masked data in the array, `edges` is a list of the first and last index. See Also -------- flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous, clump_masked, clump_unmasked Examples -------- >>> a = np.arange(9).reshape((3, 3)) >>> m = np.zeros_like(a) >>> m[1:, 1:] = 1 >>> am = np.ma.array(a, mask=m) >>> np.array(am[~am.mask]) array([0, 1, 2, 3, 6]) >>> np.ma.notmasked_edges(ma) array([0, 6]) """ a = asarray(a) if axis is None or a.ndim == 1: return flatnotmasked_edges(a) m = getmaskarray(a) idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim)) return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]), tuple([idx[i].max(axis).compressed() for i in range(a.ndim)]), ]
[ "def", "notmasked_edges", "(", "a", ",", "axis", "=", "None", ")", ":", "a", "=", "asarray", "(", "a", ")", "if", "axis", "is", "None", "or", "a", ".", "ndim", "==", "1", ":", "return", "flatnotmasked_edges", "(", "a", ")", "m", "=", "getmaskarray"...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/ma/extras.py#L1642-L1690
freedombox/FreedomBox
335a7f92cc08f27981f838a7cddfc67740598e54
plinth/modules/backups/repository.py
python
BaseBorgRepository._run
(self, cmd, arguments, superuser=True, **kwargs)
Run a backups or sshfs action script command.
Run a backups or sshfs action script command.
[ "Run", "a", "backups", "or", "sshfs", "action", "script", "command", "." ]
def _run(self, cmd, arguments, superuser=True, **kwargs): """Run a backups or sshfs action script command.""" try: if superuser: return actions.superuser_run(cmd, arguments, **kwargs) return actions.run(cmd, arguments, **kwargs) except ActionError as err: self.reraise_known_error(err)
[ "def", "_run", "(", "self", ",", "cmd", ",", "arguments", ",", "superuser", "=", "True", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "superuser", ":", "return", "actions", ".", "superuser_run", "(", "cmd", ",", "arguments", ",", "*", "*", ...
https://github.com/freedombox/FreedomBox/blob/335a7f92cc08f27981f838a7cddfc67740598e54/plinth/modules/backups/repository.py#L212-L220
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_serviceaccount.py
python
ServiceAccount.secrets
(self)
return self._secrets
property for secrets
property for secrets
[ "property", "for", "secrets" ]
def secrets(self): ''' property for secrets ''' if not self._secrets: self._secrets = self.get(ServiceAccount.secrets_path) or [] return self._secrets
[ "def", "secrets", "(", "self", ")", ":", "if", "not", "self", ".", "_secrets", ":", "self", ".", "_secrets", "=", "self", ".", "get", "(", "ServiceAccount", ".", "secrets_path", ")", "or", "[", "]", "return", "self", ".", "_secrets" ]
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_serviceaccount.py#L1519-L1523
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/urllib2.py
python
CacheFTPHandler.setMaxConns
(self, m)
[]
def setMaxConns(self, m): self.max_conns = m
[ "def", "setMaxConns", "(", "self", ",", "m", ")", ":", "self", ".", "max_conns", "=", "m" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/urllib2.py#L1452-L1453
prlz77/ResNeXt.pytorch
39fb8d03847f26ec02fb9b880ecaaa88db7a7d16
models/model.py
python
ResNeXtBottleneck.__init__
(self, in_channels, out_channels, stride, cardinality, base_width, widen_factor)
Constructor Args: in_channels: input channel dimensionality out_channels: output channel dimensionality stride: conv stride. Replaces pooling layer. cardinality: num of convolution groups. base_width: base number of channels in each group. widen_factor: factor to reduce the input dimensionality before convolution.
Constructor
[ "Constructor" ]
def __init__(self, in_channels, out_channels, stride, cardinality, base_width, widen_factor): """ Constructor Args: in_channels: input channel dimensionality out_channels: output channel dimensionality stride: conv stride. Replaces pooling layer. cardinality: num of convolution groups. base_width: base number of channels in each group. widen_factor: factor to reduce the input dimensionality before convolution. """ super(ResNeXtBottleneck, self).__init__() width_ratio = out_channels / (widen_factor * 64.) D = cardinality * int(base_width * width_ratio) self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=1, padding=0, bias=False) self.bn_reduce = nn.BatchNorm2d(D) self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False) self.bn = nn.BatchNorm2d(D) self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride=1, padding=0, bias=False) self.bn_expand = nn.BatchNorm2d(out_channels) self.shortcut = nn.Sequential() if in_channels != out_channels: self.shortcut.add_module('shortcut_conv', nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, padding=0, bias=False)) self.shortcut.add_module('shortcut_bn', nn.BatchNorm2d(out_channels))
[ "def", "__init__", "(", "self", ",", "in_channels", ",", "out_channels", ",", "stride", ",", "cardinality", ",", "base_width", ",", "widen_factor", ")", ":", "super", "(", "ResNeXtBottleneck", ",", "self", ")", ".", "__init__", "(", ")", "width_ratio", "=", ...
https://github.com/prlz77/ResNeXt.pytorch/blob/39fb8d03847f26ec02fb9b880ecaaa88db7a7d16/models/model.py#L26-L52
spender-sandbox/cuckoo-modified
eb93ef3d41b8fee51b4330306dcd315d8101e021
lib/cuckoo/common/peepdf/PDFCore.py
python
PDFDictionary.getURLs
(self)
return self.urlsFound
Gets the URLs of the object @return: An array of URLs
Gets the URLs of the object
[ "Gets", "the", "URLs", "of", "the", "object" ]
def getURLs(self): ''' Gets the URLs of the object @return: An array of URLs ''' return self.urlsFound
[ "def", "getURLs", "(", "self", ")", ":", "return", "self", ".", "urlsFound" ]
https://github.com/spender-sandbox/cuckoo-modified/blob/eb93ef3d41b8fee51b4330306dcd315d8101e021/lib/cuckoo/common/peepdf/PDFCore.py#L1484-L1490
NVlabs/STEP
59da38af240869fa6f1bc565803cff34aafdaa99
external/ActivityNet/Evaluation/ava/np_box_mask_list_ops.py
python
intersection
(box_mask_list1, box_mask_list2)
return np_mask_ops.intersection(box_mask_list1.get_masks(), box_mask_list2.get_masks())
Compute pairwise intersection areas between masks. Args: box_mask_list1: BoxMaskList holding N boxes and masks box_mask_list2: BoxMaskList holding M boxes and masks Returns: a numpy array with shape [N*M] representing pairwise intersection area
Compute pairwise intersection areas between masks.
[ "Compute", "pairwise", "intersection", "areas", "between", "masks", "." ]
def intersection(box_mask_list1, box_mask_list2): """Compute pairwise intersection areas between masks. Args: box_mask_list1: BoxMaskList holding N boxes and masks box_mask_list2: BoxMaskList holding M boxes and masks Returns: a numpy array with shape [N*M] representing pairwise intersection area """ return np_mask_ops.intersection(box_mask_list1.get_masks(), box_mask_list2.get_masks())
[ "def", "intersection", "(", "box_mask_list1", ",", "box_mask_list2", ")", ":", "return", "np_mask_ops", ".", "intersection", "(", "box_mask_list1", ".", "get_masks", "(", ")", ",", "box_mask_list2", ".", "get_masks", "(", ")", ")" ]
https://github.com/NVlabs/STEP/blob/59da38af240869fa6f1bc565803cff34aafdaa99/external/ActivityNet/Evaluation/ava/np_box_mask_list_ops.py#L65-L76
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/macpath.py
python
expandvars
(path)
return path
Dummy to retain interface-compatibility with other operating systems.
Dummy to retain interface-compatibility with other operating systems.
[ "Dummy", "to", "retain", "interface", "-", "compatibility", "with", "other", "operating", "systems", "." ]
def expandvars(path): """Dummy to retain interface-compatibility with other operating systems.""" return path
[ "def", "expandvars", "(", "path", ")", ":", "return", "path" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/macpath.py#L140-L142
mrlesmithjr/Ansible
d44f0dc0d942bdf3bf7334b307e6048f0ee16e36
roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/setuptools/command/easy_install.py
python
samefile
(p1, p2)
return norm_p1 == norm_p2
Determine if two paths reference the same file. Augments os.path.samefile to work on Windows and suppresses errors if the path doesn't exist.
Determine if two paths reference the same file.
[ "Determine", "if", "two", "paths", "reference", "the", "same", "file", "." ]
def samefile(p1, p2): """ Determine if two paths reference the same file. Augments os.path.samefile to work on Windows and suppresses errors if the path doesn't exist. """ both_exist = os.path.exists(p1) and os.path.exists(p2) use_samefile = hasattr(os.path, 'samefile') and both_exist if use_samefile: return os.path.samefile(p1, p2) norm_p1 = os.path.normpath(os.path.normcase(p1)) norm_p2 = os.path.normpath(os.path.normcase(p2)) return norm_p1 == norm_p2
[ "def", "samefile", "(", "p1", ",", "p2", ")", ":", "both_exist", "=", "os", ".", "path", ".", "exists", "(", "p1", ")", "and", "os", ".", "path", ".", "exists", "(", "p2", ")", "use_samefile", "=", "hasattr", "(", "os", ".", "path", ",", "'samefi...
https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/setuptools/command/easy_install.py#L77-L90
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/asyncio/selector_events.py
python
BaseSelectorEventLoop.remove_reader
(self, fd)
Remove a reader callback.
Remove a reader callback.
[ "Remove", "a", "reader", "callback", "." ]
def remove_reader(self, fd): """Remove a reader callback.""" if self.is_closed(): return False try: key = self._selector.get_key(fd) except KeyError: return False else: mask, (reader, writer) = key.events, key.data mask &= ~selectors.EVENT_READ if not mask: self._selector.unregister(fd) else: self._selector.modify(fd, mask, (None, writer)) if reader is not None: reader.cancel() return True else: return False
[ "def", "remove_reader", "(", "self", ",", "fd", ")", ":", "if", "self", ".", "is_closed", "(", ")", ":", "return", "False", "try", ":", "key", "=", "self", ".", "_selector", ".", "get_key", "(", "fd", ")", "except", "KeyError", ":", "return", "False"...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/asyncio/selector_events.py#L245-L265
natashamjaques/neural_chat
ddb977bb4602a67c460d02231e7bbf7b2cb49a97
ParlAI/parlai/mturk/core/worlds.py
python
MTurkTaskWorld.review_work
(self)
Programmatically approve/reject the turker's work. Doing this now (if possible) means that you don't need to do the work of reviewing later on. For example: .. code-block:: python if self.turker_response == '0': self.mturk_agent.reject_work( 'You rated our model's response as a 0/10 but we ' 'know we\'re better than that' ) else: if self.turker_response == '10': self.mturk_agent.pay_bonus(1, 'Thanks for a great rating!') self.mturk_agent.approve_work()
Programmatically approve/reject the turker's work. Doing this now (if possible) means that you don't need to do the work of reviewing later on.
[ "Programmatically", "approve", "/", "reject", "the", "turker", "s", "work", ".", "Doing", "this", "now", "(", "if", "possible", ")", "means", "that", "you", "don", "t", "need", "to", "do", "the", "work", "of", "reviewing", "later", "on", "." ]
def review_work(self): """Programmatically approve/reject the turker's work. Doing this now (if possible) means that you don't need to do the work of reviewing later on. For example: .. code-block:: python if self.turker_response == '0': self.mturk_agent.reject_work( 'You rated our model's response as a 0/10 but we ' 'know we\'re better than that' ) else: if self.turker_response == '10': self.mturk_agent.pay_bonus(1, 'Thanks for a great rating!') self.mturk_agent.approve_work() """ # self.mturk_agent.approve_work() # self.mturk_agent.reject_work() # self.mturk_agent.pay_bonus(1000) # Pay $1000 as bonus # self.mturk_agent.block_worker() # Block this worker from future HITs pass
[ "def", "review_work", "(", "self", ")", ":", "# self.mturk_agent.approve_work()", "# self.mturk_agent.reject_work()", "# self.mturk_agent.pay_bonus(1000) # Pay $1000 as bonus", "# self.mturk_agent.block_worker() # Block this worker from future HITs", "pass" ]
https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/mturk/core/worlds.py#L107-L128
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
Utils/Download.py
python
SizeReportingFile.read
(self, size)
return file.read(self, size)
[]
def read(self, size): global pbar #self.readSize += size if pbar != None: percent = int(self.tell() * 100 / self.totalSize) percent = max(0, min(percent, 100)) # clamp pbar.update(percent) return file.read(self, size)
[ "def", "read", "(", "self", ",", "size", ")", ":", "global", "pbar", "#self.readSize += size", "if", "pbar", "!=", "None", ":", "percent", "=", "int", "(", "self", ".", "tell", "(", ")", "*", "100", "/", "self", ".", "totalSize", ")", "percent", "=",...
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/Utils/Download.py#L39-L46
slackapi/python-slack-sdk
2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7
slack_sdk/web/legacy_client.py
python
LegacyWebClient.admin_teams_admins_list
( self, *, team_id: str, cursor: Optional[str] = None, limit: Optional[int] = None, **kwargs, )
return self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
List all of the admins on a given workspace. https://api.slack.com/methods/admin.inviteRequests.list
List all of the admins on a given workspace. https://api.slack.com/methods/admin.inviteRequests.list
[ "List", "all", "of", "the", "admins", "on", "a", "given", "workspace", ".", "https", ":", "//", "api", ".", "slack", ".", "com", "/", "methods", "/", "admin", ".", "inviteRequests", ".", "list" ]
def admin_teams_admins_list( self, *, team_id: str, cursor: Optional[str] = None, limit: Optional[int] = None, **kwargs, ) -> Union[Future, SlackResponse]: """List all of the admins on a given workspace. https://api.slack.com/methods/admin.inviteRequests.list """ kwargs.update( { "cursor": cursor, "limit": limit, "team_id": team_id, } ) return self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
[ "def", "admin_teams_admins_list", "(", "self", ",", "*", ",", "team_id", ":", "str", ",", "cursor", ":", "Optional", "[", "str", "]", "=", "None", ",", "limit", ":", "Optional", "[", "int", "]", "=", "None", ",", "*", "*", "kwargs", ",", ")", "->",...
https://github.com/slackapi/python-slack-sdk/blob/2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7/slack_sdk/web/legacy_client.py#L1109-L1127
HonglinChu/SiamTrackers
8471660b14f970578a43f077b28207d44a27e867
SiamRPN/SiamRPN/siamrpn/bbox_util.py
python
clip_box
(bbox, clip_box, alpha)
return bbox
Clip the bounding boxes to the borders of an image Parameters ---------- bbox: numpy.ndarray Numpy array containing bounding boxes of shape `N X 4` where N is the number of bounding boxes and the bounding boxes are represented in the format `x1 y1 x2 y2` clip_box: numpy.ndarray An array of shape (4,) specifying the diagonal co-ordinates of the image The coordinates are represented in the format `x1 y1 x2 y2` alpha: float If the fraction of a bounding box left in the image after being clipped is less than `alpha` the bounding box is dropped. Returns ------- numpy.ndarray Numpy array containing **clipped** bounding boxes of shape `N X 4` where N is the number of bounding boxes left are being clipped and the bounding boxes are represented in the format `x1 y1 x2 y2`
Clip the bounding boxes to the borders of an image Parameters ---------- bbox: numpy.ndarray Numpy array containing bounding boxes of shape `N X 4` where N is the number of bounding boxes and the bounding boxes are represented in the format `x1 y1 x2 y2` clip_box: numpy.ndarray An array of shape (4,) specifying the diagonal co-ordinates of the image The coordinates are represented in the format `x1 y1 x2 y2` alpha: float If the fraction of a bounding box left in the image after being clipped is less than `alpha` the bounding box is dropped. Returns ------- numpy.ndarray Numpy array containing **clipped** bounding boxes of shape `N X 4` where N is the number of bounding boxes left are being clipped and the bounding boxes are represented in the format `x1 y1 x2 y2`
[ "Clip", "the", "bounding", "boxes", "to", "the", "borders", "of", "an", "image", "Parameters", "----------", "bbox", ":", "numpy", ".", "ndarray", "Numpy", "array", "containing", "bounding", "boxes", "of", "shape", "N", "X", "4", "where", "N", "is", "the",...
def clip_box(bbox, clip_box, alpha): """Clip the bounding boxes to the borders of an image Parameters ---------- bbox: numpy.ndarray Numpy array containing bounding boxes of shape `N X 4` where N is the number of bounding boxes and the bounding boxes are represented in the format `x1 y1 x2 y2` clip_box: numpy.ndarray An array of shape (4,) specifying the diagonal co-ordinates of the image The coordinates are represented in the format `x1 y1 x2 y2` alpha: float If the fraction of a bounding box left in the image after being clipped is less than `alpha` the bounding box is dropped. Returns ------- numpy.ndarray Numpy array containing **clipped** bounding boxes of shape `N X 4` where N is the number of bounding boxes left are being clipped and the bounding boxes are represented in the format `x1 y1 x2 y2` """ ar_ = (bbox_area(bbox)) x_min = np.maximum(bbox[:,0], clip_box[0]).reshape(-1,1) y_min = np.maximum(bbox[:,1], clip_box[1]).reshape(-1,1) x_max = np.minimum(bbox[:,2], clip_box[2]).reshape(-1,1) y_max = np.minimum(bbox[:,3], clip_box[3]).reshape(-1,1) bbox = np.hstack((x_min, y_min, x_max, y_max, bbox[:,4:])) delta_area = ((ar_ - bbox_area(bbox))/ar_) mask = (delta_area < (1 - alpha)).astype(int) bbox = bbox[mask == 1,:] return bbox
[ "def", "clip_box", "(", "bbox", ",", "clip_box", ",", "alpha", ")", ":", "ar_", "=", "(", "bbox_area", "(", "bbox", ")", ")", "x_min", "=", "np", ".", "maximum", "(", "bbox", "[", ":", ",", "0", "]", ",", "clip_box", "[", "0", "]", ")", ".", ...
https://github.com/HonglinChu/SiamTrackers/blob/8471660b14f970578a43f077b28207d44a27e867/SiamRPN/SiamRPN/siamrpn/bbox_util.py#L46-L89
glumpy/glumpy
46a7635c08d3a200478397edbe0371a6c59cd9d7
glumpy/ext/png.py
python
_add_common_options
(parser)
return parser
Call *parser.add_option* for each of the options that are common between this PNG--PNM conversion tool and the gen tool.
Call *parser.add_option* for each of the options that are common between this PNG--PNM conversion tool and the gen tool.
[ "Call", "*", "parser", ".", "add_option", "*", "for", "each", "of", "the", "options", "that", "are", "common", "between", "this", "PNG", "--", "PNM", "conversion", "tool", "and", "the", "gen", "tool", "." ]
def _add_common_options(parser): """Call *parser.add_option* for each of the options that are common between this PNG--PNM conversion tool and the gen tool. """ parser.add_option("-i", "--interlace", default=False, action="store_true", help="create an interlaced PNG file (Adam7)") parser.add_option("-t", "--transparent", action="store", type="string", metavar="#RRGGBB", help="mark the specified colour as transparent") parser.add_option("-b", "--background", action="store", type="string", metavar="#RRGGBB", help="save the specified background colour") parser.add_option("-g", "--gamma", action="store", type="float", metavar="value", help="save the specified gamma value") parser.add_option("-c", "--compression", action="store", type="int", metavar="level", help="zlib compression level (0-9)") return parser
[ "def", "_add_common_options", "(", "parser", ")", ":", "parser", ".", "add_option", "(", "\"-i\"", ",", "\"--interlace\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"create an interlaced PNG file (Adam7)\"", ")", "pars...
https://github.com/glumpy/glumpy/blob/46a7635c08d3a200478397edbe0371a6c59cd9d7/glumpy/ext/png.py#L2638-L2658
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/lobotomy/core/logging/logger.py
python
Logger.binja_log
(self, t, m)
Log a message to the console. Args: param1: Type of log {info, warn, critical} param2: Log message Returns: None
Log a message to the console.
[ "Log", "a", "message", "to", "the", "console", "." ]
def binja_log(self, t, m): """ Log a message to the console. Args: param1: Type of log {info, warn, critical} param2: Log message Returns: None """ if t == "info": print(self.t.cyan("[{}] ".format(datetime.now())) + "{}".format(m)) elif t == "critical": print(self.t.red("[{}] ".format(datetime.now())) + self.t.white("{}".format(m)))
[ "def", "binja_log", "(", "self", ",", "t", ",", "m", ")", ":", "if", "t", "==", "\"info\"", ":", "print", "(", "self", ".", "t", ".", "cyan", "(", "\"[{}] \"", ".", "format", "(", "datetime", ".", "now", "(", ")", ")", ")", "+", "\"{}\"", ".", ...
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/lobotomy/core/logging/logger.py#L47-L61
bbfamily/abu
2de85ae57923a720dac99a545b4f856f6b87304b
abupy/CoreBu/ABuBase.py
python
PickleStateMixin.__setstate__
(self, state)
开始从本地序列化文件转换为python对象,即unpick
开始从本地序列化文件转换为python对象,即unpick
[ "开始从本地序列化文件转换为python对象,即unpick" ]
def __setstate__(self, state): """开始从本地序列化文件转换为python对象,即unpick""" # 从本地序列化文件中读取的pickle的最高支持版本, 默认0 pickle_highest_protocol = state.pop("_pickle_highest_protocol", 0) # 从本地序列化文件中读取的abupy的版本号, 默认0.0.1 old_abupy_version = state.pop("_abupy_version", '0.0.1') # 从本地序列化文件中读取的python版本号, 默认2.7.0 python_version = state.pop("_python_version", '2.7.0') # 从本地序列化文件中读取的平台信息, 默认False,即windows platform_version = state.pop("_is_mac_os", False) if self.skip_abupy_version: # 忽略abupy的版本号 _abupy_version = old_abupy_version else: from .. import __version__ _abupy_version = __version__ if self._pickle_highest_protocol != pickle_highest_protocol \ or _abupy_version != old_abupy_version or self._python_version != python_version \ or self._is_mac_os != platform_version: """只要有一个信息不一致,打印info,即有序列化读取失败的可能""" logging.info( "unpickle {} : " "old pickle_highest_protocol={}," "now pickle_highest_protocol={}, " "old abupy_version={}, " "now abupy_version={}, " "old python_version={}, " "now python_version={}, " "old platform_version={}, " "now platform_version={}, ".format( self.__class__.__name__, pickle_highest_protocol, self._pickle_highest_protocol, old_abupy_version, _abupy_version, python_version, self._python_version, platform_version, self._is_mac_os)) self.__dict__.update(state) # 混入对象可覆盖unpick_extend_work方法,完成对象特有的unpick工作 self.unpick_extend_work(state)
[ "def", "__setstate__", "(", "self", ",", "state", ")", ":", "# 从本地序列化文件中读取的pickle的最高支持版本, 默认0", "pickle_highest_protocol", "=", "state", ".", "pop", "(", "\"_pickle_highest_protocol\"", ",", "0", ")", "# 从本地序列化文件中读取的abupy的版本号, 默认0.0.1", "old_abupy_version", "=", "state", ...
https://github.com/bbfamily/abu/blob/2de85ae57923a720dac99a545b4f856f6b87304b/abupy/CoreBu/ABuBase.py#L56-L97
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/sets.py
python
BaseSet.union
(self, other)
return result
Return the union of two sets as a new set. (I.e. all elements that are in either set.)
Return the union of two sets as a new set.
[ "Return", "the", "union", "of", "two", "sets", "as", "a", "new", "set", "." ]
def union(self, other): """Return the union of two sets as a new set. (I.e. all elements that are in either set.) """ result = self.__class__(self) result._update(other) return result
[ "def", "union", "(", "self", ",", "other", ")", ":", "result", "=", "self", ".", "__class__", "(", "self", ")", "result", ".", "_update", "(", "other", ")", "return", "result" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/sets.py#L187-L194
brutasse/graphite-api
0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff
graphite_api/functions.py
python
highestAverage
(requestContext, seriesList, n=1)
return sorted(seriesList, key=safeAvg)[-n:]
Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the top N metrics with the highest average value for the time period specified. Example:: &target=highestAverage(server*.instance*.threads.busy,5) Draws the top 5 servers with the highest average value.
Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the top N metrics with the highest average value for the time period specified.
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "followed", "by", "an", "integer", "N", ".", "Out", "of", "all", "metrics", "passed", "draws", "only", "the", "top", "N", "metrics", "with", "the", "highest", "average", "value", "for", "the", ...
def highestAverage(requestContext, seriesList, n=1): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the top N metrics with the highest average value for the time period specified. Example:: &target=highestAverage(server*.instance*.threads.busy,5) Draws the top 5 servers with the highest average value. """ return sorted(seriesList, key=safeAvg)[-n:]
[ "def", "highestAverage", "(", "requestContext", ",", "seriesList", ",", "n", "=", "1", ")", ":", "return", "sorted", "(", "seriesList", ",", "key", "=", "safeAvg", ")", "[", "-", "n", ":", "]" ]
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2266-L2279
SciTools/cartopy
591fb5450e11b42b6de1cebe4f240112f915bd52
lib/cartopy/mpl/geoaxes.py
python
GeoAxes.cla
(self)
return result
Clear the current axes and adds boundary lines.
Clear the current axes and adds boundary lines.
[ "Clear", "the", "current", "axes", "and", "adds", "boundary", "lines", "." ]
def cla(self): """Clear the current axes and adds boundary lines.""" result = super().cla() self.xaxis.set_visible(False) self.yaxis.set_visible(False) # Enable tight autoscaling. self._tight = True self.set_aspect('equal') self._boundary() # XXX consider a margin - but only when the map is not global... # self._xmargin = 0.15 # self._ymargin = 0.15 self.dataLim.intervalx = self.projection.x_limits self.dataLim.intervaly = self.projection.y_limits return result
[ "def", "cla", "(", "self", ")", ":", "result", "=", "super", "(", ")", ".", "cla", "(", ")", "self", ".", "xaxis", ".", "set_visible", "(", "False", ")", "self", ".", "yaxis", ".", "set_visible", "(", "False", ")", "# Enable tight autoscaling.", "self"...
https://github.com/SciTools/cartopy/blob/591fb5450e11b42b6de1cebe4f240112f915bd52/lib/cartopy/mpl/geoaxes.py#L571-L589
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/app_manager/views/forms.py
python
get_form_questions
(request, domain, app_id)
return json_response(xform_questions)
[]
def get_form_questions(request, domain, app_id): form_unique_id = request.GET.get('form_unique_id') module_id_temp = request.GET.get('module_id') form_id_temp = request.GET.get('form_id') try: app = get_app(domain, app_id) if module_id_temp is not None and form_id_temp is not None: # temporary fallback form = app.get_module(module_id_temp).get_form(form_id_temp) else: form = app.get_form(form_unique_id) lang, langs = get_langs(request, app) except FormNotFoundException: raise Http404() xform_questions = form.get_questions(langs, include_triggers=True) return json_response(xform_questions)
[ "def", "get_form_questions", "(", "request", ",", "domain", ",", "app_id", ")", ":", "form_unique_id", "=", "request", ".", "GET", ".", "get", "(", "'form_unique_id'", ")", "module_id_temp", "=", "request", ".", "GET", ".", "get", "(", "'module_id'", ")", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/app_manager/views/forms.py#L595-L610
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/root_system/ambient_space.py
python
AmbientSpaceElement.is_positive_root
(self)
return self.parent().rho().scalar(self) > 0
EXAMPLES:: sage: R = RootSystem(['A',3]).ambient_space() sage: r=R.simple_root(1)+R.simple_root(2) sage: r.is_positive_root() True sage: r=R.simple_root(1)-R.simple_root(2) sage: r.is_positive_root() False
EXAMPLES::
[ "EXAMPLES", "::" ]
def is_positive_root(self): """ EXAMPLES:: sage: R = RootSystem(['A',3]).ambient_space() sage: r=R.simple_root(1)+R.simple_root(2) sage: r.is_positive_root() True sage: r=R.simple_root(1)-R.simple_root(2) sage: r.is_positive_root() False """ return self.parent().rho().scalar(self) > 0
[ "def", "is_positive_root", "(", "self", ")", ":", "return", "self", ".", "parent", "(", ")", ".", "rho", "(", ")", ".", "scalar", "(", "self", ")", ">", "0" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/root_system/ambient_space.py#L408-L420
BigBrotherBot/big-brother-bot
848823c71413c86e7f1ff9584f43e08d40a7f2c0
b3/tools/debug/statlib/stats.py
python
lbetai
(a,b,x)
Returns the incomplete beta function: I-sub-x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt) where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma function of a. The continued fraction formulation is implemented here, using the betacf function. (Adapted from: Numerical Recipes in C.) Usage: lbetai(a,b,x)
Returns the incomplete beta function:
[ "Returns", "the", "incomplete", "beta", "function", ":" ]
def lbetai(a,b,x): """ Returns the incomplete beta function: I-sub-x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt) where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma function of a. The continued fraction formulation is implemented here, using the betacf function. (Adapted from: Numerical Recipes in C.) Usage: lbetai(a,b,x) """ if (x<0.0 or x>1.0): raise ValueError, 'Bad x in lbetai' if (x==0.0 or x==1.0): bt = 0.0 else: bt = math.exp(gammln(a+b)-gammln(a)-gammln(b)+a*math.log(x)+b* math.log(1.0-x)) if (x<(a+1.0)/(a+b+2.0)): return bt*betacf(a,b,x)/float(a) else: return 1.0-bt*betacf(b,a,1.0-x)/float(b)
[ "def", "lbetai", "(", "a", ",", "b", ",", "x", ")", ":", "if", "(", "x", "<", "0.0", "or", "x", ">", "1.0", ")", ":", "raise", "ValueError", ",", "'Bad x in lbetai'", "if", "(", "x", "==", "0.0", "or", "x", "==", "1.0", ")", ":", "bt", "=", ...
https://github.com/BigBrotherBot/big-brother-bot/blob/848823c71413c86e7f1ff9584f43e08d40a7f2c0/b3/tools/debug/statlib/stats.py#L1563-L1585
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/bsddb/dbobj.py
python
DBEnv.dbremove
(self, *args, **kwargs)
return self._cobj.dbremove(*args, **kwargs)
[]
def dbremove(self, *args, **kwargs): return self._cobj.dbremove(*args, **kwargs)
[ "def", "dbremove", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_cobj", ".", "dbremove", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/bsddb/dbobj.py#L108-L109
google-research/language
61fa7260ac7d690d11ef72ca863e45a37c0bdc80
language/labs/drkit/run_multihop_follow.py
python
validate_flags_or_throw
()
Validate the input FLAGS or throw an exception.
Validate the input FLAGS or throw an exception.
[ "Validate", "the", "input", "FLAGS", "or", "throw", "an", "exception", "." ]
def validate_flags_or_throw(): """Validate the input FLAGS or throw an exception.""" if (not FLAGS.do_train and not FLAGS.do_predict and not FLAGS.do_test): raise ValueError("At least one of `do_train`, `do_predict` or " "`do_test` must be True.") if FLAGS.do_train: if not FLAGS.train_file: raise ValueError( "If `do_train` is True, then `train_file` must be specified.") if FLAGS.do_predict: if not FLAGS.predict_file: raise ValueError( "If `do_predict` is True, then `predict_file` must be specified.")
[ "def", "validate_flags_or_throw", "(", ")", ":", "if", "(", "not", "FLAGS", ".", "do_train", "and", "not", "FLAGS", ".", "do_predict", "and", "not", "FLAGS", ".", "do_test", ")", ":", "raise", "ValueError", "(", "\"At least one of `do_train`, `do_predict` or \"", ...
https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/labs/drkit/run_multihop_follow.py#L631-L644
LiyuanLucasLiu/LD-Net
f9489b6e7d436b7e3ed6447b797fb6ce9a886483
model_word_ada/utils.py
python
init_lstm
(input_lstm)
random initialize lstms
random initialize lstms
[ "random", "initialize", "lstms" ]
def init_lstm(input_lstm): """ random initialize lstms """ for ind in range(0, input_lstm.num_layers): weight = eval('input_lstm.weight_ih_l'+str(ind)) bias = np.sqrt(6.0 / (weight.size(0)/4 + weight.size(1))) nn.init.uniform_(weight, -bias, bias) weight = eval('input_lstm.weight_hh_l'+str(ind)) bias = np.sqrt(6.0 / (weight.size(0)/4 + weight.size(1))) nn.init.uniform_(weight, -bias, bias) if input_lstm.bias: for ind in range(0, input_lstm.num_layers): weight = eval('input_lstm.bias_ih_l'+str(ind)) weight.data.zero_() weight.data[input_lstm.hidden_size: 2 * input_lstm.hidden_size] = 1 weight = eval('input_lstm.bias_hh_l'+str(ind)) weight.data.zero_() weight.data[input_lstm.hidden_size: 2 * input_lstm.hidden_size] = 1
[ "def", "init_lstm", "(", "input_lstm", ")", ":", "for", "ind", "in", "range", "(", "0", ",", "input_lstm", ".", "num_layers", ")", ":", "weight", "=", "eval", "(", "'input_lstm.weight_ih_l'", "+", "str", "(", "ind", ")", ")", "bias", "=", "np", ".", ...
https://github.com/LiyuanLucasLiu/LD-Net/blob/f9489b6e7d436b7e3ed6447b797fb6ce9a886483/model_word_ada/utils.py#L72-L91
gmate/gmate
83312e64e0c115a9842500e4eb8617d3f5f4025b
plugins/gedit3/zencoding/zencoding/zencoding/zen_actions.py
python
unindent
(editor, text)
return unindent_text(text, get_current_line_padding(editor))
Unindent content, thus preparing text for tag wrapping @param editor: Editor instance @type editor: ZenEditor @param text: str @return str
Unindent content, thus preparing text for tag wrapping
[ "Unindent", "content", "thus", "preparing", "text", "for", "tag", "wrapping" ]
def unindent(editor, text): """ Unindent content, thus preparing text for tag wrapping @param editor: Editor instance @type editor: ZenEditor @param text: str @return str """ return unindent_text(text, get_current_line_padding(editor))
[ "def", "unindent", "(", "editor", ",", "text", ")", ":", "return", "unindent_text", "(", "text", ",", "get_current_line_padding", "(", "editor", ")", ")" ]
https://github.com/gmate/gmate/blob/83312e64e0c115a9842500e4eb8617d3f5f4025b/plugins/gedit3/zencoding/zencoding/zencoding/zen_actions.py#L190-L198
aplanas/kmanga
61162f09e8c61fa22831aea101b2899a28bf01fc
scraper/scraper/spiders/mangadex.py
python
MangaDex.parse_collection
(self, response, manga=None)
return response.follow(url, self._parse_issues, meta=meta)
Generate the list of issues for a manga @url https://mangadex.org/manga/39/one-piece @returns items 0 @returns request 1
Generate the list of issues for a manga
[ "Generate", "the", "list", "of", "issues", "for", "a", "manga" ]
def parse_collection(self, response, manga=None): """Generate the list of issues for a manga @url https://mangadex.org/manga/39/one-piece @returns items 0 @returns request 1 """ if 'manga' in response.meta: manga = response.meta['manga'] else: manga = Manga(url=response.url) # URL manga['url'] = response.url # Name xp = '//h3[@class="panel-title"]/text()' manga['name'] = response.xpath(xp).extract() # Alternate name xp = '//th[contains(text(),"%s")]' \ '/following-sibling::td/descendant-or-self::*/text()' manga['alt_name'] = response.xpath(xp % 'Alt name(s):').extract() # Author manga['author'] = response.xpath(xp % 'Author:').re(r'([^,]+),?') # Artist manga['artist'] = response.xpath(xp % 'Artist:').re(r'([^,]+),?') # Reading direction xp = '//h3[@class="panel-title"]/img/@alt' manga['reading_direction'] = response.xpath(xp).extract_first() # Status xp = '//th[contains(text(),"%s")]' \ '/following-sibling::td/descendant-or-self::*/text()' manga['status'] = response.xpath(xp % 'Pub. status:').extract_first() # Genres demographic = response.xpath(xp % 'Demographic:').extract() genres = response.xpath(xp % 'Genres:').extract() manga['genres'] = demographic + genres # Rank rank = response.xpath(xp % 'Rating:').extract_first() manga['rank'] = 100 * convert_to_number(rank) # Rank order manga['rank_order'] = 'DESC' # Description manga['description'] = response.xpath(xp % 'Description:').extract() # Cover image xp = '//img[@class="border-radius"]/@src' url = response.xpath(xp).extract_first() manga['image_urls'] = [response.urljoin(url)] # Information needed to deduce the issue order xp = '//p[@class="text-center"]/text()' chapters = response.xpath(xp).re_first(r'of (.*) chapters') if chapters: chapters = convert_to_number(chapters, as_int=True) else: xp = '//tr[contains(@id,"chapter_")]' chapters = len(response.xpath(xp)) # If the manga is empty (is frequent in MangaDex), end the # processing if not chapters: return # Parse the manga issues list manga['issues'] = [] meta = { 'manga': manga, 'chapters': chapters, } url = response.url + '/chapters/1' return response.follow(url, self._parse_issues, meta=meta)
[ "def", "parse_collection", "(", "self", ",", "response", ",", "manga", "=", "None", ")", ":", "if", "'manga'", "in", "response", ".", "meta", ":", "manga", "=", "response", ".", "meta", "[", "'manga'", "]", "else", ":", "manga", "=", "Manga", "(", "u...
https://github.com/aplanas/kmanga/blob/61162f09e8c61fa22831aea101b2899a28bf01fc/scraper/scraper/spiders/mangadex.py#L95-L165
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/tf/util/data.py
python
Data.set_dynamic_size
(self, axis, sizes)
:param int axis: counted with batch-dim :param tf.Tensor sizes: shape [B]
:param int axis: counted with batch-dim :param tf.Tensor sizes: shape [B]
[ ":", "param", "int", "axis", ":", "counted", "with", "batch", "-", "dim", ":", "param", "tf", ".", "Tensor", "sizes", ":", "shape", "[", "B", "]" ]
def set_dynamic_size(self, axis, sizes): """ :param int axis: counted with batch-dim :param tf.Tensor sizes: shape [B] """ # Note: The following code is somewhat ugly patchwork # to fix some other currently incomplete or buggy behavior of some layers # which introduce sizes without correctly setting the dim tag. # The beam information is also missing currently. # We make the ugly assumption that when it is unset, # the first usage should hopefully define the correct beam. if getattr(sizes, "_RETURNN_dyn_size_beam", NotSpecified) is NotSpecified: sizes._RETURNN_dyn_size_beam = self.beam if self.beam and getattr(sizes, "_RETURNN_dyn_size_beam", None) != self.beam: tag = Dim.get_tag_from_size_tensor(sizes) assert tag and self.batch tag = tag.get_for_batch_ctx(batch=self.batch, ctx=self.control_flow_ctx) assert tag.dyn_size is not None sizes = tag.dyn_size sizes_tag = Dim.get_tag_from_size_tensor(sizes) if sizes_tag: assert sizes_tag.is_same_size_tensor(sizes) tag = self.dim_tags[axis] assert tag.dimension is None # dynamic axis if tag.is_same_size_tensor(sizes): return # nothing to do if tag.dyn_size is None: if sizes_tag: # special rule for older code: overtake previous existing assert sizes_tag.is_same_size_tensor(sizes) self._dim_tags = self.dim_tags[:axis] + (sizes_tag,) + self.dim_tags[axis + 1:] # Also assume the existing dim tag should be expected as equal. # Likely there is anyway no reference so this does not matter. tag.declare_same_as(sizes_tag) else: # Assign now. This should also set the dim tag on sizes. new_tag = tag.set_tag_on_size_tensor(sizes, batch=self.batch) if new_tag is not tag: self._dim_tags = self.dim_tags[:axis] + (new_tag,) + self.dim_tags[axis + 1:] else: # Reset to some new size. # Use new dim tag, or previous existing attached to size. assert sizes_tag, "%s: assign dyn sizes %s without defined dim tag" % (self, sizes) self._dim_tags = self.dim_tags[:axis] + (sizes_tag,) + self.dim_tags[axis + 1:]
[ "def", "set_dynamic_size", "(", "self", ",", "axis", ",", "sizes", ")", ":", "# Note: The following code is somewhat ugly patchwork", "# to fix some other currently incomplete or buggy behavior of some layers", "# which introduce sizes without correctly setting the dim tag.", "# The beam i...
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/tf/util/data.py#L4774-L4817
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/turtle.py
python
TurtleScreenBase._drawimage
(self, item, pos, image)
Configure image item as to draw image object at position (x,y) on canvas)
Configure image item as to draw image object at position (x,y) on canvas)
[ "Configure", "image", "item", "as", "to", "draw", "image", "object", "at", "position", "(", "x", "y", ")", "on", "canvas", ")" ]
def _drawimage(self, item, pos, image): """Configure image item as to draw image object at position (x,y) on canvas) """ x, y = pos self.cv.coords(item, (x * self.xscale, -y * self.yscale)) self.cv.itemconfig(item, image=image)
[ "def", "_drawimage", "(", "self", ",", "item", ",", "pos", ",", "image", ")", ":", "x", ",", "y", "=", "pos", "self", ".", "cv", ".", "coords", "(", "item", ",", "(", "x", "*", "self", ".", "xscale", ",", "-", "y", "*", "self", ".", "yscale",...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/turtle.py#L725-L731
tobegit3hub/deep_image_model
8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e
java_predict_client/src/main/proto/tensorflow/contrib/layers/python/layers/layers.py
python
max_pool2d
(inputs, kernel_size, stride=2, padding='VALID', data_format=DATA_FORMAT_NHWC, outputs_collections=None, scope=None)
Adds a 2D Max Pooling op. It is assumed that the pooling is done per image but not in batch or channels. Args: inputs: A 4-D tensor of shape `[batch_size, height, width, channels]` if `data_format` is `NHWC`, and `[batch_size, channels, height, width]` if `data_format` is `NCHW`. kernel_size: A list of length 2: [kernel_height, kernel_width] of the pooling kernel over which the op is computed. Can be an int if both values are the same. stride: A list of length 2: [stride_height, stride_width]. Can be an int if both strides are the same. Note that presently both strides must have the same value. padding: The padding method, either 'VALID' or 'SAME'. data_format: A string. `NHWC` (default) and `NCHW` are supported. outputs_collections: The collections to which the outputs are added. scope: Optional scope for name_scope. Returns: A `Tensor` representing the results of the pooling operation. Raises: ValueError: if `data_format` is neither `NHWC` nor `NCHW`. ValueError: If 'kernel_size' is not a 2-D list
Adds a 2D Max Pooling op.
[ "Adds", "a", "2D", "Max", "Pooling", "op", "." ]
def max_pool2d(inputs, kernel_size, stride=2, padding='VALID', data_format=DATA_FORMAT_NHWC, outputs_collections=None, scope=None): """Adds a 2D Max Pooling op. It is assumed that the pooling is done per image but not in batch or channels. Args: inputs: A 4-D tensor of shape `[batch_size, height, width, channels]` if `data_format` is `NHWC`, and `[batch_size, channels, height, width]` if `data_format` is `NCHW`. kernel_size: A list of length 2: [kernel_height, kernel_width] of the pooling kernel over which the op is computed. Can be an int if both values are the same. stride: A list of length 2: [stride_height, stride_width]. Can be an int if both strides are the same. Note that presently both strides must have the same value. padding: The padding method, either 'VALID' or 'SAME'. data_format: A string. `NHWC` (default) and `NCHW` are supported. outputs_collections: The collections to which the outputs are added. scope: Optional scope for name_scope. Returns: A `Tensor` representing the results of the pooling operation. Raises: ValueError: if `data_format` is neither `NHWC` nor `NCHW`. ValueError: If 'kernel_size' is not a 2-D list """ if data_format not in (DATA_FORMAT_NCHW, DATA_FORMAT_NHWC): raise ValueError('data_format has to be either NCHW or NHWC.') with ops.name_scope(scope, 'MaxPool2D', [inputs]) as sc: inputs = ops.convert_to_tensor(inputs) kernel_h, kernel_w = utils.two_element_tuple(kernel_size) stride_h, stride_w = utils.two_element_tuple(stride) if data_format == DATA_FORMAT_NHWC: ksize = [1, kernel_h, kernel_w, 1] strides = [1, stride_h, stride_w, 1] else: ksize = [1, 1, kernel_h, kernel_w] strides = [1, 1, stride_h, stride_w] outputs = nn.max_pool(inputs, ksize=ksize, strides=strides, padding=padding, data_format=data_format) return utils.collect_named_outputs(outputs_collections, sc, outputs)
[ "def", "max_pool2d", "(", "inputs", ",", "kernel_size", ",", "stride", "=", "2", ",", "padding", "=", "'VALID'", ",", "data_format", "=", "DATA_FORMAT_NHWC", ",", "outputs_collections", "=", "None", ",", "scope", "=", "None", ")", ":", "if", "data_format", ...
https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/contrib/layers/python/layers/layers.py#L1430-L1480
ReactionMechanismGenerator/RMG-Py
2b7baf51febf27157def58fb3f6cee03fb6a684c
rmgpy/reaction.py
python
Reaction.is_isomerization
(self)
return len(self.reactants) == 1 and len(self.products) == 1
Return ``True`` if the reaction represents an isomerization reaction :math:`\\ce{A <=> B}` or ``False`` if not.
Return ``True`` if the reaction represents an isomerization reaction :math:`\\ce{A <=> B}` or ``False`` if not.
[ "Return", "True", "if", "the", "reaction", "represents", "an", "isomerization", "reaction", ":", "math", ":", "\\\\", "ce", "{", "A", "<", "=", ">", "B", "}", "or", "False", "if", "not", "." ]
def is_isomerization(self): """ Return ``True`` if the reaction represents an isomerization reaction :math:`\\ce{A <=> B}` or ``False`` if not. """ return len(self.reactants) == 1 and len(self.products) == 1
[ "def", "is_isomerization", "(", "self", ")", ":", "return", "len", "(", "self", ".", "reactants", ")", "==", "1", "and", "len", "(", "self", ".", "products", ")", "==", "1" ]
https://github.com/ReactionMechanismGenerator/RMG-Py/blob/2b7baf51febf27157def58fb3f6cee03fb6a684c/rmgpy/reaction.py#L359-L364
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/ultimatelistctrl.py
python
UltimateListItemData.GetX
(self)
return self._rect.x
Returns the item `x` position.
Returns the item `x` position.
[ "Returns", "the", "item", "x", "position", "." ]
def GetX(self): """ Returns the item `x` position. """ return self._rect.x
[ "def", "GetX", "(", "self", ")", ":", "return", "self", ".", "_rect", ".", "x" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/ultimatelistctrl.py#L3096-L3099
nathanlopez/Stitch
8e22e91c94237959c02d521aab58dc7e3d994cea
Application/stitch_help.py
python
usage_screenshot
()
[]
def usage_screenshot(): st_print('[*] Usage: screenshot\n')
[ "def", "usage_screenshot", "(", ")", ":", "st_print", "(", "'[*] Usage: screenshot\\n'", ")" ]
https://github.com/nathanlopez/Stitch/blob/8e22e91c94237959c02d521aab58dc7e3d994cea/Application/stitch_help.py#L111-L111
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/venv/lib/python2.7/site-packages/pip/_vendor/distlib/markers.py
python
Evaluator.get_handler
(self, node_type)
return getattr(self, 'do_%s' % node_type, None)
Get a handler for the specified AST node type.
Get a handler for the specified AST node type.
[ "Get", "a", "handler", "for", "the", "specified", "AST", "node", "type", "." ]
def get_handler(self, node_type): """ Get a handler for the specified AST node type. """ return getattr(self, 'do_%s' % node_type, None)
[ "def", "get_handler", "(", "self", ",", "node_type", ")", ":", "return", "getattr", "(", "self", ",", "'do_%s'", "%", "node_type", ",", "None", ")" ]
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/venv/lib/python2.7/site-packages/pip/_vendor/distlib/markers.py#L70-L74
jaraco/irc
19859340b2ad3bffc58d842a7657fae9ec3563f8
irc/server.py
python
IRCClient.handle_dump
(self, params)
Dump internal server information for debugging purposes.
Dump internal server information for debugging purposes.
[ "Dump", "internal", "server", "information", "for", "debugging", "purposes", "." ]
def handle_dump(self, params): """ Dump internal server information for debugging purposes. """ print("Clients:", self.server.clients) for client in self.server.clients.values(): print(" ", client) for channel in client.channels.values(): print(" ", channel.name) print("Channels:", self.server.channels) for channel in self.server.channels.values(): print(" ", channel.name, channel) for client in channel.clients: print(" ", client.nick, client)
[ "def", "handle_dump", "(", "self", ",", "params", ")", ":", "print", "(", "\"Clients:\"", ",", "self", ".", "server", ".", "clients", ")", "for", "client", "in", "self", ".", "server", ".", "clients", ".", "values", "(", ")", ":", "print", "(", "\" \...
https://github.com/jaraco/irc/blob/19859340b2ad3bffc58d842a7657fae9ec3563f8/irc/server.py#L429-L442
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/iottid/v20190411/models.py
python
UploadDeviceUniqueCodeRequest.__init__
(self)
r""" :param CodeSet: 硬件唯一标识码 :type CodeSet: list of str :param OrderId: 硬件标识码绑定的申请编号 :type OrderId: str
r""" :param CodeSet: 硬件唯一标识码 :type CodeSet: list of str :param OrderId: 硬件标识码绑定的申请编号 :type OrderId: str
[ "r", ":", "param", "CodeSet", ":", "硬件唯一标识码", ":", "type", "CodeSet", ":", "list", "of", "str", ":", "param", "OrderId", ":", "硬件标识码绑定的申请编号", ":", "type", "OrderId", ":", "str" ]
def __init__(self): r""" :param CodeSet: 硬件唯一标识码 :type CodeSet: list of str :param OrderId: 硬件标识码绑定的申请编号 :type OrderId: str """ self.CodeSet = None self.OrderId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "CodeSet", "=", "None", "self", ".", "OrderId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/iottid/v20190411/models.py#L415-L423
toxinu/Sublimall
58eb7bc624234720003ad4df82d13ce23d70e4e1
sublimall/requests/api.py
python
patch
(url, data=None, **kwargs)
return request('patch', url, data=data, **kwargs)
Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes.
Sends a PATCH request. Returns :class:`Response` object.
[ "Sends", "a", "PATCH", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def patch(url, data=None, **kwargs): """Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. """ return request('patch', url, data=data, **kwargs)
[ "def", "patch", "(", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "request", "(", "'patch'", ",", "url", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
https://github.com/toxinu/Sublimall/blob/58eb7bc624234720003ad4df82d13ce23d70e4e1/sublimall/requests/api.py#L102-L110
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/devops_sdk/v6_0/client_factory.py
python
ClientFactoryV6_0.get_release_client
(self)
return self._connection.get_client('azure.devops.v6_0.release.release_client.ReleaseClient')
get_release_client. Gets the 6.0 version of the ReleaseClient :rtype: :class:`<ReleaseClient> <azure.devops.v6_0.release.release_client.ReleaseClient>`
get_release_client. Gets the 6.0 version of the ReleaseClient :rtype: :class:`<ReleaseClient> <azure.devops.v6_0.release.release_client.ReleaseClient>`
[ "get_release_client", ".", "Gets", "the", "6", ".", "0", "version", "of", "the", "ReleaseClient", ":", "rtype", ":", ":", "class", ":", "<ReleaseClient", ">", "<azure", ".", "devops", ".", "v6_0", ".", "release", ".", "release_client", ".", "ReleaseClient", ...
def get_release_client(self): """get_release_client. Gets the 6.0 version of the ReleaseClient :rtype: :class:`<ReleaseClient> <azure.devops.v6_0.release.release_client.ReleaseClient>` """ return self._connection.get_client('azure.devops.v6_0.release.release_client.ReleaseClient')
[ "def", "get_release_client", "(", "self", ")", ":", "return", "self", ".", "_connection", ".", "get_client", "(", "'azure.devops.v6_0.release.release_client.ReleaseClient'", ")" ]
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v6_0/client_factory.py#L263-L268
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/crystals/affine.py
python
AffineCrystalFromClassicalAndPromotion.__init__
(self, cartan_type, classical_crystal, p_automorphism, p_inverse_automorphism, dynkin_node, category=None)
Input is an affine Cartan type ``cartan_type``, a classical crystal ``classical_crystal``, and promotion automorphism and its inverse ``p_automorphism`` and ``p_inverse_automorphism``, and the Dynkin node ``dynkin_node``. EXAMPLES:: sage: n = 1 sage: C = crystals.Tableaux(['A',n],shape=[1]) sage: pr = attrcall("promotion") sage: pr_inverse = attrcall("promotion_inverse") sage: A = crystals.AffineFromClassicalAndPromotion(['A',n,1],C,pr,pr_inverse,1) sage: A.list() [[[1]], [[2]]] sage: A.cartan_type() ['A', 1, 1] sage: A.index_set() (0, 1) TESTS:: sage: TestSuite(A).run()
Input is an affine Cartan type ``cartan_type``, a classical crystal ``classical_crystal``, and promotion automorphism and its inverse ``p_automorphism`` and ``p_inverse_automorphism``, and the Dynkin node ``dynkin_node``.
[ "Input", "is", "an", "affine", "Cartan", "type", "cartan_type", "a", "classical", "crystal", "classical_crystal", "and", "promotion", "automorphism", "and", "its", "inverse", "p_automorphism", "and", "p_inverse_automorphism", "and", "the", "Dynkin", "node", "dynkin_no...
def __init__(self, cartan_type, classical_crystal, p_automorphism, p_inverse_automorphism, dynkin_node, category=None): """ Input is an affine Cartan type ``cartan_type``, a classical crystal ``classical_crystal``, and promotion automorphism and its inverse ``p_automorphism`` and ``p_inverse_automorphism``, and the Dynkin node ``dynkin_node``. EXAMPLES:: sage: n = 1 sage: C = crystals.Tableaux(['A',n],shape=[1]) sage: pr = attrcall("promotion") sage: pr_inverse = attrcall("promotion_inverse") sage: A = crystals.AffineFromClassicalAndPromotion(['A',n,1],C,pr,pr_inverse,1) sage: A.list() [[[1]], [[2]]] sage: A.cartan_type() ['A', 1, 1] sage: A.index_set() (0, 1) TESTS:: sage: TestSuite(A).run() """ AffineCrystalFromClassical.__init__(self, cartan_type, classical_crystal, category) self.p_automorphism = p_automorphism self.p_inverse_automorphism = p_inverse_automorphism self.dynkin_node = dynkin_node
[ "def", "__init__", "(", "self", ",", "cartan_type", ",", "classical_crystal", ",", "p_automorphism", ",", "p_inverse_automorphism", ",", "dynkin_node", ",", "category", "=", "None", ")", ":", "AffineCrystalFromClassical", ".", "__init__", "(", "self", ",", "cartan...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/crystals/affine.py#L564-L592
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/base.py
python
DropboxBase.paper_docs_list_continue
(self, cursor)
return r
Once a cursor has been retrieved from :meth:`paper_docs_list`, use this to paginate through all Paper doc. Note that this endpoint will continue to work for content created by users on the older version of Paper. To check which version of Paper a user is on, use /users/features/get_values. If the paper_as_files feature is enabled, then the user is running the new version of Paper. Refer to the `Paper Migration Guide <https://www.dropbox.com/lp/developers/reference/paper-migration-guide>`_ for migration information. :param str cursor: The cursor obtained from :meth:`paper_docs_list` or :meth:`paper_docs_list_continue`. Allows for pagination. :rtype: :class:`dropbox.paper.ListPaperDocsResponse` :raises: :class:`.exceptions.ApiError` If this raises, ApiError will contain: :class:`dropbox.paper.ListDocsCursorError`
Once a cursor has been retrieved from :meth:`paper_docs_list`, use this to paginate through all Paper doc. Note that this endpoint will continue to work for content created by users on the older version of Paper. To check which version of Paper a user is on, use /users/features/get_values. If the paper_as_files feature is enabled, then the user is running the new version of Paper. Refer to the `Paper Migration Guide <https://www.dropbox.com/lp/developers/reference/paper-migration-guide>`_ for migration information.
[ "Once", "a", "cursor", "has", "been", "retrieved", "from", ":", "meth", ":", "paper_docs_list", "use", "this", "to", "paginate", "through", "all", "Paper", "doc", ".", "Note", "that", "this", "endpoint", "will", "continue", "to", "work", "for", "content", ...
def paper_docs_list_continue(self, cursor): """ Once a cursor has been retrieved from :meth:`paper_docs_list`, use this to paginate through all Paper doc. Note that this endpoint will continue to work for content created by users on the older version of Paper. To check which version of Paper a user is on, use /users/features/get_values. If the paper_as_files feature is enabled, then the user is running the new version of Paper. Refer to the `Paper Migration Guide <https://www.dropbox.com/lp/developers/reference/paper-migration-guide>`_ for migration information. :param str cursor: The cursor obtained from :meth:`paper_docs_list` or :meth:`paper_docs_list_continue`. Allows for pagination. :rtype: :class:`dropbox.paper.ListPaperDocsResponse` :raises: :class:`.exceptions.ApiError` If this raises, ApiError will contain: :class:`dropbox.paper.ListDocsCursorError` """ warnings.warn( 'docs/list/continue is deprecated.', DeprecationWarning, ) arg = paper.ListPaperDocsContinueArgs(cursor) r = self.request( paper.docs_list_continue, 'paper', arg, None, ) return r
[ "def", "paper_docs_list_continue", "(", "self", ",", "cursor", ")", ":", "warnings", ".", "warn", "(", "'docs/list/continue is deprecated.'", ",", "DeprecationWarning", ",", ")", "arg", "=", "paper", ".", "ListPaperDocsContinueArgs", "(", "cursor", ")", "r", "=", ...
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/base.py#L3527-L3559
hyperspy/hyperspy
1ffb3fab33e607045a37f30c1463350b72617e10
hyperspy/io_plugins/sur.py
python
DigitalSurfHandler._build_1D_series
(self,)
Build a series of 1D objects. The T axis is navigation and set from the first object
Build a series of 1D objects. The T axis is navigation and set from the first object
[ "Build", "a", "series", "of", "1D", "objects", ".", "The", "T", "axis", "is", "navigation", "and", "set", "from", "the", "first", "object" ]
def _build_1D_series(self,): """Build a series of 1D objects. The T axis is navigation and set from the first object""" #First object dictionary hypdic = self._list_sur_file_content[0] #Metadata are set from first dictionary self._set_metadata_and_original_metadata(hypdic) #Add the series-axis to the signal dict self.signal_dict['axes'].append(\ self._build_Tax(hypdic,'_03_Number_of_Objects',ind=0,nav=True)) #All objects must share the same signal axis self.signal_dict['axes'].append(\ self._build_Xax(hypdic,ind=1,nav=False)) #We put all the data together data = [] for obj in self._list_sur_file_content: data.append(obj['_62_points']) self.signal_dict['data'] = np.stack(data)
[ "def", "_build_1D_series", "(", "self", ",", ")", ":", "#First object dictionary", "hypdic", "=", "self", ".", "_list_sur_file_content", "[", "0", "]", "#Metadata are set from first dictionary", "self", ".", "_set_metadata_and_original_metadata", "(", "hypdic", ")", "#A...
https://github.com/hyperspy/hyperspy/blob/1ffb3fab33e607045a37f30c1463350b72617e10/hyperspy/io_plugins/sur.py#L741-L764
Eugeny/reconfigure
ff1115dede4b80222a2618d0e7657cafa36a2573
reconfigure/parsers/ini.py
python
IniFileParser.stringify
(self, tree)
return data
[]
def stringify(self, tree): cp = INIConfig() for section in tree.children: if self.sectionless and section.name is None: sectionname = self.nullsection else: sectionname = section.name cp._new_namespace(sectionname) for option in section.children: if not isinstance(option, PropertyNode): raise TypeError('Third level nodes should be PropertyNodes') cp[sectionname][option.name] = option.value if option.comment: self._set_comment(cp[sectionname]._options[option.name], option.comment) if section._extra_content: for k, v in section._extra_content.items(): cp[sectionname][k] = v if hasattr(cp[sectionname], '_lines'): self._set_comment(cp[sectionname]._lines[0], section.comment) data = (str if sys.version_info[0] >= 3 else unicode)(cp) + u'\n' if self.sectionless: data = data.replace('[' + self.nullsection + ']\n', '') return data
[ "def", "stringify", "(", "self", ",", "tree", ")", ":", "cp", "=", "INIConfig", "(", ")", "for", "section", "in", "tree", ".", "children", ":", "if", "self", ".", "sectionless", "and", "section", ".", "name", "is", "None", ":", "sectionname", "=", "s...
https://github.com/Eugeny/reconfigure/blob/ff1115dede4b80222a2618d0e7657cafa36a2573/reconfigure/parsers/ini.py#L56-L81
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/scripts/sshbackdoors/backdoors/shell/pupy/pupy/packages/windows/amd64/psutil/_psosx.py
python
swap_memory
()
return _common.sswap(total, used, free, percent, sin, sout)
Swap system memory as a (total, used, free, sin, sout) tuple.
Swap system memory as a (total, used, free, sin, sout) tuple.
[ "Swap", "system", "memory", "as", "a", "(", "total", "used", "free", "sin", "sout", ")", "tuple", "." ]
def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" total, used, free, sin, sout = cext.swap_mem() percent = usage_percent(used, total, _round=1) return _common.sswap(total, used, free, percent, sin, sout)
[ "def", "swap_memory", "(", ")", ":", "total", ",", "used", ",", "free", ",", "sin", ",", "sout", "=", "cext", ".", "swap_mem", "(", ")", "percent", "=", "usage_percent", "(", "used", ",", "total", ",", "_round", "=", "1", ")", "return", "_common", ...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/sshbackdoors/backdoors/shell/pupy/pupy/packages/windows/amd64/psutil/_psosx.py#L87-L91
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/idlelib/configHandler.py
python
IdleConf.GetExtraHelpSourceList
(self,configSet)
return helpSources
Fetch list of extra help sources from a given configSet. Valid configSets are 'user' or 'default'. Return a list of tuples of the form (menu_item , path_to_help_file , option), or return the empty list. 'option' is the sequence number of the help resource. 'option' values determine the position of the menu items on the Help menu, therefore the returned list must be sorted by 'option'.
Fetch list of extra help sources from a given configSet.
[ "Fetch", "list", "of", "extra", "help", "sources", "from", "a", "given", "configSet", "." ]
def GetExtraHelpSourceList(self,configSet): """Fetch list of extra help sources from a given configSet. Valid configSets are 'user' or 'default'. Return a list of tuples of the form (menu_item , path_to_help_file , option), or return the empty list. 'option' is the sequence number of the help resource. 'option' values determine the position of the menu items on the Help menu, therefore the returned list must be sorted by 'option'. """ helpSources=[] if configSet=='user': cfgParser=self.userCfg['main'] elif configSet=='default': cfgParser=self.defaultCfg['main'] else: raise InvalidConfigSet, 'Invalid configSet specified' options=cfgParser.GetOptionList('HelpFiles') for option in options: value=cfgParser.Get('HelpFiles',option,default=';') if value.find(';')==-1: #malformed config entry with no ';' menuItem='' #make these empty helpPath='' #so value won't be added to list else: #config entry contains ';' as expected value=string.split(value,';') menuItem=value[0].strip() helpPath=value[1].strip() if menuItem and helpPath: #neither are empty strings helpSources.append( (menuItem,helpPath,option) ) helpSources.sort(key=lambda x: int(x[2])) return helpSources
[ "def", "GetExtraHelpSourceList", "(", "self", ",", "configSet", ")", ":", "helpSources", "=", "[", "]", "if", "configSet", "==", "'user'", ":", "cfgParser", "=", "self", ".", "userCfg", "[", "'main'", "]", "elif", "configSet", "==", "'default'", ":", "cfgP...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/idlelib/configHandler.py#L628-L658
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/site-packages/win32/lib/win32serviceutil.py
python
RestartService
(serviceName, args = None, waitSeconds = 30, machine = None)
Stop the service, and then start it again (with some tolerance for allowing it to stop.)
Stop the service, and then start it again (with some tolerance for allowing it to stop.)
[ "Stop", "the", "service", "and", "then", "start", "it", "again", "(", "with", "some", "tolerance", "for", "allowing", "it", "to", "stop", ".", ")" ]
def RestartService(serviceName, args = None, waitSeconds = 30, machine = None): "Stop the service, and then start it again (with some tolerance for allowing it to stop.)" try: StopService(serviceName, machine) except pywintypes.error, exc: # Allow only "service not running" error if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE: raise # Give it a few goes, as the service may take time to stop for i in range(waitSeconds): try: StartService(serviceName, args, machine) break except pywintypes.error, exc: if exc.winerror!=winerror.ERROR_SERVICE_ALREADY_RUNNING: raise win32api.Sleep(1000) else: print "Gave up waiting for the old service to stop!"
[ "def", "RestartService", "(", "serviceName", ",", "args", "=", "None", ",", "waitSeconds", "=", "30", ",", "machine", "=", "None", ")", ":", "try", ":", "StopService", "(", "serviceName", ",", "machine", ")", "except", "pywintypes", ".", "error", ",", "e...
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/site-packages/win32/lib/win32serviceutil.py#L423-L441
algorhythms/LeetCode
3fb14aeea62a960442e47dfde9f964c7ffce32be
1000 Minimum Cost to Merge Stones.py
python
Solution.mergeStones
(self, stones: List[int], K: int)
return ret if ret != float("inf") else -1
Mergeable? K -> 1. Reduction size (K - 1) N - (K - 1) * m = 1 mergeable: (N - 1) % (K - 1) = 0 K consecutive every piles involves at least once Non-consecutive: priority queue merge the least first But here it is consecutive, need to search, cannot gready * Merge the piles cost the same as merge individual ones. Attemp 1: F[i] = cost to merge A[:i] into 1 F[i] = F[i-3] + A[i-1] + A[i-2] + A[i-3] ?? Attemp 2: F[i][j] = cost of merge A[i:j] into 1 F[i][j] = F[i][k] + F[k][j] ?? Answer: F[i][j][m] = cost of merge A[i:j] into m piles F[i][j][1] = F[i][j][k] + sum(stones[i:j]) # merge F[i][j][m] = min F[i][mid][1] + F[mid][j][m-1] # add initial: F[i][i+1][1] = 0 F[i][i+1][m] = inf since the mid goes through the middle in the i, j. Use memoization rather than dp
Mergeable? K -> 1. Reduction size (K - 1) N - (K - 1) * m = 1 mergeable: (N - 1) % (K - 1) = 0
[ "Mergeable?", "K", "-", ">", "1", ".", "Reduction", "size", "(", "K", "-", "1", ")", "N", "-", "(", "K", "-", "1", ")", "*", "m", "=", "1", "mergeable", ":", "(", "N", "-", "1", ")", "%", "(", "K", "-", "1", ")", "=", "0" ]
def mergeStones(self, stones: List[int], K: int) -> int: """ Mergeable? K -> 1. Reduction size (K - 1) N - (K - 1) * m = 1 mergeable: (N - 1) % (K - 1) = 0 K consecutive every piles involves at least once Non-consecutive: priority queue merge the least first But here it is consecutive, need to search, cannot gready * Merge the piles cost the same as merge individual ones. Attemp 1: F[i] = cost to merge A[:i] into 1 F[i] = F[i-3] + A[i-1] + A[i-2] + A[i-3] ?? Attemp 2: F[i][j] = cost of merge A[i:j] into 1 F[i][j] = F[i][k] + F[k][j] ?? Answer: F[i][j][m] = cost of merge A[i:j] into m piles F[i][j][1] = F[i][j][k] + sum(stones[i:j]) # merge F[i][j][m] = min F[i][mid][1] + F[mid][j][m-1] # add initial: F[i][i+1][1] = 0 F[i][i+1][m] = inf since the mid goes through the middle in the i, j. Use memoization rather than dp """ N = len(stones) sums = [0] for s in stones: sums.append(sums[-1] + s) @lru_cache(None) def F(i, j, m): if i >= j or m < 1: return float("inf") n = j - i if (n - m) % (K - 1) != 0: return float("inf") if j == i + 1: if m == 1: return 0 return float("inf") if m == 1: return F(i, j, K) + sums[j] - sums[i] ret = min( F(i, mid, 1) + F(mid, j, m - 1) for mid in range(i + 1, j, K - 1) ) return ret ret = F(0, N, 1) return ret if ret != float("inf") else -1
[ "def", "mergeStones", "(", "self", ",", "stones", ":", "List", "[", "int", "]", ",", "K", ":", "int", ")", "->", "int", ":", "N", "=", "len", "(", "stones", ")", "sums", "=", "[", "0", "]", "for", "s", "in", "stones", ":", "sums", ".", "appen...
https://github.com/algorhythms/LeetCode/blob/3fb14aeea62a960442e47dfde9f964c7ffce32be/1000 Minimum Cost to Merge Stones.py#L52-L114
scikit-fuzzy/scikit-fuzzy
92ad3c382ac19707086204ac6cdf6e81353345a7
skfuzzy/fuzzymath/fuzzy_ops.py
python
fuzzy_sub
(x, a, y, b)
return fuzzy_op(x, a, y, b, op=np.subtract)
Subtract fuzzy set ``b`` from fuzzy set ``a``. Parameters ---------- x : 1d array, length N Universe variable for fuzzy set ``a``. A : 1d array, length N Fuzzy set for universe ``x``. y : 1d array, length M Universe variable for fuzzy set ``b``. b : 1d array, length M Fuzzy set for universe ``y``. Returns ------- z : 1d array Output variable. mfz : 1d array Fuzzy membership set for variable z. Notes ----- Uses Zadeh's Extension Principle from Ross, Fuzzy Logic w/Engineering Applications, (2010), pp.414, Eq. 12.17. If these results are unexpected and your membership functions are convex, consider trying the ``skfuzzy.dsw_*`` functions for fuzzy mathematics using interval arithmetic via the restricted Dong, Shah, and Wong method.
Subtract fuzzy set ``b`` from fuzzy set ``a``.
[ "Subtract", "fuzzy", "set", "b", "from", "fuzzy", "set", "a", "." ]
def fuzzy_sub(x, a, y, b): """ Subtract fuzzy set ``b`` from fuzzy set ``a``. Parameters ---------- x : 1d array, length N Universe variable for fuzzy set ``a``. A : 1d array, length N Fuzzy set for universe ``x``. y : 1d array, length M Universe variable for fuzzy set ``b``. b : 1d array, length M Fuzzy set for universe ``y``. Returns ------- z : 1d array Output variable. mfz : 1d array Fuzzy membership set for variable z. Notes ----- Uses Zadeh's Extension Principle from Ross, Fuzzy Logic w/Engineering Applications, (2010), pp.414, Eq. 12.17. If these results are unexpected and your membership functions are convex, consider trying the ``skfuzzy.dsw_*`` functions for fuzzy mathematics using interval arithmetic via the restricted Dong, Shah, and Wong method. """ return fuzzy_op(x, a, y, b, op=np.subtract)
[ "def", "fuzzy_sub", "(", "x", ",", "a", ",", "y", ",", "b", ")", ":", "return", "fuzzy_op", "(", "x", ",", "a", ",", "y", ",", "b", ",", "op", "=", "np", ".", "subtract", ")" ]
https://github.com/scikit-fuzzy/scikit-fuzzy/blob/92ad3c382ac19707086204ac6cdf6e81353345a7/skfuzzy/fuzzymath/fuzzy_ops.py#L390-L422
NetManAIOps/donut
c8a44d91f102f36ba712e1e896408337501bce9b
donut/model.py
python
Donut.get_score
(self, x, y=None, n_z=None, mcmc_iteration=None, last_point_only=True)
Get the reconstruction probability for `x` and `y`. The larger `reconstruction probability`, the less likely a point is anomaly. You may take the negative of the score, if you want something to directly indicate the severity of anomaly. Args: x (tf.Tensor): 2-D `float32` :class:`tf.Tensor`, the windows of KPI observations in a mini-batch. y (tf.Tensor): 2-D `int32` :class:`tf.Tensor`, the windows of missing point indicators in a mini-batch. n_z (int or None): Number of `z` samples to take for each `x`. (default :obj:`None`, one sample without explicit sampling dimension) mcmc_iteration (int or tf.Tensor): Iteration count for MCMC missing data imputation. (default :obj:`None`, no iteration) last_point_only (bool): Whether to obtain the reconstruction probability of only the last point in each window? (default :obj:`True`) Returns: tf.Tensor: The reconstruction probability, with the shape ``(len(x) - self.x_dims + 1,)`` if `last_point_only` is :obj:`True`, or ``(len(x) - self.x_dims + 1, self.x_dims)`` if `last_point_only` is :obj:`False`. This is because the first ``self.x_dims - 1`` points are not the last point of any window.
Get the reconstruction probability for `x` and `y`.
[ "Get", "the", "reconstruction", "probability", "for", "x", "and", "y", "." ]
def get_score(self, x, y=None, n_z=None, mcmc_iteration=None, last_point_only=True): """ Get the reconstruction probability for `x` and `y`. The larger `reconstruction probability`, the less likely a point is anomaly. You may take the negative of the score, if you want something to directly indicate the severity of anomaly. Args: x (tf.Tensor): 2-D `float32` :class:`tf.Tensor`, the windows of KPI observations in a mini-batch. y (tf.Tensor): 2-D `int32` :class:`tf.Tensor`, the windows of missing point indicators in a mini-batch. n_z (int or None): Number of `z` samples to take for each `x`. (default :obj:`None`, one sample without explicit sampling dimension) mcmc_iteration (int or tf.Tensor): Iteration count for MCMC missing data imputation. (default :obj:`None`, no iteration) last_point_only (bool): Whether to obtain the reconstruction probability of only the last point in each window? (default :obj:`True`) Returns: tf.Tensor: The reconstruction probability, with the shape ``(len(x) - self.x_dims + 1,)`` if `last_point_only` is :obj:`True`, or ``(len(x) - self.x_dims + 1, self.x_dims)`` if `last_point_only` is :obj:`False`. This is because the first ``self.x_dims - 1`` points are not the last point of any window. """ with tf.name_scope('Donut.get_score'): # MCMC missing data imputation if y is not None and mcmc_iteration: x_r = iterative_masked_reconstruct( reconstruct=self.vae.reconstruct, x=x, mask=y, iter_count=mcmc_iteration, back_prop=False, ) else: x_r = x # get the reconstruction probability q_net = self.vae.variational(x=x_r, n_z=n_z) # notice: x=x_r p_net = self.vae.model(z=q_net['z'], x=x, n_z=n_z) # notice: x=x r_prob = p_net['x'].log_prob(group_ndims=0) if n_z is not None: n_z = validate_n_samples(n_z, 'n_z') assert_shape_op = tf.assert_equal( tf.shape(r_prob), tf.stack([n_z, tf.shape(x)[0], self.x_dims]), message='Unexpected shape of reconstruction prob' ) with tf.control_dependencies([assert_shape_op]): r_prob = tf.reduce_mean(r_prob, axis=0) if last_point_only: r_prob = r_prob[:, -1] return r_prob
[ "def", "get_score", "(", "self", ",", "x", ",", "y", "=", "None", ",", "n_z", "=", "None", ",", "mcmc_iteration", "=", "None", ",", "last_point_only", "=", "True", ")", ":", "with", "tf", ".", "name_scope", "(", "'Donut.get_score'", ")", ":", "# MCMC m...
https://github.com/NetManAIOps/donut/blob/c8a44d91f102f36ba712e1e896408337501bce9b/donut/model.py#L163-L222
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/plat-freebsd5/IN.py
python
IN6_IS_ADDR_MC_SITELOCAL
(a)
return
[]
def IN6_IS_ADDR_MC_SITELOCAL(a): return
[ "def", "IN6_IS_ADDR_MC_SITELOCAL", "(", "a", ")", ":", "return" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-freebsd5/IN.py#L281-L281
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/phases/iapws_phase.py
python
IAPWS97.d2A_d2tau
(self)
return d2A_d2tau
[]
def d2A_d2tau(self): try: return self._d2A_d2tau except: pass self._d2A_d2tau = d2A_d2tau = iapws.iapws97_d2A_d2tau_region3(self.tau, self.delta) return d2A_d2tau
[ "def", "d2A_d2tau", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_d2A_d2tau", "except", ":", "pass", "self", ".", "_d2A_d2tau", "=", "d2A_d2tau", "=", "iapws", ".", "iapws97_d2A_d2tau_region3", "(", "self", ".", "tau", ",", "self", ".", "de...
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/phases/iapws_phase.py#L329-L335
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
etcd/datadog_checks/etcd/config_models/defaults.py
python
instance_kerberos_keytab
(field, value)
return get_default_field_value(field, value)
[]
def instance_kerberos_keytab(field, value): return get_default_field_value(field, value)
[ "def", "instance_kerberos_keytab", "(", "field", ",", "value", ")", ":", "return", "get_default_field_value", "(", "field", ",", "value", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/etcd/datadog_checks/etcd/config_models/defaults.py#L125-L126
man-group/mdf
4b2c78084467791ad883c0b4c53832ad70fc96ef
mdf/builders/basic.py
python
NodeTypeHandler.get_dataframe
(self, dtype=object)
return df
Returns a DataFrame containing the values accumulated for each column for a node.
Returns a DataFrame containing the values accumulated for each column for a node.
[ "Returns", "a", "DataFrame", "containing", "the", "values", "accumulated", "for", "each", "column", "for", "a", "node", "." ]
def get_dataframe(self, dtype=object): """ Returns a DataFrame containing the values accumulated for each column for a node. """ columns = self.get_columns() df = pa.DataFrame(data={}, index=self._index, columns=columns, dtype=dtype) for (d, l), value in self._data.items(): df[l][d] = value return df
[ "def", "get_dataframe", "(", "self", ",", "dtype", "=", "object", ")", ":", "columns", "=", "self", ".", "get_columns", "(", ")", "df", "=", "pa", ".", "DataFrame", "(", "data", "=", "{", "}", ",", "index", "=", "self", ".", "_index", ",", "columns...
https://github.com/man-group/mdf/blob/4b2c78084467791ad883c0b4c53832ad70fc96ef/mdf/builders/basic.py#L280-L289
pengchenglin/ATX-Test
fb3354b210934726af6a369746d6bdf6359f268d
Public/report.py
python
_get_report_info
(run)
return result
获取每个设备报告的参数
获取每个设备报告的参数
[ "获取每个设备报告的参数" ]
def _get_report_info(run): '''获取每个设备报告的参数''' report = run.test_report_path + '/TestReport.html' result = {} with open(report, 'r', encoding='utf-8') as f: res_str = re.findall("测试结果(.+%)", f.read()) if res_str: res = re.findall(r"\d+", res_str[0]) result["sum"] = res[0] result["pass"] = res[1] result['fail'] = res[2] result['error'] = res[3] result['passrate'] = re.findall('通过率 = (.+%)', res_str[0])[0] else: raise Exception("The TestReport.html in %s has no string'测试结果',please check out!!!" % run.get_path()) f.close() with open(report, 'r', encoding='utf-8') as f: result['duration'] = re.findall("合计耗时 : </strong> (.+)</p>", f.read())[0].split('.')[0] f.close() return result
[ "def", "_get_report_info", "(", "run", ")", ":", "report", "=", "run", ".", "test_report_path", "+", "'/TestReport.html'", "result", "=", "{", "}", "with", "open", "(", "report", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "res_str"...
https://github.com/pengchenglin/ATX-Test/blob/fb3354b210934726af6a369746d6bdf6359f268d/Public/report.py#L39-L58
ogrisel/pygbm
686495bedd7d495bcab1d66eb74309de48d3f3c1
pygbm/loss.py
python
BaseLoss.get_baseline_prediction
(self, y_train, prediction_dim)
Return initial predictions (before the first iteration). Parameters ---------- y_train : array-like, shape=(n_samples,) The target training values. prediction_dim : int The dimension of one prediction: 1 for binary classification and regression, n_classes for multiclass classification. Returns ------- baseline_prediction: float or array of shape (1, prediction_dim) The baseline prediction.
Return initial predictions (before the first iteration).
[ "Return", "initial", "predictions", "(", "before", "the", "first", "iteration", ")", "." ]
def get_baseline_prediction(self, y_train, prediction_dim): """Return initial predictions (before the first iteration). Parameters ---------- y_train : array-like, shape=(n_samples,) The target training values. prediction_dim : int The dimension of one prediction: 1 for binary classification and regression, n_classes for multiclass classification. Returns ------- baseline_prediction: float or array of shape (1, prediction_dim) The baseline prediction. """ pass
[ "def", "get_baseline_prediction", "(", "self", ",", "y_train", ",", "prediction_dim", ")", ":", "pass" ]
https://github.com/ogrisel/pygbm/blob/686495bedd7d495bcab1d66eb74309de48d3f3c1/pygbm/loss.py#L75-L91
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/location_view_service/client.py
python
LocationViewServiceClient.from_service_account_file
(cls, filename: str, *args, **kwargs)
return cls(*args, **kwargs)
Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: LocationViewServiceClient: The constructed client.
Creates an instance of this client using the provided credentials file.
[ "Creates", "an", "instance", "of", "this", "client", "using", "the", "provided", "credentials", "file", "." ]
def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: LocationViewServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename ) kwargs["credentials"] = credentials return cls(*args, **kwargs)
[ "def", "from_service_account_file", "(", "cls", ",", "filename", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "credentials", "=", "service_account", ".", "Credentials", ".", "from_service_account_file", "(", "filename", ")", "kwargs", "[", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/location_view_service/client.py#L128-L145
jesseweisberg/moveo_ros
b9282bdadbf2505a26d3b94b91e60a98d86efa34
object_detector_app/object_detection/meta_architectures/ssd_meta_arch.py
python
SSDMetaArch._get_feature_map_spatial_dims
(self, feature_maps)
return [(shape[1], shape[2]) for shape in feature_map_shapes]
Return list of spatial dimensions for each feature map in a list. Args: feature_maps: a list of tensors where the ith tensor has shape [batch, height_i, width_i, depth_i]. Returns: a list of pairs (height, width) for each feature map in feature_maps
Return list of spatial dimensions for each feature map in a list.
[ "Return", "list", "of", "spatial", "dimensions", "for", "each", "feature", "map", "in", "a", "list", "." ]
def _get_feature_map_spatial_dims(self, feature_maps): """Return list of spatial dimensions for each feature map in a list. Args: feature_maps: a list of tensors where the ith tensor has shape [batch, height_i, width_i, depth_i]. Returns: a list of pairs (height, width) for each feature map in feature_maps """ feature_map_shapes = [ feature_map.get_shape().as_list() for feature_map in feature_maps ] return [(shape[1], shape[2]) for shape in feature_map_shapes]
[ "def", "_get_feature_map_spatial_dims", "(", "self", ",", "feature_maps", ")", ":", "feature_map_shapes", "=", "[", "feature_map", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "for", "feature_map", "in", "feature_maps", "]", "return", "[", "(", "shape...
https://github.com/jesseweisberg/moveo_ros/blob/b9282bdadbf2505a26d3b94b91e60a98d86efa34/object_detector_app/object_detection/meta_architectures/ssd_meta_arch.py#L316-L329
vlachoudis/bCNC
67126b4894dabf6579baf47af8d0f9b7de35e6e3
bCNC/CNC.py
python
CNC.toolChange
(self, tool=None)
return lines
[]
def toolChange(self, tool=None): if tool is not None: # Force a change self.tool = tool self._lastTool = None # check if it is the same tool if self.tool is None or self.tool == self._lastTool: return [] # create the necessary code lines = [] lines.append("$g") # remember state and populate variables, FIXME: move to ./controllers/_GenericController.py lines.append("m5") # stop spindle lines.append("%wait") lines.append("%_x,_y,_z = wx,wy,wz") # remember position lines.append("g53 g0 z[toolchangez]") lines.append("g53 g0 x[toolchangex] y[toolchangey]") lines.append("%wait") if CNC.comment: lines.append("%%msg Tool change T%02d (%s)"%(self.tool,CNC.comment)) else: lines.append("%%msg Tool change T%02d"%(self.tool)) lines.append("m0") # feed hold if CNC.toolPolicy < 4: lines.append("g53 g0 x[toolprobex] y[toolprobey]") lines.append("g53 g0 z[toolprobez]") # fixed WCS if CNC.vars["fastprbfeed"]: prb_reverse = {"2": "4", "3": "5", "4": "2", "5": "3"} CNC.vars["prbcmdreverse"] = (CNC.vars["prbcmd"][:-1] + prb_reverse[CNC.vars["prbcmd"][-1]]) currentFeedrate = CNC.vars["fastprbfeed"] while currentFeedrate > CNC.vars["prbfeed"]: lines.append("%wait") lines.append("g91 [prbcmd] %s z[toolprobez-mz-tooldistance]" \ % CNC.fmt('f',currentFeedrate)) lines.append("%wait") lines.append("[prbcmdreverse] %s z[toolprobez-mz]" \ % CNC.fmt('f',currentFeedrate)) currentFeedrate /= 10 lines.append("%wait") lines.append("g91 [prbcmd] f[prbfeed] z[toolprobez-mz-tooldistance]") if CNC.toolPolicy==2: # Adjust the current WCS to fit to the tool # FIXME could be done dynamically in the code p = WCS.index(CNC.vars["WCS"])+1 lines.append("g10l20p%d z[toolheight]"%(p)) lines.append("%wait") elif CNC.toolPolicy==3: # Modify the tool length, update the TLO lines.append("g4 p1") # wait a sec to get the probe info lines.append("%wait") lines.append("%global TLO; TLO=prbz-toolmz") lines.append("g43.1z[TLO]") lines.append("%update TLO") lines.append("g53 g0 z[toolchangez]") lines.append("g53 g0 x[toolchangex] y[toolchangey]") if CNC.toolWaitAfterProbe: lines.append("%wait") lines.append("%msg Restart spindle") lines.append("m0") # feed hold # restore state lines.append("g90") # restore mode lines.append("g0 x[_x] y[_y]") # ... x,y position lines.append("g0 z[_z]") # ... z position lines.append("f[feed] [spindle]")# ... feed and spindle lines.append("g4 p5") # wait 5s for spindle to speed up # remember present tool self._lastTool = self.tool return lines
[ "def", "toolChange", "(", "self", ",", "tool", "=", "None", ")", ":", "if", "tool", "is", "not", "None", ":", "# Force a change", "self", ".", "tool", "=", "tool", "self", ".", "_lastTool", "=", "None", "# check if it is the same tool", "if", "self", ".", ...
https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/CNC.py#L1753-L1831
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/utils/batchprocessors.py
python
tb_filename
(tb)
return tb.tb_frame.f_code.co_filename
Helper to get filename from traceback
Helper to get filename from traceback
[ "Helper", "to", "get", "filename", "from", "traceback" ]
def tb_filename(tb): """Helper to get filename from traceback""" return tb.tb_frame.f_code.co_filename
[ "def", "tb_filename", "(", "tb", ")", ":", "return", "tb", ".", "tb_frame", ".", "f_code", ".", "co_filename" ]
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/utils/batchprocessors.py#L296-L298
largelymfs/topical_word_embeddings
1ae3d15d0afcd3fcd39cc81eec4ad9463413a9f6
TWE-1/gensim/corpora/wikicorpus.py
python
get_namespace
(tag)
return namespace
Returns the namespace of tag.
Returns the namespace of tag.
[ "Returns", "the", "namespace", "of", "tag", "." ]
def get_namespace(tag): """Returns the namespace of tag.""" m = re.match("^{(.*?)}", tag) namespace = m.group(1) if m else "" if not namespace.startswith("http://www.mediawiki.org/xml/export-"): raise ValueError("%s not recognized as MediaWiki dump namespace" % namespace) return namespace
[ "def", "get_namespace", "(", "tag", ")", ":", "m", "=", "re", ".", "match", "(", "\"^{(.*?)}\"", ",", "tag", ")", "namespace", "=", "m", ".", "group", "(", "1", ")", "if", "m", "else", "\"\"", "if", "not", "namespace", ".", "startswith", "(", "\"ht...
https://github.com/largelymfs/topical_word_embeddings/blob/1ae3d15d0afcd3fcd39cc81eec4ad9463413a9f6/TWE-1/gensim/corpora/wikicorpus.py#L173-L180
igrishaev/f
9be7113517a4488a0b7150688043d9bbb6be0a73
f/function.py
python
arr2
(value, *forms)
return reduce(reducer, forms, value)
Clojure's second threading macro implementation. The logic is the same as `thread_first`, but puts the value at the end of each form. See https://clojuredocs.org/clojure.core/->> :param value: Initial value to process. :type value: any :param forms: A tuple of forms. :type forms: tuple of func|(func, arg1, arg2, ...) :return: A value passed through the all forms. :rtype: any
Clojure's second threading macro implementation.
[ "Clojure", "s", "second", "threading", "macro", "implementation", "." ]
def arr2(value, *forms): """ Clojure's second threading macro implementation. The logic is the same as `thread_first`, but puts the value at the end of each form. See https://clojuredocs.org/clojure.core/->> :param value: Initial value to process. :type value: any :param forms: A tuple of forms. :type forms: tuple of func|(func, arg1, arg2, ...) :return: A value passed through the all forms. :rtype: any """ def reducer(value, form): if isinstance(form, (tuple, list)): func, args = form[0], form[1:] else: func, args = form, () all_args = tuple(args) + (value, ) return func(*all_args) return reduce(reducer, forms, value)
[ "def", "arr2", "(", "value", ",", "*", "forms", ")", ":", "def", "reducer", "(", "value", ",", "form", ")", ":", "if", "isinstance", "(", "form", ",", "(", "tuple", ",", "list", ")", ")", ":", "func", ",", "args", "=", "form", "[", "0", "]", ...
https://github.com/igrishaev/f/blob/9be7113517a4488a0b7150688043d9bbb6be0a73/f/function.py#L116-L146
aws/sagemaker-python-sdk
9d259b316f7f43838c16f35c10e98a110b56735b
src/sagemaker/tuner.py
python
HyperparameterTuner._prepare_estimator_for_tuning
(cls, estimator, inputs, job_name, **kwargs)
Prepare one estimator before starting tuning.
Prepare one estimator before starting tuning.
[ "Prepare", "one", "estimator", "before", "starting", "tuning", "." ]
def _prepare_estimator_for_tuning(cls, estimator, inputs, job_name, **kwargs): """Prepare one estimator before starting tuning.""" if isinstance(inputs, (list, RecordSet, FileSystemRecordSet)): estimator._prepare_for_training(inputs, **kwargs) else: estimator._prepare_for_training(job_name)
[ "def", "_prepare_estimator_for_tuning", "(", "cls", ",", "estimator", ",", "inputs", ",", "job_name", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "inputs", ",", "(", "list", ",", "RecordSet", ",", "FileSystemRecordSet", ")", ")", ":", "esti...
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/tuner.py#L502-L507
rm-hull/luma.lcd
156d0613ceb973356cea768263f3847d68994bde
luma/lcd/device.py
python
ili9486.contrast
(self, level)
NOT SUPPORTED :param level: Desired contrast level in the range of 0-255. :type level: int
NOT SUPPORTED
[ "NOT", "SUPPORTED" ]
def contrast(self, level): """ NOT SUPPORTED :param level: Desired contrast level in the range of 0-255. :type level: int """ assert(0 <= level <= 255)
[ "def", "contrast", "(", "self", ",", "level", ")", ":", "assert", "(", "0", "<=", "level", "<=", "255", ")" ]
https://github.com/rm-hull/luma.lcd/blob/156d0613ceb973356cea768263f3847d68994bde/luma/lcd/device.py#L856-L863
PyMVPA/PyMVPA
76c476b3de8264b0bb849bf226da5674d659564e
mvpa2/mappers/flatten.py
python
ProductFlattenMapper.__init__
(self, factor_names, factor_values=None, **kwargs)
Parameters ---------- factor_names: iterable The names for each dimension. If the dataset to be flattened is shaped ns X nf1 x nf2 x ... x nfN, then factor_names should have a length of N. Furthermore when applied to a dataset ds, it should have each of the factor names factor_names[K] as an attribute and the value of this attribute should have nfK values. Applying this mapper to such a dataset yields a new dataset with size ns X (nf1 * nf2 * ... * nfN) with feature attributes nameK and nameKindices for each nameK in the factor names. factor_values: iterable or None Optionally the factor values for each dimension. If not provided or set to None, then it will be inferred upon training on a dataset. Setting this parameter explicitly means this instance does not have to be trained.
Parameters ---------- factor_names: iterable The names for each dimension. If the dataset to be flattened is shaped ns X nf1 x nf2 x ... x nfN, then factor_names should have a length of N. Furthermore when applied to a dataset ds, it should have each of the factor names factor_names[K] as an attribute and the value of this attribute should have nfK values. Applying this mapper to such a dataset yields a new dataset with size ns X (nf1 * nf2 * ... * nfN) with feature attributes nameK and nameKindices for each nameK in the factor names. factor_values: iterable or None Optionally the factor values for each dimension. If not provided or set to None, then it will be inferred upon training on a dataset. Setting this parameter explicitly means this instance does not have to be trained.
[ "Parameters", "----------", "factor_names", ":", "iterable", "The", "names", "for", "each", "dimension", ".", "If", "the", "dataset", "to", "be", "flattened", "is", "shaped", "ns", "X", "nf1", "x", "nf2", "x", "...", "x", "nfN", "then", "factor_names", "sh...
def __init__(self, factor_names, factor_values=None, **kwargs): ''' Parameters ---------- factor_names: iterable The names for each dimension. If the dataset to be flattened is shaped ns X nf1 x nf2 x ... x nfN, then factor_names should have a length of N. Furthermore when applied to a dataset ds, it should have each of the factor names factor_names[K] as an attribute and the value of this attribute should have nfK values. Applying this mapper to such a dataset yields a new dataset with size ns X (nf1 * nf2 * ... * nfN) with feature attributes nameK and nameKindices for each nameK in the factor names. factor_values: iterable or None Optionally the factor values for each dimension. If not provided or set to None, then it will be inferred upon training on a dataset. Setting this parameter explicitly means this instance does not have to be trained. ''' kwargs['auto_train'] = kwargs.get('auto_train', True) # make sure the factor names and values are properly set factor_names = list(factor_names) # override default value for space argument space = kwargs.get('space', None) if kwargs.get('space', None) is None: kwargs['space'] = '_'.join(factor_names) + '_indices' super(ProductFlattenMapper, self).__init__(**kwargs) self._factor_names = factor_names if factor_values is not None: if len(factor_values) != len(factor_names): raise ValueError('factor_values must have %d elements, ' 'found %d' % (len(factor_names), len(factor_names))) self._factor_values = factor_values
[ "def", "__init__", "(", "self", ",", "factor_names", ",", "factor_values", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'auto_train'", "]", "=", "kwargs", ".", "get", "(", "'auto_train'", ",", "True", ")", "# make sure the factor names and...
https://github.com/PyMVPA/PyMVPA/blob/76c476b3de8264b0bb849bf226da5674d659564e/mvpa2/mappers/flatten.py#L201-L241
tensorflow/tfx
b4a6b83269815ed12ba9df9e9154c7376fef2ea0
tfx/examples/custom_components/slack/example/taxi_pipeline_slack_kubeflow.py
python
_create_pipeline
()
return pipeline.Pipeline( pipeline_name=_pipeline_name, pipeline_root=_pipeline_root, components=[ example_gen, statistics_gen, schema_gen, example_validator, transform, trainer, evaluator, model_validator, slack_validator, pusher ], enable_cache=True, )
Implements the chicago taxi pipeline with TFX.
Implements the chicago taxi pipeline with TFX.
[ "Implements", "the", "chicago", "taxi", "pipeline", "with", "TFX", "." ]
def _create_pipeline(): """Implements the chicago taxi pipeline with TFX.""" examples = csv_input(_data_root) # Brings data into the pipeline or otherwise joins/converts training data. example_gen = CsvExampleGen(input=examples) # Computes statistics over data for visualization and example validation. statistics_gen = StatisticsGen(examples=example_gen.outputs['examples']) # Generates schema based on statistics files. schema_gen = SchemaGen(statistics=statistics_gen.outputs['statistics']) # Performs anomaly detection based on statistics and data schema. example_validator = ExampleValidator( statistics=statistics_gen.outputs['statistics'], schema=schema_gen.outputs['schema']) # Performs transformations and feature engineering in training and serving. transform = Transform( examples=example_gen.outputs['examples'], schema=schema_gen.outputs['schema'], preprocessing_fn=_taxi_transformer_func) # Uses user-provided Python function that implements a model. trainer = Trainer( trainer_fn=_taxi_trainer_func, examples=transform.outputs['transformed_examples'], schema=schema_gen.outputs['schema'], transform_graph=transform.outputs['transform_graph'], train_args=trainer_pb2.TrainArgs(num_steps=10000), eval_args=trainer_pb2.EvalArgs(num_steps=5000)) # Uses TFMA to compute a evaluation statistics over features of a model. evaluator = Evaluator( examples=example_gen.outputs['examples'], model=trainer.outputs['model'], feature_slicing_spec=evaluator_pb2.FeatureSlicingSpec(specs=[ evaluator_pb2.SingleSlicingSpec( column_for_slicing=['trip_start_hour']) ])) # Performs quality validation of a candidate model (compared to a baseline). model_validator = ModelValidator( examples=example_gen.outputs['examples'], model=trainer.outputs['model']) # This custom component serves as a bridge between pipeline and human model # reviewers to enable review-and-push workflow in model development cycle. It # utilizes Slack API to send message to user-defined Slack channel with model # URI info and wait for go / no-go decision from the same Slack channel: # * To approve the model, users need to reply the thread sent out by the bot # started by SlackComponent with 'lgtm' or 'approve'. # * To reject the model, users need to reply the thread sent out by the bot # started by SlackComponent with 'decline' or 'reject'. slack_validator = SlackComponent( model=trainer.outputs['model'], model_blessing=model_validator.outputs['blessing'], slack_token=_slack_token, slack_channel_id=_slack_channel_id, timeout_sec=3600, ) # Checks whether the model passed the validation steps and pushes the model # to a file destination if check passed. pusher = Pusher( model=trainer.outputs['model'], model_blessing=slack_validator.outputs['slack_blessing'], push_destination=pusher_pb2.PushDestination( filesystem=pusher_pb2.PushDestination.Filesystem( base_directory=_serving_model_dir))) return pipeline.Pipeline( pipeline_name=_pipeline_name, pipeline_root=_pipeline_root, components=[ example_gen, statistics_gen, schema_gen, example_validator, transform, trainer, evaluator, model_validator, slack_validator, pusher ], enable_cache=True, )
[ "def", "_create_pipeline", "(", ")", ":", "examples", "=", "csv_input", "(", "_data_root", ")", "# Brings data into the pipeline or otherwise joins/converts training data.", "example_gen", "=", "CsvExampleGen", "(", "input", "=", "examples", ")", "# Computes statistics over d...
https://github.com/tensorflow/tfx/blob/b4a6b83269815ed12ba9df9e9154c7376fef2ea0/tfx/examples/custom_components/slack/example/taxi_pipeline_slack_kubeflow.py#L81-L159
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/celery/backends/rpc.py
python
RPCBackend.on_out_of_band_result
(self, task_id, message)
[]
def on_out_of_band_result(self, task_id, message): # Callback called when a reply for a task is received, # but we have no idea what do do with it. # Since the result is not pending, we put it in a separate # buffer: probably it will become pending later. if self.result_consumer: self.result_consumer.on_out_of_band_result(message) self._out_of_band[task_id] = message
[ "def", "on_out_of_band_result", "(", "self", ",", "task_id", ",", "message", ")", ":", "# Callback called when a reply for a task is received,", "# but we have no idea what do do with it.", "# Since the result is not pending, we put it in a separate", "# buffer: probably it will become pen...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/backends/rpc.py#L227-L234
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/litterrobot/vacuum.py
python
LitterRobotCleaner.async_reset_waste_drawer
(self)
Reset the waste drawer level.
Reset the waste drawer level.
[ "Reset", "the", "waste", "drawer", "level", "." ]
async def async_reset_waste_drawer(self) -> None: """Reset the waste drawer level.""" # The Litter-Robot reset waste drawer service has been replaced by a # dedicated button entity and marked as deprecated _LOGGER.warning( "The 'litterrobot.reset_waste_drawer' service is deprecated and " "replaced by a dedicated reset waste drawer button entity; Please " "use that entity to reset the waste drawer instead" ) await self.robot.reset_waste_drawer() self.coordinator.async_set_updated_data(True)
[ "async", "def", "async_reset_waste_drawer", "(", "self", ")", "->", "None", ":", "# The Litter-Robot reset waste drawer service has been replaced by a", "# dedicated button entity and marked as deprecated", "_LOGGER", ".", "warning", "(", "\"The 'litterrobot.reset_waste_drawer' service...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/litterrobot/vacuum.py#L125-L135