text:
import io
import json
import time
import asyncio
import traceback
import collections
from concurrent.futures._base import CancelledError
from . import helper, api
from .. import (
    _BotBase, flavor, _find_first_key, _isstring, _strip, _rectify,
    _dismantle_message_identifier, _split_input_media_array
)

# Patch aiohttp for sending unicode filename
from . import hack

from .. import exception

def flavor_router(routing_table):
    router = helper.Router(flavor, routing_table)
    return router.route

class Bot(_BotBase):
    class Scheduler(object):
        def __init__(self, loop):
            self._loop = loop
            self._callback = None

        def on_event(self, callback):
            self._callback = callback

        def event_at(self, when, data):
            delay = when - time.time()
            return self._loop.call_later(delay, self._callback, data)
            # call_at() uses event loop time, not unix time.
            # May as well use call_later here.

        def event_later(self, delay, data):
            return self._loop.call_later(delay, self._callback, data)

        def event_now(self, data):
            return self._loop.call_soon(self._callback, data)

        def cancel(self, event):
            return event.cancel()

    def __init__(self, token, loop=None):
        super(Bot, self).__init__(token)

        self._loop = loop or asyncio.get_event_loop()
        api._loop = self._loop  # sync loop with api module

        self._scheduler = self.Scheduler(self._loop)

        self._router = helper.Router(flavor, {'chat': helper._create_invoker(self, 'on_chat_message'),
                                              'callback_query': helper._create_invoker(self, 'on_callback_query'),
                                              'inline_query': helper._create_invoker(self, 'on_inline_query'),
                                              'chosen_inline_result': helper._create_invoker(self, 'on_chosen_inline_result')})

    @property
    def loop(self):
        return self._loop

    @property
    def scheduler(self):
        return self._scheduler

    @property
    def router(self):
        return self._router

    async def handle(self, msg):
        await self._router.route(msg)

    async def _api_request(self, method, params=None, files=None, **kwargs):
        return await api.request((self._token, method, params, files), **kwargs)

    async def _api_request_with_file(self, method, params, file_key, file_value, **kwargs):
        if _isstring(file_value):
            params[file_key] = file_value
            return await self._api_request(method, _rectify(params), **kwargs)
        else:
            files = {file_key: file_value}
            return await self._api_request(method, _rectify(params), files, **kwargs)

    async def getMe(self):
        """ See: https://core.telegram.org/bots/api#getme """
        return await self._api_request('getMe')

    async def sendMessage(self, chat_id, text,
                          parse_mode=None,
                          disable_web_page_preview=None,
                          disable_notification=None,
                          reply_to_message_id=None,
                          reply_markup=None):
        """ See: https://core.telegram.org/bots/api#sendmessage """
        p = _strip(locals())
        return await self._api_request('sendMessage', _rectify(p))

    async def forwardMessage(self, chat_id, from_chat_id, message_id,
                             disable_notification=None):
        """ See: https://core.telegram.org/bots/api#forwardmessage """
        p = _strip(locals())
        return await self._api_request('forwardMessage', _rectify(p))

    async def sendPhoto(self, chat_id, photo,
                        caption=None,
                        parse_mode=None,
                        disable_notification=None,
                        reply_to_message_id=None,
                        reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#sendphoto

        :param photo:
            - string: ``file_id`` for a photo existing on Telegram servers
            - string: HTTP URL of a photo from the Internet
            - file-like object: obtained by ``open(path, 'rb')``
            - tuple: (filename, file-like object). If the filename contains
              non-ASCII characters and you are using Python 2.7, make sure the
              filename is a unicode string.
        """
        p = _strip(locals(), more=['photo'])
        return await self._api_request_with_file('sendPhoto', _rectify(p), 'photo', photo)

    async def sendAudio(self, chat_id, audio,
                        caption=None,
                        parse_mode=None,
                        duration=None,
                        performer=None,
                        title=None,
                        disable_notification=None,
                        reply_to_message_id=None,
                        reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#sendaudio

        :param audio: Same as ``photo`` in :meth:`telepot.aio.Bot.sendPhoto`
        """
        p = _strip(locals(), more=['audio'])
        return await self._api_request_with_file('sendAudio', _rectify(p), 'audio', audio)

    async def sendDocument(self, chat_id, document,
                           caption=None,
                           parse_mode=None,
                           disable_notification=None,
                           reply_to_message_id=None,
                           reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#senddocument

        :param document: Same as ``photo`` in :meth:`telepot.aio.Bot.sendPhoto`
        """
        p = _strip(locals(), more=['document'])
        return await self._api_request_with_file('sendDocument', _rectify(p), 'document', document)

    async def sendVideo(self, chat_id, video,
                        duration=None,
                        width=None,
                        height=None,
                        caption=None,
                        parse_mode=None,
                        supports_streaming=None,
                        disable_notification=None,
                        reply_to_message_id=None,
                        reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#sendvideo

        :param video: Same as ``photo`` in :meth:`telepot.aio.Bot.sendPhoto`
        """
        p = _strip(locals(), more=['video'])
        return await self._api_request_with_file('sendVideo', _rectify(p), 'video', video)

    async def sendVoice(self, chat_id, voice,
                        caption=None,
                        parse_mode=None,
                        duration=None,
                        disable_notification=None,
                        reply_to_message_id=None,
                        reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#sendvoice

        :param voice: Same as ``photo`` in :meth:`telepot.aio.Bot.sendPhoto`
        """
        p = _strip(locals(), more=['voice'])
        return await self._api_request_with_file('sendVoice', _rectify(p), 'voice', voice)

    async def sendVideoNote(self, chat_id, video_note,
                            duration=None,
                            length=None,
                            disable_notification=None,
                            reply_to_message_id=None,
                            reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#sendvideonote

        :param voice: Same as ``photo`` in :meth:`telepot.aio.Bot.sendPhoto`

        :param length:
            Although marked as optional, this method does not seem to work without
            it being specified. Supply any integer you want. It seems to have no effect
            on the video note's display size.
        """
        p = _strip(locals(), more=['video_note'])
        return await self._api_request_with_file('sendVideoNote', _rectify(p), 'video_note', video_note)

    async def sendMediaGroup(self, chat_id, media,
                             disable_notification=None,
                             reply_to_message_id=None):
        """
        See: https://core.telegram.org/bots/api#sendmediagroup

        :type media: array of `InputMedia <https://core.telegram.org/bots/api#inputmedia>`_ objects
        :param media:
            To indicate media locations, each InputMedia object's ``media`` field
            should be one of these:

            - string: ``file_id`` for a file existing on Telegram servers
            - string: HTTP URL of a file from the Internet
            - file-like object: obtained by ``open(path, 'rb')``
            - tuple: (form-data name, file-like object)
            - tuple: (form-data name, (filename, file-like object))

            In case of uploading, you may supply customized multipart/form-data
            names for each uploaded file (as in last 2 options above). Otherwise,
            telepot assigns unique names to each uploaded file. Names assigned by
            telepot will not collide with user-supplied names, if any.
        """
        p = _strip(locals(), more=['media'])
        legal_media, files_to_attach = _split_input_media_array(media)

        p['media'] = legal_media
        return await self._api_request('sendMediaGroup', _rectify(p), files_to_attach)

    async def sendLocation(self, chat_id, latitude, longitude,
                           live_period=None,
                           disable_notification=None,
                           reply_to_message_id=None,
                           reply_markup=None):
        """ See: https://core.telegram.org/bots/api#sendlocation """
        p = _strip(locals())
        return await self._api_request('sendLocation', _rectify(p))

    async def editMessageLiveLocation(self, msg_identifier, latitude, longitude,
                                      reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#editmessagelivelocation

        :param msg_identifier: Same as in :meth:`.Bot.editMessageText`
        """
        p = _strip(locals(), more=['msg_identifier'])
        p.update(_dismantle_message_identifier(msg_identifier))
        return await self._api_request('editMessageLiveLocation', _rectify(p))

    async def stopMessageLiveLocation(self, msg_identifier,
                                      reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#stopmessagelivelocation

        :param msg_identifier: Same as in :meth:`.Bot.editMessageText`
        """
        p = _strip(locals(), more=['msg_identifier'])
        p.update(_dismantle_message_identifier(msg_identifier))
        return await self._api_request('stopMessageLiveLocation', _rectify(p))

    async def sendVenue(self, chat_id, latitude, longitude, title, address,
                        foursquare_id=None,
                        disable_notification=None,
                        reply_to_message_id=None,
                        reply_markup=None):
        """ See: https://core.telegram.org/bots/api#sendvenue """
        p = _strip(locals())
        return await self._api_request('sendVenue', _rectify(p))

    async def sendContact(self, chat_id, phone_number, first_name,
                          last_name=None,
                          disable_notification=None,
                          reply_to_message_id=None,
                          reply_markup=None):
        """ See: https://core.telegram.org/bots/api#sendcontact """
        p = _strip(locals())
        return await self._api_request('sendContact', _rectify(p))

    async def sendGame(self, chat_id, game_short_name,
                       disable_notification=None,
                       reply_to_message_id=None,
                       reply_markup=None):
        """ See: https://core.telegram.org/bots/api#sendgame """
        p = _strip(locals())
        return await self._api_request('sendGame', _rectify(p))

    async def sendInvoice(self, chat_id, title, description, payload,
                          provider_token, start_parameter, currency, prices,
                          provider_data=None,
                          photo_url=None,
                          photo_size=None,
                          photo_width=None,
                          photo_height=None,
                          need_name=None,
                          need_phone_number=None,
                          need_email=None,
                          need_shipping_address=None,
                          is_flexible=None,
                          disable_notification=None,
                          reply_to_message_id=None,
                          reply_markup=None):
        """ See: https://core.telegram.org/bots/api#sendinvoice """
        p = _strip(locals())
        return await self._api_request('sendInvoice', _rectify(p))

    async def sendChatAction(self, chat_id, action):
        """ See: https://core.telegram.org/bots/api#sendchataction """
        p = _strip(locals())
        return await self._api_request('sendChatAction', _rectify(p))

    async def getUserProfilePhotos(self, user_id,
                                   offset=None,
                                   limit=None):
        """ See: https://core.telegram.org/bots/api#getuserprofilephotos """
        p = _strip(locals())
        return await self._api_request('getUserProfilePhotos', _rectify(p))

    async def getFile(self, file_id):
        """ See: https://core.telegram.org/bots/api#getfile """
        p = _strip(locals())
        return await self._api_request('getFile', _rectify(p))

    async def kickChatMember(self, chat_id, user_id,
                             until_date=None):
        """ See: https://core.telegram.org/bots/api#kickchatmember """
        p = _strip(locals())
        return await self._api_request('kickChatMember', _rectify(p))

    async def unbanChatMember(self, chat_id, user_id):
        """ See: https://core.telegram.org/bots/api#unbanchatmember """
        p = _strip(locals())
        return await self._api_request('unbanChatMember', _rectify(p))

    async def restrictChatMember(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):
        """ See: https://core.telegram.org/bots/api#restrictchatmember """
        p = _strip(locals())
        return await self._api_request('restrictChatMember', _rectify(p))

    async def promoteChatMember(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):
        """ See: https://core.telegram.org/bots/api#promotechatmember """
        p = _strip(locals())
        return await self._api_request('promoteChatMember', _rectify(p))

    async def exportChatInviteLink(self, chat_id):
        """ See: https://core.telegram.org/bots/api#exportchatinvitelink """
        p = _strip(locals())
        return await self._api_request('exportChatInviteLink', _rectify(p))

    async def setChatPhoto(self, chat_id, photo):
        """ See: https://core.telegram.org/bots/api#setchatphoto """
        p = _strip(locals(), more=['photo'])
        return await self._api_request_with_file('setChatPhoto', _rectify(p), 'photo', photo)

    async def deleteChatPhoto(self, chat_id):
        """ See: https://core.telegram.org/bots/api#deletechatphoto """
        p = _strip(locals())
        return await self._api_request('deleteChatPhoto', _rectify(p))

    async def setChatTitle(self, chat_id, title):
        """ See: https://core.telegram.org/bots/api#setchattitle """
        p = _strip(locals())
        return await self._api_request('setChatTitle', _rectify(p))

    async def setChatDescription(self, chat_id,
                                 description=None):
        """ See: https://core.telegram.org/bots/api#setchatdescription """
        p = _strip(locals())
        return await self._api_request('setChatDescription', _rectify(p))

    async def pinChatMessage(self, chat_id, message_id,
                             disable_notification=None):
        """ See: https://core.telegram.org/bots/api#pinchatmessage """
        p = _strip(locals())
        return await self._api_request('pinChatMessage', _rectify(p))

    async def unpinChatMessage(self, chat_id):
        """ See: https://core.telegram.org/bots/api#unpinchatmessage """
        p = _strip(locals())
        return await self._api_request('unpinChatMessage', _rectify(p))

    async def leaveChat(self, chat_id):
        """ See: https://core.telegram.org/bots/api#leavechat """
        p = _strip(locals())
        return await self._api_request('leaveChat', _rectify(p))

    async def getChat(self, chat_id):
        """ See: https://core.telegram.org/bots/api#getchat """
        p = _strip(locals())
        return await self._api_request('getChat', _rectify(p))

    async def getChatAdministrators(self, chat_id):
        """ See: https://core.telegram.org/bots/api#getchatadministrators """
        p = _strip(locals())
        return await self._api_request('getChatAdministrators', _rectify(p))

    async def getChatMembersCount(self, chat_id):
        """ See: https://core.telegram.org/bots/api#getchatmemberscount """
        p = _strip(locals())
        return await self._api_request('getChatMembersCount', _rectify(p))

    async def getChatMember(self, chat_id, user_id):
        """ See: https://core.telegram.org/bots/api#getchatmember """
        p = _strip(locals())
        return await self._api_request('getChatMember', _rectify(p))

    async def setChatStickerSet(self, chat_id, sticker_set_name):
        """ See: https://core.telegram.org/bots/api#setchatstickerset """
        p = _strip(locals())
        return await self._api_request('setChatStickerSet', _rectify(p))

    async def deleteChatStickerSet(self, chat_id):
        """ See: https://core.telegram.org/bots/api#deletechatstickerset """
        p = _strip(locals())
        return await self._api_request('deleteChatStickerSet', _rectify(p))

    async def answerCallbackQuery(self, callback_query_id,
                                  text=None,
                                  show_alert=None,
                                  url=None,
                                  cache_time=None):
        """ See: https://core.telegram.org/bots/api#answercallbackquery """
        p = _strip(locals())
        return await self._api_request('answerCallbackQuery', _rectify(p))

    async def answerShippingQuery(self, shipping_query_id, ok,
                                  shipping_options=None,
                                  error_message=None):
        """ See: https://core.telegram.org/bots/api#answershippingquery """
        p = _strip(locals())
        return await self._api_request('answerShippingQuery', _rectify(p))

    async def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
                                     error_message=None):
        """ See: https://core.telegram.org/bots/api#answerprecheckoutquery """
        p = _strip(locals())
        return await self._api_request('answerPreCheckoutQuery', _rectify(p))

    async def editMessageText(self, msg_identifier, text,
                              parse_mode=None,
                              disable_web_page_preview=None,
                              reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#editmessagetext

        :param msg_identifier:
            a 2-tuple (``chat_id``, ``message_id``),
            a 1-tuple (``inline_message_id``),
            or simply ``inline_message_id``.
            You may extract this value easily with :meth:`telepot.message_identifier`
        """
        p = _strip(locals(), more=['msg_identifier'])
        p.update(_dismantle_message_identifier(msg_identifier))
        return await self._api_request('editMessageText', _rectify(p))

    async def editMessageCaption(self, msg_identifier,
                                 caption=None,
                                 parse_mode=None,
                                 reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#editmessagecaption

        :param msg_identifier: Same as ``msg_identifier`` in :meth:`telepot.aio.Bot.editMessageText`
        """
        p = _strip(locals(), more=['msg_identifier'])
        p.update(_dismantle_message_identifier(msg_identifier))
        return await self._api_request('editMessageCaption', _rectify(p))

    async def editMessageReplyMarkup(self, msg_identifier,
                                     reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#editmessagereplymarkup

        :param msg_identifier: Same as ``msg_identifier`` in :meth:`telepot.aio.Bot.editMessageText`
        """
        p = _strip(locals(), more=['msg_identifier'])
        p.update(_dismantle_message_identifier(msg_identifier))
        return await self._api_request('editMessageReplyMarkup', _rectify(p))

    async def deleteMessage(self, msg_identifier):
        """
        See: https://core.telegram.org/bots/api#deletemessage

        :param msg_identifier:
            Same as ``msg_identifier`` in :meth:`telepot.aio.Bot.editMessageText`,
            except this method does not work on inline messages.
        """
        p = _strip(locals(), more=['msg_identifier'])
        p.update(_dismantle_message_identifier(msg_identifier))
        return await self._api_request('deleteMessage', _rectify(p))

    async def sendSticker(self, chat_id, sticker,
                          disable_notification=None,
                          reply_to_message_id=None,
                          reply_markup=None):
        """
        See: https://core.telegram.org/bots/api#sendsticker

        :param sticker: Same as ``photo`` in :meth:`telepot.aio.Bot.sendPhoto`
        """
        p = _strip(locals(), more=['sticker'])
        return await self._api_request_with_file('sendSticker', _rectify(p), 'sticker', sticker)

    async def getStickerSet(self, name):
        """
        See: https://core.telegram.org/bots/api#getstickerset
        """
        p = _strip(locals())
        return await self._api_request('getStickerSet', _rectify(p))

    async def uploadStickerFile(self, user_id, png_sticker):
        """
        See: https://core.telegram.org/bots/api#uploadstickerfile
        """
        p = _strip(locals(), more=['png_sticker'])
        return await self._api_request_with_file('uploadStickerFile', _rectify(p), 'png_sticker', png_sticker)

    async def createNewStickerSet(self, user_id, name, title, png_sticker, emojis,
                                  contains_masks=None,
                                  mask_position=None):
        """
        See: https://core.telegram.org/bots/api#createnewstickerset
        """
        p = _strip(locals(), more=['png_sticker'])
        return await self._api_request_with_file('createNewStickerSet', _rectify(p), 'png_sticker', png_sticker)

    async def addStickerToSet(self, user_id, name, png_sticker, emojis,
                              mask_position=None):
        """
        See: https://core.telegram.org/bots/api#addstickertoset
        """
        p = _strip(locals(), more=['png_sticker'])
        return await self._api_request_with_file('addStickerToSet', _rectify(p), 'png_sticker', png_sticker)

    async def setStickerPositionInSet(self, sticker, position):
        """
        See: https://core.telegram.org/bots/api#setstickerpositioninset
        """
        p = _strip(locals())
        return await self._api_request('setStickerPositionInSet', _rectify(p))

    async def deleteStickerFromSet(self, sticker):
        """
        See: https://core.telegram.org/bots/api#deletestickerfromset
        """
        p = _strip(locals())
        return await self._api_request('deleteStickerFromSet', _rectify(p))

    async def answerInlineQuery(self, inline_query_id, results,
                                cache_time=None,
                                is_personal=None,
                                next_offset=None,
                                switch_pm_text=None,
                                switch_pm_parameter=None):
        """ See: https://core.telegram.org/bots/api#answerinlinequery """
        p = _strip(locals())
        return await self._api_request('answerInlineQuery', _rectify(p))

    async def getUpdates(self,
                         offset=None,
                         limit=None,
                         timeout=None,
                         allowed_updates=None):
        """ See: https://core.telegram.org/bots/api#getupdates """
        p = _strip(locals())
        return await self._api_request('getUpdates', _rectify(p))

    async def setWebhook(self,
                         url=None,
                         certificate=None,
                         max_connections=None,
                         allowed_updates=None):
        """ See: https://core.telegram.org/bots/api#setwebhook """
        p = _strip(locals(), more=['certificate'])

        if certificate:
            files = {'certificate': certificate}
            return await self._api_request('setWebhook', _rectify(p), files)
        else:
            return await self._api_request('setWebhook', _rectify(p))

    async def deleteWebhook(self):
        """ See: https://core.telegram.org/bots/api#deletewebhook """
        return await self._api_request('deleteWebhook')

    async def getWebhookInfo(self):
        """ See: https://core.telegram.org/bots/api#getwebhookinfo """
        return await self._api_request('getWebhookInfo')

    async def setGameScore(self, user_id, score, game_message_identifier,
                           force=None,
                           disable_edit_message=None):
        """ See: https://core.telegram.org/bots/api#setgamescore """
        p = _strip(locals(), more=['game_message_identifier'])
        p.update(_dismantle_message_identifier(game_message_identifier))
        return await self._api_request('setGameScore', _rectify(p))

    async def getGameHighScores(self, user_id, game_message_identifier):
        """ See: https://core.telegram.org/bots/api#getgamehighscores """
        p = _strip(locals(), more=['game_message_identifier'])
        p.update(_dismantle_message_identifier(game_message_identifier))
        return await self._api_request('getGameHighScores', _rectify(p))

    async def download_file(self, file_id, dest):
        """
        Download a file to local disk.

        :param dest: a path or a ``file`` object
        """
        f = await self.getFile(file_id)

        try:
            d = dest if isinstance(dest, io.IOBase) else open(dest, 'wb')

            session, request = api.download((self._token, f['file_path']))

            async with session:
                async with request as r:
                    while 1:
                        chunk = await r.content.read(self._file_chunk_size)
                        if not chunk:
                            break
                        d.write(chunk)
                        d.flush()
        finally:
            if not isinstance(dest, io.IOBase) and 'd' in locals():
                d.close()

    async def message_loop(self, handler=None, relax=0.1,
                           timeout=20, allowed_updates=None,
                           source=None, ordered=True, maxhold=3):
        """
        Return a task to constantly ``getUpdates`` or pull updates from a queue.
        Apply ``handler`` to every message received.

        :param handler:
            a function that takes one argument (the message), or a routing table.
            If ``None``, the bot's ``handle`` method is used.

        A *routing table* is a dictionary of ``{flavor: function}``, mapping messages to appropriate
        handler functions according to their flavors. It allows you to define functions specifically
        to handle one flavor of messages. It usually looks like this: ``{'chat': fn1,
        'callback_query': fn2, 'inline_query': fn3, ...}``. Each handler function should take
        one argument (the message).

        :param source:
            Source of updates.
            If ``None``, ``getUpdates`` is used to obtain new messages from Telegram servers.
            If it is a ``asyncio.Queue``, new messages are pulled from the queue.
            A web application implementing a webhook can dump updates into the queue,
            while the bot pulls from it. This is how telepot can be integrated with webhooks.

        Acceptable contents in queue:

        - ``str`` or ``bytes`` (decoded using UTF-8)
          representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object.
        - a ``dict`` representing an Update object.

        When ``source`` is a queue, these parameters are meaningful:

        :type ordered: bool
        :param ordered:
            If ``True``, ensure in-order delivery of messages to ``handler``
            (i.e. updates with a smaller ``update_id`` always come before those with
            a larger ``update_id``).
            If ``False``, no re-ordering is done. ``handler`` is applied to messages
            as soon as they are pulled from queue.

        :type maxhold: float
        :param maxhold:
            Applied only when ``ordered`` is ``True``. The maximum number of seconds
            an update is held waiting for a not-yet-arrived smaller ``update_id``.
            When this number of seconds is up, the update is delivered to ``handler``
            even if some smaller ``update_id``\s have not yet arrived. If those smaller
            ``update_id``\s arrive at some later time, they are discarded.

        :type timeout: int
        :param timeout:
            ``timeout`` parameter supplied to :meth:`telepot.aio.Bot.getUpdates`,
            controlling how long to poll in seconds.

        :type allowed_updates: array of string
        :param allowed_updates:
            ``allowed_updates`` parameter supplied to :meth:`telepot.aio.Bot.getUpdates`,
            controlling which types of updates to receive.
        """
        if handler is None:
            handler = self.handle
        elif isinstance(handler, dict):
            handler = flavor_router(handler)

        def create_task_for(msg):
            self.loop.create_task(handler(msg))

        if asyncio.iscoroutinefunction(handler):
            callback = create_task_for
        else:
            callback = handler

        def handle(update):
            try:
                key = _find_first_key(update, ['message',
                                               'edited_message',
                                               'channel_post',
                                               'edited_channel_post',
                                               'callback_query',
                                               'inline_query',
                                               'chosen_inline_result',
                                               'shipping_query',
                                               'pre_checkout_query'])

                callback(update[key])
            except:
                # Localize the error so message thread can keep going.
                traceback.print_exc()
            finally:
                return update['update_id']

        async def get_from_telegram_server():
            offset = None  # running offset
            allowed_upd = allowed_updates
            while 1:
                try:
                    result = await self.getUpdates(offset=offset,
                                                   timeout=timeout,
                                                   allowed_updates=allowed_upd)

                    # Once passed, this parameter is no longer needed.
                    allowed_upd = None

                    if len(result) > 0:
                        # No sort. Trust server to give messages in correct order.
                        # Update offset to max(update_id) + 1
                        offset = max([handle(update) for update in result]) + 1
                except CancelledError:
                    raise
                except exception.BadHTTPResponse as e:
                    traceback.print_exc()

                    # Servers probably down. Wait longer.
                    if e.status == 502:
                        await asyncio.sleep(30)
                except:
                    traceback.print_exc()
                    await asyncio.sleep(relax)
                else:
                    await asyncio.sleep(relax)

        def dictify(data):
            if type(data) is bytes:
                return json.loads(data.decode('utf-8'))
            elif type(data) is str:
                return json.loads(data)
            elif type(data) is dict:
                return data
            else:
                raise ValueError()

        async def get_from_queue_unordered(qu):
            while 1:
                try:
                    data = await qu.get()
                    update = dictify(data)
                    handle(update)
                except:
                    traceback.print_exc()

        async def get_from_queue(qu):
            # Here is the re-ordering mechanism, ensuring in-order delivery of updates.
            max_id = None                 # max update_id passed to callback
            buffer = collections.deque()  # keep those updates which skip some update_id
            qwait = None                  # how long to wait for updates,
                                          # because buffer's content has to be returned in time.

            while 1:
                try:
                    data = await asyncio.wait_for(qu.get(), qwait)
                    update = dictify(data)

                    if max_id is None:
                        # First message received, handle regardless.
                        max_id = handle(update)

                    elif update['update_id'] == max_id + 1:
                        # No update_id skipped, handle naturally.
                        max_id = handle(update)

                        # clear contagious updates in buffer
                        if len(buffer) > 0:
                            buffer.popleft()  # first element belongs to update just received, useless now.
                            while 1:
                                try:
                                    if type(buffer[0]) is dict:
                                        max_id = handle(buffer.popleft())  # updates that arrived earlier, handle them.
                                    else:
                                        break  # gap, no more contagious updates
                                except IndexError:
                                    break  # buffer empty

                    elif update['update_id'] > max_id + 1:
                        # Update arrives pre-maturely, insert to buffer.
                        nbuf = len(buffer)
                        if update['update_id'] <= max_id + nbuf:
                            # buffer long enough, put update at position
                            buffer[update['update_id'] - max_id - 1] = update
                        else:
                            # buffer too short, lengthen it
                            expire = time.time() + maxhold
                            for a in range(nbuf, update['update_id']-max_id-1):
                                buffer.append(expire)  # put expiry time in gaps
                            buffer.append(update)

                    else:
                        pass  # discard

                except asyncio.TimeoutError:
                    # debug message
                    # print('Timeout')

                    # some buffer contents have to be handled
                    # flush buffer until a non-expired time is encountered
                    while 1:
                        try:
                            if type(buffer[0]) is dict:
                                max_id = handle(buffer.popleft())
                            else:
                                expire = buffer[0]
                                if expire <= time.time():
                                    max_id += 1
                                    buffer.popleft()
                                else:
                                    break  # non-expired
                        except IndexError:
                            break  # buffer empty
                except:
                    traceback.print_exc()
                finally:
                    try:
                        # don't wait longer than next expiry time
                        qwait = buffer[0] - time.time()
                        if qwait < 0:
                            qwait = 0
                    except IndexError:
                        # buffer empty, can wait forever
                        qwait = None

                    # debug message
                    # print ('Buffer:', str(buffer), ', To Wait:', qwait, ', Max ID:', max_id)

        self._scheduler._callback = callback

        if source is None:
            await get_from_telegram_server()
        elif isinstance(source, asyncio.Queue):
            if ordered:
                await get_from_queue(source)
            else:
                await get_from_queue_unordered(source)
        else:
            raise ValueError('Invalid source')

class SpeakerBot(Bot):
    def __init__(self, token, loop=None):
        super(SpeakerBot, self).__init__(token, loop)
        self._mic = helper.Microphone()

    @property
    def mic(self):
        return self._mic

    def create_listener(self):
        q = asyncio.Queue()
        self._mic.add(q)
        ln = helper.Listener(self._mic, q)
        return ln

class DelegatorBot(SpeakerBot):
    def __init__(self, token, delegation_patterns, loop=None):
        """
        :param delegation_patterns: a list of (seeder, delegator) tuples.
        """
        super(DelegatorBot, self).__init__(token, loop)
        self._delegate_records = [p+({},) for p in delegation_patterns]

    def handle(self, msg):
        self._mic.send(msg)

        for calculate_seed, make_coroutine_obj, dict in self._delegate_records:
            id = calculate_seed(msg)

            if id is None:
                continue
            elif isinstance(id, collections.Hashable):
                if id not in dict or dict[id].done():
                    c = make_coroutine_obj((self, msg, id))

                    if not asyncio.iscoroutine(c):
                        raise RuntimeError('You must produce a coroutine *object* as delegate.')

                    dict[id] = self._loop.create_task(c)
            else:
                c = make_coroutine_obj((self, msg, id))
                self._loop.create_task(c)


text:
module.exports.create = function(req, res) {
  var attachment = req.param('attachment')
  ,   file = req.files['attachment']['file']
  ,   re = new RegExp("public(/.*)")
  ,   url = re.exec("public/uploads/31201-1n8se41.png")[1];
  console.dir(attachment);
  console.dir(file);
  res.send(200, {file: {url: url, large: {url: url}}});
};

redpajama_set_name: RedPajamaGithub


text:
'use strict';

exports.init = function(req, res){
  res.render('dataEntry/index');
};


text:
import logging
from typing import Union

import anndata
import torch

from scvi import _CONSTANTS
from scvi.core.data_loaders import TotalDataLoader
from scvi.core.modules import TOTALVAE, Classifier
from scvi.core.modules.utils import one_hot
from scvi.core.trainers import UnsupervisedTrainer

logger = logging.getLogger(__name__)

default_early_stopping_kwargs = {
    "early_stopping_metric": "elbo",
    "save_best_state_metric": "elbo",
    "patience": 45,
    "threshold": 0,
    "reduce_lr_on_plateau": True,
    "lr_patience": 30,
    "lr_factor": 0.6,
    "scvi_data_loader_class": TotalDataLoader,
}

def _unpack_tensors(tensors):
    x = tensors[_CONSTANTS.X_KEY]
    local_l_mean = tensors[_CONSTANTS.LOCAL_L_MEAN_KEY]
    local_l_var = tensors[_CONSTANTS.LOCAL_L_VAR_KEY]
    batch_index = tensors[_CONSTANTS.BATCH_KEY]
    labels = tensors[_CONSTANTS.LABELS_KEY]
    y = tensors[_CONSTANTS.PROTEIN_EXP_KEY]
    return x, local_l_mean, local_l_var, batch_index, labels, y

class TotalTrainer(UnsupervisedTrainer):
    """
    Unsupervised training for totalVI using variational inference.

    Parameters
    ----------
    model
        A model instance from class ``TOTALVAE``
    adata
        A registered AnnData object
    train_size
        The train size, a float between 0 and 1 representing proportion of dataset to use for training
        to use Default: ``0.90``.
    test_size
        The test size, a float between 0 and 1 representing proportion of dataset to use for testing
        to use Default: ``0.10``. Note that if train and test do not add to 1 the remainder is placed in a validation set
    pro_recons_weight
        Scaling factor on the reconstruction loss for proteins. Default: ``1.0``.
    n_epochs_kl_warmup
        Number of epochs for annealing the KL terms for `z` and `mu` of the ELBO (from 0 to 1). If None, no warmup performed, unless
        `n_iter_kl_warmup` is set.
    n_iter_kl_warmup
        Number of minibatches for annealing the KL terms for `z` and `mu` of the ELBO (from 0 to 1). If set to "auto", the number
        of iterations is equal to 75% of the number of cells. `n_epochs_kl_warmup` takes precedence if it is not None. If both are None, then
        no warmup is performed.
    discriminator
        Classifier used for adversarial training scheme
    use_adversarial_loss
        Whether to use adversarial classifier to improve mixing
    kappa
        Scaling factor for adversarial loss. If None, follow inverse of kl warmup schedule.
    early_stopping_kwargs
        Keyword args for early stopping. If "auto", use totalVI defaults. If None, disable early stopping.
    """

    default_metrics_to_monitor = ["elbo"]

    def __init__(
        self,
        model: TOTALVAE,
        dataset: anndata.AnnData,
        train_size: float = 0.90,
        test_size: float = 0.10,
        pro_recons_weight: float = 1.0,
        n_epochs_kl_warmup: int = None,
        n_iter_kl_warmup: Union[str, int] = "auto",
        discriminator: Classifier = None,
        use_adversarial_loss: bool = False,
        kappa: float = None,
        early_stopping_kwargs: Union[dict, str, None] = "auto",
        **kwargs,
    ):
        train_size = float(train_size)
        if train_size > 1.0 or train_size <= 0.0:
            raise ValueError(
                "train_size needs to be greater than 0 and less than or equal to 1"
            )
        self.n_genes = model.n_input_genes
        self.n_proteins = model.n_input_proteins
        self.use_adversarial_loss = use_adversarial_loss
        self.kappa = kappa
        self.pro_recons_weight = pro_recons_weight

        if early_stopping_kwargs == "auto":
            early_stopping_kwargs = default_early_stopping_kwargs

        super().__init__(
            model,
            dataset,
            n_epochs_kl_warmup=n_epochs_kl_warmup,
            n_iter_kl_warmup=0.75 * len(dataset)
            if n_iter_kl_warmup == "auto"
            else n_iter_kl_warmup,
            early_stopping_kwargs=early_stopping_kwargs,
            **kwargs,
        )

        if use_adversarial_loss is True and discriminator is None:
            discriminator = Classifier(
                n_input=self.model.n_latent,
                n_hidden=32,
                n_labels=self.adata.uns["_scvi"]["summary_stats"]["n_batch"],
                n_layers=2,
                logits=True,
            )

        self.discriminator = discriminator
        if self.use_cuda and self.discriminator is not None:
            self.discriminator.cuda()

        if isinstance(self, TotalTrainer):
            (
                self.train_set,
                self.test_set,
                self.validation_set,
            ) = self.train_test_validation(
                model, dataset, train_size, test_size, type_class=TotalDataLoader
            )
            self.train_set.to_monitor = []
            self.test_set.to_monitor = ["elbo"]
            self.validation_set.to_monitor = ["elbo"]

    def loss(self, tensors):
        (
            sample_batch_x,
            local_l_mean,
            local_l_var,
            batch_index,
            label,
            sample_batch_y,
        ) = _unpack_tensors(tensors)
        (
            reconst_loss_gene,
            reconst_loss_protein,
            kl_div_z,
            kl_div_l_gene,
            kl_div_back_pro,
        ) = self.model(
            sample_batch_x,
            sample_batch_y,
            local_l_mean,
            local_l_var,
            batch_index,
            label,
        )

        loss = torch.mean(
            reconst_loss_gene
            + self.pro_recons_weight * reconst_loss_protein
            + self.kl_weight * kl_div_z
            + kl_div_l_gene
            + self.kl_weight * kl_div_back_pro
        )

        return loss

    def loss_discriminator(
        self, z, batch_index, predict_true_class=True, return_details=True
    ):

        n_classes = self.adata.uns["_scvi"]["summary_stats"]["n_batch"]
        cls_logits = torch.nn.LogSoftmax(dim=1)(self.discriminator(z))

        if predict_true_class:
            cls_target = one_hot(batch_index, n_classes)
        else:
            one_hot_batch = one_hot(batch_index, n_classes)
            cls_target = torch.zeros_like(one_hot_batch)
            # place zeroes where true label is
            cls_target.masked_scatter_(
                ~one_hot_batch.bool(), torch.ones_like(one_hot_batch) / (n_classes - 1)
            )

        l_soft = cls_logits * cls_target
        loss = -l_soft.sum(dim=1).mean()

        return loss

    def _get_z(self, tensors):
        (
            sample_batch_x,
            local_l_mean,
            local_l_var,
            batch_index,
            label,
            sample_batch_y,
        ) = _unpack_tensors(tensors)

        z = self.model.sample_from_posterior_z(
            sample_batch_x, sample_batch_y, batch_index, give_mean=False
        )

        return z

    def train(self, n_epochs=500, lr=4e-3, eps=0.01, params=None, max_grad_value=None):
        self.max_grad_value = max_grad_value

        super().train(n_epochs=n_epochs, lr=lr, eps=eps, params=params)

    def on_training_loop(self, tensors_dict):
        if self.use_adversarial_loss:
            if self.kappa is None:
                kappa = 1 - self.kl_weight
            else:
                kappa = self.kappa
            batch_index = tensors_dict[0][_CONSTANTS.BATCH_KEY]
            if kappa > 0:
                z = self._get_z(*tensors_dict)
                # Train discriminator
                d_loss = self.loss_discriminator(z.detach(), batch_index, True)
                d_loss *= kappa
                self.d_optimizer.zero_grad()
                d_loss.backward()
                self.d_optimizer.step()

                # Train generative model to fool discriminator
                fool_loss = self.loss_discriminator(z, batch_index, False)
                fool_loss *= kappa

            # Train generative model
            self.optimizer.zero_grad()
            self.current_loss = loss = self.loss(*tensors_dict)
            if kappa > 0:
                (loss + fool_loss).backward()
            else:
                loss.backward()
            if self.max_grad_value is not None:
                torch.nn.utils.clip_grad_norm_(
                    self.optimizer.param_groups[0]["params"],
                    self.max_grad_value,
                    norm_type="inf",
                )
            self.optimizer.step()

        else:
            self.current_loss = loss = self.loss(*tensors_dict)
            self.optimizer.zero_grad()
            loss.backward()
            if self.max_grad_value is not None:
                torch.nn.utils.clip_grad_norm_(
                    self.optimizer.param_groups[0]["params"],
                    self.max_grad_value,
                    norm_type="inf",
                )
            self.optimizer.step()

    def training_extras_init(self, lr_d=1e-3, eps=0.01):
        if self.discriminator is not None:
            self.discriminator.train()

            d_params = filter(
                lambda p: p.requires_grad, self.discriminator.parameters()
            )
            self.d_optimizer = torch.optim.Adam(d_params, lr=lr_d, eps=eps)

    def training_extras_end(self):
        if self.discriminator is not None:
            self.discriminator.eval()


text:
/*+**************************************************************************/
/***                                                                      ***/
/***   This file is distributed under a BSD license.                      ***/
/***   See LICENSE.txt for details.                                       ***/
/***                                                                      ***/
/**************************************************************************+*/

#define sPEDANTIC_WARN 1
#include "doc.hpp"

/****************************************************************************/

static const sChar *MakePlatforms[] =
{
  L"???",
  L"MinGW",
  L"Linux",
};

/****************************************************************************/
/****************************************************************************/

static sBool ConfigMatchesPlatform(Config *config,sInt platform)
{
  switch(platform)
  {
  case sMAKE_LINUX: return (config->VSPlatformMask & sVSPLAT_LINUX) != 0; break;
  default:          return sFALSE;
  }
}

Config *FindConfig(sArray<Config *>*list,sInt platform)
{
  Config *config;

  sFORALL(*list,config)
  {
    if(ConfigMatchesPlatform(config,platform))
      return config;
  }
  return 0;
}

static void CheckConfig(Config *config,sInt platform)
{
  if(!config)
    sPrintF(L"configuration for platform <%s> not found\n",MakePlatforms[platform]);
  else if(config->MakeTarget.GetCount()==0 || config->MakeDefine.GetCount()==0 || config->TargetExeTemplate.IsEmpty() ||
    config->LinkExe.GetCount()==0 || config->ObjectExtension.IsEmpty())
    sPrintF(L"configuration for platform <%s> is incomplete\n",MakePlatforms[platform]);
}

Config *FindConfigCheck(sArray<Config *>*list,sInt platform)
{
  Config *config = FindConfig(list,platform);
  CheckConfig(config,platform);
  return config;
}

/****************************************************************************/

void Document::OutputPrepareMakefile()
{
  ProjectData *proj;
  Config *config;

  config = FindConfigCheck(&BaseConfigs,ConfMakefile);
  if(config)
  {
    sFORALL(Projects,proj)
    {
      if(proj->ConfigurationType == 1)
        sSPrintF(proj->MakeTarget,config->TargetExeTemplate,proj->Name);
      else
        sSPrintF(proj->MakeTarget,config->TargetLibTemplate,proj->Name);
    }
  }
}

/****************************************************************************/

void Document::OutputSolutionMakefile()
{
  ProjectData *proj;
  Depend *depend;
  sPoolString *nameptr;
  sArray<Depend *> deps;
  Config *config;

  config = FindConfigCheck(&BaseConfigs,ConfMakefile);
  if(!config) return;

  sString<256> mext;
  if (!config->MakefileExtension.IsEmpty())
  {
    mext=L".";
    mext.Add(config->MakefileExtension);
  }

  OutBuffer.Clear();
  OutBuffer.PrintF(L"#\n# Automatic Generated Makefile for %s\n#\n\n",MakePlatforms[ConfigFile.Makefile]);

  OutBuffer.Print (L"all:\t");
  sFORALL(Solution->Projects, proj)
    OutBuffer.PrintF(L" %s", proj->Name);
  OutBuffer.Print (L"\n");
  OutBuffer.Print (L"\n");

  sFORALL(Solution->Projects, proj)
  {
    OutBuffer.PrintF(L"%s:", proj->Name);
    sFORALL(proj->Dependencies,depend)
    {
      OutBuffer.PrintF(L" %s",depend->Project->Name);
	    if(!sFind(deps,&Depend::Project,depend->Project) && !sFindPtr(Solution->Projects,depend->Project))
        deps.AddTail(depend);
    }
    OutBuffer.PrintF(L"\n\t@echo --- %s\n",proj->Name);
    OutBuffer.PrintF(L"\t+@make -s --no-print-directory -C %s -f Makefile.%s%s\n",proj->Path.Path(OmniPath::PT_MAKEFILE),proj->Name,mext);
    OutBuffer.PrintF(L"\t@echo Done.\n\n");
  }

	OutBuffer.PrintF(L"\n# deps\n\n");

  sFORALL(deps,depend)
  {
    proj = depend->Project;
    OutBuffer.PrintF(L"%s:",proj->Name);
    sFORALL(proj->Dependencies,depend)
    {
      OutBuffer.PrintF(L" %s",depend->Project->Name);
      if(!sFind(deps,&Depend::Project,depend->Project) && !sFindPtr(Solution->Projects,depend->Project))
        deps.AddTail(depend);
    }
    OutBuffer.PrintF(L"\n\t@echo --- %s\n",proj->Name);
    OutBuffer.PrintF(L"\t+@make -s --no-print-directory -C %s -f Makefile.%s%s\n\n",proj->Path.Path(OmniPath::PT_MAKEFILE),proj->Name,mext);
  }

	OutBuffer.PrintF(L"\n# faketargetall\n\n");

	sFORALL(config->FakeTargetAll,nameptr)
  {
    OutBuffer.PrintF(L"%s:\n",*nameptr);

    sFORALL(Solution->Projects, proj)
      OutBuffer.PrintF(L"\t@make -s --no-print-directory -C %s -f Makefile.%s%s %s\n",proj->Path.Path(OmniPath::PT_MAKEFILE),proj->Name,mext,*nameptr );
    sFORALL(deps,depend)
    {
      proj = depend->Project;
      OutBuffer.PrintF(L"\t@make -s --no-print-directory -C %s -f Makefile.%s%s %s\n",proj->Path.Path(OmniPath::PT_MAKEFILE),proj->Name,mext,*nameptr );
    }
    OutBuffer.PrintF(L"\t@echo Done.\n");
    OutBuffer.PrintF(L"\n");
  }

	OutBuffer.PrintF(L"\n# faketargetonce\n\n");

	sFORALL(config->FakeTargetOnce,nameptr)
  {
    OutBuffer.PrintF(L"%s:",*nameptr);
    sFORALL(deps,depend)
      OutBuffer.PrintF(L" %s",depend->Project->Name);
    OutBuffer.PrintF(L"\n");

    sFORALL(Solution->Projects, proj)
      OutBuffer.PrintF(L"\t@make -s --no-print-directory -C %s -f Makefile.%s%s %s\n",proj->Path.Path(OmniPath::PT_MAKEFILE),proj->Name,mext,*nameptr );
    OutBuffer.PrintF(L"\t@echo Done.\n");
    OutBuffer.PrintF(L"\n");
  }

  if(WriteFlag)
  {
    sString<4096> makefilename=Solution->GNUMakeOutputfile;
    if (!config->MakefileExtension.IsEmpty())
    {
      makefilename.Add(L".");
      makefilename.Add(config->MakefileExtension);
    }
    if(!BriefFlag)
      sPrintF(L"  write <%s>\n",makefilename);
    sSaveTextAnsiIfDifferent(makefilename,OutBuffer.Get());
  }
}

/****************************************************************************/

static void PrintList(sTextBuffer &out,const sChar *macro,sInt &n)
{
  if(n%8==0)
  {
    if(n==0)
      out.PrintF(L"\n%-11s =",macro);
    else
      out.PrintF(L"\n%-11s+=",macro);
  }
  n++;
}

void Document::AddMakefileFolder(ProjFolder *parent,sInt &n,Config *projcfg)
{
  File *file;
  ProjFolder *folder;
  Config *config;
  sFORALL(parent->Files,file)
  {
    const sChar *ext=sFindFileExtension(file->Name);
    if (sFind(projcfg->SourceExtensions,sPoolString(ext)))
    {
      config = sFind(file->Modifications,&Config::Name,projcfg->Name);
      if(!(config && config->ExcludeFromBuild))
      {
        PrintList(OutBuffer,L"OBJS",n);
        sString<256> buffer;
        sCopyString(buffer,file->Name,ext-file->Name);

        for(sInt i=0;buffer[i];i++)
        {
          if(buffer[i]=='\\')
            buffer[i] = '/';
        }

        OutBuffer.PrintF(L" $(CONFIG)/%s.%s",buffer,projcfg->ObjectExtension);
      }
    }
  }
  sFORALL(parent->Folders,folder)
    AddMakefileFolder(folder,n,projcfg);
}

sBool Document::AddMakefileCustomSteps(ProjFolder *parent,sInt &n,Config *projcfg)
{
  File *file;
  ProjFolder *folder;
  Config *config;
  sBool result=sFALSE;

  sFORALL(parent->Files,file)
  {
    const sChar *ext=sFindFileExtension(file->Name);
    if (sFind(projcfg->CustomExtensions,sPoolString(ext)))
    {
      config = sFind(file->Modifications,&Config::Name,projcfg->Name);
      if(!(config && config->ExcludeFromBuild))
      {
        PrintList(OutBuffer,L"CUSTOMDEPS",n);
        sString<256> buffer;
        sCopyString(buffer,file->Name,ext-file->Name);
        for(sInt i=0;buffer[i];i++)
          if(buffer[i]=='\\')
            buffer[i] = '/';
        OutBuffer.PrintF(L" %s.hpp",buffer);
        result = sTRUE;
      }
    }
  }
  sFORALL(parent->Folders,folder)
    result|=AddMakefileCustomSteps(folder,n,projcfg);

  return result;
}

static void BuildCachedLinksR(ProjFolder *parent,Config *projcfg,CachedLink *cache)
{
  File *file;
  ProjFolder *folder;
  sFORALL(parent->Files,file)
  {
    const sChar *ext=sFindFileExtension(file->Name);
    if(sFind(projcfg->SourceExtensions,sPoolString(ext)))
    {
      Config *config = sFind(file->Modifications,&Config::Name,projcfg->Name);
      if(config && !config->ExcludeFromBuild)
      {
        // add libraries required by any of the source files to the links
        sPoolString *link;
        sFORALL(config->Links,link)
        {
          if(!sFind(cache->Links,*link))
            cache->Links.AddTail(*link);
        }
      }
    }
  }
  sFORALL(parent->Folders,folder)
    BuildCachedLinksR(folder,projcfg,cache);
}

CachedLink *Document::GetMakefileCachedLinks(ProjectData *proj,Config *projcfg)
{
  CachedLink *cache;

  sFORALL(proj->CachedLinks,cache)
  {
    if(cache->ProjectConfig == projcfg)
      return cache;
  }

  // First time around, need to create the cache first
  cache = new CachedLink;
  cache->ProjectConfig = projcfg;
  cache->Links = projcfg->Links;
  BuildCachedLinksR(&proj->Files,projcfg,cache);
  return cache;
}

static void AddLinks(sArray<sPoolString> &current,sArray<sPoolString> &more)
{
  sPoolString *link;
  sFORALL(more,link)
  {
    if(!sFind(current,*link))
      current.AddTail(*link);
  }
}

static void AddDepsR(ProjectData *proj,SolutionData *solution,sArray<ProjectData*> &deps)
{
  if(proj->CycleDetect)
  {
    sPrintF(L"Cyclic dependency between libraries detected! This won't (easily) work on Linux.\n");
    return;
  }

  proj->CycleDetect = 1;

  // add all my dependencies first
  Depend *dep;
  sFORALL(proj->Dependencies,dep)
    AddDepsR(dep->Project,solution,deps);

  // add this project if it's not already in and if it's not part of the solution anyway
  if(!sFindPtr(deps,proj) && !sFindPtr(solution->Projects,proj))
    deps.AddTail(proj);

  proj->CycleDetect = 0;
}

void Document::OutputProjectMakefile()
{
  sPoolString *name;
  Config *defconfig;

  defconfig = FindConfig(&Solution->Configs,ConfMakefile);
  if(!defconfig) return;

  OutBuffer.Clear();
  OutBuffer.PrintF(L"#\n# Automatic Generated Makefile for %s\n#\n",MakePlatforms[ConfMakefile]);

  // configuration selector
  OutBuffer.PrintF(L"ifndef CONFIG\nCONFIG      = %s\nendif\n",defconfig->Name);

  // --- configuration-dependent section

  // object files
  Config *config;
  sBool first = sTRUE;
  sInt numendifs=0;
  sFORALL(Solution->Configs,config)
  {
    if(!ConfigMatchesPlatform(config,ConfMakefile))
      continue;

    CheckConfig(config,ConfMakefile);
    OutBuffer.PrintF(L"\n%sifeq ($(CONFIG),%s)\n\n",first ? L"" : L"else\n",config->Name);
    numendifs++;
    first = sFALSE;

    // deep copy is necessary here (we might modify it later)
    sArray<sPoolString> links = GetMakefileCachedLinks(Project,config)->Links;

    sInt n=0;
    AddMakefileFolder(&Project->Files,n,config);
    sInt nObjFiles=n;
    if(n==0)
      PrintList(OutBuffer,L"OBJS",n);

    // asc generated files (if necessary)
    const sChar *customString = L"";
    n = 0;
    if (AddMakefileCustomSteps(&Project->Files,n,config))
    {
      if(n==0)
        PrintList(OutBuffer,L"CUSTOMDEPS",n);
      customString = L"$(CUSTOMDEPS) ";
    }

    // depending libraries: topological sort so we don't need to do it manually anymore.
    sArray<ProjectData *> deps;
    AddDepsR(Project,Solution,deps);

    // output deps
    n = 0;
    ProjectData *depend;
    sFORALLREVERSE(deps,depend)
    {
      PrintList(OutBuffer,L"DEPS",n);
      OutBuffer.PrintF(L" %s/$(CONFIG)/%s",depend->Path.Path(OmniPath::PT_MAKEFILE),depend->MakeTarget);

      // if any of our deps needs a library, we need it to
      AddLinks(links,GetMakefileCachedLinks(depend,config)->Links);
    }
    if(n==0)
      PrintList(OutBuffer,L"DEPS",n);

    // defines
    n=0;
    PrintList(OutBuffer,L"DEFINES",n);
    OutBuffer.PrintF(L" -DsCONFIG_GUID=");
    const sChar *g=Project->Guid;
    if(ConfigFile.Makefile != sMAKE_LINUX)
    {
      OutBuffer.PrintF(L"{0x%!8s\\\\\\,{0x%!4s\\\\\\,0x%!4s\\\\\\,0x%!4s}\\\\\\,{0x%!2s\\\\\\,0x%!2s\\\\\\,0x%!2s\\\\\\,0x%!2s\\\\\\,0x%!2s\\\\\\,0x%!2s}}",g+1,g+10,g+15,g+20,g+25,g+27,g+29,g+31,g+33,g+35);
    }
    else
    {
      OutBuffer.PrintF(L"{0x%!8s\\,{0x%!4s\\,0x%!4s\\,0x%!4s}\\,{0x%!2s\\,0x%!2s\\,0x%!2s\\,0x%!2s\\,0x%!2s\\,0x%!2s}}",g+1,g+10,g+15,g+20,g+25,g+27,g+29,g+31,g+33,g+35);
    }

    sFORALL(config->Defines,name)
    {
      PrintList(OutBuffer,L"DEFINES",n);
      OutBuffer.PrintF(L" -D%s",*name);
    }

    // libs
    n=0;
    sFORALL(links,name)
    {
      PrintList(OutBuffer,L"LIBS",n);
      if((*name)[0]=='$')
        OutBuffer.PrintF(L" %s",*name);
      else
        OutBuffer.PrintF(L" -l%s",*name);
    }
    if(n==0)
      PrintList(OutBuffer,L"LIBS",n);

    // includes
    n=0;
    OmniPath *path;
    sFORALL(Project->Includes,path)
    {
      PrintList(OutBuffer,L"INCDIR",n);
      OutBuffer.PrintF(L" -I%s",path->Path(OmniPath::PT_MAKEFILE));
    }
    if (n==0)
      PrintList(OutBuffer,L"INCDIR",n);

    // misc

    OutBuffer.PrintChar('\n');
    OutBuffer.PrintF(L"TARGET      = $(CONFIG)/%s\n",Project->MakeTarget);

    // the text

    OutBuffer.Print(L"\n#\n# defines\n#\n\n");
    OutBuffer.PrintF(L"ALTONAPATH = \"%s\"\n",RootPath.Path(OmniPath::PT_MAKEFILE));
    OutBuffer.Print(config->MakeDefine.Get());

    OutBuffer.Print(L"\n#\n# the main target\n#\n\n");
    if(nObjFiles)
    {
      if(Project->ConfigurationType == 1)
      {
        OutBuffer.PrintF(L"$(TARGET): $(OBJS) $(DEPS)\n");
        OutBuffer.Print(L"\t@echo \"LD  $(TARGET)\"\n");
        OutBuffer.Print(config->LinkExe.Get());
      }
      else
      {
        OutBuffer.PrintF(L"$(TARGET): $(OBJS)\n");
        OutBuffer.Print(L"\t@echo \"AR  $(TARGET)\"\n");
        OutBuffer.Print(config->LinkLib.Get());
      }
      if (customString[0]!=0)
      {
        OutBuffer.Print(L"\n#\n# custom build step dependencies\n#\n\n");
        OutBuffer.PrintF(L"$(OBJS): | %s\n",customString);
      }
    }
    else
      OutBuffer.Print(L"$(TARGET):\n\n");

    OutBuffer.Print(L"\n#\n# other targets\n#\n\n");
    OutBuffer.Print(config->MakeTarget.Get());
  }

  OutBuffer.PrintF(L"\nelse\n$(error CONFIG set to an invalid value)\n");
  for (sInt i=0; i<numendifs; i++)
    OutBuffer.PrintF(L"endif\n");

  if(WriteFlag)
  {
    sString<sMAXPATH> filename;

    filename = Project->Path.Path(OmniPath::PT_SYSTEM);
    filename.Add(L"/Makefile.");
    filename.Add(Project->Name);
    if (!defconfig->MakefileExtension.IsEmpty())
    {
      filename.Add(L".");
      filename.Add(defconfig->MakefileExtension);
    }
    if(TestFlag)
      filename.Add(L".txt");

    if(!BriefFlag)
      sPrintF(L"  write <%s>\n",filename);

    sSaveTextAnsiIfDifferent(filename,OutBuffer.Get());
  }
}

/****************************************************************************/


text:
package com.github.mrgoro.interactivedata.api.service.annotations;

import com.github.mrgoro.interactivedata.processors.ProcessedAnnotation;

import java.lang.annotation.*;

/**
 * Annotation indicating the root of a collection of corresponding APIs.
 *
 * @author Philipp Schürmann
 */
@Documented
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ProcessedAnnotation
public @interface ChartService {

    /**
     * Name of the service.
     * <p>
     * The name is part of the identification pattern for the api. The identification of a chart api has the format
     * of %Service-Name%/%Chart-Name%.
     *
     * @return Path String
     */
    String value();

    /**
     * Description of the service. Summary of charts inside the service.
     *
     * Description is only used for documentation. Automatically generated when empty.
     *
     * @return Description String
     */
    String description() default "";
}


text:
{% extends "base.html" %}

{% block pagecss %}

{% endblock %}
{% block pagehead %}
Cottage Grove — Umpqua 200k
March 30, 2019
{% endblock %}

{% block subhead %}{% endblock %}

{% block content %}

Umpqua River (James Taylor)

Unofficial map and downloadable track:

  https://ridewithgps.com/routes/29419451;

  Cue sheet as PDF or
      xlsx (Excel)

  Contact for more information:
  rba@will-rando.org

  Registration form

Start

 7:30am, Backstage Bakery, 25 S 7th St, Cottage Grove, OR.

Cost

$5 by Thursday
      March 28, $10 day of ride.

Finish

by 9:00pm at The BREW STATION @ Coast Fork Feed
       106 S 6th St, Cottage Grove..

Parking

Ample free parking at Bohemia Park, S 10th St & Adams Ave

South to the Land of Umpqua!

This very pretty, somewhat remote route was designed by James Taylor,
        who will be greeting riders at the start and finish.  We
    loop south from Cottage Grove through Drain and Yoncalla to the Umpqua river,
    then back north through Sutherlin.  There is some climbing, but it is not
        extreme.  There is some gravel, but for the most part it is paved.
        Expect it to be a little tougher than your typical 200k brevet.
    There are no services between Oakland (mile 89) and the finish in Cottage Grove.
        You should  pack some food and fill your bottles
    at the Sutherlin controle, mile 87.6, and consider picking up an extra bottle
        of water for the 40 mile stretch to Cottage Grove.

Requirements

As a condition of participation, you will be asked to sign a release and waiver of liability
        at the ride start.  Read it now
        so that you are familiar with it.  Be sure you know what you're getting into and
        are prepared and comfortable with the risks.

This brevet is sanctioned by Audax Club Parisien and Randonneurs
  USA, and is subject to RUSA Rules for
  Riders.  If you are not familiar with these rules, please
  read them well in advance so that you can be prepared.  They are
    <emph>not</emph> the same as a club century ride.

RUSA membership is not required to participate.  However, only
    RUSA members can buy a nifty medal to commemorate their
  achievement.

  Your bicycle must be equipped with front and rear lights,
  even if you expect to finish in daylight.  After dusk, you must
  use your lights.
  You must carry adequate reflective garments, preferably conforming
  to
  RUSA reflectivity
  guidelines.  If you are observed riding in low light conditions
  with inadequate lights or reflectivity, you will be
  disqualified.

Familiarize yourself with procedures for riding a brevet,
  incuding collection of times and signatures on the control card.
  The card must be signed and turned in at the finish.

What to expect

This is a self-supported ride. There is no SAG.  Food and
  drinks are available at markets along the route, but there
      are sections of up to 40 miles without services, so
      be sure to provision well.  I expect two bottles will be
      enough for most riders in spring weather.  Randonneuring
  rules prohibit personal support vehicles or other
  personal support except at the
  controles, which are marked on the route.

This is an all-conditions ride. There will be some kind of
  weather.  Maybe it will be wonderful,
  and maybe it won't.  Come prepared.  Unless you feel your life or
  health are at risk, ride through.

Expect this to be somewhat tougher than a typical club century
  ride.
      You need not be a fast rider, but it takes some discipline
   to move efficiently through the controles. Remember,
   the clock doesn't stop, even when you do!  The slower you ride,
  the more important is your “controle discipline.”

Most important: Be safe, and enjoy the ride.

{% endblock %}


text:
module ChatWork
  class Multipart < ::Faraday::Multipart::Middleware
    self.mime_type = "multipart/form-data".freeze

    def create_multipart(env, params)
      original_body = super(env, params)

      # replace from Faraday::Parts::EpiloguePart to ChatWork::Multipart::EpiloguePart
      parts = original_body.instance_variable_get(:@parts)
      parts.pop
      parts << EpiloguePart.new(env.request.boundary)

      new_body = ::Faraday::CompositeReadIO.new(*parts)
      env.request_headers[Faraday::Env::ContentLength] = new_body.length.to_s
      new_body
    end
  end

  class EpiloguePart < ::Faraday::Parts::EpiloguePart
    def initialize(boundary) # rubocop:disable Lint/MissingSuper
      # NOTE: ChatWork doesn't accepts ending "\r\n\r\n" of payload...
      # @part = "--#{boundary}--\r\n\r\n"
      @part = "--#{boundary}--\r\n"
      @io = StringIO.new(@part)
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using ModestTree;

namespace Zenject
{
    public class SubContainerCreatorByInstaller : ISubContainerCreator
    {
        readonly Type _installerType;
        readonly DiContainer _container;
        readonly List<TypeValuePair> _extraArgs;

        public SubContainerCreatorByInstaller(
            DiContainer container, Type installerType, List<TypeValuePair> extraArgs)
        {
            _installerType = installerType;
            _container = container;
            _extraArgs = extraArgs;

            Assert.That(installerType.DerivesFrom<InstallerBase>(),
                "Invalid installer type given during bind command.  Expected type '{0}' to derive from 'Installer<>'", installerType);
        }

        public SubContainerCreatorByInstaller(
            DiContainer container, Type installerType)
            : this(container, installerType, new List<TypeValuePair>())
        {
        }

        public DiContainer CreateSubContainer(List<TypeValuePair> args)
        {
            var subContainer = _container.CreateSubContainer();

            var installer = (InstallerBase)subContainer.InstantiateExplicit(
                _installerType, args.Concat(_extraArgs).ToList());
            installer.InstallBindings();

            subContainer.FlushInjectQueue();
            subContainer.ResolveDependencyRoots();

            if (subContainer.IsValidating)
            {
                // The root-level Container has its ValidateValidatables method
                // called explicitly - however, this is not so for sub-containers
                // so call it here instead
                subContainer.ValidateValidatables();
            }

            return subContainer;
        }
    }
}


text:
package com.badlogic.gdx.tests;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.ParticleEmitter;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.Array;

public class ParticleEmitterChangeSpriteTest extends GdxTest {
	private SpriteBatch spriteBatch;
	ParticleEffect effect;
	int emitterIndex = 0;
	Array<ParticleEmitter> emitters;
	TextureAtlas atlas;
	Array<Sprite> sprites;
	int currentSprite = 0;
	float fpsCounter;
	InputProcessor inputProcessor;

	@Override
	public void create () {
		spriteBatch = new SpriteBatch();

		atlas = new TextureAtlas("data/particles.atlas");

		int spriteCount = atlas.getRegions().size;
		sprites = new Array<Sprite>(spriteCount);
		for (TextureRegion region : atlas.getRegions()) {
			sprites.add(new Sprite(region));
		}

		effect = new ParticleEffect();
		effect.load(Gdx.files.internal("data/test.p"), Gdx.files.internal("data"));
		effect.setPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
		// Of course, a ParticleEffect is normally just used, without messing around with its emitters.
		emitters = new Array(effect.getEmitters());
		effect.getEmitters().clear();
		effect.getEmitters().add(emitters.get(0));

		inputProcessor = new InputProcessor() {
			public boolean touchUp (int x, int y, int pointer, int button) {
				return false;
			}

			public boolean touchDragged (int x, int y, int pointer) {
				effect.setPosition(x, Gdx.graphics.getHeight() - y);
				return false;
			}

			public boolean touchDown (int x, int y, int pointer, int newParam) {
				ParticleEmitter emitter = emitters.get(emitterIndex);
				currentSprite = (currentSprite + 1) % sprites.size;
				emitter.setSprite(sprites.get(currentSprite));
				return false;
			}

			public boolean keyUp (int keycode) {
				return false;
			}

			public boolean keyTyped (char character) {
				return false;
			}

			public boolean keyDown (int keycode) {
				return false;
			}

			@Override
			public boolean mouseMoved (int x, int y) {
				return false;
			}

			@Override
			public boolean scrolled (int amount) {
				return false;
			}
		};

		Gdx.input.setInputProcessor(inputProcessor);
	}

	@Override
	public void dispose () {
		spriteBatch.dispose();
		effect.dispose();
		atlas.dispose();
	}

	public void render () {
		spriteBatch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
		float delta = Gdx.graphics.getDeltaTime();
		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
		spriteBatch.begin();
		effect.draw(spriteBatch, delta);
		spriteBatch.end();
		fpsCounter += delta;
		if (fpsCounter > 3) {
			fpsCounter = 0;
			Gdx.app.log("libgdx", "current sprite: " + currentSprite + ", FPS: " + Gdx.graphics.getFramesPerSecond());
		}
	}

	public boolean needsGL20 () {
		return false;
	}
}


text:
---
order: 2
title:
  zh-CN: 拖动示例
  en-US: draggable
---

## zh-CN

将节点拖拽到其他节点内部或前后。

## en-US

Drag treeNode to insert after the other treeNode or insert into the other parent TreeNode.

````jsx
import { Tree } from 'antd';

const TreeNode = Tree.TreeNode;

const x = 3;
const y = 2;
const z = 1;
const gData = [];

const generateData = (_level, _preKey, _tns) => {
  const preKey = _preKey || '0';
  const tns = _tns || gData;

  const children = [];
  for (let i = 0; i < x; i++) {
    const key = `${preKey}-${i}`;
    tns.push({ title: key, key });
    if (i < y) {
      children.push(key);
    }
  }
  if (_level < 0) {
    return tns;
  }
  const level = _level - 1;
  children.forEach((key, index) => {
    tns[index].children = [];
    return generateData(level, key, tns[index].children);
  });
};
generateData(z);

class Demo extends React.Component {
  state = {
    gData,
    expandedKeys: ['0-0', '0-0-0', '0-0-0-0'],
  }

  onDragEnter = (info) => {
    console.log(info);
    // expandedKeys 需要受控时设置
    // this.setState({
    //   expandedKeys: info.expandedKeys,
    // });
  }

  onDrop = (info) => {
    console.log(info);
    const dropKey = info.node.props.eventKey;
    const dragKey = info.dragNode.props.eventKey;
    const dropPos = info.node.props.pos.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
    // const dragNodesKeys = info.dragNodesKeys;
    const loop = (data, key, callback) => {
      data.forEach((item, index, arr) => {
        if (item.key === key) {
          return callback(item, index, arr);
        }
        if (item.children) {
          return loop(item.children, key, callback);
        }
      });
    };
    const data = [...this.state.gData];
    let dragObj;
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });
    if (info.dropToGap) {
      let ar;
      let i;
      loop(data, dropKey, (item, index, arr) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    } else {
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        // where to insert 示例添加到尾部,可以是随意位置
        item.children.push(dragObj);
      });
    }
    this.setState({
      gData: data,
    });
  }

  render() {
    const loop = data => data.map((item) => {
      if (item.children && item.children.length) {
        return <TreeNode key={item.key} title={item.title}>{loop(item.children)}</TreeNode>;
      }
      return <TreeNode key={item.key} title={item.title} />;
    });
    return (
      <Tree
        className="draggable-tree"
        defaultExpandedKeys={this.state.expandedKeys}
        draggable
        onDragEnter={this.onDragEnter}
        onDrop={this.onDrop}
      >
        {loop(this.state.gData)}
      </Tree>
    );
  }
}

ReactDOM.render(<Demo />, mountNode);
````

````css
/* You can add the following CSS to your project to make draggable area bigger */
#components-tree-demo-draggable .draggable-tree .ant-tree-node-content-wrapper {
  width: calc(100% - 18px);
}
````


text:
<?php

namespace Symfony\Component\HttpFoundation;

/**
 * Represents a cookie
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class Cookie
{
    protected $name;
    protected $value;
    protected $domain;
    protected $expire;
    protected $path;
    protected $secure;
    protected $httpOnly;

    public function __construct($name, $value = null, $expire = 0, $path = '/', $domain = null, $secure = false, $httpOnly = true)
    {
        // from PHP source code
        if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
            throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name));
        }

        if (preg_match("/[,; \t\r\n\013\014]/", $value)) {
            throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $name));
        }

        if (empty($name)) {
            throw new \InvalidArgumentException('The cookie name cannot be empty');
        }

        // check if the expiration is valid
        if (!$expire instanceof \DateTime && !is_numeric($expire) && (strtotime($expire) === false || strtotime($expire) === -1)) {
            throw new \InvalidArgumentException('The cookie expiration is not valid');
        }

        $this->name = $name;
        $this->value = $value;
        $this->domain = $domain;
        $this->expire = $expire;
        $this->path = $path;
        $this->secure = (Boolean) $secure;
        $this->httpOnly = (Boolean) $httpOnly;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getValue()
    {
        return $this->value;
    }

    public function getDomain()
    {
        return $this->domain;
    }

    public function getExpire()
    {
        return $this->expire;
    }

    public function getPath()
    {
        return $this->path;
    }

    public function isSecure()
    {
        return $this->secure;
    }

    public function isHttpOnly()
    {
        return $this->httpOnly;
    }

    /**
     * Whether this cookie is about to be cleared
     *
     * @return Boolean
     */
    public function isCleared()
    {
        return $this->expire < time();
    }
}


text:
@interface UISegmentedControl (ARTheme)

- (void)applyStyle:(NSString *)styleName;

@end


text:
#include "dcgf.h"
#include "UIText.h"

IMPLEMENT_PERSISTENT(CUIText, false);

//////////////////////////////////////////////////////////////////////////
CUIText::CUIText(CBGame* inGame):CUIObject(inGame)
{
	m_TextAlign = TAL_LEFT;
	m_VerticalAlign = VAL_CENTER;
	m_Type = UI_STATIC;
	m_CanFocus = false;
}

//////////////////////////////////////////////////////////////////////////
CUIText::~CUIText()
{

}

//////////////////////////////////////////////////////////////////////////
HRESULT CUIText::Display(int OffsetX, int OffsetY)
{
	if(!m_Visible) return S_OK;

	CBFont* font = m_Font;
	if(!font) font = Game->m_SystemFont;

	if(m_Back) m_Back->Display(OffsetX + m_PosX, OffsetY + m_PosY, m_Width, m_Height);
	if(m_Image) m_Image->Draw(OffsetX + m_PosX, OffsetY + m_PosY, NULL);

	if(font && m_Text){
		int text_offset;
		switch(m_VerticalAlign)
		{
			case VAL_TOP:
				text_offset = 0;
				break;
			case VAL_BOTTOM:
				text_offset = m_Height - font->GetTextHeight((BYTE*)m_Text, m_Width);
				break;
			default: text_offset = (m_Height - font->GetTextHeight((BYTE*)m_Text, m_Width)) / 2;
		}
		font->DrawText((BYTE*)m_Text, OffsetX + m_PosX, OffsetY + m_PosY + text_offset, m_Width, m_TextAlign, m_Height);
	}

	//Game->m_Renderer->m_RectList.Add(new CBActiveRect(Game, this, NULL, OffsetX + m_PosX, OffsetY + m_PosY, m_Width, m_Height, 100, 100, false));

	return S_OK;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CUIText::LoadFile(char* Filename)
{
	BYTE* Buffer = Game->m_FileManager->ReadWholeFile(Filename);
	if(Buffer==NULL){
		Game->LOG(0, "CUIText::LoadFile failed for file '%s'", Filename);
		return E_FAIL;
	}

	HRESULT ret;

	m_Filename = new char [strlen(Filename)+1];
	strcpy(m_Filename, Filename);

	if(FAILED(ret = LoadBuffer(Buffer, true))) Game->LOG(0, "Error parsing STATIC file '%s'", Filename);

	delete [] Buffer;

	return ret;
}

TOKEN_DEF_START
	TOKEN_DEF (STATIC)
	TOKEN_DEF (TEMPLATE)
	TOKEN_DEF (DISABLED)
	TOKEN_DEF (VISIBLE)
	TOKEN_DEF (BACK)
	TOKEN_DEF (IMAGE)
	TOKEN_DEF (FONT)
	TOKEN_DEF (TEXT_ALIGN)
	TOKEN_DEF (VERTICAL_ALIGN)
	TOKEN_DEF (TEXT)
	TOKEN_DEF (X)
	TOKEN_DEF (Y)
	TOKEN_DEF (WIDTH)
	TOKEN_DEF (HEIGHT)
	TOKEN_DEF (CURSOR)
	TOKEN_DEF (NAME)
	TOKEN_DEF (SCRIPT)
	TOKEN_DEF (CAPTION)
	TOKEN_DEF (PARENT_NOTIFY)
	TOKEN_DEF (EDITOR_PROPERTY)
TOKEN_DEF_END
//////////////////////////////////////////////////////////////////////////
HRESULT CUIText::LoadBuffer(BYTE* Buffer, bool Complete)
{
	TOKEN_TABLE_START(commands)
		TOKEN_TABLE (STATIC)
		TOKEN_TABLE (TEMPLATE)
		TOKEN_TABLE (DISABLED)
		TOKEN_TABLE (VISIBLE)
		TOKEN_TABLE (BACK)
		TOKEN_TABLE (IMAGE)
		TOKEN_TABLE (FONT)
		TOKEN_TABLE (TEXT_ALIGN)
		TOKEN_TABLE (VERTICAL_ALIGN)
		TOKEN_TABLE (TEXT)
		TOKEN_TABLE (X)
		TOKEN_TABLE (Y)
		TOKEN_TABLE (WIDTH)
		TOKEN_TABLE (HEIGHT)
		TOKEN_TABLE (CURSOR)
		TOKEN_TABLE (NAME)
		TOKEN_TABLE (SCRIPT)
		TOKEN_TABLE (CAPTION)
		TOKEN_TABLE (PARENT_NOTIFY)
		TOKEN_TABLE (EDITOR_PROPERTY)
	TOKEN_TABLE_END

	BYTE* params;
	int cmd=2;
	CBParser parser(Game);

	if(Complete){
		if(parser.GetCommand ((char**)&Buffer, commands, (char**)&params)!=TOKEN_STATIC){
			Game->LOG(0, "'STATIC' keyword expected.");
			return E_FAIL;
		}
		Buffer = params;
	}

	while (cmd > 0 && (cmd = parser.GetCommand ((char**)&Buffer, commands, (char**)&params)) > 0)
	{
		switch (cmd)
		{
			case TOKEN_TEMPLATE:
				if(FAILED(LoadFile((char*)params))) cmd = PARSERR_GENERIC;
			break;

			case TOKEN_NAME:
				SetName((char*)params);
			break;

			case TOKEN_CAPTION:
				SetCaption((char*)params);
			break;

			case TOKEN_BACK:
				SAFE_DELETE(m_Back);
				m_Back = new CUITiledImage(Game);
				if(!m_Back || FAILED(m_Back->LoadFile((char*)params))){
					SAFE_DELETE(m_Back);
					cmd = PARSERR_GENERIC;
				}
			break;

			case TOKEN_IMAGE:
				SAFE_DELETE(m_Image);
				m_Image = new CBSprite(Game);
				if(!m_Image || FAILED(m_Image->LoadFile((char*)params))){
					SAFE_DELETE(m_Image);
					cmd = PARSERR_GENERIC;
				}
			break;

			case TOKEN_FONT:
				if(m_Font) Game->m_FontStorage->RemoveFont(m_Font);
				m_Font = Game->m_FontStorage->AddFont((char*)params);
				if(!m_Font) cmd = PARSERR_GENERIC;
			break;

			case TOKEN_TEXT:
				SetText((char*)params);
				Game->m_StringTable->Expand(&m_Text);
			break;

			case TOKEN_TEXT_ALIGN:
				if(_stricmp((char*)params, "left")==0) m_TextAlign = TAL_LEFT;
				else if(_stricmp((char*)params, "right")==0) m_TextAlign = TAL_RIGHT;
				else m_TextAlign = TAL_CENTER;
			break;

			case TOKEN_VERTICAL_ALIGN:
				if(_stricmp((char*)params, "top")==0) m_VerticalAlign = VAL_TOP;
				else if(_stricmp((char*)params, "bottom")==0) m_VerticalAlign = VAL_BOTTOM;
				else m_VerticalAlign = VAL_CENTER;
			break;

			case TOKEN_X:
				parser.ScanStr((char*)params, "%d", &m_PosX);
			break;

			case TOKEN_Y:
				parser.ScanStr((char*)params, "%d", &m_PosY);
			break;

			case TOKEN_WIDTH:
				parser.ScanStr((char*)params, "%d", &m_Width);
			break;

			case TOKEN_HEIGHT:
				parser.ScanStr((char*)params, "%d", &m_Height);
			break;

			case TOKEN_CURSOR:
				SAFE_DELETE(m_Cursor);
				m_Cursor = new CBSprite(Game);
				if(!m_Cursor || FAILED(m_Cursor->LoadFile((char*)params))){
					SAFE_DELETE(m_Cursor);
					cmd = PARSERR_GENERIC;
				}
			break;

			case TOKEN_SCRIPT:
				AddScript((char*)params);
			break;

			case TOKEN_PARENT_NOTIFY:
				parser.ScanStr((char*)params, "%b", &m_ParentNotify);
			break;

			case TOKEN_DISABLED:
				parser.ScanStr((char*)params, "%b", &m_Disable);
			break;

			case TOKEN_VISIBLE:
				parser.ScanStr((char*)params, "%b", &m_Visible);
			break;

			case TOKEN_EDITOR_PROPERTY:
				ParseEditorProperty(params, false);
			break;
		}
	}
	if (cmd == PARSERR_TOKENNOTFOUND){
		Game->LOG(0, "Syntax error in STATIC definition");
		return E_FAIL;
	}
	if (cmd == PARSERR_GENERIC){
		Game->LOG(0, "Error loading STATIC definition");
		return E_FAIL;
	}

	CorrectSize();

	return S_OK;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CUIText::SaveAsText(CBDynBuffer* Buffer, int Indent)
{
	Buffer->PutTextIndent(Indent, "STATIC\n");
	Buffer->PutTextIndent(Indent, "{\n");

	Buffer->PutTextIndent(Indent+2, "NAME=\"%s\"\n", m_Name);
	Buffer->PutTextIndent(Indent+2, "CAPTION=\"%s\"\n", GetCaption());

	Buffer->PutTextIndent(Indent+2, "\n");

	if(m_Back && m_Back->m_Filename)
		Buffer->PutTextIndent(Indent+2, "BACK=\"%s\"\n", m_Back->m_Filename);

	if(m_Image && m_Image->m_Filename)
		Buffer->PutTextIndent(Indent+2, "IMAGE=\"%s\"\n", m_Image->m_Filename);

	if(m_Font && m_Font->m_Filename)
		Buffer->PutTextIndent(Indent+2, "FONT=\"%s\"\n", m_Font->m_Filename);

	if(m_Cursor && m_Cursor->m_Filename)
		Buffer->PutTextIndent(Indent+2, "CURSOR=\"%s\"\n", m_Cursor->m_Filename);

	if(m_Text)
		Buffer->PutTextIndent(Indent+2, "TEXT=\"%s\"\n", m_Text);

	switch(m_TextAlign)
	{
		case TAL_LEFT:
			Buffer->PutTextIndent(Indent+2, "TEXT_ALIGN=\"%s\"\n", "left");
			break;
		case TAL_RIGHT:
			Buffer->PutTextIndent(Indent+2, "TEXT_ALIGN=\"%s\"\n", "right");
			break;
		case TAL_CENTER:
			Buffer->PutTextIndent(Indent+2, "TEXT_ALIGN=\"%s\"\n", "center");
			break;
	}

	switch(m_VerticalAlign)
	{
		case VAL_TOP:
			Buffer->PutTextIndent(Indent+2, "VERTICAL_ALIGN=\"%s\"\n", "top");
			break;
		case VAL_BOTTOM:
			Buffer->PutTextIndent(Indent+2, "VERTICAL_ALIGN=\"%s\"\n", "bottom");
			break;
		case VAL_CENTER:
			Buffer->PutTextIndent(Indent+2, "VERTICAL_ALIGN=\"%s\"\n", "center");
			break;
	}

	Buffer->PutTextIndent(Indent+2, "\n");

	Buffer->PutTextIndent(Indent+2, "X=%d\n", m_PosX);
	Buffer->PutTextIndent(Indent+2, "Y=%d\n", m_PosY);
	Buffer->PutTextIndent(Indent+2, "WIDTH=%d\n", m_Width);
	Buffer->PutTextIndent(Indent+2, "HEIGHT=%d\n", m_Height);

	Buffer->PutTextIndent(Indent+2, "DISABLED=%s\n", m_Disable?"TRUE":"FALSE");
	Buffer->PutTextIndent(Indent+2, "VISIBLE=%s\n", m_Visible?"TRUE":"FALSE");
	Buffer->PutTextIndent(Indent+2, "PARENT_NOTIFY=%s\n", m_ParentNotify?"TRUE":"FALSE");

	Buffer->PutTextIndent(Indent+2, "\n");

	// scripts
	for(int i=0; i<m_Scripts.GetSize(); i++)
	{
		Buffer->PutTextIndent(Indent+2, "SCRIPT=\"%s\"\n", m_Scripts[i]->m_Filename);
	}

	Buffer->PutTextIndent(Indent+2, "\n");

	// editor properties
	CBBase::SaveAsText(Buffer, Indent+2);

	Buffer->PutTextIndent(Indent, "}\n");
	return S_OK;
}

//////////////////////////////////////////////////////////////////////////
// high level scripting interface
//////////////////////////////////////////////////////////////////////////
HRESULT CUIText::ScCallMethod(CScScript* Script, CScStack *Stack, CScStack *ThisStack, char *Name)
{
	//////////////////////////////////////////////////////////////////////////
	// SizeToFit
	//////////////////////////////////////////////////////////////////////////
	if(strcmp(Name, "SizeToFit")==0){
		Stack->CorrectParams(0);
		SizeToFit();
		Stack->PushNULL();
		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// HeightToFit
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "HeightToFit")==0){
		Stack->CorrectParams(0);
		if(m_Font && m_Text) m_Height = m_Font->GetTextHeight((BYTE*)m_Text, m_Width);
		Stack->PushNULL();
		return S_OK;
	}

	else return CUIObject::ScCallMethod(Script, Stack, ThisStack, Name);
}

//////////////////////////////////////////////////////////////////////////
CScValue* CUIText::ScGetProperty(char *Name)
{
	m_ScValue->SetNULL();

	//////////////////////////////////////////////////////////////////////////
	// Type
	//////////////////////////////////////////////////////////////////////////
	if(strcmp(Name, "Type")==0){
		m_ScValue->SetString("static");
		return m_ScValue;
	}

	//////////////////////////////////////////////////////////////////////////
	// TextAlign
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "TextAlign")==0){
		m_ScValue->SetInt(m_TextAlign);
		return m_ScValue;
	}

	//////////////////////////////////////////////////////////////////////////
	// VerticalAlign
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "VerticalAlign")==0){
		m_ScValue->SetInt(m_VerticalAlign);
		return m_ScValue;
	}

	else return CUIObject::ScGetProperty(Name);
}

//////////////////////////////////////////////////////////////////////////
HRESULT CUIText::ScSetProperty(char *Name, CScValue *Value)
{
	//////////////////////////////////////////////////////////////////////////
	// TextAlign
	//////////////////////////////////////////////////////////////////////////
	if(strcmp(Name, "TextAlign")==0){
		int i = Value->GetInt();
		if(i<0 || i>=NUM_TEXT_ALIGN) i = 0;
		m_TextAlign = (TTextAlign)i;
		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// VerticalAlign
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "VerticalAlign")==0){
		int i = Value->GetInt();
		if(i<0 || i>=NUM_VERTICAL_ALIGN) i = 0;
		m_VerticalAlign = (TVerticalAlign)i;
		return S_OK;
	}

	else return CUIObject::ScSetProperty(Name, Value);
}

//////////////////////////////////////////////////////////////////////////
char* CUIText::ScToString()
{
	return "[static]";
}

//////////////////////////////////////////////////////////////////////////
HRESULT CUIText::Persist(CBPersistMgr* PersistMgr){

	CUIObject::Persist(PersistMgr);
	PersistMgr->Transfer(TMEMBER_INT(m_TextAlign));

	// 1.1.36
	if(PersistMgr->CheckVersion(1, 1, 36)){
		PersistMgr->Transfer(TMEMBER_INT(m_VerticalAlign));
	}
	else{
		m_VerticalAlign = VAL_CENTER;
	}

	return S_OK;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CUIText::SizeToFit()
{
	if(m_Font && m_Text){
		m_Width = m_Font->GetTextWidth((BYTE*)m_Text);
		m_Height = m_Font->GetTextHeight((BYTE*)m_Text, m_Width);
	}
	return S_OK;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sporormia leguminosa Fairm.

### Remarks
null


text:
enyo.kind({
	name: "enyo.webos.sample.LunaService",
	classes: "onyx enyo-fit",
	kind:"enyo.Scroller",
	components: [
		{classes: "webos-sample", components:[
			{name:"networkStatus", kind:"enyo.LunaService", service:"luna://com.palm.connectionmanager", method: "getstatus", onResponse:"serviceResponse", onError:"serviceError"},
			{kind:"enyo.Signals", ondeviceready:"deviceready"},
			{classes: "webos-sample-divider", content: "Device API"},
			{kind: "onyx.Groupbox", classes:"webos-sample-result-box", components: [
				{kind: "onyx.GroupboxHeader", content: "enyo.LunaService"},
				{name:"result", classes:"webos-sample-result", content:"LunaService API not supported on this platform.", allowHtml:true}
			]}
		]}
	],
	deviceready: function(inSender, inEvent) {
		if(enyo.platform.webos) {
			this.request = this.$.networkStatus.send({}); //no parameters needed for this service call
			//in this example, can cancel the request from this.request.cancel()
		}
	},
	serviceResponse: function(inSender, inEvent) {
		//Note: inEvent.originator will point to the request object (the same one set to this.request above)
		this.$.result.setContent("isInternetConnectionAvailable: " + inEvent.isInternetConnectionAvailable + "

"
				+ "Wired: " + enyo.json.stringify(inEvent.wired, null, "\t") + "

"
				+ "WiFi: " + enyo.json.stringify(inEvent.wifi, null, "\t") + "

"
				+ "WAN: " + enyo.json.stringify(inEvent.wan, null, "\t"));
	},
	serviceError: function(inSender, inEvent) {
		this.$.result.setContent("Error: " + inEvent.errorText);
	}
});


text:
export default class Module {
    /**
     * Register method, called when application started.
     */
    async register() {}

    /**
     * Boot method, called right before the request route.
     */
    async boot() {}

    /**
     * Registers any stores.
     *
     * @return {Object}
     */
    async registerStore () {
        return {};
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>岛主</title>

  <link rel="stylesheet" href="/assets/css/main.css" type="text/css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link href='//spoqa.github.io/spoqa-han-sans/css/SpoqaHanSans-kr.css' rel='stylesheet' type='text/css'>

  <link rel="alternate" type="application/rss+xml" title="RSS Feed for 岛主" href="/feed.xml" />

<title>岛主</title>
<meta property="og:title" content="岛主" />
<link rel="canonical" href="http://localhost:4000/404/" />
<meta property="og:url" content="http://localhost:4000/404/" />
<meta property="og:site_name" content="岛主" />

    岛主

  Sorry, but the page you were trying to view does not exist.