_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q8800
not_next
train
def not_next(e): """ Create a PEG function for negative lookahead. """ def match_not_next(s, grm=None, pos=0): try: e(s, grm, pos) except PegreError as ex: return PegreResult(s, Ignore, (pos, pos)) else: raise PegreError('Negative lookahead failed', pos) return match_not_next
python
{ "resource": "" }
q8801
sequence
train
def sequence(*es): """ Create a PEG function to match a sequence. """ def match_sequence(s, grm=None, pos=0): data = [] start = pos for e in es: s, obj, span = e(s, grm, pos) pos = span[1] if obj is not Ignore: data.append(obj) return PegreResult(s, data, (start, pos)) return match_sequence
python
{ "resource": "" }
q8802
choice
train
def choice(*es): """ Create a PEG function to match an ordered choice. """ msg = 'Expected one of: {}'.format(', '.join(map(repr, es))) def match_choice(s, grm=None, pos=0): errs = [] for e in es: try: return e(s, grm, pos) except PegreError as ex: errs.append((ex.message, ex.position)) if errs: raise PegreChoiceError(errs, pos) return match_choice
python
{ "resource": "" }
q8803
optional
train
def optional(e, default=Ignore): """ Create a PEG function to optionally match an expression. """ def match_optional(s, grm=None, pos=0): try: return e(s, grm, pos) except PegreError: return PegreResult(s, default, (pos, pos)) return match_optional
python
{ "resource": "" }
q8804
zero_or_more
train
def zero_or_more(e, delimiter=None): """ Create a PEG function to match zero or more expressions. Args: e: the expression to match delimiter: an optional expression to match between the primary *e* matches. """ if delimiter is None: delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos)) def match_zero_or_more(s, grm=None, pos=0): start = pos try: s, obj, span = e(s, grm, pos) pos = span[1] data = [] if obj is Ignore else [obj] except PegreError: return PegreResult(s, [], (pos, pos)) try: while True: s, obj, span = delimiter(s, grm, pos) pos = span[1] if obj is not Ignore: data.append(obj) s, obj, span = e(s, grm, pos) pos = span[1] if obj is not Ignore: data.append(obj) except PegreError: pass return PegreResult(s, data, (start, pos)) return match_zero_or_more
python
{ "resource": "" }
q8805
one_or_more
train
def one_or_more(e, delimiter=None): """ Create a PEG function to match one or more expressions. Args: e: the expression to match delimiter: an optional expression to match between the primary *e* matches. """ if delimiter is None: delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos)) msg = 'Expected one or more of: {}'.format(repr(e)) def match_one_or_more(s, grm=None, pos=0): start = pos s, obj, span = e(s, grm, pos) pos = span[1] data = [] if obj is Ignore else [obj] try: while True: s, obj, span = delimiter(s, grm, pos) pos = span[1] if obj is not Ignore: data.append(obj) s, obj, span = e(s, grm, pos) pos = span[1] if obj is not Ignore: data.append(obj) except PegreError: pass return PegreResult(s, data, (start, pos)) return match_one_or_more
python
{ "resource": "" }
q8806
_prepare_axes
train
def _prepare_axes(node, sort_key): """ Sort axes and combine those that point to the same target and go in the same direction. """ links = node.links o_links = node._overlapping_links overlap = {ax2 for ax in links for ax2 in o_links.get(ax, [])} axes = [] for axis in sorted(links.keys(), key=sort_key): if axis in overlap: continue tgt = links[axis] if axis in o_links: s, e = axis[0], axis[-1] axis = '%s%s%s' % ( s, '&'.join(a[1:-1] for a in [axis] + o_links[axis]), e ) axes.append((axis, tgt)) return axes
python
{ "resource": "" }
q8807
_lex
train
def _lex(s): """ Lex the input string according to _tsql_lex_re. Yields (gid, token, line_number) """ s += '.' # make sure there's a terminator to know when to stop parsing lines = enumerate(s.splitlines(), 1) lineno = pos = 0 try: for lineno, line in lines: matches = _tsql_lex_re.finditer(line) for m in matches: gid = m.lastindex if gid == 11: raise TSQLSyntaxError('unexpected input', lineno=lineno, offset=m.start(), text=line) else: token = m.group(gid) yield (gid, token, lineno) except StopIteration: pass
python
{ "resource": "" }
q8808
Bot.get_webhook_info
train
def get_webhook_info(self, ): """ Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. https://core.telegram.org/bots/api#getwebhookinfo Returns: :return: On success, returns a WebhookInfo object :rtype: pytgbot.api_types.receivable.updates.WebhookInfo """ result = self.do("getWebhookInfo", ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import WebhookInfo try: return WebhookInfo.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type WebhookInfo", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8809
Bot.send_contact
train
def send_contact(self, chat_id, phone_number, first_name, last_name=None, vcard=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send phone contacts. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendcontact Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param phone_number: Contact's phone number :type phone_number: str|unicode :param first_name: Contact's first name :type first_name: str|unicode Optional keyword parameters: :param last_name: Contact's last name :type last_name: str|unicode :param vcard: Additional data about the contact in the form of a vCard, 0-2048 bytes :type vcard: str|unicode :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: bool :param reply_to_message_id: If the message is a reply, ID of the original message :type reply_to_message_id: int :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove keyboard or to force a reply from the user. :type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply Returns: :return: On success, the sent Message is returned :rtype: pytgbot.api_types.receivable.updates.Message """ from pytgbot.api_types.sendable.reply_markup import ForceReply from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardRemove assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(phone_number, unicode_type, parameter_name="phone_number") assert_type_or_raise(first_name, unicode_type, parameter_name="first_name") assert_type_or_raise(last_name, None, unicode_type, parameter_name="last_name") assert_type_or_raise(vcard, None, unicode_type, parameter_name="vcard") assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification") assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id") assert_type_or_raise(reply_markup, None, (InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply), parameter_name="reply_markup") result = self.do("sendContact", chat_id=chat_id, phone_number=phone_number, first_name=first_name, last_name=last_name, vcard=vcard, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8810
Bot.restrict_chat_member
train
def restrict_chat_member(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None): """ Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success. https://core.telegram.org/bots/api#restrictchatmember Parameters: :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) :type chat_id: int | str|unicode :param user_id: Unique identifier of the target user :type user_id: int Optional keyword parameters: :param until_date: Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever :type until_date: int :param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues :type can_send_messages: bool :param can_send_media_messages: Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages :type can_send_media_messages: bool :param can_send_other_messages: Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages :type can_send_other_messages: bool :param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, implies can_send_media_messages :type can_add_web_page_previews: bool Returns: :return: Returns True on success :rtype: bool """ assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(until_date, None, int, parameter_name="until_date") assert_type_or_raise(can_send_messages, None, bool, parameter_name="can_send_messages") assert_type_or_raise(can_send_media_messages, None, bool, parameter_name="can_send_media_messages") assert_type_or_raise(can_send_other_messages, None, bool, parameter_name="can_send_other_messages") assert_type_or_raise(can_add_web_page_previews, None, bool, parameter_name="can_add_web_page_previews") result = self.do("restrictChatMember", chat_id=chat_id, user_id=user_id, until_date=until_date, can_send_messages=can_send_messages, can_send_media_messages=can_send_media_messages, can_send_other_messages=can_send_other_messages, can_add_web_page_previews=can_add_web_page_previews) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8811
Bot.promote_chat_member
train
def promote_chat_member(self, chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None): """ Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success. https://core.telegram.org/bots/api#promotechatmember Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param user_id: Unique identifier of the target user :type user_id: int Optional keyword parameters: :param can_change_info: Pass True, if the administrator can change chat title, photo and other settings :type can_change_info: bool :param can_post_messages: Pass True, if the administrator can create channel posts, channels only :type can_post_messages: bool :param can_edit_messages: Pass True, if the administrator can edit messages of other users and can pin messages, channels only :type can_edit_messages: bool :param can_delete_messages: Pass True, if the administrator can delete messages of other users :type can_delete_messages: bool :param can_invite_users: Pass True, if the administrator can invite new users to the chat :type can_invite_users: bool :param can_restrict_members: Pass True, if the administrator can restrict, ban or unban chat members :type can_restrict_members: bool :param can_pin_messages: Pass True, if the administrator can pin messages, supergroups only :type can_pin_messages: bool :param can_promote_members: Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him) :type can_promote_members: bool Returns: :return: Returns True on success :rtype: bool """ assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(can_change_info, None, bool, parameter_name="can_change_info") assert_type_or_raise(can_post_messages, None, bool, parameter_name="can_post_messages") assert_type_or_raise(can_edit_messages, None, bool, parameter_name="can_edit_messages") assert_type_or_raise(can_delete_messages, None, bool, parameter_name="can_delete_messages") assert_type_or_raise(can_invite_users, None, bool, parameter_name="can_invite_users") assert_type_or_raise(can_restrict_members, None, bool, parameter_name="can_restrict_members") assert_type_or_raise(can_pin_messages, None, bool, parameter_name="can_pin_messages") assert_type_or_raise(can_promote_members, None, bool, parameter_name="can_promote_members") result = self.do("promoteChatMember", chat_id=chat_id, user_id=user_id, can_change_info=can_change_info, can_post_messages=can_post_messages, can_edit_messages=can_edit_messages, can_delete_messages=can_delete_messages, can_invite_users=can_invite_users, can_restrict_members=can_restrict_members, can_pin_messages=can_pin_messages, can_promote_members=can_promote_members) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8812
Bot.set_chat_photo
train
def set_chat_photo(self, chat_id, photo): """ Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group. https://core.telegram.org/bots/api#setchatphoto Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param photo: New chat photo, uploaded using multipart/form-data :type photo: pytgbot.api_types.sendable.files.InputFile Returns: :return: Returns True on success :rtype: bool """ from pytgbot.api_types.sendable.files import InputFile assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(photo, InputFile, parameter_name="photo") result = self.do("setChatPhoto", chat_id=chat_id, photo=photo) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8813
Bot.answer_callback_query
train
def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None): """ Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @Botfather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. https://core.telegram.org/bots/api#answercallbackquery Parameters: :param callback_query_id: Unique identifier for the query to be answered :type callback_query_id: str|unicode Optional keyword parameters: :param text: Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters :type text: str|unicode :param show_alert: If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. :type show_alert: bool :param url: URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. :type url: str|unicode :param cache_time: The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. :type cache_time: int Returns: :return: On success, True is returned :rtype: bool """ assert_type_or_raise(callback_query_id, unicode_type, parameter_name="callback_query_id") assert_type_or_raise(text, None, unicode_type, parameter_name="text") assert_type_or_raise(show_alert, None, bool, parameter_name="show_alert") assert_type_or_raise(url, None, unicode_type, parameter_name="url") assert_type_or_raise(cache_time, None, int, parameter_name="cache_time") result = self.do("answerCallbackQuery", callback_query_id=callback_query_id, text=text, show_alert=show_alert, url=url, cache_time=cache_time) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8814
Bot.get_sticker_set
train
def get_sticker_set(self, name): """ Use this method to get a sticker set. On success, a StickerSet object is returned. https://core.telegram.org/bots/api#getstickerset Parameters: :param name: Name of the sticker set :type name: str|unicode Returns: :return: On success, a StickerSet object is returned :rtype: pytgbot.api_types.receivable.stickers.StickerSet """ assert_type_or_raise(name, unicode_type, parameter_name="name") result = self.do("getStickerSet", name=name) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.stickers import StickerSet try: return StickerSet.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type StickerSet", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8815
Bot.create_new_sticker_set
train
def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, mask_position=None): """ Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success. https://core.telegram.org/bots/api#createnewstickerset Parameters: :param user_id: User identifier of created sticker set owner :type user_id: int :param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters. :type name: str|unicode :param title: Sticker set title, 1-64 characters :type title: str|unicode :param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files » :type png_sticker: pytgbot.api_types.sendable.files.InputFile | str|unicode :param emojis: One or more emoji corresponding to the sticker :type emojis: str|unicode Optional keyword parameters: :param contains_masks: Pass True, if a set of mask stickers should be created :type contains_masks: bool :param mask_position: A JSON-serialized object for position where the mask should be placed on faces :type mask_position: pytgbot.api_types.receivable.stickers.MaskPosition Returns: :return: Returns True on success :rtype: bool """ from pytgbot.api_types.receivable.stickers import MaskPosition from pytgbot.api_types.sendable.files import InputFile assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(name, unicode_type, parameter_name="name") assert_type_or_raise(title, unicode_type, parameter_name="title") assert_type_or_raise(png_sticker, (InputFile, unicode_type), parameter_name="png_sticker") assert_type_or_raise(emojis, unicode_type, parameter_name="emojis") assert_type_or_raise(contains_masks, None, bool, parameter_name="contains_masks") assert_type_or_raise(mask_position, None, MaskPosition, parameter_name="mask_position") result = self.do("createNewStickerSet", user_id=user_id, name=name, title=title, png_sticker=png_sticker, emojis=emojis, contains_masks=contains_masks, mask_position=mask_position) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8816
Bot.set_sticker_position_in_set
train
def set_sticker_position_in_set(self, sticker, position): """ Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. https://core.telegram.org/bots/api#setstickerpositioninset Parameters: :param sticker: File identifier of the sticker :type sticker: str|unicode :param position: New sticker position in the set, zero-based :type position: int Returns: :return: Returns True on success :rtype: bool """ assert_type_or_raise(sticker, unicode_type, parameter_name="sticker") assert_type_or_raise(position, int, parameter_name="position") result = self.do("setStickerPositionInSet", sticker=sticker, position=position) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8817
Bot.answer_shipping_query
train
def answer_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None): """ If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. https://core.telegram.org/bots/api#answershippingquery Parameters: :param shipping_query_id: Unique identifier for the query to be answered :type shipping_query_id: str|unicode :param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) :type ok: bool Optional keyword parameters: :param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options. :type shipping_options: list of pytgbot.api_types.sendable.payments.ShippingOption :param error_message: Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. :type error_message: str|unicode Returns: :return: On success, True is returned :rtype: bool """ from pytgbot.api_types.sendable.payments import ShippingOption assert_type_or_raise(shipping_query_id, unicode_type, parameter_name="shipping_query_id") assert_type_or_raise(ok, bool, parameter_name="ok") assert_type_or_raise(shipping_options, None, list, parameter_name="shipping_options") assert_type_or_raise(error_message, None, unicode_type, parameter_name="error_message") result = self.do("answerShippingQuery", shipping_query_id=shipping_query_id, ok=ok, shipping_options=shipping_options, error_message=error_message) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8818
Bot.send_game
train
def send_game(self, chat_id, game_short_name, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send a game. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendgame Parameters: :param chat_id: Unique identifier for the target chat :type chat_id: int :param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather. :type game_short_name: str|unicode Optional keyword parameters: :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: bool :param reply_to_message_id: If the message is a reply, ID of the original message :type reply_to_message_id: int :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game. :type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup Returns: :return: On success, the sent Message is returned :rtype: pytgbot.api_types.receivable.updates.Message """ from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup assert_type_or_raise(chat_id, int, parameter_name="chat_id") assert_type_or_raise(game_short_name, unicode_type, parameter_name="game_short_name") assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification") assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id") assert_type_or_raise(reply_markup, None, InlineKeyboardMarkup, parameter_name="reply_markup") result = self.do("sendGame", chat_id=chat_id, game_short_name=game_short_name, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8819
Bot.get_download_url
train
def get_download_url(self, file): """ Creates a url to download the file. Note: Contains the secret API key, so you should not share this url! :param file: The File you want to get the url to download. :type file: pytgbot.api_types.receivable.media.File :return: url :rtype: str """ from .api_types.receivable.media import File assert isinstance(file, File) return file.get_download_url(self.api_key)
python
{ "resource": "" }
q8820
InputMediaVideo.to_array
train
def to_array(self): """ Serializes this InputMediaVideo to a dictionary. :return: dictionary representation of this object. :rtype: dict """ from .files import InputFile array = super(InputMediaVideo, self).to_array() # 'type' given by superclass # 'media' given by superclass if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = None # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if # 'caption' given by superclass # 'parse_mode' given by superclass if self.width is not None: array['width'] = int(self.width) # type int if self.height is not None: array['height'] = int(self.height) # type int if self.duration is not None: array['duration'] = int(self.duration) # type int if self.supports_streaming is not None: array['supports_streaming'] = bool(self.supports_streaming) # type bool return array
python
{ "resource": "" }
q8821
InputMediaDocument.from_array
train
def from_array(array): """ Deserialize a new InputMediaDocument from a given dictionary. :return: new InputMediaDocument instance. :rtype: InputMediaDocument """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.files import InputFile data = {} # 'type' is given by class type data['media'] = u(array.get('media')) if array.get('thumb') is None: data['thumb'] = None elif isinstance(array.get('thumb'), InputFile): data['thumb'] = None # will be filled later by get_request_data() elif isinstance(array.get('thumb'), str): data['thumb'] = u(array.get('thumb')) else: raise TypeError('Unknown type, must be one of InputFile, str or None.') # end if data['caption'] = u(array.get('caption')) if array.get('caption') is not None else None data['parse_mode'] = u(array.get('parse_mode')) if array.get('parse_mode') is not None else None instance = InputMediaDocument(**data) instance._raw = array return instance
python
{ "resource": "" }
q8822
REPP.from_config
train
def from_config(cls, path, directory=None): """ Instantiate a REPP from a PET-style `.set` configuration file. The *path* parameter points to the configuration file. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. Args: path (str): the path to the REPP configuration file directory (str, optional): the directory in which to search for submodules """ if not exists(path): raise REPPError('REPP config file not found: {}'.format(path)) confdir = dirname(path) # TODO: can TDL parsing be repurposed for this variant? conf = io.open(path, encoding='utf-8').read() conf = re.sub(r';.*', '', conf).replace('\n',' ') m = re.search( r'repp-modules\s*:=\s*((?:[-\w]+\s+)*[-\w]+)\s*\.', conf) t = re.search( r'repp-tokenizer\s*:=\s*([-\w]+)\s*\.', conf) a = re.search( r'repp-calls\s*:=\s*((?:[-\w]+\s+)*[-\w]+)\s*\.', conf) f = re.search( r'format\s*:=\s*(\w+)\s*\.', conf) d = re.search( r'repp-directory\s*:=\s*(.*)\.\s*$', conf) if m is None: raise REPPError('repp-modules option must be set') if t is None: raise REPPError('repp-tokenizer option must be set') mods = m.group(1).split() tok = t.group(1).strip() active = a.group(1).split() if a is not None else None fmt = f.group(1).strip() if f is not None else None if directory is None: if d is not None: directory = d.group(1).strip(' "') elif exists(joinpath(confdir, tok + '.rpp')): directory = confdir elif exists(joinpath(confdir, 'rpp', tok + '.rpp')): directory = joinpath(confdir, 'rpp') elif exists(joinpath(confdir, '../rpp', tok + '.rpp')): directory = joinpath(confdir, '../rpp') else: raise REPPError('Could not find a suitable REPP directory.') # ignore repp-modules and format? return REPP.from_file( joinpath(directory, tok + '.rpp'), directory=directory, active=active )
python
{ "resource": "" }
q8823
REPP.from_file
train
def from_file(cls, path, directory=None, modules=None, active=None): """ Instantiate a REPP from a `.rpp` file. The *path* parameter points to the top-level module. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. A REPP module may utilize external submodules, which may be defined in two ways. The first method is to map a module name to an instantiated REPP instance in *modules*. The second method assumes that an external group call `>abc` corresponds to a file `abc.rpp` in *directory* and loads that file. The second method only happens if the name (e.g., `abc`) does not appear in *modules*. Only one module may define a tokenization pattern. Args: path (str): the path to the base REPP file to load directory (str, optional): the directory in which to search for submodules modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations """ name = basename(path) if name.endswith('.rpp'): name = name[:-4] lines = _repp_lines(path) directory = dirname(path) if directory is None else directory r = cls(name=name, modules=modules, active=active) _parse_repp(lines, r, directory) return r
python
{ "resource": "" }
q8824
REPP.from_string
train
def from_string(cls, s, name=None, modules=None, active=None): """ Instantiate a REPP from a string. Args: name (str, optional): the name of the REPP module modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations """ r = cls(name=name, modules=modules, active=active) _parse_repp(s.splitlines(), r, None) return r
python
{ "resource": "" }
q8825
TextMessage.to_array
train
def to_array(self): """ Serializes this TextMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(TextMessage, self).to_array() array['text'] = u(self.text) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_web_page_preview is not None: array['disable_web_page_preview'] = bool(self.disable_web_page_preview) # type bool if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
{ "resource": "" }
q8826
AudioMessage.to_array
train
def to_array(self): """ Serializes this AudioMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(AudioMessage, self).to_array() if isinstance(self.audio, InputFile): array['audio'] = self.audio.to_array() # type InputFile elif isinstance(self.audio, str): array['audio'] = u(self.audio) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.duration is not None: array['duration'] = int(self.duration) # type int if self.performer is not None: array['performer'] = u(self.performer) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
{ "resource": "" }
q8827
AnimationMessage.to_array
train
def to_array(self): """ Serializes this AnimationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(AnimationMessage, self).to_array() if isinstance(self.animation, InputFile): array['animation'] = self.animation.to_array() # type InputFile elif isinstance(self.animation, str): array['animation'] = u(self.animation) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.duration is not None: array['duration'] = int(self.duration) # type int if self.width is not None: array['width'] = int(self.width) # type int if self.height is not None: array['height'] = int(self.height) # type int if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
{ "resource": "" }
q8828
VoiceMessage.to_array
train
def to_array(self): """ Serializes this VoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VoiceMessage, self).to_array() if isinstance(self.voice, InputFile): array['voice'] = self.voice.to_array() # type InputFile elif isinstance(self.voice, str): array['voice'] = u(self.voice) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.duration is not None: array['duration'] = int(self.duration) # type int if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
{ "resource": "" }
q8829
VideoNoteMessage.to_array
train
def to_array(self): """ Serializes this VideoNoteMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VideoNoteMessage, self).to_array() if isinstance(self.video_note, InputFile): array['video_note'] = self.video_note.to_array() # type InputFile elif isinstance(self.video_note, str): array['video_note'] = u(self.video_note) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.duration is not None: array['duration'] = int(self.duration) # type int if self.length is not None: array['length'] = int(self.length) # type int if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
{ "resource": "" }
q8830
MediaGroupMessage.to_array
train
def to_array(self): """ Serializes this MediaGroupMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(MediaGroupMessage, self).to_array() if isinstance(self.media, InputMediaPhoto): array['media'] = self._as_array(self.media) # type list of InputMediaPhoto | list of InputMediaVideo elif isinstance(self.media, InputMediaVideo): array['media'] = self._as_array(self.media) # type list of InputMediaPhoto | list of InputMediaVideo else: raise TypeError('Unknown type, must be one of InputMediaPhoto, InputMediaVideo.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool return array
python
{ "resource": "" }
q8831
MediaGroupMessage.from_array
train
def from_array(array): """ Deserialize a new MediaGroupMessage from a given dictionary. :return: new MediaGroupMessage instance. :rtype: MediaGroupMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.input_media import InputMediaPhoto from pytgbot.api_types.sendable.input_media import InputMediaVideo data = {} if isinstance(array.get('media'), InputMediaPhoto): data['media'] = InputMediaPhoto.from_array_list(array.get('media'), list_level=1) elif isinstance(array.get('media'), InputMediaVideo): data['media'] = InputMediaVideo.from_array_list(array.get('media'), list_level=1) else: raise TypeError('Unknown type, must be one of InputMediaPhoto, InputMediaVideo.') # end if if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None return MediaGroupMessage(**data)
python
{ "resource": "" }
q8832
LocationMessage.to_array
train
def to_array(self): """ Serializes this LocationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(LocationMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.live_period is not None: array['live_period'] = int(self.live_period) # type int if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
{ "resource": "" }
q8833
VenueMessage.to_array
train
def to_array(self): """ Serializes this VenueMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VenueMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str array['address'] = u(self.address) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.foursquare_id is not None: array['foursquare_id'] = u(self.foursquare_id) # py2: type unicode, py3: type str if self.foursquare_type is not None: array['foursquare_type'] = u(self.foursquare_type) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
{ "resource": "" }
q8834
ContactMessage.to_array
train
def to_array(self): """ Serializes this ContactMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ContactMessage, self).to_array() array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.vcard is not None: array['vcard'] = u(self.vcard) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
{ "resource": "" }
q8835
ChatActionMessage.to_array
train
def to_array(self): """ Serializes this ChatActionMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ChatActionMessage, self).to_array() array['action'] = u(self.action) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if return array
python
{ "resource": "" }
q8836
ChatActionMessage.from_array
train
def from_array(array): """ Deserialize a new ChatActionMessage from a given dictionary. :return: new ChatActionMessage instance. :rtype: ChatActionMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['action'] = u(array.get('action')) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if return ChatActionMessage(**data)
python
{ "resource": "" }
q8837
StickerMessage.to_array
train
def to_array(self): """ Serializes this StickerMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(StickerMessage, self).to_array() if isinstance(self.sticker, InputFile): array['sticker'] = self.sticker.to_array() # type InputFile elif isinstance(self.sticker, str): array['sticker'] = u(self.sticker) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
{ "resource": "" }
q8838
InvoiceMessage.to_array
train
def to_array(self): """ Serializes this InvoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InvoiceMessage, self).to_array() array['title'] = u(self.title) # py2: type unicode, py3: type str array['description'] = u(self.description) # py2: type unicode, py3: type str array['payload'] = u(self.payload) # py2: type unicode, py3: type str array['provider_token'] = u(self.provider_token) # py2: type unicode, py3: type str array['start_parameter'] = u(self.start_parameter) # py2: type unicode, py3: type str array['currency'] = u(self.currency) # py2: type unicode, py3: type str array['prices'] = self._as_array(self.prices) # type list of LabeledPrice if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.provider_data is not None: array['provider_data'] = u(self.provider_data) # py2: type unicode, py3: type str if self.photo_url is not None: array['photo_url'] = u(self.photo_url) # py2: type unicode, py3: type str if self.photo_size is not None: array['photo_size'] = int(self.photo_size) # type int if self.photo_width is not None: array['photo_width'] = int(self.photo_width) # type int if self.photo_height is not None: array['photo_height'] = int(self.photo_height) # type int if self.need_name is not None: array['need_name'] = bool(self.need_name) # type bool if self.need_phone_number is not None: array['need_phone_number'] = bool(self.need_phone_number) # type bool if self.need_email is not None: array['need_email'] = bool(self.need_email) # type bool if self.need_shipping_address is not None: array['need_shipping_address'] = bool(self.need_shipping_address) # type bool if self.send_phone_number_to_provider is not None: array['send_phone_number_to_provider'] = bool(self.send_phone_number_to_provider) # type bool if self.send_email_to_provider is not None: array['send_email_to_provider'] = bool(self.send_email_to_provider) # type bool if self.is_flexible is not None: array['is_flexible'] = bool(self.is_flexible) # type bool if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup return array
python
{ "resource": "" }
q8839
GameMessage.to_array
train
def to_array(self): """ Serializes this GameMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(GameMessage, self).to_array() array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup return array
python
{ "resource": "" }
q8840
GameMessage.from_array
train
def from_array(array): """ Deserialize a new GameMessage from a given dictionary. :return: new GameMessage instance. :rtype: GameMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup data = {} data['game_short_name'] = u(array.get('game_short_name')) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None return GameMessage(**data)
python
{ "resource": "" }
q8841
find_subgraphs_by_preds
train
def find_subgraphs_by_preds(xmrs, preds, connected=None): """ Yield subgraphs matching a list of predicates. Predicates may match multiple EPs/nodes in the *xmrs*, meaning that more than one subgraph is possible. Also, predicates in *preds* match in number, so if a predicate appears twice in *preds*, there will be two matching EPs/nodes in each subgraph. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to use preds: iterable of predicates to include in subgraphs connected (bool, optional): if `True`, all yielded subgraphs must be connected, as determined by :meth:`Xmrs.is_connected() <delphin.mrs.xmrs.Xmrs.is_connected>`. Yields: A :class:`~delphin.mrs.xmrs.Xmrs` object for each subgraphs found. """ preds = list(preds) count = len(preds) # find all lists of nodeids such that the lists have no repeated nids; # keep them as a list (fixme: why not just get sets?) nidsets = set( tuple(sorted(ns)) for ns in filter( lambda ns: len(set(ns)) == count, product(*[select_nodeids(xmrs, pred=p) for p in preds]) ) ) for nidset in nidsets: sg = xmrs.subgraph(nidset) if connected is None or sg.is_connected() == connected: yield sg
python
{ "resource": "" }
q8842
in_labelset
train
def in_labelset(xmrs, nodeids, label=None): """ Test if all nodeids share a label. Args: nodeids: iterable of nodeids label (str, optional): the label that all nodeids must share Returns: bool: `True` if all nodeids share a label, otherwise `False` """ nodeids = set(nodeids) if label is None: label = xmrs.ep(next(iter(nodeids))).label return nodeids.issubset(xmrs._vars[label]['refs']['LBL'])
python
{ "resource": "" }
q8843
InputFile.factory
train
def factory( cls, file_id=None, path=None, url=None, blob=None, mime=None, prefer_local_download=True, prefer_str=False, create_instance=True ): """ Creates a new InputFile subclass instance fitting the given parameters. :param prefer_local_download: If `True`, we download the file and send it to telegram. This is the default. If `False`, we send Telegram just the URL, and they'll try to download it. :type prefer_local_download: bool :param prefer_str: Return just the `str` instead of a `InputFileUseFileID` or `InputFileUseUrl` object. :type prefer_str: bool :param create_instance: If we should return a instance ready to use (default), or the building parts being a tuple of `(class, args_tuple, kwargs_dict)`. Setting this to `False` is probably only ever required for internal usage by the :class:`InputFile` constructor which uses this very factory. :type create_instance: bool :returns: if `create_instance=True` it returns a instance of some InputFile subclass or a string, if `create_instance=False` it returns a tuple of the needed class, args and kwargs needed to create a instance. :rtype: InputFile|InputFileFromBlob|InputFileFromDisk|InputFileFromURL|str|tuple """ if create_instance: clazz, args, kwargs = cls.factory( file_id=file_id, path=path, url=url, blob=blob, mime=mime, create_instance=False, ) return clazz(*args, **kwargs) if file_id: if prefer_str: assert_type_or_raise(file_id, str, parameter_name='file_id') return str, (file_id,), dict() # end if return InputFileUseFileID, (file_id,), dict() if blob: name = "file" suffix = ".blob" if path: name = os_path.basename(os_path.normpath(path)) # http://stackoverflow.com/a/3925147/3423324#last-part name, suffix = os_path.splitext(name) # http://stackoverflow.com/a/541394/3423324#extension elif url: # http://stackoverflow.com/a/18727481/3423324#how-to-extract-a-filename-from-a-url url = urlparse(url) name = os_path.basename(url.path) name, suffix = os_path.splitext(name) # end if if mime: import mimetypes suffix = mimetypes.guess_extension(mime) suffix = '.jpg' if suffix == '.jpe' else suffix # .jpe -> .jpg # end if if not suffix or not suffix.strip().lstrip("."): logger.debug("suffix was empty. Using '.blob'") suffix = ".blob" # end if name = "{filename}{suffix}".format(filename=name, suffix=suffix) return InputFileFromBlob, (blob,), dict(name=name, mime=mime) if path: return InputFileFromDisk, (path,), dict(mime=mime) if url: if prefer_local_download: return InputFileFromURL, (url,), dict(mime=mime) # end if # else -> so we wanna let telegram handle it if prefer_str: assert_type_or_raise(url, str, parameter_name='url') return str, (url,), dict() # end if return InputFileUseUrl, (url,), dict() # end if raise ValueError('Could not find a matching subclass. You might need to do it manually instead.')
python
{ "resource": "" }
q8844
PassportData.to_array
train
def to_array(self): """ Serializes this PassportData to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(PassportData, self).to_array() array['data'] = self._as_array(self.data) # type list of EncryptedPassportElement array['credentials'] = self.credentials.to_array() # type EncryptedCredentials return array
python
{ "resource": "" }
q8845
PassportFile.to_array
train
def to_array(self): """ Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(PassportFile, self).to_array() array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str array['file_size'] = int(self.file_size) # type int array['file_date'] = int(self.file_date) # type int return array
python
{ "resource": "" }
q8846
EncryptedPassportElement.to_array
train
def to_array(self): """ Serializes this EncryptedPassportElement to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(EncryptedPassportElement, self).to_array() array['type'] = u(self.type) # py2: type unicode, py3: type str array['hash'] = u(self.hash) # py2: type unicode, py3: type str if self.data is not None: array['data'] = u(self.data) # py2: type unicode, py3: type str if self.phone_number is not None: array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str if self.email is not None: array['email'] = u(self.email) # py2: type unicode, py3: type str if self.files is not None: array['files'] = self._as_array(self.files) # type list of PassportFile if self.front_side is not None: array['front_side'] = self.front_side.to_array() # type PassportFile if self.reverse_side is not None: array['reverse_side'] = self.reverse_side.to_array() # type PassportFile if self.selfie is not None: array['selfie'] = self.selfie.to_array() # type PassportFile if self.translation is not None: array['translation'] = self._as_array(self.translation) # type list of PassportFile return array
python
{ "resource": "" }
q8847
EncryptedCredentials.to_array
train
def to_array(self): """ Serializes this EncryptedCredentials to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(EncryptedCredentials, self).to_array() array['data'] = u(self.data) # py2: type unicode, py3: type str array['hash'] = u(self.hash) # py2: type unicode, py3: type str array['secret'] = u(self.secret) # py2: type unicode, py3: type str return array
python
{ "resource": "" }
q8848
EncryptedCredentials.from_array
train
def from_array(array): """ Deserialize a new EncryptedCredentials from a given dictionary. :return: new EncryptedCredentials instance. :rtype: EncryptedCredentials """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['data'] = u(array.get('data')) data['hash'] = u(array.get('hash')) data['secret'] = u(array.get('secret')) data['_raw'] = array return EncryptedCredentials(**data)
python
{ "resource": "" }
q8849
Bot.get_updates
train
def get_updates(self, offset=None, limit=100, poll_timeout=0, allowed_updates=None, request_timeout=None, delta=timedelta(milliseconds=100), error_as_empty=False): """ Use this method to receive incoming updates using long polling. An Array of Update objects is returned. You can choose to set `error_as_empty` to `True` or `False`. If `error_as_empty` is set to `True`, it will log that exception as warning, and fake an empty result, intended for use in for loops. In case of such error (and only in such case) it contains an "exception" field. Ìt will look like this: `{"result": [], "exception": e}` This is useful if you want to use a for loop, but ignore Network related burps. If `error_as_empty` is set to `False` however, all `requests.RequestException` exceptions are normally raised. :keyword offset: (Optional) Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as :func:`get_updates` is called with an offset higher than its `update_id`. :type offset: int :param limit: Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100 :type limit: int :param poll_timeout: Timeout in seconds for long polling, e.g. how long we want to wait maximum. Defaults to 0, i.e. usual short polling. :type poll_timeout: int :param allowed_updates: List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used. Please note that this parameter doesn't affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. :type allowed_updates: list of str :param request_timeout: Timeout of the request. Not the long polling server side timeout. If not specified, it is set to `poll_timeout`+2. :type request_timeout: int :param delta: Wait minimal 'delta' seconds, between requests. Useful in a loop. :type delta: datetime. :param error_as_empty: If errors which subclasses `requests.RequestException` will be logged but not raised. Instead the returned DictObject will contain an "exception" field containing the exception occured, the "result" field will be an empty list `[]`. Defaults to `False`. :type error_as_empty: bool Returns: :return: An Array of Update objects is returned, or an empty array if there was an requests.RequestException and error_as_empty is set to True. :rtype: list of pytgbot.api_types.receivable.updates.Update """ from datetime import datetime assert(offset is None or isinstance(offset, int)) assert(limit is None or isinstance(limit, int)) assert(poll_timeout is None or isinstance(poll_timeout, int)) assert(allowed_updates is None or isinstance(allowed_updates, list)) if poll_timeout and not request_timeout is None: request_timeout = poll_timeout + 2 # end if if delta.total_seconds() > poll_timeout: now = datetime.now() if self._last_update - now < delta: wait = ((now - self._last_update) - delta).total_seconds() # can be 0.2 wait = 0 if wait < 0 else wait if wait != 0: logger.debug("Sleeping {i} seconds.".format(i=wait)) # end if sleep(wait) # end if # end if self._last_update = datetime.now() try: result = self.do( "getUpdates", offset=offset, limit=limit, timeout=poll_timeout, allowed_updates=allowed_updates, use_long_polling=poll_timeout != 0, request_timeout=request_timeout ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Update try: return Update.from_array_list(result, list_level=1) except TgApiParseException: logger.debug("Failed parsing as api_type Update", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result except (requests.RequestException, TgApiException) as e: if error_as_empty: logger.warn("Network related error happened in get_updates(), but will be ignored: " + str(e), exc_info=True) self._last_update = datetime.now() return DictObject(result=[], exception=e) else: raise
python
{ "resource": "" }
q8850
Bot.set_game_score
train
def set_game_score(self, user_id, score, force=False, disable_edit_message=False, chat_id=None, message_id=None, inline_message_id=None): """ Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. https://core.telegram.org/bots/api#setgamescore Parameters: :param user_id: User identifier :type user_id: int :param score: New score, must be non-negative :type score: int Optional keyword parameters: :param force: Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters :type force: bool :param disable_edit_message: Pass True, if the game message should not be automatically edited to include the current scoreboard :type disable_edit_message: bool :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat (or username of the target channel in the format @channelusername) :type chat_id: int :param message_id: Required if inline_message_id is not specified. Identifier of the sent message :type message_id: int :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message :type inline_message_id: str|unicode Returns: :return: On success, if the message was sent by the bot, returns the edited Message, otherwise returns True :rtype: pytgbot.api_types.receivable.updates.Message | bool """ assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(score, int, parameter_name="score") assert_type_or_raise(force, None, bool, parameter_name="force") assert_type_or_raise(disable_edit_message, None, bool, parameter_name="disable_edit_message") assert_type_or_raise(chat_id, None, int, parameter_name="chat_id") assert_type_or_raise(message_id, None, int, parameter_name="message_id") assert_type_or_raise(inline_message_id, None, unicode_type, parameter_name="inline_message_id") result = self.do("setGameScore", user_id=user_id, score=score, force=force, disable_edit_message=disable_edit_message, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
{ "resource": "" }
q8851
LabeledPrice.to_array
train
def to_array(self): """ Serializes this LabeledPrice to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(LabeledPrice, self).to_array() array['label'] = u(self.label) # py2: type unicode, py3: type str array['amount'] = int(self.amount) # type int return array
python
{ "resource": "" }
q8852
LabeledPrice.from_array
train
def from_array(array): """ Deserialize a new LabeledPrice from a given dictionary. :return: new LabeledPrice instance. :rtype: LabeledPrice """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['label'] = u(array.get('label')) data['amount'] = int(array.get('amount')) instance = LabeledPrice(**data) instance._raw = array return instance
python
{ "resource": "" }
q8853
ShippingOption.to_array
train
def to_array(self): """ Serializes this ShippingOption to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ShippingOption, self).to_array() array['id'] = u(self.id) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str array['prices'] = self._as_array(self.prices) # type list of LabeledPrice return array
python
{ "resource": "" }
q8854
_prepare_target
train
def _prepare_target(ts, tables, buffer_size): """Clear tables affected by the processing.""" for tablename in tables: table = ts[tablename] table[:] = [] if buffer_size is not None and table.is_attached(): table.write(append=False)
python
{ "resource": "" }
q8855
_prepare_source
train
def _prepare_source(selector, source): """Normalize source rows and selectors.""" tablename, fields = get_data_specifier(selector) if len(fields) != 1: raise ItsdbError( 'Selector must specify exactly one data column: {}' .format(selector) ) if isinstance(source, TestSuite): if not tablename: tablename = source.relations.find(fields[0])[0] source = source[tablename] cols = list(source.fields.keys()) + fields return source, cols
python
{ "resource": "" }
q8856
_add_record
train
def _add_record(table, data, buffer_size): """ Prepare and append a Record into its Table; flush to disk if necessary. """ fields = table.fields # remove any keys that aren't relation fields for invalid_key in set(data).difference([f.name for f in fields]): del data[invalid_key] table.append(Record.from_dict(fields, data)) # write if requested and possible if buffer_size is not None and table.is_attached(): # for now there isn't a public method to get the number of new # records, so use private members if (len(table) - 1) - table._last_synced_index > buffer_size: table.commit()
python
{ "resource": "" }
q8857
decode_row
train
def decode_row(line, fields=None): """ Decode a raw line from a profile into a list of column values. Decoding involves splitting the line by the field delimiter (`"@"` by default) and unescaping special characters. If *fields* is given, cast the values into the datatype given by their respective Field object. Args: line: a raw line from a [incr tsdb()] profile. fields: a list or Relation object of Fields for the row Returns: A list of column values. """ cols = line.rstrip('\n').split(_field_delimiter) cols = list(map(unescape, cols)) if fields is not None: if len(cols) != len(fields): raise ItsdbError( 'Wrong number of fields: {} != {}' .format(len(cols), len(fields)) ) for i in range(len(cols)): col = cols[i] if col: field = fields[i] col = _cast_to_datatype(col, field) cols[i] = col return cols
python
{ "resource": "" }
q8858
_table_filename
train
def _table_filename(tbl_filename): """ Determine if the table path should end in .gz or not and return it. A .gz path is preferred only if it exists and is newer than any regular text file path. Raises: :class:`delphin.exceptions.ItsdbError`: when neither the .gz nor text file exist. """ tbl_filename = str(tbl_filename) # convert any Path objects txfn = _normalize_table_path(tbl_filename) gzfn = txfn + '.gz' if os.path.exists(txfn): if (os.path.exists(gzfn) and os.stat(gzfn).st_mtime > os.stat(txfn).st_mtime): tbl_filename = gzfn else: tbl_filename = txfn elif os.path.exists(gzfn): tbl_filename = gzfn else: raise ItsdbError( 'Table does not exist at {}(.gz)' .format(tbl_filename) ) return tbl_filename
python
{ "resource": "" }
q8859
_open_table
train
def _open_table(tbl_filename, encoding): """ Transparently open the compressed or text table file. Can be used as a context manager in a 'with' statement. """ path = _table_filename(tbl_filename) if path.endswith('.gz'): # gzip.open() cannot use mode='rt' until Python2.7 support # is gone; until then use TextIOWrapper gzfile = GzipFile(path, mode='r') gzfile.read1 = gzfile.read # Python2 hack with TextIOWrapper(gzfile, encoding=encoding) as f: yield f else: with io.open(path, encoding=encoding) as f: yield f
python
{ "resource": "" }
q8860
select_rows
train
def select_rows(cols, rows, mode='list', cast=True): """ Yield data selected from rows. It is sometimes useful to select a subset of data from a profile. This function selects the data in *cols* from *rows* and yields it in a form specified by *mode*. Possible values of *mode* are: ================== ================= ========================== mode description example `['i-id', 'i-wf']` ================== ================= ========================== `'list'` (default) a list of values `[10, 1]` `'dict'` col to value map `{'i-id': 10,'i-wf': 1}` `'row'` [incr tsdb()] row `'10@1'` ================== ================= ========================== Args: cols: an iterable of column names to select data for rows: the rows to select column data from mode: the form yielded data should take cast: if `True`, cast column values to their datatype (requires *rows* to be :class:`Record` objects) Yields: Selected data in the form specified by *mode*. """ mode = mode.lower() if mode == 'list': modecast = lambda cols, data: data elif mode == 'dict': modecast = lambda cols, data: dict(zip(cols, data)) elif mode == 'row': modecast = lambda cols, data: encode_row(data) else: raise ItsdbError('Invalid mode for select operation: {}\n' ' Valid options include: list, dict, row' .format(mode)) for row in rows: try: data = [row.get(c, cast=cast) for c in cols] except TypeError: data = [row.get(c) for c in cols] yield modecast(cols, data)
python
{ "resource": "" }
q8861
join
train
def join(table1, table2, on=None, how='inner', name=None): """ Join two tables and return the resulting Table object. Fields in the resulting table have their names prefixed with their corresponding table name. For example, when joining `item` and `parse` tables, the `i-input` field of the `item` table will be named `item:i-input` in the resulting Table. Pivot fields (those in *on*) are only stored once without the prefix. Both inner and left joins are possible by setting the *how* parameter to `inner` and `left`, respectively. .. warning:: Both *table2* and the resulting joined table will exist in memory for this operation, so it is not recommended for very large tables on low-memory systems. Args: table1 (:class:`Table`): the left table to join table2 (:class:`Table`): the right table to join on (str): the shared key to use for joining; if `None`, find shared keys using the schemata of the tables how (str): the method used for joining (`"inner"` or `"left"`) name (str): the name assigned to the resulting table """ if how not in ('inner', 'left'): ItsdbError('Only \'inner\' and \'left\' join methods are allowed.') # validate and normalize the pivot on = _join_pivot(on, table1, table2) # the fields of the joined table fields = _RelationJoin(table1.fields, table2.fields, on=on) # get key mappings to the right side (useful for inner and left joins) get_key = lambda rec: tuple(rec.get(k) for k in on) key_indices = set(table2.fields.index(k) for k in on) right = defaultdict(list) for rec in table2: right[get_key(rec)].append([c for i, c in enumerate(rec) if i not in key_indices]) # build joined table rfill = [f.default_value() for f in table2.fields if f.name not in on] joined = [] for lrec in table1: k = get_key(lrec) if how == 'left' or k in right: joined.extend(lrec + rrec for rrec in right.get(k, [rfill])) return Table(fields, joined)
python
{ "resource": "" }
q8862
default_value
train
def default_value(fieldname, datatype): """ Return the default value for a column. If the column name (e.g. *i-wf*) is defined to have an idiosyncratic value, that value is returned. Otherwise the default value for the column's datatype is returned. Args: fieldname: the column name (e.g. `i-wf`) datatype: the datatype of the column (e.g. `:integer`) Returns: The default value for the column. .. deprecated:: v0.7.0 """ if fieldname in tsdb_coded_attributes: return str(tsdb_coded_attributes[fieldname]) else: return _default_datatype_values.get(datatype, '')
python
{ "resource": "" }
q8863
filter_rows
train
def filter_rows(filters, rows): """ Yield rows matching all applicable filters. Filter functions have binary arity (e.g. `filter(row, col)`) where the first parameter is the dictionary of row data, and the second parameter is the data at one particular column. Args: filters: a tuple of (cols, filter_func) where filter_func will be tested (filter_func(row, col)) for each col in cols where col exists in the row rows: an iterable of rows to filter Yields: Rows matching all applicable filters .. deprecated:: v0.7.0 """ for row in rows: if all(condition(row, row.get(col)) for (cols, condition) in filters for col in cols if col is None or col in row): yield row
python
{ "resource": "" }
q8864
apply_rows
train
def apply_rows(applicators, rows): """ Yield rows after applying the applicator functions to them. Applicators are simple unary functions that return a value, and that value is stored in the yielded row. E.g. `row[col] = applicator(row[col])`. These are useful to, e.g., cast strings to numeric datatypes, to convert formats stored in a cell, extract features for machine learning, and so on. Args: applicators: a tuple of (cols, applicator) where the applicator will be applied to each col in cols rows: an iterable of rows for applicators to be called on Yields: Rows with specified column values replaced with the results of the applicators .. deprecated:: v0.7.0 """ for row in rows: for (cols, function) in applicators: for col in (cols or []): value = row.get(col, '') row[col] = function(row, value) yield row
python
{ "resource": "" }
q8865
Field.default_value
train
def default_value(self): """Get the default value of the field.""" if self.name in tsdb_coded_attributes: return tsdb_coded_attributes[self.name] elif self.datatype == ':integer': return -1 else: return ''
python
{ "resource": "" }
q8866
Relation.keys
train
def keys(self): """Return the tuple of field names of key fields.""" keys = self._keys if keys is None: keys = tuple(self[i].name for i in self.key_indices) return keys
python
{ "resource": "" }
q8867
Relations.from_file
train
def from_file(cls, source): """Instantiate Relations from a relations file.""" if hasattr(source, 'read'): relations = cls.from_string(source.read()) else: with open(source) as f: relations = cls.from_string(f.read()) return relations
python
{ "resource": "" }
q8868
Relations.from_string
train
def from_string(cls, s): """Instantiate Relations from a relations string.""" tables = [] seen = set() current_table = None lines = list(reversed(s.splitlines())) # to pop() in right order while lines: line = lines.pop().strip() table_m = re.match(r'^(?P<table>\w.+):$', line) field_m = re.match(r'\s*(?P<name>\S+)' r'(\s+(?P<attrs>[^#]+))?' r'(\s*#\s*(?P<comment>.*)$)?', line) if table_m is not None: table_name = table_m.group('table') if table_name in seen: raise ItsdbError( 'Table {} already defined.'.format(table_name) ) current_table = (table_name, []) tables.append(current_table) seen.add(table_name) elif field_m is not None and current_table is not None: name = field_m.group('name') attrs = field_m.group('attrs').split() datatype = attrs.pop(0) key = ':key' in attrs partial = ':partial' in attrs comment = field_m.group('comment') current_table[1].append( Field(name, datatype, key, partial, comment) ) elif line != '': raise ItsdbError('Invalid line: ' + line) return cls(tables)
python
{ "resource": "" }
q8869
Relations.path
train
def path(self, source, target): """ Find the path of id fields connecting two tables. This is just a basic breadth-first-search. The relations file should be small enough to not be a problem. Returns: list: (table, fieldname) pairs describing the path from the source to target tables Raises: :class:`delphin.exceptions.ItsdbError`: when no path is found Example: >>> relations.path('item', 'result') [('parse', 'i-id'), ('result', 'parse-id')] >>> relations.path('parse', 'item') [('item', 'i-id')] >>> relations.path('item', 'item') [] """ visited = set(source.split('+')) # split on + for joins targets = set(target.split('+')) - visited # ensure sources and targets exists for tablename in visited.union(targets): self[tablename] # base case; nothing to do if len(targets) == 0: return [] paths = [[(tablename, None)] for tablename in visited] while True: newpaths = [] for path in paths: laststep, pivot = path[-1] if laststep in targets: return path[1:] else: for key in self[laststep].keys(): for step in set(self.find(key)) - visited: visited.add(step) newpaths.append(path + [(step, key)]) if newpaths: paths = newpaths else: break raise ItsdbError('no relation path found from {} to {}' .format(source, target))
python
{ "resource": "" }
q8870
Record.from_dict
train
def from_dict(cls, fields, mapping): """ Create a Record from a dictionary of field mappings. The *fields* object is used to determine the column indices of fields in the mapping. Args: fields: the Relation schema for the table of this record mapping: a dictionary or other mapping from field names to column values Returns: a :class:`Record` object """ iterable = [None] * len(fields) for key, value in mapping.items(): try: index = fields.index(key) except KeyError: raise ItsdbError('Invalid field name(s): ' + key) iterable[index] = value return cls(fields, iterable)
python
{ "resource": "" }
q8871
Table.from_file
train
def from_file(cls, path, fields=None, encoding='utf-8'): """ Instantiate a Table from a database file. This method instantiates a table attached to the file at *path*. The file will be opened and traversed to determine the number of records, but the contents will not be stored in memory unless they are modified. Args: path: the path to the table file fields: the Relation schema for the table (loaded from the relations file in the same directory if not given) encoding: the character encoding of the file at *path* """ path = _table_filename(path) # do early in case file not found if fields is None: fields = _get_relation_from_table_path(path) table = cls(fields) table.attach(path, encoding=encoding) return table
python
{ "resource": "" }
q8872
Table.write
train
def write(self, records=None, path=None, fields=None, append=False, gzip=None): """ Write the table to disk. The basic usage has no arguments and writes the table's data to the attached file. The parameters accommodate a variety of use cases, such as using *fields* to refresh a table to a new schema or *records* and *append* to incrementally build a table. Args: records: an iterable of :class:`Record` objects to write; if `None` the table's existing data is used path: the destination file path; if `None` use the path of the file attached to the table fields (:class:`Relation`): table schema to use for writing, otherwise use the current one append: if `True`, append rather than overwrite gzip: compress with gzip if non-empty Examples: >>> table.write() >>> table.write(results, path='new/path/result') """ if path is None: if not self.is_attached(): raise ItsdbError('no path given for detached table') else: path = self.path path = _normalize_table_path(path) dirpath, name = os.path.split(path) if fields is None: fields = self.fields if records is None: records = iter(self) _write_table( dirpath, name, records, fields, append=append, gzip=gzip, encoding=self.encoding) if self.is_attached() and path == _normalize_table_path(self.path): self.path = _table_filename(path) self._sync_with_file()
python
{ "resource": "" }
q8873
Table.commit
train
def commit(self): """ Commit changes to disk if attached. This method helps normalize the interface for detached and attached tables and makes writing attached tables a bit more efficient. For detached tables nothing is done, as there is no notion of changes, but neither is an error raised (unlike with :meth:`write`). For attached tables, if all changes are new records, the changes are appended to the existing file, and otherwise the whole file is rewritten. """ if not self.is_attached(): return changes = self.list_changes() if changes: indices, records = zip(*changes) if min(indices) > self._last_synced_index: self.write(records, append=True) else: self.write(append=False)
python
{ "resource": "" }
q8874
Table.detach
train
def detach(self): """ Detach the table from a file. Detaching a table reads all data from the file and places it in memory. This is useful when constructing or significantly manipulating table data, or when more speed is needed. Tables created by the default constructor are detached. When detaching, only unmodified records are loaded from the file; any uncommited changes in the Table are left as-is. .. warning:: Very large tables may consume all available RAM when detached. Expect the in-memory table to take up about twice the space of an uncompressed table on disk, although this may vary by system. """ if not self.is_attached(): raise ItsdbError('already detached') records = self._records for i, line in self._enum_lines(): if records[i] is None: # check number of columns? records[i] = tuple(decode_row(line)) self.path = None self.encoding = None
python
{ "resource": "" }
q8875
Table.list_changes
train
def list_changes(self): """ Return a list of modified records. This is only applicable for attached tables. Returns: A list of `(row_index, record)` tuples of modified records Raises: :class:`delphin.exceptions.ItsdbError`: when called on a detached table """ if not self.is_attached(): raise ItsdbError('changes are not tracked for detached tables.') return [(i, self[i]) for i, row in enumerate(self._records) if row is not None]
python
{ "resource": "" }
q8876
Table._sync_with_file
train
def _sync_with_file(self): """Clear in-memory structures so table is synced with the file.""" self._records = [] i = -1 for i, line in self._enum_lines(): self._records.append(None) self._last_synced_index = i
python
{ "resource": "" }
q8877
Table._enum_lines
train
def _enum_lines(self): """Enumerate lines from the attached file.""" with _open_table(self.path, self.encoding) as lines: for i, line in enumerate(lines): yield i, line
python
{ "resource": "" }
q8878
Table._enum_attached_rows
train
def _enum_attached_rows(self, indices): """Enumerate on-disk and in-memory records.""" records = self._records i = 0 # first rows covered by the file for i, line in self._enum_lines(): if i in indices: row = records[i] if row is None: row = decode_row(line) yield (i, row) # then any uncommitted rows for j in range(i, len(records)): if j in indices: if records[j] is not None: yield (j, records[j])
python
{ "resource": "" }
q8879
Table._iterslice
train
def _iterslice(self, slice): """Yield records from a slice index.""" indices = range(*slice.indices(len(self._records))) if self.is_attached(): rows = self._enum_attached_rows(indices) if slice.step is not None and slice.step < 0: rows = reversed(list(rows)) else: rows = zip(indices, self._records[slice]) fields = self.fields for i, row in rows: yield Record._make(fields, row, self, i)
python
{ "resource": "" }
q8880
Table._getitem
train
def _getitem(self, index): """Get a single non-slice index.""" row = self._records[index] if row is not None: pass elif self.is_attached(): # need to handle negative indices manually if index < 0: index = len(self._records) + index row = next((decode_row(line) for i, line in self._enum_lines() if i == index), None) if row is None: raise ItsdbError('could not retrieve row in attached table') else: raise ItsdbError('invalid row in detached table: {}'.format(index)) return Record._make(self.fields, row, self, index)
python
{ "resource": "" }
q8881
Table.select
train
def select(self, cols, mode='list'): """ Select columns from each row in the table. See :func:`select_rows` for a description of how to use the *mode* parameter. Args: cols: an iterable of Field (column) names mode: how to return the data """ if isinstance(cols, stringtypes): cols = _split_cols(cols) if not cols: cols = [f.name for f in self.fields] return select_rows(cols, self, mode=mode)
python
{ "resource": "" }
q8882
ItsdbProfile.exists
train
def exists(self, table=None): """ Return True if the profile or a table exist. If *table* is `None`, this function returns True if the root directory exists and contains a valid relations file. If *table* is given, the function returns True if the table exists as a file (even if empty). Otherwise it returns False. """ if not os.path.isdir(self.root): return False if not os.path.isfile(os.path.join(self.root, _relations_filename)): return False if table is not None: try: _table_filename(os.path.join(self.root, table)) except ItsdbError: return False return True
python
{ "resource": "" }
q8883
_calculate_crc_ccitt
train
def _calculate_crc_ccitt(data): """ All CRC stuff ripped from PyCRC, GPLv3 licensed """ global CRC_CCITT_TABLE if not CRC_CCITT_TABLE: crc_ccitt_table = [] for i in range(0, 256): crc = 0 c = i << 8 for j in range(0, 8): if (crc ^ c) & 0x8000: crc = c_ushort(crc << 1).value ^ 0x1021 else: crc = c_ushort(crc << 1).value c = c_ushort(c << 1).value crc_ccitt_table.append(crc) CRC_CCITT_TABLE = crc_ccitt_table is_string = _is_string(data) crc_value = 0x0000 # XModem version for c in data: d = ord(c) if is_string else c tmp = ((crc_value >> 8) & 0xff) ^ d crc_value = ((crc_value << 8) & 0xff00) ^ CRC_CCITT_TABLE[tmp] return crc_value
python
{ "resource": "" }
q8884
GRF.to_zpl
train
def to_zpl( self, quantity=1, pause_and_cut=0, override_pause=False, print_mode='C', print_orientation='N', media_tracking='Y', **kwargs ): """ The most basic ZPL to print the GRF. Since ZPL printers are stateful this may not work and you may need to build your own. """ zpl = [ self.to_zpl_line(**kwargs), # Download image to printer '^XA', # Start Label Format '^MM%s,Y' % print_mode, '^PO%s' % print_orientation, '^MN%s' % media_tracking, '^FO0,0', # Field Origin to 0,0 '^XGR:%s.GRF,1,1' % self.filename, # Draw image '^FS', # Field Separator '^PQ%s,%s,0,%s' % ( int(quantity), # Print Quantity int(pause_and_cut), # Pause and cut every N labels 'Y' if override_pause else 'N' # Don't pause between cuts ), '^XZ', # End Label Format '^IDR:%s.GRF' % self.filename # Delete image from printer ] return ''.join(zpl)
python
{ "resource": "" }
q8885
GRF._optimise_barcodes
train
def _optimise_barcodes( self, data, min_bar_height=20, min_bar_count=100, max_gap_size=30, min_percent_white=0.2, max_percent_white=0.8, **kwargs ): """ min_bar_height = Minimum height of black bars in px. Set this too low and it might pick up text and data matrices, too high and it might pick up borders, tables, etc. min_bar_count = Minimum number of parallel black bars before a pattern is considered a potential barcode. max_gap_size = Biggest white gap in px allowed between black bars. This is only important if you have multiple barcodes next to each other. min_percent_white = Minimum percentage of white bars between black bars. This helps to ignore solid rectangles. max_percent_white = Maximum percentage of white bars between black bars. This helps to ignore solid rectangles. """ re_bars = re.compile(r'1{%s,}' % min_bar_height) bars = {} for i, line in enumerate(data): for match in re_bars.finditer(line): try: bars[match.span()].append(i) except KeyError: bars[match.span()] = [i] grouped_bars = [] for span, seen_at in bars.items(): group = [] for coords in seen_at: if group and coords - group[-1] > max_gap_size: grouped_bars.append((span, group)) group = [] group.append(coords) grouped_bars.append((span, group)) suspected_barcodes = [] for span, seen_at in grouped_bars: if len(seen_at) < min_bar_count: continue pc_white = len(seen_at) / float(seen_at[-1] - seen_at[0]) if pc_white >= min_percent_white and pc_white <= max_percent_white: suspected_barcodes.append((span, seen_at)) for span, seen_at in suspected_barcodes: barcode = [] for line in data[seen_at[0]:seen_at[-1]+1]: barcode.append(line[span[0]]) barcode = ''.join(barcode) # Do the actual optimisation barcode = self._optimise_barcode(barcode) barcode = list(barcode) barcode.reverse() width = span[1] - span[0] for i in range(seen_at[0], seen_at[-1]+1): line = data[i] line = ( line[:span[0]] + (barcode.pop() * width) + line[span[1]:] ) data[i] = line return data
python
{ "resource": "" }
q8886
convert_to_underscore
train
def convert_to_underscore(name): """ "someFunctionWhatever" -> "some_function_whatever" """ s1 = _first_cap_re.sub(r'\1_\2', name) return _all_cap_re.sub(r'\1_\2', s1).lower()
python
{ "resource": "" }
q8887
User.to_array
train
def to_array(self): """ Serializes this User to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(User, self).to_array() array['id'] = int(self.id) # type int array['is_bot'] = bool(self.is_bot) # type bool array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.username is not None: array['username'] = u(self.username) # py2: type unicode, py3: type str if self.language_code is not None: array['language_code'] = u(self.language_code) # py2: type unicode, py3: type str return array
python
{ "resource": "" }
q8888
User.from_array
train
def from_array(array): """ Deserialize a new User from a given dictionary. :return: new User instance. :rtype: User """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['id'] = int(array.get('id')) data['is_bot'] = bool(array.get('is_bot')) data['first_name'] = u(array.get('first_name')) data['last_name'] = u(array.get('last_name')) if array.get('last_name') is not None else None data['username'] = u(array.get('username')) if array.get('username') is not None else None data['language_code'] = u(array.get('language_code')) if array.get('language_code') is not None else None data['_raw'] = array return User(**data)
python
{ "resource": "" }
q8889
Chat.to_array
train
def to_array(self): """ Serializes this Chat to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Chat, self).to_array() array['id'] = int(self.id) # type int array['type'] = u(self.type) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.username is not None: array['username'] = u(self.username) # py2: type unicode, py3: type str if self.first_name is not None: array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.all_members_are_administrators is not None: array['all_members_are_administrators'] = bool(self.all_members_are_administrators) # type bool if self.photo is not None: array['photo'] = self.photo.to_array() # type ChatPhoto if self.description is not None: array['description'] = u(self.description) # py2: type unicode, py3: type str if self.invite_link is not None: array['invite_link'] = u(self.invite_link) # py2: type unicode, py3: type str if self.pinned_message is not None: array['pinned_message'] = self.pinned_message.to_array() # type Message if self.sticker_set_name is not None: array['sticker_set_name'] = u(self.sticker_set_name) # py2: type unicode, py3: type str if self.can_set_sticker_set is not None: array['can_set_sticker_set'] = bool(self.can_set_sticker_set) # type bool return array
python
{ "resource": "" }
q8890
Chat.from_array
train
def from_array(array): """ Deserialize a new Chat from a given dictionary. :return: new Chat instance. :rtype: Chat """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.media import ChatPhoto from pytgbot.api_types.receivable.updates import Message data = {} data['id'] = int(array.get('id')) data['type'] = u(array.get('type')) data['title'] = u(array.get('title')) if array.get('title') is not None else None data['username'] = u(array.get('username')) if array.get('username') is not None else None data['first_name'] = u(array.get('first_name')) if array.get('first_name') is not None else None data['last_name'] = u(array.get('last_name')) if array.get('last_name') is not None else None data['all_members_are_administrators'] = bool(array.get('all_members_are_administrators')) if array.get('all_members_are_administrators') is not None else None data['photo'] = ChatPhoto.from_array(array.get('photo')) if array.get('photo') is not None else None data['description'] = u(array.get('description')) if array.get('description') is not None else None data['invite_link'] = u(array.get('invite_link')) if array.get('invite_link') is not None else None data['pinned_message'] = Message.from_array(array.get('pinned_message')) if array.get('pinned_message') is not None else None data['sticker_set_name'] = u(array.get('sticker_set_name')) if array.get('sticker_set_name') is not None else None data['can_set_sticker_set'] = bool(array.get('can_set_sticker_set')) if array.get('can_set_sticker_set') is not None else None data['_raw'] = array return Chat(**data)
python
{ "resource": "" }
q8891
ChatMember.to_array
train
def to_array(self): """ Serializes this ChatMember to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ChatMember, self).to_array() array['user'] = self.user.to_array() # type User array['status'] = u(self.status) # py2: type unicode, py3: type str if self.until_date is not None: array['until_date'] = int(self.until_date) # type int if self.can_be_edited is not None: array['can_be_edited'] = bool(self.can_be_edited) # type bool if self.can_change_info is not None: array['can_change_info'] = bool(self.can_change_info) # type bool if self.can_post_messages is not None: array['can_post_messages'] = bool(self.can_post_messages) # type bool if self.can_edit_messages is not None: array['can_edit_messages'] = bool(self.can_edit_messages) # type bool if self.can_delete_messages is not None: array['can_delete_messages'] = bool(self.can_delete_messages) # type bool if self.can_invite_users is not None: array['can_invite_users'] = bool(self.can_invite_users) # type bool if self.can_restrict_members is not None: array['can_restrict_members'] = bool(self.can_restrict_members) # type bool if self.can_pin_messages is not None: array['can_pin_messages'] = bool(self.can_pin_messages) # type bool if self.can_promote_members is not None: array['can_promote_members'] = bool(self.can_promote_members) # type bool if self.can_send_messages is not None: array['can_send_messages'] = bool(self.can_send_messages) # type bool if self.can_send_media_messages is not None: array['can_send_media_messages'] = bool(self.can_send_media_messages) # type bool if self.can_send_other_messages is not None: array['can_send_other_messages'] = bool(self.can_send_other_messages) # type bool if self.can_add_web_page_previews is not None: array['can_add_web_page_previews'] = bool(self.can_add_web_page_previews) # type bool return array
python
{ "resource": "" }
q8892
loads
train
def loads(s, single=False): """ Deserialize MRX string representations Args: s (str): a MRX string single (bool): if `True`, only return the first Xmrs object Returns: a generator of Xmrs objects (unless *single* is `True`) """ corpus = etree.fromstring(s) if single: ds = _deserialize_mrs(next(corpus)) else: ds = (_deserialize_mrs(mrs_elem) for mrs_elem in corpus) return ds
python
{ "resource": "" }
q8893
InlineQueryResultArticle.to_array
train
def to_array(self): """ Serializes this InlineQueryResultArticle to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultArticle, self).to_array() # 'type' and 'id' given by superclass array['title'] = u(self.title) # py2: type unicode, py3: type str array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.url is not None: array['url'] = u(self.url) # py2: type unicode, py3: type str if self.hide_url is not None: array['hide_url'] = bool(self.hide_url) # type bool if self.description is not None: array['description'] = u(self.description) # py2: type unicode, py3: type str if self.thumb_url is not None: array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.thumb_width is not None: array['thumb_width'] = int(self.thumb_width) # type int if self.thumb_height is not None: array['thumb_height'] = int(self.thumb_height) # type int return array
python
{ "resource": "" }
q8894
InlineQueryResultGif.to_array
train
def to_array(self): """ Serializes this InlineQueryResultGif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultGif, self).to_array() # 'type' and 'id' given by superclass array['gif_url'] = u(self.gif_url) # py2: type unicode, py3: type str array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.gif_width is not None: array['gif_width'] = int(self.gif_width) # type int if self.gif_height is not None: array['gif_height'] = int(self.gif_height) # type int if self.gif_duration is not None: array['gif_duration'] = int(self.gif_duration) # type int if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
python
{ "resource": "" }
q8895
InlineQueryResultAudio.to_array
train
def to_array(self): """ Serializes this InlineQueryResultAudio to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultAudio, self).to_array() # 'type' and 'id' given by superclass array['audio_url'] = u(self.audio_url) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.performer is not None: array['performer'] = u(self.performer) # py2: type unicode, py3: type str if self.audio_duration is not None: array['audio_duration'] = int(self.audio_duration) # type int if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
python
{ "resource": "" }
q8896
InlineQueryResultLocation.to_array
train
def to_array(self): """ Serializes this InlineQueryResultLocation to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultLocation, self).to_array() # 'type' and 'id' given by superclass array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str if self.live_period is not None: array['live_period'] = int(self.live_period) # type int if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent if self.thumb_url is not None: array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.thumb_width is not None: array['thumb_width'] = int(self.thumb_width) # type int if self.thumb_height is not None: array['thumb_height'] = int(self.thumb_height) # type int return array
python
{ "resource": "" }
q8897
InlineQueryResultContact.to_array
train
def to_array(self): """ Serializes this InlineQueryResultContact to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultContact, self).to_array() # 'type' and 'id' given by superclass array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent if self.thumb_url is not None: array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.thumb_width is not None: array['thumb_width'] = int(self.thumb_width) # type int if self.thumb_height is not None: array['thumb_height'] = int(self.thumb_height) # type int return array
python
{ "resource": "" }
q8898
InlineQueryResultCachedGif.to_array
train
def to_array(self): """ Serializes this InlineQueryResultCachedGif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedGif, self).to_array() # 'type' and 'id' given by superclass array['gif_file_id'] = u(self.gif_file_id) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
python
{ "resource": "" }
q8899
InlineQueryResultCachedDocument.to_array
train
def to_array(self): """ Serializes this InlineQueryResultCachedDocument to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedDocument, self).to_array() # 'type' and 'id' given by superclass array['title'] = u(self.title) # py2: type unicode, py3: type str array['document_file_id'] = u(self.document_file_id) # py2: type unicode, py3: type str if self.description is not None: array['description'] = u(self.description) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
python
{ "resource": "" }