partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | Client.send_text_message | 发送文本消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param content: 消息正文
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包 | werobot/client.py | def send_text_message(self, user_id, content, kf_account=None):
"""
发送文本消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param content: 消息正文
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"touser": us... | def send_text_message(self, user_id, content, kf_account=None):
"""
发送文本消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param content: 消息正文
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"touser": us... | [
"发送文本消息。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L728-L749 | [
"def",
"send_text_message",
"(",
"self",
",",
"user_id",
",",
"content",
",",
"kf_account",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"touser\"",
":",
"user_id",
",",
"\"msgtype\"",
":",
"\"text\"",
",",
"\"text\"",
":",
"{",
"\"content\"",
":",
"content"... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.send_image_message | 发送图片消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 图片的媒体ID。 可以通过 :func:`upload_media` 上传。
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包 | werobot/client.py | def send_image_message(self, user_id, media_id, kf_account=None):
"""
发送图片消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 图片的媒体ID。 可以通过 :func:`upload_media` 上传。
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
... | def send_image_message(self, user_id, media_id, kf_account=None):
"""
发送图片消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 图片的媒体ID。 可以通过 :func:`upload_media` 上传。
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
... | [
"发送图片消息。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L751-L772 | [
"def",
"send_image_message",
"(",
"self",
",",
"user_id",
",",
"media_id",
",",
"kf_account",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"touser\"",
":",
"user_id",
",",
"\"msgtype\"",
":",
"\"image\"",
",",
"\"image\"",
":",
"{",
"\"media_id\"",
":",
"med... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.send_voice_message | 发送语音消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 发送的语音的媒体ID。 可以通过 :func:`upload_media` 上传。
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包 | werobot/client.py | def send_voice_message(self, user_id, media_id, kf_account=None):
"""
发送语音消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 发送的语音的媒体ID。 可以通过 :func:`upload_media` 上传。
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
... | def send_voice_message(self, user_id, media_id, kf_account=None):
"""
发送语音消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 发送的语音的媒体ID。 可以通过 :func:`upload_media` 上传。
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
... | [
"发送语音消息。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L774-L795 | [
"def",
"send_voice_message",
"(",
"self",
",",
"user_id",
",",
"media_id",
",",
"kf_account",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"touser\"",
":",
"user_id",
",",
"\"msgtype\"",
":",
"\"voice\"",
",",
"\"voice\"",
":",
"{",
"\"media_id\"",
":",
"med... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.send_music_message | 发送音乐消息。
注意如果你遇到了缩略图不能正常显示的问题, 不要慌张; 目前来看是微信服务器端的问题。
对此我们也无能为力 ( `#197 <https://github.com/whtsky/WeRoBot/issues/197>`_ )
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param url: 音乐链接
:param hq_url: 高品质音乐链接,wifi环境优先使用该链接播放音乐
:param thumb_media_id: 缩略图的媒体ID。 可以通过 :fun... | werobot/client.py | def send_music_message(
self,
user_id,
url,
hq_url,
thumb_media_id,
title=None,
description=None,
kf_account=None
):
"""
发送音乐消息。
注意如果你遇到了缩略图不能正常显示的问题, 不要慌张; 目前来看是微信服务器端的问题。
对此我们也无能为力 ( `#197 <https://github.com/whtsky/We... | def send_music_message(
self,
user_id,
url,
hq_url,
thumb_media_id,
title=None,
description=None,
kf_account=None
):
"""
发送音乐消息。
注意如果你遇到了缩略图不能正常显示的问题, 不要慌张; 目前来看是微信服务器端的问题。
对此我们也无能为力 ( `#197 <https://github.com/whtsky/We... | [
"发送音乐消息。",
"注意如果你遇到了缩略图不能正常显示的问题,",
"不要慌张;",
"目前来看是微信服务器端的问题。",
"对此我们也无能为力",
"(",
"#197",
"<https",
":",
"//",
"github",
".",
"com",
"/",
"whtsky",
"/",
"WeRoBot",
"/",
"issues",
"/",
"197",
">",
"_",
")"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L825-L865 | [
"def",
"send_music_message",
"(",
"self",
",",
"user_id",
",",
"url",
",",
"hq_url",
",",
"thumb_media_id",
",",
"title",
"=",
"None",
",",
"description",
"=",
"None",
",",
"kf_account",
"=",
"None",
")",
":",
"music_data",
"=",
"{",
"\"musicurl\"",
":",
... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.send_article_message | 发送图文消息::
articles = [
{
"title":"Happy Day",
"description":"Is Really A Happy Day",
"url":"URL",
"picurl":"PIC_URL"
},
{
"title":"Happy Day",
... | werobot/client.py | def send_article_message(self, user_id, articles, kf_account=None):
"""
发送图文消息::
articles = [
{
"title":"Happy Day",
"description":"Is Really A Happy Day",
"url":"URL",
"picurl":"PIC_URL"
... | def send_article_message(self, user_id, articles, kf_account=None):
"""
发送图文消息::
articles = [
{
"title":"Happy Day",
"description":"Is Really A Happy Day",
"url":"URL",
"picurl":"PIC_URL"
... | [
"发送图文消息",
"::"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L867-L912 | [
"def",
"send_article_message",
"(",
"self",
",",
"user_id",
",",
"articles",
",",
"kf_account",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"articles",
"[",
"0",
"]",
",",
"Article",
")",
":",
"formatted_articles",
"=",
"[",
"]",
"for",
"article",
"i... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.send_news_message | 发送永久素材中的图文消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 媒体文件 ID
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包 | werobot/client.py | def send_news_message(self, user_id, media_id, kf_account=None):
"""
发送永久素材中的图文消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 媒体文件 ID
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"... | def send_news_message(self, user_id, media_id, kf_account=None):
"""
发送永久素材中的图文消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 媒体文件 ID
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"... | [
"发送永久素材中的图文消息。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L914-L935 | [
"def",
"send_news_message",
"(",
"self",
",",
"user_id",
",",
"media_id",
",",
"kf_account",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"touser\"",
":",
"user_id",
",",
"\"msgtype\"",
":",
"\"mpnews\"",
",",
"\"mpnews\"",
":",
"{",
"\"media_id\"",
":",
"me... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.send_miniprogrampage_message | 发送小程序卡片(要求小程序与公众号已关联)
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param title: 小程序卡片的标题
:param appid: 小程序的 appid,要求小程序的 appid 需要与公众号有关联关系
:param pagepath: 小程序的页面路径,跟 app.json 对齐,支持参数,比如 pages/index/index?foo=bar
:param thumb_media_id: 小程序卡片图片的媒体 ID,小程序卡片图片建议大小为 520*416
... | werobot/client.py | def send_miniprogrampage_message(
self, user_id, title, appid, pagepath, thumb_media_id, kf_account=None
):
"""
发送小程序卡片(要求小程序与公众号已关联)
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param title: 小程序卡片的标题
:param appid: 小程序的 appid,要求小程序的 appid 需要与公众号有关联关系
:p... | def send_miniprogrampage_message(
self, user_id, title, appid, pagepath, thumb_media_id, kf_account=None
):
"""
发送小程序卡片(要求小程序与公众号已关联)
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param title: 小程序卡片的标题
:param appid: 小程序的 appid,要求小程序的 appid 需要与公众号有关联关系
:p... | [
"发送小程序卡片(要求小程序与公众号已关联)"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L937-L966 | [
"def",
"send_miniprogrampage_message",
"(",
"self",
",",
"user_id",
",",
"title",
",",
"appid",
",",
"pagepath",
",",
"thumb_media_id",
",",
"kf_account",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"touser\"",
":",
"user_id",
",",
"\"msgtype\"",
":",
"\"mini... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.send_template_message | 发送模板消息
详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param template_id: 模板 ID。
:param data: 用于渲染模板的数据。
:param url: 模板消息的可选链接。
:return: 返回的 JSON 数据包 | werobot/client.py | def send_template_message(self, user_id, template_id, data, url=''):
"""
发送模板消息
详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param template_id: 模板 ID。
:param data: 用于渲染模板的数据。
:param... | def send_template_message(self, user_id, template_id, data, url=''):
"""
发送模板消息
详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param template_id: 模板 ID。
:param data: 用于渲染模板的数据。
:param... | [
"发送模板消息",
"详情请参考",
"http",
":",
"//",
"mp",
".",
"weixin",
".",
"qq",
".",
"com",
"/",
"wiki",
"/",
"17",
"/",
"304c1885ea66dbedf7dc170d84999a9d",
".",
"html"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L991-L1010 | [
"def",
"send_template_message",
"(",
"self",
",",
"user_id",
",",
"template_id",
",",
"data",
",",
"url",
"=",
"''",
")",
":",
"return",
"self",
".",
"post",
"(",
"url",
"=",
"\"https://api.weixin.qq.com/cgi-bin/message/template/send\"",
",",
"data",
"=",
"{",
... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.update_tag | 修改标签
:param tag_id: 标签 ID
:param tag_name: 新的标签名
:return: 返回的 JSON 数据包 | werobot/client.py | def update_tag(self, tag_id, tag_name):
"""
修改标签
:param tag_id: 标签 ID
:param tag_name: 新的标签名
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/tags/update",
data={"tag": {
"id": tag_id,
... | def update_tag(self, tag_id, tag_name):
"""
修改标签
:param tag_id: 标签 ID
:param tag_name: 新的标签名
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/tags/update",
data={"tag": {
"id": tag_id,
... | [
"修改标签"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L1034-L1048 | [
"def",
"update_tag",
"(",
"self",
",",
"tag_id",
",",
"tag_name",
")",
":",
"return",
"self",
".",
"post",
"(",
"url",
"=",
"\"https://api.weixin.qq.com/cgi-bin/tags/update\"",
",",
"data",
"=",
"{",
"\"tag\"",
":",
"{",
"\"id\"",
":",
"tag_id",
",",
"\"name... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.get_users_by_tag | 获取标签下粉丝列表
:param tag_id: 标签 ID
:param next_open_id: 第一个拉取用户的 OPENID,默认从头开始拉取
:return: 返回的 JSON 数据包 | werobot/client.py | def get_users_by_tag(self, tag_id, next_open_id=""):
"""
获取标签下粉丝列表
:param tag_id: 标签 ID
:param next_open_id: 第一个拉取用户的 OPENID,默认从头开始拉取
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/user/tag/get",
data={
... | def get_users_by_tag(self, tag_id, next_open_id=""):
"""
获取标签下粉丝列表
:param tag_id: 标签 ID
:param next_open_id: 第一个拉取用户的 OPENID,默认从头开始拉取
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/user/tag/get",
data={
... | [
"获取标签下粉丝列表"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L1064-L1078 | [
"def",
"get_users_by_tag",
"(",
"self",
",",
"tag_id",
",",
"next_open_id",
"=",
"\"\"",
")",
":",
"return",
"self",
".",
"post",
"(",
"url",
"=",
"\"https://api.weixin.qq.com/cgi-bin/user/tag/get\"",
",",
"data",
"=",
"{",
"\"tagid\"",
":",
"tag_id",
",",
"\"... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.tag_users | 批量为用户打标签
:param tag_id: 标签 ID
:param open_id_list: 包含一个或多个用户的 OPENID 的列表
:return: 返回的 JSON 数据包 | werobot/client.py | def tag_users(self, tag_id, open_id_list):
"""
批量为用户打标签
:param tag_id: 标签 ID
:param open_id_list: 包含一个或多个用户的 OPENID 的列表
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging",
data={
... | def tag_users(self, tag_id, open_id_list):
"""
批量为用户打标签
:param tag_id: 标签 ID
:param open_id_list: 包含一个或多个用户的 OPENID 的列表
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging",
data={
... | [
"批量为用户打标签"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L1094-L1108 | [
"def",
"tag_users",
"(",
"self",
",",
"tag_id",
",",
"open_id_list",
")",
":",
"return",
"self",
".",
"post",
"(",
"url",
"=",
"\"https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging\"",
",",
"data",
"=",
"{",
"\"openid_list\"",
":",
"open_id_list",
",",
"\... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Client.untag_users | 批量为用户取消标签
:param tag_id: 标签 ID
:param open_id_list: 包含一个或多个用户的 OPENID 的列表
:return: 返回的 JSON 数据包 | werobot/client.py | def untag_users(self, tag_id, open_id_list):
"""
批量为用户取消标签
:param tag_id: 标签 ID
:param open_id_list: 包含一个或多个用户的 OPENID 的列表
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging",
dat... | def untag_users(self, tag_id, open_id_list):
"""
批量为用户取消标签
:param tag_id: 标签 ID
:param open_id_list: 包含一个或多个用户的 OPENID 的列表
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging",
dat... | [
"批量为用户取消标签"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L1110-L1124 | [
"def",
"untag_users",
"(",
"self",
",",
"tag_id",
",",
"open_id_list",
")",
":",
"return",
"self",
".",
"post",
"(",
"url",
"=",
"\"https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging\"",
",",
"data",
"=",
"{",
"\"openid_list\"",
":",
"open_id_list",
",",
... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | FileStorage.get | 根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 | werobot/session/filestorage.py | def get(self, id):
"""
根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
"""
try:
session_json = self.db[id]
except KeyError:
session_json = "{}"
return json_loads(session_json) | def get(self, id):
"""
根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
"""
try:
session_json = self.db[id]
except KeyError:
session_json = "{}"
return json_loads(session_json) | [
"根据",
"id",
"获取数据。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/session/filestorage.py#L28-L39 | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"try",
":",
"session_json",
"=",
"self",
".",
"db",
"[",
"id",
"]",
"except",
"KeyError",
":",
"session_json",
"=",
"\"{}\"",
"return",
"json_loads",
"(",
"session_json",
")"
] | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | PrpCrypto.encrypt | 对明文进行加密
:param text: 需要加密的明文
:param app_id: 微信公众平台的 AppID
:return: 加密后的字符串 | werobot/crypto/__init__.py | def encrypt(self, text, app_id):
"""
对明文进行加密
:param text: 需要加密的明文
:param app_id: 微信公众平台的 AppID
:return: 加密后的字符串
"""
text = b"".join(
[
to_binary(self.get_random_string()),
struct.pack(b"I", socket.htonl(len(to_binary(tex... | def encrypt(self, text, app_id):
"""
对明文进行加密
:param text: 需要加密的明文
:param app_id: 微信公众平台的 AppID
:return: 加密后的字符串
"""
text = b"".join(
[
to_binary(self.get_random_string()),
struct.pack(b"I", socket.htonl(len(to_binary(tex... | [
"对明文进行加密",
":",
"param",
"text",
":",
"需要加密的明文",
":",
"param",
"app_id",
":",
"微信公众平台的",
"AppID",
":",
"return",
":",
"加密后的字符串"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/crypto/__init__.py#L45-L63 | [
"def",
"encrypt",
"(",
"self",
",",
"text",
",",
"app_id",
")",
":",
"text",
"=",
"b\"\"",
".",
"join",
"(",
"[",
"to_binary",
"(",
"self",
".",
"get_random_string",
"(",
")",
")",
",",
"struct",
".",
"pack",
"(",
"b\"I\"",
",",
"socket",
".",
"hto... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | PrpCrypto.decrypt | 对密文进行解密
:param text: 需要解密的密文
:param app_id: 微信公众平台的 AppID
:return: 解密后的字符串 | werobot/crypto/__init__.py | def decrypt(self, text, app_id):
"""
对密文进行解密
:param text: 需要解密的密文
:param app_id: 微信公众平台的 AppID
:return: 解密后的字符串
"""
text = to_binary(text)
decryptor = self.cipher.decryptor()
plain_text = decryptor.update(base64.b64decode(text)
... | def decrypt(self, text, app_id):
"""
对密文进行解密
:param text: 需要解密的密文
:param app_id: 微信公众平台的 AppID
:return: 解密后的字符串
"""
text = to_binary(text)
decryptor = self.cipher.decryptor()
plain_text = decryptor.update(base64.b64decode(text)
... | [
"对密文进行解密",
":",
"param",
"text",
":",
"需要解密的密文",
":",
"param",
"app_id",
":",
"微信公众平台的",
"AppID",
":",
"return",
":",
"解密后的字符串"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/crypto/__init__.py#L65-L87 | [
"def",
"decrypt",
"(",
"self",
",",
"text",
",",
"app_id",
")",
":",
"text",
"=",
"to_binary",
"(",
"text",
")",
"decryptor",
"=",
"self",
".",
"cipher",
".",
"decryptor",
"(",
")",
"plain_text",
"=",
"decryptor",
".",
"update",
"(",
"base64",
".",
"... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | MessageCrypt.decrypt_message | 解密收到的微信消息
:param timestamp: 请求 URL 中收到的 timestamp
:param nonce: 请求 URL 中收到的 nonce
:param msg_signature: 请求 URL 中收到的 msg_signature
:param encrypt_msg: 收到的加密文本. ( XML 中的 <Encrypt> 部分 )
:return: 解密后的 XML 文本 | werobot/crypto/__init__.py | def decrypt_message(self, timestamp, nonce, msg_signature, encrypt_msg):
"""
解密收到的微信消息
:param timestamp: 请求 URL 中收到的 timestamp
:param nonce: 请求 URL 中收到的 nonce
:param msg_signature: 请求 URL 中收到的 msg_signature
:param encrypt_msg: 收到的加密文本. ( XML 中的 <Encrypt> 部分 )
:ret... | def decrypt_message(self, timestamp, nonce, msg_signature, encrypt_msg):
"""
解密收到的微信消息
:param timestamp: 请求 URL 中收到的 timestamp
:param nonce: 请求 URL 中收到的 nonce
:param msg_signature: 请求 URL 中收到的 msg_signature
:param encrypt_msg: 收到的加密文本. ( XML 中的 <Encrypt> 部分 )
:ret... | [
"解密收到的微信消息",
":",
"param",
"timestamp",
":",
"请求",
"URL",
"中收到的",
"timestamp",
":",
"param",
"nonce",
":",
"请求",
"URL",
"中收到的",
"nonce",
":",
"param",
"msg_signature",
":",
"请求",
"URL",
"中收到的",
"msg_signature",
":",
"param",
"encrypt_msg",
":",
"收到的加密文本",
... | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/crypto/__init__.py#L109-L121 | [
"def",
"decrypt_message",
"(",
"self",
",",
"timestamp",
",",
"nonce",
",",
"msg_signature",
",",
"encrypt_msg",
")",
":",
"signature",
"=",
"get_signature",
"(",
"self",
".",
"token",
",",
"timestamp",
",",
"nonce",
",",
"encrypt_msg",
")",
"if",
"signature... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | MessageCrypt.encrypt_message | 加密微信回复
:param reply: 加密前的回复
:type reply: WeChatReply 或 XML 文本
:return: 加密后的回复文本 | werobot/crypto/__init__.py | def encrypt_message(self, reply, timestamp=None, nonce=None):
"""
加密微信回复
:param reply: 加密前的回复
:type reply: WeChatReply 或 XML 文本
:return: 加密后的回复文本
"""
if hasattr(reply, "render"):
reply = reply.render()
timestamp = timestamp or to_text(int(time... | def encrypt_message(self, reply, timestamp=None, nonce=None):
"""
加密微信回复
:param reply: 加密前的回复
:type reply: WeChatReply 或 XML 文本
:return: 加密后的回复文本
"""
if hasattr(reply, "render"):
reply = reply.render()
timestamp = timestamp or to_text(int(time... | [
"加密微信回复",
":",
"param",
"reply",
":",
"加密前的回复",
":",
"type",
"reply",
":",
"WeChatReply",
"或",
"XML",
"文本",
":",
"return",
":",
"加密后的回复文本"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/crypto/__init__.py#L123-L144 | [
"def",
"encrypt_message",
"(",
"self",
",",
"reply",
",",
"timestamp",
"=",
"None",
",",
"nonce",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"reply",
",",
"\"render\"",
")",
":",
"reply",
"=",
"reply",
".",
"render",
"(",
")",
"timestamp",
"=",
"ti... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | SaeKVDBStorage.set | 根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象 | werobot/session/saekvstorage.py | def set(self, id, value):
"""
根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象
"""
return self.kv.set(self.key_name(id), value) | def set(self, id, value):
"""
根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象
"""
return self.kv.set(self.key_name(id), value) | [
"根据",
"id",
"写入数据。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/session/saekvstorage.py#L42-L49 | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"value",
")",
":",
"return",
"self",
".",
"kv",
".",
"set",
"(",
"self",
".",
"key_name",
"(",
"id",
")",
",",
"value",
")"
] | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | make_view | 为一个 BaseRoBot 生成 Django view。
:param robot: 一个 BaseRoBot 实例。
:return: 一个标准的 Django view | werobot/contrib/django.py | def make_view(robot):
"""
为一个 BaseRoBot 生成 Django view。
:param robot: 一个 BaseRoBot 实例。
:return: 一个标准的 Django view
"""
@csrf_exempt
def werobot_view(request):
timestamp = request.GET.get("timestamp", "")
nonce = request.GET.get("nonce", "")
signature = request.GET.ge... | def make_view(robot):
"""
为一个 BaseRoBot 生成 Django view。
:param robot: 一个 BaseRoBot 实例。
:return: 一个标准的 Django view
"""
@csrf_exempt
def werobot_view(request):
timestamp = request.GET.get("timestamp", "")
nonce = request.GET.get("nonce", "")
signature = request.GET.ge... | [
"为一个",
"BaseRoBot",
"生成",
"Django",
"view。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/contrib/django.py#L13-L50 | [
"def",
"make_view",
"(",
"robot",
")",
":",
"@",
"csrf_exempt",
"def",
"werobot_view",
"(",
"request",
")",
":",
"timestamp",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"timestamp\"",
",",
"\"\"",
")",
"nonce",
"=",
"request",
".",
"GET",
".",
"get... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | WeixinPayClient.create_js_pay_package | 签名 pay package 需要的参数
详情请参考 支付开发文档
:param package: 需要签名的的参数
:return: 可以使用的packagestr | werobot/pay.py | def create_js_pay_package(self, **package):
"""
签名 pay package 需要的参数
详情请参考 支付开发文档
:param package: 需要签名的的参数
:return: 可以使用的packagestr
"""
assert self.pay_partner_id, "PAY_PARTNER_ID IS EMPTY"
assert self.pay_partner_key, "PAY_PARTNER_KEY IS EMPTY"
... | def create_js_pay_package(self, **package):
"""
签名 pay package 需要的参数
详情请参考 支付开发文档
:param package: 需要签名的的参数
:return: 可以使用的packagestr
"""
assert self.pay_partner_id, "PAY_PARTNER_ID IS EMPTY"
assert self.pay_partner_key, "PAY_PARTNER_KEY IS EMPTY"
... | [
"签名",
"pay",
"package",
"需要的参数",
"详情请参考",
"支付开发文档"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/pay.py#L27-L58 | [
"def",
"create_js_pay_package",
"(",
"self",
",",
"*",
"*",
"package",
")",
":",
"assert",
"self",
".",
"pay_partner_id",
",",
"\"PAY_PARTNER_ID IS EMPTY\"",
"assert",
"self",
".",
"pay_partner_key",
",",
"\"PAY_PARTNER_KEY IS EMPTY\"",
"package",
".",
"update",
"("... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | WeixinPayClient.create_js_pay_params | 签名 js 需要的参数
详情请参考 支付开发文档
::
wxclient.create_js_pay_params(
body=标题, out_trade_no=本地订单号, total_fee=价格单位分,
notify_url=通知url,
spbill_create_ip=建议为支付人ip,
)
:param package: 需要签名的的参数
:return: 支付需要的对象 | werobot/pay.py | def create_js_pay_params(self, **package):
"""
签名 js 需要的参数
详情请参考 支付开发文档
::
wxclient.create_js_pay_params(
body=标题, out_trade_no=本地订单号, total_fee=价格单位分,
notify_url=通知url,
spbill_create_ip=建议为支付人ip,
)
:param... | def create_js_pay_params(self, **package):
"""
签名 js 需要的参数
详情请参考 支付开发文档
::
wxclient.create_js_pay_params(
body=标题, out_trade_no=本地订单号, total_fee=价格单位分,
notify_url=通知url,
spbill_create_ip=建议为支付人ip,
)
:param... | [
"签名",
"js",
"需要的参数",
"详情请参考",
"支付开发文档"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/pay.py#L60-L86 | [
"def",
"create_js_pay_params",
"(",
"self",
",",
"*",
"*",
"package",
")",
":",
"pay_param",
",",
"sign",
",",
"sign_type",
"=",
"self",
".",
"_pay_sign_dict",
"(",
"package",
"=",
"self",
".",
"create_js_pay_package",
"(",
"*",
"*",
"package",
")",
")",
... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | WeixinPayClient.create_js_edit_address_param | alpha
暂时不建议使用
这个接口使用起来十分不友好
而且会引起巨大的误解
url 需要带上 code 和 state (url?code=xxx&state=1)
code 和state 是 oauth 时候回来的
token 要传用户的 token
这尼玛 你能相信这些支付接口都是腾讯出的? | werobot/pay.py | def create_js_edit_address_param(self, accesstoken, **params):
"""
alpha
暂时不建议使用
这个接口使用起来十分不友好
而且会引起巨大的误解
url 需要带上 code 和 state (url?code=xxx&state=1)
code 和state 是 oauth 时候回来的
token 要传用户的 token
这尼玛 你能相信这些支付接口都是腾讯出的?
"""
params.u... | def create_js_edit_address_param(self, accesstoken, **params):
"""
alpha
暂时不建议使用
这个接口使用起来十分不友好
而且会引起巨大的误解
url 需要带上 code 和 state (url?code=xxx&state=1)
code 和state 是 oauth 时候回来的
token 要传用户的 token
这尼玛 你能相信这些支付接口都是腾讯出的?
"""
params.u... | [
"alpha",
"暂时不建议使用",
"这个接口使用起来十分不友好",
"而且会引起巨大的误解"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/pay.py#L88-L123 | [
"def",
"create_js_edit_address_param",
"(",
"self",
",",
"accesstoken",
",",
"*",
"*",
"params",
")",
":",
"params",
".",
"update",
"(",
"{",
"'appId'",
":",
"self",
".",
"appid",
",",
"'nonceStr'",
":",
"generate_token",
"(",
"8",
")",
",",
"'timeStamp'",... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | WeixinPayClient.create_native_pay_url | 创建 native pay url
详情请参考 支付开发文档
:param productid: 本地商品ID
:return: 返回URL | werobot/pay.py | def create_native_pay_url(self, productid):
"""
创建 native pay url
详情请参考 支付开发文档
:param productid: 本地商品ID
:return: 返回URL
"""
params, sign, = self._pay_sign_dict(productid=productid)
params['sign'] = sign
return NATIVE_BASE_URL + urlencode(params) | def create_native_pay_url(self, productid):
"""
创建 native pay url
详情请参考 支付开发文档
:param productid: 本地商品ID
:return: 返回URL
"""
params, sign, = self._pay_sign_dict(productid=productid)
params['sign'] = sign
return NATIVE_BASE_URL + urlencode(params) | [
"创建",
"native",
"pay",
"url",
"详情请参考",
"支付开发文档"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/pay.py#L125-L138 | [
"def",
"create_native_pay_url",
"(",
"self",
",",
"productid",
")",
":",
"params",
",",
"sign",
",",
"=",
"self",
".",
"_pay_sign_dict",
"(",
"productid",
"=",
"productid",
")",
"params",
"[",
"'sign'",
"]",
"=",
"sign",
"return",
"NATIVE_BASE_URL",
"+",
"... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | WeixinPayClient.pay_deliver_notify | 通知 腾讯发货
一般形式 ::
wxclient.pay_delivernotify(
openid=openid,
transid=transaction_id,
out_trade_no=本地订单号,
deliver_timestamp=int(time.time()),
deliver_status="1",
deliver_msg="ok"
)
:par... | werobot/pay.py | def pay_deliver_notify(self, **deliver_info):
"""
通知 腾讯发货
一般形式 ::
wxclient.pay_delivernotify(
openid=openid,
transid=transaction_id,
out_trade_no=本地订单号,
deliver_timestamp=int(time.time()),
deliver_status... | def pay_deliver_notify(self, **deliver_info):
"""
通知 腾讯发货
一般形式 ::
wxclient.pay_delivernotify(
openid=openid,
transid=transaction_id,
out_trade_no=本地订单号,
deliver_timestamp=int(time.time()),
deliver_status... | [
"通知",
"腾讯发货"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/pay.py#L140-L166 | [
"def",
"pay_deliver_notify",
"(",
"self",
",",
"*",
"*",
"deliver_info",
")",
":",
"params",
",",
"sign",
",",
"_",
"=",
"self",
".",
"_pay_sign_dict",
"(",
"add_noncestr",
"=",
"False",
",",
"add_timestamp",
"=",
"False",
",",
"*",
"*",
"deliver_info",
... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | WeixinPayClient.pay_order_query | 查询订单状态
一般用于无法确定 订单状态时候补偿
:param out_trade_no: 本地订单号
:return: 订单信息dict | werobot/pay.py | def pay_order_query(self, out_trade_no):
"""
查询订单状态
一般用于无法确定 订单状态时候补偿
:param out_trade_no: 本地订单号
:return: 订单信息dict
"""
package = {
'partner': self.pay_partner_id,
'out_trade_no': out_trade_no,
}
_package = package.items()... | def pay_order_query(self, out_trade_no):
"""
查询订单状态
一般用于无法确定 订单状态时候补偿
:param out_trade_no: 本地订单号
:return: 订单信息dict
"""
package = {
'partner': self.pay_partner_id,
'out_trade_no': out_trade_no,
}
_package = package.items()... | [
"查询订单状态",
"一般用于无法确定",
"订单状态时候补偿"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/pay.py#L168-L204 | [
"def",
"pay_order_query",
"(",
"self",
",",
"out_trade_no",
")",
":",
"package",
"=",
"{",
"'partner'",
":",
"self",
".",
"pay_partner_id",
",",
"'out_trade_no'",
":",
"out_trade_no",
",",
"}",
"_package",
"=",
"package",
".",
"items",
"(",
")",
"_package",
... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | byte2int | Get the ASCII int value of a character in a string.
:param s: a string
:param index: the position of desired character
:return: ASCII int value | werobot/utils.py | def byte2int(s, index=0):
"""Get the ASCII int value of a character in a string.
:param s: a string
:param index: the position of desired character
:return: ASCII int value
"""
if six.PY2:
return ord(s[index])
return s[index] | def byte2int(s, index=0):
"""Get the ASCII int value of a character in a string.
:param s: a string
:param index: the position of desired character
:return: ASCII int value
"""
if six.PY2:
return ord(s[index])
return s[index] | [
"Get",
"the",
"ASCII",
"int",
"value",
"of",
"a",
"character",
"in",
"a",
"string",
"."
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/utils.py#L76-L86 | [
"def",
"byte2int",
"(",
"s",
",",
"index",
"=",
"0",
")",
":",
"if",
"six",
".",
"PY2",
":",
"return",
"ord",
"(",
"s",
"[",
"index",
"]",
")",
"return",
"s",
"[",
"index",
"]"
] | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | pay_sign_dict | 支付参数签名 | werobot/utils.py | def pay_sign_dict(
appid,
pay_sign_key,
add_noncestr=True,
add_timestamp=True,
add_appid=True,
**kwargs
):
"""
支付参数签名
"""
assert pay_sign_key, "PAY SIGN KEY IS EMPTY"
if add_appid:
kwargs.update({'appid': appid})
if add_noncestr:
kwargs.update({'noncestr... | def pay_sign_dict(
appid,
pay_sign_key,
add_noncestr=True,
add_timestamp=True,
add_appid=True,
**kwargs
):
"""
支付参数签名
"""
assert pay_sign_key, "PAY SIGN KEY IS EMPTY"
if add_appid:
kwargs.update({'appid': appid})
if add_noncestr:
kwargs.update({'noncestr... | [
"支付参数签名"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/utils.py#L107-L142 | [
"def",
"pay_sign_dict",
"(",
"appid",
",",
"pay_sign_key",
",",
"add_noncestr",
"=",
"True",
",",
"add_timestamp",
"=",
"True",
",",
"add_appid",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"pay_sign_key",
",",
"\"PAY SIGN KEY IS EMPTY\"",
"if",
... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | BaseRoBot.key_click | 为自定义菜单 ``(click)`` 事件添加 handler 的简便方法。
**@key_click('KEYNAME')** 用来为特定 key 的点击事件添加 handler 方法。 | werobot/robot.py | def key_click(self, key):
"""
为自定义菜单 ``(click)`` 事件添加 handler 的简便方法。
**@key_click('KEYNAME')** 用来为特定 key 的点击事件添加 handler 方法。
"""
def wraps(f):
argc = len(signature(f).parameters.keys())
@self.click
def onclick(message, session=None):
... | def key_click(self, key):
"""
为自定义菜单 ``(click)`` 事件添加 handler 的简便方法。
**@key_click('KEYNAME')** 用来为特定 key 的点击事件添加 handler 方法。
"""
def wraps(f):
argc = len(signature(f).parameters.keys())
@self.click
def onclick(message, session=None):
... | [
"为自定义菜单",
"(",
"click",
")",
"事件添加",
"handler",
"的简便方法。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L467-L484 | [
"def",
"key_click",
"(",
"self",
",",
"key",
")",
":",
"def",
"wraps",
"(",
"f",
")",
":",
"argc",
"=",
"len",
"(",
"signature",
"(",
"f",
")",
".",
"parameters",
".",
"keys",
"(",
")",
")",
"@",
"self",
".",
"click",
"def",
"onclick",
"(",
"me... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | BaseRoBot.filter | 为文本 ``(text)`` 消息添加 handler 的简便方法。
使用 ``@filter("xxx")``, ``@filter(re.compile("xxx"))``
或 ``@filter("xxx", "xxx2")`` 的形式为特定内容添加 handler。 | werobot/robot.py | def filter(self, *args):
"""
为文本 ``(text)`` 消息添加 handler 的简便方法。
使用 ``@filter("xxx")``, ``@filter(re.compile("xxx"))``
或 ``@filter("xxx", "xxx2")`` 的形式为特定内容添加 handler。
"""
def wraps(f):
self.add_filter(func=f, rules=list(args))
return f
r... | def filter(self, *args):
"""
为文本 ``(text)`` 消息添加 handler 的简便方法。
使用 ``@filter("xxx")``, ``@filter(re.compile("xxx"))``
或 ``@filter("xxx", "xxx2")`` 的形式为特定内容添加 handler。
"""
def wraps(f):
self.add_filter(func=f, rules=list(args))
return f
r... | [
"为文本",
"(",
"text",
")",
"消息添加",
"handler",
"的简便方法。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L486-L498 | [
"def",
"filter",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"wraps",
"(",
"f",
")",
":",
"self",
".",
"add_filter",
"(",
"func",
"=",
"f",
",",
"rules",
"=",
"list",
"(",
"args",
")",
")",
"return",
"f",
"return",
"wraps"
] | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | BaseRoBot.add_handler | 为 BaseRoBot 实例添加一个 handler。
:param func: 要作为 handler 的方法。
:param type: handler 的种类。
:return: None | werobot/robot.py | def add_handler(self, func, type='all'):
"""
为 BaseRoBot 实例添加一个 handler。
:param func: 要作为 handler 的方法。
:param type: handler 的种类。
:return: None
"""
if not callable(func):
raise ValueError("{} is not callable".format(func))
self._handlers[type]... | def add_handler(self, func, type='all'):
"""
为 BaseRoBot 实例添加一个 handler。
:param func: 要作为 handler 的方法。
:param type: handler 的种类。
:return: None
"""
if not callable(func):
raise ValueError("{} is not callable".format(func))
self._handlers[type]... | [
"为",
"BaseRoBot",
"实例添加一个",
"handler。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L500-L513 | [
"def",
"add_handler",
"(",
"self",
",",
"func",
",",
"type",
"=",
"'all'",
")",
":",
"if",
"not",
"callable",
"(",
"func",
")",
":",
"raise",
"ValueError",
"(",
"\"{} is not callable\"",
".",
"format",
"(",
"func",
")",
")",
"self",
".",
"_handlers",
"... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | BaseRoBot.add_filter | 为 BaseRoBot 添加一个 ``filter handler``。
:param func: 如果 rules 通过,则处理该消息的 handler。
:param rules: 一个 list,包含要匹配的字符串或者正则表达式。
:return: None | werobot/robot.py | def add_filter(self, func, rules):
"""
为 BaseRoBot 添加一个 ``filter handler``。
:param func: 如果 rules 通过,则处理该消息的 handler。
:param rules: 一个 list,包含要匹配的字符串或者正则表达式。
:return: None
"""
if not callable(func):
raise ValueError("{} is not callable".format(func))
... | def add_filter(self, func, rules):
"""
为 BaseRoBot 添加一个 ``filter handler``。
:param func: 如果 rules 通过,则处理该消息的 handler。
:param rules: 一个 list,包含要匹配的字符串或者正则表达式。
:return: None
"""
if not callable(func):
raise ValueError("{} is not callable".format(func))
... | [
"为",
"BaseRoBot",
"添加一个",
"filter",
"handler",
"。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L518-L554 | [
"def",
"add_filter",
"(",
"self",
",",
"func",
",",
"rules",
")",
":",
"if",
"not",
"callable",
"(",
"func",
")",
":",
"raise",
"ValueError",
"(",
"\"{} is not callable\"",
".",
"format",
"(",
"func",
")",
")",
"if",
"not",
"isinstance",
"(",
"rules",
... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | BaseRoBot.parse_message | 解析获取到的 Raw XML ,如果需要的话进行解密,返回 WeRoBot Message。
:param body: 微信服务器发来的请求中的 Body。
:return: WeRoBot Message | werobot/robot.py | def parse_message(
self, body, timestamp=None, nonce=None, msg_signature=None
):
"""
解析获取到的 Raw XML ,如果需要的话进行解密,返回 WeRoBot Message。
:param body: 微信服务器发来的请求中的 Body。
:return: WeRoBot Message
"""
message_dict = parse_xml(body)
if "Encrypt" in message_dict... | def parse_message(
self, body, timestamp=None, nonce=None, msg_signature=None
):
"""
解析获取到的 Raw XML ,如果需要的话进行解密,返回 WeRoBot Message。
:param body: 微信服务器发来的请求中的 Body。
:return: WeRoBot Message
"""
message_dict = parse_xml(body)
if "Encrypt" in message_dict... | [
"解析获取到的",
"Raw",
"XML",
",如果需要的话进行解密,返回",
"WeRoBot",
"Message。",
":",
"param",
"body",
":",
"微信服务器发来的请求中的",
"Body。",
":",
"return",
":",
"WeRoBot",
"Message"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L556-L573 | [
"def",
"parse_message",
"(",
"self",
",",
"body",
",",
"timestamp",
"=",
"None",
",",
"nonce",
"=",
"None",
",",
"msg_signature",
"=",
"None",
")",
":",
"message_dict",
"=",
"parse_xml",
"(",
"body",
")",
"if",
"\"Encrypt\"",
"in",
"message_dict",
":",
"... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | BaseRoBot.get_reply | 根据 message 的内容获取 Reply 对象。
:param message: 要处理的 message
:return: 获取的 Reply 对象 | werobot/robot.py | def get_reply(self, message):
"""
根据 message 的内容获取 Reply 对象。
:param message: 要处理的 message
:return: 获取的 Reply 对象
"""
session_storage = self.session_storage
id = None
session = None
if session_storage and hasattr(message, "source"):
id ... | def get_reply(self, message):
"""
根据 message 的内容获取 Reply 对象。
:param message: 要处理的 message
:return: 获取的 Reply 对象
"""
session_storage = self.session_storage
id = None
session = None
if session_storage and hasattr(message, "source"):
id ... | [
"根据",
"message",
"的内容获取",
"Reply",
"对象。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L575-L600 | [
"def",
"get_reply",
"(",
"self",
",",
"message",
")",
":",
"session_storage",
"=",
"self",
".",
"session_storage",
"id",
"=",
"None",
"session",
"=",
"None",
"if",
"session_storage",
"and",
"hasattr",
"(",
"message",
",",
"\"source\"",
")",
":",
"id",
"=",... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | BaseRoBot.get_encrypted_reply | 对一个指定的 WeRoBot Message ,获取 handlers 处理后得到的 Reply。
如果可能,对该 Reply 进行加密。
返回 Reply Render 后的文本。
:param message: 一个 WeRoBot Message 实例。
:return: reply (纯文本) | werobot/robot.py | def get_encrypted_reply(self, message):
"""
对一个指定的 WeRoBot Message ,获取 handlers 处理后得到的 Reply。
如果可能,对该 Reply 进行加密。
返回 Reply Render 后的文本。
:param message: 一个 WeRoBot Message 实例。
:return: reply (纯文本)
"""
reply = self.get_reply(message)
if not reply:
... | def get_encrypted_reply(self, message):
"""
对一个指定的 WeRoBot Message ,获取 handlers 处理后得到的 Reply。
如果可能,对该 Reply 进行加密。
返回 Reply Render 后的文本。
:param message: 一个 WeRoBot Message 实例。
:return: reply (纯文本)
"""
reply = self.get_reply(message)
if not reply:
... | [
"对一个指定的",
"WeRoBot",
"Message",
",获取",
"handlers",
"处理后得到的",
"Reply。",
"如果可能,对该",
"Reply",
"进行加密。",
"返回",
"Reply",
"Render",
"后的文本。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L602-L618 | [
"def",
"get_encrypted_reply",
"(",
"self",
",",
"message",
")",
":",
"reply",
"=",
"self",
".",
"get_reply",
"(",
"message",
")",
"if",
"not",
"reply",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"No handler responded message %s\"",
"%",
"message",
")... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | BaseRoBot.check_signature | 根据时间戳和生成签名的字符串 (nonce) 检查签名。
:param timestamp: 时间戳
:param nonce: 生成签名的随机字符串
:param signature: 要检查的签名
:return: 如果签名合法将返回 ``True``,不合法将返回 ``False`` | werobot/robot.py | def check_signature(self, timestamp, nonce, signature):
"""
根据时间戳和生成签名的字符串 (nonce) 检查签名。
:param timestamp: 时间戳
:param nonce: 生成签名的随机字符串
:param signature: 要检查的签名
:return: 如果签名合法将返回 ``True``,不合法将返回 ``False``
"""
return check_signature(
self.conf... | def check_signature(self, timestamp, nonce, signature):
"""
根据时间戳和生成签名的字符串 (nonce) 检查签名。
:param timestamp: 时间戳
:param nonce: 生成签名的随机字符串
:param signature: 要检查的签名
:return: 如果签名合法将返回 ``True``,不合法将返回 ``False``
"""
return check_signature(
self.conf... | [
"根据时间戳和生成签名的字符串",
"(",
"nonce",
")",
"检查签名。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L620-L631 | [
"def",
"check_signature",
"(",
"self",
",",
"timestamp",
",",
"nonce",
",",
"signature",
")",
":",
"return",
"check_signature",
"(",
"self",
".",
"config",
"[",
"\"TOKEN\"",
"]",
",",
"timestamp",
",",
"nonce",
",",
"signature",
")"
] | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | WeRoBot.run | 运行 WeRoBot。
:param server: 传递给 Bottle 框架 run 方法的参数,详情见\
`bottle 文档 <https://bottlepy.org/docs/dev/deployment.html#switching-the-server-backend>`_
:param host: 运行时绑定的主机地址
:param port: 运行时绑定的主机端口
:param enable_pretty_logging: 是否开启 log 的输出格式优化 | werobot/robot.py | def run(
self, server=None, host=None, port=None, enable_pretty_logging=True
):
"""
运行 WeRoBot。
:param server: 传递给 Bottle 框架 run 方法的参数,详情见\
`bottle 文档 <https://bottlepy.org/docs/dev/deployment.html#switching-the-server-backend>`_
:param host: 运行时绑定的主机地址
:para... | def run(
self, server=None, host=None, port=None, enable_pretty_logging=True
):
"""
运行 WeRoBot。
:param server: 传递给 Bottle 框架 run 方法的参数,详情见\
`bottle 文档 <https://bottlepy.org/docs/dev/deployment.html#switching-the-server-backend>`_
:param host: 运行时绑定的主机地址
:para... | [
"运行",
"WeRoBot。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L665-L689 | [
"def",
"run",
"(",
"self",
",",
"server",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"enable_pretty_logging",
"=",
"True",
")",
":",
"if",
"enable_pretty_logging",
":",
"from",
"werobot",
".",
"logger",
"import",
"enable_pretty_l... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | PostgreSQLStorage.get | 根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 | werobot/session/postgresqlstorage.py | def get(self, id):
"""
根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
"""
cur = self.conn.cursor()
cur.execute("SELECT value FROM WeRoBot WHERE id=%s LIMIT 1;", (id, ))
session_json = cur.fetchone()
if session_json is N... | def get(self, id):
"""
根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
"""
cur = self.conn.cursor()
cur.execute("SELECT value FROM WeRoBot WHERE id=%s LIMIT 1;", (id, ))
session_json = cur.fetchone()
if session_json is N... | [
"根据",
"id",
"获取数据。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/session/postgresqlstorage.py#L41-L53 | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"cur",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"\"SELECT value FROM WeRoBot WHERE id=%s LIMIT 1;\"",
",",
"(",
"id",
",",
")",
")",
"session_json",
"=",
"cur",
".",
... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | PostgreSQLStorage.delete | 根据 id 删除数据。
:param id: 要删除的数据的 id | werobot/session/postgresqlstorage.py | def delete(self, id):
"""
根据 id 删除数据。
:param id: 要删除的数据的 id
"""
self.conn.cursor().execute("DELETE FROM WeRoBot WHERE id=%s", (id, ))
self.conn.commit() | def delete(self, id):
"""
根据 id 删除数据。
:param id: 要删除的数据的 id
"""
self.conn.cursor().execute("DELETE FROM WeRoBot WHERE id=%s", (id, ))
self.conn.commit() | [
"根据",
"id",
"删除数据。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/session/postgresqlstorage.py#L73-L80 | [
"def",
"delete",
"(",
"self",
",",
"id",
")",
":",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"\"DELETE FROM WeRoBot WHERE id=%s\"",
",",
"(",
"id",
",",
")",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")"
] | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | make_view | 为一个 BaseRoBot 生成 Bottle view。
Usage ::
from werobot import WeRoBot
robot = WeRoBot(token='token')
@robot.handler
def hello(message):
return 'Hello World!'
from bottle import Bottle
from werobot.contrib.bottle import make_view
app = Bottle()
... | werobot/contrib/bottle.py | def make_view(robot):
"""
为一个 BaseRoBot 生成 Bottle view。
Usage ::
from werobot import WeRoBot
robot = WeRoBot(token='token')
@robot.handler
def hello(message):
return 'Hello World!'
from bottle import Bottle
from werobot.contrib.bottle import ... | def make_view(robot):
"""
为一个 BaseRoBot 生成 Bottle view。
Usage ::
from werobot import WeRoBot
robot = WeRoBot(token='token')
@robot.handler
def hello(message):
return 'Hello World!'
from bottle import Bottle
from werobot.contrib.bottle import ... | [
"为一个",
"BaseRoBot",
"生成",
"Bottle",
"view。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/contrib/bottle.py#L12-L63 | [
"def",
"make_view",
"(",
"robot",
")",
":",
"def",
"werobot_view",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"robot",
".",
"check_signature",
"(",
"request",
".",
"query",
".",
"timestamp",
",",
"request",
".",
"query",
".",
"... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | process_message | Process a message dict and return a Message Object
:param message: Message dict returned by `parse_xml` function
:return: Message Object | werobot/parser.py | def process_message(message):
"""
Process a message dict and return a Message Object
:param message: Message dict returned by `parse_xml` function
:return: Message Object
"""
message["type"] = message.pop("MsgType").lower()
if message["type"] == 'event':
message["type"] = str(message... | def process_message(message):
"""
Process a message dict and return a Message Object
:param message: Message dict returned by `parse_xml` function
:return: Message Object
"""
message["type"] = message.pop("MsgType").lower()
if message["type"] == 'event':
message["type"] = str(message... | [
"Process",
"a",
"message",
"dict",
"and",
"return",
"a",
"Message",
"Object",
":",
"param",
"message",
":",
"Message",
"dict",
"returned",
"by",
"parse_xml",
"function",
":",
"return",
":",
"Message",
"Object"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/parser.py#L20-L34 | [
"def",
"process_message",
"(",
"message",
")",
":",
"message",
"[",
"\"type\"",
"]",
"=",
"message",
".",
"pop",
"(",
"\"MsgType\"",
")",
".",
"lower",
"(",
")",
"if",
"message",
"[",
"\"type\"",
"]",
"==",
"'event'",
":",
"message",
"[",
"\"type\"",
"... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | MySQLStorage.set | 根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象 | werobot/session/mysqlstorage.py | def set(self, id, value):
"""
根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象
"""
value = json_dumps(value)
self.conn.cursor().execute(
"INSERT INTO WeRoBot (id, value) VALUES (%s,%s) \
ON DUPLICATE KEY UPDATE val... | def set(self, id, value):
"""
根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象
"""
value = json_dumps(value)
self.conn.cursor().execute(
"INSERT INTO WeRoBot (id, value) VALUES (%s,%s) \
ON DUPLICATE KEY UPDATE val... | [
"根据",
"id",
"写入数据。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/session/mysqlstorage.py#L72-L88 | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"value",
")",
":",
"value",
"=",
"json_dumps",
"(",
"value",
")",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"\"INSERT INTO WeRoBot (id, value) VALUES (%s,%s) \\\n ON DUPLICATE KEY U... | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | RedisStorage.get | 根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 | werobot/session/redisstorage.py | def get(self, id):
"""
根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
"""
id = self.key_name(id)
session_json = self.redis.get(id) or '{}'
return json_loads(session_json) | def get(self, id):
"""
根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
"""
id = self.key_name(id)
session_json = self.redis.get(id) or '{}'
return json_loads(session_json) | [
"根据",
"id",
"获取数据。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/session/redisstorage.py#L36-L45 | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"key_name",
"(",
"id",
")",
"session_json",
"=",
"self",
".",
"redis",
".",
"get",
"(",
"id",
")",
"or",
"'{}'",
"return",
"json_loads",
"(",
"session_json",
")"
] | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | RedisStorage.set | 根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象 | werobot/session/redisstorage.py | def set(self, id, value):
"""
根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象
"""
id = self.key_name(id)
self.redis.set(id, json_dumps(value)) | def set(self, id, value):
"""
根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象
"""
id = self.key_name(id)
self.redis.set(id, json_dumps(value)) | [
"根据",
"id",
"写入数据。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/session/redisstorage.py#L47-L55 | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"value",
")",
":",
"id",
"=",
"self",
".",
"key_name",
"(",
"id",
")",
"self",
".",
"redis",
".",
"set",
"(",
"id",
",",
"json_dumps",
"(",
"value",
")",
")"
] | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | RedisStorage.delete | 根据 id 删除数据。
:param id: 要删除的数据的 id | werobot/session/redisstorage.py | def delete(self, id):
"""
根据 id 删除数据。
:param id: 要删除的数据的 id
"""
id = self.key_name(id)
self.redis.delete(id) | def delete(self, id):
"""
根据 id 删除数据。
:param id: 要删除的数据的 id
"""
id = self.key_name(id)
self.redis.delete(id) | [
"根据",
"id",
"删除数据。"
] | offu/WeRoBot | python | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/session/redisstorage.py#L57-L64 | [
"def",
"delete",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"key_name",
"(",
"id",
")",
"self",
".",
"redis",
".",
"delete",
"(",
"id",
")"
] | fd42109105b03f9acf45ebd9dcabb9d5cff98f3c |
train | Vocab.load_vectors | Arguments:
vectors: one of or a list containing instantiations of the
GloVe, CharNGram, or Vectors classes. Alternatively, one
of or a list of available pretrained vectors:
charngram.100d
fasttext.en.300d
fasttext.simple.300d
... | torchtext/vocab.py | def load_vectors(self, vectors, **kwargs):
"""
Arguments:
vectors: one of or a list containing instantiations of the
GloVe, CharNGram, or Vectors classes. Alternatively, one
of or a list of available pretrained vectors:
charngram.100d
... | def load_vectors(self, vectors, **kwargs):
"""
Arguments:
vectors: one of or a list containing instantiations of the
GloVe, CharNGram, or Vectors classes. Alternatively, one
of or a list of available pretrained vectors:
charngram.100d
... | [
"Arguments",
":",
"vectors",
":",
"one",
"of",
"or",
"a",
"list",
"containing",
"instantiations",
"of",
"the",
"GloVe",
"CharNGram",
"or",
"Vectors",
"classes",
".",
"Alternatively",
"one",
"of",
"or",
"a",
"list",
"of",
"available",
"pretrained",
"vectors",
... | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/vocab.py#L117-L165 | [
"def",
"load_vectors",
"(",
"self",
",",
"vectors",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"vectors",
",",
"list",
")",
":",
"vectors",
"=",
"[",
"vectors",
"]",
"for",
"idx",
",",
"vector",
"in",
"enumerate",
"(",
"vector... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Vocab.set_vectors | Set the vectors for the Vocab instance from a collection of Tensors.
Arguments:
stoi: A dictionary of string to the index of the associated vector
in the `vectors` input argument.
vectors: An indexed iterable (or other structure supporting __getitem__) that
... | torchtext/vocab.py | def set_vectors(self, stoi, vectors, dim, unk_init=torch.Tensor.zero_):
"""
Set the vectors for the Vocab instance from a collection of Tensors.
Arguments:
stoi: A dictionary of string to the index of the associated vector
in the `vectors` input argument.
... | def set_vectors(self, stoi, vectors, dim, unk_init=torch.Tensor.zero_):
"""
Set the vectors for the Vocab instance from a collection of Tensors.
Arguments:
stoi: A dictionary of string to the index of the associated vector
in the `vectors` input argument.
... | [
"Set",
"the",
"vectors",
"for",
"the",
"Vocab",
"instance",
"from",
"a",
"collection",
"of",
"Tensors",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/vocab.py#L167-L189 | [
"def",
"set_vectors",
"(",
"self",
",",
"stoi",
",",
"vectors",
",",
"dim",
",",
"unk_init",
"=",
"torch",
".",
"Tensor",
".",
"zero_",
")",
":",
"self",
".",
"vectors",
"=",
"torch",
".",
"Tensor",
"(",
"len",
"(",
"self",
")",
",",
"dim",
")",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | SST.splits | Create dataset objects for splits of the SST dataset.
Arguments:
text_field: The field that will be used for the sentence.
label_field: The field that will be used for label data.
root: The root directory that the dataset's zip archive will be
expanded into; ... | torchtext/datasets/sst.py | def splits(cls, text_field, label_field, root='.data',
train='train.txt', validation='dev.txt', test='test.txt',
train_subtrees=False, **kwargs):
"""Create dataset objects for splits of the SST dataset.
Arguments:
text_field: The field that will be used for the... | def splits(cls, text_field, label_field, root='.data',
train='train.txt', validation='dev.txt', test='test.txt',
train_subtrees=False, **kwargs):
"""Create dataset objects for splits of the SST dataset.
Arguments:
text_field: The field that will be used for the... | [
"Create",
"dataset",
"objects",
"for",
"splits",
"of",
"the",
"SST",
"dataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/sst.py#L47-L78 | [
"def",
"splits",
"(",
"cls",
",",
"text_field",
",",
"label_field",
",",
"root",
"=",
"'.data'",
",",
"train",
"=",
"'train.txt'",
",",
"validation",
"=",
"'dev.txt'",
",",
"test",
"=",
"'test.txt'",
",",
"train_subtrees",
"=",
"False",
",",
"*",
"*",
"k... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | SST.iters | Create iterator objects for splits of the SST dataset.
Arguments:
batch_size: Batch_size
device: Device to create batches on. Use - 1 for CPU and None for
the currently active GPU device.
root: The root directory that the dataset's zip archive will be
... | torchtext/datasets/sst.py | def iters(cls, batch_size=32, device=0, root='.data', vectors=None, **kwargs):
"""Create iterator objects for splits of the SST dataset.
Arguments:
batch_size: Batch_size
device: Device to create batches on. Use - 1 for CPU and None for
the currently active GPU d... | def iters(cls, batch_size=32, device=0, root='.data', vectors=None, **kwargs):
"""Create iterator objects for splits of the SST dataset.
Arguments:
batch_size: Batch_size
device: Device to create batches on. Use - 1 for CPU and None for
the currently active GPU d... | [
"Create",
"iterator",
"objects",
"for",
"splits",
"of",
"the",
"SST",
"dataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/sst.py#L81-L104 | [
"def",
"iters",
"(",
"cls",
",",
"batch_size",
"=",
"32",
",",
"device",
"=",
"0",
",",
"root",
"=",
"'.data'",
",",
"vectors",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"TEXT",
"=",
"data",
".",
"Field",
"(",
")",
"LABEL",
"=",
"data",
"... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | interleave_keys | Interleave bits from two sort keys to form a joint sort key.
Examples that are similar in both of the provided keys will have similar
values for the key defined by this function. Useful for tasks with two
text fields like machine translation or natural language inference. | torchtext/data/utils.py | def interleave_keys(a, b):
"""Interleave bits from two sort keys to form a joint sort key.
Examples that are similar in both of the provided keys will have similar
values for the key defined by this function. Useful for tasks with two
text fields like machine translation or natural language inference.
... | def interleave_keys(a, b):
"""Interleave bits from two sort keys to form a joint sort key.
Examples that are similar in both of the provided keys will have similar
values for the key defined by this function. Useful for tasks with two
text fields like machine translation or natural language inference.
... | [
"Interleave",
"bits",
"from",
"two",
"sort",
"keys",
"to",
"form",
"a",
"joint",
"sort",
"key",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/utils.py#L89-L98 | [
"def",
"interleave_keys",
"(",
"a",
",",
"b",
")",
":",
"def",
"interleave",
"(",
"args",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"x",
"for",
"t",
"in",
"zip",
"(",
"*",
"args",
")",
"for",
"x",
"in",
"t",
"]",
")",
"return",
"int",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | RandomShuffler.use_internal_state | Use a specific RNG state. | torchtext/data/utils.py | def use_internal_state(self):
"""Use a specific RNG state."""
old_state = random.getstate()
random.setstate(self._random_state)
yield
self._random_state = random.getstate()
random.setstate(old_state) | def use_internal_state(self):
"""Use a specific RNG state."""
old_state = random.getstate()
random.setstate(self._random_state)
yield
self._random_state = random.getstate()
random.setstate(old_state) | [
"Use",
"a",
"specific",
"RNG",
"state",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/utils.py#L127-L133 | [
"def",
"use_internal_state",
"(",
"self",
")",
":",
"old_state",
"=",
"random",
".",
"getstate",
"(",
")",
"random",
".",
"setstate",
"(",
"self",
".",
"_random_state",
")",
"yield",
"self",
".",
"_random_state",
"=",
"random",
".",
"getstate",
"(",
")",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | download_from_url | Download file, with logic (from tensor2tensor) for Google Drive | torchtext/utils.py | def download_from_url(url, path):
"""Download file, with logic (from tensor2tensor) for Google Drive"""
def process_response(r):
chunk_size = 16 * 1024
total_size = int(r.headers.get('Content-length', 0))
with open(path, "wb") as file:
with tqdm(total=total_size, unit='B',
... | def download_from_url(url, path):
"""Download file, with logic (from tensor2tensor) for Google Drive"""
def process_response(r):
chunk_size = 16 * 1024
total_size = int(r.headers.get('Content-length', 0))
with open(path, "wb") as file:
with tqdm(total=total_size, unit='B',
... | [
"Download",
"file",
"with",
"logic",
"(",
"from",
"tensor2tensor",
")",
"for",
"Google",
"Drive"
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/utils.py#L27-L57 | [
"def",
"download_from_url",
"(",
"url",
",",
"path",
")",
":",
"def",
"process_response",
"(",
"r",
")",
":",
"chunk_size",
"=",
"16",
"*",
"1024",
"total_size",
"=",
"int",
"(",
"r",
".",
"headers",
".",
"get",
"(",
"'Content-length'",
",",
"0",
")",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | unicode_csv_reader | Since the standard csv library does not handle unicode in Python 2, we need a wrapper.
Borrowed and slightly modified from the Python docs:
https://docs.python.org/2/library/csv.html#csv-examples | torchtext/utils.py | def unicode_csv_reader(unicode_csv_data, **kwargs):
"""Since the standard csv library does not handle unicode in Python 2, we need a wrapper.
Borrowed and slightly modified from the Python docs:
https://docs.python.org/2/library/csv.html#csv-examples"""
if six.PY2:
# csv.py doesn't do Unicode; e... | def unicode_csv_reader(unicode_csv_data, **kwargs):
"""Since the standard csv library does not handle unicode in Python 2, we need a wrapper.
Borrowed and slightly modified from the Python docs:
https://docs.python.org/2/library/csv.html#csv-examples"""
if six.PY2:
# csv.py doesn't do Unicode; e... | [
"Since",
"the",
"standard",
"csv",
"library",
"does",
"not",
"handle",
"unicode",
"in",
"Python",
"2",
"we",
"need",
"a",
"wrapper",
".",
"Borrowed",
"and",
"slightly",
"modified",
"from",
"the",
"Python",
"docs",
":",
"https",
":",
"//",
"docs",
".",
"p... | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/utils.py#L60-L72 | [
"def",
"unicode_csv_reader",
"(",
"unicode_csv_data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY2",
":",
"# csv.py doesn't do Unicode; encode temporarily as UTF-8:",
"csv_reader",
"=",
"csv",
".",
"reader",
"(",
"utf_8_encoder",
"(",
"unicode_csv_data",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | TranslationDataset.splits | Create dataset objects for splits of a TranslationDataset.
Arguments:
exts: A tuple containing the extension to path for each language.
fields: A tuple containing the fields that will be used for data
in each language.
path (str): Common prefix of the splits'... | torchtext/datasets/translation.py | def splits(cls, exts, fields, path=None, root='.data',
train='train', validation='val', test='test', **kwargs):
"""Create dataset objects for splits of a TranslationDataset.
Arguments:
exts: A tuple containing the extension to path for each language.
fields: A tup... | def splits(cls, exts, fields, path=None, root='.data',
train='train', validation='val', test='test', **kwargs):
"""Create dataset objects for splits of a TranslationDataset.
Arguments:
exts: A tuple containing the extension to path for each language.
fields: A tup... | [
"Create",
"dataset",
"objects",
"for",
"splits",
"of",
"a",
"TranslationDataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/translation.py#L45-L72 | [
"def",
"splits",
"(",
"cls",
",",
"exts",
",",
"fields",
",",
"path",
"=",
"None",
",",
"root",
"=",
"'.data'",
",",
"train",
"=",
"'train'",
",",
"validation",
"=",
"'val'",
",",
"test",
"=",
"'test'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"p... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Multi30k.splits | Create dataset objects for splits of the Multi30k dataset.
Arguments:
exts: A tuple containing the extension to path for each language.
fields: A tuple containing the fields that will be used for data
in each language.
root: Root dataset storage directory. De... | torchtext/datasets/translation.py | def splits(cls, exts, fields, root='.data',
train='train', validation='val', test='test2016', **kwargs):
"""Create dataset objects for splits of the Multi30k dataset.
Arguments:
exts: A tuple containing the extension to path for each language.
fields: A tuple cont... | def splits(cls, exts, fields, root='.data',
train='train', validation='val', test='test2016', **kwargs):
"""Create dataset objects for splits of the Multi30k dataset.
Arguments:
exts: A tuple containing the extension to path for each language.
fields: A tuple cont... | [
"Create",
"dataset",
"objects",
"for",
"splits",
"of",
"the",
"Multi30k",
"dataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/translation.py#L86-L114 | [
"def",
"splits",
"(",
"cls",
",",
"exts",
",",
"fields",
",",
"root",
"=",
"'.data'",
",",
"train",
"=",
"'train'",
",",
"validation",
"=",
"'val'",
",",
"test",
"=",
"'test2016'",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: This is a _HORRIBLE_ patch rela... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | IWSLT.splits | Create dataset objects for splits of the IWSLT dataset.
Arguments:
exts: A tuple containing the extension to path for each language.
fields: A tuple containing the fields that will be used for data
in each language.
root: Root dataset storage directory. Defau... | torchtext/datasets/translation.py | def splits(cls, exts, fields, root='.data',
train='train', validation='IWSLT16.TED.tst2013',
test='IWSLT16.TED.tst2014', **kwargs):
"""Create dataset objects for splits of the IWSLT dataset.
Arguments:
exts: A tuple containing the extension to path for each lan... | def splits(cls, exts, fields, root='.data',
train='train', validation='IWSLT16.TED.tst2013',
test='IWSLT16.TED.tst2014', **kwargs):
"""Create dataset objects for splits of the IWSLT dataset.
Arguments:
exts: A tuple containing the extension to path for each lan... | [
"Create",
"dataset",
"objects",
"for",
"splits",
"of",
"the",
"IWSLT",
"dataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/translation.py#L125-L161 | [
"def",
"splits",
"(",
"cls",
",",
"exts",
",",
"fields",
",",
"root",
"=",
"'.data'",
",",
"train",
"=",
"'train'",
",",
"validation",
"=",
"'IWSLT16.TED.tst2013'",
",",
"test",
"=",
"'IWSLT16.TED.tst2014'",
",",
"*",
"*",
"kwargs",
")",
":",
"cls",
".",... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | RawField.process | Process a list of examples to create a batch.
Postprocess the batch with user-provided Pipeline.
Args:
batch (list(object)): A list of object from a batch of examples.
Returns:
object: Processed object given the input and custom
postprocessing Pipeline. | torchtext/data/field.py | def process(self, batch, *args, **kwargs):
""" Process a list of examples to create a batch.
Postprocess the batch with user-provided Pipeline.
Args:
batch (list(object)): A list of object from a batch of examples.
Returns:
object: Processed object given the inp... | def process(self, batch, *args, **kwargs):
""" Process a list of examples to create a batch.
Postprocess the batch with user-provided Pipeline.
Args:
batch (list(object)): A list of object from a batch of examples.
Returns:
object: Processed object given the inp... | [
"Process",
"a",
"list",
"of",
"examples",
"to",
"create",
"a",
"batch",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L48-L61 | [
"def",
"process",
"(",
"self",
",",
"batch",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"postprocessing",
"is",
"not",
"None",
":",
"batch",
"=",
"self",
".",
"postprocessing",
"(",
"batch",
")",
"return",
"batch"
] | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Field.preprocess | Load a single example using this field, tokenizing if necessary.
If the input is a Python 2 `str`, it will be converted to Unicode
first. If `sequential=True`, it will be tokenized. Then the input
will be optionally lowercased and passed to the user-provided
`preprocessing` Pipeline. | torchtext/data/field.py | def preprocess(self, x):
"""Load a single example using this field, tokenizing if necessary.
If the input is a Python 2 `str`, it will be converted to Unicode
first. If `sequential=True`, it will be tokenized. Then the input
will be optionally lowercased and passed to the user-provided
... | def preprocess(self, x):
"""Load a single example using this field, tokenizing if necessary.
If the input is a Python 2 `str`, it will be converted to Unicode
first. If `sequential=True`, it will be tokenized. Then the input
will be optionally lowercased and passed to the user-provided
... | [
"Load",
"a",
"single",
"example",
"using",
"this",
"field",
"tokenizing",
"if",
"necessary",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L204-L223 | [
"def",
"preprocess",
"(",
"self",
",",
"x",
")",
":",
"if",
"(",
"six",
".",
"PY2",
"and",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_types",
")",
"and",
"not",
"isinstance",
"(",
"x",
",",
"six",
".",
"text_type",
")",
")",
":",
"x",
"=",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Field.process | Process a list of examples to create a torch.Tensor.
Pad, numericalize, and postprocess a batch and create a tensor.
Args:
batch (list(object)): A list of object from a batch of examples.
Returns:
torch.autograd.Variable: Processed object given the input
and... | torchtext/data/field.py | def process(self, batch, device=None):
""" Process a list of examples to create a torch.Tensor.
Pad, numericalize, and postprocess a batch and create a tensor.
Args:
batch (list(object)): A list of object from a batch of examples.
Returns:
torch.autograd.Variabl... | def process(self, batch, device=None):
""" Process a list of examples to create a torch.Tensor.
Pad, numericalize, and postprocess a batch and create a tensor.
Args:
batch (list(object)): A list of object from a batch of examples.
Returns:
torch.autograd.Variabl... | [
"Process",
"a",
"list",
"of",
"examples",
"to",
"create",
"a",
"torch",
".",
"Tensor",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L225-L238 | [
"def",
"process",
"(",
"self",
",",
"batch",
",",
"device",
"=",
"None",
")",
":",
"padded",
"=",
"self",
".",
"pad",
"(",
"batch",
")",
"tensor",
"=",
"self",
".",
"numericalize",
"(",
"padded",
",",
"device",
"=",
"device",
")",
"return",
"tensor"
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Field.pad | Pad a batch of examples using this field.
Pads to self.fix_length if provided, otherwise pads to the length of
the longest example in the batch. Prepends self.init_token and appends
self.eos_token if those attributes are not None. Returns a tuple of the
padded list and a list containing... | torchtext/data/field.py | def pad(self, minibatch):
"""Pad a batch of examples using this field.
Pads to self.fix_length if provided, otherwise pads to the length of
the longest example in the batch. Prepends self.init_token and appends
self.eos_token if those attributes are not None. Returns a tuple of the
... | def pad(self, minibatch):
"""Pad a batch of examples using this field.
Pads to self.fix_length if provided, otherwise pads to the length of
the longest example in the batch. Prepends self.init_token and appends
self.eos_token if those attributes are not None. Returns a tuple of the
... | [
"Pad",
"a",
"batch",
"of",
"examples",
"using",
"this",
"field",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L240-L275 | [
"def",
"pad",
"(",
"self",
",",
"minibatch",
")",
":",
"minibatch",
"=",
"list",
"(",
"minibatch",
")",
"if",
"not",
"self",
".",
"sequential",
":",
"return",
"minibatch",
"if",
"self",
".",
"fix_length",
"is",
"None",
":",
"max_len",
"=",
"max",
"(",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Field.build_vocab | Construct the Vocab object for this field from one or more datasets.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
represents the set of possible values for this field. If
... | torchtext/data/field.py | def build_vocab(self, *args, **kwargs):
"""Construct the Vocab object for this field from one or more datasets.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
represents the set of... | def build_vocab(self, *args, **kwargs):
"""Construct the Vocab object for this field from one or more datasets.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
represents the set of... | [
"Construct",
"the",
"Vocab",
"object",
"for",
"this",
"field",
"from",
"one",
"or",
"more",
"datasets",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L277-L309 | [
"def",
"build_vocab",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"counter",
"=",
"Counter",
"(",
")",
"sources",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Dataset",
")",
":",
"sou... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Field.numericalize | Turn a batch of examples that use this field into a Variable.
If the field has include_lengths=True, a tensor of lengths will be
included in the return value.
Arguments:
arr (List[List[str]], or tuple of (List[List[str]], List[int])):
List of tokenized and padded ex... | torchtext/data/field.py | def numericalize(self, arr, device=None):
"""Turn a batch of examples that use this field into a Variable.
If the field has include_lengths=True, a tensor of lengths will be
included in the return value.
Arguments:
arr (List[List[str]], or tuple of (List[List[str]], List[in... | def numericalize(self, arr, device=None):
"""Turn a batch of examples that use this field into a Variable.
If the field has include_lengths=True, a tensor of lengths will be
included in the return value.
Arguments:
arr (List[List[str]], or tuple of (List[List[str]], List[in... | [
"Turn",
"a",
"batch",
"of",
"examples",
"that",
"use",
"this",
"field",
"into",
"a",
"Variable",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L311-L368 | [
"def",
"numericalize",
"(",
"self",
",",
"arr",
",",
"device",
"=",
"None",
")",
":",
"if",
"self",
".",
"include_lengths",
"and",
"not",
"isinstance",
"(",
"arr",
",",
"tuple",
")",
":",
"raise",
"ValueError",
"(",
"\"Field has include_lengths set to True, bu... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | SubwordField.segment | Segment one or more datasets with this subword field.
Arguments:
Positional arguments: Dataset objects or other indexable
mutable sequences to segment. If a Dataset object is provided,
all columns corresponding to this field are used; individual
colum... | torchtext/data/field.py | def segment(self, *args):
"""Segment one or more datasets with this subword field.
Arguments:
Positional arguments: Dataset objects or other indexable
mutable sequences to segment. If a Dataset object is provided,
all columns corresponding to this field are u... | def segment(self, *args):
"""Segment one or more datasets with this subword field.
Arguments:
Positional arguments: Dataset objects or other indexable
mutable sequences to segment. If a Dataset object is provided,
all columns corresponding to this field are u... | [
"Segment",
"one",
"or",
"more",
"datasets",
"with",
"this",
"subword",
"field",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L424-L442 | [
"def",
"segment",
"(",
"self",
",",
"*",
"args",
")",
":",
"sources",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Dataset",
")",
":",
"sources",
"+=",
"[",
"getattr",
"(",
"arg",
",",
"name",
")",
"for",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | NestedField.preprocess | Preprocess a single example.
Firstly, tokenization and the supplied preprocessing pipeline is applied. Since
this field is always sequential, the result is a list. Then, each element of
the list is preprocessed using ``self.nesting_field.preprocess`` and the resulting
list is returned.
... | torchtext/data/field.py | def preprocess(self, xs):
"""Preprocess a single example.
Firstly, tokenization and the supplied preprocessing pipeline is applied. Since
this field is always sequential, the result is a list. Then, each element of
the list is preprocessed using ``self.nesting_field.preprocess`` and the... | def preprocess(self, xs):
"""Preprocess a single example.
Firstly, tokenization and the supplied preprocessing pipeline is applied. Since
this field is always sequential, the result is a list. Then, each element of
the list is preprocessed using ``self.nesting_field.preprocess`` and the... | [
"Preprocess",
"a",
"single",
"example",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L528-L543 | [
"def",
"preprocess",
"(",
"self",
",",
"xs",
")",
":",
"return",
"[",
"self",
".",
"nesting_field",
".",
"preprocess",
"(",
"x",
")",
"for",
"x",
"in",
"super",
"(",
"NestedField",
",",
"self",
")",
".",
"preprocess",
"(",
"xs",
")",
"]"
] | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | NestedField.pad | Pad a batch of examples using this field.
If ``self.nesting_field.sequential`` is ``False``, each example in the batch must
be a list of string tokens, and pads them as if by a ``Field`` with
``sequential=True``. Otherwise, each example must be a list of list of tokens.
Using ``self.nes... | torchtext/data/field.py | def pad(self, minibatch):
"""Pad a batch of examples using this field.
If ``self.nesting_field.sequential`` is ``False``, each example in the batch must
be a list of string tokens, and pads them as if by a ``Field`` with
``sequential=True``. Otherwise, each example must be a list of lis... | def pad(self, minibatch):
"""Pad a batch of examples using this field.
If ``self.nesting_field.sequential`` is ``False``, each example in the batch must
be a list of string tokens, and pads them as if by a ``Field`` with
``sequential=True``. Otherwise, each example must be a list of lis... | [
"Pad",
"a",
"batch",
"of",
"examples",
"using",
"this",
"field",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L545-L644 | [
"def",
"pad",
"(",
"self",
",",
"minibatch",
")",
":",
"minibatch",
"=",
"list",
"(",
"minibatch",
")",
"if",
"not",
"self",
".",
"nesting_field",
".",
"sequential",
":",
"return",
"super",
"(",
"NestedField",
",",
"self",
")",
".",
"pad",
"(",
"miniba... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | NestedField.build_vocab | Construct the Vocab object for nesting field and combine it with this field's vocab.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
represents the set of possible values for the nesting fi... | torchtext/data/field.py | def build_vocab(self, *args, **kwargs):
"""Construct the Vocab object for nesting field and combine it with this field's vocab.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
repre... | def build_vocab(self, *args, **kwargs):
"""Construct the Vocab object for nesting field and combine it with this field's vocab.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
repre... | [
"Construct",
"the",
"Vocab",
"object",
"for",
"nesting",
"field",
"and",
"combine",
"it",
"with",
"this",
"field",
"s",
"vocab",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L646-L692 | [
"def",
"build_vocab",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"sources",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Dataset",
")",
":",
"sources",
".",
"extend",
"(",
"[",
"geta... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | NestedField.numericalize | Convert a padded minibatch into a variable tensor.
Each item in the minibatch will be numericalized independently and the resulting
tensors will be stacked at the first dimension.
Arguments:
arr (List[List[str]]): List of tokenized and padded examples.
device (str or to... | torchtext/data/field.py | def numericalize(self, arrs, device=None):
"""Convert a padded minibatch into a variable tensor.
Each item in the minibatch will be numericalized independently and the resulting
tensors will be stacked at the first dimension.
Arguments:
arr (List[List[str]]): List of tokeni... | def numericalize(self, arrs, device=None):
"""Convert a padded minibatch into a variable tensor.
Each item in the minibatch will be numericalized independently and the resulting
tensors will be stacked at the first dimension.
Arguments:
arr (List[List[str]]): List of tokeni... | [
"Convert",
"a",
"padded",
"minibatch",
"into",
"a",
"variable",
"tensor",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L694-L723 | [
"def",
"numericalize",
"(",
"self",
",",
"arrs",
",",
"device",
"=",
"None",
")",
":",
"numericalized",
"=",
"[",
"]",
"self",
".",
"nesting_field",
".",
"include_lengths",
"=",
"False",
"if",
"self",
".",
"include_lengths",
":",
"arrs",
",",
"sentence_len... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | batch | Yield elements from data in chunks of batch_size. | torchtext/data/iterator.py | def batch(data, batch_size, batch_size_fn=None):
"""Yield elements from data in chunks of batch_size."""
if batch_size_fn is None:
def batch_size_fn(new, count, sofar):
return count
minibatch, size_so_far = [], 0
for ex in data:
minibatch.append(ex)
size_so_far = batc... | def batch(data, batch_size, batch_size_fn=None):
"""Yield elements from data in chunks of batch_size."""
if batch_size_fn is None:
def batch_size_fn(new, count, sofar):
return count
minibatch, size_so_far = [], 0
for ex in data:
minibatch.append(ex)
size_so_far = batc... | [
"Yield",
"elements",
"from",
"data",
"in",
"chunks",
"of",
"batch_size",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/iterator.py#L255-L271 | [
"def",
"batch",
"(",
"data",
",",
"batch_size",
",",
"batch_size_fn",
"=",
"None",
")",
":",
"if",
"batch_size_fn",
"is",
"None",
":",
"def",
"batch_size_fn",
"(",
"new",
",",
"count",
",",
"sofar",
")",
":",
"return",
"count",
"minibatch",
",",
"size_so... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | pool | Sort within buckets, then batch, then shuffle batches.
Partitions data into chunks of size 100*batch_size, sorts examples within
each chunk using sort_key, then batch these examples and shuffle the
batches. | torchtext/data/iterator.py | def pool(data, batch_size, key, batch_size_fn=lambda new, count, sofar: count,
random_shuffler=None, shuffle=False, sort_within_batch=False):
"""Sort within buckets, then batch, then shuffle batches.
Partitions data into chunks of size 100*batch_size, sorts examples within
each chunk using sort_ke... | def pool(data, batch_size, key, batch_size_fn=lambda new, count, sofar: count,
random_shuffler=None, shuffle=False, sort_within_batch=False):
"""Sort within buckets, then batch, then shuffle batches.
Partitions data into chunks of size 100*batch_size, sorts examples within
each chunk using sort_ke... | [
"Sort",
"within",
"buckets",
"then",
"batch",
"then",
"shuffle",
"batches",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/iterator.py#L274-L293 | [
"def",
"pool",
"(",
"data",
",",
"batch_size",
",",
"key",
",",
"batch_size_fn",
"=",
"lambda",
"new",
",",
"count",
",",
"sofar",
":",
"count",
",",
"random_shuffler",
"=",
"None",
",",
"shuffle",
"=",
"False",
",",
"sort_within_batch",
"=",
"False",
")... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Iterator.splits | Create Iterator objects for multiple splits of a dataset.
Arguments:
datasets: Tuple of Dataset objects corresponding to the splits. The
first such object should be the train set.
batch_sizes: Tuple of batch sizes to use for the different splits,
or None ... | torchtext/data/iterator.py | def splits(cls, datasets, batch_sizes=None, **kwargs):
"""Create Iterator objects for multiple splits of a dataset.
Arguments:
datasets: Tuple of Dataset objects corresponding to the splits. The
first such object should be the train set.
batch_sizes: Tuple of bat... | def splits(cls, datasets, batch_sizes=None, **kwargs):
"""Create Iterator objects for multiple splits of a dataset.
Arguments:
datasets: Tuple of Dataset objects corresponding to the splits. The
first such object should be the train set.
batch_sizes: Tuple of bat... | [
"Create",
"Iterator",
"objects",
"for",
"multiple",
"splits",
"of",
"a",
"dataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/iterator.py#L79-L97 | [
"def",
"splits",
"(",
"cls",
",",
"datasets",
",",
"batch_sizes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"batch_sizes",
"is",
"None",
":",
"batch_sizes",
"=",
"[",
"kwargs",
".",
"pop",
"(",
"'batch_size'",
")",
"]",
"*",
"len",
"(",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Iterator.data | Return the examples in the dataset in order, sorted, or shuffled. | torchtext/data/iterator.py | def data(self):
"""Return the examples in the dataset in order, sorted, or shuffled."""
if self.sort:
xs = sorted(self.dataset, key=self.sort_key)
elif self.shuffle:
xs = [self.dataset[i] for i in self.random_shuffler(range(len(self.dataset)))]
else:
x... | def data(self):
"""Return the examples in the dataset in order, sorted, or shuffled."""
if self.sort:
xs = sorted(self.dataset, key=self.sort_key)
elif self.shuffle:
xs = [self.dataset[i] for i in self.random_shuffler(range(len(self.dataset)))]
else:
x... | [
"Return",
"the",
"examples",
"in",
"the",
"dataset",
"in",
"order",
"sorted",
"or",
"shuffled",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/iterator.py#L99-L107 | [
"def",
"data",
"(",
"self",
")",
":",
"if",
"self",
".",
"sort",
":",
"xs",
"=",
"sorted",
"(",
"self",
".",
"dataset",
",",
"key",
"=",
"self",
".",
"sort_key",
")",
"elif",
"self",
".",
"shuffle",
":",
"xs",
"=",
"[",
"self",
".",
"dataset",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Iterator.init_epoch | Set up the batch generator for a new epoch. | torchtext/data/iterator.py | def init_epoch(self):
"""Set up the batch generator for a new epoch."""
if self._restored_from_state:
self.random_shuffler.random_state = self._random_state_this_epoch
else:
self._random_state_this_epoch = self.random_shuffler.random_state
self.create_batches()
... | def init_epoch(self):
"""Set up the batch generator for a new epoch."""
if self._restored_from_state:
self.random_shuffler.random_state = self._random_state_this_epoch
else:
self._random_state_this_epoch = self.random_shuffler.random_state
self.create_batches()
... | [
"Set",
"up",
"the",
"batch",
"generator",
"for",
"a",
"new",
"epoch",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/iterator.py#L109-L125 | [
"def",
"init_epoch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_restored_from_state",
":",
"self",
".",
"random_shuffler",
".",
"random_state",
"=",
"self",
".",
"_random_state_this_epoch",
"else",
":",
"self",
".",
"_random_state_this_epoch",
"=",
"self",
".",... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Batch.fromvars | Create a Batch directly from a number of Variables. | torchtext/data/batch.py | def fromvars(cls, dataset, batch_size, train=None, **kwargs):
"""Create a Batch directly from a number of Variables."""
batch = cls()
batch.batch_size = batch_size
batch.dataset = dataset
batch.fields = dataset.fields.keys()
for k, v in kwargs.items():
setattr... | def fromvars(cls, dataset, batch_size, train=None, **kwargs):
"""Create a Batch directly from a number of Variables."""
batch = cls()
batch.batch_size = batch_size
batch.dataset = dataset
batch.fields = dataset.fields.keys()
for k, v in kwargs.items():
setattr... | [
"Create",
"a",
"Batch",
"directly",
"from",
"a",
"number",
"of",
"Variables",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/batch.py#L37-L45 | [
"def",
"fromvars",
"(",
"cls",
",",
"dataset",
",",
"batch_size",
",",
"train",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"batch",
"=",
"cls",
"(",
")",
"batch",
".",
"batch_size",
"=",
"batch_size",
"batch",
".",
"dataset",
"=",
"dataset",
"ba... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | UDPOS.splits | Downloads and loads the Universal Dependencies Version 2 POS Tagged
data. | torchtext/datasets/sequence_tagging.py | def splits(cls, fields, root=".data", train="en-ud-tag.v2.train.txt",
validation="en-ud-tag.v2.dev.txt",
test="en-ud-tag.v2.test.txt", **kwargs):
"""Downloads and loads the Universal Dependencies Version 2 POS Tagged
data.
"""
return super(UDPOS, cls).split... | def splits(cls, fields, root=".data", train="en-ud-tag.v2.train.txt",
validation="en-ud-tag.v2.dev.txt",
test="en-ud-tag.v2.test.txt", **kwargs):
"""Downloads and loads the Universal Dependencies Version 2 POS Tagged
data.
"""
return super(UDPOS, cls).split... | [
"Downloads",
"and",
"loads",
"the",
"Universal",
"Dependencies",
"Version",
"2",
"POS",
"Tagged",
"data",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/sequence_tagging.py#L57-L66 | [
"def",
"splits",
"(",
"cls",
",",
"fields",
",",
"root",
"=",
"\".data\"",
",",
"train",
"=",
"\"en-ud-tag.v2.train.txt\"",
",",
"validation",
"=",
"\"en-ud-tag.v2.dev.txt\"",
",",
"test",
"=",
"\"en-ud-tag.v2.test.txt\"",
",",
"*",
"*",
"kwargs",
")",
":",
"r... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | CoNLL2000Chunking.splits | Downloads and loads the CoNLL 2000 Chunking dataset.
NOTE: There is only a train and test dataset so we use
10% of the train set as validation | torchtext/datasets/sequence_tagging.py | def splits(cls, fields, root=".data", train="train.txt",
test="test.txt", validation_frac=0.1, **kwargs):
"""Downloads and loads the CoNLL 2000 Chunking dataset.
NOTE: There is only a train and test dataset so we use
10% of the train set as validation
"""
tr... | def splits(cls, fields, root=".data", train="train.txt",
test="test.txt", validation_frac=0.1, **kwargs):
"""Downloads and loads the CoNLL 2000 Chunking dataset.
NOTE: There is only a train and test dataset so we use
10% of the train set as validation
"""
tr... | [
"Downloads",
"and",
"loads",
"the",
"CoNLL",
"2000",
"Chunking",
"dataset",
".",
"NOTE",
":",
"There",
"is",
"only",
"a",
"train",
"and",
"test",
"dataset",
"so",
"we",
"use",
"10%",
"of",
"the",
"train",
"set",
"as",
"validation"
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/sequence_tagging.py#L78-L103 | [
"def",
"splits",
"(",
"cls",
",",
"fields",
",",
"root",
"=",
"\".data\"",
",",
"train",
"=",
"\"train.txt\"",
",",
"test",
"=",
"\"test.txt\"",
",",
"validation_frac",
"=",
"0.1",
",",
"*",
"*",
"kwargs",
")",
":",
"train",
",",
"test",
"=",
"super",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | IMDB.splits | Create dataset objects for splits of the IMDB dataset.
Arguments:
text_field: The field that will be used for the sentence.
label_field: The field that will be used for label data.
root: Root dataset storage directory. Default is '.data'.
train: The directory tha... | torchtext/datasets/imdb.py | def splits(cls, text_field, label_field, root='.data',
train='train', test='test', **kwargs):
"""Create dataset objects for splits of the IMDB dataset.
Arguments:
text_field: The field that will be used for the sentence.
label_field: The field that will be used fo... | def splits(cls, text_field, label_field, root='.data',
train='train', test='test', **kwargs):
"""Create dataset objects for splits of the IMDB dataset.
Arguments:
text_field: The field that will be used for the sentence.
label_field: The field that will be used fo... | [
"Create",
"dataset",
"objects",
"for",
"splits",
"of",
"the",
"IMDB",
"dataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/imdb.py#L40-L55 | [
"def",
"splits",
"(",
"cls",
",",
"text_field",
",",
"label_field",
",",
"root",
"=",
"'.data'",
",",
"train",
"=",
"'train'",
",",
"test",
"=",
"'test'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"IMDB",
",",
"cls",
")",
".",
"spl... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | WikiText2.splits | Create dataset objects for splits of the WikiText-2 dataset.
This is the most flexible way to use the dataset.
Arguments:
text_field: The field that will be used for text data.
root: The root directory that the dataset's zip archive will be
expanded into; theref... | torchtext/datasets/language_modeling.py | def splits(cls, text_field, root='.data', train='wiki.train.tokens',
validation='wiki.valid.tokens', test='wiki.test.tokens',
**kwargs):
"""Create dataset objects for splits of the WikiText-2 dataset.
This is the most flexible way to use the dataset.
Arguments:
... | def splits(cls, text_field, root='.data', train='wiki.train.tokens',
validation='wiki.valid.tokens', test='wiki.test.tokens',
**kwargs):
"""Create dataset objects for splits of the WikiText-2 dataset.
This is the most flexible way to use the dataset.
Arguments:
... | [
"Create",
"dataset",
"objects",
"for",
"splits",
"of",
"the",
"WikiText",
"-",
"2",
"dataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/language_modeling.py#L40-L60 | [
"def",
"splits",
"(",
"cls",
",",
"text_field",
",",
"root",
"=",
"'.data'",
",",
"train",
"=",
"'wiki.train.tokens'",
",",
"validation",
"=",
"'wiki.valid.tokens'",
",",
"test",
"=",
"'wiki.test.tokens'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super"... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | WikiText2.iters | Create iterator objects for splits of the WikiText-2 dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
Arguments:
batch_size: Batch size.
bptt_len: Length of sequences for backpropagation th... | torchtext/datasets/language_modeling.py | def iters(cls, batch_size=32, bptt_len=35, device=0, root='.data',
vectors=None, **kwargs):
"""Create iterator objects for splits of the WikiText-2 dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
... | def iters(cls, batch_size=32, bptt_len=35, device=0, root='.data',
vectors=None, **kwargs):
"""Create iterator objects for splits of the WikiText-2 dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
... | [
"Create",
"iterator",
"objects",
"for",
"splits",
"of",
"the",
"WikiText",
"-",
"2",
"dataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/language_modeling.py#L63-L91 | [
"def",
"iters",
"(",
"cls",
",",
"batch_size",
"=",
"32",
",",
"bptt_len",
"=",
"35",
",",
"device",
"=",
"0",
",",
"root",
"=",
"'.data'",
",",
"vectors",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"TEXT",
"=",
"data",
".",
"Field",
"(",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Pipeline.call | Apply _only_ the convert_token function of the current pipeline
to the input. If the input is a list, a list with the results of
applying the `convert_token` function to all input elements is
returned.
Arguments:
x: The input to apply the convert_token function to.
... | torchtext/data/pipeline.py | def call(self, x, *args):
"""Apply _only_ the convert_token function of the current pipeline
to the input. If the input is a list, a list with the results of
applying the `convert_token` function to all input elements is
returned.
Arguments:
x: The input to apply the... | def call(self, x, *args):
"""Apply _only_ the convert_token function of the current pipeline
to the input. If the input is a list, a list with the results of
applying the `convert_token` function to all input elements is
returned.
Arguments:
x: The input to apply the... | [
"Apply",
"_only_",
"the",
"convert_token",
"function",
"of",
"the",
"current",
"pipeline",
"to",
"the",
"input",
".",
"If",
"the",
"input",
"is",
"a",
"list",
"a",
"list",
"with",
"the",
"results",
"of",
"applying",
"the",
"convert_token",
"function",
"to",
... | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/pipeline.py#L40-L53 | [
"def",
"call",
"(",
"self",
",",
"x",
",",
"*",
"args",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"return",
"[",
"self",
".",
"convert_token",
"(",
"tok",
",",
"*",
"args",
")",
"for",
"tok",
"in",
"x",
"]",
"return",
"self... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Pipeline.add_before | Add a Pipeline to be applied before this processing pipeline.
Arguments:
pipeline: The Pipeline or callable to apply before this
Pipeline. | torchtext/data/pipeline.py | def add_before(self, pipeline):
"""Add a Pipeline to be applied before this processing pipeline.
Arguments:
pipeline: The Pipeline or callable to apply before this
Pipeline.
"""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
... | def add_before(self, pipeline):
"""Add a Pipeline to be applied before this processing pipeline.
Arguments:
pipeline: The Pipeline or callable to apply before this
Pipeline.
"""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
... | [
"Add",
"a",
"Pipeline",
"to",
"be",
"applied",
"before",
"this",
"processing",
"pipeline",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/pipeline.py#L55-L65 | [
"def",
"add_before",
"(",
"self",
",",
"pipeline",
")",
":",
"if",
"not",
"isinstance",
"(",
"pipeline",
",",
"Pipeline",
")",
":",
"pipeline",
"=",
"Pipeline",
"(",
"pipeline",
")",
"self",
".",
"pipes",
"=",
"pipeline",
".",
"pipes",
"[",
":",
"]",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Pipeline.add_after | Add a Pipeline to be applied after this processing pipeline.
Arguments:
pipeline: The Pipeline or callable to apply after this
Pipeline. | torchtext/data/pipeline.py | def add_after(self, pipeline):
"""Add a Pipeline to be applied after this processing pipeline.
Arguments:
pipeline: The Pipeline or callable to apply after this
Pipeline.
"""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
... | def add_after(self, pipeline):
"""Add a Pipeline to be applied after this processing pipeline.
Arguments:
pipeline: The Pipeline or callable to apply after this
Pipeline.
"""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
... | [
"Add",
"a",
"Pipeline",
"to",
"be",
"applied",
"after",
"this",
"processing",
"pipeline",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/pipeline.py#L67-L77 | [
"def",
"add_after",
"(",
"self",
",",
"pipeline",
")",
":",
"if",
"not",
"isinstance",
"(",
"pipeline",
",",
"Pipeline",
")",
":",
"pipeline",
"=",
"Pipeline",
"(",
"pipeline",
")",
"self",
".",
"pipes",
"=",
"self",
".",
"pipes",
"[",
":",
"]",
"+",... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | check_split_ratio | Check that the split ratio argument is not malformed | torchtext/data/dataset.py | def check_split_ratio(split_ratio):
"""Check that the split ratio argument is not malformed"""
valid_ratio = 0.
if isinstance(split_ratio, float):
# Only the train set relative ratio is provided
# Assert in bounds, validation size is zero
assert 0. < split_ratio < 1., (
"... | def check_split_ratio(split_ratio):
"""Check that the split ratio argument is not malformed"""
valid_ratio = 0.
if isinstance(split_ratio, float):
# Only the train set relative ratio is provided
# Assert in bounds, validation size is zero
assert 0. < split_ratio < 1., (
"... | [
"Check",
"that",
"the",
"split",
"ratio",
"argument",
"is",
"not",
"malformed"
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/dataset.py#L284-L311 | [
"def",
"check_split_ratio",
"(",
"split_ratio",
")",
":",
"valid_ratio",
"=",
"0.",
"if",
"isinstance",
"(",
"split_ratio",
",",
"float",
")",
":",
"# Only the train set relative ratio is provided",
"# Assert in bounds, validation size is zero",
"assert",
"0.",
"<",
"spli... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Dataset.split | Create train-test(-valid?) splits from the instance's examples.
Arguments:
split_ratio (float or List of floats): a number [0, 1] denoting the amount
of data to be used for the training split (rest is used for validation),
or a list of numbers denoting the relative s... | torchtext/data/dataset.py | def split(self, split_ratio=0.7, stratified=False, strata_field='label',
random_state=None):
"""Create train-test(-valid?) splits from the instance's examples.
Arguments:
split_ratio (float or List of floats): a number [0, 1] denoting the amount
of data to be u... | def split(self, split_ratio=0.7, stratified=False, strata_field='label',
random_state=None):
"""Create train-test(-valid?) splits from the instance's examples.
Arguments:
split_ratio (float or List of floats): a number [0, 1] denoting the amount
of data to be u... | [
"Create",
"train",
"-",
"test",
"(",
"-",
"valid?",
")",
"splits",
"from",
"the",
"instance",
"s",
"examples",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/dataset.py#L86-L136 | [
"def",
"split",
"(",
"self",
",",
"split_ratio",
"=",
"0.7",
",",
"stratified",
"=",
"False",
",",
"strata_field",
"=",
"'label'",
",",
"random_state",
"=",
"None",
")",
":",
"train_ratio",
",",
"test_ratio",
",",
"val_ratio",
"=",
"check_split_ratio",
"(",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Dataset.download | Download and unzip an online archive (.zip, .gz, or .tgz).
Arguments:
root (str): Folder to download data to.
check (str or None): Folder whose existence indicates
that the dataset has already been downloaded, or
None to check the existence of root/{cls.n... | torchtext/data/dataset.py | def download(cls, root, check=None):
"""Download and unzip an online archive (.zip, .gz, or .tgz).
Arguments:
root (str): Folder to download data to.
check (str or None): Folder whose existence indicates
that the dataset has already been downloaded, or
... | def download(cls, root, check=None):
"""Download and unzip an online archive (.zip, .gz, or .tgz).
Arguments:
root (str): Folder to download data to.
check (str or None): Folder whose existence indicates
that the dataset has already been downloaded, or
... | [
"Download",
"and",
"unzip",
"an",
"online",
"archive",
"(",
".",
"zip",
".",
"gz",
"or",
".",
"tgz",
")",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/dataset.py#L157-L199 | [
"def",
"download",
"(",
"cls",
",",
"root",
",",
"check",
"=",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"cls",
".",
"name",
")",
"check",
"=",
"path",
"if",
"check",
"is",
"None",
"else",
"check",
"if",
"... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | Dataset.filter_examples | Remove unknown words from dataset examples with respect to given field.
Arguments:
field_names (list(str)): Within example only the parts with field names in
field_names will have their unknown words deleted. | torchtext/data/dataset.py | def filter_examples(self, field_names):
"""Remove unknown words from dataset examples with respect to given field.
Arguments:
field_names (list(str)): Within example only the parts with field names in
field_names will have their unknown words deleted.
"""
for... | def filter_examples(self, field_names):
"""Remove unknown words from dataset examples with respect to given field.
Arguments:
field_names (list(str)): Within example only the parts with field names in
field_names will have their unknown words deleted.
"""
for... | [
"Remove",
"unknown",
"words",
"from",
"dataset",
"examples",
"with",
"respect",
"to",
"given",
"field",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/dataset.py#L201-L214 | [
"def",
"filter_examples",
"(",
"self",
",",
"field_names",
")",
":",
"for",
"i",
",",
"example",
"in",
"enumerate",
"(",
"self",
".",
"examples",
")",
":",
"for",
"field_name",
"in",
"field_names",
":",
"vocab",
"=",
"set",
"(",
"self",
".",
"fields",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | NLIDataset.splits | Create dataset objects for splits of the SNLI dataset.
This is the most flexible way to use the dataset.
Arguments:
text_field: The field that will be used for premise and hypothesis
data.
label_field: The field that will be used for label data.
pars... | torchtext/datasets/nli.py | def splits(cls, text_field, label_field, parse_field=None,
extra_fields={}, root='.data', train='train.jsonl',
validation='val.jsonl', test='test.jsonl'):
"""Create dataset objects for splits of the SNLI dataset.
This is the most flexible way to use the dataset.
A... | def splits(cls, text_field, label_field, parse_field=None,
extra_fields={}, root='.data', train='train.jsonl',
validation='val.jsonl', test='test.jsonl'):
"""Create dataset objects for splits of the SNLI dataset.
This is the most flexible way to use the dataset.
A... | [
"Create",
"dataset",
"objects",
"for",
"splits",
"of",
"the",
"SNLI",
"dataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/nli.py#L46-L88 | [
"def",
"splits",
"(",
"cls",
",",
"text_field",
",",
"label_field",
",",
"parse_field",
"=",
"None",
",",
"extra_fields",
"=",
"{",
"}",
",",
"root",
"=",
"'.data'",
",",
"train",
"=",
"'train.jsonl'",
",",
"validation",
"=",
"'val.jsonl'",
",",
"test",
... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | NLIDataset.iters | Create iterator objects for splits of the SNLI dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
Arguments:
batch_size: Batch size.
device: Device to create batches on. Use -1 for CPU and No... | torchtext/datasets/nli.py | def iters(cls, batch_size=32, device=0, root='.data',
vectors=None, trees=False, **kwargs):
"""Create iterator objects for splits of the SNLI dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
... | def iters(cls, batch_size=32, device=0, root='.data',
vectors=None, trees=False, **kwargs):
"""Create iterator objects for splits of the SNLI dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
... | [
"Create",
"iterator",
"objects",
"for",
"splits",
"of",
"the",
"SNLI",
"dataset",
"."
] | pytorch/text | python | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/nli.py#L91-L126 | [
"def",
"iters",
"(",
"cls",
",",
"batch_size",
"=",
"32",
",",
"device",
"=",
"0",
",",
"root",
"=",
"'.data'",
",",
"vectors",
"=",
"None",
",",
"trees",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"trees",
":",
"TEXT",
"=",
"ParsedTe... | 26bfce6869dc704f1d86792f9a681d453d7e7bb8 |
train | bytes_to_unicode | Decode given bytes using specified escaping method.
:param byte_data: The byte-like object with bytes to decode.
:param escape: The escape method to use.
:param skip_printable: If True, don't escape byte_data with all 'printable ASCII' bytes. Defaults to False.
:return: New unicode string, escaped with ... | rdbtools/encodehelpers.py | def bytes_to_unicode(byte_data, escape, skip_printable=False):
"""
Decode given bytes using specified escaping method.
:param byte_data: The byte-like object with bytes to decode.
:param escape: The escape method to use.
:param skip_printable: If True, don't escape byte_data with all 'printable ASCI... | def bytes_to_unicode(byte_data, escape, skip_printable=False):
"""
Decode given bytes using specified escaping method.
:param byte_data: The byte-like object with bytes to decode.
:param escape: The escape method to use.
:param skip_printable: If True, don't escape byte_data with all 'printable ASCI... | [
"Decode",
"given",
"bytes",
"using",
"specified",
"escaping",
"method",
".",
":",
"param",
"byte_data",
":",
"The",
"byte",
"-",
"like",
"object",
"with",
"bytes",
"to",
"decode",
".",
":",
"param",
"escape",
":",
"The",
"escape",
"method",
"to",
"use",
... | sripathikrishnan/redis-rdb-tools | python | https://github.com/sripathikrishnan/redis-rdb-tools/blob/543a73e84702e911ddcd31325ecfde77d7fd230b/rdbtools/encodehelpers.py#L96-L123 | [
"def",
"bytes_to_unicode",
"(",
"byte_data",
",",
"escape",
",",
"skip_printable",
"=",
"False",
")",
":",
"if",
"isnumber",
"(",
"byte_data",
")",
":",
"if",
"skip_printable",
":",
"return",
"num2unistr",
"(",
"byte_data",
")",
"else",
":",
"byte_data",
"="... | 543a73e84702e911ddcd31325ecfde77d7fd230b |
train | apply_escape_bytes | Apply the specified escape method on the given bytes.
:param byte_data: The byte-like object with bytes to escape.
:param escape: The escape method to use.
:param skip_printable: If True, don't escape byte_data with all 'printable ASCII' bytes. Defaults to False.
:return: new bytes object with the escap... | rdbtools/encodehelpers.py | def apply_escape_bytes(byte_data, escape, skip_printable=False):
"""
Apply the specified escape method on the given bytes.
:param byte_data: The byte-like object with bytes to escape.
:param escape: The escape method to use.
:param skip_printable: If True, don't escape byte_data with all 'printable ... | def apply_escape_bytes(byte_data, escape, skip_printable=False):
"""
Apply the specified escape method on the given bytes.
:param byte_data: The byte-like object with bytes to escape.
:param escape: The escape method to use.
:param skip_printable: If True, don't escape byte_data with all 'printable ... | [
"Apply",
"the",
"specified",
"escape",
"method",
"on",
"the",
"given",
"bytes",
".",
":",
"param",
"byte_data",
":",
"The",
"byte",
"-",
"like",
"object",
"with",
"bytes",
"to",
"escape",
".",
":",
"param",
"escape",
":",
"The",
"escape",
"method",
"to",... | sripathikrishnan/redis-rdb-tools | python | https://github.com/sripathikrishnan/redis-rdb-tools/blob/543a73e84702e911ddcd31325ecfde77d7fd230b/rdbtools/encodehelpers.py#L126-L154 | [
"def",
"apply_escape_bytes",
"(",
"byte_data",
",",
"escape",
",",
"skip_printable",
"=",
"False",
")",
":",
"if",
"isnumber",
"(",
"byte_data",
")",
":",
"if",
"skip_printable",
":",
"return",
"num2bytes",
"(",
"byte_data",
")",
"else",
":",
"byte_data",
"=... | 543a73e84702e911ddcd31325ecfde77d7fd230b |
train | RdbParser._decode_module_id | decode module id to string
based on @antirez moduleTypeNameByID function from redis/src/module.c
:param module_id: 64bit integer
:return: string | rdbtools/parser.py | def _decode_module_id(self, module_id):
"""
decode module id to string
based on @antirez moduleTypeNameByID function from redis/src/module.c
:param module_id: 64bit integer
:return: string
"""
name = [''] * 9
module_id >>= 10
for i in reversed(rang... | def _decode_module_id(self, module_id):
"""
decode module id to string
based on @antirez moduleTypeNameByID function from redis/src/module.c
:param module_id: 64bit integer
:return: string
"""
name = [''] * 9
module_id >>= 10
for i in reversed(rang... | [
"decode",
"module",
"id",
"to",
"string",
"based",
"on"
] | sripathikrishnan/redis-rdb-tools | python | https://github.com/sripathikrishnan/redis-rdb-tools/blob/543a73e84702e911ddcd31325ecfde77d7fd230b/rdbtools/parser.py#L941-L953 | [
"def",
"_decode_module_id",
"(",
"self",
",",
"module_id",
")",
":",
"name",
"=",
"[",
"''",
"]",
"*",
"9",
"module_id",
">>=",
"10",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"9",
")",
")",
":",
"name",
"[",
"i",
"]",
"=",
"self",
".",
... | 543a73e84702e911ddcd31325ecfde77d7fd230b |
train | format_step | Return the step value in format suitable for display. | hiddenlayer/history.py | def format_step(step, zero_prefix=False):
"""Return the step value in format suitable for display."""
if isinstance(step, int):
return "{:06}".format(step) if zero_prefix else "{}".format(step)
elif isinstance(step, tuple):
return "{:04}:{:06}".format(*step) if zero_prefix else "{}:{}".forma... | def format_step(step, zero_prefix=False):
"""Return the step value in format suitable for display."""
if isinstance(step, int):
return "{:06}".format(step) if zero_prefix else "{}".format(step)
elif isinstance(step, tuple):
return "{:04}:{:06}".format(*step) if zero_prefix else "{}:{}".forma... | [
"Return",
"the",
"step",
"value",
"in",
"format",
"suitable",
"for",
"display",
"."
] | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/history.py#L27-L32 | [
"def",
"format_step",
"(",
"step",
",",
"zero_prefix",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"step",
",",
"int",
")",
":",
"return",
"\"{:06}\"",
".",
"format",
"(",
"step",
")",
"if",
"zero_prefix",
"else",
"\"{}\"",
".",
"format",
"(",
"st... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
train | History.log | Record metrics at a specific step. E.g.
my_history.log(34, loss=2.3, accuracy=0.2)
Okay to call multiple times for the same step. New values overwrite
older ones if they have the same metric name.
step: An integer or tuple of integers. If a tuple, then the first
value is c... | hiddenlayer/history.py | def log(self, step, **kwargs):
"""Record metrics at a specific step. E.g.
my_history.log(34, loss=2.3, accuracy=0.2)
Okay to call multiple times for the same step. New values overwrite
older ones if they have the same metric name.
step: An integer or tuple of integers. If a tu... | def log(self, step, **kwargs):
"""Record metrics at a specific step. E.g.
my_history.log(34, loss=2.3, accuracy=0.2)
Okay to call multiple times for the same step. New values overwrite
older ones if they have the same metric name.
step: An integer or tuple of integers. If a tu... | [
"Record",
"metrics",
"at",
"a",
"specific",
"step",
".",
"E",
".",
"g",
"."
] | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/history.py#L67-L88 | [
"def",
"log",
"(",
"self",
",",
"step",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"step",
",",
"(",
"int",
",",
"tuple",
")",
")",
",",
"\"Step must be an int or a tuple of two ints\"",
"self",
".",
"step",
"=",
"step",
"# Any new met... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
train | History.get_total_time | Returns the total period between when the first and last steps
where logged. This usually correspnods to the total training time
if there were no gaps in the training. | hiddenlayer/history.py | def get_total_time(self):
"""Returns the total period between when the first and last steps
where logged. This usually correspnods to the total training time
if there were no gaps in the training.
"""
first_step = self.steps[0]
last_step = self.steps[-1]
seconds =... | def get_total_time(self):
"""Returns the total period between when the first and last steps
where logged. This usually correspnods to the total training time
if there were no gaps in the training.
"""
first_step = self.steps[0]
last_step = self.steps[-1]
seconds =... | [
"Returns",
"the",
"total",
"period",
"between",
"when",
"the",
"first",
"and",
"last",
"steps",
"where",
"logged",
".",
"This",
"usually",
"correspnods",
"to",
"the",
"total",
"training",
"time",
"if",
"there",
"were",
"no",
"gaps",
"in",
"the",
"training",
... | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/history.py#L125-L134 | [
"def",
"get_total_time",
"(",
"self",
")",
":",
"first_step",
"=",
"self",
".",
"steps",
"[",
"0",
"]",
"last_step",
"=",
"self",
".",
"steps",
"[",
"-",
"1",
"]",
"seconds",
"=",
"self",
".",
"history",
"[",
"last_step",
"]",
"[",
"\"__timestamp__\"",... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
train | Graph.outgoing | Returns nodes connecting out of the given node (or list of nodes). | hiddenlayer/graph.py | def outgoing(self, node):
"""Returns nodes connecting out of the given node (or list of nodes)."""
nodes = node if isinstance(node, list) else [node]
node_ids = [self.id(n) for n in nodes]
# Find edges outgoing from this group but not incoming to it
outgoing = [self[e[1]] for e i... | def outgoing(self, node):
"""Returns nodes connecting out of the given node (or list of nodes)."""
nodes = node if isinstance(node, list) else [node]
node_ids = [self.id(n) for n in nodes]
# Find edges outgoing from this group but not incoming to it
outgoing = [self[e[1]] for e i... | [
"Returns",
"nodes",
"connecting",
"out",
"of",
"the",
"given",
"node",
"(",
"or",
"list",
"of",
"nodes",
")",
"."
] | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/graph.py#L221-L228 | [
"def",
"outgoing",
"(",
"self",
",",
"node",
")",
":",
"nodes",
"=",
"node",
"if",
"isinstance",
"(",
"node",
",",
"list",
")",
"else",
"[",
"node",
"]",
"node_ids",
"=",
"[",
"self",
".",
"id",
"(",
"n",
")",
"for",
"n",
"in",
"nodes",
"]",
"#... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
train | Graph.siblings | Returns all nodes that share the same parent (incoming node) with
the given node, including the node itself. | hiddenlayer/graph.py | def siblings(self, node):
"""Returns all nodes that share the same parent (incoming node) with
the given node, including the node itself.
"""
incoming = self.incoming(node)
# TODO: Not handling the case of multiple incoming nodes yet
if len(incoming) == 1:
inc... | def siblings(self, node):
"""Returns all nodes that share the same parent (incoming node) with
the given node, including the node itself.
"""
incoming = self.incoming(node)
# TODO: Not handling the case of multiple incoming nodes yet
if len(incoming) == 1:
inc... | [
"Returns",
"all",
"nodes",
"that",
"share",
"the",
"same",
"parent",
"(",
"incoming",
"node",
")",
"with",
"the",
"given",
"node",
"including",
"the",
"node",
"itself",
"."
] | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/graph.py#L239-L250 | [
"def",
"siblings",
"(",
"self",
",",
"node",
")",
":",
"incoming",
"=",
"self",
".",
"incoming",
"(",
"node",
")",
"# TODO: Not handling the case of multiple incoming nodes yet",
"if",
"len",
"(",
"incoming",
")",
"==",
"1",
":",
"incoming",
"=",
"incoming",
"... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
train | Graph.remove | Remove a node and its edges. | hiddenlayer/graph.py | def remove(self, nodes):
"""Remove a node and its edges."""
nodes = nodes if isinstance(nodes, list) else [nodes]
for node in nodes:
k = self.id(node)
self.edges = list(filter(lambda e: e[0] != k and e[1] != k, self.edges))
del self.nodes[k] | def remove(self, nodes):
"""Remove a node and its edges."""
nodes = nodes if isinstance(nodes, list) else [nodes]
for node in nodes:
k = self.id(node)
self.edges = list(filter(lambda e: e[0] != k and e[1] != k, self.edges))
del self.nodes[k] | [
"Remove",
"a",
"node",
"and",
"its",
"edges",
"."
] | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/graph.py#L258-L264 | [
"def",
"remove",
"(",
"self",
",",
"nodes",
")",
":",
"nodes",
"=",
"nodes",
"if",
"isinstance",
"(",
"nodes",
",",
"list",
")",
"else",
"[",
"nodes",
"]",
"for",
"node",
"in",
"nodes",
":",
"k",
"=",
"self",
".",
"id",
"(",
"node",
")",
"self",
... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
train | Graph.replace | Replace nodes with node. Edges incoming to nodes[0] are connected to
the new node, and nodes outgoing from nodes[-1] become outgoing from
the new node. | hiddenlayer/graph.py | def replace(self, nodes, node):
"""Replace nodes with node. Edges incoming to nodes[0] are connected to
the new node, and nodes outgoing from nodes[-1] become outgoing from
the new node."""
nodes = nodes if isinstance(nodes, list) else [nodes]
# Is the new node part of the replac... | def replace(self, nodes, node):
"""Replace nodes with node. Edges incoming to nodes[0] are connected to
the new node, and nodes outgoing from nodes[-1] become outgoing from
the new node."""
nodes = nodes if isinstance(nodes, list) else [nodes]
# Is the new node part of the replac... | [
"Replace",
"nodes",
"with",
"node",
".",
"Edges",
"incoming",
"to",
"nodes",
"[",
"0",
"]",
"are",
"connected",
"to",
"the",
"new",
"node",
"and",
"nodes",
"outgoing",
"from",
"nodes",
"[",
"-",
"1",
"]",
"become",
"outgoing",
"from",
"the",
"new",
"no... | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/graph.py#L266-L286 | [
"def",
"replace",
"(",
"self",
",",
"nodes",
",",
"node",
")",
":",
"nodes",
"=",
"nodes",
"if",
"isinstance",
"(",
"nodes",
",",
"list",
")",
"else",
"[",
"nodes",
"]",
"# Is the new node part of the replace nodes (i.e. want to collapse",
"# a group of nodes into o... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
train | Graph.search | Searches the graph for a sub-graph that matches the given pattern
and returns the first match it finds. | hiddenlayer/graph.py | def search(self, pattern):
"""Searches the graph for a sub-graph that matches the given pattern
and returns the first match it finds.
"""
for node in self.nodes.values():
match, following = pattern.match(self, node)
if match:
return match, followin... | def search(self, pattern):
"""Searches the graph for a sub-graph that matches the given pattern
and returns the first match it finds.
"""
for node in self.nodes.values():
match, following = pattern.match(self, node)
if match:
return match, followin... | [
"Searches",
"the",
"graph",
"for",
"a",
"sub",
"-",
"graph",
"that",
"matches",
"the",
"given",
"pattern",
"and",
"returns",
"the",
"first",
"match",
"it",
"finds",
"."
] | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/graph.py#L288-L296 | [
"def",
"search",
"(",
"self",
",",
"pattern",
")",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
".",
"values",
"(",
")",
":",
"match",
",",
"following",
"=",
"pattern",
".",
"match",
"(",
"self",
",",
"node",
")",
"if",
"match",
":",
"return",
... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
train | Graph.sequence_id | Make up an ID for a sequence (list) of nodes.
Note: `getrandbits()` is very uninformative as a "readable" ID. Here, we build a name
such that when the mouse hovers over the drawn node in Jupyter, one can figure out
which original nodes make up the sequence. This is actually quite useful. | hiddenlayer/graph.py | def sequence_id(self, sequence):
"""Make up an ID for a sequence (list) of nodes.
Note: `getrandbits()` is very uninformative as a "readable" ID. Here, we build a name
such that when the mouse hovers over the drawn node in Jupyter, one can figure out
which original nodes make up the sequ... | def sequence_id(self, sequence):
"""Make up an ID for a sequence (list) of nodes.
Note: `getrandbits()` is very uninformative as a "readable" ID. Here, we build a name
such that when the mouse hovers over the drawn node in Jupyter, one can figure out
which original nodes make up the sequ... | [
"Make",
"up",
"an",
"ID",
"for",
"a",
"sequence",
"(",
"list",
")",
"of",
"nodes",
".",
"Note",
":",
"getrandbits",
"()",
"is",
"very",
"uninformative",
"as",
"a",
"readable",
"ID",
".",
"Here",
"we",
"build",
"a",
"name",
"such",
"that",
"when",
"th... | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/graph.py#L299-L309 | [
"def",
"sequence_id",
"(",
"self",
",",
"sequence",
")",
":",
"if",
"self",
".",
"meaningful_ids",
":",
"# TODO: This might fail if the ID becomes too long",
"return",
"\"><\"",
".",
"join",
"(",
"[",
"node",
".",
"id",
"for",
"node",
"in",
"sequence",
"]",
")... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
train | Graph.build_dot | Generate a GraphViz Dot graph.
Returns a GraphViz Digraph object. | hiddenlayer/graph.py | def build_dot(self):
"""Generate a GraphViz Dot graph.
Returns a GraphViz Digraph object.
"""
from graphviz import Digraph
# Build GraphViz Digraph
dot = Digraph()
dot.attr("graph",
bgcolor=self.theme["background_color"],
color... | def build_dot(self):
"""Generate a GraphViz Dot graph.
Returns a GraphViz Digraph object.
"""
from graphviz import Digraph
# Build GraphViz Digraph
dot = Digraph()
dot.attr("graph",
bgcolor=self.theme["background_color"],
color... | [
"Generate",
"a",
"GraphViz",
"Dot",
"graph",
"."
] | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/graph.py#L311-L355 | [
"def",
"build_dot",
"(",
"self",
")",
":",
"from",
"graphviz",
"import",
"Digraph",
"# Build GraphViz Digraph",
"dot",
"=",
"Digraph",
"(",
")",
"dot",
".",
"attr",
"(",
"\"graph\"",
",",
"bgcolor",
"=",
"self",
".",
"theme",
"[",
"\"background_color\"",
"]"... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
train | to_data | Standardize data types. Converts PyTorch tensors to Numpy arrays,
and Numpy scalars to Python scalars. | hiddenlayer/utils.py | def to_data(value):
"""Standardize data types. Converts PyTorch tensors to Numpy arrays,
and Numpy scalars to Python scalars."""
# TODO: Use get_framework() for better detection.
if value.__class__.__module__.startswith("torch"):
import torch
if isinstance(value, torch.nn.parameter.Param... | def to_data(value):
"""Standardize data types. Converts PyTorch tensors to Numpy arrays,
and Numpy scalars to Python scalars."""
# TODO: Use get_framework() for better detection.
if value.__class__.__module__.startswith("torch"):
import torch
if isinstance(value, torch.nn.parameter.Param... | [
"Standardize",
"data",
"types",
".",
"Converts",
"PyTorch",
"tensors",
"to",
"Numpy",
"arrays",
"and",
"Numpy",
"scalars",
"to",
"Python",
"scalars",
"."
] | waleedka/hiddenlayer | python | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/utils.py#L17-L35 | [
"def",
"to_data",
"(",
"value",
")",
":",
"# TODO: Use get_framework() for better detection.",
"if",
"value",
".",
"__class__",
".",
"__module__",
".",
"startswith",
"(",
"\"torch\"",
")",
":",
"import",
"torch",
"if",
"isinstance",
"(",
"value",
",",
"torch",
"... | 294f8732b271cbdd6310c55bdf5ce855cbf61c75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.