text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}

module Y2021.M01.D21.Solution where

import Y2021.M01.D20.Solution    -- for wineries

import Data.Aeson.WikiDatum (Name)

import Graph.Query
import Graph.JSON.Cypher
import qualified Graph.JSON.Cypher.Read.Rows as RR

{--
Okay, yesterday, we got some lat/longs, or, more precisely, some LongLats
for wineries via wikipedia. Today, we're going to compare this against the
wine graph database.

To set up the wine graph database, upload the CSV files from the neo4j
repository, following the instructions of the README there:

https://github.com/lju-lazarevic/wine

Now, that done, compare the wineries from the wikidata-set to the ones in the
wine graph database. What matches do we have?
--}

import Control.Arrow ((&&&))

import Data.Aeson

import Data.Map (Map)
import qualified Data.Map as Map

import Data.Maybe (mapMaybe)

import Data.Set (Set)
import qualified Data.Set as Set

{--
>>> readWineries (wineriesDir ++ wineriesJSON)
...
>>> let wikiwineries = it
>>> Map.size wikiwineries
610
--}

type Idx = Integer
type IxWineries = Map Name Idx

wineriesQuery :: Cypher
wineriesQuery = "MATCH (w:Winery) RETURN w.name AS winery, id(w) AS ix"

wineriesFromGraph :: Endpoint -> IO IxWineries
wineriesFromGraph url =
   Map.fromList . mapMaybe (list2tup . RR.row) . RR.justRows
       <$> getGraphResponse url [wineriesQuery]

list2tup :: [Value] -> Maybe (Name, Idx)
-- list2tup = sequence . (fromJSON1 . head &&& fromJSON1 . last) -- ugh
list2tup [a,b] = fromJSON1 a >>= \ma -> fromJSON1 b >>= return . (ma,)

fromJSON1 :: FromJSON a => Value -> Maybe a
fromJSON1 = reifySuccess . fromJSON

reifySuccess :: Result a -> Maybe a
reifySuccess (Success a) = Just a
reifySuccess _           = Nothing

{--
>>> graphEndpoint
...
>>> let url = it
>>> wineriesFromGraph url
fromList [("1+1=3",8695),("10 Knots",6989),("100 Percent Wine",10397),...]

How many wineries are in the graph database?

>>> let graphWineries = it
>>> Map.size graphWineries
16757

Okay, so there's quite a disparity between the two data sets.
--}

wineries2wineries :: Wineries -> IxWineries -> Set Name
wineries2wineries w = Map.keysSet . Map.intersection w

-- How many wineries are in the intersection?

{--
>>> let geowineries = wineries2wineries wikiwineries graphWineries
>>> Set.size geowineries
125
>>> geowineries
fromList ["Anglim","Ar\237nzano","Au Bon Climat","Beaulieu Vineyard",
          "Belden Barns","Bodega de Edgar","Bodegas Ateca","Bodegas Paso Robles",
          "Bosman Family Vineyards","Brecon Estate","Brochelle Vineyards",
          "Brown Estate","Casaj\250s","Castello di Amorosa","Chateau Chantal",
          "Chateau Grand Traverse","Chateau Montelena","Chateau St. Jean",
          "Chateau Ste. Michelle","Ch\226teau Ang\233lus",...]
--}

{-- BONUS -------------------------------------------------------

Are there wineries that should intersect, but don't? Which ones? How would
you fix this non-intersection (if it exists) to be in the intersection-set?

... actually, the winery's country helps quite a bit to answer this bonus,
so we will defer it until tomorrow.
--}

-- hmmm, shall we upload LongLat data to the graph? YES! ... but not today.


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape>
        <solid android:color="@color/white"/>
        <corners android:radius="10dp"/>
        <stroke android:width="1dp" android:color="@color/grey_300"/>
    </shape>
</item>
</selector>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>io.github.lhanson</groupId>
	<artifactId>possum</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>possum</name>
	<description>Possum - A trash-eating game engine</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<repositories>
		<repository>
			<!-- Service which allows us to use GitHub repos as dependencies -->
			<id>jitpack.io</id>
			<url>https://jitpack.io</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.codehaus.groovy</groupId>
			<artifactId>groovy</artifactId>
		</dependency>
		<dependency>
			<groupId>net.mikera</groupId>
			<artifactId>vectorz</artifactId>
			<version>0.65.0</version>
		</dependency>
		<dependency>
			<groupId>com.github.trystan</groupId>
			<artifactId>AsciiPanel</artifactId>
			<version>372dfbae987c64ff34d26fa1da0763b0f1c2bf37</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.spockframework</groupId>
			<artifactId>spock-core</artifactId>
			<version>1.1-groovy-2.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.spockframework</groupId>
			<artifactId>spock-spring</artifactId>
			<version>1.1-groovy-2.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib-nodep</artifactId>
			<version>3.2.5</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.codehaus.gmavenplus</groupId>
				<artifactId>gmavenplus-plugin</artifactId>
				<version>1.6</version>
				<executions>
					<execution>
						<goals>
							<goal>addSources</goal>
							<goal>addTestSources</goal>
							<goal>compile</goal>
							<goal>compileTests</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

</project>


text:
using System;
using System.Text.Json;
using Azure.Core;

namespace Azure.IoT.TimeSeriesInsights
{
    public partial class DateTimeRange : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("from");
            writer.WriteStringValue(From, "O");
            writer.WritePropertyName("to");
            writer.WriteStringValue(To, "O");
            writer.WriteEndObject();
        }

        internal static DateTimeRange DeserializeDateTimeRange(JsonElement element)
        {
            DateTimeOffset @from = default;
            DateTimeOffset to = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("from"))
                {
                    @from = property.Value.GetDateTimeOffset("O");
                    continue;
                }
                if (property.NameEquals("to"))
                {
                    to = property.Value.GetDateTimeOffset("O");
                    continue;
                }
            }
            return new DateTimeRange(@from, to);
        }
    }
}


text:
from django.db import models
from uuid import uuid4
import hashlib

def get_rand_hash():
    uid = uuid4()
    return hashlib.sha1(str(uid)).hexdigest()

class User(models.Model):
    username = models.CharField(max_length=200, unique=True)
    password = models.CharField(max_length=200)
    token = models.CharField(max_length=200, default=get_rand_hash)
    secret = models.CharField(max_length=200, default=get_rand_hash)

    def __unicode__(self):
        return self.username

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    favorite_color = models.CharField(max_length=20,
            help_text="English or hex")

    def __unicode__(self):
        return "User Profile for %s" % self.user.username


text:
class Pet(object):
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def getName(self):
        return self.name

    def getSpecies(self):
        return self.species

    def __str__(self):
        return "%s is a %s" % (self.name, self.species)


text:
แก้ไขข้อมูลเอกสาร

            <form class="form-horizontal touched-validate" name="editForm" novalidate>

                        ประเภท *
                        <select class="form-control" style="max-width:150px;margin-left:5px" id="fileType" name="fileType" ng-model="formData.file_type" required>
                            <option value="Application">Application</option>
                            <option value="Resume">Resume</option>
                            <option value="Certificate">Certificate</option>
                            <option value="Other">Other</option>
                        </select>

                        คำอธิบาย *เอกสารประเภทใบรับรองต้องกรอกหัวข้อด้วย(ไม่จำเป็น)
                        <input type="text" ng-class="{'ex-touched':formData.file_type!='Certificate'}" class="form-control" id="desc" name="desc" ng-model="formData.description" placeholder="คำอธิบาย" for="fileUpload"  style="max-width:250px;">

                        การตรวจสอบ*

                            Approve
                            Decline

                        ความคิดเห็น
                        <textarea  type="text" class="form-control text-med" cols="40" rows="2" ng-model="formData.comment" placeholder="Note" id="note" name="note" autocomplete="off"></textarea>

            </form>

    <button type="submit" class="btn btn-success" ng-click="validateForm(editForm)">บันทึก</button>
    <button type="button" class="btn btn-warning" ng-click="getDocumentData()">คืนค่า</button>
    <button class="btn btn-default" ng-click="ok()">ปิด</button>


text:
import pygame
import sys

class Controller:
    '''
    Objeto que se encarga del flujo del programa, del loop principal.

    Llama a la función dada un cierto número de veces por segundo implementando
    un loop. Además chequea si el juego está siendo cerrado por el usuario
    leyendo los eventos de ``pygame``.

    Se debe llamar a la función ``start()`` que comienza el loop principal.

    Examples
    --------
    ::

        def loop(dt):
            print("Tiempo entre frame actual y anterior en segundos:", dt)

        control = toledo.Controller(loop, 60)
        control.start()

        print("El juego se está cerrando")

    Parameters
    ----------
    loop : Callable[[float], [None]]
        Función a llamar varias veces por segundo. La función debe aceptar un
        argumento numérico que es el deltatime entre el frame actual y el
        anterior.
    fps : float
        Número de veces por segundo que se llamará a la función dada.
    '''

    def __init__(self, loop, fps):
        self._loop = loop
        self._fps = fps

        self._clock = pygame.time.Clock()

    def start(self):
        '''
        Comenzar a llamar a la función dada.

        Una vez que el programa entra a esta función, no continúa hasta que se
        cierre el juego. Entonces el código que esté después de esta llamada se
        ejecutará recién en el cierre del juego.

        Detecta cuando el jugador cierra el juego y termina la ejecución del
        loop.
        '''
        self._main_loop()

    def get_fps(self):
        '''
        Devuelve el parámetro ``fps`` dado en el constructor.

        Returns
        -------
        float
            FPS que se están respetando actualmente.
        '''
        return self._fps

    def _main_loop(self):

        while 1:
            # limitar FPS y al mismo tiempo obtener el deltatime (en ms) y
            # convertir a segundos
            dt = self._clock.tick(self._fps) / 1000

            for event in pygame.event.get():
                # si se apreto el boton de cerrar
                if event.type == pygame.QUIT:
                    sys.exit()

            self._loop(dt)


text:
ISMMING - API
=====================

Provide the APIs for ISMMING FO&BO

Compiling using Maven
---------------------
To compile the server using Maven type `mvn clean install` in the `api` directory.

To run the server type `java -jar target/api.jar`.

To visit the link `http://localhost:8080/api/category` in the browser.


text:
<?php

namespace Rsmakota\UtilityBundle\Date;

/**
 * Class DayIterator
 *
 * @package Rsmakota\UtilityBundle\Date
 */
class MonthIterator implements RangeIteratorInterface
{
    /**
     * @var \DateTime
     */
    private $start;
    /**
     * @var \DateTime
     */
    private $end;
    /**
     * @var \DateTime|null
     */
    private $current;
    /**
     * DayIterator constructor.
     *
     * @param \DateTime $start
     * @param \DateTime $end
     */
    public function __construct(\DateTime $start, \DateTime $end)
    {
        $this->start = clone $start;
        $this->end   = clone $end;
    }

    /**
     * @return \DateTime|false
     */
    public function next()
    {
        if (null == $this->current) {
            $this->current = clone $this->start;

            return clone $this->current;
        }

        if ($this->current->format('Ym') < $this->end->format('Ym')) {
            return clone $this->current->modify('+1 month');
        }

        return false;
    }

    /**
     * @return \DateTime|false
     */
    public function previous()
    {
        if ($this->current->format('U') > $this->start->format('U')) {
            return clone $this->current->modify('-1 month');
        }

        return false;
    }

    /**
     * @return \DateTime
     */
    public function current()
    {
        return clone $this->current();
    }

    /**
     * @return void
     */
    public function rewind()
    {
        $this->current = null;
    }
}


text:
/*!
    \file    standard_hid_core.c
    \brief   HID class driver

    \version 2020-08-01, V3.0.0, firmware for GD32F30x
*/

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

    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_transc.h"
#include "standard_hid_core.h"

#include <string.h>

#define USBD_VID                     0x28E9U
#define USBD_PID                     0x0380U

/* Note:it should use the C99 standard when compiling the below codes */
/* USB standard device descriptor */
usb_desc_dev hid_dev_desc =
{
    .header =
     {
         .bLength          = USB_DEV_DESC_LEN,
         .bDescriptorType  = USB_DESCTYPE_DEV
     },
#ifdef LPM_ENABLED
    .bcdUSB                = 0x0201U,
#else
    .bcdUSB                = 0x0200U,
#endif /* LPM_ENABLED */
    .bDeviceClass          = 0x00U,
    .bDeviceSubClass       = 0x00U,
    .bDeviceProtocol       = 0x00U,
    .bMaxPacketSize0       = USBD_EP0_MAX_SIZE,
    .idVendor              = USBD_VID,
    .idProduct             = USBD_PID,
    .bcdDevice             = 0x0100U,
    .iManufacturer         = STR_IDX_MFC,
    .iProduct              = STR_IDX_PRODUCT,
    .iSerialNumber         = STR_IDX_SERIAL,
    .bNumberConfigurations = USBD_CFG_MAX_NUM
};

#ifdef LPM_ENABLED

/* BOS descriptor */
uint8_t USBD_BOSDesc[USB_BOS_DESC_LEN] =
{
    0x05,
    USB_DESCTYPE_BOS,
    0x0C,
    0x00,
    0x01,  /* 1 device capability descriptor */

    /* device capability*/
    0x07,
    USB_DEVICE_CAPABITY,
    0x02,
    0x06,  /* LPM capability bit set */
    0x00,
    0x00,
    0x00
};

#endif /* LPM_ENABLED */

usb_hid_desc_config_set hid_config_desc =
{
    .config =
    {
        .header =
         {
             .bLength         = sizeof(usb_desc_config),
             .bDescriptorType = USB_DESCTYPE_CONFIG
         },
        .wTotalLength         = USB_HID_CONFIG_DESC_LEN,
        .bNumInterfaces       = 0x01U,
        .bConfigurationValue  = 0x01U,
        .iConfiguration       = 0x00U,
        .bmAttributes         = 0xA0U,
        .bMaxPower            = 0x32U
    },

    .hid_itf =
    {
        .header =
         {
             .bLength         = sizeof(usb_desc_itf),
             .bDescriptorType = USB_DESCTYPE_ITF
         },
        .bInterfaceNumber     = 0x00U,
        .bAlternateSetting    = 0x00U,
        .bNumEndpoints        = 0x01U,
        .bInterfaceClass      = USB_HID_CLASS,
        .bInterfaceSubClass   = USB_HID_SUBCLASS_BOOT_ITF,
        .bInterfaceProtocol   = USB_HID_PROTOCOL_KEYBOARD,
        .iInterface           = 0x00U
    },

    .hid_vendor =
    {
        .header =
         {
             .bLength         = sizeof(usb_desc_hid),
             .bDescriptorType = USB_DESCTYPE_HID
         },
        .bcdHID               = 0x0111U,
        .bCountryCode         = 0x00U,
        .bNumDescriptors      = 0x01U,
        .bDescriptorType      = USB_DESCTYPE_REPORT,
        .wDescriptorLength    = USB_HID_REPORT_DESC_LEN,
    },

    .hid_epin =
    {
        .header =
         {
             .bLength         = sizeof(usb_desc_ep),
             .bDescriptorType = USB_DESCTYPE_EP
         },
        .bEndpointAddress     = HID_IN_EP,
        .bmAttributes         = USB_EP_ATTR_INT,
        .wMaxPacketSize       = HID_IN_PACKET,
        .bInterval            = 0x40U
    }
};

/* USB language ID Descriptor */
static usb_desc_LANGID usbd_language_id_desc =
{
    .header =
     {
         .bLength         = sizeof(usb_desc_LANGID),
         .bDescriptorType = USB_DESCTYPE_STR
     },
    .wLANGID              = ENG_LANGID
};

/* USB manufacture string */
static usb_desc_str manufacturer_string =
{
    .header =
     {
         .bLength         = USB_STRING_LEN(10U),
         .bDescriptorType = USB_DESCTYPE_STR,
     },
    .unicode_string = {'G', 'i', 'g', 'a', 'D', 'e', 'v', 'i', 'c', 'e'}
};

/* USB product string */
static usb_desc_str product_string =
{
    .header =
     {
         .bLength         = USB_STRING_LEN(17U),
         .bDescriptorType = USB_DESCTYPE_STR,
     },
    .unicode_string = {'G', 'D', '3', '2', '-', 'U', 'S', 'B', '_', 'K', 'e', 'y', 'b', 'o', 'a', 'r', 'd'}
};

/* USBD serial string */
static usb_desc_str serial_string =
{
    .header =
     {
         .bLength         = USB_STRING_LEN(12U),
         .bDescriptorType = USB_DESCTYPE_STR,
     }
};

uint8_t* usbd_hid_strings[] =
{
    [STR_IDX_LANGID]  = (uint8_t *)&usbd_language_id_desc,
    [STR_IDX_MFC]     = (uint8_t *)&manufacturer_string,
    [STR_IDX_PRODUCT] = (uint8_t *)&product_string,
    [STR_IDX_SERIAL]  = (uint8_t *)&serial_string
};

usb_desc hid_desc = {
#ifdef LPM_ENABLED
    .bos_desc    = (uint8_t *)&USBD_BOSDesc,
#endif /* LPM_ENABLED */
    .dev_desc    = (uint8_t *)&hid_dev_desc,
    .config_desc = (uint8_t *)&hid_config_desc,
    .strings     = usbd_hid_strings
};

/* local function prototypes ('static') */
static uint8_t hid_init            (usb_dev *udev, uint8_t config_index);
static uint8_t hid_deinit          (usb_dev *udev, uint8_t config_index);
static uint8_t hid_req_handler     (usb_dev *udev, usb_req *req);
static void hid_data_in_handler    (usb_dev *udev, uint8_t ep_num);

usb_class hid_class = {
    .init            = hid_init,
    .deinit          = hid_deinit,
    .req_process     = hid_req_handler,
    .data_in         = hid_data_in_handler
};

const uint8_t hid_report_desc[USB_HID_REPORT_DESC_LEN] =
{
    0x05, 0x01,  /* USAGE_PAGE (Generic Desktop) */
    0x09, 0x06,  /* USAGE (Keyboard) */
    0xa1, 0x01,  /* COLLECTION (Application) */

    0x05, 0x07,  /* USAGE_PAGE (Keyboard/Keypad) */
    0x19, 0xe0,  /* USAGE_MINIMUM (Keyboard LeftControl) */
    0x29, 0xe7,  /* USAGE_MAXIMUM (Keyboard Right GUI) */
    0x15, 0x00,  /* LOGICAL_MINIMUM (0) */
    0x25, 0x01,  /* LOGICAL_MAXIMUM (1) */
    0x95, 0x08,  /* REPORT_COUNT (8) */
    0x75, 0x01,  /* REPORT_SIZE (1) */
    0x81, 0x02,  /* INPUT (Data,Var,Abs) */

    0x95, 0x01,  /* REPORT_COUNT (1) */
    0x75, 0x08,  /* REPORT_SIZE (8) */
    0x81, 0x03,  /* INPUT (Cnst,Var,Abs) */

    0x95, 0x06,  /* REPORT_COUNT (6) */
    0x75, 0x08,  /* REPORT_SIZE (8) */
    0x15, 0x00,  /* LOGICAL_MINIMUM (0) */
    0x26, 0xFF, 0x00,  /* LOGICAL_MAXIMUM (255) */
    0x05, 0x07,  /* USAGE_PAGE (Keyboard/Keypad) */
    0x19, 0x00,  /* USAGE_MINIMUM (Reserved (no event indicated)) */
    0x29, 0x65,  /* USAGE_MAXIMUM (Keyboard Application) */
    0x81, 0x00,  /* INPUT (Data,Ary,Abs) */

    0xc0         /* END_COLLECTION */
};

/*!
    \brief      register HID interface operation functions
    \param[in]  udev: pointer to USB device instance
    \param[in]  hid_fop: HID operation functions structure
    \param[out] none
    \retval     USB device operation status
*/
uint8_t hid_itfop_register (usb_dev *udev, hid_fop_handler *hid_fop)
{
    if (NULL != hid_fop) {
        udev->user_data = (void *)hid_fop;

        return USBD_OK;
    }

    return USBD_FAIL;
}

/*!
    \brief      send keyboard report
    \param[in]  udev: pointer to USB device instance
    \param[in]  report: pointer to HID report
    \param[in]  len: data length
    \param[out] none
    \retval     USB device operation status
*/
uint8_t hid_report_send (usb_dev *udev, uint8_t *report, uint16_t len)
{
    standard_hid_handler *hid = (standard_hid_handler *)udev->class_data[USBD_HID_INTERFACE];

    /* check if USB is configured */
    hid->prev_transfer_complete = 0U;

    usbd_ep_send(udev, HID_IN_EP, report, len);

    return USBD_OK;
}

/*!
    \brief      initialize the HID device
    \param[in]  udev: pointer to USB device instance
    \param[in]  config_index: configuration index
    \param[out] none
    \retval     USB device operation status
*/
static uint8_t hid_init (usb_dev *udev, uint8_t config_index)
{
    static standard_hid_handler hid_handler;

    memset((void *)&hid_handler, 0, sizeof(standard_hid_handler));

    /* initialize Tx endpoint */
    usbd_ep_init(udev, EP_BUF_SNG, INT_TX_ADDR, &(hid_config_desc.hid_epin));

    udev->ep_transc[EP_ID(HID_IN_EP)][TRANSC_IN] = hid_class.data_in;

    hid_handler.prev_transfer_complete = 1U;

    udev->class_data[USBD_HID_INTERFACE] = (void *)&hid_handler;

    if (NULL != udev->user_data) {
        ((hid_fop_handler *)udev->user_data)->hid_itf_config();
    }

    return USBD_OK;
}

/*!
    \brief      de-initialize the HID device
    \param[in]  udev: pointer to USB device instance
    \param[in]  config_index: configuration index
    \param[out] none
    \retval     USB device operation status
*/
static uint8_t hid_deinit (usb_dev *udev, uint8_t config_index)
{
    /* deinitialize HID endpoints */
    usbd_ep_deinit (udev, HID_IN_EP);

    return USBD_OK;
}

/*!
    \brief      handle the HID class-specific requests
    \param[in]  udev: pointer to USB device instance
    \param[in]  req: device class-specific request
    \param[out] none
    \retval     USB device operation status
*/
static uint8_t hid_req_handler (usb_dev *udev, usb_req *req)
{
    uint8_t status = REQ_NOTSUPP;

    standard_hid_handler *hid = (standard_hid_handler *)udev->class_data[USBD_HID_INTERFACE];

    switch (req->bRequest) {
    case GET_REPORT:
        /* no use for this driver */
        break;

    case GET_IDLE:
        usb_transc_config(&udev->transc_in[0U], (uint8_t *)&hid->idle_state, 1U, 0U);

        status = REQ_SUPP;
        break;

    case GET_PROTOCOL:
        usb_transc_config(&udev->transc_in[0U], (uint8_t *)&hid->protocol, 1U, 0U);

        status = REQ_SUPP;
        break;

    case SET_REPORT:
        /* no use for this driver */
        break;

    case SET_IDLE:
        hid->idle_state = (uint8_t)(req->wValue >> 8);

        status = REQ_SUPP;
        break;

    case SET_PROTOCOL:
        hid->protocol = (uint8_t)(req->wValue);

        status = REQ_SUPP;
        break;

    case USB_GET_DESCRIPTOR:
        if (USB_DESCTYPE_REPORT == (req->wValue >> 8)) {
            usb_transc_config(&udev->transc_in[0U],
                              (uint8_t *)hid_report_desc,
                              USB_MIN(USB_HID_REPORT_DESC_LEN, req->wLength),
                              0U);

            status = REQ_SUPP;
        } else if (USB_DESCTYPE_HID == (req->wValue >> 8U)) {
            usb_transc_config(&udev->transc_in[0U],
                              (uint8_t *)(&(hid_config_desc.hid_vendor)),
                              USB_MIN(9U, req->wLength),
                              0U);
        }
        break;

    default:
        break;
    }

    return status;
}

/*!
    \brief      handle data stage in DATA IN transaction
    \param[in]  udev: pointer to USB device instance
    \param[in]  ep_num: endpoint identifier
    \param[out] none
    \retval     none
*/
static void hid_data_in_handler (usb_dev *udev, uint8_t ep_num)
{
    standard_hid_handler *hid = (standard_hid_handler *)udev->class_data[USBD_HID_INTERFACE];

    if (hid->data[2]) {
        hid->data[2] = 0x00U;

        usbd_ep_send(udev, HID_IN_EP, hid->data, HID_IN_PACKET);
    } else {
        hid->prev_transfer_complete = 1U;
    }
}


text:
#ifndef     __FTPixmapGlyph__
#define     __FTPixmapGlyph__

#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H

#include "FTGL.h"
#include "FTGlyph.h"

/**
 * FTPixmapGlyph is a specialisation of FTGlyph for creating pixmaps.
 *
 * @see FTGlyphContainer
 *
 */
class  FTGL_EXPORT FTPixmapGlyph : public FTGlyph
{
    public:
        /**
         * Constructor
         *
         * @param glyph The Freetype glyph to be processed
         */
        FTPixmapGlyph( FT_GlyphSlot glyph);

        /**
         * Destructor
         */
        virtual ~FTPixmapGlyph();

        /**
         * Renders this glyph at the current pen position.
         *
         * @param pen   The current pen position.
         * @return      The advance distance for this glyph.
         */
        virtual const FTPoint& Render( const FTPoint& pen);

        // attributes

    private:
        /**
         * The width of the glyph 'image'
         */
        int destWidth;

        /**
         * The height of the glyph 'image'
         */
        int destHeight;

        /**
         * Vector from the pen position to the topleft corner of the pixmap
         */
        FTPoint pos;

        /**
         * Pointer to the 'image' data
         */
        unsigned char* data;

};

#endif  //  __FTPixmapGlyph__


text:
package org.apache.polygene.library.sql.generator.grammar.query;

import org.apache.polygene.library.sql.generator.Typeable;
import org.apache.polygene.library.sql.generator.grammar.common.ColumnNameList;

/**
 * This syntax element represents the alias for a table. Table alias may have additional list of column aliases.
 *
 *
 */
public interface TableAlias
    extends Typeable<TableAlias>
{

    /**
     * Returns an alias for a table name.
     *
     * @return The alias for the table name.
     */
    String getTableAlias();

    /**
     * Returns aliases for columns in the original table.
     *
     * @return Aliases for columns in the original table. May be {@code null}.
     */
    ColumnNameList getColumnAliases();
}


text:
package tjs.tuneramblr.util;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

import org.apache.http.client.utils.URIUtils;

import tjs.tuneramblr.meta.model.CheckinType;
import tjs.tuneramblr.meta.model.Weather;
import android.location.Location;

/**
 * URL helper
 */
public class TuneramblrUrlHelper {

	private static final String PROTOCOL_HTTP = "http";
	// private static final String PROTOCOL_HTTP_SSL = "https";

	private static final Integer NO_PORT = -1;
	// private static final Integer DEFAULT_HTTP = 80;

	private static final String QUERY_SEP = "&";

	/* the base songmap URL */
	private static final String TUNERAMBLR_BASE_URL = "tuneramblr.herokuapp.com";

	/* some other important locations (relative) */
	private static final String TUNERAMBLR_ADD_SONG_URL = "/mobile/songs/add";
	private static final String TUNERAMBLR_LOGIN_URL = "/mobile/login";

	private static TuneramblrUrlHelper URL_HELPER = null;

	private TuneramblrUrlHelper() {
		// nadda
	}

	/**
	 * retrieves the lone instance of the TuneramblrUrlHelper
	 *
	 * @return the lone instance of this class
	 */
	public static TuneramblrUrlHelper getInstance() {
		if (URL_HELPER == null) {
			URL_HELPER = new TuneramblrUrlHelper();
		}
		return URL_HELPER;
	}

	/**
	 * builds the stem of the add song URL. this includes the protocol, port,
	 * base, and location. note: this URL does NOT contain a query string.
	 *
	 * @return returns a string representing tuneramblr add song URL
	 */
	public URI getAddSongHttpPostUrl() {
		URI builtUrl = null;
		try {
			builtUrl = URIUtils.createURI(PROTOCOL_HTTP, TUNERAMBLR_BASE_URL,
					NO_PORT, TUNERAMBLR_ADD_SONG_URL, null, null);
		} catch (URISyntaxException e) {
			builtUrl = null;
		}

		return builtUrl;
	}

	/**
	 * builds the mobile login URL.this includes the protocol, port, base, and
	 * location. note: this URL does NOT contain a query string.
	 *
	 * @return returns a string representing tuneramblr mobile login URL
	 */
	public URI getLoginHttpPostUrl() {
		URI builtUrl = null;
		try {
			builtUrl = URIUtils.createURI(PROTOCOL_HTTP, TUNERAMBLR_BASE_URL,
					NO_PORT, TUNERAMBLR_LOGIN_URL, null, null);
		} catch (URISyntaxException e) {
			builtUrl = null;
		}

		return builtUrl;
	}

	/**
	 * Builds an "add" song URI given the set of desired parameters.
	 *
	 * @param userLocation
	 *            the user's current location (i.e. where the track was
	 *            recorded)
	 * @param trackName
	 *            the name of the track being recorded
	 * @param artist
	 *            the artist of the track
	 * @param album
	 *            the album on which the track appears
	 * @param localWeather
	 *            the weather when the track was recorded
	 * @param userDef
	 *            any user defined tags to be associated with the track
	 * @param username
	 *            the username of the user
	 * @param password
	 *            the password of the user
	 * @param img
	 *            a string representation of the image that is being recorded
	 *            against the track
	 * @param checkinType
	 *            the type of the checking user/passive (skipped track, listened
	 *            to the whole thing, etc.)
	 * @return a valid URI for adding a song with the supplied parameters
	 */
	public URI buildAddSongHttpUrl(Location userLocation, String trackName,
			String artist, String album, Weather localWeather,
			String[] userDef, String username, String password, String img,
			long currentTime, CheckinType checkinType) {
		URI builtUrl = null;

		String queryString = buildAddSongQueryString(userLocation, trackName,
				artist, album, localWeather, userDef, username, password, img,
				currentTime, checkinType);

		try {
			builtUrl = URIUtils.createURI(PROTOCOL_HTTP, TUNERAMBLR_BASE_URL,
					NO_PORT, TUNERAMBLR_ADD_SONG_URL, queryString, null);
		} catch (URISyntaxException e) {
			// this shouldn't happen since I am building it,
			// but if it does, just null out the builtUrl and
			// return that...just need to be sure to check for
			// that on the other side
			builtUrl = null;
		}

		return builtUrl;
	}

	/**
	 * Builds the query string portion of the add song URL
	 *
	 * @param userLocation
	 *            the user's current location (i.e. where the track was
	 *            recorded)
	 * @param trackName
	 *            the name of the track being recorded
	 * @param artist
	 *            the artist of the track
	 * @param album
	 *            the album on which the track appears
	 * @param localWeather
	 *            the weather when the track was recorded
	 * @param userDef
	 *            any user defined tags to be associated with the track
	 * @param username
	 *            the username of the user
	 * @param password
	 *            the password of the user
	 * @param img
	 *            a string representation of the image that is being recorded
	 *            against the track
	 * @param checkinType
	 *            the type of the checking user/passive (skipped track, listened
	 *            to the whole thing, etc.)
	 * @return a query string representing the set of supplied parameters
	 */
	public String buildAddSongQueryString(Location userLocation,
			String trackName, String artist, String album,
			Weather localWeather, String[] userDef, String username,
			String password, String img, long currentTime,
			CheckinType checkinType) {

		// time to build the query string
		StringBuilder queryBuilder = new StringBuilder();

		boolean last = true;
		addQueryPair(queryBuilder, "lat",
				String.valueOf(userLocation.getLatitude()), !last);
		addQueryPair(queryBuilder, "lng",
				String.valueOf(userLocation.getLongitude()), !last);
		addQueryPair(queryBuilder, "title", trackName, !last);
		addQueryPair(queryBuilder, "artist", artist, !last);
		addQueryPair(queryBuilder, "album", album, !last);
		addQueryPair(queryBuilder, "weather", localWeather.toString(), !last);

		addQueryPair(queryBuilder, "userdef", buildUserDefParam(userDef), !last);

		addQueryPair(queryBuilder, "username", username, !last);
		addQueryPair(queryBuilder, "password", password, !last);

		addQueryPair(queryBuilder, "img", img, !last);
		addQueryPair(queryBuilder, "tstamp", String.valueOf(currentTime), !last);
		addQueryPair(queryBuilder, "ctype", checkinType.toValue(), last);

		return queryBuilder.toString();
	}

	/**
	 * Builds a query string for the login request
	 *
	 * @param username
	 *            the username of the user
	 * @param password
	 *            the password of the user
	 * @return
	 */
	public String buildLoginQueryString(String username, String password) {
		StringBuilder queryBuilder = new StringBuilder();
		boolean last = true;

		addQueryPair(queryBuilder, "username", username, !last);
		addQueryPair(queryBuilder, "password", password, last);

		return queryBuilder.toString();
	}

	/*
	 * GENERAL HELPER FUNCTIONS
	 */
	private void addQueryPair(StringBuilder builder, String key, String value,
			boolean last) {
		// only add the parameter if the value is NOT null. a null value means
		// we could not get the parameter (if it is an automatically acquired
		// parameter) or the user did not enter it, if it is optional. either
		// way, we do not want to include it in the query string.
		if (value != null) {
			builder.append(key);
			builder.append("=");
			builder.append(URLEncoder.encode(value));
			if (!last) {
				builder.append(QUERY_SEP);
			}
		}

	}

	private String buildUserDefParam(String[] userDef) {
		String userDefStr = "";
		int idx = 0;
		int lastIdx = userDef.length - 1;
		for (String val : userDef) {
			userDefStr += (idx < lastIdx) ? val + "," : val;
			idx++;
		}
		return userDefStr;
	}
}


text:
using System.Linq;
using System.Collections.Generic;
using System;
using Machine.Specifications;
using NOtherLookup;
using Tests.Utils;

namespace Tests
{
    [Subject("IEnumerable<IGrouping>.ToLookup")]
    public class When_converting_IEnumerable_of_IGrouping_to_lookup
    {
        Establish context = () =>
            grouping = Lookup.Builder
                .WithKey("a", new[] { 1, 3 })
                .WithKey("b", new[] { 2, 4 }).Build();

        Because of = () =>
            lookup = grouping.ToLookup();

        It should_create_lookup_with_all_keys = () =>
            lookup.Count.ShouldEqual(2);

        It should_have_valid_IEnumerables_inside = () =>
        {
            lookup["a"].ShouldContainExactly(1, 3);
            lookup["b"].ShouldContainExactly(2, 4);
        };

        private static IEnumerable<IGrouping<string, int>> grouping;
        private static ILookup<string, int> lookup;
    }

    [Subject("IEnumerable<IGrouping>.ToLookup")]
    public class When_converting_IEnumerable_of_IGrouping_to_lookup_with_comparer
    {
        Establish context = () =>
            grouping = Lookup.Builder
                .WithKey("a", new[] { 1, 3 })
                .WithKey("b", new[] { 2, 4 }).Build();

        Because of = () =>
            lookup = grouping.ToLookup(new StringLengthComparer());

        It should_create_lookup_with_all_keys_respecting_comparer = () =>
            lookup.Count.ShouldEqual(1);

        It should_have_valid_IEnumerables_inside_with_all_elements_for_key_respecting_comparer = () =>
        {
            lookup["a"].ShouldContainExactly(1, 3, 2, 4);
            lookup["b"].ShouldContainExactly(1, 3, 2, 4);
        };

        private static IEnumerable<IGrouping<string, int>> grouping;
        private static ILookup<string, int> lookup;
    }

    [Subject("IEnumerable<IGrouping>.ToLookup")]
    public class When_converting_null_IEnumerable_of_IGrouping_to_lookup
    {
        Establish context = () =>
            grouping = null;

        Because of = () =>
            exception = Catch.Exception(() => grouping.ToLookup());

        It should_throw_ArgumentNullException = () =>
            exception.ShouldBeOfType<ArgumentNullException>();

        private static IEnumerable<IGrouping<string, int>> grouping;
        private static Exception exception;
    }
}


text:
package temptable

import (
	"context"
	"testing"

	"github.com/pingcap/tidb/infoschema"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/parser/model"
	"github.com/pingcap/tidb/parser/mysql"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/store/mockstore"
	"github.com/pingcap/tidb/tablecodec"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/mock"
	"github.com/stretchr/testify/require"
)

func createTestSuite(t *testing.T) (sessionctx.Context, *temporaryTableDDL, func()) {
	store, err := mockstore.NewMockStore()
	require.NoError(t, err)

	sctx := mock.NewContext()
	sctx.Store = store
	ddl := GetTemporaryTableDDL(sctx).(*temporaryTableDDL)
	clean := func() {
		require.NoError(t, store.Close())
	}

	return sctx, ddl, clean
}

func TestAddLocalTemporaryTable(t *testing.T) {
	sctx, ddl, clean := createTestSuite(t)
	defer clean()

	sessVars := sctx.GetSessionVars()

	db1 := newMockSchema("db1")
	db2 := newMockSchema("db2")
	tbl1 := newMockTable("t1")
	tbl2 := newMockTable("t2")

	require.Nil(t, sessVars.LocalTemporaryTables)
	require.Nil(t, sessVars.TemporaryTableData)

	// insert t1
	err := ddl.CreateLocalTemporaryTable(db1, tbl1)
	require.NoError(t, err)
	require.NotNil(t, sessVars.LocalTemporaryTables)
	require.NotNil(t, sessVars.TemporaryTableData)
	require.Equal(t, int64(1), tbl1.ID)
	got, exists := sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1"))
	require.True(t, exists)
	require.Equal(t, got.Meta(), tbl1)

	// insert t2 with data
	err = ddl.CreateLocalTemporaryTable(db1, tbl2)
	require.NoError(t, err)
	require.Equal(t, int64(2), tbl2.ID)
	got, exists = sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t2"))
	require.True(t, exists)
	require.Equal(t, got.Meta(), tbl2)

	// should success to set a key for a table
	k := tablecodec.EncodeRowKeyWithHandle(tbl1.ID, kv.IntHandle(1))
	err = sessVars.TemporaryTableData.SetTableKey(tbl1.ID, k, []byte("v1"))
	require.NoError(t, err)

	val, err := sessVars.TemporaryTableData.Get(context.Background(), k)
	require.NoError(t, err)
	require.Equal(t, []byte("v1"), val)

	// insert dup table
	tbl1x := newMockTable("t1")
	err = ddl.CreateLocalTemporaryTable(db1, tbl1x)
	require.True(t, infoschema.ErrTableExists.Equal(err))
	got, exists = sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1"))
	require.True(t, exists)
	require.Equal(t, got.Meta(), tbl1)

	// insert should be success for same table name in different db
	err = ddl.CreateLocalTemporaryTable(db2, tbl1x)
	require.NoError(t, err)
	got, exists = sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables).TableByName(model.NewCIStr("db2"), model.NewCIStr("t1"))
	require.Equal(t, int64(4), got.Meta().ID)
	require.True(t, exists)
	require.Equal(t, got.Meta(), tbl1x)

	// tbl1 still exist
	got, exists = sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1"))
	require.True(t, exists)
	require.Equal(t, got.Meta(), tbl1)
}

func TestRemoveLocalTemporaryTable(t *testing.T) {
	sctx, ddl, clean := createTestSuite(t)
	defer clean()

	sessVars := sctx.GetSessionVars()
	db1 := newMockSchema("db1")

	// remove when empty
	err := ddl.DropLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t1"))
	require.True(t, infoschema.ErrTableNotExists.Equal(err))

	// add one table
	tbl1 := newMockTable("t1")
	err = ddl.CreateLocalTemporaryTable(db1, tbl1)
	require.NoError(t, err)
	require.Equal(t, int64(1), tbl1.ID)
	k := tablecodec.EncodeRowKeyWithHandle(1, kv.IntHandle(1))
	err = sessVars.TemporaryTableData.SetTableKey(tbl1.ID, k, []byte("v1"))
	require.NoError(t, err)

	// remove failed when table not found
	err = ddl.DropLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t2"))
	require.True(t, infoschema.ErrTableNotExists.Equal(err))

	// remove failed when table not found (same table name in different db)
	err = ddl.DropLocalTemporaryTable(model.NewCIStr("db2"), model.NewCIStr("t1"))
	require.True(t, infoschema.ErrTableNotExists.Equal(err))

	// check failed remove should have no effects
	got, exists := sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables).TableByID(tbl1.ID)
	require.True(t, exists)
	require.Equal(t, got.Meta(), tbl1)
	val, err := sessVars.TemporaryTableData.Get(context.Background(), k)
	require.NoError(t, err)
	require.Equal(t, []byte("v1"), val)

	// remove success
	err = ddl.DropLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t1"))
	require.NoError(t, err)
	got, exists = sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1"))
	require.Nil(t, got)
	require.False(t, exists)
	val, err = sessVars.TemporaryTableData.Get(context.Background(), k)
	require.NoError(t, err)
	require.Equal(t, []byte{}, val)
}

func TestTruncateLocalTemporaryTable(t *testing.T) {
	sctx, ddl, clean := createTestSuite(t)
	defer clean()

	sessVars := sctx.GetSessionVars()
	db1 := newMockSchema("db1")

	// truncate when empty
	err := ddl.TruncateLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t1"))
	require.True(t, infoschema.ErrTableNotExists.Equal(err))
	require.Equal(t, 0, sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables).Count())
	require.Nil(t, sessVars.TemporaryTableData)

	// add one table
	tbl1 := newMockTable("t1")
	err = ddl.CreateLocalTemporaryTable(db1, tbl1)
	require.Equal(t, int64(1), tbl1.ID)
	require.NoError(t, err)
	k := tablecodec.EncodeRowKeyWithHandle(1, kv.IntHandle(1))
	err = sessVars.TemporaryTableData.SetTableKey(1, k, []byte("v1"))
	require.NoError(t, err)

	// truncate failed for table not exist
	err = ddl.TruncateLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t2"))
	require.True(t, infoschema.ErrTableNotExists.Equal(err))
	err = ddl.TruncateLocalTemporaryTable(model.NewCIStr("db2"), model.NewCIStr("t1"))
	require.True(t, infoschema.ErrTableNotExists.Equal(err))

	// check failed should have no effects
	got, exists := sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1"))
	require.True(t, exists)
	require.Equal(t, got.Meta(), tbl1)
	val, err := sessVars.TemporaryTableData.Get(context.Background(), k)
	require.NoError(t, err)
	require.Equal(t, []byte("v1"), val)

	// insert a new tbl
	tbl2 := newMockTable("t2")
	err = ddl.CreateLocalTemporaryTable(db1, tbl2)
	require.Equal(t, int64(2), tbl2.ID)
	require.NoError(t, err)
	k2 := tablecodec.EncodeRowKeyWithHandle(2, kv.IntHandle(1))
	err = sessVars.TemporaryTableData.SetTableKey(2, k2, []byte("v2"))
	require.NoError(t, err)

	// truncate success
	err = ddl.TruncateLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t1"))
	require.NoError(t, err)
	got, exists = sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1"))
	require.True(t, exists)
	require.NotEqual(t, got.Meta(), tbl1)
	require.Equal(t, int64(3), got.Meta().ID)
	val, err = sessVars.TemporaryTableData.Get(context.Background(), k)
	require.NoError(t, err)
	require.Equal(t, []byte{}, val)

	// truncate just effect its own data
	val, err = sessVars.TemporaryTableData.Get(context.Background(), k2)
	require.NoError(t, err)
	require.Equal(t, []byte("v2"), val)
}

func newMockTable(tblName string) *model.TableInfo {
	c1 := &model.ColumnInfo{ID: 1, Name: model.NewCIStr("c1"), State: model.StatePublic, Offset: 0, FieldType: *types.NewFieldType(mysql.TypeLonglong)}
	c2 := &model.ColumnInfo{ID: 2, Name: model.NewCIStr("c2"), State: model.StatePublic, Offset: 1, FieldType: *types.NewFieldType(mysql.TypeVarchar)}

	tblInfo := &model.TableInfo{Name: model.NewCIStr(tblName), Columns: []*model.ColumnInfo{c1, c2}, PKIsHandle: true}
	return tblInfo
}

func newMockSchema(schemaName string) *model.DBInfo {
	return &model.DBInfo{ID: 10, Name: model.NewCIStr(schemaName), State: model.StatePublic}
}


text:
package de.hub.clickwatch.analysis.results;

/**
 *
 * A representation of the model object 'Box And Whiskers'.
 *
 *
 *
 * @see de.hub.clickwatch.analysis.results.ResultsPackage#getBoxAndWhiskers()
 * @model
 * @generated
 */
public interface BoxAndWhiskers extends ChartType {
} // BoxAndWhiskers


text:
<?php
namespace inklabs\kommerce\EntityDTO;

use DateTime;

class UserDTO
{
    use IdDTOTrait, TimeDTOTrait;

    /** @var string */
    public $externalId;

    /** @var string */
    public $email;

    /** @var string */
    public $firstName;

    /** @var string */
    public $lastName;

    /** @var int */
    public $totalLogins;

    /** @var DateTime */
    public $lastLogin;

    /** @var UserStatusTypeDTO */
    public $status;

    /** @var UserRoleDTO[] */
    public $userRoles = [];

    /** @var UserTokenDTO[] */
    public $userTokens = [];

    /** @var UserLoginDTO[] */
    public $userLogins = [];
}


text:
import {tid} from '../support/commands';
import {Landing, Room} from '../elements/elements';

beforeEach(function () {
  cy.fixture('users/default.json').then((data) => (this.user = data));
});

it('load page with mobile screen dimensions and toggle menues in room', function () {
  cy.viewport('iphone-x');
  cy.visit('/');

  cy.clearLocalStorage(); // this should not be needed.  Cypress promises to clear all local storage in between tests.

  Landing.joinButton().click();
  Landing.usernameField().type(this.user.username);
  Landing.joinButton().click();

  cy.get(tid('backlogToggle')).click(); // show backlog

  Room.Backlog.StoryAddForm.titleField().type('This is visibile. I could add a story...');

  cy.get(tid('settingsToggle')).click(); // show settings, will hide backlog

  cy.get(tid('usernameInput')).type('{selectall}can type in here');

  cy.get(tid('actionLogToggle')).click(); // show log (actions)  will hide settings

  cy.wait(200);

  cy.get(tid('actionLogToggle')).click(); // hide log again
});


text:
The logout method logs the user out and destroys all Sentry sessions / cookies for the user.

This method does **not** fail or throw any Exceptions if there is no user logged in.

----------

#### Example

	// Logs the user out
	Sentry::logout();


text:
var CLI = require('../lib/clui.js'),
    clear = CLI.Clear,
    clc = require('cli-color');

var Line          = CLI.Line,
    LineBuffer    = CLI.LineBuffer;

var drawTimeout;

function draw() {
  clear()

  var xLocation = Math.floor(process.stdout.columns / 2) - 35;
  if (xLocation < 0)
    xLocation = 0;

  var yLocation = Math.floor(process.stdout.rows / 2) - 10;
  if (yLocation < 0)
    yLocation = 0;

  var outputBuffer = new LineBuffer({
    x: xLocation,
    y: yLocation,
    width: 71,
    height: 21
  });

  var message = new Line(outputBuffer)
    .column('Press Control+C to quit. Try resizing terminal.', 71, [clc.green])
    .fill()
    .store();

  var blankLine = new Line(outputBuffer)
    .fill()
    .store();

  var header = new Line(outputBuffer)
    .column('Suscipit', 20, [clc.cyan])
    .column('Voluptatem', 20, [clc.cyan])
    .column('Nesciunt', 20, [clc.cyan])
    .column('Laudantium', 11, [clc.cyan])
    .fill()
    .store();

  var line;
  for(var l = 0; l < 20; l++)
  {
  line = new Line(outputBuffer)
    .column((Math.random()*100).toFixed(3), 20)
    .column((Math.random()*100).toFixed(3), 20)
    .column((Math.random()*100).toFixed(3), 20)
    .column((Math.random()*100).toFixed(3), 11)
    .fill()
    .store();
  }

  outputBuffer.output();

  drawTimeout = setTimeout(draw, 1000);
}

draw();

process.stdout.on('resize', function() {
  clearTimeout(drawTimeout);
  draw();
});