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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
twisted/twisted | dee676b040dd38b847ea6fb112a712cb5e119490 | src/twisted/mail/_pop3client.py | python | POP3Client.connectionLost | (self, reason) | Clean up when the connection has been lost.
When the loss of connection was initiated by the client due to a
timeout, the L{_timedOut} flag will be set. When it was initiated by
the client due to an error in the server greeting, L{_greetingError}
will be set to the server response minus the status indicator.
@type reason: L{Failure <twisted.python.failure.Failure>}
@param reason: The reason the connection was terminated. | Clean up when the connection has been lost. | [
"Clean",
"up",
"when",
"the",
"connection",
"has",
"been",
"lost",
"."
] | def connectionLost(self, reason):
"""
Clean up when the connection has been lost.
When the loss of connection was initiated by the client due to a
timeout, the L{_timedOut} flag will be set. When it was initiated by
the client due to an error in the server greeting, L{_greetingError}
will be set to the server response minus the status indicator.
@type reason: L{Failure <twisted.python.failure.Failure>}
@param reason: The reason the connection was terminated.
"""
if self.timeout > 0:
self.setTimeout(None)
if self._timedOut:
reason = error.TimeoutError()
elif self._greetingError:
reason = ServerErrorResponse(self._greetingError)
d = []
if self._waiting is not None:
d.append(self._waiting)
self._waiting = None
if self._blockedQueue is not None:
d.extend([deferred for (deferred, f, a) in self._blockedQueue])
self._blockedQueue = None
for w in d:
w.errback(reason) | [
"def",
"connectionLost",
"(",
"self",
",",
"reason",
")",
":",
"if",
"self",
".",
"timeout",
">",
"0",
":",
"self",
".",
"setTimeout",
"(",
"None",
")",
"if",
"self",
".",
"_timedOut",
":",
"reason",
"=",
"error",
".",
"TimeoutError",
"(",
")",
"elif... | https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/mail/_pop3client.py#L405-L433 | ||
tensorflow/tensor2tensor | 2a33b152d7835af66a6d20afe7961751047e28dd | tensor2tensor/models/research/universal_transformer.py | python | adaptive_universal_transformer_multilayer_tpu | () | return hparams | Multi-layer config for adaptive Transformer on TPU. | Multi-layer config for adaptive Transformer on TPU. | [
"Multi",
"-",
"layer",
"config",
"for",
"adaptive",
"Transformer",
"on",
"TPU",
"."
] | def adaptive_universal_transformer_multilayer_tpu():
"""Multi-layer config for adaptive Transformer on TPU."""
hparams = adaptive_universal_transformer_base_tpu()
hparams.num_inrecurrence_layers = 2
hparams.mix_with_transformer = "before_ut,after_ut"
hparams.num_mixedin_layers = 1
hparams.transformer_ffn_type = "sepconv"
# TODO(lukaszkaiser): the options below don't work on TPU yet, make them work.
# hparams.add_step_timing_signal = True
# hparams.add_sru = True
# hparams.self_attention_type = "dot_product_relative_v2"
# hparams.max_relative_position = 256
return hparams | [
"def",
"adaptive_universal_transformer_multilayer_tpu",
"(",
")",
":",
"hparams",
"=",
"adaptive_universal_transformer_base_tpu",
"(",
")",
"hparams",
".",
"num_inrecurrence_layers",
"=",
"2",
"hparams",
".",
"mix_with_transformer",
"=",
"\"before_ut,after_ut\"",
"hparams",
... | https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/models/research/universal_transformer.py#L546-L558 | |
out0fmemory/GoAgent-Always-Available | c4254984fea633ce3d1893fe5901debd9f22c2a9 | server/lib/google/appengine/api/taskqueue/taskqueue.py | python | Queue.__DeleteTasks | (self, tasks, multiple, rpc=None) | return _MakeAsyncCall('Delete',
request,
response,
ResultHook,
rpc) | Internal implementation of delete_tasks_async(), tasks must be a list. | Internal implementation of delete_tasks_async(), tasks must be a list. | [
"Internal",
"implementation",
"of",
"delete_tasks_async",
"()",
"tasks",
"must",
"be",
"a",
"list",
"."
] | def __DeleteTasks(self, tasks, multiple, rpc=None):
"""Internal implementation of delete_tasks_async(), tasks must be a list."""
def ResultHook(rpc):
"""Process the TaskQueueDeleteResponse."""
try:
rpc.check_success()
except apiproxy_errors.ApplicationError, e:
raise _TranslateError(e.application_error, e.error_detail)
assert rpc.response.result_size() == len(tasks), (
'expected %d results from delete(), got %d' % (
len(tasks), rpc.response.result_size()))
IGNORED_STATES = [
taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_TASK,
taskqueue_service_pb.TaskQueueServiceError.TOMBSTONED_TASK]
exception = None
for task, result in zip(tasks, rpc.response.result_list()):
if result == taskqueue_service_pb.TaskQueueServiceError.OK:
task._Task__deleted = True
elif result in IGNORED_STATES:
task._Task__deleted = False
elif exception is None:
exception = _TranslateError(result)
if exception is not None:
raise exception
if multiple:
return tasks
else:
assert len(tasks) == 1
return tasks[0]
request = taskqueue_service_pb.TaskQueueDeleteRequest()
response = taskqueue_service_pb.TaskQueueDeleteResponse()
request.set_queue_name(self.__name)
task_names = set()
for task in tasks:
if not task.name:
raise BadTaskStateError('Task name must be specified for a task')
if task.was_deleted:
raise BadTaskStateError('Task %s has already been deleted' % task.name)
if task.name in task_names:
raise DuplicateTaskNameError(
'The task name %r is used more than once in the request' %
task.name)
task_names.add(task.name)
request.add_task_name(task.name)
return _MakeAsyncCall('Delete',
request,
response,
ResultHook,
rpc) | [
"def",
"__DeleteTasks",
"(",
"self",
",",
"tasks",
",",
"multiple",
",",
"rpc",
"=",
"None",
")",
":",
"def",
"ResultHook",
"(",
"rpc",
")",
":",
"\"\"\"Process the TaskQueueDeleteResponse.\"\"\"",
"try",
":",
"rpc",
".",
"check_success",
"(",
")",
"except",
... | https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/api/taskqueue/taskqueue.py#L1559-L1618 | |
frerich/clcache | cae73d8255d78db8ba11e23c51fd2c9a89e7475b | clcache/__main__.py | python | CommandLineAnalyzer._getParameterizedArgumentType | (cmdLineArgument) | return None | [] | def _getParameterizedArgumentType(cmdLineArgument):
# Sort by length to handle prefixes
for arg in CommandLineAnalyzer.argumentsWithParameterSorted:
if cmdLineArgument.startswith(arg.name, 1):
return arg
return None | [
"def",
"_getParameterizedArgumentType",
"(",
"cmdLineArgument",
")",
":",
"# Sort by length to handle prefixes",
"for",
"arg",
"in",
"CommandLineAnalyzer",
".",
"argumentsWithParameterSorted",
":",
"if",
"cmdLineArgument",
".",
"startswith",
"(",
"arg",
".",
"name",
",",
... | https://github.com/frerich/clcache/blob/cae73d8255d78db8ba11e23c51fd2c9a89e7475b/clcache/__main__.py#L1229-L1234 | |||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/sqlalchemy_utils/observer.py | python | PropertyObserver.remove_listeners | (self) | [] | def remove_listeners(self):
for args in self.listener_args:
sa.event.remove(*args) | [
"def",
"remove_listeners",
"(",
"self",
")",
":",
"for",
"args",
"in",
"self",
".",
"listener_args",
":",
"sa",
".",
"event",
".",
"remove",
"(",
"*",
"args",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy_utils/observer.py#L210-L212 | ||||
GluuFederation/community-edition-setup | d0c9427ed9e3ea3d95691677b73c1402ed9ca4db | pylib/jproperties.py | python | Properties.clear | (self) | Remove all properties and related metadata.
:return: None. | Remove all properties and related metadata. | [
"Remove",
"all",
"properties",
"and",
"related",
"metadata",
"."
] | def clear(self):
"""
Remove all properties and related metadata.
:return: None.
"""
# The actual properties.
self._properties = {}
# Metadata for properties (dict of dicts).
self._metadata = {}
# Key order. Populated when parsing so that key order can be preserved when writing the data back.
self._key_order = [] | [
"def",
"clear",
"(",
"self",
")",
":",
"# The actual properties.",
"self",
".",
"_properties",
"=",
"{",
"}",
"# Metadata for properties (dict of dicts).",
"self",
".",
"_metadata",
"=",
"{",
"}",
"# Key order. Populated when parsing so that key order can be preserved when wr... | https://github.com/GluuFederation/community-edition-setup/blob/d0c9427ed9e3ea3d95691677b73c1402ed9ca4db/pylib/jproperties.py#L770-L783 | ||
alteryx/featuretools | d59e11082962f163540fd6e185901f65c506326a | featuretools/primitives/standard/binary_transform.py | python | NotEqualScalar.generate_name | (self, base_feature_names) | return "%s != %s" % (base_feature_names[0], str(self.value)) | [] | def generate_name(self, base_feature_names):
return "%s != %s" % (base_feature_names[0], str(self.value)) | [
"def",
"generate_name",
"(",
"self",
",",
"base_feature_names",
")",
":",
"return",
"\"%s != %s\"",
"%",
"(",
"base_feature_names",
"[",
"0",
"]",
",",
"str",
"(",
"self",
".",
"value",
")",
")"
] | https://github.com/alteryx/featuretools/blob/d59e11082962f163540fd6e185901f65c506326a/featuretools/primitives/standard/binary_transform.py#L382-L383 | |||
yinhm/datafeed | 62193278212c2441d8e49b45d71b8d9d79aab31c | datafeed/providers/tongshi.py | python | run_tongshi_win | (server_addr='localhost', server_password=None) | [] | def run_tongshi_win(server_addr='localhost', server_password=None):
if program_running():
print "already running"
exit(0)
w=MainWindow(host=server_addr, password=server_password)
win32gui.PumpMessages() | [
"def",
"run_tongshi_win",
"(",
"server_addr",
"=",
"'localhost'",
",",
"server_password",
"=",
"None",
")",
":",
"if",
"program_running",
"(",
")",
":",
"print",
"\"already running\"",
"exit",
"(",
"0",
")",
"w",
"=",
"MainWindow",
"(",
"host",
"=",
"server_... | https://github.com/yinhm/datafeed/blob/62193278212c2441d8e49b45d71b8d9d79aab31c/datafeed/providers/tongshi.py#L490-L496 | ||||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/motech/repeaters/models.py | python | RepeatRecord.handle_success | (self, response) | return RepeatRecordAttempt(
cancelled=False,
datetime=now,
failure_reason=None,
success_response=self._format_response(response),
next_check=None,
succeeded=True,
info=self.get_attempt_info(),
) | Log success in Datadog and return a success RepeatRecordAttempt.
``response`` can be a Requests response instance, or True if the
payload did not result in an API call. | Log success in Datadog and return a success RepeatRecordAttempt. | [
"Log",
"success",
"in",
"Datadog",
"and",
"return",
"a",
"success",
"RepeatRecordAttempt",
"."
] | def handle_success(self, response):
"""
Log success in Datadog and return a success RepeatRecordAttempt.
``response`` can be a Requests response instance, or True if the
payload did not result in an API call.
"""
now = datetime.utcnow()
if is_response(response):
# ^^^ Don't bother logging success in Datadog if the payload
# did not need to be sent. (This can happen with DHIS2 if
# the form that triggered the forwarder doesn't contain data
# for a DHIS2 Event.)
log_repeater_success_in_datadog(
self.domain,
response.status_code,
self.repeater_type
)
return RepeatRecordAttempt(
cancelled=False,
datetime=now,
failure_reason=None,
success_response=self._format_response(response),
next_check=None,
succeeded=True,
info=self.get_attempt_info(),
) | [
"def",
"handle_success",
"(",
"self",
",",
"response",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"is_response",
"(",
"response",
")",
":",
"# ^^^ Don't bother logging success in Datadog if the payload",
"# did not need to be sent. (This can happen w... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/motech/repeaters/models.py#L1049-L1075 | |
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | tls/datadog_checks/tls/config_models/defaults.py | python | shared_allowed_versions | (field, value) | return get_default_field_value(field, value) | [] | def shared_allowed_versions(field, value):
return get_default_field_value(field, value) | [
"def",
"shared_allowed_versions",
"(",
"field",
",",
"value",
")",
":",
"return",
"get_default_field_value",
"(",
"field",
",",
"value",
")"
] | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/tls/datadog_checks/tls/config_models/defaults.py#L13-L14 | |||
wildfoundry/dataplicity-lomond | 2e3235fb64f4c630ceb9a141f4d44977e89e7322 | lomond/frame_parser.py | python | ClientFrameParser.on_frame | (self, frame) | Prohibit masked frames from server. | Prohibit masked frames from server. | [
"Prohibit",
"masked",
"frames",
"from",
"server",
"."
] | def on_frame(self, frame):
"""Prohibit masked frames from server."""
if frame.mask:
log.warning(
'%r must not have mask bit set',
frame
)
raise errors.ProtocolError(
'server sent masked frame'
)
super(ClientFrameParser, self).on_frame(frame) | [
"def",
"on_frame",
"(",
"self",
",",
"frame",
")",
":",
"if",
"frame",
".",
"mask",
":",
"log",
".",
"warning",
"(",
"'%r must not have mask bit set'",
",",
"frame",
")",
"raise",
"errors",
".",
"ProtocolError",
"(",
"'server sent masked frame'",
")",
"super",... | https://github.com/wildfoundry/dataplicity-lomond/blob/2e3235fb64f4c630ceb9a141f4d44977e89e7322/lomond/frame_parser.py#L127-L137 | ||
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/setuptools/windows_support.py | python | windows_only | (func) | return func | [] | def windows_only(func):
if platform.system() != 'Windows':
return lambda *args, **kwargs: None
return func | [
"def",
"windows_only",
"(",
"func",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"!=",
"'Windows'",
":",
"return",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"None",
"return",
"func"
] | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/setuptools/windows_support.py#L5-L8 | |||
makcedward/nlp | 2f12277b952dca39d8a392fb14e5f086a562d269 | aion/embeddings/elmo.py | python | ELMoEmbeddings.to_keras_layer | (self, x) | return self.model(
tf.squeeze(tf.cast(x, tf.string)),
signature="default", as_dict=True)[self.layer] | For signature and layer parameters, you can visit https://alpha.tfhub.dev/google/elmo/2 | For signature and layer parameters, you can visit https://alpha.tfhub.dev/google/elmo/2 | [
"For",
"signature",
"and",
"layer",
"parameters",
"you",
"can",
"visit",
"https",
":",
"//",
"alpha",
".",
"tfhub",
".",
"dev",
"/",
"google",
"/",
"elmo",
"/",
"2"
] | def to_keras_layer(self, x):
# Source: https://github.com/strongio/keras-elmo/blob/master/Elmo%20Keras.ipynb
'''
For signature and layer parameters, you can visit https://alpha.tfhub.dev/google/elmo/2
'''
return self.model(
tf.squeeze(tf.cast(x, tf.string)),
signature="default", as_dict=True)[self.layer] | [
"def",
"to_keras_layer",
"(",
"self",
",",
"x",
")",
":",
"# Source: https://github.com/strongio/keras-elmo/blob/master/Elmo%20Keras.ipynb",
"return",
"self",
".",
"model",
"(",
"tf",
".",
"squeeze",
"(",
"tf",
".",
"cast",
"(",
"x",
",",
"tf",
".",
"string",
")... | https://github.com/makcedward/nlp/blob/2f12277b952dca39d8a392fb14e5f086a562d269/aion/embeddings/elmo.py#L42-L49 | |
n1nj4sec/pupy | a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39 | pupy/pupylib/PupyClient.py | python | PupyClient.is_unix | (self) | return not self.is_windows() | [] | def is_unix(self):
return not self.is_windows() | [
"def",
"is_unix",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"is_windows",
"(",
")"
] | https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/pupylib/PupyClient.py#L121-L122 | |||
beeware/ouroboros | a29123c6fab6a807caffbb7587cf548e0c370296 | ouroboros/logging/config.py | python | DictConfigurator.configure_handler | (self, config) | return result | Configure a handler from a dictionary. | Configure a handler from a dictionary. | [
"Configure",
"a",
"handler",
"from",
"a",
"dictionary",
"."
] | def configure_handler(self, config):
"""Configure a handler from a dictionary."""
config_copy = dict(config) # for restoring in case of error
formatter = config.pop('formatter', None)
if formatter:
try:
formatter = self.config['formatters'][formatter]
except Exception as e:
raise ValueError('Unable to set formatter '
'%r: %s' % (formatter, e))
level = config.pop('level', None)
filters = config.pop('filters', None)
if '()' in config:
c = config.pop('()')
if not callable(c):
c = self.resolve(c)
factory = c
else:
cname = config.pop('class')
klass = self.resolve(cname)
#Special case for handler which refers to another handler
if issubclass(klass, logging.handlers.MemoryHandler) and\
'target' in config:
try:
th = self.config['handlers'][config['target']]
if not isinstance(th, logging.Handler):
config.update(config_copy) # restore for deferred cfg
raise TypeError('target not configured yet')
config['target'] = th
except Exception as e:
raise ValueError('Unable to set target handler '
'%r: %s' % (config['target'], e))
elif issubclass(klass, logging.handlers.SMTPHandler) and\
'mailhost' in config:
config['mailhost'] = self.as_tuple(config['mailhost'])
elif issubclass(klass, logging.handlers.SysLogHandler) and\
'address' in config:
config['address'] = self.as_tuple(config['address'])
factory = klass
props = config.pop('.', None)
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
try:
result = factory(**kwargs)
except TypeError as te:
if "'stream'" not in str(te):
raise
#The argument name changed from strm to stream
#Retry with old name.
#This is so that code can be used with older Python versions
#(e.g. by Django)
kwargs['strm'] = kwargs.pop('stream')
result = factory(**kwargs)
if formatter:
result.setFormatter(formatter)
if level is not None:
result.setLevel(logging._checkLevel(level))
if filters:
self.add_filters(result, filters)
if props:
for name, value in props.items():
setattr(result, name, value)
return result | [
"def",
"configure_handler",
"(",
"self",
",",
"config",
")",
":",
"config_copy",
"=",
"dict",
"(",
"config",
")",
"# for restoring in case of error",
"formatter",
"=",
"config",
".",
"pop",
"(",
"'formatter'",
",",
"None",
")",
"if",
"formatter",
":",
"try",
... | https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/logging/config.py#L683-L744 | |
steeve/xbmctorrent | e6bcb1037668959e1e3cb5ba8cf3e379c6638da9 | resources/site-packages/xbmctorrent/player.py | python | TorrentPlayer.init | (self, uri) | return self | [] | def init(self, uri):
self.display_name = ""
self.torrent2http_options = {
"uri": uri,
"dlpath": xbmc.validatePath(xbmc.translatePath(plugin.get_setting("dlpath"))) or ".",
"dlrate": plugin.get_setting("max_download_rate") or "0",
"encryption": plugin.get_setting("encryption"),
"buffer": "0.005",
}
if "://" in self.torrent2http_options["dlpath"]:
# Translate smb:// url to UNC path on windows, very hackish
if PLATFORM["os"] == "windows" and self.torrent2http_options["dlpath"].lower().startswith("smb://"):
self.torrent2http_options["dlpath"] = self.torrent2http_options["dlpath"].replace("smb:", "").replace("/", "\\")
else:
plugin.notify("Downloading to an unmounted network share is not supported. Resetting.", delay=15000)
plugin.set_setting("dlpath", "")
self.torrent2http_options["dlpath"] = "."
# Check for Android and FAT32 SD card issues
if PLATFORM["os"] == "android" and self.torrent2http_options["dlpath"] != ".":
from xbmctorrent.utils import get_path_fs
fs = get_path_fs(self.torrent2http_options["dlpath"])
plugin.log.info("Download path filesytem is %s" % fs)
if fs == "vfat": # FAT32 is not supported
plugin.notify("Downloading to FAT32 is not supported. Resetting.", delay=15000)
plugin.set_setting("dlpath", "")
self.torrent2http_options["dlpath"] = "."
if plugin.get_setting("keep_files", bool):
plugin.log.info("Will keep file after playback.")
self.torrent2http_options["keep"] = None
self.on_playback_started = []
self.on_playback_resumed = []
self.on_playback_paused = []
self.on_playback_stopped = []
return self | [
"def",
"init",
"(",
"self",
",",
"uri",
")",
":",
"self",
".",
"display_name",
"=",
"\"\"",
"self",
".",
"torrent2http_options",
"=",
"{",
"\"uri\"",
":",
"uri",
",",
"\"dlpath\"",
":",
"xbmc",
".",
"validatePath",
"(",
"xbmc",
".",
"translatePath",
"(",... | https://github.com/steeve/xbmctorrent/blob/e6bcb1037668959e1e3cb5ba8cf3e379c6638da9/resources/site-packages/xbmctorrent/player.py#L100-L136 | |||
kyubotics/python-cqhttp | 85301c6982ad5846ad36df1fbfe68d37d9e6e864 | cqhttp_helper.py | python | CQHttp.set_friend_add_request | (self, *, flag, approve=True, remark=None) | return super().__getattr__('set_friend_add_request') \
(flag=flag, approve=approve, remark=remark) | 处理加好友请求
------------
:param str flag: 加好友请求的 flag(需从上报的数据中获得)
:param bool approve: 是否同意请求
:param str remark: 添加后的好友备注(仅在同意时有效)
:return: None
:rtype: None | 处理加好友请求 | [
"处理加好友请求"
] | def set_friend_add_request(self, *, flag, approve=True, remark=None):
"""
处理加好友请求
------------
:param str flag: 加好友请求的 flag(需从上报的数据中获得)
:param bool approve: 是否同意请求
:param str remark: 添加后的好友备注(仅在同意时有效)
:return: None
:rtype: None
"""
return super().__getattr__('set_friend_add_request') \
(flag=flag, approve=approve, remark=remark) | [
"def",
"set_friend_add_request",
"(",
"self",
",",
"*",
",",
"flag",
",",
"approve",
"=",
"True",
",",
"remark",
"=",
"None",
")",
":",
"return",
"super",
"(",
")",
".",
"__getattr__",
"(",
"'set_friend_add_request'",
")",
"(",
"flag",
"=",
"flag",
",",
... | https://github.com/kyubotics/python-cqhttp/blob/85301c6982ad5846ad36df1fbfe68d37d9e6e864/cqhttp_helper.py#L513-L526 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/_pyio.py | python | BufferedWriter.tell | (self) | return _BufferedIOMixin.tell(self) + len(self._write_buf) | [] | def tell(self):
return _BufferedIOMixin.tell(self) + len(self._write_buf) | [
"def",
"tell",
"(",
"self",
")",
":",
"return",
"_BufferedIOMixin",
".",
"tell",
"(",
"self",
")",
"+",
"len",
"(",
"self",
".",
"_write_buf",
")"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/_pyio.py#L1327-L1328 | |||
entropy1337/infernal-twin | 10995cd03312e39a48ade0f114ebb0ae3a711bb8 | Modules/build/reportlab/src/reportlab/platypus/paraparser.py | python | ParaParser._tt_handle | (self,tt) | Iterate through a pre-parsed tuple tree (e.g. from pyRXP) | Iterate through a pre-parsed tuple tree (e.g. from pyRXP) | [
"Iterate",
"through",
"a",
"pre",
"-",
"parsed",
"tuple",
"tree",
"(",
"e",
".",
"g",
".",
"from",
"pyRXP",
")"
] | def _tt_handle(self,tt):
"Iterate through a pre-parsed tuple tree (e.g. from pyRXP)"
#import pprint
#pprint.pprint(tt)
#find the corresponding start_tagname and end_tagname methods.
#These must be defined.
tag = tt[0]
try:
start = getattr(self,'start_'+tag)
end = getattr(self,'end_'+tag)
except AttributeError:
if not self.ignoreUnknownTags:
raise ValueError('Invalid tag "%s"' % tag)
start = self.start_unknown
end = self.end_unknown
#call the start_tagname method
start(tt[1] or {})
#if tree node has any children, they will either be further nodes,
#or text. Accordingly, call either this function, or handle_data.
C = tt[2]
if C:
M = self._tt_handlers
for c in C:
M[isinstance(c,(list,tuple))](c)
#call the end_tagname method
end() | [
"def",
"_tt_handle",
"(",
"self",
",",
"tt",
")",
":",
"#import pprint",
"#pprint.pprint(tt)",
"#find the corresponding start_tagname and end_tagname methods.",
"#These must be defined.",
"tag",
"=",
"tt",
"[",
"0",
"]",
"try",
":",
"start",
"=",
"getattr",
"(",
"self... | https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/reportlab/src/reportlab/platypus/paraparser.py#L1115-L1142 | ||
conansherry/detectron2 | 72c935d9aad8935406b1038af408aa06077d950a | detectron2/modeling/roi_heads/fast_rcnn.py | python | FastRCNNOutputs.inference | (self, score_thresh, nms_thresh, topk_per_image) | return fast_rcnn_inference(
boxes, scores, image_shapes, score_thresh, nms_thresh, topk_per_image
) | Args:
score_thresh (float): same as fast_rcnn_inference.
nms_thresh (float): same as fast_rcnn_inference.
topk_per_image (int): same as fast_rcnn_inference.
Returns:
list[Instances]: same as fast_rcnn_inference.
list[Tensor]: same as fast_rcnn_inference. | Args:
score_thresh (float): same as fast_rcnn_inference.
nms_thresh (float): same as fast_rcnn_inference.
topk_per_image (int): same as fast_rcnn_inference.
Returns:
list[Instances]: same as fast_rcnn_inference.
list[Tensor]: same as fast_rcnn_inference. | [
"Args",
":",
"score_thresh",
"(",
"float",
")",
":",
"same",
"as",
"fast_rcnn_inference",
".",
"nms_thresh",
"(",
"float",
")",
":",
"same",
"as",
"fast_rcnn_inference",
".",
"topk_per_image",
"(",
"int",
")",
":",
"same",
"as",
"fast_rcnn_inference",
".",
"... | def inference(self, score_thresh, nms_thresh, topk_per_image):
"""
Args:
score_thresh (float): same as fast_rcnn_inference.
nms_thresh (float): same as fast_rcnn_inference.
topk_per_image (int): same as fast_rcnn_inference.
Returns:
list[Instances]: same as fast_rcnn_inference.
list[Tensor]: same as fast_rcnn_inference.
"""
boxes = self.predict_boxes()
scores = self.predict_probs()
image_shapes = self.image_shapes
return fast_rcnn_inference(
boxes, scores, image_shapes, score_thresh, nms_thresh, topk_per_image
) | [
"def",
"inference",
"(",
"self",
",",
"score_thresh",
",",
"nms_thresh",
",",
"topk_per_image",
")",
":",
"boxes",
"=",
"self",
".",
"predict_boxes",
"(",
")",
"scores",
"=",
"self",
".",
"predict_probs",
"(",
")",
"image_shapes",
"=",
"self",
".",
"image_... | https://github.com/conansherry/detectron2/blob/72c935d9aad8935406b1038af408aa06077d950a/detectron2/modeling/roi_heads/fast_rcnn.py#L296-L312 | |
openstack/nova | b49b7663e1c3073917d5844b81d38db8e86d05c4 | nova/virt/libvirt/imagebackend.py | python | Image.snapshot_extract | (self, target, out_format) | Extract a snapshot of the image.
This is used during cold (offline) snapshots. Live snapshots
while the guest is still running are handled separately.
:param target: The target path for the image snapshot.
:param out_format: The image snapshot format. | Extract a snapshot of the image. | [
"Extract",
"a",
"snapshot",
"of",
"the",
"image",
"."
] | def snapshot_extract(self, target, out_format):
"""Extract a snapshot of the image.
This is used during cold (offline) snapshots. Live snapshots
while the guest is still running are handled separately.
:param target: The target path for the image snapshot.
:param out_format: The image snapshot format.
"""
raise NotImplementedError() | [
"def",
"snapshot_extract",
"(",
"self",
",",
"target",
",",
"out_format",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/openstack/nova/blob/b49b7663e1c3073917d5844b81d38db8e86d05c4/nova/virt/libvirt/imagebackend.py#L337-L346 | ||
runawayhorse001/LearningApacheSpark | 67f3879dce17553195f094f5728b94a01badcf24 | pyspark/accumulators.py | python | AccumulatorParam.addInPlace | (self, value1, value2) | Add two values of the accumulator's data type, returning a new value;
for efficiency, can also update C{value1} in place and return it. | Add two values of the accumulator's data type, returning a new value;
for efficiency, can also update C{value1} in place and return it. | [
"Add",
"two",
"values",
"of",
"the",
"accumulator",
"s",
"data",
"type",
"returning",
"a",
"new",
"value",
";",
"for",
"efficiency",
"can",
"also",
"update",
"C",
"{",
"value1",
"}",
"in",
"place",
"and",
"return",
"it",
"."
] | def addInPlace(self, value1, value2):
"""
Add two values of the accumulator's data type, returning a new value;
for efficiency, can also update C{value1} in place and return it.
"""
raise NotImplementedError | [
"def",
"addInPlace",
"(",
"self",
",",
"value1",
",",
"value2",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/runawayhorse001/LearningApacheSpark/blob/67f3879dce17553195f094f5728b94a01badcf24/pyspark/accumulators.py#L192-L197 | ||
LuxCoreRender/BlendLuxCore | bf31ca58501d54c02acd97001b6db7de81da7cbf | ui/world.py | python | LUXCORE_WORLD_PT_volume.poll | (cls, context) | return context.world and engine == "LUXCORE" | [] | def poll(cls, context):
engine = context.scene.render.engine
return context.world and engine == "LUXCORE" | [
"def",
"poll",
"(",
"cls",
",",
"context",
")",
":",
"engine",
"=",
"context",
".",
"scene",
".",
"render",
".",
"engine",
"return",
"context",
".",
"world",
"and",
"engine",
"==",
"\"LUXCORE\""
] | https://github.com/LuxCoreRender/BlendLuxCore/blob/bf31ca58501d54c02acd97001b6db7de81da7cbf/ui/world.py#L182-L184 | |||
missionpinball/mpf | 8e6b74cff4ba06d2fec9445742559c1068b88582 | mpf/core/config_spec_loader.py | python | ConfigSpecLoader.process_config_spec | (cls, spec, path) | return spec | Process a config spec dictionary. | Process a config spec dictionary. | [
"Process",
"a",
"config",
"spec",
"dictionary",
"."
] | def process_config_spec(cls, spec, path):
"""Process a config spec dictionary."""
if not isinstance(spec, dict):
raise AssertionError("Expected a dict at: {} {}".format(path, spec))
for element, value in spec.items():
if element.startswith("__"):
spec[element] = value
elif isinstance(value, str):
if value == "ignore":
spec[element] = value
else:
spec[element] = value.split('|')
if len(spec[element]) != 3:
raise AssertionError("Format incorrect: {}".format(value))
else:
spec[element] = cls.process_config_spec(value, path + ":" + element)
return spec | [
"def",
"process_config_spec",
"(",
"cls",
",",
"spec",
",",
"path",
")",
":",
"if",
"not",
"isinstance",
"(",
"spec",
",",
"dict",
")",
":",
"raise",
"AssertionError",
"(",
"\"Expected a dict at: {} {}\"",
".",
"format",
"(",
"path",
",",
"spec",
")",
")",... | https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/core/config_spec_loader.py#L17-L35 | |
pyqtgraph/pyqtgraph | ac3887abfca4e529aac44f022f8e40556a2587b0 | pyqtgraph/widgets/ColorButton.py | python | ColorButton.setColor | (self, color, finished=True) | Sets the button's color and emits both sigColorChanged and sigColorChanging. | Sets the button's color and emits both sigColorChanged and sigColorChanging. | [
"Sets",
"the",
"button",
"s",
"color",
"and",
"emits",
"both",
"sigColorChanged",
"and",
"sigColorChanging",
"."
] | def setColor(self, color, finished=True):
"""Sets the button's color and emits both sigColorChanged and sigColorChanging."""
self._color = functions.mkColor(color)
self.update()
if finished:
self.sigColorChanged.emit(self)
else:
self.sigColorChanging.emit(self) | [
"def",
"setColor",
"(",
"self",
",",
"color",
",",
"finished",
"=",
"True",
")",
":",
"self",
".",
"_color",
"=",
"functions",
".",
"mkColor",
"(",
"color",
")",
"self",
".",
"update",
"(",
")",
"if",
"finished",
":",
"self",
".",
"sigColorChanged",
... | https://github.com/pyqtgraph/pyqtgraph/blob/ac3887abfca4e529aac44f022f8e40556a2587b0/pyqtgraph/widgets/ColorButton.py#L50-L57 | ||
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit - MAC OSX/scripts/sshbackdoors/rpyc/core/brine.py | python | _load_tup_l1 | (stream) | return tuple(_load(stream) for i in range(l)) | [] | def _load_tup_l1(stream):
l, = I1.unpack(stream.read(1))
return tuple(_load(stream) for i in range(l)) | [
"def",
"_load_tup_l1",
"(",
"stream",
")",
":",
"l",
",",
"=",
"I1",
".",
"unpack",
"(",
"stream",
".",
"read",
"(",
"1",
")",
")",
"return",
"tuple",
"(",
"_load",
"(",
"stream",
")",
"for",
"i",
"in",
"range",
"(",
"l",
")",
")"
] | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/sshbackdoors/rpyc/core/brine.py#L293-L295 | |||
dmlc/dgl | 8d14a739bc9e446d6c92ef83eafe5782398118de | python/dgl/readout.py | python | softmax_edges | (graph, feat, *, etype=None) | return segment.segment_softmax(graph.batch_num_edges(etype), x) | r"""Perform graph-wise softmax on the edge features.
For each edge :math:`e\in\mathcal{E}` and its feature :math:`x_e`,
calculate its normalized feature as follows:
.. math::
z_e = \frac{\exp(x_e)}{\sum_{e'\in\mathcal{E}}\exp(x_{e'})}
If the graph is a batch of multiple graphs, each graph computes softmax
independently. The result tensor has the same shape as the original edge
feature.
Parameters
----------
graph : DGLGraph.
The input graph.
feat : str
The edge feature name.
etype : str or (str, str, str), optional
The type names of the edges. The allowed type name formats are:
* ``(str, str, str)`` for source node type, edge type and destination node type.
* or one ``str`` edge type name if the name can uniquely identify a
triplet format in the graph.
Can be omitted if the graph has only one type of edges.
Returns
-------
Tensor
Result tensor.
Examples
--------
>>> import dgl
>>> import torch as th
Create two :class:`~dgl.DGLGraph` objects and initialize their
edge features.
>>> g1 = dgl.graph(([0, 1], [1, 0])) # Graph 1
>>> g1.edata['h'] = th.tensor([1., 1.])
>>> g2 = dgl.graph(([0, 1, 0], [1, 2, 2])) # Graph 2
>>> g2.edata['h'] = th.tensor([1., 1., 1.])
Softmax over one graph:
>>> dgl.softmax_edges(g1, 'h')
tensor([.5000, .5000])
Softmax over a batched graph:
>>> bg = dgl.batch([g1, g2])
>>> dgl.softmax_edges(bg, 'h')
tensor([.5000, .5000, .3333, .3333, .3333])
See Also
--------
softmax_nodes | r"""Perform graph-wise softmax on the edge features. | [
"r",
"Perform",
"graph",
"-",
"wise",
"softmax",
"on",
"the",
"edge",
"features",
"."
] | def softmax_edges(graph, feat, *, etype=None):
r"""Perform graph-wise softmax on the edge features.
For each edge :math:`e\in\mathcal{E}` and its feature :math:`x_e`,
calculate its normalized feature as follows:
.. math::
z_e = \frac{\exp(x_e)}{\sum_{e'\in\mathcal{E}}\exp(x_{e'})}
If the graph is a batch of multiple graphs, each graph computes softmax
independently. The result tensor has the same shape as the original edge
feature.
Parameters
----------
graph : DGLGraph.
The input graph.
feat : str
The edge feature name.
etype : str or (str, str, str), optional
The type names of the edges. The allowed type name formats are:
* ``(str, str, str)`` for source node type, edge type and destination node type.
* or one ``str`` edge type name if the name can uniquely identify a
triplet format in the graph.
Can be omitted if the graph has only one type of edges.
Returns
-------
Tensor
Result tensor.
Examples
--------
>>> import dgl
>>> import torch as th
Create two :class:`~dgl.DGLGraph` objects and initialize their
edge features.
>>> g1 = dgl.graph(([0, 1], [1, 0])) # Graph 1
>>> g1.edata['h'] = th.tensor([1., 1.])
>>> g2 = dgl.graph(([0, 1, 0], [1, 2, 2])) # Graph 2
>>> g2.edata['h'] = th.tensor([1., 1., 1.])
Softmax over one graph:
>>> dgl.softmax_edges(g1, 'h')
tensor([.5000, .5000])
Softmax over a batched graph:
>>> bg = dgl.batch([g1, g2])
>>> dgl.softmax_edges(bg, 'h')
tensor([.5000, .5000, .3333, .3333, .3333])
See Also
--------
softmax_nodes
"""
x = graph.edges[etype].data[feat]
return segment.segment_softmax(graph.batch_num_edges(etype), x) | [
"def",
"softmax_edges",
"(",
"graph",
",",
"feat",
",",
"*",
",",
"etype",
"=",
"None",
")",
":",
"x",
"=",
"graph",
".",
"edges",
"[",
"etype",
"]",
".",
"data",
"[",
"feat",
"]",
"return",
"segment",
".",
"segment_softmax",
"(",
"graph",
".",
"ba... | https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/python/dgl/readout.py#L286-L349 | |
vlachoudis/bCNC | 67126b4894dabf6579baf47af8d0f9b7de35e6e3 | bCNC/lib/svg_elements.py | python | Length.__repr__ | (self) | return 'Length(\'%s\')' % (str(self)) | [] | def __repr__(self):
return 'Length(\'%s\')' % (str(self)) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'Length(\\'%s\\')'",
"%",
"(",
"str",
"(",
"self",
")",
")"
] | https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/lib/svg_elements.py#L759-L760 | |||
thiderman/doge | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | doge/core.py | python | Doge.load_doge | (self) | Return pretty ASCII Shibe.
wow | Return pretty ASCII Shibe. | [
"Return",
"pretty",
"ASCII",
"Shibe",
"."
] | def load_doge(self):
"""
Return pretty ASCII Shibe.
wow
"""
if self.ns.no_shibe:
return ['']
with open(self.doge_path) as f:
if sys.version_info < (3, 0):
if locale.getpreferredencoding() == 'UTF-8':
doge_lines = [l.decode('utf-8') for l in f.xreadlines()]
else:
# encode to printable characters, leaving a space in place
# of untranslatable characters, resulting in a slightly
# blockier doge on non-UTF8 terminals
doge_lines = [
l.decode('utf-8')
.encode(locale.getpreferredencoding(), 'replace')
.replace('?', ' ')
for l in f.xreadlines()
]
else:
doge_lines = [l for l in f.readlines()]
return doge_lines | [
"def",
"load_doge",
"(",
"self",
")",
":",
"if",
"self",
".",
"ns",
".",
"no_shibe",
":",
"return",
"[",
"''",
"]",
"with",
"open",
"(",
"self",
".",
"doge_path",
")",
"as",
"f",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
"... | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L140-L167 | ||
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/CPython/27/Lib/zipfile.py | python | ZipFile._writecheck | (self, zinfo) | Check for errors before writing a file to the archive. | Check for errors before writing a file to the archive. | [
"Check",
"for",
"errors",
"before",
"writing",
"a",
"file",
"to",
"the",
"archive",
"."
] | def _writecheck(self, zinfo):
"""Check for errors before writing a file to the archive."""
if zinfo.filename in self.NameToInfo:
if self.debug: # Warning for duplicate names
print "Duplicate name:", zinfo.filename
if self.mode not in ("w", "a"):
raise RuntimeError, 'write() requires mode "w" or "a"'
if not self.fp:
raise RuntimeError, \
"Attempt to write ZIP archive that was already closed"
if zinfo.compress_type == ZIP_DEFLATED and not zlib:
raise RuntimeError, \
"Compression requires the (missing) zlib module"
if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED):
raise RuntimeError, \
"That compression method is not supported"
if zinfo.file_size > ZIP64_LIMIT:
if not self._allowZip64:
raise LargeZipFile("Filesize would require ZIP64 extensions")
if zinfo.header_offset > ZIP64_LIMIT:
if not self._allowZip64:
raise LargeZipFile("Zipfile size would require ZIP64 extensions") | [
"def",
"_writecheck",
"(",
"self",
",",
"zinfo",
")",
":",
"if",
"zinfo",
".",
"filename",
"in",
"self",
".",
"NameToInfo",
":",
"if",
"self",
".",
"debug",
":",
"# Warning for duplicate names",
"print",
"\"Duplicate name:\"",
",",
"zinfo",
".",
"filename",
... | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/zipfile.py#L1001-L1022 | ||
qilingframework/qiling | 32cc674f2f6fa4b4c9d64a35a1a57853fe1e4142 | qiling/arch/evm/abc.py | python | ComputationAPI.add_child_computation | (self, child_computation: 'ComputationAPI') | Add the given ``child_computation``. | Add the given ``child_computation``. | [
"Add",
"the",
"given",
"child_computation",
"."
] | def add_child_computation(self, child_computation: 'ComputationAPI') -> None:
"""
Add the given ``child_computation``.
"""
... | [
"def",
"add_child_computation",
"(",
"self",
",",
"child_computation",
":",
"'ComputationAPI'",
")",
"->",
"None",
":",
"..."
] | https://github.com/qilingframework/qiling/blob/32cc674f2f6fa4b4c9d64a35a1a57853fe1e4142/qiling/arch/evm/abc.py#L859-L863 | ||
longld/peda | 84d38bda505941ba823db7f6c1bcca1e485a2d43 | lib/utils.py | python | blue | (text, attrib=None) | return colorize(text, "blue", attrib) | Wrapper for colorize(text, 'blue') | Wrapper for colorize(text, 'blue') | [
"Wrapper",
"for",
"colorize",
"(",
"text",
"blue",
")"
] | def blue(text, attrib=None):
"""Wrapper for colorize(text, 'blue')"""
return colorize(text, "blue", attrib) | [
"def",
"blue",
"(",
"text",
",",
"attrib",
"=",
"None",
")",
":",
"return",
"colorize",
"(",
"text",
",",
"\"blue\"",
",",
"attrib",
")"
] | https://github.com/longld/peda/blob/84d38bda505941ba823db7f6c1bcca1e485a2d43/lib/utils.py#L146-L148 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/xml/dom/xmlbuilder.py | python | DOMEntityResolver._create_opener | (self) | return urllib2.build_opener() | [] | def _create_opener(self):
import urllib2
return urllib2.build_opener() | [
"def",
"_create_opener",
"(",
"self",
")",
":",
"import",
"urllib2",
"return",
"urllib2",
".",
"build_opener",
"(",
")"
] | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/xml/dom/xmlbuilder.py#L244-L246 | |||
iclavera/learning_to_adapt | bd7d99ba402521c96631e7d09714128f549db0f1 | viskit/core.py | python | load_exps_data | (exp_folder_paths, disable_variant=False) | return exps_data | [] | def load_exps_data(exp_folder_paths, disable_variant=False):
exps = []
for exp_folder_path in exp_folder_paths:
exps += [x[0] for x in os.walk(exp_folder_path)]
exps_data = []
for exp in exps:
try:
exp_path = exp
params_json_path = os.path.join(exp_path, "params.json")
variant_json_path = os.path.join(exp_path, "variant.json")
progress_csv_path = os.path.join(exp_path, "progress.csv")
progress = load_progress(progress_csv_path)
if disable_variant:
params = load_params(params_json_path)
else:
try:
params = load_params(variant_json_path)
except IOError:
params = load_params(params_json_path)
exps_data.append(AttrDict(
progress=progress, params=params, flat_params=flatten_dict(params)))
except IOError as e:
print(e)
return exps_data | [
"def",
"load_exps_data",
"(",
"exp_folder_paths",
",",
"disable_variant",
"=",
"False",
")",
":",
"exps",
"=",
"[",
"]",
"for",
"exp_folder_path",
"in",
"exp_folder_paths",
":",
"exps",
"+=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"os",
".",
"walk",
... | https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/viskit/core.py#L93-L116 | |||
facebookresearch/nevergrad | c1e83e279d5e16ff7ce6c82854425ec3fd17e981 | nevergrad/benchmark/experiments.py | python | seq_keras_tuning | (seed: tp.Optional[int] = None) | return keras_tuning(seed, overfitter=False, seq=True) | Sequential counterpart of keras tuning. | Sequential counterpart of keras tuning. | [
"Sequential",
"counterpart",
"of",
"keras",
"tuning",
"."
] | def seq_keras_tuning(seed: tp.Optional[int] = None) -> tp.Iterator[Experiment]:
"""Sequential counterpart of keras tuning."""
return keras_tuning(seed, overfitter=False, seq=True) | [
"def",
"seq_keras_tuning",
"(",
"seed",
":",
"tp",
".",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"tp",
".",
"Iterator",
"[",
"Experiment",
"]",
":",
"return",
"keras_tuning",
"(",
"seed",
",",
"overfitter",
"=",
"False",
",",
"seq",
"=",
... | https://github.com/facebookresearch/nevergrad/blob/c1e83e279d5e16ff7ce6c82854425ec3fd17e981/nevergrad/benchmark/experiments.py#L148-L150 | |
citrusCS/csgo-menu-maker | 60e055b4b6f61c7081fc231da47be51eb6e1d47f | csgomenumaker/command/file.py | python | File.__str__ | (self) | Wrapper to correctly format the file's path. | Wrapper to correctly format the file's path. | [
"Wrapper",
"to",
"correctly",
"format",
"the",
"file",
"s",
"path",
"."
] | def __str__(self):
"""
Wrapper to correctly format the file's path.
"""
if not self.is_obf:
if self.name == "":
return str(self.parent) + "." + self.cls + "-" + str(self.id) \
+ ".cfg"
else:
return str(self.parent) + "." + self.cls + "-" + str(self.id) \
+ "_" + self.name + ".cfg"
else:
# Make the path, e.g. "menumaker/file/6/mm_DEADBEEF.cfg"
return self.root.name_space + "/file/" + ("%0.1X" % self.bucket) \
+ "/" + self.obf_name + ".cfg" | [
"def",
"__str__",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_obf",
":",
"if",
"self",
".",
"name",
"==",
"\"\"",
":",
"return",
"str",
"(",
"self",
".",
"parent",
")",
"+",
"\".\"",
"+",
"self",
".",
"cls",
"+",
"\"-\"",
"+",
"str",
"... | https://github.com/citrusCS/csgo-menu-maker/blob/60e055b4b6f61c7081fc231da47be51eb6e1d47f/csgomenumaker/command/file.py#L26-L40 | ||
virt-manager/virt-manager | c51ebdd76a9fc198c40cefcd78838860199467d3 | virtinst/connection.py | python | _real_local_libvirt_version | () | return getattr(libvirt, key) | Lookup the local libvirt library version, but cache the value since
it never changes. | Lookup the local libvirt library version, but cache the value since
it never changes. | [
"Lookup",
"the",
"local",
"libvirt",
"library",
"version",
"but",
"cache",
"the",
"value",
"since",
"it",
"never",
"changes",
"."
] | def _real_local_libvirt_version():
"""
Lookup the local libvirt library version, but cache the value since
it never changes.
"""
key = "__virtinst_cached_getVersion"
if not hasattr(libvirt, key):
setattr(libvirt, key, libvirt.getVersion())
return getattr(libvirt, key) | [
"def",
"_real_local_libvirt_version",
"(",
")",
":",
"key",
"=",
"\"__virtinst_cached_getVersion\"",
"if",
"not",
"hasattr",
"(",
"libvirt",
",",
"key",
")",
":",
"setattr",
"(",
"libvirt",
",",
"key",
",",
"libvirt",
".",
"getVersion",
"(",
")",
")",
"retur... | https://github.com/virt-manager/virt-manager/blob/c51ebdd76a9fc198c40cefcd78838860199467d3/virtinst/connection.py#L23-L31 | |
deanishe/alfred-convert | 97407f4ec8dbca5abbc6952b2b56cf3918624177 | src/workflow/update.py | python | install_update | () | return True | If a newer release is available, download and install it.
:returns: ``True`` if an update is installed, else ``False`` | If a newer release is available, download and install it. | [
"If",
"a",
"newer",
"release",
"is",
"available",
"download",
"and",
"install",
"it",
"."
] | def install_update():
"""If a newer release is available, download and install it.
:returns: ``True`` if an update is installed, else ``False``
"""
key = '__workflow_latest_version'
# data stored when no update is available
no_update = {
'available': False,
'download': None,
'version': None,
}
status = wf().cached_data(key, max_age=0)
if not status or not status.get('available'):
wf().logger.info('no update available')
return False
dl = status.get('download')
if not dl:
wf().logger.info('no download information')
return False
path = retrieve_download(Download.from_dict(dl))
wf().logger.info('installing updated workflow ...')
subprocess.call(['open', path]) # nosec
wf().cache_data(key, no_update)
return True | [
"def",
"install_update",
"(",
")",
":",
"key",
"=",
"'__workflow_latest_version'",
"# data stored when no update is available",
"no_update",
"=",
"{",
"'available'",
":",
"False",
",",
"'download'",
":",
"None",
",",
"'version'",
":",
"None",
",",
"}",
"status",
"... | https://github.com/deanishe/alfred-convert/blob/97407f4ec8dbca5abbc6952b2b56cf3918624177/src/workflow/update.py#L495-L525 | |
gem/oq-engine | 1bdb88f3914e390abcbd285600bfd39477aae47c | openquake/hazardlib/gsim/mcverry_2006.py | python | _compute_stress_drop_adjustment_2 | (kind, SC, mag) | return np.log(10 ** ((np.log(scale_fac) / np.log(2)) *
np.minimum(0.05 + SC['delta'],
0.05 + SC['delta'] * fac))) | Compute equation (6) p. 2200 from Atkinson and Boore (2006). However,
the ratio of scale factors is in log space rather than linear space,
to reflect that log PSA scales linearly with log stress drop. Then
convert from log10 to natural log (G McVerry, personal communication). | Compute equation (6) p. 2200 from Atkinson and Boore (2006). However,
the ratio of scale factors is in log space rather than linear space,
to reflect that log PSA scales linearly with log stress drop. Then
convert from log10 to natural log (G McVerry, personal communication). | [
"Compute",
"equation",
"(",
"6",
")",
"p",
".",
"2200",
"from",
"Atkinson",
"and",
"Boore",
"(",
"2006",
")",
".",
"However",
"the",
"ratio",
"of",
"scale",
"factors",
"is",
"in",
"log",
"space",
"rather",
"than",
"linear",
"space",
"to",
"reflect",
"t... | def _compute_stress_drop_adjustment_2(kind, SC, mag):
"""
Compute equation (6) p. 2200 from Atkinson and Boore (2006). However,
the ratio of scale factors is in log space rather than linear space,
to reflect that log PSA scales linearly with log stress drop. Then
convert from log10 to natural log (G McVerry, personal communication).
"""
scale_fac = 1.5
fac = np.maximum(mag - SC['M1'], 0) / (SC['Mh'] - SC['M1'])
return np.log(10 ** ((np.log(scale_fac) / np.log(2)) *
np.minimum(0.05 + SC['delta'],
0.05 + SC['delta'] * fac))) | [
"def",
"_compute_stress_drop_adjustment_2",
"(",
"kind",
",",
"SC",
",",
"mag",
")",
":",
"scale_fac",
"=",
"1.5",
"fac",
"=",
"np",
".",
"maximum",
"(",
"mag",
"-",
"SC",
"[",
"'M1'",
"]",
",",
"0",
")",
"/",
"(",
"SC",
"[",
"'Mh'",
"]",
"-",
"S... | https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hazardlib/gsim/mcverry_2006.py#L272-L283 | |
uqfoundation/multiprocess | 028cc73f02655e6451d92e5147d19d8c10aebe50 | pypy3.6/multiprocess/managers.py | python | MakeProxyType | (name, exposed, _cache={}) | return ProxyType | Return a proxy type whose methods are given by `exposed` | Return a proxy type whose methods are given by `exposed` | [
"Return",
"a",
"proxy",
"type",
"whose",
"methods",
"are",
"given",
"by",
"exposed"
] | def MakeProxyType(name, exposed, _cache={}):
'''
Return a proxy type whose methods are given by `exposed`
'''
exposed = tuple(exposed)
try:
return _cache[(name, exposed)]
except KeyError:
pass
dic = {}
for meth in exposed:
exec('''def %s(self, *args, **kwds):
return self._callmethod(%r, args, kwds)''' % (meth, meth), dic)
ProxyType = type(name, (BaseProxy,), dic)
ProxyType._exposed_ = exposed
_cache[(name, exposed)] = ProxyType
return ProxyType | [
"def",
"MakeProxyType",
"(",
"name",
",",
"exposed",
",",
"_cache",
"=",
"{",
"}",
")",
":",
"exposed",
"=",
"tuple",
"(",
"exposed",
")",
"try",
":",
"return",
"_cache",
"[",
"(",
"name",
",",
"exposed",
")",
"]",
"except",
"KeyError",
":",
"pass",
... | https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/pypy3.6/multiprocess/managers.py#L887-L906 | |
OpenMDAO/OpenMDAO-Framework | f2e37b7de3edeaaeb2d251b375917adec059db9b | openmdao.main/src/openmdao/main/hasparameters.py | python | ParameterGroup.copy | (self) | return ParameterGroup([p.copy() for p in self._params]) | Return a copy of this ParameterGroup. | Return a copy of this ParameterGroup. | [
"Return",
"a",
"copy",
"of",
"this",
"ParameterGroup",
"."
] | def copy(self):
"""Return a copy of this ParameterGroup."""
return ParameterGroup([p.copy() for p in self._params]) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"ParameterGroup",
"(",
"[",
"p",
".",
"copy",
"(",
")",
"for",
"p",
"in",
"self",
".",
"_params",
"]",
")"
] | https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.main/src/openmdao/main/hasparameters.py#L456-L458 | |
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/pyparsing.py | python | ParserElement.__rand__ | (self, other ) | return other & self | Implementation of & operator when left operand is not a C{L{ParserElement}} | Implementation of & operator when left operand is not a C{L{ParserElement}} | [
"Implementation",
"of",
"&",
"operator",
"when",
"left",
"operand",
"is",
"not",
"a",
"C",
"{",
"L",
"{",
"ParserElement",
"}}"
] | def __rand__(self, other ):
"""Implementation of & operator when left operand is not a C{L{ParserElement}}"""
if isinstance( other, basestring ):
other = ParserElement.literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other & self | [
"def",
"__rand__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement... | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/pyparsing.py#L1387-L1395 | |
DataBiosphere/toil | 2e148eee2114ece8dcc3ec8a83f36333266ece0d | src/toil/batchSystems/parasol.py | python | ParasolBatchSystem.supportsWorkerCleanup | (cls) | return False | [] | def supportsWorkerCleanup(cls):
return False | [
"def",
"supportsWorkerCleanup",
"(",
"cls",
")",
":",
"return",
"False"
] | https://github.com/DataBiosphere/toil/blob/2e148eee2114ece8dcc3ec8a83f36333266ece0d/src/toil/batchSystems/parasol.py#L42-L43 | |||
lad1337/XDM | 0c1b7009fe00f06f102a6f67c793478f515e7efe | site-packages/cherrypy/_cpchecker.py | python | Checker.__call__ | (self) | Run all check_* methods. | Run all check_* methods. | [
"Run",
"all",
"check_",
"*",
"methods",
"."
] | def __call__(self):
"""Run all check_* methods."""
if self.on:
oldformatwarning = warnings.formatwarning
warnings.formatwarning = self.formatwarning
try:
for name in dir(self):
if name.startswith("check_"):
method = getattr(self, name)
if method and hasattr(method, '__call__'):
method()
finally:
warnings.formatwarning = oldformatwarning | [
"def",
"__call__",
"(",
"self",
")",
":",
"if",
"self",
".",
"on",
":",
"oldformatwarning",
"=",
"warnings",
".",
"formatwarning",
"warnings",
".",
"formatwarning",
"=",
"self",
".",
"formatwarning",
"try",
":",
"for",
"name",
"in",
"dir",
"(",
"self",
"... | https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/cherrypy/_cpchecker.py#L29-L41 | ||
ant4g0nist/lisa.py | fb74a309a314d041d4902944a8d449650afc76db | lisa.py | python | ContextCommand.name | (self) | return "context" | [] | def name(self):
return "context" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"\"context\""
] | https://github.com/ant4g0nist/lisa.py/blob/fb74a309a314d041d4902944a8d449650afc76db/lisa.py#L3425-L3426 | |||
qutebrowser/qutebrowser | 3a2aaaacbf97f4bf0c72463f3da94ed2822a5442 | qutebrowser/browser/eventfilter.py | python | TabEventFilter._handle_mouse_release | (self, _e) | return False | Handle releasing of a mouse button.
Args:
e: The QMouseEvent.
Return:
True if the event should be filtered, False otherwise. | Handle releasing of a mouse button. | [
"Handle",
"releasing",
"of",
"a",
"mouse",
"button",
"."
] | def _handle_mouse_release(self, _e):
"""Handle releasing of a mouse button.
Args:
e: The QMouseEvent.
Return:
True if the event should be filtered, False otherwise.
"""
# We want to make sure we check the focus element after the WebView is
# updated completely.
QTimer.singleShot(0, self._mouserelease_insertmode)
return False | [
"def",
"_handle_mouse_release",
"(",
"self",
",",
"_e",
")",
":",
"# We want to make sure we check the focus element after the WebView is",
"# updated completely.",
"QTimer",
".",
"singleShot",
"(",
"0",
",",
"self",
".",
"_mouserelease_insertmode",
")",
"return",
"False"
] | https://github.com/qutebrowser/qutebrowser/blob/3a2aaaacbf97f4bf0c72463f3da94ed2822a5442/qutebrowser/browser/eventfilter.py#L120-L132 | |
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/utils/__init__.py | python | untar_file | (filename, location) | Untar the file (with path `filename`) to the destination `location`.
All files are written based on system defaults and umask (i.e. permissions
are not preserved), except that regular file members with any execute
permissions (user, group, or world) have "chmod +x" applied after being
written. Note that for windows, any execute changes using os.chmod are
no-ops per the python docs. | Untar the file (with path `filename`) to the destination `location`.
All files are written based on system defaults and umask (i.e. permissions
are not preserved), except that regular file members with any execute
permissions (user, group, or world) have "chmod +x" applied after being
written. Note that for windows, any execute changes using os.chmod are
no-ops per the python docs. | [
"Untar",
"the",
"file",
"(",
"with",
"path",
"filename",
")",
"to",
"the",
"destination",
"location",
".",
"All",
"files",
"are",
"written",
"based",
"on",
"system",
"defaults",
"and",
"umask",
"(",
"i",
".",
"e",
".",
"permissions",
"are",
"not",
"prese... | def untar_file(filename, location):
"""
Untar the file (with path `filename`) to the destination `location`.
All files are written based on system defaults and umask (i.e. permissions
are not preserved), except that regular file members with any execute
permissions (user, group, or world) have "chmod +x" applied after being
written. Note that for windows, any execute changes using os.chmod are
no-ops per the python docs.
"""
ensure_dir(location)
if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'):
mode = 'r:gz'
elif filename.lower().endswith(BZ2_EXTENSIONS):
mode = 'r:bz2'
elif filename.lower().endswith(XZ_EXTENSIONS):
mode = 'r:xz'
elif filename.lower().endswith('.tar'):
mode = 'r'
else:
logger.warning(
'Cannot determine compression type for file %s', filename,
)
mode = 'r:*'
tar = tarfile.open(filename, mode)
try:
# note: python<=2.5 doesn't seem to know about pax headers, filter them
leading = has_leading_dir([
member.name for member in tar.getmembers()
if member.name != 'pax_global_header'
])
for member in tar.getmembers():
fn = member.name
if fn == 'pax_global_header':
continue
if leading:
fn = split_leading_dir(fn)[1]
path = os.path.join(location, fn)
if member.isdir():
ensure_dir(path)
elif member.issym():
try:
tar._extract_member(member, path)
except Exception as exc:
# Some corrupt tar files seem to produce this
# (specifically bad symlinks)
logger.warning(
'In the tar file %s the member %s is invalid: %s',
filename, member.name, exc,
)
continue
else:
try:
fp = tar.extractfile(member)
except (KeyError, AttributeError) as exc:
# Some corrupt tar files seem to produce this
# (specifically bad symlinks)
logger.warning(
'In the tar file %s the member %s is invalid: %s',
filename, member.name, exc,
)
continue
ensure_dir(os.path.dirname(path))
with open(path, 'wb') as destfp:
shutil.copyfileobj(fp, destfp)
fp.close()
# Update the timestamp (useful for cython compiled files)
tar.utime(member, path)
# member have any execute permissions for user/group/world?
if member.mode & 0o111:
# make dest file have execute for user/group/world
# no-op on windows per python docs
os.chmod(path, (0o777 - current_umask() | 0o111))
finally:
tar.close() | [
"def",
"untar_file",
"(",
"filename",
",",
"location",
")",
":",
"ensure_dir",
"(",
"location",
")",
"if",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.gz'",
")",
"or",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.tgz'",... | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/utils/__init__.py#L515-L588 | ||
securityclippy/elasticintel | aa08d3e9f5ab1c000128e95161139ce97ff0e334 | ingest_feed_lambda/pandas/core/sparse/series.py | python | SparseSeries.__array_wrap__ | (self, result, context=None) | return self._constructor(result, index=self.index,
sparse_index=self.sp_index,
fill_value=fill_value,
copy=False).__finalize__(self) | Gets called prior to a ufunc (and after)
See SparseArray.__array_wrap__ for detail. | Gets called prior to a ufunc (and after) | [
"Gets",
"called",
"prior",
"to",
"a",
"ufunc",
"(",
"and",
"after",
")"
] | def __array_wrap__(self, result, context=None):
"""
Gets called prior to a ufunc (and after)
See SparseArray.__array_wrap__ for detail.
"""
if isinstance(context, tuple) and len(context) == 3:
ufunc, args, domain = context
args = [getattr(a, 'fill_value', a) for a in args]
with np.errstate(all='ignore'):
fill_value = ufunc(self.fill_value, *args[1:])
else:
fill_value = self.fill_value
return self._constructor(result, index=self.index,
sparse_index=self.sp_index,
fill_value=fill_value,
copy=False).__finalize__(self) | [
"def",
"__array_wrap__",
"(",
"self",
",",
"result",
",",
"context",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"context",
",",
"tuple",
")",
"and",
"len",
"(",
"context",
")",
"==",
"3",
":",
"ufunc",
",",
"args",
",",
"domain",
"=",
"context",... | https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/pandas/core/sparse/series.py#L304-L321 | |
fonttools/fonttools | 892322aaff6a89bea5927379ec06bc0da3dfb7df | Lib/fontTools/pens/cu2quPen.py | python | Cu2QuPointPen._drawPoints | (self, segments) | [] | def _drawPoints(self, segments):
pen = self.pen
pen.beginPath()
last_offcurves = []
for i, (segment_type, points) in enumerate(segments):
if segment_type in ("move", "line"):
assert len(points) == 1, (
"illegal line segment point count: %d" % len(points))
pt, smooth, name, kwargs = points[0]
pen.addPoint(pt, segment_type, smooth, name, **kwargs)
elif segment_type == "qcurve":
assert len(points) >= 2, (
"illegal qcurve segment point count: %d" % len(points))
offcurves = points[:-1]
if offcurves:
if i == 0:
# any off-curve points preceding the first on-curve
# will be appended at the end of the contour
last_offcurves = offcurves
else:
for (pt, smooth, name, kwargs) in offcurves:
pen.addPoint(pt, None, smooth, name, **kwargs)
pt, smooth, name, kwargs = points[-1]
if pt is None:
# special quadratic contour with no on-curve points:
# we need to skip the "None" point. See also the Pen
# protocol's qCurveTo() method and fontTools.pens.basePen
pass
else:
pen.addPoint(pt, segment_type, smooth, name, **kwargs)
else:
# 'curve' segments must have been converted to 'qcurve' by now
raise AssertionError(
"unexpected segment type: %r" % segment_type)
for (pt, smooth, name, kwargs) in last_offcurves:
pen.addPoint(pt, None, smooth, name, **kwargs)
pen.endPath() | [
"def",
"_drawPoints",
"(",
"self",
",",
"segments",
")",
":",
"pen",
"=",
"self",
".",
"pen",
"pen",
".",
"beginPath",
"(",
")",
"last_offcurves",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"segment_type",
",",
"points",
")",
"in",
"enumerate",
"(",
"segme... | https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/pens/cu2quPen.py#L220-L256 | ||||
tensorflow/graphics | 86997957324bfbdd85848daae989b4c02588faa0 | tensorflow_graphics/projects/cvxnet/lib/resnet.py | python | ResLayer.call | (self, x, training=True) | return x | [] | def call(self, x, training=True):
for layer in self.conv_layers:
x = layer(x, training=training)
return x | [
"def",
"call",
"(",
"self",
",",
"x",
",",
"training",
"=",
"True",
")",
":",
"for",
"layer",
"in",
"self",
".",
"conv_layers",
":",
"x",
"=",
"layer",
"(",
"x",
",",
"training",
"=",
"training",
")",
"return",
"x"
] | https://github.com/tensorflow/graphics/blob/86997957324bfbdd85848daae989b4c02588faa0/tensorflow_graphics/projects/cvxnet/lib/resnet.py#L75-L78 | |||
prompt-toolkit/python-prompt-toolkit | e9eac2eb59ec385e81742fa2ac623d4b8de00925 | prompt_toolkit/layout/containers.py | python | to_container | (container: AnyContainer) | Make sure that the given object is a :class:`.Container`. | Make sure that the given object is a :class:`.Container`. | [
"Make",
"sure",
"that",
"the",
"given",
"object",
"is",
"a",
":",
"class",
":",
".",
"Container",
"."
] | def to_container(container: AnyContainer) -> Container:
"""
Make sure that the given object is a :class:`.Container`.
"""
if isinstance(container, Container):
return container
elif hasattr(container, "__pt_container__"):
return to_container(container.__pt_container__())
else:
raise ValueError("Not a container object: %r" % (container,)) | [
"def",
"to_container",
"(",
"container",
":",
"AnyContainer",
")",
"->",
"Container",
":",
"if",
"isinstance",
"(",
"container",
",",
"Container",
")",
":",
"return",
"container",
"elif",
"hasattr",
"(",
"container",
",",
"\"__pt_container__\"",
")",
":",
"ret... | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/e9eac2eb59ec385e81742fa2ac623d4b8de00925/prompt_toolkit/layout/containers.py#L2724-L2733 | ||
Decalogue/chat | 3c33ad986ce52168026f4ee02d2f176fa65766a6 | chat/apilib.py | python | get_location_by_ip | (city="上海市"): | return location | 根据IP获取当前地址 | 根据IP获取当前地址 | [
"根据IP获取当前地址"
] | def get_location_by_ip(city="上海市"):
"""根据IP获取当前地址
"""
url = "http://api.map.baidu.com/location/ip"
data = {
"ak": "wllxHD5CmWv8qX6CN2lyY73a",
"coor": "bd09ll"
}
try:
result = requests.post(url, data, timeout=20).text
location = json.loads(result)["content"]["address"]
print("当前所在城市:", location)
except:
location = city
print("采用默认城市:", location)
return location | [
"def",
"get_location_by_ip",
"(",
"city",
"=",
"\"上海市\"):",
"",
"",
"url",
"=",
"\"http://api.map.baidu.com/location/ip\"",
"data",
"=",
"{",
"\"ak\"",
":",
"\"wllxHD5CmWv8qX6CN2lyY73a\"",
",",
"\"coor\"",
":",
"\"bd09ll\"",
"}",
"try",
":",
"result",
"=",
"reques... | https://github.com/Decalogue/chat/blob/3c33ad986ce52168026f4ee02d2f176fa65766a6/chat/apilib.py#L45-L60 | |
XuezheMax/flowseq | 8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b | flownmt/flows/couplings/blocks.py | python | NICESelfAttnBlock.__init__ | (self, src_features, in_features, out_features, hidden_features, heads, dropout=0.0,
pos_enc='add', max_length=100) | [] | def __init__(self, src_features, in_features, out_features, hidden_features, heads, dropout=0.0,
pos_enc='add', max_length=100):
super(NICESelfAttnBlock, self).__init__()
assert pos_enc in ['add', 'attn']
self.src_proj = nn.Linear(src_features, in_features, bias=False) if src_features != in_features else None
self.pos_enc = PositionalEncoding(in_features, padding_idx=None, init_size=max_length + 1)
self.pos_attn = MultiHeadAttention(in_features, heads, dropout=dropout) if pos_enc == 'attn' else None
self.transformer = TransformerDecoderLayer(in_features, hidden_features, heads, dropout=dropout)
self.linear = LinearWeightNorm(in_features, out_features, bias=True) | [
"def",
"__init__",
"(",
"self",
",",
"src_features",
",",
"in_features",
",",
"out_features",
",",
"hidden_features",
",",
"heads",
",",
"dropout",
"=",
"0.0",
",",
"pos_enc",
"=",
"'add'",
",",
"max_length",
"=",
"100",
")",
":",
"super",
"(",
"NICESelfAt... | https://github.com/XuezheMax/flowseq/blob/8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b/flownmt/flows/couplings/blocks.py#L89-L97 | ||||
liaohuqiu/btcbot-open | bb46896b5e24449bc41f65a876d8d7c886a340c1 | src/btfxwss/queue_processor.py | python | QueueProcessor._handle_book | (self, dtype, data, ts) | Updates the order book stored in self.books[chan_id].
:param dtype:
:param data:
:param ts:
:return: | Updates the order book stored in self.books[chan_id]. | [
"Updates",
"the",
"order",
"book",
"stored",
"in",
"self",
".",
"books",
"[",
"chan_id",
"]",
"."
] | def _handle_book(self, dtype, data, ts):
"""Updates the order book stored in self.books[chan_id].
:param dtype:
:param data:
:param ts:
:return:
"""
log.debug("_handle_book: %s - %s - %s", dtype, data, ts)
channel_id, data = data
log.debug("ts: %s\tchan_id: %s\tdata: %s", ts, channel_id, data)
channel_identifier = self.channel_directory[channel_id]
self._put_data_to_queue(data, ts, self.books[channel_identifier]) | [
"def",
"_handle_book",
"(",
"self",
",",
"dtype",
",",
"data",
",",
"ts",
")",
":",
"log",
".",
"debug",
"(",
"\"_handle_book: %s - %s - %s\"",
",",
"dtype",
",",
"data",
",",
"ts",
")",
"channel_id",
",",
"data",
"=",
"data",
"log",
".",
"debug",
"(",... | https://github.com/liaohuqiu/btcbot-open/blob/bb46896b5e24449bc41f65a876d8d7c886a340c1/src/btfxwss/queue_processor.py#L294-L306 | ||
TurboGears/tg2 | f40a82d016d70ce560002593b4bb8f83b57f87b3 | tg/support/paginate.py | python | Page._pagerlink | (self, pagenr, text) | Create a URL that links to another page.
Parameters:
pagenr
Number of the page that the link points to
text
Text to be printed in the A-HREF tag | Create a URL that links to another page. | [
"Create",
"a",
"URL",
"that",
"links",
"to",
"another",
"page",
"."
] | def _pagerlink(self, pagenr, text):
"""
Create a URL that links to another page.
Parameters:
pagenr
Number of the page that the link points to
text
Text to be printed in the A-HREF tag
"""
link_params = {}
# Use the instance kwargs as URL parameters
link_params.update(self.kwargs)
# Add keyword arguments from pager() to the link as parameters
link_params.update(self.pager_kwargs)
link_params[self.page_param] = pagenr
# Create the URL to load the page area part of a certain page (AJAX updates)
partial_url = link_params.pop('partial', '')
# Create the URL to load a certain page
link_url = link_params.pop('link', request.path_info)
link_url = Markup(url(link_url, params=link_params))
if self.onclick: # create link with onclick action for AJAX
try: # if '%s' is used in the 'onclick' parameter (backwards compatibility)
onclick_action = self.onclick % (partial_url,)
except TypeError:
onclick_action = string.Template(self.onclick).safe_substitute({
"partial_url": partial_url,
"page": pagenr
})
return _make_tag(self.page_link_template, text, href=link_url, onclick=onclick_action, **self.link_attr)
else: # return static link
return _make_tag(self.page_link_template, text, href=link_url, **self.link_attr) | [
"def",
"_pagerlink",
"(",
"self",
",",
"pagenr",
",",
"text",
")",
":",
"link_params",
"=",
"{",
"}",
"# Use the instance kwargs as URL parameters",
"link_params",
".",
"update",
"(",
"self",
".",
"kwargs",
")",
"# Add keyword arguments from pager() to the link as param... | https://github.com/TurboGears/tg2/blob/f40a82d016d70ce560002593b4bb8f83b57f87b3/tg/support/paginate.py#L430-L466 | ||
vmware/vsphere-automation-sdk-python | ba7d4e0742f58a641dfed9538ecbbb1db4f3891e | samples/vsphere/vcenter/guest/customizationSpecs.py | python | CustomizationSpecManager.parseLinuxCfg | (self) | [] | def parseLinuxCfg(self):
self.config.read(self.linCfgPath)
self.parseSpecInfo()
self.linSpecName = self.specName
self.parseNetwork()
self.parseHostname()
self.domainName = self.config['LINUXCONFIG'].get('domainName')
self.timezone = self.config['LINUXCONFIG'].get('timezone')
self.script_text = self.config['LINUXCONFIG'].get('script_text')
self.parseDns() | [
"def",
"parseLinuxCfg",
"(",
"self",
")",
":",
"self",
".",
"config",
".",
"read",
"(",
"self",
".",
"linCfgPath",
")",
"self",
".",
"parseSpecInfo",
"(",
")",
"self",
".",
"linSpecName",
"=",
"self",
".",
"specName",
"self",
".",
"parseNetwork",
"(",
... | https://github.com/vmware/vsphere-automation-sdk-python/blob/ba7d4e0742f58a641dfed9538ecbbb1db4f3891e/samples/vsphere/vcenter/guest/customizationSpecs.py#L158-L167 | ||||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/sympy/functions/special/delta_functions.py | python | Heaviside._eval_rewrite_as_SingularityFunction | (self, args, **kwargs) | Returns the Heaviside expression written in the form of Singularity Functions. | Returns the Heaviside expression written in the form of Singularity Functions. | [
"Returns",
"the",
"Heaviside",
"expression",
"written",
"in",
"the",
"form",
"of",
"Singularity",
"Functions",
"."
] | def _eval_rewrite_as_SingularityFunction(self, args, **kwargs):
"""
Returns the Heaviside expression written in the form of Singularity Functions.
"""
from sympy.solvers import solve
from sympy.functions import SingularityFunction
if self == Heaviside(0):
return SingularityFunction(0, 0, 0)
free = self.free_symbols
if len(free) == 1:
x = (free.pop())
return SingularityFunction(x, solve(args, x)[0], 0)
# TODO
# ((x - 5)**3*Heaviside(x - 5)).rewrite(SingularityFunction) should output
# SingularityFunction(x, 5, 0) instead of (x - 5)**3*SingularityFunction(x, 5, 0)
else:
# I don't know how to handle the case for Heaviside expressions
# having arguments with more than one variable.
raise TypeError(filldedent('''
rewrite(SingularityFunction) doesn't
support arguments with more that 1 variable.''')) | [
"def",
"_eval_rewrite_as_SingularityFunction",
"(",
"self",
",",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"sympy",
".",
"solvers",
"import",
"solve",
"from",
"sympy",
".",
"functions",
"import",
"SingularityFunction",
"if",
"self",
"==",
"Heaviside",
... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/functions/special/delta_functions.py#L594-L615 | ||
wzpan/dingdang-robot | 66d95402232a9102e223a2d8ccefcb83500d2c6a | dingdang.py | python | Dingdang.__init__ | (self) | [] | def __init__(self):
self._logger = logging.getLogger(__name__)
# Create config dir if it does not exist yet
if not os.path.exists(dingdangpath.CONFIG_PATH):
try:
os.makedirs(dingdangpath.CONFIG_PATH)
except OSError:
self._logger.error("Could not create config dir: '%s'",
dingdangpath.CONFIG_PATH, exc_info=True)
raise
# Check if config dir is writable
if not os.access(dingdangpath.CONFIG_PATH, os.W_OK):
self._logger.critical("Config dir %s is not writable. Dingdang " +
"won't work correctly.",
dingdangpath.CONFIG_PATH)
config_file = dingdangpath.config('profile.yml')
# Read config
self._logger.debug("Trying to read config file: '%s'", config_file)
try:
with open(config_file, "r") as f:
self.config = yaml.safe_load(f)
except OSError:
self._logger.error("Can't open config file: '%s'", config_file)
raise
try:
stt_engine_slug = self.config['stt_engine']
except KeyError:
stt_engine_slug = 'sphinx'
logger.warning("stt_engine not specified in profile, defaulting " +
"to '%s'", stt_engine_slug)
stt_engine_class = stt.get_engine_by_slug(stt_engine_slug)
try:
slug = self.config['stt_passive_engine']
stt_passive_engine_class = stt.get_engine_by_slug(slug)
except KeyError:
stt_passive_engine_class = stt_engine_class
try:
tts_engine_slug = self.config['tts_engine']
except KeyError:
tts_engine_slug = tts.get_default_engine_slug()
logger.warning("tts_engine not specified in profile, defaulting " +
"to '%s'", tts_engine_slug)
tts_engine_class = tts.get_engine_by_slug(tts_engine_slug)
# Initialize Mic
self.mic = Mic(
self.config,
tts_engine_class.get_instance(),
stt_passive_engine_class.get_passive_instance(),
stt_engine_class.get_active_instance()) | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"_logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# Create config dir if it does not exist yet",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dingdangpath",
".",
"CONFIG_PATH",
")... | https://github.com/wzpan/dingdang-robot/blob/66d95402232a9102e223a2d8ccefcb83500d2c6a/dingdang.py#L41-L96 | ||||
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/antiddos/v20200309/models.py | python | DeleteDDoSSpeedLimitConfigRequest.__init__ | (self) | r"""
:param InstanceId: 资源实例ID
:type InstanceId: str
:param DDoSSpeedLimitConfig: 访问限速配置,填写参数时配置ID不能为空
:type DDoSSpeedLimitConfig: :class:`tencentcloud.antiddos.v20200309.models.DDoSSpeedLimitConfig` | r"""
:param InstanceId: 资源实例ID
:type InstanceId: str
:param DDoSSpeedLimitConfig: 访问限速配置,填写参数时配置ID不能为空
:type DDoSSpeedLimitConfig: :class:`tencentcloud.antiddos.v20200309.models.DDoSSpeedLimitConfig` | [
"r",
":",
"param",
"InstanceId",
":",
"资源实例ID",
":",
"type",
"InstanceId",
":",
"str",
":",
"param",
"DDoSSpeedLimitConfig",
":",
"访问限速配置,填写参数时配置ID不能为空",
":",
"type",
"DDoSSpeedLimitConfig",
":",
":",
"class",
":",
"tencentcloud",
".",
"antiddos",
".",
"v2020030... | def __init__(self):
r"""
:param InstanceId: 资源实例ID
:type InstanceId: str
:param DDoSSpeedLimitConfig: 访问限速配置,填写参数时配置ID不能为空
:type DDoSSpeedLimitConfig: :class:`tencentcloud.antiddos.v20200309.models.DDoSSpeedLimitConfig`
"""
self.InstanceId = None
self.DDoSSpeedLimitConfig = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"InstanceId",
"=",
"None",
"self",
".",
"DDoSSpeedLimitConfig",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/antiddos/v20200309/models.py#L1710-L1718 | ||
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/jinja2/filters.py | python | do_filesizeformat | (value, binary=False) | Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
prefixes are used (Mebi, Gibi). | Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
prefixes are used (Mebi, Gibi). | [
"Format",
"the",
"value",
"like",
"a",
"human",
"-",
"readable",
"file",
"size",
"(",
"i",
".",
"e",
".",
"13",
"kB",
"4",
".",
"1",
"MB",
"102",
"Bytes",
"etc",
")",
".",
"Per",
"default",
"decimal",
"prefixes",
"are",
"used",
"(",
"Mega",
"Giga",... | def do_filesizeformat(value, binary=False):
"""Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
prefixes are used (Mebi, Gibi).
"""
bytes = float(value)
base = binary and 1024 or 1000
prefixes = [
(binary and 'KiB' or 'kB'),
(binary and 'MiB' or 'MB'),
(binary and 'GiB' or 'GB'),
(binary and 'TiB' or 'TB'),
(binary and 'PiB' or 'PB'),
(binary and 'EiB' or 'EB'),
(binary and 'ZiB' or 'ZB'),
(binary and 'YiB' or 'YB')
]
if bytes == 1:
return '1 Byte'
elif bytes < base:
return '%d Bytes' % bytes
else:
for i, prefix in enumerate(prefixes):
unit = base ** (i + 2)
if bytes < unit:
return '%.1f %s' % ((base * bytes / unit), prefix)
return '%.1f %s' % ((base * bytes / unit), prefix) | [
"def",
"do_filesizeformat",
"(",
"value",
",",
"binary",
"=",
"False",
")",
":",
"bytes",
"=",
"float",
"(",
"value",
")",
"base",
"=",
"binary",
"and",
"1024",
"or",
"1000",
"prefixes",
"=",
"[",
"(",
"binary",
"and",
"'KiB'",
"or",
"'kB'",
")",
","... | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/jinja2/filters.py#L372-L399 | ||
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/pandas/indexes/base.py | python | Index._maybe_cast_indexer | (self, key) | return key | If we have a float key and are not a floating index
then try to cast to an int if equivalent | If we have a float key and are not a floating index
then try to cast to an int if equivalent | [
"If",
"we",
"have",
"a",
"float",
"key",
"and",
"are",
"not",
"a",
"floating",
"index",
"then",
"try",
"to",
"cast",
"to",
"an",
"int",
"if",
"equivalent"
] | def _maybe_cast_indexer(self, key):
"""
If we have a float key and are not a floating index
then try to cast to an int if equivalent
"""
if is_float(key) and not self.is_floating():
try:
ckey = int(key)
if ckey == key:
key = ckey
except (ValueError, TypeError):
pass
return key | [
"def",
"_maybe_cast_indexer",
"(",
"self",
",",
"key",
")",
":",
"if",
"is_float",
"(",
"key",
")",
"and",
"not",
"self",
".",
"is_floating",
"(",
")",
":",
"try",
":",
"ckey",
"=",
"int",
"(",
"key",
")",
"if",
"ckey",
"==",
"key",
":",
"key",
"... | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/indexes/base.py#L3007-L3020 | |
aewallin/allantools | afa029676cf013828280e00eab3568636586fd1c | allantools/ci.py | python | rn_theory | (af, b) | R(n) ratio expected from theory for given noise type
alpha = b + 2 | R(n) ratio expected from theory for given noise type | [
"R",
"(",
"n",
")",
"ratio",
"expected",
"from",
"theory",
"for",
"given",
"noise",
"type"
] | def rn_theory(af, b):
""" R(n) ratio expected from theory for given noise type
alpha = b + 2
"""
# From IEEE1139-2008
# alpha beta ADEV_mu MDEV_mu Rn_mu
# -2 -4 1 1 0 Random Walk FM
# -1 -3 0 0 0 Flicker FM
# 0 -2 -1 -1 0 White FM
# 1 -1 -2 -2 0 Flicker PM
# 2 0 -2 -3 -1 White PM
# (a=-3 flicker walk FM)
# (a=-4 random run FM)
if b == 0:
return pow(af, -1)
elif b == -1:
# f_h = 0.5/tau0 (assumed!)
# af = tau/tau0
# so f_h*tau = 0.5/tau0 * af*tau0 = 0.5*af
avar = (1.038+3*np.log(2*np.pi*0.5*af)) / (4.0*pow(np.pi, 2))
mvar = 3*np.log(256.0/27.0)/(8.0*pow(np.pi, 2))
return mvar/avar
else:
return pow(af, 0) | [
"def",
"rn_theory",
"(",
"af",
",",
"b",
")",
":",
"# From IEEE1139-2008",
"# alpha beta ADEV_mu MDEV_mu Rn_mu",
"# -2 -4 1 1 0 Random Walk FM",
"# -1 -3 0 0 0 Flicker FM",
"# 0 -2 -1 -1 0 White F... | https://github.com/aewallin/allantools/blob/afa029676cf013828280e00eab3568636586fd1c/allantools/ci.py#L154-L179 | ||
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/jinja2/visitor.py | python | NodeVisitor.get_visitor | (self, node) | return getattr(self, method, None) | Return the visitor function for this node or `None` if no visitor
exists for this node. In that case the generic visit function is
used instead. | Return the visitor function for this node or `None` if no visitor
exists for this node. In that case the generic visit function is
used instead. | [
"Return",
"the",
"visitor",
"function",
"for",
"this",
"node",
"or",
"None",
"if",
"no",
"visitor",
"exists",
"for",
"this",
"node",
".",
"In",
"that",
"case",
"the",
"generic",
"visit",
"function",
"is",
"used",
"instead",
"."
] | def get_visitor(self, node):
"""Return the visitor function for this node or `None` if no visitor
exists for this node. In that case the generic visit function is
used instead.
"""
method = 'visit_' + node.__class__.__name__
return getattr(self, method, None) | [
"def",
"get_visitor",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"'visit_'",
"+",
"node",
".",
"__class__",
".",
"__name__",
"return",
"getattr",
"(",
"self",
",",
"method",
",",
"None",
")"
] | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/jinja2/visitor.py#L26-L32 | |
OpenBazaar/OpenBazaar-Installer | ca17cf4e283bcc408603832ba745f5319126a44a | windows/PyNaCl-0.3.0-py2.7-win-amd64.egg/nacl/bindings/crypto_hash.py | python | crypto_hash | (message) | return lib.ffi.buffer(digest, crypto_hash_BYTES)[:] | Hashes and returns the message ``message``.
:param message: bytes
:rtype: bytes | Hashes and returns the message ``message``. | [
"Hashes",
"and",
"returns",
"the",
"message",
"message",
"."
] | def crypto_hash(message):
"""
Hashes and returns the message ``message``.
:param message: bytes
:rtype: bytes
"""
digest = lib.ffi.new("unsigned char[]", crypto_hash_BYTES)
if lib.crypto_hash(digest, message, len(message)) != 0:
raise CryptoError("Hashing failed")
return lib.ffi.buffer(digest, crypto_hash_BYTES)[:] | [
"def",
"crypto_hash",
"(",
"message",
")",
":",
"digest",
"=",
"lib",
".",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_hash_BYTES",
")",
"if",
"lib",
".",
"crypto_hash",
"(",
"digest",
",",
"message",
",",
"len",
"(",
"message",
")",
")",... | https://github.com/OpenBazaar/OpenBazaar-Installer/blob/ca17cf4e283bcc408603832ba745f5319126a44a/windows/PyNaCl-0.3.0-py2.7-win-amd64.egg/nacl/bindings/crypto_hash.py#L27-L37 | |
PaloAltoNetworks/pan-os-python | 30f6cd9e29d0e3c2549d46c722f6dcb507acd437 | panos/base.py | python | PanDevice.refresh_version | (self) | return self.version | Refresh version of PAN-OS
Version is stored in self.version and returned
returns:
str: version of PAN-OS | Refresh version of PAN-OS | [
"Refresh",
"version",
"of",
"PAN",
"-",
"OS"
] | def refresh_version(self):
"""Refresh version of PAN-OS
Version is stored in self.version and returned
returns:
str: version of PAN-OS
"""
system_info = self.refresh_system_info()
self.version = system_info[0]
return self.version | [
"def",
"refresh_version",
"(",
"self",
")",
":",
"system_info",
"=",
"self",
".",
"refresh_system_info",
"(",
")",
"self",
".",
"version",
"=",
"system_info",
"[",
"0",
"]",
"return",
"self",
".",
"version"
] | https://github.com/PaloAltoNetworks/pan-os-python/blob/30f6cd9e29d0e3c2549d46c722f6dcb507acd437/panos/base.py#L4033-L4044 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/combinat/superpartition.py | python | SuperPartitions_n_m.__contains__ | (self, x) | TESTS::
sage: [[3,2,1,0],[2]] in SuperPartitions(8,4)
True
sage: [[3,2,1,0],[]] in SuperPartitions(6,3)
False
sage: [[],[]] in SuperPartitions(0,0)
True
sage: [[0],[]] in SuperPartitions(0,1)
True
sage: [[],[]] in SuperPartitions(0,1)
False
sage: [-3,-2,-1,0,2] in SuperPartitions(8,4)
True
sage: [0] in SuperPartitions(0,0)
False
sage: [] in SuperPartitions(0,0)
True
sage: [0] in SuperPartitions(0,1)
True | TESTS:: | [
"TESTS",
"::"
] | def __contains__(self, x) -> bool:
"""
TESTS::
sage: [[3,2,1,0],[2]] in SuperPartitions(8,4)
True
sage: [[3,2,1,0],[]] in SuperPartitions(6,3)
False
sage: [[],[]] in SuperPartitions(0,0)
True
sage: [[0],[]] in SuperPartitions(0,1)
True
sage: [[],[]] in SuperPartitions(0,1)
False
sage: [-3,-2,-1,0,2] in SuperPartitions(8,4)
True
sage: [0] in SuperPartitions(0,0)
False
sage: [] in SuperPartitions(0,0)
True
sage: [0] in SuperPartitions(0,1)
True
"""
if x in SuperPartitions():
if not x:
return self.n == 0 and self.m == 0
if isinstance(x[0], (list, tuple)):
n = sum(x[0] + x[1])
m = len(x[0])
else:
n = sum(abs(a) for a in x)
m = len([a for a in x if a <= 0])
return n == self.n and m == self.m
else:
return False | [
"def",
"__contains__",
"(",
"self",
",",
"x",
")",
"->",
"bool",
":",
"if",
"x",
"in",
"SuperPartitions",
"(",
")",
":",
"if",
"not",
"x",
":",
"return",
"self",
".",
"n",
"==",
"0",
"and",
"self",
".",
"m",
"==",
"0",
"if",
"isinstance",
"(",
... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/superpartition.py#L1032-L1066 | ||
RealHacker/leetcode-solutions | 50b21ea270dd095bef0b21e4e8bd79c1f279a85a | 216_combination_sum_iii/combination_sum_iii.py | python | Solution.combinationSum3 | (self, k, n) | return self.result | :type k: int
:type n: int
:rtype: List[List[int]] | :type k: int
:type n: int
:rtype: List[List[int]] | [
":",
"type",
"k",
":",
"int",
":",
"type",
"n",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"List",
"[",
"int",
"]]"
] | def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
self.result = []
self.recurse(k, n, [], 0)
return self.result | [
"def",
"combinationSum3",
"(",
"self",
",",
"k",
",",
"n",
")",
":",
"self",
".",
"result",
"=",
"[",
"]",
"self",
".",
"recurse",
"(",
"k",
",",
"n",
",",
"[",
"]",
",",
"0",
")",
"return",
"self",
".",
"result"
] | https://github.com/RealHacker/leetcode-solutions/blob/50b21ea270dd095bef0b21e4e8bd79c1f279a85a/216_combination_sum_iii/combination_sum_iii.py#L2-L11 | |
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | txdav/xml/parser_sax.py | python | WebDAVContentHandler.endDocument | (self) | [] | def endDocument(self):
top = self.stack[-1]
assert top["name"] is None
assert top["class"] is None
assert top["attributes"] is None
assert len(top["children"]) is 1, "Must have exactly one root element, got %d" % len(top["children"])
self.dom = WebDAVDocument(top["children"][0])
del(self.unknownElementClasses) | [
"def",
"endDocument",
"(",
"self",
")",
":",
"top",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"assert",
"top",
"[",
"\"name\"",
"]",
"is",
"None",
"assert",
"top",
"[",
"\"class\"",
"]",
"is",
"None",
"assert",
"top",
"[",
"\"attributes\"",
"]",... | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/xml/parser_sax.py#L64-L73 | ||||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/jinja2/filters.py | python | do_reject | (*args, **kwargs) | return _select_or_reject(args, kwargs, lambda x: not x, False) | Filters a sequence of objects by appying a test to either the object
or the attribute and rejecting the ones with the test succeeding.
Example usage:
.. sourcecode:: jinja
{{ numbers|reject("odd") }}
.. versionadded:: 2.7 | Filters a sequence of objects by appying a test to either the object
or the attribute and rejecting the ones with the test succeeding. | [
"Filters",
"a",
"sequence",
"of",
"objects",
"by",
"appying",
"a",
"test",
"to",
"either",
"the",
"object",
"or",
"the",
"attribute",
"and",
"rejecting",
"the",
"ones",
"with",
"the",
"test",
"succeeding",
"."
] | def do_reject(*args, **kwargs):
"""Filters a sequence of objects by appying a test to either the object
or the attribute and rejecting the ones with the test succeeding.
Example usage:
.. sourcecode:: jinja
{{ numbers|reject("odd") }}
.. versionadded:: 2.7
"""
return _select_or_reject(args, kwargs, lambda x: not x, False) | [
"def",
"do_reject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_select_or_reject",
"(",
"args",
",",
"kwargs",
",",
"lambda",
"x",
":",
"not",
"x",
",",
"False",
")"
] | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/jinja2/filters.py#L860-L872 | |
AB-CE/abce | 5dcd5232829a63309bc26144e85b1febdc4162a6 | abcEconomics/contracts/flexiblecontracting.py | python | bound_zero | (x) | asserts that variable is above zero, where foating point imprecission is accounted for,
and than makes sure it is above 0, without floating point imprecission | asserts that variable is above zero, where foating point imprecission is accounted for,
and than makes sure it is above 0, without floating point imprecission | [
"asserts",
"that",
"variable",
"is",
"above",
"zero",
"where",
"foating",
"point",
"imprecission",
"is",
"accounted",
"for",
"and",
"than",
"makes",
"sure",
"it",
"is",
"above",
"0",
"without",
"floating",
"point",
"imprecission"
] | def bound_zero(x):
""" asserts that variable is above zero, where foating point imprecission is accounted for,
and than makes sure it is above 0, without floating point imprecission """
assert x > - epsilon, \
'%.30f is smaller than 0 - epsilon (%.30f)' % (x, - epsilon)
if x < 0:
return 0
else:
return x | [
"def",
"bound_zero",
"(",
"x",
")",
":",
"assert",
"x",
">",
"-",
"epsilon",
",",
"'%.30f is smaller than 0 - epsilon (%.30f)'",
"%",
"(",
"x",
",",
"-",
"epsilon",
")",
"if",
"x",
"<",
"0",
":",
"return",
"0",
"else",
":",
"return",
"x"
] | https://github.com/AB-CE/abce/blob/5dcd5232829a63309bc26144e85b1febdc4162a6/abcEconomics/contracts/flexiblecontracting.py#L352-L360 | ||
ctxis/canape | 5f0e03424577296bcc60c2008a60a98ec5307e4b | CANAPE.Scripting/Lib/cgi.py | python | parse_header | (line) | return key, pdict | Parse a Content-type like header.
Return the main content-type and a dictionary of options. | Parse a Content-type like header. | [
"Parse",
"a",
"Content",
"-",
"type",
"like",
"header",
"."
] | def parse_header(line):
"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
"""
parts = _parseparam(';' + line)
key = parts.next()
pdict = {}
for p in parts:
i = p.find('=')
if i >= 0:
name = p[:i].strip().lower()
value = p[i+1:].strip()
if len(value) >= 2 and value[0] == value[-1] == '"':
value = value[1:-1]
value = value.replace('\\\\', '\\').replace('\\"', '"')
pdict[name] = value
return key, pdict | [
"def",
"parse_header",
"(",
"line",
")",
":",
"parts",
"=",
"_parseparam",
"(",
"';'",
"+",
"line",
")",
"key",
"=",
"parts",
".",
"next",
"(",
")",
"pdict",
"=",
"{",
"}",
"for",
"p",
"in",
"parts",
":",
"i",
"=",
"p",
".",
"find",
"(",
"'='",... | https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/cgi.py#L304-L322 | |
openseg-group/OCNet.pytorch | 812cc57b560fe7fb3b3d9c80da5db80d1e83fbaa | utils/files.py | python | save_checkpoint | (state, args, is_best, filename='checkpoint.pth.tar') | Saves checkpoint to disk | Saves checkpoint to disk | [
"Saves",
"checkpoint",
"to",
"disk"
] | def save_checkpoint(state, args, is_best, filename='checkpoint.pth.tar'):
"""Saves checkpoint to disk"""
directory = "runs/%s/%s/%s/"%(args.dataset, args.model, args.checkname)
if not os.path.exists(directory):
os.makedirs(directory)
filename = directory + filename
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, directory + 'model_best.pth.tar') | [
"def",
"save_checkpoint",
"(",
"state",
",",
"args",
",",
"is_best",
",",
"filename",
"=",
"'checkpoint.pth.tar'",
")",
":",
"directory",
"=",
"\"runs/%s/%s/%s/\"",
"%",
"(",
"args",
".",
"dataset",
",",
"args",
".",
"model",
",",
"args",
".",
"checkname",
... | https://github.com/openseg-group/OCNet.pytorch/blob/812cc57b560fe7fb3b3d9c80da5db80d1e83fbaa/utils/files.py#L11-L19 | ||
spack/spack | 675210bd8bd1c5d32ad1cc83d898fb43b569ed74 | lib/spack/llnl/util/tty/log.py | python | _file_descriptors_work | (*streams) | Whether we can get file descriptors for the streams specified.
This tries to call ``fileno()`` on all streams in the argument list,
and returns ``False`` if anything goes wrong.
This can happen, when, e.g., the test framework replaces stdout with
a ``StringIO`` object.
We have to actually try this to see whether it works, rather than
checking for the fileno attribute, beacuse frameworks like pytest add
dummy fileno methods on their dummy file objects that return
``UnsupportedOperationErrors``. | Whether we can get file descriptors for the streams specified. | [
"Whether",
"we",
"can",
"get",
"file",
"descriptors",
"for",
"the",
"streams",
"specified",
"."
] | def _file_descriptors_work(*streams):
"""Whether we can get file descriptors for the streams specified.
This tries to call ``fileno()`` on all streams in the argument list,
and returns ``False`` if anything goes wrong.
This can happen, when, e.g., the test framework replaces stdout with
a ``StringIO`` object.
We have to actually try this to see whether it works, rather than
checking for the fileno attribute, beacuse frameworks like pytest add
dummy fileno methods on their dummy file objects that return
``UnsupportedOperationErrors``.
"""
# test whether we can get fds for out and error
try:
for stream in streams:
stream.fileno()
return True
except BaseException:
return False | [
"def",
"_file_descriptors_work",
"(",
"*",
"streams",
")",
":",
"# test whether we can get fds for out and error",
"try",
":",
"for",
"stream",
"in",
"streams",
":",
"stream",
".",
"fileno",
"(",
")",
"return",
"True",
"except",
"BaseException",
":",
"return",
"Fa... | https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/llnl/util/tty/log.py#L272-L293 | ||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/models/speech_to_text/modeling_speech_to_text.py | python | Speech2TextSinusoidalPositionalEmbedding.forward | (self, input_ids: torch.Tensor, past_key_values_length: int = 0) | return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, -1).detach() | [] | def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
bsz, seq_len = input_ids.size()
# Create the position ids from the input token ids. Any padded tokens remain padded.
position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
input_ids.device
)
# expand embeddings if needed
max_pos = self.padding_idx + 1 + seq_len
if max_pos > self.weights.size(0):
self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, -1).detach() | [
"def",
"forward",
"(",
"self",
",",
"input_ids",
":",
"torch",
".",
"Tensor",
",",
"past_key_values_length",
":",
"int",
"=",
"0",
")",
":",
"bsz",
",",
"seq_len",
"=",
"input_ids",
".",
"size",
"(",
")",
"# Create the position ids from the input token ids. Any ... | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/speech_to_text/modeling_speech_to_text.py#L179-L191 | |||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_label.py | python | Utils.create_tmpfile_copy | (inc_file) | return tmpfile | create a temporary copy of a file | create a temporary copy of a file | [
"create",
"a",
"temporary",
"copy",
"of",
"a",
"file"
] | def create_tmpfile_copy(inc_file):
'''create a temporary copy of a file'''
tmpfile = Utils.create_tmpfile('lib_openshift-')
Utils._write(tmpfile, open(inc_file).read())
# Cleanup the tmpfile
atexit.register(Utils.cleanup, [tmpfile])
return tmpfile | [
"def",
"create_tmpfile_copy",
"(",
"inc_file",
")",
":",
"tmpfile",
"=",
"Utils",
".",
"create_tmpfile",
"(",
"'lib_openshift-'",
")",
"Utils",
".",
"_write",
"(",
"tmpfile",
",",
"open",
"(",
"inc_file",
")",
".",
"read",
"(",
")",
")",
"# Cleanup the tmpfi... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_label.py#L1213-L1221 | |
1040003585/WebScrapingWithPython | a770fa5b03894076c8c9539b1ffff34424ffc016 | portia_examle/lib/python2.7/site-packages/pip/_vendor/ipaddress.py | python | IPv4Address.packed | (self) | return v4_int_to_packed(self._ip) | The binary representation of this address. | The binary representation of this address. | [
"The",
"binary",
"representation",
"of",
"this",
"address",
"."
] | def packed(self):
"""The binary representation of this address."""
return v4_int_to_packed(self._ip) | [
"def",
"packed",
"(",
"self",
")",
":",
"return",
"v4_int_to_packed",
"(",
"self",
".",
"_ip",
")"
] | https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/portia_examle/lib/python2.7/site-packages/pip/_vendor/ipaddress.py#L1412-L1414 | |
saymedia/remoteobjects | d250e9a0e53c53744cb16c5fb2dc136df3785c1f | remoteobjects/fields.py | python | Constant.encode | (self, value) | return self.value | [] | def encode(self, value):
# Don't even bother caring what we were given; it's our constant.
return self.value | [
"def",
"encode",
"(",
"self",
",",
"value",
")",
":",
"# Don't even bother caring what we were given; it's our constant.",
"return",
"self",
".",
"value"
] | https://github.com/saymedia/remoteobjects/blob/d250e9a0e53c53744cb16c5fb2dc136df3785c1f/remoteobjects/fields.py#L249-L251 | |||
robotlearn/pyrobolearn | 9cd7c060723fda7d2779fa255ac998c2c82b8436 | pyrobolearn/simulators/mujoco.py | python | Mujoco.set_time_step | (self, time_step) | Set the specified time step in the simulator.
"Warning: in many cases it is best to leave the timeStep to default, which is 240Hz. Several parameters are
tuned with this value in mind. For example the number of solver iterations and the error reduction parameters
(erp) for contact, friction and non-contact joints are related to the time step. If you change the time step,
you may need to re-tune those values accordingly, especially the erp values.
You can set the physics engine timestep that is used when calling 'stepSimulation'. It is best to only call
this method at the start of a simulation. Don't change this time step regularly. setTimeStep can also be
achieved using the new setPhysicsEngineParameter API." [1]
Args:
time_step (float): Each time you call 'step' the time step will proceed with 'time_step'. | Set the specified time step in the simulator. | [
"Set",
"the",
"specified",
"time",
"step",
"in",
"the",
"simulator",
"."
] | def set_time_step(self, time_step): # TODO: modify the option tag
"""Set the specified time step in the simulator.
"Warning: in many cases it is best to leave the timeStep to default, which is 240Hz. Several parameters are
tuned with this value in mind. For example the number of solver iterations and the error reduction parameters
(erp) for contact, friction and non-contact joints are related to the time step. If you change the time step,
you may need to re-tune those values accordingly, especially the erp values.
You can set the physics engine timestep that is used when calling 'stepSimulation'. It is best to only call
this method at the start of a simulation. Don't change this time step regularly. setTimeStep can also be
achieved using the new setPhysicsEngineParameter API." [1]
Args:
time_step (float): Each time you call 'step' the time step will proceed with 'time_step'.
"""
# self.sim.model.opt.timestep = time_step
time_step = self._parser.convert_attribute_to_string(time_step)
self._parser.option_tag.attrib.setdefault('timestep', time_step)
self._update_sim() | [
"def",
"set_time_step",
"(",
"self",
",",
"time_step",
")",
":",
"# TODO: modify the option tag",
"# self.sim.model.opt.timestep = time_step",
"time_step",
"=",
"self",
".",
"_parser",
".",
"convert_attribute_to_string",
"(",
"time_step",
")",
"self",
".",
"_parser",
".... | https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/simulators/mujoco.py#L1054-L1071 | ||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py | python | Polynomial_padic_capped_relative_dense._quo_rem_list | (self, right, secure) | return parent(q), parent(a[:db]) | An implementation of quo_rem using lists of coefficients.
Faster than :meth:`_quo_rem_naive`.
AUTHOR:
- Xavier Caruso (2013-03) | An implementation of quo_rem using lists of coefficients. | [
"An",
"implementation",
"of",
"quo_rem",
"using",
"lists",
"of",
"coefficients",
"."
] | def _quo_rem_list(self, right, secure):
"""
An implementation of quo_rem using lists of coefficients.
Faster than :meth:`_quo_rem_naive`.
AUTHOR:
- Xavier Caruso (2013-03)
"""
if right.is_zero():
raise ZeroDivisionError("cannot divide by a polynomial "
"indistinguishable from 0")
a = self.list()
da = len(a) - 1
b = right.list()
db = right.degree(secure=secure)
inv = ~b[db]
q = [ ]
for i in range(da, db - 1, -1):
c = inv * a[i]
q.append(c)
for j in range(db):
a[j + i - db] -= c * b[j]
q.reverse()
K = self.base_ring().fraction_field()
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
parent = PolynomialRing(K, name=self.parent().variable_name())
return parent(q), parent(a[:db]) | [
"def",
"_quo_rem_list",
"(",
"self",
",",
"right",
",",
"secure",
")",
":",
"if",
"right",
".",
"is_zero",
"(",
")",
":",
"raise",
"ZeroDivisionError",
"(",
"\"cannot divide by a polynomial \"",
"\"indistinguishable from 0\"",
")",
"a",
"=",
"self",
".",
"list",... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py#L1092-L1120 | |
simpeg/simpeg | d93145d768b5512621cdd75566b4a8175fee9ed3 | SimPEG/electromagnetics/natural_source/fields.py | python | Fields3DPrimarySecondary._e_pxPrimary | (self, e_pxSolution, source_list) | return e_pxPrimary | px polarization of primary electric field from source
:param numpy.ndarray e_pxSolution: px polarization that was solved for
:param list source_list: list of sources
:rtype: numpy.ndarray
:return: primary electric field as defined by the sources | px polarization of primary electric field from source | [
"px",
"polarization",
"of",
"primary",
"electric",
"field",
"from",
"source"
] | def _e_pxPrimary(self, e_pxSolution, source_list):
"""
px polarization of primary electric field from source
:param numpy.ndarray e_pxSolution: px polarization that was solved for
:param list source_list: list of sources
:rtype: numpy.ndarray
:return: primary electric field as defined by the sources
"""
e_pxPrimary = np.zeros_like(e_pxSolution)
for i, src in enumerate(source_list):
ep = src.ePrimary(self.simulation)
if ep is not None:
e_pxPrimary[:, i] = ep[:, 0]
return e_pxPrimary | [
"def",
"_e_pxPrimary",
"(",
"self",
",",
"e_pxSolution",
",",
"source_list",
")",
":",
"e_pxPrimary",
"=",
"np",
".",
"zeros_like",
"(",
"e_pxSolution",
")",
"for",
"i",
",",
"src",
"in",
"enumerate",
"(",
"source_list",
")",
":",
"ep",
"=",
"src",
".",
... | https://github.com/simpeg/simpeg/blob/d93145d768b5512621cdd75566b4a8175fee9ed3/SimPEG/electromagnetics/natural_source/fields.py#L251-L265 | |
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/requests/models.py | python | PreparedRequest.prepare | (self, method=None, url=None, headers=None, files=None,
data=None, params=None, auth=None, cookies=None, hooks=None,
json=None) | Prepares the entire request with the given parameters. | Prepares the entire request with the given parameters. | [
"Prepares",
"the",
"entire",
"request",
"with",
"the",
"given",
"parameters",
"."
] | def prepare(self, method=None, url=None, headers=None, files=None,
data=None, params=None, auth=None, cookies=None, hooks=None,
json=None):
"""Prepares the entire request with the given parameters."""
self.prepare_method(method)
self.prepare_url(url, params)
self.prepare_headers(headers)
self.prepare_cookies(cookies)
self.prepare_body(data, files, json)
self.prepare_auth(auth, url)
# Note that prepare_auth must be last to enable authentication schemes
# such as OAuth to work on a fully prepared request.
# This MUST go after prepare_auth. Authenticators could add a hook
self.prepare_hooks(hooks) | [
"def",
"prepare",
"(",
"self",
",",
"method",
"=",
"None",
",",
"url",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"files",
"=",
"None",
",",
"data",
"=",
"None",
",",
"params",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"cookies",
"=",
"None... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/requests/models.py#L298-L313 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/asn1crypto/crl.py | python | CertificateList.sha1 | (self) | return self._sha1 | :return:
The SHA1 hash of the DER-encoded bytes of this certificate list | :return:
The SHA1 hash of the DER-encoded bytes of this certificate list | [
":",
"return",
":",
"The",
"SHA1",
"hash",
"of",
"the",
"DER",
"-",
"encoded",
"bytes",
"of",
"this",
"certificate",
"list"
] | def sha1(self):
"""
:return:
The SHA1 hash of the DER-encoded bytes of this certificate list
"""
if self._sha1 is None:
self._sha1 = hashlib.sha1(self.dump()).digest()
return self._sha1 | [
"def",
"sha1",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sha1",
"is",
"None",
":",
"self",
".",
"_sha1",
"=",
"hashlib",
".",
"sha1",
"(",
"self",
".",
"dump",
"(",
")",
")",
".",
"digest",
"(",
")",
"return",
"self",
".",
"_sha1"
] | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/asn1crypto/crl.py#L517-L525 | |
dranjan/python-plyfile | 54ea588490c2dba30579065b38a8a347519868b0 | plyfile.py | python | PlyProperty.__repr__ | (self) | return 'PlyProperty(%r, %r)' % (self.name,
_lookup_type(self.val_dtype)) | [] | def __repr__(self):
return 'PlyProperty(%r, %r)' % (self.name,
_lookup_type(self.val_dtype)) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'PlyProperty(%r, %r)'",
"%",
"(",
"self",
".",
"name",
",",
"_lookup_type",
"(",
"self",
".",
"val_dtype",
")",
")"
] | https://github.com/dranjan/python-plyfile/blob/54ea588490c2dba30579065b38a8a347519868b0/plyfile.py#L872-L874 | |||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/encodings/cp424.py | python | IncrementalEncoder.encode | (self, input, final=False) | return codecs.charmap_encode(input,self.errors,encoding_table)[0] | [] | def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0] | [
"def",
"encode",
"(",
"self",
",",
"input",
",",
"final",
"=",
"False",
")",
":",
"return",
"codecs",
".",
"charmap_encode",
"(",
"input",
",",
"self",
".",
"errors",
",",
"encoding_table",
")",
"[",
"0",
"]"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/encodings/cp424.py#L18-L19 | |||
FarMcKon/gitmarks_2 | 44c04494627c422d85ac3d836715fa9944c779e0 | gitmark_add.py | python | isInGitmarkPublicRepo | (gitmarkObj) | return os.path.isfile(filename) | Checks if a gitmarks object is already in the public repository
by checking for it's' hash in our public bookmarks directory. | Checks if a gitmarks object is already in the public repository
by checking for it's' hash in our public bookmarks directory. | [
"Checks",
"if",
"a",
"gitmarks",
"object",
"is",
"already",
"in",
"the",
"public",
"repository",
"by",
"checking",
"for",
"it",
"s",
"hash",
"in",
"our",
"public",
"bookmarks",
"directory",
"."
] | def isInGitmarkPublicRepo(gitmarkObj):
""" Checks if a gitmarks object is already in the public repository
by checking for it's' hash in our public bookmarks directory. """
if(gitmarkObj.hash == None):
return False
filename = os.path.join(settings.GITMARK_BASE_DIR, settings.PUBLIC_GITMARK_REPO_DIR,
settings.BOOKMARK_SUB_PATH, gitmarkObj.hash)
return os.path.isfile(filename) | [
"def",
"isInGitmarkPublicRepo",
"(",
"gitmarkObj",
")",
":",
"if",
"(",
"gitmarkObj",
".",
"hash",
"==",
"None",
")",
":",
"return",
"False",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"GITMARK_BASE_DIR",
",",
"settings",
".",
... | https://github.com/FarMcKon/gitmarks_2/blob/44c04494627c422d85ac3d836715fa9944c779e0/gitmark_add.py#L251-L258 | |
pantsbuild/pants | 2e126e78ffc40cb108408316b90e8beebee1df9e | src/python/pants/option/arg_splitter.py | python | ArgSplitter.split_args | (self, args: Sequence[str]) | return SplitArgs(
builtin_goal=builtin_goal,
goals=list(goals),
unknown_goals=unknown_scopes,
scope_to_flags=dict(scope_to_flags),
specs=specs,
passthru=passthru,
) | Split the specified arg list (or sys.argv if unspecified).
args[0] is ignored.
Returns a SplitArgs tuple. | Split the specified arg list (or sys.argv if unspecified). | [
"Split",
"the",
"specified",
"arg",
"list",
"(",
"or",
"sys",
".",
"argv",
"if",
"unspecified",
")",
"."
] | def split_args(self, args: Sequence[str]) -> SplitArgs:
"""Split the specified arg list (or sys.argv if unspecified).
args[0] is ignored.
Returns a SplitArgs tuple.
"""
goals: OrderedSet[str] = OrderedSet()
scope_to_flags: DefaultDict[str, list[str]] = defaultdict(list)
specs: list[str] = []
passthru: list[str] = []
unknown_scopes: list[str] = []
builtin_goal: str | None = None
def add_scope(s: str) -> None:
# Force the scope to appear, even if empty.
if s not in scope_to_flags:
scope_to_flags[s] = []
def add_goal(scope: str) -> str:
"""Returns the scope name to assign flags to."""
scope_info = self._known_goal_scopes.get(scope)
if not scope_info:
unknown_scopes.append(scope)
add_scope(scope)
return scope
nonlocal builtin_goal
if scope_info.is_builtin and not builtin_goal:
# Get scope from info in case we hit an aliased builtin goal.
builtin_goal = scope_info.scope
else:
goals.add(scope_info.scope)
add_scope(scope_info.scope)
# Use builtin goal as default scope for args.
return builtin_goal or scope_info.scope
self._unconsumed_args = list(reversed(args))
# The first token is the binary name, so skip it.
self._unconsumed_args.pop()
def assign_flag_to_scope(flg: str, default_scope: str) -> None:
flag_scope, descoped_flag = self._descope_flag(flg, default_scope=default_scope)
scope_to_flags[flag_scope].append(descoped_flag)
global_flags = self._consume_flags()
add_scope(GLOBAL_SCOPE)
for flag in global_flags:
assign_flag_to_scope(flag, GLOBAL_SCOPE)
scope, flags = self._consume_scope()
while scope:
# `add_goal` returns the currently active scope to assign flags to.
scope = add_goal(scope)
for flag in flags:
assign_flag_to_scope(flag, scope)
scope, flags = self._consume_scope()
while self._unconsumed_args and not self._at_double_dash():
if self._at_flag():
arg = self._unconsumed_args.pop()
# We assume any args here are in global scope.
assign_flag_to_scope(arg, GLOBAL_SCOPE)
continue
arg = self._unconsumed_args.pop()
if self.likely_a_spec(arg):
specs.append(arg)
else:
add_goal(arg)
if not builtin_goal:
if unknown_scopes and UNKNOWN_GOAL_NAME in self._known_goal_scopes:
builtin_goal = UNKNOWN_GOAL_NAME
elif not goals and NO_GOAL_NAME in self._known_goal_scopes:
builtin_goal = NO_GOAL_NAME
if self._at_double_dash():
self._unconsumed_args.pop()
passthru = list(reversed(self._unconsumed_args))
for goal in goals:
si = self._known_goal_scopes[goal]
if (
si.deprecated_scope
and goal == si.deprecated_scope
and si.subsystem_cls
and si.deprecated_scope_removal_version
):
warn_or_error(
si.deprecated_scope_removal_version,
f"the {si.deprecated_scope} goal",
f"The {si.deprecated_scope} goal was renamed to {si.subsystem_cls.options_scope}",
)
return SplitArgs(
builtin_goal=builtin_goal,
goals=list(goals),
unknown_goals=unknown_scopes,
scope_to_flags=dict(scope_to_flags),
specs=specs,
passthru=passthru,
) | [
"def",
"split_args",
"(",
"self",
",",
"args",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"SplitArgs",
":",
"goals",
":",
"OrderedSet",
"[",
"str",
"]",
"=",
"OrderedSet",
"(",
")",
"scope_to_flags",
":",
"DefaultDict",
"[",
"str",
",",
"list",
"[",
... | https://github.com/pantsbuild/pants/blob/2e126e78ffc40cb108408316b90e8beebee1df9e/src/python/pants/option/arg_splitter.py#L118-L221 | |
gregversteeg/bio_corex | ce450c8562679a21959ecfe94843e1fe4dc79ca4 | corex.py | python | Corex.marginal_p | (self, xi, thetai) | Estimate marginals, log p(xi|yj) for each possible type. | Estimate marginals, log p(xi|yj) for each possible type. | [
"Estimate",
"marginals",
"log",
"p",
"(",
"xi|yj",
")",
"for",
"each",
"possible",
"type",
"."
] | def marginal_p(self, xi, thetai):
"""Estimate marginals, log p(xi|yj) for each possible type. """
if self.marginal_description == 'gaussian':
mu, sig = thetai # mu, sig have size m by k
xi = xi.reshape((-1, 1, 1))
return (-(xi - mu)**2 / (2. * sig) - 0.5 * np.log(2 * np.pi * sig)).transpose((1, 0, 2)) # log p(xi|yj)
elif self.marginal_description == 'discrete':
# Discrete data: should be non-negative integers starting at 0: 0,...k. k < 32 because of np.choose limits
logp = [theta[np.newaxis, ...] for theta in thetai] # Size dim_visible by n_hidden by dim_hidden
return np.choose(xi.reshape((-1, 1, 1)), logp).transpose((1, 0, 2))
else:
print('Marginal description "%s" not implemented.' % self.marginal_description)
sys.exit() | [
"def",
"marginal_p",
"(",
"self",
",",
"xi",
",",
"thetai",
")",
":",
"if",
"self",
".",
"marginal_description",
"==",
"'gaussian'",
":",
"mu",
",",
"sig",
"=",
"thetai",
"# mu, sig have size m by k",
"xi",
"=",
"xi",
".",
"reshape",
"(",
"(",
"-",
"1",
... | https://github.com/gregversteeg/bio_corex/blob/ce450c8562679a21959ecfe94843e1fe4dc79ca4/corex.py#L492-L506 | ||
pyg-team/pytorch_geometric | b920e9a3a64e22c8356be55301c88444ff051cae | torch_geometric/data/temporal.py | python | TemporalData.__repr__ | (self) | return f'{cls}({shapes})' | [] | def __repr__(self):
cls = str(self.__class__.__name__)
shapes = ', '.join([f'{k}={list(v.shape)}' for k, v in self])
return f'{cls}({shapes})' | [
"def",
"__repr__",
"(",
"self",
")",
":",
"cls",
"=",
"str",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
"shapes",
"=",
"', '",
".",
"join",
"(",
"[",
"f'{k}={list(v.shape)}'",
"for",
"k",
",",
"v",
"in",
"self",
"]",
")",
"return",
"f'{cls}... | https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/data/temporal.py#L116-L119 | |||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | scripts/Samples/HideLines.py | python | find_correspondig_marker | (next_marker_line, searching_marker_mask) | return next_marker_line | [] | def find_correspondig_marker(next_marker_line, searching_marker_mask):
start_marker_count = 0
end_marker_count = 0
# to avoid having two functions, markerNext or markerPrevious
# gets assigned to find_marker variable
if searching_marker_mask == MARK_HIDELINESEND_MASK:
find_marker = editor.markerNext
add_to_line_value = 1
start_marker_count = 1
else:
find_marker = editor.markerPrevious
add_to_line_value = -1
end_marker_count = 1
# the idea is to search as long for start and end markers
# until we get the same amount for both
while (start_marker_count != end_marker_count):
next_marker_line = find_marker(next_marker_line+add_to_line_value, MARK_COMBINED_MASK)
if (next_marker_line != -1):
if (editor.markerGet(next_marker_line) & MARK_COMBINED_MASK) == MARK_COMBINED_MASK:
if searching_marker_mask == MARK_HIDELINESEND_MASK:
end_marker_count += 1
if end_marker_count == start_marker_count:
break # found the matching marker
start_marker_count += 1
else:
start_marker_count += 1
if end_marker_count == start_marker_count:
break # found the matching marker
end_marker_count += 1
elif editor.markerGet(next_marker_line) & MARK_HIDELINESBEGIN_MASK:
start_marker_count += 1
elif editor.markerGet(next_marker_line) & MARK_HIDELINESEND_MASK:
end_marker_count += 1
else:
msg = 'Now we are in trouble - should not happen !! ??'
notepad.messageBox(msg, 'ERROR')
list_all_markers() # only used for debugging purpose
next_marker_line = -1
break
return next_marker_line | [
"def",
"find_correspondig_marker",
"(",
"next_marker_line",
",",
"searching_marker_mask",
")",
":",
"start_marker_count",
"=",
"0",
"end_marker_count",
"=",
"0",
"# to avoid having two functions, markerNext or markerPrevious",
"# gets assigned to find_marker variable",
"if",
"searc... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/scripts/Samples/HideLines.py#L132-L181 | |||
TophantTechnology/osprey | addf0edc75bb68d0534b624a50c5c10c131f3e33 | thirdparty/requests_toolbelt/threaded/pool.py | python | Pool.responses | (self) | Iterate over all the responses in the pool.
:returns: Generator of :class:`~ThreadResponse` | Iterate over all the responses in the pool. | [
"Iterate",
"over",
"all",
"the",
"responses",
"in",
"the",
"pool",
"."
] | def responses(self):
"""Iterate over all the responses in the pool.
:returns: Generator of :class:`~ThreadResponse`
"""
while True:
resp = self.get_response()
if resp is None:
break
yield resp | [
"def",
"responses",
"(",
"self",
")",
":",
"while",
"True",
":",
"resp",
"=",
"self",
".",
"get_response",
"(",
")",
"if",
"resp",
"is",
"None",
":",
"break",
"yield",
"resp"
] | https://github.com/TophantTechnology/osprey/blob/addf0edc75bb68d0534b624a50c5c10c131f3e33/thirdparty/requests_toolbelt/threaded/pool.py#L133-L142 | ||
smart-on-fhir/client-py | 6047277daa31f10931e44ed19e92128298cdb64b | fhirclient/models/invoice.py | python | Invoice.__init__ | (self, jsondict=None, strict=True) | Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError | Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError | [
"Initialize",
"all",
"valid",
"properties",
".",
":",
"raises",
":",
"FHIRValidationError",
"on",
"validation",
"errors",
"unless",
"strict",
"is",
"False",
":",
"param",
"dict",
"jsondict",
":",
"A",
"JSON",
"dictionary",
"to",
"use",
"for",
"initialization",
... | def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.account = None
""" Account that is being balanced.
Type `FHIRReference` (represented as `dict` in JSON). """
self.cancelledReason = None
""" Reason for cancellation of this Invoice.
Type `str`. """
self.date = None
""" Invoice date / posting date.
Type `FHIRDate` (represented as `str` in JSON). """
self.identifier = None
""" Business Identifier for item.
List of `Identifier` items (represented as `dict` in JSON). """
self.issuer = None
""" Issuing Organization of Invoice.
Type `FHIRReference` (represented as `dict` in JSON). """
self.lineItem = None
""" Line items of this Invoice.
List of `InvoiceLineItem` items (represented as `dict` in JSON). """
self.note = None
""" Comments made about the invoice.
List of `Annotation` items (represented as `dict` in JSON). """
self.participant = None
""" Participant in creation of this Invoice.
List of `InvoiceParticipant` items (represented as `dict` in JSON). """
self.paymentTerms = None
""" Payment details.
Type `str`. """
self.recipient = None
""" Recipient of this invoice.
Type `FHIRReference` (represented as `dict` in JSON). """
self.status = None
""" draft | issued | balanced | cancelled | entered-in-error.
Type `str`. """
self.subject = None
""" Recipient(s) of goods and services.
Type `FHIRReference` (represented as `dict` in JSON). """
self.totalGross = None
""" Gross total of this Invoice.
Type `Money` (represented as `dict` in JSON). """
self.totalNet = None
""" Net total of this Invoice.
Type `Money` (represented as `dict` in JSON). """
self.totalPriceComponent = None
""" Components of Invoice total.
List of `InvoiceLineItemPriceComponent` items (represented as `dict` in JSON). """
self.type = None
""" Type of Invoice.
Type `CodeableConcept` (represented as `dict` in JSON). """
super(Invoice, self).__init__(jsondict=jsondict, strict=strict) | [
"def",
"__init__",
"(",
"self",
",",
"jsondict",
"=",
"None",
",",
"strict",
"=",
"True",
")",
":",
"self",
".",
"account",
"=",
"None",
"\"\"\" Account that is being balanced.\n Type `FHIRReference` (represented as `dict` in JSON). \"\"\"",
"self",
".",
"cancelled... | https://github.com/smart-on-fhir/client-py/blob/6047277daa31f10931e44ed19e92128298cdb64b/fhirclient/models/invoice.py#L19-L91 | ||
MultiChain/multichain-explorer | 9e850fa79d0759b7348647ccf73a31d387c945a5 | Mce/util.py | python | parse_op_return_data_10007 | (data) | return parse_op_return_data_10006(data) | [] | def parse_op_return_data_10007(data):
return parse_op_return_data_10006(data) | [
"def",
"parse_op_return_data_10007",
"(",
"data",
")",
":",
"return",
"parse_op_return_data_10006",
"(",
"data",
")"
] | https://github.com/MultiChain/multichain-explorer/blob/9e850fa79d0759b7348647ccf73a31d387c945a5/Mce/util.py#L885-L886 | |||
google/pytype | fa43edc95dd42ade6e3147d6580d63e778c9d506 | pytype/state.py | python | Frame.__init__ | (self, node, ctx, f_code, f_globals, f_locals, f_back, callargs,
closure, func, first_arg: Optional[cfg.Variable],
substs: Collection[Dict[str, cfg.Variable]]) | Initialize a special frame as needed by TypegraphVirtualMachine.
Args:
node: The current CFG graph node.
ctx: The owning abstract context.
f_code: The code object to execute in this frame.
f_globals: The global context to execute in as a SimpleValue as
used by TypegraphVirtualMachine.
f_locals: Local variables. Will be modified if callargs is passed.
f_back: The frame above this one on the stack.
callargs: Additional function arguments to store in f_locals.
closure: A tuple containing the new co_freevars.
func: An Optional[cfg.Binding] to the function this frame corresponds to.
first_arg: First argument to the function.
substs: Maps from type parameter names in scope for this frame to their
possible values.
Raises:
NameError: If we can't resolve any references into the outer frame. | Initialize a special frame as needed by TypegraphVirtualMachine. | [
"Initialize",
"a",
"special",
"frame",
"as",
"needed",
"by",
"TypegraphVirtualMachine",
"."
] | def __init__(self, node, ctx, f_code, f_globals, f_locals, f_back, callargs,
closure, func, first_arg: Optional[cfg.Variable],
substs: Collection[Dict[str, cfg.Variable]]):
"""Initialize a special frame as needed by TypegraphVirtualMachine.
Args:
node: The current CFG graph node.
ctx: The owning abstract context.
f_code: The code object to execute in this frame.
f_globals: The global context to execute in as a SimpleValue as
used by TypegraphVirtualMachine.
f_locals: Local variables. Will be modified if callargs is passed.
f_back: The frame above this one on the stack.
callargs: Additional function arguments to store in f_locals.
closure: A tuple containing the new co_freevars.
func: An Optional[cfg.Binding] to the function this frame corresponds to.
first_arg: First argument to the function.
substs: Maps from type parameter names in scope for this frame to their
possible values.
Raises:
NameError: If we can't resolve any references into the outer frame.
"""
super().__init__(ctx)
assert isinstance(f_globals, abstract.LazyConcreteDict)
assert isinstance(f_locals, abstract.LazyConcreteDict)
self.node = node
self.current_opcode = None
self.f_code = f_code
self.states = {}
self.f_globals = f_globals
self.f_locals = f_locals
self.f_back = f_back
if f_back and f_back.f_builtins:
self.f_builtins = f_back.f_builtins
else:
_, bltin = self.ctx.attribute_handler.get_attribute(
self.ctx.root_node, f_globals, "__builtins__")
builtins_pu, = bltin.bindings
self.f_builtins = builtins_pu.data
self.f_lineno = f_code.co_firstlineno
# The first argument is used to make Python 3 super calls when super is not
# passed any arguments.
self.first_arg = first_arg
self.cells = {}
self.allowed_returns = None
self.check_return = False
self.return_variable = self.ctx.program.NewVariable()
self.yield_variable = self.ctx.program.NewVariable()
# Keep track of the current opcode block and and block targets we add while
# executing it; they can potentially be removed if the block returns early.
self.current_block = None
self.targets = collections.defaultdict(list)
# A map from function name to @typing.overload-decorated signatures. The
# overloads are copied to the implementation in InterpreterFunction.make.
self.overloads = collections.defaultdict(list)
# A closure g communicates with its outer function f through two
# fields in CodeType (both of which are tuples of strings):
# f.co_cellvars: All f-local variables that are used in g (or any other
# closure).
# g.co_freevars: All variables from f that g uses.
# Also, note that f.co_cellvars will only also be in f.co_varnames
# if they are also parameters of f (because co_varnames[0:co_argcount] are
# always the parameters), but won't otherwise.
# Cells 0 .. num(cellvars)-1 : cellvar; num(cellvars) .. end : freevar
assert len(f_code.co_freevars) == len(closure or [])
self.cells = [self.ctx.program.NewVariable() for _ in f_code.co_cellvars]
self.cells.extend(closure or [])
if callargs:
for name, value in sorted(callargs.items()):
if name in f_code.co_cellvars:
i = f_code.co_cellvars.index(name)
self.cells[i].PasteVariable(value, node)
else:
self.ctx.attribute_handler.set_attribute(node, f_locals, name, value)
# Python 3 supports calling 'super' without any arguments. In such a case
# the implicit type argument is inserted into __build_class__'s cellvars
# and propagated as a closure variable to all method/functions calling
# 'super' without any arguments.
# If this is a frame for the function called by __build_class__ (see
# abstract.BuildClass), then we will store a reference to the variable
# corresponding to the cellvar named "__class__" separately for convenient
# access. After the class is built, abstract.BuildClass.call will add the
# binding for the new class into this variable.
self.class_closure_var = None
if func and isinstance(func.data, abstract.InterpreterFunction):
closure_name = abstract.BuildClass.CLOSURE_NAME
if func.data.is_class_builder and closure_name in f_code.co_cellvars:
i = f_code.co_cellvars.index(closure_name)
self.class_closure_var = self.cells[i]
self.func = func
self.substs = substs | [
"def",
"__init__",
"(",
"self",
",",
"node",
",",
"ctx",
",",
"f_code",
",",
"f_globals",
",",
"f_locals",
",",
"f_back",
",",
"callargs",
",",
"closure",
",",
"func",
",",
"first_arg",
":",
"Optional",
"[",
"cfg",
".",
"Variable",
"]",
",",
"substs",
... | https://github.com/google/pytype/blob/fa43edc95dd42ade6e3147d6580d63e778c9d506/pytype/state.py#L199-L294 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/django/contrib/admindocs/utils.py | python | parse_rst | (text, default_reference_context, thing_being_parsed=None) | return mark_safe(parts['fragment']) | Convert the string from reST to an XHTML fragment. | Convert the string from reST to an XHTML fragment. | [
"Convert",
"the",
"string",
"from",
"reST",
"to",
"an",
"XHTML",
"fragment",
"."
] | def parse_rst(text, default_reference_context, thing_being_parsed=None):
"""
Convert the string from reST to an XHTML fragment.
"""
overrides = {
'doctitle_xform': True,
'initial_header_level': 3,
"default_reference_context": default_reference_context,
"link_base": reverse('django-admindocs-docroot').rstrip('/'),
'raw_enabled': False,
'file_insertion_enabled': False,
}
if thing_being_parsed:
thing_being_parsed = force_bytes("<%s>" % thing_being_parsed)
# Wrap ``text`` in some reST that sets the default role to ``cmsreference``,
# then restores it.
source = """
.. default-role:: cmsreference
%s
.. default-role::
"""
parts = docutils.core.publish_parts(
source % text,
source_path=thing_being_parsed, destination_path=None,
writer_name='html', settings_overrides=overrides,
)
return mark_safe(parts['fragment']) | [
"def",
"parse_rst",
"(",
"text",
",",
"default_reference_context",
",",
"thing_being_parsed",
"=",
"None",
")",
":",
"overrides",
"=",
"{",
"'doctitle_xform'",
":",
"True",
",",
"'initial_header_level'",
":",
"3",
",",
"\"default_reference_context\"",
":",
"default_... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/admindocs/utils.py#L62-L90 | |
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/beets/dbcore/db.py | python | FormattedMapping.__iter__ | (self) | return iter(self.model_keys) | [] | def __iter__(self):
return iter(self.model_keys) | [
"def",
"__iter__",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"self",
".",
"model_keys",
")"
] | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/beets/dbcore/db.py#L57-L58 | |||
QQuick/Transcrypt | 68b4b71d4ff3e4d58281b24e9e2dcc9fc766e822 | transcrypt/modules/logging/__init__.py | python | Handler.emit | (self, record) | Do whatever it takes to actually log the specified logging record.
This version is intended to be implemented by subclasses and so
raises a NotImplementedError. | Do whatever it takes to actually log the specified logging record. | [
"Do",
"whatever",
"it",
"takes",
"to",
"actually",
"log",
"the",
"specified",
"logging",
"record",
"."
] | def emit(self, record):
"""
Do whatever it takes to actually log the specified logging record.
This version is intended to be implemented by subclasses and so
raises a NotImplementedError.
"""
raise NotImplementedError("Must be implemented by handler") | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Must be implemented by handler\"",
")"
] | https://github.com/QQuick/Transcrypt/blob/68b4b71d4ff3e4d58281b24e9e2dcc9fc766e822/transcrypt/modules/logging/__init__.py#L974-L981 | ||
tosher/Mediawiker | 81bf97cace59bedcb1668e7830b85c36e014428e | lib/Crypto.lin.x64/Crypto/Hash/BLAKE2b.py | python | BLAKE2b_Hash.verify | (self, mac_tag) | Verify that a given **binary** MAC (computed by another party)
is valid.
Args:
mac_tag (byte string/array): the expected MAC of the message.
Raises:
ValueError: if the MAC does not match. It means that the message
has been tampered with or that the MAC key is incorrect. | Verify that a given **binary** MAC (computed by another party)
is valid. | [
"Verify",
"that",
"a",
"given",
"**",
"binary",
"**",
"MAC",
"(",
"computed",
"by",
"another",
"party",
")",
"is",
"valid",
"."
] | def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
Args:
mac_tag (byte string/array): the expected MAC of the message.
Raises:
ValueError: if the MAC does not match. It means that the message
has been tampered with or that the MAC key is incorrect.
"""
secret = get_random_bytes(16)
mac1 = new(digest_bits=160, key=secret, data=mac_tag)
mac2 = new(digest_bits=160, key=secret, data=self.digest())
if mac1.digest() != mac2.digest():
raise ValueError("MAC check failed") | [
"def",
"verify",
"(",
"self",
",",
"mac_tag",
")",
":",
"secret",
"=",
"get_random_bytes",
"(",
"16",
")",
"mac1",
"=",
"new",
"(",
"digest_bits",
"=",
"160",
",",
"key",
"=",
"secret",
",",
"data",
"=",
"mac_tag",
")",
"mac2",
"=",
"new",
"(",
"di... | https://github.com/tosher/Mediawiker/blob/81bf97cace59bedcb1668e7830b85c36e014428e/lib/Crypto.lin.x64/Crypto/Hash/BLAKE2b.py#L150-L168 | ||
tobegit3hub/deep_image_model | 8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e | java_predict_client/src/main/proto/tensorflow/python/ops/control_flow_ops.py | python | exit | (data, name=None) | Exits the current frame to its parent frame.
Exit makes its input `data` available to the parent frame.
Args:
data: The tensor to be made available to the parent frame.
name: A name for this operation (optional).
Returns:
The same tensor as `data`. | Exits the current frame to its parent frame. | [
"Exits",
"the",
"current",
"frame",
"to",
"its",
"parent",
"frame",
"."
] | def exit(data, name=None):
"""Exits the current frame to its parent frame.
Exit makes its input `data` available to the parent frame.
Args:
data: The tensor to be made available to the parent frame.
name: A name for this operation (optional).
Returns:
The same tensor as `data`.
"""
data = ops.convert_to_tensor_or_indexed_slices(data, as_ref=True)
if isinstance(data, ops.Tensor):
if data.dtype.is_ref_dtype:
return gen_control_flow_ops._ref_exit(data, name)
else:
return gen_control_flow_ops._exit(data, name)
else:
if not isinstance(data, (ops.IndexedSlices, sparse_tensor.SparseTensor)):
raise TypeError("Type %s not supported" % type(data))
values = exit(data.values, name=name)
indices = gen_control_flow_ops._exit(data.indices, name="indices")
if isinstance(data, ops.IndexedSlices):
dense_shape = data.dense_shape
if dense_shape is not None:
dense_shape = gen_control_flow_ops._exit(dense_shape, name)
return ops.IndexedSlices(values, indices, dense_shape)
else:
dense_shape = gen_control_flow_ops._exit(data.shape, name)
return sparse_tensor.SparseTensor(indices, values, dense_shape) | [
"def",
"exit",
"(",
"data",
",",
"name",
"=",
"None",
")",
":",
"data",
"=",
"ops",
".",
"convert_to_tensor_or_indexed_slices",
"(",
"data",
",",
"as_ref",
"=",
"True",
")",
"if",
"isinstance",
"(",
"data",
",",
"ops",
".",
"Tensor",
")",
":",
"if",
... | https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/python/ops/control_flow_ops.py#L262-L292 | ||
isnowfy/pydown | 71ecc891868cd2a34b7e5fe662c99474f2d0fd7f | pygments/lexers/hdl.py | python | VerilogLexer.get_tokens_unprocessed | (self, text) | [] | def get_tokens_unprocessed(self, text):
for index, token, value in \
RegexLexer.get_tokens_unprocessed(self, text):
# Convention: mark all upper case names as constants
if token is Name:
if value.isupper():
token = Name.Constant
yield index, token, value | [
"def",
"get_tokens_unprocessed",
"(",
"self",
",",
"text",
")",
":",
"for",
"index",
",",
"token",
",",
"value",
"in",
"RegexLexer",
".",
"get_tokens_unprocessed",
"(",
"self",
",",
"text",
")",
":",
"# Convention: mark all upper case names as constants",
"if",
"t... | https://github.com/isnowfy/pydown/blob/71ecc891868cd2a34b7e5fe662c99474f2d0fd7f/pygments/lexers/hdl.py#L122-L129 | ||||
alegonz/baikal | 332623c1d6121d3321f9cd9972fc36b6d16462d4 | baikal/_core/step.py | python | _StepBase.targets | (self) | return self._get_step_attr("targets") | Get the targets of the step.
You can use this only when the step has been called exactly once.
Returns
-------
List of targets.
Raises
------
AttributeError
If the step has not been called yet or it is a shared step
(called several times). | Get the targets of the step. | [
"Get",
"the",
"targets",
"of",
"the",
"step",
"."
] | def targets(self) -> List[DataPlaceholder]:
"""Get the targets of the step.
You can use this only when the step has been called exactly once.
Returns
-------
List of targets.
Raises
------
AttributeError
If the step has not been called yet or it is a shared step
(called several times).
"""
return self._get_step_attr("targets") | [
"def",
"targets",
"(",
"self",
")",
"->",
"List",
"[",
"DataPlaceholder",
"]",
":",
"return",
"self",
".",
"_get_step_attr",
"(",
"\"targets\"",
")"
] | https://github.com/alegonz/baikal/blob/332623c1d6121d3321f9cd9972fc36b6d16462d4/baikal/_core/step.py#L132-L147 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.