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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
statsmodels/statsmodels | debbe7ea6ba28fe5bdb78f09f8cac694bef98722 | statsmodels/tsa/exponential_smoothing/ets.py | python | ETSModel._loglike_internal | (
self,
params,
yhat,
xhat,
is_fixed=None,
fixed_values=None,
use_beta_star=False,
use_gamma_star=False,
) | return logL | Log-likelihood function to be called from fit to avoid reallocation of
memory.
Parameters
----------
params : np.ndarray of np.float
Model parameters: (alpha, beta, gamma, phi, l[-1],
b[-1], s[-1], ..., s[-m]). If there are no fixed values this must
be in the format of internal parameters. Otherwise the fixed values
are skipped.
yhat : np.ndarray
Array of size (n,) where fitted values will be written to.
xhat : np.ndarray
Array of size (n, _k_states_internal) where fitted states will be
written to.
is_fixed : np.ndarray or None
Boolean array indicating values which are fixed during fitting.
This must have the full length of internal parameters.
fixed_values : np.ndarray or None
Array of fixed values (arbitrary values for non-fixed parameters)
This must have the full length of internal parameters.
use_beta_star : boolean
Whether to internally use beta_star as parameter
use_gamma_star : boolean
Whether to internally use gamma_star as parameter | Log-likelihood function to be called from fit to avoid reallocation of
memory. | [
"Log",
"-",
"likelihood",
"function",
"to",
"be",
"called",
"from",
"fit",
"to",
"avoid",
"reallocation",
"of",
"memory",
"."
] | def _loglike_internal(
self,
params,
yhat,
xhat,
is_fixed=None,
fixed_values=None,
use_beta_star=False,
use_gamma_star=False,
):
"""
Log-likelihood function to be called from fit to avoid reallocation of
memory.
Parameters
----------
params : np.ndarray of np.float
Model parameters: (alpha, beta, gamma, phi, l[-1],
b[-1], s[-1], ..., s[-m]). If there are no fixed values this must
be in the format of internal parameters. Otherwise the fixed values
are skipped.
yhat : np.ndarray
Array of size (n,) where fitted values will be written to.
xhat : np.ndarray
Array of size (n, _k_states_internal) where fitted states will be
written to.
is_fixed : np.ndarray or None
Boolean array indicating values which are fixed during fitting.
This must have the full length of internal parameters.
fixed_values : np.ndarray or None
Array of fixed values (arbitrary values for non-fixed parameters)
This must have the full length of internal parameters.
use_beta_star : boolean
Whether to internally use beta_star as parameter
use_gamma_star : boolean
Whether to internally use gamma_star as parameter
"""
if np.iscomplexobj(params):
data = np.asarray(self.endog, dtype=complex)
else:
data = self.endog
if is_fixed is None:
is_fixed = np.zeros(self._k_params_internal, dtype=int)
fixed_values = np.empty(
self._k_params_internal, dtype=params.dtype
)
self._smoothing_func(
params,
data,
yhat,
xhat,
is_fixed,
fixed_values,
use_beta_star,
use_gamma_star,
)
res = self._residuals(yhat, data=data)
logL = -self.nobs / 2 * (np.log(2 * np.pi * np.mean(res ** 2)) + 1)
if self.error == "mul":
# GH-7331: in some cases, yhat can become negative, so that a
# multiplicative model is no longer well-defined. To avoid these
# parameterizations, we clip negative values to very small positive
# values so that the log-transformation yields very large negative
# values.
yhat[yhat <= 0] = 1 / (1e-8 * (1 + np.abs(yhat[yhat < 0])))
logL -= np.sum(np.log(yhat))
return logL | [
"def",
"_loglike_internal",
"(",
"self",
",",
"params",
",",
"yhat",
",",
"xhat",
",",
"is_fixed",
"=",
"None",
",",
"fixed_values",
"=",
"None",
",",
"use_beta_star",
"=",
"False",
",",
"use_gamma_star",
"=",
"False",
",",
")",
":",
"if",
"np",
".",
"... | https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/tsa/exponential_smoothing/ets.py#L1102-L1170 | |
KhronosGroup/NNEF-Tools | c913758ca687dab8cb7b49e8f1556819a2d0ca25 | nnef_tools/io/tf/lite/flatbuffers/QuantizationParameters.py | python | QuantizationParametersAddScale | (builder, scale) | [] | def QuantizationParametersAddScale(builder, scale): builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(scale), 0) | [
"def",
"QuantizationParametersAddScale",
"(",
"builder",
",",
"scale",
")",
":",
"builder",
".",
"PrependUOffsetTRelativeSlot",
"(",
"2",
",",
"flatbuffers",
".",
"number_types",
".",
"UOffsetTFlags",
".",
"py_type",
"(",
"scale",
")",
",",
"0",
")"
] | https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/io/tf/lite/flatbuffers/QuantizationParameters.py#L164-L164 | ||||
gruns/furl | 63b0bbeb40a8113862a61501cb12f9aad1f321e9 | furl/furl.py | python | Fragment.asdict | (self) | return {
'encoded': str(self),
'separator': self.separator,
'path': self.path.asdict(),
'query': self.query.asdict(),
} | [] | def asdict(self):
return {
'encoded': str(self),
'separator': self.separator,
'path': self.path.asdict(),
'query': self.query.asdict(),
} | [
"def",
"asdict",
"(",
"self",
")",
":",
"return",
"{",
"'encoded'",
":",
"str",
"(",
"self",
")",
",",
"'separator'",
":",
"self",
".",
"separator",
",",
"'path'",
":",
"self",
".",
"path",
".",
"asdict",
"(",
")",
",",
"'query'",
":",
"self",
".",... | https://github.com/gruns/furl/blob/63b0bbeb40a8113862a61501cb12f9aad1f321e9/furl/furl.py#L1261-L1267 | |||
emesene/emesene | 4548a4098310e21b16437bb36223a7f632a4f7bc | emesene/gui/gtkui/MainWindow.py | python | MainWindow.unsubscribe_signals | (self, close=None) | callback called when the disconnect option is selected | callback called when the disconnect option is selected | [
"callback",
"called",
"when",
"the",
"disconnect",
"option",
"is",
"selected"
] | def unsubscribe_signals(self, close=None):
'''callback called when the disconnect option is selected'''
gui.MainWindowBase.unsubscribe_signals(self)
self.menu.remove_subscriptions()
self.contact_list.contact_selected.unsubscribe(
self._on_contact_selected)
self.contact_list.group_selected.unsubscribe(self._on_group_selected)
self.contact_list.contact_menu_selected.unsubscribe(
self._on_contact_menu_selected)
if self.session.session_has_service(e3.Session.SERVICE_GROUP_MANAGING):
self.contact_list.group_menu_selected.unsubscribe(
self._on_group_menu_selected)
self.contact_list.remove_subscriptions()
self.panel.remove_subscriptions()
self.panel = None | [
"def",
"unsubscribe_signals",
"(",
"self",
",",
"close",
"=",
"None",
")",
":",
"gui",
".",
"MainWindowBase",
".",
"unsubscribe_signals",
"(",
"self",
")",
"self",
".",
"menu",
".",
"remove_subscriptions",
"(",
")",
"self",
".",
"contact_list",
".",
"contact... | https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/gui/gtkui/MainWindow.py#L275-L290 | ||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/numpy/distutils/misc_util.py | python | msvc_runtime_library | () | return lib | Return name of MSVC runtime library if Python was built with MSVC >= 7 | Return name of MSVC runtime library if Python was built with MSVC >= 7 | [
"Return",
"name",
"of",
"MSVC",
"runtime",
"library",
"if",
"Python",
"was",
"built",
"with",
"MSVC",
">",
"=",
"7"
] | def msvc_runtime_library():
"Return name of MSVC runtime library if Python was built with MSVC >= 7"
msc_pos = sys.version.find('MSC v.')
if msc_pos != -1:
msc_ver = sys.version[msc_pos+6:msc_pos+10]
lib = {'1300': 'msvcr70', # MSVC 7.0
'1310': 'msvcr71', # MSVC 7.1
'1400': 'msvcr80', # MSVC 8
'1500': 'msvcr90', # MSVC 9 (VS 2008)
'1600': 'msvcr100', # MSVC 10 (aka 2010)
}.get(msc_ver, None)
else:
lib = None
return lib | [
"def",
"msvc_runtime_library",
"(",
")",
":",
"msc_pos",
"=",
"sys",
".",
"version",
".",
"find",
"(",
"'MSC v.'",
")",
"if",
"msc_pos",
"!=",
"-",
"1",
":",
"msc_ver",
"=",
"sys",
".",
"version",
"[",
"msc_pos",
"+",
"6",
":",
"msc_pos",
"+",
"10",
... | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/numpy/distutils/misc_util.py#L355-L368 | |
pyvisa/pyvisa | ae8c8b1180851ee4d120bc3527923c944b9623d6 | pyvisa/errors.py | python | LibraryError.from_wrong_arch | (cls, filename: str) | return cls("Error while accessing %s: %s" % (filename, s)) | Build the exception when the library has a mismatched architecture. | Build the exception when the library has a mismatched architecture. | [
"Build",
"the",
"exception",
"when",
"the",
"library",
"has",
"a",
"mismatched",
"architecture",
"."
] | def from_wrong_arch(cls, filename: str) -> "LibraryError":
"""Build the exception when the library has a mismatched architecture."""
s = ""
details = util.get_system_details(backends=False)
visalib = util.LibraryPath(
filename, "user" if filename == util.read_user_library_path() else "auto"
)
s += "No matching architecture.\n"
s += " Current Python interpreter is %s bits\n" % details["bits"]
s += " The library in: %s\n" % visalib.path
s += " found by: %s\n" % visalib.found_by
s += " bitness: %s\n" % visalib.bitness
return cls("Error while accessing %s: %s" % (filename, s)) | [
"def",
"from_wrong_arch",
"(",
"cls",
",",
"filename",
":",
"str",
")",
"->",
"\"LibraryError\"",
":",
"s",
"=",
"\"\"",
"details",
"=",
"util",
".",
"get_system_details",
"(",
"backends",
"=",
"False",
")",
"visalib",
"=",
"util",
".",
"LibraryPath",
"(",... | https://github.com/pyvisa/pyvisa/blob/ae8c8b1180851ee4d120bc3527923c944b9623d6/pyvisa/errors.py#L726-L739 | |
ucaiado/rl_trading | f4168c69f44fe5a11a06461387d4591426a43735 | market_gym/scripts/book_cleaner.py | python | Order.__str__ | (self) | return self.name | Return the name of the Order | Return the name of the Order | [
"Return",
"the",
"name",
"of",
"the",
"Order"
] | def __str__(self):
'''
Return the name of the Order
'''
return self.name | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"name"
] | https://github.com/ucaiado/rl_trading/blob/f4168c69f44fe5a11a06461387d4591426a43735/market_gym/scripts/book_cleaner.py#L79-L83 | |
thouska/spotpy | 92c3aad416ccd6becbeb345c58cae36b3a63d892 | spotpy/parameter.py | python | Base.__repr__ | (self) | return "{tname}('{p.name}', {p.rndargs})".format(tname=type(self).__name__, p=self) | Returns a textual representation of the parameter | Returns a textual representation of the parameter | [
"Returns",
"a",
"textual",
"representation",
"of",
"the",
"parameter"
] | def __repr__(self):
"""
Returns a textual representation of the parameter
"""
return "{tname}('{p.name}', {p.rndargs})".format(tname=type(self).__name__, p=self) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"{tname}('{p.name}', {p.rndargs})\"",
".",
"format",
"(",
"tname",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"p",
"=",
"self",
")"
] | https://github.com/thouska/spotpy/blob/92c3aad416ccd6becbeb345c58cae36b3a63d892/spotpy/parameter.py#L230-L234 | |
ehForwarderBot/efb-telegram-master | 4ba2d019c68170e0f7ce08c5beaaa1ef36b1654d | efb_telegram_master/chat_binding.py | python | ChatBindingManager.chat_head_req_generate | (self, chat_id: TelegramChatID,
message_id: TelegramMessageID = None,
offset: int = 0, pattern: str = "",
chats: List[EFBChannelChatIDStr] = None) | Generate the list for chat head, and update it to a message.
Args:
chat_id: Chat ID
message_id: ID of message to be updated, None to send a new message.
offset: Offset for pagination.
pattern: Regex String used as a filter.
chats: Specified list of chats to start a chat head. | Generate the list for chat head, and update it to a message. | [
"Generate",
"the",
"list",
"for",
"chat",
"head",
"and",
"update",
"it",
"to",
"a",
"message",
"."
] | def chat_head_req_generate(self, chat_id: TelegramChatID,
message_id: TelegramMessageID = None,
offset: int = 0, pattern: str = "",
chats: List[EFBChannelChatIDStr] = None):
"""
Generate the list for chat head, and update it to a message.
Args:
chat_id: Chat ID
message_id: ID of message to be updated, None to send a new message.
offset: Offset for pagination.
pattern: Regex String used as a filter.
chats: Specified list of chats to start a chat head.
"""
if message_id is None:
message_id = self.bot.send_message(chat_id, text=self._("Processing...")).message_id
self.bot.send_chat_action(chat_id, ChatAction.TYPING)
if chats and len(chats):
if len(chats) == 1:
slave_channel_id, slave_chat_id, _ = utils.chat_id_str_to_id(chats[0])
# TODO: Channel might be gone, add a check here.
chat = self.chat_manager.get_chat(slave_channel_id, slave_chat_id)
if chat:
msg_text = self._('This group is linked to {0}. '
'Send a message to this group to deliver it to the chat.\n'
'Do NOT reply to this system message.').format(chat.full_name)
else:
try:
channel = coordinator.get_module_by_id(slave_channel_id)
if isinstance(channel, Channel):
name = channel.channel_name
else:
name = channel.middleware_name
msg_text = self._("This group is linked to an unknown chat ({chat_id}) "
"on channel {channel_name} ({channel_id}). Possibly you can "
"no longer reach this chat. Send /unlink_all to unlink all chats "
"from this group.").format(channel_name=name,
channel_id=slave_channel_id,
chat_id=slave_chat_id)
except NameError:
msg_text = self._("This group is linked to a chat from a channel that is not activated "
"({channel_id}, {chat_id}). You cannot reach this chat unless the channel is "
"enabled. Send /unlink_all to unlink all chats "
"from this group.").format(channel_id=slave_channel_id,
chat_id=slave_chat_id)
self.bot.edit_message_text(text=msg_text,
chat_id=chat_id,
message_id=message_id)
return ConversationHandler.END
else:
msg_text = self._("This Telegram group is linked to the following chats, "
"choose one to start a conversation with.")
else:
msg_text = "Choose a chat you want to start a conversation with."
legend, chat_btn_list = self.slave_chats_pagination((chat_id, message_id), offset, pattern=pattern,
source_chats=chats)
msg_text += self._("\n\nLegend:\n")
for i in legend:
msg_text += f"{i}\n"
self.bot.edit_message_text(text=msg_text,
chat_id=chat_id,
message_id=message_id,
reply_markup=InlineKeyboardMarkup(chat_btn_list))
self.chat_head_handler.conversations[(chat_id, message_id)] = Flags.CHAT_HEAD_CONFIRM | [
"def",
"chat_head_req_generate",
"(",
"self",
",",
"chat_id",
":",
"TelegramChatID",
",",
"message_id",
":",
"TelegramMessageID",
"=",
"None",
",",
"offset",
":",
"int",
"=",
"0",
",",
"pattern",
":",
"str",
"=",
"\"\"",
",",
"chats",
":",
"List",
"[",
"... | https://github.com/ehForwarderBot/efb-telegram-master/blob/4ba2d019c68170e0f7ce08c5beaaa1ef36b1654d/efb_telegram_master/chat_binding.py#L648-L716 | ||
WPO-Foundation/wptagent | 94470f007294213f900dcd9a207678b5b9fce5d3 | internal/android_browser.py | python | AndroidBrowser.wait_for_processing | (self, task) | Wait for any background processing threads to finish | Wait for any background processing threads to finish | [
"Wait",
"for",
"any",
"background",
"processing",
"threads",
"to",
"finish"
] | def wait_for_processing(self, task):
"""Wait for any background processing threads to finish"""
if self.video_processing is not None:
self.video_processing.communicate()
self.video_processing = None
if not self.job['keepvideo']:
try:
os.remove(task['video_file'])
except Exception:
pass
if self.tcpdump_processing is not None:
try:
stdout, _ = self.tcpdump_processing.communicate()
if stdout is not None:
result = json.loads(stdout)
if result:
if 'in' in result:
task['page_data']['pcapBytesIn'] = result['in']
if 'out' in result:
task['page_data']['pcapBytesOut'] = result['out']
if 'in_dup' in result:
task['page_data']['pcapBytesInDup'] = result['in_dup']
if 'tcpdump' not in self.job or not self.job['tcpdump']:
if self.tcpdump_file is not None:
os.remove(self.tcpdump_file)
except Exception:
logging.exception('Error processing tcpdump') | [
"def",
"wait_for_processing",
"(",
"self",
",",
"task",
")",
":",
"if",
"self",
".",
"video_processing",
"is",
"not",
"None",
":",
"self",
".",
"video_processing",
".",
"communicate",
"(",
")",
"self",
".",
"video_processing",
"=",
"None",
"if",
"not",
"se... | https://github.com/WPO-Foundation/wptagent/blob/94470f007294213f900dcd9a207678b5b9fce5d3/internal/android_browser.py#L333-L359 | ||
mandiant/flare-fakenet-ng | 596bb139b59eb15323510ed41e33661a40c8d80c | fakenet/diverters/windows.py | python | Diverter.redirIcmpIpUnconditionally | (self, crit, pkt) | return pkt | Redirect ICMP to loopback or external IP if necessary.
On Windows, we can't conveniently use an iptables REDIRECT rule to get
ICMP packets sent back home for free, so here is some code. | Redirect ICMP to loopback or external IP if necessary. | [
"Redirect",
"ICMP",
"to",
"loopback",
"or",
"external",
"IP",
"if",
"necessary",
"."
] | def redirIcmpIpUnconditionally(self, crit, pkt):
"""Redirect ICMP to loopback or external IP if necessary.
On Windows, we can't conveniently use an iptables REDIRECT rule to get
ICMP packets sent back home for free, so here is some code.
"""
if (pkt.is_icmp and
pkt.dst_ip not in [self.loopback_ip, self.external_ip]):
self.logger.info('Modifying ICMP packet (type %d, code %d):' %
(pkt.icmp_type, pkt.icmp_code))
self.logger.info(' from: %s' % (pkt.hdrToStr()))
pkt.dst_ip = self.getNewDestinationIp(pkt.src_ip)
self.logger.info(' to: %s' % (pkt.hdrToStr()))
return pkt | [
"def",
"redirIcmpIpUnconditionally",
"(",
"self",
",",
"crit",
",",
"pkt",
")",
":",
"if",
"(",
"pkt",
".",
"is_icmp",
"and",
"pkt",
".",
"dst_ip",
"not",
"in",
"[",
"self",
".",
"loopback_ip",
",",
"self",
".",
"external_ip",
"]",
")",
":",
"self",
... | https://github.com/mandiant/flare-fakenet-ng/blob/596bb139b59eb15323510ed41e33661a40c8d80c/fakenet/diverters/windows.py#L293-L307 | |
TengXiaoDai/DistributedCrawling | f5c2439e6ce68dd9b49bde084d76473ff9ed4963 | Lib/site-packages/pip/_vendor/distlib/_backport/shutil.py | python | unpack_archive | (filename, extract_dir=None, format=None) | Unpack an archive.
`filename` is the name of the archive.
`extract_dir` is the name of the target directory, where the archive
is unpacked. If not provided, the current working directory is used.
`format` is the archive format: one of "zip", "tar", or "gztar". Or any
other registered format. If not provided, unpack_archive will use the
filename extension and see if an unpacker was registered for that
extension.
In case none is found, a ValueError is raised. | Unpack an archive. | [
"Unpack",
"an",
"archive",
"."
] | def unpack_archive(filename, extract_dir=None, format=None):
"""Unpack an archive.
`filename` is the name of the archive.
`extract_dir` is the name of the target directory, where the archive
is unpacked. If not provided, the current working directory is used.
`format` is the archive format: one of "zip", "tar", or "gztar". Or any
other registered format. If not provided, unpack_archive will use the
filename extension and see if an unpacker was registered for that
extension.
In case none is found, a ValueError is raised.
"""
if extract_dir is None:
extract_dir = os.getcwd()
if format is not None:
try:
format_info = _UNPACK_FORMATS[format]
except KeyError:
raise ValueError("Unknown unpack format '{0}'".format(format))
func = format_info[1]
func(filename, extract_dir, **dict(format_info[2]))
else:
# we need to look at the registered unpackers supported extensions
format = _find_unpack_format(filename)
if format is None:
raise ReadError("Unknown archive format '{0}'".format(filename))
func = _UNPACK_FORMATS[format][1]
kwargs = dict(_UNPACK_FORMATS[format][2])
func(filename, extract_dir, **kwargs) | [
"def",
"unpack_archive",
"(",
"filename",
",",
"extract_dir",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"if",
"extract_dir",
"is",
"None",
":",
"extract_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"format",
"is",
"not",
"None",
":",
"try",... | https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pip/_vendor/distlib/_backport/shutil.py#L727-L761 | ||
coin-or/python-mip | ce72b669d77960a8839641d58c4fdc844cbb3836 | mip/entities.py | python | Var.model | (self) | return self.__model | Model which this variable refers to.
:rtype: mip.Model | Model which this variable refers to. | [
"Model",
"which",
"this",
"variable",
"refers",
"to",
"."
] | def model(self) -> "mip.Model":
"""Model which this variable refers to.
:rtype: mip.Model
"""
return self.__model | [
"def",
"model",
"(",
"self",
")",
"->",
"\"mip.Model\"",
":",
"return",
"self",
".",
"__model"
] | https://github.com/coin-or/python-mip/blob/ce72b669d77960a8839641d58c4fdc844cbb3836/mip/entities.py#L819-L824 | |
geofront-auth/geofront | 1db8d3c1a7ae1d59caa3a5bb2a36a6e466b226f6 | geofront/server.py | python | get_remote_set | () | Get the configured remote set.
:return: the configured remote set
:rtype: :class:`~.remote.RemoteSet`
:raise RuntimeError: if ``'REMOTE_SET'`` is not configured,
or it's not a mapping object | Get the configured remote set. | [
"Get",
"the",
"configured",
"remote",
"set",
"."
] | def get_remote_set() -> RemoteSet:
"""Get the configured remote set.
:return: the configured remote set
:rtype: :class:`~.remote.RemoteSet`
:raise RuntimeError: if ``'REMOTE_SET'`` is not configured,
or it's not a mapping object
"""
try:
set_ = app.config['REMOTE_SET']
except KeyError:
raise RuntimeError('REMOTE_SET configuration is not present')
if isinstance(set_, collections.abc.Mapping):
return set_
raise RuntimeError(
'REMOTE_SET configuration must be an instance of {0.__module__}.'
'{0.__qualname__}, not {1!r}'.format(collections.abc.Mapping, set_)
) | [
"def",
"get_remote_set",
"(",
")",
"->",
"RemoteSet",
":",
"try",
":",
"set_",
"=",
"app",
".",
"config",
"[",
"'REMOTE_SET'",
"]",
"except",
"KeyError",
":",
"raise",
"RuntimeError",
"(",
"'REMOTE_SET configuration is not present'",
")",
"if",
"isinstance",
"("... | https://github.com/geofront-auth/geofront/blob/1db8d3c1a7ae1d59caa3a5bb2a36a6e466b226f6/geofront/server.py#L871-L889 | ||
replit-archive/empythoned | 977ec10ced29a3541a4973dc2b59910805695752 | cpython/Lib/codecs.py | python | IncrementalDecoder.decode | (self, input, final=False) | Decodes input and returns the resulting object. | Decodes input and returns the resulting object. | [
"Decodes",
"input",
"and",
"returns",
"the",
"resulting",
"object",
"."
] | def decode(self, input, final=False):
"""
Decodes input and returns the resulting object.
"""
raise NotImplementedError | [
"def",
"decode",
"(",
"self",
",",
"input",
",",
"final",
"=",
"False",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/codecs.py#L245-L249 | ||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/verify/v2/service/entity/__init__.py | python | EntityInstance.new_factors | (self) | return self._proxy.new_factors | Access the new_factors
:returns: twilio.rest.verify.v2.service.entity.new_factor.NewFactorList
:rtype: twilio.rest.verify.v2.service.entity.new_factor.NewFactorList | Access the new_factors | [
"Access",
"the",
"new_factors"
] | def new_factors(self):
"""
Access the new_factors
:returns: twilio.rest.verify.v2.service.entity.new_factor.NewFactorList
:rtype: twilio.rest.verify.v2.service.entity.new_factor.NewFactorList
"""
return self._proxy.new_factors | [
"def",
"new_factors",
"(",
"self",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"new_factors"
] | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/verify/v2/service/entity/__init__.py#L454-L461 | |
ztosec/hunter | 4ee5cca8dc5fc5d7e631e935517bd0f493c30a37 | SqlmapCelery/sqlmap/lib/utils/hash.py | python | sha384_generic_passwd | (password, uppercase=False) | return retVal.upper() if uppercase else retVal.lower() | >>> sha384_generic_passwd(password='testpass', uppercase=False)
'6823546e56adf46849343be991d4b1be9b432e42ed1b4bb90635a0e4b930e49b9ca007bc3e04bf0a4e0df6f1f82769bf' | >>> sha384_generic_passwd(password='testpass', uppercase=False)
'6823546e56adf46849343be991d4b1be9b432e42ed1b4bb90635a0e4b930e49b9ca007bc3e04bf0a4e0df6f1f82769bf' | [
">>>",
"sha384_generic_passwd",
"(",
"password",
"=",
"testpass",
"uppercase",
"=",
"False",
")",
"6823546e56adf46849343be991d4b1be9b432e42ed1b4bb90635a0e4b930e49b9ca007bc3e04bf0a4e0df6f1f82769bf"
] | def sha384_generic_passwd(password, uppercase=False):
"""
>>> sha384_generic_passwd(password='testpass', uppercase=False)
'6823546e56adf46849343be991d4b1be9b432e42ed1b4bb90635a0e4b930e49b9ca007bc3e04bf0a4e0df6f1f82769bf'
"""
retVal = sha384(password).hexdigest()
return retVal.upper() if uppercase else retVal.lower() | [
"def",
"sha384_generic_passwd",
"(",
"password",
",",
"uppercase",
"=",
"False",
")",
":",
"retVal",
"=",
"sha384",
"(",
"password",
")",
".",
"hexdigest",
"(",
")",
"return",
"retVal",
".",
"upper",
"(",
")",
"if",
"uppercase",
"else",
"retVal",
".",
"l... | https://github.com/ztosec/hunter/blob/4ee5cca8dc5fc5d7e631e935517bd0f493c30a37/SqlmapCelery/sqlmap/lib/utils/hash.py#L267-L275 | |
lazylibrarian/LazyLibrarian | ae3c14e9db9328ce81765e094ab2a14ed7155624 | lib/pythontwitter/__init__.py | python | User.SetLocation | (self, location) | Set the geographic location of this user.
Args:
location: The geographic location of this user | Set the geographic location of this user. | [
"Set",
"the",
"geographic",
"location",
"of",
"this",
"user",
"."
] | def SetLocation(self, location):
'''Set the geographic location of this user.
Args:
location: The geographic location of this user
'''
self._location = location | [
"def",
"SetLocation",
"(",
"self",
",",
"location",
")",
":",
"self",
".",
"_location",
"=",
"location"
] | https://github.com/lazylibrarian/LazyLibrarian/blob/ae3c14e9db9328ce81765e094ab2a14ed7155624/lib/pythontwitter/__init__.py#L964-L970 | ||
geopython/pycsw | 43a5c92fa819a3a3fdc8a8e3ef075d784dff73fc | pycsw/core/repository.py | python | Repository.query_domain | (self, domain, typenames, domainquerytype='list',
count=False) | return self._get_repo_filter(query).all() | Query by property domain values | Query by property domain values | [
"Query",
"by",
"property",
"domain",
"values"
] | def query_domain(self, domain, typenames, domainquerytype='list',
count=False):
''' Query by property domain values '''
domain_value = getattr(self.dataset, domain)
if domainquerytype == 'range':
LOGGER.info('Generating property name range values')
query = self.session.query(func.min(domain_value),
func.max(domain_value))
else:
if count:
LOGGER.info('Generating property name frequency counts')
query = self.session.query(getattr(self.dataset, domain),
func.count(domain_value)).group_by(domain_value)
else:
query = self.session.query(domain_value).distinct()
return self._get_repo_filter(query).all() | [
"def",
"query_domain",
"(",
"self",
",",
"domain",
",",
"typenames",
",",
"domainquerytype",
"=",
"'list'",
",",
"count",
"=",
"False",
")",
":",
"domain_value",
"=",
"getattr",
"(",
"self",
".",
"dataset",
",",
"domain",
")",
"if",
"domainquerytype",
"=="... | https://github.com/geopython/pycsw/blob/43a5c92fa819a3a3fdc8a8e3ef075d784dff73fc/pycsw/core/repository.py#L244-L261 | |
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/markdown/extensions/footnotes.py | python | makeExtension | (configs=[]) | return FootnoteExtension(configs=configs) | Return an instance of the FootnoteExtension | Return an instance of the FootnoteExtension | [
"Return",
"an",
"instance",
"of",
"the",
"FootnoteExtension"
] | def makeExtension(configs=[]):
""" Return an instance of the FootnoteExtension """
return FootnoteExtension(configs=configs) | [
"def",
"makeExtension",
"(",
"configs",
"=",
"[",
"]",
")",
":",
"return",
"FootnoteExtension",
"(",
"configs",
"=",
"configs",
")"
] | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/markdown/extensions/footnotes.py#L302-L304 | |
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/urllib/parse.py | python | urlsplit | (url, scheme='', allow_fragments=True) | return _coerce_result(v) | Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment>
Return a 5-tuple: (scheme, netloc, path, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes. | Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment>
Return a 5-tuple: (scheme, netloc, path, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes. | [
"Parse",
"a",
"URL",
"into",
"5",
"components",
":",
"<scheme",
">",
":",
"//",
"<netloc",
">",
"/",
"<path",
">",
"?<query",
">",
"#<fragment",
">",
"Return",
"a",
"5",
"-",
"tuple",
":",
"(",
"scheme",
"netloc",
"path",
"query",
"fragment",
")",
".... | def urlsplit(url, scheme='', allow_fragments=True):
"""Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment>
Return a 5-tuple: (scheme, netloc, path, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes."""
url, scheme, _coerce_result = _coerce_args(url, scheme)
allow_fragments = bool(allow_fragments)
key = url, scheme, allow_fragments, type(url), type(scheme)
cached = _parse_cache.get(key, None)
if cached:
return _coerce_result(cached)
if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
clear_cache()
netloc = query = fragment = ''
i = url.find(':')
if i > 0:
if url[:i] == 'http': # optimize the common case
scheme = url[:i].lower()
url = url[i+1:]
if url[:2] == '//':
netloc, url = _splitnetloc(url, 2)
if (('[' in netloc and ']' not in netloc) or
(']' in netloc and '[' not in netloc)):
raise ValueError("Invalid IPv6 URL")
if allow_fragments and '#' in url:
url, fragment = url.split('#', 1)
if '?' in url:
url, query = url.split('?', 1)
_checknetloc(netloc)
v = SplitResult(scheme, netloc, url, query, fragment)
_parse_cache[key] = v
return _coerce_result(v)
for c in url[:i]:
if c not in scheme_chars:
break
else:
# make sure "url" is not actually a port number (in which case
# "scheme" is really part of the path)
rest = url[i+1:]
if not rest or any(c not in '0123456789' for c in rest):
# not a port number
scheme, url = url[:i].lower(), rest
if url[:2] == '//':
netloc, url = _splitnetloc(url, 2)
if (('[' in netloc and ']' not in netloc) or
(']' in netloc and '[' not in netloc)):
raise ValueError("Invalid IPv6 URL")
if allow_fragments and '#' in url:
url, fragment = url.split('#', 1)
if '?' in url:
url, query = url.split('?', 1)
_checknetloc(netloc)
v = SplitResult(scheme, netloc, url, query, fragment)
_parse_cache[key] = v
return _coerce_result(v) | [
"def",
"urlsplit",
"(",
"url",
",",
"scheme",
"=",
"''",
",",
"allow_fragments",
"=",
"True",
")",
":",
"url",
",",
"scheme",
",",
"_coerce_result",
"=",
"_coerce_args",
"(",
"url",
",",
"scheme",
")",
"allow_fragments",
"=",
"bool",
"(",
"allow_fragments"... | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/urllib/parse.py#L334-L390 | |
Blueqat/Blueqat | b676f30489b71767419fd20503403d290d4950b5 | blueqat/gate.py | python | Mat1Gate.create | (cls,
targets: Targets,
params: tuple,
options: Optional[dict] = None) | return cls(targets, params[0]) | [] | def create(cls,
targets: Targets,
params: tuple,
options: Optional[dict] = None) -> 'Mat1Gate':
if options:
raise ValueError(f"{cls.__name__} doesn't take options")
return cls(targets, params[0]) | [
"def",
"create",
"(",
"cls",
",",
"targets",
":",
"Targets",
",",
"params",
":",
"tuple",
",",
"options",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
")",
"->",
"'Mat1Gate'",
":",
"if",
"options",
":",
"raise",
"ValueError",
"(",
"f\"{cls.__name__} d... | https://github.com/Blueqat/Blueqat/blob/b676f30489b71767419fd20503403d290d4950b5/blueqat/gate.py#L200-L206 | |||
freqtrade/freqtrade | 13651fd3be8d5ce8dcd7c94b920bda4e00b75aca | freqtrade/plugins/pairlist/VolumePairList.py | python | VolumePairList.gen_pairlist | (self, tickers: Dict) | return pairlist | Generate the pairlist
:param tickers: Tickers (from exchange.get_tickers()). May be cached.
:return: List of pairs | Generate the pairlist
:param tickers: Tickers (from exchange.get_tickers()). May be cached.
:return: List of pairs | [
"Generate",
"the",
"pairlist",
":",
"param",
"tickers",
":",
"Tickers",
"(",
"from",
"exchange",
".",
"get_tickers",
"()",
")",
".",
"May",
"be",
"cached",
".",
":",
"return",
":",
"List",
"of",
"pairs"
] | def gen_pairlist(self, tickers: Dict) -> List[str]:
"""
Generate the pairlist
:param tickers: Tickers (from exchange.get_tickers()). May be cached.
:return: List of pairs
"""
# Generate dynamic whitelist
# Must always run if this pairlist is not the first in the list.
pairlist = self._pair_cache.get('pairlist')
if pairlist:
# Item found - no refresh necessary
return pairlist.copy()
else:
# Use fresh pairlist
# Check if pair quote currency equals to the stake currency.
_pairlist = [k for k in self._exchange.get_markets(
quote_currencies=[self._stake_currency],
pairs_only=True, active_only=True).keys()]
# No point in testing for blacklisted pairs...
_pairlist = self.verify_blacklist(_pairlist, logger.info)
filtered_tickers = [
v for k, v in tickers.items()
if (self._exchange.get_pair_quote_currency(k) == self._stake_currency
and (self._use_range or v[self._sort_key] is not None)
and v['symbol'] in _pairlist)]
pairlist = [s['symbol'] for s in filtered_tickers]
pairlist = self.filter_pairlist(pairlist, tickers)
self._pair_cache['pairlist'] = pairlist.copy()
return pairlist | [
"def",
"gen_pairlist",
"(",
"self",
",",
"tickers",
":",
"Dict",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# Generate dynamic whitelist",
"# Must always run if this pairlist is not the first in the list.",
"pairlist",
"=",
"self",
".",
"_pair_cache",
".",
"get",
"(",
... | https://github.com/freqtrade/freqtrade/blob/13651fd3be8d5ce8dcd7c94b920bda4e00b75aca/freqtrade/plugins/pairlist/VolumePairList.py#L107-L138 | |
nadineproject/nadine | c41c8ef7ffe18f1853029c97eecc329039b4af6c | nadine/utils/payment_api.py | python | USAEPAY_SOAP_API.runTransactions4 | (self, customer_number, amount, description, invoice=None, comment=None, auth_only=False) | return response | [] | def runTransactions4(self, customer_number, amount, description, invoice=None, comment=None, auth_only=False):
params = self.client.factory.create('CustomerTransactionRequest')
if auth_only:
command = "AuthOnly"
else:
command = "Sale"
params.CustReceipt = True
params.MerchReceipt = True
params.Command = command
params.Details.Amount = float(amount)
params.Details.Description = description
if invoice:
params.Details.Invoice = invoice
if comment:
params.Details.Comments = comment
paymentID = int(0) # sets it to use default
response = self.client.service.runCustomerTransaction(self.token, int(customer_number), paymentID, params)
if response.Error:
raise Exception(response.Error)
return response | [
"def",
"runTransactions4",
"(",
"self",
",",
"customer_number",
",",
"amount",
",",
"description",
",",
"invoice",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"auth_only",
"=",
"False",
")",
":",
"params",
"=",
"self",
".",
"client",
".",
"factory",
"... | https://github.com/nadineproject/nadine/blob/c41c8ef7ffe18f1853029c97eecc329039b4af6c/nadine/utils/payment_api.py#L342-L363 | |||
skylander86/lambda-text-extractor | 6da52d077a2fc571e38bfe29c33ae68f6443cd5a | lib-linux_x64/odf/odf2moinmoin.py | python | ODF2MoinMoin.toString | (self) | return self.compressCodeBlocks('\n'.join(buffer)) | Converts the document to a string.
FIXME: Result from second call differs from first call | Converts the document to a string.
FIXME: Result from second call differs from first call | [
"Converts",
"the",
"document",
"to",
"a",
"string",
".",
"FIXME",
":",
"Result",
"from",
"second",
"call",
"differs",
"from",
"first",
"call"
] | def toString(self):
""" Converts the document to a string.
FIXME: Result from second call differs from first call
"""
body = self.content.getElementsByTagName("office:body")[0]
text = body.childNodes[0]
buffer = []
paragraphs = [el for el in text.childNodes
if el.tagName in ["draw:page", "text:p", "text:h","text:section",
"text:list", "table:table"]]
for paragraph in paragraphs:
if paragraph.tagName == "text:list":
text = self.listToString(paragraph)
elif paragraph.tagName == "text:section":
text = self.textToString(paragraph)
elif paragraph.tagName == "table:table":
text = self.tableToString(paragraph)
else:
text = self.paragraphToString(paragraph)
if text:
buffer.append(text)
if self.footnotes:
buffer.append("----")
for cite, body in self.footnotes:
buffer.append("%s: %s" % (cite, body))
buffer.append("")
return self.compressCodeBlocks('\n'.join(buffer)) | [
"def",
"toString",
"(",
"self",
")",
":",
"body",
"=",
"self",
".",
"content",
".",
"getElementsByTagName",
"(",
"\"office:body\"",
")",
"[",
"0",
"]",
"text",
"=",
"body",
".",
"childNodes",
"[",
"0",
"]",
"buffer",
"=",
"[",
"]",
"paragraphs",
"=",
... | https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/odf/odf2moinmoin.py#L452-L485 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/pip/_vendor/colorama/winterm.py | python | WinTerm.erase_line | (self, mode=0, on_stderr=False) | [] | def erase_line(self, mode=0, on_stderr=False):
# 0 should clear from the cursor to the end of the line.
# 1 should clear from the cursor to the beginning of the line.
# 2 should clear the entire line.
handle = win32.STDOUT
if on_stderr:
handle = win32.STDERR
csbi = win32.GetConsoleScreenBufferInfo(handle)
if mode == 0:
from_coord = csbi.dwCursorPosition
cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X
if mode == 1:
from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
cells_to_erase = csbi.dwCursorPosition.X
elif mode == 2:
from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
cells_to_erase = csbi.dwSize.X
# fill the entire screen with blanks
win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
# now set the buffer's attributes accordingly
win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) | [
"def",
"erase_line",
"(",
"self",
",",
"mode",
"=",
"0",
",",
"on_stderr",
"=",
"False",
")",
":",
"# 0 should clear from the cursor to the end of the line.",
"# 1 should clear from the cursor to the beginning of the line.",
"# 2 should clear the entire line.",
"handle",
"=",
"... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/colorama/winterm.py#L139-L159 | ||||
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/tkinter/__init__.py | python | Misc._options | (self, cnf, kw = None) | return res | Internal function. | Internal function. | [
"Internal",
"function",
"."
] | def _options(self, cnf, kw = None):
"""Internal function."""
if kw:
cnf = _cnfmerge((cnf, kw))
else:
cnf = _cnfmerge(cnf)
res = ()
for k, v in cnf.items():
if v is not None:
if k[-1] == '_': k = k[:-1]
if callable(v):
v = self._register(v)
elif isinstance(v, (tuple, list)):
nv = []
for item in v:
if isinstance(item, int):
nv.append(str(item))
elif isinstance(item, str):
nv.append(_stringify(item))
else:
break
else:
v = ' '.join(nv)
res = res + ('-'+k, v)
return res | [
"def",
"_options",
"(",
"self",
",",
"cnf",
",",
"kw",
"=",
"None",
")",
":",
"if",
"kw",
":",
"cnf",
"=",
"_cnfmerge",
"(",
"(",
"cnf",
",",
"kw",
")",
")",
"else",
":",
"cnf",
"=",
"_cnfmerge",
"(",
"cnf",
")",
"res",
"=",
"(",
")",
"for",
... | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/tkinter/__init__.py#L1157-L1181 | |
matrix-org/synapse | 8e57584a5859a9002759963eb546d523d2498a01 | synapse/storage/databases/main/signatures.py | python | SignatureWorkerStore.add_event_hashes | (
self, event_ids: Iterable[str]
) | return list(encoded_hashes.items()) | Args:
event_ids: The event IDs
Returns:
A list of tuples of event ID and a mapping of algorithm to base-64 encoded hash. | [] | async def add_event_hashes(
self, event_ids: Iterable[str]
) -> List[Tuple[str, Dict[str, str]]]:
"""
Args:
event_ids: The event IDs
Returns:
A list of tuples of event ID and a mapping of algorithm to base-64 encoded hash.
"""
hashes = await self.get_event_reference_hashes(event_ids)
encoded_hashes = {
e_id: {k: encode_base64(v) for k, v in h.items() if k == "sha256"}
for e_id, h in hashes.items()
}
return list(encoded_hashes.items()) | [
"async",
"def",
"add_event_hashes",
"(",
"self",
",",
"event_ids",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"]",
":",
"hashes",
"=",
"await",
"self",
".",
"get_eve... | https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/storage/databases/main/signatures.py#L54-L71 | ||
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-windows/x86/psutil/_psosx.py | python | Process.cpu_times | (self) | return _common.pcputimes(
rawtuple[pidtaskinfo_map['cpuutime']],
rawtuple[pidtaskinfo_map['cpustime']],
# children user / system times are not retrievable (set to 0)
0.0, 0.0) | [] | def cpu_times(self):
rawtuple = self._get_pidtaskinfo()
return _common.pcputimes(
rawtuple[pidtaskinfo_map['cpuutime']],
rawtuple[pidtaskinfo_map['cpustime']],
# children user / system times are not retrievable (set to 0)
0.0, 0.0) | [
"def",
"cpu_times",
"(",
"self",
")",
":",
"rawtuple",
"=",
"self",
".",
"_get_pidtaskinfo",
"(",
")",
"return",
"_common",
".",
"pcputimes",
"(",
"rawtuple",
"[",
"pidtaskinfo_map",
"[",
"'cpuutime'",
"]",
"]",
",",
"rawtuple",
"[",
"pidtaskinfo_map",
"[",
... | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/psutil/_psosx.py#L477-L483 | |||
datawire/forge | d501be4571dcef5691804c7db7008ee877933c8d | versioneer.py | python | git_pieces_from_vcs | (tag_prefix, root, verbose, run_command=run_command) | return pieces | Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree. | Get version from 'git describe' in the root of the source tree. | [
"Get",
"version",
"from",
"git",
"describe",
"in",
"the",
"root",
"of",
"the",
"source",
"tree",
"."
] | def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree.
"""
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,
hide_stderr=True)
if rc != 0:
if verbose:
print("Directory %s not under git control" % root)
raise NotThisMethod("'git rev-parse --git-dir' returned error")
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
cwd=root)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
describe_out = describe_out.strip()
full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if full_out is None:
raise NotThisMethod("'git rev-parse' failed")
full_out = full_out.strip()
pieces = {}
pieces["long"] = full_out
pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None
# parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
# TAG might have hyphens.
git_describe = describe_out
# look for -dirty suffix
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
# now we have TAG-NUM-gHEX or HEX
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
return pieces
# tag
full_tag = mo.group(1)
if not full_tag.startswith(tag_prefix):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
# commit: short hex revision ID
pieces["short"] = mo.group(3)
else:
# HEX: no tags
pieces["closest-tag"] = None
count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],
cwd=root)
pieces["distance"] = int(count_out) # total number of commits
# commit date: see ISO-8601 comment in git_versions_from_keywords()
date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"],
cwd=root)[0].strip()
pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
return pieces | [
"def",
"git_pieces_from_vcs",
"(",
"tag_prefix",
",",
"root",
",",
"verbose",
",",
"run_command",
"=",
"run_command",
")",
":",
"GITS",
"=",
"[",
"\"git\"",
"]",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"GITS",
"=",
"[",
"\"git.cmd\"",
",",
... | https://github.com/datawire/forge/blob/d501be4571dcef5691804c7db7008ee877933c8d/versioneer.py#L1029-L1117 | |
stopstalk/stopstalk-deployment | 10c3ab44c4ece33ae515f6888c15033db2004bb1 | aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_internal/req/req_install.py | python | InstallRequirement.from_path | (self) | return s | Format a nice indicator to show where this "comes from" | Format a nice indicator to show where this "comes from" | [
"Format",
"a",
"nice",
"indicator",
"to",
"show",
"where",
"this",
"comes",
"from"
] | def from_path(self):
"""Format a nice indicator to show where this "comes from"
"""
if self.req is None:
return None
s = str(self.req)
if self.comes_from:
if isinstance(self.comes_from, six.string_types):
comes_from = self.comes_from
else:
comes_from = self.comes_from.from_path()
if comes_from:
s += '->' + comes_from
return s | [
"def",
"from_path",
"(",
"self",
")",
":",
"if",
"self",
".",
"req",
"is",
"None",
":",
"return",
"None",
"s",
"=",
"str",
"(",
"self",
".",
"req",
")",
"if",
"self",
".",
"comes_from",
":",
"if",
"isinstance",
"(",
"self",
".",
"comes_from",
",",
... | https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_internal/req/req_install.py#L383-L396 | |
nerdvegas/rez | d392c65bf63b4bca8106f938cec49144ba54e770 | src/rez/vendor/pika/connection.py | python | Connection.close | (self, reply_code=200, reply_text='Normal shutdown') | Disconnect from RabbitMQ. If there are any open channels, it will
attempt to close them prior to fully disconnecting. Channels which
have active consumers will attempt to send a Basic.Cancel to RabbitMQ
to cleanly stop the delivery of messages prior to closing the channel.
:param int reply_code: The code number for the close
:param str reply_text: The text reason for the close
:raises pika.exceptions.ConnectionWrongStateError: if connection is
closed or closing. | Disconnect from RabbitMQ. If there are any open channels, it will
attempt to close them prior to fully disconnecting. Channels which
have active consumers will attempt to send a Basic.Cancel to RabbitMQ
to cleanly stop the delivery of messages prior to closing the channel. | [
"Disconnect",
"from",
"RabbitMQ",
".",
"If",
"there",
"are",
"any",
"open",
"channels",
"it",
"will",
"attempt",
"to",
"close",
"them",
"prior",
"to",
"fully",
"disconnecting",
".",
"Channels",
"which",
"have",
"active",
"consumers",
"will",
"attempt",
"to",
... | def close(self, reply_code=200, reply_text='Normal shutdown'):
"""Disconnect from RabbitMQ. If there are any open channels, it will
attempt to close them prior to fully disconnecting. Channels which
have active consumers will attempt to send a Basic.Cancel to RabbitMQ
to cleanly stop the delivery of messages prior to closing the channel.
:param int reply_code: The code number for the close
:param str reply_text: The text reason for the close
:raises pika.exceptions.ConnectionWrongStateError: if connection is
closed or closing.
"""
if self.is_closing or self.is_closed:
msg = ('Illegal close({}, {!r}) request on {} because it '
'was called while connection state={}.'.format(
reply_code, reply_text, self,
self._STATE_NAMES[self.connection_state]))
LOGGER.error(msg)
raise exceptions.ConnectionWrongStateError(msg)
# NOTE The connection is either in opening or open state
# Initiate graceful closing of channels that are OPEN or OPENING
if self._channels:
self._close_channels(reply_code, reply_text)
prev_state = self.connection_state
# Transition to closing
self._set_connection_state(self.CONNECTION_CLOSING)
LOGGER.info("Closing connection (%s): %r", reply_code, reply_text)
if not self._opened:
# It was opening, but not fully open yet, so we won't attempt
# graceful AMQP Connection.Close.
LOGGER.info('Connection.close() is terminating stream and '
'bypassing graceful AMQP close, since AMQP is still '
'opening.')
error = exceptions.ConnectionOpenAborted(
'Connection.close() called before connection '
'finished opening: prev_state={} ({}): {!r}'.format(
self._STATE_NAMES[prev_state], reply_code, reply_text))
self._terminate_stream(error)
else:
self._error = exceptions.ConnectionClosedByClient(
reply_code, reply_text)
# If there are channels that haven't finished closing yet, then
# _on_close_ready will finally be called from _on_channel_cleanup once
# all channels have been closed
if not self._channels:
# We can initiate graceful closing of the connection right away,
# since no more channels remain
self._on_close_ready()
else:
LOGGER.info(
'Connection.close is waiting for %d channels to close: %s',
len(self._channels), self) | [
"def",
"close",
"(",
"self",
",",
"reply_code",
"=",
"200",
",",
"reply_text",
"=",
"'Normal shutdown'",
")",
":",
"if",
"self",
".",
"is_closing",
"or",
"self",
".",
"is_closed",
":",
"msg",
"=",
"(",
"'Illegal close({}, {!r}) request on {} because it '",
"'was... | https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/vendor/pika/connection.py#L1266-L1325 | ||
LMFDB/lmfdb | 6cf48a4c18a96e6298da6ae43f587f96845bcb43 | lmfdb/knowledge/knowl.py | python | KnowlBackend.broken_links_knowls | (self) | return [(kid, results[kid]) for kid in sorted(results)] | A list of knowl ids that have broken links.
OUTPUT:
A list of pairs ``kid``, ``links``, where ``links`` is a list of broken links on the knowl with id ``kid``. | A list of knowl ids that have broken links. | [
"A",
"list",
"of",
"knowl",
"ids",
"that",
"have",
"broken",
"links",
"."
] | def broken_links_knowls(self):
"""
A list of knowl ids that have broken links.
OUTPUT:
A list of pairs ``kid``, ``links``, where ``links`` is a list of broken links on the knowl with id ``kid``.
"""
selecter = SQL("SELECT id, link FROM (SELECT DISTINCT ON (id) id, UNNEST(links) AS link FROM kwl_knowls WHERE status >= 0 ORDER BY id, timestamp DESC) knowls WHERE (SELECT COUNT(*) FROM kwl_knowls kw WHERE kw.id = link) = 0")
results = defaultdict(list)
for kid, link in self._execute(selecter):
results[kid].append(link)
return [(kid, results[kid]) for kid in sorted(results)] | [
"def",
"broken_links_knowls",
"(",
"self",
")",
":",
"selecter",
"=",
"SQL",
"(",
"\"SELECT id, link FROM (SELECT DISTINCT ON (id) id, UNNEST(links) AS link FROM kwl_knowls WHERE status >= 0 ORDER BY id, timestamp DESC) knowls WHERE (SELECT COUNT(*) FROM kwl_knowls kw WHERE kw.id = link) = 0\"",... | https://github.com/LMFDB/lmfdb/blob/6cf48a4c18a96e6298da6ae43f587f96845bcb43/lmfdb/knowledge/knowl.py#L641-L653 | |
rlisagor/freshen | 5578f7368e8d53b4cf51c589fb192090d3524968 | freshen/compat.py | python | relpath | (path, start=curdir) | return join(*rel_list) | Return a relative version of a path | Return a relative version of a path | [
"Return",
"a",
"relative",
"version",
"of",
"a",
"path"
] | def relpath(path, start=curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = abspath(start).split(sep)
path_list = abspath(path).split(sep)
# Work out how much of the filepath is shared by start and path.
i = len(commonprefix([start_list, path_list]))
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list) | [
"def",
"relpath",
"(",
"path",
",",
"start",
"=",
"curdir",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"\"no path specified\"",
")",
"start_list",
"=",
"abspath",
"(",
"start",
")",
".",
"split",
"(",
"sep",
")",
"path_list",
"=",
... | https://github.com/rlisagor/freshen/blob/5578f7368e8d53b4cf51c589fb192090d3524968/freshen/compat.py#L7-L22 | |
nicrusso7/rex-gym | 26663048bd3c3da307714da4458b1a2a9dc81824 | rex_gym/envs/rex_gym_env.py | python | RexGymEnv.set_time_step | (self, control_step, simulation_step=0.001) | Sets the time step of the environment.
Args:
control_step: The time period (in seconds) between two adjacent control
actions are applied.
simulation_step: The simulation time step in PyBullet. By default, the
simulation step is 0.001s, which is a good trade-off between simulation
speed and accuracy.
Raises:
ValueError: If the control step is smaller than the simulation step. | Sets the time step of the environment. | [
"Sets",
"the",
"time",
"step",
"of",
"the",
"environment",
"."
] | def set_time_step(self, control_step, simulation_step=0.001):
"""Sets the time step of the environment.
Args:
control_step: The time period (in seconds) between two adjacent control
actions are applied.
simulation_step: The simulation time step in PyBullet. By default, the
simulation step is 0.001s, which is a good trade-off between simulation
speed and accuracy.
Raises:
ValueError: If the control step is smaller than the simulation step.
"""
if control_step < simulation_step:
raise ValueError("Control step should be larger than or equal to simulation step.")
self.control_time_step = control_step
self._time_step = simulation_step
self._action_repeat = int(round(control_step / simulation_step))
self._num_bullet_solver_iterations = (NUM_SIMULATION_ITERATION_STEPS / self._action_repeat)
self._pybullet_client.setPhysicsEngineParameter(
numSolverIterations=self._num_bullet_solver_iterations)
self._pybullet_client.setTimeStep(self._time_step)
self.rex.SetTimeSteps(action_repeat=self._action_repeat, simulation_step=self._time_step) | [
"def",
"set_time_step",
"(",
"self",
",",
"control_step",
",",
"simulation_step",
"=",
"0.001",
")",
":",
"if",
"control_step",
"<",
"simulation_step",
":",
"raise",
"ValueError",
"(",
"\"Control step should be larger than or equal to simulation step.\"",
")",
"self",
"... | https://github.com/nicrusso7/rex-gym/blob/26663048bd3c3da307714da4458b1a2a9dc81824/rex_gym/envs/rex_gym_env.py#L623-L644 | ||
jaimeMF/youtube-dl-api-server | a7456b502047e038439cefafba880aab91497665 | youtube_dl_server/app.py | python | get_videos | (url, extra_params) | return res | Get a list with a dict for every video founded | Get a list with a dict for every video founded | [
"Get",
"a",
"list",
"with",
"a",
"dict",
"for",
"every",
"video",
"founded"
] | def get_videos(url, extra_params):
'''
Get a list with a dict for every video founded
'''
ydl_params = {
'format': 'best',
'cachedir': False,
'logger': current_app.logger.getChild('youtube-dl'),
}
ydl_params.update(extra_params)
ydl = SimpleYDL(ydl_params)
res = ydl.extract_info(url, download=False)
return res | [
"def",
"get_videos",
"(",
"url",
",",
"extra_params",
")",
":",
"ydl_params",
"=",
"{",
"'format'",
":",
"'best'",
",",
"'cachedir'",
":",
"False",
",",
"'logger'",
":",
"current_app",
".",
"logger",
".",
"getChild",
"(",
"'youtube-dl'",
")",
",",
"}",
"... | https://github.com/jaimeMF/youtube-dl-api-server/blob/a7456b502047e038439cefafba880aab91497665/youtube_dl_server/app.py#L24-L36 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/translations/forms.py | python | MigrateTransifexProjectForm.__init__ | (self, domain, *args, **kwargs) | [] | def __init__(self, domain, *args, **kwargs):
super(MigrateTransifexProjectForm, self).__init__(*args, **kwargs)
self.domain = domain
self._set_choices()
self.helper = HQFormHelper()
self.helper.layout = crispy.Layout(
crispy.Fieldset(
"Migrate Project",
hqcrispy.Field('from_app_id', css_class="hqwebapp-select2"),
hqcrispy.Field('to_app_id', css_class="hqwebapp-select2"),
hqcrispy.Field('transifex_project_slug'),
hqcrispy.Field('mapping_file')
),
hqcrispy.FormActions(
twbscrispy.StrictButton(
ugettext_lazy("Submit"),
type="submit",
css_class="btn btn-primary disable-on-submit",
onclick="return confirm('%s')" % ugettext_lazy(
"We recommend taking a backup if you have not already."
"Please confirm that you want to proceed?")
)
)
) | [
"def",
"__init__",
"(",
"self",
",",
"domain",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"MigrateTransifexProjectForm",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"domain",... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/translations/forms.py#L382-L405 | ||||
accel-brain/accel-brain-code | 86f489dc9be001a3bae6d053f48d6b57c0bedb95 | Reinforcement-Learning/pyqlearning/annealing_model.py | python | AnnealingModel.set_var_log_arr | (self, value) | setter | setter | [
"setter"
] | def set_var_log_arr(self, value):
''' setter '''
if isinstance(value, np.ndarray):
self.__var_log_arr = value
else:
raise TypeError() | [
"def",
"set_var_log_arr",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"np",
".",
"ndarray",
")",
":",
"self",
".",
"__var_log_arr",
"=",
"value",
"else",
":",
"raise",
"TypeError",
"(",
")"
] | https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Reinforcement-Learning/pyqlearning/annealing_model.py#L124-L129 | ||
bachya/smart-home | 536b989e0d7057c7a8a65b2ac9bbffd4b826cce7 | hass/settings/custom_components/hacs/repositories/integration.py | python | HacsIntegrationRepository.update_repository | (self, ignore_issues=False, force=False) | Update. | Update. | [
"Update",
"."
] | async def update_repository(self, ignore_issues=False, force=False):
"""Update."""
if not await self.common_update(ignore_issues, force):
return
if self.data.content_in_root:
self.content.path.remote = ""
if self.content.path.remote == "custom_components":
name = get_first_directory_in_directory(self.tree, "custom_components")
self.content.path.remote = f"custom_components/{name}"
try:
await get_integration_manifest(self)
except HacsException as exception:
self.logger.error("%s %s", self, exception)
# Set local path
self.content.path.local = self.localpath | [
"async",
"def",
"update_repository",
"(",
"self",
",",
"ignore_issues",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"await",
"self",
".",
"common_update",
"(",
"ignore_issues",
",",
"force",
")",
":",
"return",
"if",
"self",
".",
"da... | https://github.com/bachya/smart-home/blob/536b989e0d7057c7a8a65b2ac9bbffd4b826cce7/hass/settings/custom_components/hacs/repositories/integration.py#L72-L90 | ||
pwnieexpress/pwn_plug_sources | 1a23324f5dc2c3de20f9c810269b6a29b2758cad | src/wifitap/scapy.py | python | TracerouteResult.make_graph | (self,ASN,padding) | [] | def make_graph(self,ASN,padding):
self.graphASN = ASN
self.graphpadding = padding
ips = {}
rt = {}
ports = {}
ports_done = {}
for s,r in self.res:
ips[r.src] = None
if s.haslayer(TCP) or s.haslayer(UDP):
trace_id = (s.src,s.dst,s.proto,s.dport)
elif s.haslayer(ICMP):
trace_id = (s.src,s.dst,s.proto,s.type)
else:
trace_id = (s.src,s.dst,s.proto,0)
trace = rt.get(trace_id,{})
if not r.haslayer(ICMP) or r.type != 11:
if ports_done.has_key(trace_id):
continue
ports_done[trace_id] = None
p = ports.get(r.src,[])
if r.haslayer(TCP):
p.append(r.sprintf("<T%ir,TCP.sport%> %TCP.sport%: %TCP.flags%"))
trace[s.ttl] = r.sprintf('"%IP.src%":T%ir,TCP.sport%')
elif r.haslayer(UDP):
p.append(r.sprintf("<U%ir,UDP.sport%> %UDP.sport%"))
trace[s.ttl] = r.sprintf('"%IP.src%":U%ir,UDP.sport%')
elif r.haslayer(ICMP):
p.append(r.sprintf("<I%ir,ICMP.type%> ICMP %ICMP.type%"))
trace[s.ttl] = r.sprintf('"%IP.src%":I%ir,ICMP.type%')
else:
p.append(r.sprintf("<P%ir,IP.proto> IP %IP.proto%"))
trace[s.ttl] = r.sprintf('"%IP.src%":P%ir,IP.proto%')
ports[r.src] = p
else:
trace[s.ttl] = r.sprintf('"%IP.src%"')
rt[trace_id] = trace
# Fill holes with unk%i nodes
unk = 0
blackholes = []
bhip = {}
for rtk in rt:
trace = rt[rtk]
k = trace.keys()
for n in range(min(k), max(k)):
if not trace.has_key(n):
trace[n] = "unk%i" % unk
unk += 1
if not ports_done.has_key(rtk):
if rtk[2] == 1: #ICMP
bh = "%s %i" % (rtk[1],rtk[3])
elif rtk[2] == 6: #TCP
bh = "%s:%i/tcp" % (rtk[1],rtk[3])
elif rtk[2] == 17: #UDP
bh = '%s:%i/udp' % (rtk[1],rtk[3])
else:
bh = '%s,proto %i' % (rtk[1],rtk[2])
ips[bh] = None
bhip[rtk[1]] = bh
bh = '"%s"' % bh
trace[max(k)+1] = bh
blackholes.append(bh)
# Find AS numbers
def getASNlist_radb(list):
def parseWhois(x):
asn,desc = None,""
for l in x.splitlines():
if not asn and l.startswith("origin:"):
asn = l[7:].strip()
if l.startswith("descr:"):
if desc:
desc += r"\n"
desc += l[6:].strip()
if asn is not None and desc:
break
return asn,desc.strip()
ASNlist = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("whois.ra.net",43))
for ip in list:
s.send("-k %s\n" % ip)
asn,desc = parseWhois(s.recv(8192))
ASNlist.append((ip,asn,desc))
return ASNlist
def getASNlist_cymru(list):
ASNlist = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("whois.cymru.com",43))
s.send("begin\r\n"+"\r\n".join(list)+"\r\nend\r\n")
r = ""
while 1:
l = s.recv(8192)
if l == "":
break
r += l
s.close()
for l in r.splitlines()[1:]:
asn,ip,desc = map(str.strip, l.split("|"))
if asn == "NA":
continue
asn = int(asn)
ASNlist.append((ip,asn,desc))
return ASNlist
ASN_query_list = dict.fromkeys(map(lambda x:x.split(":")[0],ips)).keys()
if ASN in [1,2]:
ASNlist = getASNlist_cymru(ASN_query_list)
elif ASN == 3:
ASNlist = getASNlist_radb(ASN_query_list)
else:
ASNlist = []
if ASN == 1:
ASN_ans_list = map(lambda x:x[0], ASNlist)
ASN_remain_list = filter(lambda x: x not in ASN_ans_list, ASN_query_list)
if ASN_remain_list:
ASNlist += getASNlist_radb(ASN_remain_list)
ASNs = {}
ASDs = {}
for ip,asn,desc, in ASNlist:
if asn is None:
continue
iplist = ASNs.get(asn,[])
if ip in bhip:
if ip in ports:
iplist.append(ip)
iplist.append(bhip[ip])
else:
iplist.append(ip)
ASNs[asn] = iplist
ASDs[asn] = desc
backcolorlist=colgen("60","86","ba","ff")
forecolorlist=colgen("a0","70","40","20")
s = "digraph trace {\n"
s += "\n\tnode [shape=ellipse,color=black,style=solid];\n\n"
s += "\n#ASN clustering\n"
for asn in ASNs:
s += '\tsubgraph cluster_%s {\n' % asn
col = backcolorlist.next()
s += '\t\tcolor="#%s%s%s";' % col
s += '\t\tnode [fillcolor="#%s%s%s",style=filled];' % col
s += '\t\tfontsize = 10;'
s += '\t\tlabel = "%s\\n[%s]"\n' % (asn,ASDs[asn])
for ip in ASNs[asn]:
s += '\t\t"%s";\n'%ip
s += "\t}\n"
s += "#endpoints\n"
for p in ports:
s += '\t"%s" [shape=record,color=black,fillcolor=green,style=filled,label="%s|%s"];\n' % (p,p,"|".join(ports[p]))
s += "\n#Blackholes\n"
for bh in blackholes:
s += '\t%s [shape=octagon,color=black,fillcolor=red,style=filled];\n' % bh
if padding:
s += "\n#Padding\n"
pad={}
for snd,rcv in self.res:
if rcv.src not in ports and rcv.haslayer(Padding):
p = rcv.getlayer(Padding).load
if p != "\x00"*len(p):
pad[rcv.src]=None
for rcv in pad:
s += '\t"%s" [shape=triangle,color=black,fillcolor=red,style=filled];\n' % rcv
s += "\n\tnode [shape=ellipse,color=black,style=solid];\n\n"
for rtk in rt:
s += "#---[%s\n" % `rtk`
s += '\t\tedge [color="#%s%s%s"];\n' % forecolorlist.next()
trace = rt[rtk]
k = trace.keys()
for n in range(min(k), max(k)):
s += '\t%s ->\n' % trace[n]
s += '\t%s;\n' % trace[max(k)]
s += "}\n";
self.graphdef = s | [
"def",
"make_graph",
"(",
"self",
",",
"ASN",
",",
"padding",
")",
":",
"self",
".",
"graphASN",
"=",
"ASN",
"self",
".",
"graphpadding",
"=",
"padding",
"ips",
"=",
"{",
"}",
"rt",
"=",
"{",
"}",
"ports",
"=",
"{",
"}",
"ports_done",
"=",
"{",
"... | https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/wifitap/scapy.py#L3393-L3595 | ||||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/patched/notpip/_vendor/urllib3/util/retry.py | python | _RetryMeta.DEFAULT_METHOD_WHITELIST | (cls, value) | [] | def DEFAULT_METHOD_WHITELIST(cls, value):
warnings.warn(
"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",
DeprecationWarning,
)
cls.DEFAULT_ALLOWED_METHODS = value | [
"def",
"DEFAULT_METHOD_WHITELIST",
"(",
"cls",
",",
"value",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and \"",
"\"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead\"",
",",
"DeprecationWarning",
",",
")",
"... | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/urllib3/util/retry.py#L46-L52 | ||||
ctxis/canape | 5f0e03424577296bcc60c2008a60a98ec5307e4b | CANAPE.Scripting/Lib/numbers.py | python | Complex.__truediv__ | (self, other) | self / other with __future__ division.
Should promote to float when necessary. | self / other with __future__ division. | [
"self",
"/",
"other",
"with",
"__future__",
"division",
"."
] | def __truediv__(self, other):
"""self / other with __future__ division.
Should promote to float when necessary.
"""
raise NotImplementedError | [
"def",
"__truediv__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/numbers.py#L124-L129 | ||
Blizzard/s2protocol | 4bfe857bb832eee12cc6307dd699e3b74bd7e1b2 | s2protocol/versions/protocol77661.py | python | decode_replay_game_events | (contents) | Decodes and yields each game event from the contents byte string. | Decodes and yields each game event from the contents byte string. | [
"Decodes",
"and",
"yields",
"each",
"game",
"event",
"from",
"the",
"contents",
"byte",
"string",
"."
] | def decode_replay_game_events(contents):
"""Decodes and yields each game event from the contents byte string."""
decoder = BitPackedDecoder(contents, typeinfos)
for event in _decode_event_stream(decoder,
game_eventid_typeid,
game_event_types,
decode_user_id=True):
yield event | [
"def",
"decode_replay_game_events",
"(",
"contents",
")",
":",
"decoder",
"=",
"BitPackedDecoder",
"(",
"contents",
",",
"typeinfos",
")",
"for",
"event",
"in",
"_decode_event_stream",
"(",
"decoder",
",",
"game_eventid_typeid",
",",
"game_event_types",
",",
"decode... | https://github.com/Blizzard/s2protocol/blob/4bfe857bb832eee12cc6307dd699e3b74bd7e1b2/s2protocol/versions/protocol77661.py#L442-L449 | ||
lingtengqiu/Deeperlab-pytorch | 5c500780a6655ff343d147477402aa20e0ed7a7c | utils/pyt_utils.py | python | extant_file | (x) | return x | 'Type' for argparse - checks that file exists but does not open. | 'Type' for argparse - checks that file exists but does not open. | [
"Type",
"for",
"argparse",
"-",
"checks",
"that",
"file",
"exists",
"but",
"does",
"not",
"open",
"."
] | def extant_file(x):
"""
'Type' for argparse - checks that file exists but does not open.
"""
if not os.path.exists(x):
# Argparse uses the ArgumentTypeError to give a rejection message like:
# error: argument input: x does not exist
raise argparse.ArgumentTypeError("{0} does not exist".format(x))
return x | [
"def",
"extant_file",
"(",
"x",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"x",
")",
":",
"# Argparse uses the ArgumentTypeError to give a rejection message like:",
"# error: argument input: x does not exist",
"raise",
"argparse",
".",
"ArgumentTypeErro... | https://github.com/lingtengqiu/Deeperlab-pytorch/blob/5c500780a6655ff343d147477402aa20e0ed7a7c/utils/pyt_utils.py#L93-L101 | |
tdpetrou/pandas_cub | 9f933c2a1a11a7f8eebab29b62c320cedb9d631a | pandas_cub/__init__.py | python | DataFrame.var | (self) | return self._agg(np.var) | [] | def var(self):
return self._agg(np.var) | [
"def",
"var",
"(",
"self",
")",
":",
"return",
"self",
".",
"_agg",
"(",
"np",
".",
"var",
")"
] | https://github.com/tdpetrou/pandas_cub/blob/9f933c2a1a11a7f8eebab29b62c320cedb9d631a/pandas_cub/__init__.py#L217-L218 | |||
easezyc/deep-transfer-learning | 9af0921f4f21bc2ccea61be53cf8e8a49873d613 | UDA/pytorch1.0/DSAN/lmmd.py | python | LMMD_loss.guassian_kernel | (self, source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None) | return sum(kernel_val) | [] | def guassian_kernel(self, source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None):
n_samples = int(source.size()[0]) + int(target.size()[0])
total = torch.cat([source, target], dim=0)
total0 = total.unsqueeze(0).expand(
int(total.size(0)), int(total.size(0)), int(total.size(1)))
total1 = total.unsqueeze(1).expand(
int(total.size(0)), int(total.size(0)), int(total.size(1)))
L2_distance = ((total0-total1)**2).sum(2)
if fix_sigma:
bandwidth = fix_sigma
else:
bandwidth = torch.sum(L2_distance.data) / (n_samples**2-n_samples)
bandwidth /= kernel_mul ** (kernel_num // 2)
bandwidth_list = [bandwidth * (kernel_mul**i)
for i in range(kernel_num)]
kernel_val = [torch.exp(-L2_distance / bandwidth_temp)
for bandwidth_temp in bandwidth_list]
return sum(kernel_val) | [
"def",
"guassian_kernel",
"(",
"self",
",",
"source",
",",
"target",
",",
"kernel_mul",
"=",
"2.0",
",",
"kernel_num",
"=",
"5",
",",
"fix_sigma",
"=",
"None",
")",
":",
"n_samples",
"=",
"int",
"(",
"source",
".",
"size",
"(",
")",
"[",
"0",
"]",
... | https://github.com/easezyc/deep-transfer-learning/blob/9af0921f4f21bc2ccea61be53cf8e8a49873d613/UDA/pytorch1.0/DSAN/lmmd.py#L14-L31 | |||
Pymol-Scripts/Pymol-script-repo | bcd7bb7812dc6db1595953dfa4471fa15fb68c77 | modules/pdb2pqr/contrib/ZSI-2.1-a1/ZSI/wstools/WSDLTools.py | python | Operation.getWSDL | (self) | return self.parent().parent().parent().parent() | Return the WSDL object that contains this Operation. | Return the WSDL object that contains this Operation. | [
"Return",
"the",
"WSDL",
"object",
"that",
"contains",
"this",
"Operation",
"."
] | def getWSDL(self):
"""Return the WSDL object that contains this Operation."""
return self.parent().parent().parent().parent() | [
"def",
"getWSDL",
"(",
"self",
")",
":",
"return",
"self",
".",
"parent",
"(",
")",
".",
"parent",
"(",
")",
".",
"parent",
"(",
")",
".",
"parent",
"(",
")"
] | https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/contrib/ZSI-2.1-a1/ZSI/wstools/WSDLTools.py#L650-L652 | |
accel-brain/accel-brain-code | 86f489dc9be001a3bae6d053f48d6b57c0bedb95 | Generative-Adversarial-Networks/pygan/gan_image_generator.py | python | GANImageGenerator.__init__ | (
self,
dir_list,
width=28,
height=28,
channel=1,
initializer=None,
batch_size=40,
learning_rate=1e-03,
ctx=mx.gpu(),
discriminative_model=None,
generative_model=None,
generator_loss_weight=1.0,
discriminator_loss_weight=1.0,
feature_matching_loss_weight=1.0,
) | Init.
If you are not satisfied with this simple default setting,
delegate `discriminative_model` and `generative_model` designed by yourself.
Args:
dir_list: `list` of `str` of path to image files.
width: `int` of image width.
height: `int` of image height.
channel: `int` of image channel.
initializer: is-a `mxnet.initializer` for parameters of model.
If `None`, it is drawing from the Xavier distribution.
batch_size: `int` of batch size.
learning_rate: `float` of learning rate.
ctx: `mx.gpu()` or `mx.cpu()`.
discriminative_model: is-a `accelbrainbase.observabledata._mxnet.adversarialmodel.discriminative_model.DiscriminativeModel`.
generative_model: is-a `accelbrainbase.observabledata._mxnet.adversarialmodel.generative_model.GenerativeModel`.
generator_loss_weight: `float` of weight for generator loss.
discriminator_loss_weight: `float` of weight for discriminator loss.
feature_matching_loss_weight: `float` of weight for feature matching loss. | Init. | [
"Init",
"."
] | def __init__(
self,
dir_list,
width=28,
height=28,
channel=1,
initializer=None,
batch_size=40,
learning_rate=1e-03,
ctx=mx.gpu(),
discriminative_model=None,
generative_model=None,
generator_loss_weight=1.0,
discriminator_loss_weight=1.0,
feature_matching_loss_weight=1.0,
):
'''
Init.
If you are not satisfied with this simple default setting,
delegate `discriminative_model` and `generative_model` designed by yourself.
Args:
dir_list: `list` of `str` of path to image files.
width: `int` of image width.
height: `int` of image height.
channel: `int` of image channel.
initializer: is-a `mxnet.initializer` for parameters of model.
If `None`, it is drawing from the Xavier distribution.
batch_size: `int` of batch size.
learning_rate: `float` of learning rate.
ctx: `mx.gpu()` or `mx.cpu()`.
discriminative_model: is-a `accelbrainbase.observabledata._mxnet.adversarialmodel.discriminative_model.DiscriminativeModel`.
generative_model: is-a `accelbrainbase.observabledata._mxnet.adversarialmodel.generative_model.GenerativeModel`.
generator_loss_weight: `float` of weight for generator loss.
discriminator_loss_weight: `float` of weight for discriminator loss.
feature_matching_loss_weight: `float` of weight for feature matching loss.
'''
image_extractor = ImageExtractor(
width=width,
height=height,
channel=channel,
ctx=ctx
)
unlabeled_image_iterator = UnlabeledImageIterator(
image_extractor=image_extractor,
dir_list=dir_list,
batch_size=batch_size,
norm_mode="z_score",
scale=1.0,
noiseable_data=GaussNoise(sigma=1e-03, mu=0.0),
)
true_sampler = TrueSampler()
true_sampler.iteratorable_data = unlabeled_image_iterator
condition_sampler = ConditionSampler()
condition_sampler.true_sampler = true_sampler
computable_loss = L2NormLoss()
if initializer is None:
initializer = mx.initializer.Uniform()
else:
if isinstance(initializer, mx.initializer.Initializer) is False:
raise TypeError("The type of `initializer` must be `mxnet.initializer.Initializer`.")
if discriminative_model is None:
output_nn = NeuralNetworks(
computable_loss=computable_loss,
initializer=initializer,
learning_rate=learning_rate,
learning_attenuate_rate=1.0,
attenuate_epoch=50,
units_list=[100, 1],
dropout_rate_list=[0.5, 0.0],
optimizer_name="SGD",
activation_list=["relu", "sigmoid"],
hidden_batch_norm_list=[BatchNorm(), None],
ctx=ctx,
hybridize_flag=True,
regularizatable_data_list=[],
scale=1.0,
output_no_bias_flag=True,
all_no_bias_flag=True,
not_init_flag=False,
)
d_model = ConvolutionalNeuralNetworks(
computable_loss=computable_loss,
initializer=initializer,
learning_rate=learning_rate,
learning_attenuate_rate=1.0,
attenuate_epoch=50,
hidden_units_list=[
Conv2D(
channels=16,
kernel_size=6,
strides=(2, 2),
padding=(1, 1),
),
Conv2D(
channels=32,
kernel_size=3,
strides=(2, 2),
padding=(1, 1),
),
],
input_nn=None,
input_result_height=None,
input_result_width=None,
input_result_channel=None,
output_nn=output_nn,
hidden_dropout_rate_list=[0.5, 0.5],
hidden_batch_norm_list=[BatchNorm(), BatchNorm()],
optimizer_name="SGD",
hidden_activation_list=["relu", "relu"],
hidden_residual_flag=False,
hidden_dense_flag=False,
dense_axis=1,
ctx=ctx,
hybridize_flag=True,
regularizatable_data_list=[],
scale=1.0,
)
discriminative_model = DiscriminativeModel(
model=d_model,
initializer=None,
learning_rate=learning_rate,
optimizer_name="SGD",
hybridize_flag=True,
scale=1.0,
ctx=ctx,
)
else:
if isinstance(discriminative_model, DiscriminativeModel) is False:
raise TypeError("The type of `discriminative_model` must be `DiscriminativeModel`.")
if generative_model is None:
g_model = ConvolutionalNeuralNetworks(
computable_loss=computable_loss,
initializer=initializer,
learning_rate=learning_rate,
learning_attenuate_rate=1.0,
attenuate_epoch=50,
hidden_units_list=[
Conv2DTranspose(
channels=16,
kernel_size=6,
strides=(1, 1),
padding=(1, 1),
),
Conv2DTranspose(
channels=channel,
kernel_size=3,
strides=(1, 1),
padding=(1, 1),
),
],
input_nn=None,
input_result_height=None,
input_result_width=None,
input_result_channel=None,
output_nn=None,
hidden_dropout_rate_list=[0.5, 0.0],
hidden_batch_norm_list=[BatchNorm(), None],
optimizer_name="SGD",
hidden_activation_list=["relu", "identity"],
hidden_residual_flag=False,
hidden_dense_flag=False,
dense_axis=1,
ctx=ctx,
hybridize_flag=True,
regularizatable_data_list=[],
scale=1.0,
)
generative_model = GenerativeModel(
noise_sampler=UniformNoiseSampler(
low=-1e-05,
high=1e-05,
batch_size=batch_size,
seq_len=0,
channel=channel,
height=height,
width=width,
ctx=ctx
),
model=g_model,
initializer=None,
condition_sampler=condition_sampler,
conditonal_dim=1,
learning_rate=learning_rate,
optimizer_name="SGD",
hybridize_flag=True,
scale=1.0,
ctx=ctx,
)
else:
if isinstance(generative_model, GenerativeModel) is False:
raise TypeError("The type of `generative_model` must be `GenerativeModel`.")
GAN = GANController(
true_sampler=true_sampler,
generative_model=generative_model,
discriminative_model=discriminative_model,
generator_loss=GeneratorLoss(weight=generator_loss_weight),
discriminator_loss=DiscriminatorLoss(weight=discriminator_loss_weight),
feature_matching_loss=L2NormLoss(weight=feature_matching_loss_weight),
optimizer_name="SGD",
learning_rate=learning_rate,
learning_attenuate_rate=1.0,
attenuate_epoch=50,
hybridize_flag=True,
scale=1.0,
ctx=ctx,
initializer=initializer,
)
self.GAN = GAN | [
"def",
"__init__",
"(",
"self",
",",
"dir_list",
",",
"width",
"=",
"28",
",",
"height",
"=",
"28",
",",
"channel",
"=",
"1",
",",
"initializer",
"=",
"None",
",",
"batch_size",
"=",
"40",
",",
"learning_rate",
"=",
"1e-03",
",",
"ctx",
"=",
"mx",
... | https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Generative-Adversarial-Networks/pygan/gan_image_generator.py#L66-L290 | ||
JulianEberius/SublimeRope | c6ac5179ce8c1e7af0c2c1134589f945252c362d | rope/refactor/change_signature.py | python | ArgumentReorderer.__init__ | (self, new_order, autodef=None) | Construct an `ArgumentReorderer`
Note that the `new_order` is a list containing the new
position of parameters; not the position each parameter
is going to be moved to. (changed in ``0.5m4``)
For example changing ``f(a, b, c)`` to ``f(c, a, b)``
requires passing ``[2, 0, 1]`` and *not* ``[1, 2, 0]``.
The `autodef` (automatic default) argument, forces rope to use
it as a default if a default is needed after the change. That
happens when an argument without default is moved after
another that has a default value. Note that `autodef` should
be a string or `None`; the latter disables adding automatic
default. | Construct an `ArgumentReorderer` | [
"Construct",
"an",
"ArgumentReorderer"
] | def __init__(self, new_order, autodef=None):
"""Construct an `ArgumentReorderer`
Note that the `new_order` is a list containing the new
position of parameters; not the position each parameter
is going to be moved to. (changed in ``0.5m4``)
For example changing ``f(a, b, c)`` to ``f(c, a, b)``
requires passing ``[2, 0, 1]`` and *not* ``[1, 2, 0]``.
The `autodef` (automatic default) argument, forces rope to use
it as a default if a default is needed after the change. That
happens when an argument without default is moved after
another that has a default value. Note that `autodef` should
be a string or `None`; the latter disables adding automatic
default.
"""
self.new_order = new_order
self.autodef = autodef | [
"def",
"__init__",
"(",
"self",
",",
"new_order",
",",
"autodef",
"=",
"None",
")",
":",
"self",
".",
"new_order",
"=",
"new_order",
"self",
".",
"autodef",
"=",
"autodef"
] | https://github.com/JulianEberius/SublimeRope/blob/c6ac5179ce8c1e7af0c2c1134589f945252c362d/rope/refactor/change_signature.py#L249-L268 | ||
PaddlePaddle/PaddleHub | 107ee7e1a49d15e9c94da3956475d88a53fc165f | paddlehub/compat/task/batch.py | python | pad_batch_data | (insts: List,
pad_idx: int = 0,
max_seq_len: int = 128,
return_pos: bool = False,
return_input_mask: bool = False,
return_max_len: bool = False,
return_num_token: bool = False,
return_seq_lens: bool = False) | return return_list if len(return_list) > 1 else return_list[0] | Pad the instances to the max sequence length in batch, and generate the
corresponding position data and input mask. | Pad the instances to the max sequence length in batch, and generate the
corresponding position data and input mask. | [
"Pad",
"the",
"instances",
"to",
"the",
"max",
"sequence",
"length",
"in",
"batch",
"and",
"generate",
"the",
"corresponding",
"position",
"data",
"and",
"input",
"mask",
"."
] | def pad_batch_data(insts: List,
pad_idx: int = 0,
max_seq_len: int = 128,
return_pos: bool = False,
return_input_mask: bool = False,
return_max_len: bool = False,
return_num_token: bool = False,
return_seq_lens: bool = False) -> Union[List, np.ndarray]:
'''
Pad the instances to the max sequence length in batch, and generate the
corresponding position data and input mask.
'''
return_list = []
#max_len = max(len(inst) for inst in insts)
max_len = max_seq_len
# Any token included in dict can be used to pad, since the paddings' loss
# will be masked out by weights and make no effect on parameter gradients.
inst_data = np.array([list(inst) + list([pad_idx] * (max_len - len(inst))) for inst in insts])
return_list += [inst_data.astype('int64').reshape([-1, max_len, 1])]
# position data
if return_pos:
inst_pos = np.array([list(range(0, len(inst))) + [pad_idx] * (max_len - len(inst)) for inst in insts])
return_list += [inst_pos.astype('int64').reshape([-1, max_len, 1])]
if return_input_mask:
# This is used to avoid attention on paddings.
input_mask_data = np.array([[1] * len(inst) + [0] * (max_len - len(inst)) for inst in insts])
input_mask_data = np.expand_dims(input_mask_data, axis=-1)
return_list += [input_mask_data.astype('float32')]
if return_max_len:
return_list += [max_len]
if return_num_token:
num_token = 0
for inst in insts:
num_token += len(inst)
return_list += [num_token]
if return_seq_lens:
seq_lens = np.array([len(inst) for inst in insts])
return_list += [seq_lens.astype('int64').reshape([-1, 1])]
return return_list if len(return_list) > 1 else return_list[0] | [
"def",
"pad_batch_data",
"(",
"insts",
":",
"List",
",",
"pad_idx",
":",
"int",
"=",
"0",
",",
"max_seq_len",
":",
"int",
"=",
"128",
",",
"return_pos",
":",
"bool",
"=",
"False",
",",
"return_input_mask",
":",
"bool",
"=",
"False",
",",
"return_max_len"... | https://github.com/PaddlePaddle/PaddleHub/blob/107ee7e1a49d15e9c94da3956475d88a53fc165f/paddlehub/compat/task/batch.py#L22-L68 | |
misterch0c/shadowbroker | e3a069bea47a2c1009697941ac214adc6f90aa8d | windows/Resources/Python/Core/Lib/decimal.py | python | Decimal.same_quantum | (self, other) | return self._exp == other._exp | Return True if self and other have the same exponent; otherwise
return False.
If either operand is a special value, the following rules are used:
* return True if both operands are infinities
* return True if both operands are NaNs
* otherwise, return False. | Return True if self and other have the same exponent; otherwise
return False.
If either operand is a special value, the following rules are used:
* return True if both operands are infinities
* return True if both operands are NaNs
* otherwise, return False. | [
"Return",
"True",
"if",
"self",
"and",
"other",
"have",
"the",
"same",
"exponent",
";",
"otherwise",
"return",
"False",
".",
"If",
"either",
"operand",
"is",
"a",
"special",
"value",
"the",
"following",
"rules",
"are",
"used",
":",
"*",
"return",
"True",
... | def same_quantum(self, other):
"""Return True if self and other have the same exponent; otherwise
return False.
If either operand is a special value, the following rules are used:
* return True if both operands are infinities
* return True if both operands are NaNs
* otherwise, return False.
"""
other = _convert_other(other, raiseit=True)
if self._is_special or other._is_special:
return self.is_nan() and other.is_nan() or self.is_infinite() and other.is_infinite()
return self._exp == other._exp | [
"def",
"same_quantum",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
",",
"raiseit",
"=",
"True",
")",
"if",
"self",
".",
"_is_special",
"or",
"other",
".",
"_is_special",
":",
"return",
"self",
".",
"is_nan",
"(",
... | https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/decimal.py#L1977-L1989 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/libs/hadoop/src/hadoop/fs/hadoopfs.py | python | encode_fs_path | (path) | return smart_str(path, HDFS_ENCODING, errors='strict') | encode_fs_path(path) -> byte string in utf8 | encode_fs_path(path) -> byte string in utf8 | [
"encode_fs_path",
"(",
"path",
")",
"-",
">",
"byte",
"string",
"in",
"utf8"
] | def encode_fs_path(path):
"""encode_fs_path(path) -> byte string in utf8"""
return smart_str(path, HDFS_ENCODING, errors='strict') | [
"def",
"encode_fs_path",
"(",
"path",
")",
":",
"return",
"smart_str",
"(",
"path",
",",
"HDFS_ENCODING",
",",
"errors",
"=",
"'strict'",
")"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/libs/hadoop/src/hadoop/fs/hadoopfs.py#L76-L78 | |
hottbox/hottbox | 26580018ec6d38a1b08266c04ce4408c9e276130 | hottbox/core/structures.py | python | TensorTKD.reconstruct | (self, keep_meta=0) | return tensor | Converts the Tucker representation of a tensor into a full tensor
Parameters
----------
keep_meta : int
Keep meta information about modes of the given `tensor`.
0 - the output will have default values for the meta data
1 - keep only mode names
2 - keep mode names and indices
Returns
-------
tensor : Tensor | Converts the Tucker representation of a tensor into a full tensor | [
"Converts",
"the",
"Tucker",
"representation",
"of",
"a",
"tensor",
"into",
"a",
"full",
"tensor"
] | def reconstruct(self, keep_meta=0):
""" Converts the Tucker representation of a tensor into a full tensor
Parameters
----------
keep_meta : int
Keep meta information about modes of the given `tensor`.
0 - the output will have default values for the meta data
1 - keep only mode names
2 - keep mode names and indices
Returns
-------
tensor : Tensor
"""
tensor = self.core
for mode, fmat in enumerate(self.fmat):
tensor.mode_n_product(fmat, mode=mode, inplace=True)
if keep_meta == 1:
mode_names = {i: mode.name for i, mode in enumerate(self.modes)}
tensor.set_mode_names(mode_names=mode_names)
elif keep_meta == 2:
tensor.copy_modes(self)
else:
pass
return tensor | [
"def",
"reconstruct",
"(",
"self",
",",
"keep_meta",
"=",
"0",
")",
":",
"tensor",
"=",
"self",
".",
"core",
"for",
"mode",
",",
"fmat",
"in",
"enumerate",
"(",
"self",
".",
"fmat",
")",
":",
"tensor",
".",
"mode_n_product",
"(",
"fmat",
",",
"mode",... | https://github.com/hottbox/hottbox/blob/26580018ec6d38a1b08266c04ce4408c9e276130/hottbox/core/structures.py#L1704-L1731 | |
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/nova/nova/db/sqlalchemy/api.py | python | fixed_ip_get_by_address_detailed | (context, address, session=None) | return result | :returns: a tuple of (models.FixedIp, models.Network, models.Instance) | :returns: a tuple of (models.FixedIp, models.Network, models.Instance) | [
":",
"returns",
":",
"a",
"tuple",
"of",
"(",
"models",
".",
"FixedIp",
"models",
".",
"Network",
"models",
".",
"Instance",
")"
] | def fixed_ip_get_by_address_detailed(context, address, session=None):
"""
:returns: a tuple of (models.FixedIp, models.Network, models.Instance)
"""
if not session:
session = get_session()
result = model_query(context, models.FixedIp, models.Network,
models.Instance, session=session).\
filter_by(address=address).\
outerjoin((models.Network,
models.Network.id ==
models.FixedIp.network_id)).\
outerjoin((models.Instance,
models.Instance.uuid ==
models.FixedIp.instance_uuid)).\
first()
if not result:
raise exception.FixedIpNotFoundForAddress(address=address)
return result | [
"def",
"fixed_ip_get_by_address_detailed",
"(",
"context",
",",
"address",
",",
"session",
"=",
"None",
")",
":",
"if",
"not",
"session",
":",
"session",
"=",
"get_session",
"(",
")",
"result",
"=",
"model_query",
"(",
"context",
",",
"models",
".",
"FixedIp... | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/db/sqlalchemy/api.py#L1178-L1199 | |
owid/covid-19-data | 936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92 | scripts/scripts/utils/db_imports.py | python | print_err | (*args, **kwargs) | return print(*args, file=sys.stderr, **kwargs) | [] | def print_err(*args, **kwargs):
return print(*args, file=sys.stderr, **kwargs) | [
"def",
"print_err",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"print",
"(",
"*",
"args",
",",
"file",
"=",
"sys",
".",
"stderr",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/owid/covid-19-data/blob/936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92/scripts/scripts/utils/db_imports.py#L36-L37 | |||
OpenEIT/OpenEIT | 0448694e8092361ae5ccb45fba81dee543a6244b | OpenEIT/backend/bluetooth/old/build/dlib/Adafruit_BluefruitLE/bluez_dbus/adapter.py | python | BluezAdapter.__init__ | (self, dbus_obj) | Create an instance of the bluetooth adapter from the provided bluez
DBus object. | Create an instance of the bluetooth adapter from the provided bluez
DBus object. | [
"Create",
"an",
"instance",
"of",
"the",
"bluetooth",
"adapter",
"from",
"the",
"provided",
"bluez",
"DBus",
"object",
"."
] | def __init__(self, dbus_obj):
"""Create an instance of the bluetooth adapter from the provided bluez
DBus object.
"""
self._adapter = dbus.Interface(dbus_obj, _INTERFACE)
self._props = dbus.Interface(dbus_obj, 'org.freedesktop.DBus.Properties')
self._scan_started = threading.Event()
self._scan_stopped = threading.Event()
self._props.connect_to_signal('PropertiesChanged', self._prop_changed) | [
"def",
"__init__",
"(",
"self",
",",
"dbus_obj",
")",
":",
"self",
".",
"_adapter",
"=",
"dbus",
".",
"Interface",
"(",
"dbus_obj",
",",
"_INTERFACE",
")",
"self",
".",
"_props",
"=",
"dbus",
".",
"Interface",
"(",
"dbus_obj",
",",
"'org.freedesktop.DBus.P... | https://github.com/OpenEIT/OpenEIT/blob/0448694e8092361ae5ccb45fba81dee543a6244b/OpenEIT/backend/bluetooth/old/build/dlib/Adafruit_BluefruitLE/bluez_dbus/adapter.py#L38-L46 | ||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/modules/vagrant.py | python | _build_machine_uri | (machine, cwd) | return _build_sdb_uri(key) | returns string used to fetch id names from the sdb store.
the cwd and machine name are concatenated with '?' which should
never collide with a Salt node id -- which is important since we
will be storing both in the same table. | returns string used to fetch id names from the sdb store. | [
"returns",
"string",
"used",
"to",
"fetch",
"id",
"names",
"from",
"the",
"sdb",
"store",
"."
] | def _build_machine_uri(machine, cwd):
"""
returns string used to fetch id names from the sdb store.
the cwd and machine name are concatenated with '?' which should
never collide with a Salt node id -- which is important since we
will be storing both in the same table.
"""
key = "{}?{}".format(machine, os.path.abspath(cwd))
return _build_sdb_uri(key) | [
"def",
"_build_machine_uri",
"(",
"machine",
",",
"cwd",
")",
":",
"key",
"=",
"\"{}?{}\"",
".",
"format",
"(",
"machine",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"cwd",
")",
")",
"return",
"_build_sdb_uri",
"(",
"key",
")"
] | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/vagrant.py#L68-L77 | |
ShreyAmbesh/Traffic-Rule-Violation-Detection-System | ae0c327ce014ce6a427da920b5798a0d4bbf001e | metrics/coco_tools.py | python | COCOEvalWrapper.GetCategoryIdList | (self) | return self.params.catIds | Returns list of valid category ids. | Returns list of valid category ids. | [
"Returns",
"list",
"of",
"valid",
"category",
"ids",
"."
] | def GetCategoryIdList(self):
"""Returns list of valid category ids."""
return self.params.catIds | [
"def",
"GetCategoryIdList",
"(",
"self",
")",
":",
"return",
"self",
".",
"params",
".",
"catIds"
] | https://github.com/ShreyAmbesh/Traffic-Rule-Violation-Detection-System/blob/ae0c327ce014ce6a427da920b5798a0d4bbf001e/metrics/coco_tools.py#L188-L190 | |
jina-ai/jina | c77a492fcd5adba0fc3de5347bea83dd4e7d8087 | jina/logging/profile.py | python | TimeContext.__exit__ | (self, typ, value, traceback) | [] | def __exit__(self, typ, value, traceback):
self.duration = self.now()
self.readable_duration = get_readable_time(seconds=self.duration)
self._exit_msg() | [
"def",
"__exit__",
"(",
"self",
",",
"typ",
",",
"value",
",",
"traceback",
")",
":",
"self",
".",
"duration",
"=",
"self",
".",
"now",
"(",
")",
"self",
".",
"readable_duration",
"=",
"get_readable_time",
"(",
"seconds",
"=",
"self",
".",
"duration",
... | https://github.com/jina-ai/jina/blob/c77a492fcd5adba0fc3de5347bea83dd4e7d8087/jina/logging/profile.py#L166-L171 | ||||
huawei-noah/vega | d9f13deede7f2b584e4b1d32ffdb833856129989 | vega/common/task_ops.py | python | TaskOps.step_name | (self, value) | Setter: set step_name with value.
:param value: step name
:type value: str | Setter: set step_name with value. | [
"Setter",
":",
"set",
"step_name",
"with",
"value",
"."
] | def step_name(self, value):
"""Setter: set step_name with value.
:param value: step name
:type value: str
"""
self._step_name = value | [
"def",
"step_name",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_step_name",
"=",
"value"
] | https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/common/task_ops.py#L254-L260 | ||
Fantomas42/django-blog-zinnia | 881101a9d1d455b2fc581d6f4ae0947cdd8126c6 | zinnia/signals.py | python | count_trackbacks_handler | (sender, **kwargs) | Update Entry.trackback_count when a trackback was posted. | Update Entry.trackback_count when a trackback was posted. | [
"Update",
"Entry",
".",
"trackback_count",
"when",
"a",
"trackback",
"was",
"posted",
"."
] | def count_trackbacks_handler(sender, **kwargs):
"""
Update Entry.trackback_count when a trackback was posted.
"""
entry = kwargs['entry']
entry.trackback_count = F('trackback_count') + 1
entry.save(update_fields=['trackback_count']) | [
"def",
"count_trackbacks_handler",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"entry",
"=",
"kwargs",
"[",
"'entry'",
"]",
"entry",
".",
"trackback_count",
"=",
"F",
"(",
"'trackback_count'",
")",
"+",
"1",
"entry",
".",
"save",
"(",
"update_fields"... | https://github.com/Fantomas42/django-blog-zinnia/blob/881101a9d1d455b2fc581d6f4ae0947cdd8126c6/zinnia/signals.py#L126-L132 | ||
tern-tools/tern | 723f43dcaae2f2f0a08a63e5e8de3938031a386e | tern/analyze/default/dockerfile/parse.py | python | get_from_indices | (dfobj) | return from_lines | Given a dockerfile object, return the indices of FROM lines
in the dfobj structure. | Given a dockerfile object, return the indices of FROM lines
in the dfobj structure. | [
"Given",
"a",
"dockerfile",
"object",
"return",
"the",
"indices",
"of",
"FROM",
"lines",
"in",
"the",
"dfobj",
"structure",
"."
] | def get_from_indices(dfobj):
"""Given a dockerfile object, return the indices of FROM lines
in the dfobj structure."""
from_lines = []
for idx, st in enumerate(dfobj.structure):
if st['instruction'] == 'FROM':
from_lines.append(idx)
from_lines.append(len(dfobj.structure))
return from_lines | [
"def",
"get_from_indices",
"(",
"dfobj",
")",
":",
"from_lines",
"=",
"[",
"]",
"for",
"idx",
",",
"st",
"in",
"enumerate",
"(",
"dfobj",
".",
"structure",
")",
":",
"if",
"st",
"[",
"'instruction'",
"]",
"==",
"'FROM'",
":",
"from_lines",
".",
"append... | https://github.com/tern-tools/tern/blob/723f43dcaae2f2f0a08a63e5e8de3938031a386e/tern/analyze/default/dockerfile/parse.py#L301-L309 | |
anymail/django-anymail | dc0a46a815d062d52660b9237627b22f89093bce | anymail/backends/base.py | python | AnymailBaseBackend.open | (self) | return False | Open and persist a connection to the ESP's API, and whether
a new connection was created.
Callers must ensure they later call close, if (and only if) open
returns True. | Open and persist a connection to the ESP's API, and whether
a new connection was created. | [
"Open",
"and",
"persist",
"a",
"connection",
"to",
"the",
"ESP",
"s",
"API",
"and",
"whether",
"a",
"new",
"connection",
"was",
"created",
"."
] | def open(self):
"""
Open and persist a connection to the ESP's API, and whether
a new connection was created.
Callers must ensure they later call close, if (and only if) open
returns True.
"""
# Subclasses should use an instance property to maintain a cached
# connection, and return True iff they initialize that instance
# property in _this_ open call. (If the cached connection already
# exists, just do nothing and return False.)
#
# Subclasses should swallow operational errors if self.fail_silently
# (e.g., network errors), but otherwise can raise any errors.
#
# (Returning a bool to indicate whether connection was created is
# borrowed from django.core.email.backends.SMTPBackend)
return False | [
"def",
"open",
"(",
"self",
")",
":",
"# Subclasses should use an instance property to maintain a cached",
"# connection, and return True iff they initialize that instance",
"# property in _this_ open call. (If the cached connection already",
"# exists, just do nothing and return False.)",
"#",
... | https://github.com/anymail/django-anymail/blob/dc0a46a815d062d52660b9237627b22f89093bce/anymail/backends/base.py#L43-L61 | |
emre/storm | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | storm/__main__.py | python | list | (config=None) | Lists all hosts from ssh config. | Lists all hosts from ssh config. | [
"Lists",
"all",
"hosts",
"from",
"ssh",
"config",
"."
] | def list(config=None):
"""
Lists all hosts from ssh config.
"""
storm_ = get_storm_instance(config)
try:
result = colored('Listing entries:', 'white', attrs=["bold", ]) + "\n\n"
result_stack = ""
for host in storm_.list_entries(True):
if host.get("type") == 'entry':
if not host.get("host") == "*":
result += " {0} -> {1}@{2}:{3}".format(
colored(host["host"], 'green', attrs=["bold", ]),
host.get("options").get(
"user", get_default("user", storm_.defaults)
),
host.get("options").get(
"hostname", "[hostname_not_specified]"
),
host.get("options").get(
"port", get_default("port", storm_.defaults)
)
)
extra = False
for key, value in six.iteritems(host.get("options")):
if not key in ["user", "hostname", "port"]:
if not extra:
custom_options = colored(
'\n\t[custom options] ', 'white'
)
result += " {0}".format(custom_options)
extra = True
if isinstance(value, collections.Sequence):
if isinstance(value, builtins.list):
value = ",".join(value)
result += "{0}={1} ".format(key, value)
if extra:
result = result[0:-1]
result += "\n\n"
else:
result_stack = colored(
" (*) General options: \n", "green", attrs=["bold",]
)
for key, value in six.iteritems(host.get("options")):
if isinstance(value, type([])):
result_stack += "\t {0}: ".format(
colored(key, "magenta")
)
result_stack += ', '.join(value)
result_stack += "\n"
else:
result_stack += "\t {0}: {1}\n".format(
colored(key, "magenta"),
value,
)
result_stack = result_stack[0:-1] + "\n"
result += result_stack
print(get_formatted_message(result, ""))
except Exception as error:
print(get_formatted_message(str(error), 'error'), file=sys.stderr)
sys.exit(1) | [
"def",
"list",
"(",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"try",
":",
"result",
"=",
"colored",
"(",
"'Listing entries:'",
",",
"'white'",
",",
"attrs",
"=",
"[",
"\"bold\"",
",",
"]",
")",
"+",
"\"\\... | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L190-L258 | ||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/requests/utils.py | python | get_encoding_from_headers | (headers) | Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from.
:rtype: str | Returns encodings from given HTTP Header Dict. | [
"Returns",
"encodings",
"from",
"given",
"HTTP",
"Header",
"Dict",
"."
] | def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from.
:rtype: str
"""
content_type = headers.get('content-type')
if not content_type:
return None
content_type, params = _parse_content_type_header(content_type)
if 'charset' in params:
return params['charset'].strip("'\"")
if 'text' in content_type:
return 'ISO-8859-1'
if 'application/json' in content_type:
# Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset
return 'utf-8' | [
"def",
"get_encoding_from_headers",
"(",
"headers",
")",
":",
"content_type",
"=",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"if",
"not",
"content_type",
":",
"return",
"None",
"content_type",
",",
"params",
"=",
"_parse_content_type_header",
"(",
"conten... | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/requests/utils.py#L507-L529 | ||
songyingxin/python-algorithm | 1c3cc9f73687f5bf291d95d4c6558d982ad98985 | niuke/2_8_maximum_gap.py | python | Solution.which_bucket | (self, num, arr_len, arr_min, arr_max) | return int((num - arr_min) * arr_len / (arr_max - arr_min)) | 判断 num 属于第几个桶 | 判断 num 属于第几个桶 | [
"判断",
"num",
"属于第几个桶"
] | def which_bucket(self, num, arr_len, arr_min, arr_max):
""" 判断 num 属于第几个桶 """
return int((num - arr_min) * arr_len / (arr_max - arr_min)) | [
"def",
"which_bucket",
"(",
"self",
",",
"num",
",",
"arr_len",
",",
"arr_min",
",",
"arr_max",
")",
":",
"return",
"int",
"(",
"(",
"num",
"-",
"arr_min",
")",
"*",
"arr_len",
"/",
"(",
"arr_max",
"-",
"arr_min",
")",
")"
] | https://github.com/songyingxin/python-algorithm/blob/1c3cc9f73687f5bf291d95d4c6558d982ad98985/niuke/2_8_maximum_gap.py#L38-L40 | |
tensorflow/ranking | 94cccec8b4e71d2cc4489c61e2623522738c2924 | tensorflow_ranking/extension/pipeline.py | python | RankingPipeline._required_hparam_keys | (self) | return required_hparam_keys | Returns a list of keys for the required hparams for RankingPipeline. | Returns a list of keys for the required hparams for RankingPipeline. | [
"Returns",
"a",
"list",
"of",
"keys",
"for",
"the",
"required",
"hparams",
"for",
"RankingPipeline",
"."
] | def _required_hparam_keys(self):
"""Returns a list of keys for the required hparams for RankingPipeline."""
required_hparam_keys = [
"train_input_pattern", "eval_input_pattern", "train_batch_size",
"eval_batch_size", "checkpoint_secs", "num_checkpoints",
"num_train_steps", "num_eval_steps", "loss", "list_size",
"convert_labels_to_binary", "model_dir", "listwise_inference"
]
return required_hparam_keys | [
"def",
"_required_hparam_keys",
"(",
"self",
")",
":",
"required_hparam_keys",
"=",
"[",
"\"train_input_pattern\"",
",",
"\"eval_input_pattern\"",
",",
"\"train_batch_size\"",
",",
"\"eval_batch_size\"",
",",
"\"checkpoint_secs\"",
",",
"\"num_checkpoints\"",
",",
"\"num_tr... | https://github.com/tensorflow/ranking/blob/94cccec8b4e71d2cc4489c61e2623522738c2924/tensorflow_ranking/extension/pipeline.py#L180-L188 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/encodings/iso8859_6.py | python | Codec.encode | (self,input,errors='strict') | return codecs.charmap_encode(input,errors,encoding_table) | [] | def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table) | [
"def",
"encode",
"(",
"self",
",",
"input",
",",
"errors",
"=",
"'strict'",
")",
":",
"return",
"codecs",
".",
"charmap_encode",
"(",
"input",
",",
"errors",
",",
"encoding_table",
")"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/encodings/iso8859_6.py#L11-L12 | |||
Guanghan/lighttrack | a980585acb4189da12f5d3dec68b5c3cd1b69de9 | lib/lib_kernel/lib_nms/setup.py | python | locate_cuda | () | return cudaconfig | Locate the CUDA environment on the system
Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64'
and values giving the absolute path to each directory.
Starts by looking for the CUDAHOME env variable. If not found, everything
is based on finding 'nvcc' in the PATH. | Locate the CUDA environment on the system | [
"Locate",
"the",
"CUDA",
"environment",
"on",
"the",
"system"
] | def locate_cuda():
"""Locate the CUDA environment on the system
Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64'
and values giving the absolute path to each directory.
Starts by looking for the CUDAHOME env variable. If not found, everything
is based on finding 'nvcc' in the PATH.
"""
# first check if the CUDAHOME env variable is in use
if 'CUDAHOME' in os.environ:
home = os.environ['CUDAHOME']
nvcc = pjoin(home, 'bin', 'nvcc')
else:
# otherwise, search the PATH for NVCC
default_path = pjoin(os.sep, 'usr', 'local', 'cuda', 'bin')
nvcc = find_in_path('nvcc', os.environ['PATH'] + os.pathsep + default_path)
if nvcc is None:
raise EnvironmentError('The nvcc binary could not be '
'located in your $PATH. Either add it to your path, or set $CUDAHOME')
home = os.path.dirname(os.path.dirname(nvcc))
cudaconfig = {'home':home, 'nvcc':nvcc,
'include': pjoin(home, 'include'),
'lib64': pjoin(home, 'lib64')}
for k, v in cudaconfig.items():
if not os.path.exists(v):
raise EnvironmentError('The CUDA %s path could not be located in %s' % (k, v))
return cudaconfig | [
"def",
"locate_cuda",
"(",
")",
":",
"# first check if the CUDAHOME env variable is in use",
"if",
"'CUDAHOME'",
"in",
"os",
".",
"environ",
":",
"home",
"=",
"os",
".",
"environ",
"[",
"'CUDAHOME'",
"]",
"nvcc",
"=",
"pjoin",
"(",
"home",
",",
"'bin'",
",",
... | https://github.com/Guanghan/lighttrack/blob/a980585acb4189da12f5d3dec68b5c3cd1b69de9/lib/lib_kernel/lib_nms/setup.py#L27-L57 | |
Ridter/acefile | 31f90219fb560364b6f5d27f512fccfae81d04f4 | acefile.py | python | Pic.classinit_pic_dif_bit_width | (cls) | return cls | Decorator that adds the PIC dif_bit_width static table to *cls*. | Decorator that adds the PIC dif_bit_width static table to *cls*. | [
"Decorator",
"that",
"adds",
"the",
"PIC",
"dif_bit_width",
"static",
"table",
"to",
"*",
"cls",
"*",
"."
] | def classinit_pic_dif_bit_width(cls):
"""
Decorator that adds the PIC dif_bit_width static table to *cls*.
"""
cls._dif_bit_width = []
for i in range(0, 128):
cls._dif_bit_width.append((2 * i).bit_length())
for i in range(-128, 0):
cls._dif_bit_width.append((- 2 * i - 1).bit_length())
return cls | [
"def",
"classinit_pic_dif_bit_width",
"(",
"cls",
")",
":",
"cls",
".",
"_dif_bit_width",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"128",
")",
":",
"cls",
".",
"_dif_bit_width",
".",
"append",
"(",
"(",
"2",
"*",
"i",
")",
".",
"bit... | https://github.com/Ridter/acefile/blob/31f90219fb560364b6f5d27f512fccfae81d04f4/acefile.py#L1839-L1848 | |
zaxlct/imooc-django | daf1ced745d3d21989e8191b658c293a511b37fd | apps/users/views.py | python | UserInfoView.get | (self, request) | return render(request, 'usercenter-info.html') | [] | def get(self, request):
return render(request, 'usercenter-info.html') | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"return",
"render",
"(",
"request",
",",
"'usercenter-info.html'",
")"
] | https://github.com/zaxlct/imooc-django/blob/daf1ced745d3d21989e8191b658c293a511b37fd/apps/users/views.py#L181-L182 | |||
WenmuZhou/DBNet.pytorch | 678b2ae55e018c6c16d5ac182558517a154a91ed | utils/cal_recall/script.py | python | evaluate_method | (gtFilePath, submFilePath, evaluationParams) | return resDict | Method evaluate_method: evaluate method and returns the results
Results. Dictionary with the following values:
- method (required) Global method metrics. Ex: { 'Precision':0.8,'Recall':0.9 }
- samples (optional) Per sample metrics. Ex: {'sample1' : { 'Precision':0.8,'Recall':0.9 } , 'sample2' : { 'Precision':0.8,'Recall':0.9 } | Method evaluate_method: evaluate method and returns the results
Results. Dictionary with the following values:
- method (required) Global method metrics. Ex: { 'Precision':0.8,'Recall':0.9 }
- samples (optional) Per sample metrics. Ex: {'sample1' : { 'Precision':0.8,'Recall':0.9 } , 'sample2' : { 'Precision':0.8,'Recall':0.9 } | [
"Method",
"evaluate_method",
":",
"evaluate",
"method",
"and",
"returns",
"the",
"results",
"Results",
".",
"Dictionary",
"with",
"the",
"following",
"values",
":",
"-",
"method",
"(",
"required",
")",
"Global",
"method",
"metrics",
".",
"Ex",
":",
"{",
"Pre... | def evaluate_method(gtFilePath, submFilePath, evaluationParams):
"""
Method evaluate_method: evaluate method and returns the results
Results. Dictionary with the following values:
- method (required) Global method metrics. Ex: { 'Precision':0.8,'Recall':0.9 }
- samples (optional) Per sample metrics. Ex: {'sample1' : { 'Precision':0.8,'Recall':0.9 } , 'sample2' : { 'Precision':0.8,'Recall':0.9 }
"""
def polygon_from_points(points):
"""
Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4
"""
resBoxes = np.empty([1, 8], dtype='int32')
resBoxes[0, 0] = int(points[0])
resBoxes[0, 4] = int(points[1])
resBoxes[0, 1] = int(points[2])
resBoxes[0, 5] = int(points[3])
resBoxes[0, 2] = int(points[4])
resBoxes[0, 6] = int(points[5])
resBoxes[0, 3] = int(points[6])
resBoxes[0, 7] = int(points[7])
pointMat = resBoxes[0].reshape([2, 4]).T
return plg.Polygon(pointMat)
def rectangle_to_polygon(rect):
resBoxes = np.empty([1, 8], dtype='int32')
resBoxes[0, 0] = int(rect.xmin)
resBoxes[0, 4] = int(rect.ymax)
resBoxes[0, 1] = int(rect.xmin)
resBoxes[0, 5] = int(rect.ymin)
resBoxes[0, 2] = int(rect.xmax)
resBoxes[0, 6] = int(rect.ymin)
resBoxes[0, 3] = int(rect.xmax)
resBoxes[0, 7] = int(rect.ymax)
pointMat = resBoxes[0].reshape([2, 4]).T
return plg.Polygon(pointMat)
def rectangle_to_points(rect):
points = [int(rect.xmin), int(rect.ymax), int(rect.xmax), int(rect.ymax), int(rect.xmax), int(rect.ymin),
int(rect.xmin), int(rect.ymin)]
return points
def get_union(pD, pG):
areaA = pD.area();
areaB = pG.area();
return areaA + areaB - get_intersection(pD, pG);
def get_intersection_over_union(pD, pG):
try:
return get_intersection(pD, pG) / get_union(pD, pG);
except:
return 0
def get_intersection(pD, pG):
pInt = pD & pG
if len(pInt) == 0:
return 0
return pInt.area()
def compute_ap(confList, matchList, numGtCare):
correct = 0
AP = 0
if len(confList) > 0:
confList = np.array(confList)
matchList = np.array(matchList)
sorted_ind = np.argsort(-confList)
confList = confList[sorted_ind]
matchList = matchList[sorted_ind]
for n in range(len(confList)):
match = matchList[n]
if match:
correct += 1
AP += float(correct) / (n + 1)
if numGtCare > 0:
AP /= numGtCare
return AP
perSampleMetrics = {}
matchedSum = 0
Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax')
gt = rrc_evaluation_funcs.load_folder_file(gtFilePath, evaluationParams['GT_SAMPLE_NAME_2_ID'])
subm = rrc_evaluation_funcs.load_folder_file(submFilePath, evaluationParams['DET_SAMPLE_NAME_2_ID'], True)
numGlobalCareGt = 0;
numGlobalCareDet = 0;
arrGlobalConfidences = [];
arrGlobalMatches = [];
for resFile in gt:
gtFile = gt[resFile] # rrc_evaluation_funcs.decode_utf8(gt[resFile])
recall = 0
precision = 0
hmean = 0
detMatched = 0
iouMat = np.empty([1, 1])
gtPols = []
detPols = []
gtPolPoints = []
detPolPoints = []
# Array of Ground Truth Polygons' keys marked as don't Care
gtDontCarePolsNum = []
# Array of Detected Polygons' matched with a don't Care GT
detDontCarePolsNum = []
pairs = []
detMatchedNums = []
arrSampleConfidences = [];
arrSampleMatch = [];
sampleAP = 0;
evaluationLog = ""
pointsList, _, transcriptionsList = rrc_evaluation_funcs.get_tl_line_values_from_file_contents(gtFile,
evaluationParams[
'CRLF'],
evaluationParams[
'LTRB'],
True, False)
for n in range(len(pointsList)):
points = pointsList[n]
transcription = transcriptionsList[n]
dontCare = transcription == "###"
if evaluationParams['LTRB']:
gtRect = Rectangle(*points)
gtPol = rectangle_to_polygon(gtRect)
else:
gtPol = polygon_from_points(points)
gtPols.append(gtPol)
gtPolPoints.append(points)
if dontCare:
gtDontCarePolsNum.append(len(gtPols) - 1)
evaluationLog += "GT polygons: " + str(len(gtPols)) + (
" (" + str(len(gtDontCarePolsNum)) + " don't care)\n" if len(gtDontCarePolsNum) > 0 else "\n")
if resFile in subm:
detFile = subm[resFile] # rrc_evaluation_funcs.decode_utf8(subm[resFile])
pointsList, confidencesList, _ = rrc_evaluation_funcs.get_tl_line_values_from_file_contents(detFile,
evaluationParams[
'CRLF'],
evaluationParams[
'LTRB'],
False,
evaluationParams[
'CONFIDENCES'])
for n in range(len(pointsList)):
points = pointsList[n]
if evaluationParams['LTRB']:
detRect = Rectangle(*points)
detPol = rectangle_to_polygon(detRect)
else:
detPol = polygon_from_points(points)
detPols.append(detPol)
detPolPoints.append(points)
if len(gtDontCarePolsNum) > 0:
for dontCarePol in gtDontCarePolsNum:
dontCarePol = gtPols[dontCarePol]
intersected_area = get_intersection(dontCarePol, detPol)
pdDimensions = detPol.area()
precision = 0 if pdDimensions == 0 else intersected_area / pdDimensions
if (precision > evaluationParams['AREA_PRECISION_CONSTRAINT']):
detDontCarePolsNum.append(len(detPols) - 1)
break
evaluationLog += "DET polygons: " + str(len(detPols)) + (
" (" + str(len(detDontCarePolsNum)) + " don't care)\n" if len(detDontCarePolsNum) > 0 else "\n")
if len(gtPols) > 0 and len(detPols) > 0:
# Calculate IoU and precision matrixs
outputShape = [len(gtPols), len(detPols)]
iouMat = np.empty(outputShape)
gtRectMat = np.zeros(len(gtPols), np.int8)
detRectMat = np.zeros(len(detPols), np.int8)
for gtNum in range(len(gtPols)):
for detNum in range(len(detPols)):
pG = gtPols[gtNum]
pD = detPols[detNum]
iouMat[gtNum, detNum] = get_intersection_over_union(pD, pG)
for gtNum in range(len(gtPols)):
for detNum in range(len(detPols)):
if gtRectMat[gtNum] == 0 and detRectMat[
detNum] == 0 and gtNum not in gtDontCarePolsNum and detNum not in detDontCarePolsNum:
if iouMat[gtNum, detNum] > evaluationParams['IOU_CONSTRAINT']:
gtRectMat[gtNum] = 1
detRectMat[detNum] = 1
detMatched += 1
pairs.append({'gt': gtNum, 'det': detNum})
detMatchedNums.append(detNum)
evaluationLog += "Match GT #" + str(gtNum) + " with Det #" + str(detNum) + "\n"
if evaluationParams['CONFIDENCES']:
for detNum in range(len(detPols)):
if detNum not in detDontCarePolsNum:
# we exclude the don't care detections
match = detNum in detMatchedNums
arrSampleConfidences.append(confidencesList[detNum])
arrSampleMatch.append(match)
arrGlobalConfidences.append(confidencesList[detNum]);
arrGlobalMatches.append(match);
numGtCare = (len(gtPols) - len(gtDontCarePolsNum))
numDetCare = (len(detPols) - len(detDontCarePolsNum))
if numGtCare == 0:
recall = float(1)
precision = float(0) if numDetCare > 0 else float(1)
sampleAP = precision
else:
recall = float(detMatched) / numGtCare
precision = 0 if numDetCare == 0 else float(detMatched) / numDetCare
if evaluationParams['CONFIDENCES'] and evaluationParams['PER_SAMPLE_RESULTS']:
sampleAP = compute_ap(arrSampleConfidences, arrSampleMatch, numGtCare)
hmean = 0 if (precision + recall) == 0 else 2.0 * precision * recall / (precision + recall)
matchedSum += detMatched
numGlobalCareGt += numGtCare
numGlobalCareDet += numDetCare
if evaluationParams['PER_SAMPLE_RESULTS']:
perSampleMetrics[resFile] = {
'precision': precision,
'recall': recall,
'hmean': hmean,
'pairs': pairs,
'AP': sampleAP,
'iouMat': [] if len(detPols) > 100 else iouMat.tolist(),
'gtPolPoints': gtPolPoints,
'detPolPoints': detPolPoints,
'gtDontCare': gtDontCarePolsNum,
'detDontCare': detDontCarePolsNum,
'evaluationParams': evaluationParams,
'evaluationLog': evaluationLog
}
# Compute MAP and MAR
AP = 0
if evaluationParams['CONFIDENCES']:
AP = compute_ap(arrGlobalConfidences, arrGlobalMatches, numGlobalCareGt)
methodRecall = 0 if numGlobalCareGt == 0 else float(matchedSum) / numGlobalCareGt
methodPrecision = 0 if numGlobalCareDet == 0 else float(matchedSum) / numGlobalCareDet
methodHmean = 0 if methodRecall + methodPrecision == 0 else 2 * methodRecall * methodPrecision / (
methodRecall + methodPrecision)
methodMetrics = {'precision': methodPrecision, 'recall': methodRecall, 'hmean': methodHmean, 'AP': AP}
resDict = {'calculated': True, 'Message': '', 'method': methodMetrics, 'per_sample': perSampleMetrics}
return resDict; | [
"def",
"evaluate_method",
"(",
"gtFilePath",
",",
"submFilePath",
",",
"evaluationParams",
")",
":",
"def",
"polygon_from_points",
"(",
"points",
")",
":",
"\"\"\"\n Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4\n ... | https://github.com/WenmuZhou/DBNet.pytorch/blob/678b2ae55e018c6c16d5ac182558517a154a91ed/utils/cal_recall/script.py#L48-L317 | |
ni/nidaqmx-python | 62fc6b48cbbb330fe1bcc9aedadc86610a1269b6 | nidaqmx/_task_modules/export_signals.py | python | ExportSignals.samp_clk_delay_offset | (self) | return val.value | float: Specifies in seconds the amount of time to offset the
exported Sample clock. Refer to timing diagrams for
generation applications in the device documentation for more
information about this value. | float: Specifies in seconds the amount of time to offset the
exported Sample clock. Refer to timing diagrams for
generation applications in the device documentation for more
information about this value. | [
"float",
":",
"Specifies",
"in",
"seconds",
"the",
"amount",
"of",
"time",
"to",
"offset",
"the",
"exported",
"Sample",
"clock",
".",
"Refer",
"to",
"timing",
"diagrams",
"for",
"generation",
"applications",
"in",
"the",
"device",
"documentation",
"for",
"more... | def samp_clk_delay_offset(self):
"""
float: Specifies in seconds the amount of time to offset the
exported Sample clock. Refer to timing diagrams for
generation applications in the device documentation for more
information about this value.
"""
val = ctypes.c_double()
cfunc = lib_importer.windll.DAQmxGetExportedSampClkDelayOffset
if cfunc.argtypes is None:
with cfunc.arglock:
if cfunc.argtypes is None:
cfunc.argtypes = [
lib_importer.task_handle,
ctypes.POINTER(ctypes.c_double)]
error_code = cfunc(
self._handle, ctypes.byref(val))
check_for_error(error_code)
return val.value | [
"def",
"samp_clk_delay_offset",
"(",
"self",
")",
":",
"val",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"cfunc",
"=",
"lib_importer",
".",
"windll",
".",
"DAQmxGetExportedSampClkDelayOffset",
"if",
"cfunc",
".",
"argtypes",
"is",
"None",
":",
"with",
"cfunc",
... | https://github.com/ni/nidaqmx-python/blob/62fc6b48cbbb330fe1bcc9aedadc86610a1269b6/nidaqmx/_task_modules/export_signals.py#L2196-L2217 | |
smart-mobile-software/gitstack | d9fee8f414f202143eb6e620529e8e5539a2af56 | python/Lib/StringIO.py | python | StringIO.seek | (self, pos, mode = 0) | Set the file's current position.
The mode argument is optional and defaults to 0 (absolute file
positioning); other values are 1 (seek relative to the current
position) and 2 (seek relative to the file's end).
There is no return value. | Set the file's current position. | [
"Set",
"the",
"file",
"s",
"current",
"position",
"."
] | def seek(self, pos, mode = 0):
"""Set the file's current position.
The mode argument is optional and defaults to 0 (absolute file
positioning); other values are 1 (seek relative to the current
position) and 2 (seek relative to the file's end).
There is no return value.
"""
_complain_ifclosed(self.closed)
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
if mode == 1:
pos += self.pos
elif mode == 2:
pos += self.len
self.pos = max(0, pos) | [
"def",
"seek",
"(",
"self",
",",
"pos",
",",
"mode",
"=",
"0",
")",
":",
"_complain_ifclosed",
"(",
"self",
".",
"closed",
")",
"if",
"self",
".",
"buflist",
":",
"self",
".",
"buf",
"+=",
"''",
".",
"join",
"(",
"self",
".",
"buflist",
")",
"sel... | https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/StringIO.py#L95-L112 | ||
coderSkyChen/Action_Recognition_Zoo | 92ec5ec3efeee852aec5c057798298cd3a8e58ae | model_zoo/models/neural_gpu/neural_gpu.py | python | make_dense | (targets, noclass) | return tf.reshape(dense, [-1, noclass]) | Move a batch of targets to a dense 1-hot representation. | Move a batch of targets to a dense 1-hot representation. | [
"Move",
"a",
"batch",
"of",
"targets",
"to",
"a",
"dense",
"1",
"-",
"hot",
"representation",
"."
] | def make_dense(targets, noclass):
"""Move a batch of targets to a dense 1-hot representation."""
with tf.device("/cpu:0"):
shape = tf.shape(targets)
batch_size = shape[0]
indices = targets + noclass * tf.range(0, batch_size)
length = tf.expand_dims(batch_size * noclass, 0)
dense = tf.sparse_to_dense(indices, length, 1.0, 0.0)
return tf.reshape(dense, [-1, noclass]) | [
"def",
"make_dense",
"(",
"targets",
",",
"noclass",
")",
":",
"with",
"tf",
".",
"device",
"(",
"\"/cpu:0\"",
")",
":",
"shape",
"=",
"tf",
".",
"shape",
"(",
"targets",
")",
"batch_size",
"=",
"shape",
"[",
"0",
"]",
"indices",
"=",
"targets",
"+",... | https://github.com/coderSkyChen/Action_Recognition_Zoo/blob/92ec5ec3efeee852aec5c057798298cd3a8e58ae/model_zoo/models/neural_gpu/neural_gpu.py#L119-L127 | |
tschellenbach/Django-facebook | fecbb5dd4931cc03a8425bde84e5e7b1ba22786d | docs/docs_env/Lib/posixpath.py | python | isfile | (path) | return stat.S_ISREG(st.st_mode) | Test whether a path is a regular file | Test whether a path is a regular file | [
"Test",
"whether",
"a",
"path",
"is",
"a",
"regular",
"file"
] | def isfile(path):
"""Test whether a path is a regular file"""
try:
st = os.stat(path)
except os.error:
return False
return stat.S_ISREG(st.st_mode) | [
"def",
"isfile",
"(",
"path",
")",
":",
"try",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"path",
")",
"except",
"os",
".",
"error",
":",
"return",
"False",
"return",
"stat",
".",
"S_ISREG",
"(",
"st",
".",
"st_mode",
")"
] | https://github.com/tschellenbach/Django-facebook/blob/fecbb5dd4931cc03a8425bde84e5e7b1ba22786d/docs/docs_env/Lib/posixpath.py#L205-L211 | |
barneygale/quarry | eac47471fc55598de6b4723a728a37d035002237 | quarry/types/buffer/v1_13_2.py | python | Buffer1_13_2.unpack_slot | (self) | return slot | Unpacks a slot. | Unpacks a slot. | [
"Unpacks",
"a",
"slot",
"."
] | def unpack_slot(self):
"""
Unpacks a slot.
"""
slot = {}
item_id = self.unpack_optional(self.unpack_varint)
if item_id is None:
slot['item'] = None
else:
slot['item'] = self.registry.decode('minecraft:item', item_id)
slot['count'] = self.unpack('b')
slot['tag'] = self.unpack_nbt()
return slot | [
"def",
"unpack_slot",
"(",
"self",
")",
":",
"slot",
"=",
"{",
"}",
"item_id",
"=",
"self",
".",
"unpack_optional",
"(",
"self",
".",
"unpack_varint",
")",
"if",
"item_id",
"is",
"None",
":",
"slot",
"[",
"'item'",
"]",
"=",
"None",
"else",
":",
"slo... | https://github.com/barneygale/quarry/blob/eac47471fc55598de6b4723a728a37d035002237/quarry/types/buffer/v1_13_2.py#L20-L33 | |
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/core/index.py | python | Index.get_level_values | (self, level) | return self | Return vector of label values for requested level, equal to the length
of the index
Parameters
----------
level : int
Returns
-------
values : ndarray | Return vector of label values for requested level, equal to the length
of the index | [
"Return",
"vector",
"of",
"label",
"values",
"for",
"requested",
"level",
"equal",
"to",
"the",
"length",
"of",
"the",
"index"
] | def get_level_values(self, level):
"""
Return vector of label values for requested level, equal to the length
of the index
Parameters
----------
level : int
Returns
-------
values : ndarray
"""
# checks that level number is actually just 1
self._validate_index_level(level)
return self | [
"def",
"get_level_values",
"(",
"self",
",",
"level",
")",
":",
"# checks that level number is actually just 1",
"self",
".",
"_validate_index_level",
"(",
"level",
")",
"return",
"self"
] | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/core/index.py#L1754-L1769 | |
salabim/salabim | e0de846b042daf2dc71aaf43d8adc6486b57f376 | salabim_exp.py | python | test107 | () | [] | def test107():
env = sim.Environment()
mylist = [1, 2, 3, 400]
m = sim.Monitor("Test", type="int8", fill=mylist)
m.print_histogram()
print(m._t)
print(m._x) | [
"def",
"test107",
"(",
")",
":",
"env",
"=",
"sim",
".",
"Environment",
"(",
")",
"mylist",
"=",
"[",
"1",
",",
"2",
",",
"3",
",",
"400",
"]",
"m",
"=",
"sim",
".",
"Monitor",
"(",
"\"Test\"",
",",
"type",
"=",
"\"int8\"",
",",
"fill",
"=",
... | https://github.com/salabim/salabim/blob/e0de846b042daf2dc71aaf43d8adc6486b57f376/salabim_exp.py#L1056-L1062 | ||||
replit-archive/empythoned | 977ec10ced29a3541a4973dc2b59910805695752 | dist/lib/python2.7/collections.py | python | OrderedDict.iterkeys | (self) | return iter(self) | od.iterkeys() -> an iterator over the keys in od | od.iterkeys() -> an iterator over the keys in od | [
"od",
".",
"iterkeys",
"()",
"-",
">",
"an",
"iterator",
"over",
"the",
"keys",
"in",
"od"
] | def iterkeys(self):
'od.iterkeys() -> an iterator over the keys in od'
return iter(self) | [
"def",
"iterkeys",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"self",
")"
] | https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/collections.py#L115-L117 | |
GalSim-developers/GalSim | a05d4ec3b8d8574f99d3b0606ad882cbba53f345 | galsim/catalog.py | python | OutputCatalog.makeData | (self) | return data | Returns a numpy array of the data as it should be written to an output file. | Returns a numpy array of the data as it should be written to an output file. | [
"Returns",
"a",
"numpy",
"array",
"of",
"the",
"data",
"as",
"it",
"should",
"be",
"written",
"to",
"an",
"output",
"file",
"."
] | def makeData(self):
"""Returns a numpy array of the data as it should be written to an output file.
"""
from .angle import Angle
from .position import PositionD, PositionI
from .shear import Shear
cols = zip(*self.rows)
dtypes = []
new_cols = []
for col, name, t in zip(cols, self.names, self.types):
name = str(name) # numpy will barf if the name is a unicode string
dt = np.dtype(t) # just used to categorize the type into int, float, str
if dt.kind in np.typecodes['AllInteger']:
dtypes.append( (name, int) )
new_cols.append(col)
elif dt.kind in np.typecodes['AllFloat']:
dtypes.append( (name, float) )
new_cols.append(col)
elif t == Angle:
dtypes.append( (name + ".rad", float) )
new_cols.append( [ val.rad for val in col ] )
elif t == PositionI:
dtypes.append( (name + ".x", int) )
dtypes.append( (name + ".y", int) )
new_cols.append( [ val.x for val in col ] )
new_cols.append( [ val.y for val in col ] )
elif t == PositionD:
dtypes.append( (name + ".x", float) )
dtypes.append( (name + ".y", float) )
new_cols.append( [ val.x for val in col ] )
new_cols.append( [ val.y for val in col ] )
elif t == Shear:
dtypes.append( (name + ".g1", float) )
dtypes.append( (name + ".g2", float) )
new_cols.append( [ val.g1 for val in col ] )
new_cols.append( [ val.g2 for val in col ] )
else:
col = [ str(s).encode() for s in col ]
maxlen = np.max([ len(s) for s in col ])
dtypes.append( (name, str, maxlen) )
new_cols.append(col)
data = np.array(list(zip(*new_cols)), dtype=dtypes)
sort_index = np.argsort(self.sort_keys)
data = data[sort_index]
return data | [
"def",
"makeData",
"(",
"self",
")",
":",
"from",
".",
"angle",
"import",
"Angle",
"from",
".",
"position",
"import",
"PositionD",
",",
"PositionI",
"from",
".",
"shear",
"import",
"Shear",
"cols",
"=",
"zip",
"(",
"*",
"self",
".",
"rows",
")",
"dtype... | https://github.com/GalSim-developers/GalSim/blob/a05d4ec3b8d8574f99d3b0606ad882cbba53f345/galsim/catalog.py#L470-L519 | |
numenta/numenta-apps | 02903b0062c89c2c259b533eea2df6e8bb44eaf3 | taurus_metric_collectors/taurus_metric_collectors/metric_utils.py | python | createAllModels | (host, apiKey, onlyMetricNames=None) | return allModels | Create models corresponding to all metrics in the metrics configuration.
NOTE: Has no effect on metrics that have already been promoted to models.
:param str host: API server's hostname or IP address
:param str apiKey: API server's API Key
:param onlyMetricNames: None to create models for all configured metrics; an
iterable of metric names to limit creation of models only to metrics with
those names - the metric names in the iterable MUST be a non-empty subset of
the configured metrics.
:type onlyMetricNames: None or iterable
:returns: List of models that were created; each element is a model info
dictionary from the successful result of the _models POST request
:rtype: list of dicts
:raises: ModelQuotaExceededError if quota limit was exceeded
:raises: ModelMonitorRequestError for non-specific error in request
:raises: RetriesExceededError if retries were exceeded | Create models corresponding to all metrics in the metrics configuration. | [
"Create",
"models",
"corresponding",
"to",
"all",
"metrics",
"in",
"the",
"metrics",
"configuration",
"."
] | def createAllModels(host, apiKey, onlyMetricNames=None):
""" Create models corresponding to all metrics in the metrics configuration.
NOTE: Has no effect on metrics that have already been promoted to models.
:param str host: API server's hostname or IP address
:param str apiKey: API server's API Key
:param onlyMetricNames: None to create models for all configured metrics; an
iterable of metric names to limit creation of models only to metrics with
those names - the metric names in the iterable MUST be a non-empty subset of
the configured metrics.
:type onlyMetricNames: None or iterable
:returns: List of models that were created; each element is a model info
dictionary from the successful result of the _models POST request
:rtype: list of dicts
:raises: ModelQuotaExceededError if quota limit was exceeded
:raises: ModelMonitorRequestError for non-specific error in request
:raises: RetriesExceededError if retries were exceeded
"""
metricsConfig = getMetricsConfiguration()
configuredMetricNames = set(getMetricNamesFromConfig(metricsConfig))
if onlyMetricNames is not None:
# Validate onlyMetricNames and convert it to set
if not onlyMetricNames:
raise ValueError("onlyMetricNames is empty")
asSet = set(onlyMetricNames)
onlyMetricNames = asSet
unknownMetricNames = (onlyMetricNames -
configuredMetricNames)
if unknownMetricNames:
raise ValueError(
"{count} elements in onlyMetricNames are not in metrics configuration: "
"{unknown}".format(count=len(unknownMetricNames),
unknown=unknownMetricNames)
)
else:
onlyMetricNames = configuredMetricNames
allModels = []
i = 0
for resName, resVal in metricsConfig.iteritems():
for metricName, metricVal in resVal["metrics"].iteritems():
if metricName not in onlyMetricNames:
continue
i += 1
userInfo = {
"metricType": metricVal["metricType"],
"metricTypeName": metricVal["metricTypeName"],
"symbol": resVal["symbol"]
}
modelParams = metricVal.get("modelParams", {})
try:
model = createCustomHtmModel(host=host,
apiKey=apiKey,
metricName=metricName,
resourceName=resName,
userInfo=userInfo,
modelParams=modelParams)
except ModelQuotaExceededError as e:
g_log.error("Model quota exceeded: %r", e)
raise
g_log.info("Enabled monitoring of metric=%s; uid=%s (%d of %d)",
model["name"], model["uid"], i, len(onlyMetricNames))
allModels.append(model)
return allModels | [
"def",
"createAllModels",
"(",
"host",
",",
"apiKey",
",",
"onlyMetricNames",
"=",
"None",
")",
":",
"metricsConfig",
"=",
"getMetricsConfiguration",
"(",
")",
"configuredMetricNames",
"=",
"set",
"(",
"getMetricNamesFromConfig",
"(",
"metricsConfig",
")",
")",
"i... | https://github.com/numenta/numenta-apps/blob/02903b0062c89c2c259b533eea2df6e8bb44eaf3/taurus_metric_collectors/taurus_metric_collectors/metric_utils.py#L275-L356 | |
translate/pootle | 742c08fce1a0dc16e6ab8d2494eb867c8879205d | pootle/apps/pootle_translationproject/utils.py | python | TPTool.update_children | (self, source_dir, target_dir) | Update a target Directory and its children from a given
source Directory | Update a target Directory and its children from a given
source Directory | [
"Update",
"a",
"target",
"Directory",
"and",
"its",
"children",
"from",
"a",
"given",
"source",
"Directory"
] | def update_children(self, source_dir, target_dir):
"""Update a target Directory and its children from a given
source Directory
"""
stores = []
dirs = []
source_stores = source_dir.child_stores.select_related(
"filetype__extension",
"filetype__template_extension")
for store in source_stores:
store.parent = source_dir
stores.append(store.name)
try:
self.update_store(
store,
target_dir.child_stores.select_related(
"filetype__extension",
"filetype__template_extension").get(name=store.name))
except target_dir.child_stores.model.DoesNotExist:
self.clone_store(store, target_dir)
for subdir in source_dir.child_dirs.live():
subdir.parent = source_dir
dirs.append(subdir.name)
try:
self.update_children(
subdir,
target_dir.child_dirs.get(name=subdir.name))
except target_dir.child_dirs.model.DoesNotExist:
self.clone_directory(subdir, target_dir)
for store in target_dir.child_stores.exclude(name__in=stores):
store.makeobsolete() | [
"def",
"update_children",
"(",
"self",
",",
"source_dir",
",",
"target_dir",
")",
":",
"stores",
"=",
"[",
"]",
"dirs",
"=",
"[",
"]",
"source_stores",
"=",
"source_dir",
".",
"child_stores",
".",
"select_related",
"(",
"\"filetype__extension\"",
",",
"\"filet... | https://github.com/translate/pootle/blob/742c08fce1a0dc16e6ab8d2494eb867c8879205d/pootle/apps/pootle_translationproject/utils.py#L222-L253 | ||
plone/guillotina | 57ad54988f797a93630e424fd4b6a75fa26410af | guillotina/component/interfaces.py | python | IComponentArchitecture.get_adapters | (objects, provided, context=None) | Look for all matching adapters to a provided interface for objects
Return a list of adapters that match. If an adapter is named, only the
most specific adapter of a given name is returned.
If context is None, an application-defined policy is used to choose
an appropriate service manager from which to get an 'Adapters'
service.
If 'context' is not None, context is adapted to IServiceService,
and this adapter's 'Adapters' service is used. | Look for all matching adapters to a provided interface for objects | [
"Look",
"for",
"all",
"matching",
"adapters",
"to",
"a",
"provided",
"interface",
"for",
"objects"
] | def get_adapters(objects, provided, context=None):
"""Look for all matching adapters to a provided interface for objects
Return a list of adapters that match. If an adapter is named, only the
most specific adapter of a given name is returned.
If context is None, an application-defined policy is used to choose
an appropriate service manager from which to get an 'Adapters'
service.
If 'context' is not None, context is adapted to IServiceService,
and this adapter's 'Adapters' service is used.
""" | [
"def",
"get_adapters",
"(",
"objects",
",",
"provided",
",",
"context",
"=",
"None",
")",
":"
] | https://github.com/plone/guillotina/blob/57ad54988f797a93630e424fd4b6a75fa26410af/guillotina/component/interfaces.py#L166-L178 | ||
Huangying-Zhan/DF-VO | 6a2ec43fc6209d9058ae1709d779c5ada68a31f3 | tools/generate_flow_prediction.py | python | initialize_deep_flow_model | (h, w, weight) | return flow_net | Initialize optical flow network
Args:
h (int): image height
w (int): image width
Returns:
flow_net (nn.Module): optical flow network | Initialize optical flow network | [
"Initialize",
"optical",
"flow",
"network"
] | def initialize_deep_flow_model(h, w, weight):
"""Initialize optical flow network
Args:
h (int): image height
w (int): image width
Returns:
flow_net (nn.Module): optical flow network
"""
flow_net = LiteFlow(h, w)
flow_net.initialize_network_model(
weight_path=weight
)
return flow_net | [
"def",
"initialize_deep_flow_model",
"(",
"h",
",",
"w",
",",
"weight",
")",
":",
"flow_net",
"=",
"LiteFlow",
"(",
"h",
",",
"w",
")",
"flow_net",
".",
"initialize_network_model",
"(",
"weight_path",
"=",
"weight",
")",
"return",
"flow_net"
] | https://github.com/Huangying-Zhan/DF-VO/blob/6a2ec43fc6209d9058ae1709d779c5ada68a31f3/tools/generate_flow_prediction.py#L47-L61 | |
4shadoww/hakkuframework | 409a11fc3819d251f86faa3473439f8c19066a21 | lib/urllib3/util/url.py | python | parse_url | (url) | return Url(
scheme=ensure_type(scheme),
auth=ensure_type(auth),
host=ensure_type(host),
port=port,
path=ensure_type(path),
query=ensure_type(query),
fragment=ensure_type(fragment),
) | Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
This parser is RFC 3986 compliant.
The parser logic and helper functions are based heavily on
work done in the ``rfc3986`` module.
:param str url: URL to parse into a :class:`.Url` namedtuple.
Partly backwards-compatible with :mod:`urlparse`.
Example::
>>> parse_url('http://google.com/mail/')
Url(scheme='http', host='google.com', port=None, path='/mail/', ...)
>>> parse_url('google.com:80')
Url(scheme=None, host='google.com', port=80, path=None, ...)
>>> parse_url('/foo?bar')
Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) | Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
This parser is RFC 3986 compliant. | [
"Given",
"a",
"url",
"return",
"a",
"parsed",
":",
"class",
":",
".",
"Url",
"namedtuple",
".",
"Best",
"-",
"effort",
"is",
"performed",
"to",
"parse",
"incomplete",
"urls",
".",
"Fields",
"not",
"provided",
"will",
"be",
"None",
".",
"This",
"parser",
... | def parse_url(url):
"""
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
This parser is RFC 3986 compliant.
The parser logic and helper functions are based heavily on
work done in the ``rfc3986`` module.
:param str url: URL to parse into a :class:`.Url` namedtuple.
Partly backwards-compatible with :mod:`urlparse`.
Example::
>>> parse_url('http://google.com/mail/')
Url(scheme='http', host='google.com', port=None, path='/mail/', ...)
>>> parse_url('google.com:80')
Url(scheme=None, host='google.com', port=80, path=None, ...)
>>> parse_url('/foo?bar')
Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
"""
if not url:
# Empty
return Url()
source_url = url
if not SCHEME_RE.search(url):
url = "//" + url
try:
scheme, authority, path, query, fragment = URI_RE.match(url).groups()
normalize_uri = scheme is None or scheme.lower() in NORMALIZABLE_SCHEMES
if scheme:
scheme = scheme.lower()
if authority:
auth, _, host_port = authority.rpartition("@")
auth = auth or None
host, port = _HOST_PORT_RE.match(host_port).groups()
if auth and normalize_uri:
auth = _encode_invalid_chars(auth, USERINFO_CHARS)
if port == "":
port = None
else:
auth, host, port = None, None, None
if port is not None:
port = int(port)
if not (0 <= port <= 65535):
raise LocationParseError(url)
host = _normalize_host(host, scheme)
if normalize_uri and path:
path = _remove_path_dot_segments(path)
path = _encode_invalid_chars(path, PATH_CHARS)
if normalize_uri and query:
query = _encode_invalid_chars(query, QUERY_CHARS)
if normalize_uri and fragment:
fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS)
except (ValueError, AttributeError):
return six.raise_from(LocationParseError(source_url), None)
# For the sake of backwards compatibility we put empty
# string values for path if there are any defined values
# beyond the path in the URL.
# TODO: Remove this when we break backwards compatibility.
if not path:
if query is not None or fragment is not None:
path = ""
else:
path = None
# Ensure that each part of the URL is a `str` for
# backwards compatibility.
if isinstance(url, six.text_type):
ensure_func = six.ensure_text
else:
ensure_func = six.ensure_str
def ensure_type(x):
return x if x is None else ensure_func(x)
return Url(
scheme=ensure_type(scheme),
auth=ensure_type(auth),
host=ensure_type(host),
port=port,
path=ensure_type(path),
query=ensure_type(query),
fragment=ensure_type(fragment),
) | [
"def",
"parse_url",
"(",
"url",
")",
":",
"if",
"not",
"url",
":",
"# Empty",
"return",
"Url",
"(",
")",
"source_url",
"=",
"url",
"if",
"not",
"SCHEME_RE",
".",
"search",
"(",
"url",
")",
":",
"url",
"=",
"\"//\"",
"+",
"url",
"try",
":",
"scheme"... | https://github.com/4shadoww/hakkuframework/blob/409a11fc3819d251f86faa3473439f8c19066a21/lib/urllib3/util/url.py#L330-L424 | |
microsoft/azure-devops-python-api | 451cade4c475482792cbe9e522c1fee32393139e | azure-devops/azure/devops/released/work/work_client.py | python | WorkClient.update_team_settings | (self, team_settings_patch, team_context) | return self._deserialize('TeamSetting', response) | UpdateTeamSettings.
Update a team's settings
:param :class:`<TeamSettingsPatch> <azure.devops.v5_1.work.models.TeamSettingsPatch>` team_settings_patch: TeamSettings changes
:param :class:`<TeamContext> <azure.devops.v5_1.work.models.TeamContext>` team_context: The team context for the operation
:rtype: :class:`<TeamSetting> <azure.devops.v5_1.work.models.TeamSetting>` | UpdateTeamSettings.
Update a team's settings
:param :class:`<TeamSettingsPatch> <azure.devops.v5_1.work.models.TeamSettingsPatch>` team_settings_patch: TeamSettings changes
:param :class:`<TeamContext> <azure.devops.v5_1.work.models.TeamContext>` team_context: The team context for the operation
:rtype: :class:`<TeamSetting> <azure.devops.v5_1.work.models.TeamSetting>` | [
"UpdateTeamSettings",
".",
"Update",
"a",
"team",
"s",
"settings",
":",
"param",
":",
"class",
":",
"<TeamSettingsPatch",
">",
"<azure",
".",
"devops",
".",
"v5_1",
".",
"work",
".",
"models",
".",
"TeamSettingsPatch",
">",
"team_settings_patch",
":",
"TeamSet... | def update_team_settings(self, team_settings_patch, team_context):
"""UpdateTeamSettings.
Update a team's settings
:param :class:`<TeamSettingsPatch> <azure.devops.v5_1.work.models.TeamSettingsPatch>` team_settings_patch: TeamSettings changes
:param :class:`<TeamContext> <azure.devops.v5_1.work.models.TeamContext>` team_context: The team context for the operation
:rtype: :class:`<TeamSetting> <azure.devops.v5_1.work.models.TeamSetting>`
"""
project = None
team = None
if team_context is not None:
if team_context.project_id:
project = team_context.project_id
else:
project = team_context.project
if team_context.team_id:
team = team_context.team_id
else:
team = team_context.team
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'string')
if team is not None:
route_values['team'] = self._serialize.url('team', team, 'string')
content = self._serialize.body(team_settings_patch, 'TeamSettingsPatch')
response = self._send(http_method='PATCH',
location_id='c3c1012b-bea7-49d7-b45e-1664e566f84c',
version='5.1',
route_values=route_values,
content=content)
return self._deserialize('TeamSetting', response) | [
"def",
"update_team_settings",
"(",
"self",
",",
"team_settings_patch",
",",
"team_context",
")",
":",
"project",
"=",
"None",
"team",
"=",
"None",
"if",
"team_context",
"is",
"not",
"None",
":",
"if",
"team_context",
".",
"project_id",
":",
"project",
"=",
... | https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/released/work/work_client.py#L1098-L1128 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/wled/coordinator.py | python | WLEDDataUpdateCoordinator._async_update_data | (self) | return device | Fetch data from WLED. | Fetch data from WLED. | [
"Fetch",
"data",
"from",
"WLED",
"."
] | async def _async_update_data(self) -> WLEDDevice:
"""Fetch data from WLED."""
try:
device = await self.wled.update(full_update=not self.last_update_success)
except WLEDError as error:
raise UpdateFailed(f"Invalid response from API: {error}") from error
# If the device supports a WebSocket, try activating it.
if (
device.info.websocket is not None
and not self.wled.connected
and not self.unsub
):
self._use_websocket()
return device | [
"async",
"def",
"_async_update_data",
"(",
"self",
")",
"->",
"WLEDDevice",
":",
"try",
":",
"device",
"=",
"await",
"self",
".",
"wled",
".",
"update",
"(",
"full_update",
"=",
"not",
"self",
".",
"last_update_success",
")",
"except",
"WLEDError",
"as",
"... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/wled/coordinator.py#L106-L121 | |
larryhastings/gilectomy | 4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a | Lib/pdb.py | python | Pdb.do_commands | (self, arg) | commands [bpnumber]
(com) ...
(com) end
(Pdb)
Specify a list of commands for breakpoint number bpnumber.
The commands themselves are entered on the following lines.
Type a line containing just 'end' to terminate the commands.
The commands are executed when the breakpoint is hit.
To remove all commands from a breakpoint, type commands and
follow it immediately with end; that is, give no commands.
With no bpnumber argument, commands refers to the last
breakpoint set.
You can use breakpoint commands to start your program up
again. Simply use the continue command, or step, or any other
command that resumes execution.
Specifying any command resuming execution (currently continue,
step, next, return, jump, quit and their abbreviations)
terminates the command list (as if that command was
immediately followed by end). This is because any time you
resume execution (even with a simple next or step), you may
encounter another breakpoint -- which could have its own
command list, leading to ambiguities about which list to
execute.
If you use the 'silent' command in the command list, the usual
message about stopping at a breakpoint is not printed. This
may be desirable for breakpoints that are to print a specific
message and then continue. If none of the other commands
print anything, you will see no sign that the breakpoint was
reached. | commands [bpnumber]
(com) ...
(com) end
(Pdb) | [
"commands",
"[",
"bpnumber",
"]",
"(",
"com",
")",
"...",
"(",
"com",
")",
"end",
"(",
"Pdb",
")"
] | def do_commands(self, arg):
"""commands [bpnumber]
(com) ...
(com) end
(Pdb)
Specify a list of commands for breakpoint number bpnumber.
The commands themselves are entered on the following lines.
Type a line containing just 'end' to terminate the commands.
The commands are executed when the breakpoint is hit.
To remove all commands from a breakpoint, type commands and
follow it immediately with end; that is, give no commands.
With no bpnumber argument, commands refers to the last
breakpoint set.
You can use breakpoint commands to start your program up
again. Simply use the continue command, or step, or any other
command that resumes execution.
Specifying any command resuming execution (currently continue,
step, next, return, jump, quit and their abbreviations)
terminates the command list (as if that command was
immediately followed by end). This is because any time you
resume execution (even with a simple next or step), you may
encounter another breakpoint -- which could have its own
command list, leading to ambiguities about which list to
execute.
If you use the 'silent' command in the command list, the usual
message about stopping at a breakpoint is not printed. This
may be desirable for breakpoints that are to print a specific
message and then continue. If none of the other commands
print anything, you will see no sign that the breakpoint was
reached.
"""
if not arg:
bnum = len(bdb.Breakpoint.bpbynumber) - 1
else:
try:
bnum = int(arg)
except:
self.error("Usage: commands [bnum]\n ...\n end")
return
self.commands_bnum = bnum
# Save old definitions for the case of a keyboard interrupt.
if bnum in self.commands:
old_command_defs = (self.commands[bnum],
self.commands_doprompt[bnum],
self.commands_silent[bnum])
else:
old_command_defs = None
self.commands[bnum] = []
self.commands_doprompt[bnum] = True
self.commands_silent[bnum] = False
prompt_back = self.prompt
self.prompt = '(com) '
self.commands_defining = True
try:
self.cmdloop()
except KeyboardInterrupt:
# Restore old definitions.
if old_command_defs:
self.commands[bnum] = old_command_defs[0]
self.commands_doprompt[bnum] = old_command_defs[1]
self.commands_silent[bnum] = old_command_defs[2]
else:
del self.commands[bnum]
del self.commands_doprompt[bnum]
del self.commands_silent[bnum]
self.error('command definition aborted, old commands restored')
finally:
self.commands_defining = False
self.prompt = prompt_back | [
"def",
"do_commands",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"arg",
":",
"bnum",
"=",
"len",
"(",
"bdb",
".",
"Breakpoint",
".",
"bpbynumber",
")",
"-",
"1",
"else",
":",
"try",
":",
"bnum",
"=",
"int",
"(",
"arg",
")",
"except",
":",
... | https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/pdb.py#L511-L586 | ||
dropbox/pyannotate | a7a46f394f0ba91a1b5fbf657e2393af542969ae | pyannotate_runtime/collect_types.py | python | TentativeType.merge | (self, other) | Merge two TentativeType instances | Merge two TentativeType instances | [
"Merge",
"two",
"TentativeType",
"instances"
] | def merge(self, other):
# type: (TentativeType) -> None
"""
Merge two TentativeType instances
"""
for hashables in other.types_hashable:
self.add(hashables)
for non_hashbles in other.types:
self.add(non_hashbles) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"# type: (TentativeType) -> None",
"for",
"hashables",
"in",
"other",
".",
"types_hashable",
":",
"self",
".",
"add",
"(",
"hashables",
")",
"for",
"non_hashbles",
"in",
"other",
".",
"types",
":",
"self",... | https://github.com/dropbox/pyannotate/blob/a7a46f394f0ba91a1b5fbf657e2393af542969ae/pyannotate_runtime/collect_types.py#L369-L377 | ||
cylc/cylc-flow | 5ec221143476c7c616c156b74158edfbcd83794a | cylc/flow/task_pool.py | python | TaskPool.can_spawn | (self, name: str, point: 'PointBase') | return True | Return True if name.point is within various workflow limits. | Return True if name.point is within various workflow limits. | [
"Return",
"True",
"if",
"name",
".",
"point",
"is",
"within",
"various",
"workflow",
"limits",
"."
] | def can_spawn(self, name: str, point: 'PointBase') -> bool:
"""Return True if name.point is within various workflow limits."""
if name not in self.config.get_task_name_list():
LOG.debug('No task definition %s', name)
return False
# Don't spawn outside of graph limits.
# TODO: is it possible for initial_point to not be defined??
# (see also the similar check + log message in scheduler.py)
if self.config.initial_point and point < self.config.initial_point:
# Attempted manual trigger prior to FCP
# or future triggers like foo[+P1] => bar, with foo at ICP.
LOG.debug(
'Not spawning %s.%s: before initial cycle point', name, point)
return False
elif self.config.final_point and point > self.config.final_point:
# Only happens on manual trigger beyond FCP
LOG.debug(
'Not spawning %s.%s: beyond final cycle point', name, point)
return False
return True | [
"def",
"can_spawn",
"(",
"self",
",",
"name",
":",
"str",
",",
"point",
":",
"'PointBase'",
")",
"->",
"bool",
":",
"if",
"name",
"not",
"in",
"self",
".",
"config",
".",
"get_task_name_list",
"(",
")",
":",
"LOG",
".",
"debug",
"(",
"'No task definiti... | https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/task_pool.py#L1273-L1292 | |
INK-USC/KagNet | b386661ac5841774b9d17cc132e991a7bef3c5ef | baselines/pytorch-pretrained-BERT/pytorch_pretrained_bert/modeling_transfo_xl.py | python | TransfoXLPreTrainedModel.init_weight | (self, weight) | [] | def init_weight(self, weight):
if self.config.init == 'uniform':
nn.init.uniform_(weight, -self.config.init_range, self.config.init_range)
elif self.config.init == 'normal':
nn.init.normal_(weight, 0.0, self.config.init_std) | [
"def",
"init_weight",
"(",
"self",
",",
"weight",
")",
":",
"if",
"self",
".",
"config",
".",
"init",
"==",
"'uniform'",
":",
"nn",
".",
"init",
".",
"uniform_",
"(",
"weight",
",",
"-",
"self",
".",
"config",
".",
"init_range",
",",
"self",
".",
"... | https://github.com/INK-USC/KagNet/blob/b386661ac5841774b9d17cc132e991a7bef3c5ef/baselines/pytorch-pretrained-BERT/pytorch_pretrained_bert/modeling_transfo_xl.py#L831-L835 | ||||
santhoshkolloju/Abstractive-Summarization-With-Transfer-Learning | 97ff2ae3ba9f2d478e174444c4e0f5349f28c319 | texar_repo/examples/bert/utils/data_utils.py | python | SSTProcessor.get_labels | (self) | return ["0", "1"] | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def get_labels(self):
"""See base class."""
return ["0", "1"] | [
"def",
"get_labels",
"(",
"self",
")",
":",
"return",
"[",
"\"0\"",
",",
"\"1\"",
"]"
] | https://github.com/santhoshkolloju/Abstractive-Summarization-With-Transfer-Learning/blob/97ff2ae3ba9f2d478e174444c4e0f5349f28c319/texar_repo/examples/bert/utils/data_utils.py#L106-L108 | |
alan-turing-institute/CleverCSV | a7c7c812f2dc220b8f45f3409daac6e933bc44a2 | clevercsv/utils.py | python | sha1sum | (filename) | return hasher.hexdigest() | Compute the SHA1 checksum of a given file
Parameters
----------
filename : str
Path to a file
Returns
-------
checksum : str
The SHA1 checksum of the file contents. | Compute the SHA1 checksum of a given file | [
"Compute",
"the",
"SHA1",
"checksum",
"of",
"a",
"given",
"file"
] | def sha1sum(filename):
"""Compute the SHA1 checksum of a given file
Parameters
----------
filename : str
Path to a file
Returns
-------
checksum : str
The SHA1 checksum of the file contents.
"""
blocksize = 1 << 16
hasher = hashlib.sha1()
with open(filename, "rb") as fp:
buf = fp.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = fp.read(blocksize)
return hasher.hexdigest() | [
"def",
"sha1sum",
"(",
"filename",
")",
":",
"blocksize",
"=",
"1",
"<<",
"16",
"hasher",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"fp",
":",
"buf",
"=",
"fp",
".",
"read",
"(",
"blocksize",
... | https://github.com/alan-turing-institute/CleverCSV/blob/a7c7c812f2dc220b8f45f3409daac6e933bc44a2/clevercsv/utils.py#L21-L41 | |
khalim19/gimp-plugin-export-layers | b37255f2957ad322f4d332689052351cdea6e563 | export_layers/pygimplib/_lib/python_standard_modules/logging/__init__.py | python | captureWarnings | (capture) | If capture is true, redirect all warnings to the logging package.
If capture is False, ensure that warnings are not redirected to logging
but to their original destinations. | If capture is true, redirect all warnings to the logging package.
If capture is False, ensure that warnings are not redirected to logging
but to their original destinations. | [
"If",
"capture",
"is",
"true",
"redirect",
"all",
"warnings",
"to",
"the",
"logging",
"package",
".",
"If",
"capture",
"is",
"False",
"ensure",
"that",
"warnings",
"are",
"not",
"redirected",
"to",
"logging",
"but",
"to",
"their",
"original",
"destinations",
... | def captureWarnings(capture):
"""
If capture is true, redirect all warnings to the logging package.
If capture is False, ensure that warnings are not redirected to logging
but to their original destinations.
"""
global _warnings_showwarning
if capture:
if _warnings_showwarning is None:
_warnings_showwarning = warnings.showwarning
warnings.showwarning = _showwarning
else:
if _warnings_showwarning is not None:
warnings.showwarning = _warnings_showwarning
_warnings_showwarning = None | [
"def",
"captureWarnings",
"(",
"capture",
")",
":",
"global",
"_warnings_showwarning",
"if",
"capture",
":",
"if",
"_warnings_showwarning",
"is",
"None",
":",
"_warnings_showwarning",
"=",
"warnings",
".",
"showwarning",
"warnings",
".",
"showwarning",
"=",
"_showwa... | https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/pygimplib/_lib/python_standard_modules/logging/__init__.py#L1730-L1744 | ||
linkchecker/linkchecker | d1078ed8480e5cfc4264d0dbf026b45b45aede4d | linkcheck/log.py | python | warn | (logname, msg, *args, **kwargs) | Log a warning.
return: None | Log a warning. | [
"Log",
"a",
"warning",
"."
] | def warn(logname, msg, *args, **kwargs):
"""Log a warning.
return: None
"""
log = logging.getLogger(logname)
if log.isEnabledFor(logging.WARN):
_log(log.warning, msg, args, **kwargs) | [
"def",
"warn",
"(",
"logname",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"logname",
")",
"if",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"WARN",
")",
":",
"_log",
"(",
"l... | https://github.com/linkchecker/linkchecker/blob/d1078ed8480e5cfc4264d0dbf026b45b45aede4d/linkcheck/log.py#L95-L102 | ||
fabioz/PyDev.Debugger | 0f8c02a010fe5690405da1dd30ed72326191ce63 | _pydevd_bundle/pydevd_daemon_thread.py | python | PyDBDaemonThread.__init__ | (self, py_db, target_and_args=None) | :param target_and_args:
tuple(func, args, kwargs) if this should be a function and args to run.
-- Note: use through run_as_pydevd_daemon_thread(). | :param target_and_args:
tuple(func, args, kwargs) if this should be a function and args to run.
-- Note: use through run_as_pydevd_daemon_thread(). | [
":",
"param",
"target_and_args",
":",
"tuple",
"(",
"func",
"args",
"kwargs",
")",
"if",
"this",
"should",
"be",
"a",
"function",
"and",
"args",
"to",
"run",
".",
"--",
"Note",
":",
"use",
"through",
"run_as_pydevd_daemon_thread",
"()",
"."
] | def __init__(self, py_db, target_and_args=None):
'''
:param target_and_args:
tuple(func, args, kwargs) if this should be a function and args to run.
-- Note: use through run_as_pydevd_daemon_thread().
'''
threading.Thread.__init__(self)
notify_about_gevent_if_needed()
self._py_db = weakref.ref(py_db)
self._kill_received = False
mark_as_pydevd_daemon_thread(self)
self._target_and_args = target_and_args | [
"def",
"__init__",
"(",
"self",
",",
"py_db",
",",
"target_and_args",
"=",
"None",
")",
":",
"threading",
".",
"Thread",
".",
"__init__",
"(",
"self",
")",
"notify_about_gevent_if_needed",
"(",
")",
"self",
".",
"_py_db",
"=",
"weakref",
".",
"ref",
"(",
... | https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/_pydevd_bundle/pydevd_daemon_thread.py#L19-L30 | ||
insanum/sncli | c34729c6c286b924eb9ab72a2a5ec4f950465e57 | simplenote_cli/simplenote.py | python | Simplenote.authenticate | (self, user: str, password: str) | return api | Method to get simplenote auth token
Arguments:
- user (string): simplenote email address
- password (string): simplenote password
Returns:
Simplenote API instance | Method to get simplenote auth token | [
"Method",
"to",
"get",
"simplenote",
"auth",
"token"
] | def authenticate(self, user: str, password: str) -> Api:
""" Method to get simplenote auth token
Arguments:
- user (string): simplenote email address
- password (string): simplenote password
Returns:
Simplenote API instance
"""
token = self.auth.authorize(user, password)
api = Api(SIMPLENOTE_APP_ID, token)
self.status = "online"
return api | [
"def",
"authenticate",
"(",
"self",
",",
"user",
":",
"str",
",",
"password",
":",
"str",
")",
"->",
"Api",
":",
"token",
"=",
"self",
".",
"auth",
".",
"authorize",
"(",
"user",
",",
"password",
")",
"api",
"=",
"Api",
"(",
"SIMPLENOTE_APP_ID",
",",... | https://github.com/insanum/sncli/blob/c34729c6c286b924eb9ab72a2a5ec4f950465e57/simplenote_cli/simplenote.py#L77-L92 | |
gkrizek/bash-lambda-layer | 703b0ade8174022d44779d823172ab7ac33a5505 | bin/docutils/statemachine.py | python | StateMachine.at_eof | (self) | return self.line_offset >= len(self.input_lines) - 1 | Return 1 if the input is at or past end-of-file. | Return 1 if the input is at or past end-of-file. | [
"Return",
"1",
"if",
"the",
"input",
"is",
"at",
"or",
"past",
"end",
"-",
"of",
"-",
"file",
"."
] | def at_eof(self):
"""Return 1 if the input is at or past end-of-file."""
return self.line_offset >= len(self.input_lines) - 1 | [
"def",
"at_eof",
"(",
"self",
")",
":",
"return",
"self",
".",
"line_offset",
">=",
"len",
"(",
"self",
".",
"input_lines",
")",
"-",
"1"
] | https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/docutils/statemachine.py#L322-L324 | |
odlgroup/odl | 0b088df8dc4621c68b9414c3deff9127f4c4f11d | odl/util/ufuncs.py | python | ProductSpaceUfuncs.sum | (self) | return np.sum(results) | Return the sum of ``self``.
See Also
--------
numpy.sum
prod | Return the sum of ``self``. | [
"Return",
"the",
"sum",
"of",
"self",
"."
] | def sum(self):
"""Return the sum of ``self``.
See Also
--------
numpy.sum
prod
"""
results = [x.ufuncs.sum() for x in self.elem]
return np.sum(results) | [
"def",
"sum",
"(",
"self",
")",
":",
"results",
"=",
"[",
"x",
".",
"ufuncs",
".",
"sum",
"(",
")",
"for",
"x",
"in",
"self",
".",
"elem",
"]",
"return",
"np",
".",
"sum",
"(",
"results",
")"
] | https://github.com/odlgroup/odl/blob/0b088df8dc4621c68b9414c3deff9127f4c4f11d/odl/util/ufuncs.py#L255-L264 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.