text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: almartinez
 * Date: 8/10/13
 * Time: 10:00
 * To change this template use File | Settings | File Templates.
 */
namespace Cloud\StorageSystemBundle\Utility;

use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Process\Exception\InvalidArgumentException;

class Swift
{
    private $authUrl;
    private $tenant;
    private $container;
    private $username;
    private $password;

    private $tokenId;
    private $url;

    private $httpClient;

    function __construct($httpClient, $authUrl,
                         $tenant=null, $username=null, $password=null){
        $this->authUrl = $authUrl; //        $authUrl = 'http://folsom2.tissat.es:5000/v2.0/tokens';
        $this->tenant = $tenant;
        $this->username = $username;
        $this->password = $password;
        $this->httpClient = $httpClient;

        if (!empty($username)) $this->getAuthTokens();
    }

    /*
     * In order to execute swift commands, the first thing you need to do is to call
     * getAuthTokens().
     * */
    public function getAuthTokens(){

        $json_string = json_encode(array(
            'auth' => array(
                'passwordCredentials' => array(
                    'username' => $this->username,
                    'password' => $this->password,
                ),
                'tenantName' => $this->tenant,
            )
        ));

// Configuring curl options
        $options = array(
            CURLOPT_URL => $this->authUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('Content-type: application/json'),
            CURLOPT_POSTFIELDS => $json_string
        );

        $tokens = $this->httpClient->exec($options);
        $tokensDecode = json_decode($tokens);

        try {
             $this->tokenId = $tokensDecode->{'access'}->{'token'}->{'id'};
             $this->url = $tokensDecode->{'access'}->{'serviceCatalog'}[0]->{'endpoints'}[0]->{'publicURL'};
        } catch(Exception $a){
               throw new InvalidArgumentException("Bad authentication");
        }
    }

    public function getMetadata($fileId=null){
        $options = array(
            CURLOPT_URL => $this->url . "/" . $this->container . "/metadata?file_id=". $fileId .'&list=true',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('stacksync-api:true',
                'X-Auth-Token:' . $this->tokenId),
        );

        $contenido = $this->httpClient->exec($options);

        $contenido = json_decode($contenido, false);
   //     if(!$this->checkErrors($contenido))usort($contenido->contents, array($this, "compareSortOrderByFoldersFirst"));
        return $contenido;
    }

    public function uploadFileToSwift($localFilePath, $fileName, $parent=null)
    {

        $fd = fopen($localFilePath, "r");
        $options = array(
            CURLOPT_URL => $this->url . '/' . $this->container . '/files?file_name=' . $fileName .'&parent='.$parent,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "PUT",
            CURLOPT_VERBOSE => true,
            CURLOPT_INFILE => $fd,
            CURLOPT_INFILESIZE => filesize($localFilePath),
            CURLOPT_READFUNCTION, array("_read_cb"),
            CURLOPT_UPLOAD => true,
            CURLOPT_HTTPHEADER => array('stacksync-api:true',
                'X-Auth-Token:' . $this->tokenId),
        );

        $message = $this->httpClient->exec($options);
        fclose($fd);

        return json_decode($message, false);
    }

    public function _read_cb($ch, $fd, $length)
    {
        $data = fread($fd, $length);
        $len = strlen($data);
//        if (isset($this->_user_write_progress_callback_func)) {
//            call_user_func($this->_user_write_progress_callback_func, $len);
//        }
        return $data;
    }

    public function deleteFile($id) {

        $options = array(
            CURLOPT_URL => $this->url . '/' . $this->container . '/files?file_id=' . $id,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "DELETE",
            CURLOPT_VERBOSE => true,
            CURLOPT_HTTPHEADER => array('stacksync-api:true',
                'X-Auth-Token:' . $this->tokenId),
        );

        $message = $this->httpClient->exec($options);

        return json_decode($message, false);
    }

    public function downloadFileFromSwift($id) {
        $fd = fopen($id, "w+");
        $options = array(
            CURLOPT_URL => $this->url . '/' . $this->container . '/files?file_id=' . $id,
            CURLOPT_FILE => $fd,
            CURLOPT_HTTPHEADER => array('stacksync-api:true',
                'X-Auth-Token:' . $this->tokenId),
        );

        $contents = $this->httpClient->exec($options);
        fclose($fd);

        return $contents;
    }

    public function createContainer($container)
    {
        $options = array(
            CURLOPT_URL => $this->url . '/' . $container,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "PUT",
            CURLOPT_HTTPHEADER => array('X-Auth-Token:' . $this->tokenId),
        );

        $message = $this->httpClient->exec($options);

        return $message;
    }

    public function deleteContainer($container)
    {
        $options = array(
            CURLOPT_URL => $this->url . '/' . $container,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "DELETE",
            CURLOPT_HTTPHEADER => array('X-Auth-Token:' . $this->tokenId),
        );

        $message = $this->httpClient->exec($options);

        return $message;
    }

    public function createFolder($folderName, $parent_id=null)
    {
        $options = array(
            CURLOPT_URL => $this->url . '/' . $this->container . '/files?folder_name=' . $folderName . '&parent=' . $parent_id,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_HTTPHEADER => array('X-Auth-Token:' . $this->tokenId,
                'stacksync-api:true')
        );

        $message = $this->httpClient->exec($options);

        return json_decode($message, false);
    }

    private function compareSortOrderByFoldersFirst($a, $b)
    {
        if ($a->is_folder && !$b->is_folder) {
            return -1;
        } else if (!$a->is_folder && $b->is_folder) {
            return 1;
        } else {
            return strcmp($a->filename, $b->filename);
        }
    }

    public function checkErrors($message){
        if (property_exists($message, 'error')){
            return true;
        }
    }

    public function setAuthUrl($authUrl)
    {
        $this->authUrl = $authUrl;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.siemens.ct.exi</groupId>
  <artifactId>exificient</artifactId>
  <name>EXIficient</name>
  <url>http://exificient.github.io/</url>
  <version>1.0.5-SNAPSHOT</version>
  <packaging>jar</packaging><!-- bundle -->
  <description>EXIficient is an open source implementation of the W3C Efficient XML Interchange
    (EXI) format specification written in the Java programming language. The EXI format is a very
    compact representation for the Extensible Markup Language (XML) Information Set that is intended
    to simultaneously optimize performance and the utilization of computational resources. </description>
  <organization>
    <name>Siemens AG</name>
    <url>http://www.siemens.com/corporate-technology/</url>
  </organization>

  <developers>
    <developer>
      <name>Daniel Peintner</name>
      <email>Daniel.Peintner.EXT@siemens.com</email>
      <organization>Siemens AG</organization>
    </developer>
  </developers>

  <licenses>
    <license>
      <name>MIT License</name>
      <url>http://www.opensource.org/licenses/mit-license.php</url>
    </license>
  </licenses>

  <issueManagement>
    <system>Github Issues</system>
    <url>https://github.com/EXIficient/exificient/issues</url>
  </issueManagement>

  <scm>
    <connection>scm:git:git://github.com/EXIficient/exificient.git</connection>
    <!-- <developerConnection>scm:git:git@github.com:EXIficient/exificient.git</developerConnection> -->
    <developerConnection>scm:git:https://github.com/EXIficient/exificient.git</developerConnection>
    <url>https://github.com/EXIficient/exificient</url>
    <tag>HEAD</tag>
  </scm>

  <dependencies>
    <dependency>
      <groupId>com.siemens.ct.exi</groupId>
      <artifactId>exificient-core</artifactId>
      <version>1.0.5-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>com.siemens.ct.exi</groupId>
      <artifactId>exificient-grammars</artifactId>
      <version>1.0.5-SNAPSHOT</version>
    </dependency>
	<dependency>
	  <groupId>xmlpull</groupId>
	  <artifactId>xmlpull</artifactId>
	  <version>1.1.3.1</version>
	</dependency>
    <!-- Test Dependencies -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>xmlunit</groupId>
      <artifactId>xmlunit</artifactId>
      <version>1.6</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.codehaus.woodstox</groupId>
      <artifactId>woodstox-core-asl</artifactId>
      <version>4.1.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>xpp3</groupId>
      <artifactId>xpp3</artifactId>
      <version>1.1.4c</version>
      <scope>test</scope>
    </dependency>
	<dependency>
		<groupId>javax.xml.bind</groupId>
		<artifactId>jaxb-api</artifactId>
		<version>2.2.11</version>
	</dependency>
	<dependency>
		<groupId>com.sun.xml.bind</groupId>
		<artifactId>jaxb-core</artifactId>
		<version>2.2.11</version>
	</dependency>
	<dependency>
		<groupId>com.sun.xml.bind</groupId>
		<artifactId>jaxb-impl</artifactId>
		<version>2.2.11</version>
	</dependency>
	<dependency>
		<groupId>javax.activation</groupId>
		<artifactId>activation</artifactId>
		<version>1.1.1</version>
	</dependency>

    <!-- Eclipse m2e -->
    <!--
	<dependency>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-resources-plugin</artifactId>
		<version>2.5</version>
	</dependency>
	-->
  </dependencies>

  <properties>
    <!-- maven-compiler-plugin configuration -->
    <maven.compiler.source>1.6</maven.compiler.source>
    <maven.compiler.target>1.6</maven.compiler.target>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
    <finalName>exificient</finalName>
    <plugins>
      <!-- OSGI -->
      <!-- <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>3.2.0</version>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
            <Bundle-Version>${project.version}</Bundle-Version>
            <Export-Package> com.siemens.ct.exi.api.*, com.siemens.ct.exi.cmd.*,
              com.siemens.ct.exi.util.* </Export-Package>
          </instructions>
        </configuration>
      </plugin> -->
      <!-- Include test classes -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.4</version>
        <executions>
          <execution>
            <id>attach-test</id>
            <goals>
              <goal>test-jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <!-- Include Java Source OR mvn source:jar  -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>2.2.1</version>
        <!--2.3.2-->
        <executions>
          <execution>
            <id>attach-sources</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <downloadSources>true</downloadSources>
          <downloadJavadocs>true</downloadJavadocs>
        </configuration>
      </plugin>
      <!-- Include Java Doc OR mvn javadoc:jar  -->
      <!-- see http://maven.apache.org/plugins/maven-javadoc-plugin/examples/javadoc-resources.html -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9.1</version>
        <!--2.3.2-->
        <configuration>
          <overview>${basedir}/src/main/java/overview.html</overview>
        </configuration>
        <executions>
          <execution>
            <id>attach-javadocs</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <!-- without it Travis seems to pick Xmx32m which is not a lot -->
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19</version>
        <configuration>
          <argLine>-Xmx64m</argLine>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-release-plugin</artifactId>
        <configuration>
          <tagNameFormat>v@{project.version}</tagNameFormat>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.siemens.ct.exi.main.cmd.EXIficientCMD</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <parent>
    <groupId>org.sonatype.oss</groupId>
    <artifactId>oss-parent</artifactId>
    <version>7</version>
  </parent>

</project>

redpajama_set_name: RedPajamaGithub


text:
{% extends "layout.html" %}

{% block head %}
  <link href="/public/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
  <link href="/public/stylesheets/static-2016-07-04.css" media="screen" rel="stylesheet" type="text/css" />
  {% include "includes/implementations/deskpro.html" %}
{% endblock %}

{% block page_title %}
  Shared Parental Leave and Pay - GOV.UK
{% endblock %}

{% block content %}

{% include "includes/breadcrumbs/childcare.html" %}

Shared Parental Leave and Pay

 1. Overview

 2. Eligibility

 3. When you can start

 4. What you'll get

 5. Applying for leave and pay

 6. Booking blocks of leave

1. Overview

You may be able to get Shared Parental Leave (SPL) and Statutory Shared Parental Pay (ShPP) if:

your baby is due on or after 5 April 2015

you adopt a child on or after 5 April 2015

If you're eligible for SPL you can use it to take leave in blocks separated
              by periods of work, instead of taking it all in one go.

To start SPL or ShPP the mother must end her maternity leave (for SPL)
              or her Maternity Allowance or maternity pay (for ShPP). If she doesn't get maternity leave (but she ends her Maternity Allowance or pay early) her partner might still get SPL.

If you're adopting then you or your partner must end any adoption leave or adoption pay early instead.

If you're eligible you can take:

the remaining leave as SPL (52 weeks minus any weeks of maternity or adoption leave)

the remaining pay as ShPP (39 weeks minus any weeks of maternity pay, maternity allowance or adoption pay)

If neither of you is entitled to maternity or adoption leave then SPL will be 52 weeks minus any weeks of maternity pay, Maternity Allowance or adoption pay.

You can share SPL and ShPP between you if you're both eligible.

Example A mother and her partner are both eligible for SPL and ShPP. The mother ends her maternity leave and pay after 12 weeks,
                leaving 40 weeks available for SPL and 27 weeks available for ShPP. The parents can choose how to split this.

SPL and ShPP must be taken between the baby's birth and first birthday (or within one year of adoption).

                     Next Eligibility

Print entire guide

Last updated: 16 March 2016

    {% include "includes/related-content/childcare.html" %}

  {% include "includes/report-a-problem.html" %}

{% endblock %}


text:
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Collections;
using System.Text;

namespace System.DirectoryServices.Protocols
{
    public static class BerConverter
    {
        public static byte[] Encode(string format, params object[] value)
        {
            if (format == null)
                throw new ArgumentNullException("format");

            // no need to turn on invalid encoding detection as we just do string->byte[] conversion.
            UTF8Encoding utf8Encoder = new UTF8Encoding();
            byte[] encodingResult = null;
            // value is allowed to be null in certain scenario, so if it is null, just set it to empty array.
            if (value == null)
                value = new object[0];

            Debug.WriteLine("Begin encoding\n");

            // allocate the berelement
            BerSafeHandle berElement = new BerSafeHandle();

            int valueCount = 0;
            int error = 0;
            for (int formatCount = 0; formatCount < format.Length; formatCount++)
            {
                char fmt = format[formatCount];
                if (fmt == '{' || fmt == '}' || fmt == '[' || fmt == ']' || fmt == 'n')
                {
                    // no argument needed
                    error = Wldap32.ber_printf_emptyarg(berElement, new string(fmt, 1));
                }
                else if (fmt == 't' || fmt == 'i' || fmt == 'e')
                {
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    if (!(value[valueCount] is int))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be int\n");
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    // one int argument
                    error = Wldap32.ber_printf_int(berElement, new string(fmt, 1), (int)value[valueCount]);

                    // increase the value count
                    valueCount++;
                }
                else if (fmt == 'b')
                {
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    if (!(value[valueCount] is bool))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be boolean\n");
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    // one int argument
                    error = Wldap32.ber_printf_int(berElement, new string(fmt, 1), (bool)value[valueCount] ? 1 : 0);

                    // increase the value count
                    valueCount++;
                }
                else if (fmt == 's')
                {
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    if (value[valueCount] != null && !(value[valueCount] is string))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be string, but receiving value has type of ");
                        Debug.WriteLine(value[valueCount].GetType());
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    // one string argument
                    byte[] tempValue = null;
                    if (value[valueCount] != null)
                    {
                        tempValue = utf8Encoder.GetBytes((string)value[valueCount]);
                    }
                    error = EncodingByteArrayHelper(berElement, tempValue, 'o');

                    // increase the value count
                    valueCount++;
                }
                else if (fmt == 'o' || fmt == 'X')
                {
                    // we need to have one arguments
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    if (value[valueCount] != null && !(value[valueCount] is byte[]))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be byte[], but receiving value has type of ");
                        Debug.WriteLine(value[valueCount].GetType());
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    byte[] tempValue = (byte[])value[valueCount];
                    error = EncodingByteArrayHelper(berElement, tempValue, fmt);

                    valueCount++;
                }
                else if (fmt == 'v')
                {
                    // we need to have one arguments
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    if (value[valueCount] != null && !(value[valueCount] is string[]))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be string[], but receiving value has type of ");
                        Debug.WriteLine(value[valueCount].GetType());
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    string[] stringValues = (string[])value[valueCount];
                    byte[][] tempValues = null;
                    if (stringValues != null)
                    {
                        tempValues = new byte[stringValues.Length][];
                        for (int i = 0; i < stringValues.Length; i++)
                        {
                            string s = stringValues[i];
                            if (s == null)
                                tempValues[i] = null;
                            else
                            {
                                tempValues[i] = utf8Encoder.GetBytes(s);
                            }
                        }
                    }

                    error = EncodingMultiByteArrayHelper(berElement, tempValues, 'V');

                    valueCount++;
                }
                else if (fmt == 'V')
                {
                    // we need to have one arguments
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    if (value[valueCount] != null && !(value[valueCount] is byte[][]))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be byte[][], but receiving value has type of ");
                        Debug.WriteLine(value[valueCount].GetType());
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
                    }

                    byte[][] tempValue = (byte[][])value[valueCount];

                    error = EncodingMultiByteArrayHelper(berElement, tempValue, fmt);

                    valueCount++;
                }
                else
                {
                    Debug.WriteLine("Format string contains undefined character: ");
                    Debug.WriteLine(new string(fmt, 1));
                    throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterUndefineChar));
                }

                // process the return value
                if (error == -1)
                {
                    Debug.WriteLine("ber_printf failed\n");
                    throw new BerConversionException();
                }
            }

            // get the binary value back
            berval binaryValue = new berval();
            IntPtr flattenptr = (IntPtr)0;

            try
            {
                // can't use SafeBerval here as CLR creates a SafeBerval which points to a different memory location, but when doing memory
                // deallocation, wldap has special check. So have to use IntPtr directly here.
                error = Wldap32.ber_flatten(berElement, ref flattenptr);

                if (error == -1)
                {
                    Debug.WriteLine("ber_flatten failed\n");
                    throw new BerConversionException();
                }

                if (flattenptr != (IntPtr)0)
                {
                    Marshal.PtrToStructure(flattenptr, binaryValue);
                }

                if (binaryValue == null || binaryValue.bv_len == 0)
                {
                    encodingResult = new byte[0];
                }
                else
                {
                    encodingResult = new byte[binaryValue.bv_len];

                    Marshal.Copy(binaryValue.bv_val, encodingResult, 0, binaryValue.bv_len);
                }
            }
            finally
            {
                if (flattenptr != (IntPtr)0)
                    Wldap32.ber_bvfree(flattenptr);
            }

            return encodingResult;
        }

        public static object[] Decode(string format, byte[] value)
        {
            bool decodeSucceeded;
            object[] decodeResult = TryDecode(format, value, out decodeSucceeded);
            if (decodeSucceeded)
                return decodeResult;
            else
                throw new BerConversionException();
        }

        internal static object[] TryDecode(string format, byte[] value, out bool decodeSucceeded)
        {
            if (format == null)
                throw new ArgumentNullException("format");

            Debug.WriteLine("Begin decoding\n");

            UTF8Encoding utf8Encoder = new UTF8Encoding(false, true);
            berval berValue = new berval();
            ArrayList resultList = new ArrayList();
            BerSafeHandle berElement = null;

            object[] decodeResult = null;
            decodeSucceeded = false;

            if (value == null)
            {
                berValue.bv_len = 0;
                berValue.bv_val = (IntPtr)0;
            }
            else
            {
                berValue.bv_len = value.Length;
                berValue.bv_val = Marshal.AllocHGlobal(value.Length);
                Marshal.Copy(value, 0, berValue.bv_val, value.Length);
            }

            try
            {
                berElement = new BerSafeHandle(berValue);
            }
            finally
            {
                if (berValue.bv_val != (IntPtr)0)
                    Marshal.FreeHGlobal(berValue.bv_val);
            }

            int error = 0;

            for (int formatCount = 0; formatCount < format.Length; formatCount++)
            {
                char fmt = format[formatCount];
                if (fmt == '{' || fmt == '}' || fmt == '[' || fmt == ']' || fmt == 'n' || fmt == 'x')
                {
                    error = Wldap32.ber_scanf(berElement, new string(fmt, 1));

                    if (error != 0)
                        Debug.WriteLine("ber_scanf for {, }, [, ], n or x failed");
                }
                else if (fmt == 'i' || fmt == 'e' || fmt == 'b')
                {
                    int result = 0;
                    error = Wldap32.ber_scanf_int(berElement, new string(fmt, 1), ref result);

                    if (error == 0)
                    {
                        if (fmt == 'b')
                        {
                            // should return a bool
                            bool boolResult = false;
                            if (result == 0)
                                boolResult = false;
                            else
                                boolResult = true;
                            resultList.Add(boolResult);
                        }
                        else
                        {
                            resultList.Add(result);
                        }
                    }
                    else
                        Debug.WriteLine("ber_scanf for format character 'i', 'e' or 'b' failed");
                }
                else if (fmt == 'a')
                {
                    // return a string
                    byte[] byteArray = DecodingByteArrayHelper(berElement, 'O', ref error);
                    if (error == 0)
                    {
                        string s = null;
                        if (byteArray != null)
                            s = utf8Encoder.GetString(byteArray);

                        resultList.Add(s);
                    }
                }
                else if (fmt == 'O')
                {
                    // return berval
                    byte[] byteArray = DecodingByteArrayHelper(berElement, fmt, ref error);
                    if (error == 0)
                    {
                        // add result to the list
                        resultList.Add(byteArray);
                    }
                }
                else if (fmt == 'B')
                {
                    // return a bitstring and its length
                    IntPtr ptrResult = (IntPtr)0;
                    int length = 0;
                    error = Wldap32.ber_scanf_bitstring(berElement, "B", ref ptrResult, ref length);

                    if (error == 0)
                    {
                        byte[] byteArray = null;
                        if (ptrResult != (IntPtr)0)
                        {
                            byteArray = new byte[length];
                            Marshal.Copy(ptrResult, byteArray, 0, length);
                        }
                        resultList.Add(byteArray);
                    }
                    else
                        Debug.WriteLine("ber_scanf for format character 'B' failed");

                    // no need to free memory as wldap32 returns the original pointer instead of a duplicating memory pointer that
                    // needs to be freed
                }
                else if (fmt == 'v')
                {
                    //null terminate strings
                    byte[][] byteArrayresult = null;
                    string[] stringArray = null;

                    byteArrayresult = DecodingMultiByteArrayHelper(berElement, 'V', ref error);
                    if (error == 0)
                    {
                        if (byteArrayresult != null)
                        {
                            stringArray = new string[byteArrayresult.Length];
                            for (int i = 0; i < byteArrayresult.Length; i++)
                            {
                                if (byteArrayresult[i] == null)
                                {
                                    stringArray[i] = null;
                                }
                                else
                                {
                                    stringArray[i] = utf8Encoder.GetString(byteArrayresult[i]);
                                }
                            }
                        }

                        resultList.Add(stringArray);
                    }
                }
                else if (fmt == 'V')
                {
                    byte[][] result = null;

                    result = DecodingMultiByteArrayHelper(berElement, fmt, ref error);
                    if (error == 0)
                    {
                        resultList.Add(result);
                    }
                }
                else
                {
                    Debug.WriteLine("Format string contains undefined character\n");
                    throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterUndefineChar));
                }

                if (error != 0)
                {
                    // decode failed, just return
                    return decodeResult;
                }
            }

            decodeResult = new object[resultList.Count];
            for (int count = 0; count < resultList.Count; count++)
            {
                decodeResult[count] = resultList[count];
            }

            decodeSucceeded = true;
            return decodeResult;
        }

        private static int EncodingByteArrayHelper(BerSafeHandle berElement, byte[] tempValue, char fmt)
        {
            int error = 0;

            // one byte array, one int arguments
            if (tempValue != null)
            {
                IntPtr tmp = Marshal.AllocHGlobal(tempValue.Length);
                Marshal.Copy(tempValue, 0, tmp, tempValue.Length);
                HGlobalMemHandle memHandle = new HGlobalMemHandle(tmp);

                error = Wldap32.ber_printf_bytearray(berElement, new string(fmt, 1), memHandle, tempValue.Length);
            }
            else
            {
                error = Wldap32.ber_printf_bytearray(berElement, new string(fmt, 1), new HGlobalMemHandle((IntPtr)0), 0);
            }

            return error;
        }

        private static byte[] DecodingByteArrayHelper(BerSafeHandle berElement, char fmt, ref int error)
        {
            error = 0;
            IntPtr result = (IntPtr)0;
            berval binaryValue = new berval();
            byte[] byteArray = null;

            // can't use SafeBerval here as CLR creates a SafeBerval which points to a different memory location, but when doing memory
            // deallocation, wldap has special check. So have to use IntPtr directly here.
            error = Wldap32.ber_scanf_ptr(berElement, new string(fmt, 1), ref result);

            try
            {
                if (error == 0)
                {
                    if (result != (IntPtr)0)
                    {
                        Marshal.PtrToStructure(result, binaryValue);

                        byteArray = new byte[binaryValue.bv_len];
                        Marshal.Copy(binaryValue.bv_val, byteArray, 0, binaryValue.bv_len);
                    }
                }
                else
                    Debug.WriteLine("ber_scanf for format character 'O' failed");
            }
            finally
            {
                if (result != (IntPtr)0)
                    Wldap32.ber_bvfree(result);
            }

            return byteArray;
        }

        private static int EncodingMultiByteArrayHelper(BerSafeHandle berElement, byte[][] tempValue, char fmt)
        {
            IntPtr berValArray = (IntPtr)0;
            IntPtr tempPtr = (IntPtr)0;
            SafeBerval[] managedBerVal = null;
            int error = 0;

            try
            {
                if (tempValue != null)
                {
                    int i = 0;
                    berValArray = Utility.AllocHGlobalIntPtrArray(tempValue.Length + 1);
                    int structSize = Marshal.SizeOf(typeof(SafeBerval));
                    managedBerVal = new SafeBerval[tempValue.Length];

                    for (i = 0; i < tempValue.Length; i++)
                    {
                        byte[] byteArray = tempValue[i];

                        // construct the managed berval
                        managedBerVal[i] = new SafeBerval();

                        if (byteArray == null)
                        {
                            managedBerVal[i].bv_len = 0;
                            managedBerVal[i].bv_val = (IntPtr)0;
                        }
                        else
                        {
                            managedBerVal[i].bv_len = byteArray.Length;
                            managedBerVal[i].bv_val = Marshal.AllocHGlobal(byteArray.Length);
                            Marshal.Copy(byteArray, 0, managedBerVal[i].bv_val, byteArray.Length);
                        }

                        // allocate memory for the unmanaged structure
                        IntPtr valPtr = Marshal.AllocHGlobal(structSize);
                        Marshal.StructureToPtr(managedBerVal[i], valPtr, false);

                        tempPtr = (IntPtr)((long)berValArray + IntPtr.Size * i);
                        Marshal.WriteIntPtr(tempPtr, valPtr);
                    }

                    tempPtr = (IntPtr)((long)berValArray + IntPtr.Size * i);
                    Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
                }

                error = Wldap32.ber_printf_berarray(berElement, new string(fmt, 1), berValArray);

                GC.KeepAlive(managedBerVal);
            }
            finally
            {
                if (berValArray != (IntPtr)0)
                {
                    for (int i = 0; i < tempValue.Length; i++)
                    {
                        IntPtr ptr = Marshal.ReadIntPtr(berValArray, IntPtr.Size * i);
                        if (ptr != (IntPtr)0)
                            Marshal.FreeHGlobal(ptr);
                    }
                    Marshal.FreeHGlobal(berValArray);
                }
            }

            return error;
        }

        private static byte[][] DecodingMultiByteArrayHelper(BerSafeHandle berElement, char fmt, ref int error)
        {
            error = 0;
            // several berval
            IntPtr ptrResult = (IntPtr)0;
            int i = 0;
            ArrayList binaryList = new ArrayList();
            IntPtr tempPtr = (IntPtr)0;
            byte[][] result = null;

            try
            {
                error = Wldap32.ber_scanf_ptr(berElement, new string(fmt, 1), ref ptrResult);

                if (error == 0)
                {
                    if (ptrResult != (IntPtr)0)
                    {
                        tempPtr = Marshal.ReadIntPtr(ptrResult);
                        while (tempPtr != (IntPtr)0)
                        {
                            berval ber = new berval();
                            Marshal.PtrToStructure(tempPtr, ber);

                            byte[] berArray = new byte[ber.bv_len];
                            Marshal.Copy(ber.bv_val, berArray, 0, ber.bv_len);

                            binaryList.Add(berArray);

                            i++;
                            tempPtr = Marshal.ReadIntPtr(ptrResult, i * IntPtr.Size);
                        }

                        result = new byte[binaryList.Count][];
                        for (int j = 0; j < binaryList.Count; j++)
                        {
                            result[j] = (byte[])binaryList[j];
                        }
                    }
                }
                else
                    Debug.WriteLine("ber_scanf for format character 'V' failed");
            }
            finally
            {
                if (ptrResult != (IntPtr)0)
                {
                    Wldap32.ber_bvecfree(ptrResult);
                }
            }

            return result;
        }
    }
}


text:
package io.github.bckfnn.actioner;

import io.github.bckfnn.taggersty.StandardFilter;
import io.github.bckfnn.taggersty.vertx.VertxHtmlTags;
import io.github.bckfnn.taggersty.vertx.VertxHtmlTags.VertxOutput;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpHeaders;
import io.vertx.ext.web.RoutingContext;

public class LayoutTemplateHandler implements Handler<RoutingContext> {
    @Override
    public void handle(RoutingContext ctx) {
        LayoutTemplate template = ctx.get("template");
        if (template == null) {
            ctx.next();
            return;
        }
        ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8");
        ctx.response().setChunked(true);
        if (ctx.request().method().equals("HEAD")) {
            ctx.response().end();
            return;
        }
        VertxOutput out = new VertxOutput(ctx.response());
        out.endHandler($ -> {
            System.out.println("end");
            ctx.response().end();
        });
        VertxHtmlTags htmlWriter = new VertxHtmlTags(out);
        htmlWriter.filter(new StandardFilter());

        htmlWriter.setAutoIndent(false);
        htmlWriter.setAutoIndent(true);
        template.layout(htmlWriter);
        htmlWriter.close();
    }
}


text:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pred', 'age', 'class']
data = pd.read_csv('indians-diabetes.data', names=names)
array = data.values

x = array[:,0:8]
y = array[:,8]

test_size = 0.33
seed = 7	# removing this arg will cause the accuracy to vary
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_size, random_state=seed)

model = LogisticRegression()
model.fit(x_train, y_train)
result = model.score(x_test, y_test)

print("Accuracy: ", result.mean()*100.0, result.std()*100)
print(result*100)


text:
class CreatePods < ActiveRecord::Migration
  def change
    create_table :pods do |t|
      t.date :month

      t.timestamps
    end
  end
end


text:
ngApp.controller("SlotController", ["$scope",
    function($scope) {
        this.init = function(slotId, options) {
            $scope.slotId = slotId;
            $scope.options = options;
            $scope.toggleEnableButtons();

        };
        $scope.rebuildActions = function() {
            var newContentButton = $('.vic-new-widget', '#vic-slot-' + $scope.slotId).first();
            newContentButton.addClass('vic-new-widget-disabled');
            $('.vic-new-widget', '#vic-slot-' + $scope.slotId).remove();
            $('.vic-widget-container', '#vic-slot-' + $scope.slotId).after(newContentButton);
            $('#vic-slot-' + $scope.slotId).prepend(newContentButton.clone());
            $scope.toggleEnableButtons();
        };
        $scope.toggleEnableButtons = function() {
            widgets = $('.vic-widget-container', '#vic-slot-' + $scope.slotId);
            if (!("max" in $scope.options) || ("max" in $scope.options) && $scope.options.max > widgets.length) {
                $('.vic-new-widget', '#vic-slot-' + $scope.slotId).removeClass('vic-new-widget-disabled');
            } else {
                $('.vic-new-widget', '#vic-slot-' + $scope.slotId).addClass('vic-new-widget-disabled');
            }
        };
    }
]);


text:
module TravelWebsite
class PasswordsController < Devise::PasswordsController
  def create
    self.resource = resource_class.send_reset_password_instructions(resource_params)

    if successfully_sent?(resource)
      respond_with({}, :location => after_sending_reset_password_instructions_path_for(resource_name))
    else
      a_email = resource_params[:email]
      if a_email
        em = Email.where(:email_data_type => 'UserInfo').where(:email_address => a_email).first
        ui = em.email_data if em
        if ui
          if ui.user

          else
            u = User.new(:email => a_email)
            u.save
            ui.user = u
            ui.save
            self.resource = resource_class.send_reset_password_instructions(resource_params)
            if successfully_sent?(resource)
              respond_with({}, :location => after_sending_reset_password_instructions_path_for(resource_name))
              return
            end
          end
        end
      end
      respond_with(resource)
    end
  end
end
end


text:
<!DOCTYPE html>

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

		<meta name="description" content="">
		<meta name="author" content="">
		<link rel="icon" href="../../favicon.ico">

		<title>医卫里课堂登录</title>

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

		<link href="css/login.css" rel="stylesheet">

登录

				<input type="email" id="inputEmail" class="form-control" placeholder="用户名/手机号码" required autofocus>
				<input type="password" id="inputPassword" class="form-control" placeholder="密码" required>

						<input type="checkbox" value="remember-me">记住密码

				<button class="btn btn-lg btn-info btn-block" type="submit" id="login">登录</button>


text:
layout: default
title: List.js
---

## What is List.js?

> List.js takes a **list of items** and renders them using a **template**.

You can provide the items in several ways:

* Inline as a JSON-serialized `data-attribute`
* Provided as an array to a JavaScript initializer
* Loaded from a remote url

As well as the template:

* Written as the inner HTML of the container element
* Inline as a `data-attribute`
* As a text or compiled template to a JavaScript initializer

Any way you configure it, the list is rendered using the same jQuery plugin, and has access to the same set of rendering helpers: pagination, sorting and filtering. This lets your list evolve from a simple hard-coded test set to your final database-driven, searchable, sortable table, without swapping in different plugins as your requirements expand.

---

* [Usage]({{ site.baseurl }}#javascript-usage)
* [Examples](#examples)
  * [Templates](#example-templates)
  * [Filtering / Searching](#example-filtering)
  * [Sorting](#example-sorting)
  * [Pagination](#example-pagination)
* [Options](#options)
* [API](#api)
* [Events](#events)

---

## Examples

These examples show a subset of the ways you can configure lists; they use example snippets of HTML and JavaScript that **you can edit**, and the rendered result is displayed below.

You can configure all of the Adcom plugins either through JavaScript as in the following examples, or through data-attributes. Read more about your options [here]({{ site.baseurl }}#plugin-initialization).

Templates Render a simple table of data

To render a dynamic table, simply write the HTML necessary to render a single row. Add a unique identifier to the element that will contain all of the items (in this case, the `tbody`). List.js includes a minimal template syntax that lets you insert the value of any element by specifying a JSON path as `data-field`.

Then, initialize your list by calling `.list()` on the `tbody` with any options you need. Here, we specify the template by passing in the HTML contents of the `tbody` explicitly; but this happens by default if you don't specify a template, it is shown here to be explicit. You can also pass in a compiled JavaScript template. Functions will be evaluated by passing the item to the template.

``` example-list
<table>
  <tbody id="1">
    <tr>
      <td data-field="id"></td>
      <td data-field="name"></td>
    </tr>
  </tbody>
</table>

<script type="text/javascript">
  var items = [
    {"id": 1, "name": "one"},
    {"id": 2, "name": "two"},
    // {"id": 3, "name": "three"}
  ];
  $('#1').list({
    items: items,
    template: $('#1')[0].innerHTML
  });
</script>
```

Try adding additional items or more columns to see how it changes the output.

While not possible for all element types, where possible we encourage including the template inline inside the list element (as shown above) as a convention to reduce ambiguity in how a page is constructed.

---

Filtering and Searching

You can tie various input "triggers", such as `<input>` tags, to a list by adding `data-target="#id"` to each of them.

The value of each trigger element (either the natural `value` of something like a text input, or a custom value or regular expression specified with `data-pattern`) will be matched against every item in the list. If any of the attributes referenced in the trigger's `data-fields` (specified using a top-level attribute name, or a JSON path) match the value, it will be included.

Items must match every active filter to be included.

``` example-list
<input type="text" data-target="#2" data-filter="name" data-trigger="keyup" placeholder="Search name">
<input type="checkbox" data-target="#2" data-filter="checkbox" data-pattern="true" value="true">
<label for="checkbox">On?</label>
<input type="radio" data-target="#2" data-filter="radio" data-pattern="1" name="radio">
<label>1</label>
<input type="radio" data-target="#2" data-filter="radio" data-pattern="2" name="radio">
<label>2</label>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Checkbox</th>
      <th>Radio</th>
    </tr>
  </thead>
  <tbody id="2">
    <tr>
      <td data-field="name"></td>
      <td data-field="checkbox"></td>
      <td data-field="radio"></td>
    </tr>
  </tbody>
</table>

<script type="text/javascript">
  var items = [
    {"name": "Number one!", "checkbox": true, radio: "1"},
    {"name": "Number two :(", "checkbox": false, radio: "2"}
  ];
  $('#2').list({ items: items });
</script>
```

---

Sorting

Any field can be sorted by adding a "sort trigger" to an element, which is triggered on click. Just add `data-target` and `data-sort` (where you specify a single field or JSON path) to an element.

On click, the sort cycles through ascending and descending, and is kept track of with the `sort-ascending` and `sort-descending` classes on the trigger. Add one of these at the start to default the sort. (`number` in the example below starts out with `sort-ascending`.)

``` example-list-bs
<table class="table">
  <thead>
    <tr>
      <th class="sort-control sort-ascending" data-target="#3" data-sort="number">Number</th>
      <th class="sort-control" data-target="#3" data-sort="text">Text</th>
    </tr>
  </thead>
  <tbody id="3">
    <tr>
      <td data-field="number"></td>
      <td data-field="text"></td>
    </tr>
  </tbody>
</table>

<script type="text/javascript">
  var items = [
    {"number": 1, "text": "Beta"},
    {"number": 2, "text": "Alpha"}
  ];
  $('#3').list({ items: items });
</script>
```

You can customize the order / availability of the sort states by adding `data-states` to the trigger element, with any of the following comma-separated in the desired cycle order: `ascending`, `descending` or `off` (default is just the first two).

---

Pagination

Two configuration options can be set or updated on a list: `pageSize` and `currentPage`. The text inputs below are set to update the list's settings on change; try updating their values.

``` example-list
<input id="4-size" value="5" type="number" min="1">
<input id="4-page" value="1" type="number" min="1">
<div id="4">
  <button disabled data-field="#"></button>
</div>

<script type="text/javascript">
  var items = [ {"#": 1}, {"#": 2}, {"#": 3}, {"#": 4}, {"#": 5}, {"#": 6}, {"#": 7}, {"#": 8}, {"#": 9}, {"#": 10} ];
  $('#4').list({
    items: items,
    pageSize: $('#4-size').val(),
    currentPage: $('#4-page').val(),
  });

  $('#4-size').on('change', function() {
    $('#4').list({pageSize: $(this).val()});
  });
  $('#4-page').on('change', function() {
    $('#4').list({currentPage: $(this).val()});
  });
</script>
```

Similar to the filter and sort triggers above, clicked on an element with `data-target` and `data-page` attributes will change the current page.

Remember, you can specify any of the list-level configuration options as data-attributes on the list element itself. For example, `pageSize` can also be configured by adding a `data-page-size` attribute to the list element.

---

## Options

[A note]({{ site.baseurl }}#plugin-initialization) on using data attributes versus initializer functions.

Initialization List elements

| attribute        | type           | default | description |
| ---------------- | -------------- | ------- | ----------- |
| items | array, serialized array | | The entire set of items to include in the list. |
| template | string, function | List element's `.innerHTML` | Either a compiled template function (which will receieve each item in the list to be rendered), or a string that will be compiled into a template. If a `template-engine` is also passed, that engine will be used to generate the function from the passed-in string. |
| template-engine | function | | Specify a custom templating function, such as `_.template`. Used when a string is passed for the template. |
| page-size | integer | 20 | How many items to display at a time. |
| current-page | integer | 1 | What page to start with. Can also be updated to switch pages. |
| show | boolean | true | Whether to render the list immediately after initialization. |
| remote | string | | A path to an endpoing containing a JSON representation of the items to load into the list. |

### Filter triggers

| attribute        | type           | default | description |
| ---------------- | -------------- | ------- | ----------- |
| target | jQuery selector | | Selector for the list element. |
| filter | CSV | | Comma-separated string of fields to include when searching for `pattern`. |
| pattern | string, regex | | A case-insensitive string or regex that will be compared against the fields from `filter`. |
| trigger | string | click, change | The page event that will trigger the filter updating. Defaults to `click` for static elements, `change` for inputs. |

### Sort triggers

| attribute        | type           | default | description |
| ---------------- | -------------- | ------- | ----------- |
| target | jQuery selector | | Selector for the list element. |
| sort | string | | The field to sort by. |
| states | string | ascending, descending | Comma-separated list of which states to cycle through when toggling the sort. Can specify any combination of `ascending`, `descending`, and / or `off`. The initial state defaults to `off`, but can be set to another one by adding the `sort-ascending` or `sort-descending` class to the trigger. |

### Page triggers

| attribute        | type           | default | description |
| ---------------- | -------------- | ------- | ----------- |
| target | jQuery selector | | Selector for the list element. |
| page | integer | | The list's `currentPage` will be updated to this number when the trigger is clicked. |

---

API Public methods

| method           | description |
| ---------------- | ----------- |
| .list({ options }) | Any of the [list options](#options-initialization) can be set or updated with this function. Multi word options should be camelcased (`page-size` = `pageSize`). You can also set the sorting behavior by passing a sort function as `sort`. This will override any default sort that is produced by the sort triggers. Similarly, you can override or add filters by passing a slug and filter function as `filter`, or several of them by passing them as a key/value hash. Filters are addititve; pass `null` as the value for a given slug to delete a filter. |
| .list('show') | Re-render the list with the latest settings. If `data-show` is set to false, then this needs to be called manually. |
| .list('destroy') | Destroy the internal list. |
| .list('add', Object[, index]) | Add an item to the list. You can optionally pass the index at which the item should be rendered, if you are not sorting the list. |
| .list('update', index || element || Object, Object) | Update an item in the list. The second argument can be any of the following: 1) the index in the original `items` list of the element, 2) the DOM element currently rendered within the list representing the item, or 3) a reference to the original item object that was passed into `items`. The item is replaced with the new item. |
| .list('delete', index || element || Object) | Remove a given item from the list. Same rules for arguments options as above. |

---

## Events

All events with a pre and post version (such as `show` and `shown`) can be cancelled by calling `.preventDefault()` on the pre event.

| event | trigger | event properties |
| ----- | ------- | ---------------- |
| show.ac.list | Before each time the list is rendered. | |
| shown.ac.list | After each time the list is rendered. | |
| loaded.ac.list | When the remote list of items has successfully been fetched. Only if the `remote` option is used | |
| sortChange.ac.list | When the sort function is about to be set or updated | `fields` the fields to sort on |
| sortChanged.ac.list | After the sort function has changed, before the list is rendered | `fields` the fields to sort on
 `function` resulting sort function |
| filterChange.ac.list | When any filter is about to be set, updated or deleted | `key` slug for the filter
 `filter` arguments passed to the filter |
| filterChanged.ac.list | After any filter has changed, before the list is rendered | `key` slug for the filter
 `filter` arguments passed to the filter
 `function` resulting filter function |
| pageChange.ac.list | When the page is about to be changed | `page` |
| pageChanged.ac.list | After the page has been changed, before the list is rendered | `page` |
| paginated.ac.list | After the list of items has been paginated internall, before the list is rendered. Use to render dynamic pagination triggers. | `page`
 `pages` number of pages
 `count` item count
 `items` items in the current page
 `start` index
 `end` index |


text:
require 'spec_helper'

describe Spree::Checkout::Update, type: :service do
  describe '#transform_address_params' do
    let!(:state)              { create(:state) }
    let!(:country)            { state.country }
    let!(:replace_country)    { described_class.new }
    let!(:address) do
      {
        firstname: 'John',
        lastname: 'Doe',
        address1: '7735 Old Georgetown Road',
        city: 'Bethesda',
        phone: '3014445002',
        zipcode: '20814',
        state_id: state.id,
        country_iso: country.iso
      }
    end

    context 'with ship_address order params' do
      let(:order_params) do
        ActionController::Parameters.new(
          order: {
            ship_address_attributes: address
          }
        )
      end
      let(:result) { replace_country.send(:replace_country_iso_with_id, order_params, 'ship') }

      before { result }

      it 'will return hash contain country_id' do
        expect(result[:order][:ship_address_attributes][:country_id]).to eq country.id
      end

      it 'will return hash without country_iso' do
        expect(result[:order][:ship_address_attributes]).not_to include(:country_iso)
      end
    end

    context 'with bill_address order params' do
      let(:order_params) do
        ActionController::Parameters.new(
          order: {
            bill_address_attributes: address
          }
        )
      end
      let(:result) { replace_country.send(:replace_country_iso_with_id, order_params, 'bill') }

      before { result }

      it 'will return hash contain country_id' do
        expect(result[:order][:bill_address_attributes][:country_id]).to eq country.id
      end

      it 'will return hash without country_iso' do
        expect(result[:order][:bill_address_attributes]).not_to include(:country_iso)
      end
    end
  end

  describe 'update address' do
    let(:order) { create(:order_with_line_items) }
    let(:state) { create(:state) }
    let(:country) { state.country }
    let(:update_service) { described_class.new }
    let(:address) do
      {
        firstname: 'John',
        lastname: 'Doe',
        address1: '7735 Old Georgetown Road',
        city: 'Bethesda',
        phone: '3014445002',
        zipcode: '20814',
        state_id: state.id,
        country_iso: country.iso
      }
    end
    let(:order_params) do
      ActionController::Parameters.new(
        order: {
          ship_address_attributes: address
        }
      )
    end
    let(:permitted_attributes) do
      Spree::PermittedAttributes.checkout_attributes + [
        bill_address_attributes: Spree::PermittedAttributes.address_attributes,
        ship_address_attributes: Spree::PermittedAttributes.address_attributes
      ]
    end

    it 'should set order back to address state' do
      expect(order.state).not_to eq 'address'
      expect(order.ship_address.state.id).not_to eq state.id

      update_service.send(:call, order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)

      expect(order.state).to eq 'address'
      expect(order.ship_address.state.id).to eq state.id
    end
  end

  describe 'update selected shipping rate' do
    let(:update_service) { described_class.new }
    let(:order) { create(:order_with_line_items) }
    let(:order_params) do
      ActionController::Parameters.new(
        order: {
          shipments_attributes: [
            {
              id: order.shipments.first.id,
              selected_shipping_rate_id: order.shipments.first.shipping_rates.first.id
            }
          ]
        }
      )
    end
    let(:permitted_attributes) do
      Spree::PermittedAttributes.checkout_attributes + [
        shipments_attributes: Spree::PermittedAttributes.shipment_attributes
      ]
    end

    it 'should set order back to delivery state' do
      expect(order.state).not_to eq 'delivery'

      update_service.send(:call, order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)

      expect(order.state).to eq 'delivery'
    end
  end
end


text:
/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#ifndef QT5XHB_MACROS_QTWEBVIEW_H
#define QT5XHB_MACROS_QTWEBVIEW_H

#endif /* QT5XHB_MACROS_QTWEBVIEW_H */


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuilderModel.Model
{
    public abstract class CarModel
    {
        //各个基本方法的执行顺序
        private List<string> Sequence = new List<string>();
        //模型是启动开始跑了
        protected abstract void Start();
        //能发动,还要能停下来,那才是真本事
        protected abstract void Stop();
        //喇叭会出声音,是滴滴叫,还是哔哔叫
        protected abstract void Alarm();
        //引擎会轰隆隆地响,不响那是假的
        protected abstract void EngineBoom();
        //那模型应该会跑吧,别管是人推的,还是电力驱动,总之要会跑
        public void Run()
        {
            for (int i = 0; i < this.Sequence.Count; i++)
            {
                string actionName = Sequence[i];
                if(actionName.Equals("start", StringComparison.OrdinalIgnoreCase))
                {
                    this.Start();
                }
                else if (actionName.Equals("stop", StringComparison.OrdinalIgnoreCase))
                {
                    this.Stop();
                }
                else if (actionName.Equals("alarm", StringComparison.OrdinalIgnoreCase))
                {
                    this.Alarm();
                }
                else if (actionName.Equals("engine boom", StringComparison.OrdinalIgnoreCase))
                {
                    this.EngineBoom();
                }
            }
            Console.WriteLine("------------------------------------");
        }
        //把传递过来的值传递到类内
        public void SetSequence(IEnumerable<string> sequence)
        {
            this.Sequence.Clear();
            this.Sequence.AddRange(sequence);
        }
    }
}


text:
package mesosphere.marathon.state

import com.codahale.metrics.MetricRegistry
import mesosphere.marathon.MarathonSpec
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.state.PathId._
import org.mockito.Matchers._
import org.mockito.Mockito._

import scala.concurrent.duration._
import scala.concurrent.{ Await, Future }
import scala.language.postfixOps

class AppRepositoryTest extends MarathonSpec {
  var metrics: Metrics = _

  before {
    metrics = new Metrics(new MetricRegistry)
  }

  test("App") {
    val path = "testApp".toRootPath
    val store = mock[MarathonStore[AppDefinition]]
    val timestamp = Timestamp.now()
    val appDef = AppDefinition(id = path, versionInfo = AppDefinition.VersionInfo.forNewConfig(timestamp))
    val future = Future.successful(Some(appDef))

    when(store.fetch(s"testApp:$timestamp")).thenReturn(future)

    val repo = new AppRepository(store, None, metrics)
    val res = repo.app(path, timestamp)

    assert(Some(appDef) == Await.result(res, 5.seconds), "Should return the correct AppDefinition")
    verify(store).fetch(s"testApp:$timestamp")
  }

  test("Store") {
    val path = "testApp".toRootPath
    val store = mock[MarathonStore[AppDefinition]]
    val appDef = AppDefinition(id = path)
    val future = Future.successful(appDef)
    val versionedKey = s"testApp:${appDef.version}"

    when(store.store(versionedKey, appDef)).thenReturn(future)
    when(store.store("testApp", appDef)).thenReturn(future)

    val repo = new AppRepository(store, None, metrics)
    val res = repo.store(appDef)

    assert(appDef == Await.result(res, 5.seconds), "Should return the correct AppDefinition")
    verify(store).store(versionedKey, appDef)
    verify(store).store(s"testApp", appDef)
  }

  test("AppIds") {
    val store = mock[MarathonStore[AppDefinition]]
    val future = Future.successful(Seq("app1", "app2", "app1:version", "app2:version"))

    when(store.names()).thenReturn(future)

    val repo = new AppRepository(store, None, metrics)
    val res = repo.allIds()

    assert(Seq("app1", "app2") == Await.result(res, 5.seconds), "Should return only unversioned names")
    verify(store).names()
  }

  test("Apps") {
    val store = mock[MarathonStore[AppDefinition]]
    val appDef1 = AppDefinition("app1".toPath)
    val appDef2 = AppDefinition("app2".toPath)
    val appDef1Old = appDef1.copy(
      versionInfo = AppDefinition.VersionInfo.forNewConfig(Timestamp(appDef1.version.toDateTime.minusDays(1)))
    )
    val appDef2Old = appDef2.copy(
      versionInfo = AppDefinition.VersionInfo.forNewConfig(Timestamp(appDef2.version.toDateTime.minusDays(1)))
    )
    val allApps = Seq(appDef1, appDef2, appDef1Old, appDef2Old)

    val future = Future.successful(Seq("app1", "app2") ++ allApps.map(x => s"${x.id}:${x.version}"))

    when(store.names()).thenReturn(future)
    when(store.fetch(appDef1.id.toString)).thenReturn(Future.successful(Some(appDef1)))
    when(store.fetch(appDef2.id.toString)).thenReturn(Future.successful(Some(appDef2)))

    val repo = new AppRepository(store, None, metrics)
    val res = repo.apps()

    assert(Seq(appDef1, appDef2) == Await.result(res, 5.seconds), "Should return only current versions")
    verify(store).names()
    verify(store).fetch(appDef1.id.toString)
    verify(store).fetch(appDef2.id.toString)
  }

  test("ListVersions") {
    val store = mock[MarathonStore[AppDefinition]]
    val appDef1 = AppDefinition("app1".toRootPath)
    val version1 = appDef1.copy(
      versionInfo = AppDefinition.VersionInfo.forNewConfig(Timestamp(appDef1.version.toDateTime.minusDays(1)))
    )
    val version2 = appDef1.copy(
      versionInfo = AppDefinition.VersionInfo.forNewConfig(Timestamp(appDef1.version.toDateTime.minusDays(2)))
    )
    val version3 = appDef1.copy(
      versionInfo = AppDefinition.VersionInfo.forNewConfig(Timestamp(appDef1.version.toDateTime.minusDays(3)))
    )
    val appDef2 = AppDefinition("app2".toRootPath)
    val allApps = Seq(appDef1, version1, version2, version3, appDef2)

    val future = Future.successful(Seq("app1", "app2") ++ allApps.map(x => s"${x.id.safePath}:${x.version}"))

    when(store.names()).thenReturn(future)

    val repo = new AppRepository(store, None, metrics)
    val res = repo.listVersions(appDef1.id)

    val expected = Seq(appDef1.version, version1.version, version2.version, version3.version)
    assert(expected == Await.result(res, 5.seconds), "Should return all versions of given app")
    verify(store).names()
  }

  test("Expunge") {
    val store = mock[MarathonStore[AppDefinition]]
    val appDef1 = AppDefinition("app1".toRootPath)
    val version1 = appDef1.copy(
      versionInfo = AppDefinition.VersionInfo.forNewConfig(Timestamp(appDef1.version.toDateTime.minusDays(1)))
    )
    val version2 = appDef1.copy(
      versionInfo = AppDefinition.VersionInfo.forNewConfig(Timestamp(appDef1.version.toDateTime.minusDays(2)))
    )
    val version3 = appDef1.copy(
      versionInfo = AppDefinition.VersionInfo.forNewConfig(Timestamp(appDef1.version.toDateTime.minusDays(3)))
    )
    val appDef2 = AppDefinition("app2".toRootPath)
    val allApps = Seq(appDef1, version1, version2, version3, appDef2)

    val future = Future.successful(Seq("app1", "app2") ++ allApps.map(x => s"${x.id.safePath}:${x.version}"))

    when(store.names()).thenReturn(future)
    when(store.expunge(any())).thenReturn(Future.successful(true))

    val repo = new AppRepository(store, None, metrics)
    val res = Await.result(repo.expunge(appDef1.id), 5.seconds).toSeq

    assert(res.size == 5, "Should expunge all versions")
    assert(res.forall(identity), "Should succeed")

    verify(store).names()
    verify(store).expunge("app1")
    for {
      app <- allApps
      if app.id.toString == "app1"
    } verify(store).expunge(s"${app.id}:${app.version}")
  }
}


text:
@implementation THStudentTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

        self.iconimage = [UIImage imageNamed:@"green_status"];
        UIImageView *icon = [[UIImageView alloc] initWithImage:self.iconimage];
        icon.frame = CGRectMake(screenW-10-30, (self.frame.size.height-30)/2, 30, 30);
        self.accessoryView = icon;

    }
    return self;
}

- (void)changeCellIconWith :(UIImage *)icon{
    self.iconimage = icon;
    UIImageView *iconView = [[UIImageView alloc] initWithImage:self.iconimage];
    self.accessoryView = iconView;
}

@end


text:
<theme>
  <name>alfresco</name>
  <description>alfresco</description>
  <properties/>
  <resource-bundle-rules/>
</theme>