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
blurstudio/cross3d
277968d1227de740fc87ef61005c75034420eadf
cross3d/abstract/abstractscenewrapper.py
python
AbstractSceneWrapper.property
(self, key, default=None)
return self._scene._fromNativeValue(self._nativeProperty(key, default))
Return the value of the property defined by the inputed key
Return the value of the property defined by the inputed key
[ "Return", "the", "value", "of", "the", "property", "defined", "by", "the", "inputed", "key" ]
def property(self, key, default=None): """ Return the value of the property defined by the inputed key """ return self._scene._fromNativeValue(self._nativeProperty(key, default))
[ "def", "property", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "return", "self", ".", "_scene", ".", "_fromNativeValue", "(", "self", ".", "_nativeProperty", "(", "key", ",", "default", ")", ")" ]
https://github.com/blurstudio/cross3d/blob/277968d1227de740fc87ef61005c75034420eadf/cross3d/abstract/abstractscenewrapper.py#L202-L207
aim-uofa/AdelaiDet
fffb2ca1fbca88ec4d96e9ebc285bffe5027a947
adet/modeling/MEInst/LME/utils.py
python
inverse_sigmoid
(x)
return y
Apply the inverse sigmoid operation. y = -ln(1-x/x)
Apply the inverse sigmoid operation. y = -ln(1-x/x)
[ "Apply", "the", "inverse", "sigmoid", "operation", ".", "y", "=", "-", "ln", "(", "1", "-", "x", "/", "x", ")" ]
def inverse_sigmoid(x): """Apply the inverse sigmoid operation. y = -ln(1-x/x) """ y = -1 * np.log((1-x)/x) return y
[ "def", "inverse_sigmoid", "(", "x", ")", ":", "y", "=", "-", "1", "*", "np", ".", "log", "(", "(", "1", "-", "x", ")", "/", "x", ")", "return", "y" ]
https://github.com/aim-uofa/AdelaiDet/blob/fffb2ca1fbca88ec4d96e9ebc285bffe5027a947/adet/modeling/MEInst/LME/utils.py#L14-L19
iiau-tracker/SPLT
a196e603798e9be969d9d985c087c11cad1cda43
lib/object_detection/exporter.py
python
_write_frozen_graph
(frozen_graph_path, frozen_graph_def)
Writes frozen graph to disk. Args: frozen_graph_path: Path to write inference graph. frozen_graph_def: tf.GraphDef holding frozen graph.
Writes frozen graph to disk.
[ "Writes", "frozen", "graph", "to", "disk", "." ]
def _write_frozen_graph(frozen_graph_path, frozen_graph_def): """Writes frozen graph to disk. Args: frozen_graph_path: Path to write inference graph. frozen_graph_def: tf.GraphDef holding frozen graph. """ with gfile.GFile(frozen_graph_path, 'wb') as f: f.write(frozen_graph_def.SerializeToString()) logging.info('%d ops in the final graph.', len(frozen_graph_def.node))
[ "def", "_write_frozen_graph", "(", "frozen_graph_path", ",", "frozen_graph_def", ")", ":", "with", "gfile", ".", "GFile", "(", "frozen_graph_path", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "frozen_graph_def", ".", "SerializeToString", "(", ")"...
https://github.com/iiau-tracker/SPLT/blob/a196e603798e9be969d9d985c087c11cad1cda43/lib/object_detection/exporter.py#L225-L234
OpenMined/PySyft
f181ca02d307d57bfff9477610358df1a12e3ac9
packages/syft/src/syft/ast/attribute.py
python
Attribute.properties
(self)
return out
Extract all properties from the current node attributes. Returns: The list of properties in the current AST node attributes.
Extract all properties from the current node attributes.
[ "Extract", "all", "properties", "from", "the", "current", "node", "attributes", "." ]
def properties(self) -> List["ast.property.Property"]: """Extract all properties from the current node attributes. Returns: The list of properties in the current AST node attributes. """ out = [] if isinstance(self, ast.property.Property): out.append(self) self._extract_attr_type(out, "properties") return out
[ "def", "properties", "(", "self", ")", "->", "List", "[", "\"ast.property.Property\"", "]", ":", "out", "=", "[", "]", "if", "isinstance", "(", "self", ",", "ast", ".", "property", ".", "Property", ")", ":", "out", ".", "append", "(", "self", ")", "s...
https://github.com/OpenMined/PySyft/blob/f181ca02d307d57bfff9477610358df1a12e3ac9/packages/syft/src/syft/ast/attribute.py#L114-L126
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/pydoc.py
python
render_doc
(thing, title='Python Library Documentation: %s', forceload=0)
return title % desc + '\n\n' + text.document(object, name)
Render text documentation, given an object or a path to an object.
Render text documentation, given an object or a path to an object.
[ "Render", "text", "documentation", "given", "an", "object", "or", "a", "path", "to", "an", "object", "." ]
def render_doc(thing, title='Python Library Documentation: %s', forceload=0): """Render text documentation, given an object or a path to an object.""" object, name = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ if type(object) is _OLD_INSTANCE_TYPE: # If the passed object is an instance of an old-style class, # document its available methods instead of its value. object = object.__class__ elif not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or inspect.ismemberdescriptor(object) or isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) desc += ' object' return title % desc + '\n\n' + text.document(object, name)
[ "def", "render_doc", "(", "thing", ",", "title", "=", "'Python Library Documentation: %s'", ",", "forceload", "=", "0", ")", ":", "object", ",", "name", "=", "resolve", "(", "thing", ",", "forceload", ")", "desc", "=", "describe", "(", "object", ")", "modu...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/pydoc.py#L1545-L1568
tylerlaberge/PyPattyrn
6561e9927553a9074d0a71247a1b1e933f2ec423
pypattyrn/behavioral/memento.py
python
Originator.rollback
(self, memento)
Rollback this objects state to a previous state. @param memento: The memento object holding the state to rollback to. @type memento: Memento
Rollback this objects state to a previous state.
[ "Rollback", "this", "objects", "state", "to", "a", "previous", "state", "." ]
def rollback(self, memento): """ Rollback this objects state to a previous state. @param memento: The memento object holding the state to rollback to. @type memento: Memento """ self.__dict__ = memento.state
[ "def", "rollback", "(", "self", ",", "memento", ")", ":", "self", ".", "__dict__", "=", "memento", ".", "state" ]
https://github.com/tylerlaberge/PyPattyrn/blob/6561e9927553a9074d0a71247a1b1e933f2ec423/pypattyrn/behavioral/memento.py#L40-L47
jamiecaesar/securecrt-tools
f3cbb49223a485fc9af86e9799b5c940f19e8027
securecrt_tools/sessions.py
python
Session.end_cisco_session
(self)
End the session by returning the device's terminal parameters that were modified by start_session() to their previous values. This should always be called before a disconnect (assuming that start_cisco_session was called after connect)
End the session by returning the device's terminal parameters that were modified by start_session() to their previous values.
[ "End", "the", "session", "by", "returning", "the", "device", "s", "terminal", "parameters", "that", "were", "modified", "by", "start_session", "()", "to", "their", "previous", "values", "." ]
def end_cisco_session(self): """ End the session by returning the device's terminal parameters that were modified by start_session() to their previous values. This should always be called before a disconnect (assuming that start_cisco_session was called after connect) """ pass
[ "def", "end_cisco_session", "(", "self", ")", ":", "pass" ]
https://github.com/jamiecaesar/securecrt-tools/blob/f3cbb49223a485fc9af86e9799b5c940f19e8027/securecrt_tools/sessions.py#L194-L201
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tbaas/v20180416/models.py
python
GetLatesdTransactionListResponse.__init__
(self)
r""" :param TotalCount: 交易总数量 :type TotalCount: int :param TransactionList: 交易列表 :type TransactionList: list of TransactionItem :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param TotalCount: 交易总数量 :type TotalCount: int :param TransactionList: 交易列表 :type TransactionList: list of TransactionItem :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "TotalCount", ":", "交易总数量", ":", "type", "TotalCount", ":", "int", ":", "param", "TransactionList", ":", "交易列表", ":", "type", "TransactionList", ":", "list", "of", "TransactionItem", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定位问题时...
def __init__(self): r""" :param TotalCount: 交易总数量 :type TotalCount: int :param TransactionList: 交易列表 :type TransactionList: list of TransactionItem :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.TotalCount = None self.TransactionList = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "TotalCount", "=", "None", "self", ".", "TransactionList", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tbaas/v20180416/models.py#L1937-L1948
aws/sagemaker-python-sdk
9d259b316f7f43838c16f35c10e98a110b56735b
src/sagemaker/workflow/conditions.py
python
ConditionGreaterThan.__init__
( self, left: Union[ConditionValueType, PrimitiveType], right: Union[ConditionValueType, PrimitiveType], )
Construct an instance of ConditionGreaterThan for greater than comparisons. Args: left (Union[ConditionValueType, PrimitiveType]): The execution variable, parameter, property, or Python primitive value to use in the comparison. right (Union[ConditionValueType, PrimitiveType]): The execution variable, parameter, property, or Python primitive value to compare to.
Construct an instance of ConditionGreaterThan for greater than comparisons.
[ "Construct", "an", "instance", "of", "ConditionGreaterThan", "for", "greater", "than", "comparisons", "." ]
def __init__( self, left: Union[ConditionValueType, PrimitiveType], right: Union[ConditionValueType, PrimitiveType], ): """Construct an instance of ConditionGreaterThan for greater than comparisons. Args: left (Union[ConditionValueType, PrimitiveType]): The execution variable, parameter, property, or Python primitive value to use in the comparison. right (Union[ConditionValueType, PrimitiveType]): The execution variable, parameter, property, or Python primitive value to compare to. """ super(ConditionGreaterThan, self).__init__(ConditionTypeEnum.GT, left, right)
[ "def", "__init__", "(", "self", ",", "left", ":", "Union", "[", "ConditionValueType", ",", "PrimitiveType", "]", ",", "right", ":", "Union", "[", "ConditionValueType", ",", "PrimitiveType", "]", ",", ")", ":", "super", "(", "ConditionGreaterThan", ",", "self...
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/workflow/conditions.py#L110-L124
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/zope.interface-4.5.0/src/zope/interface/common/mapping.py
python
IWriteMapping.__delitem__
(key)
Delete a value from the mapping using the key.
Delete a value from the mapping using the key.
[ "Delete", "a", "value", "from", "the", "mapping", "using", "the", "key", "." ]
def __delitem__(key): """Delete a value from the mapping using the key."""
[ "def", "__delitem__", "(", "key", ")", ":" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/zope.interface-4.5.0/src/zope/interface/common/mapping.py#L46-L47
nottombrown/rl-teacher
b2c2201e9d2457b13185424a19da7209364f23df
agents/pposgd-mpi/pposgd_mpi/run_mujoco.py
python
train_pposgd_mpi
(make_env, num_timesteps, seed, predictor=None)
[]
def train_pposgd_mpi(make_env, num_timesteps, seed, predictor=None): from pposgd_mpi import mlp_policy, pposgd_simple U.make_session(num_cpu=1).__enter__() logger.session().__enter__() set_global_seeds(seed) env = make_env() def policy_fn(name, ob_space, ac_space): return mlp_policy.MlpPolicy(name=name, ob_space=ob_space, ac_space=ac_space, hid_size=64, num_hid_layers=2) env = bench.Monitor(env, osp.join(logger.get_dir(), "monitor.json")) env.seed(seed) gym.logger.setLevel(logging.WARN) pposgd_simple.learn(env, policy_fn, max_timesteps=num_timesteps, timesteps_per_batch=2048*8, clip_param=0.2, entcoeff=0.0, optim_epochs=10, optim_stepsize=3e-4, optim_batchsize=64, gamma=0.99, lam=0.95, predictor=predictor ) env.close()
[ "def", "train_pposgd_mpi", "(", "make_env", ",", "num_timesteps", ",", "seed", ",", "predictor", "=", "None", ")", ":", "from", "pposgd_mpi", "import", "mlp_policy", ",", "pposgd_simple", "U", ".", "make_session", "(", "num_cpu", "=", "1", ")", ".", "__enter...
https://github.com/nottombrown/rl-teacher/blob/b2c2201e9d2457b13185424a19da7209364f23df/agents/pposgd-mpi/pposgd_mpi/run_mujoco.py#L10-L32
astropy/astroquery
11c9c83fa8e5f948822f8f73c854ec4b72043016
astroquery/utils/tap/gui/login.py
python
LoginDialog.__init__
(self, host)
[]
def __init__(self, host): self.__interna_init() self.__host = host self.__initialized = False if TKTk is not None: self.__create_content() self.__initialized = True
[ "def", "__init__", "(", "self", ",", "host", ")", ":", "self", ".", "__interna_init", "(", ")", "self", ".", "__host", "=", "host", "self", ".", "__initialized", "=", "False", "if", "TKTk", "is", "not", "None", ":", "self", ".", "__create_content", "("...
https://github.com/astropy/astroquery/blob/11c9c83fa8e5f948822f8f73c854ec4b72043016/astroquery/utils/tap/gui/login.py#L46-L52
wbond/asn1crypto
9ae350f212532dfee7f185f6b3eda24753249cf3
asn1crypto/core.py
python
Sequence.__delitem__
(self, key)
Allows deleting optional or default fields by name or index :param key: A unicode string of the field name, or an integer of the field index :raises: ValueError - when a field name or index is invalid, or the field is not optional or defaulted
Allows deleting optional or default fields by name or index
[ "Allows", "deleting", "optional", "or", "default", "fields", "by", "name", "or", "index" ]
def __delitem__(self, key): """ Allows deleting optional or default fields by name or index :param key: A unicode string of the field name, or an integer of the field index :raises: ValueError - when a field name or index is invalid, or the field is not optional or defaulted """ # We inline this check to prevent method invocation each time if self.children is None: self._parse_children() if not isinstance(key, int_types): if key not in self._field_map: raise KeyError(unwrap( ''' No field named "%s" defined for %s ''', key, type_name(self) )) key = self._field_map[key] name, _, params = self._fields[key] if not params or ('default' not in params and 'optional' not in params): raise ValueError(unwrap( ''' Can not delete the value for the field "%s" of %s since it is not optional or defaulted ''', name, type_name(self) )) if 'optional' in params: self.children[key] = VOID if self._native is not None: self._native[name] = None else: self.__setitem__(key, None) self._mutated = True
[ "def", "__delitem__", "(", "self", ",", "key", ")", ":", "# We inline this check to prevent method invocation each time", "if", "self", ".", "children", "is", "None", ":", "self", ".", "_parse_children", "(", ")", "if", "not", "isinstance", "(", "key", ",", "int...
https://github.com/wbond/asn1crypto/blob/9ae350f212532dfee7f185f6b3eda24753249cf3/asn1crypto/core.py#L3593-L3636
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/cronjobs.py
python
CronManager.__init__
(self, max_threads=10)
[]
def __init__(self, max_threads=10): super().__init__() if max_threads <= 0: raise ValueError("max_threads should be >= 1") self.max_threads = max_threads
[ "def", "__init__", "(", "self", ",", "max_threads", "=", "10", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "if", "max_threads", "<=", "0", ":", "raise", "ValueError", "(", "\"max_threads should be >= 1\"", ")", "self", ".", "max_threads", "=", ...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/cronjobs.py#L200-L206
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/metagoofil/hachoir_core/stream/input.py
python
FileFromInputStream.read
(self, size=None)
[]
def read(self, size=None): def read(address, size): shift, data, missing = self.stream.read(8 * address, 8 * size) if shift: raise InputStreamError("TODO: handle non-byte-aligned data") return data if self._size or size is not None and not self._from_end: # We don't want self.tell() to read anything # and the size must be known if we read until the end. pos = self.tell() if size is None or None < self._size < pos + size: size = self._size - pos if size <= 0: return '' data = read(pos, size) self._offset += len(data) return data elif self._from_end: # TODO: not tested max_size = - self._offset if size is None or max_size < size: size = max_size if size <= 0: return '' data = '', '' self._offset = max(0, self.stream._current_size // 8 + self._offset) self._from_end = False bs = max(max_size, 1 << 16) while True: d = read(self._offset, bs) data = data[1], d self._offset += len(d) if self._size: bs = self._size - self._offset if not bs: data = data[0] + data[1] d = len(data) - max_size return data[d:d+size] else: # TODO: not tested data = [ ] size = 1 << 16 while True: d = read(self._offset, size) data.append(d) self._offset += len(d) if self._size: size = self._size - self._offset if not size: return ''.join(data)
[ "def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "def", "read", "(", "address", ",", "size", ")", ":", "shift", ",", "data", ",", "missing", "=", "self", ".", "stream", ".", "read", "(", "8", "*", "address", ",", "8", "*", "size"...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_core/stream/input.py#L69-L118
google-research/rigl
f18abc7d82ae3acc6736068408a0186c9efa575c
rigl/rigl_tf2/interpolate.py
python
test_model
(model, d_test, batch_size=1000)
return test_loss.result().numpy(), test_accuracy.result().numpy()
Tests the model and calculates cross entropy loss and accuracy.
Tests the model and calculates cross entropy loss and accuracy.
[ "Tests", "the", "model", "and", "calculates", "cross", "entropy", "loss", "and", "accuracy", "." ]
def test_model(model, d_test, batch_size=1000): """Tests the model and calculates cross entropy loss and accuracy.""" test_loss = tf.keras.metrics.Mean(name='test_loss') test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy( name='test_accuracy') loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) for x, y in d_test.batch(batch_size): predictions = model(x, training=False) batch_loss = loss_object(y, predictions) test_loss.update_state(batch_loss) test_accuracy.update_state(y, predictions) logging.info('Test loss: %f', test_loss.result().numpy()) logging.info('Test accuracy: %f', test_accuracy.result().numpy()) return test_loss.result().numpy(), test_accuracy.result().numpy()
[ "def", "test_model", "(", "model", ",", "d_test", ",", "batch_size", "=", "1000", ")", ":", "test_loss", "=", "tf", ".", "keras", ".", "metrics", ".", "Mean", "(", "name", "=", "'test_loss'", ")", "test_accuracy", "=", "tf", ".", "keras", ".", "metrics...
https://github.com/google-research/rigl/blob/f18abc7d82ae3acc6736068408a0186c9efa575c/rigl/rigl_tf2/interpolate.py#L62-L75
oaubert/python-vlc
908ffdbd0844dc1849728c456e147788798c99da
generated/3.0/distribute_setup.py
python
_build_install_args
(options)
return install_args
Build the arguments to 'python setup.py install' on the distribute package
Build the arguments to 'python setup.py install' on the distribute package
[ "Build", "the", "arguments", "to", "python", "setup", ".", "py", "install", "on", "the", "distribute", "package" ]
def _build_install_args(options): """ Build the arguments to 'python setup.py install' on the distribute package """ install_args = [] if options.user_install: if sys.version_info < (2, 6): log.warn("--user requires Python 2.6 or later") raise SystemExit(1) install_args.append('--user') return install_args
[ "def", "_build_install_args", "(", "options", ")", ":", "install_args", "=", "[", "]", "if", "options", ".", "user_install", ":", "if", "sys", ".", "version_info", "<", "(", "2", ",", "6", ")", ":", "log", ".", "warn", "(", "\"--user requires Python 2.6 or...
https://github.com/oaubert/python-vlc/blob/908ffdbd0844dc1849728c456e147788798c99da/generated/3.0/distribute_setup.py#L515-L525
awslabs/deeplearning-benchmark
3e9a906422b402869537f91056ae771b66487a8e
word_language_model/word_language_model_train.py
python
eval
(data_source, ctx)
return total_L / ntotal
[]
def eval(data_source, ctx): total_L = 0.0 ntotal = 0 hidden_states = [ model.begin_state(func=mx.nd.zeros, batch_size=args.batch_size/len(ctx), ctx=ctx[i]) for i in range(len(ctx)) ] for i in range(0, data_source.shape[0] - 1, args.bptt): data_batch, target_batch = get_batch(data_source, i) data = gluon.utils.split_and_load(data_batch, ctx_list=ctx, batch_axis=1) target = gluon.utils.split_and_load(target_batch, ctx_list=ctx, batch_axis=1) for (d, t) in zip(data, target): hidden = hidden_states[d.context.device_id] output, hidden = model(d, hidden) L = loss(output, t.reshape((-1,))) total_L += mx.nd.sum(L).asscalar() ntotal += L.size return total_L / ntotal
[ "def", "eval", "(", "data_source", ",", "ctx", ")", ":", "total_L", "=", "0.0", "ntotal", "=", "0", "hidden_states", "=", "[", "model", ".", "begin_state", "(", "func", "=", "mx", ".", "nd", ".", "zeros", ",", "batch_size", "=", "args", ".", "batch_s...
https://github.com/awslabs/deeplearning-benchmark/blob/3e9a906422b402869537f91056ae771b66487a8e/word_language_model/word_language_model_train.py#L90-L107
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/psutil/_pssunos.py
python
disk_partitions
(all=False)
return retlist
Return system disk partitions.
Return system disk partitions.
[ "Return", "system", "disk", "partitions", "." ]
def disk_partitions(all=False): """Return system disk partitions.""" # TODO - the filtering logic should be better checked so that # it tries to reflect 'df' as much as possible retlist = [] partitions = cext.disk_partitions() for partition in partitions: device, mountpoint, fstype, opts = partition if device == 'none': device = '' if not all: # Differently from, say, Linux, we don't have a list of # common fs types so the best we can do, AFAIK, is to # filter by filesystem having a total size > 0. if not disk_usage(mountpoint).total: continue ntuple = _common.sdiskpart(device, mountpoint, fstype, opts) retlist.append(ntuple) return retlist
[ "def", "disk_partitions", "(", "all", "=", "False", ")", ":", "# TODO - the filtering logic should be better checked so that", "# it tries to reflect 'df' as much as possible", "retlist", "=", "[", "]", "partitions", "=", "cext", ".", "disk_partitions", "(", ")", "for", "...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/psutil/_pssunos.py#L215-L233
pschanely/CrossHair
11702dda7cbd47cb7ac978844094a26fb12d296c
crosshair/libimpl/builtinslib.py
python
tracing_iter
(itr: Iterable[_T])
Selectively re-enable tracing only during iteration.
Selectively re-enable tracing only during iteration.
[ "Selectively", "re", "-", "enable", "tracing", "only", "during", "iteration", "." ]
def tracing_iter(itr: Iterable[_T]) -> Iterable[_T]: """Selectively re-enable tracing only during iteration.""" assert not is_tracing() itr = iter(itr) while True: try: with ResumedTracing(): value = next(itr) except StopIteration: return yield value
[ "def", "tracing_iter", "(", "itr", ":", "Iterable", "[", "_T", "]", ")", "->", "Iterable", "[", "_T", "]", ":", "assert", "not", "is_tracing", "(", ")", "itr", "=", "iter", "(", "itr", ")", "while", "True", ":", "try", ":", "with", "ResumedTracing", ...
https://github.com/pschanely/CrossHair/blob/11702dda7cbd47cb7ac978844094a26fb12d296c/crosshair/libimpl/builtinslib.py#L2119-L2129
spywhere/Javatar
e273ec40c209658247a71b109bb90cd126984a29
core/java_utils.py
python
_JavaUtils.normalize_package_path
(self, class_path)
return RE().get("normalize_package_path", "^\\.*|\\.*$").sub( "", class_path )
Returns a dot-trimmed class path @param class_path: a class path to be trimmed
Returns a dot-trimmed class path
[ "Returns", "a", "dot", "-", "trimmed", "class", "path" ]
def normalize_package_path(self, class_path): """ Returns a dot-trimmed class path @param class_path: a class path to be trimmed """ return RE().get("normalize_package_path", "^\\.*|\\.*$").sub( "", class_path )
[ "def", "normalize_package_path", "(", "self", ",", "class_path", ")", ":", "return", "RE", "(", ")", ".", "get", "(", "\"normalize_package_path\"", ",", "\"^\\\\.*|\\\\.*$\"", ")", ".", "sub", "(", "\"\"", ",", "class_path", ")" ]
https://github.com/spywhere/Javatar/blob/e273ec40c209658247a71b109bb90cd126984a29/core/java_utils.py#L207-L215
cocrawler/cocrawler
a9be74308fe666130cb9ca3dd64e18f4c30d2894
cocrawler/datalayer.py
python
Datalayer.memory
(self)
return {'seen_set': seen_set, 'robots': robots}
Return a dict summarizing the datalayer's memory usage
Return a dict summarizing the datalayer's memory usage
[ "Return", "a", "dict", "summarizing", "the", "datalayer", "s", "memory", "usage" ]
def memory(self): '''Return a dict summarizing the datalayer's memory usage''' seen_set = {} seen_set['bytes'] = memory.total_size(self.seen_set) seen_set['len'] = len(self.seen_set) robots = {} robots['bytes'] = memory.total_size(self.robots) robots['len'] = len(self.robots) return {'seen_set': seen_set, 'robots': robots}
[ "def", "memory", "(", "self", ")", ":", "seen_set", "=", "{", "}", "seen_set", "[", "'bytes'", "]", "=", "memory", ".", "total_size", "(", "self", ".", "seen_set", ")", "seen_set", "[", "'len'", "]", "=", "len", "(", "self", ".", "seen_set", ")", "...
https://github.com/cocrawler/cocrawler/blob/a9be74308fe666130cb9ca3dd64e18f4c30d2894/cocrawler/datalayer.py#L52-L60
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_image.py
python
OpenShiftCLIConfig.to_option_list
(self, ascommalist='')
return self.stringify(ascommalist)
return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs
return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs
[ "return", "all", "options", "as", "a", "string", "if", "ascommalist", "is", "set", "to", "the", "name", "of", "a", "key", "and", "the", "value", "of", "that", "key", "is", "a", "dict", "format", "the", "dict", "as", "a", "list", "of", "comma", "delim...
def to_option_list(self, ascommalist=''): '''return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs''' return self.stringify(ascommalist)
[ "def", "to_option_list", "(", "self", ",", "ascommalist", "=", "''", ")", ":", "return", "self", ".", "stringify", "(", "ascommalist", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_image.py#L1436-L1441
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/jc-weather/requests/packages/urllib3/util.py
python
make_headers
(keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None)
return headers
Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. Example: :: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'}
Shortcuts for generating request headers.
[ "Shortcuts", "for", "generating", "request", "headers", "." ]
def make_headers(keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None): """ Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. Example: :: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'} """ headers = {} if accept_encoding: if isinstance(accept_encoding, str): pass elif isinstance(accept_encoding, list): accept_encoding = ','.join(accept_encoding) else: accept_encoding = 'gzip,deflate' headers['accept-encoding'] = accept_encoding if user_agent: headers['user-agent'] = user_agent if keep_alive: headers['connection'] = 'keep-alive' if basic_auth: headers['authorization'] = 'Basic ' + \ b64encode(six.b(basic_auth)).decode('utf-8') return headers
[ "def", "make_headers", "(", "keep_alive", "=", "None", ",", "accept_encoding", "=", "None", ",", "user_agent", "=", "None", ",", "basic_auth", "=", "None", ")", ":", "headers", "=", "{", "}", "if", "accept_encoding", ":", "if", "isinstance", "(", "accept_e...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/jc-weather/requests/packages/urllib3/util.py#L182-L231
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/tools/interfaces/sensors/myo/myo_raw.py
python
MyoRaw.start_raw
(self)
Sending this sequence for v1.0 firmware seems to enable both raw data and pose notifications.
Sending this sequence for v1.0 firmware seems to enable both raw data and pose notifications.
[ "Sending", "this", "sequence", "for", "v1", ".", "0", "firmware", "seems", "to", "enable", "both", "raw", "data", "and", "pose", "notifications", "." ]
def start_raw(self): """Sending this sequence for v1.0 firmware seems to enable both raw data and pose notifications. """ self.write_attr(0x28, b'\x01\x00') # EMG? # self.write_attr(0x19, b'\x01\x03\x01\x01\x00') self.write_attr(0x19, b'\x01\x03\x01\x01\x01')
[ "def", "start_raw", "(", "self", ")", ":", "self", ".", "write_attr", "(", "0x28", ",", "b'\\x01\\x00'", ")", "# EMG?", "# self.write_attr(0x19, b'\\x01\\x03\\x01\\x01\\x00')", "self", ".", "write_attr", "(", "0x19", ",", "b'\\x01\\x03\\x01\\x01\\x01'", ")" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/tools/interfaces/sensors/myo/myo_raw.py#L376-L383
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/core/mail/utils.py
python
CachedDnsName.__str__
(self)
return self.get_fqdn()
[]
def __str__(self): return self.get_fqdn()
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "get_fqdn", "(", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/core/mail/utils.py#L11-L12
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/xml/dom/minidom.py
python
Element.removeAttributeNS
(self, namespaceURI, localName)
[]
def removeAttributeNS(self, namespaceURI, localName): try: attr = self._attrsNS[(namespaceURI, localName)] except KeyError: raise xml.dom.NotFoundErr() self.removeAttributeNode(attr)
[ "def", "removeAttributeNS", "(", "self", ",", "namespaceURI", ",", "localName", ")", ":", "try", ":", "attr", "=", "self", ".", "_attrsNS", "[", "(", "namespaceURI", ",", "localName", ")", "]", "except", "KeyError", ":", "raise", "xml", ".", "dom", ".", ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/xml/dom/minidom.py#L754-L759
sabnzbd/sabnzbd
52d21e94d3cc6e30764a833fe2a256783d1a8931
sabnzbd/misc.py
python
find_on_path
(targets)
return None
Search the PATH for a program and return full path
Search the PATH for a program and return full path
[ "Search", "the", "PATH", "for", "a", "program", "and", "return", "full", "path" ]
def find_on_path(targets): """Search the PATH for a program and return full path""" if sabnzbd.WIN32: paths = os.getenv("PATH").split(";") else: paths = os.getenv("PATH").split(":") if isinstance(targets, str): targets = (targets,) for path in paths: for target in targets: target_path = os.path.abspath(os.path.join(path, target)) if os.path.isfile(target_path) and os.access(target_path, os.X_OK): return target_path return None
[ "def", "find_on_path", "(", "targets", ")", ":", "if", "sabnzbd", ".", "WIN32", ":", "paths", "=", "os", ".", "getenv", "(", "\"PATH\"", ")", ".", "split", "(", "\";\"", ")", "else", ":", "paths", "=", "os", ".", "getenv", "(", "\"PATH\"", ")", "."...
https://github.com/sabnzbd/sabnzbd/blob/52d21e94d3cc6e30764a833fe2a256783d1a8931/sabnzbd/misc.py#L859-L874
datacenter/acitoolkit
629b84887dd0f0183b81efc8adb16817f985541a
acitoolkit/aciphysobject.py
python
Linecard._populate_from_attributes
(self, attributes)
Fills in an object with the desired attributes. Overridden by inheriting classes to provide the specific attributes when getting objects from the APIC.
Fills in an object with the desired attributes. Overridden by inheriting classes to provide the specific attributes when getting objects from the APIC.
[ "Fills", "in", "an", "object", "with", "the", "desired", "attributes", ".", "Overridden", "by", "inheriting", "classes", "to", "provide", "the", "specific", "attributes", "when", "getting", "objects", "from", "the", "APIC", "." ]
def _populate_from_attributes(self, attributes): """Fills in an object with the desired attributes. Overridden by inheriting classes to provide the specific attributes when getting objects from the APIC. """ self.serial = str(attributes['ser']) self.model = str(attributes['model']) self.descr = str(attributes['descr']) self.num_ports = str(attributes['numP']) self.hardware_version = str(attributes['hwVer']) self.hardware_revision = str(attributes['rev']) self.type = str(attributes['type']) self.oper_st = str(attributes['operSt']) self.dn = str(attributes['dn']) self.modify_time = str(attributes['modTs'])
[ "def", "_populate_from_attributes", "(", "self", ",", "attributes", ")", ":", "self", ".", "serial", "=", "str", "(", "attributes", "[", "'ser'", "]", ")", "self", ".", "model", "=", "str", "(", "attributes", "[", "'model'", "]", ")", "self", ".", "des...
https://github.com/datacenter/acitoolkit/blob/629b84887dd0f0183b81efc8adb16817f985541a/acitoolkit/aciphysobject.py#L349-L363
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/pdb.py
python
Pdb.user_line
(self, frame)
This function is called when we stop or break at this line.
This function is called when we stop or break at this line.
[ "This", "function", "is", "called", "when", "we", "stop", "or", "break", "at", "this", "line", "." ]
def user_line(self, frame): """This function is called when we stop or break at this line.""" if self._wait_for_mainpyfile: if (self.mainpyfile != self.canonic(frame.f_code.co_filename) or frame.f_lineno<= 0): return self._wait_for_mainpyfile = 0 if self.bp_commands(frame): self.interaction(frame, None)
[ "def", "user_line", "(", "self", ",", "frame", ")", ":", "if", "self", ".", "_wait_for_mainpyfile", ":", "if", "(", "self", ".", "mainpyfile", "!=", "self", ".", "canonic", "(", "frame", ".", "f_code", ".", "co_filename", ")", "or", "frame", ".", "f_li...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/pdb.py#L150-L158
CGCookie/retopoflow
3d8b3a47d1d661f99ab0aeb21d31370bf15de35e
retopoflow/updater.py
python
addon_updater_update_now.poll
(cls, context)
return True
[]
def poll(cls, context): # return False if retopoflow_version_git: return False # do not allow update if under git version control if updater.invalid_updater: return False # something bad happened; bail! if not updater.update_ready: return False # update not ready, yet return True
[ "def", "poll", "(", "cls", ",", "context", ")", ":", "# return False", "if", "retopoflow_version_git", ":", "return", "False", "# do not allow update if under git version control", "if", "updater", ".", "invalid_updater", ":", "return", "False", "# something bad happened;...
https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/retopoflow/updater.py#L263-L268
LinkedInAttic/indextank-service
880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e
nebu/flaptor/indextank/rpc/Indexer.py
python
Client.updateCategories
(self, docid, categories)
Parameters: - docid - categories
Parameters: - docid - categories
[ "Parameters", ":", "-", "docid", "-", "categories" ]
def updateCategories(self, docid, categories): """ Parameters: - docid - categories """ self.send_updateCategories(docid, categories) self.recv_updateCategories()
[ "def", "updateCategories", "(", "self", ",", "docid", ",", "categories", ")", ":", "self", ".", "send_updateCategories", "(", "docid", ",", "categories", ")", "self", ".", "recv_updateCategories", "(", ")" ]
https://github.com/LinkedInAttic/indextank-service/blob/880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e/nebu/flaptor/indextank/rpc/Indexer.py#L215-L222
KhronosGroup/OpenXR-SDK-Source
76756e2e7849b15466d29bee7d80cada92865550
external/python/jinja2/sandbox.py
python
SandboxedEnvironment.getattr
(self, obj, attribute)
return self.undefined(obj=obj, name=attribute)
Subscribe an object from sandboxed code and prefer the attribute. The attribute passed *must* be a bytestring.
Subscribe an object from sandboxed code and prefer the attribute. The attribute passed *must* be a bytestring.
[ "Subscribe", "an", "object", "from", "sandboxed", "code", "and", "prefer", "the", "attribute", ".", "The", "attribute", "passed", "*", "must", "*", "be", "a", "bytestring", "." ]
def getattr(self, obj, attribute): """Subscribe an object from sandboxed code and prefer the attribute. The attribute passed *must* be a bytestring. """ try: value = getattr(obj, attribute) except AttributeError: try: return obj[attribute] except (TypeError, LookupError): pass else: if self.is_safe_attribute(obj, attribute, value): return value return self.unsafe_undefined(obj, attribute) return self.undefined(obj=obj, name=attribute)
[ "def", "getattr", "(", "self", ",", "obj", ",", "attribute", ")", ":", "try", ":", "value", "=", "getattr", "(", "obj", ",", "attribute", ")", "except", "AttributeError", ":", "try", ":", "return", "obj", "[", "attribute", "]", "except", "(", "TypeErro...
https://github.com/KhronosGroup/OpenXR-SDK-Source/blob/76756e2e7849b15466d29bee7d80cada92865550/external/python/jinja2/sandbox.py#L382-L397
debian-calibre/calibre
020fc81d3936a64b2ac51459ecb796666ab6a051
src/calibre/db/fields.py
python
Field.for_book
(self, book_id, default_value=None)
Return the value of this field for the book identified by book_id. When no value is found, returns ``default_value``.
Return the value of this field for the book identified by book_id. When no value is found, returns ``default_value``.
[ "Return", "the", "value", "of", "this", "field", "for", "the", "book", "identified", "by", "book_id", ".", "When", "no", "value", "is", "found", "returns", "default_value", "." ]
def for_book(self, book_id, default_value=None): ''' Return the value of this field for the book identified by book_id. When no value is found, returns ``default_value``. ''' raise NotImplementedError()
[ "def", "for_book", "(", "self", ",", "book_id", ",", "default_value", "=", "None", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/db/fields.py#L120-L125
OpenMDAO/OpenMDAO1
791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317
openmdao/examples/sellar_MDF_optimize.py
python
SellarDis1.linearize
(self, params, unknowns, resids)
return J
Jacobian for Sellar discipline 1.
Jacobian for Sellar discipline 1.
[ "Jacobian", "for", "Sellar", "discipline", "1", "." ]
def linearize(self, params, unknowns, resids): """ Jacobian for Sellar discipline 1.""" J = {} J['y1','y2'] = -0.2 J['y1','z'] = np.array([[2*params['z'][0], 1.0]]) J['y1','x'] = 1.0 return J
[ "def", "linearize", "(", "self", ",", "params", ",", "unknowns", ",", "resids", ")", ":", "J", "=", "{", "}", "J", "[", "'y1'", ",", "'y2'", "]", "=", "-", "0.2", "J", "[", "'y1'", ",", "'z'", "]", "=", "np", ".", "array", "(", "[", "[", "2...
https://github.com/OpenMDAO/OpenMDAO1/blob/791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317/openmdao/examples/sellar_MDF_optimize.py#L36-L44
shubhtuls/factored3d
1bb77c7ae7dbaba7056e94cb99fdd6c9cc73c7cd
experiments/suncg/box3d.py
python
Box3dTrainer.forward
(self)
[]
def forward(self): opts = self.opts self.codes_pred = self.model.forward((self.input_imgs_fine, self.input_imgs, self.rois)) self.total_loss, self.loss_factors = loss_utils.code_loss( self.codes_pred, self.codes_gt, pred_voxels=opts.pred_voxels, classify_rot=opts.classify_rot, shape_wt=opts.shape_loss_wt, scale_wt=opts.scale_loss_wt, quat_wt=opts.quat_loss_wt, trans_wt=opts.trans_loss_wt ) for k in self.smoothed_factor_losses.keys(): self.smoothed_factor_losses[k] = 0.99*self.smoothed_factor_losses[k] + 0.01*self.loss_factors[k].data[0]
[ "def", "forward", "(", "self", ")", ":", "opts", "=", "self", ".", "opts", "self", ".", "codes_pred", "=", "self", ".", "model", ".", "forward", "(", "(", "self", ".", "input_imgs_fine", ",", "self", ".", "input_imgs", ",", "self", ".", "rois", ")", ...
https://github.com/shubhtuls/factored3d/blob/1bb77c7ae7dbaba7056e94cb99fdd6c9cc73c7cd/experiments/suncg/box3d.py#L243-L257
lyft/cartography
921a790d686c679ab5d8936b07e167fd424ee8d6
cartography/graph/statement.py
python
GraphStatement.as_dict
(self)
return { "query": self.query, "parameters": self.parameters, "iterative": self.iterative, "iterationsize": self.iterationsize, }
Convert statement to a dictionary.
Convert statement to a dictionary.
[ "Convert", "statement", "to", "a", "dictionary", "." ]
def as_dict(self): """ Convert statement to a dictionary. """ return { "query": self.query, "parameters": self.parameters, "iterative": self.iterative, "iterationsize": self.iterationsize, }
[ "def", "as_dict", "(", "self", ")", ":", "return", "{", "\"query\"", ":", "self", ".", "query", ",", "\"parameters\"", ":", "self", ".", "parameters", ",", "\"iterative\"", ":", "self", ".", "iterative", ",", "\"iterationsize\"", ":", "self", ".", "iterati...
https://github.com/lyft/cartography/blob/921a790d686c679ab5d8936b07e167fd424ee8d6/cartography/graph/statement.py#L74-L83
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/ttLib/tables/otConverters.py
python
ValueRecord.xmlWrite
(self, xmlWriter, font, value, name, attrs)
[]
def xmlWrite(self, xmlWriter, font, value, name, attrs): if value is None: pass # NULL table, ignore else: value.toXML(xmlWriter, font, self.name, attrs)
[ "def", "xmlWrite", "(", "self", ",", "xmlWriter", ",", "font", ",", "value", ",", "name", ",", "attrs", ")", ":", "if", "value", "is", "None", ":", "pass", "# NULL table, ignore", "else", ":", "value", ".", "toXML", "(", "xmlWriter", ",", "font", ",", ...
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/ttLib/tables/otConverters.py#L708-L712
ManiacalLabs/BiblioPixel
afb993fbbe56e75e7c98f252df402b0f3e83bb6e
bibliopixel/builder/runner.py
python
Runner.instance
(cls)
return cls._INSTANCE and cls._INSTANCE()
Return the unique instance of Runner, if any, or None
Return the unique instance of Runner, if any, or None
[ "Return", "the", "unique", "instance", "of", "Runner", "if", "any", "or", "None" ]
def instance(cls): """Return the unique instance of Runner, if any, or None""" return cls._INSTANCE and cls._INSTANCE()
[ "def", "instance", "(", "cls", ")", ":", "return", "cls", ".", "_INSTANCE", "and", "cls", ".", "_INSTANCE", "(", ")" ]
https://github.com/ManiacalLabs/BiblioPixel/blob/afb993fbbe56e75e7c98f252df402b0f3e83bb6e/bibliopixel/builder/runner.py#L46-L48
tanghaibao/jcvi
5e720870c0928996f8b77a38208106ff0447ccb6
jcvi/projects/tgbs.py
python
count
(args)
%prog count cdhit.consensus.fasta Scan the headers for the consensus clusters and count the number of reads.
%prog count cdhit.consensus.fasta
[ "%prog", "count", "cdhit", ".", "consensus", ".", "fasta" ]
def count(args): """ %prog count cdhit.consensus.fasta Scan the headers for the consensus clusters and count the number of reads. """ from jcvi.graphics.histogram import stem_leaf_plot from jcvi.utils.cbook import SummaryStats p = OptionParser(count.__doc__) p.add_option("--csv", help="Write depth per contig to file") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) (fastafile,) = args csv = open(opts.csv, "w") if opts.csv else None f = Fasta(fastafile, lazy=True) sizes = [] for desc, rec in f.iterdescriptions_ordered(): if desc.startswith("singleton"): sizes.append(1) continue # consensus_for_cluster_0 with 63 sequences if "with" in desc: name, w, size, seqs = desc.split() if csv: print("\t".join(str(x) for x in (name, size, len(rec))), file=csv) assert w == "with" sizes.append(int(size)) # MRD85:00603:02472;size=167; else: name, size, tail = desc.split(";") sizes.append(int(size.replace("size=", ""))) if csv: csv.close() logging.debug("File written to `%s`.", opts.csv) s = SummaryStats(sizes) print(s, file=sys.stderr) stem_leaf_plot(s.data, 0, 100, 20, title="Cluster size")
[ "def", "count", "(", "args", ")", ":", "from", "jcvi", ".", "graphics", ".", "histogram", "import", "stem_leaf_plot", "from", "jcvi", ".", "utils", ".", "cbook", "import", "SummaryStats", "p", "=", "OptionParser", "(", "count", ".", "__doc__", ")", "p", ...
https://github.com/tanghaibao/jcvi/blob/5e720870c0928996f8b77a38208106ff0447ccb6/jcvi/projects/tgbs.py#L279-L323
EventGhost/EventGhost
177be516849e74970d2e13cda82244be09f277ce
lib27/site-packages/tornado/concurrent.py
python
Future.result
(self, timeout=None)
return self._result
If the operation succeeded, return its result. If it failed, re-raise its exception. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is done, so the ``timeout`` is never used.
If the operation succeeded, return its result. If it failed, re-raise its exception.
[ "If", "the", "operation", "succeeded", "return", "its", "result", ".", "If", "it", "failed", "re", "-", "raise", "its", "exception", "." ]
def result(self, timeout=None): """If the operation succeeded, return its result. If it failed, re-raise its exception. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is done, so the ``timeout`` is never used. """ self._clear_tb_log() if self._result is not None: return self._result if self._exc_info is not None: raise_exc_info(self._exc_info) self._check_done() return self._result
[ "def", "result", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "_clear_tb_log", "(", ")", "if", "self", ".", "_result", "is", "not", "None", ":", "return", "self", ".", "_result", "if", "self", ".", "_exc_info", "is", "not", "None"...
https://github.com/EventGhost/EventGhost/blob/177be516849e74970d2e13cda82244be09f277ce/lib27/site-packages/tornado/concurrent.py#L220-L234
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
whois_lambda/requests/sessions.py
python
Session.close
(self)
Closes all adapters and as such the session
Closes all adapters and as such the session
[ "Closes", "all", "adapters", "and", "as", "such", "the", "session" ]
def close(self): """Closes all adapters and as such the session""" for v in self.adapters.values(): v.close()
[ "def", "close", "(", "self", ")", ":", "for", "v", "in", "self", ".", "adapters", ".", "values", "(", ")", ":", "v", ".", "close", "(", ")" ]
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/whois_lambda/requests/sessions.py#L646-L649
VisionLearningGroup/DA_Detection
730eaca8528d22ed3aa6b4dbc1965828a697cf9a
lib/model/utils/blob.py
python
prep_im_for_blob
(im, pixel_means, target_size, max_size)
return im, im_scale
Mean subtract and scale an image for use in a blob.
Mean subtract and scale an image for use in a blob.
[ "Mean", "subtract", "and", "scale", "an", "image", "for", "use", "in", "a", "blob", "." ]
def prep_im_for_blob(im, pixel_means, target_size, max_size): """Mean subtract and scale an image for use in a blob.""" im = im.astype(np.float32, copy=False) im -= pixel_means # im = im[:, :, ::-1] im_shape = im.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) im_scale = float(target_size) / float(im_size_min) # Prevent the biggest axis from being more than MAX_SIZE #if np.round(im_scale * im_size_max) > max_size: # im_scale = float(max_size) / float(im_size_max) # im = imresize(im, im_scale) im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) return im, im_scale
[ "def", "prep_im_for_blob", "(", "im", ",", "pixel_means", ",", "target_size", ",", "max_size", ")", ":", "im", "=", "im", ".", "astype", "(", "np", ".", "float32", ",", "copy", "=", "False", ")", "im", "-=", "pixel_means", "# im = im[:, :, ::-1]", "im_shap...
https://github.com/VisionLearningGroup/DA_Detection/blob/730eaca8528d22ed3aa6b4dbc1965828a697cf9a/lib/model/utils/blob.py#L35-L52
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/cloud/clouds/aliyun.py
python
destroy
(name, call=None)
return node
Destroy a node. CLI Example: .. code-block:: bash salt-cloud -a destroy myinstance salt-cloud -d myinstance
Destroy a node.
[ "Destroy", "a", "node", "." ]
def destroy(name, call=None): """ Destroy a node. CLI Example: .. code-block:: bash salt-cloud -a destroy myinstance salt-cloud -d myinstance """ if call == "function": raise SaltCloudSystemExit( "The destroy action must be called with -d, --destroy, -a or --action." ) __utils__["cloud.fire_event"]( "event", "destroying instance", "salt/cloud/{}/destroying".format(name), args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], ) instanceId = _get_node(name)["InstanceId"] # have to stop instance before del it stop_params = {"Action": "StopInstance", "InstanceId": instanceId} query(stop_params) params = {"Action": "DeleteInstance", "InstanceId": instanceId} node = query(params) __utils__["cloud.fire_event"]( "event", "destroyed instance", "salt/cloud/{}/destroyed".format(name), args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], ) return node
[ "def", "destroy", "(", "name", ",", "call", "=", "None", ")", ":", "if", "call", "==", "\"function\"", ":", "raise", "SaltCloudSystemExit", "(", "\"The destroy action must be called with -d, --destroy, -a or --action.\"", ")", "__utils__", "[", "\"cloud.fire_event\"", "...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/cloud/clouds/aliyun.py#L966-L1010
brython-dev/brython
9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3
www/src/Lib/cmath.py
python
log10
(x)
return complex(_real, _imag)
Return the base-10 logarithm of x. This has the same branch cut as log().
Return the base-10 logarithm of x.
[ "Return", "the", "base", "-", "10", "logarithm", "of", "x", "." ]
def log10(x): """ Return the base-10 logarithm of x. This has the same branch cut as log(). """ ret = log(x) _real = ret.real / _M_LN10 _imag = ret.imag / _M_LN10 return complex(_real, _imag)
[ "def", "log10", "(", "x", ")", ":", "ret", "=", "log", "(", "x", ")", "_real", "=", "ret", ".", "real", "/", "_M_LN10", "_imag", "=", "ret", ".", "imag", "/", "_M_LN10", "return", "complex", "(", "_real", ",", "_imag", ")" ]
https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/cmath.py#L554-L563
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/tabs/utils.py
python
sidebar_to_dropdown
(sidebar_items, domain=None, current_url=None)
Formats sidebar_items as dropdown items Sample input: [(u'Application Users', [{'description': u'Create and manage users for CommCare and CloudCare.', 'show_in_dropdown': True, 'subpages': [{'title': <function commcare_username at 0x109869488>, 'urlname': 'edit_commcare_user'}, {'title': u'Bulk Upload', 'urlname': 'upload_commcare_users'}, {'title': 'Confirm Billing Information',], 'title': u'Mobile Workers', 'url': '/a/sravan-test/settings/users/commcare/'}, (u'Project Users', [{'description': u'Grant other CommCare HQ users access to your project and manage user roles.', 'show_in_dropdown': True, 'subpages': [{'title': u'Invite Web User', 'urlname': 'invite_web_user'}, {'title': <function web_username at 0x10982a9b0>, 'urlname': 'user_account'}, {'title': u'My Information', 'urlname': 'domain_my_account'}], 'title': <django.utils.functional.__proxy__ object at 0x106a5c790>, 'url': '/a/sravan-test/settings/users/web/'}])] Sample output: [{'data_id': None, 'html': None, 'is_divider': False, 'is_header': True, 'title': u'Application Users', 'url': None}, {'data_id': None, 'html': None, 'is_divider': False, 'is_header': False, 'title': u'Mobile Workers', 'url': '/a/sravan-test/settings/users/commcare/'}, {'data_id': None, 'html': None, 'is_divider': False, 'is_header': False, 'title': u'Groups', 'url': '/a/sravan-test/settings/users/groups/'}, {'data_id': None, 'html': None, 'is_divider': False, 'is_header': True, 'title': u'Project Users', 'url': None},]
Formats sidebar_items as dropdown items Sample input: [(u'Application Users', [{'description': u'Create and manage users for CommCare and CloudCare.', 'show_in_dropdown': True, 'subpages': [{'title': <function commcare_username at 0x109869488>, 'urlname': 'edit_commcare_user'}, {'title': u'Bulk Upload', 'urlname': 'upload_commcare_users'}, {'title': 'Confirm Billing Information',], 'title': u'Mobile Workers', 'url': '/a/sravan-test/settings/users/commcare/'}, (u'Project Users', [{'description': u'Grant other CommCare HQ users access to your project and manage user roles.', 'show_in_dropdown': True, 'subpages': [{'title': u'Invite Web User', 'urlname': 'invite_web_user'}, {'title': <function web_username at 0x10982a9b0>, 'urlname': 'user_account'}, {'title': u'My Information', 'urlname': 'domain_my_account'}], 'title': <django.utils.functional.__proxy__ object at 0x106a5c790>, 'url': '/a/sravan-test/settings/users/web/'}])] Sample output: [{'data_id': None, 'html': None, 'is_divider': False, 'is_header': True, 'title': u'Application Users', 'url': None}, {'data_id': None, 'html': None, 'is_divider': False, 'is_header': False, 'title': u'Mobile Workers', 'url': '/a/sravan-test/settings/users/commcare/'}, {'data_id': None, 'html': None, 'is_divider': False, 'is_header': False, 'title': u'Groups', 'url': '/a/sravan-test/settings/users/groups/'}, {'data_id': None, 'html': None, 'is_divider': False, 'is_header': True, 'title': u'Project Users', 'url': None},]
[ "Formats", "sidebar_items", "as", "dropdown", "items", "Sample", "input", ":", "[", "(", "u", "Application", "Users", "[", "{", "description", ":", "u", "Create", "and", "manage", "users", "for", "CommCare", "and", "CloudCare", ".", "show_in_dropdown", ":", ...
def sidebar_to_dropdown(sidebar_items, domain=None, current_url=None): """ Formats sidebar_items as dropdown items Sample input: [(u'Application Users', [{'description': u'Create and manage users for CommCare and CloudCare.', 'show_in_dropdown': True, 'subpages': [{'title': <function commcare_username at 0x109869488>, 'urlname': 'edit_commcare_user'}, {'title': u'Bulk Upload', 'urlname': 'upload_commcare_users'}, {'title': 'Confirm Billing Information',], 'title': u'Mobile Workers', 'url': '/a/sravan-test/settings/users/commcare/'}, (u'Project Users', [{'description': u'Grant other CommCare HQ users access to your project and manage user roles.', 'show_in_dropdown': True, 'subpages': [{'title': u'Invite Web User', 'urlname': 'invite_web_user'}, {'title': <function web_username at 0x10982a9b0>, 'urlname': 'user_account'}, {'title': u'My Information', 'urlname': 'domain_my_account'}], 'title': <django.utils.functional.__proxy__ object at 0x106a5c790>, 'url': '/a/sravan-test/settings/users/web/'}])] Sample output: [{'data_id': None, 'html': None, 'is_divider': False, 'is_header': True, 'title': u'Application Users', 'url': None}, {'data_id': None, 'html': None, 'is_divider': False, 'is_header': False, 'title': u'Mobile Workers', 'url': '/a/sravan-test/settings/users/commcare/'}, {'data_id': None, 'html': None, 'is_divider': False, 'is_header': False, 'title': u'Groups', 'url': '/a/sravan-test/settings/users/groups/'}, {'data_id': None, 'html': None, 'is_divider': False, 'is_header': True, 'title': u'Project Users', 'url': None},] """ dropdown_items = [] more_items_in_sidebar = False for side_header, side_list in sidebar_items: dropdown_header = dropdown_dict(side_header, is_header=True) current_dropdown_items = [] for side_item in side_list: show_in_dropdown = side_item.get("show_in_dropdown", False) if show_in_dropdown: second_level_dropdowns = subpages_as_dropdowns( side_item.get('subpages', []), level=2, domain=domain) dropdown_item = dropdown_dict( side_item['title'], url=side_item['url'], second_level_dropdowns=second_level_dropdowns, ) current_dropdown_items.append(dropdown_item) first_level_dropdowns = subpages_as_dropdowns( side_item.get('subpages', []), level=1, domain=domain ) current_dropdown_items = current_dropdown_items + first_level_dropdowns else: more_items_in_sidebar = True if current_dropdown_items: dropdown_items.extend([dropdown_header] + current_dropdown_items) if dropdown_items and more_items_in_sidebar and current_url: return dropdown_items + divider_and_more_menu(current_url) else: return dropdown_items
[ "def", "sidebar_to_dropdown", "(", "sidebar_items", ",", "domain", "=", "None", ",", "current_url", "=", "None", ")", ":", "dropdown_items", "=", "[", "]", "more_items_in_sidebar", "=", "False", "for", "side_header", ",", "side_list", "in", "sidebar_items", ":",...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/tabs/utils.py#L20-L100
tensorflow/model-analysis
e38c23ce76eff039548ce69e3160ed4d7984f2fc
tensorflow_model_analysis/metrics/example_count.py
python
example_count
( name: str = EXAMPLE_COUNT_NAME, model_names: Optional[List[str]] = None, output_names: Optional[List[str]] = None, sub_keys: Optional[List[metric_types.SubKey]] = None, example_weighted: bool = False)
return computations
Returns metric computations for example count.
Returns metric computations for example count.
[ "Returns", "metric", "computations", "for", "example", "count", "." ]
def example_count( name: str = EXAMPLE_COUNT_NAME, model_names: Optional[List[str]] = None, output_names: Optional[List[str]] = None, sub_keys: Optional[List[metric_types.SubKey]] = None, example_weighted: bool = False) -> metric_types.MetricComputations: """Returns metric computations for example count.""" computations = [] for model_name in model_names or ['']: for output_name in output_names or ['']: keys = [] for sub_key in sub_keys or [None]: key = metric_types.MetricKey( name=name, model_name=model_name, output_name=output_name, sub_key=sub_key, example_weighted=example_weighted) keys.append(key) # Note: This cannot be implemented based on the weight stored in # calibration because weighted example count is used with multi-class, etc # models that do not use calibration metrics. computations.append( metric_types.MetricComputation( keys=keys, preprocessor=None, combiner=_ExampleCountCombiner(model_name, output_name, keys, example_weighted))) return computations
[ "def", "example_count", "(", "name", ":", "str", "=", "EXAMPLE_COUNT_NAME", ",", "model_names", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "output_names", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", ...
https://github.com/tensorflow/model-analysis/blob/e38c23ce76eff039548ce69e3160ed4d7984f2fc/tensorflow_model_analysis/metrics/example_count.py#L59-L88
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/modulefinder.py
python
ModuleFinder.any_missing_maybe
(self)
return missing, maybe
Return two lists, one with modules that are certainly missing and one with modules that *may* be missing. The latter names could either be submodules *or* just global names in the package. The reason it can't always be determined is that it's impossible to tell which names are imported when "from module import *" is done with an extension module, short of actually importing it.
Return two lists, one with modules that are certainly missing and one with modules that *may* be missing. The latter names could either be submodules *or* just global names in the package.
[ "Return", "two", "lists", "one", "with", "modules", "that", "are", "certainly", "missing", "and", "one", "with", "modules", "that", "*", "may", "*", "be", "missing", ".", "The", "latter", "names", "could", "either", "be", "submodules", "*", "or", "*", "j...
def any_missing_maybe(self): """Return two lists, one with modules that are certainly missing and one with modules that *may* be missing. The latter names could either be submodules *or* just global names in the package. The reason it can't always be determined is that it's impossible to tell which names are imported when "from module import *" is done with an extension module, short of actually importing it. """ missing = [] maybe = [] for name in self.badmodules: if name in self.excludes: continue i = name.rfind(".") if i < 0: missing.append(name) continue subname = name[i+1:] pkgname = name[:i] pkg = self.modules.get(pkgname) if pkg is not None: if pkgname in self.badmodules[name]: # The package tried to import this module itself and # failed. It's definitely missing. missing.append(name) elif subname in pkg.globalnames: # It's a global in the package: definitely not missing. pass elif pkg.starimports: # It could be missing, but the package did an "import *" # from a non-Python module, so we simply can't be sure. maybe.append(name) else: # It's not a global in the package, the package didn't # do funny star imports, it's very likely to be missing. # The symbol could be inserted into the package from the # outside, but since that's not good style we simply list # it missing. missing.append(name) else: missing.append(name) missing.sort() maybe.sort() return missing, maybe
[ "def", "any_missing_maybe", "(", "self", ")", ":", "missing", "=", "[", "]", "maybe", "=", "[", "]", "for", "name", "in", "self", ".", "badmodules", ":", "if", "name", "in", "self", ".", "excludes", ":", "continue", "i", "=", "name", ".", "rfind", ...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/modulefinder.py#L504-L548
microsoft/Cognitive-Face-Python
13017a13000ee1200b5b2487b38823ff787da447
cognitive_face/large_face_list_face.py
python
add
(image, large_face_list_id, user_data=None, target_face=None)
return util.request( 'POST', url, headers=headers, params=params, json=json, data=data)
Add a face to a large face list. The input face is specified as an image with a `target_face` rectangle. It returns a `persisted_face_id` representing the added face, and `persisted_face_id` will not expire. Args: image: A URL or a file path or a file-like object represents an image. large_face_list_id: Valid character is letter in lower case or digit or '-' or '_', maximum length is 64. user_data: Optional parameter. User-specified data about the large face list for any purpose. The maximum length is 1KB. target_face: Optional parameter. A face rectangle to specify the target face to be added into the large face list, in the format of "left,top,width,height". E.g. "10,10,100,100". If there are more than one faces in the image, `target_face` is required to specify which face to add. No `target_face` means there is only one face detected in the entire image. Returns: A new `persisted_face_id`.
Add a face to a large face list.
[ "Add", "a", "face", "to", "a", "large", "face", "list", "." ]
def add(image, large_face_list_id, user_data=None, target_face=None): """Add a face to a large face list. The input face is specified as an image with a `target_face` rectangle. It returns a `persisted_face_id` representing the added face, and `persisted_face_id` will not expire. Args: image: A URL or a file path or a file-like object represents an image. large_face_list_id: Valid character is letter in lower case or digit or '-' or '_', maximum length is 64. user_data: Optional parameter. User-specified data about the large face list for any purpose. The maximum length is 1KB. target_face: Optional parameter. A face rectangle to specify the target face to be added into the large face list, in the format of "left,top,width,height". E.g. "10,10,100,100". If there are more than one faces in the image, `target_face` is required to specify which face to add. No `target_face` means there is only one face detected in the entire image. Returns: A new `persisted_face_id`. """ url = 'largefacelists/{}/persistedFaces'.format(large_face_list_id) headers, data, json = util.parse_image(image) params = { 'userData': user_data, 'targetFace': target_face, } return util.request( 'POST', url, headers=headers, params=params, json=json, data=data)
[ "def", "add", "(", "image", ",", "large_face_list_id", ",", "user_data", "=", "None", ",", "target_face", "=", "None", ")", ":", "url", "=", "'largefacelists/{}/persistedFaces'", ".", "format", "(", "large_face_list_id", ")", "headers", ",", "data", ",", "json...
https://github.com/microsoft/Cognitive-Face-Python/blob/13017a13000ee1200b5b2487b38823ff787da447/cognitive_face/large_face_list_face.py#L10-L41
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/root_system/cartan_matrix.py
python
CartanMatrix.cartan_type
(self)
return self._cartan_type
Return the Cartan type of ``self`` or ``self`` if unknown. EXAMPLES:: sage: C = CartanMatrix(['A',4,1]) sage: C.cartan_type() ['A', 4, 1] If the Cartan type is unknown:: sage: C = CartanMatrix([[2,-1,-2], [-1,2,-1], [-2,-1,2]]) sage: C.cartan_type() [ 2 -1 -2] [-1 2 -1] [-2 -1 2]
Return the Cartan type of ``self`` or ``self`` if unknown.
[ "Return", "the", "Cartan", "type", "of", "self", "or", "self", "if", "unknown", "." ]
def cartan_type(self): """ Return the Cartan type of ``self`` or ``self`` if unknown. EXAMPLES:: sage: C = CartanMatrix(['A',4,1]) sage: C.cartan_type() ['A', 4, 1] If the Cartan type is unknown:: sage: C = CartanMatrix([[2,-1,-2], [-1,2,-1], [-2,-1,2]]) sage: C.cartan_type() [ 2 -1 -2] [-1 2 -1] [-2 -1 2] """ if self._cartan_type is None: return self if is_borcherds_cartan_matrix(self) and not is_generalized_cartan_matrix(self): return self return self._cartan_type
[ "def", "cartan_type", "(", "self", ")", ":", "if", "self", ".", "_cartan_type", "is", "None", ":", "return", "self", "if", "is_borcherds_cartan_matrix", "(", "self", ")", "and", "not", "is_generalized_cartan_matrix", "(", "self", ")", ":", "return", "self", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/root_system/cartan_matrix.py#L534-L556
recipy/recipy
d8f8fe8ace3659f1d700bb454e68a8db453e84f4
recipy/log.py
python
add_file_diff_to_db
(filename, tempfilename, db)
[]
def add_file_diff_to_db(filename, tempfilename, db): diffs = db.table('filediffs') diffs.insert({'run_id': RUN_ID, 'filename': filename, 'tempfilename': tempfilename})
[ "def", "add_file_diff_to_db", "(", "filename", ",", "tempfilename", ",", "db", ")", ":", "diffs", "=", "db", ".", "table", "(", "'filediffs'", ")", "diffs", ".", "insert", "(", "{", "'run_id'", ":", "RUN_ID", ",", "'filename'", ":", "filename", ",", "'te...
https://github.com/recipy/recipy/blob/d8f8fe8ace3659f1d700bb454e68a8db453e84f4/recipy/log.py#L254-L258
liaohuqiu/btcbot-open
bb46896b5e24449bc41f65a876d8d7c886a340c1
src/btfxwss/client.py
python
BtfxWssClient.funding_loan_cancel
(self)
return self.queue_processor.account['Funding Loan Cancel']
Return queue containing canceled funding loan associated with the user account. :return: Queue()
Return queue containing canceled funding loan associated with the user account.
[ "Return", "queue", "containing", "canceled", "funding", "loan", "associated", "with", "the", "user", "account", "." ]
def funding_loan_cancel(self): """Return queue containing canceled funding loan associated with the user account. :return: Queue() """ return self.queue_processor.account['Funding Loan Cancel']
[ "def", "funding_loan_cancel", "(", "self", ")", ":", "return", "self", ".", "queue_processor", ".", "account", "[", "'Funding Loan Cancel'", "]" ]
https://github.com/liaohuqiu/btcbot-open/blob/bb46896b5e24449bc41f65a876d8d7c886a340c1/src/btfxwss/client.py#L185-L190
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/recorder/statistics.py
python
delete_duplicates
(instance: Recorder, session: scoped_session)
Identify and delete duplicated statistics. A backup will be made of duplicated statistics before it is deleted.
Identify and delete duplicated statistics.
[ "Identify", "and", "delete", "duplicated", "statistics", "." ]
def delete_duplicates(instance: Recorder, session: scoped_session) -> None: """Identify and delete duplicated statistics. A backup will be made of duplicated statistics before it is deleted. """ deleted_statistics_rows, non_identical_duplicates = _delete_duplicates_from_table( session, Statistics ) if deleted_statistics_rows: _LOGGER.info("Deleted %s duplicated statistics rows", deleted_statistics_rows) if non_identical_duplicates: isotime = dt_util.utcnow().isoformat() backup_file_name = f"deleted_statistics.{isotime}.json" backup_path = instance.hass.config.path(STORAGE_DIR, backup_file_name) os.makedirs(os.path.dirname(backup_path), exist_ok=True) with open(backup_path, "w", encoding="utf8") as backup_file: json.dump( non_identical_duplicates, backup_file, indent=4, sort_keys=True, cls=JSONEncoder, ) _LOGGER.warning( "Deleted %s non identical duplicated %s rows, a backup of the deleted rows " "has been saved to %s", len(non_identical_duplicates), Statistics.__tablename__, backup_path, ) if deleted_statistics_rows >= MAX_DUPLICATES: _LOGGER.warning( "Found more than %s duplicated statistic rows, please report at " 'https://github.com/home-assistant/core/issues?q=is%%3Aissue+label%%3A"integration%%3A+recorder"+', MAX_DUPLICATES - 1, ) deleted_short_term_statistics_rows, _ = _delete_duplicates_from_table( session, StatisticsShortTerm ) if deleted_short_term_statistics_rows: _LOGGER.warning( "Deleted duplicated short term statistic rows, please report at " 'https://github.com/home-assistant/core/issues?q=is%%3Aissue+label%%3A"integration%%3A+recorder"+' )
[ "def", "delete_duplicates", "(", "instance", ":", "Recorder", ",", "session", ":", "scoped_session", ")", "->", "None", ":", "deleted_statistics_rows", ",", "non_identical_duplicates", "=", "_delete_duplicates_from_table", "(", "session", ",", "Statistics", ")", "if",...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/recorder/statistics.py#L359-L406
Spacelog/Spacelog
92df308be5923765607a89b022acb57c041c86b3
ext/xappy-0.5-sja-1/xappy/searchconnection.py
python
SearchConnection._get_prefix_from_term
(self, term)
return term
Get the prefix of a term. Prefixes are any initial capital letters, with the exception that R always ends a prefix, even if followed by capital letters.
Get the prefix of a term. Prefixes are any initial capital letters, with the exception that R always ends a prefix, even if followed by capital letters.
[ "Get", "the", "prefix", "of", "a", "term", ".", "Prefixes", "are", "any", "initial", "capital", "letters", "with", "the", "exception", "that", "R", "always", "ends", "a", "prefix", "even", "if", "followed", "by", "capital", "letters", "." ]
def _get_prefix_from_term(self, term): """Get the prefix of a term. Prefixes are any initial capital letters, with the exception that R always ends a prefix, even if followed by capital letters. """ for p in xrange(len(term)): if term[p].islower(): return term[:p] elif term[p] == 'R': return term[:p+1] return term
[ "def", "_get_prefix_from_term", "(", "self", ",", "term", ")", ":", "for", "p", "in", "xrange", "(", "len", "(", "term", ")", ")", ":", "if", "term", "[", "p", "]", ".", "islower", "(", ")", ":", "return", "term", "[", ":", "p", "]", "elif", "t...
https://github.com/Spacelog/Spacelog/blob/92df308be5923765607a89b022acb57c041c86b3/ext/xappy-0.5-sja-1/xappy/searchconnection.py#L1546-L1558
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/networkx/classes/multidigraph.py
python
MultiDiGraph.in_edges
(self)
return InMultiEdgeView(self)
An InMultiEdgeView of the Graph as G.in_edges or G.in_edges(). in_edges(self, nbunch=None, data=False, keys=False, default=None) Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes. data : string or bool, optional (default=False) The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v). keys : bool, optional (default=False) If True, return edge keys with each edge. default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False. Returns ------- in_edges : InMultiEdgeView A view of edge attributes, usually it iterates over (u, v) or (u, v, k) or (u, v, k, d) tuples of edges, but can also be used for attribute lookup as `edges[u, v, k]['foo']`. See Also -------- edges
An InMultiEdgeView of the Graph as G.in_edges or G.in_edges().
[ "An", "InMultiEdgeView", "of", "the", "Graph", "as", "G", ".", "in_edges", "or", "G", ".", "in_edges", "()", "." ]
def in_edges(self): """An InMultiEdgeView of the Graph as G.in_edges or G.in_edges(). in_edges(self, nbunch=None, data=False, keys=False, default=None) Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes. data : string or bool, optional (default=False) The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v). keys : bool, optional (default=False) If True, return edge keys with each edge. default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False. Returns ------- in_edges : InMultiEdgeView A view of edge attributes, usually it iterates over (u, v) or (u, v, k) or (u, v, k, d) tuples of edges, but can also be used for attribute lookup as `edges[u, v, k]['foo']`. See Also -------- edges """ return InMultiEdgeView(self)
[ "def", "in_edges", "(", "self", ")", ":", "return", "InMultiEdgeView", "(", "self", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/networkx/classes/multidigraph.py#L600-L630
windelbouwman/ppci
915c069e0667042c085ec42c78e9e3c9a5295324
ppci/wasm/ppci2wasm.py
python
IrToWasmCompiler.do_block
(self, ir_block)
Generate code for the given block
Generate code for the given block
[ "Generate", "code", "for", "the", "given", "block" ]
def do_block(self, ir_block): """ Generate code for the given block """ self.logger.debug("Generating %s", ir_block) block_trees = self.ds.split_group_into_trees( self.sdag, self.fi, ir_block ) for tree in block_trees: # print(tree) self.do_tree(tree)
[ "def", "do_block", "(", "self", ",", "ir_block", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Generating %s\"", ",", "ir_block", ")", "block_trees", "=", "self", ".", "ds", ".", "split_group_into_trees", "(", "self", ".", "sdag", ",", "self", "...
https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/wasm/ppci2wasm.py#L368-L376
edublancas/sklearn-evaluation
bdf721b20c42d8cfde0f8716ab1ed6ae1029a2ea
src/sklearn_evaluation/util.py
python
_product
(k, v)
return list(product(k, v))
Perform the product between two objects even if they don't support iteration
Perform the product between two objects even if they don't support iteration
[ "Perform", "the", "product", "between", "two", "objects", "even", "if", "they", "don", "t", "support", "iteration" ]
def _product(k, v): """ Perform the product between two objects even if they don't support iteration """ if not _can_iterate(k): k = [k] if not _can_iterate(v): v = [v] return list(product(k, v))
[ "def", "_product", "(", "k", ",", "v", ")", ":", "if", "not", "_can_iterate", "(", "k", ")", ":", "k", "=", "[", "k", "]", "if", "not", "_can_iterate", "(", "v", ")", ":", "v", "=", "[", "v", "]", "return", "list", "(", "product", "(", "k", ...
https://github.com/edublancas/sklearn-evaluation/blob/bdf721b20c42d8cfde0f8716ab1ed6ae1029a2ea/src/sklearn_evaluation/util.py#L90-L99
SHI-Labs/Decoupled-Classification-Refinement
16202b48eb9cbf79a9b130a98e8c209d4f24693e
faster_rcnn/core/module.py
python
MutableModule.data_shapes
(self)
return self._curr_module.data_shapes
[]
def data_shapes(self): assert self.binded return self._curr_module.data_shapes
[ "def", "data_shapes", "(", "self", ")", ":", "assert", "self", ".", "binded", "return", "self", ".", "_curr_module", ".", "data_shapes" ]
https://github.com/SHI-Labs/Decoupled-Classification-Refinement/blob/16202b48eb9cbf79a9b130a98e8c209d4f24693e/faster_rcnn/core/module.py#L773-L775
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/whoosh/codec/plaintext.py
python
PlainTermsReader._find_field
(self, fieldname)
[]
def _find_field(self, fieldname): self._find_root("TERMS") if self._find_line(1, "TERMFIELD", fn=fieldname) is None: raise TermNotFound("No field %r" % fieldname)
[ "def", "_find_field", "(", "self", ",", "fieldname", ")", ":", "self", ".", "_find_root", "(", "\"TERMS\"", ")", "if", "self", ".", "_find_line", "(", "1", ",", "\"TERMFIELD\"", ",", "fn", "=", "fieldname", ")", "is", "None", ":", "raise", "TermNotFound"...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/codec/plaintext.py#L353-L356
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_daemon_set_list.py
python
V1DaemonSetList.__ne__
(self, other)
return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
Returns true if both objects are not equal
[ "Returns", "true", "if", "both", "objects", "are", "not", "equal" ]
def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1DaemonSetList): return True return self.to_dict() != other.to_dict()
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "V1DaemonSetList", ")", ":", "return", "True", "return", "self", ".", "to_dict", "(", ")", "!=", "other", ".", "to_dict", "(", ")" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_daemon_set_list.py#L200-L205
gkrizek/bash-lambda-layer
703b0ade8174022d44779d823172ab7ac33a5505
bin/docutils/utils/math/math2html.py
python
HybridSize.getsize
(self, function)
return eval(sizestring)
Read the size for a function and parse it.
Read the size for a function and parse it.
[ "Read", "the", "size", "for", "a", "function", "and", "parse", "it", "." ]
def getsize(self, function): "Read the size for a function and parse it." sizestring = self.configsizes[function.command] for name in function.params: if name in sizestring: size = function.params[name].value.computesize() sizestring = sizestring.replace(name, str(size)) if '$' in sizestring: Trace.error('Unconverted variable in hybrid size: ' + sizestring) return 1 return eval(sizestring)
[ "def", "getsize", "(", "self", ",", "function", ")", ":", "sizestring", "=", "self", ".", "configsizes", "[", "function", ".", "command", "]", "for", "name", "in", "function", ".", "params", ":", "if", "name", "in", "sizestring", ":", "size", "=", "fun...
https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/docutils/utils/math/math2html.py#L5052-L5062
online-ml/river
3732f700da72642afe54095d4b252b05c5018c7d
river/base/regressor.py
python
Regressor.predict_one
(self, x: dict)
Predicts the target value of a set of features `x`. Parameters ---------- x A dictionary of features. Returns ------- The prediction.
Predicts the target value of a set of features `x`.
[ "Predicts", "the", "target", "value", "of", "a", "set", "of", "features", "x", "." ]
def predict_one(self, x: dict) -> base.typing.RegTarget: """Predicts the target value of a set of features `x`. Parameters ---------- x A dictionary of features. Returns ------- The prediction. """
[ "def", "predict_one", "(", "self", ",", "x", ":", "dict", ")", "->", "base", ".", "typing", ".", "RegTarget", ":" ]
https://github.com/online-ml/river/blob/3732f700da72642afe54095d4b252b05c5018c7d/river/base/regressor.py#L33-L45
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/cli/pmg_config.py
python
configure_pmg
(args)
Handle configure command. :param args:
Handle configure command.
[ "Handle", "configure", "command", "." ]
def configure_pmg(args): """ Handle configure command. :param args: """ if args.potcar_dirs: setup_potcars(args) elif args.install: install_software(args) elif args.var_spec: add_config_var(args)
[ "def", "configure_pmg", "(", "args", ")", ":", "if", "args", ".", "potcar_dirs", ":", "setup_potcars", "(", "args", ")", "elif", "args", ".", "install", ":", "install_software", "(", "args", ")", "elif", "args", ".", "var_spec", ":", "add_config_var", "(",...
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/cli/pmg_config.py#L207-L218
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
golismero/managers/importmanager.py
python
ImportManager.orchestrator
(self)
return self.__orchestrator
:returns: Orchestrator instance. :rtype: Orchestrator
:returns: Orchestrator instance. :rtype: Orchestrator
[ ":", "returns", ":", "Orchestrator", "instance", ".", ":", "rtype", ":", "Orchestrator" ]
def orchestrator(self): """ :returns: Orchestrator instance. :rtype: Orchestrator """ return self.__orchestrator
[ "def", "orchestrator", "(", "self", ")", ":", "return", "self", ".", "__orchestrator" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/golismero/managers/importmanager.py#L100-L105
jina-ai/jina
c77a492fcd5adba0fc3de5347bea83dd4e7d8087
jina/parsers/hubble/new.py
python
mixin_hub_new_parser
(parser)
Add the arguments for hub new to the parser :param parser: the parser configure
Add the arguments for hub new to the parser :param parser: the parser configure
[ "Add", "the", "arguments", "for", "hub", "new", "to", "the", "parser", ":", "param", "parser", ":", "the", "parser", "configure" ]
def mixin_hub_new_parser(parser): """Add the arguments for hub new to the parser :param parser: the parser configure """ gp = add_arg_group(parser, title='Create Executor') gp.add_argument( '--name', help='the name of the Executor', type=str, ) gp.add_argument( '--path', help='the path to store the Executor', type=str, ) gp.add_argument( '--advance-configuration', help='If set, always set up advance configuration like description, keywords and url', action='store_true', ) gp.add_argument( '--description', help='the short description of the Executor', type=str, ) gp.add_argument( '--keywords', help='some keywords to help people search your Executor (separated by comma)', type=str, ) gp.add_argument( '--url', help='the URL of your GitHub repo', type=str, ) gp.add_argument( '--add-dockerfile', help='If set, add a Dockerfile to the created Executor bundle', action='store_true', )
[ "def", "mixin_hub_new_parser", "(", "parser", ")", ":", "gp", "=", "add_arg_group", "(", "parser", ",", "title", "=", "'Create Executor'", ")", "gp", ".", "add_argument", "(", "'--name'", ",", "help", "=", "'the name of the Executor'", ",", "type", "=", "str",...
https://github.com/jina-ai/jina/blob/c77a492fcd5adba0fc3de5347bea83dd4e7d8087/jina/parsers/hubble/new.py#L6-L51
CastagnaIT/plugin.video.netflix
5cf5fa436eb9956576c0f62aa31a4c7d6c5b8a4a
resources/lib/common/kodi_ops.py
python
json_rpc
(method, params=None)
return response['result']
Executes a JSON-RPC in Kodi :param method: The JSON-RPC method to call :type method: string :param params: The parameters of the method call (optional) :type params: dict :returns: dict -- Method call result
Executes a JSON-RPC in Kodi
[ "Executes", "a", "JSON", "-", "RPC", "in", "Kodi" ]
def json_rpc(method, params=None): """ Executes a JSON-RPC in Kodi :param method: The JSON-RPC method to call :type method: string :param params: The parameters of the method call (optional) :type params: dict :returns: dict -- Method call result """ request_data = {'jsonrpc': '2.0', 'method': method, 'id': 1, 'params': params or {}} request = json.dumps(request_data) LOG.debug('Executing JSON-RPC: {}', request) raw_response = xbmc.executeJSONRPC(request) # debug('JSON-RPC response: {}'.format(raw_response)) response = json.loads(raw_response) if 'error' in response: raise IOError(f'JSONRPC-Error {response["error"]["code"]}: {response["error"]["message"]}') return response['result']
[ "def", "json_rpc", "(", "method", ",", "params", "=", "None", ")", ":", "request_data", "=", "{", "'jsonrpc'", ":", "'2.0'", ",", "'method'", ":", "method", ",", "'id'", ":", "1", ",", "'params'", ":", "params", "or", "{", "}", "}", "request", "=", ...
https://github.com/CastagnaIT/plugin.video.netflix/blob/5cf5fa436eb9956576c0f62aa31a4c7d6c5b8a4a/resources/lib/common/kodi_ops.py#L37-L56
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/io/fits/scripts/fitsheader.py
python
HeaderFormatter._parse_internal
(self, hdukeys, keywords, compressed)
return ''.join(result)
The meat of the formatting; in a separate method to allow overriding.
The meat of the formatting; in a separate method to allow overriding.
[ "The", "meat", "of", "the", "formatting", ";", "in", "a", "separate", "method", "to", "allow", "overriding", "." ]
def _parse_internal(self, hdukeys, keywords, compressed): """The meat of the formatting; in a separate method to allow overriding. """ result = [] for idx, hdu in enumerate(hdukeys): try: cards = self._get_cards(hdu, keywords, compressed) except ExtensionNotFoundException: continue if idx > 0: # Separate HDUs by a blank line result.append('\n') result.append(f'# HDU {hdu} in {self.filename}:\n') for c in cards: result.append(f'{c}\n') return ''.join(result)
[ "def", "_parse_internal", "(", "self", ",", "hdukeys", ",", "keywords", ",", "compressed", ")", ":", "result", "=", "[", "]", "for", "idx", ",", "hdu", "in", "enumerate", "(", "hdukeys", ")", ":", "try", ":", "cards", "=", "self", ".", "_get_cards", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/io/fits/scripts/fitsheader.py#L148-L163
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_version.py
python
Yedit.parse_value
(inc_value, vtype='')
return inc_value
determine value type passed
determine value type passed
[ "determine", "value", "type", "passed" ]
def parse_value(inc_value, vtype=''): '''determine value type passed''' true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON', ] false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF'] # It came in as a string but you didn't specify value_type as string # we will convert to bool if it matches any of the above cases if isinstance(inc_value, str) and 'bool' in vtype: if inc_value not in true_bools and inc_value not in false_bools: raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype)) elif isinstance(inc_value, bool) and 'str' in vtype: inc_value = str(inc_value) # There is a special case where '' will turn into None after yaml loading it so skip if isinstance(inc_value, str) and inc_value == '': pass # If vtype is not str then go ahead and attempt to yaml load it. elif isinstance(inc_value, str) and 'str' not in vtype: try: inc_value = yaml.safe_load(inc_value) except Exception: raise YeditException('Could not determine type of incoming value. ' + 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype)) return inc_value
[ "def", "parse_value", "(", "inc_value", ",", "vtype", "=", "''", ")", ":", "true_bools", "=", "[", "'y'", ",", "'Y'", ",", "'yes'", ",", "'Yes'", ",", "'YES'", ",", "'true'", ",", "'True'", ",", "'TRUE'", ",", "'on'", ",", "'On'", ",", "'ON'", ",",...
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_version.py#L643-L669
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/compiler/misc.py
python
Stack.top
(self)
return self.stack[-1]
[]
def top(self): return self.stack[-1]
[ "def", "top", "(", "self", ")", ":", "return", "self", ".", "stack", "[", "-", "1", "]" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/compiler/misc.py#L39-L40
eborboihuc/SoundNet-tensorflow
b603cd4584a9c95a613580eef85750981214c3ae
main.py
python
Model.load_from_npy
(self)
return True
[]
def load_from_npy(self): if self.param_G is None: return False data_dict = self.param_G for key in data_dict: with tf.variable_scope(self.config['name_scope'] + '/'+ key, reuse=True): for subkey in data_dict[key]: try: var = tf.get_variable(subkey) self.sess.run(var.assign(data_dict[key][subkey])) print('Assign pretrain model {} to {}'.format(subkey, key)) except: print('Ignore {}'.format(key)) self.param_G.clear() return True
[ "def", "load_from_npy", "(", "self", ")", ":", "if", "self", ".", "param_G", "is", "None", ":", "return", "False", "data_dict", "=", "self", ".", "param_G", "for", "key", "in", "data_dict", ":", "with", "tf", ".", "variable_scope", "(", "self", ".", "c...
https://github.com/eborboihuc/SoundNet-tensorflow/blob/b603cd4584a9c95a613580eef85750981214c3ae/main.py#L230-L244
beeware/toga
090370a943bdeefcdbe035b1621fbc7caeebdf1a
src/dummy/toga_dummy/utils.py
python
LoggedObject._get_value
(self, attr, default=None)
return self._sets.get(attr, [default])[-1]
Get a value on the dummy object. Logs the request for the attribute, and returns the value as stored on a local attribute. Args: attr: The name of the attribute to get default: The default value for the attribute if it hasn't already been set. Returns: The value of the attribute, or ``default`` if the value has not been set.
Get a value on the dummy object.
[ "Get", "a", "value", "on", "the", "dummy", "object", "." ]
def _get_value(self, attr, default=None): """Get a value on the dummy object. Logs the request for the attribute, and returns the value as stored on a local attribute. Args: attr: The name of the attribute to get default: The default value for the attribute if it hasn't already been set. Returns: The value of the attribute, or ``default`` if the value has not been set. """ EventLog.log(EventLog.GET_VALUE, instance=self, attr=attr) self._gets.add(attr) return self._sets.get(attr, [default])[-1]
[ "def", "_get_value", "(", "self", ",", "attr", ",", "default", "=", "None", ")", ":", "EventLog", ".", "log", "(", "EventLog", ".", "GET_VALUE", ",", "instance", "=", "self", ",", "attr", "=", "attr", ")", "self", ".", "_gets", ".", "add", "(", "at...
https://github.com/beeware/toga/blob/090370a943bdeefcdbe035b1621fbc7caeebdf1a/src/dummy/toga_dummy/utils.py#L132-L147
FabriceSalvaire/CodeReview
c48433467ac2a9a14b9c9026734f8c494af4aa95
CodeReview/Diff/RawTextDocument.py
python
RawTextDocument.light_view
(self, slice_)
return RawTextDocumentLightView(self, flat_slice)
Return a :class:`RawTextDocumentLightView` instance for the corresponding slice.
Return a :class:`RawTextDocumentLightView` instance for the corresponding slice.
[ "Return", "a", ":", "class", ":", "RawTextDocumentLightView", "instance", "for", "the", "corresponding", "slice", "." ]
def light_view(self, slice_): """Return a :class:`RawTextDocumentLightView` instance for the corresponding slice.""" flat_slice = self.to_flat_slice(slice_) return RawTextDocumentLightView(self, flat_slice)
[ "def", "light_view", "(", "self", ",", "slice_", ")", ":", "flat_slice", "=", "self", ".", "to_flat_slice", "(", "slice_", ")", "return", "RawTextDocumentLightView", "(", "self", ",", "flat_slice", ")" ]
https://github.com/FabriceSalvaire/CodeReview/blob/c48433467ac2a9a14b9c9026734f8c494af4aa95/CodeReview/Diff/RawTextDocument.py#L380-L386
StanfordVL/taskonomy
9f814867b5fe4165860862211e8e99b0f200144d
code/lib/data/load_ops.py
python
resize_rescale_image_low_sat_2
(img, new_dims, new_scale, interp_order=1, current_scale=None, no_clip=False)
return img
Resize an image array with interpolation, and rescale to be between Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. new_scale : (min, max) tuple of new scale. interp_order : interpolation order, default is linear. Returns ------- im : resized ndarray with shape (new_dims[0], new_dims[1], K)
Resize an image array with interpolation, and rescale to be between Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. new_scale : (min, max) tuple of new scale. interp_order : interpolation order, default is linear. Returns ------- im : resized ndarray with shape (new_dims[0], new_dims[1], K)
[ "Resize", "an", "image", "array", "with", "interpolation", "and", "rescale", "to", "be", "between", "Parameters", "----------", "im", ":", "(", "H", "x", "W", "x", "K", ")", "ndarray", "new_dims", ":", "(", "height", "width", ")", "tuple", "of", "new", ...
def resize_rescale_image_low_sat_2(img, new_dims, new_scale, interp_order=1, current_scale=None, no_clip=False): """ Resize an image array with interpolation, and rescale to be between Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. new_scale : (min, max) tuple of new scale. interp_order : interpolation order, default is linear. Returns ------- im : resized ndarray with shape (new_dims[0], new_dims[1], K) """ img = skimage.img_as_float( img ) img = resize_image( img, new_dims, interp_order ) img = np.clip(img, 0.2, 0.8) # low_sat_scale = [0.05, 0.95] # img = rescale_image( img, low_sat_scale, current_scale=current_scale, no_clip=no_clip ) img = rescale_image( img, new_scale, current_scale=current_scale, no_clip=no_clip ) return img
[ "def", "resize_rescale_image_low_sat_2", "(", "img", ",", "new_dims", ",", "new_scale", ",", "interp_order", "=", "1", ",", "current_scale", "=", "None", ",", "no_clip", "=", "False", ")", ":", "img", "=", "skimage", ".", "img_as_float", "(", "img", ")", "...
https://github.com/StanfordVL/taskonomy/blob/9f814867b5fe4165860862211e8e99b0f200144d/code/lib/data/load_ops.py#L188-L208
WeblateOrg/weblate
8126f3dda9d24f2846b755955132a8b8410866c8
weblate/vcs/mercurial.py
python
HgRepository.is_valid
(self)
return os.path.exists(os.path.join(self.path, ".hg", "requires"))
Check whether this is a valid repository.
Check whether this is a valid repository.
[ "Check", "whether", "this", "is", "a", "valid", "repository", "." ]
def is_valid(self): """Check whether this is a valid repository.""" return os.path.exists(os.path.join(self.path, ".hg", "requires"))
[ "def", "is_valid", "(", "self", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\".hg\"", ",", "\"requires\"", ")", ")" ]
https://github.com/WeblateOrg/weblate/blob/8126f3dda9d24f2846b755955132a8b8410866c8/weblate/vcs/mercurial.py#L57-L59
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex/cv/models/classifier.py
python
HRNet_W18_C.__init__
(self, num_classes=1000, **params)
[]
def __init__(self, num_classes=1000, **params): super(HRNet_W18_C, self).__init__( model_name='HRNet_W18_C', num_classes=num_classes, **params)
[ "def", "__init__", "(", "self", ",", "num_classes", "=", "1000", ",", "*", "*", "params", ")", ":", "super", "(", "HRNet_W18_C", ",", "self", ")", ".", "__init__", "(", "model_name", "=", "'HRNet_W18_C'", ",", "num_classes", "=", "num_classes", ",", "*",...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/cv/models/classifier.py#L760-L762
OpenXenManager/openxenmanager
1cb5c1cb13358ba584856e99a94f9669d17670ff
src/OXM/window_vm_snapshot.py
python
oxcWindowVMSnapshot.on_m_snap_newvm_activate
(self, widget, data=None)
Function called when you press "Take snapshot"
Function called when you press "Take snapshot"
[ "Function", "called", "when", "you", "press", "Take", "snapshot" ]
def on_m_snap_newvm_activate(self, widget, data=None): # print self.selected_snap_ref # TODO -> select vm with name_label """ Function called when you press "Take snapshot" """ self.on_m_newvm_activate(widget, data)
[ "def", "on_m_snap_newvm_activate", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "# print self.selected_snap_ref", "# TODO -> select vm with name_label", "self", ".", "on_m_newvm_activate", "(", "widget", ",", "data", ")" ]
https://github.com/OpenXenManager/openxenmanager/blob/1cb5c1cb13358ba584856e99a94f9669d17670ff/src/OXM/window_vm_snapshot.py#L54-L60
CoinAlpha/hummingbot
36f6149c1644c07cd36795b915f38b8f49b798e7
hummingbot/connector/exchange/liquid/liquid_api_order_book_data_source.py
python
LiquidAPIOrderBookDataSource._inner_messages
(self, ws: websockets.WebSocketClientProtocol)
Generator function that returns messages from the web socket stream :param ws: current web socket connection :returns: message in AsyncIterable format
Generator function that returns messages from the web socket stream :param ws: current web socket connection :returns: message in AsyncIterable format
[ "Generator", "function", "that", "returns", "messages", "from", "the", "web", "socket", "stream", ":", "param", "ws", ":", "current", "web", "socket", "connection", ":", "returns", ":", "message", "in", "AsyncIterable", "format" ]
async def _inner_messages(self, ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]: """ Generator function that returns messages from the web socket stream :param ws: current web socket connection :returns: message in AsyncIterable format """ # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect. try: while True: try: msg: str = await asyncio.wait_for(ws.recv(), timeout=Constants.MESSAGE_TIMEOUT) yield msg except asyncio.TimeoutError: pong_waiter = await ws.ping() await asyncio.wait_for(pong_waiter, timeout=Constants.PING_TIMEOUT) except asyncio.TimeoutError: self.logger().warning("WebSocket ping timed out. Going to reconnect...") return except ConnectionClosed: return finally: await ws.close()
[ "async", "def", "_inner_messages", "(", "self", ",", "ws", ":", "websockets", ".", "WebSocketClientProtocol", ")", "->", "AsyncIterable", "[", "str", "]", ":", "# Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.", "try", ":", ...
https://github.com/CoinAlpha/hummingbot/blob/36f6149c1644c07cd36795b915f38b8f49b798e7/hummingbot/connector/exchange/liquid/liquid_api_order_book_data_source.py#L247-L269
mrkipling/maraschino
c6be9286937783ae01df2d6d8cebfc8b2734a7d7
lib/jinja2/environment.py
python
Environment._compile
(self, source, filename)
return compile(source, filename, 'exec')
Internal hook that can be overriden to hook a different compile method in. .. versionadded:: 2.5
Internal hook that can be overriden to hook a different compile method in.
[ "Internal", "hook", "that", "can", "be", "overriden", "to", "hook", "a", "different", "compile", "method", "in", "." ]
def _compile(self, source, filename): """Internal hook that can be overriden to hook a different compile method in. .. versionadded:: 2.5 """ return compile(source, filename, 'exec')
[ "def", "_compile", "(", "self", ",", "source", ",", "filename", ")", ":", "return", "compile", "(", "source", ",", "filename", ",", "'exec'", ")" ]
https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/jinja2/environment.py#L445-L451
IOActive/XDiFF
552d3394e119ca4ced8115f9fd2d7e26760e40b1
xdiff_analyze.py
python
Analyze.analyze_canary_token_code
(self, output, toplimit)
return rows
Find canary tokens of code executed in the stdout or in the stderr
Find canary tokens of code executed in the stdout or in the stderr
[ "Find", "canary", "tokens", "of", "code", "executed", "in", "the", "stdout", "or", "in", "the", "stderr" ]
def analyze_canary_token_code(self, output, toplimit): """Find canary tokens of code executed in the stdout or in the stderr""" title = "Analyze Presence of Canary Tokens Code - analyze_canary_token_code" columns = ["Testcase", "Software", "Type", "OS", "Stdout", "Stderr"] function_risk = 3 if not self.check_minimum_risk(function_risk, title): return False if output: self.settings['logger'].info(title) rows = [] results = self.settings['db'].analyze_string_disclosure("canarytokencode") for result in results: if toplimit is not None and len(rows) >= toplimit: break rows.append([(result[0][:self.settings['testcase_limit']], result[1], result[2], result[3], result[4], result[5])]) self.dump.general(output, title, columns, rows) return rows
[ "def", "analyze_canary_token_code", "(", "self", ",", "output", ",", "toplimit", ")", ":", "title", "=", "\"Analyze Presence of Canary Tokens Code - analyze_canary_token_code\"", "columns", "=", "[", "\"Testcase\"", ",", "\"Software\"", ",", "\"Type\"", ",", "\"OS\"", "...
https://github.com/IOActive/XDiFF/blob/552d3394e119ca4ced8115f9fd2d7e26760e40b1/xdiff_analyze.py#L536-L555
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/pandas/core/missing.py
python
mask_missing
(arr, values_to_mask)
return mask
Return a masking array of same size/shape as arr with entries equaling any member of values_to_mask set to True
Return a masking array of same size/shape as arr with entries equaling any member of values_to_mask set to True
[ "Return", "a", "masking", "array", "of", "same", "size", "/", "shape", "as", "arr", "with", "entries", "equaling", "any", "member", "of", "values_to_mask", "set", "to", "True" ]
def mask_missing(arr, values_to_mask): """ Return a masking array of same size/shape as arr with entries equaling any member of values_to_mask set to True """ dtype, values_to_mask = infer_dtype_from_array(values_to_mask) try: values_to_mask = np.array(values_to_mask, dtype=dtype) except Exception: values_to_mask = np.array(values_to_mask, dtype=object) na_mask = isnull(values_to_mask) nonna = values_to_mask[~na_mask] mask = None for x in nonna: if mask is None: # numpy elementwise comparison warning if is_numeric_v_string_like(arr, x): mask = False else: mask = arr == x # if x is a string and arr is not, then we get False and we must # expand the mask to size arr.shape if is_scalar(mask): mask = np.zeros(arr.shape, dtype=bool) else: # numpy elementwise comparison warning if is_numeric_v_string_like(arr, x): mask |= False else: mask |= arr == x if na_mask.any(): if mask is None: mask = isnull(arr) else: mask |= isnull(arr) return mask
[ "def", "mask_missing", "(", "arr", ",", "values_to_mask", ")", ":", "dtype", ",", "values_to_mask", "=", "infer_dtype_from_array", "(", "values_to_mask", ")", "try", ":", "values_to_mask", "=", "np", ".", "array", "(", "values_to_mask", ",", "dtype", "=", "dty...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/core/missing.py#L26-L70
cronyo/cronyo
cd5abab0871b68bf31b18aac934303928130a441
cronyo/vendor/yaml/constructor.py
python
FullConstructor.find_python_module
(self, name, mark, unsafe=False)
return sys.modules[name]
[]
def find_python_module(self, name, mark, unsafe=False): if not name: raise ConstructorError("while constructing a Python module", mark, "expected non-empty name appended to the tag", mark) if unsafe: try: __import__(name) except ImportError as exc: raise ConstructorError("while constructing a Python module", mark, "cannot find module %r (%s)" % (name, exc), mark) if not name in sys.modules: raise ConstructorError("while constructing a Python module", mark, "module %r is not imported" % name, mark) return sys.modules[name]
[ "def", "find_python_module", "(", "self", ",", "name", ",", "mark", ",", "unsafe", "=", "False", ")", ":", "if", "not", "name", ":", "raise", "ConstructorError", "(", "\"while constructing a Python module\"", ",", "mark", ",", "\"expected non-empty name appended to ...
https://github.com/cronyo/cronyo/blob/cd5abab0871b68bf31b18aac934303928130a441/cronyo/vendor/yaml/constructor.py#L506-L519
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/idlelib/PyShell.py
python
ModifiedInterpreter.showsyntaxerror
(self, filename=None)
Extend base class method: Add Colorizing Color the offending position instead of printing it and pointing at it with a caret.
Extend base class method: Add Colorizing
[ "Extend", "base", "class", "method", ":", "Add", "Colorizing" ]
def showsyntaxerror(self, filename=None): """Extend base class method: Add Colorizing Color the offending position instead of printing it and pointing at it with a caret. """ text = self.tkconsole.text stuff = self.unpackerror() if stuff: msg, lineno, offset, line = stuff if lineno == 1: pos = "iomark + %d chars" % (offset-1) else: pos = "iomark linestart + %d lines + %d chars" % \ (lineno-1, offset-1) text.tag_add("ERROR", pos) text.see(pos) char = text.get(pos) if char and char in IDENTCHARS: text.tag_add("ERROR", pos + " wordstart", pos) self.tkconsole.resetoutput() self.write("SyntaxError: %s\n" % str(msg)) else: self.tkconsole.resetoutput() InteractiveInterpreter.showsyntaxerror(self, filename) self.tkconsole.showprompt()
[ "def", "showsyntaxerror", "(", "self", ",", "filename", "=", "None", ")", ":", "text", "=", "self", ".", "tkconsole", ".", "text", "stuff", "=", "self", ".", "unpackerror", "(", ")", "if", "stuff", ":", "msg", ",", "lineno", ",", "offset", ",", "line...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/idlelib/PyShell.py#L709-L735
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/tolo/fan.py
python
ToloFan.turn_on
( self, speed: str | None = None, percentage: int | None = None, preset_mode: str | None = None, **kwargs: Any, )
Turn on sauna fan.
Turn on sauna fan.
[ "Turn", "on", "sauna", "fan", "." ]
def turn_on( self, speed: str | None = None, percentage: int | None = None, preset_mode: str | None = None, **kwargs: Any, ) -> None: """Turn on sauna fan.""" self.coordinator.client.set_fan_on(True)
[ "def", "turn_on", "(", "self", ",", "speed", ":", "str", "|", "None", "=", "None", ",", "percentage", ":", "int", "|", "None", "=", "None", ",", "preset_mode", ":", "str", "|", "None", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ",", ")", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/tolo/fan.py#L44-L52
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
pytorch/pytorchcv/models/efficientnet.py
python
efficientnet_b3b
(in_size=(300, 300), **kwargs)
return get_efficientnet(version="b3", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b3b", **kwargs)
EfficientNet-B3-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (300, 300) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location for keeping the model parameters.
EfficientNet-B3-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946.
[ "EfficientNet", "-", "B3", "-", "b", "(", "like", "TF", "-", "implementation", ")", "model", "from", "EfficientNet", ":", "Rethinking", "Model", "Scaling", "for", "Convolutional", "Neural", "Networks", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "...
def efficientnet_b3b(in_size=(300, 300), **kwargs): """ EfficientNet-B3-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (300, 300) Spatial size of the expected input image. 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_efficientnet(version="b3", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b3b", **kwargs)
[ "def", "efficientnet_b3b", "(", "in_size", "=", "(", "300", ",", "300", ")", ",", "*", "*", "kwargs", ")", ":", "return", "get_efficientnet", "(", "version", "=", "\"b3\"", ",", "in_size", "=", "in_size", ",", "tf_mode", "=", "True", ",", "bn_eps", "="...
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/pytorch/pytorchcv/models/efficientnet.py#L693-L708
funcwj/conv-tasnet
f3333b0e3b20a15dfaff2a41e7abdadc0e1ff932
nnet/libs/audio.py
python
read_wav
(fname, normalize=True, return_rate=False)
return samps
Read wave files using scipy.io.wavfile(support multi-channel)
Read wave files using scipy.io.wavfile(support multi-channel)
[ "Read", "wave", "files", "using", "scipy", ".", "io", ".", "wavfile", "(", "support", "multi", "-", "channel", ")" ]
def read_wav(fname, normalize=True, return_rate=False): """ Read wave files using scipy.io.wavfile(support multi-channel) """ # samps_int16: N x C or N # N: number of samples # C: number of channels samp_rate, samps_int16 = wf.read(fname) # N x C => C x N samps = samps_int16.astype(np.float) # tranpose because I used to put channel axis first if samps.ndim != 1: samps = np.transpose(samps) # normalize like MATLAB and librosa if normalize: samps = samps / MAX_INT16 if return_rate: return samp_rate, samps return samps
[ "def", "read_wav", "(", "fname", ",", "normalize", "=", "True", ",", "return_rate", "=", "False", ")", ":", "# samps_int16: N x C or N", "# N: number of samples", "# C: number of channels", "samp_rate", ",", "samps_int16", "=", "wf", ".", "read", "(", "fname", ...
https://github.com/funcwj/conv-tasnet/blob/f3333b0e3b20a15dfaff2a41e7abdadc0e1ff932/nnet/libs/audio.py#L31-L49
WerWolv/EdiZon_CheatsConfigsAndScripts
d16d36c7509c01dca770f402babd83ff2e9ae6e7
Scripts/lib/python3.5/email/message.py
python
Message.__getitem__
(self, name)
return self.get(name)
Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name.
Get a header value.
[ "Get", "a", "header", "value", "." ]
def __getitem__(self, name): """Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name. """ return self.get(name)
[ "def", "__getitem__", "(", "self", ",", "name", ")", ":", "return", "self", ".", "get", "(", "name", ")" ]
https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/email/message.py#L383-L392
cherrypy/cherrypy
a7983fe61f7237f2354915437b04295694100372
cherrypy/process/plugins.py
python
SimplePlugin.subscribe
(self)
Register this object as a (multi-channel) listener on the bus.
Register this object as a (multi-channel) listener on the bus.
[ "Register", "this", "object", "as", "a", "(", "multi", "-", "channel", ")", "listener", "on", "the", "bus", "." ]
def subscribe(self): """Register this object as a (multi-channel) listener on the bus.""" for channel in self.bus.listeners: # Subscribe self.start, self.exit, etc. if present. method = getattr(self, channel, None) if method is not None: self.bus.subscribe(channel, method)
[ "def", "subscribe", "(", "self", ")", ":", "for", "channel", "in", "self", ".", "bus", ".", "listeners", ":", "# Subscribe self.start, self.exit, etc. if present.", "method", "=", "getattr", "(", "self", ",", "channel", ",", "None", ")", "if", "method", "is", ...
https://github.com/cherrypy/cherrypy/blob/a7983fe61f7237f2354915437b04295694100372/cherrypy/process/plugins.py#L44-L50
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/lib2to3/fixer_base.py
python
BaseFix.new_name
(self, template='xxx_todo_changeme')
return name
Return a string suitable for use as an identifier The new name is guaranteed not to conflict with other identifiers.
Return a string suitable for use as an identifier The new name is guaranteed not to conflict with other identifiers.
[ "Return", "a", "string", "suitable", "for", "use", "as", "an", "identifier", "The", "new", "name", "is", "guaranteed", "not", "to", "conflict", "with", "other", "identifiers", "." ]
def new_name(self, template='xxx_todo_changeme'): """Return a string suitable for use as an identifier The new name is guaranteed not to conflict with other identifiers. """ name = template while name in self.used_names: name = template + unicode(self.numbers.next()) self.used_names.add(name) return name
[ "def", "new_name", "(", "self", ",", "template", "=", "'xxx_todo_changeme'", ")", ":", "name", "=", "template", "while", "name", "in", "self", ".", "used_names", ":", "name", "=", "template", "+", "unicode", "(", "self", ".", "numbers", ".", "next", "(",...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/lib2to3/fixer_base.py#L96-L106
ChineseGLUE/ChineseGLUE
1591b85cf5427c2ff60f718d359ecb71d2b44879
baselines/models/ernie/conlleval.py
python
evaluate
(iterable, options=None)
return counts
[]
def evaluate(iterable, options=None): if options is None: options = parse_args([]) # use defaults counts = EvalCounts() num_features = None # number of features per line in_correct = False # currently processed chunks is correct until now last_correct = 'O' # previous chunk tag in corpus last_correct_type = '' # type of previously identified chunk tag last_guessed = 'O' # previously identified chunk tag last_guessed_type = '' # type of previous chunk tag in corpus for line in iterable: line = line.rstrip('\r\n') if options.delimiter == ANY_SPACE: features = line.split() else: features = line.split(options.delimiter) if num_features is None: num_features = len(features) elif num_features != len(features) and len(features) != 0: raise FormatError('unexpected number of features: %d (%d)' % (len(features), num_features)) if len(features) == 0 or features[0] == options.boundary: features = [options.boundary, 'O', 'O'] if len(features) < 3: raise FormatError('unexpected number of features in line %s' % line) guessed, guessed_type = parse_tag(features.pop()) correct, correct_type = parse_tag(features.pop()) first_item = features.pop(0) if first_item == options.boundary: guessed = 'O' end_correct = end_of_chunk(last_correct, correct, last_correct_type, correct_type) end_guessed = end_of_chunk(last_guessed, guessed, last_guessed_type, guessed_type) start_correct = start_of_chunk(last_correct, correct, last_correct_type, correct_type) start_guessed = start_of_chunk(last_guessed, guessed, last_guessed_type, guessed_type) if in_correct: if (end_correct and end_guessed and last_guessed_type == last_correct_type): in_correct = False counts.correct_chunk += 1 counts.t_correct_chunk[last_correct_type] += 1 elif (end_correct != end_guessed or guessed_type != correct_type): in_correct = False if start_correct and start_guessed and guessed_type == correct_type: in_correct = True if start_correct: counts.found_correct += 1 counts.t_found_correct[correct_type] += 1 if start_guessed: counts.found_guessed += 1 counts.t_found_guessed[guessed_type] += 1 if first_item != options.boundary: if correct == guessed and guessed_type == correct_type: counts.correct_tags += 1 counts.token_counter += 1 last_guessed = guessed last_correct = correct last_guessed_type = guessed_type last_correct_type = correct_type if in_correct: counts.correct_chunk += 1 counts.t_correct_chunk[last_correct_type] += 1 return counts
[ "def", "evaluate", "(", "iterable", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "parse_args", "(", "[", "]", ")", "# use defaults", "counts", "=", "EvalCounts", "(", ")", "num_features", "=", "None", "# numb...
https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models/ernie/conlleval.py#L64-L143
celery/django-celery
c679b05b2abc174e6fa3231b120a07b49ec8f911
djcelery/backends/database.py
python
DatabaseBackend._store_result
(self, task_id, result, status, traceback=None, request=None)
return result
Store return value and status of an executed task.
Store return value and status of an executed task.
[ "Store", "return", "value", "and", "status", "of", "an", "executed", "task", "." ]
def _store_result(self, task_id, result, status, traceback=None, request=None): """Store return value and status of an executed task.""" self.TaskModel._default_manager.store_result( task_id, result, status, traceback=traceback, children=self.current_task_children(request), ) return result
[ "def", "_store_result", "(", "self", ",", "task_id", ",", "result", ",", "status", ",", "traceback", "=", "None", ",", "request", "=", "None", ")", ":", "self", ".", "TaskModel", ".", "_default_manager", ".", "store_result", "(", "task_id", ",", "result", ...
https://github.com/celery/django-celery/blob/c679b05b2abc174e6fa3231b120a07b49ec8f911/djcelery/backends/database.py#L28-L35
openid/python-openid
afa6adacbe1a41d8f614c8bce2264dfbe9e76489
openid/consumer/discover.py
python
normalizeXRI
(xri)
return xri
Normalize an XRI, stripping its scheme if present
Normalize an XRI, stripping its scheme if present
[ "Normalize", "an", "XRI", "stripping", "its", "scheme", "if", "present" ]
def normalizeXRI(xri): """Normalize an XRI, stripping its scheme if present""" if xri.startswith("xri://"): xri = xri[6:] return xri
[ "def", "normalizeXRI", "(", "xri", ")", ":", "if", "xri", ".", "startswith", "(", "\"xri://\"", ")", ":", "xri", "=", "xri", "[", "6", ":", "]", "return", "xri" ]
https://github.com/openid/python-openid/blob/afa6adacbe1a41d8f614c8bce2264dfbe9e76489/openid/consumer/discover.py#L313-L317
JustDoPython/python-100-day
4e75007195aa4cdbcb899aeb06b9b08996a4606c
day-033/enum_extend.py
python
EnumExtend.test_extending
(self)
[]
def test_extending(self): class Color(Enum): red = 1 green = 2 blue = 3 # TypeError: Cannot extend enumerations with self.assertRaises(TypeError): class MoreColor(Color): cyan = 4 magenta = 5 yellow = 6
[ "def", "test_extending", "(", "self", ")", ":", "class", "Color", "(", "Enum", ")", ":", "red", "=", "1", "green", "=", "2", "blue", "=", "3", "# TypeError: Cannot extend enumerations", "with", "self", ".", "assertRaises", "(", "TypeError", ")", ":", "clas...
https://github.com/JustDoPython/python-100-day/blob/4e75007195aa4cdbcb899aeb06b9b08996a4606c/day-033/enum_extend.py#L7-L18
nullism/pycnic
fe6cc4a06a18656fea875517aef508989da2a8e9
pycnic/cli.py
python
class_sort
(routes, verbose=False)
Sort routes alphabetically by their class name.
Sort routes alphabetically by their class name.
[ "Sort", "routes", "alphabetically", "by", "their", "class", "name", "." ]
def class_sort(routes, verbose=False): """Sort routes alphabetically by their class name.""" routes.sort(key=lambda x: full_class_name(x[2])) max_route_length = 5 # Length of the word "route" max_method_length = 6 # Length of the word "method" # Determine justified string lengths for route in routes: methods_str = ', '.join(route[1]) max_route_length = max(max_route_length, len(route[0])) max_method_length = max(max_method_length, len(methods_str)) ljust_method_word = 'Method'.ljust(max_method_length) ljust_route_word = 'Route'.ljust(max_route_length) print(ljust_route_word + ' ' + ljust_method_word + ' Class') print('') # Print justified strings for route in routes: ljust_route = route[0].ljust(max_route_length) methods_str = ', '.join(route[1]).upper() ljust_methods = methods_str.ljust(max_method_length) route_cls_name = full_class_name(route[2]) print(' '.join([ljust_route, ljust_methods, route_cls_name])) if verbose: print_description(route[2], max_route_length, max_method_length)
[ "def", "class_sort", "(", "routes", ",", "verbose", "=", "False", ")", ":", "routes", ".", "sort", "(", "key", "=", "lambda", "x", ":", "full_class_name", "(", "x", "[", "2", "]", ")", ")", "max_route_length", "=", "5", "# Length of the word \"route\"", ...
https://github.com/nullism/pycnic/blob/fe6cc4a06a18656fea875517aef508989da2a8e9/pycnic/cli.py#L84-L108
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/axis.py
python
Axis.get_ticklabel_extents
(self, renderer)
return bbox, bbox2
Get the extents of the tick labels on either side of the axes.
Get the extents of the tick labels on either side of the axes.
[ "Get", "the", "extents", "of", "the", "tick", "labels", "on", "either", "side", "of", "the", "axes", "." ]
def get_ticklabel_extents(self, renderer): """ Get the extents of the tick labels on either side of the axes. """ ticks_to_draw = self._update_ticks(renderer) ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw, renderer) if len(ticklabelBoxes): bbox = mtransforms.Bbox.union(ticklabelBoxes) else: bbox = mtransforms.Bbox.from_extents(0, 0, 0, 0) if len(ticklabelBoxes2): bbox2 = mtransforms.Bbox.union(ticklabelBoxes2) else: bbox2 = mtransforms.Bbox.from_extents(0, 0, 0, 0) return bbox, bbox2
[ "def", "get_ticklabel_extents", "(", "self", ",", "renderer", ")", ":", "ticks_to_draw", "=", "self", ".", "_update_ticks", "(", "renderer", ")", "ticklabelBoxes", ",", "ticklabelBoxes2", "=", "self", ".", "_get_tick_bboxes", "(", "ticks_to_draw", ",", "renderer",...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/axis.py#L986-L1004
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/admin/tool.py
python
AdminTool.delete_folder_contents
(folder)
[]
def delete_folder_contents(folder): shutil.rmtree(folder)
[ "def", "delete_folder_contents", "(", "folder", ")", ":", "shutil", ".", "rmtree", "(", "folder", ")" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/admin/tool.py#L59-L60
pyvista/pyvista
012dbb95a9aae406c3cd4cd94fc8c477f871e426
examples/99-advanced/warp-by-vector-eigenmodes.py
python
make_cijkl_E_nu
(E=200, nu=0.3)
return cijkl, cij
Makes cijkl from E and nu. Default values for steel are: E=200 GPa, nu=0.3.
Makes cijkl from E and nu. Default values for steel are: E=200 GPa, nu=0.3.
[ "Makes", "cijkl", "from", "E", "and", "nu", ".", "Default", "values", "for", "steel", "are", ":", "E", "=", "200", "GPa", "nu", "=", "0", ".", "3", "." ]
def make_cijkl_E_nu(E=200, nu=0.3): """Makes cijkl from E and nu. Default values for steel are: E=200 GPa, nu=0.3.""" lambd = E * nu / (1 + nu) / (1 - 2 * nu) mu = E / 2 / (1 + nu) cij = np.zeros((6, 6)) cij[(0, 1, 2), (0, 1, 2)] = lambd + 2 * mu cij[(0, 0, 1, 1, 2, 2), (1, 2, 0, 2, 0, 1)] = lambd cij[(3, 4, 5), (3, 4, 5)] = mu # check symmetry assert np.allclose(cij, cij.T) # convert to order 4 tensor coord_mapping = {(1, 1): 1, (2, 2): 2, (3, 3): 3, (2, 3): 4, (1, 3): 5, (1, 2): 6, (2, 1): 6, (3, 1): 5, (3, 2): 4} cijkl = np.zeros((3, 3, 3, 3)) for i in range(3): for j in range(3): for k in range(3): for l in range(3): u = coord_mapping[(i + 1, j + 1)] v = coord_mapping[(k + 1, l + 1)] cijkl[i, j, k, l] = cij[u - 1, v - 1] return cijkl, cij
[ "def", "make_cijkl_E_nu", "(", "E", "=", "200", ",", "nu", "=", "0.3", ")", ":", "lambd", "=", "E", "*", "nu", "/", "(", "1", "+", "nu", ")", "/", "(", "1", "-", "2", "*", "nu", ")", "mu", "=", "E", "/", "2", "/", "(", "1", "+", "nu", ...
https://github.com/pyvista/pyvista/blob/012dbb95a9aae406c3cd4cd94fc8c477f871e426/examples/99-advanced/warp-by-vector-eigenmodes.py#L39-L69
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/reshape/merge.py
python
_groupby_and_merge
(by, on, left, right, _merge_pieces, check_duplicates=True)
return result, lby
groupby & merge; we are always performing a left-by type operation Parameters ---------- by: field to group on: duplicates field left: left frame right: right frame _merge_pieces: function for merging check_duplicates: boolean, default True should we check & clean duplicates
groupby & merge; we are always performing a left-by type operation
[ "groupby", "&", "merge", ";", "we", "are", "always", "performing", "a", "left", "-", "by", "type", "operation" ]
def _groupby_and_merge(by, on, left, right, _merge_pieces, check_duplicates=True): """ groupby & merge; we are always performing a left-by type operation Parameters ---------- by: field to group on: duplicates field left: left frame right: right frame _merge_pieces: function for merging check_duplicates: boolean, default True should we check & clean duplicates """ pieces = [] if not isinstance(by, (list, tuple)): by = [by] lby = left.groupby(by, sort=False) # if we can groupby the rhs # then we can get vastly better perf try: # we will check & remove duplicates if indicated if check_duplicates: if on is None: on = [] elif not isinstance(on, (list, tuple)): on = [on] if right.duplicated(by + on).any(): right = right.drop_duplicates(by + on, keep='last') rby = right.groupby(by, sort=False) except KeyError: rby = None for key, lhs in lby: if rby is None: rhs = right else: try: rhs = right.take(rby.indices[key]) except KeyError: # key doesn't exist in left lcols = lhs.columns.tolist() cols = lcols + [r for r in right.columns if r not in set(lcols)] merged = lhs.reindex(columns=cols) merged.index = range(len(merged)) pieces.append(merged) continue merged = _merge_pieces(lhs, rhs) # make sure join keys are in the merged # TODO, should _merge_pieces do this? for k in by: try: if k in merged: merged[k] = key except KeyError: pass pieces.append(merged) # preserve the original order # if we have a missing piece this can be reset from pandas.core.reshape.concat import concat result = concat(pieces, ignore_index=True) result = result.reindex(columns=pieces[0].columns, copy=False) return result, lby
[ "def", "_groupby_and_merge", "(", "by", ",", "on", ",", "left", ",", "right", ",", "_merge_pieces", ",", "check_duplicates", "=", "True", ")", ":", "pieces", "=", "[", "]", "if", "not", "isinstance", "(", "by", ",", "(", "list", ",", "tuple", ")", ")...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/reshape/merge.py#L55-L129
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/dviread.py
python
Dvi.close
(self)
Close the underlying file if it is open.
Close the underlying file if it is open.
[ "Close", "the", "underlying", "file", "if", "it", "is", "open", "." ]
def close(self): """ Close the underlying file if it is open. """ if not self.file.closed: self.file.close()
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "file", ".", "closed", ":", "self", ".", "file", ".", "close", "(", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/dviread.py#L92-L97
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
ingest_feed_lambda/numpy/lib/npyio.py
python
load
(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding='ASCII')
Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files. Parameters ---------- file : file-like object, string, or pathlib.Path The file to read. File-like objects must support the ``seek()`` and ``read()`` methods. Pickled files require that the file-like object support the ``readline()`` method as well. mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional If not None, then memory-map the file, using the given mode (see `numpy.memmap` for a detailed description of the modes). A memory-mapped array is kept on disk. However, it can be accessed and sliced like any ndarray. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory. allow_pickle : bool, optional Allow loading pickled object arrays stored in npy files. Reasons for disallowing pickles include security, as loading pickled data can execute arbitrary code. If pickles are disallowed, loading object arrays will fail. Default: True fix_imports : bool, optional Only useful when loading Python 2 generated pickled files on Python 3, which includes npy/npz files containing object arrays. If `fix_imports` is True, pickle will try to map the old Python 2 names to the new names used in Python 3. encoding : str, optional What encoding to use when reading Python 2 strings. Only useful when loading Python 2 generated pickled files on Python 3, which includes npy/npz files containing object arrays. Values other than 'latin1', 'ASCII', and 'bytes' are not allowed, as they can corrupt numerical data. Default: 'ASCII' Returns ------- result : array, tuple, dict, etc. Data stored in the file. For ``.npz`` files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors. Raises ------ IOError If the input file does not exist or cannot be read. ValueError The file contains an object array, but allow_pickle=False given. See Also -------- save, savez, savez_compressed, loadtxt memmap : Create a memory-map to an array stored in a file on disk. lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file. Notes ----- - If the file contains pickle data, then whatever object is stored in the pickle is returned. - If the file is a ``.npy`` file, then a single array is returned. - If the file is a ``.npz`` file, then a dictionary-like object is returned, containing ``{filename: array}`` key-value pairs, one for each file in the archive. - If the file is a ``.npz`` file, the returned value supports the context manager protocol in a similar fashion to the open function:: with load('foo.npz') as data: a = data['a'] The underlying file descriptor is closed when exiting the 'with' block. Examples -------- Store data to disk, and load it again: >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]])) >>> np.load('/tmp/123.npy') array([[1, 2, 3], [4, 5, 6]]) Store compressed data to disk, and load it again: >>> a=np.array([[1, 2, 3], [4, 5, 6]]) >>> b=np.array([1, 2]) >>> np.savez('/tmp/123.npz', a=a, b=b) >>> data = np.load('/tmp/123.npz') >>> data['a'] array([[1, 2, 3], [4, 5, 6]]) >>> data['b'] array([1, 2]) >>> data.close() Mem-map the stored array, and then access the second row directly from disk: >>> X = np.load('/tmp/123.npy', mmap_mode='r') >>> X[1, :] memmap([4, 5, 6])
Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.
[ "Load", "arrays", "or", "pickled", "objects", "from", ".", "npy", ".", "npz", "or", "pickled", "files", "." ]
def load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding='ASCII'): """ Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files. Parameters ---------- file : file-like object, string, or pathlib.Path The file to read. File-like objects must support the ``seek()`` and ``read()`` methods. Pickled files require that the file-like object support the ``readline()`` method as well. mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional If not None, then memory-map the file, using the given mode (see `numpy.memmap` for a detailed description of the modes). A memory-mapped array is kept on disk. However, it can be accessed and sliced like any ndarray. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory. allow_pickle : bool, optional Allow loading pickled object arrays stored in npy files. Reasons for disallowing pickles include security, as loading pickled data can execute arbitrary code. If pickles are disallowed, loading object arrays will fail. Default: True fix_imports : bool, optional Only useful when loading Python 2 generated pickled files on Python 3, which includes npy/npz files containing object arrays. If `fix_imports` is True, pickle will try to map the old Python 2 names to the new names used in Python 3. encoding : str, optional What encoding to use when reading Python 2 strings. Only useful when loading Python 2 generated pickled files on Python 3, which includes npy/npz files containing object arrays. Values other than 'latin1', 'ASCII', and 'bytes' are not allowed, as they can corrupt numerical data. Default: 'ASCII' Returns ------- result : array, tuple, dict, etc. Data stored in the file. For ``.npz`` files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors. Raises ------ IOError If the input file does not exist or cannot be read. ValueError The file contains an object array, but allow_pickle=False given. See Also -------- save, savez, savez_compressed, loadtxt memmap : Create a memory-map to an array stored in a file on disk. lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file. Notes ----- - If the file contains pickle data, then whatever object is stored in the pickle is returned. - If the file is a ``.npy`` file, then a single array is returned. - If the file is a ``.npz`` file, then a dictionary-like object is returned, containing ``{filename: array}`` key-value pairs, one for each file in the archive. - If the file is a ``.npz`` file, the returned value supports the context manager protocol in a similar fashion to the open function:: with load('foo.npz') as data: a = data['a'] The underlying file descriptor is closed when exiting the 'with' block. Examples -------- Store data to disk, and load it again: >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]])) >>> np.load('/tmp/123.npy') array([[1, 2, 3], [4, 5, 6]]) Store compressed data to disk, and load it again: >>> a=np.array([[1, 2, 3], [4, 5, 6]]) >>> b=np.array([1, 2]) >>> np.savez('/tmp/123.npz', a=a, b=b) >>> data = np.load('/tmp/123.npz') >>> data['a'] array([[1, 2, 3], [4, 5, 6]]) >>> data['b'] array([1, 2]) >>> data.close() Mem-map the stored array, and then access the second row directly from disk: >>> X = np.load('/tmp/123.npy', mmap_mode='r') >>> X[1, :] memmap([4, 5, 6]) """ own_fid = False if isinstance(file, basestring): fid = open(file, "rb") own_fid = True elif is_pathlib_path(file): fid = file.open("rb") own_fid = True else: fid = file if encoding not in ('ASCII', 'latin1', 'bytes'): # The 'encoding' value for pickle also affects what encoding # the serialized binary data of NumPy arrays is loaded # in. Pickle does not pass on the encoding information to # NumPy. The unpickling code in numpy.core.multiarray is # written to assume that unicode data appearing where binary # should be is in 'latin1'. 'bytes' is also safe, as is 'ASCII'. # # Other encoding values can corrupt binary data, and we # purposefully disallow them. For the same reason, the errors= # argument is not exposed, as values other than 'strict' # result can similarly silently corrupt numerical data. raise ValueError("encoding must be 'ASCII', 'latin1', or 'bytes'") if sys.version_info[0] >= 3: pickle_kwargs = dict(encoding=encoding, fix_imports=fix_imports) else: # Nothing to do on Python 2 pickle_kwargs = {} try: # Code to distinguish from NumPy binary files and pickles. _ZIP_PREFIX = b'PK\x03\x04' N = len(format.MAGIC_PREFIX) magic = fid.read(N) # If the file size is less than N, we need to make sure not # to seek past the beginning of the file fid.seek(-min(N, len(magic)), 1) # back-up if magic.startswith(_ZIP_PREFIX): # zip-file (assume .npz) # Transfer file ownership to NpzFile tmp = own_fid own_fid = False return NpzFile(fid, own_fid=tmp, allow_pickle=allow_pickle, pickle_kwargs=pickle_kwargs) elif magic == format.MAGIC_PREFIX: # .npy file if mmap_mode: return format.open_memmap(file, mode=mmap_mode) else: return format.read_array(fid, allow_pickle=allow_pickle, pickle_kwargs=pickle_kwargs) else: # Try a pickle if not allow_pickle: raise ValueError("allow_pickle=False, but file does not contain " "non-pickled data") try: return pickle.load(fid, **pickle_kwargs) except: raise IOError( "Failed to interpret file %s as a pickle" % repr(file)) finally: if own_fid: fid.close()
[ "def", "load", "(", "file", ",", "mmap_mode", "=", "None", ",", "allow_pickle", "=", "True", ",", "fix_imports", "=", "True", ",", "encoding", "=", "'ASCII'", ")", ":", "own_fid", "=", "False", "if", "isinstance", "(", "file", ",", "basestring", ")", "...
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/numpy/lib/npyio.py#L266-L432
JetBrains/python-skeletons
95ad24b666e475998e5d1cc02ed53a2188036167
datetime.py
python
date.replace
(self, year=None, month=None, day=None)
return _datetime.date(0, 0, 0)
Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified. :type year: numbers.Integral :type month: numbers.Integral :type day: numbers.Integral :rtype: _datetime.date
Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified.
[ "Return", "a", "date", "with", "the", "same", "value", "except", "for", "those", "parameters", "given", "new", "values", "by", "whichever", "keyword", "arguments", "are", "specified", "." ]
def replace(self, year=None, month=None, day=None): """Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified. :type year: numbers.Integral :type month: numbers.Integral :type day: numbers.Integral :rtype: _datetime.date """ return _datetime.date(0, 0, 0)
[ "def", "replace", "(", "self", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ")", ":", "return", "_datetime", ".", "date", "(", "0", ",", "0", ",", "0", ")" ]
https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/datetime.py#L189-L198