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
assertpy/assertpy
c970c6612a80aa10769dc612324630d27019e1b5
assertpy/helpers.py
python
HelpersMixin._validate_close_to_args
(self, val, other, tolerance)
Helper for validate given arg and delta.
Helper for validate given arg and delta.
[ "Helper", "for", "validate", "given", "arg", "and", "delta", "." ]
def _validate_close_to_args(self, val, other, tolerance): """Helper for validate given arg and delta.""" if type(val) is complex or type(other) is complex or type(tolerance) is complex: raise TypeError('ordering is not defined for complex numbers') if isinstance(val, numbers.Number) is False and type(val) is not datetime.datetime: raise TypeError('val is not numeric or datetime') if type(val) is datetime.datetime: if type(other) is not datetime.datetime: raise TypeError('given arg must be datetime, but was <%s>' % type(other).__name__) if type(tolerance) is not datetime.timedelta: raise TypeError('given tolerance arg must be timedelta, but was <%s>' % type(tolerance).__name__) else: if isinstance(other, numbers.Number) is False: raise TypeError('given arg must be numeric') if isinstance(tolerance, numbers.Number) is False: raise TypeError('given tolerance arg must be numeric') if tolerance < 0: raise ValueError('given tolerance arg must be positive')
[ "def", "_validate_close_to_args", "(", "self", ",", "val", ",", "other", ",", "tolerance", ")", ":", "if", "type", "(", "val", ")", "is", "complex", "or", "type", "(", "other", ")", "is", "complex", "or", "type", "(", "tolerance", ")", "is", "complex",...
https://github.com/assertpy/assertpy/blob/c970c6612a80aa10769dc612324630d27019e1b5/assertpy/helpers.py#L95-L114
bnpy/bnpy
d5b311e8f58ccd98477f4a0c8a4d4982e3fca424
bnpy/obsmodel/MultObsModel.py
python
MultObsModel.calcMargLik
(self, SS)
return self.calcMargLik_CFuncForLoop(SS)
Calc log marginal likelihood combining all comps, given suff stats Returns -------- logM : scalar real logM = \sum_{k=1}^K log p( data assigned to comp k | Prior)
Calc log marginal likelihood combining all comps, given suff stats
[ "Calc", "log", "marginal", "likelihood", "combining", "all", "comps", "given", "suff", "stats" ]
def calcMargLik(self, SS): ''' Calc log marginal likelihood combining all comps, given suff stats Returns -------- logM : scalar real logM = \sum_{k=1}^K log p( data assigned to comp k | Prior) ''' return self.calcMargLik_CFuncForLoop(SS)
[ "def", "calcMargLik", "(", "self", ",", "SS", ")", ":", "return", "self", ".", "calcMargLik_CFuncForLoop", "(", "SS", ")" ]
https://github.com/bnpy/bnpy/blob/d5b311e8f58ccd98477f4a0c8a4d4982e3fca424/bnpy/obsmodel/MultObsModel.py#L512-L520
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/glance/glance/image_cache/drivers/base.py
python
Driver.set_paths
(self)
Creates all necessary directories under the base cache directory
Creates all necessary directories under the base cache directory
[ "Creates", "all", "necessary", "directories", "under", "the", "base", "cache", "directory" ]
def set_paths(self): """ Creates all necessary directories under the base cache directory """ self.base_dir = CONF.image_cache_dir if self.base_dir is None: msg = _('Failed to read %s from config') % 'image_cache_dir' LOG.error(msg) driver = self.__class__.__module__ raise exception.BadDriverConfiguration(driver_name=driver, reason=msg) self.incomplete_dir = os.path.join(self.base_dir, 'incomplete') self.invalid_dir = os.path.join(self.base_dir, 'invalid') self.queue_dir = os.path.join(self.base_dir, 'queue') dirs = [self.incomplete_dir, self.invalid_dir, self.queue_dir] for path in dirs: utils.safe_mkdirs(path)
[ "def", "set_paths", "(", "self", ")", ":", "self", ".", "base_dir", "=", "CONF", ".", "image_cache_dir", "if", "self", ".", "base_dir", "is", "None", ":", "msg", "=", "_", "(", "'Failed to read %s from config'", ")", "%", "'image_cache_dir'", "LOG", ".", "...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/glance/glance/image_cache/drivers/base.py#L49-L69
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/astroprint/api/connection.py
python
connectionState
()
return jsonify({"current": current, "options": pm.getConnectionOptions()})
[]
def connectionState(): pm = printerManager() state, port, baudrate = pm.getCurrentConnection() current = { "state": state, "port": port, "baudrate": baudrate } return jsonify({"current": current, "options": pm.getConnectionOptions()})
[ "def", "connectionState", "(", ")", ":", "pm", "=", "printerManager", "(", ")", "state", ",", "port", ",", "baudrate", "=", "pm", ".", "getCurrentConnection", "(", ")", "current", "=", "{", "\"state\"", ":", "state", ",", "\"port\"", ":", "port", ",", ...
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/api/connection.py#L18-L27
WerWolv/EdiZon_CheatsConfigsAndScripts
d16d36c7509c01dca770f402babd83ff2e9ae6e7
Scripts/lib/python3.5/importlib/_bootstrap.py
python
FrozenImporter.module_repr
(m)
return '<module {!r} (frozen)>'.format(m.__name__)
Return repr for the module. The method is deprecated. The import machinery does the job itself.
Return repr for the module.
[ "Return", "repr", "for", "the", "module", "." ]
def module_repr(m): """Return repr for the module. The method is deprecated. The import machinery does the job itself. """ return '<module {!r} (frozen)>'.format(m.__name__)
[ "def", "module_repr", "(", "m", ")", ":", "return", "'<module {!r} (frozen)>'", ".", "format", "(", "m", ".", "__name__", ")" ]
https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/importlib/_bootstrap.py#L781-L787
espnet/espnet
ea411f3f627b8f101c211e107d0ff7053344ac80
espnet/nets/pytorch_backend/e2e_vc_tacotron2.py
python
Tacotron2.inference
(self, x, inference_args, spemb=None, *args, **kwargs)
Generate the sequence of features given the sequences of characters. Args: x (Tensor): Input sequence of acoustic features (T, idim). inference_args (Namespace): - threshold (float): Threshold in inference. - minlenratio (float): Minimum length ratio in inference. - maxlenratio (float): Maximum length ratio in inference. spemb (Tensor, optional): Speaker embedding vector (spk_embed_dim). Returns: Tensor: Output sequence of features (L, odim). Tensor: Output sequence of stop probabilities (L,). Tensor: Attention weights (L, T).
Generate the sequence of features given the sequences of characters.
[ "Generate", "the", "sequence", "of", "features", "given", "the", "sequences", "of", "characters", "." ]
def inference(self, x, inference_args, spemb=None, *args, **kwargs): """Generate the sequence of features given the sequences of characters. Args: x (Tensor): Input sequence of acoustic features (T, idim). inference_args (Namespace): - threshold (float): Threshold in inference. - minlenratio (float): Minimum length ratio in inference. - maxlenratio (float): Maximum length ratio in inference. spemb (Tensor, optional): Speaker embedding vector (spk_embed_dim). Returns: Tensor: Output sequence of features (L, odim). Tensor: Output sequence of stop probabilities (L,). Tensor: Attention weights (L, T). """ # get options threshold = inference_args.threshold minlenratio = inference_args.minlenratio maxlenratio = inference_args.maxlenratio # thin out input frames for reduction factor # (B, Lmax, idim) -> (B, Lmax // r, idim * r) if self.encoder_reduction_factor > 1: Lmax, idim = x.shape if Lmax % self.encoder_reduction_factor != 0: x = x[: -(Lmax % self.encoder_reduction_factor), :] x_ds = x.contiguous().view( int(Lmax / self.encoder_reduction_factor), idim * self.encoder_reduction_factor, ) else: x_ds = x # inference h = self.enc.inference(x_ds) if self.spk_embed_dim is not None: spemb = F.normalize(spemb, dim=0).unsqueeze(0).expand(h.size(0), -1) h = torch.cat([h, spemb], dim=-1) outs, probs, att_ws = self.dec.inference(h, threshold, minlenratio, maxlenratio) if self.use_cbhg: cbhg_outs = self.cbhg.inference(outs) return cbhg_outs, probs, att_ws else: return outs, probs, att_ws
[ "def", "inference", "(", "self", ",", "x", ",", "inference_args", ",", "spemb", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# get options", "threshold", "=", "inference_args", ".", "threshold", "minlenratio", "=", "inference_args", "...
https://github.com/espnet/espnet/blob/ea411f3f627b8f101c211e107d0ff7053344ac80/espnet/nets/pytorch_backend/e2e_vc_tacotron2.py#L663-L709
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/fmu/v20191213/models.py
python
CancelBeautifyVideoJobRequest.__init__
(self)
r""" :param JobId: 美颜视频的Job id :type JobId: str
r""" :param JobId: 美颜视频的Job id :type JobId: str
[ "r", ":", "param", "JobId", ":", "美颜视频的Job", "id", ":", "type", "JobId", ":", "str" ]
def __init__(self): r""" :param JobId: 美颜视频的Job id :type JobId: str """ self.JobId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "JobId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/fmu/v20191213/models.py#L257-L262
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/mailbox.py
python
_singlefileMailbox.close
(self)
Flush and close the mailbox.
Flush and close the mailbox.
[ "Flush", "and", "close", "the", "mailbox", "." ]
def close(self): """Flush and close the mailbox.""" try: self.flush() finally: try: if self._locked: self.unlock() finally: self._file.close()
[ "def", "close", "(", "self", ")", ":", "try", ":", "self", ".", "flush", "(", ")", "finally", ":", "try", ":", "if", "self", ".", "_locked", ":", "self", ".", "unlock", "(", ")", "finally", ":", "self", ".", "_file", ".", "close", "(", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/mailbox.py#L720-L729
TUDelft-CNS-ATM/bluesky
55a538a3cd936f33cff9df650c38924aa97557b1
bluesky/ui/qtgl/glhelpers.py
python
Rectangle.create
(self, w, h, fill=False)
Create the Rectangle VAO.
Create the Rectangle VAO.
[ "Create", "the", "Rectangle", "VAO", "." ]
def create(self, w, h, fill=False): ''' Create the Rectangle VAO.''' if fill: self.set_primitive_type(gl.GL_TRIANGLE_FAN) vrect = np.array([(-0.5 * h, 0.5 * w), (-0.5 * h, -0.5 * w), (0.5 * h, -0.5 * w), (0.5 * h, 0.5 * w)], dtype=np.float32) super().create(vertex=vrect)
[ "def", "create", "(", "self", ",", "w", ",", "h", ",", "fill", "=", "False", ")", ":", "if", "fill", ":", "self", ".", "set_primitive_type", "(", "gl", ".", "GL_TRIANGLE_FAN", ")", "vrect", "=", "np", ".", "array", "(", "[", "(", "-", "0.5", "*",...
https://github.com/TUDelft-CNS-ATM/bluesky/blob/55a538a3cd936f33cff9df650c38924aa97557b1/bluesky/ui/qtgl/glhelpers.py#L870-L876
pybuilder/pybuilder
12ea2f54e04f97daada375dc3309a3f525f1b5e1
src/main/python/pybuilder/_vendor/pkg_resources/__init__.py
python
invalid_marker
(text)
return False
Validate text as a PEP 508 environment marker; return an exception if invalid or False otherwise.
Validate text as a PEP 508 environment marker; return an exception if invalid or False otherwise.
[ "Validate", "text", "as", "a", "PEP", "508", "environment", "marker", ";", "return", "an", "exception", "if", "invalid", "or", "False", "otherwise", "." ]
def invalid_marker(text): """ Validate text as a PEP 508 environment marker; return an exception if invalid or False otherwise. """ try: evaluate_marker(text) except SyntaxError as e: e.filename = None e.lineno = None return e return False
[ "def", "invalid_marker", "(", "text", ")", ":", "try", ":", "evaluate_marker", "(", "text", ")", "except", "SyntaxError", "as", "e", ":", "e", ".", "filename", "=", "None", "e", ".", "lineno", "=", "None", "return", "e", "return", "False" ]
https://github.com/pybuilder/pybuilder/blob/12ea2f54e04f97daada375dc3309a3f525f1b5e1/src/main/python/pybuilder/_vendor/pkg_resources/__init__.py#L1346-L1357
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
ingest_feed_lambda/pandas/core/internals.py
python
_multi_blockify
(tuples, dtype=None)
return new_blocks
return an array of blocks that potentially have different dtypes
return an array of blocks that potentially have different dtypes
[ "return", "an", "array", "of", "blocks", "that", "potentially", "have", "different", "dtypes" ]
def _multi_blockify(tuples, dtype=None): """ return an array of blocks that potentially have different dtypes """ # group by dtype grouper = itertools.groupby(tuples, lambda x: x[2].dtype) new_blocks = [] for dtype, tup_block in grouper: values, placement = _stack_arrays(list(tup_block), dtype) block = make_block(values, placement=placement) new_blocks.append(block) return new_blocks
[ "def", "_multi_blockify", "(", "tuples", ",", "dtype", "=", "None", ")", ":", "# group by dtype", "grouper", "=", "itertools", ".", "groupby", "(", "tuples", ",", "lambda", "x", ":", "x", "[", "2", "]", ".", "dtype", ")", "new_blocks", "=", "[", "]", ...
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/pandas/core/internals.py#L4764-L4778
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/ui/gui/helpers.py
python
GUISpokeInputCheckHandler.on_password_changed
(self, editable, data=None)
Tell checker that the content of the password field changed.
Tell checker that the content of the password field changed.
[ "Tell", "checker", "that", "the", "content", "of", "the", "password", "field", "changed", "." ]
def on_password_changed(self, editable, data=None): """Tell checker that the content of the password field changed.""" self.checker.password.content = self.password
[ "def", "on_password_changed", "(", "self", ",", "editable", ",", "data", "=", "None", ")", ":", "self", ".", "checker", ".", "password", ".", "content", "=", "self", ".", "password" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/ui/gui/helpers.py#L341-L343
anforaProject/anfora
a8efa2a3039955d2623d003bfc920c5d24641e93
src/managers/notification_manager.py
python
NotificationManager.create_follow_notification
(self, target:UserProfile)
return n
target: The user receiving the notification
target: The user receiving the notification
[ "target", ":", "The", "user", "receiving", "the", "notification" ]
def create_follow_notification(self, target:UserProfile) -> Notification: """ target: The user receiving the notification """ n = Notification.create( target = target, user = self.user, notification_type = 'follow', ) self._notify_user(n) return n
[ "def", "create_follow_notification", "(", "self", ",", "target", ":", "UserProfile", ")", "->", "Notification", ":", "n", "=", "Notification", ".", "create", "(", "target", "=", "target", ",", "user", "=", "self", ".", "user", ",", "notification_type", "=", ...
https://github.com/anforaProject/anfora/blob/a8efa2a3039955d2623d003bfc920c5d24641e93/src/managers/notification_manager.py#L27-L41
NervanaSystems/neon
8c3fb8a93b4a89303467b25817c60536542d08bd
neon/data/convert_manifest.py
python
convert_manifest
(source_manifest, output_manifest)
Converts manifest created for previous aeon versions for use with aeon v1.0+. Args: source_manifest: Path to old manifest output_manifest: Path to save converted manifest.
Converts manifest created for previous aeon versions for use with aeon v1.0+.
[ "Converts", "manifest", "created", "for", "previous", "aeon", "versions", "for", "use", "with", "aeon", "v1", ".", "0", "+", "." ]
def convert_manifest(source_manifest, output_manifest): """ Converts manifest created for previous aeon versions for use with aeon v1.0+. Args: source_manifest: Path to old manifest output_manifest: Path to save converted manifest. """ tmp_manifest = '/tmp/manifest{}'.format(os.getpid()) tmp_dest = open(tmp_manifest, 'w') source = open(source_manifest, 'r') record = source.readline() splited = record.split(',') headerbody = "FILE\t" * len(splited) header = "@" + headerbody[:-1] + '\n' tmp_dest.write(header) record = record.replace(',', '\t') tmp_dest.write(record) for record in source: record = record.replace(',', '\t') tmp_dest.write(record) source.close() tmp_dest.close() if output_manifest is None: output_manifest = source_manifest if os.path.exists(output_manifest): os.remove(output_manifest) shutil.move(tmp_manifest, output_manifest)
[ "def", "convert_manifest", "(", "source_manifest", ",", "output_manifest", ")", ":", "tmp_manifest", "=", "'/tmp/manifest{}'", ".", "format", "(", "os", ".", "getpid", "(", ")", ")", "tmp_dest", "=", "open", "(", "tmp_manifest", ",", "'w'", ")", "source", "=...
https://github.com/NervanaSystems/neon/blob/8c3fb8a93b4a89303467b25817c60536542d08bd/neon/data/convert_manifest.py#L12-L44
dmsimard/ara-archive
8747ff45004fd962337587c7c13d725797cd2d40
ara/config.py
python
_ara_config
(config, key, env_var, default=None, section='ara', value_type=None)
return get_config(config, section, key, env_var, default, **args[value_type])
Wrapper around Ansible's get_config backward/forward compatibility
Wrapper around Ansible's get_config backward/forward compatibility
[ "Wrapper", "around", "Ansible", "s", "get_config", "backward", "/", "forward", "compatibility" ]
def _ara_config(config, key, env_var, default=None, section='ara', value_type=None): """ Wrapper around Ansible's get_config backward/forward compatibility """ if default is None: try: # We're using env_var as keys in the DEFAULTS dict default = DEFAULTS.get(env_var) except KeyError as e: msg = 'There is no default value for {0}: {1}'.format(key, str(e)) raise KeyError(msg) # >= 2.3.0.0 (NOTE: Ansible trunk versioning scheme has 3 digits, not 4) if LooseVersion(ansible_version) >= LooseVersion('2.3.0'): return get_config(config, section, key, env_var, default, value_type=value_type) # < 2.3.0.0 compatibility if value_type is None: return get_config(config, section, key, env_var, default) args = { 'boolean': dict(boolean=True), 'integer': dict(integer=True), 'list': dict(islist=True), 'tmppath': dict(istmppath=True) } return get_config(config, section, key, env_var, default, **args[value_type])
[ "def", "_ara_config", "(", "config", ",", "key", ",", "env_var", ",", "default", "=", "None", ",", "section", "=", "'ara'", ",", "value_type", "=", "None", ")", ":", "if", "default", "is", "None", ":", "try", ":", "# We're using env_var as keys in the DEFAUL...
https://github.com/dmsimard/ara-archive/blob/8747ff45004fd962337587c7c13d725797cd2d40/ara/config.py#L41-L70
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
osh/builtin_comp.py
python
CompAdjust.__init__
(self, mem)
[]
def __init__(self, mem): # type: (Mem) -> None self.mem = mem
[ "def", "__init__", "(", "self", ",", "mem", ")", ":", "# type: (Mem) -> None", "self", ".", "mem", "=", "mem" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/osh/builtin_comp.py#L454-L456
GalSim-developers/GalSim
a05d4ec3b8d8574f99d3b0606ad882cbba53f345
galsim/chromatic.py
python
ChromaticSum.withScaledFlux
(self, flux_ratio)
return new_obj
Multiply the flux of the object by ``flux_ratio`` Parameters: flux_ratio: The factor by which to scale the flux. Returns: the object with the new flux.
Multiply the flux of the object by ``flux_ratio``
[ "Multiply", "the", "flux", "of", "the", "object", "by", "flux_ratio" ]
def withScaledFlux(self, flux_ratio): """Multiply the flux of the object by ``flux_ratio`` Parameters: flux_ratio: The factor by which to scale the flux. Returns: the object with the new flux. """ new_obj = ChromaticSum([ obj.withScaledFlux(flux_ratio) for obj in self.obj_list ]) if hasattr(self, 'covspec'): new_covspec = self.covspec * flux_ratio**2 new_obj.covspec = new_covspec return new_obj
[ "def", "withScaledFlux", "(", "self", ",", "flux_ratio", ")", ":", "new_obj", "=", "ChromaticSum", "(", "[", "obj", ".", "withScaledFlux", "(", "flux_ratio", ")", "for", "obj", "in", "self", ".", "obj_list", "]", ")", "if", "hasattr", "(", "self", ",", ...
https://github.com/GalSim-developers/GalSim/blob/a05d4ec3b8d8574f99d3b0606ad882cbba53f345/galsim/chromatic.py#L2236-L2249
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/http/request.py
python
HttpRequest.xreadlines
(self)
[]
def xreadlines(self): while True: buf = self.readline() if not buf: break yield buf
[ "def", "xreadlines", "(", "self", ")", ":", "while", "True", ":", "buf", "=", "self", ".", "readline", "(", ")", "if", "not", "buf", ":", "break", "yield", "buf" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/http/request.py#L342-L347
lmfit/lmfit-py
47219daa401639831136d39aa472ccee9a712320
lmfit/parameter.py
python
Parameter.expr
(self, val)
Set the mathematical expression used to constrain the value in fit. To remove a constraint you must supply an empty string.
Set the mathematical expression used to constrain the value in fit.
[ "Set", "the", "mathematical", "expression", "used", "to", "constrain", "the", "value", "in", "fit", "." ]
def expr(self, val): """Set the mathematical expression used to constrain the value in fit. To remove a constraint you must supply an empty string. """ self.__set_expression(val)
[ "def", "expr", "(", "self", ",", "val", ")", ":", "self", ".", "__set_expression", "(", "val", ")" ]
https://github.com/lmfit/lmfit-py/blob/47219daa401639831136d39aa472ccee9a712320/lmfit/parameter.py#L839-L845
pympler/pympler
8019a883eec547d91ecda6ba12669d4f4504c625
pympler/refgraph.py
python
ReferenceGraph.reduce_to_cycles
(self)
return self._reduced
Iteratively eliminate leafs to reduce the set of objects to only those that build cycles. Return the reduced graph. If there are no cycles, None is returned.
Iteratively eliminate leafs to reduce the set of objects to only those that build cycles. Return the reduced graph. If there are no cycles, None is returned.
[ "Iteratively", "eliminate", "leafs", "to", "reduce", "the", "set", "of", "objects", "to", "only", "those", "that", "build", "cycles", ".", "Return", "the", "reduced", "graph", ".", "If", "there", "are", "no", "cycles", "None", "is", "returned", "." ]
def reduce_to_cycles(self): """ Iteratively eliminate leafs to reduce the set of objects to only those that build cycles. Return the reduced graph. If there are no cycles, None is returned. """ if not self._reduced: reduced = copy(self) reduced.objects = self.objects[:] reduced.metadata = [] reduced.edges = [] self.num_in_cycles = reduced._reduce_to_cycles() reduced.num_in_cycles = self.num_in_cycles if self.num_in_cycles: reduced._get_edges() reduced._annotate_objects() for meta in reduced.metadata: meta.cycle = True else: reduced = None self._reduced = reduced return self._reduced
[ "def", "reduce_to_cycles", "(", "self", ")", ":", "if", "not", "self", ".", "_reduced", ":", "reduced", "=", "copy", "(", "self", ")", "reduced", ".", "objects", "=", "self", ".", "objects", "[", ":", "]", "reduced", ".", "metadata", "=", "[", "]", ...
https://github.com/pympler/pympler/blob/8019a883eec547d91ecda6ba12669d4f4504c625/pympler/refgraph.py#L121-L142
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/internet/cfreactor.py
python
CFReactor.removeWriter
(self, writer)
Implement L{IReactorFDSet.removeWriter}.
Implement L{IReactorFDSet.removeWriter}.
[ "Implement", "L", "{", "IReactorFDSet", ".", "removeWriter", "}", "." ]
def removeWriter(self, writer): """ Implement L{IReactorFDSet.removeWriter}. """ self._unwatchFD(writer.fileno(), writer, kCFSocketWriteCallBack)
[ "def", "removeWriter", "(", "self", ",", "writer", ")", ":", "self", ".", "_unwatchFD", "(", "writer", ".", "fileno", "(", ")", ",", "writer", ",", "kCFSocketWriteCallBack", ")" ]
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/internet/cfreactor.py#L325-L329
karanchahal/distiller
a17ec06cbeafcdd2aea19d7c7663033c951392f5
distill_archive/research_seed/baselines/rkd_baseline/losses.py
python
HardDarkRank.forward
(self, student, teacher)
return loss
[]
def forward(self, student, teacher): score_teacher = -1 * self.alpha * pdist(teacher, squared=False).pow(self.beta) score_student = -1 * self.alpha * pdist(student, squared=False).pow(self.beta) permute_idx = score_teacher.sort(dim=1, descending=True)[1][:, 1:(self.permute_len+1)] ordered_student = torch.gather(score_student, 1, permute_idx) log_prob = (ordered_student - torch.stack([torch.logsumexp(ordered_student[:, i:], dim=1) for i in range(permute_idx.size(1))], dim=1)).sum(dim=1) loss = (-1 * log_prob).mean() return loss
[ "def", "forward", "(", "self", ",", "student", ",", "teacher", ")", ":", "score_teacher", "=", "-", "1", "*", "self", ".", "alpha", "*", "pdist", "(", "teacher", ",", "squared", "=", "False", ")", ".", "pow", "(", "self", ".", "beta", ")", "score_s...
https://github.com/karanchahal/distiller/blob/a17ec06cbeafcdd2aea19d7c7663033c951392f5/distill_archive/research_seed/baselines/rkd_baseline/losses.py#L78-L88
cournape/Bento
37de23d784407a7c98a4a15770ffc570d5f32d70
bento/private/_simplejson/simplejson/ordered_dict.py
python
OrderedDict.__iter__
(self)
[]
def __iter__(self): end = self.__end curr = end[2] while curr is not end: yield curr[0] curr = curr[2]
[ "def", "__iter__", "(", "self", ")", ":", "end", "=", "self", ".", "__end", "curr", "=", "end", "[", "2", "]", "while", "curr", "is", "not", "end", ":", "yield", "curr", "[", "0", "]", "curr", "=", "curr", "[", "2", "]" ]
https://github.com/cournape/Bento/blob/37de23d784407a7c98a4a15770ffc570d5f32d70/bento/private/_simplejson/simplejson/ordered_dict.py#L49-L54
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/github/Issue.py
python
Issue.title
(self)
return self._title.value
:type: string
:type: string
[ ":", "type", ":", "string" ]
def title(self): """ :type: string """ self._completeIfNotSet(self._title) return self._title.value
[ "def", "title", "(", "self", ")", ":", "self", ".", "_completeIfNotSet", "(", "self", ".", "_title", ")", "return", "self", ".", "_title", ".", "value" ]
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/github/Issue.py#L231-L236
dabeaz-course/practical-python
92a8a73c078e7721d75fd0400e973b44bf7639b8
Solutions/7_11/stock.py
python
Stock.cost
(self)
return self.shares * self.price
Return the cost as shares*price
Return the cost as shares*price
[ "Return", "the", "cost", "as", "shares", "*", "price" ]
def cost(self): ''' Return the cost as shares*price ''' return self.shares * self.price
[ "def", "cost", "(", "self", ")", ":", "return", "self", ".", "shares", "*", "self", ".", "price" ]
https://github.com/dabeaz-course/practical-python/blob/92a8a73c078e7721d75fd0400e973b44bf7639b8/Solutions/7_11/stock.py#L22-L26
qinxuye/cola
9b4803dfef8d91f80c6787dea953bf9f5830818b
cola/core/mq/node.py
python
LocalMessageQueueNode.remove_node
(self, addr)
For the removed node, this method is for the cleaning job including shutting down the backup storage for the removed node.
For the removed node, this method is for the cleaning job including shutting down the backup storage for the removed node.
[ "For", "the", "removed", "node", "this", "method", "is", "for", "the", "cleaning", "job", "including", "shutting", "down", "the", "backup", "storage", "for", "the", "removed", "node", "." ]
def remove_node(self, addr): """ For the removed node, this method is for the cleaning job including shutting down the backup storage for the removed node. """ if addr not in self.addrs: return self.addrs.remove(addr) self.backup_stores[addr].shutdown() del self.backup_stores[addr]
[ "def", "remove_node", "(", "self", ",", "addr", ")", ":", "if", "addr", "not", "in", "self", ".", "addrs", ":", "return", "self", ".", "addrs", ".", "remove", "(", "addr", ")", "self", ".", "backup_stores", "[", "addr", "]", ".", "shutdown", "(", "...
https://github.com/qinxuye/cola/blob/9b4803dfef8d91f80c6787dea953bf9f5830818b/cola/core/mq/node.py#L230-L239
eggnogdb/eggnog-mapper
d6e6cdf0a829f2bd85480f3f3f16e38c213cd091
eggnogmapper/annotation/annotator_worker.py
python
get_member_ogs
(name, eggnog_db)
return ogs
[]
def get_member_ogs(name, eggnog_db): ogs = None match = eggnog_db.get_member_ogs(name) if match is not None and match[0] is not None: ogs = [str(x).strip() for x in match[0].split(',')] return ogs
[ "def", "get_member_ogs", "(", "name", ",", "eggnog_db", ")", ":", "ogs", "=", "None", "match", "=", "eggnog_db", ".", "get_member_ogs", "(", "name", ")", "if", "match", "is", "not", "None", "and", "match", "[", "0", "]", "is", "not", "None", ":", "og...
https://github.com/eggnogdb/eggnog-mapper/blob/d6e6cdf0a829f2bd85480f3f3f16e38c213cd091/eggnogmapper/annotation/annotator_worker.py#L157-L162
enzienaudio/hvcc
30e47328958d600c54889e2a254c3f17f2b2fd06
generators/ir2c/ControlSwitchcase.py
python
ControlSwitchcase.get_C_onMessage
(clazz, obj_type, obj_id, inlet_index, args)
return [ "cSwitchcase_{0}_onMessage(_c, NULL, {1}, m, NULL);".format( obj_id, inlet_index) ]
[]
def get_C_onMessage(clazz, obj_type, obj_id, inlet_index, args): return [ "cSwitchcase_{0}_onMessage(_c, NULL, {1}, m, NULL);".format( obj_id, inlet_index) ]
[ "def", "get_C_onMessage", "(", "clazz", ",", "obj_type", ",", "obj_id", ",", "inlet_index", ",", "args", ")", ":", "return", "[", "\"cSwitchcase_{0}_onMessage(_c, NULL, {1}, m, NULL);\"", ".", "format", "(", "obj_id", ",", "inlet_index", ")", "]" ]
https://github.com/enzienaudio/hvcc/blob/30e47328958d600c54889e2a254c3f17f2b2fd06/generators/ir2c/ControlSwitchcase.py#L38-L43
VingtCinq/python-mailchimp
babf492a4ee14782b0c883ddbbbb15c275655ba9
mailchimp3/entities/listsegmentmembers.py
python
ListSegmentMembers.create
(self, list_id, segment_id, data)
return response
Add a member to a static segment. The documentation does not currently elaborate on the path or request body parameters. Looking at the example provided, it will be assumed that email_address and status are required request body parameters and they are documented and error-checked as such. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param segment_id: The unique id for the segment. :type segment_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "email_address": string*, "status": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending') }
Add a member to a static segment.
[ "Add", "a", "member", "to", "a", "static", "segment", "." ]
def create(self, list_id, segment_id, data): """ Add a member to a static segment. The documentation does not currently elaborate on the path or request body parameters. Looking at the example provided, it will be assumed that email_address and status are required request body parameters and they are documented and error-checked as such. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param segment_id: The unique id for the segment. :type segment_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "email_address": string*, "status": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending') } """ self.list_id = list_id self.segment_id = segment_id if 'email_address' not in data: raise KeyError('The list segment member must have an email_address') check_email(data['email_address']) if 'status' not in data: raise KeyError('The list segment member must have a status') if data['status'] not in ['subscribed', 'unsubscribed', 'cleaned', 'pending']: raise ValueError('The list segment member status must be one of "subscribed", "unsubscribed", "cleaned" or' '"pending"') response = self._mc_client._post(url=self._build_path(list_id, 'segments', segment_id, 'members'), data=data) if response is not None: self.subscriber_hash = response['id'] else: self.subscriber_hash = None return response
[ "def", "create", "(", "self", ",", "list_id", ",", "segment_id", ",", "data", ")", ":", "self", ".", "list_id", "=", "list_id", "self", ".", "segment_id", "=", "segment_id", "if", "'email_address'", "not", "in", "data", ":", "raise", "KeyError", "(", "'T...
https://github.com/VingtCinq/python-mailchimp/blob/babf492a4ee14782b0c883ddbbbb15c275655ba9/mailchimp3/entities/listsegmentmembers.py#L29-L64
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/email/header.py
python
_ValueFormatter._str
(self, linesep)
return linesep.join(self._lines)
[]
def _str(self, linesep): self.newline() return linesep.join(self._lines)
[ "def", "_str", "(", "self", ",", "linesep", ")", ":", "self", ".", "newline", "(", ")", "return", "linesep", ".", "join", "(", "self", ".", "_lines", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/email/header.py#L385-L387
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/gse/v20191112/models.py
python
GetGameServerSessionLogUrlRequest.__init__
(self)
r""" :param GameServerSessionId: 游戏服务器会话ID,最小长度不小于1个ASCII字符,最大长度不超过48个ASCII字符 :type GameServerSessionId: str
r""" :param GameServerSessionId: 游戏服务器会话ID,最小长度不小于1个ASCII字符,最大长度不超过48个ASCII字符 :type GameServerSessionId: str
[ "r", ":", "param", "GameServerSessionId", ":", "游戏服务器会话ID,最小长度不小于1个ASCII字符,最大长度不超过48个ASCII字符", ":", "type", "GameServerSessionId", ":", "str" ]
def __init__(self): r""" :param GameServerSessionId: 游戏服务器会话ID,最小长度不小于1个ASCII字符,最大长度不超过48个ASCII字符 :type GameServerSessionId: str """ self.GameServerSessionId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "GameServerSessionId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/gse/v20191112/models.py#L4135-L4140
qiucheng025/zao-
3a5edf3607b3a523f95746bc69b688090c76d89a
lib/queue_manager.py
python
QueueManager.add_queue
(self, name, maxsize=0, multiprocessing_queue=True)
Add a queue to the manager Adds an event "shutdown" to the queue that can be used to indicate to a process that any activity on the queue should cease
Add a queue to the manager
[ "Add", "a", "queue", "to", "the", "manager" ]
def add_queue(self, name, maxsize=0, multiprocessing_queue=True): """ Add a queue to the manager Adds an event "shutdown" to the queue that can be used to indicate to a process that any activity on the queue should cease """ logger.debug("QueueManager adding: (name: '%s', maxsize: %s)", name, maxsize) if name in self.queues.keys(): raise ValueError("Queue '{}' already exists.".format(name)) if multiprocessing_queue: queue = self.manager.Queue(maxsize=maxsize) else: queue = Queue(maxsize=maxsize) setattr(queue, "shutdown", self.shutdown) self.queues[name] = queue logger.debug("QueueManager added: (name: '%s')", name)
[ "def", "add_queue", "(", "self", ",", "name", ",", "maxsize", "=", "0", ",", "multiprocessing_queue", "=", "True", ")", ":", "logger", ".", "debug", "(", "\"QueueManager adding: (name: '%s', maxsize: %s)\"", ",", "name", ",", "maxsize", ")", "if", "name", "in"...
https://github.com/qiucheng025/zao-/blob/3a5edf3607b3a523f95746bc69b688090c76d89a/lib/queue_manager.py#L40-L57
tensorflow/datasets
2e496976d7d45550508395fb2f35cf958c8a3414
tensorflow_datasets/core/decode/partial_decode.py
python
_normalize_feature_item
( feature: features_lib.FeatureConnector, expected_feature: FeatureSpecs, )
Extract the features matching the expected_feature structure.
Extract the features matching the expected_feature structure.
[ "Extract", "the", "features", "matching", "the", "expected_feature", "structure", "." ]
def _normalize_feature_item( feature: features_lib.FeatureConnector, expected_feature: FeatureSpecs, ) -> FeatureSpecs: """Extract the features matching the expected_feature structure.""" # If user provide a FeatureConnector, use this if isinstance(expected_feature, (features_lib.FeatureConnector, tf.dtypes.DType)): return expected_feature # If the user provide a bool, use the matching feature connector # Example: {'cameras': True} -> `{'camera': FeatureDict({'image': Image()})}` elif isinstance(expected_feature, bool): assert expected_feature # `False` values should have been filtered already return feature # If the user provide a sequence, merge it with the associated feature. elif isinstance(expected_feature, (list, set, dict)): if isinstance(expected_feature, (list, set)): expected_feature = {k: True for k in expected_feature} return _normalize_feature_dict( feature=feature, expected_feature=expected_feature, ) else: raise TypeError(f'Unexpected partial feature spec: {expected_feature!r}')
[ "def", "_normalize_feature_item", "(", "feature", ":", "features_lib", ".", "FeatureConnector", ",", "expected_feature", ":", "FeatureSpecs", ",", ")", "->", "FeatureSpecs", ":", "# If user provide a FeatureConnector, use this", "if", "isinstance", "(", "expected_feature", ...
https://github.com/tensorflow/datasets/blob/2e496976d7d45550508395fb2f35cf958c8a3414/tensorflow_datasets/core/decode/partial_decode.py#L86-L109
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-graalpython/python_cext.py
python
PyTruffle_GetBuiltin
(name)
return getattr(sys.modules["builtins"], name)
[]
def PyTruffle_GetBuiltin(name): return getattr(sys.modules["builtins"], name)
[ "def", "PyTruffle_GetBuiltin", "(", "name", ")", ":", "return", "getattr", "(", "sys", ".", "modules", "[", "\"builtins\"", "]", ",", "name", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-graalpython/python_cext.py#L480-L481
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/collections.py
python
OrderedDict.keys
(self)
return list(self)
od.keys() -> list of keys in od
od.keys() -> list of keys in od
[ "od", ".", "keys", "()", "-", ">", "list", "of", "keys", "in", "od" ]
def keys(self): 'od.keys() -> list of keys in od' return list(self)
[ "def", "keys", "(", "self", ")", ":", "return", "list", "(", "self", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/collections.py#L103-L105
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/msgpack/__init__.py
python
packb
(o, **kwargs)
return Packer(**kwargs).pack(o)
Pack object `o` and return packed bytes See :class:`Packer` for options.
Pack object `o` and return packed bytes
[ "Pack", "object", "o", "and", "return", "packed", "bytes" ]
def packb(o, **kwargs): """ Pack object `o` and return packed bytes See :class:`Packer` for options. """ return Packer(**kwargs).pack(o)
[ "def", "packb", "(", "o", ",", "*", "*", "kwargs", ")", ":", "return", "Packer", "(", "*", "*", "kwargs", ")", ".", "pack", "(", "o", ")" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/msgpack/__init__.py#L29-L35
glue-viz/glue
840b4c1364b0fa63bf67c914540c93dd71df41e1
glue/app/qt/layer_tree_widget.py
python
LayerTreeWidget.is_checkable
(self)
return self.ui.layerTree.checkable
Return whether checkboxes appear next o layers
Return whether checkboxes appear next o layers
[ "Return", "whether", "checkboxes", "appear", "next", "o", "layers" ]
def is_checkable(self): """ Return whether checkboxes appear next o layers""" return self.ui.layerTree.checkable
[ "def", "is_checkable", "(", "self", ")", ":", "return", "self", ".", "ui", ".", "layerTree", ".", "checkable" ]
https://github.com/glue-viz/glue/blob/840b4c1364b0fa63bf67c914540c93dd71df41e1/glue/app/qt/layer_tree_widget.py#L539-L541
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/plat-mac/lib-scriptpackages/Finder/Finder_items.py
python
Finder_items_Events.reveal
(self, _object, _attributes={}, **_arguments)
reveal: Bring the specified object(s) into view Required argument: the object to be made visible Keyword argument _attributes: AppleEvent attribute dictionary
reveal: Bring the specified object(s) into view Required argument: the object to be made visible Keyword argument _attributes: AppleEvent attribute dictionary
[ "reveal", ":", "Bring", "the", "specified", "object", "(", "s", ")", "into", "view", "Required", "argument", ":", "the", "object", "to", "be", "made", "visible", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def reveal(self, _object, _attributes={}, **_arguments): """reveal: Bring the specified object(s) into view Required argument: the object to be made visible Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'misc' _subcode = 'mvis' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "reveal", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'misc'", "_subcode", "=", "'mvis'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "_...
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/plat-mac/lib-scriptpackages/Finder/Finder_items.py#L120-L138
open-mmlab/mmcv
48419395e3220af5b6df78346d6ce58991e8ba90
mmcv/fileio/file_client.py
python
FileClient.parse_uri_prefix
(uri: Union[str, Path])
Parse the prefix of a uri. Args: uri (str | Path): Uri to be parsed that contains the file prefix. Examples: >>> FileClient.parse_uri_prefix('s3://path/of/your/file') 's3' Returns: str | None: Return the prefix of uri if the uri contains '://' else ``None``.
Parse the prefix of a uri.
[ "Parse", "the", "prefix", "of", "a", "uri", "." ]
def parse_uri_prefix(uri: Union[str, Path]) -> Optional[str]: """Parse the prefix of a uri. Args: uri (str | Path): Uri to be parsed that contains the file prefix. Examples: >>> FileClient.parse_uri_prefix('s3://path/of/your/file') 's3' Returns: str | None: Return the prefix of uri if the uri contains '://' else ``None``. """ assert is_filepath(uri) uri = str(uri) if '://' not in uri: return None else: prefix, _ = uri.split('://') # In the case of PetrelBackend, the prefix may contains the cluster # name like clusterName:s3 if ':' in prefix: _, prefix = prefix.split(':') return prefix
[ "def", "parse_uri_prefix", "(", "uri", ":", "Union", "[", "str", ",", "Path", "]", ")", "->", "Optional", "[", "str", "]", ":", "assert", "is_filepath", "(", "uri", ")", "uri", "=", "str", "(", "uri", ")", "if", "'://'", "not", "in", "uri", ":", ...
https://github.com/open-mmlab/mmcv/blob/48419395e3220af5b6df78346d6ce58991e8ba90/mmcv/fileio/file_client.py#L832-L856
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/utils/evtable.py
python
EvCell._center
(self, text, width, pad_char)
Horizontally center text on line of certain width, using padding. Args: text (str): The text to center. width (int): How wide the area is (in characters) where `text` should be centered. pad_char (str): Which padding character to use. Returns: text (str): Centered text.
Horizontally center text on line of certain width, using padding.
[ "Horizontally", "center", "text", "on", "line", "of", "certain", "width", "using", "padding", "." ]
def _center(self, text, width, pad_char): """ Horizontally center text on line of certain width, using padding. Args: text (str): The text to center. width (int): How wide the area is (in characters) where `text` should be centered. pad_char (str): Which padding character to use. Returns: text (str): Centered text. """ excess = width - d_len(text) if excess <= 0: return text if excess % 2: # uneven padding narrowside = (excess // 2) * pad_char widerside = narrowside + pad_char if width % 2: return narrowside + text + widerside else: return widerside + text + narrowside else: # even padding - same on both sides side = (excess // 2) * pad_char return side + text + side
[ "def", "_center", "(", "self", ",", "text", ",", "width", ",", "pad_char", ")", ":", "excess", "=", "width", "-", "d_len", "(", "text", ")", "if", "excess", "<=", "0", ":", "return", "text", "if", "excess", "%", "2", ":", "# uneven padding", "narrows...
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/utils/evtable.py#L546-L574
freedombox/FreedomBox
335a7f92cc08f27981f838a7cddfc67740598e54
plinth/setup.py
python
Helper.run
(self, allow_install=True)
Execute the setup process.
Execute the setup process.
[ "Execute", "the", "setup", "process", "." ]
def run(self, allow_install=True): """Execute the setup process.""" # Setup for the module is already running if self.current_operation: return app = self.module.app current_version = app.get_setup_version() if current_version >= app.info.version: return self.allow_install = allow_install self.exception = None self.current_operation = None self.is_finished = False try: if hasattr(self.module, 'setup'): logger.info('Running module setup - %s', self.module_name) self.module.setup(self, old_version=current_version) else: logger.info('Module does not require setup - %s', self.module_name) except Exception as exception: logger.exception('Error running setup - %s', exception) raise exception else: app.set_setup_version(app.info.version) post_setup.send_robust(sender=self.__class__, module_name=self.module_name) finally: self.is_finished = True self.current_operation = None
[ "def", "run", "(", "self", ",", "allow_install", "=", "True", ")", ":", "# Setup for the module is already running", "if", "self", ".", "current_operation", ":", "return", "app", "=", "self", ".", "module", ".", "app", "current_version", "=", "app", ".", "get_...
https://github.com/freedombox/FreedomBox/blob/335a7f92cc08f27981f838a7cddfc67740598e54/plinth/setup.py#L62-L93
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/flaskbb/plugins/utils.py
python
remove_zombie_plugins_from_db
()
return remove_me
Removes 'zombie' plugins from the db. A zombie plugin is a plugin which exists in the database but isn't installed in the env anymore. Returns the names of the deleted plugins.
Removes 'zombie' plugins from the db. A zombie plugin is a plugin which exists in the database but isn't installed in the env anymore. Returns the names of the deleted plugins.
[ "Removes", "zombie", "plugins", "from", "the", "db", ".", "A", "zombie", "plugin", "is", "a", "plugin", "which", "exists", "in", "the", "database", "but", "isn", "t", "installed", "in", "the", "env", "anymore", ".", "Returns", "the", "names", "of", "the"...
def remove_zombie_plugins_from_db(): """Removes 'zombie' plugins from the db. A zombie plugin is a plugin which exists in the database but isn't installed in the env anymore. Returns the names of the deleted plugins. """ d_fs_plugins = [p[0] for p in current_app.pluggy.list_disabled_plugins()] d_db_plugins = [p.name for p in PluginRegistry.query.filter_by(enabled=False).all()] plugin_names = [p.name for p in PluginRegistry.query.all()] remove_me = [] for p in plugin_names: if p in d_db_plugins and p not in d_fs_plugins: remove_me.append(p) if len(remove_me) > 0: PluginRegistry.query.filter( PluginRegistry.name.in_(remove_me) ).delete(synchronize_session='fetch') db.session.commit() return remove_me
[ "def", "remove_zombie_plugins_from_db", "(", ")", ":", "d_fs_plugins", "=", "[", "p", "[", "0", "]", "for", "p", "in", "current_app", ".", "pluggy", ".", "list_disabled_plugins", "(", ")", "]", "d_db_plugins", "=", "[", "p", ".", "name", "for", "p", "in"...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/flaskbb/plugins/utils.py#L57-L77
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/iotvideoindustry/v20201201/models.py
python
DescribeScenesResponse.__init__
(self)
r""" :param Total: 场景总数 注意:此字段可能返回 null,表示取不到有效值。 :type Total: int :param List: 场景列表 注意:此字段可能返回 null,表示取不到有效值。 :type List: list of SceneItem :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param Total: 场景总数 注意:此字段可能返回 null,表示取不到有效值。 :type Total: int :param List: 场景列表 注意:此字段可能返回 null,表示取不到有效值。 :type List: list of SceneItem :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "Total", ":", "场景总数", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "Total", ":", "int", ":", "param", "List", ":", "场景列表", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "List", ":", "list", "of", "SceneItem", ":", "param", "RequestId", ":...
def __init__(self): r""" :param Total: 场景总数 注意:此字段可能返回 null,表示取不到有效值。 :type Total: int :param List: 场景列表 注意:此字段可能返回 null,表示取不到有效值。 :type List: list of SceneItem :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.Total = None self.List = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Total", "=", "None", "self", ".", "List", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/iotvideoindustry/v20201201/models.py#L4225-L4238
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/requests/models.py
python
PreparedRequest.prepare_cookies
(self, cookies)
Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand.
Prepares the given HTTP cookie data.
[ "Prepares", "the", "given", "HTTP", "cookie", "data", "." ]
def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand.""" if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if cookie_header is not None: self.headers['Cookie'] = cookie_header
[ "def", "prepare_cookies", "(", "self", ",", "cookies", ")", ":", "if", "isinstance", "(", "cookies", ",", "cookielib", ".", "CookieJar", ")", ":", "self", ".", "_cookies", "=", "cookies", "else", ":", "self", ".", "_cookies", "=", "cookiejar_from_dict", "(...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/requests/models.py#L498-L516
robclewley/pydstool
939e3abc9dd1f180d35152bacbde57e24c85ff26
PyDSTool/PyCont/misc.py
python
hess3
(func, x0, ind)
return C
Computes third derivative using hess function.
Computes third derivative using hess function.
[ "Computes", "third", "derivative", "using", "hess", "function", "." ]
def hess3(func, x0, ind): """Computes third derivative using hess function.""" eps = sqrt(1e-3) n = len(x0) m = len(ind) C = zeros((func.m,m,m,m), float) for i in range(m): ei = zeros(n, float) ei[ind[i]] = 1.0 C[i,:,:,:] = (hess(func,x0+eps*ei,ind) - hess(func,x0-eps*ei,ind))/(2*eps) return C
[ "def", "hess3", "(", "func", ",", "x0", ",", "ind", ")", ":", "eps", "=", "sqrt", "(", "1e-3", ")", "n", "=", "len", "(", "x0", ")", "m", "=", "len", "(", "ind", ")", "C", "=", "zeros", "(", "(", "func", ".", "m", ",", "m", ",", "m", ",...
https://github.com/robclewley/pydstool/blob/939e3abc9dd1f180d35152bacbde57e24c85ff26/PyDSTool/PyCont/misc.py#L155-L165
tableau/server-client-python
b3ca20e6765c7cff2d5b095e880dc2b2a811d825
tableauserverclient/_version.py
python
get_keywords
()
return keywords
Get the keywords needed to look up the version information.
Get the keywords needed to look up the version information.
[ "Get", "the", "keywords", "needed", "to", "look", "up", "the", "version", "information", "." ]
def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords
[ "def", "get_keywords", "(", ")", ":", "# these strings will be replaced by git during git-archive.", "# setup.py/versioneer.py will grep for the variable names, so they must", "# each be defined on a line of their own. _version.py will just call", "# get_keywords().", "git_refnames", "=", "\"$...
https://github.com/tableau/server-client-python/blob/b3ca20e6765c7cff2d5b095e880dc2b2a811d825/tableauserverclient/_version.py#L19-L29
postlund/pyatv
4ed1f5539f37d86d80272663d1f2ea34a6c41ec4
pyatv/protocols/companion/__init__.py
python
CompanionRemoteControl.previous
(self)
Press key previous.
Press key previous.
[ "Press", "key", "previous", "." ]
async def previous(self) -> None: """Press key previous.""" await self.api.mediacontrol_command(MediaControlCommand.PreviousTrack)
[ "async", "def", "previous", "(", "self", ")", "->", "None", ":", "await", "self", ".", "api", ".", "mediacontrol_command", "(", "MediaControlCommand", ".", "PreviousTrack", ")" ]
https://github.com/postlund/pyatv/blob/4ed1f5539f37d86d80272663d1f2ea34a6c41ec4/pyatv/protocols/companion/__init__.py#L256-L258
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/idlelib/EditorWindow.py
python
EditorWindow.get_selection_indices
(self)
[]
def get_selection_indices(self): try: first = self.text.index("sel.first") last = self.text.index("sel.last") return first, last except TclError: return None, None
[ "def", "get_selection_indices", "(", "self", ")", ":", "try", ":", "first", "=", "self", ".", "text", ".", "index", "(", "\"sel.first\"", ")", "last", "=", "self", ".", "text", ".", "index", "(", "\"sel.last\"", ")", "return", "first", ",", "last", "ex...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/idlelib/EditorWindow.py#L1193-L1199
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/pdb2pqr/main_cgi.py
python
redirector
(name)
return string
Prints a page which redirects the user to querystatus.cgi and writes starting time to file
Prints a page which redirects the user to querystatus.cgi and writes starting time to file
[ "Prints", "a", "page", "which", "redirects", "the", "user", "to", "querystatus", ".", "cgi", "and", "writes", "starting", "time", "to", "file" ]
def redirector(name): """ Prints a page which redirects the user to querystatus.cgi and writes starting time to file """ utilities.appendToLogFile(name, 'pdb2pqr_start_time', str(time.time())) string = "" string+= "<html>\n" string+= "\t<head>\n" string+= "\t\t<meta http-equiv=\"Refresh\" content=\"0; url=%squerystatus.cgi?jobid=%s&calctype=pdb2pqr\">\n" % (WEBSITE, name) string+= "\t</head>\n" string+= "</html>\n" return string
[ "def", "redirector", "(", "name", ")", ":", "utilities", ".", "appendToLogFile", "(", "name", ",", "'pdb2pqr_start_time'", ",", "str", "(", "time", ".", "time", "(", ")", ")", ")", "string", "=", "\"\"", "string", "+=", "\"<html>\\n\"", "string", "+=", "...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/main_cgi.py#L98-L111
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/commands/default/admin.py
python
CmdBoot.func
(self)
Implementing the function
Implementing the function
[ "Implementing", "the", "function" ]
def func(self): """Implementing the function""" caller = self.caller args = self.args if not args: caller.msg("Usage: boot[/switches] <account> [:reason]") return if ":" in args: args, reason = [a.strip() for a in args.split(":", 1)] else: args, reason = args, "" boot_list = [] if "sid" in self.switches: # Boot a particular session id. sessions = SESSIONS.get_sessions(True) for sess in sessions: # Find the session with the matching session id. if sess.sessid == int(args): boot_list.append(sess) break else: # Boot by account object pobj = search.account_search(args) if not pobj: caller.msg("Account %s was not found." % args) return pobj = pobj[0] if not pobj.access(caller, "boot"): string = "You don't have the permission to boot %s." % (pobj.key,) caller.msg(string) return # we have a bootable object with a connected user matches = SESSIONS.sessions_from_account(pobj) for match in matches: boot_list.append(match) if not boot_list: caller.msg("No matching sessions found. The Account does not seem to be online.") return # Carry out the booting of the sessions in the boot list. feedback = None if "quiet" not in self.switches: feedback = "You have been disconnected by %s.\n" % caller.name if reason: feedback += "\nReason given: %s" % reason for session in boot_list: session.msg(feedback) session.account.disconnect_session_from_account(session) if pobj and boot_list: logger.log_sec( "Booted: %s (Reason: %s, Caller: %s, IP: %s)." % (pobj, reason, caller, self.session.address) )
[ "def", "func", "(", "self", ")", ":", "caller", "=", "self", ".", "caller", "args", "=", "self", ".", "args", "if", "not", "args", ":", "caller", ".", "msg", "(", "\"Usage: boot[/switches] <account> [:reason]\"", ")", "return", "if", "\":\"", "in", "args",...
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/commands/default/admin.py#L51-L111
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/ad_group_label_service/client.py
python
AdGroupLabelServiceClient.common_organization_path
(organization: str,)
return "organizations/{organization}".format(organization=organization,)
Return a fully-qualified organization string.
Return a fully-qualified organization string.
[ "Return", "a", "fully", "-", "qualified", "organization", "string", "." ]
def common_organization_path(organization: str,) -> str: """Return a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,)
[ "def", "common_organization_path", "(", "organization", ":", "str", ",", ")", "->", "str", ":", "return", "\"organizations/{organization}\"", ".", "format", "(", "organization", "=", "organization", ",", ")" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/ad_group_label_service/client.py#L233-L235
tribe29/checkmk
6260f2512e159e311f426e16b84b19d0b8e9ad0c
cmk/gui/plugins/views/utils.py
python
ViewStore.get_instance
(cls)
return cls()
Return the request bound instance
Return the request bound instance
[ "Return", "the", "request", "bound", "instance" ]
def get_instance(cls) -> ViewStore: """Return the request bound instance""" return cls()
[ "def", "get_instance", "(", "cls", ")", "->", "ViewStore", ":", "return", "cls", "(", ")" ]
https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/cmk/gui/plugins/views/utils.py#L1729-L1731
pts/pdfsizeopt
33ec5e5c637fc8967d6d238dfdaf8c55605efe83
lib/pdfsizeopt/main.py
python
PdfObj.ResolveReferencesChanged
(cls, data, objs, do_strings=False)
return data2, data2 != data
Resolve references (<x> <y> R) in a PDF token sequence. Like ResolveReferences, but returns has_changed as well. Returns: (new_data, has_changed). has_changed may be True even if there were no references found, but comments were removed.
Resolve references (<x> <y> R) in a PDF token sequence.
[ "Resolve", "references", "(", "<x", ">", "<y", ">", "R", ")", "in", "a", "PDF", "token", "sequence", "." ]
def ResolveReferencesChanged(cls, data, objs, do_strings=False): """Resolve references (<x> <y> R) in a PDF token sequence. Like ResolveReferences, but returns has_changed as well. Returns: (new_data, has_changed). has_changed may be True even if there were no references found, but comments were removed. """ if not isinstance(data, str): return data, False data2 = cls.ResolveReferences(data, objs, do_strings) return data2, data2 != data
[ "def", "ResolveReferencesChanged", "(", "cls", ",", "data", ",", "objs", ",", "do_strings", "=", "False", ")", ":", "if", "not", "isinstance", "(", "data", ",", "str", ")", ":", "return", "data", ",", "False", "data2", "=", "cls", ".", "ResolveReferences...
https://github.com/pts/pdfsizeopt/blob/33ec5e5c637fc8967d6d238dfdaf8c55605efe83/lib/pdfsizeopt/main.py#L3764-L3776
oauthlib/oauthlib
553850bc85dfd408be0dae9884b4a0aefda8e579
oauthlib/oauth1/rfc5849/endpoints/base.py
python
BaseEndpoint._get_signature_type_and_params
(self, request)
return signature_type, params, oauth_params
Extracts parameters from query, headers and body. Signature type is set to the source in which parameters were found.
Extracts parameters from query, headers and body. Signature type is set to the source in which parameters were found.
[ "Extracts", "parameters", "from", "query", "headers", "and", "body", ".", "Signature", "type", "is", "set", "to", "the", "source", "in", "which", "parameters", "were", "found", "." ]
def _get_signature_type_and_params(self, request): """Extracts parameters from query, headers and body. Signature type is set to the source in which parameters were found. """ # Per RFC5849, only the Authorization header may contain the 'realm' # optional parameter. header_params = signature.collect_parameters(headers=request.headers, exclude_oauth_signature=False, with_realm=True) body_params = signature.collect_parameters(body=request.body, exclude_oauth_signature=False) query_params = signature.collect_parameters(uri_query=request.uri_query, exclude_oauth_signature=False) params = [] params.extend(header_params) params.extend(body_params) params.extend(query_params) signature_types_with_oauth_params = list(filter(lambda s: s[2], ( (SIGNATURE_TYPE_AUTH_HEADER, params, utils.filter_oauth_params(header_params)), (SIGNATURE_TYPE_BODY, params, utils.filter_oauth_params(body_params)), (SIGNATURE_TYPE_QUERY, params, utils.filter_oauth_params(query_params)) ))) if len(signature_types_with_oauth_params) > 1: found_types = [s[0] for s in signature_types_with_oauth_params] raise errors.InvalidRequestError( description=('oauth_ params must come from only 1 signature' 'type but were found in %s', ', '.join(found_types))) try: signature_type, params, oauth_params = signature_types_with_oauth_params[ 0] except IndexError: raise errors.InvalidRequestError( description='Missing mandatory OAuth parameters.') return signature_type, params, oauth_params
[ "def", "_get_signature_type_and_params", "(", "self", ",", "request", ")", ":", "# Per RFC5849, only the Authorization header may contain the 'realm'", "# optional parameter.", "header_params", "=", "signature", ".", "collect_parameters", "(", "headers", "=", "request", ".", ...
https://github.com/oauthlib/oauthlib/blob/553850bc85dfd408be0dae9884b4a0aefda8e579/oauthlib/oauth1/rfc5849/endpoints/base.py#L28-L68
OpenCobolIDE/OpenCobolIDE
c78d0d335378e5fe0a5e74f53c19b68b55e85388
open_cobol_ide/extlibs/pyqode/core/widgets/_pty.py
python
spawn
(argv, master_read=_read, stdin_read=_read)
return os.waitpid(pid, 0)[1]
Create a spawned process.
Create a spawned process.
[ "Create", "a", "spawned", "process", "." ]
def spawn(argv, master_read=_read, stdin_read=_read): """Create a spawned process.""" if type(argv) == type(''): argv = (argv,) pid, master_fd = fork() if pid == CHILD: try: os.execlp(argv[0], *argv) except: # If we wanted to be really clever, we would use # the same method as subprocess() to pass the error # back to the parent. For now just dump stack trace. traceback.print_exc() finally: os._exit(1) try: mode = tty.tcgetattr(STDIN_FILENO) tty.setraw(STDIN_FILENO) restore = 1 except tty.error: # This is the same as termios.error restore = 0 try: _copy(master_fd, master_read, stdin_read) except OSError: # Some OSes never return an EOF on pty, just raise # an error instead. pass finally: if restore: tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode) os.close(master_fd) return os.waitpid(pid, 0)[1]
[ "def", "spawn", "(", "argv", ",", "master_read", "=", "_read", ",", "stdin_read", "=", "_read", ")", ":", "if", "type", "(", "argv", ")", "==", "type", "(", "''", ")", ":", "argv", "=", "(", "argv", ",", ")", "pid", ",", "master_fd", "=", "fork",...
https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/pyqode/core/widgets/_pty.py#L150-L182
ppizarror/pygame-menu
da5827a1ad0686e8ff2aa536b74bbfba73967bcf
pygame_menu/widgets/widget/textinput.py
python
TextInput._check_input_size
(self)
return self._maxchar <= len(self._input_string)
Check input size. :return: ``True`` if the input must be limited
Check input size.
[ "Check", "input", "size", "." ]
def _check_input_size(self) -> bool: """ Check input size. :return: ``True`` if the input must be limited """ if self._maxchar == 0: return False return self._maxchar <= len(self._input_string)
[ "def", "_check_input_size", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_maxchar", "==", "0", ":", "return", "False", "return", "self", ".", "_maxchar", "<=", "len", "(", "self", ".", "_input_string", ")" ]
https://github.com/ppizarror/pygame-menu/blob/da5827a1ad0686e8ff2aa536b74bbfba73967bcf/pygame_menu/widgets/widget/textinput.py#L1104-L1112
lykops/lykchat
9efe12ad5a4fa079f700b183476a4c7b3322e135
library/storage/database/mongo.py
python
Op_Mongo._handler_condition
(self, condition_dict)
return condition_dict
在查询或更新数据时,对查询条件进行处理
在查询或更新数据时,对查询条件进行处理
[ "在查询或更新数据时,对查询条件进行处理" ]
def _handler_condition(self, condition_dict): ''' 在查询或更新数据时,对查询条件进行处理 ''' condition_dict = dot2_(condition_dict) for k, v in condition_dict.items() : if k == '_id' : # 把_id的值进行转化 if isinstance(v, str) : try : v = int(v) except : v = ObjectId(v) condition_dict[k] = v return condition_dict
[ "def", "_handler_condition", "(", "self", ",", "condition_dict", ")", ":", "condition_dict", "=", "dot2_", "(", "condition_dict", ")", "for", "k", ",", "v", "in", "condition_dict", ".", "items", "(", ")", ":", "if", "k", "==", "'_id'", ":", "# 把_id的值进行转化",...
https://github.com/lykops/lykchat/blob/9efe12ad5a4fa079f700b183476a4c7b3322e135/library/storage/database/mongo.py#L159-L175
almarklein/visvis
766ed97767b44a55a6ff72c742d7385e074d3d55
core/cameras.py
python
ThreeDCamera.OnResize
(self, event)
OnResize(event) Callback that adjusts the daspect (if axes.daspectAuto is True) when the window dimensions change.
OnResize(event) Callback that adjusts the daspect (if axes.daspectAuto is True) when the window dimensions change.
[ "OnResize", "(", "event", ")", "Callback", "that", "adjusts", "the", "daspect", "(", "if", "axes", ".", "daspectAuto", "is", "True", ")", "when", "the", "window", "dimensions", "change", "." ]
def OnResize(self, event): """ OnResize(event) Callback that adjusts the daspect (if axes.daspectAuto is True) when the window dimensions change. """ # Get new size factor w,h = self.axes.position.size sizeFactor1 = float(h) / w # Get old size factor sizeFactor2 = self._windowSizeFactor # Make it quick if daspect is not in auto-mode if not self.axes.daspectAuto: self._windowSizeFactor = sizeFactor1 return # Get daspect factor daspectFactor = sizeFactor1 if sizeFactor2: daspectFactor /= sizeFactor2 # Set size factor for next time self._windowSizeFactor = sizeFactor1 # Change daspect. Zoom is never changed self._SetDaspect(daspectFactor, 2, 2)
[ "def", "OnResize", "(", "self", ",", "event", ")", ":", "# Get new size factor", "w", ",", "h", "=", "self", ".", "axes", ".", "position", ".", "size", "sizeFactor1", "=", "float", "(", "h", ")", "/", "w", "# Get old size factor", "sizeFactor2", "=", "se...
https://github.com/almarklein/visvis/blob/766ed97767b44a55a6ff72c742d7385e074d3d55/core/cameras.py#L851-L880
tensorwerk/hangar-py
a6deb22854a6c9e9709011b91c1c0eeda7f47bb0
src/hangar/repository.py
python
Repository.force_release_writer_lock
(self)
return success
Force release the lock left behind by an unclosed writer-checkout .. warning:: *NEVER USE THIS METHOD IF WRITER PROCESS IS CURRENTLY ACTIVE.* At the time of writing, the implications of improper/malicious use of this are not understood, and there is a a risk of of undefined behavior or (potentially) data corruption. At the moment, the responsibility to close a write-enabled checkout is placed entirely on the user. If the `close()` method is not called before the program terminates, a new checkout with write=True will fail. The lock can only be released via a call to this method. .. note:: This entire mechanism is subject to review/replacement in the future. Returns ------- bool if the operation was successful.
Force release the lock left behind by an unclosed writer-checkout
[ "Force", "release", "the", "lock", "left", "behind", "by", "an", "unclosed", "writer", "-", "checkout" ]
def force_release_writer_lock(self) -> bool: """Force release the lock left behind by an unclosed writer-checkout .. warning:: *NEVER USE THIS METHOD IF WRITER PROCESS IS CURRENTLY ACTIVE.* At the time of writing, the implications of improper/malicious use of this are not understood, and there is a a risk of of undefined behavior or (potentially) data corruption. At the moment, the responsibility to close a write-enabled checkout is placed entirely on the user. If the `close()` method is not called before the program terminates, a new checkout with write=True will fail. The lock can only be released via a call to this method. .. note:: This entire mechanism is subject to review/replacement in the future. Returns ------- bool if the operation was successful. """ self.__verify_repo_initialized() forceReleaseSentinal = parsing.repo_writer_lock_force_release_sentinal() success = heads.release_writer_lock(self._env.branchenv, forceReleaseSentinal) return success
[ "def", "force_release_writer_lock", "(", "self", ")", "->", "bool", ":", "self", ".", "__verify_repo_initialized", "(", ")", "forceReleaseSentinal", "=", "parsing", ".", "repo_writer_lock_force_release_sentinal", "(", ")", "success", "=", "heads", ".", "release_writer...
https://github.com/tensorwerk/hangar-py/blob/a6deb22854a6c9e9709011b91c1c0eeda7f47bb0/src/hangar/repository.py#L816-L843
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/django_opentracing-1.1.0/versioneer.py
python
render_git_describe_long
(pieces)
return rendered
TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
TAG-DISTANCE-gHEX[-dirty].
[ "TAG", "-", "DISTANCE", "-", "gHEX", "[", "-", "dirty", "]", "." ]
def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered
[ "def", "render_git_describe_long", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "rendered", "+=", "\"-%d-g%s\"", "%", "(", "pieces", "[", "\"distance\"", "]", ",", "pieces", ...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/django_opentracing-1.1.0/versioneer.py#L1346-L1363
tlsfuzzer/tlsfuzzer
fe2e4af145446d603a9da2e202e10ea80ccd298d
tlsfuzzer/analysis.py
python
Analysis.ecdf_plot
(self)
Generate ECDF plot comparing distributions of the test classes.
Generate ECDF plot comparing distributions of the test classes.
[ "Generate", "ECDF", "plot", "comparing", "distributions", "of", "the", "test", "classes", "." ]
def ecdf_plot(self): """Generate ECDF plot comparing distributions of the test classes.""" if not self.draw_ecdf_plot: return None data = self.load_data() fig = Figure(figsize=(16, 12)) canvas = FigureCanvas(fig) ax = fig.add_subplot(1, 1, 1) for classname in data: values = data.loc[:, classname] levels = np.linspace(1. / len(values), 1, len(values)) ax.step(sorted(values), levels, where='post') self.make_legend(ax) ax.set_title("Empirical Cumulative Distribution Function") ax.set_xlabel("Time [s]") ax.set_ylabel("Cumulative probability") canvas.print_figure(join(self.output, "ecdf_plot.png"), bbox_inches="tight") quant = np.quantile(values, [0.01, 0.95]) quant[0] *= 0.98 quant[1] *= 1.02 ax.set_xlim(quant) canvas.print_figure(join(self.output, "ecdf_plot_zoom_in.png"), bbox_inches="tight")
[ "def", "ecdf_plot", "(", "self", ")", ":", "if", "not", "self", ".", "draw_ecdf_plot", ":", "return", "None", "data", "=", "self", ".", "load_data", "(", ")", "fig", "=", "Figure", "(", "figsize", "=", "(", "16", ",", "12", ")", ")", "canvas", "=",...
https://github.com/tlsfuzzer/tlsfuzzer/blob/fe2e4af145446d603a9da2e202e10ea80ccd298d/tlsfuzzer/analysis.py#L440-L463
firewalld/firewalld
368e5a1e3eeff21ed55d4f2549836d45d8636ab5
src/firewall/server/config.py
python
FirewallDConfig.addService2
(self, service, settings, sender=None)
return config_service
add service with given name and settings
add service with given name and settings
[ "add", "service", "with", "given", "name", "and", "settings" ]
def addService2(self, service, settings, sender=None): """add service with given name and settings """ service = dbus_to_python(service, str) settings = dbus_to_python(settings) log.debug1("config.addService2('%s')", service) self.accessCheck(sender) obj = self.config.new_service_dict(service, settings) config_service = self._addService(obj) return config_service
[ "def", "addService2", "(", "self", ",", "service", ",", "settings", ",", "sender", "=", "None", ")", ":", "service", "=", "dbus_to_python", "(", "service", ",", "str", ")", "settings", "=", "dbus_to_python", "(", "settings", ")", "log", ".", "debug1", "(...
https://github.com/firewalld/firewalld/blob/368e5a1e3eeff21ed55d4f2549836d45d8636ab5/src/firewall/server/config.py#L1157-L1166
akanazawa/human_dynamics
0887f37464c9a079ad7d69c8358cecd0f43c4f2a
src/omega.py
python
OmegasPred.set_cams
(self, cams)
Only used for opt_cam
Only used for opt_cam
[ "Only", "used", "for", "opt_cam" ]
def set_cams(self, cams): """ Only used for opt_cam """ assert self.use_optcam self.cams = cams
[ "def", "set_cams", "(", "self", ",", "cams", ")", ":", "assert", "self", ".", "use_optcam", "self", ".", "cams", "=", "cams" ]
https://github.com/akanazawa/human_dynamics/blob/0887f37464c9a079ad7d69c8358cecd0f43c4f2a/src/omega.py#L318-L323
espnet/espnet
ea411f3f627b8f101c211e107d0ff7053344ac80
espnet/optimizer/chainer.py
python
SGDFactory.from_args
(target, args: argparse.Namespace)
return opt
Initialize optimizer from argparse Namespace. Args: target: for pytorch `model.parameters()`, for chainer `model` args (argparse.Namespace): parsed command-line args
Initialize optimizer from argparse Namespace.
[ "Initialize", "optimizer", "from", "argparse", "Namespace", "." ]
def from_args(target, args: argparse.Namespace): """Initialize optimizer from argparse Namespace. Args: target: for pytorch `model.parameters()`, for chainer `model` args (argparse.Namespace): parsed command-line args """ opt = chainer.optimizers.SGD( lr=args.lr, ) opt.setup(target) opt.add_hook(WeightDecay(args.weight_decay)) return opt
[ "def", "from_args", "(", "target", ",", "args", ":", "argparse", ".", "Namespace", ")", ":", "opt", "=", "chainer", ".", "optimizers", ".", "SGD", "(", "lr", "=", "args", ".", "lr", ",", ")", "opt", ".", "setup", "(", "target", ")", "opt", ".", "...
https://github.com/espnet/espnet/blob/ea411f3f627b8f101c211e107d0ff7053344ac80/espnet/optimizer/chainer.py#L50-L64
frappe/frappe
b64cab6867dfd860f10ccaf41a4ec04bc890b583
frappe/core/doctype/file/file.py
python
delete_file
(path)
Delete file from `public folder`
Delete file from `public folder`
[ "Delete", "file", "from", "public", "folder" ]
def delete_file(path): """Delete file from `public folder`""" if path: if ".." in path.split("/"): frappe.msgprint(_("It is risky to delete this file: {0}. Please contact your System Manager.").format(path)) parts = os.path.split(path.strip("/")) if parts[0]=="files": path = frappe.utils.get_site_path("public", "files", parts[-1]) else: path = frappe.utils.get_site_path("private", "files", parts[-1]) path = encode(path) if os.path.exists(path): os.remove(path)
[ "def", "delete_file", "(", "path", ")", ":", "if", "path", ":", "if", "\"..\"", "in", "path", ".", "split", "(", "\"/\"", ")", ":", "frappe", ".", "msgprint", "(", "_", "(", "\"It is risky to delete this file: {0}. Please contact your System Manager.\"", ")", "....
https://github.com/frappe/frappe/blob/b64cab6867dfd860f10ccaf41a4ec04bc890b583/frappe/core/doctype/file/file.py#L730-L745
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_pt_objects.py
python
ConvBertForMaskedLM.forward
(self, *args, **kwargs)
[]
def forward(self, *args, **kwargs): requires_backends(self, ["torch"])
[ "def", "forward", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "self", ",", "[", "\"torch\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L1463-L1464
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/relay/op/transform.py
python
expand_dims
(data, axis, num_newaxis=1)
Insert `num_newaxis` axes at the position given by `axis`. Parameters ---------- data : relay.Expr The input data to the operator. axis : Union[int, Expr] The axis at which the input array is expanded. Should lie in range `[-data.ndim - 1, data.ndim]`. If `axis < 0`, it is the first axis inserted; If `axis >= 0`, it is the last axis inserted in Python's negative indexing. num_newaxis : int Number of axes to be inserted. Should be >= 0. Returns ------- result : relay.Expr The reshaped result.
Insert `num_newaxis` axes at the position given by `axis`.
[ "Insert", "num_newaxis", "axes", "at", "the", "position", "given", "by", "axis", "." ]
def expand_dims(data, axis, num_newaxis=1): """Insert `num_newaxis` axes at the position given by `axis`. Parameters ---------- data : relay.Expr The input data to the operator. axis : Union[int, Expr] The axis at which the input array is expanded. Should lie in range `[-data.ndim - 1, data.ndim]`. If `axis < 0`, it is the first axis inserted; If `axis >= 0`, it is the last axis inserted in Python's negative indexing. num_newaxis : int Number of axes to be inserted. Should be >= 0. Returns ------- result : relay.Expr The reshaped result. """ if isinstance(axis, int): return _make.expand_dims(data, axis, num_newaxis) if isinstance(axis, Expr): # TODO (AndrewZhaoLuo): investigate performance issues with consecutive # dynamic expand_dims on non-llvm targets. return _dyn_make.expand_dims(data, axis, num_newaxis) raise ValueError(f"Unknown type for axis: {type(axis)}")
[ "def", "expand_dims", "(", "data", ",", "axis", ",", "num_newaxis", "=", "1", ")", ":", "if", "isinstance", "(", "axis", ",", "int", ")", ":", "return", "_make", ".", "expand_dims", "(", "data", ",", "axis", ",", "num_newaxis", ")", "if", "isinstance",...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/relay/op/transform.py#L149-L177
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/myq/light.py
python
MyQLight.is_on
(self)
return MYQ_TO_HASS.get(self._device.state) == STATE_ON
Return true if the light is on, else False.
Return true if the light is on, else False.
[ "Return", "true", "if", "the", "light", "is", "on", "else", "False", "." ]
def is_on(self): """Return true if the light is on, else False.""" return MYQ_TO_HASS.get(self._device.state) == STATE_ON
[ "def", "is_on", "(", "self", ")", ":", "return", "MYQ_TO_HASS", ".", "get", "(", "self", ".", "_device", ".", "state", ")", "==", "STATE_ON" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/myq/light.py#L36-L38
django-nonrel/django-nonrel
4fbfe7344481a5eab8698f79207f09124310131b
django/contrib/contenttypes/generic.py
python
GenericRelation.extra_filters
(self, pieces, pos, negate)
return [("%s__%s" % (prefix, self.content_type_field_name), content_type)]
Return an extra filter to the queryset so that the results are filtered on the appropriate content type.
Return an extra filter to the queryset so that the results are filtered on the appropriate content type.
[ "Return", "an", "extra", "filter", "to", "the", "queryset", "so", "that", "the", "results", "are", "filtered", "on", "the", "appropriate", "content", "type", "." ]
def extra_filters(self, pieces, pos, negate): """ Return an extra filter to the queryset so that the results are filtered on the appropriate content type. """ if negate: return [] ContentType = get_model("contenttypes", "contenttype") content_type = ContentType.objects.get_for_model(self.model) prefix = "__".join(pieces[:pos + 1]) return [("%s__%s" % (prefix, self.content_type_field_name), content_type)]
[ "def", "extra_filters", "(", "self", ",", "pieces", ",", "pos", ",", "negate", ")", ":", "if", "negate", ":", "return", "[", "]", "ContentType", "=", "get_model", "(", "\"contenttypes\"", ",", "\"contenttype\"", ")", "content_type", "=", "ContentType", ".", ...
https://github.com/django-nonrel/django-nonrel/blob/4fbfe7344481a5eab8698f79207f09124310131b/django/contrib/contenttypes/generic.py#L167-L178
pengming617/bert_textMatching
b79c9110447b0eef2c1919bf8bf3c8e3656900a8
modeling.py
python
BertConfig.__init__
(self, vocab_size, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, initializer_range=0.02)
Constructs BertConfig. Args: vocab_size: Vocabulary size of `inputs_ids` in `BertModel`. hidden_size: Size of the encoder layers and the pooler layer. num_hidden_layers: Number of hidden layers in the Transformer encoder. num_attention_heads: Number of attention heads for each attention layer in the Transformer encoder. intermediate_size: The size of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act: The non-linear activation function (function or string) in the encoder and pooler. hidden_dropout_prob: The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob: The dropout ratio for the attention probabilities. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size: The vocabulary size of the `token_type_ids` passed into `BertModel`. initializer_range: The stdev of the truncated_normal_initializer for initializing all weight matrices.
Constructs BertConfig.
[ "Constructs", "BertConfig", "." ]
def __init__(self, vocab_size, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, initializer_range=0.02): """Constructs BertConfig. Args: vocab_size: Vocabulary size of `inputs_ids` in `BertModel`. hidden_size: Size of the encoder layers and the pooler layer. num_hidden_layers: Number of hidden layers in the Transformer encoder. num_attention_heads: Number of attention heads for each attention layer in the Transformer encoder. intermediate_size: The size of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act: The non-linear activation function (function or string) in the encoder and pooler. hidden_dropout_prob: The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob: The dropout ratio for the attention probabilities. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size: The vocabulary size of the `token_type_ids` passed into `BertModel`. initializer_range: The stdev of the truncated_normal_initializer for initializing all weight matrices. """ self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range
[ "def", "__init__", "(", "self", ",", "vocab_size", ",", "hidden_size", "=", "768", ",", "num_hidden_layers", "=", "12", ",", "num_attention_heads", "=", "12", ",", "intermediate_size", "=", "3072", ",", "hidden_act", "=", "\"gelu\"", ",", "hidden_dropout_prob", ...
https://github.com/pengming617/bert_textMatching/blob/b79c9110447b0eef2c1919bf8bf3c8e3656900a8/modeling.py#L33-L79
BillBillBillBill/Tickeys-linux
2df31b8665004c58a5d4ab05277f245267d96364
tickeys/kivy/support.py
python
install_android
()
Install hooks for the android platform. * Automatically sleep when the device is paused. * Automatically kill the application when the return key is pressed.
Install hooks for the android platform.
[ "Install", "hooks", "for", "the", "android", "platform", "." ]
def install_android(): '''Install hooks for the android platform. * Automatically sleep when the device is paused. * Automatically kill the application when the return key is pressed. ''' try: import android except ImportError: print('Android lib is missing, cannot install android hooks') return from kivy.clock import Clock from kivy.logger import Logger import pygame Logger.info('Support: Android install hooks') # Init the library android.init() android.map_key(android.KEYCODE_MENU, pygame.K_MENU) android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) # Check if android should be paused or not. # If pause is requested, just leave the app. def android_check_pause(*largs): # do nothing until android asks for it. if not android.check_pause(): return from kivy.app import App from kivy.base import stopTouchApp from kivy.logger import Logger from kivy.core.window import Window global g_android_redraw_count # try to get the current running application Logger.info('Android: Must go into sleep mode, check the app') app = App.get_running_app() # no running application, stop our loop. if app is None: Logger.info('Android: No app running, stop everything.') stopTouchApp() return # try to go to pause mode if app.dispatch('on_pause'): Logger.info('Android: App paused, now wait for resume.') # app goes in pause mode, wait. android.wait_for_resume() # is it a stop or resume ? if android.check_stop(): # app must stop Logger.info('Android: Android wants to close our app.') stopTouchApp() else: # app resuming now ! Logger.info('Android: Android has resumed, resume the app.') app.dispatch('on_resume') Window.canvas.ask_update() g_android_redraw_count = 25 # 5 frames/seconds for 5 seconds Clock.unschedule(_android_ask_redraw) Clock.schedule_interval(_android_ask_redraw, 1 / 5) Logger.info('Android: App resume completed.') # app doesn't support pause mode, just stop it. else: Logger.info('Android: App doesn\'t support pause mode, stop.') stopTouchApp() Clock.schedule_interval(android_check_pause, 0)
[ "def", "install_android", "(", ")", ":", "try", ":", "import", "android", "except", "ImportError", ":", "print", "(", "'Android lib is missing, cannot install android hooks'", ")", "return", "from", "kivy", ".", "clock", "import", "Clock", "from", "kivy", ".", "lo...
https://github.com/BillBillBillBill/Tickeys-linux/blob/2df31b8665004c58a5d4ab05277f245267d96364/tickeys/kivy/support.py#L64-L137
DonnchaC/shadowbrokers-exploits
42d8265db860b634717da4faa668b2670457cf7e
windows/fuzzbunch/env.py
python
setup_lib_paths
(fbdir, libdir)
This is a little bit of a hack, but it should work. If we detect that the EDFLIB_DIR is not in LD_LIBRARY_PATH, restart after adding it.
This is a little bit of a hack, but it should work. If we detect that the EDFLIB_DIR is not in LD_LIBRARY_PATH, restart after adding it.
[ "This", "is", "a", "little", "bit", "of", "a", "hack", "but", "it", "should", "work", ".", "If", "we", "detect", "that", "the", "EDFLIB_DIR", "is", "not", "in", "LD_LIBRARY_PATH", "restart", "after", "adding", "it", "." ]
def setup_lib_paths(fbdir, libdir): """This is a little bit of a hack, but it should work. If we detect that the EDFLIB_DIR is not in LD_LIBRARY_PATH, restart after adding it. """ try: libpath = os.environ['LD_LIBRARY_PATH'] except KeyError: libpath = "" if not (sys.platform == "win32") and (libdir not in libpath): # To get the Fuzzbunch environment setup properly, we need to modify LD_LIBRARY_PATH. # To do that, we need to rerun Fuzzbunch so that it picks up the new LD_LIBRARY_PATH os.environ['LD_LIBRARY_PATH'] = "%s:%s" % (libdir,libpath)
[ "def", "setup_lib_paths", "(", "fbdir", ",", "libdir", ")", ":", "try", ":", "libpath", "=", "os", ".", "environ", "[", "'LD_LIBRARY_PATH'", "]", "except", "KeyError", ":", "libpath", "=", "\"\"", "if", "not", "(", "sys", ".", "platform", "==", "\"win32\...
https://github.com/DonnchaC/shadowbrokers-exploits/blob/42d8265db860b634717da4faa668b2670457cf7e/windows/fuzzbunch/env.py#L44-L55
brython-dev/brython
9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3
www/src/Lib/genericpath.py
python
isfile
(path)
return stat.S_ISREG(st.st_mode)
Test whether a path is a regular file
Test whether a path is a regular file
[ "Test", "whether", "a", "path", "is", "a", "regular", "file" ]
def isfile(path): """Test whether a path is a regular file""" try: st = os.stat(path) except (OSError, ValueError): return False return stat.S_ISREG(st.st_mode)
[ "def", "isfile", "(", "path", ")", ":", "try", ":", "st", "=", "os", ".", "stat", "(", "path", ")", "except", "(", "OSError", ",", "ValueError", ")", ":", "return", "False", "return", "stat", ".", "S_ISREG", "(", "st", ".", "st_mode", ")" ]
https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/genericpath.py#L27-L33
sqall01/alertR
e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13
alertClientRaspberryPi/lib/client/util.py
python
MsgBuilder.build_auth_msg
(username: str, password: str, version: float, rev: int, regMessageSize: int)
return json.dumps(message)
Internal function that builds the client authentication message. :param username: :param password: :param version: :param rev: :param regMessageSize: :return:
Internal function that builds the client authentication message.
[ "Internal", "function", "that", "builds", "the", "client", "authentication", "message", "." ]
def build_auth_msg(username: str, password: str, version: float, rev: int, regMessageSize: int) -> str: """ Internal function that builds the client authentication message. :param username: :param password: :param version: :param rev: :param regMessageSize: :return: """ payload = {"type": "request", "version": version, "rev": rev, "username": username, "password": password} utc_timestamp = int(time.time()) message = {"msgTime": utc_timestamp, "size": regMessageSize, "message": "initialization", "payload": payload} return json.dumps(message)
[ "def", "build_auth_msg", "(", "username", ":", "str", ",", "password", ":", "str", ",", "version", ":", "float", ",", "rev", ":", "int", ",", "regMessageSize", ":", "int", ")", "->", "str", ":", "payload", "=", "{", "\"type\"", ":", "\"request\"", ",",...
https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/alertClientRaspberryPi/lib/client/util.py#L1299-L1324
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/groups/cubic_braid.py
python
CubicBraidGroup.braid_group
(self)
return self._braid_group
r""" Return an Instance of :class:`BraidGroup` with identical generators, such that there exists an epimorphism to ``self``. OUTPUT: Instance of :class:`BraidGroup` having conversion maps to and from ``self`` (which is just a section in the latter case). EXAMPLES:: sage: U5 = AssionGroupU(5); U5 Assion group on 5 strands of type U sage: B5 = U5.braid_group(); B5 Braid group on 5 strands sage: b = B5([4,3,2,-4,1]) sage: u = U5([4,3,2,-4,1]) sage: u == b False sage: b.burau_matrix() [ 1 - t t 0 0 0] [ 1 - t 0 t 0 0] [ 1 - t 0 0 0 t] [ 1 - t 0 0 1 -1 + t] [ 1 0 0 0 0] sage: u.burau_matrix() [t + 1 t 0 0 0] [t + 1 0 t 0 0] [t + 1 0 0 0 t] [t + 1 0 0 1 t + 1] [ 1 0 0 0 0] sage: bU = U5(b) sage: uB = B5(u) sage: bU == u True sage: uB == b True
r""" Return an Instance of :class:`BraidGroup` with identical generators, such that there exists an epimorphism to ``self``.
[ "r", "Return", "an", "Instance", "of", ":", "class", ":", "BraidGroup", "with", "identical", "generators", "such", "that", "there", "exists", "an", "epimorphism", "to", "self", "." ]
def braid_group(self): r""" Return an Instance of :class:`BraidGroup` with identical generators, such that there exists an epimorphism to ``self``. OUTPUT: Instance of :class:`BraidGroup` having conversion maps to and from ``self`` (which is just a section in the latter case). EXAMPLES:: sage: U5 = AssionGroupU(5); U5 Assion group on 5 strands of type U sage: B5 = U5.braid_group(); B5 Braid group on 5 strands sage: b = B5([4,3,2,-4,1]) sage: u = U5([4,3,2,-4,1]) sage: u == b False sage: b.burau_matrix() [ 1 - t t 0 0 0] [ 1 - t 0 t 0 0] [ 1 - t 0 0 0 t] [ 1 - t 0 0 1 -1 + t] [ 1 0 0 0 0] sage: u.burau_matrix() [t + 1 t 0 0 0] [t + 1 0 t 0 0] [t + 1 0 0 0 t] [t + 1 0 0 1 t + 1] [ 1 0 0 0 0] sage: bU = U5(b) sage: uB = B5(u) sage: bU == u True sage: uB == b True """ return self._braid_group
[ "def", "braid_group", "(", "self", ")", ":", "return", "self", ".", "_braid_group" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/groups/cubic_braid.py#L1346-L1385
googleapis/python-ndb
e780c81cde1016651afbfcad8180d9912722cf1b
google/cloud/ndb/_datastore_api.py
python
_LookupBatch.idle_callback
(self)
Perform a Datastore Lookup on all batched Lookup requests.
Perform a Datastore Lookup on all batched Lookup requests.
[ "Perform", "a", "Datastore", "Lookup", "on", "all", "batched", "Lookup", "requests", "." ]
def idle_callback(self): """Perform a Datastore Lookup on all batched Lookup requests.""" keys = [] for todo_key in self.todo.keys(): key_pb = entity_pb2.Key() key_pb.ParseFromString(todo_key) keys.append(key_pb) read_options = get_read_options(self.options) rpc = _datastore_lookup( keys, read_options, retries=self.options.retries, timeout=self.options.timeout, ) rpc.add_done_callback(self.lookup_callback)
[ "def", "idle_callback", "(", "self", ")", ":", "keys", "=", "[", "]", "for", "todo_key", "in", "self", ".", "todo", ".", "keys", "(", ")", ":", "key_pb", "=", "entity_pb2", ".", "Key", "(", ")", "key_pb", ".", "ParseFromString", "(", "todo_key", ")",...
https://github.com/googleapis/python-ndb/blob/e780c81cde1016651afbfcad8180d9912722cf1b/google/cloud/ndb/_datastore_api.py#L219-L234
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/distutils/command/install.py
python
install.create_home_path
(self)
Create directories under ~.
Create directories under ~.
[ "Create", "directories", "under", "~", "." ]
def create_home_path(self): """Create directories under ~.""" if not self.user: return home = convert_path(os.path.expanduser("~")) for name, path in self.config_vars.items(): if path.startswith(home) and not os.path.isdir(path): self.debug_print("os.makedirs('%s', 0o700)" % path) os.makedirs(path, 0o700)
[ "def", "create_home_path", "(", "self", ")", ":", "if", "not", "self", ".", "user", ":", "return", "home", "=", "convert_path", "(", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", ")", "for", "name", ",", "path", "in", "self", ".", "config_...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/distutils/command/install.py#L523-L531
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/guicomponents.py
python
BinInfoPanel.__init__
(self)
[]
def __init__(self): GObject.GObject.__init__(self) self.set_homogeneous(False) if editorstate.screen_size_small_height() == True: font_desc = "sans bold 8" else: font_desc = "sans bold 9" self.bin_name = Gtk.Label() self.bin_name.modify_font(Pango.FontDescription(font_desc)) self.bin_name.set_sensitive(False) self.items = Gtk.Label() self.items_value = Gtk.Label() self.items.modify_font(Pango.FontDescription(font_desc)) self.items_value.modify_font(Pango.FontDescription(font_desc)) self.items.set_sensitive(False) self.items_value.set_sensitive(False) info_col_2 = Gtk.HBox() info_col_2.pack_start(self.bin_name, False, True, 0) info_col_2.pack_start(Gtk.Label(), True, True, 0) info_col_3 = Gtk.HBox() info_col_3.pack_start(self.items, False, False, 0) info_col_3.pack_start(self.items_value, False, False, 0) info_col_3.pack_start(Gtk.Label(), True, True, 0) self.pack_start(guiutils.pad_label(24, 4), False, False, 0) self.pack_start(info_col_2, False, False, 0) self.pack_start(guiutils.pad_label(12, 4), False, False, 0) self.pack_start(info_col_3, False, False, 0) self.pack_start(Gtk.Label(), True, True, 0) self.set_spacing(4)
[ "def", "__init__", "(", "self", ")", ":", "GObject", ".", "GObject", ".", "__init__", "(", "self", ")", "self", ".", "set_homogeneous", "(", "False", ")", "if", "editorstate", ".", "screen_size_small_height", "(", ")", "==", "True", ":", "font_desc", "=", ...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/guicomponents.py#L1064-L1101
keras-team/keras-contrib
3fc5ef709e061416f4bc8a92ca3750c824b5d2b0
keras_contrib/utils/save_load_utils.py
python
save_all_weights
(model, filepath, include_optimizer=True)
Save model weights and optimizer weights but not configuration to a HDF5 file. Functionally between `save` and `save_weights`. The HDF5 file contains: - the model's weights - the model's optimizer's state (if any) If you have a complicated model or set of models that do not serialize to JSON correctly, use this method. # Arguments model: Keras model instance to be saved. filepath: String, path where to save the model. include_optimizer: If True, save optimizer's state together. # Raises ImportError: if h5py is not available.
Save model weights and optimizer weights but not configuration to a HDF5 file. Functionally between `save` and `save_weights`.
[ "Save", "model", "weights", "and", "optimizer", "weights", "but", "not", "configuration", "to", "a", "HDF5", "file", ".", "Functionally", "between", "save", "and", "save_weights", "." ]
def save_all_weights(model, filepath, include_optimizer=True): """ Save model weights and optimizer weights but not configuration to a HDF5 file. Functionally between `save` and `save_weights`. The HDF5 file contains: - the model's weights - the model's optimizer's state (if any) If you have a complicated model or set of models that do not serialize to JSON correctly, use this method. # Arguments model: Keras model instance to be saved. filepath: String, path where to save the model. include_optimizer: If True, save optimizer's state together. # Raises ImportError: if h5py is not available. """ if h5py is None: raise ImportError('`save_all_weights` requires h5py.') with h5py.File(filepath, 'w') as f: model_weights_group = f.create_group('model_weights') model_layers = model.layers saving.save_weights_to_hdf5_group(model_weights_group, model_layers) if include_optimizer and hasattr(model, 'optimizer') and model.optimizer: if isinstance(model.optimizer, optimizers.TFOptimizer): warnings.warn( 'TensorFlow optimizers do not ' 'make it possible to access ' 'optimizer attributes or optimizer state ' 'after instantiation. ' 'As a result, we cannot save the optimizer ' 'as part of the model save file.' 'You will have to compile your model again after loading it. ' 'Prefer using a Keras optimizer instead ' '(see keras.io/optimizers).') else: # Save optimizer weights. symbolic_weights = getattr(model.optimizer, 'weights') if symbolic_weights: optimizer_weights_group = f.create_group('optimizer_weights') weight_values = K.batch_get_value(symbolic_weights) weight_names = [] for i, (w, val) in enumerate(zip(symbolic_weights, weight_values)): # Default values of symbolic_weights is /variable for theano if K.backend() == 'theano': if hasattr(w, 'name') and w.name != "/variable": name = str(w.name) else: name = 'param_' + str(i) else: if hasattr(w, 'name') and w.name: name = str(w.name) else: name = 'param_' + str(i) weight_names.append(name.encode('utf8')) optimizer_weights_group.attrs['weight_names'] = weight_names for name, val in zip(weight_names, weight_values): param_dset = optimizer_weights_group.create_dataset( name, val.shape, dtype=val.dtype) if not val.shape: # scalar param_dset[()] = val else: param_dset[:] = val
[ "def", "save_all_weights", "(", "model", ",", "filepath", ",", "include_optimizer", "=", "True", ")", ":", "if", "h5py", "is", "None", ":", "raise", "ImportError", "(", "'`save_all_weights` requires h5py.'", ")", "with", "h5py", ".", "File", "(", "filepath", "...
https://github.com/keras-team/keras-contrib/blob/3fc5ef709e061416f4bc8a92ca3750c824b5d2b0/keras_contrib/utils/save_load_utils.py#L9-L76
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/wallet.py
python
Abstract_Wallet.relayfee
(self)
return relayfee(self.network)
[]
def relayfee(self): return relayfee(self.network)
[ "def", "relayfee", "(", "self", ")", ":", "return", "relayfee", "(", "self", ".", "network", ")" ]
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/wallet.py#L1218-L1219
warfares/pretty-json
2bf88fc675f684b95ea01af31014b9fac206b6b7
build/tools/BeautifulSoup.py
python
BeautifulStoneSoup.reset
(self)
[]
def reset(self): Tag.__init__(self, self, self.ROOT_TAG_NAME) self.hidden = 1 SGMLParser.reset(self) self.currentData = [] self.currentTag = None self.tagStack = [] self.quoteStack = [] self.pushTag(self)
[ "def", "reset", "(", "self", ")", ":", "Tag", ".", "__init__", "(", "self", ",", "self", ",", "self", ".", "ROOT_TAG_NAME", ")", "self", ".", "hidden", "=", "1", "SGMLParser", ".", "reset", "(", "self", ")", "self", ".", "currentData", "=", "[", "]...
https://github.com/warfares/pretty-json/blob/2bf88fc675f684b95ea01af31014b9fac206b6b7/build/tools/BeautifulSoup.py#L996-L1004
adulau/Forban
4b06c8a2e2f18ff872ca20a534587a5f15a692fa
lib/ext/cherrypy/_cpcompat.py
python
base64_decode
(n, encoding='ISO-8859-1')
Return the native string base64-decoded (as a native string).
Return the native string base64-decoded (as a native string).
[ "Return", "the", "native", "string", "base64", "-", "decoded", "(", "as", "a", "native", "string", ")", "." ]
def base64_decode(n, encoding='ISO-8859-1'): """Return the native string base64-decoded (as a native string).""" if isinstance(n, unicodestr): b = n.encode(encoding) else: b = n b = _base64_decodebytes(b) if nativestr is unicodestr: return b.decode(encoding) else: return b
[ "def", "base64_decode", "(", "n", ",", "encoding", "=", "'ISO-8859-1'", ")", ":", "if", "isinstance", "(", "n", ",", "unicodestr", ")", ":", "b", "=", "n", ".", "encode", "(", "encoding", ")", "else", ":", "b", "=", "n", "b", "=", "_base64_decodebyte...
https://github.com/adulau/Forban/blob/4b06c8a2e2f18ff872ca20a534587a5f15a692fa/lib/ext/cherrypy/_cpcompat.py#L103-L113
gmr/queries
6995ad18ee2b7fe2ce36d75f50979a47e3e2171d
queries/session.py
python
Session._incr_exceptions
(self)
Increment the number of exceptions for the current connection.
Increment the number of exceptions for the current connection.
[ "Increment", "the", "number", "of", "exceptions", "for", "the", "current", "connection", "." ]
def _incr_exceptions(self): """Increment the number of exceptions for the current connection.""" self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
[ "def", "_incr_exceptions", "(", "self", ")", ":", "self", ".", "_pool_manager", ".", "get_connection", "(", "self", ".", "pid", ",", "self", ".", "_conn", ")", ".", "exceptions", "+=", "1" ]
https://github.com/gmr/queries/blob/6995ad18ee2b7fe2ce36d75f50979a47e3e2171d/queries/session.py#L330-L332
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/gzip.py
python
GzipFile.__init__
(self, filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None)
Constructor for the GzipFile class. At least one of fileobj and filename must be given a non-trivial value. The new class instance is based on fileobj, which can be a regular file, a StringIO object, or any other object which simulates a file. It defaults to None, in which case filename is opened to provide a file object. When fileobj is not None, the filename argument is only used to be included in the gzip file header, which may includes the original filename of the uncompressed file. It defaults to the filename of fileobj, if discernible; otherwise, it defaults to the empty string, and in this case the original filename is not included in the header. The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb', depending on whether the file will be read or written. The default is the mode of fileobj if discernible; otherwise, the default is 'rb'. Be aware that only the 'rb', 'ab', and 'wb' values should be used for cross-platform portability. The compresslevel argument is an integer from 1 to 9 controlling the level of compression; 1 is fastest and produces the least compression, and 9 is slowest and produces the most compression. The default is 9. The mtime argument is an optional numeric timestamp to be written to the stream when compressing. All gzip compressed streams are required to contain a timestamp. If omitted or None, the current time is used. This module ignores the timestamp when decompressing; however, some programs, such as gunzip, make use of it. The format of the timestamp is the same as that of the return value of time.time() and of the st_mtime member of the object returned by os.stat().
Constructor for the GzipFile class.
[ "Constructor", "for", "the", "GzipFile", "class", "." ]
def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None): """Constructor for the GzipFile class. At least one of fileobj and filename must be given a non-trivial value. The new class instance is based on fileobj, which can be a regular file, a StringIO object, or any other object which simulates a file. It defaults to None, in which case filename is opened to provide a file object. When fileobj is not None, the filename argument is only used to be included in the gzip file header, which may includes the original filename of the uncompressed file. It defaults to the filename of fileobj, if discernible; otherwise, it defaults to the empty string, and in this case the original filename is not included in the header. The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb', depending on whether the file will be read or written. The default is the mode of fileobj if discernible; otherwise, the default is 'rb'. Be aware that only the 'rb', 'ab', and 'wb' values should be used for cross-platform portability. The compresslevel argument is an integer from 1 to 9 controlling the level of compression; 1 is fastest and produces the least compression, and 9 is slowest and produces the most compression. The default is 9. The mtime argument is an optional numeric timestamp to be written to the stream when compressing. All gzip compressed streams are required to contain a timestamp. If omitted or None, the current time is used. This module ignores the timestamp when decompressing; however, some programs, such as gunzip, make use of it. The format of the timestamp is the same as that of the return value of time.time() and of the st_mtime member of the object returned by os.stat(). """ # guarantee the file is opened in binary mode on platforms # that care about that sort of thing if mode and 'b' not in mode: mode += 'b' if fileobj is None: fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb') if filename is None: if hasattr(fileobj, 'name'): filename = fileobj.name else: filename = '' if mode is None: if hasattr(fileobj, 'mode'): mode = fileobj.mode else: mode = 'rb' if mode[0:1] == 'r': self.mode = READ # Set flag indicating start of a new member self._new_member = True # Buffer data read from gzip file. extrastart is offset in # stream where buffer starts. extrasize is number of # bytes remaining in buffer from current stream position. self.extrabuf = "" self.extrasize = 0 self.extrastart = 0 self.name = filename # Starts small, scales exponentially self.min_readsize = 100 elif mode[0:1] == 'w' or mode[0:1] == 'a': self.mode = WRITE self._init_write(filename) self.compress = zlib.compressobj(compresslevel, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0) else: raise IOError, "Mode " + mode + " not supported" self.fileobj = fileobj self.offset = 0 self.mtime = mtime if self.mode == WRITE: self._write_gzip_header()
[ "def", "__init__", "(", "self", ",", "filename", "=", "None", ",", "mode", "=", "None", ",", "compresslevel", "=", "9", ",", "fileobj", "=", "None", ",", "mtime", "=", "None", ")", ":", "# guarantee the file is opened in binary mode on platforms", "# that care a...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/gzip.py#L45-L127
transferwise/pipelinewise
6934b3851512dbdd4280790bf253a0a13ab65684
pipelinewise/cli/pipelinewise.py
python
PipelineWise.status
(self)
Prints a status summary table of every imported pipeline with their tap and target.
Prints a status summary table of every imported pipeline with their tap and target.
[ "Prints", "a", "status", "summary", "table", "of", "every", "imported", "pipeline", "with", "their", "tap", "and", "target", "." ]
def status(self): """ Prints a status summary table of every imported pipeline with their tap and target. """ targets = self.get_targets() tab_headers = [ 'Tap ID', 'Tap Type', 'Target ID', 'Target Type', 'Enabled', 'Status', 'Last Sync', 'Last Sync Result', ] tab_body = [] pipelines = 0 for target in targets: taps = self.get_taps(target['id']) for tap in taps: tab_body.append( [ tap.get('id', '<Unknown>'), tap.get('type', '<Unknown>'), target.get('id', '<Unknown>'), target.get('type', '<Unknown>'), tap.get('enabled', '<Unknown>'), tap.get('status', {}).get('currentStatus', '<Unknown>'), tap.get('status', {}).get('lastTimestamp', '<Unknown>'), tap.get('status', {}).get('lastStatus', '<Unknown>'), ] ) pipelines += 1 print(tabulate(tab_body, headers=tab_headers, tablefmt='simple')) print(f'{pipelines} pipeline(s)')
[ "def", "status", "(", "self", ")", ":", "targets", "=", "self", ".", "get_targets", "(", ")", "tab_headers", "=", "[", "'Tap ID'", ",", "'Tap Type'", ",", "'Target ID'", ",", "'Target Type'", ",", "'Enabled'", ",", "'Status'", ",", "'Last Sync'", ",", "'La...
https://github.com/transferwise/pipelinewise/blob/6934b3851512dbdd4280790bf253a0a13ab65684/pipelinewise/cli/pipelinewise.py#L956-L993
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/middlebar.py
python
_get_conf_panel
()
return pane
[]
def _get_conf_panel(): prefs = editorpersistance.prefs global toolbar_list_box # Widgets layout_select = Gtk.ComboBoxText() layout_select.set_tooltip_text(_("Select Render quality")) layout_select.append_text(_("Timecode Left")) layout_select.append_text(_("Timecode Center")) layout_select.append_text(_("Components Centered")) layout_select.set_active(prefs.midbar_layout) # indexes correspond with appconsts values. layout_select.connect("changed", lambda w,e: _layout_conf_changed(w), None) layout_row = guiutils.get_left_justified_box([layout_select]) layout_frame = guiutils.get_named_frame(_("Layout"), layout_row) vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) choice = Gtk.Label(_("Set button group active state and position.")) toolbar_list_box = Gtk.ListBox() toolbar_list_box.set_selection_mode(Gtk.SelectionMode.SINGLE) box_move = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) button_up = Gtk.Button(label=_("Up")) button_up.connect("clicked", row_up, vbox) box_move.pack_start(button_up, False, False, 0) button_down = Gtk.Button(label=_("Down")) button_down.connect("clicked", row_down, vbox) box_move.pack_start(button_down, False, False, 0) button_reset = Gtk.Button(label=_("Reset Positions")) button_reset.connect("clicked", row_down, vbox) box_move.pack_start(Gtk.Label(), True, True, 0) box_move.pack_start(button_reset, False, False, 0) vbox.pack_start(choice, False, False, 0) vbox.pack_start(toolbar_list_box, False, False, 0) vbox.pack_start(box_move, False, False, 0) draw_listbox(vbox) vbox.set_size_request(400, 200) groups_frame = guiutils.get_named_frame(_("Buttons Groups"), vbox) pane = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) pane.pack_start(layout_frame, False, False, 0) pane.pack_start(groups_frame, False, False, 0) return pane
[ "def", "_get_conf_panel", "(", ")", ":", "prefs", "=", "editorpersistance", ".", "prefs", "global", "toolbar_list_box", "# Widgets", "layout_select", "=", "Gtk", ".", "ComboBoxText", "(", ")", "layout_select", ".", "set_tooltip_text", "(", "_", "(", "\"Select Rend...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/middlebar.py#L507-L555
tobegit3hub/deep_image_model
8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e
java_predict_client/src/main/proto/tensorflow/contrib/layers/python/layers/feature_column.py
python
_SparseColumn.weight_tensor
(self, input_tensor)
return None
Returns the weight tensor from the given transformed input_tensor.
Returns the weight tensor from the given transformed input_tensor.
[ "Returns", "the", "weight", "tensor", "from", "the", "given", "transformed", "input_tensor", "." ]
def weight_tensor(self, input_tensor): """Returns the weight tensor from the given transformed input_tensor.""" return None
[ "def", "weight_tensor", "(", "self", ",", "input_tensor", ")", ":", "return", "None" ]
https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/contrib/layers/python/layers/feature_column.py#L340-L342
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/Shared/requests/packages/urllib3/fields.py
python
guess_content_type
(filename, default='application/octet-stream')
return default
Guess the "Content-Type" of a file. :param filename: The filename to guess the "Content-Type" of using :mod:`mimetypes`. :param default: If no "Content-Type" can be guessed, default to `default`.
Guess the "Content-Type" of a file.
[ "Guess", "the", "Content", "-", "Type", "of", "a", "file", "." ]
def guess_content_type(filename, default='application/octet-stream'): """ Guess the "Content-Type" of a file. :param filename: The filename to guess the "Content-Type" of using :mod:`mimetypes`. :param default: If no "Content-Type" can be guessed, default to `default`. """ if filename: return mimetypes.guess_type(filename)[0] or default return default
[ "def", "guess_content_type", "(", "filename", ",", "default", "=", "'application/octet-stream'", ")", ":", "if", "filename", ":", "return", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "or", "default", "return", "default" ]
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Shared/requests/packages/urllib3/fields.py#L8-L19
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/inspect.py
python
isclass
(object)
return isinstance(object, (type, types.ClassType))
Return true if the object is a class. Class objects provide these attributes: __doc__ documentation string __module__ name of module in which this class was defined
Return true if the object is a class.
[ "Return", "true", "if", "the", "object", "is", "a", "class", "." ]
def isclass(object): """Return true if the object is a class. Class objects provide these attributes: __doc__ documentation string __module__ name of module in which this class was defined""" return isinstance(object, (type, types.ClassType))
[ "def", "isclass", "(", "object", ")", ":", "return", "isinstance", "(", "object", ",", "(", "type", ",", "types", ".", "ClassType", ")", ")" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/inspect.py#L59-L65
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/pwiki/customtreectrl.py
python
CustomTreeCtrl.GetTreeStyle
(self)
return self._windowStyle
Returns the CustomTreeCtrl style.
Returns the CustomTreeCtrl style.
[ "Returns", "the", "CustomTreeCtrl", "style", "." ]
def GetTreeStyle(self): """Returns the CustomTreeCtrl style.""" return self._windowStyle
[ "def", "GetTreeStyle", "(", "self", ")", ":", "return", "self", ".", "_windowStyle" ]
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/pwiki/customtreectrl.py#L2417-L2420
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/cookielib.py
python
DefaultCookiePolicy.set_allowed_domains
(self, allowed_domains)
Set the sequence of allowed domains, or None.
Set the sequence of allowed domains, or None.
[ "Set", "the", "sequence", "of", "allowed", "domains", "or", "None", "." ]
def set_allowed_domains(self, allowed_domains): """Set the sequence of allowed domains, or None.""" if allowed_domains is not None: allowed_domains = tuple(allowed_domains) self._allowed_domains = allowed_domains
[ "def", "set_allowed_domains", "(", "self", ",", "allowed_domains", ")", ":", "if", "allowed_domains", "is", "not", "None", ":", "allowed_domains", "=", "tuple", "(", "allowed_domains", ")", "self", ".", "_allowed_domains", "=", "allowed_domains" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/cookielib.py#L897-L901
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/core/debuginfo.py
python
NvvmDIBuilder.mark_location
(self, builder, line)
[]
def mark_location(self, builder, line): # Avoid duplication if self._last_lineno == line: return self._last_lineno = line # Add call to an inline asm to mark line location asmty = ir.FunctionType(ir.VoidType(), []) asm = ir.InlineAsm(asmty, "// dbg {}".format(line), "", side_effect=True) call = builder.call(asm, []) md = self._di_location(line) call.set_metadata('numba.dbg', md)
[ "def", "mark_location", "(", "self", ",", "builder", ",", "line", ")", ":", "# Avoid duplication", "if", "self", ".", "_last_lineno", "==", "line", ":", "return", "self", ".", "_last_lineno", "=", "line", "# Add call to an inline asm to mark line location", "asmty",...
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/debuginfo.py#L485-L496
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/pkg_resources/pkg_resources/__init__.py
python
_ReqExtras.markers_pass
(self, req, extras=None)
return not req.marker or any(extra_evals)
Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True.
Evaluate markers for req against each extra that demanded it.
[ "Evaluate", "markers", "for", "req", "against", "each", "extra", "that", "demanded", "it", "." ]
def markers_pass(self, req, extras=None): """ Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True. """ extra_evals = ( req.marker.evaluate({'extra': extra}) for extra in self.get(req, ()) + (extras or (None,)) ) return not req.marker or any(extra_evals)
[ "def", "markers_pass", "(", "self", ",", "req", ",", "extras", "=", "None", ")", ":", "extra_evals", "=", "(", "req", ".", "marker", ".", "evaluate", "(", "{", "'extra'", ":", "extra", "}", ")", "for", "extra", "in", "self", ".", "get", "(", "req",...
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/pkg_resources/pkg_resources/__init__.py#L965-L977
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cwp/v20180228/models.py
python
DescribeAssetCoreModuleInfoResponse.__init__
(self)
r""" :param Module: 内核模块详情 :type Module: :class:`tencentcloud.cwp.v20180228.models.AssetCoreModuleDetail` :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param Module: 内核模块详情 :type Module: :class:`tencentcloud.cwp.v20180228.models.AssetCoreModuleDetail` :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "Module", ":", "内核模块详情", ":", "type", "Module", ":", ":", "class", ":", "tencentcloud", ".", "cwp", ".", "v20180228", ".", "models", ".", "AssetCoreModuleDetail", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定位问题时需要提供该次请求的", "Request...
def __init__(self): r""" :param Module: 内核模块详情 :type Module: :class:`tencentcloud.cwp.v20180228.models.AssetCoreModuleDetail` :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.Module = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Module", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cwp/v20180228/models.py#L4996-L5004
mrkipling/maraschino
c6be9286937783ae01df2d6d8cebfc8b2734a7d7
lib/sqlalchemy/schema.py
python
Table.drop
(self, bind=None, checkfirst=False)
Issue a ``DROP`` statement for this :class:`.Table`, using the given :class:`.Connectable` for connectivity. See also :meth:`.MetaData.drop_all`.
Issue a ``DROP`` statement for this :class:`.Table`, using the given :class:`.Connectable` for connectivity.
[ "Issue", "a", "DROP", "statement", "for", "this", ":", "class", ":", ".", "Table", "using", "the", "given", ":", "class", ":", ".", "Connectable", "for", "connectivity", "." ]
def drop(self, bind=None, checkfirst=False): """Issue a ``DROP`` statement for this :class:`.Table`, using the given :class:`.Connectable` for connectivity. See also :meth:`.MetaData.drop_all`. """ if bind is None: bind = _bind_or_error(self) bind._run_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
[ "def", "drop", "(", "self", ",", "bind", "=", "None", ",", "checkfirst", "=", "False", ")", ":", "if", "bind", "is", "None", ":", "bind", "=", "_bind_or_error", "(", "self", ")", "bind", ".", "_run_visitor", "(", "ddl", ".", "SchemaDropper", ",", "se...
https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/sqlalchemy/schema.py#L567-L579
isnowfy/pydown
71ecc891868cd2a34b7e5fe662c99474f2d0fd7f
pygments/formatters/img.py
python
ImageFormatter._get_char_width
(self)
return self.fontw
Get the width of a character.
Get the width of a character.
[ "Get", "the", "width", "of", "a", "character", "." ]
def _get_char_width(self): """ Get the width of a character. """ return self.fontw
[ "def", "_get_char_width", "(", "self", ")", ":", "return", "self", ".", "fontw" ]
https://github.com/isnowfy/pydown/blob/71ecc891868cd2a34b7e5fe662c99474f2d0fd7f/pygments/formatters/img.py#L351-L355
StorjOld/pyp2p
7024208c3af20511496a652ff212f54c420e0464
pyp2p/rendezvous_client.py
python
RendezvousClient.parse_remote_port
(self, reply)
return remote_port
Parses a remote port from a Rendezvous Server's response.
Parses a remote port from a Rendezvous Server's response.
[ "Parses", "a", "remote", "port", "from", "a", "Rendezvous", "Server", "s", "response", "." ]
def parse_remote_port(self, reply): """ Parses a remote port from a Rendezvous Server's response. """ remote_port = re.findall("^REMOTE (TCP|UDP) ([0-9]+)$", reply) if not len(remote_port): remote_port = 0 else: remote_port = int(remote_port[0][1]) if remote_port < 1 or remote_port > 65535: remote_port = 0 return remote_port
[ "def", "parse_remote_port", "(", "self", ",", "reply", ")", ":", "remote_port", "=", "re", ".", "findall", "(", "\"^REMOTE (TCP|UDP) ([0-9]+)$\"", ",", "reply", ")", "if", "not", "len", "(", "remote_port", ")", ":", "remote_port", "=", "0", "else", ":", "r...
https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L544-L557
microsoft/TextWorld
c419bb63a92c7f6960aa004a367fb18894043e7f
textworld/logic/__init__.py
python
Action.added
(self)
return self._post_set - self._pre_set
All the new propositions being introduced by this action.
All the new propositions being introduced by this action.
[ "All", "the", "new", "propositions", "being", "introduced", "by", "this", "action", "." ]
def added(self) -> Collection[Proposition]: """ All the new propositions being introduced by this action. """ return self._post_set - self._pre_set
[ "def", "added", "(", "self", ")", "->", "Collection", "[", "Proposition", "]", ":", "return", "self", ".", "_post_set", "-", "self", ".", "_pre_set" ]
https://github.com/microsoft/TextWorld/blob/c419bb63a92c7f6960aa004a367fb18894043e7f/textworld/logic/__init__.py#L974-L978
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/pdb2pqr/contrib/ZSI-2.1-a1/ZSI/wstools/XMLSchema.py
python
XMLSchemaComponent.getAttributeName
(self)
return self.getAttribute('name')
return attribute name or None
return attribute name or None
[ "return", "attribute", "name", "or", "None" ]
def getAttributeName(self): """return attribute name or None """ return self.getAttribute('name')
[ "def", "getAttributeName", "(", "self", ")", ":", "return", "self", ".", "getAttribute", "(", "'name'", ")" ]
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/contrib/ZSI-2.1-a1/ZSI/wstools/XMLSchema.py#L694-L697
redhat-imaging/imagefactory
176f6e045e1df049d50f33a924653128d5ab8b27
imgfac/rest/bottle.py
python
StplParser.write_code
(self, line, comment='')
[]
def write_code(self, line, comment=''): line, comment = self.fix_backward_compatibility(line, comment) code = ' ' * (self.indent+self.indent_mod) code += line.lstrip() + comment + '\n' self.code_buffer.append(code)
[ "def", "write_code", "(", "self", ",", "line", ",", "comment", "=", "''", ")", ":", "line", ",", "comment", "=", "self", ".", "fix_backward_compatibility", "(", "line", ",", "comment", ")", "code", "=", "' '", "*", "(", "self", ".", "indent", "+", "...
https://github.com/redhat-imaging/imagefactory/blob/176f6e045e1df049d50f33a924653128d5ab8b27/imgfac/rest/bottle.py#L3575-L3579