text:
require "support/shared/integration/integration_helper"
require "support/shared/context/config"
require "openssl"

describe "knife client create", :workstation do
  include IntegrationSupport
  include KnifeSupport

  include_context "default config options"

  let(:out) { "Created client[bah]\n" }

  when_the_chef_server "is empty" do
    it "creates a new client" do
      knife("client create -k bah").should_succeed stderr: out
    end

    it "creates a new validator client" do
      knife("client create -k --validator bah").should_succeed stderr: out
      knife("client show bah").should_succeed <<~EOM
        admin:     false
        chef_type: client
        name:      bah
        validator: true
EOM
    end

    it "refuses to add an existing client" do
      pending "Knife client create must not blindly overwrite an existing client"
      knife("client create -k bah").should_succeed stderr: out
      expect { knife("client create -k bah") }.to raise_error(Net::HTTPServerException)
    end

    it "saves the private key to a file" do
      Dir.mktmpdir do |tgt|
        knife("client create -f #{tgt}/bah.pem bah").should_succeed stderr: out
        expect(File).to exist("#{tgt}/bah.pem")
      end
    end

    it "reads the public key from a file" do
      Dir.mktmpdir do |tgt|
        key = OpenSSL::PKey::RSA.generate(1024)
        File.open("#{tgt}/public.pem", "w") { |pub| pub.write(key.public_key.to_pem) }
        knife("client create -p #{tgt}/public.pem bah").should_succeed stderr: out
      end
    end

    it "refuses to run if conflicting options are passed" do
      knife("client create -p public.pem --prevent-keygen blah").should_fail stderr: "FATAL: You cannot pass --public-key and --prevent-keygen\n", stdout: /^USAGE.*/
    end
  end
end

redpajama_set_name: RedPajamaGithub


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

<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="MainImage">

    <typeAlias  alias="MainImage" type="egovframework.com.uss.ion.msi.service.MainImage"/>
    <typeAlias  alias="MainImageVO" type="egovframework.com.uss.ion.msi.service.MainImageVO"/>

    <resultMap id="mainImage" class="egovframework.com.uss.ion.msi.service.MainImageVO">
        <result property="imageId" column="IMAGE_ID" columnIndex="1"/>
        <result property="imageNm" column="IMAGE_NM" columnIndex="2"/>
        <result property="image" column="IMAGE" columnIndex="3"/>
        <result property="imageFile" column="IMAGE_FILE" columnIndex="4"/>
        <result property="imageDc" column="IMAGE_DC" columnIndex="5"/>
        <result property="reflctAt" column="REFLCT_AT" columnIndex="6"/>
        <result property="userId" column="FRST_REGISTER_ID" columnIndex="7"/>
        <result property="regDate" column="FRST_REGIST_PNTTM" columnIndex="8"/>
    </resultMap>

    <resultMap id="image" class="egovframework.com.uss.ion.msi.service.MainImageVO">
        <result property="imageFile" column="IMAGE_FILE" columnIndex="1"/>
    </resultMap>

    <resultMap id="mainImageFile" class="egovframework.com.cmm.service.FileVO">
        <result property="fileStreCours" column="FILE_STRE_COURS" columnIndex="1"/>
        <result property="streFileNm" column="STRE_FILE_NM" columnIndex="2"/>
    </resultMap>

    <select id="mainImageDAO.selectMainImageList" parameterClass="MainImageVO" resultMap="mainImage">
        <![CDATA[
            SELECT  *
              FROM  (
            SELECT ROWNUM RNUM, ALL_LIST.*
              FROM  (
            SELECT IMAGE_ID,
                   IMAGE_NM,
                   IMAGE,
                   IMAGE_FILE,
                   IMAGE_DC,
                   REFLCT_AT,
                   FRST_REGISTER_ID,
                   FRST_REGIST_PNTTM
              FROM COMTNMAINIMAGE
             WHERE 1=1
        ]]>
            <isEqual prepend="AND" property="searchCondition" compareValue="1">
                IMAGE_NM LIKE '%'||#searchKeyword#||'%'
            </isEqual>
        <![CDATA[
            ORDER BY FRST_REGIST_PNTTM DESC
                    ) ALL_LIST
                    ) Z
             WHERE  RNUM  > #firstIndex#
               AND  RNUM <= #firstIndex# + #recordCountPerPage#
        ]]>
    </select>

    <select id="mainImageDAO.selectMainImageListTotCnt" parameterClass="MainImageVO" resultClass="int">

            SELECT COUNT(*) totcnt
            FROM COMTNMAINIMAGE
            WHERE 1=1
            <isEqual prepend="AND" property="searchCondition" compareValue="1">
                IMAGE_NM LIKE '%'||#searchKeyword#||'%'
            </isEqual>
    </select>

    <select id="mainImageDAO.selectMainImage" resultMap="mainImage">
        <![CDATA[
            SELECT IMAGE_ID,
                   IMAGE_NM,
                   IMAGE,
                   IMAGE_FILE,
                   IMAGE_DC,
                   REFLCT_AT,
                   FRST_REGISTER_ID,
                   FRST_REGIST_PNTTM
              FROM COMTNMAINIMAGE
             WHERE IMAGE_ID = #imageId#
        ]]>
    </select>

    <insert id="mainImageDAO.insertMainImage" parameterClass="MainImage">
        <![CDATA[
            INSERT INTO COMTNMAINIMAGE
                       (IMAGE_ID,
                        IMAGE_NM,
                        IMAGE,
                        IMAGE_FILE,
                        IMAGE_DC,
                        REFLCT_AT,
                        FRST_REGISTER_ID,
                        FRST_REGIST_PNTTM)
                VALUES (#imageId#,
                        #imageNm#,
                        #image#,
                        #imageFile#,
                        #imageDc#,
                        #reflctAt#,
                        #userId#,
                        SYSDATETIME)
        ]]>
    </insert>

    <update id="mainImageDAO.updateMainImage" parameterClass="MainImage">
            UPDATE COMTNMAINIMAGE
               SET IMAGE_NM = #imageNm#,
                   <isEqual property="isAtchFile" compareValue="true">
                   IMAGE = #image#,
                   IMAGE_FILE = #imageFile#,
                   </isEqual>
                   IMAGE_DC = #imageDc#,
                   REFLCT_AT = #reflctAt#,
                   LAST_UPDUSR_ID = #userId#,
                   LAST_UPDT_PNTTM = SYSDATETIME
             WHERE IMAGE_ID = #imageId#
    </update>

    <delete id="mainImageDAO.deleteMainImage" parameterClass="MainImage">
        <![CDATA[
            DELETE FROM COMTNMAINIMAGE
             WHERE IMAGE_ID = #imageId#
        ]]>
    </delete>

    <select id="mainImageDAO.selectMainImageResult" resultMap="image">
        <![CDATA[
            SELECT IMAGE_FILE
              FROM COMTNMAINIMAGE
             WHERE REFLCT_AT = 'Y'
        ]]>
    </select>

    <select id="mainImageDAO.selectMainImageFile" parameterClass="MainImage" resultMap="mainImageFile">
        <![CDATA[
            SELECT B.FILE_STRE_COURS AS FILE_STRE_COURS,
                   B.STRE_FILE_NM AS STRE_FILE_NM
              FROM COMTNMAINIMAGE A,
                   COMTNFILEDETAIL B
             WHERE 1 = 1
               AND IMAGE_ID = #imageId#
               AND A.IMAGE_FILE = B.ATCH_FILE_ID
        ]]>
    </select>

</sqlMap>


text:
<?php

namespace Mlo\Babl\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;

/**
 * AddCommand
 *
 * @author Matthew Loberg <loberg.matt@gmail.com>
 */
class AddCommand extends AbstractCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('add')
            ->setDescription('Add translation entry to file')
            ->addArgument('file', InputArgument::REQUIRED, 'File to add translation entry to')
            ->addArgument('key', InputArgument::REQUIRED, 'Translation key')
            ->addArgument('value', InputArgument::OPTIONAL, 'Translation value (if none given, it will prompt)')
            ->addOption(
                'force',
                null,
                InputOption::VALUE_NONE,
                'Will overwrite key if it exists without asking.'
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $file   = $input->getArgument('file');
        $key    = $input->getArgument('key');
        $value  = $input->getArgument('value');
        $helper = $this->getHelper('question');

        if (empty($value)) {
            $question = new Question(sprintf('Translation value for "%s": ', $key), '');
            $value = $helper->ask($input, $output, $question);
        }

        $fileInfo = $this->getFileInfo($file);

        $processor = $this->getProcessor($fileInfo->getExtension());
        $converter = $this->getConverter($fileInfo->getExtension());

        $data = $processor->process($file);

        $text     = sprintf('Translation key "%s" already exists. Update value? [yn] ', $key);
        $question = new ConfirmationQuestion($text, false);

        if (
            false === $input->getOption('force') &&
            array_key_exists($key, $data) &&
            !$helper->ask($input, $output, $question)
        ) {
            return;
        }

        $data[$key] = $value;

        file_put_contents($file, $converter->convert($data));

        $output->writeln(sprintf('<info>Translation key "%s" added to "%s".', $key, $file));
    }
}


text:
mvn clean package -Ppayara

java -jar ./target/payara-micro.jar --deploy ./target/micro-javaee.war


text:
       Crear Almacén

<?php
     $attributes = array('class' => 'bs-example form-horizontal');
echo form_open('miembros/agregar_almacen', $attributes);
?>

    <fieldset>
        <legend> Crear Nuevo Cliente </legend>

             Nombre

    <input name="inputNombre" class="form-control" type="text" placeholder=""></input>

             Punto de Reorden

<input name="inputPuntoReorden" class="form-control" type="text" placeholder=""></input>

             Código

<input name="inputCodigo" class="form-control" type="text" placeholder=""></input>

             Notas

<textarea name="inputNotas" class="form-control" type="text" placeholder=""></textarea>

<button class="btn btn-primary" type="submit"> Crear </button>

    </fieldset>

<?php echo form_close(); ?>

 Recordatorio

Reglas a seguir durante el llenado de la información así como cualquier forma de contactar a un admnistrador en caso de ser necesario.

También contiene un panel para mostrar errores.

<?php echo validation_errors(); ?>


text:
<?php

namespace Home\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Home\IndexBundle\Controller\BaseController;
use Doctrine\Common\Util\Debug;

class IndexController extends BaseController
{
    public function indexAction()
    {
    	$langs = $this->getDoctrine()
    	              ->getRepository('HomeIndexBundle:Lang')
    	              ->findAll();
    	$arr = array('langlist' => $langs);
        return $this->render('HomeUserBundle:Index:index.html.twig', $arr);
    }

    /**
     * 用户中心
     */
    public function usersAction($userid){
    	$em = $this->getDoctrine()->getManager();
    	$dql = "SELECT ui.pic, ui.motto, u.username, u.points, u.logintime, r.name
    	        FROM HomeUserBundle:Userinfo ui
    	        JOIN ui.user u
    	        JOIN u.role r
    	        WHERE u.status = :status
    	        AND u.id = :userid
    	        ORDER BY u.points DESC";
    	$query = $em->createQuery($dql)
    	            ->setParameter('status', 1)
    	            ->setParameter('userid', $userid);
    	$user = $query->getArrayResult();
    	echo "
";
    	Debug::dump($user[0]);
    	echo "
";
    	exit;
    }

    /**
     * 编辑用户资料信息
     */
    public function edituserAction($userid){
    	$em = $this->getDoctrine()->getManager();
    	$dql = "SELECT ui, u.username, u.isopen
    	        FROM HomeUserBundle:Userinfo ui
    	        JOIN ui.user u
    	        JOIN u.role r
    	        WHERE u.status = :status
    	        AND u.id = :userid
    	        ORDER BY u.points DESC";
    	$query = $em->createQuery($dql)
    	            ->setParameter('status', 1)
    	            ->setParameter('userid', $userid);
    	$user = $query->getArrayResult();
    	echo "
";
    	Debug::dump($user[0]);
    	echo "
";
    	exit;
    }

    /**
     * 保存用户编辑的内容
     */
    public function doedituserAction(){
    	// 验证数据 然后插入数据库
    	var_dump($_POST);
    	exit;
    }
}


text:
imdone-atom
----
I have decided to retire as the imdone-atom maintainer.  Instead, I'm putting all my energy into **[imdone](https://imdone.io/docs)**, an electron based desktop app that works with any text editor.  If you would like to take over maintenance of imdone-atom, please [contact me](email:jesse@imdone.io).

The latest release source code is available in the **[archive](https://github.com/imdone/imdone-atom/tree/archive)** branch.

Sincerely,

Jesse Piascik

![imdone desktop image](https://imdone.io/docs/images/imdone-screenshot.png)


text:
/*
 * SoundPort.cpp
 *
 *  Created on: Dec 5, 2013
 *      Author: lukas
 */

#include "SoundPort.h"

SoundPort::SoundPort(int portnumber) : Port(portnumber){ }

SoundPort::~SoundPort() { }

int SoundPort::init(){

    /* clear outgoing sample data */
    clearWriteBuffer();

    return 0;
}

void SoundPort::clearWriteBuffer(){

    char* writeBuffer;
    if((writeBuffer =  getWriteBuffer())){
        memset(writeBuffer, 0, Synthesizer::config::bytesPerBlock);
    }
}

char* SoundPort::getReadBuffer(){

    BufferedLinkPtr soundlink = boost::static_pointer_cast<BufferedLink>( getLink());
    if(soundlink){
        return soundlink->getReadBuffer();
    }
    return NULL;
}
char* SoundPort::getWriteBuffer(){

    BufferedLinkPtr soundlink = boost::static_pointer_cast<BufferedLink>( getLink());
    if (soundlink) {
        return soundlink->getWriteBuffer();
    }
    return NULL;
}

void SoundPort::writeSample(int32_t pcm_data, uint32_t nIndex){
    BufferedLinkPtr soundlink = boost::static_pointer_cast<BufferedLink>( getLink());

    if (soundlink != NULL) {
        if (nIndex >= 0 && (nIndex * Synthesizer::config::bytesPerSample) < soundlink->getBufferDepth()) {
            ((int32_t*) soundlink->getWriteBuffer())[nIndex] = pcm_data;
        } else {
            LOG_ERROR("Index out of bounds, while writing to soundport");
        }
    }else{
        LOG_ERROR("Try to access sample buffer of unconnected");
        //TODO throw exception here
    }
}

int SoundPort::operator[](size_t nIndex) {

    BufferedLinkPtr soundlink = boost::static_pointer_cast<BufferedLink>( getLink());

    /*
     * Check if index is not out of bound and port is connected
     */
    if(soundlink){
        if(nIndex >= 0 && (nIndex * Synthesizer::config::bytesPerSample) < soundlink->getBufferDepth()){
            return ((int*)soundlink->getReadBuffer())[nIndex];
        }else{
            LOG_ERROR("Index out of bounds, while reading from soundport");
        }
    }else{
        LOG_ERROR("Try to access sample buffer of unconnected");
        //TODO throw exception here
    }

    return 0;
}

SoundPort& SoundPort::operator= (SoundPort& rhs){

    if (this != &rhs) {

        BufferedLinkPtr rhslink = boost::static_pointer_cast<BufferedLink>(rhs.getLink());
        BufferedLinkPtr lhslink = boost::static_pointer_cast<BufferedLink>(this->getLink());

       if(rhslink && lhslink){

           memcpy(lhslink->getWriteBuffer(), rhslink->getReadBuffer(), Synthesizer::config::bytesPerBlock);
       }
    }

    return *this;
}


text:
using namespace soci;
using namespace soci::details;

void ref_counted_prepare_info::exchange(into_type_ptr const & i)
{
    intos_.push_back(i.get());
    i.release();
}

void ref_counted_prepare_info::exchange(use_type_ptr const & u)
{
    uses_.push_back(u.get());
    u.release();
}

void ref_counted_prepare_info::final_action()
{
    // deallocate all bind and define objects
    for (std::size_t i = intos_.size(); i > 0; --i)
    {
        delete intos_[i - 1];
        intos_.resize(i - 1);
    }

    for (std::size_t i = uses_.size(); i > 0; --i)
    {
        delete uses_[i - 1];
        uses_.resize(i - 1);
    }
}

std::string ref_counted_prepare_info::get_query() const
{
    return session_.get_query_stream().str();
}


text:
from typing import Any
import torch
from torch.nn import functional as F

from detectron2.config import CfgNode
from detectron2.layers import ConvTranspose2d

from densepose.modeling.confidence import DensePoseConfidenceModelConfig
from densepose.modeling.utils import initialize_module_params
from densepose.structures import decorate_cse_predictor_output_class_with_confidences

class DensePoseEmbeddingConfidencePredictorMixin:
    """
    Predictor contains the last layers of a DensePose model that take DensePose head
    outputs as an input and produce model outputs. Confidence predictor mixin is used
    to generate confidences for coarse segmentation estimated by some
    base predictor. Several assumptions need to hold for the base predictor:
    1) the `forward` method must return CSE DensePose head outputs,
        tensor of shape [N, D, H, W]
    2) `interp2d` method must be defined to perform bilinear interpolation;
        the same method is typically used for masks and confidences
    Confidence predictor mixin provides confidence estimates, as described in:
        N. Neverova et al., Correlated Uncertainty for Learning Dense Correspondences
            from Noisy Labels, NeurIPS 2019
        A. Sanakoyeu et al., Transferring Dense Pose to Proximal Animal Classes, CVPR 2020
    """

    def __init__(self, cfg: CfgNode, input_channels: int):
        """
        Initialize confidence predictor using configuration options.

        Args:
            cfg (CfgNode): configuration options
            input_channels (int): number of input channels
        """
        # we rely on base predictor to call nn.Module.__init__
        super().__init__(cfg, input_channels)  # pyre-ignore[19]
        self.confidence_model_cfg = DensePoseConfidenceModelConfig.from_cfg(cfg)
        self._initialize_confidence_estimation_layers(cfg, input_channels)
        self._registry = {}
        initialize_module_params(self)  # pyre-ignore[6]

    def _initialize_confidence_estimation_layers(self, cfg: CfgNode, dim_in: int):
        """
        Initialize confidence estimation layers based on configuration options

        Args:
            cfg (CfgNode): configuration options
            dim_in (int): number of input channels
        """
        kernel_size = cfg.MODEL.ROI_DENSEPOSE_HEAD.DECONV_KERNEL
        if self.confidence_model_cfg.segm_confidence.enabled:
            self.coarse_segm_confidence_lowres = ConvTranspose2d(  # pyre-ignore[16]
                dim_in, 1, kernel_size, stride=2, padding=int(kernel_size / 2 - 1)
            )

    def forward(self, head_outputs: torch.Tensor):
        """
        Perform forward operation on head outputs used as inputs for the predictor.
        Calls forward method from the base predictor and uses its outputs to compute
        confidences.

        Args:
            head_outputs (Tensor): head outputs used as predictor inputs
        Return:
            An instance of outputs with confidences,
            see `decorate_cse_predictor_output_class_with_confidences`
        """
        # assuming base class returns SIUV estimates in its first result
        base_predictor_outputs = super().forward(head_outputs)  # pyre-ignore[16]

        # create output instance by extending base predictor outputs:
        output = self._create_output_instance(base_predictor_outputs)

        if self.confidence_model_cfg.segm_confidence.enabled:
            # base predictor outputs are assumed to have `coarse_segm` attribute
            # base predictor is assumed to define `interp2d` method for bilinear interpolation
            output.coarse_segm_confidence = (
                F.softplus(
                    self.interp2d(  # pyre-ignore[16]
                        self.coarse_segm_confidence_lowres(head_outputs)  # pyre-ignore[16]
                    )
                )
                + self.confidence_model_cfg.segm_confidence.epsilon
            )
            output.coarse_segm = base_predictor_outputs.coarse_segm * torch.repeat_interleave(
                output.coarse_segm_confidence, base_predictor_outputs.coarse_segm.shape[1], dim=1
            )

        return output

    def _create_output_instance(self, base_predictor_outputs: Any):
        """
        Create an instance of predictor outputs by copying the outputs from the
        base predictor and initializing confidence

        Args:
            base_predictor_outputs: an instance of base predictor outputs
                (the outputs type is assumed to be a dataclass)
        Return:
           An instance of outputs with confidences
        """
        PredictorOutput = decorate_cse_predictor_output_class_with_confidences(
            type(base_predictor_outputs)  # pyre-ignore[6]
        )
        # base_predictor_outputs is assumed to be a dataclass
        # reassign all the fields from base_predictor_outputs (no deep copy!), add new fields
        output = PredictorOutput(
            **base_predictor_outputs.__dict__,
            coarse_segm_confidence=None,
        )
        return output


text:
package kumoi.shell.fob;

import java.lang.annotation.*;

/**
 *
 * @author Akiyoshi Sugiki
 */
// @Target({ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR,
//	   ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME)
public @interface foblivious {
	String value() default "";
}


text:
using NUnit.Framework;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace DistributedLockCodeGen;

[Category("CI")]
public class DocCommentGenerator
{
    [Test]
    public void GenerateDocComments()
    {
        var changes = CodeGenHelpers.EnumerateSolutionFiles()
            .Select(f => (file: f, code: File.ReadAllText(f)))
            .Select(t => (t.file, t.code, updatedCode: AddDocComments(t.code)))
            .Where(t => CodeGenHelpers.NormalizeCodeWhitespace(t.updatedCode) != CodeGenHelpers.NormalizeCodeWhitespace(t.code))
            .ToList();
        changes.ForEach(t => File.WriteAllText(t.file, t.updatedCode));
        Assert.IsEmpty(changes.Select(t => t.file));
    }

    internal static string AddDocComments(string code)
    {
        if (!CodeGenHelpers.HasPublicType(code, out var typeInfo)) { return code; }

        var acquireMethods = Regex.Matches(
                code,
                $@"(?<docComment>([ \t]+///.*?\n)*)(?<indent>    (    )?|\t(\t)?){(typeInfo.isInterface ? "" : "public ")}(?<returnType>\S+) (?<name>([a-zA-Z])+)\("
                    + @"((?<paramType>\S+) (?<paramName>([a-zA-Z])+)( = \S+)(, )?)+\)"
            );

        var updatedCode = code;
        foreach (var acquireMethod in acquireMethods.Cast<Match>())
        {
            var name = acquireMethod.Groups["name"].Value;
            if (!name.Contains("Acquire")) { continue; }

            var isTry = name.StartsWith("Try");
            var isAsync = name.EndsWith("Async");
            var lockType = name.Contains("Upgradeable") ? LockType.Upgrade
                : name.Contains("Write") ? LockType.Write
                : name.Contains("Read") ? LockType.Read
                : typeInfo.typeName.Contains("Semaphore") ? LockType.Semaphore
                : LockType.Mutex;

            var @object = lockType == LockType.Semaphore ? "semaphore" : "lock";
            var handleObject = lockType == LockType.Semaphore ? "ticket" : "lock";

            var lineStart = acquireMethod.Groups["indent"].Value + "/// ";
            var docComment = new StringBuilder();

            docComment.AppendLine(lineStart + "");

            docComment.Append(lineStart);
            if (isTry) { docComment.Append("Attempts to acquire "); }
            else { docComment.Append("Acquires "); }
            docComment.Append(lockType switch
            {
                LockType.Read => "a READ lock ",
                LockType.Upgrade => "an UPGRADE lock ",
                LockType.Write => "a WRITE lock ",
                LockType.Mutex => "the lock ",
                LockType.Semaphore => "a semaphore ticket ",
                _ => throw new NotSupportedException()
            });
            docComment.Append(isAsync ? "asynchronously" : "synchronously");
            docComment.Append(isTry ? ". " : ", failing with <see cref=\"TimeoutException\"/> if the attempt times out. ");
            docComment.Append(lockType switch
            {
                LockType.Read => "Multiple readers are allowed. Not compatible with a WRITE lock. ",
                LockType.Upgrade => "Not compatible with another UPGRADE lock or a WRITE lock. ",
                LockType.Write => "Not compatible with another WRITE lock or an UPGRADE lock. ",
                LockType.Mutex => "",
                LockType.Semaphore => "",
                _ => throw new NotSupportedException(),
            });
            docComment.AppendLine("Usage: ");

            docComment.Append(lineStart).AppendLine("");
            docComment.Append(lineStart).Append($"    {(isAsync ? "await " : "")}using (")
                .Append(isTry ? "var handle = " : "")
                .Append(isAsync ? "await " : "")
                .Append($"my{char.ToUpper(@object[0])}{@object[1..]}.")
                .AppendLine($"{name}(...))");
            docComment.Append(lineStart).AppendLine("    {");
            docComment.Append(lineStart).Append(' ', 8)
                .Append(isTry ? "if (handle != null) { " : "")
                .Append($"/* we have the {handleObject}! */")
                .AppendLine(isTry ? " }" : "");
            docComment.Append(lineStart).AppendLine("    }");
            docComment.Append(lineStart)
                .Append($"    // dispose releases the {handleObject}")
                .AppendLine(isTry ? " if we took it" : "");
            docComment.Append(lineStart).AppendLine("");

            docComment.Append(lineStart).AppendLine("");

            docComment.Append(lineStart).Append("<param name=\"timeout\">How long to wait before giving up on the acquisition attempt. ")
                .AppendLine($"Defaults to {(isTry ? "0" : "<see cref=\"Timeout.InfiniteTimeSpan\"/>")}</param>");
            docComment.Append(lineStart).AppendLine("<param name=\"cancellationToken\">Specifies a token by which the wait can be canceled</param>");

            var returnType = acquireMethod.Groups["returnType"].Value;
            if (returnType.StartsWith("ValueTask<")) { returnType = returnType.Replace("ValueTask<", "").TrimEnd('>'); }
            var useAn = "aeiou".Contains(char.ToLower(returnType[0]));
            docComment.Append(lineStart).Append($"<returns>A{(useAn ? "n" : "")} <see cref=\"{returnType.TrimEnd('?')}\"/> which can be used to release the {handleObject}")
                .Append(isTry ? " or null on failure" : "")
                .AppendLine("</returns>");

            updatedCode = updatedCode.Replace(acquireMethod.Value, docComment + acquireMethod.Value[acquireMethod.Groups["docComment"].Length..]);
        }

        return updatedCode;
    }
}

internal enum LockType
{
    Mutex,
    Read,
    Write,
    Upgrade,
    Semaphore,
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	">

	<!-- 引入属性文件 -->
	<context:property-placeholder location="classpath:config.properties" />

	<!-- 自动扫描dao和service包(自动注入) -->
	<context:component-scan base-package="tiams.dao, tiams.service" />

</beans>


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout android:id="@+id/container"
    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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:colorBackground"
    android:orientation="vertical">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="48dp">

        <me.tatarka.fakeartist.game.main.DrawingView
            android:id="@+id/drawing"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:background="@android:color/white"
            android:elevation="1dp" />
    </FrameLayout>

    <LinearLayout
        android:id="@+id/controls"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginBottom="48dp"
        android:gravity="end"
        android:elevation="2dp"
        android:orientation="horizontal"
        android:visibility="invisible"
        tools:visibility="visible">

        <ImageButton
            android:id="@+id/button_undo"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="?selectableItemBackgroundBorderless"
            android:contentDescription="@string/undo"
            android:src="@drawable/ic_action_undo" />

        <ImageButton
            android:id="@+id/button_done"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="?selectableItemBackgroundBorderless"
            android:contentDescription="@string/accept"
            android:src="@drawable/ic_action_check" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/end_game_controls"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:orientation="horizontal"
        android:visibility="invisible"
        android:elevation="2dp"
        tools:visibility="visible">

        <Button
            android:id="@+id/button_new_game"
            android:layout_width="wrap_content"
            android:layout_height="48dp"
            android:background="?selectableItemBackgroundBorderless"
            android:text="@string/new_game"
            android:textAppearance="@style/TextAppearance.AppCompat.Widget.Button" />

        <ImageButton
            android:id="@+id/button_share"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="?selectableItemBackgroundBorderless"
            android:contentDescription="@string/share"
            android:src="@drawable/ic_action_share" />
    </LinearLayout>

    <View
        android:id="@+id/overlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/tranlucent"
        android:clickable="true"
        android:visibility="gone" />

    <FrameLayout
        android:id="@+id/info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?colorPrimary"
        android:elevation="2dp"
        android:foreground="?selectableItemBackground"
        app:behavior_peekHeight="48dp"
        app:layout_behavior="@string/bottom_sheet_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/category"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:gravity="center_vertical"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:textColor="?android:textColorPrimaryInverse"
                tools:text="Category: Animals" />

            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:gravity="center_vertical"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:textColor="?android:textColorPrimaryInverse"
                tools:text="Title: Lion" />

            <TextView
                android:id="@+id/role"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:gravity="center_vertical"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:textColor="?android:textColorPrimaryInverse"
                tools:text="Role: Artiest" />
        </LinearLayout>

        <TextView
            android:id="@+id/status"
            android:layout_width="wrap_content"
            android:layout_height="48dp"
            android:layout_gravity="end"
            android:gravity="center_vertical"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:textAppearance="@style/TextAppearance.AppCompat.Caption"
            android:textColor="?colorAccent"
            android:textStyle="bold"
            android:visibility="visible"
            tools:text="@string/your_turn" />
    </FrameLayout>
</android.support.design.widget.CoordinatorLayout>


text:
<?php

namespace Amadeus\Client\Struct\Pnr\DisplayHistory;

/**
 * PnrInfo
 *
 * @package Amadeus\Client\Struct\Pnr\DisplayHistory
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class PnrInfo
{
    /**
     * @var Reservation
     */
    public $reservation;

    /**
     * PnrInfo constructor.
     *
     * @param string $recordLocator
     * @param \DateTime|null $creationDateTime
     */
    public function __construct($recordLocator, $creationDateTime = null)
    {
        $this->reservation = new Reservation($recordLocator, $creationDateTime);
    }
}


text:
MMHackathon
===========

MM Hackathon Template


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC 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.

package com.thoughtworks.selenium.webdriven;

import java.util.regex.Pattern;

/**
 * Prepend a variable declaration to a script.
 */
public class VariableDeclaration implements ScriptMutator {
  private final Pattern pattern;
  private final String declaration;

  public VariableDeclaration(String raw, String declaration) {
    this.declaration = declaration;
    raw = raw.replace(".", "\\s*\\.\\s*")
        .replace("(", "\\(")
        .replace(")", "\\)");

    pattern = Pattern.compile(".*" + raw + ".*");
  }

  public void mutate(String script, StringBuilder outputTo) {
    if (!pattern.matcher(script).matches()) {
      return;
    }

    outputTo.append(declaration);
  }
}


text:
require File.dirname(__FILE__) + '/helper'
require File.dirname(__FILE__) + '/lib/activerecord_test_case'

require 'will_paginate'
WillPaginate.enable_activerecord

class FinderTest < ActiveRecordTestCase
  fixtures :topics, :replies, :users, :projects, :developers_projects

  def test_new_methods_presence
    assert_respond_to_all Topic, %w(per_page paginate paginate_by_sql)
  end

  def test_simple_paginate
    entries = Topic.paginate :page => nil
    assert_equal 1, entries.current_page
    assert_nil entries.previous_page
    assert_nil entries.next_page
    assert_equal 1, entries.page_count
    assert_equal 4, entries.size

    entries = Topic.paginate :page => 2
    assert_equal 2, entries.current_page
    assert_equal 1, entries.previous_page
    assert_equal 1, entries.page_count
    assert entries.empty?
  end

  def test_parameter_api
    # :page parameter in options is required!
    assert_raise(ArgumentError){ Topic.paginate }
    assert_raise(ArgumentError){ Topic.paginate({}) }

    # explicit :all should not break anything
    assert_equal Topic.paginate(:page => nil), Topic.paginate(:all, :page => 1)

    # :count could be nil and we should still not cry
    assert_nothing_raised { Topic.paginate :page => 1, :count => nil }
  end

  def test_paginate_with_per_page
    entries = Topic.paginate :page => 1, :per_page => 1
    assert_equal 1, entries.size
    assert_equal 4, entries.page_count

    # Developer class has explicit per_page at 10
    entries = Developer.paginate :page => 1
    assert_equal 10, entries.size
    assert_equal 2, entries.page_count

    entries = Developer.paginate :page => 1, :per_page => 5
    assert_equal 11, entries.total_entries
    assert_equal 5, entries.size
    assert_equal 3, entries.page_count
  end

  def test_paginate_with_order
    entries = Topic.paginate :page => 1, :order => 'created_at desc'
    expected = [topics(:futurama), topics(:harvey_birdman), topics(:rails), topics(:ar)].reverse
    assert_equal expected, entries.to_a
    assert_equal 1, entries.page_count
  end

  def test_paginate_with_conditions
    entries = Topic.paginate :page => 1, :conditions => ["created_at > ?", 30.minutes.ago]
    expected = [topics(:rails), topics(:ar)]
    assert_equal expected, entries.to_a
    assert_equal 1, entries.page_count
  end

  def test_paginate_with_include_and_conditions
    entries = Topic.paginate \
      :page     => 1,
      :include  => :replies,
      :conditions => "replies.content LIKE 'Bird%' ",
      :per_page => 10

    expected = Topic.find :all,
      :include => 'replies',
      :conditions => "replies.content LIKE 'Bird%' ",
      :limit   => 10

    assert_equal expected, entries.to_a
    assert_equal 1, entries.total_entries
  end

  def test_paginate_with_include_and_order
    entries = Topic.paginate \
      :page     => 1,
      :include  => :replies,
      :order    => 'replies.created_at asc, topics.created_at asc',
      :per_page => 10

    expected = Topic.find :all,
      :include => 'replies',
      :order   => 'replies.created_at asc, topics.created_at asc',
      :limit   => 10

    assert_equal expected, entries.to_a
    assert_equal 4, entries.total_entries
  end

  def test_paginate_associations_with_include
    entries, project = nil, projects(:active_record)

    assert_nothing_raised "THIS IS A BUG in Rails 1.2.3 that was fixed in [7326]. " +
        "Please upgrade to the 1-2-stable branch or edge Rails." do
      entries = project.topics.paginate \
        :page     => 1,
        :include  => :replies,
        :conditions => "replies.content LIKE 'Nice%' ",
        :per_page => 10
    end

    expected = Topic.find :all,
      :include => 'replies',
      :conditions => "project_id = #{project.id} AND replies.content LIKE 'Nice%' ",
      :limit   => 10

    assert_equal expected, entries.to_a
  end

  def test_paginate_associations
    dhh = users :david
    expected_name_ordered = [projects(:action_controller), projects(:active_record)]
    expected_id_ordered   = [projects(:active_record), projects(:action_controller)]

    # with association-specified order
    entries = dhh.projects.paginate(:page => 1)
    assert_equal expected_name_ordered, entries
    assert_equal 2, entries.total_entries

    # with explicit order
    entries = dhh.projects.paginate(:page => 1, :order => 'projects.id')
    assert_equal expected_id_ordered, entries
    assert_equal 2, entries.total_entries

    assert_nothing_raised { dhh.projects.find(:all, :order => 'projects.id', :limit => 4) }
    entries = dhh.projects.paginate(:page => 1, :order => 'projects.id', :per_page => 4)
    assert_equal expected_id_ordered, entries

    # has_many with implicit order
    topic = Topic.find(1)
    expected = [replies(:spam), replies(:witty_retort)]
    assert_equal expected.map(&:id).sort, topic.replies.paginate(:page => 1).map(&:id).sort
    assert_equal expected.reverse, topic.replies.paginate(:page => 1, :order => 'replies.id ASC')
  end

  def test_paginate_association_extension
    project = Project.find(:first)
    entries = project.replies.paginate_recent :page => 1
    assert_equal [replies(:brave)], entries
  end

  def test_paginate_with_joins
    entries = Developer.paginate :page => 1,
                        :joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id',
                        :conditions => 'project_id = 1'
    assert_equal 2, entries.size
    developer_names = entries.map { |d| d.name }
    assert developer_names.include?('David')
    assert developer_names.include?('Jamis')

    expected = entries.to_a
    entries = Developer.paginate :page => 1,
                        :joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id',
                        :conditions => 'project_id = 1', :count => { :select => "users.id" }
    assert_equal expected, entries.to_a
  end

  def test_paginate_with_group
    entries = Developer.paginate :page => 1, :per_page => 10, :group => 'salary'
    expected = [ users(:david), users(:jamis), users(:dev_10), users(:poor_jamis) ].map(&:salary).sort
    assert_equal expected, entries.map(&:salary).sort
  end

  def test_paginate_with_dynamic_finder
    expected = [replies(:witty_retort), replies(:spam)]
    assert_equal expected, Reply.paginate_by_topic_id(1, :page => 1)

    entries = Developer.paginate :conditions => { :salary => 100000 }, :page => 1, :per_page => 5
    assert_equal 8, entries.total_entries
    assert_equal entries, Developer.paginate_by_salary(100000, :page => 1, :per_page => 5)

    # dynamic finder + conditions
    entries = Developer.paginate_by_salary(100000, :page => 1,
                                           :conditions => ['id > ?', 6])
    assert_equal 4, entries.total_entries
    assert_equal (7..10).to_a, entries.map(&:id)

    assert_raises NoMethodError do
      Developer.paginate_by_inexistent_attribute 100000, :page => 1
    end
  end

  def test_paginate_by_sql
    assert_respond_to Developer, :paginate_by_sql
    entries = Developer.paginate_by_sql ['select * from users where salary > ?', 80000],
      :page => 2, :per_page => 3, :total_entries => 9

    assert_equal (5..7).to_a, entries.map(&:id)
    assert_equal 9, entries.total_entries
  end

  def test_count_by_sql
    entries = Developer.paginate_by_sql ['select * from users where salary > ?', 60000],
      :page => 2, :per_page => 3

    assert_equal 12, entries.total_entries
  end

  def test_count_distinct
    entries = Developer.paginate :select => 'DISTINCT salary', :page => 1, :per_page => 4
    assert_equal 4, entries.size
    assert_equal 4, entries.total_entries
  end

  def test_scoped_paginate
    entries =
      Developer.with_poor_ones do
        Developer.paginate :page => 1
      end

    assert_equal 2, entries.size
    assert_equal 2, entries.total_entries
  end

  # Are we on edge? Find out by testing find_all which was removed in [6998]
  unless Developer.respond_to? :find_all
    def test_paginate_array_of_ids
      # AR finders also accept arrays of IDs
      # (this was broken in Rails before [6912])
      entries = Developer.paginate((1..8).to_a, :per_page => 3, :page => 2)
      assert_equal (4..6).to_a, entries.map(&:id)
      assert_equal 8, entries.total_entries
    end
  end

  uses_mocha 'parameter' do
    def test_implicit_all_with_dynamic_finders
      Topic.expects(:find_all_by_foo).returns([])
      Topic.expects(:wp_extract_finder_conditions)
      Topic.expects(:count)
      Topic.paginate_by_foo :page => 1
    end

    def test_guessing_the_total_count
      Topic.expects(:find).returns(Array.new(2))
      Topic.expects(:count).never

      entries = Topic.paginate :page => 2, :per_page => 4
      assert_equal 6, entries.total_entries
    end

    def test_extra_parameters_stay_untouched
      Topic.expects(:find).with() { |*args| args.last.key? :foo }.returns(Array.new(5))
      Topic.expects(:count).with(){ |*args| args.last.key? :foo }.returns(1)

      Topic.paginate :foo => 'bar', :page => 1, :per_page => 4
    end

    def test_count_doesnt_use_select_options
      Developer.expects(:find).with() { |*args| args.last.key? :select }.returns(Array.new(5))
      Developer.expects(:count).with(){ |*args| !args.last.key?(:select) }.returns(1)

      Developer.paginate :select => 'users.*', :page => 1, :per_page => 4
    end

    def test_should_use_scoped_finders_if_present
      # scope-out compatibility
      Topic.expects(:find_best).returns(Array.new(5))
      Topic.expects(:with_best).returns(1)

      Topic.paginate_best :page => 1, :per_page => 4
    end

    def test_ability_to_use_with_custom_finders
      # acts_as_taggable defines `find_tagged_with(tag, options)`
      Topic.expects(:find_tagged_with).with('will_paginate', :offset => 0, :limit => 5).returns([])
      Topic.expects(:count).with({}).returns(0)

      Topic.paginate_tagged_with 'will_paginate', :page => 1, :per_page => 5
    end
  end
end


text:
cask 'sciencefair' do
  version '1.0.6'
  sha256 '24607fd3b708569f9d72d3db5b555919d1f8fcb2d8a0e3c3700fef20faf48274'

  # github.com/codeforscience/sciencefair was verified as official when first introduced to the cask
  url "https://github.com/codeforscience/sciencefair/releases/download/v#{version}/scienceFair-#{version}.dmg"
  appcast 'https://github.com/codeforscience/sciencefair/releases.atom'
  name 'ScienceFair'
  homepage 'http://sciencefair-app.com/'

  app 'ScienceFair.app'

  zap trash: [
               '~/Documents/sciencefair',
               '~/Library/Application Support/sciencefair',
               '~/Library/Logs/sciencefair',
               '~/Library/Preferences/org.codeforscience.sciencefair.helper.plist',
               '~/Library/Preferences/org.codeforscience.sciencefair.plist',
               '~/Library/Saved Application State/org.codeforscience.sciencefair.savedState',
             ]
end


text:
// # What is "packing"?
//
// Before feeding data to the gemm kernels (the parts of Ruy that do lots
// of multiply-add operations), Ruy first performs a data transformation (which
// we call "packing") on the input matrices. This transformation has two main
// goals:
// - rearrange data into blocks that are a convenient size/layout for the gemm
// kernels to consume. This helps make the memory access pattern of the gemm
// kernel simpler and more contiguous, and puts the data in a layout most
// convenient for specific arithmetic instructions in the gemm kernel.
// - compute row/column sums needed for handling quantization with non-symmetric
// zero points.
//
// # Simplified algorithmic analysis of packing
//
// Packing is a relatively simple transformation which does a small constant
// amount of work on each element of an input matrix, and hence for an NxM
// matrix performs O(N*M) work. If N and M are of the same order, then this is
// O(N^2) work.
//
// A NxKxM matrix multiplication requires N*K*M multiply-accumulate operations.
// Note that if N, K, and M are all the same order, then the number of
// multiply-accumulate operations is O(N^3).
//
// Thus, the O(N^2) cost of packing is small compared to the O(N^3) work, in the
// case of all dimensions being roughly the same order.
//
// # Packing cost can be significant
//
// When matrix * matrix multiplications begin to look more like matrix * vector
// multiplications, packing cost can become significant. We sometimes call these
// cases "gemv-like".
//
// Continuing the algorithmic analysis above, if we consider a case where an
// NxKxM matrix multiplication has either N = O(1) or M = O(1), then the
// situation is different. In this case, the multiply-accumulate work is only
// quadratic, so the quadratic cost of packing can be come significant.
//
// Another way to say this is that the cost of packing an input matrix (either
// the LHS or RHS) is amortized across the non-depth dimension of the opposite
// input matrix. Thus, when the LHS has very few rows or the RHS has very few
// columns, the cost of packing the opposite input matrix can become
// significant.
//
// As a rough rule of thumb, the cost of packing starts to become significant
// when either N or M is below 32 (and other dimensions are hundreds), with very
// significant packing costs at 8 or below. This varies by data type, Path, and
// tuning, so these numbers are only rough guides.
//
// One practical use case that is affected by this is inference of
// fully connected neural network layers with a low batch size. The weight
// matrix (which is a constant for inference) is the one affected by significant
// packing cost.
//
// Ruy provides an API in ruy_advanced.h for advanced users to pre-pack
// input matrices that are affected by significant packing costs.
//
// # Implementation notes
//
// Ruy's packing routines always operate on a range of columns and can be
// applied to either the LHS or RHS. This is possible because Ruy internally
// implements a TrMul, so the accumulation along depth is done along columns of
// both the LHS and RHS (whereas for a normal Mul the accumulation along depth
// for the LHS is along rows). As another example, we are always computing
// column sums for quantization (and never row sums, since the LHS is
// transposed).

#ifndef TENSORFLOW_LITE_EXPERIMENTAL_RUY_PACK_COMMON_H_
#define TENSORFLOW_LITE_EXPERIMENTAL_RUY_PACK_COMMON_H_

#include <cstdint>

#include "profiling/instrumentation.h"
#include "tensorflow/lite/experimental/ruy/check_macros.h"
#include "tensorflow/lite/experimental/ruy/common.h"
#include "tensorflow/lite/experimental/ruy/internal_matrix.h"
#include "tensorflow/lite/experimental/ruy/matrix.h"
#include "tensorflow/lite/experimental/ruy/opt_set.h"
#include "tensorflow/lite/experimental/ruy/path.h"
#include "tensorflow/lite/experimental/ruy/platform.h"
#include "tensorflow/lite/experimental/ruy/tune.h"

namespace ruy {

template <Path ThePath, typename Scalar>
struct PackedTypeImpl {
  using Type = Scalar;
};

#if RUY_PLATFORM(NEON_32)
struct PackParams8bit {
  const void* src_ptr0;
  const void* src_ptr1;
  const void* src_ptr2;
  const void* src_ptr3;
  const std::int32_t* sums_ptr;
  const std::int8_t* packed_ptr;
  int src_inc0;
  int src_inc1;
  int src_inc2;
  int src_inc3;
  int src_rows;
  int src_zero_point;
  int input_xor;
};

inline void MakePackParams8bit(const void* src_ptr0, const void* src_ptr1,
                               const void* src_ptr2, const void* src_ptr3,
                               const std::int32_t* sums_ptr,
                               const std::int8_t* packed_ptr, int src_inc0,
                               int src_inc1, int src_inc2, int src_inc3,
                               int src_rows, int src_zero_point, int input_xor,
                               PackParams8bit* params) {
  params->src_ptr0 = src_ptr0;
  params->src_ptr1 = src_ptr1;
  params->src_ptr2 = src_ptr2;
  params->src_ptr3 = src_ptr3;
  params->sums_ptr = sums_ptr;
  params->packed_ptr = packed_ptr;
  params->src_inc0 = src_inc0;
  params->src_inc1 = src_inc1;
  params->src_inc2 = src_inc2;
  params->src_inc3 = src_inc3;
  params->src_rows = src_rows;
  params->src_zero_point = src_zero_point;
  params->input_xor = input_xor;
}
#endif

#if RUY_PLATFORM(NEON)
template <>
struct PackedTypeImpl<Path::kNeon, std::uint8_t> {
  using Type = std::int8_t;
};
template <>
struct PackedTypeImpl<Path::kNeonDotprod, std::uint8_t> {
  using Type = std::int8_t;
};
#elif RUY_PLATFORM(X86)
template <>
struct PackedTypeImpl<Path::kAvx2, std::uint8_t> {
  using Type = std::int8_t;
};
template <>
struct PackedTypeImpl<Path::kAvx512, std::uint8_t> {
  using Type = std::int8_t;
};
#endif

template <Path ThePath, typename Scalar>
using PackedType = typename PackedTypeImpl<ThePath, Scalar>::Type;

template <typename PackedScalar, typename Scalar>
PackedScalar Pack(Scalar x) {
  return x - SymmetricZeroPoint<Scalar>() + SymmetricZeroPoint<PackedScalar>();
}

template <Path ThePath, typename FixedKernelLayout, typename Scalar,
          typename PackedScalar, typename SumsType>
struct PackImpl {};

#define RUY_INHERIT_PACK(PARENT, CHILD)                                       \
  template <typename FixedKernelLayout, typename Scalar,                      \
            typename PackedScalar, typename SumsType>                         \
  struct PackImpl<CHILD, FixedKernelLayout, Scalar, PackedScalar, SumsType>   \
      : PackImpl<PARENT, FixedKernelLayout, Scalar, PackedScalar, SumsType> { \
  };

template <typename FixedKernelLayout, typename Scalar, typename PackedScalar,
          typename SumsType>
struct PackImpl<Path::kStandardCpp, FixedKernelLayout, Scalar, PackedScalar,
                SumsType> {
  static void Run(Tuning, const Matrix<Scalar>& src_matrix,
                  PackedMatrix<PackedScalar>* packed_matrix, int start_col,
                  int end_col) {
    gemmlowp::ScopedProfilingLabel label("Pack (generic)");
    RUY_DCHECK_EQ((end_col - start_col) % FixedKernelLayout::kCols, 0);
    SumsType* sums = packed_matrix->sums;
    for (int col = start_col; col < end_col; col++) {
      SumsType accum = 0;
      for (int row = 0; row < packed_matrix->layout.rows; row++) {
        PackedScalar packed_val;
        if (col < src_matrix.layout.cols && row < src_matrix.layout.rows) {
          packed_val = Pack<PackedScalar>(Element(src_matrix, row, col));
        } else {
          packed_val = packed_matrix->zero_point;
        }
        accum += packed_val;
        *ElementPtr(packed_matrix, row, col) = packed_val;
      }
      if (sums) {
        sums[col] = accum;
      }
    }
  }
};

#if RUY_PLATFORM(NEON)
RUY_INHERIT_PACK(Path::kStandardCpp, Path::kNeon)
#if RUY_PLATFORM(NEON_64) && RUY_OPT_ENABLED(RUY_OPT_ASM)
RUY_INHERIT_PACK(Path::kNeon, Path::kNeonDotprod)
#endif
#elif RUY_PLATFORM(X86)
RUY_INHERIT_PACK(Path::kStandardCpp, Path::kAvx2)
RUY_INHERIT_PACK(Path::kAvx2, Path::kAvx512)
#endif

// Main entry point for packing.
template <Path ThePath, typename FixedKernelLayout, typename Scalar,
          typename PackedScalar>
void RunPack(Tuning tuning, const DMatrix& src_matrix, PMatrix* packed_matrix,
             int start_col, int end_col) {
  using SumsType = typename PackedMatrix<PackedScalar>::SumsType;
  Matrix<Scalar> src = ToMatrix<Scalar>(src_matrix);
  PackedMatrix<PackedScalar> packed =
      ToPackedMatrix<PackedScalar>(*packed_matrix);
  PackImpl<ThePath, FixedKernelLayout, Scalar, PackedScalar, SumsType>::Run(
      tuning, src, &packed, start_col, end_col);
}

}  // namespace ruy

#endif  // TENSORFLOW_LITE_EXPERIMENTAL_RUY_PACK_COMMON_H_


text:
<?php

namespace JustForWeb;

class QuoteForm
{
  private $method;

  private $requiredFields = array(
    'fullname' => "Missing name field.",
    'contact-email' => "Missing email field.",
    'city' => "Missing city field.",
    'phone' => "Missing phone field.",
    'g-recaptcha-response-quote' => "Please verify that you are not robot."
  );

  private $outputFields = array(
    'fullname' => "Name:",
    'contact-email' => "Email:",
    'city' => "City:",
    'callback' => "Callback Time:",
    'phone' => "Phone:",
    'how' => "How did you hear about us?",
    'types' => "Applicable Items:",
    'message' => "Message:"
  );

  public function __construct()
  {
    $this->method = $_SERVER['REQUEST_METHOD'];
  }

  public function getField($field) {
    if (isset($_POST[$field])) {
      return $_POST[$field];
    }
    return "";
  }

  public function processForm()
  {
    if ($this->method == "POST") {

      $this->checkRequiredFields();
      $recaptcha = new GoogleRecaptcha();

      if ($recaptcha->verify($_POST['g-recaptcha-response-quote'])) {
      // if (true) {
        return $this->sendEmail();
      } else {
        throw new \Exception("Could not verify captcha, try again.");
      }

    }
    return false;
  }

  public function checkRequiredFields()
  {
    foreach ($this->requiredFields as $field=>$message) {
      if (empty($_POST[$field])) {
        throw new \Exception($message);
      }
    }
  }

  public function sendEmail()
  {
    $mail = $this->configureMailer();
    $mail->addReplyTo($_POST['contact-email'], $_POST['fullname']);
    $mail->addCC($_POST['contact-email'], $_POST['fullname']);

    $mail->Subject = 'Request a Quote From: ' . $_POST['fullname'];

    $message = '';

    foreach ($_POST as $key=>$content) {

      if (in_array($key, array_keys($this->outputFields)) ) {

        if (is_array($content)) {
          $content = implode(", ", $content);
        }

        $content = strip_tags($content);
        $content = htmlentities($content);
        $content = nl2br($content);

        $message .= "
          {$this->outputFields[$key]}

          {$content}

        ";
      }
    }

    $mail->Body = $message;

    // $mail->Body    = "
    //   From: {$name} <{$email}>
    //

    //   Message:
    //

    //   {$message}
    // ";
    $mail->AltBody = strip_tags($message);

    if(!$mail->send()) {
      throw new \Exception("Message could not be sent. " . $mail->ErrorInfo);
    } else {
      return true;
    }
  }

  public function configureMailer()
  {
    $mail = new \PHPMailer();

    // $mail->SMTPDebug = 3;                               // Enable verbose debug output

    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = getenv('EMAIL_SMTP');            // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = getenv('EMAIL_FROM');               // SMTP username
    $mail->Password = getenv('EMAIL_FROM_PASSWORD');      // SMTP password
    $mail->SMTPSecure = getenv('EMAIL_SMTP_SECURITY');    // Enable TLS encryption, `ssl` also accepted
    $mail->Port = getenv('EMAIL_SMTP_PORT');              // TCP port to connect to

    //From myself to myself (alter reply address)
    $mail->setFrom(getenv('EMAIL_FROM'), getenv('EMAIL_FROM_NAME'));
    $mail->addAddress(getenv('EMAIL_TO'), getenv('EMAIL_TO_NAME'));
    $mail->isHTML(true);                                  // Set email format to HTML

    return $mail;
  }
}


text:
#include "../atrshmlog_internal.h"

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

/**
 * \file atrshmlogimpl_remove_tbuff.c
 */

/**
 * \n Main code:
 *
 * \brief We remove the buffer from the threads buffer list.
 *
 * If we detect a empty buffer list we also swith it to not ok logging.
 *
 * test t_turn_logging_off.c
 */
void atrshmlog_remove_tbuff(atrshmlog_g_tl_t* i_g, int i)
{
  if (i_g == NULL)
    return;

  if (i < 0)
    return;

  if (i_g->atrshmlog_targetbuffer_count <= i)
    return;

  // special case : we are the last buffer ....
  if (i_g->atrshmlog_targetbuffer_count == 1)
    {
      i_g->atrshmlog_targetbuffer_count = 0;

      i_g->atrshmlog_targetbuffer_index = 0;

      // we switch logging of for this thread
      i_g->atrshmlog_idnotok = 1;

      return;
    }

  // normal case : we have at least two buffers ...
  // so we copy the ptr from i + 1 to i and so on till end
  for (int k = i + 1; k < i_g->atrshmlog_targetbuffer_count; ++k)
    {
      i_g->atrshmlog_targetbuffer_arr[k-1] = i_g->atrshmlog_targetbuffer_arr[k];
    }

  // ok. now we have to correct the count
  --i_g->atrshmlog_targetbuffer_count;

  // and now we have to check for a valid index too
  if (i_g->atrshmlog_targetbuffer_count <= i_g->atrshmlog_targetbuffer_index)
    {
      i_g->atrshmlog_targetbuffer_index = 0;
    }
}


text:
namespace facebook {
namespace react {

JSCNativeModules::JSCNativeModules(std::shared_ptr<ModuleRegistry> moduleRegistry) :
  m_moduleRegistry(std::move(moduleRegistry)) {}

JSValueRef JSCNativeModules::getModule(JSContextRef context, JSStringRef jsName) {
  std::string moduleName = String::ref(jsName).str();

  const auto it = m_objects.find(moduleName);
  if (it != m_objects.end()) {
    return static_cast<JSObjectRef>(it->second);
  }

  auto module = createModule(moduleName, context);
  if (!module.hasValue()) {
    return JSValueMakeUndefined(context);
  }

  // Protect since we'll be holding on to this value, even though JS may not
  module->makeProtected();

  auto result = m_objects.emplace(std::move(moduleName), std::move(*module)).first;
  return static_cast<JSObjectRef>(result->second);
}

void JSCNativeModules::reset() {
  m_genNativeModuleJS = nullptr;
  m_objects.clear();
}

folly::Optional<Object> JSCNativeModules::createModule(const std::string& name, JSContextRef context) {
  if (!m_genNativeModuleJS) {
    auto global = Object::getGlobalObject(context);
    m_genNativeModuleJS = global.getProperty("__fbGenNativeModule").asObject();
    m_genNativeModuleJS->makeProtected();

    // Initialize the module name list, otherwise getModuleConfig won't work
    // TODO (pieterdb): fix this in ModuleRegistry
    m_moduleRegistry->moduleNames();
  }

  auto result = m_moduleRegistry->getConfig(name);
  if (!result.hasValue()) {
    return nullptr;
  }

  Value moduleInfo = m_genNativeModuleJS->callAsFunction({
    Value::fromDynamic(context, result->config),
    JSValueMakeNumber(context, result->index)
  });
  CHECK(!moduleInfo.isNull()) << "Module returned from genNativeModule is null";

  return moduleInfo.asObject().getProperty("module").asObject();
}

} }


text:
import numpy as np
import pandas as pd
import pytz

from six import integer_types

from unittest import TestCase

import zipline.utils.factory as factory
from zipline.sources import (DataFrameSource,
                             DataPanelSource,
                             RandomWalkSource)
from zipline.utils import tradingcalendar as calendar_nyse
from zipline.assets import AssetFinder
from zipline.finance.trading import TradingEnvironment

class TestDataFrameSource(TestCase):
    def test_df_source(self):
        source, df = factory.create_test_df_source(env=None)
        assert isinstance(source.start, pd.lib.Timestamp)
        assert isinstance(source.end, pd.lib.Timestamp)

        for expected_dt, expected_price in df.iterrows():
            sid0 = next(source)

            assert expected_dt == sid0.dt
            assert expected_price[0] == sid0.price

    def test_df_sid_filtering(self):
        _, df = factory.create_test_df_source(env=None)
        source = DataFrameSource(df)
        assert 1 not in [event.sid for event in source], \
            "DataFrameSource should only stream selected sid 0, not sid 1."

    def test_panel_source(self):
        source, panel = factory.create_test_panel_source(source_type=5)
        assert isinstance(source.start, pd.lib.Timestamp)
        assert isinstance(source.end, pd.lib.Timestamp)
        for event in source:
            self.assertTrue('sid' in event)
            self.assertTrue('arbitrary' in event)
            self.assertTrue('type' in event)
            self.assertTrue(hasattr(event, 'volume'))
            self.assertTrue(hasattr(event, 'price'))
            self.assertEquals(event['type'], 5)
            self.assertEquals(event['arbitrary'], 1.)
            self.assertEquals(event['sid'], 0)
            self.assertTrue(isinstance(event['volume'], int))
            self.assertTrue(isinstance(event['arbitrary'], float))

    def test_yahoo_bars_to_panel_source(self):
        env = TradingEnvironment()
        finder = AssetFinder(env.engine)
        stocks = ['AAPL', 'GE']
        env.write_data(equities_identifiers=stocks)
        start = pd.datetime(1993, 1, 1, 0, 0, 0, 0, pytz.utc)
        end = pd.datetime(2002, 1, 1, 0, 0, 0, 0, pytz.utc)
        data = factory.load_bars_from_yahoo(stocks=stocks,
                                            indexes={},
                                            start=start,
                                            end=end)
        check_fields = ['sid', 'open', 'high', 'low', 'close',
                        'volume', 'price']

        copy_panel = data.copy()
        sids = finder.map_identifier_index_to_sids(
            data.items, data.major_axis[0]
        )
        copy_panel.items = sids
        source = DataPanelSource(copy_panel)
        for event in source:
            for check_field in check_fields:
                self.assertIn(check_field, event)
            self.assertTrue(isinstance(event['volume'], (integer_types)))
            self.assertTrue(event['sid'] in sids)

    def test_nan_filter_dataframe(self):
        dates = pd.date_range('1/1/2000', periods=2, freq='B', tz='UTC')
        df = pd.DataFrame(np.random.randn(2, 2),
                          index=dates,
                          columns=[4, 5])
        # should be filtered
        df.loc[dates[0], 4] = np.nan
        # should not be filtered, should have been ffilled
        df.loc[dates[1], 5] = np.nan
        source = DataFrameSource(df)
        event = next(source)
        self.assertEqual(5, event.sid)
        event = next(source)
        self.assertEqual(4, event.sid)
        event = next(source)
        self.assertEqual(5, event.sid)
        self.assertFalse(np.isnan(event.price))

    def test_nan_filter_panel(self):
        dates = pd.date_range('1/1/2000', periods=2, freq='B', tz='UTC')
        df = pd.Panel(np.random.randn(2, 2, 2),
                      major_axis=dates,
                      items=[4, 5],
                      minor_axis=['price', 'volume'])
        # should be filtered
        df.loc[4, dates[0], 'price'] = np.nan
        # should not be filtered, should have been ffilled
        df.loc[5, dates[1], 'price'] = np.nan
        source = DataPanelSource(df)
        event = next(source)
        self.assertEqual(5, event.sid)
        event = next(source)
        self.assertEqual(4, event.sid)
        self.assertRaises(StopIteration, next, source)

class TestRandomWalkSource(TestCase):
    def test_minute(self):
        np.random.seed(123)
        start_prices = {0: 100,
                        1: 500}
        start = pd.Timestamp('1990-01-01', tz='UTC')
        end = pd.Timestamp('1991-01-01', tz='UTC')
        source = RandomWalkSource(start_prices=start_prices,
                                  calendar=calendar_nyse, start=start,
                                  end=end)
        self.assertIsInstance(source.start, pd.lib.Timestamp)
        self.assertIsInstance(source.end, pd.lib.Timestamp)

        for event in source:
            self.assertIn(event.sid, start_prices.keys())
            self.assertIn(event.dt.replace(minute=0, hour=0),
                          calendar_nyse.trading_days)
            self.assertGreater(event.dt, start)
            self.assertLess(event.dt, end)
            self.assertGreater(event.price, 0,
                               "price should never go negative.")
            self.assertTrue(13 <= event.dt.hour <= 21,
                            "event.dt.hour == %i, not during market \
                            hours." % event.dt.hour)

    def test_day(self):
        np.random.seed(123)
        start_prices = {0: 100,
                        1: 500}
        start = pd.Timestamp('1990-01-01', tz='UTC')
        end = pd.Timestamp('1992-01-01', tz='UTC')
        source = RandomWalkSource(start_prices=start_prices,
                                  calendar=calendar_nyse, start=start,
                                  end=end, freq='daily')
        self.assertIsInstance(source.start, pd.lib.Timestamp)
        self.assertIsInstance(source.end, pd.lib.Timestamp)

        for event in source:
            self.assertIn(event.sid, start_prices.keys())
            self.assertIn(event.dt.replace(minute=0, hour=0),
                          calendar_nyse.trading_days)
            self.assertGreater(event.dt, start)
            self.assertLess(event.dt, end)
            self.assertGreater(event.price, 0,
                               "price should never go negative.")
            self.assertEqual(event.dt.hour, 0)


text:
var gvizPlus = {}
gvizPlus._construct = function() {

    function VAxis(id, name) {
        this.id = id;
        this.name = name;
        this.visible = false;
    }

    function Line(column) {
        this.column = column;
        this.visible = true;
    }

    function Category(name) {
        this.name = name;

        this.lines = [];
        this.rows = [];
    }

    function DataSet(hAxis) {
        this.categories = [];
        this.allLines = new Object();
        this.hAxis = hAxis;
        this.vAxes = [new VAxis(0, 'Default')];

        // Default colors. Used http://llllll.li/randomColor/ to generate these
        this.colors = ['#4c40f7','#c9324b','#0cf44a','#ef81e4','#ef7015',
                       '#fcfbae','#88eaad','#84db39','#8bf46e','#8bef09','#ffddc9',
                       '#bcfcae','#4c40f7','#ffc9cd','#e0c582','#21c4a1','#af4933',
                       '#b25017','#cc764b','#8aea2a','#462099','#ef81e4','#c9324b',
                       '#b908d1','#77eaa7','#5ec8f9','#b0eaf4','#275f84','#aaea60',
                       '#e268e2','#f7bbf2','#e5ab75','#91f7ff','#d13c4d','#72e587',
                       '#f99dd4','#a9fcae','#e55e20','#1a557a','#7529e8','#ff89b8',
                       '#6b29ad','#90ed74','#ffada3','#cc3bd3','#3940bf','#9fd33f',
                       '#ff5b87','#0cf44a','#a2f774','#6c3fba','#ddd835','#8feadf',
                       '#d8b122','#66f9f4','#9303bf','#12698e','#ef5bc5','#efaba0'];
        this.colorIndex = 0;

        this.setColors = function(newColors) {
            this.colors = newColors;
        }

        this.getOrCreateCategoryIndex = function(name) {
            var index = -1;
            for(var i = 0; i < this.categories.length; i++) {
                if(this.categories[i].name === name) {
                    index = i;
                    break;
                }
            }

            if(index == -1) {
                index = this.categories.length;
                this.categories.push(new Category(name));
            }
            return index;
        }

        this.addCategory = function(category, lines, rows) {
            var index = this.getOrCreateCategoryIndex(category);
            for(var i = 0; i < lines.length; i++) {
                var lineObj = new Line(lines[i]);
                lineObj.vAxis = this.vAxes[0];
                lineObj.color = this.colors[this.colorIndex];
                this.colorIndex += 1;
                this.allLines[lines[i].label] = lineObj;
                this.categories[index].lines.push(lineObj);
            }
            for(var i = 0; i < rows.length; i++) {
                this.categories[index].rows.push(rows[i]);
            }
        }

        this.addAxis = function(name, lines) {
            var vAxis = new VAxis(this.vAxes.length, name);
            for(var i = 0; i < lines.length; i++) {
                this.allLines[lines[i].label].vAxis = vAxis;
            }
            this.vAxes.push(vAxis);
        }

        this.getColumnId = function(line, includeHidden) {
            var columnId = 0;
            for(var i = 0; i < this.categories.length; i++) {
                var category = this.categories[i];
                for(var k = 0; k < category.lines.length; k++) {
                    var currLine = category.lines[k];
                    if (currLine === line) {
                        return columnId;
                    } else if(includeHidden || currLine.visible){
                        columnId += 1;
                    }
                }
            }

            return -1;
        }
    }

    function Graph(id, title) {
        // Drawing properties
        this.div = document.getElementById(id);
        this.title = title;
        this.width = 1000;
        this.height = 500;
        this.legendWith = 250;
        this.axisWidth = 100;

        this.generateDataTable = function(dataSet) {
            var dataTable = new google.visualization.DataTable();
            dataTable.addColumn(dataSet.hAxis);
            for (var i = 0; i < dataSet.categories.length; i++) {
                var category = dataSet.categories[i];
                var currentColumns = dataTable.getNumberOfColumns() - 1;

                for(var j = 0; j < category.lines.length; j++) {
                    dataTable.addColumn(category.lines[j].column);
                }

                for(var j = 0; j < category.rows.length; j++) {
                    var row = category.rows[j];
                    if(i == 0) {
                        // We will take everything as-is from the first dataset
                        dataTable.addRow(row);
                    } else {
                        // For the rest, we'll add empty values until it's our spot
                        var newRow = [row[0]];

                        for(var k = 0; k < currentColumns; k++) {
                            newRow.push(null);
                        }

                        for(var k = 1; k < row.length; k++) {
                            newRow.push(row[k]);
                        }
                        dataTable.addRow(newRow);
                    }
                }
            }

            return dataTable;
        }

        this.generateGoogleAxisInfo = function(dataSet) {
            var googleAxisInfo = new Object();
            googleAxisInfo.vAxis = {0:{textPosition:'none'}};
            googleAxisInfo.series = {};
            if (dataSet.vAxes.length > 0) {
                for (var i = 0; i < dataSet.vAxes.length; i++) {
                    var vAxis = dataSet.vAxes[i];
                    if(vAxis.visible) {
                        googleAxisInfo.vAxis[vAxis.id + 1] = {textPosition: 'out', title: vAxis.name};
                    } else {
                        googleAxisInfo.vAxis[vAxis.id + 1] = {textPosition: 'none'};
                    }
                }
            }

            for (key in dataSet.allLines) {
                var line = dataSet.allLines[key];

                if (line.visible) {
                    var columnId = dataSet.getColumnId(line, false); // Lines map to columns in the dataTable
                    var vAxisId = 0;
                    if (line.vAxis) {
                        vAxisId = line.vAxis.id + 1;
                    }
                    googleAxisInfo.series[columnId] = {targetAxisIndex:vAxisId, color:line.color};
                }
            }

            return googleAxisInfo;
        }

        function addText(toElem, text) {
            var textNode = document.createTextNode(text);
            toElem.appendChild(textNode);
            return textNode
        }

        function addElement(toElem, type, name) {
            var newElem = document.createElement(type);
            newElem.setAttribute('name', name);
            toElem.appendChild(newElem);
            return newElem;
        }

        this.draw = function(dataSet) {
            this.dataSet = dataSet;
            var dataTable = this.generateDataTable(dataSet);
            this.googleHAxis = {title: dataSet.hAxis['label']};
            this.googleDataView = new google.visualization.DataView(dataTable);

            addText(this.div, this.title);

            var googleDiv = addElement(this.div, 'div', id + '_google');
            var legendDiv = addElement(this.div, 'div', id + '_legend');
            legendDiv.setAttribute('style', 'position: absolute;top: 50px;width: ' + (this.legendWith - 10) + 'px');

            for (var i = 0; i < dataSet.categories.length; i++) {
                var category = dataSet.categories[i];
                var categoryDiv = addElement(legendDiv, 'div', 'category_' + category.name);
                addText(categoryDiv, category.name);

                for(var j = 0; j < category.lines.length; j++) {
                    var line = category.lines[j];

                    var lineDiv = addElement(categoryDiv, 'div', 'line_' + line.column.label);
                    lineDiv.setAttribute('style', 'background-color: ' + line.color + ';color: white;');
                    addText(lineDiv, line.column.label);

                    lineDiv.style.cursor = 'pointer';
                    lineDiv.onclick = function(gvizPlus, line) {
                        return function() {
                            var columnId = gvizPlus.dataSet.getColumnId(line, true) + 1;
                            if (line.visible) {
                                line.visible = false;
                                gvizPlus.googleDataView.hideColumns([columnId]);
                            } else {
                                line.visible = true;
                                var currColumns = gvizPlus.googleDataView.getViewColumns();
                                currColumns.push(columnId);
                                currColumns.sort();
                                gvizPlus.googleDataView.setColumns(currColumns);
                            }
                            gvizPlus.googleDraw();
                        }
                    }(this, line);

                    lineDiv.onmouseover = function(gvizPlus, line) {
                        return function() {
                            if (line.vAxis) {
                                line.vAxis.visible = true;
                                gvizPlus.googleDraw();
                            }
                        }
                    }(this, line);

                    lineDiv.onmouseout = function(gvizPlus, line) {
                        return function() {
                            if (line.vAxis) {
                                line.vAxis.visible = false;
                                gvizPlus.googleDraw();
                            }
                        }
                    }(this, line);
                }
            }

            this.googleChart = new google.visualization.LineChart(googleDiv);
            this.googleDraw();
        }

        this.googleDraw = function() {
            var chartWidth = this.width - this.legendWith - this.axisWidth;
            var googleAxisInfo = this.generateGoogleAxisInfo(this.dataSet);
            this.googleChart.draw(this.googleDataView, {
              title : null,
              legend : 'none', // We'll draw a better legend
              interpolateNulls : false,
              chartArea : { left: this.legendWith, top: 0, width: chartWidth, height: '80%' },
              width: this.width,
              height: this.height,
              hAxis: this.googleHAxis,
              vAxes: googleAxisInfo.vAxis,
              series: googleAxisInfo.series
            });
        }
    }

    this.DataSet = DataSet
    this.Graph = Graph
}
gvizPlus._construct()


text:
@interface Data : NSObject

// To fill the data.
- (void)newLine:(NSString *)line;

// To process the data once filled.
- (void)processData;

// To fetch the data. Every series will have the same number of data points.
@property (nonatomic,readonly) NSArray *seriesArray;
@property (nonatomic,readonly) int dataPointCount;

// Plot info.
@property (nonatomic,readonly) Axis *leftAxis;
@property (nonatomic,readonly) Axis *rightAxis;

// Domains and the delta values for derivative plots.
- (Series *)domainSeriesForDerivative:(int)derivative;
@property (nonatomic,readonly) Grid *domainGrid;

@end


text:
/**
 * Created by karl on 16/07/15.
 */
'use strict';
var cluster = require('cluster');
var logMock = {
    error: function (data, msg) {
        console.error(JSON.stringify(data), msg);
    }
};
function getErrorHandler(server) {
    return function errorHandler(err, req, res, next) {
        var friendly = {
            message: err.message,
            stack: err.stack
        };
        if (!req.log) {
            req.log = logMock;
        }
        req.log.error({ error: friendly }, 'Something went wrong');
        if (cluster.isMaster) {
            res.error(err.message);
            return;
        }
        try {
            // make sure we close down within 30 seconds
            var killtimer = setTimeout(function () {
                process.exit(1);
            }, 30000);
            // But don't keep the process open just for that!
            killtimer.unref();
            // stop taking new requests.
            server.close();
            // Let the master know we're dead.  This will trigger a
            // 'disconnect' in the cluster master, and then it will fork
            // a new worker.
            if (cluster.worker) {
                cluster.worker.disconnect();
            }
            // try to send an error to the request that triggered the problem
            res.error(err.message);
        }
        catch (err2) {
            // oh well, not much we can do at this point.
            var friendly2 = {
                message: err2.message,
                stack: err2.stack
            };
            req.log.error({ error: friendly2 }, 'Error sending 500!');
            res.end();
        }
    };
}
exports.getErrorHandler = getErrorHandler;
//# sourceMappingURL=error.js.map


text:
#include <QWidget>
#include <QPushButton>
#include <QSlider>
#include <QIcon>

class controlPanel : public QWidget
{
    Q_OBJECT
public:
    enum Widget{ PreviousButton, PlayPauseButton, NextButton};
    enum PlayPauseButtonState{Playing, Paused};
    explicit controlPanel(QWidget *parent = 0);

    const QObject * widget(controlPanel::Widget widget);

    void setPlayButtonIcon(const QIcon &);
    void setPauseButtonIcon(const QIcon &);
    void setNextButtonIcon(const QIcon &);
    void setPreviousButtonIcon(const QIcon &);

    void setState(controlPanel::PlayPauseButtonState);

signals:
    void volumeSliderValueChanged(int value);

public slots:
    void togglePlayPauseState();
    void recieveNewVolumeSliderValue(int value);

private:
    QPushButton * _playPauseButton;
    QPushButton * _nextButton;
    QPushButton * _previousButton;

    QSlider * _volumeSlider;
    QIcon _playButtonIcon, _pauseButtonIcon;
    PlayPauseButtonState _currentState;
};

#endif // CONTROLPANEL_H


text:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "utils.h"

#define STORAGE_SIZE 100

/* gcc -Wall -z execstack -o lab3A lab3A.c */

/* get a number from the user and store it */
int store_number(unsigned int * data)
{
    unsigned int input = 0;
    unsigned int index = 0;

    /* get number to store */
    printf(" Number: ");
    input = get_unum();

    /* get index to store at */
    printf(" Index: ");
    index = get_unum();

    /* make sure the slot is not reserved */
    if(index % 3 == 0 || (input >> 24) == 0xb7)
    {
        printf(" *** ERROR! ***\n");
        printf("   This index is reserved for quend!\n");
        printf(" *** ERROR! ***\n");

        return 1;
    }

    /* save the number to data storage */
    data[index] = input;

    return 0;
}

/* returns the contents of a specified storage index */
int read_number(unsigned int * data)
{
    unsigned int index = 0;

    /* get index to read from */
    printf(" Index: ");
    index = get_unum();

    printf(" Number at data[%u] is %u\n", index, data[index]);

    return 0;
}

int main(int argc, char * argv[], char * envp[])
{
    int res = 0;
    char cmd[20] = {0};
    unsigned int data[STORAGE_SIZE] = {0};

    /* doom doesn't like enviroment variables */
    clear_argv(argv);
    clear_envp(envp);

    printf("----------------------------------------------------\n"\
           "  Welcome to quend's crappy number storage service!  \n"\
           "----------------------------------------------------\n"\
           " Commands:                                          \n"\
           "    store - store a number into the data storage    \n"\
           "    read  - read a number from the data storage     \n"\
           "    quit  - exit the program                        \n"\
           "----------------------------------------------------\n"\
           "   quend has reserved some storage for herself :>    \n"\
           "----------------------------------------------------\n"\
           "\n");

    /* command handler loop */
    while(1)
    {
        /* setup for this loop iteration */
        printf("Input command: ");
        res = 1;

        /* read user input, trim newline */
        fgets(cmd, sizeof(cmd), stdin);
        cmd[strlen(cmd)-1] = '\0';

        /* select specified user command */
        if(!strncmp(cmd, "store", 5))
            res = store_number(data);
        else if(!strncmp(cmd, "read", 4))
            res = read_number(data);
        else if(!strncmp(cmd, "quit", 4))
            break;

        /* print the result of our command */
        if(res)
            printf(" Failed to do %s command\n", cmd);
        else
            printf(" Completed %s command successfully\n", cmd);

        memset(cmd, 0, sizeof(cmd));
    }

    return EXIT_SUCCESS;
}


text:
author:
  display_name: Rick Kelson
  email: rkelson@utah.gov
tags: []
date: 2016-04-28 22:11:31
title: UGRC Storage Migration
categories: []
---

UGRC is in the process of migrating some of it's SGID content, downloadable via FTP, from High-Speed Network Attached Storage (HNAS) to Google Cloud Storage (GCS) available through the Google Cloud Platform (GCP). At this time only historical scanned imagery and the National Agricultural Image Program (NAIP) Mr. Sid Compressed County Mosaics (CCMs), for all available years, have been moved to the GCS. This represents over 4TB of static storage requirements.

There have not been any problems with the new storage and re-pointing downloadable files to the GCS. Testing has confirmed that even large 7GB zipfiles can be downloaded from the GCS in a timely manner comparable to that of HNAS. Over time more of UGRC's storage needs will be migrated to the GCS. End users should not notice any differences. But if you do, be sure to let us know!

Why fix something that is not broken? We are trying to find the right storage solution for the data resources we all need, balancing performance, ease-of use, complexity, and cost. As the size of GIS datasets continues to increase, we want to ensure UGRC is best positioned meet future needs.


text:
@interface YMCalendarActivity () {
    EKEventEditViewController *viewController;
}

@end

@implementation YMCalendarActivity

- (NSString *)activityType {
    return NSStringFromClass([self class]);
}

- (NSString *)activityTitle {
    return NSLocalizedString(@"Add to Calendar", nil);
}

- (UIImage *)activityImage {
    float iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (iOSVersion >= 7.0) {
        return [UIImage imageNamed:@"Calendar.png"];
    } else {
        return [UIImage imageNamed:@"Calendar-6.png"];
    }
}

- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems {
    for (id activityItem in activityItems) {
        if ([activityItem isKindOfClass:[YMCalendarActivityEvent class]]) {
            return YES;
        }
    }
    return  NO;
}

- (void)prepareWithActivityItems:(NSArray *)activityItems {
    for (id activityItem in activityItems) {
        if ([activityItem isKindOfClass:[YMCalendarActivityEvent class]]) {
            YMCalendarActivityEvent *event = activityItem;

            if (viewController == nil) {
                EKEventStore *es = [[EKEventStore alloc] init];
                EKEvent *e = [EKEvent eventWithEventStore:es];
                e.title = event.title;
                e.location = event.location;
                e.notes = event.notes;
                e.URL = event.URL;
                e.timeZone = event.timeZone;
                e.startDate = event.startDate;
                e.endDate = event.endDate;
                e.allDay = event.allDay;

                viewController = [[EKEventEditViewController alloc] init];
                viewController.editViewDelegate = self;
                viewController.event = e;
                viewController.eventStore = es;
            }
        }
    }
}

- (UIViewController *)activityViewController {
    return viewController;
}

- (void)activityDidFinish:(BOOL)completed {
    [super activityDidFinish:completed];
}

- (void)eventEditViewController:(EKEventEditViewController *)controller didCompleteWithAction:(EKEventEditViewAction)action {
    NSError *error = nil;

    switch (action) {
        case EKEventEditViewActionSaved:
            [controller.eventStore saveEvent:controller.event span:EKSpanThisEvent error:&error];
            break;

        case EKEventEditViewActionCancelled:
            break;

        default:
            break;
    }

    [self activityDidFinish:YES];
}

@end


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Flappy Kyrnu - GOOGLE IS COMING</title>
    <link rel="stylesheet" href="style.css">

</head>
<body>

    <script type="text/javascript" src="game.js"></script>
    <script type="text/javascript" src="bird.js"></script>
</body>
</html>


text:
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta itemprop="name" content="FAILRAIL.sg">
<meta itemprop="description"
	content="A timeline of train service disruptions in Singapore, visualized on Google Maps">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta property="og:title" content="FAILRAIL.sg" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://failrailsg.appspot.com/" />
<meta property="og:image" content="" />
<meta property="og:site_name" content="FAILRAIL.sg" />
<meta property="fb:app_id" content="108496995971453" />

<title>Fines | FAILRAIL.sg</title>

<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"
	type="text/css">

<link rel="stylesheet" href="bootstrap/css/bootstrap-responsive.min.css"
	type="text/css">

<link rel="stylesheet" href="styles/screen.css" type="text/css">

				FAILRAIL.sg

Map

Dashboard

Overview

Major Disruptions

Rail Line

Line Fault

Length of Delay

Reports

Service Reliability

                                        Number Game

Train Faults
										Halved?

New Rail Lines

Fine Lines

Emergency Button Activations

Search

Calendar

Archive

Data

About

						Tweet

					Fine Lines a fine history of Singapore's metro

					Under the Licensing and Operating Agreement (LOA) between the Land
					Transport Authority (LTA) and the service operators, SMRT and SBS
					Transit are required to adhere to the Operating Performance
					Standards (OPS) for service quality, safety and maintenance. Most
					notably, the OPS determines the severity of service disruptions as
					delays affecting more than 20,000 persons per incident.

					Clause 10(2) of the LOA states that if the service operator fails
					to meet the OPS, it is liable to pay a penalty as imposed by LTA,
					up to a maximum of S$1 million. In calculating the penalty to be
					paid, LTA shall consider mitigating factors such as constraints of
					the relevant working network and infrastructure as well as
					passenger intervention, which are beyond the service operator's
					control (Committee of Inquiry report, p. 26, para. 78).

The service operators were fined for failing to meet the
					OPS: (in descending order of fine amount)

SMRT was fined a total of $2 million for two major disruptions on the
						North-South Line in December 2011, which affected 221,000
						commuters. This marks the first time that the maximum penalty of
						$1 million per incident was meted out to a service operator under
						the Rapid Transit Systems Act.

SMRT was fined $900,000 for a service disruption on the
                        East-West Line in January 2014 resulting from a failure to observe signal lights. A track point was damaged when the train passed a red signal light. The service disruption lasted more than an hour and affected                        10,500 commuters. Latest

SMRT was fined $400,000 for a service disruption on the
                        East-West Line in October 2013 resulting from a failure to observe signal lights. A track point was damaged when the train passed a red signal light. The service disruption lasted nearly an hour and affected 10,000 commuters. Latest

SBS Transit was fined $400,000 for a major disruption on the
						North-East Line in March 2012, which lasted 11 hours and affected
						117,000 commuters. This was SBS Transit's first fine since it
						started rail operations in 2003.

SMRT was fined $387,176 for a major disruption on the
						East-West Line in January 2008, which lasted 7 hours and affected
						57,000 commuters.

SMRT was fined $300,000 for an electrical
							fire that broke out near Newton station in February 2013, which
						resulted in a service disruption that lasted more than 2 hours
						and affected 17,700 commuters.

SBS Transit was fined $250,000 for a
							failed train push-out incident on the North East Line on 19 June 2013, which
						resulted in a service disruption that lasted more than 2 hours
						and affected 54,900 commuters. The incident occurred on one of the worst nights in the June haze, where
						the 3-hourly Pollutant Standards Index (PSI) hit 321 at 10pm.

SMRT was fined $250,000 for maintenance lapses following the discovery of two corroded sections
						of Circle Line tracks in November 2012.

SMRT was fined $250,000 for safety lapses exposing workers to the risk of electrocution
						while carrying out track works at Ulu Pandan depot in December 2012.

SMRT was fined $200,000 for a service disruption on the
                        North-South Line in January 2014. Investigations found lapses by an SMRT technician and train captain. As a result of these lapses, there was no auxiliary electrical supply to the affected train. The service disruption lasted 1.5 hours and affected 19,000 commuters. Latest

SMRT was fined $100,000 for a service disruption on the
                        North-South Line in May 2014. Traction power could not be turned on that morning because sleeper replacement workers had failed to remove a Short Circuiting Clamp that was installed. The service disruption lasted 50 minutes and affected 1,000 commuters. Latest

SMRT was fined $60,000 for a
							train launching incident that delayed Bukit Panjang LRT service for more than 2 hours in July 2013.

SBS Transit was fined $50,000 for a service disruption on the
                        North-East Line in March 2014. Non-critical maintenance works caused a short circuit that disrupted the traction power supply. The service disruption lasted 40 minutes and affected 5,900 commuters. Latest

In 2002, SMRT was fined $10,000 when the Bukit Panjang LRT failed to
						meet the 99.7 percent service availability standard.

In 2001, SMRT was fined $10,000 when the Bukit Panjang LRT service
						broke down six times in nine months.

SMRT was fined $10,000 for a train collision on the Bukit
						Panjang LRT in November 2000. 3 people were hurt and the power
						rail at Phoenix station was damaged. This was the first fine ever
						to be meted out to a service operator.

LTA is investigating
							the train breakdown on the North-East Line in August 2012. Almost 2 years later (as of July 2014), LTA still has not announced its final investigation results, or whether SBS Transit would be penalised for this incident.

Observations:

The big ones hit after 2010, they are getting bigger and
							so are the fines.

The $387,176 fine was record-breaking in 2008 as it was a
							much larger amount than the $10,000 fines in the past.
							Unfortunately, the stick was not big enough to deter SMRT from
							its profit-making binge. In fact, it was business as usual;
							SMRT's repair and maintenance cost per train-km remained fairly
							constant from 2003 to 2011 (Committee of Inquiry report, Ch.1-7,
								Figure 41).

green bubbles Why were the service operators not penalized for major
							disruptions affecting more than 20,000 commuters,
							as spelt out in the OPS? For example, the service disruption
							between Dhoby Ghaut and Harbourfront in July 2006 (North-East
							Line) and the service disruption between Marymount and Dhoby
							Ghaut in September 2011 (Circle Line). All major disruptions that have not been fined by LTA are
							indicated as $0 for the fine amount.

The public will be very surprised if LTA does not levy a
							fine for the service disruption on the North-East Line in August 2012 (green bubble
							on the top right). Although it was an exceptionally long delay,
							SBS Transit did not disclose the number of commuters affected.
							Investigations are ongoing.


text:
@class TLInputPrivacyKey;
@class TLaccount_PrivacyRules;

@interface TLRPCaccount_setPrivacy : TLMetaRpc

@property (nonatomic, retain) TLInputPrivacyKey *key;
@property (nonatomic, retain) NSArray *rules;

- (Class)responseClass;

- (int)impliedResponseSignature;

@end

@interface TLRPCaccount_setPrivacy$account_setPrivacy : TLRPCaccount_setPrivacy

@end


text:
using Zergatul.Cryptocurrency.Base;

namespace Zergatul.Cryptocurrency.Verge
{
    public class VergeFactory : BlockchainCryptoFactory
    {
        public override ulong Multiplier => 1000000;

        public override BlockBase GetBlock() => null;
        public override TransactionBase GetTransaction() => new Transaction();
        public override P2PKHAddressBase GetP2PKHAddress() => new P2PKHAddress();
        public override P2SHAddressBase GetP2SHAddress() => new P2SHAddress();
    }
}


text:
<?php
use yupe\components\Event;

class UserActivateEvent extends Event
{
    protected $token;

    protected $user;

    /**
     * @param mixed $token
     */
    public function setToken($token)
    {
        $this->token = $token;
    }

    /**
     * @param mixed $user
     */
    public function setUser($user)
    {
        $this->user = $user;
    }

    /**
     * @return mixed
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    public function __construct($token,  User $user = null)
    {
        $this->token = $token;

        $this->user = $user;
    }
}