text:
/*!
    \file  usbd_std.c
    \brief USB device stand routines
    \note  about USB standard, please refer to the USB2.0 protocol

    \version 2014-12-26, V1.0.0, firmware for GD32F10x
    \version 2017-06-20, V2.0.0, firmware for GD32F10x
    \version 2018-07-31, V2.1.0, firmware for GD32F10x
*/

/*
    Copyright (c) 2018, GigaDevice Semiconductor Inc.

    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors
       may be used to endorse or promote products derived from this software without
       specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/

#include "usbd_std.h"

uint8_t g_device_address = 0U;

/* USB enumeration handle functions */
static void usbd_getdescriptor     (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_setaddress        (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_setconfiguration  (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_getconfiguration  (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_getstatus         (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_setfeature        (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_clearfeature      (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_reserved          (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_setdescriptor     (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_getinterface      (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_setinterface      (usbd_core_handle_struct *pudev, usb_device_req_struct *req);
static void usbd_synchframe        (usbd_core_handle_struct *pudev, usb_device_req_struct *req);

static uint8_t* usbd_device_descriptor_get        (usbd_core_handle_struct *pudev,
                                                   uint8_t index,
                                                   uint16_t *pLen);

static uint8_t* usbd_configuration_descriptor_get (usbd_core_handle_struct *pudev,
                                                   uint8_t index,
                                                   uint16_t *pLen);

static uint8_t* usbd_string_descriptor_get        (usbd_core_handle_struct *pudev,
                                                   uint8_t index,
                                                   uint16_t *pLen);

#ifdef LPM_ENABLED
static uint8_t* usbd_bos_descriptor_get           (usbd_core_handle_struct *pudev, uint16_t *pLen);
#endif /* LPM_ENABLED */

/* standard device request handler */
static void (*standard_device_request[])(usbd_core_handle_struct *pudev, usb_device_req_struct *req) =
{
    usbd_getstatus,
    usbd_clearfeature,
    usbd_reserved,
    usbd_setfeature,
    usbd_reserved,
    usbd_setaddress,
    usbd_getdescriptor,
    usbd_setdescriptor,
    usbd_getconfiguration,
    usbd_setconfiguration,
    usbd_getinterface,
    usbd_setinterface,
    usbd_synchframe,
};

/* get standard descriptor handler */
static uint8_t* (*standard_descriptor_get[])(usbd_core_handle_struct *pudev, uint8_t index, uint16_t *pLen) =
{
    usbd_device_descriptor_get,
    usbd_configuration_descriptor_get,
    usbd_string_descriptor_get
};

/*!
    \brief      USB setup stage processing
    \param[in]  pudev: pointer to USB device instance
    \param[out] none
    \retval     USB device operation status
*/
uint8_t  usbd_setup_transaction (usbd_core_handle_struct *pudev)
{
    usb_device_req_struct req;

    usbd_setup_request_parse (pudev, &req);

    switch (req.bmRequestType & USB_REQ_MASK) {
    /* standard device request */
    case USB_STANDARD_REQ:
        usbd_standard_request(pudev, &req);
        break;
    /* device class request */
    case USB_CLASS_REQ:
        usbd_device_class_request(pudev, &req);
        break;
    /* vendor defined request */
    case USB_VENDOR_REQ:
        usbd_vendor_request(pudev, &req);
        break;
    default:
        usbd_ep_stall(pudev, 0x00U);
        break;
    }
    return USBD_OK;
}

/*!
    \brief      data out stage processing
    \param[in]  pudev: pointer to USB device instance
    \param[in]  ep_num: endpoint identifier(0..7)
    \param[out] none
    \retval     USB device operation status
*/
uint8_t  usbd_out_transaction (usbd_core_handle_struct *pudev, uint8_t ep_num)
{
    usb_ep_struct *ep = &pudev->out_ep[ep_num];

    if (0U == ep_num) {
        if (0U != pudev->ctl_count) {
            if (ep->trs_len > ep->maxpacket) {
                /* one data packet has been received, update trs_len */
                ep->trs_len -= ep->maxpacket;

                /* continue to receive remain data */
                usbd_ep_rx(pudev, EP0_OUT, ep->trs_buf, (uint16_t)ep->trs_len);
            } else {
                if (USBD_CONFIGURED == pudev->status) {
                    /* device class handle */
                    pudev->class_data_handler(pudev, USBD_RX, EP0);
                }

                /* enter the control transaction status stage */
                USBD_CONTRL_STATUS_TX();

                pudev->ctl_count = 0U;
            }
        } else {
            /* clear endpoint status_out status */
            USBD_STATUS_OUT_CLEAR(EP0);
        }
    } else {
        if (USBD_CONFIGURED == pudev->status) {
            pudev->class_data_handler(pudev, USBD_RX, ep_num);
        }
    }
    return USBD_OK;
}

/*!
    \brief      data in stage processing
    \param[in]  pudev: pointer to USB device instance
    \param[in]  ep_num: endpoint identifier(0..7)
    \param[out] none
    \retval     USB device operation status
*/
uint8_t  usbd_in_transaction (usbd_core_handle_struct *pudev, uint8_t ep_num)
{
    usb_ep_struct *ep = &pudev->in_ep[ep_num];

    if (0U == ep_num) {
        if (0U != pudev->ctl_count) {
            if (ep->trs_len > ep->maxpacket) {
                /* one data packet has been transmited, update trs_len */
                ep->trs_len -= ep->maxpacket;

                /* continue to transmit remain data */
                usbd_ep_tx (pudev, EP0_IN, ep->trs_buf, (uint16_t)ep->trs_len);

                usbd_ep_rx (pudev, 0U, NULL, 0U);
            } else {
#ifndef USB_DFU
                /* transmit length is maxpacket multiple, so send zero length packet */
                if ((0U == (ep->trs_len % ep->maxpacket)) && (ep->trs_len < pudev->ctl_count)) {
                    usbd_ep_tx (pudev, EP0_IN, NULL, 0U);

                    pudev->ctl_count = 0U;

                    usbd_ep_rx (pudev, 0U, NULL, 0U);
                } else
#endif /* USB_DFU */
                {
                    ep->trs_len = 0U;

                    if (USBD_CONFIGURED == pudev->status) {
                        pudev->class_data_handler(pudev, USBD_TX, EP0);
                    }

                    USBD_CONTRL_STATUS_RX();

                    pudev->ctl_count = 0U;
                }
            }
        } else {
            if (0U != g_device_address) {
                USBD_REG_SET(USBD_DADDR, DADDR_USBEN | g_device_address);
                g_device_address = 0U;
            }
        }
    } else {
        ep->trs_len -= ep->trs_count;

        if (0U == ep->trs_len) {
            if (USBD_CONFIGURED == pudev->status) {
                pudev->class_data_handler(pudev, USBD_TX, ep_num);
            }
        } else {
            usbd_ep_tx(pudev, ep_num, ep->trs_buf, (uint16_t)ep->trs_len);
        }
    }

    return USBD_OK;
}

/*!
    \brief      handle USB standard device request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     USB device operation status
*/
uint8_t  usbd_standard_request (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    /* call device request handle function */
    (*standard_device_request[req->bRequest])(pudev, req);

    return USBD_OK;
}

/*!
    \brief      handle USB device class request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device class request
    \param[out] none
    \retval     USB device operation status
*/
uint8_t  usbd_device_class_request (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    usbd_status_enum ret;

    switch (pudev->status) {
    case USBD_CONFIGURED:
        if (LOWBYTE(req->wIndex) <= USBD_ITF_MAX_NUM) {
            /* call device class handle function */
            ret = (usbd_status_enum)(pudev->class_req_handler(pudev, req));

            if ((0U == req->wLength) && (USBD_OK == ret)) {
                /* no data stage */
                USBD_CONTRL_STATUS_TX();
            }
        } else {
            usbd_enum_error(pudev, req);
        }
        break;
    default:
        usbd_enum_error(pudev, req);
        break;
    }

    return USBD_OK;
}

/*!
    \brief      handle USB vendor request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB vendor request
    \param[out] none
    \retval     USB device operation status
*/
uint8_t  usbd_vendor_request (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    /* added by user */

    return USBD_OK;
}

/*!
    \brief      no operation, just for reserved
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_reserved (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    /* no operation */
}

#ifdef LPM_ENABLED
/*!
    \brief      get BOS descriptor
    \param[in]  pudev: pointer to USB device instance
    \param[in]  pLen: data length pointer
    \param[out] none
    \retval     descriptor buffer pointer
*/
static uint8_t* usbd_bos_descriptor_get (usbd_core_handle_struct *pudev, uint16_t *pLen)
{
    *pLen = pudev->bos_desc[2] | ((uint16_t)pudev->bos_desc[3] << 8);

    return pudev->bos_desc;
}

#endif /* LPM_ENABLED */

/*!
    \brief      get the device descriptor
    \param[in]  pudev: pointer to USB device instance
    \param[in]  index: no use
    \param[out] pLen: data length pointer
    \retval     descriptor buffer pointer
*/
static uint8_t* usbd_device_descriptor_get (usbd_core_handle_struct *pudev, uint8_t index, uint16_t *pLen)
{
    *pLen = pudev->dev_desc[0];

    return pudev->dev_desc;
}

/*!
    \brief      get the configuration descriptor
    \brief[in]  pudev: pointer to USB device instance
    \brief[in]  index: no use
    \param[out] pLen: data length pointer
    \retval     descriptor buffer pointer
*/
static uint8_t* usbd_configuration_descriptor_get (usbd_core_handle_struct *pudev, uint8_t index, uint16_t *pLen)
{
    *pLen = pudev->config_desc[2];

    return pudev->config_desc;
}

/*!
    \brief      get string descriptor
    \param[in]  pudev: pointer to USB device instance
    \param[in]  index: string descriptor index
    \param[out] pLen: pointer to string length
    \retval     none
*/
static uint8_t* usbd_string_descriptor_get (usbd_core_handle_struct *pudev, uint8_t index, uint16_t *pLen)
{
    uint8_t *desc = pudev->strings[index];

    *pLen = desc[0];

    return desc;
}

/*!
    \brief      handle Get_Status request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_getstatus (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    uint8_t  ep_addr;
    uint16_t config_status = 0x0000U;
    uint16_t endp_status = 0x0000U;

    switch(req->bmRequestType & USB_REQ_RECIPIENT_MASK) {
    case USB_REQTYPE_DEVICE:
        switch (pudev->status) {
        case USBD_ADDRESSED:
        case USBD_CONFIGURED:

#ifdef USBD_SELF_POWERED
    config_status = USB_STATUS_SELF_POWERED;
#endif /* USBD_SELF_POWERED */

            if (pudev->remote_wakeup) {
                config_status |= USB_STATUS_REMOTE_WAKEUP;
            }

            usbd_ep_tx(pudev, EP0_IN, (uint8_t *)&config_status, 2U);
            break;
        default:
            break;
        }
        break;
    case USB_REQTYPE_INTERFACE:
        switch (pudev->status) {
        case USBD_ADDRESSED:
            usbd_enum_error(pudev, req);
            break;
        case USBD_CONFIGURED:
            if (LOWBYTE(req->wIndex) <= USBD_ITF_MAX_NUM) {
                usbd_ep_tx(pudev, EP0_IN, (uint8_t *)&config_status, 2U);
            } else {
                usbd_enum_error(pudev, req);
            }
            break;
        default:
            break;
        }
        break;
    case USB_REQTYPE_ENDPOINT:
        /* get enndpoint address */
        ep_addr = LOWBYTE(req->wIndex);

        switch (pudev->status) {
        case USBD_ADDRESSED:
            if (IS_NOT_EP0(ep_addr)) {
                usbd_enum_error(pudev, req);
            }
            break;
        case USBD_CONFIGURED:
            if ((ep_addr & 0x80U) == 0x80U) {
                if(pudev->in_ep[ep_addr & 0x7FU].stall) {
                    endp_status = 0x0001U;
                }
            } else {
                if (pudev->out_ep[ep_addr].stall) {
                    endp_status = 0x0001U;
                }
            }
            usbd_ep_tx(pudev, EP0_IN, (uint8_t *)&endp_status, 2U);
            break;

        default:
            break;
        }
        break;
    default:
        usbd_enum_error(pudev, req);
        break;
    }
}

/*!
    \brief      handle USB Clear_Feature request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_clearfeature (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    uint8_t ep_addr = 0U;

    switch (req->bmRequestType & USB_REQ_RECIPIENT_MASK) {
    case USB_REQTYPE_DEVICE:
        switch (pudev->status) {
        case USBD_ADDRESSED:
        case USBD_CONFIGURED:
            /* clear device remote wakeup feature */
            if (USB_FEATURE_REMOTE_WAKEUP == req->wValue) {
                pudev->remote_wakeup = 0U;
                pudev->class_req_handler(pudev, req);
                USBD_CONTRL_STATUS_TX();
            } else if (USB_FEATURE_TEST_MODE == req->wValue) {
                /* can not clear test_mode feature */
                usbd_enum_error(pudev, req);
            } else {
                /* no operation */
            }
            break;
        default:
            break;
        }
        break;
    case USB_REQTYPE_INTERFACE:
        switch (pudev->status) {
        case USBD_ADDRESSED:
            usbd_enum_error (pudev, req);
            break;
        case USBD_CONFIGURED:
            if (LOWBYTE(req->wIndex) <= USBD_ITF_MAX_NUM) {
                /* no operation */
            } else {
                usbd_enum_error(pudev, req);
            }
            break;
        default:
            break;
        }
        break;
    case USB_REQTYPE_ENDPOINT:
        /* get endpoint address */
        ep_addr = LOWBYTE(req->wIndex);

        switch (pudev->status) {
        case USBD_ADDRESSED:
            if (IS_NOT_EP0(ep_addr)) {
                usbd_enum_error(pudev, req);
            }
            break;
        case USBD_CONFIGURED:
            /* clear endpoint halt feature */
            if (USB_FEATURE_ENDP_HALT == req->wValue) {
                if (IS_NOT_EP0(ep_addr)) {
                    usbd_ep_clear_stall(pudev, ep_addr);
                }
            }

            pudev->class_req_handler(pudev, req);

            USBD_CONTRL_STATUS_TX();
            break;
        default:
            break;
        }
        break;
    default:
        usbd_enum_error(pudev, req);
        break;
    }
}

/*!
    \brief      handle USB Set_Feature request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_setfeature (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    uint8_t ep_addr = 0U;

    switch (req->bmRequestType & USB_REQ_RECIPIENT_MASK) {
    case USB_REQTYPE_DEVICE:
        switch (pudev->status) {
        case USBD_ADDRESSED:
        case USBD_CONFIGURED:
            /* set device remote wakeup feature */
            if (USB_FEATURE_REMOTE_WAKEUP == req->wValue) {
                pudev->remote_wakeup = 1U;

                USBD_CONTRL_STATUS_TX();
            }
            break;
        default:
            break;
        }
        break;
    case USB_REQTYPE_INTERFACE:
        switch (pudev->status) {
        case USBD_ADDRESSED:
            usbd_enum_error(pudev, req);
            break;
        case USBD_CONFIGURED:
            if (LOWBYTE(req->wIndex) <= USBD_ITF_MAX_NUM) {
                /* no operation */
            } else {
                usbd_enum_error(pudev, req);
            }
            break;
        default:
            break;
        }
        break;
    case USB_REQTYPE_ENDPOINT:
        /* get endpoint address */
        ep_addr = LOWBYTE(req->wIndex);

        switch (pudev->status) {
        case USBD_ADDRESSED:
            if (IS_NOT_EP0(ep_addr)) {
                usbd_enum_error(pudev, req);
            }
            break;
        case USBD_CONFIGURED:
            /* set endpoint halt feature */
            if (USB_FEATURE_ENDP_HALT == req->wValue) {
                if (IS_NOT_EP0(ep_addr)) {
                    usbd_ep_stall(pudev, ep_addr);
                }
            }
            USBD_CONTRL_STATUS_TX();
            break;
        default:
            break;
        }
        break;
    default:
        usbd_enum_error(pudev, req);
        break;
    }
}

/*!
    \brief      handle USB Set_Address request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_setaddress (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    if ((0U == req->wIndex) && (0U == req->wLength)) {
        g_device_address = (uint8_t)(req->wValue) & 0x7FU;

        if (USBD_CONFIGURED == pudev->status) {
            usbd_enum_error(pudev, req);
        } else {
            USBD_CONTRL_STATUS_TX();

            if (0U != g_device_address) {
                pudev->status  = USBD_ADDRESSED;
            } else {
                pudev->status  = USBD_DEFAULT;
            }
        }
    } else {
        usbd_enum_error(pudev, req);
    }
}

/*!
    \brief      handle USB Get_Descriptor request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_getdescriptor (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    if (USB_REQTYPE_DEVICE == (req->bmRequestType & USB_REQ_RECIPIENT_MASK)) {
        uint8_t *pbuf = NULL;
        uint8_t  desc_type = (uint8_t)(req->wValue >> 8);
        uint8_t  desc_index = (uint8_t)(req->wValue) & 0xFFU;
        uint16_t len = 0U;

        if ((desc_type <= 0x03U) && (desc_index <= 0x05U)) {
            /* call corresponding descriptor get function */
            pbuf = standard_descriptor_get[desc_type - 1U](pudev, desc_index, &len);
        }
#ifdef LPM_ENABLED
        else if (USB_DESCTYPE_BOS == desc_type) {
            pbuf = usbd_bos_descriptor_get(pudev, &len);
        }
#endif /* LPM_ENABLED */
        else {
            usbd_enum_error(pudev, req);
        }

        if ((0U != len) && (0U != req->wLength)) {
            len = MIN(len, req->wLength);

            usbd_ep_tx (pudev, EP0_IN, pbuf, len);
        }
    } else if (USB_REQTYPE_INTERFACE == (req->bmRequestType & USB_REQ_RECIPIENT_MASK)) {
        if (NULL != pudev->class_req_handler) {
            /* get device class special descriptor */
            pudev->class_req_handler(pudev, req);
        }
    } else {

    }
}

/*!
    \brief      handle USB Set_Descriptor request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_setdescriptor (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    /* no handle */
}

/*!
    \brief      handle USB Get_Configuration request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_getconfiguration (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    uint32_t usbd_default_config = 0U;

    if (req->wLength != 1U) {
        usbd_enum_error(pudev, req);
    } else {
        switch (pudev->status) {
        case USBD_ADDRESSED:
            usbd_ep_tx (pudev, EP0_IN, (uint8_t *)&usbd_default_config, 1U);
            break;
        case USBD_CONFIGURED:
            usbd_ep_tx (pudev, EP0_IN, &pudev->config_num, 1U);
            break;
        default:
            usbd_enum_error(pudev, req);
            break;
        }
    }
}

/*!
    \brief      handle USB Set_Configuration request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_setconfiguration (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    static uint8_t  cfgidx;

    cfgidx = (uint8_t)(req->wValue);

    if (cfgidx > USBD_CFG_MAX_NUM) {
        usbd_enum_error(pudev, req);
    } else {
        switch (pudev->status) {
        case USBD_ADDRESSED:
            if (cfgidx){
                pudev->config_num = cfgidx;
                pudev->status = USBD_CONFIGURED;
                pudev->class_init(pudev, cfgidx);
                USBD_CONTRL_STATUS_TX();
            } else {
                USBD_CONTRL_STATUS_TX();
            }
            break;
        case USBD_CONFIGURED:
            if (0U == cfgidx) {
                pudev->status = USBD_ADDRESSED;
                pudev->config_num = cfgidx;
                pudev->class_deinit(pudev, cfgidx);
                USBD_CONTRL_STATUS_TX();
            } else if (cfgidx != pudev->config_num) {
                /* clear old configuration */
                pudev->class_deinit(pudev, pudev->config_num);

                /* set new configuration */
                pudev->config_num = cfgidx;
                pudev->class_init(pudev, cfgidx);
                USBD_CONTRL_STATUS_TX();
            } else {
                USBD_CONTRL_STATUS_TX();
            }
            break;
        default:
            break;
        }
    }
}

/*!
    \brief      handle USB Get_Interface request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_getinterface (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    switch (pudev->status) {
    case USBD_ADDRESSED:
        usbd_enum_error(pudev, req);
        break;
    case USBD_CONFIGURED:
        if (LOWBYTE(req->wIndex) <= USBD_ITF_MAX_NUM) {
            if (NULL != pudev->class_req_handler) {
                pudev->class_req_handler(pudev, req);
            }
        } else {
            usbd_enum_error(pudev, req);
        }
        break;
    default:
        break;
    }
}

/*!
    \brief      handle USB Set_Interface request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_setinterface (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    switch (pudev->status) {
    case USBD_ADDRESSED:
        usbd_enum_error(pudev, req);
        break;
    case USBD_CONFIGURED:
        if (LOWBYTE(req->wIndex) <= USBD_ITF_MAX_NUM) {
            if (NULL != pudev->class_req_handler) {
                pudev->class_req_handler(pudev, req);
            }

            USBD_CONTRL_STATUS_TX();
        } else {
            usbd_enum_error(pudev, req);
        }
        break;
    default:
        break;
    }
}

/*!
    \brief      handle USB SynchFrame request
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
static void  usbd_synchframe (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    /* no handle */
}

/*!
    \brief      decode setup data packet
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
void  usbd_setup_request_parse (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    uint8_t *setup_data = pudev->setup_packet;

    req->bmRequestType = *setup_data;
    req->bRequest = *(uint8_t *)(setup_data + 1U);
    req->wValue = SWAPBYTE (setup_data + 2U);
    req->wIndex = SWAPBYTE (setup_data + 4U);
    req->wLength = SWAPBYTE (setup_data + 6U);

    pudev->ctl_count = req->wLength;
}

/*!
    \brief      handle USB enumeration error event
    \param[in]  pudev: pointer to USB device instance
    \param[in]  req: pointer to USB device request
    \param[out] none
    \retval     none
*/
void  usbd_enum_error (usbd_core_handle_struct *pudev, usb_device_req_struct *req)
{
    usbd_ep_stall(pudev, EP0);
}


text:
namespace NHibernateCocoon
{
	/// <summary>
	/// A sort order, based on a property and its sort direction.
	/// </summary>
	public class NHibernateRepositorySort
	{
		/// <summary>
		/// The property which to sort on.
		/// </summary>
		public string Property { get; set; }

		/// <summary>
		/// The sort direction for the property.
		/// </summary>
		public NHibernateRepositorySortDirection SortDirection { get; set; }

		/// <summary>
		/// Creates a new NHibernateRepositorySort class.
		/// </summary>
		/// <param name="property">The property which to sort on.</param>
		/// <param name="sortDirection">The sort direction.</param>
		public NHibernateRepositorySort(string property, NHibernateRepositorySortDirection sortDirection)
        {
            Property = property;
			SortDirection = sortDirection;
        }
	}
}

redpajama_set_name: RedPajamaGithub


text:
package shark.api

import spark.api.java.function.{Function => JFunction}
import spark.api.java.JavaRDDLike
import spark.RDD
import spark.storage.StorageLevel

import java.util.{List => JavaList}

import org.apache.hadoop.hive.metastore.api.FieldSchema

class JavaTableRDD(val rdd: RDD[Row], val schema: JavaList[FieldSchema]) extends JavaRDDLike[Row, JavaTableRDD] {

  override def wrapRDD(rdd: RDD[Row]): JavaTableRDD = new JavaTableRDD(rdd, schema)

  // Common RDD functions
  override val classManifest: ClassManifest[Row] = implicitly[ClassManifest[Row]]

  // This shouldn't be necessary, but we seem to need this to get first() to return Row
  // instead of Object; possibly a compiler bug?
  override def first(): Row = rdd.first()

  /** Persist this RDD with the default storage level (`MEMORY_ONLY`). */
  def cache(): JavaTableRDD = wrapRDD(rdd.cache())

  /**
   * Set this RDD's storage level to persist its values across operations after the first time
   * it is computed. Can only be called once on each RDD.
   */
  def persist(newLevel: StorageLevel): JavaTableRDD = wrapRDD(rdd.persist(newLevel))

  // Transformations (return a new RDD)

  // Note: we didn't implement distinct() because equals() and hashCode() are not defined for Row.

  /**
   * Return a new RDD containing only the elements that satisfy a predicate.
   */
  def filter(f: JFunction[Row, java.lang.Boolean]): JavaTableRDD =
    wrapRDD(rdd.filter((x => f(x).booleanValue())))

  /**
   * Return a sampled subset of this RDD.
   */
  def sample(withReplacement: Boolean, fraction: Double, seed: Int): JavaTableRDD =
    wrapRDD(rdd.sample(withReplacement, fraction, seed))

  /**
   * Return the union of this RDD and another one. Any identical elements will appear multiple
   * times (use `.distinct()` to eliminate them).
   *
   * Note: the `schema` of a union is this RDD's schema.
   */
  def union(other: JavaTableRDD): JavaTableRDD = wrapRDD(rdd.union(other.rdd))

}


text:
//>>label: Selectable
//>>group: Interactions
//>>description: Allows groups of elements to be selected with the mouse.
//>>docs: http://api.jqueryui.com/selectable/
//>>demos: http://jqueryui.com/selectable/
//>>css.structure: ../themes/base/selectable.css

(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([
			"jquery",
			"./mouse",
			"../version",
			"../widget"
		], factory );
	} else {

	    // Browser globals
	    Elliptical(function () {
	        factory(jQuery);
	    });

	}
}(function( $ ) {

return $.widget("ui.selectable", $.ui.mouse, {
	version: "@VERSION",
	options: {
		appendTo: "body",
		autoRefresh: true,
		distance: 0,
		filter: "*",
		tolerance: "touch",

		// Callbacks
		selected: null,
		selecting: null,
		start: null,
		stop: null,
		unselected: null,
		unselecting: null
	},
	_create: function() {
		var that = this;

		this._addClass( "ui-selectable" );

		this.dragged = false;

		// Cache selectee children based on filter
		this.refresh = function() {
			that.selectees = $(that.options.filter, that.element[0]);
			that._addClass( that.selectees, "ui-selectee" );
			that.selectees.each(function() {
				var $this = $(this),
					pos = $this.offset();
				$.data(this, "selectable-item", {
					element: this,
					$element: $this,
					left: pos.left,
					top: pos.top,
					right: pos.left + $this.outerWidth(),
					bottom: pos.top + $this.outerHeight(),
					startselected: false,
					selected: $this.hasClass("ui-selected"),
					selecting: $this.hasClass("ui-selecting"),
					unselecting: $this.hasClass("ui-unselecting")
				});
			});
		};
		this.refresh();

		this._mouseInit();

		this.helper = $("<div>");
		this._addClass( this.helper, "ui-selectable-helper" );
	},

	_destroy: function() {
		this.selectees.removeData("selectable-item");
		this._mouseDestroy();
	},

	_mouseStart: function(event) {
		var that = this,
			options = this.options;

		this.opos = [ event.pageX, event.pageY ];

		if (this.options.disabled) {
			return;
		}

		this.selectees = $(options.filter, this.element[0]);

		this._trigger("start", event);

		$(options.appendTo).append(this.helper);
		// position helper (lasso)
		this.helper.css({
			"left": event.pageX,
			"top": event.pageY,
			"width": 0,
			"height": 0
		});

		if (options.autoRefresh) {
			this.refresh();
		}

		this.selectees.filter(".ui-selected").each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.startselected = true;
			if (!event.metaKey && !event.ctrlKey) {
				that._removeClass( selectee.$element, "ui-selected" );
				selectee.selected = false;
				that._addClass( selectee.$element, "ui-unselecting" );
				selectee.unselecting = true;
				// selectable UNSELECTING callback
				that._trigger("unselecting", event, {
					unselecting: selectee.element
				});
			}
		});

		$(event.target).parents().addBack().each(function() {
			var doSelect,
				selectee = $.data(this, "selectable-item");
			if (selectee) {
				doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected");
				that._removeClass( selectee.$element, doSelect ? "ui-unselecting" : "ui-selected" )
					._addClass( selectee.$element, doSelect ? "ui-selecting" : "ui-unselecting" );
				selectee.unselecting = !doSelect;
				selectee.selecting = doSelect;
				selectee.selected = doSelect;
				// selectable (UN)SELECTING callback
				if (doSelect) {
					that._trigger("selecting", event, {
						selecting: selectee.element
					});
				} else {
					that._trigger("unselecting", event, {
						unselecting: selectee.element
					});
				}
				return false;
			}
		});

	},

	_mouseDrag: function(event) {

		this.dragged = true;

		if (this.options.disabled) {
			return;
		}

		var tmp,
			that = this,
			options = this.options,
			x1 = this.opos[0],
			y1 = this.opos[1],
			x2 = event.pageX,
			y2 = event.pageY;

		if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; }
		if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; }
		this.helper.css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1 });

		this.selectees.each(function() {
			var selectee = $.data(this, "selectable-item"),
				hit = false;

			//prevent helper from being selected if appendTo: selectable
			if (!selectee || selectee.element === that.element[0]) {
				return;
			}

			if (options.tolerance === "touch") {
				hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
			} else if (options.tolerance === "fit") {
				hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
			}

			if (hit) {
				// SELECT
				if (selectee.selected) {
					that._removeClass( selectee.$element, "ui-selected" );
					selectee.selected = false;
				}
				if (selectee.unselecting) {
					that._removeClass( selectee.$element, "ui-unselecting" );
					selectee.unselecting = false;
				}
				if (!selectee.selecting) {
					that._addClass( selectee.$element, "ui-selecting" );
					selectee.selecting = true;
					// selectable SELECTING callback
					that._trigger("selecting", event, {
						selecting: selectee.element
					});
				}
			} else {
				// UNSELECT
				if (selectee.selecting) {
					if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
						that._removeClass( selectee.$element, "ui-selecting" );
						selectee.selecting = false;
						that._addClass( selectee.$element, "ui-selected" );
						selectee.selected = true;
					} else {
						that._removeClass( selectee.$element, "ui-selecting" );
						selectee.selecting = false;
						if (selectee.startselected) {
							that._addClass( selectee.$element, "ui-unselecting" );
							selectee.unselecting = true;
						}
						// selectable UNSELECTING callback
						that._trigger("unselecting", event, {
							unselecting: selectee.element
						});
					}
				}
				if (selectee.selected) {
					if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
						that._removeClass( selectee.$element, "ui-selected" );
						selectee.selected = false;

						that._addClass( selectee.$element, "ui-unselecting" );
						selectee.unselecting = true;
						// selectable UNSELECTING callback
						that._trigger("unselecting", event, {
							unselecting: selectee.element
						});
					}
				}
			}
		});

		return false;
	},

	_mouseStop: function(event) {
		var that = this;

		this.dragged = false;

		$(".ui-unselecting", this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			that._removeClass( selectee.$element, "ui-unselecting" );
			selectee.unselecting = false;
			selectee.startselected = false;
			that._trigger("unselected", event, {
				unselected: selectee.element
			});
		});
		$(".ui-selecting", this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			that._removeClass( selectee.$element, "ui-selecting" )
				._addClass( selectee.$element, "ui-selected" );
			selectee.selecting = false;
			selectee.selected = true;
			selectee.startselected = true;
			that._trigger("selected", event, {
				selected: selectee.element
			});
		});
		this._trigger("stop", event);

		this.helper.remove();

		return false;
	}

});

}));


text:
class CreateActiveAdminPermissions < ActiveRecord::Migration[5.0]
  def change
    create_table :active_admin_permissions do |t|
      t.integer :managed_resource_id, null: false
      t.integer :role,                null: false, limit: 1, default: 0
      t.integer :state,               null: false, limit: 1, default: 0

      t.timestamp null: false
    end

    add_index :active_admin_permissions, [:managed_resource_id, :role], unique: true, name: "active_admin_permissions_index"
  end
end


text:
NS_ASSUME_NONNULL_BEGIN

@protocol NKLocalStorage;

@interface NKFavoritesPresenter : NKBasePresenter <NKFavoritesViewOutput>

@property (strong, nonatomic) id <NKLocalStorage> localStorage;

@end

NS_ASSUME_NONNULL_END


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
N. Z. Jl Bot. 16(3): 353 (1978)

#### Original name
Stigmina longispora var. longispora

### Remarks
null


text:
namespace AMDiS
{
#if !AMDIS_FIXED_SIZE || !defined(DOW)
  int Global::dimOfWorld = 0;
#endif
  std::vector<std::vector<int>> Global::geoIndexTable;

  Element* Global::referenceElement[4] =
  {
    NULL,
    new Line(NULL),
    new Triangle(NULL),
    new Tetrahedron(NULL)
  };

  void Global::init()
  {
    int d = -1;

    // get dimension
    TEST_EXIT(Parameters::initialized())("Parameters not initialized!\n");
    Parameters::get("dimension of world",d,0);
#if !AMDIS_FIXED_SIZE || !defined(DOW)
    TEST_EXIT(d > 0)("Cannot initialize dimension!\n");
    TEST_EXIT((d == 1) || (d == 2) || (d == 3))("Invalid world dimension %d!\n",d);

    // set dimension
    dimOfWorld = d;
#else
    static_assert( DOW == 1 || DOW ==2 || DOW == 3, "Invalid world dimension" );
    if (d != -1 && DOW != d)
    {
      WARNING("dimOfWorld given in init-file != DOW\n");
    }
#endif

    // prepare geoIndex-Table
    int geoTableSize = abs(static_cast<int>(MINPART)) + MAXPART + 1;
    geoIndexTable.resize(4);
    for (int i = 0; i < 4; i++)
    {
      geoIndexTable[i].resize(geoTableSize);
      for (int j = 0; j < geoTableSize; j++)
        geoIndexTable[i][j] = 0;
    }

    geoIndexTable[0][PARTS - MINPART] = 1;
    geoIndexTable[0][VERTEX - MINPART] = 1;
    geoIndexTable[0][EDGE - MINPART] = 0;
    geoIndexTable[0][FACE - MINPART] = 0;
    geoIndexTable[0][WORLD - MINPART] = dimOfWorld;

    for (int i = 1; i < 4; i++)
    {
      geoIndexTable[i][CENTER - MINPART] = referenceElement[i]->getGeo(CENTER);
      geoIndexTable[i][VERTEX - MINPART] = referenceElement[i]->getGeo(VERTEX);
      geoIndexTable[i][EDGE - MINPART] = referenceElement[i]->getGeo(EDGE);
      geoIndexTable[i][FACE - MINPART] = referenceElement[i]->getGeo(FACE);
      geoIndexTable[i][DIMEN - MINPART] = referenceElement[i]->getGeo(DIMEN);
      geoIndexTable[i][PARTS - MINPART] = referenceElement[i]->getGeo(PARTS);
      geoIndexTable[i][NEIGH - MINPART] = referenceElement[i]->getGeo(NEIGH);
      geoIndexTable[i][WORLD - MINPART] = dimOfWorld;
      geoIndexTable[i][BOUNDARY - MINPART] = referenceElement[i]->getGeo(BOUNDARY);
      geoIndexTable[i][PROJECTION - MINPART] = referenceElement[i]->getGeo(PROJECTION);
    }

    // set msgWait
    Msg::setMsgWait(!(Parameters::getMsgWait() == 0));
  }

  void Global::clear()
  {
    delete referenceElement[1];
    delete referenceElement[2];
    delete referenceElement[3];
  }

} // end namespace AMDiS


text:
extern crate test_macros;

use test_macros::{nop_attr, no_output, emit_input};

fn main() {
    assert_eq!(unsafe { rust_get_test_int() }, 1isize);
    assert_eq!(unsafe { rust_dbg_extern_identity_u32(0xDEADBEEF) }, 0xDEADBEEF);
}

#[link(name = "rust_test_helpers", kind = "static")]
extern {
    #[no_output]
    fn some_definitely_unknown_symbol_which_should_be_removed();

    #[nop_attr]
    fn rust_get_test_int() -> isize;

    emit_input!(fn rust_dbg_extern_identity_u32(arg: u32) -> u32;);
}


text:
import json
import logging
import pytest

@pytest.mark.asyncio
async def test_create_repository(server, client):
    # Given the server is running.
    async with client.get('http://%s/' % server) as rep:
        assert rep.status == 200
        index = await rep.json()

    # And we try to create a new repository.
    req = json.dumps({
        'name': 'foo',
    }).encode('utf-8')
    async with client.post(index['create'], data=req) as rep:
        repo = await rep.json()

        # Then it should exist.
        assert repo == {
            'name': 'foo',
            'clone': [
                'http://%s/repositories/foo.git/' % server,
            ],
            'details': 'http://%s/repositories/foo' % server,
            'delete': 'http://%s/repositories/foo' % server,
        }

@pytest.mark.asyncio
async def test_create_existing_repository(server, client):
    # Given the server is running.
    async with client.get('http://%s/' % server) as rep:
        assert rep.status == 200
        index = await rep.json()

    # And the repository exists.
    req = json.dumps({
        'name': 'foo',
    }).encode('utf-8')
    async with client.post(index['create'], data=req) as rep:
        repo = await rep.json()
        assert repo == {
            'name': 'foo',
            'clone': [
                'http://%s/repositories/foo.git/' % server,
            ],
            'details': 'http://%s/repositories/foo' % server,
            'delete': 'http://%s/repositories/foo' % server,
        }

    # When we try to create it again.
    req = json.dumps({
        'name': 'foo',
    }).encode('utf-8')
    async with client.post(index['create'], data=req) as rep:

        # Then the request should be rejected.
        assert rep.status == 409

@pytest.mark.asyncio
async def test_create_repository_invalid_request(server, client):
    # Given the server is running.
    async with client.get('http://%s/' % server) as rep:
        assert rep.status == 200
        index = await rep.json()

    # And we try to create a new repository with an invalid request.
    req = json.dumps({
        'nme': 'foo',  # NOTE: intentional typo.
    }).encode('utf-8')
    async with client.post(index['create'], data=req) as rep:

        # Them the request should be rejected.
        assert rep.status == 400

@pytest.mark.asyncio
async def test_query_repository(server, client):
    # Given the server is running.
    async with client.get('http://%s/' % server) as rep:
        assert rep.status == 200
        index = await rep.json()

    # And the repository exists.
    req = json.dumps({
        'name': 'foo',
    }).encode('utf-8')
    async with client.post(index['create'], data=req) as rep:
        repo = await rep.json()
        assert repo == {
            'name': 'foo',
            'clone': [
                'http://%s/repositories/foo.git/' % server,
            ],
            'details': 'http://%s/repositories/foo' % server,
            'delete': 'http://%s/repositories/foo' % server,
        }

    # When we fetch the details.
    async with client.get(repo['details']) as rep:

        # Then we should get the info we got when we created it.
        assert rep.status == 200
        body = await rep.json()
        assert body == repo

@pytest.mark.asyncio
async def test_query_unknown_repository(server, client):
    # Given the server is running.
    async with client.get('http://%s/' % server) as rep:
        assert rep.status == 200

    # But the repository does not exist.
    details = 'http://%s/repositories/foo' % server

    # When we fetch the details.
    async with client.get(details) as rep:

        # Then the request should fail.
        assert rep.status == 404

@pytest.mark.asyncio
async def test_repository_listing(server, client):
    # Given the server is running.
    async with client.get('http://%s/' % server) as rep:
        assert rep.status == 200
        index = await rep.json()

    # But there are no repositories.

    # When we fetch the listing.
    async with client.get(index['list']) as rep:
        assert rep.status == 200
        listing = await rep.json()

        # Then the listing is empty.
        assert listing == {
            'repositories': [],
        }

    # Given a pair of repositories exist.
    req = json.dumps({
        'name': 'foo',
    }).encode('utf-8')
    async with client.post(index['create'], data=req) as rep:
        assert rep.status == 201
        foo = await rep.json()
    req = json.dumps({
        'name': 'bar',
    }).encode('utf-8')
    async with client.post(index['create'], data=req) as rep:
        assert rep.status == 201
        bar = await rep.json()

    # When we fetch the listing.
    async with client.get(index['list']) as rep:
        assert rep.status == 200
        listing = await rep.json()

        # Then the listing shows our two repositories.
        assert listing == {
            'repositories': [
                bar,
                foo,
            ],
        }

@pytest.mark.asyncio
async def test_delete_repository(server, client):
    # Given the server is running.
    async with client.get('http://%s/' % server) as rep:
        assert rep.status == 200
        index = await rep.json()

    # And a pair of repositories exist.
    req = json.dumps({
        'name': 'foo',
    }).encode('utf-8')
    async with client.post(index['create'], data=req) as rep:
        assert rep.status == 201
        foo = await rep.json()
    req = json.dumps({
        'name': 'bar',
    }).encode('utf-8')
    async with client.post(index['create'], data=req) as rep:
        assert rep.status == 201
        bar = await rep.json()

    # When we fetch the listing.
    async with client.get(index['list']) as rep:
        assert rep.status == 200
        listing = await rep.json()

        # Then the listing shows our two repositories.
        assert listing == {
            'repositories': [
                bar,
                foo,
            ],
        }

    # When we delete one of the repositories.
    async with client.delete(foo['delete']) as rep:
        assert rep.status == 200
        body = await rep.json()
        assert body == {}

    # And we fetch the listing.
    async with client.get(index['list']) as rep:
        assert rep.status == 200
        listing = await rep.json()

        # Then the listing shows only the remaining repository.
        assert listing == {
            'repositories': [
                bar,
            ],
        }

@pytest.mark.asyncio
async def test_delete_unknown_repository(server, client):
    # Given the server is running.
    async with client.get('http://%s/' % server) as rep:
        assert rep.status == 200

    # But the repository does not exist.
    delete = 'http://%s/repositories/foo' % server

    # When we delete the repository.
    async with client.delete(delete) as rep:

        # Then the request fails.
        assert rep.status == 404

@pytest.mark.asyncio
async def test_clone_repository(server, client, run, workspace,
                                fluent_emit, fluent_server):
    # Given the server is running.
    async with client.get('http://%s/' % server) as rep:
        assert rep.status == 200
        index = await rep.json()

    # And a repository exists.
    req = json.dumps({
        'name': 'foo',
    }).encode('utf-8')
    async with client.post(index['create'], data=req) as rep:
        repo = await rep.json()

        # Then it should exist.
        assert repo == {
            'name': 'foo',
            'clone': [
                'http://%s/repositories/foo.git/' % server,
            ],
            'details': 'http://%s/repositories/foo' % server,
            'delete': 'http://%s/repositories/foo' % server,
        }

        assert rep.headers['X-Request-Id']

    # When we try to clone it.
    logging.debug('FOO')
    clone_url = repo['clone'][0]
    await workspace.run('git clone ' + clone_url)

    # Then we should be able to push to it.
    #
    # NOTE: this test requires Git 2.9+ to use the `http.extraHeader` option.
    repo = workspace.open_repo(repo['name'], bare=False)
    await repo.run('git config user.name "py.test"')
    await repo.run('git config user.email "noreply@example.org"')
    repo.edit('README.txt', 'Nothing to see here!')
    await repo.run('git add README.txt')
    await repo.run('git commit -m "Starts project."')
    output = await repo.run(' '.join([
        'git',
        '-c http.extraheader="X-Request-Id: MY-REQ-ID"',
        'push origin master',
    ]))
    assert output == '\n'.join([
        'remote: Request ID: "MY-REQ-ID".        ',
        'To %s' % clone_url,
        ' * [new branch]      master -> master',
    ])
    assert fluent_emit.call_count > 0
    # Git hook logs will be sent to our mock FluentD server.
    assert len(fluent_server[2]) > 0


text:
/*
 * File:   InvocationReplyPacket.cpp
 * Author: rmartins
 *
 * Created on October 27, 2010, 12:26 PM
 */

#include "InvocationReplyPacket.h"

InvocationReplyPacket::InvocationReplyPacket() {
}

InvocationReplyPacket::InvocationReplyPacket(const InvocationReplyPacket& orig) {
}

InvocationReplyPacket::~InvocationReplyPacket() {
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _selectorTokenizer = require("selector-tokenizer");

var _selectorTokenizer2 = _interopRequireDefault(_selectorTokenizer);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var TYPE_SELECTOR = "type";
var ID_SELECTOR = "id";
var CLASS_SELECTOR = "class";
var ATTRIBUTE_SELECTOR = "attribute";
var UNIVERSAL_SELECTOR = "universal";
var PSEUDO_SELECTOR = "pseudo";
var DESCENDANT_COMBINATOR = "descendant";
var ADJACENT_SIBLING_COMBINATOR = "adjacent-sibling";
var GENERAL_SIBLING_COMBINATOR = "general-sibling";
var CHILD_COMBINATOR = "child";
var SCOPE_STARTING_POINT = "scope-start";
var SCOPE_ENDING_POINT = "scope-end";

var OPEN_SQUARE = "[".charCodeAt(0);
var CLOSE_SQUARE = "]".charCodeAt(0);
var WHITESPACE = " ".charCodeAt(0);
var ASTERISK = "*".charCodeAt(0);
var CARET = "^".charCodeAt(0);
var VERTICAL_LINE = "|".charCodeAt(0);
var TILDE = "~".charCodeAt(0);
var DOLLAR = "$".charCodeAt(0);
var EQUALS = "=".charCodeAt(0);
var SINGLE_QUOTE = "\'".charCodeAt(0);
var DOUBLE_QUOTE = "\"".charCodeAt(0);
var SLASH = "\\".charCodeAt(0);
var I_CODE = "i".charCodeAt(0);

/**
 * @returns {boolean}
 */
var CF_WORD = function CF_WORD(code) {
  return code >= 128 || code === 45 || code == 245 || code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
};

/**
 * The selector checker allows to match a specified DOM element with target css selector.
 * This module should be useful for custom element state matching eg. :hover, :focus etc.
 *
 * The following example illustrates the principle the SelectorChecker.check method
 * @example
 * checker = new SelectorChecker();
 * element = document.getElementById("target"); //=>
...

 * matches = checker.check(element, "h1");
 * matches   //=> true
 */

var SelectorChecker = function () {
  function SelectorChecker() {
    _classCallCheck(this, SelectorChecker);

    this.tokenizer = new _selectorTokenizer2.default();
  }

  /**
   * Check if element is a first child of its parent
   * @param element
   * @returns {boolean}
   */

  _createClass(SelectorChecker, [{
    key: "isFirstChild",
    value: function isFirstChild(element) {
      return element && element.parentElement && element.parentElement.children[0] === element;
    }

    /**
     * Check if element is a first child of its parent
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isLastChild",
    value: function isLastChild(element) {
      return element && element.parentElement && element.parentElement.children[element.parentElement.children.length - 1] === element;
    }

    /**
     * Check if element is in indeterminate state
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isIndeterminate",
    value: function isIndeterminate(element) {
      var group = void 0,
          i = void 0;
      // Any <input type="checkbox"> element whose indeterminate DOM property is set to true by JavaScript
      if (element && element.tagName === "INPUT" && element.getAttribute("type") === "checkbox") {
        return element.indeterminate === true;
      }
      // <input type="radio"> elements whose radio button group's radio buttons are all unchecked
      else if (element && element.tagName === "INPUT" && element.getAttribute("type") === "radio") {
          if (group = element.getAttribute("name")) {
            group = element.ownerDocument.querySelectorAll("input[type=\"radio\"][name=\"" + group + "\"]");
            for (i = 0; i < group.length; i++) {
              if (group[i].checked) return false;
            }
          }
          return element.checked === false;
        }
        // <progress> elements in an indeterminate state
        else if (element && element.tagName === "PROGRESS") {
            return !element.hasAttribute("value");
          }
      // Otherwise, return false
      return false;
    }

    /**
     * Check if element is has checked state
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isChecked",
    value: function isChecked(element) {
      var type = element.getAttribute("type");
      if (element && element.tagName === "INPUT" && (type = type.toLowerCase() === "checkbox" || type === "radio")) {
        return element.checked === true;
      } else if (element && element.tagName === "OPTION") {
        return element.selected === true;
      }
      return false;
    }

    /**
     * Check if element is actually disabled
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isDisabled",
    value: function isDisabled(element) {
      var elements = ["button", "input", "select", "textarea", "optgroup", "option", "menuitem", "fieldset"];

      if (elements.indexOf(element.tagName.toLowerCase()) > -1) {
        return element.disabled === true;
      }

      return false;
    }

    /**
     * Check if element is actually enabled
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isEnabled",
    value: function isEnabled(element) {
      return this.isDisabled(element) !== true;
    }

    /**
     * Check if element is actually empty
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isEmpty",
    value: function isEmpty(element) {
      return element.childNodes.length === 0;
    }

    /**
     * Check if element is actually first of type
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isFirstOfType",
    value: function isFirstOfType(element) {
      var elem = element;
      if (element) {
        while (elem = elem.previousElementSibling) {
          if (elem.tagName === element.tagName) return false;
        }
        return true;
      }
      return false;
    }

    /**
     * Check if element is actually last of type
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isLastOfType",
    value: function isLastOfType(element) {
      var elem = element;
      if (element) {
        while (elem = elem.nextElementSibling) {
          if (elem.tagName === element.tagName) return false;
        }
        return true;
      }
      return false;
    }

    /**
     * Check if element is actually the only child of its parent
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isOnlyChild",
    value: function isOnlyChild(element) {
      return this.isFirstChild(element) && this.isLastChild(element);
    }

    /**
     * Check if element is actually the only element of its type in parent
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isOnlyOfType",
    value: function isOnlyOfType(element) {
      return this.isFirstOfType(element) && this.isLastOfType(element);
    }

    /**
     * Check if element is actually required
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isRequired",
    value: function isRequired(element) {
      var elements = ["input", "select", "textarea"];
      return element && elements.indexOf(element.tagName.toLowerCase()) > -1 && element.hasAttribute("required");
    }

    /**
     * Check if element is actually optional
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isOptional",
    value: function isOptional(element) {
      var elements = ["input", "select", "textarea"];
      return element && elements.indexOf(element.tagName.toLowerCase()) > -1 && !element.hasAttribute("required");
    }

    /**
     * Check if element is actually a read-write element
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isReadWrite",
    value: function isReadWrite(element) {
      var types = ["text", "email", "date", "time", "url", "search", "number", "week", "month", "tel"],
          type = element.getAttribute("type");

      if (element && element.tagName === "TEXTAREA") {
        return !element.hasAttribute("readonly");
      } else if (element && element.tagName === "INPUT") {
        if (type && types.indexOf(type.toLowerCase()) === -1) {
          return false;
        }
        return !element.hasAttribute("readonly");
      }
      return element && element.hasAttribute("contenteditable");
    }

    /**
     * Check if element is actually a read-only element
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isReadOnly",
    value: function isReadOnly(element) {
      return this.isReadWrite(element) === false;
    }

    /**
     * Check if element is actually a document root element
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isRoot",
    value: function isRoot(element) {
      return element && element.ownerDocument.documentElement === element;
    }

    /**
     * Check if element is actually a document target element
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isTarget",
    value: function isTarget(element) {
      return element && element.hasAttribute("id") && "#" + element.getAttribute("id") === element.ownerDocument.location.hash;
    }

    /**
     * Check if element is actually out of range
     * @param element
     * @returns {boolean|undefined}
     */

  }, {
    key: "isOutOfRange",
    value: function isOutOfRange(element) {
      var types = ["number", "range", "date", "datetime", "datetime-local", "month", "time", "week"],
          type = void 0,
          min = void 0,
          max = void 0;
      if (element && element.tagName === "INPUT" && element.validity) {
        type = element.getAttribute("type");
        min = element.getAttribute("min");
        max = element.getAttribute("max");

        if (type && types.indexOf(type.toLowerCase()) > -1 && (min || max)) {
          return element.validity.rangeOverflow || element.validity.rangeUnderflow;
        }
      }
      return false;
    }

    /**
     * Check if element is actually in range
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isInRange",
    value: function isInRange(element) {
      var types = ["number", "range", "date", "datetime", "datetime-local", "month", "time", "week"],
          type = void 0,
          min = void 0,
          max = void 0;
      if (element.tagName === "INPUT" && element.validity) {
        type = element.getAttribute("type");
        min = element.getAttribute("min");
        max = element.getAttribute("max");

        if (type && types.indexOf(type.toLowerCase()) > -1 && (min || max)) {
          return !element.validity.rangeOverflow && !element.validity.rangeUnderflow;
        }
      }
      return false;
    }

    /**
     * Check if element is actually invalid
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isInvalid",
    value: function isInvalid(element) {
      return element && element.validity ? element.validity.valid === false : false;
    }

    /**
     * Check if element is actually valid
     * @param element
     * @returns {boolean}
     */

  }, {
    key: "isValid",
    value: function isValid(element) {
      return element && element.validity ? element.validity.valid === true : false;
    }

    /**
     * Checks if element is matching a target lang
     * @param element
     * @param params
     * @returns {boolean}
     */

  }, {
    key: "isLang",
    value: function isLang(element, params) {
      if (params && params.length === 1 && params[0].type === "type") {
        var elem = element,
            lang = void 0;
        while (elem) {
          if (lang = elem.getAttribute("lang")) {
            if ((lang = lang.toLowerCase()) === params[0].value.toLowerCase() || lang.indexOf(params[0].value.toLowerCase() + "-") === 0) {
              return true;
            }
          }
          elem = elem.parentElement;
        }
      }
      return false;
    }

    /**
     * Check if element is actually not matching target param
     * @param element
     * @param params
     */

  }, {
    key: "isNot",
    value: function isNot(element, params) {
      if (params && params.length === 1) {
        return this.matchSelectorToken(element, params[0]) === false;
      }
      return false;
    }

    /**
     * Check if element is actually an nth child of its parent
     * @param element
     * @param params
     * @returns {boolean}
     */

  }, {
    key: "isNthChild",
    value: function isNthChild(element, params, inverseFlag) {
      if (params && params.length) {
        var parent = element.parentElement,
            index = void 0,
            a = void 0,
            b = void 0,
            length = parent.childNodes.length,
            n = 0;

        switch (params.length) {
          case 3:
            if (params[2].value[params[2].value.length - 1] !== "n") return false;
            a = parseInt(params[2].value, 10) || (params[2].value[0] === "-" ? -1 : 1);
            b = parseInt(params[0].value, 10) || 0;
            break;
          case 1:
            if (params[0].value.toLowerCase() === "odd") {
              a = 2;
              b = 1;
            } else if (params[0].value.toLowerCase() === "even") {
              a = 2;
              b = 0;
            } else if ((index = params[0].value.indexOf("-")) > 0) {
              a = parseInt(params[0].value.substring(0, index), 10) || 1;
              b = parseInt(params[0].value.substring(index), 10) || 0;
            } else if (params[0].value[params[0].value.length - 1] === "n") {
              a = parseInt(params[0].value, 10) || (params[0].value[0] === "-" ? -1 : 1);
              b = 0;
            } else {
              a = 0;
              b = parseInt(params[0].value, 10);
            }
            break;
          default:
            return false;
        }

        if (isNaN(a) || isNaN(b)) return false;

        if (a) {
          while (n < length) {
            index = a * n + b;
            if (parent.childNodes[inverseFlag ? length - index : index - 1] === element) return true;
            n = n + 1;
          }
        } else {
          return parent.childNodes[inverseFlag ? length - b : b - 1] === element;
        }
      }
      return false;
    }

    /**
     * Check if element is actually an nth last child of its parent
     * @param element
     * @param params
     * @returns {boolean}
     */

  }, {
    key: "isNthLastChild",
    value: function isNthLastChild(element, params) {
      return this.isNthChild(element, params, true);
    }

    /**
     * Check if element is actually an nth of type of its parent
     * @param element
     * @param params
     * @returns {boolean}
     */

  }, {
    key: "isNthOfType",
    value: function isNthOfType(element, params, inverseFlag) {
      if (params && params.length) {
        var parent = element.parentElement,
            index = void 0,
            a = void 0,
            b = void 0,
            n = 0,
            nodes = void 0,
            i = void 0;

        switch (params.length) {
          case 3:
            if (params[2].value[params[2].value.length - 1] !== "n") return false;
            a = parseInt(params[2].value, 10) || (params[2].value[0] === "-" ? -1 : 1);
            b = parseInt(params[0].value, 10) || 0;
            break;
          case 1:
            if (params[0].value.toLowerCase() === "odd") {
              a = 2;
              b = 1;
            } else if (params[0].value.toLowerCase() === "even") {
              a = 2;
              b = 0;
            } else if ((index = params[0].value.indexOf("-")) > 0) {
              a = parseInt(params[0].value.substring(0, index), 10) || 1;
              b = parseInt(params[0].value.substring(index), 10) || 0;
            } else if (params[0].value[params[0].value.length - 1] === "n") {
              a = parseInt(params[0].value, 10) || (params[0].value[0] === "-" ? -1 : 1);
              b = 0;
            } else {
              a = 0;
              b = parseInt(params[0].value, 10);
            }
            break;
          default:
            return false;
        }

        if (isNaN(a) || isNaN(b)) return false;

        // Filter node of type
        nodes = [];
        for (i = 0; i < parent.childNodes.length; i++) {
          if (parent.childNodes[i].tagName === element.tagName) {
            nodes.push(parent.childNodes[i]);
          }
        }

        // Check if element is a nth of its parent
        if (a) {
          while (n < nodes.length) {
            index = a * n + b;
            if (nodes[inverseFlag ? nodes.length - index : index - 1] === element) return true;
            n = n + 1;
          }
        } else {
          return nodes[inverseFlag ? nodes.length - b : b - 1] === element;
        }
      }
      return false;
    }

    /**
     * Check if element is actually an nth of type of its parent
     * @param element
     * @param params
     * @returns {boolean}
     */

  }, {
    key: "isNthLastOfType",
    value: function isNthLastOfType(element, params) {
      return this.isNthOfType(element, params, true);
    }

    /**
     * Check if element is in a state map
     * @param element
     * @param value
     * @param stateMap
     */

  }, {
    key: "isInStateMap",
    value: function isInStateMap(element, value, stateMap) {
      return element && stateMap && stateMap[value] && stateMap[value].length && stateMap[value].indexOf(element) > -1;
    }

    /**
     * Check if specified tagName matches element
     * @param element
     * @param tagName
     * @returns {boolean}
     */

  }, {
    key: "matchTagName",
    value: function matchTagName(element, tagName) {
      return element && element.tagName.toLowerCase() === tagName.toLowerCase();
    }

    /**
     * Check if specified tagName matches
     * @param element
     * @param className
     */

  }, {
    key: "matchClassName",
    value: function matchClassName(element, className) {
      return element && element.hasAttribute("class") ? element.getAttribute("class").split(/\s+/).indexOf(className.substr(1)) > -1 : false;
    }

    /**
     * Check if element actually has a specified id
     * @param element
     * @param id
     */

  }, {
    key: "matchID",
    value: function matchID(element, id) {
      return element && element.hasAttribute("id") && element.getAttribute("id").toLowerCase() === id.toLowerCase().substring(1);
    }

    /**
     * Check if specified attribute value matches target element
     * @param element
     * @param value
     * @returns {boolean}
     */

  }, {
    key: "matchAttribute",
    value: function matchAttribute(element, value) {
      var tokens = this.splitAttributeToken(value),
          elementValue = void 0,
          i = void 0;

      switch (tokens.length) {
        // Proceed with [attr] case
        case 1:
          return element && element.hasAttribute(tokens[0]);
          break;

        // TODO: Update this fragment on CSS4 Spec release
        // Proceed with [attr operator value] or [attr operator value i] case
        case 3:
        case 4:
          // Process element by attribute operator type
          switch (tokens[1]) {
            case "=":
              return element && element.hasAttribute(tokens[0]) ? element.getAttribute(tokens[0]).toLowerCase() === tokens[2].toLowerCase() : false;
              break;
            case "~=":
              if (element && (elementValue = element.getAttribute(tokens[0]))) {
                elementValue = elementValue.split(/\s+/);
                for (i = 0; i < elementValue.length; i++) {
                  if (elementValue[i].toLowerCase() === tokens[2].toLowerCase()) return true;
                }
              }
              return false;
              break;
            case "|=":
              if (element && (elementValue = element.getAttribute(tokens[0]))) {
                elementValue = elementValue.split(/\s+/);
                if (elementValue[0].toLowerCase() === tokens[2].toLowerCase() || elementValue[0].toLowerCase().indexOf(tokens[2].toLowerCase() + "-") === 0) return true;
              }
              return false;
              break;
            case "^=":
              if (element && (elementValue = element.getAttribute(tokens[0]))) {
                elementValue = elementValue.split(/\s+/);
                if (elementValue[0].toLowerCase().indexOf("" + tokens[2].toLowerCase()) === 0) return true;
              }
              break;
            case "$=":
              if (element && (elementValue = element.getAttribute(tokens[0]))) {
                elementValue = elementValue.split(/\s+/);
                if (elementValue[elementValue.length - 1].toLowerCase().indexOf("" + tokens[2].toLowerCase()) === elementValue[elementValue.length - 1].length - tokens[2].length) return true;
              }
              break;
            case "*=":
              return element && element.hasAttribute(tokens[0]) ? element.getAttribute(tokens[0]).toLowerCase().indexOf(tokens[2].toLowerCase()) > -1 : false;
              break;
            default:
              throw new Error("Parse error on " + value);
          }

          break;
        default:
          throw new Error("Parse error on " + value);
      }

      return false;
    }

    /**
     * Check if specified element matches target pseudo selector
     * @param element
     * @param value
     * @param statesMap - optional map of elements with forced interactive states (:hover, :focus, :active, :visited)
     * @param params - a set of any additional params tokenized inside tokenization scopes
     * @returns {boolean|undefined}
     *
     * @throws TypeError - when unknown token type was spotted
     */

  }, {
    key: "matchPseudoSelector",
    value: function matchPseudoSelector(element, value, statesMap, params) {
      switch (value) {
        case ":first-child":
          return this.isFirstChild(element);
        case ":last-child":
          return this.isLastChild(element);
        case ":indeterminate":
          return this.isIndeterminate(element);
        case ":checked":
          return this.isChecked(element);
        case ":disabled":
          return this.isDisabled(element);
        case ":enabled":
          return this.isEnabled(element);
        case ":empty":
          return this.isEmpty(element);
        case ":first-of-type":
          return this.isFirstOfType(element);
        case ":last-of-type":
          return this.isLastOfType(element);
        case ":only-child":
          return this.isOnlyChild(element);
        case ":only-of-type":
          return this.isOnlyOfType(element);
        case ":required":
          return this.isRequired(element);
        case ":optional":
          return this.isOptional(element);
        case ":read-only":
          return this.isReadOnly(element);
        case ":read-write":
          return this.isReadWrite(element);
        case ":root":
          return this.isRoot(element);
        case ":target":
          return this.isTarget(element);
        case ":out-of-range":
          return this.isOutOfRange(element);
        case ":in-range":
          return this.isInRange(element);
        case ":invalid":
          return this.isInvalid(element);
        case ":valid":
          return this.isValid(element);
        case ":lang":
          return this.isLang(element, params);
        case ":not":
          return this.isNot(element, params);
        case ":nth-child":
          return this.isNthChild(element, params);
        case ":nth-last-child":
          return this.isNthLastChild(element, params);
        case ":nth-of-type":
          return this.isNthOfType(element, params);
        case ":nth-last-of-type":
          return this.isNthLastOfType(element, params);
        case ":hover":
        case ":focus":
        case ":active":
        case ":visited":
          return this.isInStateMap(element, value, statesMap);

        case ":link":
          return !this.isInStateMap(element, ":visited", statesMap);

        // TODO: Add in feature releases
        case ":any":
        case ":dir":
        case ":default":
        case ":first":
        case ":fullscreen":
        case ":scope":
          return false;

        // Ignore all other pseudo-classes and pseudo-elements
        default:
          return false;
      }
    }

    /**
     * Check if specified element matches target token
     * @param element
     * @param token
     * @param statesMap - optional map of elements with forced interactive states (:hover, :focus, :active, :visited)
     * @param params - a set of any additional params tokenized inside tokenization scopes
     * @param tokens - a set of remaining tokens
     * @returns {boolean}
     *
     * @throws TypeError - when unknown token type was spotted
     */

  }, {
    key: "matchSelectorToken",
    value: function matchSelectorToken(element, token, stateMap, params, tokens) {
      switch (token.type) {
        case TYPE_SELECTOR:
          return this.matchTagName(element, token.value);

        case ID_SELECTOR:
          return this.matchID(element, token.value);

        case CLASS_SELECTOR:
          return this.matchClassName(element, token.value);

        case UNIVERSAL_SELECTOR:
          return element ? true : false;

        case ATTRIBUTE_SELECTOR:
          return this.matchAttribute(element, token.value);

        case PSEUDO_SELECTOR:
          return this.matchPseudoSelector(element, token.value, stateMap, params);

        case SCOPE_ENDING_POINT:
          if (!tokens || !tokens.length) return false;

          params = [];
          while ((token = tokens.pop()).type !== SCOPE_STARTING_POINT) {
            params.push(token);
          }

          // Read token which is starting a scope
          token = tokens.pop();

          return this.matchSelectorToken(element, token, stateMap, params);

        default:
          throw new TypeError("Unexpected token " + token.value + " to match");
      }
    }

    /**
     * Split an attribute token on attr, operand and value
     * @param value
     * @returns {Array}
     */

  }, {
    key: "splitAttributeToken",
    value: function splitAttributeToken(value) {
      var attr = void 0,
          val = void 0,
          type = void 0,
          nextCode = void 0,
          i = void 0,
          size = void 0,
          start = void 0,
          quotes = void 0,
          ignore = void 0,
          result = [];

      for (i = 0; i < value.length; i++) {
        nextCode = value.charCodeAt(i);

        // Tokenize attribute
        if (!attr && CF_WORD(nextCode)) {
          start = i;
          size = 0;
          while (CF_WORD(nextCode)) {
            size++;
            nextCode = value.charCodeAt(++i);
          }

          result.push(attr = value.substr(start, size));
        }

        // Tokenize operation type
        if (!type && (nextCode === CARET || nextCode === ASTERISK || nextCode === VERTICAL_LINE || nextCode === DOLLAR || nextCode === EQUALS || nextCode === TILDE)) {
          if (nextCode === EQUALS) {
            result.push(type = value[i]);
          } else if (value.charCodeAt(i + 1) !== EQUALS) {
            throw new SyntaxError("Unexpected character " + value[i + 1] + " at " + i);
          } else {
            result.push(type = value[i] + value[++i]);
          }
        }

        // Tokenize value
        if (!val && (CF_WORD(nextCode) || nextCode === SINGLE_QUOTE || nextCode === DOUBLE_QUOTE)) {
          size = 0;
          if (nextCode === SINGLE_QUOTE || nextCode === DOUBLE_QUOTE) {
            start = ++i;
            quotes = nextCode;

            nextCode = value.charCodeAt(i);

            while (nextCode && nextCode !== quotes) {
              size++;
              nextCode = value.charCodeAt(++i);
            }
          } else {
            start = i;
            while (CF_WORD(nextCode)) {
              size++;
              nextCode = value.charCodeAt(++i);
            }
          }

          result.push(val = value.substr(start, size));
        }

        // Tokenize ignore case flag
        if (!ignore && nextCode === I_CODE) {
          if (!CF_WORD(value.charCodeAt(i + 1))) {
            result.push(ignore = value[i]);
            break;
          }
        }
      }

      return result;
    }

    /**
     * Check if specified element matches target css selector
     * @param element
     * @param selector
     * @param stateMap - optional map of elements with forced interactive states (:hover, :focus, :active, :visited)
     * @returns {boolean}
     *
     * @example
     * checker = new SelectorChecker();
     * element = document.getElementById("target"); //=>
...

     * matches = checker.check(element, "h1");
     * matches   //=> true
     */

  }, {
    key: "check",
    value: function check(element, selector, stateMap) {
      var tokens = this.tokenizer.tokenize(selector);
      var token = void 0,
          matches = void 0,
          elem = element;

      // While has next token
      while (token = tokens.pop()) {
        // Reset matching holder
        matches = false;

        // Switch through token type
        switch (token.type) {
          case ADJACENT_SIBLING_COMBINATOR:
            if (!(elem = elem.previousElementSibling)) return false;
            matches = this.matchSelectorToken(elem, tokens.pop(), stateMap, null, tokens);
            break;

          case DESCENDANT_COMBINATOR:
            token = tokens.pop();
            while (elem = elem.parentElement) {
              if (matches = this.matchSelectorToken(elem, token, stateMap, null, tokens)) break;
            }
            break;

          case GENERAL_SIBLING_COMBINATOR:
            token = tokens.pop();
            while (elem = elem.previousElementSibling) {
              if (matches = this.matchSelectorToken(elem, token, stateMap, null, tokens)) break;
            }
            break;

          case CHILD_COMBINATOR:
            if (!(elem = elem.parentElement)) return false;
            matches = this.matchSelectorToken(elem, tokens.pop(), stateMap, null, tokens);
            break;

          default:
            matches = this.matchSelectorToken(elem, token, stateMap, null, tokens);
            break;
        }

        // Stop looping on first mismatch
        if (!matches) return false;
      }
      return true;
    }

    /**
     * Check if specified element matches target multiple css selector
     * @param element
     * @param multipleSelector
     * @param stateMap - optional map of elements with forced interactive states (:hover, :focus, :active, :visited)
     * @returns {boolean}
     *
     * @example
     * checker = new SelectorChecker();
     * element = document.getElementById("target"); //=>
...

     * matches = checker.checkAll(element, "div, h1");
     * matches   //=> true
     */

  }, {
    key: "checkAll",
    value: function checkAll(element, multipleSelector, stateMap) {
      var selectors = multipleSelector.split(/\s*,\s*/),
          i = void 0;
      for (i = 0; i < selectors.length; i++) {
        if (this.check(element, selectors[i], stateMap)) return true;
      }
      return false;
    }
  }]);

  return SelectorChecker;
}();

exports.default = SelectorChecker;


text:
FROM ubuntu:14.04
MAINTAINER Omar Al-Ithawi <i@omardo.com>

RUN apt-get -y update
RUN apt-get -y install nginx

ADD edxapp.conf /etc/nginx/sites-enabled/edxapp
RUN echo "\ndaemon off;" >> /etc/nginx/nginx.conf

WORKDIR /etc/nginx

CMD ["/usr/sbin/nginx"]


text:
const path = require('path');
const url = require('url');
const webpack = require('webpack');
const _ = require('lodash');

const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const ImageminPlugin = require('imagemin-webpack-plugin').default;
const imageminMozjpeg = require('imagemin-mozjpeg');

const DIRNAME = process.cwd();
const CFG = require('./common.js');
const dllConfig = require(path.resolve(DIRNAME, 'config', CFG.dllName));

const registPlugin = function (config) {
    _.isPlainObject(CFG.Define) && !!_.size(CFG.Define) && config.plugins.push(
        new webpack.DefinePlugin(CFG.Define)
    );

    _.isPlainObject(CFG.Provide) && !!_.size(CFG.Provide) && config.plugins.push(
        new webpack.ProvidePlugin(CFG.Provide)
    );

    _.isString(CFG.banner) && config.plugins.push(
        new webpack.BannerPlugin({
            banner: CFG.banner
        })
    );

    if (_.isPlainObject(CFG.Resource.copy) && _.isArray(CFG.Resource.copy.path)) {
        const copy = CFG.Resource.copy;
        const paths = [];
        copy.path.forEach((item) => {
            paths.push({ from: path.resolve(DIRNAME, CFG.src, item), to: item });
        });
        config.plugins.push(
            new CopyWebpackPlugin(paths, {
                ignore: copy.ignore
            })
        )
    }

    if (!!CFG.dllType && CFG.dllType === 2) {
        if (!!_.size(CFG.dll)) {
            _.forEach(CFG.dll, function (value, key) {
                config.plugins.push(
                    new webpack.optimize.CommonsChunkPlugin({
                        name: key,
                        filename: path.join(CFG.Resource.jsDist, CFG.Resource.jsName).replace(/\\/g, '/'),
                    })
                );
            });
        } else {
            config.plugins.push(
                new webpack.optimize.CommonsChunkPlugin({
                    // name: CFG.commonName || 'common',
                    name: CFG.commonName,
                    filename: path.join(CFG.Resource.jsDist, CFG.Resource.jsName.replace('[name]', CFG.commonName)).replace(/\\/g, '/'),
                })
            );
        }
    }

    _.isPlainObject(CFG.dll) && !!_.size(CFG.dll) && CFG.dllType === 1 && (
        config.plugins.push(
            new webpack.DllReferencePlugin({
                context: '.',
                manifest: require(path.join(DIRNAME, CFG.dist, CFG.dllName)),
            })
        ),
        config.plugins.push(
            new AddAssetHtmlPlugin(function () {
                let arr = [];
                Object.keys(CFG.dll).forEach(function (value) {
                    Object.keys(dllConfig[value]).forEach(function (type, index) {
                        let asset = dllConfig[value][type];
                        arr.push({
                            filepath: path.join(DIRNAME, CFG.dist, asset),
                            outputPath: CFG.Resource[type + 'Dist'] || '',
                            includeSourcemap: false,
                            publicPath: url.resolve((CFG.publicPath ? CFG.publicPath : ''), (CFG.Resource[type + 'Dist'] || '')),
                            typeOfAsset: type
                        })
                    });
                });
                return arr;
            }())
        )
    );

    /**
     * ContextReplacementPlugin
    */
    if(!!CFG.ContextReplacement && CFG.ContextReplacement.usage === true && CFG.ContextReplacement && _.isArray(CFG.ContextReplacement.context)){
        _.forEach(CFG.ContextReplacement.context, function({resourceRegExp, newContentResource, newContentRegExp}){
            config.plugins.push(
                new webpack.ContextReplacementPlugin(resourceRegExp, newContentResource, newContentRegExp)
            )
        })
    }

    config.plugins.push(
        new ImageminPlugin({
            // disable: process.env.NODE_ENV !== 'production',
            test: /\.(jpe?g|png|gif|svg)$/i,
            plugins: [
                imageminMozjpeg({
                    quality: 75,
                    // progressive: true
                })
            ],
            pngquant: {
                // quality: '80-100'
            }
        })
    )
};

module.exports = registPlugin;


text:
for i in "ArchiveConstraint"  "IArchiveConstraint"  "IRsdConstraint"  "RsdConstraint"
do
mv Orchard.Web/Modules/Orchard.Blogs/Routing/$i.CS Orchard.Web/Modules/Orchard.Blogs/Routing/$i.cs
done

#/var/orchard/src/Orchard.Web/Modules/Orchard.Recipes
#RecipeHandlers/MetadataRecipeHandler.cs # looking for
mv /var/orchard/src/Orchard.Web/Modules/Orchard.Recipes/RecipeHandlers/MetaDataRecipeHandler.cs /var/orchard/src/Orchard.Web/Modules/Orchard.Recipes/RecipeHandlers/MetadataRecipeHandler.cs


text:
define(function (require) {
    'use strict';

    /**
     * Processes all container type UI elements
     */
    return function (options) {
        var handlers = {
            TAB: require('./tab'),
            SECTION: require('./section'),
            COLUMN: require('./column')
        };

        if (Array.isArray(options.content)) {
            // pick content by type
            var contents = options.content.reduce(function (picked, container) {
                var type = container.type;
                picked[type] = picked[type] || [];
                picked[type].push(container);
                return picked;
            }, {});

            // list of container types, highest priority first
            var priority = ['TAB', 'SECTION', 'COLUMN'];

            priority.forEach(function (type) {
                // add content, if exists
                var content = contents[type];
                if (content) {
                    var handler = handlers[type];
                    var createResult = handler.create(options);
                    handler.add.call(this, content.map(createResult, this));
                }
            }, this);
        }
        return this;
    };
});


text:
/*
Code provided as-is, no warranty implied
Thanks to https://github.com/r2d2rigo for the restricted aspect ratio formula and MinItemWidth MinItemHeight approach
*/

using System;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace TheChan.Controls {
    /// <summary>
    /// A GridView that lets you set a MinWidth and MinHeight for items you want to restrict to an aspect ration, but still resize
    /// </summary>
    public class AdaptiveGridView : GridView {
        #region DependencyProperties

        /// <summary>
        /// Minimum height for item
        /// </summary>
        public double MinItemHeight {
            get { return (double)GetValue(MinItemHeightProperty); }
            set { SetValue(MinItemHeightProperty, value); }
        }

        public static readonly DependencyProperty MinItemHeightProperty =
            DependencyProperty.Register(
                "MinItemHeight",
                typeof(double),
                typeof(AdaptiveGridView),
                new PropertyMetadata(1.0, (s, a) => {
                    if (!double.IsNaN((double)a.NewValue)) {
                        ((AdaptiveGridView)s).InvalidateMeasure();
                    }
                }));

        /// <summary>
        /// Minimum width for item (must be greater than zero)
        /// </summary>
        public double MinItemWidth {
            get { return (double)GetValue(MinimumItemWidthProperty); }
            set { SetValue(MinimumItemWidthProperty, value); }
        }

        public static readonly DependencyProperty MinimumItemWidthProperty =
            DependencyProperty.Register(
                "MinItemWidth",
                typeof(double),
                typeof(AdaptiveGridView),
                new PropertyMetadata(1.0, (s, a) => {
                    if (!double.IsNaN((double)a.NewValue)) {
                        ((AdaptiveGridView)s).InvalidateMeasure();
                    }
                }));

        #endregion

        public AdaptiveGridView() {
            if (ItemContainerStyle == null) {
                ItemContainerStyle = new Style(typeof(GridViewItem));
            }

            ItemContainerStyle.Setters.Add(new Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Stretch));

            Loaded += (s, a) => {
                if (ItemsPanelRoot != null) {
                    InvalidateMeasure();
                }
            };
        }

        protected override Size MeasureOverride(Size availableSize) {
            var panel = ItemsPanelRoot as ItemsWrapGrid;
            if (panel != null) {
                if (MinItemWidth == 0)
                    throw new DivideByZeroException("You need to have a MinItemWidth greater than zero");

                var availableWidth = availableSize.Width - (Padding.Right + Padding.Left);

                var numColumns = Math.Floor(availableWidth / MinItemWidth);
                numColumns = numColumns == 0 ? 1 : numColumns;
                var numRows = Math.Ceiling(Items.Count / numColumns);

                var itemWidth = availableWidth / numColumns;
                var aspectRatio = MinItemHeight / MinItemWidth;
                var itemHeight = itemWidth * aspectRatio;

                panel.ItemWidth = itemWidth;
                panel.ItemHeight = itemHeight;
            }

            return base.MeasureOverride(availableSize);
        }
    }
}


text:
<?xml version="1.0" ?>
<!DOCTYPE project [
        <!ENTITY properties SYSTEM "file:../../../xmls/properties.xml">
        <!ENTITY paths  SYSTEM "file:../../../xmls/path_refs.xml">
        <!ENTITY taskdefs SYSTEM "file:../../../xmls/taskdefs.xml">
        <!ENTITY taskdefs_post_compile SYSTEM "file:../../../xmls/taskdefs_post_compile.xml">
        <!ENTITY targets SYSTEM "file:../../../xmls/targets.xml">
]>

<!-- ===================================================================
<description>
   Test/Sample Component file for Axis

Notes:
   This is a build file for use with the Jakarta Ant build tool.

Prerequisites:

   jakarta-ant from http://jakarta.apache.org

Build Instructions:
   To compile
        ant compile
   To execute
        ant run

Author:
  Matt Seibert mseibert@us.ibm.com

Copyright:
  Copyright (c) 2002-2003 Apache Software Foundation.
</description>
==================================================================== -->

<project default="compile">

<property name="axis.home" location="../../.." />
<property name="componentName" value="test/wsdl/literal" />
        &properties;
        &paths;
        &taskdefs;
        &taskdefs_post_compile;
        &targets;

<target name="clean">
    <echo message="Removing ${build.dir}/classes/${componentName} and ${build.dir}/work/${componentName}" />
    <delete dir="${build.dir}/classes/${componentName}"/>
    <delete dir="${build.dir}/work/${componentName}"/>
</target>

<target name="copy" depends="setenv"/>

<target name="compile" depends="copy">
  <echo message="Compiling test.wsdl.literal"/>

<!--
    remote version of the WSDL
    <wsdl2java url="http://www.perfectxml.net/WebServices/SalesRankNPrice/BookService.asmx?WSDL"
-->
    <wsdl2java url="${axis.home}/test/wsdl/literal/SalesRankNPrice.wsdl"
               output="${axis.home}/build/work"
               verbose="no"
               serverSide="no"
               testcase="no">
        <mapping namespace="http://www.PerfectXML.com/NETWebSvcs/BookService" package="test.wsdl.literal"/>
    </wsdl2java>

    <copy todir="${build.dir}/work/test/wsdl/literal" overwrite="yes">
      <fileset dir="${axis.home}/test/wsdl/literal">
        <include name="*TestCase.java"/>
        <include name="*Impl.java"/>
      </fileset>
    </copy>

    <javac srcdir="${build.dir}/work" destdir="${build.dest}" nowarn="${nowarn}" source="${source}" fork="${javac.fork}"
           debug="${debug}">
      <classpath refid="classpath" />
      <include name="test/wsdl/literal/*.java" />
    </javac>
</target>

<target name="run" >
  <antcall target="execute-Component" />
</target>

</project>


text:
package org.apache.spark.sql.execution.datasources

import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation
import org.apache.spark.sql.catalyst.catalog.CatalogTable
import org.apache.spark.sql.catalyst.expressions.{AttributeMap, AttributeReference}
import org.apache.spark.sql.catalyst.plans.logical.{LeafNode, LogicalPlan, Statistics}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.sources.BaseRelation
import org.apache.spark.util.Utils

/**
 * Used to link a [[BaseRelation]] in to a logical query plan.
 */
case class LogicalRelation(
    relation: BaseRelation,
    output: Seq[AttributeReference],
    catalogTable: Option[CatalogTable])
  extends LeafNode with MultiInstanceRelation {

  // Logical Relations are distinct if they have different output for the sake of transformations.
  override def equals(other: Any): Boolean = other match {
    case l @ LogicalRelation(otherRelation, _, _) => relation == otherRelation && output == l.output
    case _ => false
  }

  override def hashCode: Int = {
    com.google.common.base.Objects.hashCode(relation, output)
  }

  // Only care about relation when canonicalizing.
  override def preCanonicalized: LogicalPlan = copy(catalogTable = None)

  @transient override def computeStats(conf: SQLConf): Statistics = {
    catalogTable.flatMap(_.stats.map(_.toPlanStats(output))).getOrElse(
      Statistics(sizeInBytes = relation.sizeInBytes))
  }

  /** Used to lookup original attribute capitalization */
  val attributeMap: AttributeMap[AttributeReference] = AttributeMap(output.map(o => (o, o)))

  /**
   * Returns a new instance of this LogicalRelation. According to the semantics of
   * MultiInstanceRelation, this method returns a copy of this object with
   * unique expression ids. We respect the `expectedOutputAttributes` and create
   * new instances of attributes in it.
   */
  override def newInstance(): LogicalRelation = {
    this.copy(output = output.map(_.newInstance()))
  }

  override def refresh(): Unit = relation match {
    case fs: HadoopFsRelation => fs.location.refresh()
    case _ =>  // Do nothing.
  }

  override def simpleString: String = s"Relation[${Utils.truncatedString(output, ",")}] $relation"
}

object LogicalRelation {
  def apply(relation: BaseRelation): LogicalRelation =
    LogicalRelation(relation, relation.schema.toAttributes, None)

  def apply(relation: BaseRelation, table: CatalogTable): LogicalRelation =
    LogicalRelation(relation, relation.schema.toAttributes, Some(table))
}


text:
\hypertarget{namespace_p_e_a_r}{
\section{\-P\-E\-A\-R \-Namespace \-Reference}
\label{namespace_p_e_a_r}\index{\-P\-E\-A\-R@{\-P\-E\-A\-R}}
}

\subsection{\-Detailed \-Description}
\begin{DoxyAuthor}{\-Author}
\-Tomas \-V.\-V.\-Cox $<$\href{mailto:cox@idecnet.com}{\tt cox@idecnet.\-com}$>$

\-Hans \-Lellelid $<$\href{mailto:hans@velum.net}{\tt hans@velum.\-net}$>$

\-Bertrand \-Mansion $<$\href{mailto:bmansion@mamasam.com}{\tt bmansion@mamasam.\-com}$>$

\-Greg \-Beaver $<$\href{mailto:cellog@php.net}{\tt cellog@php.\-net}$>$
\end{DoxyAuthor}
\begin{DoxyCopyright}{\-Copyright}
1997-\/2007 \-The \-P\-H\-P \-Group  \href{http://opensource.org/licenses/bsd-license.php}{\tt http\-://opensource.\-org/licenses/bsd-\/license.\-php} \-New \-B\-S\-D \-License
\end{DoxyCopyright}
\begin{DoxyVersion}{\-Version}
\-Release\-: @ \hyperlink{}{\-Class available since \-Release 0.\-1.\-0 }
\end{DoxyVersion}