text:
<?php

/**
 * The ezcArchiveBlockFile class provides an interface for reading from and writing to a block file.
 *
 * A block file is a file that consist of zero or more blocks. Each block has a predefined amount
 * of bytes known as the block-size. The block file implements the Iterator interface. Via the methods
 *
 * - key()
 * - valid()
 * - current()
 * - rewind()
 *
 * can single blocks be accessed. The append(), appendToCurrent() method, appends and possibly removes
 * blocks from and to the file.
 *
 * The block-file takes the necessary measurements to read and write to a compressed stream.
 *
 * The following example stores 16 bytes in 4 blocks. The current() points to the second block: 1.
 * <code>
 *  ---- ---- ---- ----
 * |0 1 | 5 6| 9 0| 3 4|
 * |2 4 | 7 8| 1 2| 5 6|
 *  ---- ---- ---- ----
 *   0    1    2    3
 *
 *        ^         ^
 *        |         \ LastBlock
 *
 *     Current
 * </code>
 *
 *
 * @package Archive
 * @version 1.4.1
 * @access private
 */
class ezcArchiveBlockFile extends ezcArchiveFile
{
    /**
     * The block size.
     *
     * @var int
     */
    private $blockSize;

    /**
     * The current number of the block.
     *
     * The first block starts with zero.
     *
     * @var int
     */
    private $blockNumber = -1;

    /**
     * The current block data.
     *
     * @var string
     */
    private $blockData;

    /**
     * Holds the last block number.
     *
     * @var int
     */
    private $lastBlock = -1;

    /**
     * Sets the property $name to $value.
     *
     * Because there are no properties available, this method will always
     * throw an {@link ezcBasePropertyNotFoundException}.
     *
     * @throws ezcBasePropertyNotFoundException if the property does not exist.
     * @param string $name
     * @param mixed $value
     * @return void
     * @ignore
     */
    public function __set( $name, $value )
    {
        throw new ezcBasePropertyNotFoundException( $name );
    }

    /**
     * Returns the property $name.
     *
     * Available read-only property: blockSize
     *
     * @throws ezcBasePropertyNotFoundException if the property does not exist.
     * @param string $name
     * @return mixed
     * @ignore
     */
    public function __get( $name )
    {
        switch ( $name )
        {
            case "blockSize":
                return $this->blockSize;
        }

        throw new ezcBasePropertyNotFoundException( $name );
    }

    /**
     * Constructs a new ezcArchiveBlockFile.
     *
     * The given file name is tried to be opened in read / write mode. If that fails, the file will be opened
     * in read-only mode.
     *
     * If the bool $createIfNotExist is set to true, it will create the file if it doesn't exist.
     *
     * @throws ezcBaseFileNotFoundException if the file cannot be found.
     * @throws ezcBaseFilePermissionException if the file permissions are wrong.
     *
     * @param string $fileName
     * @param bool $createIfNotExist
     * @param int $blockSize
     * @param bool $readOnly
     */
    public function __construct( $fileName, $createIfNotExist = false, $blockSize = 512, $readOnly = false )
    {
        $this->blockSize = $blockSize;

        $this->openFile( $fileName, $createIfNotExist, $readOnly );
    }

    /**
     * The destructor will close all open files.
     */
    public function __destruct()
    {
        if ( $this->fp )
        {
            fclose( $this->fp );
        }
    }

    /**
     * Rewind the current file.
     *
     * @return void
     */
    public function rewind()
    {
        $this->blockNumber = -1;

        parent::rewind();
    }

    /**
     * Return the data from the current block if the block is valid.
     *
     * If the block is not valid, the value false is returned.
     *
     * @return string
     */
    public function current()
    {
        return ( $this->isValid ? $this->blockData : false );
    }

    /**
     * Iterate to the next block.
     *
     * Returns the data of the next block if it exists; otherwise returns false.
     *
     * @return string
     */
    public function next()
    {
        if ( $this->isValid  )
        {
            // XXX move the calc to readmode?
            // $this->switchReadMode( ( $this->blockNumber + 1 ) * $this->blockSize );

            // Read one block.
            $this->blockData = fread( $this->fp, $this->blockSize );

            if ( strlen( $this->blockData ) < $this->blockSize )
            {
                if ( $this->lastBlock != -1 )
                {
                    if ( $this->blockNumber != $this->lastBlock )
                    {
                        throw new ezcArchiveInternalException( "Something weird happened with the blockNumber. Lastblock number registered at " . $this->lastBlock . " but changed into " . $this->blockNumber );
                    }
                }
                $this->lastBlock = $this->blockNumber;
                $this->isValid = false;
                return false;
            }
            $this->blockNumber++;

            return $this->blockData;
        }

        return false;
    }

    /**
     * Returns the key, the current block number of the current element.
     *
     * The first block has the number zero.
     *
     * @return int
     */
    public function key()
    {
        return ( $this->isValid ? $this->blockNumber : false );
    }

    /**
     * Returns true if the current block is valid, otherwise false.
     *
     * @return bool
     */
    public function valid()
    {
        return $this->isValid;
    }

    /**
     * Returns true if the current block is a null block, otherwise false.
     *
     * A null block is a block consisting of only NUL characters.
     * If the current block is invalid, this method will return false.
     *
     * @return bool
     */
    public function isNullBlock()
    {
        if ( $this->isValid )
        {
            for ( $i = 0; $i < $this->blockSize; $i++ )
            {
                if ( ord( $this->blockData[$i] ) != 0 )
                {
                    return false;
                }
            }
            return true;
        }

        return false;
    }

    /**
     * Appends with truncate.
     */
    private function appendTruncate()
    {
        if ( $this->fileAccess == self::READ_ONLY )
        {
            throw new ezcBaseFilePermissionException( $this->fileName, ezcBaseFilePermissionException::WRITE, "The archive is opened in a read-only mode." );
        }

        if ( !$this->isEmpty && $this->isValid )
        {
            $needToTruncate = true;
            $currentBlock = $this->blockNumber;
            // Do we need to truncate the file?

            // Check if we already read the entire file. This way is quicker to check.
            if ( $this->lastBlock != -1 )
            {
                // Last block is known.
                if ( $this->lastBlock == $this->blockNumber )
                {
                    // We are at the last block.
                    $needToTruncate = false;
                }
            }
            else
            {
                // The slower method. Check if we can read the next block.
                if ( !$this->next() )
                {
                    // We got a next block.
                    $needToTruncate = false;
                }
            }

            if ( $needToTruncate )
            {
                if ( $this->fileAccess == self::READ_APPEND )
                {
                    // Sorry, don't know how to truncate this file (except copying everything).
                    throw new ezcArchiveException( "Cannot truncate the file" );
                }

                if ( $this->blockNumber < $this->lastBlock )
                {
                    throw new ezcArchiveInternalException( "Expected to be at the last block." );
                }
                $pos = $currentBlock * $this->blockSize;
                ftruncate( $this->fp, $pos );

                $this->lastBlock = $currentBlock;
                $this->blockNumber = $currentBlock;
            }
        }
        else
        {
            if ( !$this->isEmpty && !$this->isValid )
            {
                throw new ezcArchiveInternalException( "Not at a valid block position to append" );
            }
        }
    }

    /**
     * Appends the string $data after the current block.
     *
     * The blocks after the current block are removed and the $data will be
     * appended. The data will always be appended after the current block.
     * To replace the data from the first block, the truncate() method should
     * be called first.
     *
     * Multiple blocks will be written when the length of the $data exceeds
     * the block size. If the data doesn't fill an entire block, the rest
     * of the block will be filled with NUL characters.
     *
     * @param   string  $data  Data that should be appended.
     * @return int        The total amount of blocks added.
     *
     * @throws  ezcBaseFilePermissionException when the file is opened in read-only mode.
     */
    public function append( $data )
    {
        $this->appendTruncate();

        // We are at the end of the file. Let's append the data.
        // Switch write mode, if needed.
        $this->switchWriteMode();

        $dataLength = sizeof( $data );
        $length = $this->writeBytes( $data );

        if ( ( $mod = ( $length % $this->blockSize ) ) > 0 )
        {
            $this->writeBytes( pack( "a". ( $this->blockSize  - $mod ), "" ) );
        }

        $addedBlocks = ( (int) (($length - 1) / $this->blockSize ) ) + 1;

        // Added the blocks.
        $this->isModified = true;
        $this->isEmpty = false;

        $this->blockNumber += $addedBlocks;
        $this->lastBlock += $addedBlocks;
        $this->blockData = $data;
        $this->isValid = true;

        $this->switchReadMode();

        return $addedBlocks;
    }

    /**
     * Appends the data from the given file $fileName to the current block file.
     *
     * The blocks after the current block are removed and the data will be
     * appended. The data will always be appended after the current block.
     * To replace the data from the first block, the truncate() method should
     * be called first.
     *
     * Multiple blocks will be written when the length of the data exceeds
     * the block size. If the data doesn't fill an entire block, the rest
     * of the block will be filled with NUL characters.
     *
     * @param   string  $fileName  The filename that contains the data.
     * @return int                 The total amount of blocks added.
     *
     * @throws  ezcBaseFilePermissionException when the file is opened in read-only mode.
     */
    public function appendFile( $fileName )
    {
        $this->appendTruncate();

        $this->switchWriteMode();

        $localFile = @fopen( $fileName, "rb" );
        if ( !$localFile )
        {
            throw new ezcArchiveException( "Cannot open the file '{$fileName}' for reading." );
        }

        $addedBlocks = 0;
        $length = 0;
        while ( !feof( $localFile ) && ( $data = fread( $localFile, $this->blockSize ) ) !== false )
        {
            $addedBlocks++;
            $length = $this->writeBytes( $data );
        }

        if ( ( $mod = ( $length % $this->blockSize ) ) > 0 )
        {
            $this->writeBytes( pack( "a". ( $this->blockSize  - $mod ), "" ) );
        }

        fclose( $localFile );

        // Added the blocks.
        $this->isModified = true;
        $this->isEmpty = false;

        $this->blockNumber += $addedBlocks;
        $this->lastBlock += $addedBlocks;
        $this->blockData = $data;
        $this->isValid = true;

        $this->switchReadMode();

        return $addedBlocks;
    }

    /**
     * Write the given string $data to the current file.
     *
     * This method tries to write the $data to the file. Upon failure, this method
     * will retry, until no progress is made anymore. And eventually it will throw
     * an exception. Sometimes an (invalid) interrupt may stop the writing process.
     *
     * @throws ezcBaseFileIoException if it is not possible to write to the file.
     *
     * @param string $data
     * @return void
     */
    protected function writeBytes( $data )
    {
        $dl = strlen( $data );
        if ( $dl == 0 )
        {
            return; // No bytes to write.
        }

        $wl = fwrite( $this->fp, $data );

        // Partly written? For example an interrupt can occur when writing a remote file.
        while ( $dl > $wl && $wl != 0 )
        {
            // retry, until no progress is made.
            $data = substr( $data, $wl );

            $dl = strlen( $data );
            $wl = fwrite( $this->fp, $data );
        }

        if ( $wl == 0 )
        {
            throw new ezcBaseFileIoException ( $this->fileName, ezcBaseFileIoException::WRITE, "Retried to write, but no progress was made. Disk full?" );
        }

        return $wl;
    }

    /**
     * Appends one block with only NUL characters to the file.
     *
     * @throws ezcBaseFilePermissionException if the file is opened in read-only mode.
     * @apichange Rename to appendNullBlocks
     *
     * @param int $amount
     * @return void
     */
    public function appendNullBlock( $amount = 1 )
    {
        $this->append( pack( "a". ( $amount * $this->blockSize ), "" ) );
    }

    /**
     * Truncate the current block file to $block blocks.
     *
     * If $blocks is zero, the entire block file will be truncated. After the file is truncated,
     * make sure the current block position is valid. So, do a rewind() after
     * truncating the entire block file.
     *
     * @param int $blocks
     * @return void
     */
    public function truncate( $blocks = 0 )
    {
        // Empty files don't need to be truncated.
        if ( $this->isEmpty() )
        {
            return true;
        }

        if ( $this->fileAccess !== self::READ_APPEND )
        {
            // We can read-write in the file. Easy.
            $pos = $blocks * $this->blockSize;
            ftruncate( $this->fp, $pos );
            $this->isModified = true;
            if ( $pos == 0 )
            {
                $this->isEmpty = true;
            }

            if ( $this->blockNumber >= $blocks )
            {
                $this->isValid = false;
            }

            $this->lastBlock = $blocks - 1;

            return true;
        }

        // Truncate at the end?
        if ( !$this->isValid )
        {
            $this->rewind();
        }

        while ( $this->isValid && $blocks > $this->blockNumber )
        {
            $this->next();
        }

        if ( $this->isValid )
        {
            throw new ezcArchiveInternalException( "Failed to truncate the file" );
        }

        return true;
    }

    /**
     * Sets the current block position.
     *
     * The new position is obtained by adding the $blockOffset amount of blocks to
     * the position specified by $whence.
     *
     * These values are:
     *  SEEK_SET: The first block,
     *  SEEK_CUR: The current block position,
     *  SEEK_END: The last block.
     *
     * The blockOffset can be negative.
     *
     * @param int $blockOffset
     * @param int $whence
     * @return void
     */
    public function seek( $blockOffset, $whence = SEEK_SET )
    {
        if ( $this->fileAccess == self::WRITE_ONLY && $blockOffset == 0 && $whence == SEEK_END )
        {
            return true;
        }

        if ( ftell( $this->fp ) === false || $this->fileAccess == self::READ_APPEND )
        {
            // Okay, cannot tell the current file position.
            // This happens with some compression streams.

            if ( !$this->isValid )
            {
                if ( $whence == SEEK_CUR )
                {
                    throw new ezcArchiveException( "Cannot seek SEEK_CUR with an invalid block position" );
                }

                $this->rewind();
            }

            if ( $whence == SEEK_END && $this->lastBlock == -1 )
            {
                // Go to the end.
                while ( $this->next() );
            }

            switch ( $whence )
            {
                case SEEK_CUR:
                    $searchBlock = $this->blockNumber += $blockOffset;
                    break;

                case SEEK_END:
                    $searchBlock = $this->lastBlock += $blockOffset;
                    break;

                case SEEK_SET:
                    $searchBlock = $blockOffset;
                    break;
            }

            if ( $searchBlock < $this->blockNumber )
            {
                $this->rewind();
            }

            while ( $this->isValid && $this->blockNumber < $searchBlock )
            {
                $this->next();
            }

            return ( $this->blockNumber == $searchBlock );
        }
        else
        {
            $this->isValid = true;

            $pos = $this->blockSize * $blockOffset;
            if ( $whence == SEEK_END || $whence == SEEK_CUR )
            {
                if ( !$this->isEmpty() )
                {
                    $pos -= $this->blockSize;
                }
            }

            if ( !( $whence == SEEK_SET && $pos == ftell( $this->fp ) ) )
            {
                $this->positionSeek( $pos, $whence );
            }

            if ( ftell( $this->fp ) === false )
            {
                throw new ezcArchiveException( "Cannot tell the current position, but this is after the position seek. " );
            }

            $this->blockNumber = $this->getBlocksFromBytes( ftell( $this->fp ) ) - 1;
            $this->next(); // Will set isValid to false, if blockfile is empty.
        }
    }

    /**
     * Calculates the blocks for the given $bytes.
     *
     * @param  int $bytes
     * @return int
     */
    public function getBlocksFromBytes( $bytes )
    {
        return (int) ceil ($bytes  / $this->blockSize );
    }

    /**
     * Returns true if the blockfile is empty, otherwise false.
     *
     * @return bool
     */
    public function isEmpty()
    {
        return $this->isEmpty;
    }

    /**
     * Returns the last block number.
     *
     * @return int
     */
    public function getLastBlockNumber()
    {
        return $this->lastBlock;
    }
}
?>


text:
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.cometd;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;

/**
 * Generated by camel build tools - do NOT edit this file!
 */
@SuppressWarnings("unchecked")
public class CometdComponentConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {

    @Override
    public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
        CometdComponent target = (CometdComponent) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "autowiredenabled":
        case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
        case "bridgeerrorhandler":
        case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
        case "extensions": target.setExtensions(property(camelContext, java.util.List.class, value)); return true;
        case "lazystartproducer":
        case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
        case "securitypolicy":
        case "securityPolicy": target.setSecurityPolicy(property(camelContext, org.cometd.bayeux.server.SecurityPolicy.class, value)); return true;
        case "sslcontextparameters":
        case "sslContextParameters": target.setSslContextParameters(property(camelContext, org.apache.camel.support.jsse.SSLContextParameters.class, value)); return true;
        case "sslkeypassword":
        case "sslKeyPassword": target.setSslKeyPassword(property(camelContext, java.lang.String.class, value)); return true;
        case "sslkeystore":
        case "sslKeystore": target.setSslKeystore(property(camelContext, java.lang.String.class, value)); return true;
        case "sslpassword":
        case "sslPassword": target.setSslPassword(property(camelContext, java.lang.String.class, value)); return true;
        case "useglobalsslcontextparameters":
        case "useGlobalSslContextParameters": target.setUseGlobalSslContextParameters(property(camelContext, boolean.class, value)); return true;
        default: return false;
        }
    }

    @Override
    public Class<?> getOptionType(String name, boolean ignoreCase) {
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "autowiredenabled":
        case "autowiredEnabled": return boolean.class;
        case "bridgeerrorhandler":
        case "bridgeErrorHandler": return boolean.class;
        case "extensions": return java.util.List.class;
        case "lazystartproducer":
        case "lazyStartProducer": return boolean.class;
        case "securitypolicy":
        case "securityPolicy": return org.cometd.bayeux.server.SecurityPolicy.class;
        case "sslcontextparameters":
        case "sslContextParameters": return org.apache.camel.support.jsse.SSLContextParameters.class;
        case "sslkeypassword":
        case "sslKeyPassword": return java.lang.String.class;
        case "sslkeystore":
        case "sslKeystore": return java.lang.String.class;
        case "sslpassword":
        case "sslPassword": return java.lang.String.class;
        case "useglobalsslcontextparameters":
        case "useGlobalSslContextParameters": return boolean.class;
        default: return null;
        }
    }

    @Override
    public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
        CometdComponent target = (CometdComponent) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "autowiredenabled":
        case "autowiredEnabled": return target.isAutowiredEnabled();
        case "bridgeerrorhandler":
        case "bridgeErrorHandler": return target.isBridgeErrorHandler();
        case "extensions": return target.getExtensions();
        case "lazystartproducer":
        case "lazyStartProducer": return target.isLazyStartProducer();
        case "securitypolicy":
        case "securityPolicy": return target.getSecurityPolicy();
        case "sslcontextparameters":
        case "sslContextParameters": return target.getSslContextParameters();
        case "sslkeypassword":
        case "sslKeyPassword": return target.getSslKeyPassword();
        case "sslkeystore":
        case "sslKeystore": return target.getSslKeystore();
        case "sslpassword":
        case "sslPassword": return target.getSslPassword();
        case "useglobalsslcontextparameters":
        case "useGlobalSslContextParameters": return target.isUseGlobalSslContextParameters();
        default: return null;
        }
    }

    @Override
    public Object getCollectionValueType(Object target, String name, boolean ignoreCase) {
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "extensions": return org.cometd.bayeux.server.BayeuxServer.Extension.class;
        default: return null;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.bruneli.scalaopt.core.discrete

import com.github.bruneli.scalaopt.core.constraint.{CP, Constraint}
import com.github.bruneli.scalaopt.core.function.ObjectiveFunction
import com.github.bruneli.scalaopt.core.linalg.DenseVectorLike
import com.github.bruneli.scalaopt.core.variable.{ContinuousVariable, DiscreteVariable, Variable, Variables}

/**
  * Mixed Integer Program
  *
  * @tparam A objective function type
  * @tparam B constraint type
  * @tparam R relaxation program type
  * @author bruneli
  */
trait MIP[A <: ObjectiveFunction[Variable],
          B <: Constraint[Variable],
          R <: CP[ContinuousVariable, _, _]] extends CP[Variable, A, B] {
  self =>

  val matchingPrecision: Double

  lazy val discreteVariableIndices = getDiscreteVariableIndices()

  def variables: Variables[Variable]

  def relaxationProgram: R

  def adaptVariablesTo(solution: DenseVectorLike[Variable]): Variables[Variable] = {
    variables.mapWithIndex((x, i) => solution.coordinate(i))
  }

  def acceptsAsFeasibleSolution(solution: DenseVectorLike[ContinuousVariable]): Boolean = {
    discreteVariableIndices.forall(
      i => isDiscrete(solution(i), variables(i).asInstanceOf[DiscreteVariable]))
  }

  private def isDiscrete(candidate: Variable,
                         variable: DiscreteVariable): Boolean = {
    val dxLow = variable.floor(candidate).map(candidate.x - _.x)
    val dxHigh = variable.ceil(candidate).map(_.x - candidate.x)
    dxLow.exists(_ < matchingPrecision) || dxHigh.exists(_ < matchingPrecision)
  }

  private def getDiscreteVariableIndices(): Seq[Int] = {
    for {(variable, index) <- variables.zipWithIndex
         if variable.isInstanceOf[DiscreteVariable]} yield {
      index
    }
  }

}


text:
using Bridge.Contract;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.TypeSystem;

namespace Bridge.Translator
{
    public class TypeBlock : AbstractEmitterBlock
    {
        public TypeBlock(IEmitter emitter, AstType type)
        {
            this.Emitter = emitter;
            this.Type = type;
        }

        public AstType Type
        {
            get;
            set;
        }

        public override void Emit()
        {
            this.EmitTypeReference();
        }

        protected virtual void EmitTypeReference()
        {
            AstType astType = this.Type;
            this.Write(Helpers.TranslateTypeReference(astType, this.Emitter));
        }

        public static string GetTypeName(IType type, IEmitter emitter)
        {
            if (type.Kind == TypeKind.Array)
            {
                return "Array";
            }

            if (type.Kind == TypeKind.Dynamic)
            {
                return "Object";
            }

            return emitter.ShortenTypeName(Helpers.GetScriptFullName(type));
        }
    }
}


text:
from base import (
    FirstSupported,
    MethodMask,
    Planner,
    PlanningError,
    Ranked,
    Sequence,
    UnsupportedPlanningError,
)
from chomp import CHOMPPlanner
from cbirrt import CBiRRTPlanner
from ompl import OMPLPlanner
from mk import MKPlanner
from snap import SnapPlanner
from named import NamedPlanner
from ik import IKPlanner
from sbpl import SBPLPlanner
from openrave import BiRRTPlanner
from tsrplanner import TSRPlanner
from workspace import GreedyIKPlanner
from vectorfield import VectorFieldPlanner


text:
import * as types from '../constants/actionTypes';
import * as keys from '../constants/storageKeys';
import * as actions from '../actions/cartActions';
import jsonLocalStorage from '../util/jsonLocalStorage';

// NOTE: we can pass in a mock storage object here to unit test
export default function manageCartMiddleware(storage = jsonLocalStorage) {
  return (store) => {
    return (next) => (action) => {

      switch (action.type) {
        case types.ADD_TO_CART: {
          const cart = storage.getItem(keys.CART) || [];
          const cartEntry = cart.filter(({id}) => id === action.id);
          if (cartEntry.length) {
            storage.setItem(keys.CART, [...cart.filter(({id}) => id !== action.id), { id: action.id, count: cartEntry[0].count + 1 }]);
          } else {
            storage.setItem(keys.CART, [...cart, { id: action.id, count: 1 }]);
          }
          return next(action);
        }
        case types.REMOVE_FROM_CART: {
          const cart = storage.getItem(keys.CART);
          const cartEntry = cart.filter(({id}) => id === action.id);
          if (cartEntry.length && cartEntry[0].count === 1) {
            const newCart = cart.filter(({id}) => id !== action.id);
            storage.setItem(keys.CART, newCart);
            store.dispatch(actions.getCartItems(newCart.map(c => c.id))); // refresh the cart product info
          } else {
            storage.setItem(keys.CART, [...cart.filter(({id}) => id !== action.id), { id: action.id, count: cartEntry[0].count - 1 }]);
          }
          return next(action);
        }
        case types.INIT_CART: {
          const cart = storage.getItem(keys.CART) || [];
          store.dispatch({ type: types.FILL_CART, cart });
          return next(action);
        }
        default:
          return next(action);
      }
    };
  };
}


text:
import scrapy
import json
import sys
from scrapy.selector import Selector
from HuaweiAppStore.items import HuaweiAppStoreItem

class HuaweiAppStoreTrendingSpider(scrapy.Spider):
    """
    Scrape information of trending app in Huawei Application Store
    Information includes: title, appid, icon url, description

    Since link to next page is dynamically loaded by javascript, which is
    nontrivial to get, we traverse all number in trending link from 1 to ...
    Also, Huawei AppStore would give response even when requesting a page
    whose number is after last page. Eg. currently last page is 41, when we
    request for page 42, it won't return 404. Rather, it would return page
    with empty list. So we check whether list is empty or not to determine
    termination of scraping.
    """

    name = "huawei_appstore_trending"
    allowed_domains = ["huawei.com"]
    start_urls = ["http://appstore.huawei.com/more/all/40"]
    pipelines = ["HuaweiappstoreDuplicatePipeline",\
            "HuaweiappstoreTrendingPipeline"]

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, self.parse, meta={\
                    'splash': {\
                    'endpoint': 'render.html',\
                    'args': {'wait': 0.5}\
                }\
            })

    def parse(self, response):
        #First, scrape all apps' info in this page
        for app in Selector(response)\
                .xpath("//div[contains(@class, 'list-game-app')]"):
            game_info = app.xpath("div[@class='game-info  whole']")

            item = HuaweiAppStoreItem()
            item['image'] = app.xpath("./div[@class='game-info-ico']/a\
                    /img/@src").extract()[0]
            item['title'] = game_info.xpath("./h4[@class='title']/a\
                    /text()").extract()[0].encode("utf-8")
            item['appid'] = game_info.xpath("./h4[@class='title']/a/@href")\
                    .re('http://appstore.huawei.com:80/app/(C\d+)')[0]
            item['desc'] = u''.join(game_info.xpath("./div[@class='game-info-dtail part']\
                    /p[@class='content']/text()").extract()).encode("utf-8")
            yield item

        #Then, try to find next page, if exist
        next_page = Selector(response).xpath("//div[@class='page-ctrl ctrl-app']/a").extract()
        #If could not find this div, splash must be wrong
        if len(next_page) == 0:
            print "Javascript could not fetch! Please make sure splash is running and setting is corrent!"
            sys.exit(1)
        if len(next_page) >= 2 and next_page[-2].find("下一页".decode("utf-8")) != -1:
            next_url = Selector(response)\
                    .xpath("//div[@class='page-ctrl ctrl-app']/a[last()-1]/@href")\
                    .extract_first()
            yield scrapy.Request(next_url, self.parse, meta={\
                'splash': {\
                    'endpoint': 'render.html',\
                    'args': {'wait': 0.5}\
                }\
            })


text:
class InstrumentAlertsController < ApplicationController

  admin_tab :all
  layout "two_column"

  before_action :authenticate_user!
  before_action :check_acting_as
  before_action :load_instrument

  def new
    @instrument_alert = @instrument.build_alert
  end

  def create
    @instrument_alert = @instrument.build_alert(instrument_alert_params)

    if @instrument_alert.save
      redirect_to facility_instrument_schedule_path(current_facility, @instrument), notice: text("created")
    else
      render action: "new"
    end
  end

  def destroy
    @instrument.alert.destroy
    redirect_to facility_instrument_schedule_path(current_facility, @instrument), notice: text("destroyed")
  end

  private

  def load_instrument
    @instrument = current_facility.instruments.find_by!(url_name: params[:instrument_id])
  end

  def instrument_alert_params
    params.require(:instrument_alert).permit(:note)
  end

end


text:
#include "include/Importers/NifNodeImporterFallout4.h"
#include <queue>
#include <obj/BSSubIndexTriShape.h>
#include <obj/BSSkin__Instance.h>

bool NifNodeImporterFallout4::isUsedInBoneData(NiNodeRef target_node)
{
	if (this->translatorData->importedSceneRoot != NULL)
	{
		queue<NiAVObjectRef> nodes_to_scan;
		NiAVObjectRef initial_root = DynamicCast<NiAVObject>(this->translatorData->importedSceneRoot);
		nodes_to_scan.push(initial_root);

		while (!nodes_to_scan.empty())
		{
			NiAVObjectRef av_object = nodes_to_scan.front();
			nodes_to_scan.pop();

			BSShapeRef bs_shape = DynamicCast<BSShape>(av_object);

			if (bs_shape != NULL)
			{
				if (bs_shape->IsSkin())
				{
					if (bs_shape->IsSameType(BSSubIndexTriShape::TYPE))
					{
						BSSubIndexTriShapeRef bs_sub_index_tri_shape = DynamicCast<BSSubIndexTriShape>(bs_shape);
						BSSkin__InstanceRef skinInst = DynamicCast<BSSkin__Instance>(bs_sub_index_tri_shape->GetSkin());
						vector<Ref<NiNode>> bones = skinInst->GetBones();

						for (int bone_index = 0; bone_index < bones.size(); bone_index++)
						{
							if (bones[bone_index] == target_node)
							{
								return true;
							}
						}
					}

					if (bs_shape->IsSameType(BSTriShape::TYPE))
					{
						BSTriShapeRef bs_tri_shape = DynamicCast<BSTriShape>(bs_shape);
						BSSkin__InstanceRef skinInst = DynamicCast<BSSkin__Instance>(bs_tri_shape->GetSkin());
						vector<Ref<NiNode>> bones = skinInst->GetBones();

						for (int bone_index = 0; bone_index < bones.size(); bone_index++)
						{
							if (bones[bone_index] == target_node)
							{
								return true;
							}
						}
					}
				}
			}

			NiNodeRef node = DynamicCast<NiNode>(av_object);

			if (node != NULL)
			{
				vector<Ref<NiAVObject>> ni_av_objects = node->GetChildren();

				for (int child_index = 0; child_index < ni_av_objects.size(); child_index++)
				{
					nodes_to_scan.push(ni_av_objects[child_index]);
				}
			}
		}
	}

	return false;
}

void NifNodeImporterFallout4::ImportNodes(NiAVObjectRef niAVObj, map<NiAVObjectRef, MDagPath>& objs, MObject parent)
{
	MObject obj;

	//out << "Importing " << niAVObj << endl;

	////Stop at a non-node
	//if ( node == NULL )
	//	return;

	//Check if this node is a skinned NiTriBasedGeom.  If so, parent it to the scene instead
	//of whereever the NIF file has it.

	bool is_skin = false;

	vector<NiAVObjectRef> nodesToTest;

	if (niAVObj->IsDerivedType(NiNode::TYPE))
	{
		NiNodeRef nnr = DynamicCast<NiNode>(niAVObj);
		if (nnr->IsSplitMeshProxy())
		{
			//Test all children
			nodesToTest = nnr->GetChildren();
		}
	}
	else if (niAVObj->IsDerivedType(BSShape::TYPE))
	{
		//This is a shape, so test it.
		nodesToTest.push_back(niAVObj);
	}

	for (size_t i = 0; i < nodesToTest.size(); ++i)
	{
		BSShapeRef bs_shape = DynamicCast<BSShape>(nodesToTest[i]);
		if (bs_shape && bs_shape->IsSkin())
		{
			is_skin = true;
			break;
		}
	}

	if (is_skin)
	{
		parent = MObject::kNullObj;
	}

	//This must be a node, so process its basic attributes
	MFnTransform transFn;
	MString name = this->translatorUtils->MakeMayaName(niAVObj->GetName());
	string strName = name.asChar();

	int flags = niAVObj->GetFlags();

	NiNodeRef niNode = DynamicCast<NiNode>(niAVObj);

	//Determine whether this node is an IK joint
	bool is_joint = false;
	if (niNode != NULL)
	{
		if (this->translatorOptions->jointMatch != "" && strName.find(this->translatorOptions->jointMatch) != string::npos)
		{
			is_joint = true;
		}
		else if (this->isUsedInBoneData(niNode))
		{
			is_joint = true;
		}

		if (this->translatorOptions->importAllNodesAsJoints == true) {
			is_joint = true;
		}
	}

	//Check if the user wants us to try to combine new skins with an
	//existing skeleton
	if (this->translatorOptions->importCombineSkeletons)
	{
		//Check if joint already exits in scene.  If so, use it.
		if (is_joint)
		{
			obj = this->translatorUtils->GetExistingJoint(name.asChar());
		}
	}

	if (obj.isNull() == false)
	{
		//A matching object was found
		transFn.setObject(obj);
	}
	else
	{
		if (is_joint)
		{
			// This is a bone, create an IK joint parented to the given parent
			MFnIkJoint IKjointFn;
			obj = IKjointFn.create(parent);

			//Set Transform Fn to work on the new IK joint
			transFn.setObject(obj);
		}
		else
		{
			//Not a bone, create a transform node parented to the given parent
			obj = transFn.create(parent);
		}

		//--Set the Transform Matrix--//
		Matrix44 transform;

		if (is_skin)
		{
			transform = niAVObj->GetWorldTransform();
		}
		else
		{
			transform = niAVObj->GetLocalTransform();
		}

		//put matrix into a float array
		float trans_arr[4][4];
		transform.AsFloatArr(trans_arr);

		transFn.set(MTransformationMatrix(MMatrix(trans_arr)));
		transFn.setRotationOrder(MTransformationMatrix::kXYZ, false);

		//Set name
		MFnDependencyNode dnFn;
		dnFn.setObject(obj);
		dnFn.setName(name);
	}

	//Add the newly created object to the objects list
	MDagPath path;
	transFn.getPath(path);
	objs[niAVObj] = path;

	//Check if this object has a bounding box
	if (niAVObj->HasBoundingBox())
	{
		//Get bounding box info
		BoundingBox bb = niAVObj->GetBoundingBox();

		//Create a transform node to move the bounding box around
		MFnTransform tranFn;
		tranFn.create(obj);
		tranFn.setName("BoundingBox");
		Matrix44 bbTrans(bb.translation, bb.rotation, 1.0f);
		//out << "bbTrans:" << endl << bbTrans << endl;
		//out << "Translation:  " << bb.translation << endl;
		//out << "Rotation:  " << bb.rotation << endl;

		//put matrix into a float array
		float bb_arr[4][4];
		bbTrans.AsFloatArr(bb_arr);
		MStatus stat = tranFn.set(MTransformationMatrix(MMatrix(bb_arr)));
		if (stat != MS::kSuccess)
		{
			//out << stat.errorString().asChar() << endl;
			throw runtime_error("Failed to set bounding box transforms.");
		}
		tranFn.setRotationOrder(MTransformationMatrix::kXYZ, false);

		//Create an implicit box parented to the node we just created
		MFnDagNode dagFn;
		dagFn.create("implicitBox", tranFn.object());
		dagFn.findPlug("sizeX").setValue(bb.radius.x);
		dagFn.findPlug("sizeY").setValue(bb.radius.y);
		dagFn.findPlug("sizeZ").setValue(bb.radius.z);
	}

	//Check to see if this is a mesh
	if (niAVObj->IsDerivedType(BSShape::TYPE))
	{
		//This is a mesh, so add it to the mesh list
		this->translatorData->importedMeshes.push_back(pair<NiAVObjectRef, MObject>(niAVObj, obj));
	}

	if (niNode != NULL)
	{
		//Check to see if this is a mesh proxy
		if (niNode->IsSplitBSMeshProxy())
		{
			//out << niNode << " is a split mesh proxy." << endl;
			//Since this is a mesh proxy, treat it like a mesh and do not
			//call this function on any children
			this->translatorData->importedMeshes.push_back(pair<NiAVObjectRef, MObject>(niAVObj, obj));
		}
		else
		{
			//Call this function for any children
			vector<NiAVObjectRef> children = niNode->GetChildren();
			for (unsigned int i = 0; i < children.size(); ++i)
			{
				this->ImportNodes(children[i], objs, obj);
			}
		}
	}
}

NifNodeImporterFallout4::~NifNodeImporterFallout4()
{
}

NifNodeImporterFallout4::NifNodeImporterFallout4()
{
}

NifNodeImporterFallout4::NifNodeImporterFallout4(NifTranslatorOptionsRef translatorOptions, NifTranslatorDataRef translatorData, NifTranslatorUtilsRef translatorUtils) : NifNodeImporter(translatorOptions, translatorData, translatorUtils)
{
}

std::string NifNodeImporterFallout4::asString(bool verbose /*= false */) const
{
	stringstream out;

	out << NifNodeImporter::asString(verbose);
	out << "NifNodeImporterFallout4" << endl;

	return out.str();
}

const Type& NifNodeImporterFallout4::GetType() const
{
	return TYPE;
}

const Type NifNodeImporterFallout4::TYPE("NifTranslatorNodeFallout4Importer", &NifTranslatorFixtureItem::TYPE);


text:
#ifndef CAN_RAW_H
#define CAN_RAW_H

#include <linux/can.h>

#define SOL_CAN_RAW (SOL_CAN_BASE + CAN_RAW)

/* for socket options affecting the socket (not the global system) */

enum {
	CAN_RAW_FILTER = 1,	/* set 0 .. n can_filter(s)          */
	CAN_RAW_ERR_FILTER,	/* set filter for error frames       */
	CAN_RAW_LOOPBACK,	/* local loopback (default:on)       */
	CAN_RAW_RECV_OWN_MSGS	/* receive my own msgs (default:off) */
};

#endif


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.devtools_bridge.gcd;

import android.util.JsonWriter;

import org.chromium.components.devtools_bridge.commands.Command;
import org.chromium.components.devtools_bridge.commands.ParamDefinition;

import java.io.IOException;
import java.io.StringWriter;

/**
 * Helper class for constructing GCD JSON messages (HTTP requests) used in the DevTools bridge.
 */
public final class MessageWriter {
    private final StringWriter mStringWriter;
    private final JsonWriter mWriter;
    boolean mClosed = false;

    public MessageWriter() {
        mStringWriter = new StringWriter();
        mWriter = new JsonWriter(mStringWriter);
    }

    public MessageWriter close() throws IOException {
        assert !mClosed;
        mWriter.close();
        mClosed = true;
        return this;
    }

    @Override
    public String toString() {
        assert mClosed;
        return mStringWriter.toString();
    }

    /**
     * Writes body of registrationTicket PATCH request.
     */
    public MessageWriter writeTicketPatch(InstanceDescription description) throws IOException {
        mWriter.beginObject();
        mWriter.name("deviceDraft");
        writeDeviceDraft(description);
        mWriter.name("oauthClientId").value(description.oAuthClientId);
        mWriter.endObject();
        return this;
    }

    /**
     * Writes body of devices/<instanceId> PATCH request.
     */
    public MessageWriter writeDeviceGCMChannelPatch(String gcmChannelId) throws IOException {
        mWriter.beginObject();
        mWriter.name("channel");
        mWriter.beginObject();
        mWriter.name("gcmRegistrationId").value(gcmChannelId);
        mWriter.endObject();
        mWriter.endObject();
        return this;
    }

    private void writeDeviceDraft(InstanceDescription description) throws IOException {
        mWriter.beginObject();
        mWriter.name("deviceKind").value("vendor");
        mWriter.name("displayName").value(description.displayName);
        mWriter.name("systemName").value("Chrome DevTools Bridge");
        mWriter.name("channel");
        writeChannelDefinition(description);
        mWriter.name("commandDefs");
        writeCommandsDefinition();
        mWriter.endObject();
    }

    private void writeChannelDefinition(InstanceDescription description) throws IOException {
        mWriter.beginObject();
        mWriter.name("supportedType").value("gcm");
        mWriter.name("gcmRegistrationId").value(description.gcmChannelId);
        mWriter.endObject();
    }

    private void writeCommandsDefinition() throws IOException {
        mWriter.beginObject();
        mWriter.name("base");
        writeCommandsDefinitionBase();
        mWriter.endObject();
    }

    private void writeCommandsDefinitionBase() throws IOException {
        mWriter.beginObject();
        for (Command.Type type : Command.Type.values()) {
            mWriter.name(type.definition.shortName());
            beginParameters();
            for (ParamDefinition<?> param : type.definition.inParams()) {
                writeParameter(param.name(), param.type());
            }
            endParameters();
        }
        mWriter.endObject();
    }

    private void beginParameters() throws IOException {
        mWriter.beginObject();
        mWriter.name("parameters");
        mWriter.beginObject();
    }

    private void endParameters() throws IOException {
        mWriter.endObject();
        mWriter.endObject();
    }

    private void writeParameter(String name, String type) throws IOException {
        mWriter.name(name);
        mWriter.beginObject();
        mWriter.name("type").value(type);
        mWriter.endObject();
    }

    /**
     * Writes body of command PATCH request. Updates command status and out parametes
     * when the command has processed.
     */
    public MessageWriter writeCommandPatch(Command command) throws IOException {
        mWriter.beginObject();
        if (command.state() == Command.State.DONE) {
            mWriter.name("state").value("done");
            mWriter.name("results");
            mWriter.beginObject();
            command.visitOutParams(new ParamWriter());
            mWriter.endObject();
        } else if (command.state() == Command.State.ERROR) {
            mWriter.name("state").value("error");
            mWriter.name("error");
            mWriter.beginObject();
            mWriter.name("message").value(command.getErrorMessage());
            mWriter.endObject();
        }
        mWriter.endObject();
        return this;
    }

    private class ParamWriter implements Command.ParamVisitor {
        @Override
        public void visit(ParamDefinition<?> param, String value) {
            try {
                mWriter.name(param.name()).value(value);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}


text:
Author: esterTion

---

A quick demo can be found [here](https://estertion.github.io/LightWeightMusicPlayer/demo.htm)

---

## Parameter

MusicPlayer accepts an object with following properties as parameter
 * element: The element to attach (required)
 * src: The audio file URL to play (required)
 * id: The id of generated div
 * borderWidth: The border width of div
 * autoPlay: Automatic starts play after summoned (won't work on mobile device)
 * loop: Loops the playback
 * color: An object with optional color defination for parts, including "played" "buffered" "blank" and "border"

---

### Default config
This will be overwrote by config passed to the function

```Javascript
{
	color:{
		played:'#FFFFFF',
		buffered:'#C8C7C7',
		blank:'#918F8F',
		border:'#000000'
	},
	id:'MusicPlayer_'+Date.now(),
	borderWidth:0,
	autoPlay:false,
	loop:false
}
```

---

### Example config

```Javascript
{
	element:document.getElementById('music_container'),
	src:'https://estertion.win/DREAMCATCHER.m4a',
	id:'LightWeightPlayer',
	borderWidth:'1px',
	autoPlay:true,
	loop:true,
	color:{
		played:'#E05959',
		buffered:'#FFA7A7',
		blank:'#EEE',
		border:'#DDD'
	}
}
```

---
# 中文

## 轻量级音乐播放器

示例页面在[这里](https://estertion.github.io/LightWeightMusicPlayer/demo.htm)

---

## 参数

MusicPlayer接收一个包含以下属性的对象为参数
 * element: 要附属到的元素 (必须)
 * src: 要播放的音频文件URL (必须)
 * id: div的id
 * borderWidth: div的边框宽度
 * autoPlay: 生成后自动开始播放(移动端不可实现)
 * loop: 洗脑循环
 * color: 带可选值的对象, 包括 "played" "buffered" "blank" 和 "border"