repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
carpedm20/fbchat | fbchat/_client.py | Client.muteThreadReactions | def muteThreadReactions(self, mute=True, thread_id=None):
"""
Mutes thread reactions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"reactions_mute_mode": int(mute), "thread_fbid": thread_id}
r = self._post(self.req_url.MUTE_REACTIONS, data, fix_request=True) | python | def muteThreadReactions(self, mute=True, thread_id=None):
"""
Mutes thread reactions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"reactions_mute_mode": int(mute), "thread_fbid": thread_id}
r = self._post(self.req_url.MUTE_REACTIONS, data, fix_request=True) | [
"def",
"muteThreadReactions",
"(",
"self",
",",
"mute",
"=",
"True",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"{",
"\"reactions_mute_mode\"",
... | Mutes thread reactions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads` | [
"Mutes",
"thread",
"reactions"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2353-L2362 | train | 215,200 |
carpedm20/fbchat | fbchat/_client.py | Client.muteThreadMentions | def muteThreadMentions(self, mute=True, thread_id=None):
"""
Mutes thread mentions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"mentions_mute_mode": int(mute), "thread_fbid": thread_id}
r = self._post(self.req_url.MUTE_MENTIONS, data, fix_request=True) | python | def muteThreadMentions(self, mute=True, thread_id=None):
"""
Mutes thread mentions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"mentions_mute_mode": int(mute), "thread_fbid": thread_id}
r = self._post(self.req_url.MUTE_MENTIONS, data, fix_request=True) | [
"def",
"muteThreadMentions",
"(",
"self",
",",
"mute",
"=",
"True",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"{",
"\"mentions_mute_mode\"",
":... | Mutes thread mentions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads` | [
"Mutes",
"thread",
"mentions"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2372-L2381 | train | 215,201 |
carpedm20/fbchat | fbchat/_client.py | Client._pullMessage | def _pullMessage(self):
"""Call pull api with seq value to get message data."""
data = {
"msgs_recv": 0,
"sticky_token": self._sticky,
"sticky_pool": self._pool,
"clientid": self._client_id,
"state": "active" if self._markAlive else "offline",
}
return self._get(self.req_url.STICKY, data, fix_request=True, as_json=True) | python | def _pullMessage(self):
"""Call pull api with seq value to get message data."""
data = {
"msgs_recv": 0,
"sticky_token": self._sticky,
"sticky_pool": self._pool,
"clientid": self._client_id,
"state": "active" if self._markAlive else "offline",
}
return self._get(self.req_url.STICKY, data, fix_request=True, as_json=True) | [
"def",
"_pullMessage",
"(",
"self",
")",
":",
"data",
"=",
"{",
"\"msgs_recv\"",
":",
"0",
",",
"\"sticky_token\"",
":",
"self",
".",
"_sticky",
",",
"\"sticky_pool\"",
":",
"self",
".",
"_pool",
",",
"\"clientid\"",
":",
"self",
".",
"_client_id",
",",
... | Call pull api with seq value to get message data. | [
"Call",
"pull",
"api",
"with",
"seq",
"value",
"to",
"get",
"message",
"data",
"."
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2409-L2418 | train | 215,202 |
carpedm20/fbchat | fbchat/_client.py | Client._parseMessage | def _parseMessage(self, content):
"""Get message and author name from content. May contain multiple messages in the content."""
self._seq = content.get("seq", "0")
if "lb_info" in content:
self._sticky = content["lb_info"]["sticky"]
self._pool = content["lb_info"]["pool"]
if "batches" in content:
for batch in content["batches"]:
self._parseMessage(batch)
if "ms" not in content:
return
for m in content["ms"]:
mtype = m.get("type")
try:
# Things that directly change chat
if mtype == "delta":
self._parseDelta(m)
# Inbox
elif mtype == "inbox":
self.onInbox(
unseen=m["unseen"],
unread=m["unread"],
recent_unread=m["recent_unread"],
msg=m,
)
# Typing
elif mtype == "typ" or mtype == "ttyp":
author_id = str(m.get("from"))
thread_id = m.get("thread_fbid")
if thread_id:
thread_type = ThreadType.GROUP
thread_id = str(thread_id)
else:
thread_type = ThreadType.USER
if author_id == self._uid:
thread_id = m.get("to")
else:
thread_id = author_id
typing_status = TypingStatus(m.get("st"))
self.onTyping(
author_id=author_id,
status=typing_status,
thread_id=thread_id,
thread_type=thread_type,
msg=m,
)
# Delivered
# Seen
# elif mtype == "m_read_receipt":
#
# self.onSeen(m.get('realtime_viewer_fbid'), m.get('reader'), m.get('time'))
elif mtype in ["jewel_requests_add"]:
from_id = m["from"]
self.onFriendRequest(from_id=from_id, msg=m)
# Happens on every login
elif mtype == "qprimer":
self.onQprimer(ts=m.get("made"), msg=m)
# Is sent before any other message
elif mtype == "deltaflow":
pass
# Chat timestamp
elif mtype == "chatproxy-presence":
statuses = dict()
for id_, data in m.get("buddyList", {}).items():
statuses[id_] = ActiveStatus._from_chatproxy_presence(id_, data)
self._buddylist[id_] = statuses[id_]
self.onChatTimestamp(buddylist=statuses, msg=m)
# Buddylist overlay
elif mtype == "buddylist_overlay":
statuses = dict()
for id_, data in m.get("overlay", {}).items():
old_in_game = None
if id_ in self._buddylist:
old_in_game = self._buddylist[id_].in_game
statuses[id_] = ActiveStatus._from_buddylist_overlay(
data, old_in_game
)
self._buddylist[id_] = statuses[id_]
self.onBuddylistOverlay(statuses=statuses, msg=m)
# Unknown message type
else:
self.onUnknownMesssageType(msg=m)
except Exception as e:
self.onMessageError(exception=e, msg=m) | python | def _parseMessage(self, content):
"""Get message and author name from content. May contain multiple messages in the content."""
self._seq = content.get("seq", "0")
if "lb_info" in content:
self._sticky = content["lb_info"]["sticky"]
self._pool = content["lb_info"]["pool"]
if "batches" in content:
for batch in content["batches"]:
self._parseMessage(batch)
if "ms" not in content:
return
for m in content["ms"]:
mtype = m.get("type")
try:
# Things that directly change chat
if mtype == "delta":
self._parseDelta(m)
# Inbox
elif mtype == "inbox":
self.onInbox(
unseen=m["unseen"],
unread=m["unread"],
recent_unread=m["recent_unread"],
msg=m,
)
# Typing
elif mtype == "typ" or mtype == "ttyp":
author_id = str(m.get("from"))
thread_id = m.get("thread_fbid")
if thread_id:
thread_type = ThreadType.GROUP
thread_id = str(thread_id)
else:
thread_type = ThreadType.USER
if author_id == self._uid:
thread_id = m.get("to")
else:
thread_id = author_id
typing_status = TypingStatus(m.get("st"))
self.onTyping(
author_id=author_id,
status=typing_status,
thread_id=thread_id,
thread_type=thread_type,
msg=m,
)
# Delivered
# Seen
# elif mtype == "m_read_receipt":
#
# self.onSeen(m.get('realtime_viewer_fbid'), m.get('reader'), m.get('time'))
elif mtype in ["jewel_requests_add"]:
from_id = m["from"]
self.onFriendRequest(from_id=from_id, msg=m)
# Happens on every login
elif mtype == "qprimer":
self.onQprimer(ts=m.get("made"), msg=m)
# Is sent before any other message
elif mtype == "deltaflow":
pass
# Chat timestamp
elif mtype == "chatproxy-presence":
statuses = dict()
for id_, data in m.get("buddyList", {}).items():
statuses[id_] = ActiveStatus._from_chatproxy_presence(id_, data)
self._buddylist[id_] = statuses[id_]
self.onChatTimestamp(buddylist=statuses, msg=m)
# Buddylist overlay
elif mtype == "buddylist_overlay":
statuses = dict()
for id_, data in m.get("overlay", {}).items():
old_in_game = None
if id_ in self._buddylist:
old_in_game = self._buddylist[id_].in_game
statuses[id_] = ActiveStatus._from_buddylist_overlay(
data, old_in_game
)
self._buddylist[id_] = statuses[id_]
self.onBuddylistOverlay(statuses=statuses, msg=m)
# Unknown message type
else:
self.onUnknownMesssageType(msg=m)
except Exception as e:
self.onMessageError(exception=e, msg=m) | [
"def",
"_parseMessage",
"(",
"self",
",",
"content",
")",
":",
"self",
".",
"_seq",
"=",
"content",
".",
"get",
"(",
"\"seq\"",
",",
"\"0\"",
")",
"if",
"\"lb_info\"",
"in",
"content",
":",
"self",
".",
"_sticky",
"=",
"content",
"[",
"\"lb_info\"",
"]... | Get message and author name from content. May contain multiple messages in the content. | [
"Get",
"message",
"and",
"author",
"name",
"from",
"content",
".",
"May",
"contain",
"multiple",
"messages",
"in",
"the",
"content",
"."
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2966-L3066 | train | 215,203 |
carpedm20/fbchat | fbchat/_client.py | Client.doOneListen | def doOneListen(self, markAlive=None):
"""
Does one cycle of the listening loop.
This method is useful if you want to control fbchat from an external event loop
.. warning::
`markAlive` parameter is deprecated now, use :func:`fbchat.Client.setActiveStatus`
or `markAlive` parameter in :func:`fbchat.Client.listen` instead.
:return: Whether the loop should keep running
:rtype: bool
"""
if markAlive is not None:
self._markAlive = markAlive
try:
if self._markAlive:
self._ping()
content = self._pullMessage()
if content:
self._parseMessage(content)
except KeyboardInterrupt:
return False
except requests.Timeout:
pass
except requests.ConnectionError:
# If the client has lost their internet connection, keep trying every 30 seconds
time.sleep(30)
except FBchatFacebookError as e:
# Fix 502 and 503 pull errors
if e.request_status_code in [502, 503]:
self.req_url.change_pull_channel()
self.startListening()
else:
raise e
except Exception as e:
return self.onListenError(exception=e)
return True | python | def doOneListen(self, markAlive=None):
"""
Does one cycle of the listening loop.
This method is useful if you want to control fbchat from an external event loop
.. warning::
`markAlive` parameter is deprecated now, use :func:`fbchat.Client.setActiveStatus`
or `markAlive` parameter in :func:`fbchat.Client.listen` instead.
:return: Whether the loop should keep running
:rtype: bool
"""
if markAlive is not None:
self._markAlive = markAlive
try:
if self._markAlive:
self._ping()
content = self._pullMessage()
if content:
self._parseMessage(content)
except KeyboardInterrupt:
return False
except requests.Timeout:
pass
except requests.ConnectionError:
# If the client has lost their internet connection, keep trying every 30 seconds
time.sleep(30)
except FBchatFacebookError as e:
# Fix 502 and 503 pull errors
if e.request_status_code in [502, 503]:
self.req_url.change_pull_channel()
self.startListening()
else:
raise e
except Exception as e:
return self.onListenError(exception=e)
return True | [
"def",
"doOneListen",
"(",
"self",
",",
"markAlive",
"=",
"None",
")",
":",
"if",
"markAlive",
"is",
"not",
"None",
":",
"self",
".",
"_markAlive",
"=",
"markAlive",
"try",
":",
"if",
"self",
".",
"_markAlive",
":",
"self",
".",
"_ping",
"(",
")",
"c... | Does one cycle of the listening loop.
This method is useful if you want to control fbchat from an external event loop
.. warning::
`markAlive` parameter is deprecated now, use :func:`fbchat.Client.setActiveStatus`
or `markAlive` parameter in :func:`fbchat.Client.listen` instead.
:return: Whether the loop should keep running
:rtype: bool | [
"Does",
"one",
"cycle",
"of",
"the",
"listening",
"loop",
".",
"This",
"method",
"is",
"useful",
"if",
"you",
"want",
"to",
"control",
"fbchat",
"from",
"an",
"external",
"event",
"loop"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3076-L3113 | train | 215,204 |
carpedm20/fbchat | fbchat/_client.py | Client.listen | def listen(self, markAlive=None):
"""
Initializes and runs the listening loop continually
:param markAlive: Whether this should ping the Facebook server each time the loop runs
:type markAlive: bool
"""
if markAlive is not None:
self.setActiveStatus(markAlive)
self.startListening()
self.onListening()
while self.listening and self.doOneListen():
pass
self.stopListening() | python | def listen(self, markAlive=None):
"""
Initializes and runs the listening loop continually
:param markAlive: Whether this should ping the Facebook server each time the loop runs
:type markAlive: bool
"""
if markAlive is not None:
self.setActiveStatus(markAlive)
self.startListening()
self.onListening()
while self.listening and self.doOneListen():
pass
self.stopListening() | [
"def",
"listen",
"(",
"self",
",",
"markAlive",
"=",
"None",
")",
":",
"if",
"markAlive",
"is",
"not",
"None",
":",
"self",
".",
"setActiveStatus",
"(",
"markAlive",
")",
"self",
".",
"startListening",
"(",
")",
"self",
".",
"onListening",
"(",
")",
"w... | Initializes and runs the listening loop continually
:param markAlive: Whether this should ping the Facebook server each time the loop runs
:type markAlive: bool | [
"Initializes",
"and",
"runs",
"the",
"listening",
"loop",
"continually"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3120-L3136 | train | 215,205 |
carpedm20/fbchat | fbchat/_client.py | Client.onMessage | def onMessage(
self,
mid=None,
author_id=None,
message=None,
message_object=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody sends a message
:param mid: The message ID
:param author_id: The ID of the author
:param message: (deprecated. Use `message_object.text` instead)
:param message_object: The message (As a `Message` object)
:param thread_id: Thread ID that the message was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the message was sent to. See :ref:`intro_threads`
:param ts: The timestamp of the message
:param metadata: Extra metadata about the message
:param msg: A full set of the data recieved
:type message_object: models.Message
:type thread_type: models.ThreadType
"""
log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name)) | python | def onMessage(
self,
mid=None,
author_id=None,
message=None,
message_object=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody sends a message
:param mid: The message ID
:param author_id: The ID of the author
:param message: (deprecated. Use `message_object.text` instead)
:param message_object: The message (As a `Message` object)
:param thread_id: Thread ID that the message was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the message was sent to. See :ref:`intro_threads`
:param ts: The timestamp of the message
:param metadata: Extra metadata about the message
:param msg: A full set of the data recieved
:type message_object: models.Message
:type thread_type: models.ThreadType
"""
log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name)) | [
"def",
"onMessage",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"message",
"=",
"None",
",",
"message_object",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
",",
"ts",
"=",... | Called when the client is listening, and somebody sends a message
:param mid: The message ID
:param author_id: The ID of the author
:param message: (deprecated. Use `message_object.text` instead)
:param message_object: The message (As a `Message` object)
:param thread_id: Thread ID that the message was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the message was sent to. See :ref:`intro_threads`
:param ts: The timestamp of the message
:param metadata: Extra metadata about the message
:param msg: A full set of the data recieved
:type message_object: models.Message
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"sends",
"a",
"message"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3189-L3216 | train | 215,206 |
carpedm20/fbchat | fbchat/_client.py | Client.onColorChange | def onColorChange(
self,
mid=None,
author_id=None,
new_color=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes a thread's color
:param mid: The action ID
:param author_id: The ID of the person who changed the color
:param new_color: The new color
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type new_color: models.ThreadColor
:type thread_type: models.ThreadType
"""
log.info(
"Color change from {} in {} ({}): {}".format(
author_id, thread_id, thread_type.name, new_color
)
) | python | def onColorChange(
self,
mid=None,
author_id=None,
new_color=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes a thread's color
:param mid: The action ID
:param author_id: The ID of the person who changed the color
:param new_color: The new color
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type new_color: models.ThreadColor
:type thread_type: models.ThreadType
"""
log.info(
"Color change from {} in {} ({}): {}".format(
author_id, thread_id, thread_type.name, new_color
)
) | [
"def",
"onColorChange",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"new_color",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
",",
"ts",
"=",
"None",
",",
"metadata",
"=",... | Called when the client is listening, and somebody changes a thread's color
:param mid: The action ID
:param author_id: The ID of the person who changed the color
:param new_color: The new color
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type new_color: models.ThreadColor
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"changes",
"a",
"thread",
"s",
"color"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3218-L3247 | train | 215,207 |
carpedm20/fbchat | fbchat/_client.py | Client.onEmojiChange | def onEmojiChange(
self,
mid=None,
author_id=None,
new_emoji=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes a thread's emoji
:param mid: The action ID
:param author_id: The ID of the person who changed the emoji
:param new_emoji: The new emoji
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Emoji change from {} in {} ({}): {}".format(
author_id, thread_id, thread_type.name, new_emoji
)
) | python | def onEmojiChange(
self,
mid=None,
author_id=None,
new_emoji=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes a thread's emoji
:param mid: The action ID
:param author_id: The ID of the person who changed the emoji
:param new_emoji: The new emoji
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Emoji change from {} in {} ({}): {}".format(
author_id, thread_id, thread_type.name, new_emoji
)
) | [
"def",
"onEmojiChange",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"new_emoji",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
",",
"ts",
"=",
"None",
",",
"metadata",
"=",... | Called when the client is listening, and somebody changes a thread's emoji
:param mid: The action ID
:param author_id: The ID of the person who changed the emoji
:param new_emoji: The new emoji
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"changes",
"a",
"thread",
"s",
"emoji"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3249-L3277 | train | 215,208 |
carpedm20/fbchat | fbchat/_client.py | Client.onTitleChange | def onTitleChange(
self,
mid=None,
author_id=None,
new_title=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes the title of a thread
:param mid: The action ID
:param author_id: The ID of the person who changed the title
:param new_title: The new title
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Title change from {} in {} ({}): {}".format(
author_id, thread_id, thread_type.name, new_title
)
) | python | def onTitleChange(
self,
mid=None,
author_id=None,
new_title=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes the title of a thread
:param mid: The action ID
:param author_id: The ID of the person who changed the title
:param new_title: The new title
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Title change from {} in {} ({}): {}".format(
author_id, thread_id, thread_type.name, new_title
)
) | [
"def",
"onTitleChange",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"new_title",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
",",
"ts",
"=",
"None",
",",
"metadata",
"=",... | Called when the client is listening, and somebody changes the title of a thread
:param mid: The action ID
:param author_id: The ID of the person who changed the title
:param new_title: The new title
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"changes",
"the",
"title",
"of",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3279-L3307 | train | 215,209 |
carpedm20/fbchat | fbchat/_client.py | Client.onImageChange | def onImageChange(
self,
mid=None,
author_id=None,
new_image=None,
thread_id=None,
thread_type=ThreadType.GROUP,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes the image of a thread
:param mid: The action ID
:param author_id: The ID of the person who changed the image
:param new_image: The ID of the new image
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info("{} changed thread image in {}".format(author_id, thread_id)) | python | def onImageChange(
self,
mid=None,
author_id=None,
new_image=None,
thread_id=None,
thread_type=ThreadType.GROUP,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes the image of a thread
:param mid: The action ID
:param author_id: The ID of the person who changed the image
:param new_image: The ID of the new image
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info("{} changed thread image in {}".format(author_id, thread_id)) | [
"def",
"onImageChange",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"new_image",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"GROUP",
",",
"ts",
"=",
"None",
",",
"msg",
"=",
"... | Called when the client is listening, and somebody changes the image of a thread
:param mid: The action ID
:param author_id: The ID of the person who changed the image
:param new_image: The ID of the new image
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"changes",
"the",
"image",
"of",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3309-L3331 | train | 215,210 |
carpedm20/fbchat | fbchat/_client.py | Client.onNicknameChange | def onNicknameChange(
self,
mid=None,
author_id=None,
changed_for=None,
new_nickname=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes the nickname of a person
:param mid: The action ID
:param author_id: The ID of the person who changed the nickname
:param changed_for: The ID of the person whom got their nickname changed
:param new_nickname: The new nickname
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Nickname change from {} in {} ({}) for {}: {}".format(
author_id, thread_id, thread_type.name, changed_for, new_nickname
)
) | python | def onNicknameChange(
self,
mid=None,
author_id=None,
changed_for=None,
new_nickname=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes the nickname of a person
:param mid: The action ID
:param author_id: The ID of the person who changed the nickname
:param changed_for: The ID of the person whom got their nickname changed
:param new_nickname: The new nickname
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Nickname change from {} in {} ({}) for {}: {}".format(
author_id, thread_id, thread_type.name, changed_for, new_nickname
)
) | [
"def",
"onNicknameChange",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"changed_for",
"=",
"None",
",",
"new_nickname",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
",",
"ts... | Called when the client is listening, and somebody changes the nickname of a person
:param mid: The action ID
:param author_id: The ID of the person who changed the nickname
:param changed_for: The ID of the person whom got their nickname changed
:param new_nickname: The new nickname
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"changes",
"the",
"nickname",
"of",
"a",
"person"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3333-L3363 | train | 215,211 |
carpedm20/fbchat | fbchat/_client.py | Client.onAdminAdded | def onAdminAdded(
self,
mid=None,
added_id=None,
author_id=None,
thread_id=None,
thread_type=ThreadType.GROUP,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody adds an admin to a group thread
:param mid: The action ID
:param added_id: The ID of the admin who got added
:param author_id: The ID of the person who added the admins
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
"""
log.info("{} added admin: {} in {}".format(author_id, added_id, thread_id)) | python | def onAdminAdded(
self,
mid=None,
added_id=None,
author_id=None,
thread_id=None,
thread_type=ThreadType.GROUP,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody adds an admin to a group thread
:param mid: The action ID
:param added_id: The ID of the admin who got added
:param author_id: The ID of the person who added the admins
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
"""
log.info("{} added admin: {} in {}".format(author_id, added_id, thread_id)) | [
"def",
"onAdminAdded",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"added_id",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"GROUP",
",",
"ts",
"=",
"None",
",",
"msg",
"=",
"No... | Called when the client is listening, and somebody adds an admin to a group thread
:param mid: The action ID
:param added_id: The ID of the admin who got added
:param author_id: The ID of the person who added the admins
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"adds",
"an",
"admin",
"to",
"a",
"group",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3365-L3385 | train | 215,212 |
carpedm20/fbchat | fbchat/_client.py | Client.onAdminRemoved | def onAdminRemoved(
self,
mid=None,
removed_id=None,
author_id=None,
thread_id=None,
thread_type=ThreadType.GROUP,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody removes an admin from a group thread
:param mid: The action ID
:param removed_id: The ID of the admin who got removed
:param author_id: The ID of the person who removed the admins
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
"""
log.info("{} removed admin: {} in {}".format(author_id, removed_id, thread_id)) | python | def onAdminRemoved(
self,
mid=None,
removed_id=None,
author_id=None,
thread_id=None,
thread_type=ThreadType.GROUP,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody removes an admin from a group thread
:param mid: The action ID
:param removed_id: The ID of the admin who got removed
:param author_id: The ID of the person who removed the admins
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
"""
log.info("{} removed admin: {} in {}".format(author_id, removed_id, thread_id)) | [
"def",
"onAdminRemoved",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"removed_id",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"GROUP",
",",
"ts",
"=",
"None",
",",
"msg",
"=",
... | Called when the client is listening, and somebody removes an admin from a group thread
:param mid: The action ID
:param removed_id: The ID of the admin who got removed
:param author_id: The ID of the person who removed the admins
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"removes",
"an",
"admin",
"from",
"a",
"group",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3387-L3407 | train | 215,213 |
carpedm20/fbchat | fbchat/_client.py | Client.onApprovalModeChange | def onApprovalModeChange(
self,
mid=None,
approval_mode=None,
author_id=None,
thread_id=None,
thread_type=ThreadType.GROUP,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes approval mode in a group thread
:param mid: The action ID
:param approval_mode: True if approval mode is activated
:param author_id: The ID of the person who changed approval mode
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
"""
if approval_mode:
log.info("{} activated approval mode in {}".format(author_id, thread_id))
else:
log.info("{} disabled approval mode in {}".format(author_id, thread_id)) | python | def onApprovalModeChange(
self,
mid=None,
approval_mode=None,
author_id=None,
thread_id=None,
thread_type=ThreadType.GROUP,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody changes approval mode in a group thread
:param mid: The action ID
:param approval_mode: True if approval mode is activated
:param author_id: The ID of the person who changed approval mode
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
"""
if approval_mode:
log.info("{} activated approval mode in {}".format(author_id, thread_id))
else:
log.info("{} disabled approval mode in {}".format(author_id, thread_id)) | [
"def",
"onApprovalModeChange",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"approval_mode",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"GROUP",
",",
"ts",
"=",
"None",
",",
"msg",... | Called when the client is listening, and somebody changes approval mode in a group thread
:param mid: The action ID
:param approval_mode: True if approval mode is activated
:param author_id: The ID of the person who changed approval mode
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"changes",
"approval",
"mode",
"in",
"a",
"group",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3409-L3432 | train | 215,214 |
carpedm20/fbchat | fbchat/_client.py | Client.onMessageSeen | def onMessageSeen(
self,
seen_by=None,
thread_id=None,
thread_type=ThreadType.USER,
seen_ts=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody marks a message as seen
:param seen_by: The ID of the person who marked the message as seen
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param seen_ts: A timestamp of when the person saw the message
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Messages seen by {} in {} ({}) at {}s".format(
seen_by, thread_id, thread_type.name, seen_ts / 1000
)
) | python | def onMessageSeen(
self,
seen_by=None,
thread_id=None,
thread_type=ThreadType.USER,
seen_ts=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody marks a message as seen
:param seen_by: The ID of the person who marked the message as seen
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param seen_ts: A timestamp of when the person saw the message
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Messages seen by {} in {} ({}) at {}s".format(
seen_by, thread_id, thread_type.name, seen_ts / 1000
)
) | [
"def",
"onMessageSeen",
"(",
"self",
",",
"seen_by",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
",",
"seen_ts",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"msg",
"=",
"... | Called when the client is listening, and somebody marks a message as seen
:param seen_by: The ID of the person who marked the message as seen
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param seen_ts: A timestamp of when the person saw the message
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"marks",
"a",
"message",
"as",
"seen"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3434-L3460 | train | 215,215 |
carpedm20/fbchat | fbchat/_client.py | Client.onMessageDelivered | def onMessageDelivered(
self,
msg_ids=None,
delivered_for=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody marks messages as delivered
:param msg_ids: The messages that are marked as delivered
:param delivered_for: The person that marked the messages as delivered
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Messages {} delivered to {} in {} ({}) at {}s".format(
msg_ids, delivered_for, thread_id, thread_type.name, ts / 1000
)
) | python | def onMessageDelivered(
self,
msg_ids=None,
delivered_for=None,
thread_id=None,
thread_type=ThreadType.USER,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody marks messages as delivered
:param msg_ids: The messages that are marked as delivered
:param delivered_for: The person that marked the messages as delivered
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Messages {} delivered to {} in {} ({}) at {}s".format(
msg_ids, delivered_for, thread_id, thread_type.name, ts / 1000
)
) | [
"def",
"onMessageDelivered",
"(",
"self",
",",
"msg_ids",
"=",
"None",
",",
"delivered_for",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
",",
"ts",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"msg",... | Called when the client is listening, and somebody marks messages as delivered
:param msg_ids: The messages that are marked as delivered
:param delivered_for: The person that marked the messages as delivered
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"marks",
"messages",
"as",
"delivered"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3462-L3488 | train | 215,216 |
carpedm20/fbchat | fbchat/_client.py | Client.onMarkedSeen | def onMarkedSeen(
self, threads=None, seen_ts=None, ts=None, metadata=None, msg=None
):
"""
Called when the client is listening, and the client has successfully marked threads as seen
:param threads: The threads that were marked
:param author_id: The ID of the person who changed the emoji
:param seen_ts: A timestamp of when the threads were seen
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Marked messages as seen in threads {} at {}s".format(
[(x[0], x[1].name) for x in threads], seen_ts / 1000
)
) | python | def onMarkedSeen(
self, threads=None, seen_ts=None, ts=None, metadata=None, msg=None
):
"""
Called when the client is listening, and the client has successfully marked threads as seen
:param threads: The threads that were marked
:param author_id: The ID of the person who changed the emoji
:param seen_ts: A timestamp of when the threads were seen
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"Marked messages as seen in threads {} at {}s".format(
[(x[0], x[1].name) for x in threads], seen_ts / 1000
)
) | [
"def",
"onMarkedSeen",
"(",
"self",
",",
"threads",
"=",
"None",
",",
"seen_ts",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"msg",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"Marked messages as seen in threads {} at {}s\... | Called when the client is listening, and the client has successfully marked threads as seen
:param threads: The threads that were marked
:param author_id: The ID of the person who changed the emoji
:param seen_ts: A timestamp of when the threads were seen
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"the",
"client",
"has",
"successfully",
"marked",
"threads",
"as",
"seen"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3490-L3508 | train | 215,217 |
carpedm20/fbchat | fbchat/_client.py | Client.onPeopleAdded | def onPeopleAdded(
self,
mid=None,
added_ids=None,
author_id=None,
thread_id=None,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody adds people to a group thread
:param mid: The action ID
:param added_ids: The IDs of the people who got added
:param author_id: The ID of the person who added the people
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
"""
log.info(
"{} added: {} in {}".format(author_id, ", ".join(added_ids), thread_id)
) | python | def onPeopleAdded(
self,
mid=None,
added_ids=None,
author_id=None,
thread_id=None,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody adds people to a group thread
:param mid: The action ID
:param added_ids: The IDs of the people who got added
:param author_id: The ID of the person who added the people
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
"""
log.info(
"{} added: {} in {}".format(author_id, ", ".join(added_ids), thread_id)
) | [
"def",
"onPeopleAdded",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"added_ids",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"msg",
"=",
"None",
",",
")",
":",
"log",
".",
"info",
"(",
"\... | Called when the client is listening, and somebody adds people to a group thread
:param mid: The action ID
:param added_ids: The IDs of the people who got added
:param author_id: The ID of the person who added the people
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"adds",
"people",
"to",
"a",
"group",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3536-L3557 | train | 215,218 |
carpedm20/fbchat | fbchat/_client.py | Client.onPersonRemoved | def onPersonRemoved(
self,
mid=None,
removed_id=None,
author_id=None,
thread_id=None,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody removes a person from a group thread
:param mid: The action ID
:param removed_id: The ID of the person who got removed
:param author_id: The ID of the person who removed the person
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
"""
log.info("{} removed: {} in {}".format(author_id, removed_id, thread_id)) | python | def onPersonRemoved(
self,
mid=None,
removed_id=None,
author_id=None,
thread_id=None,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody removes a person from a group thread
:param mid: The action ID
:param removed_id: The ID of the person who got removed
:param author_id: The ID of the person who removed the person
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
"""
log.info("{} removed: {} in {}".format(author_id, removed_id, thread_id)) | [
"def",
"onPersonRemoved",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"removed_id",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"msg",
"=",
"None",
",",
")",
":",
"log",
".",
"info",
"(",
... | Called when the client is listening, and somebody removes a person from a group thread
:param mid: The action ID
:param removed_id: The ID of the person who got removed
:param author_id: The ID of the person who removed the person
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"removes",
"a",
"person",
"from",
"a",
"group",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3559-L3578 | train | 215,219 |
carpedm20/fbchat | fbchat/_client.py | Client.onGamePlayed | def onGamePlayed(
self,
mid=None,
author_id=None,
game_id=None,
game_name=None,
score=None,
leaderboard=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody plays a game
:param mid: The action ID
:param author_id: The ID of the person who played the game
:param game_id: The ID of the game
:param game_name: Name of the game
:param score: Score obtained in the game
:param leaderboard: Actual leaderboard of the game in the thread
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
'{} played "{}" in {} ({})'.format(
author_id, game_name, thread_id, thread_type.name
)
) | python | def onGamePlayed(
self,
mid=None,
author_id=None,
game_id=None,
game_name=None,
score=None,
leaderboard=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody plays a game
:param mid: The action ID
:param author_id: The ID of the person who played the game
:param game_id: The ID of the game
:param game_name: Name of the game
:param score: Score obtained in the game
:param leaderboard: Actual leaderboard of the game in the thread
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
'{} played "{}" in {} ({})'.format(
author_id, game_name, thread_id, thread_type.name
)
) | [
"def",
"onGamePlayed",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"game_id",
"=",
"None",
",",
"game_name",
"=",
"None",
",",
"score",
"=",
"None",
",",
"leaderboard",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"t... | Called when the client is listening, and somebody plays a game
:param mid: The action ID
:param author_id: The ID of the person who played the game
:param game_id: The ID of the game
:param game_name: Name of the game
:param score: Score obtained in the game
:param leaderboard: Actual leaderboard of the game in the thread
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"plays",
"a",
"game"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3617-L3651 | train | 215,220 |
carpedm20/fbchat | fbchat/_client.py | Client.onReactionAdded | def onReactionAdded(
self,
mid=None,
reaction=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody reacts to a message
:param mid: Message ID, that user reacted to
:param reaction: Reaction
:param add_reaction: Whether user added or removed reaction
:param author_id: The ID of the person who reacted to the message
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type reaction: models.MessageReaction
:type thread_type: models.ThreadType
"""
log.info(
"{} reacted to message {} with {} in {} ({})".format(
author_id, mid, reaction.name, thread_id, thread_type.name
)
) | python | def onReactionAdded(
self,
mid=None,
reaction=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody reacts to a message
:param mid: Message ID, that user reacted to
:param reaction: Reaction
:param add_reaction: Whether user added or removed reaction
:param author_id: The ID of the person who reacted to the message
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type reaction: models.MessageReaction
:type thread_type: models.ThreadType
"""
log.info(
"{} reacted to message {} with {} in {} ({})".format(
author_id, mid, reaction.name, thread_id, thread_type.name
)
) | [
"def",
"onReactionAdded",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"reaction",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"msg",
"=",
"None",
",",
")",
... | Called when the client is listening, and somebody reacts to a message
:param mid: Message ID, that user reacted to
:param reaction: Reaction
:param add_reaction: Whether user added or removed reaction
:param author_id: The ID of the person who reacted to the message
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type reaction: models.MessageReaction
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"reacts",
"to",
"a",
"message"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3653-L3681 | train | 215,221 |
carpedm20/fbchat | fbchat/_client.py | Client.onReactionRemoved | def onReactionRemoved(
self,
mid=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody removes reaction from a message
:param mid: Message ID, that user reacted to
:param author_id: The ID of the person who removed reaction
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"{} removed reaction from {} message in {} ({})".format(
author_id, mid, thread_id, thread_type
)
) | python | def onReactionRemoved(
self,
mid=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody removes reaction from a message
:param mid: Message ID, that user reacted to
:param author_id: The ID of the person who removed reaction
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"{} removed reaction from {} message in {} ({})".format(
author_id, mid, thread_id, thread_type
)
) | [
"def",
"onReactionRemoved",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"msg",
"=",
"None",
",",
")",
":",
"log",
".",
"info",
"("... | Called when the client is listening, and somebody removes reaction from a message
:param mid: Message ID, that user reacted to
:param author_id: The ID of the person who removed reaction
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"removes",
"reaction",
"from",
"a",
"message"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3683-L3707 | train | 215,222 |
carpedm20/fbchat | fbchat/_client.py | Client.onBlock | def onBlock(
self, author_id=None, thread_id=None, thread_type=None, ts=None, msg=None
):
"""
Called when the client is listening, and somebody blocks client
:param author_id: The ID of the person who blocked
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"{} blocked {} ({}) thread".format(author_id, thread_id, thread_type.name)
) | python | def onBlock(
self, author_id=None, thread_id=None, thread_type=None, ts=None, msg=None
):
"""
Called when the client is listening, and somebody blocks client
:param author_id: The ID of the person who blocked
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"{} blocked {} ({}) thread".format(author_id, thread_id, thread_type.name)
) | [
"def",
"onBlock",
"(",
"self",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"msg",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"{} blocked {} ({}) thread\"",
".",
"for... | Called when the client is listening, and somebody blocks client
:param author_id: The ID of the person who blocked
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"blocks",
"client"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3709-L3724 | train | 215,223 |
carpedm20/fbchat | fbchat/_client.py | Client.onLiveLocation | def onLiveLocation(
self,
mid=None,
location=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
msg=None,
):
"""
Called when the client is listening and somebody sends live location info
:param mid: The action ID
:param location: Sent location info
:param author_id: The ID of the person who sent location info
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type location: models.LiveLocationAttachment
:type thread_type: models.ThreadType
"""
log.info(
"{} sent live location info in {} ({}) with latitude {} and longitude {}".format(
author_id, thread_id, thread_type, location.latitude, location.longitude
)
) | python | def onLiveLocation(
self,
mid=None,
location=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
msg=None,
):
"""
Called when the client is listening and somebody sends live location info
:param mid: The action ID
:param location: Sent location info
:param author_id: The ID of the person who sent location info
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type location: models.LiveLocationAttachment
:type thread_type: models.ThreadType
"""
log.info(
"{} sent live location info in {} ({}) with latitude {} and longitude {}".format(
author_id, thread_id, thread_type, location.latitude, location.longitude
)
) | [
"def",
"onLiveLocation",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"location",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"msg",
"=",
"None",
",",
")",
"... | Called when the client is listening and somebody sends live location info
:param mid: The action ID
:param location: Sent location info
:param author_id: The ID of the person who sent location info
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type location: models.LiveLocationAttachment
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"sends",
"live",
"location",
"info"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3743-L3770 | train | 215,224 |
carpedm20/fbchat | fbchat/_client.py | Client.onUserJoinedCall | def onUserJoinedCall(
self,
mid=None,
joined_id=None,
is_video_call=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody joins a group call
:param mid: The action ID
:param joined_id: The ID of the person who joined the call
:param is_video_call: True if it's video call
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"{} joined call in {} ({})".format(joined_id, thread_id, thread_type.name)
) | python | def onUserJoinedCall(
self,
mid=None,
joined_id=None,
is_video_call=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody joins a group call
:param mid: The action ID
:param joined_id: The ID of the person who joined the call
:param is_video_call: True if it's video call
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
"""
log.info(
"{} joined call in {} ({})".format(joined_id, thread_id, thread_type.name)
) | [
"def",
"onUserJoinedCall",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"joined_id",
"=",
"None",
",",
"is_video_call",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"metadata",
"=",
"None",
","... | Called when the client is listening, and somebody joins a group call
:param mid: The action ID
:param joined_id: The ID of the person who joined the call
:param is_video_call: True if it's video call
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"joins",
"a",
"group",
"call"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3836-L3862 | train | 215,225 |
carpedm20/fbchat | fbchat/_client.py | Client.onPollCreated | def onPollCreated(
self,
mid=None,
poll=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody creates a group poll
:param mid: The action ID
:param poll: Created poll
:param author_id: The ID of the person who created the poll
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type poll: models.Poll
:type thread_type: models.ThreadType
"""
log.info(
"{} created poll {} in {} ({})".format(
author_id, poll, thread_id, thread_type.name
)
) | python | def onPollCreated(
self,
mid=None,
poll=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody creates a group poll
:param mid: The action ID
:param poll: Created poll
:param author_id: The ID of the person who created the poll
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type poll: models.Poll
:type thread_type: models.ThreadType
"""
log.info(
"{} created poll {} in {} ({})".format(
author_id, poll, thread_id, thread_type.name
)
) | [
"def",
"onPollCreated",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"poll",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"msg",
... | Called when the client is listening, and somebody creates a group poll
:param mid: The action ID
:param poll: Created poll
:param author_id: The ID of the person who created the poll
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type poll: models.Poll
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"creates",
"a",
"group",
"poll"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3864-L3893 | train | 215,226 |
carpedm20/fbchat | fbchat/_client.py | Client.onPollVoted | def onPollVoted(
self,
mid=None,
poll=None,
added_options=None,
removed_options=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody votes in a group poll
:param mid: The action ID
:param poll: Poll, that user voted in
:param author_id: The ID of the person who voted in the poll
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type poll: models.Poll
:type thread_type: models.ThreadType
"""
log.info(
"{} voted in poll {} in {} ({})".format(
author_id, poll, thread_id, thread_type.name
)
) | python | def onPollVoted(
self,
mid=None,
poll=None,
added_options=None,
removed_options=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody votes in a group poll
:param mid: The action ID
:param poll: Poll, that user voted in
:param author_id: The ID of the person who voted in the poll
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type poll: models.Poll
:type thread_type: models.ThreadType
"""
log.info(
"{} voted in poll {} in {} ({})".format(
author_id, poll, thread_id, thread_type.name
)
) | [
"def",
"onPollVoted",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"poll",
"=",
"None",
",",
"added_options",
"=",
"None",
",",
"removed_options",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
... | Called when the client is listening, and somebody votes in a group poll
:param mid: The action ID
:param poll: Poll, that user voted in
:param author_id: The ID of the person who voted in the poll
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type poll: models.Poll
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"votes",
"in",
"a",
"group",
"poll"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3895-L3926 | train | 215,227 |
carpedm20/fbchat | fbchat/_client.py | Client.onPlanDeleted | def onPlanDeleted(
self,
mid=None,
plan=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody deletes a plan
:param mid: The action ID
:param plan: Deleted plan
:param author_id: The ID of the person who deleted the plan
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type thread_type: models.ThreadType
"""
log.info(
"{} deleted plan {} in {} ({})".format(
author_id, plan, thread_id, thread_type.name
)
) | python | def onPlanDeleted(
self,
mid=None,
plan=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody deletes a plan
:param mid: The action ID
:param plan: Deleted plan
:param author_id: The ID of the person who deleted the plan
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type thread_type: models.ThreadType
"""
log.info(
"{} deleted plan {} in {} ({})".format(
author_id, plan, thread_id, thread_type.name
)
) | [
"def",
"onPlanDeleted",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"plan",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"msg",
... | Called when the client is listening, and somebody deletes a plan
:param mid: The action ID
:param plan: Deleted plan
:param author_id: The ID of the person who deleted the plan
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"deletes",
"a",
"plan"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L4017-L4046 | train | 215,228 |
carpedm20/fbchat | fbchat/_client.py | Client.onPlanParticipation | def onPlanParticipation(
self,
mid=None,
plan=None,
take_part=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody takes part in a plan or not
:param mid: The action ID
:param plan: Plan
:param take_part: Whether the person takes part in the plan or not
:param author_id: The ID of the person who will participate in the plan or not
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type take_part: bool
:type thread_type: models.ThreadType
"""
if take_part:
log.info(
"{} will take part in {} in {} ({})".format(
author_id, plan, thread_id, thread_type.name
)
)
else:
log.info(
"{} won't take part in {} in {} ({})".format(
author_id, plan, thread_id, thread_type.name
)
) | python | def onPlanParticipation(
self,
mid=None,
plan=None,
take_part=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody takes part in a plan or not
:param mid: The action ID
:param plan: Plan
:param take_part: Whether the person takes part in the plan or not
:param author_id: The ID of the person who will participate in the plan or not
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type take_part: bool
:type thread_type: models.ThreadType
"""
if take_part:
log.info(
"{} will take part in {} in {} ({})".format(
author_id, plan, thread_id, thread_type.name
)
)
else:
log.info(
"{} won't take part in {} in {} ({})".format(
author_id, plan, thread_id, thread_type.name
)
) | [
"def",
"onPlanParticipation",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"plan",
"=",
"None",
",",
"take_part",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"... | Called when the client is listening, and somebody takes part in a plan or not
:param mid: The action ID
:param plan: Plan
:param take_part: Whether the person takes part in the plan or not
:param author_id: The ID of the person who will participate in the plan or not
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type take_part: bool
:type thread_type: models.ThreadType | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"takes",
"part",
"in",
"a",
"plan",
"or",
"not"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L4048-L4087 | train | 215,229 |
carpedm20/fbchat | fbchat/_graphql.py | graphql_queries_to_json | def graphql_queries_to_json(*queries):
"""
Queries should be a list of GraphQL objects
"""
rtn = {}
for i, query in enumerate(queries):
rtn["q{}".format(i)] = query.value
return json.dumps(rtn) | python | def graphql_queries_to_json(*queries):
"""
Queries should be a list of GraphQL objects
"""
rtn = {}
for i, query in enumerate(queries):
rtn["q{}".format(i)] = query.value
return json.dumps(rtn) | [
"def",
"graphql_queries_to_json",
"(",
"*",
"queries",
")",
":",
"rtn",
"=",
"{",
"}",
"for",
"i",
",",
"query",
"in",
"enumerate",
"(",
"queries",
")",
":",
"rtn",
"[",
"\"q{}\"",
".",
"format",
"(",
"i",
")",
"]",
"=",
"query",
".",
"value",
"ret... | Queries should be a list of GraphQL objects | [
"Queries",
"should",
"be",
"a",
"list",
"of",
"GraphQL",
"objects"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_graphql.py#L30-L37 | train | 215,230 |
jarun/Buku | bukuserver/server.py | get_tags | def get_tags():
"""get tags."""
tags = getattr(flask.g, 'bukudb', get_bukudb()).get_tag_all()
result = {
'tags': tags[0]
}
if request.path.startswith('/api/'):
res = jsonify(result)
else:
res = render_template('bukuserver/tags.html', result=result)
return res | python | def get_tags():
"""get tags."""
tags = getattr(flask.g, 'bukudb', get_bukudb()).get_tag_all()
result = {
'tags': tags[0]
}
if request.path.startswith('/api/'):
res = jsonify(result)
else:
res = render_template('bukuserver/tags.html', result=result)
return res | [
"def",
"get_tags",
"(",
")",
":",
"tags",
"=",
"getattr",
"(",
"flask",
".",
"g",
",",
"'bukudb'",
",",
"get_bukudb",
"(",
")",
")",
".",
"get_tag_all",
"(",
")",
"result",
"=",
"{",
"'tags'",
":",
"tags",
"[",
"0",
"]",
"}",
"if",
"request",
"."... | get tags. | [
"get",
"tags",
"."
] | 5f101363cf68f7666d4f5b28f0887ee07e916054 | https://github.com/jarun/Buku/blob/5f101363cf68f7666d4f5b28f0887ee07e916054/bukuserver/server.py#L42-L52 | train | 215,231 |
jarun/Buku | bukuserver/server.py | create_app | def create_app(config_filename=None):
"""create app."""
app = FlaskAPI(__name__)
per_page = int(os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE)))
per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE
app.config['BUKUSERVER_PER_PAGE'] = per_page
url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE)
if url_render_mode not in ('full', 'netloc'):
url_render_mode = views.DEFAULT_URL_RENDER_MODE
app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode
app.config['SECRET_KEY'] = os.getenv('BUKUSERVER_SECRET_KEY') or os.urandom(24)
app.config['BUKUSERVER_DB_FILE'] = os.getenv('BUKUSERVER_DB_FILE')
bukudb = BukuDb(dbfile=app.config['BUKUSERVER_DB_FILE'])
app.app_context().push()
setattr(flask.g, 'bukudb', bukudb)
@app.shell_context_processor
def shell_context():
"""Shell context definition."""
return {'app': app, 'bukudb': bukudb}
app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc # pylint: disable=no-member
Bootstrap(app)
admin = Admin(
app, name='Buku Server', template_mode='bootstrap3',
index_view=views.CustomAdminIndexView(
template='bukuserver/home.html', url='/'
)
)
# routing
# api
app.add_url_rule('/api/tags', 'get_tags', tag_list, methods=['GET'])
app.add_url_rule('/api/tags/<tag>', 'update_tag', tag_detail, methods=['GET', 'PUT'])
app.add_url_rule(
'/api/network_handle',
'networkk_handle',
network_handle_detail,
methods=['POST'])
app.add_url_rule('/api/bookmarks', 'bookmarks', bookmarks, methods=['GET', 'POST', 'DELETE'])
app.add_url_rule(
'/api/bookmarks/refresh',
'refresh_bookmarks',
refresh_bookmarks,
methods=['POST'])
app.add_url_rule(
'/api/bookmarks/<id>',
'bookmark_api',
bookmark_api,
methods=['GET', 'PUT', 'DELETE'])
app.add_url_rule(
'/api/bookmarks/<id>/refresh',
'refresh_bookmark',
refresh_bookmark,
methods=['POST'])
app.add_url_rule('/api/bookmarks/<id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET'])
app.add_url_rule('/api/bookmarks/<id>/long', 'get_long_url', get_long_url, methods=['GET'])
app.add_url_rule(
'/api/bookmarks/<starting_id>/<ending_id>',
'bookmark_range_operations', bookmark_range_operations, methods=['GET', 'PUT', 'DELETE'])
app.add_url_rule(
'/api/bookmarks/search',
'search_bookmarks',
search_bookmarks,
methods=['GET', 'DELETE'])
# non api
admin.add_view(views.BookmarkModelView(
bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode))
admin.add_view(views.TagModelView(
bukudb, 'Tags', page_size=per_page))
admin.add_view(views.StatisticView(
bukudb, 'Statistic', endpoint='statistic'))
return app | python | def create_app(config_filename=None):
"""create app."""
app = FlaskAPI(__name__)
per_page = int(os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE)))
per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE
app.config['BUKUSERVER_PER_PAGE'] = per_page
url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE)
if url_render_mode not in ('full', 'netloc'):
url_render_mode = views.DEFAULT_URL_RENDER_MODE
app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode
app.config['SECRET_KEY'] = os.getenv('BUKUSERVER_SECRET_KEY') or os.urandom(24)
app.config['BUKUSERVER_DB_FILE'] = os.getenv('BUKUSERVER_DB_FILE')
bukudb = BukuDb(dbfile=app.config['BUKUSERVER_DB_FILE'])
app.app_context().push()
setattr(flask.g, 'bukudb', bukudb)
@app.shell_context_processor
def shell_context():
"""Shell context definition."""
return {'app': app, 'bukudb': bukudb}
app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc # pylint: disable=no-member
Bootstrap(app)
admin = Admin(
app, name='Buku Server', template_mode='bootstrap3',
index_view=views.CustomAdminIndexView(
template='bukuserver/home.html', url='/'
)
)
# routing
# api
app.add_url_rule('/api/tags', 'get_tags', tag_list, methods=['GET'])
app.add_url_rule('/api/tags/<tag>', 'update_tag', tag_detail, methods=['GET', 'PUT'])
app.add_url_rule(
'/api/network_handle',
'networkk_handle',
network_handle_detail,
methods=['POST'])
app.add_url_rule('/api/bookmarks', 'bookmarks', bookmarks, methods=['GET', 'POST', 'DELETE'])
app.add_url_rule(
'/api/bookmarks/refresh',
'refresh_bookmarks',
refresh_bookmarks,
methods=['POST'])
app.add_url_rule(
'/api/bookmarks/<id>',
'bookmark_api',
bookmark_api,
methods=['GET', 'PUT', 'DELETE'])
app.add_url_rule(
'/api/bookmarks/<id>/refresh',
'refresh_bookmark',
refresh_bookmark,
methods=['POST'])
app.add_url_rule('/api/bookmarks/<id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET'])
app.add_url_rule('/api/bookmarks/<id>/long', 'get_long_url', get_long_url, methods=['GET'])
app.add_url_rule(
'/api/bookmarks/<starting_id>/<ending_id>',
'bookmark_range_operations', bookmark_range_operations, methods=['GET', 'PUT', 'DELETE'])
app.add_url_rule(
'/api/bookmarks/search',
'search_bookmarks',
search_bookmarks,
methods=['GET', 'DELETE'])
# non api
admin.add_view(views.BookmarkModelView(
bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode))
admin.add_view(views.TagModelView(
bukudb, 'Tags', page_size=per_page))
admin.add_view(views.StatisticView(
bukudb, 'Statistic', endpoint='statistic'))
return app | [
"def",
"create_app",
"(",
"config_filename",
"=",
"None",
")",
":",
"app",
"=",
"FlaskAPI",
"(",
"__name__",
")",
"per_page",
"=",
"int",
"(",
"os",
".",
"getenv",
"(",
"'BUKUSERVER_PER_PAGE'",
",",
"str",
"(",
"views",
".",
"DEFAULT_PER_PAGE",
")",
")",
... | create app. | [
"create",
"app",
"."
] | 5f101363cf68f7666d4f5b28f0887ee07e916054 | https://github.com/jarun/Buku/blob/5f101363cf68f7666d4f5b28f0887ee07e916054/bukuserver/server.py#L519-L591 | train | 215,232 |
jarun/Buku | bukuserver/views.py | CustomAdminIndexView.search | def search(self):
"redirect to bookmark search"
form = forms.HomeForm()
bbm_filter = bs_filters.BookmarkBukuFilter(
all_keywords=False, deep=form.deep.data, regex=form.regex.data)
op_text = bbm_filter.operation()
values_combi = sorted(itertools.product([True, False], repeat=3))
for idx, (all_keywords, deep, regex) in enumerate(values_combi):
if deep == form.deep.data and regex == form.regex.data and not all_keywords:
choosen_idx = idx
url_op_text = op_text.replace(', ', '_').replace(' ', ' ').replace(' ', '_')
key = ''.join(['flt', str(choosen_idx), '_buku_', url_op_text])
kwargs = {key: form.keyword.data}
url = url_for('bookmark.index_view', **kwargs)
return redirect(url) | python | def search(self):
"redirect to bookmark search"
form = forms.HomeForm()
bbm_filter = bs_filters.BookmarkBukuFilter(
all_keywords=False, deep=form.deep.data, regex=form.regex.data)
op_text = bbm_filter.operation()
values_combi = sorted(itertools.product([True, False], repeat=3))
for idx, (all_keywords, deep, regex) in enumerate(values_combi):
if deep == form.deep.data and regex == form.regex.data and not all_keywords:
choosen_idx = idx
url_op_text = op_text.replace(', ', '_').replace(' ', ' ').replace(' ', '_')
key = ''.join(['flt', str(choosen_idx), '_buku_', url_op_text])
kwargs = {key: form.keyword.data}
url = url_for('bookmark.index_view', **kwargs)
return redirect(url) | [
"def",
"search",
"(",
"self",
")",
":",
"form",
"=",
"forms",
".",
"HomeForm",
"(",
")",
"bbm_filter",
"=",
"bs_filters",
".",
"BookmarkBukuFilter",
"(",
"all_keywords",
"=",
"False",
",",
"deep",
"=",
"form",
".",
"deep",
".",
"data",
",",
"regex",
"=... | redirect to bookmark search | [
"redirect",
"to",
"bookmark",
"search"
] | 5f101363cf68f7666d4f5b28f0887ee07e916054 | https://github.com/jarun/Buku/blob/5f101363cf68f7666d4f5b28f0887ee07e916054/bukuserver/views.py#L38-L52 | train | 215,233 |
lepture/mistune | mistune.py | Renderer.autolink | def autolink(self, link, is_email=False):
"""Rendering a given link or email address.
:param link: link content or email address.
:param is_email: whether this is an email or not.
"""
text = link = escape_link(link)
if is_email:
link = 'mailto:%s' % link
return '<a href="%s">%s</a>' % (link, text) | python | def autolink(self, link, is_email=False):
"""Rendering a given link or email address.
:param link: link content or email address.
:param is_email: whether this is an email or not.
"""
text = link = escape_link(link)
if is_email:
link = 'mailto:%s' % link
return '<a href="%s">%s</a>' % (link, text) | [
"def",
"autolink",
"(",
"self",
",",
"link",
",",
"is_email",
"=",
"False",
")",
":",
"text",
"=",
"link",
"=",
"escape_link",
"(",
"link",
")",
"if",
"is_email",
":",
"link",
"=",
"'mailto:%s'",
"%",
"link",
"return",
"'<a href=\"%s\">%s</a>'",
"%",
"("... | Rendering a given link or email address.
:param link: link content or email address.
:param is_email: whether this is an email or not. | [
"Rendering",
"a",
"given",
"link",
"or",
"email",
"address",
"."
] | 449c2b52961c30665ccba6a822652ec7d0e15938 | https://github.com/lepture/mistune/blob/449c2b52961c30665ccba6a822652ec7d0e15938/mistune.py#L871-L880 | train | 215,234 |
getsentry/sentry-python | sentry_sdk/hub.py | init | def init(*args, **kwargs):
"""Initializes the SDK and optionally integrations.
This takes the same arguments as the client constructor.
"""
global _initial_client
client = Client(*args, **kwargs)
Hub.current.bind_client(client)
rv = _InitGuard(client)
if client is not None:
_initial_client = weakref.ref(client)
return rv | python | def init(*args, **kwargs):
"""Initializes the SDK and optionally integrations.
This takes the same arguments as the client constructor.
"""
global _initial_client
client = Client(*args, **kwargs)
Hub.current.bind_client(client)
rv = _InitGuard(client)
if client is not None:
_initial_client = weakref.ref(client)
return rv | [
"def",
"init",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_initial_client",
"client",
"=",
"Client",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"Hub",
".",
"current",
".",
"bind_client",
"(",
"client",
")",
"rv",
"=",
"_In... | Initializes the SDK and optionally integrations.
This takes the same arguments as the client constructor. | [
"Initializes",
"the",
"SDK",
"and",
"optionally",
"integrations",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L61-L72 | train | 215,235 |
getsentry/sentry-python | sentry_sdk/hub.py | HubMeta.current | def current(self):
# type: () -> Hub
"""Returns the current instance of the hub."""
rv = _local.get(None)
if rv is None:
rv = Hub(GLOBAL_HUB)
_local.set(rv)
return rv | python | def current(self):
# type: () -> Hub
"""Returns the current instance of the hub."""
rv = _local.get(None)
if rv is None:
rv = Hub(GLOBAL_HUB)
_local.set(rv)
return rv | [
"def",
"current",
"(",
"self",
")",
":",
"# type: () -> Hub",
"rv",
"=",
"_local",
".",
"get",
"(",
"None",
")",
"if",
"rv",
"is",
"None",
":",
"rv",
"=",
"Hub",
"(",
"GLOBAL_HUB",
")",
"_local",
".",
"set",
"(",
"rv",
")",
"return",
"rv"
] | Returns the current instance of the hub. | [
"Returns",
"the",
"current",
"instance",
"of",
"the",
"hub",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L77-L84 | train | 215,236 |
getsentry/sentry-python | sentry_sdk/hub.py | Hub.get_integration | def get_integration(self, name_or_class):
# type: (Union[str, Integration]) -> Any
"""Returns the integration for this hub by name or class. If there
is no client bound or the client does not have that integration
then `None` is returned.
If the return value is not `None` the hub is guaranteed to have a
client attached.
"""
if isinstance(name_or_class, str):
integration_name = name_or_class
elif name_or_class.identifier is not None:
integration_name = name_or_class.identifier
else:
raise ValueError("Integration has no name")
client = self._stack[-1][0]
if client is not None:
rv = client.integrations.get(integration_name)
if rv is not None:
return rv
initial_client = _initial_client
if initial_client is not None:
initial_client = initial_client()
if (
initial_client is not None
and initial_client is not client
and initial_client.integrations.get(name_or_class) is not None
):
warning = (
"Integration %r attempted to run but it was only "
"enabled on init() but not the client that "
"was bound to the current flow. Earlier versions of "
"the SDK would consider these integrations enabled but "
"this is no longer the case." % (name_or_class,)
)
warn(Warning(warning), stacklevel=3)
logger.warning(warning) | python | def get_integration(self, name_or_class):
# type: (Union[str, Integration]) -> Any
"""Returns the integration for this hub by name or class. If there
is no client bound or the client does not have that integration
then `None` is returned.
If the return value is not `None` the hub is guaranteed to have a
client attached.
"""
if isinstance(name_or_class, str):
integration_name = name_or_class
elif name_or_class.identifier is not None:
integration_name = name_or_class.identifier
else:
raise ValueError("Integration has no name")
client = self._stack[-1][0]
if client is not None:
rv = client.integrations.get(integration_name)
if rv is not None:
return rv
initial_client = _initial_client
if initial_client is not None:
initial_client = initial_client()
if (
initial_client is not None
and initial_client is not client
and initial_client.integrations.get(name_or_class) is not None
):
warning = (
"Integration %r attempted to run but it was only "
"enabled on init() but not the client that "
"was bound to the current flow. Earlier versions of "
"the SDK would consider these integrations enabled but "
"this is no longer the case." % (name_or_class,)
)
warn(Warning(warning), stacklevel=3)
logger.warning(warning) | [
"def",
"get_integration",
"(",
"self",
",",
"name_or_class",
")",
":",
"# type: (Union[str, Integration]) -> Any",
"if",
"isinstance",
"(",
"name_or_class",
",",
"str",
")",
":",
"integration_name",
"=",
"name_or_class",
"elif",
"name_or_class",
".",
"identifier",
"is... | Returns the integration for this hub by name or class. If there
is no client bound or the client does not have that integration
then `None` is returned.
If the return value is not `None` the hub is guaranteed to have a
client attached. | [
"Returns",
"the",
"integration",
"for",
"this",
"hub",
"by",
"name",
"or",
"class",
".",
"If",
"there",
"is",
"no",
"client",
"bound",
"or",
"the",
"client",
"does",
"not",
"have",
"that",
"integration",
"then",
"None",
"is",
"returned",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L196-L235 | train | 215,237 |
getsentry/sentry-python | sentry_sdk/hub.py | Hub.bind_client | def bind_client(self, new):
"""Binds a new client to the hub."""
top = self._stack[-1]
self._stack[-1] = (new, top[1]) | python | def bind_client(self, new):
"""Binds a new client to the hub."""
top = self._stack[-1]
self._stack[-1] = (new, top[1]) | [
"def",
"bind_client",
"(",
"self",
",",
"new",
")",
":",
"top",
"=",
"self",
".",
"_stack",
"[",
"-",
"1",
"]",
"self",
".",
"_stack",
"[",
"-",
"1",
"]",
"=",
"(",
"new",
",",
"top",
"[",
"1",
"]",
")"
] | Binds a new client to the hub. | [
"Binds",
"a",
"new",
"client",
"to",
"the",
"hub",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L248-L251 | train | 215,238 |
getsentry/sentry-python | sentry_sdk/hub.py | Hub.capture_event | def capture_event(self, event, hint=None):
# type: (Dict[str, Any], Dict[str, Any]) -> Optional[str]
"""Captures an event. The return value is the ID of the event.
The event is a dictionary following the Sentry v7/v8 protocol
specification. Optionally an event hint dict can be passed that
is used by processors to extract additional information from it.
Typically the event hint object would contain exception information.
"""
client, scope = self._stack[-1]
if client is not None:
rv = client.capture_event(event, hint, scope)
if rv is not None:
self._last_event_id = rv
return rv
return None | python | def capture_event(self, event, hint=None):
# type: (Dict[str, Any], Dict[str, Any]) -> Optional[str]
"""Captures an event. The return value is the ID of the event.
The event is a dictionary following the Sentry v7/v8 protocol
specification. Optionally an event hint dict can be passed that
is used by processors to extract additional information from it.
Typically the event hint object would contain exception information.
"""
client, scope = self._stack[-1]
if client is not None:
rv = client.capture_event(event, hint, scope)
if rv is not None:
self._last_event_id = rv
return rv
return None | [
"def",
"capture_event",
"(",
"self",
",",
"event",
",",
"hint",
"=",
"None",
")",
":",
"# type: (Dict[str, Any], Dict[str, Any]) -> Optional[str]",
"client",
",",
"scope",
"=",
"self",
".",
"_stack",
"[",
"-",
"1",
"]",
"if",
"client",
"is",
"not",
"None",
"... | Captures an event. The return value is the ID of the event.
The event is a dictionary following the Sentry v7/v8 protocol
specification. Optionally an event hint dict can be passed that
is used by processors to extract additional information from it.
Typically the event hint object would contain exception information. | [
"Captures",
"an",
"event",
".",
"The",
"return",
"value",
"is",
"the",
"ID",
"of",
"the",
"event",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L253-L268 | train | 215,239 |
getsentry/sentry-python | sentry_sdk/hub.py | Hub.capture_message | def capture_message(self, message, level=None):
# type: (str, Optional[Any]) -> Optional[str]
"""Captures a message. The message is just a string. If no level
is provided the default level is `info`.
"""
if self.client is None:
return None
if level is None:
level = "info"
return self.capture_event({"message": message, "level": level}) | python | def capture_message(self, message, level=None):
# type: (str, Optional[Any]) -> Optional[str]
"""Captures a message. The message is just a string. If no level
is provided the default level is `info`.
"""
if self.client is None:
return None
if level is None:
level = "info"
return self.capture_event({"message": message, "level": level}) | [
"def",
"capture_message",
"(",
"self",
",",
"message",
",",
"level",
"=",
"None",
")",
":",
"# type: (str, Optional[Any]) -> Optional[str]",
"if",
"self",
".",
"client",
"is",
"None",
":",
"return",
"None",
"if",
"level",
"is",
"None",
":",
"level",
"=",
"\"... | Captures a message. The message is just a string. If no level
is provided the default level is `info`. | [
"Captures",
"a",
"message",
".",
"The",
"message",
"is",
"just",
"a",
"string",
".",
"If",
"no",
"level",
"is",
"provided",
"the",
"default",
"level",
"is",
"info",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L270-L279 | train | 215,240 |
getsentry/sentry-python | sentry_sdk/hub.py | Hub.capture_exception | def capture_exception(self, error=None):
# type: (Optional[BaseException]) -> Optional[str]
"""Captures an exception.
The argument passed can be `None` in which case the last exception
will be reported, otherwise an exception object or an `exc_info`
tuple.
"""
client = self.client
if client is None:
return None
if error is None:
exc_info = sys.exc_info()
else:
exc_info = exc_info_from_error(error)
event, hint = event_from_exception(exc_info, client_options=client.options)
try:
return self.capture_event(event, hint=hint)
except Exception:
self._capture_internal_exception(sys.exc_info())
return None | python | def capture_exception(self, error=None):
# type: (Optional[BaseException]) -> Optional[str]
"""Captures an exception.
The argument passed can be `None` in which case the last exception
will be reported, otherwise an exception object or an `exc_info`
tuple.
"""
client = self.client
if client is None:
return None
if error is None:
exc_info = sys.exc_info()
else:
exc_info = exc_info_from_error(error)
event, hint = event_from_exception(exc_info, client_options=client.options)
try:
return self.capture_event(event, hint=hint)
except Exception:
self._capture_internal_exception(sys.exc_info())
return None | [
"def",
"capture_exception",
"(",
"self",
",",
"error",
"=",
"None",
")",
":",
"# type: (Optional[BaseException]) -> Optional[str]",
"client",
"=",
"self",
".",
"client",
"if",
"client",
"is",
"None",
":",
"return",
"None",
"if",
"error",
"is",
"None",
":",
"ex... | Captures an exception.
The argument passed can be `None` in which case the last exception
will be reported, otherwise an exception object or an `exc_info`
tuple. | [
"Captures",
"an",
"exception",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L281-L303 | train | 215,241 |
getsentry/sentry-python | sentry_sdk/hub.py | Hub.push_scope | def push_scope(self, callback=None): # noqa
"""Pushes a new layer on the scope stack. Returns a context manager
that should be used to pop the scope again. Alternatively a callback
can be provided that is executed in the context of the scope.
"""
if callback is not None:
with self.push_scope() as scope:
callback(scope)
return None
client, scope = self._stack[-1]
new_layer = (client, copy.copy(scope))
self._stack.append(new_layer)
return _ScopeManager(self) | python | def push_scope(self, callback=None): # noqa
"""Pushes a new layer on the scope stack. Returns a context manager
that should be used to pop the scope again. Alternatively a callback
can be provided that is executed in the context of the scope.
"""
if callback is not None:
with self.push_scope() as scope:
callback(scope)
return None
client, scope = self._stack[-1]
new_layer = (client, copy.copy(scope))
self._stack.append(new_layer)
return _ScopeManager(self) | [
"def",
"push_scope",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"# noqa",
"if",
"callback",
"is",
"not",
"None",
":",
"with",
"self",
".",
"push_scope",
"(",
")",
"as",
"scope",
":",
"callback",
"(",
"scope",
")",
"return",
"None",
"client",
... | Pushes a new layer on the scope stack. Returns a context manager
that should be used to pop the scope again. Alternatively a callback
can be provided that is executed in the context of the scope. | [
"Pushes",
"a",
"new",
"layer",
"on",
"the",
"scope",
"stack",
".",
"Returns",
"a",
"context",
"manager",
"that",
"should",
"be",
"used",
"to",
"pop",
"the",
"scope",
"again",
".",
"Alternatively",
"a",
"callback",
"can",
"be",
"provided",
"that",
"is",
"... | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L357-L372 | train | 215,242 |
getsentry/sentry-python | sentry_sdk/hub.py | Hub.configure_scope | def configure_scope(self, callback=None): # noqa
"""Reconfigures the scope."""
client, scope = self._stack[-1]
if callback is not None:
if client is not None:
callback(scope)
return None
@contextmanager
def inner():
if client is not None:
yield scope
else:
yield Scope()
return inner() | python | def configure_scope(self, callback=None): # noqa
"""Reconfigures the scope."""
client, scope = self._stack[-1]
if callback is not None:
if client is not None:
callback(scope)
return None
@contextmanager
def inner():
if client is not None:
yield scope
else:
yield Scope()
return inner() | [
"def",
"configure_scope",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"# noqa",
"client",
",",
"scope",
"=",
"self",
".",
"_stack",
"[",
"-",
"1",
"]",
"if",
"callback",
"is",
"not",
"None",
":",
"if",
"client",
"is",
"not",
"None",
":",
"... | Reconfigures the scope. | [
"Reconfigures",
"the",
"scope",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L393-L410 | train | 215,243 |
getsentry/sentry-python | sentry_sdk/hub.py | Hub.flush | def flush(self, timeout=None, callback=None):
"""Alias for self.client.flush"""
client, scope = self._stack[-1]
if client is not None:
return client.flush(timeout=timeout, callback=callback) | python | def flush(self, timeout=None, callback=None):
"""Alias for self.client.flush"""
client, scope = self._stack[-1]
if client is not None:
return client.flush(timeout=timeout, callback=callback) | [
"def",
"flush",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"client",
",",
"scope",
"=",
"self",
".",
"_stack",
"[",
"-",
"1",
"]",
"if",
"client",
"is",
"not",
"None",
":",
"return",
"client",
".",
"flush",
... | Alias for self.client.flush | [
"Alias",
"for",
"self",
".",
"client",
".",
"flush"
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L412-L416 | train | 215,244 |
getsentry/sentry-python | sentry_sdk/client.py | Client.capture_event | def capture_event(self, event, hint=None, scope=None):
# type: (Dict[str, Any], Any, Scope) -> Optional[str]
"""Captures an event.
This takes the ready made event and an optoinal hint and scope. The
hint is internally used to further customize the representation of the
error. When provided it's a dictionary of optional information such
as exception info.
If the transport is not set nothing happens, otherwise the return
value of this function will be the ID of the captured event.
"""
if self.transport is None:
return None
if hint is None:
hint = {}
rv = event.get("event_id")
if rv is None:
event["event_id"] = rv = uuid.uuid4().hex
if not self._should_capture(event, hint, scope):
return None
event = self._prepare_event(event, hint, scope) # type: ignore
if event is None:
return None
self.transport.capture_event(event)
return rv | python | def capture_event(self, event, hint=None, scope=None):
# type: (Dict[str, Any], Any, Scope) -> Optional[str]
"""Captures an event.
This takes the ready made event and an optoinal hint and scope. The
hint is internally used to further customize the representation of the
error. When provided it's a dictionary of optional information such
as exception info.
If the transport is not set nothing happens, otherwise the return
value of this function will be the ID of the captured event.
"""
if self.transport is None:
return None
if hint is None:
hint = {}
rv = event.get("event_id")
if rv is None:
event["event_id"] = rv = uuid.uuid4().hex
if not self._should_capture(event, hint, scope):
return None
event = self._prepare_event(event, hint, scope) # type: ignore
if event is None:
return None
self.transport.capture_event(event)
return rv | [
"def",
"capture_event",
"(",
"self",
",",
"event",
",",
"hint",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"# type: (Dict[str, Any], Any, Scope) -> Optional[str]",
"if",
"self",
".",
"transport",
"is",
"None",
":",
"return",
"None",
"if",
"hint",
"is",
... | Captures an event.
This takes the ready made event and an optoinal hint and scope. The
hint is internally used to further customize the representation of the
error. When provided it's a dictionary of optional information such
as exception info.
If the transport is not set nothing happens, otherwise the return
value of this function will be the ID of the captured event. | [
"Captures",
"an",
"event",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/client.py#L206-L231 | train | 215,245 |
getsentry/sentry-python | sentry_sdk/client.py | Client.flush | def flush(self, timeout=None, callback=None):
"""
Wait `timeout` seconds for the current events to be sent. If no
`timeout` is provided, the `shutdown_timeout` option value is used.
The `callback` is invoked with two arguments: the number of pending
events and the configured timeout. For instance the default atexit
integration will use this to render out a message on stderr.
"""
if self.transport is not None:
if timeout is None:
timeout = self.options["shutdown_timeout"]
self.transport.flush(timeout=timeout, callback=callback) | python | def flush(self, timeout=None, callback=None):
"""
Wait `timeout` seconds for the current events to be sent. If no
`timeout` is provided, the `shutdown_timeout` option value is used.
The `callback` is invoked with two arguments: the number of pending
events and the configured timeout. For instance the default atexit
integration will use this to render out a message on stderr.
"""
if self.transport is not None:
if timeout is None:
timeout = self.options["shutdown_timeout"]
self.transport.flush(timeout=timeout, callback=callback) | [
"def",
"flush",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"if",
"self",
".",
"transport",
"is",
"not",
"None",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"self",
".",
"options",
"[",
"\"shutdown_t... | Wait `timeout` seconds for the current events to be sent. If no
`timeout` is provided, the `shutdown_timeout` option value is used.
The `callback` is invoked with two arguments: the number of pending
events and the configured timeout. For instance the default atexit
integration will use this to render out a message on stderr. | [
"Wait",
"timeout",
"seconds",
"for",
"the",
"current",
"events",
"to",
"be",
"sent",
".",
"If",
"no",
"timeout",
"is",
"provided",
"the",
"shutdown_timeout",
"option",
"value",
"is",
"used",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/client.py#L243-L255 | train | 215,246 |
getsentry/sentry-python | sentry_sdk/integrations/__init__.py | setup_integrations | def setup_integrations(integrations, with_defaults=True):
# type: (List[Integration], bool) -> Dict[str, Integration]
"""Given a list of integration instances this installs them all. When
`with_defaults` is set to `True` then all default integrations are added
unless they were already provided before.
"""
integrations = dict(
(integration.identifier, integration) for integration in integrations or ()
)
logger.debug("Setting up integrations (with default = %s)", with_defaults)
if with_defaults:
for integration_cls in iter_default_integrations():
if integration_cls.identifier not in integrations:
instance = integration_cls()
integrations[instance.identifier] = instance
for identifier, integration in iteritems(integrations):
with _installer_lock:
if identifier not in _installed_integrations:
logger.debug(
"Setting up previously not enabled integration %s", identifier
)
try:
type(integration).setup_once()
except NotImplementedError:
if getattr(integration, "install", None) is not None:
logger.warn(
"Integration %s: The install method is "
"deprecated. Use `setup_once`.",
identifier,
)
integration.install()
else:
raise
_installed_integrations.add(identifier)
for identifier in integrations:
logger.debug("Enabling integration %s", identifier)
return integrations | python | def setup_integrations(integrations, with_defaults=True):
# type: (List[Integration], bool) -> Dict[str, Integration]
"""Given a list of integration instances this installs them all. When
`with_defaults` is set to `True` then all default integrations are added
unless they were already provided before.
"""
integrations = dict(
(integration.identifier, integration) for integration in integrations or ()
)
logger.debug("Setting up integrations (with default = %s)", with_defaults)
if with_defaults:
for integration_cls in iter_default_integrations():
if integration_cls.identifier not in integrations:
instance = integration_cls()
integrations[instance.identifier] = instance
for identifier, integration in iteritems(integrations):
with _installer_lock:
if identifier not in _installed_integrations:
logger.debug(
"Setting up previously not enabled integration %s", identifier
)
try:
type(integration).setup_once()
except NotImplementedError:
if getattr(integration, "install", None) is not None:
logger.warn(
"Integration %s: The install method is "
"deprecated. Use `setup_once`.",
identifier,
)
integration.install()
else:
raise
_installed_integrations.add(identifier)
for identifier in integrations:
logger.debug("Enabling integration %s", identifier)
return integrations | [
"def",
"setup_integrations",
"(",
"integrations",
",",
"with_defaults",
"=",
"True",
")",
":",
"# type: (List[Integration], bool) -> Dict[str, Integration]",
"integrations",
"=",
"dict",
"(",
"(",
"integration",
".",
"identifier",
",",
"integration",
")",
"for",
"integr... | Given a list of integration instances this installs them all. When
`with_defaults` is set to `True` then all default integrations are added
unless they were already provided before. | [
"Given",
"a",
"list",
"of",
"integration",
"instances",
"this",
"installs",
"them",
"all",
".",
"When",
"with_defaults",
"is",
"set",
"to",
"True",
"then",
"all",
"default",
"integrations",
"are",
"added",
"unless",
"they",
"were",
"already",
"provided",
"befo... | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/__init__.py#L57-L98 | train | 215,247 |
getsentry/sentry-python | sentry_sdk/scope.py | Scope.clear | def clear(self):
# type: () -> None
"""Clears the entire scope."""
self._level = None
self._fingerprint = None
self._transaction = None
self._user = None
self._tags = {} # type: Dict[str, Any]
self._contexts = {} # type: Dict[str, Dict]
self._extras = {} # type: Dict[str, Any]
self.clear_breadcrumbs()
self._should_capture = True
self._span = None | python | def clear(self):
# type: () -> None
"""Clears the entire scope."""
self._level = None
self._fingerprint = None
self._transaction = None
self._user = None
self._tags = {} # type: Dict[str, Any]
self._contexts = {} # type: Dict[str, Dict]
self._extras = {} # type: Dict[str, Any]
self.clear_breadcrumbs()
self._should_capture = True
self._span = None | [
"def",
"clear",
"(",
"self",
")",
":",
"# type: () -> None",
"self",
".",
"_level",
"=",
"None",
"self",
".",
"_fingerprint",
"=",
"None",
"self",
".",
"_transaction",
"=",
"None",
"self",
".",
"_user",
"=",
"None",
"self",
".",
"_tags",
"=",
"{",
"}",... | Clears the entire scope. | [
"Clears",
"the",
"entire",
"scope",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/scope.py#L120-L135 | train | 215,248 |
getsentry/sentry-python | sentry_sdk/scope.py | Scope.add_error_processor | def add_error_processor(self, func, cls=None):
# type: (Callable, Optional[type]) -> None
""""Register a scope local error processor on the scope.
The error processor works similar to an event processor but is
invoked with the original exception info triple as second argument.
"""
if cls is not None:
real_func = func
def func(event, exc_info):
try:
is_inst = isinstance(exc_info[1], cls)
except Exception:
is_inst = False
if is_inst:
return real_func(event, exc_info)
return event
self._error_processors.append(func) | python | def add_error_processor(self, func, cls=None):
# type: (Callable, Optional[type]) -> None
""""Register a scope local error processor on the scope.
The error processor works similar to an event processor but is
invoked with the original exception info triple as second argument.
"""
if cls is not None:
real_func = func
def func(event, exc_info):
try:
is_inst = isinstance(exc_info[1], cls)
except Exception:
is_inst = False
if is_inst:
return real_func(event, exc_info)
return event
self._error_processors.append(func) | [
"def",
"add_error_processor",
"(",
"self",
",",
"func",
",",
"cls",
"=",
"None",
")",
":",
"# type: (Callable, Optional[type]) -> None",
"if",
"cls",
"is",
"not",
"None",
":",
"real_func",
"=",
"func",
"def",
"func",
"(",
"event",
",",
"exc_info",
")",
":",
... | Register a scope local error processor on the scope.
The error processor works similar to an event processor but is
invoked with the original exception info triple as second argument. | [
"Register",
"a",
"scope",
"local",
"error",
"processor",
"on",
"the",
"scope",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/scope.py#L150-L169 | train | 215,249 |
getsentry/sentry-python | sentry_sdk/scope.py | Scope.apply_to_event | def apply_to_event(self, event, hint=None):
# type: (Dict[str, Any], Dict[str, Any]) -> Optional[Dict[str, Any]]
"""Applies the information contained on the scope to the given event."""
def _drop(event, cause, ty):
# type: (Dict[str, Any], Callable, str) -> Optional[Any]
logger.info("%s (%s) dropped event (%s)", ty, cause, event)
return None
if self._level is not None:
event["level"] = self._level
event.setdefault("breadcrumbs", []).extend(self._breadcrumbs)
if event.get("user") is None and self._user is not None:
event["user"] = self._user
if event.get("transaction") is None and self._transaction is not None:
event["transaction"] = self._transaction
if event.get("fingerprint") is None and self._fingerprint is not None:
event["fingerprint"] = self._fingerprint
if self._extras:
event.setdefault("extra", {}).update(object_to_json(self._extras))
if self._tags:
event.setdefault("tags", {}).update(self._tags)
if self._contexts:
event.setdefault("contexts", {}).update(self._contexts)
if self._span is not None:
event.setdefault("contexts", {})["trace"] = {
"trace_id": self._span.trace_id,
"span_id": self._span.span_id,
}
exc_info = hint.get("exc_info") if hint is not None else None
if exc_info is not None:
for processor in self._error_processors:
new_event = processor(event, exc_info)
if new_event is None:
return _drop(event, processor, "error processor")
event = new_event
for processor in chain(global_event_processors, self._event_processors):
new_event = event
with capture_internal_exceptions():
new_event = processor(event, hint)
if new_event is None:
return _drop(event, processor, "event processor")
event = new_event
return event | python | def apply_to_event(self, event, hint=None):
# type: (Dict[str, Any], Dict[str, Any]) -> Optional[Dict[str, Any]]
"""Applies the information contained on the scope to the given event."""
def _drop(event, cause, ty):
# type: (Dict[str, Any], Callable, str) -> Optional[Any]
logger.info("%s (%s) dropped event (%s)", ty, cause, event)
return None
if self._level is not None:
event["level"] = self._level
event.setdefault("breadcrumbs", []).extend(self._breadcrumbs)
if event.get("user") is None and self._user is not None:
event["user"] = self._user
if event.get("transaction") is None and self._transaction is not None:
event["transaction"] = self._transaction
if event.get("fingerprint") is None and self._fingerprint is not None:
event["fingerprint"] = self._fingerprint
if self._extras:
event.setdefault("extra", {}).update(object_to_json(self._extras))
if self._tags:
event.setdefault("tags", {}).update(self._tags)
if self._contexts:
event.setdefault("contexts", {}).update(self._contexts)
if self._span is not None:
event.setdefault("contexts", {})["trace"] = {
"trace_id": self._span.trace_id,
"span_id": self._span.span_id,
}
exc_info = hint.get("exc_info") if hint is not None else None
if exc_info is not None:
for processor in self._error_processors:
new_event = processor(event, exc_info)
if new_event is None:
return _drop(event, processor, "error processor")
event = new_event
for processor in chain(global_event_processors, self._event_processors):
new_event = event
with capture_internal_exceptions():
new_event = processor(event, hint)
if new_event is None:
return _drop(event, processor, "event processor")
event = new_event
return event | [
"def",
"apply_to_event",
"(",
"self",
",",
"event",
",",
"hint",
"=",
"None",
")",
":",
"# type: (Dict[str, Any], Dict[str, Any]) -> Optional[Dict[str, Any]]",
"def",
"_drop",
"(",
"event",
",",
"cause",
",",
"ty",
")",
":",
"# type: (Dict[str, Any], Callable, str) -> O... | Applies the information contained on the scope to the given event. | [
"Applies",
"the",
"information",
"contained",
"on",
"the",
"scope",
"to",
"the",
"given",
"event",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/scope.py#L172-L225 | train | 215,250 |
getsentry/sentry-python | sentry_sdk/integrations/atexit.py | default_callback | def default_callback(pending, timeout):
"""This is the default shutdown callback that is set on the options.
It prints out a message to stderr that informs the user that some events
are still pending and the process is waiting for them to flush out.
"""
def echo(msg):
sys.stderr.write(msg + "\n")
echo("Sentry is attempting to send %i pending error messages" % pending)
echo("Waiting up to %s seconds" % timeout)
echo("Press Ctrl-%s to quit" % (os.name == "nt" and "Break" or "C"))
sys.stderr.flush() | python | def default_callback(pending, timeout):
"""This is the default shutdown callback that is set on the options.
It prints out a message to stderr that informs the user that some events
are still pending and the process is waiting for them to flush out.
"""
def echo(msg):
sys.stderr.write(msg + "\n")
echo("Sentry is attempting to send %i pending error messages" % pending)
echo("Waiting up to %s seconds" % timeout)
echo("Press Ctrl-%s to quit" % (os.name == "nt" and "Break" or "C"))
sys.stderr.flush() | [
"def",
"default_callback",
"(",
"pending",
",",
"timeout",
")",
":",
"def",
"echo",
"(",
"msg",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"msg",
"+",
"\"\\n\"",
")",
"echo",
"(",
"\"Sentry is attempting to send %i pending error messages\"",
"%",
"pend... | This is the default shutdown callback that is set on the options.
It prints out a message to stderr that informs the user that some events
are still pending and the process is waiting for them to flush out. | [
"This",
"is",
"the",
"default",
"shutdown",
"callback",
"that",
"is",
"set",
"on",
"the",
"options",
".",
"It",
"prints",
"out",
"a",
"message",
"to",
"stderr",
"that",
"informs",
"the",
"user",
"that",
"some",
"events",
"are",
"still",
"pending",
"and",
... | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/atexit.py#L16-L28 | train | 215,251 |
getsentry/sentry-python | sentry_sdk/integrations/wsgi.py | get_host | def get_host(environ):
# type: (Dict[str, str]) -> str
"""Return the host for the given WSGI environment. Yanked from Werkzeug."""
if environ.get("HTTP_HOST"):
rv = environ["HTTP_HOST"]
if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"):
rv = rv[:-3]
elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"):
rv = rv[:-4]
elif environ.get("SERVER_NAME"):
rv = environ["SERVER_NAME"]
if (environ["wsgi.url_scheme"], environ["SERVER_PORT"]) not in (
("https", "443"),
("http", "80"),
):
rv += ":" + environ["SERVER_PORT"]
else:
# In spite of the WSGI spec, SERVER_NAME might not be present.
rv = "unknown"
return rv | python | def get_host(environ):
# type: (Dict[str, str]) -> str
"""Return the host for the given WSGI environment. Yanked from Werkzeug."""
if environ.get("HTTP_HOST"):
rv = environ["HTTP_HOST"]
if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"):
rv = rv[:-3]
elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"):
rv = rv[:-4]
elif environ.get("SERVER_NAME"):
rv = environ["SERVER_NAME"]
if (environ["wsgi.url_scheme"], environ["SERVER_PORT"]) not in (
("https", "443"),
("http", "80"),
):
rv += ":" + environ["SERVER_PORT"]
else:
# In spite of the WSGI spec, SERVER_NAME might not be present.
rv = "unknown"
return rv | [
"def",
"get_host",
"(",
"environ",
")",
":",
"# type: (Dict[str, str]) -> str",
"if",
"environ",
".",
"get",
"(",
"\"HTTP_HOST\"",
")",
":",
"rv",
"=",
"environ",
"[",
"\"HTTP_HOST\"",
"]",
"if",
"environ",
"[",
"\"wsgi.url_scheme\"",
"]",
"==",
"\"http\"",
"a... | Return the host for the given WSGI environment. Yanked from Werkzeug. | [
"Return",
"the",
"host",
"for",
"the",
"given",
"WSGI",
"environment",
".",
"Yanked",
"from",
"Werkzeug",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/wsgi.py#L35-L55 | train | 215,252 |
getsentry/sentry-python | sentry_sdk/integrations/wsgi.py | get_request_url | def get_request_url(environ):
# type: (Dict[str, str]) -> str
"""Return the absolute URL without query string for the given WSGI
environment."""
return "%s://%s/%s" % (
environ.get("wsgi.url_scheme"),
get_host(environ),
wsgi_decoding_dance(environ.get("PATH_INFO") or "").lstrip("/"),
) | python | def get_request_url(environ):
# type: (Dict[str, str]) -> str
"""Return the absolute URL without query string for the given WSGI
environment."""
return "%s://%s/%s" % (
environ.get("wsgi.url_scheme"),
get_host(environ),
wsgi_decoding_dance(environ.get("PATH_INFO") or "").lstrip("/"),
) | [
"def",
"get_request_url",
"(",
"environ",
")",
":",
"# type: (Dict[str, str]) -> str",
"return",
"\"%s://%s/%s\"",
"%",
"(",
"environ",
".",
"get",
"(",
"\"wsgi.url_scheme\"",
")",
",",
"get_host",
"(",
"environ",
")",
",",
"wsgi_decoding_dance",
"(",
"environ",
"... | Return the absolute URL without query string for the given WSGI
environment. | [
"Return",
"the",
"absolute",
"URL",
"without",
"query",
"string",
"for",
"the",
"given",
"WSGI",
"environment",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/wsgi.py#L58-L66 | train | 215,253 |
getsentry/sentry-python | sentry_sdk/integrations/wsgi.py | _get_environ | def _get_environ(environ):
# type: (Dict[str, str]) -> Iterator[Tuple[str, str]]
"""
Returns our whitelisted environment variables.
"""
keys = ["SERVER_NAME", "SERVER_PORT"]
if _should_send_default_pii():
# Add all three headers here to make debugging of proxy setup easier.
keys += ["REMOTE_ADDR", "HTTP_X_FORWARDED_FOR", "HTTP_X_REAL_IP"]
for key in keys:
if key in environ:
yield key, environ[key] | python | def _get_environ(environ):
# type: (Dict[str, str]) -> Iterator[Tuple[str, str]]
"""
Returns our whitelisted environment variables.
"""
keys = ["SERVER_NAME", "SERVER_PORT"]
if _should_send_default_pii():
# Add all three headers here to make debugging of proxy setup easier.
keys += ["REMOTE_ADDR", "HTTP_X_FORWARDED_FOR", "HTTP_X_REAL_IP"]
for key in keys:
if key in environ:
yield key, environ[key] | [
"def",
"_get_environ",
"(",
"environ",
")",
":",
"# type: (Dict[str, str]) -> Iterator[Tuple[str, str]]",
"keys",
"=",
"[",
"\"SERVER_NAME\"",
",",
"\"SERVER_PORT\"",
"]",
"if",
"_should_send_default_pii",
"(",
")",
":",
"# Add all three headers here to make debugging of proxy ... | Returns our whitelisted environment variables. | [
"Returns",
"our",
"whitelisted",
"environment",
"variables",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/wsgi.py#L96-L108 | train | 215,254 |
getsentry/sentry-python | sentry_sdk/integrations/wsgi.py | get_client_ip | def get_client_ip(environ):
# type: (Dict[str, str]) -> Optional[Any]
"""
Infer the user IP address from various headers. This cannot be used in
security sensitive situations since the value may be forged from a client,
but it's good enough for the event payload.
"""
try:
return environ["HTTP_X_FORWARDED_FOR"].split(",")[0].strip()
except (KeyError, IndexError):
pass
try:
return environ["HTTP_X_REAL_IP"]
except KeyError:
pass
return environ.get("REMOTE_ADDR") | python | def get_client_ip(environ):
# type: (Dict[str, str]) -> Optional[Any]
"""
Infer the user IP address from various headers. This cannot be used in
security sensitive situations since the value may be forged from a client,
but it's good enough for the event payload.
"""
try:
return environ["HTTP_X_FORWARDED_FOR"].split(",")[0].strip()
except (KeyError, IndexError):
pass
try:
return environ["HTTP_X_REAL_IP"]
except KeyError:
pass
return environ.get("REMOTE_ADDR") | [
"def",
"get_client_ip",
"(",
"environ",
")",
":",
"# type: (Dict[str, str]) -> Optional[Any]",
"try",
":",
"return",
"environ",
"[",
"\"HTTP_X_FORWARDED_FOR\"",
"]",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"except",
"(",
"KeyErr... | Infer the user IP address from various headers. This cannot be used in
security sensitive situations since the value may be forged from a client,
but it's good enough for the event payload. | [
"Infer",
"the",
"user",
"IP",
"address",
"from",
"various",
"headers",
".",
"This",
"cannot",
"be",
"used",
"in",
"security",
"sensitive",
"situations",
"since",
"the",
"value",
"may",
"be",
"forged",
"from",
"a",
"client",
"but",
"it",
"s",
"good",
"enoug... | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/wsgi.py#L132-L149 | train | 215,255 |
getsentry/sentry-python | sentry_sdk/utils.py | event_hint_with_exc_info | def event_hint_with_exc_info(exc_info=None):
# type: (ExcInfo) -> Dict[str, Optional[ExcInfo]]
"""Creates a hint with the exc info filled in."""
if exc_info is None:
exc_info = sys.exc_info()
else:
exc_info = exc_info_from_error(exc_info)
if exc_info[0] is None:
exc_info = None
return {"exc_info": exc_info} | python | def event_hint_with_exc_info(exc_info=None):
# type: (ExcInfo) -> Dict[str, Optional[ExcInfo]]
"""Creates a hint with the exc info filled in."""
if exc_info is None:
exc_info = sys.exc_info()
else:
exc_info = exc_info_from_error(exc_info)
if exc_info[0] is None:
exc_info = None
return {"exc_info": exc_info} | [
"def",
"event_hint_with_exc_info",
"(",
"exc_info",
"=",
"None",
")",
":",
"# type: (ExcInfo) -> Dict[str, Optional[ExcInfo]]",
"if",
"exc_info",
"is",
"None",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"else",
":",
"exc_info",
"=",
"exc_info_from_error... | Creates a hint with the exc info filled in. | [
"Creates",
"a",
"hint",
"with",
"the",
"exc",
"info",
"filled",
"in",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/utils.py#L81-L90 | train | 215,256 |
getsentry/sentry-python | sentry_sdk/utils.py | format_and_strip | def format_and_strip(template, params, strip_string=strip_string):
"""Format a string containing %s for placeholders and call `strip_string`
on each parameter. The string template itself does not have a maximum
length.
TODO: handle other placeholders, not just %s
"""
chunks = template.split(u"%s")
if not chunks:
raise ValueError("No formatting placeholders found")
params = list(reversed(params))
rv_remarks = []
rv_original_length = 0
rv_length = 0
rv = []
def realign_remark(remark):
return [
(rv_length + x if isinstance(x, int_types) and i < 4 else x)
for i, x in enumerate(remark)
]
for chunk in chunks[:-1]:
rv.append(chunk)
rv_length += len(chunk)
rv_original_length += len(chunk)
if not params:
raise ValueError("Not enough params.")
param = params.pop()
stripped_param = strip_string(param)
if isinstance(stripped_param, AnnotatedValue):
rv_remarks.extend(
realign_remark(remark) for remark in stripped_param.metadata["rem"]
)
stripped_param = stripped_param.value
rv_original_length += len(param)
rv_length += len(stripped_param)
rv.append(stripped_param)
rv.append(chunks[-1])
rv_length += len(chunks[-1])
rv_original_length += len(chunks[-1])
rv = u"".join(rv)
assert len(rv) == rv_length
if not rv_remarks:
return rv
return AnnotatedValue(
value=rv, metadata={"len": rv_original_length, "rem": rv_remarks}
) | python | def format_and_strip(template, params, strip_string=strip_string):
"""Format a string containing %s for placeholders and call `strip_string`
on each parameter. The string template itself does not have a maximum
length.
TODO: handle other placeholders, not just %s
"""
chunks = template.split(u"%s")
if not chunks:
raise ValueError("No formatting placeholders found")
params = list(reversed(params))
rv_remarks = []
rv_original_length = 0
rv_length = 0
rv = []
def realign_remark(remark):
return [
(rv_length + x if isinstance(x, int_types) and i < 4 else x)
for i, x in enumerate(remark)
]
for chunk in chunks[:-1]:
rv.append(chunk)
rv_length += len(chunk)
rv_original_length += len(chunk)
if not params:
raise ValueError("Not enough params.")
param = params.pop()
stripped_param = strip_string(param)
if isinstance(stripped_param, AnnotatedValue):
rv_remarks.extend(
realign_remark(remark) for remark in stripped_param.metadata["rem"]
)
stripped_param = stripped_param.value
rv_original_length += len(param)
rv_length += len(stripped_param)
rv.append(stripped_param)
rv.append(chunks[-1])
rv_length += len(chunks[-1])
rv_original_length += len(chunks[-1])
rv = u"".join(rv)
assert len(rv) == rv_length
if not rv_remarks:
return rv
return AnnotatedValue(
value=rv, metadata={"len": rv_original_length, "rem": rv_remarks}
) | [
"def",
"format_and_strip",
"(",
"template",
",",
"params",
",",
"strip_string",
"=",
"strip_string",
")",
":",
"chunks",
"=",
"template",
".",
"split",
"(",
"u\"%s\"",
")",
"if",
"not",
"chunks",
":",
"raise",
"ValueError",
"(",
"\"No formatting placeholders fou... | Format a string containing %s for placeholders and call `strip_string`
on each parameter. The string template itself does not have a maximum
length.
TODO: handle other placeholders, not just %s | [
"Format",
"a",
"string",
"containing",
"%s",
"for",
"placeholders",
"and",
"call",
"strip_string",
"on",
"each",
"parameter",
".",
"The",
"string",
"template",
"itself",
"does",
"not",
"have",
"a",
"maximum",
"length",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/utils.py#L876-L930 | train | 215,257 |
getsentry/sentry-python | sentry_sdk/utils.py | Auth.store_api_url | def store_api_url(self):
"""Returns the API url for storing events."""
return "%s://%s%sapi/%s/store/" % (
self.scheme,
self.host,
self.path,
self.project_id,
) | python | def store_api_url(self):
"""Returns the API url for storing events."""
return "%s://%s%sapi/%s/store/" % (
self.scheme,
self.host,
self.path,
self.project_id,
) | [
"def",
"store_api_url",
"(",
"self",
")",
":",
"return",
"\"%s://%s%sapi/%s/store/\"",
"%",
"(",
"self",
".",
"scheme",
",",
"self",
".",
"host",
",",
"self",
".",
"path",
",",
"self",
".",
"project_id",
",",
")"
] | Returns the API url for storing events. | [
"Returns",
"the",
"API",
"url",
"for",
"storing",
"events",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/utils.py#L182-L189 | train | 215,258 |
getsentry/sentry-python | sentry_sdk/utils.py | Auth.to_header | def to_header(self, timestamp=None):
"""Returns the auth header a string."""
rv = [("sentry_key", self.public_key), ("sentry_version", self.version)]
if timestamp is not None:
rv.append(("sentry_timestamp", str(to_timestamp(timestamp))))
if self.client is not None:
rv.append(("sentry_client", self.client))
if self.secret_key is not None:
rv.append(("sentry_secret", self.secret_key))
return u"Sentry " + u", ".join("%s=%s" % (key, value) for key, value in rv) | python | def to_header(self, timestamp=None):
"""Returns the auth header a string."""
rv = [("sentry_key", self.public_key), ("sentry_version", self.version)]
if timestamp is not None:
rv.append(("sentry_timestamp", str(to_timestamp(timestamp))))
if self.client is not None:
rv.append(("sentry_client", self.client))
if self.secret_key is not None:
rv.append(("sentry_secret", self.secret_key))
return u"Sentry " + u", ".join("%s=%s" % (key, value) for key, value in rv) | [
"def",
"to_header",
"(",
"self",
",",
"timestamp",
"=",
"None",
")",
":",
"rv",
"=",
"[",
"(",
"\"sentry_key\"",
",",
"self",
".",
"public_key",
")",
",",
"(",
"\"sentry_version\"",
",",
"self",
".",
"version",
")",
"]",
"if",
"timestamp",
"is",
"not",... | Returns the auth header a string. | [
"Returns",
"the",
"auth",
"header",
"a",
"string",
"."
] | a1d77722bdce0b94660ebf50b5c4a4645916d084 | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/utils.py#L191-L200 | train | 215,259 |
abseil/abseil-py | absl/flags/_defines.py | _register_bounds_validator_if_needed | def _register_bounds_validator_if_needed(parser, name, flag_values):
"""Enforces lower and upper bounds for numeric flags.
Args:
parser: NumericParser (either FloatParser or IntegerParser), provides lower
and upper bounds, and help text to display.
name: str, name of the flag
flag_values: FlagValues.
"""
if parser.lower_bound is not None or parser.upper_bound is not None:
def checker(value):
if value is not None and parser.is_outside_bounds(value):
message = '%s is not %s' % (value, parser.syntactic_help)
raise _exceptions.ValidationError(message)
return True
_validators.register_validator(name, checker, flag_values=flag_values) | python | def _register_bounds_validator_if_needed(parser, name, flag_values):
"""Enforces lower and upper bounds for numeric flags.
Args:
parser: NumericParser (either FloatParser or IntegerParser), provides lower
and upper bounds, and help text to display.
name: str, name of the flag
flag_values: FlagValues.
"""
if parser.lower_bound is not None or parser.upper_bound is not None:
def checker(value):
if value is not None and parser.is_outside_bounds(value):
message = '%s is not %s' % (value, parser.syntactic_help)
raise _exceptions.ValidationError(message)
return True
_validators.register_validator(name, checker, flag_values=flag_values) | [
"def",
"_register_bounds_validator_if_needed",
"(",
"parser",
",",
"name",
",",
"flag_values",
")",
":",
"if",
"parser",
".",
"lower_bound",
"is",
"not",
"None",
"or",
"parser",
".",
"upper_bound",
"is",
"not",
"None",
":",
"def",
"checker",
"(",
"value",
")... | Enforces lower and upper bounds for numeric flags.
Args:
parser: NumericParser (either FloatParser or IntegerParser), provides lower
and upper bounds, and help text to display.
name: str, name of the flag
flag_values: FlagValues. | [
"Enforces",
"lower",
"and",
"upper",
"bounds",
"for",
"numeric",
"flags",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L39-L56 | train | 215,260 |
abseil/abseil-py | absl/flags/_defines.py | DEFINE | def DEFINE(parser, name, default, help, flag_values=_flagvalues.FLAGS, # pylint: disable=redefined-builtin,invalid-name
serializer=None, module_name=None, **args):
"""Registers a generic Flag object.
NOTE: in the docstrings of all DEFINE* functions, "registers" is short
for "creates a new flag and registers it".
Auxiliary function: clients should use the specialized DEFINE_<type>
function instead.
Args:
parser: ArgumentParser, used to parse the flag arguments.
name: str, the flag name.
default: The default value of the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
serializer: ArgumentSerializer, the flag serializer instance.
module_name: str, the name of the Python module declaring this flag.
If not provided, it will be computed using the stack trace of this call.
**args: dict, the extra keyword args that are passed to Flag __init__.
"""
DEFINE_flag(_flag.Flag(parser, serializer, name, default, help, **args),
flag_values, module_name) | python | def DEFINE(parser, name, default, help, flag_values=_flagvalues.FLAGS, # pylint: disable=redefined-builtin,invalid-name
serializer=None, module_name=None, **args):
"""Registers a generic Flag object.
NOTE: in the docstrings of all DEFINE* functions, "registers" is short
for "creates a new flag and registers it".
Auxiliary function: clients should use the specialized DEFINE_<type>
function instead.
Args:
parser: ArgumentParser, used to parse the flag arguments.
name: str, the flag name.
default: The default value of the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
serializer: ArgumentSerializer, the flag serializer instance.
module_name: str, the name of the Python module declaring this flag.
If not provided, it will be computed using the stack trace of this call.
**args: dict, the extra keyword args that are passed to Flag __init__.
"""
DEFINE_flag(_flag.Flag(parser, serializer, name, default, help, **args),
flag_values, module_name) | [
"def",
"DEFINE",
"(",
"parser",
",",
"name",
",",
"default",
",",
"help",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"# pylint: disable=redefined-builtin,invalid-name",
"serializer",
"=",
"None",
",",
"module_name",
"=",
"None",
",",
"*",
"*",
... | Registers a generic Flag object.
NOTE: in the docstrings of all DEFINE* functions, "registers" is short
for "creates a new flag and registers it".
Auxiliary function: clients should use the specialized DEFINE_<type>
function instead.
Args:
parser: ArgumentParser, used to parse the flag arguments.
name: str, the flag name.
default: The default value of the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
serializer: ArgumentSerializer, the flag serializer instance.
module_name: str, the name of the Python module declaring this flag.
If not provided, it will be computed using the stack trace of this call.
**args: dict, the extra keyword args that are passed to Flag __init__. | [
"Registers",
"a",
"generic",
"Flag",
"object",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L59-L82 | train | 215,261 |
abseil/abseil-py | absl/flags/_defines.py | DEFINE_string | def DEFINE_string( # pylint: disable=invalid-name,redefined-builtin
name, default, help, flag_values=_flagvalues.FLAGS, **args):
"""Registers a flag whose value can be any string."""
parser = _argument_parser.ArgumentParser()
serializer = _argument_parser.ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args) | python | def DEFINE_string( # pylint: disable=invalid-name,redefined-builtin
name, default, help, flag_values=_flagvalues.FLAGS, **args):
"""Registers a flag whose value can be any string."""
parser = _argument_parser.ArgumentParser()
serializer = _argument_parser.ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args) | [
"def",
"DEFINE_string",
"(",
"# pylint: disable=invalid-name,redefined-builtin",
"name",
",",
"default",
",",
"help",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"*",
"*",
"args",
")",
":",
"parser",
"=",
"_argument_parser",
".",
"ArgumentParser",
"... | Registers a flag whose value can be any string. | [
"Registers",
"a",
"flag",
"whose",
"value",
"can",
"be",
"any",
"string",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L236-L241 | train | 215,262 |
abseil/abseil-py | absl/flags/_defines.py | DEFINE_boolean | def DEFINE_boolean( # pylint: disable=invalid-name,redefined-builtin
name, default, help, flag_values=_flagvalues.FLAGS, module_name=None,
**args):
"""Registers a boolean flag.
Such a boolean flag does not take an argument. If a user wants to
specify a false value explicitly, the long option beginning with 'no'
must be used: i.e. --noflag
This flag will have a value of None, True or False. None is possible
if default=None and the user does not specify the flag on the command
line.
Args:
name: str, the flag name.
default: bool|str|None, the default value of the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
module_name: str, the name of the Python module declaring this flag.
If not provided, it will be computed using the stack trace of this call.
**args: dict, the extra keyword args that are passed to Flag __init__.
"""
DEFINE_flag(_flag.BooleanFlag(name, default, help, **args),
flag_values, module_name) | python | def DEFINE_boolean( # pylint: disable=invalid-name,redefined-builtin
name, default, help, flag_values=_flagvalues.FLAGS, module_name=None,
**args):
"""Registers a boolean flag.
Such a boolean flag does not take an argument. If a user wants to
specify a false value explicitly, the long option beginning with 'no'
must be used: i.e. --noflag
This flag will have a value of None, True or False. None is possible
if default=None and the user does not specify the flag on the command
line.
Args:
name: str, the flag name.
default: bool|str|None, the default value of the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
module_name: str, the name of the Python module declaring this flag.
If not provided, it will be computed using the stack trace of this call.
**args: dict, the extra keyword args that are passed to Flag __init__.
"""
DEFINE_flag(_flag.BooleanFlag(name, default, help, **args),
flag_values, module_name) | [
"def",
"DEFINE_boolean",
"(",
"# pylint: disable=invalid-name,redefined-builtin",
"name",
",",
"default",
",",
"help",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"module_name",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"DEFINE_flag",
"(",
"_f... | Registers a boolean flag.
Such a boolean flag does not take an argument. If a user wants to
specify a false value explicitly, the long option beginning with 'no'
must be used: i.e. --noflag
This flag will have a value of None, True or False. None is possible
if default=None and the user does not specify the flag on the command
line.
Args:
name: str, the flag name.
default: bool|str|None, the default value of the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
module_name: str, the name of the Python module declaring this flag.
If not provided, it will be computed using the stack trace of this call.
**args: dict, the extra keyword args that are passed to Flag __init__. | [
"Registers",
"a",
"boolean",
"flag",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L244-L268 | train | 215,263 |
abseil/abseil-py | absl/flags/_defines.py | DEFINE_float | def DEFINE_float( # pylint: disable=invalid-name,redefined-builtin
name, default, help, lower_bound=None, upper_bound=None,
flag_values=_flagvalues.FLAGS, **args): # pylint: disable=invalid-name
"""Registers a flag whose value must be a float.
If lower_bound or upper_bound are set, then this flag must be
within the given range.
Args:
name: str, the flag name.
default: float|str|None, the default value of the flag.
help: str, the help message.
lower_bound: float, min value of the flag.
upper_bound: float, max value of the flag.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
**args: dict, the extra keyword args that are passed to DEFINE.
"""
parser = _argument_parser.FloatParser(lower_bound, upper_bound)
serializer = _argument_parser.ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_register_bounds_validator_if_needed(parser, name, flag_values=flag_values) | python | def DEFINE_float( # pylint: disable=invalid-name,redefined-builtin
name, default, help, lower_bound=None, upper_bound=None,
flag_values=_flagvalues.FLAGS, **args): # pylint: disable=invalid-name
"""Registers a flag whose value must be a float.
If lower_bound or upper_bound are set, then this flag must be
within the given range.
Args:
name: str, the flag name.
default: float|str|None, the default value of the flag.
help: str, the help message.
lower_bound: float, min value of the flag.
upper_bound: float, max value of the flag.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
**args: dict, the extra keyword args that are passed to DEFINE.
"""
parser = _argument_parser.FloatParser(lower_bound, upper_bound)
serializer = _argument_parser.ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_register_bounds_validator_if_needed(parser, name, flag_values=flag_values) | [
"def",
"DEFINE_float",
"(",
"# pylint: disable=invalid-name,redefined-builtin",
"name",
",",
"default",
",",
"help",
",",
"lower_bound",
"=",
"None",
",",
"upper_bound",
"=",
"None",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"*",
"*",
"args",
")... | Registers a flag whose value must be a float.
If lower_bound or upper_bound are set, then this flag must be
within the given range.
Args:
name: str, the flag name.
default: float|str|None, the default value of the flag.
help: str, the help message.
lower_bound: float, min value of the flag.
upper_bound: float, max value of the flag.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
**args: dict, the extra keyword args that are passed to DEFINE. | [
"Registers",
"a",
"flag",
"whose",
"value",
"must",
"be",
"a",
"float",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L271-L292 | train | 215,264 |
abseil/abseil-py | absl/flags/_defines.py | DEFINE_integer | def DEFINE_integer( # pylint: disable=invalid-name,redefined-builtin
name, default, help, lower_bound=None, upper_bound=None,
flag_values=_flagvalues.FLAGS, **args):
"""Registers a flag whose value must be an integer.
If lower_bound, or upper_bound are set, then this flag must be
within the given range.
Args:
name: str, the flag name.
default: int|str|None, the default value of the flag.
help: str, the help message.
lower_bound: int, min value of the flag.
upper_bound: int, max value of the flag.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
**args: dict, the extra keyword args that are passed to DEFINE.
"""
parser = _argument_parser.IntegerParser(lower_bound, upper_bound)
serializer = _argument_parser.ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_register_bounds_validator_if_needed(parser, name, flag_values=flag_values) | python | def DEFINE_integer( # pylint: disable=invalid-name,redefined-builtin
name, default, help, lower_bound=None, upper_bound=None,
flag_values=_flagvalues.FLAGS, **args):
"""Registers a flag whose value must be an integer.
If lower_bound, or upper_bound are set, then this flag must be
within the given range.
Args:
name: str, the flag name.
default: int|str|None, the default value of the flag.
help: str, the help message.
lower_bound: int, min value of the flag.
upper_bound: int, max value of the flag.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
**args: dict, the extra keyword args that are passed to DEFINE.
"""
parser = _argument_parser.IntegerParser(lower_bound, upper_bound)
serializer = _argument_parser.ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_register_bounds_validator_if_needed(parser, name, flag_values=flag_values) | [
"def",
"DEFINE_integer",
"(",
"# pylint: disable=invalid-name,redefined-builtin",
"name",
",",
"default",
",",
"help",
",",
"lower_bound",
"=",
"None",
",",
"upper_bound",
"=",
"None",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"*",
"*",
"args",
... | Registers a flag whose value must be an integer.
If lower_bound, or upper_bound are set, then this flag must be
within the given range.
Args:
name: str, the flag name.
default: int|str|None, the default value of the flag.
help: str, the help message.
lower_bound: int, min value of the flag.
upper_bound: int, max value of the flag.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
**args: dict, the extra keyword args that are passed to DEFINE. | [
"Registers",
"a",
"flag",
"whose",
"value",
"must",
"be",
"an",
"integer",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L295-L316 | train | 215,265 |
abseil/abseil-py | absl/flags/_defines.py | DEFINE_enum_class | def DEFINE_enum_class( # pylint: disable=invalid-name,redefined-builtin
name, default, enum_class, help, flag_values=_flagvalues.FLAGS,
module_name=None, **args):
"""Registers a flag whose value can be the name of enum members.
Args:
name: str, the flag name.
default: Enum|str|None, the default value of the flag.
enum_class: class, the Enum class with all the possible values for the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
module_name: str, the name of the Python module declaring this flag.
If not provided, it will be computed using the stack trace of this call.
**args: dict, the extra keyword args that are passed to Flag __init__.
"""
DEFINE_flag(_flag.EnumClassFlag(name, default, help, enum_class, **args),
flag_values, module_name) | python | def DEFINE_enum_class( # pylint: disable=invalid-name,redefined-builtin
name, default, enum_class, help, flag_values=_flagvalues.FLAGS,
module_name=None, **args):
"""Registers a flag whose value can be the name of enum members.
Args:
name: str, the flag name.
default: Enum|str|None, the default value of the flag.
enum_class: class, the Enum class with all the possible values for the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
module_name: str, the name of the Python module declaring this flag.
If not provided, it will be computed using the stack trace of this call.
**args: dict, the extra keyword args that are passed to Flag __init__.
"""
DEFINE_flag(_flag.EnumClassFlag(name, default, help, enum_class, **args),
flag_values, module_name) | [
"def",
"DEFINE_enum_class",
"(",
"# pylint: disable=invalid-name,redefined-builtin",
"name",
",",
"default",
",",
"enum_class",
",",
"help",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"module_name",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"... | Registers a flag whose value can be the name of enum members.
Args:
name: str, the flag name.
default: Enum|str|None, the default value of the flag.
enum_class: class, the Enum class with all the possible values for the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
module_name: str, the name of the Python module declaring this flag.
If not provided, it will be computed using the stack trace of this call.
**args: dict, the extra keyword args that are passed to Flag __init__. | [
"Registers",
"a",
"flag",
"whose",
"value",
"can",
"be",
"the",
"name",
"of",
"enum",
"members",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L343-L360 | train | 215,266 |
abseil/abseil-py | absl/flags/_defines.py | DEFINE_spaceseplist | def DEFINE_spaceseplist( # pylint: disable=invalid-name,redefined-builtin
name, default, help, comma_compat=False, flag_values=_flagvalues.FLAGS,
**args):
"""Registers a flag whose value is a whitespace-separated list of strings.
Any whitespace can be used as a separator.
Args:
name: str, the flag name.
default: list|str|None, the default value of the flag.
help: str, the help message.
comma_compat: bool - Whether to support comma as an additional separator.
If false then only whitespace is supported. This is intended only for
backwards compatibility with flags that used to be comma-separated.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
**args: Dictionary with extra keyword args that are passed to the
Flag __init__.
"""
parser = _argument_parser.WhitespaceSeparatedListParser(
comma_compat=comma_compat)
serializer = _argument_parser.ListSerializer(' ')
DEFINE(parser, name, default, help, flag_values, serializer, **args) | python | def DEFINE_spaceseplist( # pylint: disable=invalid-name,redefined-builtin
name, default, help, comma_compat=False, flag_values=_flagvalues.FLAGS,
**args):
"""Registers a flag whose value is a whitespace-separated list of strings.
Any whitespace can be used as a separator.
Args:
name: str, the flag name.
default: list|str|None, the default value of the flag.
help: str, the help message.
comma_compat: bool - Whether to support comma as an additional separator.
If false then only whitespace is supported. This is intended only for
backwards compatibility with flags that used to be comma-separated.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
**args: Dictionary with extra keyword args that are passed to the
Flag __init__.
"""
parser = _argument_parser.WhitespaceSeparatedListParser(
comma_compat=comma_compat)
serializer = _argument_parser.ListSerializer(' ')
DEFINE(parser, name, default, help, flag_values, serializer, **args) | [
"def",
"DEFINE_spaceseplist",
"(",
"# pylint: disable=invalid-name,redefined-builtin",
"name",
",",
"default",
",",
"help",
",",
"comma_compat",
"=",
"False",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"*",
"*",
"args",
")",
":",
"parser",
"=",
"... | Registers a flag whose value is a whitespace-separated list of strings.
Any whitespace can be used as a separator.
Args:
name: str, the flag name.
default: list|str|None, the default value of the flag.
help: str, the help message.
comma_compat: bool - Whether to support comma as an additional separator.
If false then only whitespace is supported. This is intended only for
backwards compatibility with flags that used to be comma-separated.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
**args: Dictionary with extra keyword args that are passed to the
Flag __init__. | [
"Registers",
"a",
"flag",
"whose",
"value",
"is",
"a",
"whitespace",
"-",
"separated",
"list",
"of",
"strings",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L383-L405 | train | 215,267 |
abseil/abseil-py | absl/flags/_defines.py | DEFINE_multi_enum | def DEFINE_multi_enum( # pylint: disable=invalid-name,redefined-builtin
name, default, enum_values, help, flag_values=_flagvalues.FLAGS,
case_sensitive=True, **args):
"""Registers a flag whose value can be a list strings from enum_values.
Use the flag on the command line multiple times to place multiple
enum values into the list. The 'default' may be a single string
(which will be converted into a single-element list) or a list of
strings.
Args:
name: str, the flag name.
default: Union[Iterable[Text], Text, None], the default value of the flag;
see `DEFINE_multi`.
enum_values: [str], a non-empty list of strings with the possible values for
the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
case_sensitive: Whether or not the enum is to be case-sensitive.
**args: Dictionary with extra keyword args that are passed to the
Flag __init__.
"""
parser = _argument_parser.EnumParser(enum_values, case_sensitive)
serializer = _argument_parser.ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) | python | def DEFINE_multi_enum( # pylint: disable=invalid-name,redefined-builtin
name, default, enum_values, help, flag_values=_flagvalues.FLAGS,
case_sensitive=True, **args):
"""Registers a flag whose value can be a list strings from enum_values.
Use the flag on the command line multiple times to place multiple
enum values into the list. The 'default' may be a single string
(which will be converted into a single-element list) or a list of
strings.
Args:
name: str, the flag name.
default: Union[Iterable[Text], Text, None], the default value of the flag;
see `DEFINE_multi`.
enum_values: [str], a non-empty list of strings with the possible values for
the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
case_sensitive: Whether or not the enum is to be case-sensitive.
**args: Dictionary with extra keyword args that are passed to the
Flag __init__.
"""
parser = _argument_parser.EnumParser(enum_values, case_sensitive)
serializer = _argument_parser.ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) | [
"def",
"DEFINE_multi_enum",
"(",
"# pylint: disable=invalid-name,redefined-builtin",
"name",
",",
"default",
",",
"enum_values",
",",
"help",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"case_sensitive",
"=",
"True",
",",
"*",
"*",
"args",
")",
":",... | Registers a flag whose value can be a list strings from enum_values.
Use the flag on the command line multiple times to place multiple
enum values into the list. The 'default' may be a single string
(which will be converted into a single-element list) or a list of
strings.
Args:
name: str, the flag name.
default: Union[Iterable[Text], Text, None], the default value of the flag;
see `DEFINE_multi`.
enum_values: [str], a non-empty list of strings with the possible values for
the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will
be registered. This should almost never need to be overridden.
case_sensitive: Whether or not the enum is to be case-sensitive.
**args: Dictionary with extra keyword args that are passed to the
Flag __init__. | [
"Registers",
"a",
"flag",
"whose",
"value",
"can",
"be",
"a",
"list",
"strings",
"from",
"enum_values",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L519-L544 | train | 215,268 |
abseil/abseil-py | absl/flags/_defines.py | DEFINE_multi_enum_class | def DEFINE_multi_enum_class( # pylint: disable=invalid-name,redefined-builtin
name,
default,
enum_class,
help,
flag_values=_flagvalues.FLAGS,
module_name=None,
**args):
"""Registers a flag whose value can be a list of enum members.
Use the flag on the command line multiple times to place multiple
enum values into the list.
Args:
name: str, the flag name.
default: Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the
default value of the flag; see
`DEFINE_multi`; only differences are documented here. If the value is
a single Enum, it is treated as a single-item list of that Enum value.
If it is an iterable, text values within the iterable will be converted
to the equivalent Enum objects.
enum_class: class, the Enum class with all the possible values for the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will be
registered. This should almost never need to be overridden.
module_name: A string, the name of the Python module declaring this flag. If
not provided, it will be computed using the stack trace of this call.
**args: Dictionary with extra keyword args that are passed to the Flag
__init__.
"""
DEFINE_flag(
_flag.MultiEnumClassFlag(name, default, help, enum_class),
flag_values, module_name, **args) | python | def DEFINE_multi_enum_class( # pylint: disable=invalid-name,redefined-builtin
name,
default,
enum_class,
help,
flag_values=_flagvalues.FLAGS,
module_name=None,
**args):
"""Registers a flag whose value can be a list of enum members.
Use the flag on the command line multiple times to place multiple
enum values into the list.
Args:
name: str, the flag name.
default: Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the
default value of the flag; see
`DEFINE_multi`; only differences are documented here. If the value is
a single Enum, it is treated as a single-item list of that Enum value.
If it is an iterable, text values within the iterable will be converted
to the equivalent Enum objects.
enum_class: class, the Enum class with all the possible values for the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will be
registered. This should almost never need to be overridden.
module_name: A string, the name of the Python module declaring this flag. If
not provided, it will be computed using the stack trace of this call.
**args: Dictionary with extra keyword args that are passed to the Flag
__init__.
"""
DEFINE_flag(
_flag.MultiEnumClassFlag(name, default, help, enum_class),
flag_values, module_name, **args) | [
"def",
"DEFINE_multi_enum_class",
"(",
"# pylint: disable=invalid-name,redefined-builtin",
"name",
",",
"default",
",",
"enum_class",
",",
"help",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"module_name",
"=",
"None",
",",
"*",
"*",
"args",
")",
":... | Registers a flag whose value can be a list of enum members.
Use the flag on the command line multiple times to place multiple
enum values into the list.
Args:
name: str, the flag name.
default: Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the
default value of the flag; see
`DEFINE_multi`; only differences are documented here. If the value is
a single Enum, it is treated as a single-item list of that Enum value.
If it is an iterable, text values within the iterable will be converted
to the equivalent Enum objects.
enum_class: class, the Enum class with all the possible values for the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues instance with which the flag will be
registered. This should almost never need to be overridden.
module_name: A string, the name of the Python module declaring this flag. If
not provided, it will be computed using the stack trace of this call.
**args: Dictionary with extra keyword args that are passed to the Flag
__init__. | [
"Registers",
"a",
"flag",
"whose",
"value",
"can",
"be",
"a",
"list",
"of",
"enum",
"members",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L547-L579 | train | 215,269 |
abseil/abseil-py | absl/flags/_argument_parser.py | ArgumentParser.parse | def parse(self, argument):
"""Parses the string argument and returns the native value.
By default it returns its argument unmodified.
Args:
argument: string argument passed in the commandline.
Raises:
ValueError: Raised when it fails to parse the argument.
TypeError: Raised when the argument has the wrong type.
Returns:
The parsed value in native type.
"""
if not isinstance(argument, six.string_types):
raise TypeError('flag value must be a string, found "{}"'.format(
type(argument)))
return argument | python | def parse(self, argument):
"""Parses the string argument and returns the native value.
By default it returns its argument unmodified.
Args:
argument: string argument passed in the commandline.
Raises:
ValueError: Raised when it fails to parse the argument.
TypeError: Raised when the argument has the wrong type.
Returns:
The parsed value in native type.
"""
if not isinstance(argument, six.string_types):
raise TypeError('flag value must be a string, found "{}"'.format(
type(argument)))
return argument | [
"def",
"parse",
"(",
"self",
",",
"argument",
")",
":",
"if",
"not",
"isinstance",
"(",
"argument",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"'flag value must be a string, found \"{}\"'",
".",
"format",
"(",
"type",
"(",
"argument"... | Parses the string argument and returns the native value.
By default it returns its argument unmodified.
Args:
argument: string argument passed in the commandline.
Raises:
ValueError: Raised when it fails to parse the argument.
TypeError: Raised when the argument has the wrong type.
Returns:
The parsed value in native type. | [
"Parses",
"the",
"string",
"argument",
"and",
"returns",
"the",
"native",
"value",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L97-L115 | train | 215,270 |
abseil/abseil-py | absl/flags/_argument_parser.py | NumericParser.is_outside_bounds | def is_outside_bounds(self, val):
"""Returns whether the value is outside the bounds or not."""
return ((self.lower_bound is not None and val < self.lower_bound) or
(self.upper_bound is not None and val > self.upper_bound)) | python | def is_outside_bounds(self, val):
"""Returns whether the value is outside the bounds or not."""
return ((self.lower_bound is not None and val < self.lower_bound) or
(self.upper_bound is not None and val > self.upper_bound)) | [
"def",
"is_outside_bounds",
"(",
"self",
",",
"val",
")",
":",
"return",
"(",
"(",
"self",
".",
"lower_bound",
"is",
"not",
"None",
"and",
"val",
"<",
"self",
".",
"lower_bound",
")",
"or",
"(",
"self",
".",
"upper_bound",
"is",
"not",
"None",
"and",
... | Returns whether the value is outside the bounds or not. | [
"Returns",
"whether",
"the",
"value",
"is",
"outside",
"the",
"bounds",
"or",
"not",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L145-L148 | train | 215,271 |
abseil/abseil-py | absl/flags/_argument_parser.py | FloatParser.convert | def convert(self, argument):
"""Returns the float value of argument."""
if (_is_integer_type(argument) or isinstance(argument, float) or
isinstance(argument, six.string_types)):
return float(argument)
else:
raise TypeError(
'Expect argument to be a string, int, or float, found {}'.format(
type(argument))) | python | def convert(self, argument):
"""Returns the float value of argument."""
if (_is_integer_type(argument) or isinstance(argument, float) or
isinstance(argument, six.string_types)):
return float(argument)
else:
raise TypeError(
'Expect argument to be a string, int, or float, found {}'.format(
type(argument))) | [
"def",
"convert",
"(",
"self",
",",
"argument",
")",
":",
"if",
"(",
"_is_integer_type",
"(",
"argument",
")",
"or",
"isinstance",
"(",
"argument",
",",
"float",
")",
"or",
"isinstance",
"(",
"argument",
",",
"six",
".",
"string_types",
")",
")",
":",
... | Returns the float value of argument. | [
"Returns",
"the",
"float",
"value",
"of",
"argument",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L209-L217 | train | 215,272 |
abseil/abseil-py | absl/flags/_argument_parser.py | IntegerParser.convert | def convert(self, argument):
"""Returns the int value of argument."""
if _is_integer_type(argument):
return argument
elif isinstance(argument, six.string_types):
base = 10
if len(argument) > 2 and argument[0] == '0':
if argument[1] == 'o':
base = 8
elif argument[1] == 'x':
base = 16
return int(argument, base)
else:
raise TypeError('Expect argument to be a string or int, found {}'.format(
type(argument))) | python | def convert(self, argument):
"""Returns the int value of argument."""
if _is_integer_type(argument):
return argument
elif isinstance(argument, six.string_types):
base = 10
if len(argument) > 2 and argument[0] == '0':
if argument[1] == 'o':
base = 8
elif argument[1] == 'x':
base = 16
return int(argument, base)
else:
raise TypeError('Expect argument to be a string or int, found {}'.format(
type(argument))) | [
"def",
"convert",
"(",
"self",
",",
"argument",
")",
":",
"if",
"_is_integer_type",
"(",
"argument",
")",
":",
"return",
"argument",
"elif",
"isinstance",
"(",
"argument",
",",
"six",
".",
"string_types",
")",
":",
"base",
"=",
"10",
"if",
"len",
"(",
... | Returns the int value of argument. | [
"Returns",
"the",
"int",
"value",
"of",
"argument",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L254-L268 | train | 215,273 |
abseil/abseil-py | absl/flags/_argument_parser.py | EnumClassParser.parse | def parse(self, argument):
"""Determines validity of argument and returns the correct element of enum.
Args:
argument: str or Enum class member, the supplied flag value.
Returns:
The first matching Enum class member in Enum class.
Raises:
ValueError: Raised when argument didn't match anything in enum.
"""
if isinstance(argument, self.enum_class):
return argument
if argument not in self.enum_class.__members__:
raise ValueError('value should be one of <%s>' %
'|'.join(self.enum_class.__members__.keys()))
else:
return self.enum_class[argument] | python | def parse(self, argument):
"""Determines validity of argument and returns the correct element of enum.
Args:
argument: str or Enum class member, the supplied flag value.
Returns:
The first matching Enum class member in Enum class.
Raises:
ValueError: Raised when argument didn't match anything in enum.
"""
if isinstance(argument, self.enum_class):
return argument
if argument not in self.enum_class.__members__:
raise ValueError('value should be one of <%s>' %
'|'.join(self.enum_class.__members__.keys()))
else:
return self.enum_class[argument] | [
"def",
"parse",
"(",
"self",
",",
"argument",
")",
":",
"if",
"isinstance",
"(",
"argument",
",",
"self",
".",
"enum_class",
")",
":",
"return",
"argument",
"if",
"argument",
"not",
"in",
"self",
".",
"enum_class",
".",
"__members__",
":",
"raise",
"Valu... | Determines validity of argument and returns the correct element of enum.
Args:
argument: str or Enum class member, the supplied flag value.
Returns:
The first matching Enum class member in Enum class.
Raises:
ValueError: Raised when argument didn't match anything in enum. | [
"Determines",
"validity",
"of",
"argument",
"and",
"returns",
"the",
"correct",
"element",
"of",
"enum",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L380-L398 | train | 215,274 |
abseil/abseil-py | absl/flags/_argument_parser.py | ListParser.parse | def parse(self, argument):
"""Parses argument as comma-separated list of strings."""
if isinstance(argument, list):
return argument
elif not argument:
return []
else:
try:
return [s.strip() for s in list(csv.reader([argument], strict=True))[0]]
except csv.Error as e:
# Provide a helpful report for case like
# --listflag="$(printf 'hello,\nworld')"
# IOW, list flag values containing naked newlines. This error
# was previously "reported" by allowing csv.Error to
# propagate.
raise ValueError('Unable to parse the value %r as a %s: %s'
% (argument, self.flag_type(), e)) | python | def parse(self, argument):
"""Parses argument as comma-separated list of strings."""
if isinstance(argument, list):
return argument
elif not argument:
return []
else:
try:
return [s.strip() for s in list(csv.reader([argument], strict=True))[0]]
except csv.Error as e:
# Provide a helpful report for case like
# --listflag="$(printf 'hello,\nworld')"
# IOW, list flag values containing naked newlines. This error
# was previously "reported" by allowing csv.Error to
# propagate.
raise ValueError('Unable to parse the value %r as a %s: %s'
% (argument, self.flag_type(), e)) | [
"def",
"parse",
"(",
"self",
",",
"argument",
")",
":",
"if",
"isinstance",
"(",
"argument",
",",
"list",
")",
":",
"return",
"argument",
"elif",
"not",
"argument",
":",
"return",
"[",
"]",
"else",
":",
"try",
":",
"return",
"[",
"s",
".",
"strip",
... | Parses argument as comma-separated list of strings. | [
"Parses",
"argument",
"as",
"comma",
"-",
"separated",
"list",
"of",
"strings",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L494-L510 | train | 215,275 |
abseil/abseil-py | absl/flags/_argument_parser.py | WhitespaceSeparatedListParser.parse | def parse(self, argument):
"""Parses argument as whitespace-separated list of strings.
It also parses argument as comma-separated list of strings if requested.
Args:
argument: string argument passed in the commandline.
Returns:
[str], the parsed flag value.
"""
if isinstance(argument, list):
return argument
elif not argument:
return []
else:
if self._comma_compat:
argument = argument.replace(',', ' ')
return argument.split() | python | def parse(self, argument):
"""Parses argument as whitespace-separated list of strings.
It also parses argument as comma-separated list of strings if requested.
Args:
argument: string argument passed in the commandline.
Returns:
[str], the parsed flag value.
"""
if isinstance(argument, list):
return argument
elif not argument:
return []
else:
if self._comma_compat:
argument = argument.replace(',', ' ')
return argument.split() | [
"def",
"parse",
"(",
"self",
",",
"argument",
")",
":",
"if",
"isinstance",
"(",
"argument",
",",
"list",
")",
":",
"return",
"argument",
"elif",
"not",
"argument",
":",
"return",
"[",
"]",
"else",
":",
"if",
"self",
".",
"_comma_compat",
":",
"argumen... | Parses argument as whitespace-separated list of strings.
It also parses argument as comma-separated list of strings if requested.
Args:
argument: string argument passed in the commandline.
Returns:
[str], the parsed flag value. | [
"Parses",
"argument",
"as",
"whitespace",
"-",
"separated",
"list",
"of",
"strings",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L534-L552 | train | 215,276 |
abseil/abseil-py | absl/flags/_flagvalues.py | FlagValues.set_gnu_getopt | def set_gnu_getopt(self, gnu_getopt=True):
"""Sets whether or not to use GNU style scanning.
GNU style allows mixing of flag and non-flag arguments. See
http://docs.python.org/library/getopt.html#getopt.gnu_getopt
Args:
gnu_getopt: bool, whether or not to use GNU style scanning.
"""
self.__dict__['__use_gnu_getopt'] = gnu_getopt
self.__dict__['__use_gnu_getopt_explicitly_set'] = True | python | def set_gnu_getopt(self, gnu_getopt=True):
"""Sets whether or not to use GNU style scanning.
GNU style allows mixing of flag and non-flag arguments. See
http://docs.python.org/library/getopt.html#getopt.gnu_getopt
Args:
gnu_getopt: bool, whether or not to use GNU style scanning.
"""
self.__dict__['__use_gnu_getopt'] = gnu_getopt
self.__dict__['__use_gnu_getopt_explicitly_set'] = True | [
"def",
"set_gnu_getopt",
"(",
"self",
",",
"gnu_getopt",
"=",
"True",
")",
":",
"self",
".",
"__dict__",
"[",
"'__use_gnu_getopt'",
"]",
"=",
"gnu_getopt",
"self",
".",
"__dict__",
"[",
"'__use_gnu_getopt_explicitly_set'",
"]",
"=",
"True"
] | Sets whether or not to use GNU style scanning.
GNU style allows mixing of flag and non-flag arguments. See
http://docs.python.org/library/getopt.html#getopt.gnu_getopt
Args:
gnu_getopt: bool, whether or not to use GNU style scanning. | [
"Sets",
"whether",
"or",
"not",
"to",
"use",
"GNU",
"style",
"scanning",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L126-L136 | train | 215,277 |
abseil/abseil-py | absl/flags/_flagvalues.py | FlagValues._assert_validators | def _assert_validators(self, validators):
"""Asserts if all validators in the list are satisfied.
It asserts validators in the order they were created.
Args:
validators: Iterable(validators.Validator), validators to be
verified.
Raises:
AttributeError: Raised if validators work with a non-existing flag.
IllegalFlagValueError: Raised if validation fails for at least one
validator.
"""
for validator in sorted(
validators, key=lambda validator: validator.insertion_index):
try:
validator.verify(self)
except _exceptions.ValidationError as e:
message = validator.print_flags_with_values(self)
raise _exceptions.IllegalFlagValueError('%s: %s' % (message, str(e))) | python | def _assert_validators(self, validators):
"""Asserts if all validators in the list are satisfied.
It asserts validators in the order they were created.
Args:
validators: Iterable(validators.Validator), validators to be
verified.
Raises:
AttributeError: Raised if validators work with a non-existing flag.
IllegalFlagValueError: Raised if validation fails for at least one
validator.
"""
for validator in sorted(
validators, key=lambda validator: validator.insertion_index):
try:
validator.verify(self)
except _exceptions.ValidationError as e:
message = validator.print_flags_with_values(self)
raise _exceptions.IllegalFlagValueError('%s: %s' % (message, str(e))) | [
"def",
"_assert_validators",
"(",
"self",
",",
"validators",
")",
":",
"for",
"validator",
"in",
"sorted",
"(",
"validators",
",",
"key",
"=",
"lambda",
"validator",
":",
"validator",
".",
"insertion_index",
")",
":",
"try",
":",
"validator",
".",
"verify",
... | Asserts if all validators in the list are satisfied.
It asserts validators in the order they were created.
Args:
validators: Iterable(validators.Validator), validators to be
verified.
Raises:
AttributeError: Raised if validators work with a non-existing flag.
IllegalFlagValueError: Raised if validation fails for at least one
validator. | [
"Asserts",
"if",
"all",
"validators",
"in",
"the",
"list",
"are",
"satisfied",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L512-L531 | train | 215,278 |
abseil/abseil-py | absl/flags/_flagvalues.py | FlagValues.set_default | def set_default(self, name, value):
"""Changes the default value of the named flag object.
The flag's current value is also updated if the flag is currently using
the default value, i.e. not specified in the command line, and not set
by FLAGS.name = value.
Args:
name: str, the name of the flag to modify.
value: The new default value.
Raises:
UnrecognizedFlagError: Raised when there is no registered flag named name.
IllegalFlagValueError: Raised when value is not valid.
"""
fl = self._flags()
if name not in fl:
self._set_unknown_flag(name, value)
return
fl[name]._set_default(value) # pylint: disable=protected-access
self._assert_validators(fl[name].validators) | python | def set_default(self, name, value):
"""Changes the default value of the named flag object.
The flag's current value is also updated if the flag is currently using
the default value, i.e. not specified in the command line, and not set
by FLAGS.name = value.
Args:
name: str, the name of the flag to modify.
value: The new default value.
Raises:
UnrecognizedFlagError: Raised when there is no registered flag named name.
IllegalFlagValueError: Raised when value is not valid.
"""
fl = self._flags()
if name not in fl:
self._set_unknown_flag(name, value)
return
fl[name]._set_default(value) # pylint: disable=protected-access
self._assert_validators(fl[name].validators) | [
"def",
"set_default",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"fl",
"=",
"self",
".",
"_flags",
"(",
")",
"if",
"name",
"not",
"in",
"fl",
":",
"self",
".",
"_set_unknown_flag",
"(",
"name",
",",
"value",
")",
"return",
"fl",
"[",
"name",... | Changes the default value of the named flag object.
The flag's current value is also updated if the flag is currently using
the default value, i.e. not specified in the command line, and not set
by FLAGS.name = value.
Args:
name: str, the name of the flag to modify.
value: The new default value.
Raises:
UnrecognizedFlagError: Raised when there is no registered flag named name.
IllegalFlagValueError: Raised when value is not valid. | [
"Changes",
"the",
"default",
"value",
"of",
"the",
"named",
"flag",
"object",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L563-L583 | train | 215,279 |
abseil/abseil-py | absl/flags/_flagvalues.py | FlagValues.flag_values_dict | def flag_values_dict(self):
"""Returns a dictionary that maps flag names to flag values."""
return {name: flag.value for name, flag in six.iteritems(self._flags())} | python | def flag_values_dict(self):
"""Returns a dictionary that maps flag names to flag values."""
return {name: flag.value for name, flag in six.iteritems(self._flags())} | [
"def",
"flag_values_dict",
"(",
"self",
")",
":",
"return",
"{",
"name",
":",
"flag",
".",
"value",
"for",
"name",
",",
"flag",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_flags",
"(",
")",
")",
"}"
] | Returns a dictionary that maps flag names to flag values. | [
"Returns",
"a",
"dictionary",
"that",
"maps",
"flag",
"names",
"to",
"flag",
"values",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L821-L823 | train | 215,280 |
abseil/abseil-py | absl/flags/_flagvalues.py | FlagValues.get_help | def get_help(self, prefix='', include_special_flags=True):
"""Returns a help string for all known flags.
Args:
prefix: str, per-line output prefix.
include_special_flags: bool, whether to include description of
SPECIAL_FLAGS, i.e. --flagfile and --undefok.
Returns:
str, formatted help message.
"""
flags_by_module = self.flags_by_module_dict()
if flags_by_module:
modules = sorted(flags_by_module)
# Print the help for the main module first, if possible.
main_module = sys.argv[0]
if main_module in modules:
modules.remove(main_module)
modules = [main_module] + modules
return self._get_help_for_modules(modules, prefix, include_special_flags)
else:
output_lines = []
# Just print one long list of flags.
values = six.itervalues(self._flags())
if include_special_flags:
values = itertools.chain(
values, six.itervalues(_helpers.SPECIAL_FLAGS._flags())) # pylint: disable=protected-access
self._render_flag_list(values, output_lines, prefix)
return '\n'.join(output_lines) | python | def get_help(self, prefix='', include_special_flags=True):
"""Returns a help string for all known flags.
Args:
prefix: str, per-line output prefix.
include_special_flags: bool, whether to include description of
SPECIAL_FLAGS, i.e. --flagfile and --undefok.
Returns:
str, formatted help message.
"""
flags_by_module = self.flags_by_module_dict()
if flags_by_module:
modules = sorted(flags_by_module)
# Print the help for the main module first, if possible.
main_module = sys.argv[0]
if main_module in modules:
modules.remove(main_module)
modules = [main_module] + modules
return self._get_help_for_modules(modules, prefix, include_special_flags)
else:
output_lines = []
# Just print one long list of flags.
values = six.itervalues(self._flags())
if include_special_flags:
values = itertools.chain(
values, six.itervalues(_helpers.SPECIAL_FLAGS._flags())) # pylint: disable=protected-access
self._render_flag_list(values, output_lines, prefix)
return '\n'.join(output_lines) | [
"def",
"get_help",
"(",
"self",
",",
"prefix",
"=",
"''",
",",
"include_special_flags",
"=",
"True",
")",
":",
"flags_by_module",
"=",
"self",
".",
"flags_by_module_dict",
"(",
")",
"if",
"flags_by_module",
":",
"modules",
"=",
"sorted",
"(",
"flags_by_module"... | Returns a help string for all known flags.
Args:
prefix: str, per-line output prefix.
include_special_flags: bool, whether to include description of
SPECIAL_FLAGS, i.e. --flagfile and --undefok.
Returns:
str, formatted help message. | [
"Returns",
"a",
"help",
"string",
"for",
"all",
"known",
"flags",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L829-L857 | train | 215,281 |
abseil/abseil-py | absl/flags/_flagvalues.py | FlagValues._get_help_for_modules | def _get_help_for_modules(self, modules, prefix, include_special_flags):
"""Returns the help string for a list of modules.
Private to absl.flags package.
Args:
modules: List[str], a list of modules to get the help string for.
prefix: str, a string that is prepended to each generated help line.
include_special_flags: bool, whether to include description of
SPECIAL_FLAGS, i.e. --flagfile and --undefok.
"""
output_lines = []
for module in modules:
self._render_our_module_flags(module, output_lines, prefix)
if include_special_flags:
self._render_module_flags(
'absl.flags',
six.itervalues(_helpers.SPECIAL_FLAGS._flags()), # pylint: disable=protected-access
output_lines,
prefix)
return '\n'.join(output_lines) | python | def _get_help_for_modules(self, modules, prefix, include_special_flags):
"""Returns the help string for a list of modules.
Private to absl.flags package.
Args:
modules: List[str], a list of modules to get the help string for.
prefix: str, a string that is prepended to each generated help line.
include_special_flags: bool, whether to include description of
SPECIAL_FLAGS, i.e. --flagfile and --undefok.
"""
output_lines = []
for module in modules:
self._render_our_module_flags(module, output_lines, prefix)
if include_special_flags:
self._render_module_flags(
'absl.flags',
six.itervalues(_helpers.SPECIAL_FLAGS._flags()), # pylint: disable=protected-access
output_lines,
prefix)
return '\n'.join(output_lines) | [
"def",
"_get_help_for_modules",
"(",
"self",
",",
"modules",
",",
"prefix",
",",
"include_special_flags",
")",
":",
"output_lines",
"=",
"[",
"]",
"for",
"module",
"in",
"modules",
":",
"self",
".",
"_render_our_module_flags",
"(",
"module",
",",
"output_lines",... | Returns the help string for a list of modules.
Private to absl.flags package.
Args:
modules: List[str], a list of modules to get the help string for.
prefix: str, a string that is prepended to each generated help line.
include_special_flags: bool, whether to include description of
SPECIAL_FLAGS, i.e. --flagfile and --undefok. | [
"Returns",
"the",
"help",
"string",
"for",
"a",
"list",
"of",
"modules",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L859-L879 | train | 215,282 |
abseil/abseil-py | absl/flags/_flagvalues.py | FlagValues._render_our_module_key_flags | def _render_our_module_key_flags(self, module, output_lines, prefix=''):
"""Returns a help string for the key flags of a given module.
Args:
module: module|str, the module to render key flags for.
output_lines: [str], a list of strings. The generated help message
lines will be appended to this list.
prefix: str, a string that is prepended to each generated help line.
"""
key_flags = self.get_key_flags_for_module(module)
if key_flags:
self._render_module_flags(module, key_flags, output_lines, prefix) | python | def _render_our_module_key_flags(self, module, output_lines, prefix=''):
"""Returns a help string for the key flags of a given module.
Args:
module: module|str, the module to render key flags for.
output_lines: [str], a list of strings. The generated help message
lines will be appended to this list.
prefix: str, a string that is prepended to each generated help line.
"""
key_flags = self.get_key_flags_for_module(module)
if key_flags:
self._render_module_flags(module, key_flags, output_lines, prefix) | [
"def",
"_render_our_module_key_flags",
"(",
"self",
",",
"module",
",",
"output_lines",
",",
"prefix",
"=",
"''",
")",
":",
"key_flags",
"=",
"self",
".",
"get_key_flags_for_module",
"(",
"module",
")",
"if",
"key_flags",
":",
"self",
".",
"_render_module_flags"... | Returns a help string for the key flags of a given module.
Args:
module: module|str, the module to render key flags for.
output_lines: [str], a list of strings. The generated help message
lines will be appended to this list.
prefix: str, a string that is prepended to each generated help line. | [
"Returns",
"a",
"help",
"string",
"for",
"the",
"key",
"flags",
"of",
"a",
"given",
"module",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L894-L905 | train | 215,283 |
abseil/abseil-py | absl/flags/_flagvalues.py | FlagValues.module_help | def module_help(self, module):
"""Describes the key flags of a module.
Args:
module: module|str, the module to describe the key flags for.
Returns:
str, describing the key flags of a module.
"""
helplist = []
self._render_our_module_key_flags(module, helplist)
return '\n'.join(helplist) | python | def module_help(self, module):
"""Describes the key flags of a module.
Args:
module: module|str, the module to describe the key flags for.
Returns:
str, describing the key flags of a module.
"""
helplist = []
self._render_our_module_key_flags(module, helplist)
return '\n'.join(helplist) | [
"def",
"module_help",
"(",
"self",
",",
"module",
")",
":",
"helplist",
"=",
"[",
"]",
"self",
".",
"_render_our_module_key_flags",
"(",
"module",
",",
"helplist",
")",
"return",
"'\\n'",
".",
"join",
"(",
"helplist",
")"
] | Describes the key flags of a module.
Args:
module: module|str, the module to describe the key flags for.
Returns:
str, describing the key flags of a module. | [
"Describes",
"the",
"key",
"flags",
"of",
"a",
"module",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L907-L918 | train | 215,284 |
abseil/abseil-py | absl/flags/_flagvalues.py | FlagValues.write_help_in_xml_format | def write_help_in_xml_format(self, outfile=None):
"""Outputs flag documentation in XML format.
NOTE: We use element names that are consistent with those used by
the C++ command-line flag library, from
https://github.com/gflags/gflags.
We also use a few new elements (e.g., <key>), but we do not
interfere / overlap with existing XML elements used by the C++
library. Please maintain this consistency.
Args:
outfile: File object we write to. Default None means sys.stdout.
"""
doc = minidom.Document()
all_flag = doc.createElement('AllFlags')
doc.appendChild(all_flag)
all_flag.appendChild(_helpers.create_xml_dom_element(
doc, 'program', os.path.basename(sys.argv[0])))
usage_doc = sys.modules['__main__'].__doc__
if not usage_doc:
usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0]
else:
usage_doc = usage_doc.replace('%s', sys.argv[0])
all_flag.appendChild(_helpers.create_xml_dom_element(
doc, 'usage', usage_doc))
# Get list of key flags for the main module.
key_flags = self.get_key_flags_for_module(sys.argv[0])
# Sort flags by declaring module name and next by flag name.
flags_by_module = self.flags_by_module_dict()
all_module_names = list(flags_by_module.keys())
all_module_names.sort()
for module_name in all_module_names:
flag_list = [(f.name, f) for f in flags_by_module[module_name]]
flag_list.sort()
for unused_flag_name, flag in flag_list:
is_key = flag in key_flags
all_flag.appendChild(flag._create_xml_dom_element( # pylint: disable=protected-access
doc, module_name, is_key=is_key))
outfile = outfile or sys.stdout
if six.PY2:
outfile.write(doc.toprettyxml(indent=' ', encoding='utf-8'))
else:
outfile.write(
doc.toprettyxml(indent=' ', encoding='utf-8').decode('utf-8'))
outfile.flush() | python | def write_help_in_xml_format(self, outfile=None):
"""Outputs flag documentation in XML format.
NOTE: We use element names that are consistent with those used by
the C++ command-line flag library, from
https://github.com/gflags/gflags.
We also use a few new elements (e.g., <key>), but we do not
interfere / overlap with existing XML elements used by the C++
library. Please maintain this consistency.
Args:
outfile: File object we write to. Default None means sys.stdout.
"""
doc = minidom.Document()
all_flag = doc.createElement('AllFlags')
doc.appendChild(all_flag)
all_flag.appendChild(_helpers.create_xml_dom_element(
doc, 'program', os.path.basename(sys.argv[0])))
usage_doc = sys.modules['__main__'].__doc__
if not usage_doc:
usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0]
else:
usage_doc = usage_doc.replace('%s', sys.argv[0])
all_flag.appendChild(_helpers.create_xml_dom_element(
doc, 'usage', usage_doc))
# Get list of key flags for the main module.
key_flags = self.get_key_flags_for_module(sys.argv[0])
# Sort flags by declaring module name and next by flag name.
flags_by_module = self.flags_by_module_dict()
all_module_names = list(flags_by_module.keys())
all_module_names.sort()
for module_name in all_module_names:
flag_list = [(f.name, f) for f in flags_by_module[module_name]]
flag_list.sort()
for unused_flag_name, flag in flag_list:
is_key = flag in key_flags
all_flag.appendChild(flag._create_xml_dom_element( # pylint: disable=protected-access
doc, module_name, is_key=is_key))
outfile = outfile or sys.stdout
if six.PY2:
outfile.write(doc.toprettyxml(indent=' ', encoding='utf-8'))
else:
outfile.write(
doc.toprettyxml(indent=' ', encoding='utf-8').decode('utf-8'))
outfile.flush() | [
"def",
"write_help_in_xml_format",
"(",
"self",
",",
"outfile",
"=",
"None",
")",
":",
"doc",
"=",
"minidom",
".",
"Document",
"(",
")",
"all_flag",
"=",
"doc",
".",
"createElement",
"(",
"'AllFlags'",
")",
"doc",
".",
"appendChild",
"(",
"all_flag",
")",
... | Outputs flag documentation in XML format.
NOTE: We use element names that are consistent with those used by
the C++ command-line flag library, from
https://github.com/gflags/gflags.
We also use a few new elements (e.g., <key>), but we do not
interfere / overlap with existing XML elements used by the C++
library. Please maintain this consistency.
Args:
outfile: File object we write to. Default None means sys.stdout. | [
"Outputs",
"flag",
"documentation",
"in",
"XML",
"format",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L1206-L1255 | train | 215,285 |
abseil/abseil-py | absl/logging/converter.py | absl_to_cpp | def absl_to_cpp(level):
"""Converts an absl log level to a cpp log level.
Args:
level: int, an absl.logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in Abseil C++.
"""
if not isinstance(level, int):
raise TypeError('Expect an int level, found {}'.format(type(level)))
if level >= 0:
# C++ log levels must be >= 0
return 0
else:
return -level | python | def absl_to_cpp(level):
"""Converts an absl log level to a cpp log level.
Args:
level: int, an absl.logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in Abseil C++.
"""
if not isinstance(level, int):
raise TypeError('Expect an int level, found {}'.format(type(level)))
if level >= 0:
# C++ log levels must be >= 0
return 0
else:
return -level | [
"def",
"absl_to_cpp",
"(",
"level",
")",
":",
"if",
"not",
"isinstance",
"(",
"level",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"'Expect an int level, found {}'",
".",
"format",
"(",
"type",
"(",
"level",
")",
")",
")",
"if",
"level",
">=",
"0",
... | Converts an absl log level to a cpp log level.
Args:
level: int, an absl.logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in Abseil C++. | [
"Converts",
"an",
"absl",
"log",
"level",
"to",
"a",
"cpp",
"log",
"level",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/converter.py#L117-L135 | train | 215,286 |
abseil/abseil-py | absl/logging/converter.py | absl_to_standard | def absl_to_standard(level):
"""Converts an integer level from the absl value to the standard value.
Args:
level: int, an absl.logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in standard logging.
"""
if not isinstance(level, int):
raise TypeError('Expect an int level, found {}'.format(type(level)))
if level < ABSL_FATAL:
level = ABSL_FATAL
if level <= ABSL_DEBUG:
return ABSL_TO_STANDARD[level]
# Maps to vlog levels.
return STANDARD_DEBUG - level + 1 | python | def absl_to_standard(level):
"""Converts an integer level from the absl value to the standard value.
Args:
level: int, an absl.logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in standard logging.
"""
if not isinstance(level, int):
raise TypeError('Expect an int level, found {}'.format(type(level)))
if level < ABSL_FATAL:
level = ABSL_FATAL
if level <= ABSL_DEBUG:
return ABSL_TO_STANDARD[level]
# Maps to vlog levels.
return STANDARD_DEBUG - level + 1 | [
"def",
"absl_to_standard",
"(",
"level",
")",
":",
"if",
"not",
"isinstance",
"(",
"level",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"'Expect an int level, found {}'",
".",
"format",
"(",
"type",
"(",
"level",
")",
")",
")",
"if",
"level",
"<",
"... | Converts an integer level from the absl value to the standard value.
Args:
level: int, an absl.logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in standard logging. | [
"Converts",
"an",
"integer",
"level",
"from",
"the",
"absl",
"value",
"to",
"the",
"standard",
"value",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/converter.py#L138-L157 | train | 215,287 |
abseil/abseil-py | absl/logging/converter.py | standard_to_absl | def standard_to_absl(level):
"""Converts an integer level from the standard value to the absl value.
Args:
level: int, a Python standard logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in absl logging.
"""
if not isinstance(level, int):
raise TypeError('Expect an int level, found {}'.format(type(level)))
if level < 0:
level = 0
if level < STANDARD_DEBUG:
# Maps to vlog levels.
return STANDARD_DEBUG - level + 1
elif level < STANDARD_INFO:
return ABSL_DEBUG
elif level < STANDARD_WARNING:
return ABSL_INFO
elif level < STANDARD_ERROR:
return ABSL_WARNING
elif level < STANDARD_CRITICAL:
return ABSL_ERROR
else:
return ABSL_FATAL | python | def standard_to_absl(level):
"""Converts an integer level from the standard value to the absl value.
Args:
level: int, a Python standard logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in absl logging.
"""
if not isinstance(level, int):
raise TypeError('Expect an int level, found {}'.format(type(level)))
if level < 0:
level = 0
if level < STANDARD_DEBUG:
# Maps to vlog levels.
return STANDARD_DEBUG - level + 1
elif level < STANDARD_INFO:
return ABSL_DEBUG
elif level < STANDARD_WARNING:
return ABSL_INFO
elif level < STANDARD_ERROR:
return ABSL_WARNING
elif level < STANDARD_CRITICAL:
return ABSL_ERROR
else:
return ABSL_FATAL | [
"def",
"standard_to_absl",
"(",
"level",
")",
":",
"if",
"not",
"isinstance",
"(",
"level",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"'Expect an int level, found {}'",
".",
"format",
"(",
"type",
"(",
"level",
")",
")",
")",
"if",
"level",
"<",
"... | Converts an integer level from the standard value to the absl value.
Args:
level: int, a Python standard logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in absl logging. | [
"Converts",
"an",
"integer",
"level",
"from",
"the",
"standard",
"value",
"to",
"the",
"absl",
"value",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/converter.py#L172-L200 | train | 215,288 |
abseil/abseil-py | absl/app.py | parse_flags_with_usage | def parse_flags_with_usage(args):
"""Tries to parse the flags, print usage, and exit if unparseable.
Args:
args: [str], a non-empty list of the command line arguments including
program name.
Returns:
[str], a non-empty list of remaining command line arguments after parsing
flags, including program name.
"""
try:
return FLAGS(args)
except flags.Error as error:
sys.stderr.write('FATAL Flags parsing error: %s\n' % error)
sys.stderr.write('Pass --helpshort or --helpfull to see help on flags.\n')
sys.exit(1) | python | def parse_flags_with_usage(args):
"""Tries to parse the flags, print usage, and exit if unparseable.
Args:
args: [str], a non-empty list of the command line arguments including
program name.
Returns:
[str], a non-empty list of remaining command line arguments after parsing
flags, including program name.
"""
try:
return FLAGS(args)
except flags.Error as error:
sys.stderr.write('FATAL Flags parsing error: %s\n' % error)
sys.stderr.write('Pass --helpshort or --helpfull to see help on flags.\n')
sys.exit(1) | [
"def",
"parse_flags_with_usage",
"(",
"args",
")",
":",
"try",
":",
"return",
"FLAGS",
"(",
"args",
")",
"except",
"flags",
".",
"Error",
"as",
"error",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'FATAL Flags parsing error: %s\\n'",
"%",
"error",
")",
... | Tries to parse the flags, print usage, and exit if unparseable.
Args:
args: [str], a non-empty list of the command line arguments including
program name.
Returns:
[str], a non-empty list of remaining command line arguments after parsing
flags, including program name. | [
"Tries",
"to",
"parse",
"the",
"flags",
"print",
"usage",
"and",
"exit",
"if",
"unparseable",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L147-L163 | train | 215,289 |
abseil/abseil-py | absl/app.py | define_help_flags | def define_help_flags():
"""Registers help flags. Idempotent."""
# Use a global to ensure idempotence.
global _define_help_flags_called
if not _define_help_flags_called:
flags.DEFINE_flag(HelpFlag())
flags.DEFINE_flag(HelpshortFlag()) # alias for --help
flags.DEFINE_flag(HelpfullFlag())
flags.DEFINE_flag(HelpXMLFlag())
_define_help_flags_called = True | python | def define_help_flags():
"""Registers help flags. Idempotent."""
# Use a global to ensure idempotence.
global _define_help_flags_called
if not _define_help_flags_called:
flags.DEFINE_flag(HelpFlag())
flags.DEFINE_flag(HelpshortFlag()) # alias for --help
flags.DEFINE_flag(HelpfullFlag())
flags.DEFINE_flag(HelpXMLFlag())
_define_help_flags_called = True | [
"def",
"define_help_flags",
"(",
")",
":",
"# Use a global to ensure idempotence.",
"global",
"_define_help_flags_called",
"if",
"not",
"_define_help_flags_called",
":",
"flags",
".",
"DEFINE_flag",
"(",
"HelpFlag",
"(",
")",
")",
"flags",
".",
"DEFINE_flag",
"(",
"He... | Registers help flags. Idempotent. | [
"Registers",
"help",
"flags",
".",
"Idempotent",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L169-L179 | train | 215,290 |
abseil/abseil-py | absl/app.py | _register_and_parse_flags_with_usage | def _register_and_parse_flags_with_usage(
argv=None,
flags_parser=parse_flags_with_usage,
):
"""Registers help flags, parses arguments and shows usage if appropriate.
This also calls sys.exit(0) if flag --only_check_args is True.
Args:
argv: [str], a non-empty list of the command line arguments including
program name, sys.argv is used if None.
flags_parser: Callable[[List[Text]], Any], the function used to parse flags.
The return value of this function is passed to `main` untouched.
It must guarantee FLAGS is parsed after this function is called.
Returns:
The return value of `flags_parser`. When using the default `flags_parser`,
it returns the following:
[str], a non-empty list of remaining command line arguments after parsing
flags, including program name.
Raises:
Error: Raised when flags_parser is called, but FLAGS is not parsed.
SystemError: Raised when it's called more than once.
"""
if _register_and_parse_flags_with_usage.done:
raise SystemError('Flag registration can be done only once.')
define_help_flags()
original_argv = sys.argv if argv is None else argv
args_to_main = flags_parser(original_argv)
if not FLAGS.is_parsed():
raise Error('FLAGS must be parsed after flags_parser is called.')
# Exit when told so.
if FLAGS.only_check_args:
sys.exit(0)
# Immediately after flags are parsed, bump verbosity to INFO if the flag has
# not been set.
if FLAGS['verbosity'].using_default_value:
FLAGS.verbosity = 0
_register_and_parse_flags_with_usage.done = True
return args_to_main | python | def _register_and_parse_flags_with_usage(
argv=None,
flags_parser=parse_flags_with_usage,
):
"""Registers help flags, parses arguments and shows usage if appropriate.
This also calls sys.exit(0) if flag --only_check_args is True.
Args:
argv: [str], a non-empty list of the command line arguments including
program name, sys.argv is used if None.
flags_parser: Callable[[List[Text]], Any], the function used to parse flags.
The return value of this function is passed to `main` untouched.
It must guarantee FLAGS is parsed after this function is called.
Returns:
The return value of `flags_parser`. When using the default `flags_parser`,
it returns the following:
[str], a non-empty list of remaining command line arguments after parsing
flags, including program name.
Raises:
Error: Raised when flags_parser is called, but FLAGS is not parsed.
SystemError: Raised when it's called more than once.
"""
if _register_and_parse_flags_with_usage.done:
raise SystemError('Flag registration can be done only once.')
define_help_flags()
original_argv = sys.argv if argv is None else argv
args_to_main = flags_parser(original_argv)
if not FLAGS.is_parsed():
raise Error('FLAGS must be parsed after flags_parser is called.')
# Exit when told so.
if FLAGS.only_check_args:
sys.exit(0)
# Immediately after flags are parsed, bump verbosity to INFO if the flag has
# not been set.
if FLAGS['verbosity'].using_default_value:
FLAGS.verbosity = 0
_register_and_parse_flags_with_usage.done = True
return args_to_main | [
"def",
"_register_and_parse_flags_with_usage",
"(",
"argv",
"=",
"None",
",",
"flags_parser",
"=",
"parse_flags_with_usage",
",",
")",
":",
"if",
"_register_and_parse_flags_with_usage",
".",
"done",
":",
"raise",
"SystemError",
"(",
"'Flag registration can be done only once... | Registers help flags, parses arguments and shows usage if appropriate.
This also calls sys.exit(0) if flag --only_check_args is True.
Args:
argv: [str], a non-empty list of the command line arguments including
program name, sys.argv is used if None.
flags_parser: Callable[[List[Text]], Any], the function used to parse flags.
The return value of this function is passed to `main` untouched.
It must guarantee FLAGS is parsed after this function is called.
Returns:
The return value of `flags_parser`. When using the default `flags_parser`,
it returns the following:
[str], a non-empty list of remaining command line arguments after parsing
flags, including program name.
Raises:
Error: Raised when flags_parser is called, but FLAGS is not parsed.
SystemError: Raised when it's called more than once. | [
"Registers",
"help",
"flags",
"parses",
"arguments",
"and",
"shows",
"usage",
"if",
"appropriate",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L182-L226 | train | 215,291 |
abseil/abseil-py | absl/app.py | _run_main | def _run_main(main, argv):
"""Calls main, optionally with pdb or profiler."""
if FLAGS.run_with_pdb:
sys.exit(pdb.runcall(main, argv))
elif FLAGS.run_with_profiling or FLAGS.profile_file:
# Avoid import overhead since most apps (including performance-sensitive
# ones) won't be run with profiling.
import atexit
if FLAGS.use_cprofile_for_profiling:
import cProfile as profile
else:
import profile
profiler = profile.Profile()
if FLAGS.profile_file:
atexit.register(profiler.dump_stats, FLAGS.profile_file)
else:
atexit.register(profiler.print_stats)
retval = profiler.runcall(main, argv)
sys.exit(retval)
else:
sys.exit(main(argv)) | python | def _run_main(main, argv):
"""Calls main, optionally with pdb or profiler."""
if FLAGS.run_with_pdb:
sys.exit(pdb.runcall(main, argv))
elif FLAGS.run_with_profiling or FLAGS.profile_file:
# Avoid import overhead since most apps (including performance-sensitive
# ones) won't be run with profiling.
import atexit
if FLAGS.use_cprofile_for_profiling:
import cProfile as profile
else:
import profile
profiler = profile.Profile()
if FLAGS.profile_file:
atexit.register(profiler.dump_stats, FLAGS.profile_file)
else:
atexit.register(profiler.print_stats)
retval = profiler.runcall(main, argv)
sys.exit(retval)
else:
sys.exit(main(argv)) | [
"def",
"_run_main",
"(",
"main",
",",
"argv",
")",
":",
"if",
"FLAGS",
".",
"run_with_pdb",
":",
"sys",
".",
"exit",
"(",
"pdb",
".",
"runcall",
"(",
"main",
",",
"argv",
")",
")",
"elif",
"FLAGS",
".",
"run_with_profiling",
"or",
"FLAGS",
".",
"prof... | Calls main, optionally with pdb or profiler. | [
"Calls",
"main",
"optionally",
"with",
"pdb",
"or",
"profiler",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L231-L251 | train | 215,292 |
abseil/abseil-py | absl/app.py | _call_exception_handlers | def _call_exception_handlers(exception):
"""Calls any installed exception handlers."""
for handler in EXCEPTION_HANDLERS:
try:
if handler.wants(exception):
handler.handle(exception)
except: # pylint: disable=bare-except
try:
# We don't want to stop for exceptions in the exception handlers but
# we shouldn't hide them either.
logging.error(traceback.format_exc())
except: # pylint: disable=bare-except
# In case even the logging statement fails, ignore.
pass | python | def _call_exception_handlers(exception):
"""Calls any installed exception handlers."""
for handler in EXCEPTION_HANDLERS:
try:
if handler.wants(exception):
handler.handle(exception)
except: # pylint: disable=bare-except
try:
# We don't want to stop for exceptions in the exception handlers but
# we shouldn't hide them either.
logging.error(traceback.format_exc())
except: # pylint: disable=bare-except
# In case even the logging statement fails, ignore.
pass | [
"def",
"_call_exception_handlers",
"(",
"exception",
")",
":",
"for",
"handler",
"in",
"EXCEPTION_HANDLERS",
":",
"try",
":",
"if",
"handler",
".",
"wants",
"(",
"exception",
")",
":",
"handler",
".",
"handle",
"(",
"exception",
")",
"except",
":",
"# pylint... | Calls any installed exception handlers. | [
"Calls",
"any",
"installed",
"exception",
"handlers",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L254-L267 | train | 215,293 |
abseil/abseil-py | absl/app.py | run | def run(
main,
argv=None,
flags_parser=parse_flags_with_usage,
):
"""Begins executing the program.
Args:
main: The main function to execute. It takes an single argument "argv",
which is a list of command line arguments with parsed flags removed.
If it returns an integer, it is used as the process's exit code.
argv: A non-empty list of the command line arguments including program name,
sys.argv is used if None.
flags_parser: Callable[[List[Text]], Any], the function used to parse flags.
The return value of this function is passed to `main` untouched.
It must guarantee FLAGS is parsed after this function is called.
- Parses command line flags with the flag module.
- If there are any errors, prints usage().
- Calls main() with the remaining arguments.
- If main() raises a UsageError, prints usage and the error message.
"""
try:
args = _run_init(
sys.argv if argv is None else argv,
flags_parser,
)
while _init_callbacks:
callback = _init_callbacks.popleft()
callback()
try:
_run_main(main, args)
except UsageError as error:
usage(shorthelp=True, detailed_error=error, exitcode=error.exitcode)
except:
if FLAGS.pdb_post_mortem:
traceback.print_exc()
pdb.post_mortem()
raise
except Exception as e:
_call_exception_handlers(e)
raise | python | def run(
main,
argv=None,
flags_parser=parse_flags_with_usage,
):
"""Begins executing the program.
Args:
main: The main function to execute. It takes an single argument "argv",
which is a list of command line arguments with parsed flags removed.
If it returns an integer, it is used as the process's exit code.
argv: A non-empty list of the command line arguments including program name,
sys.argv is used if None.
flags_parser: Callable[[List[Text]], Any], the function used to parse flags.
The return value of this function is passed to `main` untouched.
It must guarantee FLAGS is parsed after this function is called.
- Parses command line flags with the flag module.
- If there are any errors, prints usage().
- Calls main() with the remaining arguments.
- If main() raises a UsageError, prints usage and the error message.
"""
try:
args = _run_init(
sys.argv if argv is None else argv,
flags_parser,
)
while _init_callbacks:
callback = _init_callbacks.popleft()
callback()
try:
_run_main(main, args)
except UsageError as error:
usage(shorthelp=True, detailed_error=error, exitcode=error.exitcode)
except:
if FLAGS.pdb_post_mortem:
traceback.print_exc()
pdb.post_mortem()
raise
except Exception as e:
_call_exception_handlers(e)
raise | [
"def",
"run",
"(",
"main",
",",
"argv",
"=",
"None",
",",
"flags_parser",
"=",
"parse_flags_with_usage",
",",
")",
":",
"try",
":",
"args",
"=",
"_run_init",
"(",
"sys",
".",
"argv",
"if",
"argv",
"is",
"None",
"else",
"argv",
",",
"flags_parser",
",",... | Begins executing the program.
Args:
main: The main function to execute. It takes an single argument "argv",
which is a list of command line arguments with parsed flags removed.
If it returns an integer, it is used as the process's exit code.
argv: A non-empty list of the command line arguments including program name,
sys.argv is used if None.
flags_parser: Callable[[List[Text]], Any], the function used to parse flags.
The return value of this function is passed to `main` untouched.
It must guarantee FLAGS is parsed after this function is called.
- Parses command line flags with the flag module.
- If there are any errors, prints usage().
- Calls main() with the remaining arguments.
- If main() raises a UsageError, prints usage and the error message. | [
"Begins",
"executing",
"the",
"program",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L270-L310 | train | 215,294 |
abseil/abseil-py | absl/app.py | _run_init | def _run_init(
argv,
flags_parser,
):
"""Does one-time initialization and re-parses flags on rerun."""
if _run_init.done:
return flags_parser(argv)
command_name.make_process_name_useful()
# Set up absl logging handler.
logging.use_absl_handler()
args = _register_and_parse_flags_with_usage(
argv=argv,
flags_parser=flags_parser,
)
if faulthandler:
try:
faulthandler.enable()
except Exception: # pylint: disable=broad-except
# Some tests verify stderr output very closely, so don't print anything.
# Disabled faulthandler is a low-impact error.
pass
_run_init.done = True
return args | python | def _run_init(
argv,
flags_parser,
):
"""Does one-time initialization and re-parses flags on rerun."""
if _run_init.done:
return flags_parser(argv)
command_name.make_process_name_useful()
# Set up absl logging handler.
logging.use_absl_handler()
args = _register_and_parse_flags_with_usage(
argv=argv,
flags_parser=flags_parser,
)
if faulthandler:
try:
faulthandler.enable()
except Exception: # pylint: disable=broad-except
# Some tests verify stderr output very closely, so don't print anything.
# Disabled faulthandler is a low-impact error.
pass
_run_init.done = True
return args | [
"def",
"_run_init",
"(",
"argv",
",",
"flags_parser",
",",
")",
":",
"if",
"_run_init",
".",
"done",
":",
"return",
"flags_parser",
"(",
"argv",
")",
"command_name",
".",
"make_process_name_useful",
"(",
")",
"# Set up absl logging handler.",
"logging",
".",
"us... | Does one-time initialization and re-parses flags on rerun. | [
"Does",
"one",
"-",
"time",
"initialization",
"and",
"re",
"-",
"parses",
"flags",
"on",
"rerun",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L339-L361 | train | 215,295 |
abseil/abseil-py | absl/app.py | install_exception_handler | def install_exception_handler(handler):
"""Installs an exception handler.
Args:
handler: ExceptionHandler, the exception handler to install.
Raises:
TypeError: Raised when the handler was not of the correct type.
All installed exception handlers will be called if main() exits via
an abnormal exception, i.e. not one of SystemExit, KeyboardInterrupt,
FlagsError or UsageError.
"""
if not isinstance(handler, ExceptionHandler):
raise TypeError('handler of type %s does not inherit from ExceptionHandler'
% type(handler))
EXCEPTION_HANDLERS.append(handler) | python | def install_exception_handler(handler):
"""Installs an exception handler.
Args:
handler: ExceptionHandler, the exception handler to install.
Raises:
TypeError: Raised when the handler was not of the correct type.
All installed exception handlers will be called if main() exits via
an abnormal exception, i.e. not one of SystemExit, KeyboardInterrupt,
FlagsError or UsageError.
"""
if not isinstance(handler, ExceptionHandler):
raise TypeError('handler of type %s does not inherit from ExceptionHandler'
% type(handler))
EXCEPTION_HANDLERS.append(handler) | [
"def",
"install_exception_handler",
"(",
"handler",
")",
":",
"if",
"not",
"isinstance",
"(",
"handler",
",",
"ExceptionHandler",
")",
":",
"raise",
"TypeError",
"(",
"'handler of type %s does not inherit from ExceptionHandler'",
"%",
"type",
"(",
"handler",
")",
")",... | Installs an exception handler.
Args:
handler: ExceptionHandler, the exception handler to install.
Raises:
TypeError: Raised when the handler was not of the correct type.
All installed exception handlers will be called if main() exits via
an abnormal exception, i.e. not one of SystemExit, KeyboardInterrupt,
FlagsError or UsageError. | [
"Installs",
"an",
"exception",
"handler",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L444-L460 | train | 215,296 |
abseil/abseil-py | absl/flags/_validators.py | register_validator | def register_validator(flag_name,
checker,
message='Flag validation failed',
flag_values=_flagvalues.FLAGS):
"""Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: str, name of the flag to be checked.
checker: callable, a function to validate the flag.
input - A single positional argument: The value of the corresponding
flag (string, boolean, etc. This value will be passed to checker
by the library).
output - bool, True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise flags.ValidationError(desired_error_message).
message: str, error text to be shown to the user if checker returns False.
If checker raises flags.ValidationError, message from the raised
error will be shown.
flag_values: flags.FlagValues, optional FlagValues instance to validate
against.
Raises:
AttributeError: Raised when flag_name is not registered as a valid flag
name.
"""
v = SingleFlagValidator(flag_name, checker, message)
_add_validator(flag_values, v) | python | def register_validator(flag_name,
checker,
message='Flag validation failed',
flag_values=_flagvalues.FLAGS):
"""Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: str, name of the flag to be checked.
checker: callable, a function to validate the flag.
input - A single positional argument: The value of the corresponding
flag (string, boolean, etc. This value will be passed to checker
by the library).
output - bool, True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise flags.ValidationError(desired_error_message).
message: str, error text to be shown to the user if checker returns False.
If checker raises flags.ValidationError, message from the raised
error will be shown.
flag_values: flags.FlagValues, optional FlagValues instance to validate
against.
Raises:
AttributeError: Raised when flag_name is not registered as a valid flag
name.
"""
v = SingleFlagValidator(flag_name, checker, message)
_add_validator(flag_values, v) | [
"def",
"register_validator",
"(",
"flag_name",
",",
"checker",
",",
"message",
"=",
"'Flag validation failed'",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
")",
":",
"v",
"=",
"SingleFlagValidator",
"(",
"flag_name",
",",
"checker",
",",
"message",
")"... | Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: str, name of the flag to be checked.
checker: callable, a function to validate the flag.
input - A single positional argument: The value of the corresponding
flag (string, boolean, etc. This value will be passed to checker
by the library).
output - bool, True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise flags.ValidationError(desired_error_message).
message: str, error text to be shown to the user if checker returns False.
If checker raises flags.ValidationError, message from the raised
error will be shown.
flag_values: flags.FlagValues, optional FlagValues instance to validate
against.
Raises:
AttributeError: Raised when flag_name is not registered as a valid flag
name. | [
"Adds",
"a",
"constraint",
"which",
"will",
"be",
"enforced",
"during",
"program",
"execution",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L196-L223 | train | 215,297 |
abseil/abseil-py | absl/flags/_validators.py | validator | def validator(flag_name, message='Flag validation failed',
flag_values=_flagvalues.FLAGS):
"""A function decorator for defining a flag validator.
Registers the decorated function as a validator for flag_name, e.g.
@flags.validator('foo')
def _CheckFoo(foo):
...
See register_validator() for the specification of checker function.
Args:
flag_name: str, name of the flag to be checked.
message: str, error text to be shown to the user if checker returns False.
If checker raises flags.ValidationError, message from the raised
error will be shown.
flag_values: flags.FlagValues, optional FlagValues instance to validate
against.
Returns:
A function decorator that registers its function argument as a validator.
Raises:
AttributeError: Raised when flag_name is not registered as a valid flag
name.
"""
def decorate(function):
register_validator(flag_name, function,
message=message,
flag_values=flag_values)
return function
return decorate | python | def validator(flag_name, message='Flag validation failed',
flag_values=_flagvalues.FLAGS):
"""A function decorator for defining a flag validator.
Registers the decorated function as a validator for flag_name, e.g.
@flags.validator('foo')
def _CheckFoo(foo):
...
See register_validator() for the specification of checker function.
Args:
flag_name: str, name of the flag to be checked.
message: str, error text to be shown to the user if checker returns False.
If checker raises flags.ValidationError, message from the raised
error will be shown.
flag_values: flags.FlagValues, optional FlagValues instance to validate
against.
Returns:
A function decorator that registers its function argument as a validator.
Raises:
AttributeError: Raised when flag_name is not registered as a valid flag
name.
"""
def decorate(function):
register_validator(flag_name, function,
message=message,
flag_values=flag_values)
return function
return decorate | [
"def",
"validator",
"(",
"flag_name",
",",
"message",
"=",
"'Flag validation failed'",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
")",
":",
"def",
"decorate",
"(",
"function",
")",
":",
"register_validator",
"(",
"flag_name",
",",
"function",
",",
"... | A function decorator for defining a flag validator.
Registers the decorated function as a validator for flag_name, e.g.
@flags.validator('foo')
def _CheckFoo(foo):
...
See register_validator() for the specification of checker function.
Args:
flag_name: str, name of the flag to be checked.
message: str, error text to be shown to the user if checker returns False.
If checker raises flags.ValidationError, message from the raised
error will be shown.
flag_values: flags.FlagValues, optional FlagValues instance to validate
against.
Returns:
A function decorator that registers its function argument as a validator.
Raises:
AttributeError: Raised when flag_name is not registered as a valid flag
name. | [
"A",
"function",
"decorator",
"for",
"defining",
"a",
"flag",
"validator",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L226-L257 | train | 215,298 |
abseil/abseil-py | absl/flags/_validators.py | mark_flags_as_required | def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS):
"""Ensures that flags are not None during program execution.
Recommended usage:
if __name__ == '__main__':
flags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])
app.run()
Args:
flag_names: Sequence[str], names of the flags.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined.
Raises:
AttributeError: If any of flag name has not already been defined as a flag.
"""
for flag_name in flag_names:
mark_flag_as_required(flag_name, flag_values) | python | def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS):
"""Ensures that flags are not None during program execution.
Recommended usage:
if __name__ == '__main__':
flags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])
app.run()
Args:
flag_names: Sequence[str], names of the flags.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined.
Raises:
AttributeError: If any of flag name has not already been defined as a flag.
"""
for flag_name in flag_names:
mark_flag_as_required(flag_name, flag_values) | [
"def",
"mark_flags_as_required",
"(",
"flag_names",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
")",
":",
"for",
"flag_name",
"in",
"flag_names",
":",
"mark_flag_as_required",
"(",
"flag_name",
",",
"flag_values",
")"
] | Ensures that flags are not None during program execution.
Recommended usage:
if __name__ == '__main__':
flags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])
app.run()
Args:
flag_names: Sequence[str], names of the flags.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined.
Raises:
AttributeError: If any of flag name has not already been defined as a flag. | [
"Ensures",
"that",
"flags",
"are",
"not",
"None",
"during",
"program",
"execution",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L367-L384 | train | 215,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.