text:
#if defined(USE_FULL_LL_DRIVER)

/* Includes ------------------------------------------------------------------*/
#include "stm32h7xx_ll_dma.h"
#include "stm32h7xx_ll_bus.h"
#ifdef  USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif

/** @addtogroup STM32H7xx_LL_Driver
  * @{
  */

#if defined (DMA1) || defined (DMA2)

/** @addtogroup DMA_LL
  * @{
  */

/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup DMA_LL_Private_Macros
  * @{
  */
#define IS_LL_DMA_DIRECTION(__VALUE__)          (((__VALUE__) == LL_DMA_DIRECTION_PERIPH_TO_MEMORY) || \
                                                 ((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_PERIPH) || \
                                                 ((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_MEMORY))

#define IS_LL_DMA_MODE(__VALUE__)               (((__VALUE__) == LL_DMA_MODE_NORMAL)    || \
                                                 ((__VALUE__) == LL_DMA_MODE_CIRCULAR)  || \
                                                 ((__VALUE__) == LL_DMA_MODE_PFCTRL))

#define IS_LL_DMA_PERIPHINCMODE(__VALUE__)      (((__VALUE__) == LL_DMA_PERIPH_INCREMENT) || \
                                                 ((__VALUE__) == LL_DMA_PERIPH_NOINCREMENT))

#define IS_LL_DMA_MEMORYINCMODE(__VALUE__)      (((__VALUE__) == LL_DMA_MEMORY_INCREMENT) || \
                                                 ((__VALUE__) == LL_DMA_MEMORY_NOINCREMENT))

#define IS_LL_DMA_PERIPHDATASIZE(__VALUE__)     (((__VALUE__) == LL_DMA_PDATAALIGN_BYTE)      || \
                                                 ((__VALUE__) == LL_DMA_PDATAALIGN_HALFWORD)  || \
                                                 ((__VALUE__) == LL_DMA_PDATAALIGN_WORD))

#define IS_LL_DMA_MEMORYDATASIZE(__VALUE__)     (((__VALUE__) == LL_DMA_MDATAALIGN_BYTE)      || \
                                                 ((__VALUE__) == LL_DMA_MDATAALIGN_HALFWORD)  || \
                                                 ((__VALUE__) == LL_DMA_MDATAALIGN_WORD))

#define IS_LL_DMA_NBDATA(__VALUE__)             ((__VALUE__)  <= 0x0000FFFFU)

#if defined(TIM24)
#define IS_LL_DMA_REQUEST(REQUEST)              (((REQUEST)   <= LL_DMAMUX1_REQ_TIM24_TRIG))
#elif defined(ADC3)
#define IS_LL_DMA_REQUEST(REQUEST)              (((REQUEST)   <= LL_DMAMUX1_REQ_ADC3))
#else
#define IS_LL_DMA_REQUEST(REQUEST)              (((REQUEST)   <= LL_DMAMUX1_REQ_USART10_TX))
#endif /* TIM24 */

#define IS_LL_DMA_PRIORITY(__VALUE__)           (((__VALUE__) == LL_DMA_PRIORITY_LOW)    || \
                                                 ((__VALUE__) == LL_DMA_PRIORITY_MEDIUM) || \
                                                 ((__VALUE__) == LL_DMA_PRIORITY_HIGH)   || \
                                                 ((__VALUE__) == LL_DMA_PRIORITY_VERYHIGH))

#define IS_LL_DMA_ALL_STREAM_INSTANCE(INSTANCE, STREAM)   ((((INSTANCE) == DMA1) && \
                                                           (((STREAM) == LL_DMA_STREAM_0)     || \
                                                            ((STREAM) == LL_DMA_STREAM_1)     || \
                                                            ((STREAM) == LL_DMA_STREAM_2)     || \
                                                            ((STREAM) == LL_DMA_STREAM_3)     || \
                                                            ((STREAM) == LL_DMA_STREAM_4)     || \
                                                            ((STREAM) == LL_DMA_STREAM_5)     || \
                                                            ((STREAM) == LL_DMA_STREAM_6)     || \
                                                            ((STREAM) == LL_DMA_STREAM_7)     || \
                                                            ((STREAM) == LL_DMA_STREAM_ALL))) || \
                                                           (((INSTANCE) == DMA2) && \
                                                           (((STREAM) == LL_DMA_STREAM_0)     || \
                                                            ((STREAM) == LL_DMA_STREAM_1)     || \
                                                            ((STREAM) == LL_DMA_STREAM_2)     || \
                                                            ((STREAM) == LL_DMA_STREAM_3)     || \
                                                            ((STREAM) == LL_DMA_STREAM_4)     || \
                                                            ((STREAM) == LL_DMA_STREAM_5)     || \
                                                            ((STREAM) == LL_DMA_STREAM_6)     || \
                                                            ((STREAM) == LL_DMA_STREAM_7)     || \
                                                            ((STREAM) == LL_DMA_STREAM_ALL))))

#define IS_LL_DMA_FIFO_MODE_STATE(STATE)    (((STATE) == LL_DMA_FIFOMODE_DISABLE ) || \
                                             ((STATE) == LL_DMA_FIFOMODE_ENABLE))

#define IS_LL_DMA_FIFO_THRESHOLD(THRESHOLD) (((THRESHOLD) == LL_DMA_FIFOTHRESHOLD_1_4)  || \
                                             ((THRESHOLD) == LL_DMA_FIFOTHRESHOLD_1_2)  || \
                                             ((THRESHOLD) == LL_DMA_FIFOTHRESHOLD_3_4)  || \
                                             ((THRESHOLD) == LL_DMA_FIFOTHRESHOLD_FULL))

#define IS_LL_DMA_MEMORY_BURST(BURST)       (((BURST) == LL_DMA_MBURST_SINGLE) || \
                                             ((BURST) == LL_DMA_MBURST_INC4)   || \
                                             ((BURST) == LL_DMA_MBURST_INC8)   || \
                                             ((BURST) == LL_DMA_MBURST_INC16))

#define IS_LL_DMA_PERIPHERAL_BURST(BURST)  (((BURST) == LL_DMA_PBURST_SINGLE) || \
                                            ((BURST) == LL_DMA_PBURST_INC4)   || \
                                            ((BURST) == LL_DMA_PBURST_INC8)   || \
                                            ((BURST) == LL_DMA_PBURST_INC16))

/**
  * @}
  */

/* Private function prototypes -----------------------------------------------*/

/* Exported functions --------------------------------------------------------*/
/** @addtogroup DMA_LL_Exported_Functions
  * @{
  */

/** @addtogroup DMA_LL_EF_Init
  * @{
  */

/**
  * @brief  De-initialize the DMA registers to their default reset values.
  * @param  DMAx DMAx Instance
  * @param  Stream This parameter can be one of the following values:
  *         @arg @ref LL_DMA_STREAM_0
  *         @arg @ref LL_DMA_STREAM_1
  *         @arg @ref LL_DMA_STREAM_2
  *         @arg @ref LL_DMA_STREAM_3
  *         @arg @ref LL_DMA_STREAM_4
  *         @arg @ref LL_DMA_STREAM_5
  *         @arg @ref LL_DMA_STREAM_6
  *         @arg @ref LL_DMA_STREAM_7
  *         @arg @ref LL_DMA_STREAM_ALL
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: DMA registers are de-initialized
  *          - ERROR: DMA registers are not de-initialized
  */
uint32_t LL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Stream)
{
  DMA_Stream_TypeDef *tmp;
  ErrorStatus status = SUCCESS;

  /* Check the DMA Instance DMAx and Stream parameters */
  assert_param(IS_LL_DMA_ALL_STREAM_INSTANCE(DMAx, Stream));

  if (Stream == LL_DMA_STREAM_ALL)
  {
    if (DMAx == DMA1)
    {
      /* Force reset of DMA clock */
      LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_DMA1);

      /* Release reset of DMA clock */
      LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_DMA1);
    }
    else if (DMAx == DMA2)
    {
      /* Force reset of DMA clock */
       LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_DMA2);

      /* Release reset of DMA clock */
      LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_DMA2);
    }
    else
    {
      status = ERROR;
    }
  }
  else
  {
    /* Disable the selected Stream */
    LL_DMA_DisableStream(DMAx, Stream);

    /* Get the DMA Stream Instance */
    tmp = (DMA_Stream_TypeDef *)(__LL_DMA_GET_STREAM_INSTANCE(DMAx, Stream));

    /* Reset DMAx_Streamy configuration register */
    LL_DMA_WriteReg(tmp, CR, 0U);

    /* Reset DMAx_Streamy remaining bytes register */
    LL_DMA_WriteReg(tmp, NDTR, 0U);

    /* Reset DMAx_Streamy peripheral address register */
    LL_DMA_WriteReg(tmp, PAR, 0U);

    /* Reset DMAx_Streamy memory address register */
    LL_DMA_WriteReg(tmp, M0AR, 0U);

    /* Reset DMAx_Streamy memory address register */
    LL_DMA_WriteReg(tmp, M1AR, 0U);

    /* Reset DMAx_Streamy FIFO control register */
    LL_DMA_WriteReg(tmp, FCR, 0x00000021U);

    /* Reset Channel register field for DMAx Stream */
    LL_DMA_SetPeriphRequest(DMAx, Stream, LL_DMAMUX1_REQ_MEM2MEM);

    if (Stream == LL_DMA_STREAM_0)
    {
      /* Reset the Stream0 pending flags */
      DMAx->LIFCR = 0x0000003FU;
    }
    else if (Stream == LL_DMA_STREAM_1)
    {
      /* Reset the Stream1 pending flags */
      DMAx->LIFCR = 0x00000F40U;
    }
    else if (Stream == LL_DMA_STREAM_2)
    {
      /* Reset the Stream2 pending flags */
      DMAx->LIFCR = 0x003F0000U;
    }
    else if (Stream == LL_DMA_STREAM_3)
    {
      /* Reset the Stream3 pending flags */
      DMAx->LIFCR = 0x0F400000U;
    }
    else if (Stream == LL_DMA_STREAM_4)
    {
      /* Reset the Stream4 pending flags */
      DMAx->HIFCR = 0x0000003FU;
    }
    else if (Stream == LL_DMA_STREAM_5)
    {
      /* Reset the Stream5 pending flags */
      DMAx->HIFCR = 0x00000F40U;
    }
    else if (Stream == LL_DMA_STREAM_6)
    {
      /* Reset the Stream6 pending flags */
      DMAx->HIFCR = 0x003F0000U;
    }
    else if (Stream == LL_DMA_STREAM_7)
    {
      /* Reset the Stream7 pending flags */
      DMAx->HIFCR = 0x0F400000U;
    }
    else
    {
      status = ERROR;
    }
  }

  return (uint32_t)status;
}

/**
  * @brief  Initialize the DMA registers according to the specified parameters in DMA_InitStruct.
  * @note   To convert DMAx_Streamy Instance to DMAx Instance and Streamy, use helper macros :
  *         @arg @ref __LL_DMA_GET_INSTANCE
  *         @arg @ref __LL_DMA_GET_STREAM
  * @param  DMAx DMAx Instance
  * @param  Stream This parameter can be one of the following values:
  *         @arg @ref LL_DMA_STREAM_0
  *         @arg @ref LL_DMA_STREAM_1
  *         @arg @ref LL_DMA_STREAM_2
  *         @arg @ref LL_DMA_STREAM_3
  *         @arg @ref LL_DMA_STREAM_4
  *         @arg @ref LL_DMA_STREAM_5
  *         @arg @ref LL_DMA_STREAM_6
  *         @arg @ref LL_DMA_STREAM_7
  * @param  DMA_InitStruct pointer to a @ref LL_DMA_InitTypeDef structure.
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: DMA registers are initialized
  *          - ERROR: Not applicable
  */
uint32_t LL_DMA_Init(DMA_TypeDef *DMAx, uint32_t Stream, LL_DMA_InitTypeDef *DMA_InitStruct)
{
  /* Check the DMA Instance DMAx and Stream parameters */
  assert_param(IS_LL_DMA_ALL_STREAM_INSTANCE(DMAx, Stream));

  /* Check the DMA parameters from DMA_InitStruct */
  assert_param(IS_LL_DMA_DIRECTION(DMA_InitStruct->Direction));
  assert_param(IS_LL_DMA_MODE(DMA_InitStruct->Mode));
  assert_param(IS_LL_DMA_PERIPHINCMODE(DMA_InitStruct->PeriphOrM2MSrcIncMode));
  assert_param(IS_LL_DMA_MEMORYINCMODE(DMA_InitStruct->MemoryOrM2MDstIncMode));
  assert_param(IS_LL_DMA_PERIPHDATASIZE(DMA_InitStruct->PeriphOrM2MSrcDataSize));
  assert_param(IS_LL_DMA_MEMORYDATASIZE(DMA_InitStruct->MemoryOrM2MDstDataSize));
  assert_param(IS_LL_DMA_NBDATA(DMA_InitStruct->NbData));
  assert_param(IS_LL_DMA_REQUEST(DMA_InitStruct->PeriphRequest));
  assert_param(IS_LL_DMA_PRIORITY(DMA_InitStruct->Priority));
  assert_param(IS_LL_DMA_FIFO_MODE_STATE(DMA_InitStruct->FIFOMode));

  /* Check the memory burst, peripheral burst and FIFO threshold parameters only
     when FIFO mode is enabled */
  if (DMA_InitStruct->FIFOMode != LL_DMA_FIFOMODE_DISABLE)
  {
    assert_param(IS_LL_DMA_FIFO_THRESHOLD(DMA_InitStruct->FIFOThreshold));
    assert_param(IS_LL_DMA_MEMORY_BURST(DMA_InitStruct->MemBurst));
    assert_param(IS_LL_DMA_PERIPHERAL_BURST(DMA_InitStruct->PeriphBurst));
  }

  /*---------------------------- DMAx SxCR Configuration ------------------------
   * Configure DMAx_Streamy: data transfer direction, data transfer mode,
   *                          peripheral and memory increment mode,
   *                          data size alignment and  priority level with parameters :
   * - Direction:      DMA_SxCR_DIR[1:0] bits
   * - Mode:           DMA_SxCR_CIRC bit
   * - PeriphOrM2MSrcIncMode:  DMA_SxCR_PINC bit
   * - MemoryOrM2MDstIncMode:  DMA_SxCR_MINC bit
   * - PeriphOrM2MSrcDataSize: DMA_SxCR_PSIZE[1:0] bits
   * - MemoryOrM2MDstDataSize: DMA_SxCR_MSIZE[1:0] bits
   * - Priority:               DMA_SxCR_PL[1:0] bits
   */
  LL_DMA_ConfigTransfer(DMAx, Stream, DMA_InitStruct->Direction | \
                        DMA_InitStruct->Mode                    | \
                        DMA_InitStruct->PeriphOrM2MSrcIncMode   | \
                        DMA_InitStruct->MemoryOrM2MDstIncMode   | \
                        DMA_InitStruct->PeriphOrM2MSrcDataSize  | \
                        DMA_InitStruct->MemoryOrM2MDstDataSize  | \
                        DMA_InitStruct->Priority
                       );

  if (DMA_InitStruct->FIFOMode != LL_DMA_FIFOMODE_DISABLE)
  {
    /*---------------------------- DMAx SxFCR Configuration ------------------------
     * Configure DMAx_Streamy:  fifo mode and fifo threshold with parameters :
     * - FIFOMode:                DMA_SxFCR_DMDIS bit
     * - FIFOThreshold:           DMA_SxFCR_FTH[1:0] bits
     */
    LL_DMA_ConfigFifo(DMAx, Stream, DMA_InitStruct->FIFOMode, DMA_InitStruct->FIFOThreshold);

    /*---------------------------- DMAx SxCR Configuration --------------------------
     * Configure DMAx_Streamy:  memory burst transfer with parameters :
     * - MemBurst:                DMA_SxCR_MBURST[1:0] bits
     */
    LL_DMA_SetMemoryBurstxfer(DMAx, Stream, DMA_InitStruct->MemBurst);

    /*---------------------------- DMAx SxCR Configuration --------------------------
     * Configure DMAx_Streamy:  peripheral burst transfer with parameters :
     * - PeriphBurst:             DMA_SxCR_PBURST[1:0] bits
     */
    LL_DMA_SetPeriphBurstxfer(DMAx, Stream, DMA_InitStruct->PeriphBurst);
  }

  /*-------------------------- DMAx SxM0AR Configuration --------------------------
   * Configure the memory or destination base address with parameter :
   * - MemoryOrM2MDstAddress:     DMA_SxM0AR_M0A[31:0] bits
   */
  LL_DMA_SetMemoryAddress(DMAx, Stream, DMA_InitStruct->MemoryOrM2MDstAddress);

  /*-------------------------- DMAx SxPAR Configuration ---------------------------
   * Configure the peripheral or source base address with parameter :
   * - PeriphOrM2MSrcAddress:     DMA_SxPAR_PA[31:0] bits
   */
  LL_DMA_SetPeriphAddress(DMAx, Stream, DMA_InitStruct->PeriphOrM2MSrcAddress);

  /*--------------------------- DMAx SxNDTR Configuration -------------------------
   * Configure the peripheral base address with parameter :
   * - NbData:                    DMA_SxNDT[15:0] bits
   */
  LL_DMA_SetDataLength(DMAx, Stream, DMA_InitStruct->NbData);

  /*--------------------------- DMA SxCR_CHSEL Configuration ----------------------
   * Configure the peripheral base address with parameter :
   * - PeriphRequest:             DMA_SxCR_CHSEL[3:0] bits
   */
  LL_DMA_SetPeriphRequest(DMAx, Stream, DMA_InitStruct->PeriphRequest);

  return (uint32_t)SUCCESS;
}

/**
  * @brief  Set each @ref LL_DMA_InitTypeDef field to default value.
  * @param  DMA_InitStruct Pointer to a @ref LL_DMA_InitTypeDef structure.
  * @retval None
  */
void LL_DMA_StructInit(LL_DMA_InitTypeDef *DMA_InitStruct)
{
  /* Set DMA_InitStruct fields to default values */
  DMA_InitStruct->PeriphOrM2MSrcAddress  = 0x00000000U;
  DMA_InitStruct->MemoryOrM2MDstAddress  = 0x00000000U;
  DMA_InitStruct->Direction              = LL_DMA_DIRECTION_PERIPH_TO_MEMORY;
  DMA_InitStruct->Mode                   = LL_DMA_MODE_NORMAL;
  DMA_InitStruct->PeriphOrM2MSrcIncMode  = LL_DMA_PERIPH_NOINCREMENT;
  DMA_InitStruct->MemoryOrM2MDstIncMode  = LL_DMA_MEMORY_NOINCREMENT;
  DMA_InitStruct->PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_BYTE;
  DMA_InitStruct->MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_BYTE;
  DMA_InitStruct->NbData                 = 0x00000000U;
  DMA_InitStruct->PeriphRequest          = LL_DMAMUX1_REQ_MEM2MEM;
  DMA_InitStruct->Priority               = LL_DMA_PRIORITY_LOW;
  DMA_InitStruct->FIFOMode               = LL_DMA_FIFOMODE_DISABLE;
  DMA_InitStruct->FIFOThreshold          = LL_DMA_FIFOTHRESHOLD_1_4;
  DMA_InitStruct->MemBurst               = LL_DMA_MBURST_SINGLE;
  DMA_InitStruct->PeriphBurst            = LL_DMA_PBURST_SINGLE;
}

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

#endif /* DMA1 || DMA2 */

/**
  * @}
  */

#endif /* USE_FULL_LL_DRIVER */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
package org.capnproto;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

public final class BufferedInputStreamWrapper implements BufferedInputStream {

    private final ReadableByteChannel inner;
    private final ByteBuffer buf;

    public BufferedInputStreamWrapper(ReadableByteChannel chan) {
        this.inner = chan;
        this.buf = ByteBuffer.allocate(8192);
        this.buf.limit(0);
    }

    public final int read(ByteBuffer dst) throws IOException {
        int numBytes = dst.remaining();
        if (numBytes < this.buf.remaining()) {
            //# Serve from the current buffer.
            ByteBuffer slice = this.buf.slice();
            slice.limit(numBytes);
            dst.put(slice);
            this.buf.position(this.buf.position() + numBytes);
            return numBytes;
        } else {
            //# Copy current available into destination.
            int fromFirstBuffer = this.buf.remaining();
            {
                ByteBuffer slice = this.buf.slice();
                slice.limit(fromFirstBuffer);
                dst.put(slice);
            }

            numBytes -= fromFirstBuffer;
            if (numBytes <= this.buf.capacity()) {
                //# Read the next buffer-full.
                this.buf.clear();
                int n = readAtLeast(this.inner, this.buf, numBytes);

                this.buf.rewind();
                ByteBuffer slice = this.buf.slice();
                slice.limit(numBytes);
                dst.put(slice);

                this.buf.limit(n);
                this.buf.position(numBytes);
                return fromFirstBuffer + numBytes;
            } else {
                //# Forward large read to the underlying stream.
                this.buf.clear();
                this.buf.limit(0);
                return fromFirstBuffer + readAtLeast(this.inner, dst, numBytes);
            }
        }
    }

    public final ByteBuffer getReadBuffer() throws IOException {
        if (this.buf.remaining() == 0) {
            this.buf.clear();
            int n = readAtLeast(this.inner, this.buf, 1);
            this.buf.rewind();
            this.buf.limit(n);
        }
        return this.buf;
    }

    public final void close() throws IOException {
        this.inner.close();
    }

    public final boolean isOpen() {
        return this.inner.isOpen();
    }

    public static int readAtLeast(ReadableByteChannel reader, ByteBuffer buf, int minBytes) throws IOException {
        int numRead = 0;
        while (numRead < minBytes) {
            int res = reader.read(buf);
            if (res < 0) {
                throw new Error("premature EOF");
            }
            numRead += res;
        }
        return numRead;
    }
}

redpajama_set_name: RedPajamaGithub


text:
**API Version 2**

A User's custom actions. This endpoint allows a user to retrieve a list
of or create new custom actions. A `CustomAction` object must be associated
with a parent `CustomGoal` object (see [Custom Goals](/api/users/customgoals/))
*OR* with a publicly available `Goal` ([/api/goals/](/api/goals/)).

GET requests return an array of results containing the following:

* `id`: The ID of the `CustomAction` object.
* `user`: The ID of the action's owner.
* `customgoal`: The ID of the parent `CustomGoal` object (may be `null`).
* `goal`: The ID of the parent `Goal` object (may be `null`).
* `goal_title`: The title text of either the related `CustomGoal` or `Goal`.
* `title`: Title of the custom action (required).
* `title_slug`: sluggified version of the title.
* `notification_text`: Text that will be used in a notification (required).
* `custom_trigger`: A `Trigger` object.

      - `id`: Unique ID of the Trigger
      - `name`: The trigger's name
      - `trigger_date`: Date on which the trigger shoudl start
      - `time`: Time at which the trigger should fire
      - `recurrences`: an RFC 2445 RRULE string (or null)
      - `recurrences_display`: a human-readable version of recurrences
      - `disabled`: whether or not the trigger is disabled.

* `next_trigger_date`: The next date the notification will be sent.
  May be `null`.
* `prev_trigger_date`: The previous date the notficiation was sent.
  May be `null`.
* `updated_on`: Date the action was last updated.
* `created_on`: Date the action was created.
* `object_type`: Will always be the string, `customaction`.

## Filtering

**To filter on custom actions scheduled for _today_**, limit the result size,
or exclude actions which a user has already completed, use on of the following:

* `/api/users/actions/?today=1`  -- only show items for today.
* `/api/users/actions/?page_size=3`  -- retreive only 3 items.
* `/api/users/actions/?exclude_completed=1` -- Excluded completed items

You may filter the result of listing custom actions by their parent goals. To
do so, include a querystring parameter of `customgoal` or `goal` that includes
either the goal's database ID or title slug.

* `/api/users/customactions/?customgoal={id}`
* `/api/users/customactions/?customgoal={title_slug}`
* `/api/users/customactions/?goal={id}`
* `/api/users/customactions/?goal={title_slug}`

## Creating Custom Actions

Send a POST request to the
[/api/users/customactions/](/api/users/customactions/) endpoint with the
following data:

    {
        'title': 'Your action Title',
        'notification_text': 'Your action's notification',
        'customgoal': {ID of the parent custom goal},
    }

Or add a custom action associated with a public Goal:

    {
        'title': 'Your action Title',
        'notification_text': 'Your action's notification',
        'goal': {ID of the goal},
    }

## Custom Action Details

You can retrieve details for a single custom action instance via the
`/api/users/customactions/{customaction_id}/` endpoint, which will return a
single JSON representation for the object.

## Updating Custom Actions.

Send a PUT request to the `/api/users/customactions/{customaction_id}/`
endpoint, containing the information that you wish to, e.g.:

    {
        'title': 'Updated Title',
        'notification_text': 'Updated notification',
        'customgoal': {ID of the parent custom goal},
    }

## Including a Custom Trigger

CustomActions may be updated in order to set custom Triggers (aka
reminders) for the associated action.

To do this, send a PUT request to the detail url
(`api/users/customactions/{customaction_id}`) with the following information:

* `custom_trigger_time`: The time at which the reminder should fire, in
  `hh:mm` format, in the user's local time.
* `custom_trigger_date`: (optional). For a one-time reminder, this can
  include a date string (yyyy-mm-dd) to define the date at which a reminder
  should next fire. The date should be relative to the user's local time.
* `custom_trigger_rrule`: A Unicode RFC 2445 string representing the days &
  frequencies at which the reminder should occur.
* `custom_trigger_disabled`: (optional) A `true` or `false` value; if `true`
  the trigger will be disabled.

## Completing Custom Action

You can specify that you've completed a custom action (typically from a
reminder) via the `/api/users/customactions/{customaction_id}/complete/`
endpoint. Submit a POST request with the following information:

    {'state': 'completed'}

Where `state` is one of:

* `uncompleted`
* `completed`
* `dismissed`
* `snoozed`

## Custom Action Feedback

You can provide open-ended feedback on a Custom Action by sending a POST
request to the `/api/users/customactions/{customaction_id}/feedback/`
endpoint. Submit a POST request with the following information:

    {'text': 'User-supplied text'}

## Deleting Custom Actions

Send a DELETE request to the custom action's _detail_ endpoint:
`/api/users/customactions/{customaction_id}/`. Successful deletions return a
204 No Content response.

----


text:
package org.kie.event.kiebase;

public interface AfterFunctionRemovedEvent
    extends
    KieBaseEvent {
    public String getFunction();
}


text:
key_name = 'client'
chef_server_url "#{url}"
client_key "../#{key_name}.pem"
# Use both kind of quotes, also a comment for testing
node_name "test_1"
# test multiple line values
client_name = {
    'dev' =>'test_1'
}['dev']


text:
package spot.scripts;

import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import spot.BaseSelenium;
import spot.pages.AdministrationPage;
import spot.pages.AllUsersOverViewPage;
import spot.pages.EditUserProfilePage;
import spot.pages.LoginPage;
import spot.pages.StartPage;
import spot.pages.UserProfilePage;
import spot.pages.admin.AdminHomePage;

public class EditUserProfileTest extends BaseSelenium {

	private AdminHomePage adminHomePage;
	private AdministrationPage adminPage;

	private String newUserName;
	private AllUsersOverViewPage allUsersOverViewPage;

	@BeforeClass
	public void beforeClass() {
		navigateToStartPage();

//		new StartPage(driver).selectLanguage(englishSetup);

		LoginPage loginPage = new StartPage(driver).openLoginForm();
		adminHomePage = loginPage.loginAsAdmin(getPropertyAttribute(spotAdminUserName), getPropertyAttribute(spotAdminPassWord));

		adminPage = adminHomePage.goToAdminPage();

		newUserName = "edmond-test@mpdl.mpg.de";

		allUsersOverViewPage = adminPage.createNewUser(newUserName);
	}

	@AfterMethod
	public void afterMethod() {
		String allUsersOverViewLink = "http://qa-edmond.mpdl.mpg.de/imeji/users";
		driver.navigate().to(allUsersOverViewLink);
	}

	@Test
	public void changeNameOfUserTest() {
		UserProfilePage userProfilePage = allUsersOverViewPage.viewDetails(newUserName);
		EditUserProfilePage editUserProfilePage = userProfilePage.editProfile();

		String newFamilyName = "TestMan";
		userProfilePage = editUserProfilePage.changeUserFamilyName(newFamilyName);

		boolean isEditedSuccessfully = userProfilePage.checkFamilyName("TestMan");

		Assert.assertTrue(isEditedSuccessfully, "Edit Profile Test: Name of User couldn't be changed.");
	}

	@Test
	public void changePasswordOfUserTest() {
		UserProfilePage userProfilePage = allUsersOverViewPage.viewDetails(newUserName);
		userProfilePage.changePassword();

		String actualInfoMessage = userProfilePage.getMessageComponent().getInfoMessage();
		String expectedInfoMessage = "Password changed successfully";
		Assert.assertEquals(actualInfoMessage, expectedInfoMessage, "Edit Profile Test: Password couldn't be changed.");
	}

	@AfterClass
	public void afterClass() {

		// delete the user again
		allUsersOverViewPage.deleteUserByEmail(newUserName);

		adminHomePage.logout();
	}
}


text:
from django.apps import AppConfig

class FrontendConfig(AppConfig):
    name = 'nntpchan.frontend'


text:
namespace smug {
//Textureloader uses GLI to load dds and ktx
class TextureLoader : public LoaderInterface {
  public:
	TextureLoader();
	~TextureLoader();
	char* LoadTexture(const eastl::string& filename, TextureInfo& info);

	virtual LoadResult LoadAsset(const char* filename) override;
	virtual void UnloadAsset(void* asset) override;
	virtual void SerializeAsset(FileBuffer* buffer, LoadResult* asset) override;
	virtual DeSerializedResult DeSerializeAsset(void* assetBuffer) override;
	virtual bool IsExtensionSupported(const char* extension) override;
	virtual bool IsTypeSupported(int type) override;
};
}


text:
SUMMARY
=======

Simulation of a ball-clock that outputs the number of
days elapsed before the clock completely cycles through and resets its orginal state.

Better stated, the program computes the time before repetition, which varies according to the total number of balls present.

USAGE
=================
The program takes input from the command line flag parameters:

	# Run 30 balls through the ball clock cycle
	BallClock.exe -balls=30
	30 balls cycle after 15 days.

	# Run 30 balls through the ball clock cycle but stops at 325 minutes
	BallClock.exe -balls=30 -minutes=325
	{"Min":[],"FiveMin":[22,13,25,3,7],"Hour":[6,12,17,4,15],
	"Main":[11,5,26,18,2,30,19,8,24,10,29,20,16,21,28,1,23,14,27,9]}

- balls must be between 27 and 127
- minutes must be a positive integer between 0 to 3477600.

TESTS
=================
To run the unit tests:
	go test ./...


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Ripple: Who? Why? What? How?</title>

		<meta name="description" content="A walkthrew of the Ripple Mobile Environment Emulator">
		<meta name="author" content="Gord Tanner">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<link href='http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic' rel='stylesheet' type='text/css'>

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/default.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

        <link rel="stylesheet" href="accel/rpg.css" type="text/css" media="screen" title="no title" charset="utf-8">

Ripple

Who? Why? What? How?

Gord Tanner, Code Poet

(Research In Motion)

@gordtanner

Who?

The usual suspects

                    <ui>

Dan Silivestru (@confusement)

Brent Lintner (@brentlintner)

Gord Tanner (@gordtanner)

                    </ui>

Open Sourced

                    github.com/blackberry/Ripple-UI

Apache Cordova

Why?

OMFG

Edit, Refresh, Continue?

Web Inspector?

Being awesome?

What?

introducing Ripple

Runs in the browser

Chrome Extension

Where am I?

http://magicandmalarky.files.wordpress.com/2011/01/dragon_4.png

                    <button onclick="updateMap();" id="update-map" class="button">update map</button>

Accelerometer

PhoneGap

Accelerometer Demo

Start

Reset

image capture

                        <button onclick="takePic();" id="get-pic" class="button">Take Pic</button>

what about plugins?!?!

function pluginWin(info) {
    alert(info.stuff);
}

function pluginFail(error) {
    alert(error.msg);
}

function callMyAwesomePlugin() {
    var myPlugin = navigator.myPlugin;
    myPlugin.myCoolMethod(pluginWin, pluginFail, {});
}

                    <button onclick="callMyAwesomePlugin();" id="call-plugin" class="button">Call My Plugin</button>

How?

0.0.1

Javascript !== Java

#fail

tinyHippos.foo = function () {
    this.bar = "value";
    this._password = "shhh";
};

tinyHippos.foo.prototype.baz = function (thingie) {
    if (!thingie instanceof tinyHippos.Thingie) {
        throw "this isn't a thingie";
    }
    console.log(this._password);
};

tinyHippos.core.foo = new tinyHippos.foo();

Hail to the king baby

Injection

document.open();
document.write("All your dreams go here");

window.setTimeout(function () {
    document.close();
}, 100);

Bootstrapping

var fooodOrder = jWorkflow.order(garlicChicken)
                          .andThen(whiteRice)
                          .andThen(wontonSoup)
                          .andThen(cookiesFortune)
                          .andThen(noAndThen)
                          .andThen(noAndThen)
                          .andThen(noAndThen)
                          .andThen(noAndThen);

fooodOrder.start();

Bootstrapping

jWorkflow.order(function () {
    return 1;
}).andThen(function (baton, prev) {
    baton.take();

    setTimeout(function () {
        baton.pass(prev + 1);
    }, 1000);
});

                github.com/tinyhippos/jWorkflow

Modules

var private = 1;

function alsoPrivate() { return 1; }

module.exports = {
    public: 2,
    alsoPublic: function () { return 2; }
}

Sugar

define("module", function (require, module, exports) {

    var private = 1;

    function alsoPrivate() { return 1; }

    module.exports = {
        public: 2,
        alsoPublic: function () { return 2; }
    }

});

Platform Definitions

module.exports = {
    id: "atari",
    version: "1.0.0",
    name: "Atari 2600",

    initialize: function () {
        //stuff to warm up the platform
    },

    objects: {
        atari: {
            path: "atari/1.0.0/core",
            children: {
                screen: {
                    path: "atari/1.0.0/screen"
                }
            }
        }
    }
};

Loading Platforms

var builder = require('ripple/platform/builder'),
    atari = require('ripple/platform/atari/spec');

builder.build(atari.objects).into(window);
atari.initialize();

Teh new hotness

                    Not released yet!?!?! #slackers

me:~$ npm install -g ripple
me:~$ cd project
me:~/project/$ ripple init
me:~/project/$ ripple emulate

@gordtanner


text:
<!DOCTYPE html>

<?php echo session('name'); ?> | <?php echo ucfirst(session('role'));?>

        Dashboard | Change&nbspPassword | Logout


text:
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using bv.common.Configuration;
using bv.common.Core;
using eidss.model.Core;
using System;
using System.Linq;
using System.Threading;

namespace eidss.webclient.Utils
{
    public static class MenuHelper
    {
        private static string getMenuCacheKey()
        {
            return String.Format("{1}Menu{0}", EidssUserContext.Instance.CurrentUser.EmployeeID.ToString(), Thread.CurrentThread.CurrentCulture.ToString());
        }
        public static void ClearMenuCache()
        {
            HttpContext.Current.Session.Remove(getMenuCacheKey());
        }

        private static void BuildMenuList(MenuCategory cat, IMenuAction item)
        {
            if (!item.IsCategory)
            {
                string culture = Thread.CurrentThread.CurrentCulture.ToString();
                var menuItem = PermissionParser.CreateMenuItem(item, culture);
                cat.Items.Add(menuItem);
            }
            item.Items.ForEach(c => BuildMenuList(cat, c));
        }

        public static List<MenuCategory> GetMenu()
        {
            string cachekey = getMenuCacheKey();

            List<MenuCategory> menu = HttpContext.Current.Session[cachekey] as List<MenuCategory>;

            if (menu == null)
            {
                menu = MenuCategory.GetMenuList(
                    eidss.model.Core.EidssUserContext.Instance as EidssUserContext,
                    HttpRuntime.AppDomainAppPath + ConfigurationManager.AppSettings["MenuFilePath"]);

                var menuReport = menu.Find(c => c.IsReport);
                if (menuReport != null)
                {
                    var actionManager = new MenuActionManagerWeb();
                    WebMenuReportRegistrator.RegisterAllReports(actionManager);
                    actionManager.Reports.Items.ForEach(c => BuildMenuList(menuReport, c));
                }

                HttpContext.Current.Session.Add(cachekey, menu);
            }

            var m_ConnectionCredentials = new ConnectionCredentials(null, "Archive");
            if (m_ConnectionCredentials.IsCorrect && EidssUserContext.Instance.CanDo("CanReadArchivedData.Execute"))
            {
                var menucopy = new List<MenuCategory>(menu);
                string culture = Thread.CurrentThread.CurrentCulture.ToString();
                var titleDatabase = Translator.GetMenuName("MenuDatabase", "Database");
                if (!EidssUserContext.Instance.IsArchiveMode)
                {
                    var titleArchive = Translator.GetMenuName("MenuArchive", "Connect to archive data");
                    menucopy.Add(new MenuCategory(titleDatabase, true, new List<MenuItem>()
                    {
                        new MenuItem(titleArchive, String.Format("/{0}{1}", culture, "/Account/Archive"), "")
                    }));
                }
                else
                {
                    var titleActual = Translator.GetMenuName("MenuActual", "Connect to actual data");
                    menucopy.Add(new MenuCategory(titleDatabase, true, new List<MenuItem>()
                    {
                        new MenuItem(titleActual, String.Format("/{0}{1}", culture, "/Account/Actual"), "")
                    }));
                }
                return menucopy;
            }

            return menu;
        }

        public static List<MenuItem> GetIconMenu()
        {
            string cachekey = String.Format("{1}MenuIcon{0}", EidssUserContext.Instance.CurrentUser.EmployeeID.ToString(), Thread.CurrentThread.CurrentCulture.ToString());

            List<MenuItem> menu = HttpContext.Current.Session[cachekey] as List<MenuItem>;

            if (menu == null)
            {
                menu = MenuItem.GetIconMenu(
                    eidss.model.Core.EidssUserContext.Instance as EidssUserContext,
                    HttpRuntime.AppDomainAppPath + ConfigurationManager.AppSettings["IconMenuFilePath"]);

                HttpContext.Current.Session.Add(cachekey, menu);
            }

            return menu;
        }
    }
}


text:
import numpy as np
import scipy.stats

__all__ = ["prior_transform",
           "Prior", "TopHat", "Normal", "ClippedNormal",
           "LogNormal", "LogUniform", "Beta"]

def prior_transform(self, unit_coords, priors, prior_args=[]):
    """An example of one way to use the `Prior` objects below to go from unit
    cube to parameter space, for nested sampling.  This takes and returns a
    list instead of an array, to accomodate possible vector parameters.  Thus
    one will need something like ``theta_array=np.concatenate(*theta)``

    :param unit_coords:
        Coordinates on the unit prior hyper-cube.  Iterable.

    :param priors:
        A list of `Prior` objects, iterable of same length as `unit_coords`.

    :param prior_args: (optional)
        A list of dictionaries of prior function keyword arguments.

    :returns theta:
        A list of parameter values corresponding to the given coordinates on
        the prior unit hypercube.
    """
    theta = []
    for i, (u, p) in enumerate(zip(unit_coords, priors)):
        func = p.unit_transform
        try:
            kwargs = prior_args[i]
        except(IndexError):
            kwargs = {}
        theta.append(func(u, **kwargs))
    return theta

class Prior(object):
    """Encapsulate the priors in an object.  Each prior should have a
    distribution name and optional parameters specifying scale and location
    (e.g. min/max or mean/sigma).  These can be aliased. When called, the
    argument should be a variable and it should return the ln-prior-probability
    of that value.

    Should be able to sample from the prior, and to get the gradient of the
    prior at any variable value.  Methods should also be avilable to give a
    useful plotting range and, if there are bounds, to return them.
    """

    def __init__(self, parnames=[], name='', **kwargs):
        """Constructor.

        :param parnames:
            A list of names of the parameters, used to alias the intrinsic
            parameter names.  This way different instances of the same Prior
            can have different parameter names in case they are being fit for.
        """
        if len(parnames) == 0:
            parnames = self.prior_params
        assert len(parnames) == len(self.prior_params)
        self.alias = dict(zip(self.prior_params, parnames))
        self.params = {}

        self.name = name
        self.update(**kwargs)

    def update(self, **kwargs):
        """Update `params` values using alias.
        """
        for k in self.prior_params:
            try:
                self.params[k] = kwargs[self.alias[k]]
            except(KeyError):
                pass

    def __len__(self):
        """The length is set by the maximum size of any of the prior_params.
        Note that the prior params must therefore be scalar of same length as
        the maximum size of any of the parameters.  This is not checked.
        """
        return max([np.size(self.params.get(k, 1)) for k in self.prior_params])

    def __call__(self, x, **kwargs):
        """Compute the value of the probability desnity function at x and
        return the ln of that.

        :param x:
            Value of the parameter, scalar or iterable of same length as the
            Prior object.

        :param kwargs: optional
            All extra keyword arguments are sued to update the `prior_params`.

        :returns lnp:
            The natural log of the prior probability at x, scalar or ndarray of
            same length as the prior object.
        """
        if len(kwargs) > 0:
            self.update(**kwargs)
        p = self.distribution.pdf(x, *self.args,
                                  loc=self.loc, scale=self.scale)
        return np.log(p)

    def sample(self, nsample=None, **kwargs):
        """Draw a sample from the prior distribution.

        :param nsample: (optional)
            Unused
        """
        if len(kwargs) > 0:
            self.update(**kwargs)
        return self.distribution.rvs(*self.args, size=len(self),
                                     loc=self.loc, scale=self.scale)

    def unit_transform(self, x, **kwargs):
        """Go from a value of the CDF (between 0 and 1) to the corresponding
        parameter value.

        :param x:
            A scalar or vector of same length as the Prior with values between
            zero and one corresponding to the value of the CDF.

        :returns theta:
            The parameter value corresponding to the value of the CDF given by
            `x`.
        """
        if len(kwargs) > 0:
            self.update(**kwargs)
        return self.distribution.ppf(x, *self.args,
                                     loc=self.loc, scale=self.scale)

    def inverse_unit_transform(self, x, **kwargs):
        """Go from the parameter value to the unit coordinate using the cdf.
        """
        if len(kwargs) > 0:
            self.update(**kwargs)
        return self.distribution.cdf(x, *self.args,
                                     loc=self.loc, scale=self.scale)

    def gradient(self, theta):
        raise(NotImplementedError)

    @property
    def loc(self):
        """This should be overridden.
        """
        return 0

    @property
    def scale(self):
        """This should be overridden.
        """
        return 1

    @property
    def args(self):
        return []

    @property
    def range(self):
        raise(NotImplementedError)

    @property
    def bounds(self):
        raise(NotImplementedError)

    def serialize(self):
        raise(NotImplementedError)

class TopHat(Prior):

    prior_params = ['mini', 'maxi']
    distribution = scipy.stats.uniform

    @property
    def scale(self):
        return self.params['maxi'] - self.params['mini']

    @property
    def loc(self):
        return self.params['mini']

    @property
    def range(self):
        return (self.params['mini'], self.params['maxi'])

    def bounds(self, **kwargs):
        if len(kwargs) > 0:
            self.update(**kwargs)
        return self.range

class Normal(Prior):
    """A simple gaussian prior.
    """

    prior_params = ['mean', 'sigma']
    distribution = scipy.stats.norm

    @property
    def scale(self):
        return self.params['sigma']

    @property
    def loc(self):
        return self.params['mean']

    @property
    def range(self):
        nsig = 4
        return (self.params['mean'] - nsig * self.params['sigma'],
                self.params['mean'] + self.params['sigma'])

    def bounds(self, **kwargs):
        # if len(kwargs) > 0:
        #    self.update(**kwargs)
        return (-np.inf, np.inf)

class ClippedNormal(Prior):
    """A Gaussian prior clipped to some range.
    """

    prior_params = ['mean', 'sigma', 'mini', 'maxi']
    distribution = scipy.stats.truncnorm

    @property
    def scale(self):
        return self.params['sigma']

    @property
    def loc(self):
        return self.params['mean']

    @property
    def range(self):
        return (self.params['mini'], self.params['maxi'])

    @property
    def args(self):
        a = (self.params['mini'] - self.params['mean']) / self.params['sigma']
        b = (self.params['maxi'] - self.params['mean']) / self.params['sigma']
        return [a, b]

    def bounds(self, **kwargs):
        if len(kwargs) > 0:
            self.update(**kwargs)
        return self.range

class LogUniform(Prior):
    """Like log-normal, but the distribution of ln of the variable is
    distributed uniformly instead of normally.
    """

    prior_params = ['mini', 'maxi']
    distribution = scipy.stats.reciprocal

    @property
    def args(self):
        a = self.params['mini']
        b = self.params['maxi']
        return [a, b]

    @property
    def range(self):
        return (self.params['mini'], self.params['maxi'])

    def bounds(self, **kwargs):
        if len(kwargs) > 0:
            self.update(**kwargs)
        return self.range

class Beta(Prior):
    """A Beta distribution.
    """

    prior_params = ['mini', 'maxi', 'alpha', 'beta']
    distribution = scipy.stats.beta

    @property
    def scale(self):
        return self.params.get('maxi', 1) - self.params.get('mini', 0)

    @property
    def loc(self):
        return self.params.get('mini', 0)

    @property
    def args(self):
        a = self.params['alpha']
        b = self.params['beta']
        return [a, b]

    @property
    def range(self):
        return (self.params.get('mini', 0), self.params.get('maxi', 1))

    def bounds(self, **kwargs):
        if len(kwargs) > 0:
            self.update(**kwargs)
        return self.range

class LogNormal(Prior):

    prior_params = ['mode', 'sigma']
    distribution = scipy.stats.lognorm

    @property
    def args(self):
        pass

    @property
    def scale(self):
        pass

    @property
    def loc(self):
        pass


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annln K. K. naturh. Hofmus. Wien 28(1/2): 216 (1914)

#### Original name
Basiascella gallarum Bubák

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:background="@drawable/shap_half_roundrect"
              >

	<ListView
	    android:id="@+id/lv_map_layers"
	    android:layout_width="230dp"
	    android:layout_height="match_parent"
	    android:layout_marginTop="@dimen/space_10"
	    android:layout_marginBottom="@dimen/space_10"
	    />
</LinearLayout>


text:
<project name="XTF" default="compile" basedir=".">

  <description>
      eXtensible Text Framework
  </description>

  <!-- set global properties for this build -->
  <property name="src1"    location="src"/>
  <property name="src2"    location="contrib/xtf-lucene/src/java"/>
  <property name="classes" location="classes"/>
  <property name="dist"    location="dist"/>
  <property name="lib"     location="lib"/>
  <property name="cdlLib"  location="cdlLib"/>
  <property name="bin"     location="bin"/>
  <property name="doc"     location="javadoc"/>
  <property name="lucene-jar" location="${lib}/lucene-core-2.1.0.jar"/>
  <property name="saxon-jar" location="${lib}/saxonb-8.9.jar"/>
  <property name="libs"    value="${lucene-jar}:${saxon-jar}:${lib}/servlet.jar:${lib}/pdfBox.jar:${lib}/fontBox.jar:${lib}/log4j-1.2.9.jar:${lib}/Tidy.jar:${lib}/cql-java.jar:${lib}/marc4j.jar:${lib}/activation.jar:${lib}/mail.jar:${lib}/tm-extractors-1.0.jar:${lib}/poi-3.0.2-FINAL.jar:${lib}/fop-core-0.94.jar:${lib}/fop-libs-0.94.jar:${lib}/iText.jar"/>

  <target name="init">
    <!-- Create the time stamp -->
    <tstamp/>
    <!-- Create the build directory structure used by compile -->
    <mkdir dir="${classes}"/>
  </target>

  <!-- ================================================== compile -->
  <target name="compile" depends="init"
        description="compile the source " >
    <!-- Compile the java code from ${src} into ${classes} -->
    <javac target="1.5"
           source="1.5"
           debug="true"
           classpath="${libs}"
           encoding="UTF-8"
           excludes="**/.*/**/*"
           destdir="${classes}">
      <src path="${src1}"/>
      <src path="${src2}"/>
    </javac>
  </target>

  <target name="tokenizer" description="compile the XTF tokenizer">
    <javacc target="${src1}/org/cdlib/xtf/textIndexer/tokenizer/XTFTokenizer.jj"
                        javacchome="${lib}"/>
  </target>

  <!-- ================================================== jar -->
  <target name="jar" depends="compile"
          description="generate a JAR file">

    <mkdir dir="${dist}"/>

    <!-- Copy the Lucene class files -->
    <delete dir="jar-tmp" quiet="true"/>
    <mkdir dir="jar-tmp"/>

    <unzip src="${lucene-jar}" dest="jar-tmp"/>

    <!-- Copy the Saxon class files -->
    <unzip src="${saxon-jar}" dest="jar-tmp"/>

    <!-- Add/overwrite with the XTF classes -->
    <copy todir="jar-tmp" overwrite="true">
      <fileset dir="${classes}"/>
    </copy>

    <!-- Add/overwrite with the XTF classes -->
    <delete file="${dist}/xtf.jar" quiet="true"/>
    <jar jarfile="${dist}/xtf.jar" basedir="jar-tmp"/>

    <delete dir="jar-tmp" quiet="true"/>
  </target>

  <!-- ================================================== dist -->
  <target name="dist" depends="jar,docs"
          description="generate the distribution" >
    <!-- Create the distribution directory -->
    <mkdir dir="${dist}"/>

    <!-- Create a temp directory for the build -->
    <delete dir="build-tmp" quiet="true"/>
    <mkdir dir="build-tmp"/>
    <mkdir dir="build-tmp/WEB-INF"/>
    <mkdir dir="build-tmp/WEB-INF/lib"/>

    <!-- Copy the jar file containing the XTF classes -->
    <copy todir="build-tmp/WEB-INF/lib" file="${dist}/xtf.jar"/>

    <!-- Zip up the regression tests -->
    <zip zipfile="build-tmp/regress.zip">
      <fileset dir="..">
        <include name="regress/**/*"/>
        <exclude name="regress/**/IndexDB/**/*"/>
        <exclude name="regress/**/*-test.xml"/>
        <include name="bin/regressTest"/>
      </fileset>
    </zip>

    <!-- Make a zip file of all the source code, plus the extra
         libraries needed to build it.
    -->
    <zip zipfile="build-tmp/WEB-INF/src.zip">
      <fileset dir="." includes="src/**/*.java"/>
      <fileset dir="." includes="src/**/*.xml"/>
      <fileset dir="." includes="src/**/*.jj"/>
      <fileset dir="." includes="src/**/*.html"/>
      <fileset dir="." includes="contrib/**/*.java"/>
      <fileset dir="." includes="contrib/**/*.html"/>
      <fileset dir="." includes="lib/lucene*.jar"/> <!-- Normally part of xtf.jar, needed for build -->
      <fileset dir="." includes="lib/saxon*.jar"/> <!-- Normally part of xtf.jar, needed for build -->
      <fileset dir="." includes="lib/servlet.jar"/> <!-- Only needed for source build -->
    </zip>

    <!-- Zip up the JavaDocs -->
    <zip zipfile="build-tmp/WEB-INF/javadoc.zip">
      <fileset dir="." includes="javadoc/**/*"/>
    </zip>

    <!-- Copy the remaining files to the temporary build dir -->
    <copy todir="build-tmp">
      <fileset dir="..">

        <exclude name="**/backup"/>
        <exclude name="**/backup/**/*"/>
        <exclude name="**/.*"/>
        <exclude name="**/.*/**/*"/>
        <exclude name="**/CVS/**/*"/>
        <exclude name="style/crossQuery/complexQueryParser.xsl"/>

        <include name="bin/classpath.pl"/>
        <include name="bin/textIndexer"/>
        <include name="bin/indexStats"/>
        <include name="bin/indexDump"/>
        <include name="bin/indexMerge"/>
        <include name="bin/textIndexer.bat"/>

        <include name="brand/default.xml"/>

        <include name="conf/**/*"/>

        <include name="css/**/*"/>

        <include name="icons/default/**/*"/>

        <include name="profiles/**/public*"/>
        <include name="profiles/**/default*"/>

        <include name="script/**/*"/>

        <include name="style/**/*"/>

        <include name="INSTALL"/>

        <include name="LICENSE"/>
        <include name="licenses/**/*"/>
        <include name="CHANGES"/>

        <include name="docs/**/*"/>

        <include name="WEB-INF/build.xml"/>
        <include name="WEB-INF/web.xml"/>
        <include name="WEB-INF/lib/versions.txt"/>
        <include name="WEB-INF/lib/*.jar"/>
        <exclude name="WEB-INF/lib/servlet.jar"/> <!-- only needed in src.zip -->
        <exclude name="WEB-INF/lib/lucene-*.jar"/> <!-- Included in xtf.jar -->
        <exclude name="WEB-INF/lib/saxon*.jar"/> <!-- Included in xtf.jar -->

      </fileset>
    </copy>

    <!-- Now make the main distribution WAR file -->
    <delete file="${dist}/xtf-${DSTAMP}.war" quiet="true"/>
    <jar jarfile="${dist}/xtf-${DSTAMP}.war">
      <fileset dir="build-tmp">
        <include name="**/*"/>
      </fileset>
    </jar>

    <!-- Make a subset for the "core" distribution -->
    <delete file="${dist}/xtf-core-${DSTAMP}.zip" quiet="true"/>
    <zip destfile="${dist}/xtf-core-${DSTAMP}.zip">
      <fileset dir="build-tmp">
        <include name="bin/**/*"/>
        <include name="WEB-INF/**/*"/>
        <include name="INSTALL"/>
        <include name="LICENSE"/>
        <include name="licenses/**/*"/>
        <include name="regress.zip"/>
        <include name="docs/**/*"/>
      </fileset>
    </zip>

    <!-- Make a subset for the "example" distribution -->
    <delete file="${dist}/xtf-example-${DSTAMP}.zip" quiet="true"/>
    <zip destfile="${dist}/xtf-example-${DSTAMP}.zip">
      <fileset dir="build-tmp">
        <include name="brand/**/*"/>
        <include name="conf/**/*"/>
        <include name="css/**/*"/>
        <include name="icons/**/*"/>
        <include name="profiles/**/*"/>
        <include name="script/**/*"/>
        <include name="style/**/*"/>
      </fileset>
    </zip>

    <delete dir="build-tmp" quiet="true"/>
    <delete file="${dist}/xtf.jar" quiet="true"/>
  </target>

  <!-- ================================================== docs -->
  <target name="docs"
          description="generate javadoc documentation.">
    <javadoc destdir="${doc}"
             private="true"
             breakiterator="yes"
             source="1.5"
             encoding="UTF-8"
             classpath="${libs}"
             noqualifier="all">
      <tag name=".notes" description="Notes:"/>

      <packageset dir="${src1}">
        <include name="**"/>
        <exclude name="**/.*/**"/>

        <!-- Exclude the generated code because it has javadoc warnings
             we can't fix.
        -->
        <exclude name="**/org/cdlib/xtf/textIndexer/tokenizer/**"/>
      </packageset>

      <packageset dir="${src2}">
        <include name="**"/>
        <exclude name="**/.*/**"/>
      </packageset>

    </javadoc>
  </target>

  <!-- ================================================== clean -->
  <target name="clean"
        description="clean up" >
    <!-- Delete the ${classes} and ${dist} directory trees -->
    <delete dir="${classes}" quiet="true"/>
    <delete dir="${dist}" quiet="true"/>
    <delete dir="${doc}" quiet="true"/>
  </target>
</project>


text:
package com.royalrangers.service.achievement;

import com.royalrangers.dto.achievement.UserAchievementRequestDto;
import com.royalrangers.enums.UserAgeGroup;
import com.royalrangers.enums.achivement.AchievementState;
import com.royalrangers.model.achievement.UserQuarterAchievement;
import com.royalrangers.repository.achievement.UserQuarterAchievementRepository;
import com.royalrangers.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserQuarterAchievementService {

    @Autowired
    private UserQuarterAchievementRepository userQuarterAchievementRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private QuarterAchievementService quarterAchievementService;

    public List<UserQuarterAchievement> findAllForUser() {
        return userQuarterAchievementRepository.findByUserId(userService.getAuthenticatedUserId());
    }

    public void addUserQuarterAchievement(UserAgeGroup userAgeGroup) {
        UserQuarterAchievement savedUserAchievement = new UserQuarterAchievement();
        savedUserAchievement.setUserAgeGroup(userAgeGroup);
        savedUserAchievement.setAchievementState(AchievementState.IN_PROGRESS);
        savedUserAchievement.setUser(userService.getUserById(userService.getAuthenticatedUserId()));
        Integer quarterId;
        if (findAllForUser().size() == 0) {
            quarterId = 1;
        } else {
            quarterId = findAllForUser().size() + 1;
        }
        savedUserAchievement.setQuarterAchievement(quarterAchievementService.getQuarterAchievementById(quarterId.longValue()));
        savedUserAchievement.getQuarterAchievement().setUserAgeGroup(userAgeGroup);
        userQuarterAchievementRepository.saveAndFlush(savedUserAchievement);
    }

    public UserQuarterAchievement getUserQuarterAchievementById(Long id) {
        return userQuarterAchievementRepository.findOne(id);
    }

    public List<UserQuarterAchievement> getUserQuarterAchievementByAchievementId(Long achievementId) {
        return userQuarterAchievementRepository.findAllByQuarterAchievement(achievementId);
    }

    public void deleteUserQuarterAchievement(Long id) {
        userQuarterAchievementRepository.delete(id);
    }

    public UserQuarterAchievement editUserQuarterAchievement(UserAchievementRequestDto params, Long id) {
        UserQuarterAchievement savedUserAchievement = userQuarterAchievementRepository.findOne(id);
        savedUserAchievement.setUpdateDate(new Date());
        String achievementState = params.getState();
        savedUserAchievement.setAchievementState(AchievementState.valueOf(achievementState));
        Integer quarterId = params.getId();
        savedUserAchievement.setQuarterAchievement(quarterAchievementService.getQuarterAchievementById(quarterId.longValue()));
        return userQuarterAchievementRepository.saveAndFlush(savedUserAchievement);
    }

    public void autoEditQuarterAchievement(AchievementState achievementState, UserAgeGroup userAgeGroup) {
        List<UserQuarterAchievement> userQuarterAchievementList = userQuarterAchievementRepository.findByUserAgeGroup(userAgeGroup);
        UserQuarterAchievement savedUserAchievement = userQuarterAchievementList.get(userQuarterAchievementList.size() - 1);
        savedUserAchievement.setUpdateDate(new Date());
        savedUserAchievement.setAchievementState(achievementState);
        userQuarterAchievementRepository.saveAndFlush(savedUserAchievement);
    }
}


text:
#ifndef ELLIGATOR_H__
#define ELLIGATOR_H__

#include <inttypes.h>
#include <memory>
#include <openssl/bn.h>

namespace i2p
{
namespace crypto
{

	class Elligator2
	{
		public:

			Elligator2 ();
			~Elligator2 ();

			bool Encode (const uint8_t * key, uint8_t * encoded, bool highY = false, bool random = true) const;
			bool Decode (const uint8_t * encoded, uint8_t * key) const;

		private:

			void SquareRoot (const BIGNUM * x, BIGNUM * r, BN_CTX * ctx) const;
			int Legendre (const BIGNUM * a, BN_CTX * ctx) const; // a/p

		private:

			BIGNUM * p, * p38, * p12, * p14, * sqrtn1, * A, * nA, * u, * iu;
	};

	std::unique_ptr<Elligator2>& GetElligator ();
}
}

#endif


text:
#include "SkBitmapRegionDecoder.h"

bool SkBitmapRegionDecoder::decodeRegion(SkBitmap* bitmap, const SkIRect& rect,
                                         SkBitmap::Config pref, int sampleSize) {
    fDecoder->setSampleSize(sampleSize);
    return fDecoder->decodeRegion(bitmap, rect, pref);
}


text:
<?php

namespace Exifer\Exif\Gps;

use Exifer\Common\Tag;

/**
 * @author  Igor Golovanov <igor.golovanov@gmail.com>
 */
abstract class GpsTag extends Tag implements GpsTagInteface
{
    /**
     * {@inheritDoc}
     */
    protected $name = 'GPS Unknown Tag';
}


text:
set -e
set -x

source ~/.profile

# Init Arduino
cd ~

sudo apt-get install -y ca-certificates

# Install Arduino-CLI (specific version)
# To keep in sync with the version
# defined in apps/microtvm/arduino/template_project/microtvm_api_server.py
ARDUINO_CLI_VERSION="0.18.3"

export PATH="/home/vagrant/bin:$PATH"
wget -O - https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | sh -s ${ARDUINO_CLI_VERSION}

# Arduino (the CLI and GUI) require the dialout permission for uploading
sudo usermod -a -G dialout $USER

# ubuntu_init_arduino.sh only installs a few officially
# supported architectures, so we don't use it here

# 3rd party board URLs
ADAFRUIT_BOARDS_URL="https://adafruit.github.io/arduino-board-index/package_adafruit_index.json"
ESP32_BOARDS_URL="https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json"
SPARKFUN_BOARDS_URL="https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json"
SEEED_BOARDS_URL="https://files.seeedstudio.com/arduino/package_seeeduino_boards_index.json"
SPRESENSE_BOARDS_URL="https://github.com/sonydevworld/spresense-arduino-compatible/releases/download/v2.2.1/package_spresense_index.json"
arduino-cli core update-index --additional-urls $ADAFRUIT_BOARDS_URL,$ESP32_BOARDS_URL,$SPARKFUN_BOARDS_URL,$SEEED_BOARDS_URL,$SPRESENSE_BOARDS_URL

# Install supported cores from those URLS
arduino-cli version
arduino-cli core install arduino:mbed_nano
arduino-cli core install arduino:sam
arduino-cli core install adafruit:samd --additional-urls $ADAFRUIT_BOARDS_URL
arduino-cli core install esp32:esp32 --additional-urls $ESP32_BOARDS_URL
arduino-cli core install Seeeduino:samd --additional-urls $SEEED_BOARDS_URL
arduino-cli core install SPRESENSE:spresense --additional-urls $SPRESENSE_BOARDS_URL

# The Sony Spresense SDK has a major bug that breaks TVM. It's scheduled to be fixed in
# release 2.3.0, but until that's published we need to use the below hack. This ONLY
# fixes the bug in the main core release SDK - the subcore release SDK and both
# the main and subcore debug SDKs will continue to fail until an official fix is made.
# https://github.com/sonydevworld/spresense/issues/200
SPRESENSE_NUTTX_BUGFIX_PATH=~/.arduino15/packages/SPRESENSE/tools/spresense-sdk/2.2.1/spresense/release/nuttx/include/sys/types.h
sed -i 's/#ifndef CONFIG_WCHAR_BUILTIN/#if !defined(__cplusplus)/g' $SPRESENSE_NUTTX_BUGFIX_PATH

# There's also a bug in arduino-cli where {runtime.os} is not properly templated in
# platform.txt. This bug only seems to appear with the SPRESENSE SDK. A fix has been
# merged and will be part of arduino-cli 0.18.4, but that has yet to be published.
# This change is only needed to upload code (not compile) for the Spresense.
# https://github.com/arduino/arduino-cli/issues/1198
SPRESENSE_FLASH_WRITER_BUGFIX_PATH=~/.arduino15/packages/SPRESENSE/hardware/spresense/2.2.1/platform.txt
sed -i 's/tools.spresense-tools.cmd.path={path}\/flash_writer\/{runtime.os}\/flash_writer/tools.spresense-tools.cmd.path={path}\/flash_writer\/linux\/flash_writer/g' $SPRESENSE_FLASH_WRITER_BUGFIX_PATH
sed -i 's/tools.spresense-tools.cmd.path.linux={path}\/flash_writer\/{runtime.os}\/flash_writer/tools.spresense-tools.cmd.path.linux={path}\/flash_writer\/linux\/flash_writer/g' $SPRESENSE_FLASH_WRITER_BUGFIX_PATH

# Cleanup
rm -f *.sh


text:
/***********************************************************************
    created:    5/4/2005
    author:     Tomas Lindquist Olsen (based on code by Paul D Turner)

    purpose:    Implementation of MenuBase widget base class
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/widgets/MenuBase.h"
#include "CEGUI/widgets/PopupMenu.h"
#include "CEGUI/widgets/MenuItem.h"

namespace CEGUI
{
const String MenuBase::EventNamespace("MenuBase");
const String MenuBase::EventPopupOpened("PopupOpened");
const String MenuBase::EventPopupClosed("PopupClosed");

//----------------------------------------------------------------------------//
MenuBase::MenuBase(const String& type, const String& name)
    : ItemListBase(type, name)
{
    addMenuBaseProperties();
}

//----------------------------------------------------------------------------//
void MenuBase::changePopupMenuItem(MenuItem* item)
{
    if (!d_allowMultiplePopups && d_popupItem == item)
        return;

    if (!d_allowMultiplePopups && d_popupItem)
    {
        WindowEventArgs we(d_popupItem->getPopupMenu());
        d_popupItem->closePopupMenu(false);
        d_popupItem = nullptr;
        onPopupClosed(we);
    }

    if (item)
    {
        d_popupItem = item;
        d_popupItem->openPopupMenu(false);
        WindowEventArgs we(d_popupItem->getPopupMenu());
        onPopupOpened(we);
    }
}

//----------------------------------------------------------------------------//
void MenuBase::onPopupOpened(WindowEventArgs& e)
{
    fireEvent(EventPopupOpened, e, EventNamespace);
}

//----------------------------------------------------------------------------//
void MenuBase::onPopupClosed(WindowEventArgs& e)
{
    fireEvent(EventPopupClosed, e, EventNamespace);
}

//----------------------------------------------------------------------------//
void MenuBase::setAllowMultiplePopups(bool setting)
{
    if (d_allowMultiplePopups != setting)
    {
        if (!setting)
            closeAllChildPopups();
        d_allowMultiplePopups = setting;
    }
}

//----------------------------------------------------------------------------//
void MenuBase::setPopupMenuItemClosing()
{
    if (d_popupItem)
        d_popupItem->startPopupClosing();
}

//----------------------------------------------------------------------------//
void MenuBase::closeAllChildPopups()
{
    for (auto item : d_listItems)
    {
        if (auto menuItem = dynamic_cast<MenuItem*>(item))
        {
            if (!menuItem->getPopupMenu())
                continue;

            WindowEventArgs we(menuItem->getPopupMenu());
            menuItem->closePopupMenu(false);
            onPopupClosed(we);
        }
    }
}

//----------------------------------------------------------------------------//
void MenuBase::onChildRemoved(ElementEventArgs& e)
{
    // If the removed window was our tracked popup item, zero ptr to it.
    if (e.element == d_popupItem)
        d_popupItem = nullptr;

    ItemListBase::onChildRemoved(e);
}

//----------------------------------------------------------------------------//
void MenuBase::onHidden(WindowEventArgs&)
{
    if (!getAutoCloseNestedPopups())
        return;

    changePopupMenuItem(nullptr);

    if (d_allowMultiplePopups)
        closeAllChildPopups();
}

//----------------------------------------------------------------------------//
void MenuBase::addMenuBaseProperties()
{
    const String propertyOrigin = "CEGUI/MenuBase";

    CEGUI_DEFINE_PROPERTY(MenuBase, float,
        "ItemSpacing", "Property to get/set the item spacing of the menu.  Value is a float.",
        &MenuBase::setItemSpacing, &MenuBase::getItemSpacing, 10.0f
    );

    CEGUI_DEFINE_PROPERTY(MenuBase, bool,
        "AllowMultiplePopups", "Property to get/set the state of the allow multiple popups setting for the menu.  Value is either \"true\" or \"false\".",
        &MenuBase::setAllowMultiplePopups, &MenuBase::isMultiplePopupsAllowed, false /* TODO: Inconsistency and awful English */
    );

    CEGUI_DEFINE_PROPERTY(MenuBase, bool,
        "AutoCloseNestedPopups", "Property to set if the menu should close all its open child popups, when it gets hidden. Value is either \"true\" or \"false\".",
        &MenuBase::setAutoCloseNestedPopups, &MenuBase::getAutoCloseNestedPopups, false
    );

    CEGUI_DEFINE_PROPERTY(MenuBase, MenubarDirection,
        "MenubarDirection", "Property to get/set the direction in which child popups should open, or the manner in which this direction is determined. Value is either \"Down\", or \"Up\".",
        &MenuBase::setMenubarDirection, &MenuBase::getMenubarDirection, MenubarDirection::Down
    );
}

}


text:
using UnityEngine;
using System.IO;

namespace MeshEngine.Test {
    [IntegrationTest.DynamicTest("mesh-maker-scene")]
    [IntegrationTest.SucceedWithAssertions]
    [IntegrationTest.Timeout(5)]

    public class PersistanceManagerObjTest : MonoBehaviour {
        private void Start() {
            IntegrationTestManager testManager = new IntegrationTestManager();
            Mesh mesh = testManager.mesh;

            // ------------------
            // OBJ with UVs
            // ------------------
            mesh.persistence.Load("test_files/vive_teleporter");
            testManager.Assert(mesh.vertices.vertices.Count == 101);
            testManager.Assert(mesh.triangles.triangles.Count == 336);
            testManager.Assert(mesh.materials.MaterialNames().Count == 112);
            testManager.Assert(mesh.materials.GetMaterials().Count == 4);

            mesh.vertices.BuildVertices();
            mesh.triangles.BuildTriangles();

            testManager.Assert(mesh.uMesh.uv.Length == 101);

            mesh.persistence.Save("Temp/test.obj");

            ImportObj importObj = new ImportObj();
            importObj.Load("Temp/test.obj");
            testManager.Assert(importObj.vertices.Count == 101);
            testManager.Assert(importObj.uvs.Count == 101);
            testManager.Assert(importObj.triangles.Count == 336);
            testManager.Assert(importObj.materialNames.Count == 112);
            testManager.Assert(importObj.materials.Count == 4);

            testManager.Assert(File.Exists("Temp/test.obj"));
            File.Delete("Temp/test.obj");
            testManager.Assert(File.Exists("Temp/test.mtl"));
            File.Delete("Temp/test.mtl");

            testManager.Clear();
            importObj.Clear();

            // ------------------
            // OBJ without UVs
            // ------------------
            mesh.persistence.Load("test_files/pikachu");
            testManager.Assert(mesh.vertices.vertices.Count == 208);
            testManager.Assert(mesh.triangles.triangles.Count == 412 * 3);
            testManager.Assert(mesh.materials.MaterialNames().Count == 412);
            testManager.Assert(mesh.materials.GetMaterials().Count == 2);

            mesh.vertices.BuildVertices();
            mesh.triangles.BuildTriangles();

            testManager.Assert(mesh.uMesh.uv.Length == 208);

            mesh.persistence.Save("Temp/test.obj");

            importObj.Load("Temp/test.obj");
            testManager.Assert(importObj.vertices.Count == 208);
            testManager.Assert(importObj.uvs.Count == 208);
            testManager.Assert(importObj.triangles.Count == 412 * 3);
            testManager.Assert(importObj.materialNames.Count == 412);
            testManager.Assert(importObj.materials.Count == 2);

            testManager.Assert(File.Exists("Temp/test.obj"));
            File.Delete("Temp/test.obj");
            testManager.Assert(File.Exists("Temp/test.mtl"));
            File.Delete("Temp/test.mtl");

            IntegrationTest.Pass(gameObject);
        }
    }
}
#endif


text:
const ffmpegPath = require('@ffmpeg-installer/ffmpeg')
const ffmpeg = require('fluent-ffmpeg')
const Telegraf = require('telegraf')
const ytdl = require('ytdl-core')
const redis = require('redis')
const fs = require('fs')

const { NODE_ENV, TELEGRAM, REDIS } = process.env

ffmpeg.setFfmpegPath(ffmpegPath.path)

const pub = redis.createClient(REDIS)
const sub = redis.createClient(REDIS)

const Bot = new Telegraf(TELEGRAM)

sub.subscribe(`fetch-${NODE_ENV}`)
sub.on('message', (channel, message) => {
  const { id, _id, user_id } = JSON.parse(message)
  Bot.telegram.sendChatAction(user_id, 'typing')
  return new Promise((resolve, reject) => {
    const stream = ytdl(id)
    stream.on('error', err => reject(err))
    stream.on('info', ({ title, length_seconds, livestream }, { audioEncoding }) => {
      if(livestream) reject('Raven doesn\'t support live streams')
      if(length_seconds > 3300) reject('Video is too long')
      stream.pipe(fs.createWriteStream(`media/${_id}`))
      stream.on('finish', () => ffmpeg()
        .input(`media/${_id}`)
        .audioCodec(audioEncoding === 'aac' ? 'copy' : 'aac')
        .noVideo()
        .save(`media/${_id}.m4a`)
        .on('error', err => reject(err))
        .on('end', () => resolve({ url: `media/${_id}.m4a`, caption: title, duration: length_seconds })))
    })
  }).then(({ url, caption, duration }) => {
    const s = caption.split(' - ')
    Bot.telegram.sendChatAction(user_id, 'upload_audio')
    Bot.telegram.sendAudio(user_id, { source: url }, { caption: caption, duration: duration, performer: s.shift(), title: s.join(' - ') || ' ' })
      .then(res => pub.publish(`response-${NODE_ENV}`, JSON.stringify({ _id: _id, file_id: res.audio.file_id, caption: caption })))
      .catch(err => pub.publish(`response-${NODE_ENV}`, JSON.stringify({ _id: _id, err: 'Couldn\'t upload the song to Telegram. Please, try again' })))
      .then(() => fs.unlink(url, () => {}))
  }).catch(err => {
    pub.publish(`response-${NODE_ENV}`, JSON.stringify({ _id: _id, err: err.message || err }))
  }).then(() => fs.unlink(`media/${_id}`, () => {}))
})


text:
package atomic

import (
	"encoding/json"
	"strconv"
	"sync/atomic"
)

// Uintptr is an atomic wrapper around uintptr.
type Uintptr struct {
	_ nocmp // disallow non-atomic comparison

	v uintptr
}

// NewUintptr creates a new Uintptr.
func NewUintptr(i uintptr) *Uintptr {
	return &Uintptr{v: i}
}

// Load atomically loads the wrapped value.
func (i *Uintptr) Load() uintptr {
	return atomic.LoadUintptr(&i.v)
}

// Add atomically adds to the wrapped uintptr and returns the new value.
func (i *Uintptr) Add(n uintptr) uintptr {
	return atomic.AddUintptr(&i.v, n)
}

// Sub atomically subtracts from the wrapped uintptr and returns the new value.
func (i *Uintptr) Sub(n uintptr) uintptr {
	return atomic.AddUintptr(&i.v, ^(n - 1))
}

// Inc atomically increments the wrapped uintptr and returns the new value.
func (i *Uintptr) Inc() uintptr {
	return i.Add(1)
}

// Dec atomically decrements the wrapped uintptr and returns the new value.
func (i *Uintptr) Dec() uintptr {
	return i.Sub(1)
}

// CAS is an atomic compare-and-swap.
func (i *Uintptr) CAS(old, new uintptr) bool {
	return atomic.CompareAndSwapUintptr(&i.v, old, new)
}

// Store atomically stores the passed value.
func (i *Uintptr) Store(n uintptr) {
	atomic.StoreUintptr(&i.v, n)
}

// Swap atomically swaps the wrapped uintptr and returns the old value.
func (i *Uintptr) Swap(n uintptr) uintptr {
	return atomic.SwapUintptr(&i.v, n)
}

// MarshalJSON encodes the wrapped uintptr into JSON.
func (i *Uintptr) MarshalJSON() ([]byte, error) {
	return json.Marshal(i.Load())
}

// UnmarshalJSON decodes JSON into the wrapped uintptr.
func (i *Uintptr) UnmarshalJSON(b []byte) error {
	var v uintptr
	if err := json.Unmarshal(b, &v); err != nil {
		return err
	}
	i.Store(v)
	return nil
}

// String encodes the wrapped value as a string.
func (i *Uintptr) String() string {
	v := i.Load()
	return strconv.FormatUint(uint64(v), 10)
}


text:
"""
Created by: Lee Bergstrand

Description:    Functions for HMMER-DB.
"""

# Imports & Setup:
import csv
import sys
from Bio import SeqIO
import subprocess
import re

# Regex's
LocusRegex = re.compile("\(Locus:\s\S*\)")
LocationRegex = re.compile("\(Location:\s\[(\S*)\:(\S*)\]\((\S)\)\)")

# ----------------------------------------------------------------------------------------
def extract_sequence_records(organism_file_path, file_type):
	"""
	Read in sequence files as a sequence record object using Biopython.

	:param organism_file_path: The path to the input file.
	:return: Biopython sequence record object.
	"""
	try:
		print(">> Opening FASTA file: " + organism_file_path)
		handle = open(organism_file_path, "rU")
		try:
			records = list(SeqIO.parse(handle, file_type))
		except ValueError as error:
			print("Error has occurred while parsing " + organism_file_path + "!")
			print(str(error))
			sys.exit(1)
		handle.close()
	except IOError:
		print("Failed to open " + organism_file_path)
		sys.exit(1)
	return records

# -----------------------------------------------------------------------------------------------------------
def check_extensions(organism_file_path, csv_file_path, hmm_file_paths, sql_file_paths):
	"""
	Performs file extension checks.

	:param organism_file_path: Path to the organism database file.
	:param csv_file_path: Path to the organism information database file.
	:param hmm_file_paths: Path to the HMM model file.
	:param sql_file_paths: Path to the sqlite3 file.
	"""
	print(">> Performing file extension checks...")
	if not organism_file_path.endswith(".faa"):
		print("[Warning] " + organism_file_path + " may not be a fasta file!")
	if not csv_file_path.endswith(".csv"):
		print("[Warning] " + csv_file_path + " may not be a csv file!")

	for hmm_path in hmm_file_paths:
		if not hmm_path.endswith(".hmm"):
			print("[Warning] " + hmm_path + " may not be a HMM file!")

	if not sql_file_paths.endswith(".sqlite"):
		print("[Warning] " + sql_file_paths + " may not be a sqlite file!")

# ----------------------------------------------------------------------------------------
def generate_fasta_string(sec_record_list):
	"""
	Creates a FASTA formatted string containing sequences from a list of sequence record objects.

	:param sec_record_list: List of Biopython sequence record objects.
	:return: String containing FASTA formatted strings.
	"""
	fasta_string_list = []

	for record in sec_record_list:
		fasta_string_list.append(record.format("fasta"))

	fasta_string = ''.join(fasta_string_list)
	return fasta_string

# ----------------------------------------------------------------------------------------
def generate_fasta_dict(sec_record_list):
	"""
	Creates a dictionary containing FASTA formatted strings from a list of sequence record objects.
	This dictionary is keyed by the sequence ID.

	:param sec_record_list: List of Biopython sequence record objects.
	:return: Dictionary containing FASTA formatted strings.
	"""
	fasta_string_dict = {}

	for record in sec_record_list:
		fasta_string_dict[record.id] = record.format("fasta")

	return fasta_string_dict

# ----------------------------------------------------------------------------------------
def hmm_search(fasta_string, hmmer_model_path, processes):
	"""
	Runs HMMER with settings specific for extracting subject sequences.

	:param fasta_string: String containing protein sequences in FASTA format.
	:param hmmer_model_path: Path to the HMM model to be used as a query.
	:return: String containing hmmsearch output.
	"""
	process = subprocess.Popen(["hmmsearch", "--acc", "--cpu", str(processes), hmmer_model_path, "-"],
	                           stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1)

	# This returns a list with both stderr and stdout. Only return stdout. Fail if error.
	stdout, error = process.communicate(fasta_string)
	if error:
		print(str(error))
		sys.exit(1)
	else:
		return stdout

# ------------------------------------------------------------------------------------------------------------
def get_hit_protein_data(hmm_hit_table, annotation_fasta_dict, organism_accession):
	"""
	Creates a list of lists which contain protein information.

	:param hmm_hit_table: Table of HMM hit objects.
	:param annotation_fasta_dict: Dictionary containing FASTA sequences keyed by their IDs
	:param organism_accession: The accession of the organism.
	:return: A list of lists of hit protein properties.
	"""
	hit_proteins = []
	for hit in hmm_hit_table:
		protein_accession = hit.target_protein
		protein_fasta = annotation_fasta_dict[protein_accession]

		locus = str(LocusRegex.search(protein_fasta).group(0))
		locus = locus.split()[1].rstrip(")")
		location_data = LocationRegex.search(protein_fasta)
		try:
			start = int(location_data.group(1))
			end = int(location_data.group(2))
			strand = location_data.group(3)
			protein_data = [protein_accession, organism_accession, locus, start, end, strand, protein_fasta]
			hit_proteins.append(protein_data)
		except AttributeError as error:
			print(hit)
			print(protein_fasta)
			print(location_data)
			print("This is the organism: ", organism_accession)
			print("The AttributeError was ", str(error))
			sys.exit(1)
	return hit_proteins

# -----------------------------------------------------------------------------------------------------------
def extract_csv_dict(input_csv_path):
	"""
	Opens OrganismDB CSV file for reading and stores as dictionary.

	:param input_csv_path: Path to the input OrganismDB CSV file.
	:return: Dictionary with each row in the CSV keyed by the organism accession (CSV row one).
	"""
	organism_data_csv = {}
	try:
		print(">> Opening organism CSV file: " + input_csv_path)
		read_file = open(input_csv_path, "r")
		reader = csv.reader(read_file)
		for row in reader:
			organism_data_csv[row[0].split('.')[0]] = row  # Row[0] is the organism accession.
		read_file.close()
	except IOError:
		print("Failed to open " + input_csv_path)
		sys.exit(1)

	return organism_data_csv

# -----------------------------------------------------------------------------------------------------------
def insert_organism_info(db_cursor, organism_info):
	"""
	Inserts organism info into DB.

	:param db_cursor: Sqlite3 database cursor.
	:param organism_info: List containing organism info.
	"""
	query = '''INSERT OR REPLACE INTO Organisms
(
	Organism_Accession,
	Accession_Type,
	Organism_Description,
	Source,
	Organism_Phylogeny,
	Sequence_Length
)
VALUES
	(?,?,?,?,?,?)'''

	db_cursor.execute(query, organism_info)

# -----------------------------------------------------------------------------------------------------------
# 8:
def insert_proteins(db_cursor, hit_proteins):
	"""
	Inserts protein info into DB.

	:param db_cursor: Sqlite3 database cursor.
	:param hit_proteins: List containing protein info.
	"""
	query = '''INSERT OR REPLACE INTO Proteins
(
	Protein_Accession,
	Organism_Accession,
	Locus,
	Start,
	"End",
	Strand,
	FASTA_Sequence
)
VALUES
	(?,?,?,?,?,?,?)'''

	for protein in hit_proteins:
		db_cursor.execute(query, protein)

# -----------------------------------------------------------------------------------------------------------
def insert_hits(cursor, hmm_hit_list):
	"""
	Inserts hits into DB and creates md5 hash for primary key.

	:param cursor: Sqlite3 database cursor.
	:param hmm_hit_list: List of hmm hit objects.
	"""
	query = '''INSERT OR REPLACE INTO HMM_Hits
(
	Hit_HASH,
	Protein_Accession,
	HMM_Model,
	HMM_Score,
	HMM_E_Value,
	Ali_From,
	Ali_To,
	HMM_From,
	HMM_To,
	HMM_Coverage
)
VALUES
	(?,?,?,?,?,?,?,?,?,?)'''

	for hit in hmm_hit_list:
		hit_list = [hit.get_md5(), hit.target_protein, hit.hmm_name, hit.score, hit.e_value, hit.ali_from, hit.ali_to,
		            hit.hmm_from, hit.hmm_to, hit.hmm_coverage]
		cursor.execute(query, hit_list)


text:
<?php namespace flow\db\migrations;
use flow\db\FFDB;
use flow\db\FFDBMigration;
use flow\db\LADBManager;
use flow\db\SafeMySQL;

if ( ! defined( 'WPINC' ) ) die;

class FFMigration_2_17 implements FFDBMigration {

	public function version() {
		return '2.17';
	}

	/**
	 * @param SafeMySQL $conn
	 * @param LADBManager $manager
	 */
	public function execute( $conn, $manager ) {
		if (!FFDB::existColumn(FF_SNAPSHOTS_TABLE_NAME, 'version')){
			$sql = "ALTER TABLE ?n ADD COLUMN ?n VARCHAR(25) DEFAULT '2.0'";
			$conn->query($sql, FF_SNAPSHOTS_TABLE_NAME, 'version');
		}
	}
}


text:
package core

import (
	"net/http"
)

// Create new File Server and returns RouteHandler
func FileServer(dir string) RouteHandler {
	return NoDirLock{RouteHandlerFunc(func(c *Context) {
		c.Http().Exec(http.FileServer(http.Dir(dir)))
	})}
}

func fileServer(path, dir string) RouteHandler {
	return RouteHandlerFunc(func(c *Context) {
		http.StripPrefix(path, http.FileServer(http.Dir(dir))).ServeHTTP(c.Res, c.Req)
	})
}


text:
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/* eslint-disable node/no-unsupported-features/node-builtins */

import * as assert from 'assert';
import {describe, it, before, afterEach} from 'mocha';
import {octokit, setup} from './util';
import * as sinon from 'sinon';
import {
  GetResponseTypeFromEndpointMethod,
  GetResponseDataTypeFromEndpointMethod,
} from '@octokit/types';
import {openPullRequest} from '../src/github/open-pull-request';

type ListPullsResponse = GetResponseTypeFromEndpointMethod<
  typeof octokit.pulls.list
>;

type ListPullsResponseData = GetResponseDataTypeFromEndpointMethod<
  typeof octokit.pulls.list
>;

type CreatePRResponse = GetResponseTypeFromEndpointMethod<
  typeof octokit.pulls.create
>;

type CreatePRResponseData = GetResponseDataTypeFromEndpointMethod<
  typeof octokit.pulls.create
>;

before(() => {
  setup();
});

describe('Opening a pull request', async () => {
  const sandbox = sinon.createSandbox();
  const upstream = {owner: 'upstream-owner', repo: 'upstream-repo'};
  const origin = {
    owner: 'origin-owner',
    repo: 'origin-repo',
    branch: 'pr-test-branch',
  };
  const description = {
    title: 'PR-TITLE',
    body: 'PR-DESCRIPTION',
  };
  afterEach(() => {
    sandbox.restore();
  });

  it('Invokes octokit pull create when there is not an existing pull request open', async () => {
    // setup
    const responseCreatePullData = (await import(
      './fixtures/create-pr-response.json'
    )) as unknown as CreatePRResponseData;
    const createPrResponse: CreatePRResponse = {
      headers: {},
      status: 201,
      url: 'http://fake-url.com',
      data: responseCreatePullData,
    };
    const listPullResponse: ListPullsResponse = {
      headers: {},
      status: 200,
      url: 'http://fake-url.com',
      data: [],
    };
    sandbox.stub(octokit.pulls, 'list').resolves(listPullResponse);
    const stub = sandbox
      .stub(octokit.pulls, 'create')
      .resolves(createPrResponse);
    // tests
    const number = await openPullRequest(
      octokit,
      upstream,
      origin,
      description,
      undefined,
      undefined,
      true
    );
    sandbox.assert.calledOnceWithExactly(stub, {
      owner: upstream.owner,
      repo: origin.repo,
      title: description.title,
      head: 'origin-owner:pr-test-branch',
      base: 'main',
      body: description.body,
      maintainer_can_modify: true,
      draft: true,
    });
    assert.strictEqual(number, 1347);
  });

  describe('When there are similar refs with pull requests open, the current new and unique ref still opens a pr', async () => {
    const responseCreatePullData = (await import(
      './fixtures/create-pr-response.json'
    )) as unknown as CreatePRResponseData;
    const responseListPullData = (await import(
      './fixtures/list-pulls-response.json'
    )) as unknown as ListPullsResponseData;
    afterEach(() => {
      sandbox.restore();
    });
    const createPrResponse: CreatePRResponse = {
      headers: {},
      status: 201,
      url: 'http://fake-url.com',
      data: responseCreatePullData,
    };
    const listPullResponse: ListPullsResponse = {
      headers: {},
      status: 200,
      url: 'http://fake-url.com',
      data: responseListPullData,
    };

    it('Invokes octokit pull create when the similar ref has a special character and number', async () => {
      // setup
      sandbox.stub(octokit.pulls, 'list').resolves(listPullResponse);
      const stub = sandbox
        .stub(octokit.pulls, 'create')
        .resolves(createPrResponse);

      const similarOrigin1 = {
        owner: 'octocat',
        repo: 'Hello-World',
        branch: 'new-topic-1',
      };
      // tests
      await openPullRequest(
        octokit,
        upstream,
        similarOrigin1,
        description,
        undefined,
        undefined,
        false
      );
      sandbox.assert.calledOnceWithExactly(stub, {
        owner: upstream.owner,
        repo: similarOrigin1.repo,
        title: description.title,
        head: 'octocat:new-topic-1',
        base: 'main',
        body: description.body,
        maintainer_can_modify: true,
        draft: false,
      });
    });

    it('Invokes octokit pull create when the existing ref has an extra number', async () => {
      // setup
      sandbox.stub(octokit.pulls, 'list').resolves(listPullResponse);
      const stub = sandbox
        .stub(octokit.pulls, 'create')
        .resolves(createPrResponse);

      const similarOrigin2 = {
        owner: 'octocat',
        repo: 'Hello-World',
        branch: 'new-topic1',
      };
      // tests
      await openPullRequest(octokit, upstream, similarOrigin2, description);
      sandbox.assert.calledOnceWithExactly(stub, {
        owner: upstream.owner,
        repo: similarOrigin2.repo,
        title: description.title,
        head: 'octocat:new-topic1',
        base: 'main',
        body: description.body,
        maintainer_can_modify: true,
        draft: false,
      });
    });

    it('Invokes octokit pull create when the existing ref has different capitalization', async () => {
      // setup
      sandbox.stub(octokit.pulls, 'list').resolves(listPullResponse);
      const stub = sandbox
        .stub(octokit.pulls, 'create')
        .resolves(createPrResponse);

      const similarOrigin3 = {
        owner: 'octocat',
        repo: 'Hello-World',
        branch: 'New-topic',
      };

      // tests
      await openPullRequest(octokit, upstream, similarOrigin3, description);
      sandbox.assert.calledOnceWithExactly(stub, {
        owner: upstream.owner,
        repo: similarOrigin3.repo,
        title: description.title,
        head: 'octocat:New-topic',
        base: 'main',
        body: description.body,
        maintainer_can_modify: true,
        draft: false,
      });
    });

    it('Invokes octokit pull create when the existing ref is a subsequence', async () => {
      // setup
      sandbox.stub(octokit.pulls, 'list').resolves(listPullResponse);
      const stub = sandbox
        .stub(octokit.pulls, 'create')
        .resolves(createPrResponse);

      const similarOrigin4 = {
        owner: 'octocat',
        repo: 'Hello-World',
        branch: 'new-topi',
      };
      // tests
      await openPullRequest(octokit, upstream, similarOrigin4, description);
      sandbox.assert.calledOnceWithExactly(stub, {
        owner: upstream.owner,
        repo: similarOrigin4.repo,
        title: description.title,
        head: 'octocat:new-topi',
        base: 'main',
        body: description.body,
        maintainer_can_modify: true,
        draft: false,
      });
    });
  });

  it('Does not invoke octokit pull create when there is an existing pull request open', async () => {
    // setup
    const responseListPullData = (await import(
      './fixtures/list-pulls-response.json'
    )) as unknown as ListPullsResponseData;
    const listPullResponse: ListPullsResponse = {
      headers: {},
      status: 200,
      url: 'http://fake-url.com',
      data: responseListPullData,
    };

    const conflictingOrigin = {
      owner: 'octocat',
      repo: 'Hello-World',
      branch: 'new-topic',
    };
    const listStub = sandbox
      .stub(octokit.pulls, 'list')
      .resolves(listPullResponse);
    const createStub = sandbox.stub(octokit.pulls, 'create');
    // tests
    await openPullRequest(octokit, upstream, conflictingOrigin, description);
    sandbox.assert.calledOnceWithExactly(listStub, {
      owner: upstream.owner,
      repo: conflictingOrigin.repo,
      head: 'octocat:new-topic',
    });
    sandbox.assert.notCalled(createStub);
  });

  it('Passes up the error message with a throw when octokit list pull fails', async () => {
    // setup
    const error = new Error('Error message');
    sandbox.stub(octokit.pulls, 'list').rejects(error);
    await assert.rejects(
      openPullRequest(octokit, upstream, origin, description),
      error
    );
  });

  it('Passes up the error message with a throw when octokit create pull fails', async () => {
    // setup
    const listPullResponse: ListPullsResponse = {
      headers: {},
      status: 200,
      url: 'http://fake-url.com',
      data: [],
    };
    sandbox.stub(octokit.pulls, 'list').resolves(listPullResponse);
    const error = new Error('Error message');
    sandbox.stub(octokit.pulls, 'create').rejects(error);
    await assert.rejects(
      openPullRequest(octokit, upstream, origin, description),
      error
    );
  });
});


text:
                <input type="checkbox" name="interests[<?php echo $id; ?>]" value="<?php echo $id; ?>" />

            <input type="text" class="form-control" readonly="" value="<?php echo $name; ?>" />