text:
package alluxio.client.file;

import alluxio.AlluxioURI;
import alluxio.Constants;
import alluxio.conf.PropertyKey;
import alluxio.exception.AlluxioException;
import alluxio.exception.FileDoesNotExistException;
import alluxio.grpc.ScheduleAsyncPersistencePOptions;
import alluxio.util.CommonUtils;
import alluxio.util.WaitForOptions;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Collection of utility methods to handle with {@link FileSystem} related objects.
 */
@ThreadSafe
public final class FileSystemUtils {
  private static final Logger LOG = LoggerFactory.getLogger(FileSystemUtils.class);

  // prevent instantiation
  private FileSystemUtils() {}

  /**
   * Shortcut for {@code waitCompleted(fs, uri, -1, TimeUnit.MILLISECONDS)}, i.e., wait for an
   * indefinite amount of time. Note that if a file is never completed, the thread will block
   * forever, so use with care.
   *
   * @param fs a {@link FileSystem} instance
   * @param uri the URI of the file on which the thread should wait
   * @return true if the file is complete when this method returns and false if the method timed out
   *         before the file was complete.
   * @throws InterruptedException if the thread receives an interrupt while waiting for file
   *         completion
   * @see #waitCompleted(FileSystem, AlluxioURI, long, TimeUnit)
   */
  public static boolean waitCompleted(FileSystem fs, AlluxioURI uri)
      throws IOException, AlluxioException, InterruptedException {
    return FileSystemUtils.waitCompleted(fs, uri, -1, TimeUnit.MILLISECONDS);
  }

  /**
   * Waits for a file to be marked as completed.
   *

   * The calling thread will block for at most {@code timeout} time units (as specified via
   * {@code tunit} or until the file is reported as complete by the master. The method will return
   * the last known completion status of the file (hence, false only if the method has timed out). A
   * zero value on the {@code timeout} parameter will make the calling thread check once and return;
   * a negative value will make it block indefinitely. Note that, in this last case, if a file is
   * never completed, the thread will block forever, so use with care.
   *

   * Note that the file whose uri is specified, might not exist at the moment this method this call.
   * The method will deliberately block anyway for the specified amount of time, waiting for the
   * file to be created and eventually completed. Note also that the file might be moved or deleted
   * while it is waited upon. In such cases the method will throw the a {@link AlluxioException}
   *

   * IMPLEMENTATION NOTES This method is implemented by periodically polling the master about
   * the file status. The polling period is controlled by the
   * {@link PropertyKey#USER_FILE_WAITCOMPLETED_POLL_MS} java property and defaults to a generous 1
   * second.
   *
   * @param fs an instance of {@link FileSystem}
   * @param uri the URI of the file whose completion status is to be watied for
   * @param timeout maximum time the calling thread should be blocked on this call
   * @param tunit the @{link TimeUnit} instance describing the {@code timeout} parameter
   * @return true if the file is complete when this method returns and false if the method timed out
   *         before the file was complete.
   * @throws InterruptedException if the thread receives an interrupt while waiting for file
   *         completion
   */
  public static boolean waitCompleted(final FileSystem fs, final AlluxioURI uri,
      final long timeout, final TimeUnit tunit)
      throws IOException, AlluxioException, InterruptedException {

    final long deadline = System.currentTimeMillis() + tunit.toMillis(timeout);
    final long fileWaitCompletedPollMs =
        fs.getConf().getMs(PropertyKey.USER_FILE_WAITCOMPLETED_POLL_MS);
    boolean completed = false;
    long timeleft = deadline - System.currentTimeMillis();

    while (!completed && (timeout <= 0 || timeleft > 0)) {

      if (!fs.exists(uri)) {
        LOG.debug("The file {} being waited upon does not exist yet. Waiting for it to be "
            + "created.", uri);
      } else {
        completed = fs.getStatus(uri).isCompleted();
      }

      if (timeout == 0) {
        return completed;
      } else if (!completed) {
        long toSleep;

        if (timeout < 0 || timeleft > fileWaitCompletedPollMs) {
          toSleep = fileWaitCompletedPollMs;
        } else {
          toSleep = timeleft;
        }

        CommonUtils.sleepMs(LOG, toSleep);
        timeleft = deadline - System.currentTimeMillis();
      }
    }
    return completed;
  }

  /**
   * Convenience method for {@code #persistAndWait(fs, uri, persistenceWaitTime, -1)}.
   * i.e. wait for an indefinite period of time to persist. This will block
   * for an indefinite period of time if the path is never persisted. Use with care.
   *
   * @param fs {@link FileSystem} to carry out Alluxio operations
   * @param uri the uri of the file to persist
   * @param persistenceWaitTime the persistence wait time
   */
  public static void persistAndWait(final FileSystem fs, final AlluxioURI uri,
      long persistenceWaitTime) throws FileDoesNotExistException, IOException, AlluxioException,
      TimeoutException, InterruptedException {
    persistAndWait(fs, uri, persistenceWaitTime, -1);
  }

  /**
   * Persists the given path to the under file system and returns once the persist is complete.
   * Note that if this method times out, the persist may still occur after the timeout period.
   *
   * @param fs {@link FileSystem} to carry out Alluxio operations
   * @param uri the uri of the file to persist
   * @param persistenceWaitTime the initial persistence wait time
   * @param timeoutMs max amount of time to wait for persist in milliseconds. -1 to wait
   *                  indefinitely
   * @throws TimeoutException if the persist takes longer than the timeout
   */
  public static void persistAndWait(final FileSystem fs, final AlluxioURI uri,
      long persistenceWaitTime, int timeoutMs) throws FileDoesNotExistException, IOException,
      AlluxioException, TimeoutException, InterruptedException {
    fs.persist(uri, ScheduleAsyncPersistencePOptions
        .newBuilder().setPersistenceWaitTime(persistenceWaitTime).build());
    CommonUtils.waitForResult(String.format("%s to be persisted", uri) , () -> {
      try {
        return fs.getStatus(uri);
      } catch (Exception e) {
        Throwables.throwIfUnchecked(e);
        throw new RuntimeException(e);
      }
    }, (status) -> status.isPersisted(),
        WaitForOptions.defaults().setTimeoutMs(timeoutMs).setInterval(100));
  }

  /**
   * Waits until the specified file has the desired percentage in Alluxio.
   *
   * @param fs the file system
   * @param uri the uri to check the percentage for
   * @param expectedPercentage the desired percentage
   */
  public static void waitForAlluxioPercentage(final FileSystem fs, final AlluxioURI uri,
      int expectedPercentage) throws TimeoutException, InterruptedException {
    CommonUtils
        .waitFor(uri.toString() + " is " + expectedPercentage + "% stored in Alluxio", () -> {
          try {
            return fs.getStatus(uri).getInAlluxioPercentage() == expectedPercentage;
          } catch (Exception e) {
            // ignore
            return false;
          }
        }, WaitForOptions.defaults().setTimeoutMs(30 * Constants.SECOND_MS));
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Duality.Resources;
using Duality.Utility.Coroutines;

namespace Duality.Utility.Coroutines
{
	public static class CoroutineSceneExtensions
	{
		/// <summary>
		/// Starts a coroutine and registers it in the scene's CoroutineManager
		/// </summary>
		/// <param name="scene">The Scene</param>
		/// <param name="method">The coroutine implementation</param>
		/// <param name="name">The name of the coroutine, optional</param>
		/// <returns>The created corutine</returns>
		public static Coroutine StartCoroutine(this Scene scene, IEnumerable<WaitUntil> method)
		{
			return scene.CoroutineManager.StartNew(method);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import numpy as np

from chainer.dataset import dataset_mixin

class MixUpSoftLabelDataset(dataset_mixin.DatasetMixin):

    """Dataset which returns mixed images and labels for mixup learning [#]_.

    :class:`MixUpSoftLabelDataset` mixes two pairs of labeled images fetched
    from the base dataset.

    Unlike `LabeledImageDatasets`, label is a one-dimensional float array with
    at most two nonnegative weights (i.e. soft label). The sum of the two
    weights is one.

    Example:

        We construct a mixup dataset from MNIST.

        .. code::

            >>> from chainer.datasets import get_mnist
            >>> from chainercv.datasets import SiameseDataset
            >>> from chainercv.datasets import MixUpSoftLabelDataset
            >>> mnist, _ = get_mnist()
            >>> base_dataset = SiameseDataset(mnist, mnist)
            >>> dataset = MixUpSoftLabelDataset(base_dataset, 10)
            >>> mixed_image, mixed_label = dataset[0]
            >>> mixed_label.shape
            (10,)
            >>> mixed_label.dtype
            dtype('float32')

    Args:
        dataset: The underlying dataset. The dataset returns :obj:`img_0,
            label_0, img_1, label_1`, which is a tuple containing two pairs
            of an image and a label. Typically, dataset is `SiameseDataset`.

            The shapes of images and labels should be constant.
        n_class (int): The number of classes in the base dataset.
        alpha (float): A hyperparameter of Beta distribution.
            ``mix_ratio`` is sampled from :math:`B(\\alpha,\\alpha)`.
            The default value is :math:`1.0` meaning that the distribution is
            the same as Uniform distribution with lower boundary of
            :math:`0.0` and upper boundary of :math:`1.0`.

    .. [#] Hongyi Zhang, Moustapha Cisse, Yann N. Dauphin, David Lopez-Paz.
        `mixup: Beyond Empirical Risk Minimization\
        <https://arxiv.org/abs/1710.09412>`_. arXiv 2017.

    This dataset returns the following data.

    .. csv-table::
        :header: name, shape, dtype, format

        :obj:`img`, [#mixup_1]_, [#mixup_1]_, [#mixup_1]_
        :obj:`label`, ":math:`(\#class,)`", :obj:`float32`, ":math:`[0, 1]`"

    .. [#mixup_1] Same as :obj:`dataset`.
    """

    def __init__(self, dataset, n_class, alpha=1.0):
        if alpha <= 0.0:
            raise ValueError(
                'Invalid value for a shape parameter ``alpha``.'
                ' It must be positive.')
        self._dataset = dataset
        self._n_class = n_class
        self._alpha = alpha

    def __len__(self):
        return len(self._dataset)

    def get_example(self, i):
        img_0, label_0, img_1, label_1 = self._dataset[i]
        mix_ratio = np.random.beta(self._alpha, self._alpha)

        image = mix_ratio * img_0 + (1-mix_ratio) * img_1
        label = np.zeros(self._n_class, dtype=np.float32)
        label[label_0] += mix_ratio
        label[label_1] += 1 - mix_ratio
        return image, label


text:
package org.apache.geode.internal.cache.backup;

import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.admin.remote.AdminResponse;

/**
 * The response to the {@link FlushToDiskRequest}
 *
 *
 */
public class FlushToDiskResponse extends AdminResponse {

  public FlushToDiskResponse() {
    super();
  }

  public FlushToDiskResponse(InternalDistributedMember sender) {
    this.setRecipient(sender);
  }

  public int getDSFID() {
    return FLUSH_TO_DISK_RESPONSE;
  }

  @Override
  public String toString() {
    return getClass().getName();
  }
}


text:
ActiveRecord::Schema.define(version: 2018_06_09_061208) do

  create_table "active_storage_attachments", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.string "name", null: false
    t.string "record_type", null: false
    t.bigint "record_id", null: false
    t.bigint "blob_id", null: false
    t.datetime "created_at", null: false
    t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
    t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
  end

  create_table "active_storage_blobs", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.string "key", null: false
    t.string "filename", null: false
    t.string "content_type"
    t.text "metadata"
    t.bigint "byte_size", null: false
    t.string "checksum", null: false
    t.datetime "created_at", null: false
    t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
  end

  create_table "delayed_jobs", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.integer "priority", default: 0, null: false
    t.integer "attempts", default: 0, null: false
    t.text "handler", null: false
    t.text "last_error"
    t.datetime "run_at"
    t.datetime "locked_at"
    t.datetime "failed_at"
    t.string "locked_by"
    t.string "queue"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["priority", "run_at"], name: "delayed_jobs_priority"
  end

  create_table "price_plans", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.string "name"
    t.integer "number_of_urls"
    t.boolean "screenshot"
    t.decimal "price", precision: 8, scale: 2
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "urls", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.text "original"
    t.string "mini"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "user_id"
    t.boolean "screenshot_requested", default: false
    t.index ["user_id"], name: "index_urls_on_user_id"
  end

  create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.string "email", null: false
    t.string "crypted_password"
    t.string "salt"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "activation_state"
    t.string "activation_code"
    t.datetime "activation_code_expires_at"
    t.string "remember_me_token"
    t.datetime "remember_me_token_expires_at"
    t.string "reset_password_token"
    t.datetime "reset_password_token_expires_at"
    t.datetime "reset_password_email_sent_at"
    t.datetime "last_login_at"
    t.datetime "last_logout_at"
    t.datetime "last_activity_at"
    t.string "last_login_from_ip_address"
    t.integer "failed_logins_count", default: 0
    t.datetime "lock_expires_at"
    t.boolean "admin", default: false
    t.string "name"
    t.integer "urls_count", default: 0
    t.bigint "price_plan_id", default: 1
    t.index ["activation_code"], name: "index_users_on_activation_code"
    t.index ["email"], name: "index_users_on_email"
    t.index ["last_logout_at", "last_activity_at"], name: "index_users_on_last_logout_at_and_last_activity_at"
    t.index ["price_plan_id"], name: "index_users_on_price_plan_id"
    t.index ["remember_me_token"], name: "index_users_on_remember_me_token"
  end

end


text:
<?php

namespace ViewComponents\Grids\Component;

use ViewComponents\ViewComponents\Base\ViewComponentInterface;
use ViewComponents\ViewComponents\Common\UriFunctions;
use ViewComponents\ViewComponents\Component\Compound;
use ViewComponents\ViewComponents\Component\DataView;
use ViewComponents\ViewComponents\Component\Html\Tag;
use ViewComponents\ViewComponents\Component\Part;
use ViewComponents\ViewComponents\Data\DataProviderInterface;
use ViewComponents\ViewComponents\Data\Operation\PaginateOperation;
use ViewComponents\ViewComponents\Input\InputOption;
use ViewComponents\Grids\Grid;

class CsvExport extends Part
{

    private $fileName = 'data.csv';
    private $csvDelimiter = ';';
    private $exitFunction;

    /**
     * @var InputOption
     */
    private $inputOption;

    public function __construct(InputOption $inputOption = null, ViewComponentInterface $controlView = null)
    {
        $this->inputOption = $inputOption;
        parent::__construct($controlView ?: $this->makeDefaultView(), 'csv_export', 'control_container');
    }

    /**
     * @param InputOption $inputOption
     * @return CsvExport
     */
    public function setInputOption($inputOption)
    {
        $this->inputOption = $inputOption;
        return $this;
    }

    /**
     * @return InputOption
     */
    public function getInputOption()
    {
        return $this->inputOption;
    }

    /**
     * Sets exit function.
     *
     * You may specify custom exit function to finish application cleanly.
     * 'exit' will be called after rendering CSV if no exit function specified.
     *
     * @param callable|null $exitFunction
     * @return $this
     */
    public function setExitFunction($exitFunction)
    {
        $this->exitFunction = $exitFunction;
        return $this;
    }

    /**
     * @return callable|null
     */
    public function getExitFunction()
    {
        return $this->exitFunction;
    }

    /**
     * @return string
     */
    public function getCsvDelimiter()
    {
        return $this->csvDelimiter;
    }

    /**
     * @param string $csvDelimiter
     * @return $this
     */
    public function setCsvDelimiter($csvDelimiter)
    {
        $this->csvDelimiter = $csvDelimiter;
        return $this;
    }

    /**
     * @param string $name
     * @return $this
     */
    public function setFileName($name)
    {
        $this->fileName = $name;
        return $this;
    }

    /**
     * @return string
     */
    public function getFileName()
    {
        return $this->fileName;
    }

    public function attachToCompound(Compound $root, $prepend = false)
    {
        // prepend component that will render results
        $root->children()->add(new DataView(function () {
            if ($this->inputOption->hasValue()) {
                $this->renderCsv();
            }
        }), true);
        parent::attachToCompound($root, $prepend);
    }

    protected function removePagination(DataProviderInterface $provider)
    {
        $pagination = $provider->operations()->findByType(PaginateOperation::class);
        if ($pagination) {
            $provider->operations()->remove($pagination);
        }
    }

    protected function renderCsv()
    {
        ob_clean(); // removes previous output from buffer if grid was rendered inside view
        $file = fopen('php://output', 'w');
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $this->getFileName() . '"');
        header('Pragma: no-cache');
        set_time_limit(0);
        /** @var Grid $grid */
        $grid = $this->root;
        $provider = $grid->getDataProvider();
        $this->renderHeadingRow($file);
        $this->removePagination($provider);
        foreach ($provider as $row) {
            $output = [];
            $grid->setCurrentRow($row);
            foreach ($grid->getColumns() as $column) {
                $output[] = $this->escapeString($column->getCurrentValueFormatted());
            }
            fputcsv($file, $output, $this->getCsvDelimiter());
        }
        fclose($file);
        $this->finishApplication();
    }

    protected function escapeString($str)
    {
        $str = html_entity_decode($str);
        $str = strip_tags($str);
        $str = str_replace('"', '\'', $str);
        $str = preg_replace('/\s+/', ' ', $str);
        $str = trim($str);
        return $str;
    }

    /**
     * @param resource $file
     */
    protected function renderHeadingRow($file)
    {
        $output = [];
        /** @var Grid $grid */
        $grid = $this->root;
        foreach ($grid->getColumns() as $column) {
            $output[] = $this->escapeString($column->getLabel());
        }
        fputcsv($file, $output, $this->getCsvDelimiter());
    }

    protected function finishApplication()
    {
        if (!$this->getExitFunction()) {
            exit;
        }
        call_user_func($this->getExitFunction());
    }

    public function getExportUrl()
    {
        return UriFunctions::modifyQuery(null, [$this->inputOption->getKey() => 1]);
    }

    protected function makeDefaultView()
    {
        $href = $this->getExportUrl();
        return new Tag(
            'button',
            [
                // required to avoid emitting 'click' on pressing enter
                'type' => 'button',
                'onclick' => "window.location='$href'; return false;",
                'style' => 'margin:2px;'
            ],
            [new DataView('CSV Export')]
        );
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">awwong1 HoloNote</string>
    <string name="save">Commit</string>
    <string name="clear">Refresh</string>
    <string name="delete">Delete</string>
    <string name="subject">Subject</string>
    <string name="content">Content</string>
    <string name="datetime">DateTime</string>
    <string name="title_activity_cloud">CloudActivity</string>
    <string name="action_settings">Settings</string>
    <string name="histogram_stats">Histogram/Stats</string>

</resources>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Lindström & Soop, Journal des JEC, Journées Européenes du Cortinaire 2(1): 59 (1999)

#### Original name
Cortinarius andreae H. Lindstr.

### Remarks
null


text:
//
// TODO: rewrite this to allow records with different sizes
//

#include "sdstream.h"
#include <dynamic_memory.h>
#include <sdcard/sdcard.h>
#include <platform.h>
#include <assert.h>
#include <codec.h>
#include <print.h>

#if DEBUG
#define SPRINTF PRINTF
#else
#define SPRINTF(...) // nothing
#endif

#define VERIFY 0

static volatile uint32_t sdCardAddress;

// TODO: use dynamic alloc
#ifndef SDSTREAM_MAX_RECORD_SIZE
#define SDSTREAM_MAX_RECORD_SIZE 40
#endif

static uint8_t tmpBuffer[SDSTREAM_MAX_RECORD_SIZE];

// XXX: crc, if present, is acutrrently always at buffer[2]
struct HeaderWithCrc_s {
    uint16_t __unused;
    uint16_t crc;
    uint8_t data[0];
} PACKED;
typedef struct HeaderWithCrc_s HeaderWithCrc_t;

void sdStreamReset(void)
{
    sdCardAddress = 0;
}

static void sdStreamFindStart(void *buffer, uint16_t length, bool crc)
{
    bool oneInvalid = false;
    sdCardAddress = SDCARD_RESERVED;

    while (sdCardAddress < SDCARD_SIZE) {
        // PRINTF("%lu\n", sdCardAddress);
        sdcardRead(sdCardAddress, buffer, length);
        bool valid = true;
        if (crc) {
            HeaderWithCrc_t headerWithCrc;
            memcpy(&headerWithCrc, buffer, sizeof(headerWithCrc));
            uint16_t calcCrc = crc16((uint8_t *)buffer + sizeof(headerWithCrc), length - sizeof(headerWithCrc));
            valid = headerWithCrc.crc == calcCrc;
        }
        if (valid) {
            // check if all fields are 0 - also count as invalid
            uint16_t i;
            valid = false;
            for (i = 0; i < length; ++i) {
                if (((uint8_t *)buffer)[i] != 0) {
                    valid = true;
                    break;
                }
            }
        }
        if (valid) {
            oneInvalid = false;
        } else {
            // XXX: this is supposed to find first non-packet, but it will find first two invalid packets!!
            if (!oneInvalid) {
                oneInvalid = true;
            } else {
                sdCardAddress -= length;
                break;
            }
        }
        sdCardAddress += length;
    }
}

bool sdStreamWriteRecord(void *data, uint16_t length, bool crc)
{
    ASSERT(length <= sizeof(tmpBuffer));

    // XXX hack
    if (serial[SDCARD_SPI_ID].busy) return false;

    if (sdCardAddress == 0) {
        //void *buffer = memoryAlloc(length);
        sdStreamFindStart(tmpBuffer, length, crc);
        //memoryFree(buffer);
    }

    // PRINTF("write record %u bytes at %lu\n", length, sdCardAddress);

    if (crc) {
        uint16_t calcCrc = crc16((uint8_t *)data + sizeof(HeaderWithCrc_t), length - sizeof(HeaderWithCrc_t));
        memcpy((uint8_t *)data + 2, &calcCrc, sizeof(calcCrc));
    }
    // PRINTF("sdcard write at %lu\n", sdCardAddress);
    sdcardWrite(sdCardAddress, data, length);
    // make sure it's saved to the card, not just in buffers
    sdcardFlush();
#if VERIFY
    //void *copy = memoryAlloc(length);
    sdcardRead(sdCardAddress, tmpBuffer, length);
    if (memcmp(data, tmpBuffer, length)) {
        ASSERT("writing in SD card failed!" && false);
    }
    //memoryFree(copy);
#endif
    sdCardAddress += length;
    return true;
}

bool sdStreamReadRecord(void *data, uint16_t length, bool crc)
{
    if (sdCardAddress == 0) sdStreamFindStart(data, length, crc);
    sdcardRead(sdCardAddress, data, length);
    if (crc) {
        HeaderWithCrc_t headerWithCrc;
        memcpy(&headerWithCrc, data, sizeof(headerWithCrc));
        uint16_t calcCrc = crc16((uint8_t *)data + sizeof(headerWithCrc), length - sizeof(headerWithCrc));
        return headerWithCrc.crc == calcCrc;
    }
    sdCardAddress += length;
    return true;
}


text:
$(document).ready(function(){
    // This button will increment the value
    $('.qtyplus').click(function(e){
        // Stop acting like a button
        e.preventDefault();
        // Get the field name
        fieldName = $(this).attr('field');
        // Get its current value
        var currentVal = parseInt($('input[name='+fieldName+']').val());
        // If is not undefined
        if (!isNaN(currentVal)) {
            // Increment
            $('input[name='+fieldName+']').val(currentVal + 1);
        } else {
            // Otherwise put a 0 there
            $('input[name='+fieldName+']').val(0);
        }
    });
    // This button will decrement the value till 0
    $(".qtyminus").click(function(e) {
        // Stop acting like a button
        e.preventDefault();
        // Get the field name
        fieldName = $(this).attr('field');
        // Get its current value
        var currentVal = parseInt($('input[name='+fieldName+']').val());
        // If it isn't undefined or its greater than 0
        if (!isNaN(currentVal) && currentVal > 0) {
            // Decrement one
            $('input[name='+fieldName+']').val(currentVal - 1);
        } else {
            // Otherwise put a 0 there
            $('input[name='+fieldName+']').val(0);
        }
    });
});


text:
"""
Testing file for `application` module of webhook-repeater app.
"""
import cStringIO as stringio
import pickle
import unittest

import webob
import mock

from repeater.application import (
    RequestSerializer,
    QueueHandler,
    Repeater,
    sign_request,
    check_remote_address,
    generate_inet_aton
)

class RequestSerializerTestCase(unittest.TestCase):
    def setUp(self):
        self.serializer = RequestSerializer()
        self.body = 'body'
        self.request = mock.Mock()
        self.request.environ = {
            'wsgi.input': stringio.StringIO(self.body),
            'wsgi.errors': None,
            'key1': 'value1',
            'key2': 'value2',
            'webob._body_file': "body_file"
        }
        self.string = pickle.dumps({
            "key1": "val1",
            "key2": "val2",
            "X-REPEATER-BODY": "body"
        })

    def test_serialize(self):
        string = self.serializer.dumps(self.request)
        assert "key2" in string
        assert "value2" in string
        assert "key1" in string
        assert "value1" in string
        assert "X-REPEATER-BODY" in string
        assert "body" in string

    def test_deserialize(self):
        req = self.serializer.loads(self.string)
        assert req.environ['key1'] == 'val1'
        assert req.environ['key2'] == 'val2'
        assert req.environ['wsgi.input'].read() == 'body'

class QueueMock(object):
    def __init__(self, queue=[]):
        self.queue = queue

    def append(self, req):
        self.queue.append(req)

    def pop(self):
        self.queue.pop(0)

    def top(self):
        return self.queue[0]

    def __nonzero__(self):
        return bool(self.queue)

class QueueHandlerTestCase(unittest.TestCase):
    def setUp(self):
        self.registry = mock.Mock()
        self.registry.settings = {
            'backoff_timeout': 1,
            'backoff_max_timeout': 4,
            'timeout': 2
        }

        self.queue = []
        queue_mock = QueueMock(self.queue)
        self.registry.construct_request_queue.return_value = queue_mock
        concurrency_utils = self.registry.get_concurrency_utils.return_value
        self.semaphore = concurrency_utils.semaphore.return_value
        self.semaphore.__exit__ = mock.Mock()
        self.semaphore.__enter__ = mock.Mock()
        self.concurrency_utils = concurrency_utils
        self.path1_proxy = object()
        self.path2_proxy = object()
        self.proxies = {
            'path1': self.path1_proxy,
            'path2': self.path2_proxy
        }

    def test_push(self):
        handler = QueueHandler('name', self.proxies, self.registry)
        request = mock.Mock()
        handler.push(request)

        assert self.queue[0] == request

    def test_spawn_on_push(self):
        handler = QueueHandler('name', self.proxies, self.registry)
        request = mock.Mock()
        handler.push(request)

        sem = self.semaphore
        assert sem.__enter__.call_count == sem.__exit__.call_count
        assert self.concurrency_utils.spawn.call_count == 1

    def test_spawn_form_constructor(self):
        self.queue[:] = [object()]
        QueueHandler('name', self.proxies, self.registry)

        sem = self.semaphore
        assert sem.__enter__.call_count == sem.__exit__.call_count
        assert self.concurrency_utils.spawn.call_count == 1

    def test_forwarding(self):
        req = mock.Mock()
        req.path_info = 'path1'
        resp = mock.Mock()
        resp.status_code = 200
        req.get_response.return_value = resp
        self.queue[:] = [req]
        QueueHandler('name', self.proxies, self.registry)

        worker = self.concurrency_utils.spawn.mock_calls[0][1][0]
        worker()
        assert not self.queue
        assert req.get_response.mock_calls[0][1] == (self.path1_proxy,)
        assert self.concurrency_utils.sleep.call_count == 0

    def test_forwarding_two_requests(self):
        req1 = mock.Mock()
        req1.path_info = 'path1'
        req2 = mock.Mock()
        req2.path_info = 'path2'
        resp = mock.Mock()
        resp.status_code = 200
        req1.get_response.return_value = resp
        req2.get_response.return_value = resp
        self.queue[:] = [req1, req2]
        QueueHandler('name', self.proxies, self.registry)

        worker = self.concurrency_utils.spawn.mock_calls[0][1][0]
        worker()
        assert not self.queue
        assert req1.get_response.mock_calls[0][1] == (self.path1_proxy,)
        assert req2.get_response.mock_calls[0][1] == (self.path2_proxy,)
        assert self.concurrency_utils.sleep.call_count == 1
        assert self.concurrency_utils.sleep.mock_calls[0][1] == (2,)

    def test_forwarding_until_400(self):
        """
        Test forwarding requests until any response will came from
        remote (in this case 400).
        """
        req = mock.Mock()
        req.path_info = 'path1'
        resp1 = mock.Mock()
        resp1.status_code = 400
        req.get_response.side_effect = [IOError(), IOError(), resp1]
        self.queue[:] = [req]
        QueueHandler('name', self.proxies, self.registry)

        worker = self.concurrency_utils.spawn.mock_calls[0][1][0]
        worker()
        assert not self.queue
        assert req.get_response.mock_calls[0][1] == (self.path1_proxy,)
        assert req.get_response.mock_calls[1][1] == (self.path1_proxy,)
        assert req.get_response.mock_calls[2][1] == (self.path1_proxy,)
        assert req.get_response.call_count == 3
        assert self.concurrency_utils.sleep.mock_calls[0][1] == (1,)
        assert self.concurrency_utils.sleep.mock_calls[1][1] == (2,)
        assert self.concurrency_utils.sleep.call_count == 2

    def test_forwarding_two_requests_with_fail(self):
        """
        Test forwarding requests until any response will came from
        remote (in this case 200).
        """
        req1 = mock.Mock()
        req1.path_info = 'path1'
        req2 = mock.Mock()
        req2.path_info = 'path2'
        resp = mock.Mock()
        resp.status_code = 200
        req1.get_response.side_effect = [IOError(), resp]
        req2.get_response.return_value = resp
        self.queue[:] = [req1, req2]
        QueueHandler('name', self.proxies, self.registry)

        worker = self.concurrency_utils.spawn.mock_calls[0][1][0]
        worker()
        assert not self.queue
        assert req1.get_response.mock_calls[0][1] == (self.path1_proxy,)
        assert req1.get_response.mock_calls[1][1] == (self.path1_proxy,)
        assert req1.get_response.call_count == 2
        assert req2.get_response.mock_calls[0][1] == (self.path2_proxy,)
        assert req2.get_response.call_count == 1
        assert self.concurrency_utils.sleep.mock_calls[0][1] == (1,)
        assert self.concurrency_utils.sleep.mock_calls[1][1] == (2,)
        assert self.concurrency_utils.sleep.call_count == 2

    def test_max_backoff(self):
        req1 = mock.Mock()
        req1.path_info = 'path1'
        resp = mock.Mock()
        resp.status_code = 200
        req1.get_response.side_effect = [
            IOError(),
            IOError(),
            IOError(),
            IOError(),
            resp
        ]
        self.queue[:] = [req1]
        QueueHandler('name', self.proxies, self.registry)

        worker = self.concurrency_utils.spawn.mock_calls[0][1][0]
        worker()
        assert not self.queue
        assert self.concurrency_utils.sleep.mock_calls[0][1] == (1,)
        assert self.concurrency_utils.sleep.mock_calls[1][1] == (2,)
        assert self.concurrency_utils.sleep.mock_calls[2][1] == (4,)
        assert self.concurrency_utils.sleep.mock_calls[3][1] == (4,)
        assert self.concurrency_utils.sleep.call_count == 4

    def test_forwarding_raise_exception(self):
        """
        Test catching exception raised by forward method.
        """
        req1 = mock.Mock()
        req1.path_info = 'path1'
        req2 = mock.Mock()
        req2.path_info = 'path2'
        resp = mock.Mock()
        resp.status_code = 200
        req1.get_response.side_effect = [KeyError(), resp]
        req2.get_response.return_value = resp
        self.queue[:] = [req1, req2]
        proxies = {
            'path1': '',
        }
        QueueHandler('name', proxies, self.registry)

        worker = self.concurrency_utils.spawn.mock_calls[0][1][0]
        worker()
        assert self.queue
        assert req1.get_response.mock_calls[0][1] == ('',)
        assert req1.get_response.call_count == 1
        assert len(req2.get_response.mock_calls) == 0
        assert self.concurrency_utils.sleep.mock_calls == []

class RepeaterTestCase(unittest.TestCase):
    def setUp(self):
        self.registry = mock.Mock()
        self.registry.settings = {
            'backoff_timeout': 1,
            'timeout': 2,
            'secret': 'secret'
        }
        concurrency_utils = self.registry.get_concurrency_utils.return_value
        self.semaphore = concurrency_utils.semaphore.return_value
        self.semaphore.__exit__ = mock.Mock()
        self.semaphore.__enter__ = mock.Mock()
        self.concurrency_utils = concurrency_utils
        self.hooks = {
            'hook1': {
                'src_host': '127.0.0.1',
                'src_path': '/src_path1',
                'dst_host': 'dst_host1',
                'dst_path': '/dst_path1',
            },
            'hook2': {
                'src_host': '192.168.1.100',
                'src_path': '/src_path2',
                'dst_host': 'dst_host1',  # dst_host1 by purpose
                'dst_path': '/dst_path2',
            },
            'hook3': {
                'src_host': '192.168.1.100',
                'src_path': '/src_path3',
                'dst_host': 'dst_host3',
                'dst_path': '/dst_path3',
            },
        }
        self.orig_queue_handler = Repeater.queue_handler
        self.orig_proxy = Repeater.proxy
        self.handlers = [mock.Mock(), mock.Mock()]
        self.queue_handler = mock.Mock()
        self.queue_handler.side_effect = self._queue_handler_side_effect
        self.proxy = mock.Mock()
        self.proxies = [object(), object(), object()]
        self.proxy.side_effect = self._proxy_side_effect
        Repeater.queue_handler = self.queue_handler
        Repeater.proxy = self.proxy
        self.repeater = Repeater(self.hooks, self.registry)

    def tearDown(self):
        Repeater.queue_handler = self.orig_queue_handler
        Repeater.proxy = self.orig_proxy

    def _queue_handler_side_effect(self, host, *args):
        if host == 'dst_host1':
            return self.handlers[0]
        elif host == 'dst_host3':
            return self.handlers[1]

    def _proxy_side_effect(self, host_port):
        if host_port == 'dst_host1/dst_path1':
            return self.proxies[0]
        elif host_port == 'dst_host1/dst_path2':
            return self.proxies[1]
        elif host_port == 'dst_host3/dst_path3':
            return self.proxies[2]

    def _test_constructor(self, args):
        assert args[0] in ['dst_host3', 'dst_host1']
        if args[0] == 'dst_host3':
            assert len(args[1]) == 1
            assert args[1]['/src_path3'] == self.proxies[2]
        elif args[0] == 'dst_host1':
            assert len(args[1]) == 2
            assert args[1]['/src_path1'] == self.proxies[0]
            assert args[1]['/src_path2'] == self.proxies[1]
        assert args[2] == self.registry

    def test_constructor(self):
        assert self.queue_handler.call_count == 2
        args1 = self.queue_handler.mock_calls[0][1]
        self._test_constructor(args1)
        args2 = self.queue_handler.mock_calls[1][1]
        self._test_constructor(args2)
        args = [args[1][0] for args in self.proxy.mock_calls]
        assert len(args) == 3
        assert 'dst_host1/dst_path1' in args
        assert 'dst_host1/dst_path2' in args
        assert 'dst_host3/dst_path3' in args

    def test_request(self):
        req = webob.Request.blank('/src_path1')
        req.remote_addr = '127.0.0.1'
        req.get_response(self.repeater)
        req_copy = self.handlers[0].push.mock_calls[0][1][0]
        assert req_copy.path_info == '/src_path1'
        assert self.handlers[0].push.call_count == 1

        req = webob.Request.blank('/src_path2')
        req.remote_addr = '192.168.1.100'
        req.get_response(self.repeater)
        req_copy = self.handlers[0].push.mock_calls[1][1][0]
        assert req_copy.path_info == '/src_path2'
        assert self.handlers[0].push.call_count == 2

        req = webob.Request.blank('/src_path3')
        req.remote_addr = '192.168.1.100'
        req.get_response(self.repeater)
        req_copy = self.handlers[1].push.mock_calls[0][1][0]
        assert req_copy.path_info == '/src_path3'
        assert self.handlers[1].push.call_count == 1

    def test_request_catch_http_not_found(self):
        """
        Test catching exception when in Jira wrong path was set
        """
        self.hooks['hook1']['src_host'] = ''
        repeater = Repeater(self.hooks, self.registry)
        req = webob.Request.blank('/src_path1')
        response = req.get_response(repeater)
        assert len(self.handlers[0].push.mock_calls) == 0
        assert self.handlers[0].push.call_count == 0
        assert response.status_code == 404

    def test_request_catch_http_forbidden(self):
        """
        Test catching exception when different src_host was set in config
        file and from different remote_host send jira request.
        """
        self.hooks['hook1']['src_path'] = '/wrong_path'
        repeater = Repeater(self.hooks, self.registry)
        req = webob.Request.blank('/wrong_path')
        response = req.get_response(repeater)
        assert len(self.handlers[0].push.mock_calls) == 0
        assert self.handlers[0].push.call_count == 0
        assert response.status_code == 403

class ApplicationTestCase(unittest.TestCase):
    """
    Tests for functions in module `application`
    """
    def test_sign_request(self):
        req = webob.Request.blank('/')
        req.body = 'ala ma kota'
        req = sign_request(req, 'secret')
        sig = req.headers['X-REPEATER-SIG']
        assert sig == '65a415c101d8103bc3866bfe9d5dc818'

    def test_generate_inet_aton(self):
        """
        Test returning int value of ip address.
        """
        address = '127.0.0.1'
        int_address = generate_inet_aton(address)
        self.assertEqual(int_address, 2130706433)

        address = '192.168.1.10'
        int_address = generate_inet_aton(address)
        self.assertEqual(int_address, 3232235786)

        address = '192.168.1.11'
        int_address = generate_inet_aton(address)
        self.assertEqual(int_address, 3232235787)

    def test_check_remote_address_one_host(self):
        """
        Test checking if remote_address is in list of addresses taken
        from config file. Case when only one host was written in file.
        """
        address = '192.168.1.100'
        hosts = '192.168.1.0/24'
        self.assertTrue(check_remote_address(hosts, address))

    def test_check_remote_address_multiple_hosts(self):
        """
        Test checking if remote_address is in list of addresses taken
        from config file. Case when multiple host addresses was set.
        """
        address = '10.0.1.5'
        hosts = '192.168.1.0/24, 127.0.0.1, 10.0.1.0/29'
        self.assertTrue(check_remote_address(hosts, address))

    def test_check_remote_address_not_in_hosts(self):
        """
        Test checking if remote_address is not in list of addresses
        taken from config file.
        """
        address = '192.168.2.100'
        hosts = '192.168.1.0/24'
        self.assertFalse(check_remote_address(hosts, address))


text:
package org.apache.hadoop.yarn.api.protocolrecords.impl.pb;

import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationRequest;
import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationSubmissionContextPBImpl;
import org.apache.hadoop.yarn.proto.YarnProtos.ApplicationSubmissionContextProto;
import org.apache.hadoop.yarn.proto.YarnServiceProtos.SubmitApplicationRequestProto;
import org.apache.hadoop.yarn.proto.YarnServiceProtos.SubmitApplicationRequestProtoOrBuilder;

import org.apache.hadoop.thirdparty.protobuf.TextFormat;

@Private
@Unstable
public class SubmitApplicationRequestPBImpl extends SubmitApplicationRequest {
  SubmitApplicationRequestProto proto = SubmitApplicationRequestProto.getDefaultInstance();
  SubmitApplicationRequestProto.Builder builder = null;
  boolean viaProto = false;

  private ApplicationSubmissionContext applicationSubmissionContext = null;

  public SubmitApplicationRequestPBImpl() {
    builder = SubmitApplicationRequestProto.newBuilder();
  }

  public SubmitApplicationRequestPBImpl(SubmitApplicationRequestProto proto) {
    this.proto = proto;
    viaProto = true;
  }

  public SubmitApplicationRequestProto getProto() {
      mergeLocalToProto();
    proto = viaProto ? proto : builder.build();
    viaProto = true;
    return proto;
  }

  @Override
  public int hashCode() {
    return getProto().hashCode();
  }

  @Override
  public boolean equals(Object other) {
    if (other == null)
      return false;
    if (other.getClass().isAssignableFrom(this.getClass())) {
      return this.getProto().equals(this.getClass().cast(other).getProto());
    }
    return false;
  }

  @Override
  public String toString() {
    return TextFormat.shortDebugString(getProto());
  }

  private void mergeLocalToBuilder() {
    if (this.applicationSubmissionContext != null) {
      builder.setApplicationSubmissionContext(convertToProtoFormat(this.applicationSubmissionContext));
    }
  }

  private void mergeLocalToProto() {
    if (viaProto)
      maybeInitBuilder();
    mergeLocalToBuilder();
    proto = builder.build();
    viaProto = true;
  }

  private void maybeInitBuilder() {
    if (viaProto || builder == null) {
      builder = SubmitApplicationRequestProto.newBuilder(proto);
    }
    viaProto = false;
  }

  @Override
  public ApplicationSubmissionContext getApplicationSubmissionContext() {
    SubmitApplicationRequestProtoOrBuilder p = viaProto ? proto : builder;
    if (this.applicationSubmissionContext != null) {
      return this.applicationSubmissionContext;
    }
    if (!p.hasApplicationSubmissionContext()) {
      return null;
    }
    this.applicationSubmissionContext = convertFromProtoFormat(p.getApplicationSubmissionContext());
    return this.applicationSubmissionContext;
  }

  @Override
  public void setApplicationSubmissionContext(ApplicationSubmissionContext applicationSubmissionContext) {
    maybeInitBuilder();
    if (applicationSubmissionContext == null)
      builder.clearApplicationSubmissionContext();
    this.applicationSubmissionContext = applicationSubmissionContext;
  }

  private ApplicationSubmissionContextPBImpl convertFromProtoFormat(ApplicationSubmissionContextProto p) {
    return new ApplicationSubmissionContextPBImpl(p);
  }

  private ApplicationSubmissionContextProto convertToProtoFormat(ApplicationSubmissionContext t) {
    return ((ApplicationSubmissionContextPBImpl)t).getProto();
  }

}


text:
function param = set_opts(model)
% SET_OPTS.M %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% function to create parameter structure for mfit
%
% USAGE: param = set_opts(model)
%
% INPUTS: model number
%
%          all models have inverse temperature [x(1)] and stickiness [x(2)]
%           1 - single learning rate
%           2 - gems learning rate, bomb learning rate
%           3 - positive learning rate, negative learning rate
%           4 - positive gems learning rate, positive bomb learning rate
%               negative gems learning rate, negative bomb learning rate
%
% OUTPUTS: param - structure to use as input to mfit_optimize
%
% ~wem3~ [20170717]
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% params 1 - 3 are the same for all models
param(1).name = 'inverse temperature'; % inverse temperature
param(1).hp = [3 2];    % hyperparameters of the gamma prior
param(1).logpdf = @(x) sum(log(gampdf(x,param(1).hp(1),param(1).hp(2))));  % log density function for prior
param(1).lb = 1e-8; % lower bound
param(1).ub = 50;   % upper bound
param(1).fit = @(x) gamfit(x);

param(2).name = 'choice stickiness'; % perseveration parameter
param(2).hp = [0 10]; % hyperparameters of the normal prior
param(2).logpdf = @(x) sum(log(normpdf(x,param(2).hp(1),param(2).hp(2))));  % log density function for prior
param(2).lb = -5;    % lower bound
param(2).ub = 5;     % upper bound
param(2).fit = @(x) [mean(x) std(x)];

param(3).name = 'learning rate'; % learning rate
param(3).hp = [1.2 1.2];    % hyperparameters of beta prior
param(3).logpdf = @(x) sum(log(betapdf(x,param(3).hp(1),param(3).hp(2))));
param(3).lb = 0;
param(3).ub = 1;
param(3).fit = @(x) betafit(x);

switch model
    case 2
        param(4) = param(3);
        param(3).name = 'gems learning rate';
        param(4).name = 'bomb learning rate';
    case 3
        param(4) = param(3);
        param(3).name = 'positive learning rate';
        param(4).name = 'negative learning rate';
    case 4
        param(4) = param(3);
        param(5) = param(3);
        param(6) = param(3);
        param(3).name = 'positive gems learning rate';
        param(4).name = 'positive bomb learning rate';
        param(5).name = 'negative gems learning rate';
        param(6).name = 'negative bomb learning rate';
    case 5
        param(4) = param(3);
        param(4).name = 'gems preference weight';
    case 6
        param(4) = param(3);
        param(5) = param(3);
        param(3).name = 'positive learning rate';
        param(4).name = 'negative learning rate';
        param(5).name = 'gems preference weight';
end


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item android:id="@+id/action_search"
        android:title="@string/action_seatch"
        android:orderInCategory="90"
        android:icon="@mipmap/ic_search_white_24dp"
        app:showAsAction="ifRoom" />
    <!--
    这个属性可接受的值有:
  1、always:这个值会使菜单项一直显示在Action Bar上。
  2、ifRoom:如果有足够的空间,这个值会使菜单项显示在Action Bar上。
  3、never:这个值使菜单项永远都不出现在Action Bar上。
  4、withText:这个值使菜单项和它的图标,菜单文本一起显示。
    -->
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    <item
         android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never"
        />
</menu>


text:
package com.streamsets.pipeline.kafka.impl;

import com.streamsets.pipeline.kafka.api.FactoriesBean;
import com.streamsets.pipeline.kafka.api.SdcKafkaConsumerFactory;
import com.streamsets.pipeline.kafka.api.SdcKafkaLowLevelConsumerFactory;
import com.streamsets.pipeline.kafka.api.SdcKafkaProducerFactory;
import com.streamsets.pipeline.kafka.api.SdcKafkaValidationUtilFactory;

public class Kafka1_0FactoriesBean extends FactoriesBean {

  @Override
  public SdcKafkaProducerFactory createSdcKafkaProducerFactory() {
    return new Kafka09ProducerFactory();
  }

  @Override
  public SdcKafkaValidationUtilFactory createSdcKafkaValidationUtilFactory() {
    return new Kafka09ValidationUtilFactory();
  }

  @Override
  public SdcKafkaConsumerFactory createSdcKafkaConsumerFactory() {
    return new Kafka1_0ConsumerFactory();
  }

  @Override
  public SdcKafkaLowLevelConsumerFactory createSdcKafkaLowLevelConsumerFactory() {
    return new Kafka09LowLevelConsumerFactory();
  }

}


text:
using System;
using System.Runtime.InteropServices;

namespace ActivationFnBenchmarks
{
    public static class FastLog
    {
        [StructLayout(LayoutKind.Explicit)]
        private struct Ieee754
        {
            [FieldOffset(0)] public float Single;
            [FieldOffset(0)] public uint UnsignedBits;
            [FieldOffset(0)] public int SignedBits;

            public uint Sign => UnsignedBits >> 31;
            public int Exponent => (SignedBits >> 23) & 0xFF;
            public uint Mantissa => UnsignedBits & 0x007FFFFF;
        }

        static readonly float[] __mantissaLogs = new float[(int)Math.Pow(2, 23)];
        const float __base10 = 3.321928F;
        const float __baseE = 1.442695F;

        #region Static Initializer

        static FastLog()
        {
            // Create lookup table.
            for (uint i = 0; i < __mantissaLogs.Length; i++)
            {
                var n = new Ieee754 { UnsignedBits = i | 0x3F800000 }; //added the implicit 1 leading bit
                __mantissaLogs[i] = (float)Math.Log(n.Single, 2);
            }
        }

        #endregion

        #region Public Static Methods

        public static float Log2(float value)
        {
            if (value == 0f) {
                return float.NegativeInfinity;
            }

            var number = new Ieee754 { Single = value };

            if (number.UnsignedBits >> 31 == 1)
            {   //NOTE: didn't call Sign property for higher performance
                return float.NaN;
            }

            return (((number.SignedBits >> 23) & 0xFF) - 127) + __mantissaLogs[number.UnsignedBits & 0x007FFFFF];
            //NOTE: didn't call Exponent and Mantissa properties for higher performance
        }

        public static float Log10(float value)
        {
            return Log2(value) / __base10;
        }

        public static float Ln(float value)
        {
            return Log2(value) / __baseE;
        }

        public static float Log(float value, float valueBase)
        {
            return Log2(value) / Log2(valueBase);
        }

        #endregion
    }
}


text:
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Popover from '../../Popover';
import { Mode } from './constants';

const controlledErrorMsg = method =>
  `ClosablePopover.${method}() can not be called when component is Controlled. (opened prop should be undefined)`;

/**
 * Closable Popover
 * Either a normal Controlled Popover, or a Popover that is initially opened and can be the closed by
 * calling a closeAction.
 */
class ClosablePopover extends PureComponent {
  state = {
    open: this.props.initiallyOpened,
    mode: this.props.initiallyOpened ? Mode.ClickToClose : Mode.Hover,
  };

  _isControlled() {
    return typeof this.props.opened === 'boolean';
  }

  open = () => this._doOpen(Mode.ClickToClose);

  _doOpen = nextMode => {
    if (this._isControlled()) {
      throw new Error(controlledErrorMsg('open'));
    }
    !this.state.open &&
      this.setState(
        {
          open: true,
          mode: nextMode,
        },
        () => {
          this.props.onOpen && this.props.onOpen();
        },
      );
  };

  close = () => {
    if (this._isControlled()) {
      throw new Error(controlledErrorMsg('close'));
    }
    this.state.open &&
      this.setState(
        {
          open: false,
          mode: Mode.Hover,
        },
        () => {
          this.props.onClose && this.props.onClose();
        },
      );
  };

  _handleMouseEnter = () => {
    if (this.state.mode === Mode.Hover) {
      this._doOpen(Mode.Hover);
    }
  };

  _handleMouseLeave = () => {
    if (this.state.mode === Mode.Hover && this.props.closeOnMouseLeave) {
      this.close();
    }
  };

  render() {
    const {
      content,
      appearance,
      target,
      children,
      onClose,
      onOpen,
      initiallyOpened,
      closeOnMouseLeave,
      hideDelay,
      ...rest
    } = this.props;

    const open = this._isControlled() ? this.props.opened : this.state.open;

    const popoverProps = {
      ...rest,
      animate: true,
      theme: appearance,
      shown: open,
      onMouseEnter: this._handleMouseEnter,
      onMouseLeave: this._handleMouseLeave,
    };

    return (
      <Popover {...popoverProps}>
        <Popover.Element>{target}</Popover.Element>
        <Popover.Content>{content(this.actions)}</Popover.Content>
      </Popover>
    );
  }

  actions = {
    close: this.close,
  };
}

ClosablePopover.defaultProps = {
  hideDelay: 0,
  initiallyOpened: true,
  closeOnMouseLeave: true,
};

ClosablePopover.propTypes = {
  /** Controls whether the popover's content is shown or not.
   * When undefined, then the component is Uncontrolled,
   * It is initially open, and it can be closed by close-action */
  opened: PropTypes.bool,
  /** Controls whether the popover's content is initially opened (in Uncontrolled mode only) */
  initiallyOpened: PropTypes.bool,
  /** The popover's target element*/
  target: PropTypes.node.isRequired,
  /** Callback to call when the popover content is requested to be opened (Uncontrolled mode only) */
  onOpen: PropTypes.func,
  /** callback to call when the popover content is requested to be closed (Uncontrolled mode only). NOTE: this callback is called when the close timeout (if exists) starts */
  onClose: PropTypes.func,
  /** Disable close on mouseLeave */
  closeOnMouseLeave: PropTypes.bool,
  /** The popover's content, given as a function that receives control-actions and renders the contet.
   * In Uncontrolled mode, this function is still called only once.
   */
  content: PropTypes.func.isRequired,
  /** A css class to be applied to the component's root element */
  className: PropTypes.string,
};

export default ClosablePopover;


text:
define([
		'jquery',
		'backbone',
		'underscore',
		'./BaseView',
		'../uiconfig',
		'text!templates/alert.html'],
function($, Backbone, _, BaseView, config, template) {
	var View = BaseView.extend({
		events: function() {
		    return _.extend({}, BaseView.prototype.events, {
				"click #back" : function() {
					this.cleanup();
					this.router.navigate("alerts", {trigger: true});
				}
		    });
		},
		initialize: function(data, router) {
			var options = {
				header: {
					title: "V1 Alert Map",
					backHistory: true
				},
				router: router
			};
			this.constructor.__super__.initialize.apply(this, [options]);
			this.template = _.template( template) ( {} );
			this.alert = data.alert;
		},
		render: function() {
			$(this.el).html( this.headerTemplate + this.template + this.menuTemplate + this.footerTemplate );
			var f = function() {
				var mapdiv = $("#map")[0];
				this.map = plugin.google.maps.Map.getMap(mapdiv);
				this.map.addEventListener(plugin.google.maps.event.MAP_READY, function() {
					var highest = this.alert.get("highest");
					var pos = highest.positions[0];
					var band = this.alert.get("band");
					var frequency = this.alert.get("frequency");
					var strength = highest.strength;
					var location = new plugin.google.maps.LatLng(pos.latitude, pos.longitude);

					this.map.setCenter(location);
					setTimeout(function() {
						this.map.setZoom(14);
					}.bind(this), 1000);
					highest.positions.forEach(function(position) {
						var location = new plugin.google.maps.LatLng(position.latitude, position.longitude);
						this.map.addMarker({
							'position': location,
							'title': "Band: "+ band + "\nFrequency: "+frequency+"\nStrength: "+strength
						}, function(marker) {
							marker.showInfoWindow();
						});
					}.bind(this));
				}.bind(this));
			}.bind(this);
			setTimeout(f, 0);
		},
		cleanup: function() {
			if (this.map) {
				this.map.clear();
				this.map.off();
			}
		}
	});

	return View;
});


text:
.ImgarchiveZimletIcon {
  background: url("archiveZimletIcon.png") no-repeat 0 0;
  width: 16px;
  height: 16px;
  overflow: hidden;
}


text:
**Summary:**

**Issues Reference:**

**Test Plan:**

**Screenshots:**


text:
	<title>array/push_back.hpp</title>
	<link rel="stylesheet" type="text/css" href="../../styles.css">

		The array/push_back.hpp header defines a macro to append an element to the end of an array.

Usage

			#include <boost/preprocessor/array/push_back.hpp>

Contents

BOOST_PP_ARRAY_PUSH_BACK

		© Copyright Housemarque Oy 2002

© Copyright Paul Mensonides 2002

Distributed under the Boost Software License, Version 1.0. (See
		accompanying file LICENSE_1_0.txt or
		copy at www.boost.org/LICENSE_1_0.txt)


text:
import {combineReducers} from 'redux';
import courses from './courseReducer';
import authors from './authorsReducer';

const rootReducer = combineReducers({
    courses,
    authors
});

export default rootReducer;


text:
function [h] =  plotSample(sample,FV,color)

dimSample=size(sample,1);
FV.vertices=reshape(sample,dimSample/3,3);

h = patch(FV,'FaceColor',       color, ...
         'EdgeColor',       [0.5 0.5 0.5],        ...
         'FaceLighting',    'gouraud',     ...
         'FaceAlpha',       1.0,...
         'EdgeAlpha',       0.5,...
         'AmbientStrength', 0.15);
% Add a camera light, and tone down the specular highlighting
% camlight('headlight');
material('dull');


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Tomb of Sargeras</title>
  <link rel="icon" type="image/jpg" href="https://wow.zamimg.com/images/wow/icons/small/spell_deathknight_bloodpresence.jpg"
  />

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
    crossorigin="anonymous" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
    crossorigin="anonymous" />

  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" />

  <link rel="stylesheet" href="css/main.min.css" />

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-navbar" aria-expanded="false">
          Toggle navigation

        </button>

            Classes

                    Death Knight

                    Blood

                    Frost

                    Unholy

                    Demon Hunter

                    Havoc

                    Vengeance

                    Druid

                    Balance

                    Feral

                    Guardian

                    Restoration

                    Hunter

                    Beast Mastery

                    Marksmanship

                    Survival

                    Mage

                    Arcane

                    Fire

                    Frost

                    Monk

                    Brewmaster

                    Mistweaver

                    Windwalker

                    Paladin

                    Holy

                    Protection

                    Retribution

                    Priest

                    Discipline

                    Holy

                    Shadow

                    Rogue

                    Assassination

                    Outlaw

                    Subtlety

                    Shaman

                    Elemental

                    Enhancement

                    Restoration

                    Warlock

                    Affliction

                    Demonology

                    Destruction

                    Warrior

                    Arms

                    Fury

                    Protection

Brack / Doom Squadz


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <corners
        android:bottomLeftRadius="100dp"
        android:bottomRightRadius="100dp"
        android:topLeftRadius="100dp"
        android:topRightRadius="100dp"/>
    <solid android:color="@color/color_white"/>
    <stroke
        android:width="@dimen/dimen_1"
        android:color="@color/color_ABA8A8"/>
</shape>


text:
package com.tongbanjie.baymax.parser;

import com.tongbanjie.baymax.parser.model.SqlType;
import com.tongbanjie.baymax.parser.mysql.MySqlDeleteParser;
import com.tongbanjie.baymax.parser.mysql.MySqlExplainSqlParser;
import com.tongbanjie.baymax.parser.mysql.MySqlInsertParser;
import com.tongbanjie.baymax.parser.mysql.MySqlSelectParser;
import com.tongbanjie.baymax.parser.mysql.MySqlUpdateParser;

/**
 * Created by sidawei on 16/1/27.
 *
 * sql解析器工厂,根据不同的sql类型返回不同的解析器.
 */
public class SqlParserFactory {

    public static SqlParser getParser(SqlType sqlType){

        if (sqlType == null)
            return null;

        switch (sqlType){
            case SELECT:
                return new MySqlSelectParser();
            case INSERT:
                return new MySqlInsertParser();
            case UPDATE:
                return new MySqlUpdateParser();
            case DELETE:
                return new MySqlDeleteParser();
            case EXPLAIN:
                return new MySqlExplainSqlParser();
            default:
                return null;
        }
    }

}


text:
package org.fest.assertions.internal;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

/**
 * All tests for {@link Characters}.
 *
 * @author Yvonne Wang
 */
@RunWith(Suite.class)
@SuiteClasses({
  Characters_assertEqual_Test.class,
  characters_assertNotEqual_Test.class,
  Characters_assertGreaterThan_Test.class,
  Characters_assertLessThan_Test.class,
  Characters_assertNotGreaterThan_Test.class,
  Characters_assertNotLessThan_Test.class,
  Characters_assertUpperCase_Test.class,
  Characters_assertLowerCase_Test.class
})
public class Characters_TestSuite {

}


text:
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# 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.
# ----------------------------------------------------------------------------------

$createdNamespaces = @()

<#
.SYNOPSIS
Gets default location from the available list of service bus locations.
#>
function Get-DefaultServiceBusLocation
{
    $locations = Get-AzureSBLocation

    return $locations[0].Code
}

<#
.SYNOPSIS
Gets valid and available service bus namespace name.
#>
function Get-NamespaceName
{
    return getAssetName
}

<#
.SYNOPSIS
Removes given namespace when it's status is 'Active'

.PARAMETER name
The namespace name.
#>
function Remove-Namespace
{
    param([string]$name)
    Wait-NamespaceStatus $name "Active"
    Remove-AzureSBNamespace $name -Force
    Wait-NamespaceRemoved $name
}

<#
.SYNOPSIS
Waits until the namespace is removed.

.PARAMETER name
The namespace name.
#>
function Wait-NamespaceRemoved
{
    param([string]$name)

    $waitScriptBlock = {
        $removed = $false
        try
        {
            $namespace = Get-AzureSBNamespace $name
            Wait-Seconds 5
        }
        catch
        {
            $removed = $true
        }

        return $removed;
    }

    Wait-Function $waitScriptBlock $true
}

<#
.SYNOPSIS
Waits on the namespace until its status reaches provided state.

.PARAMETER name
The namespace name.

.PARAMETER status
The status to wait on.
#>
function Wait-NamespaceStatus
{
    param([string] $name, [string] $status)

    $waitScriptBlock = { (Get-AzureSBNamespace $name).Status }
    Wait-Function $waitScriptBlock $status
}

<#
.SYNOPSIS
Clears the all created resources while doing the test.
#>
function Test-CleanupServiceBus
{
    try { foreach ($name in $global:createdNamespaces) { Remove-Namespace $name -Force } }
    catch { <# Succeed #> }
    $global:createdNamespaces = @()
}

<#
.SYNOPSIS
Creates service bus namespaces with the count specified and wait until the namespace status is Active.

.PARAMETER count
The number of namespaces to create.
#>
function New-Namespace
{
    param([int]$count)
    1..$count | % {
        $name = Get-NamespaceName;
        New-AzureSBNamespace $name $(Get-DefaultServiceBusLocation);
        $global:createdNamespaces += $name;
    }

    $global:createdNamespaces | % { Wait-NamespaceStatus $_ "Active" };
}

<#
.SYNOPSIS
Removes all the active namespaces in the current subscription.
#>
function Initialize-NamespaceTest
{
    try { Get-AzureSBNamespace | Where {$_.Status -eq "Active"} | Remove-AzureSBNamespace -Force }
    catch { <# Succeed #> }
}

<#
.SYNOPSIS
Creates a ServiceBusExtensionClient instance.
#>
function New-ServiceBusClientExtensions
{
    $client = New-Object Microsoft.WindowsAzure.Commands.Utilities.ServiceBus.ServiceBusClientExtensions `
        -ArgumentList $(Get-AzureSubscription -Default)

    return $client
}


text:
class TravelDeals < ActiveRecord::Base
	has_many :travel_todos
	has_many :todos, through: :travel_todos

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.causeway.extensions</groupId>
        <artifactId>causeway-extensions</artifactId>
        <version>2.0.0-SNAPSHOT</version>
        <relativePath>../../../pom.xml</relativePath>
    </parent>

    <artifactId>causeway-extensions-excel-integtests</artifactId>
    <name>Apache Causeway Ext - Excel (Integ Tests)</name>

	<properties>
    	<jar-plugin.automaticModuleName>org.apache.causeway.extensions.excel.integtests</jar-plugin.automaticModuleName>
        <git-plugin.propertiesDir>org/apache/causeway/extensions/excel/integtests</git-plugin.propertiesDir>
    </properties>

    <build>
        <resources>
            <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**</include>
                </includes>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <filtering>false</filtering>
                <directory>src/test/resources</directory>
            </testResource>
            <testResource>
                <directory>src/test/java</directory>
                <includes>
                    <include>**</include>
                </includes>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </testResource>
        </testResources>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.causeway.testing</groupId>
                <artifactId>causeway-testing</artifactId>
                <scope>import</scope>
                <type>pom</type>
                <version>2.0.0-SNAPSHOT</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>org.apache.causeway.extensions</groupId>
            <artifactId>causeway-extensions-excel-fixtures</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.causeway.testing</groupId>
            <artifactId>causeway-testing-fakedata-applib</artifactId>
            <scope>test</scope>
        </dependency>

		<dependency>
			<groupId>org.apache.causeway.testing</groupId>
			<artifactId>causeway-testing-integtestsupport-applib</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.apache.causeway.testing</groupId>
			<artifactId>causeway-testing-fixtures-applib</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- PERSISTENCE -->

        <dependency>
            <groupId>org.apache.causeway.persistence</groupId>
			<artifactId>causeway-persistence-jdo-datanucleus</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
"use strict";

import * as languageClient from "vscode-languageclient";

export class REngine implements IREngine {
    private client: languageClient.LanguageClient;

    constructor(client: languageClient.LanguageClient) {
        this.client = client;
    }

    public getInterpreterPath(): Thenable<string> {
        return this.client.sendRequest<string>("information/getInterpreterPath");
    }

    public execute(code: string): Thenable<string> {
        return this.client.sendRequest<string>("r/execute", { code });
    }

    public async interrupt() {
        await this.client.sendRequest("r/interrupt");
    }

    public async reset() {
        await this.client.sendRequest("r/reset");
    }

    public async source(filePath: string) {
        await this.client.sendRequest("r/source", filePath);
    }
}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models

class Migration(DataMigration):

    def forwards(self, orm):
        for linkextended in orm['cmsplugin_link_extended.LinkExtension'].objects.all():
            orm['cmsplugin_link_extended.LinkExtended'].objects.create(
                name=linkextended.link.name,
                url=linkextended.link.url,
                page_link=linkextended.link.page_link,
                mailto=linkextended.link.mailto,
                target=linkextended.link.target,

                parent=linkextended.link.parent,
                placeholder=linkextended.link.placeholder,
                position=linkextended.link.position,
                language=linkextended.link.language,
                plugin_type=linkextended.link.plugin_type,
                creation_date=linkextended.link.creation_date,
                changed_date=linkextended.link.changed_date,
                level=linkextended.link.level,
                lft=linkextended.link.lft,
                rght=linkextended.link.rght,
                tree_id=linkextended.link.tree_id,

                css_classes=linkextended.css_classes,
            )

    def backwards(self, orm):
        "Write your backwards methods here."

    models = {
        'cms.cmsplugin': {
            'Meta': {'object_name': 'CMSPlugin'},
            'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
            'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
            'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
            'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
        },
        'cms.page': {
            'Meta': {'ordering': "('tree_id', 'lft')", 'unique_together': "(('publisher_is_draft', 'application_namespace'),)", 'object_name': 'Page'},
            'application_namespace': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'application_urls': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'changed_by': ('django.db.models.fields.CharField', [], {'max_length': '70'}),
            'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'created_by': ('django.db.models.fields.CharField', [], {'max_length': '70'}),
            'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'in_navigation': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),
            'is_home': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'languages': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'limit_visibility_in_menu': ('django.db.models.fields.SmallIntegerField', [], {'default': 'None', 'null': 'True', 'db_index': 'True', 'blank': 'True'}),
            'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'navigation_extenders': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '80', 'null': 'True', 'blank': 'True'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['cms.Page']"}),
            'placeholders': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['cms.Placeholder']", 'symmetrical': 'False'}),
            'publication_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
            'publication_end_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
            'publisher_is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),
            'publisher_public': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.Page']"}),
            'reverse_id': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '40', 'null': 'True', 'blank': 'True'}),
            'revision_id': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'djangocms_pages'", 'to': u"orm['sites.Site']"}),
            'soft_root': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'template': ('django.db.models.fields.CharField', [], {'default': "'INHERIT'", 'max_length': '100'}),
            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'xframe_options': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        'cms.placeholder': {
            'Meta': {'object_name': 'Placeholder'},
            'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
        },
        u'cmsplugin_link_extended.linkextended': {
            'Meta': {'object_name': 'LinkExtended', '_ormbases': [u'djangocms_link.Link']},
            'css_classes': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}),
            u'link_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['djangocms_link.Link']", 'unique': 'True', 'primary_key': 'True'})
        },
        u'cmsplugin_link_extended.linkextension': {
            'Meta': {'object_name': 'LinkExtension'},
            'css_classes': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'link': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'extensions'", 'to': u"orm['djangocms_link.Link']"})
        },
        u'djangocms_link.link': {
            'Meta': {'object_name': 'Link', '_ormbases': ['cms.CMSPlugin']},
            u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
            'mailto': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
            'page_link': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Page']", 'null': 'True', 'blank': 'True'}),
            'target': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
        },
        u'sites.site': {
            'Meta': {'ordering': "(u'domain',)", 'object_name': 'Site', 'db_table': "u'django_site'"},
            'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        }
    }

    complete_apps = ['cmsplugin_link_extended']
    symmetrical = True


text:
import React, {Component} from 'react';
import '../../assets/scss/pages/client/archives.scss';
import warp from '../../components/common/wrapCompontent';
import { Link } from 'react-router';
import Loading from '../../components/common/Loading';
import { getArchives } from '../../redux/action/action';
class Archives extends Component {
    constructor(props) {
        super(props);
        this.state = {
            archives: {}
        };
    }
    create() {
        let result = [],
            {archives} = this.state,
            date,
            list,
            articles;
        for (date in archives) {
            articles = archives[date];
            result.push(

{date}

            );
            list =

            {articles.map((item, index) => {
                return (

                            {
                                index < articles.length - 1 &&

                            }

                        <Link to={'article?id=' + item.id} className="archives-title">{item.title}</Link>

                );
             })}

;
            result.push(list);
        }
        return result;
    }
    componentWillMount() {
       this.props.getArchives(this);
    }
    render() {
        return (

              <Loading>
                {this.create()}
              </Loading>

        );
    }
}
module.exports = warp({
    Target: Archives,
    redux: {
      mapDispatchToProps: {getArchives}
    }
});


text:
import urllib

import requests

def shorten_url(url):
    r = requests.get('http://is.gd/create.php?format=simple&url={}'.format(urllib.quote(url)))
    r.raise_for_status()
    return r.text


text:
package gojenkins

import (
	"context"
	"net/http"
	"strconv"
	"time"
)

type QueueStats struct {
	Length    uint32
	TaskNames []string
}

type QueueID uint32

type QueueItem struct {
	Number BuildNumber
	URL    string
}

const (
	// DefaultWaitForBuildToBeQueuedTimeout is the default time that the client would poll before giving up.
	DefaultWaitForBuildToBeQueuedTimeout = time.Duration(1 * time.Minute)
)

// QueueAPI is the interface to interact with Jenkins Queue api.
type QueueAPI interface {
	QueueStats(ctx context.Context) (QueueStats, error)

	// WaitUntilBuildIsQueued polls jenkins queue api until the build starts to execute.
	// A timeout is enforced via context.
	// If the context does not have a timeout DefaultWaitForBuildToBeQueuedTimeout is used.
	// To not bombard jenkins after every unsuccessful call we wait for retryAfter before retrying.
	WaitUntilBuildIsQueued(ctx context.Context, id QueueID, retryAfter time.Duration) (QueueItem, error)
}

func NewQueueAPI(u URLBuilder, r Requestor) queueAPI {
	return queueAPI{u, r}
}

type queueAPI struct {
	URLBuilder
	requestor Requestor
}

func (q queueAPI) QueueStats(ctx context.Context) (QueueStats, error) {
	var queueResponse struct {
		Items []struct {
			Task struct {
				Name string
			}
		}
	}

	resp := q.requestor.Do(ctx, Request{
		Method: http.MethodGet,
		URL:    q.URLBuilder.JSONEndpoint("/queue"),
	})

	if err := resp.VerifyAndDecode(JsonDecoder(&queueResponse)); err != nil {
		return QueueStats{}, err
	}

	stats := QueueStats{Length: uint32(len(queueResponse.Items))}
	for _, item := range queueResponse.Items {
		stats.TaskNames = append(stats.TaskNames, item.Task.Name)
	}

	return stats, nil
}

func (q queueAPI) WaitUntilBuildIsQueued(ctx context.Context, id QueueID, retryAfter time.Duration) (QueueItem, error) {
	ctx, cancelFn := setTimeoutIfNotSet(ctx, DefaultWaitForBuildToBeQueuedTimeout)
	defer cancelFn()

	var queueItem struct {
		Executable struct {
			Number BuildNumber
			URL    string
		}
	}
	url := q.URLBuilder.JSONEndpoint("queue", "item", strconv.FormatUint(uint64(id), 10))

	err := retryUntilFalseOrError(ctx, retryAfter, func() (bool, error) {
		resp := q.requestor.Do(ctx, Request{Method: http.MethodGet, URL: url})
		err := resp.VerifyAndDecode(JsonDecoder(&queueItem))
		return queueItem.Executable.Number == 0, err
	})

	return QueueItem(queueItem.Executable), err
}


text:
using System;
using System.Runtime.InteropServices;

namespace LibGit2Sharp.Core
{
    [StructLayout(LayoutKind.Sequential)]
    internal class GitSmartSubtransport
    {
        static GitSmartSubtransport()
        {
            GCHandleOffset = Marshal.OffsetOf<GitSmartSubtransport>(nameof(GCHandle)).ToInt32();
        }

        public action_callback Action;
        public close_callback Close;
        public free_callback Free;

        /* The libgit2 structure definition ends here. Subsequent fields are for libgit2sharp bookkeeping. */

        public IntPtr GCHandle;

        /* The following static fields are not part of the structure definition. */

        public static int GCHandleOffset;

        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate int action_callback(
            out IntPtr stream,
            IntPtr subtransport,
            IntPtr url,
            GitSmartSubtransportAction action);

        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate int close_callback(IntPtr subtransport);

        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate void free_callback(IntPtr subtransport);
    }
}


text: A placeholder so this folder can be added to git.


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>class DSLJournal - RDoc Documentation</title>

<link href="./css/fonts.css" rel="stylesheet">
<link href="./css/rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Parent

JournalArticle

Methods

::new

#author

#journalarticle

#title_

    class DSLJournal

Public Class Methods

          new(&block)

          click to toggle source

# File lib/prct11/DSL.rb, line 48
def initialize(&block)
    self.title = []
    self.date = []
    self.number = []
    self.volume = []
    self.initpage =[]
    self.finalpage = []
    self.authors = []
    self.title = ""
    self.journal = []
    instance_eval(&block)
end

Public Instance Methods

          author(author)

          click to toggle source

# File lib/prct11/DSL.rb, line 65
def author(author)
    self.authors = author
end

          journalarticle(datos = {})

          click to toggle source

# File lib/prct11/DSL.rb, line 69
def journalarticle (datos = {})
  self.title = datos[:nombre]
   self.journal = datos[:periodico]
   self.date  = datos[:fecha]
   self.number = datos[:numero]
   self.volume = datos[:volumen]
   self.initpage = datos[:paginicio]
   self.finalpage = datos[:pagfinal]
end

          title_(titles)

          click to toggle source

# File lib/prct11/DSL.rb, line 61
def title_(titles)
    self.title = titles
end

Validate

Generated by RDoc 4.2.0.

Based on Darkfish by Michael Granger.


text: RetroCommander


text:
title: Eureka - How do I unset the context changed by `istioctl` at the end?
order: 70
type: markdown
---
{% include home.html %}

Your ```kubectl``` is switched to use the istio context at the end of the `istio context-create` command.  You can use ```kubectl config get-contexts``` to obtain the list of contexts and ```kubectl config use-context {desired-context}``` to switch to use your desired context.