text:
/*****************************************************************************
 * PRODUCT OF PT INOVACAO - EST DEPARTMENT and Aveiro University - Portugal)   *
 *****************************************************************************/

package gov.nist.javax.sdp.fields;

import java.util.Vector;
import javax.sdp.SdpException;
import javax.sdp.SdpParseException;
import gov.nist.core.NameValue;

/**
 * Precondition fields (segmented / end-to-end).
 *
 *
For one media description, precondition attributes should
 * be only of one type (segmented or end-to-end)

 *
3GPP TS 24.299,

 * IETF RFC3312 + RFC4032 (Precondition Mechanism).
 *
 * @author Miguel Freitas (IT) PT-Inovacao
 */

public class PreconditionFields
{

    // Media Description attributes for precondition
    protected Vector preconditionAttributes;

    /**
     * Constructor
     *
     */
    public PreconditionFields()
    {
        preconditionAttributes = new Vector();
    }

    /**
     * Get the number of Precondition attributes
     *
     * @return int size of segmented precondition vector of attribute fields
     */
    public int getPreconditionSize()
    {
        if (preconditionAttributes != null)
            return preconditionAttributes.size();

        else    // TODO treat this exception well
            return -1;
    }

    /**
     * Get Precondition
     *
     * @return Vector of attribute fields (segmented precondition)
     */
    public Vector getPreconditions()
    {
        return preconditionAttributes;
    }

    /**
     * Set Preconditions
     *
     * @param preconditions - vector with precondition attributes
     * @throws SdpException -- if precondition attributes is null
     */
    public void setPreconditions(Vector preconditions) throws SdpException
    {
        if (preconditions == null)
            throw new SdpException("Precondition attributes are null");
        else
            preconditionAttributes = preconditions;
    }

    /**
     *
Set attribute line for current precondition state, given
     * a string value encoded like the "curr" attribute value

     *
     * @param precondCurrValue - a string with the value for a "curr" attribute
     * @throws SdpException
     */
    public void setPreconditionCurr(String precondCurrValue) throws SdpException
    {
        if (precondCurrValue == null)
            throw new SdpException("The Precondition \"curr\" attribute value is null");
        else if (preconditionAttributes == null)
            throw new SdpException("The Precondition Attributes is null");
        else
        {
            try
            {
                /* split the "curr" attribute value into words
                 *      attributes[0] = "qos"
                 *      attributes[1] = status-type   (e2e/local/remote)
                 *      attributes[2] = direction-tag (none/send/recv/sendrecv)
                 *
                 * split() - regular expression:
                 *      \s -> a whitespace character [ \t\n\x0B\f\r]
                 *      \b -> a word boundary
                 */
                String[] attributes = precondCurrValue.split(" ");

                // which is this length?! of the string or the []?
                /*
                if (attributes.length < 3)
                {
                    throw new SdpException
                        ("The Precondition \"curr\" attribute value mal-formed (<3words)");
                }*/

                setPreconditionCurr(attributes[1],      // status-type
                                    attributes[2]       // direction-tag
                                );
            }
            catch (ArrayIndexOutOfBoundsException ex)
            {
                throw new SdpException
                    ("Error spliting the \"curr\" attribute into words", ex);
            }
        }
    }

    /**
     *
Set the value of the attributes with the name "curr"
     * for current precondition.

     *
- eg: a=curr:qos local none

     *
     *
If there is an attribute "curr" for the same status-type,
     * the direction-tag is updated with the one supplied.

     *
     * @param status - (local, remote, e2e)
     * @param directionTag - (none, send, recv, sendrecv)
     * @throws SdpParseException
     */
    public void setPreconditionCurr(String status, String directionTag)
        throws SdpException
    {
        if (status == null)
            throw new SdpException("The status-type is null");
        if (directionTag == null)
            throw new SdpException("The direction-tag is null");

        if (preconditionAttributes == null)
            throw new SdpException("Precondition Attributes is null");

        int i = 0;
        // search for attributes "curr"
        for (i = 0; i < preconditionAttributes.size(); i++)
        {
            AttributeField af =
                (AttributeField) this.preconditionAttributes.elementAt(i);

            // go to next attribute if this is not "curr"
            if (!af.getAttribute().getName().equals("curr"))
                continue;

            // if it is "curr" attribute, check the status-type
            // if it matches the value supplied, update the direction-tag
            // with the value supplied
            if (af.getValue().indexOf(status) != -1)
            {
                if (af.getValue().indexOf(directionTag) == -1)
                {
                    // attribute exists with same status, directionTag updated
                    af.setValue("qos " + status + " " + directionTag);
                    preconditionAttributes.setElementAt(af,i);
                }
                // else, exit and do nothing (attribute already exists)
                else
                    break;
            }
        }

        // attribute "curr" not found
        if (i == preconditionAttributes.size())
        {
            // create attribute for the status-type supplied
            NameValue nv = new NameValue("curr", "qos " + status + " " + directionTag);

            AttributeField newAF = new AttributeField();
            newAF.setAttribute(nv);
            preconditionAttributes.add(newAF);
        }
    }

    /**
     *
Set attribute line for desired precondition state, given
     * a string value encoded like the "des" attribute value

     *
     * @param precondDesValue - a string with the value for a "des" attribute
     * @throws SdpException
     */
    public void setPreconditionDes(String precondDesValue) throws SdpException
    {
        if (precondDesValue == null)
            throw new SdpException("The Precondition \"des\" attribute value is null");
        else if (preconditionAttributes == null)
            throw new SdpException("The Precondition Attributes is null");
        else
        {
            /* split the "des" attribute value into words
             *      attributes[0] = "qos"
             *      attributes[1] = strength-tag  (unknown/failure/none/optional/mandatory)
             *      attributes[2] = status-type   (e2e/local/remote)
             *      attributes[3] = direction-tag (none/send/recv/sendrecv)
             *
             * split() - regular expression:
             *      \s -> a whitespace character [ \t\n\x0B\f\r]
             *      \b -> a word boundary
             */
            try
            {
                String[] attributes = precondDesValue.split(" ");

                // which is this length?! of the string or the []?
                /*
                if (attributes.length < 4)
                {
                    throw new SdpException
                        ("The Precondition \"des\" attribute value mal-formed (<4words)");
                }*/

                setPreconditionDes( attributes[1],      // strength-tag
                                    attributes[2],      // status-type
                                    attributes[3]       // direction-tag
                                );
            }
            catch (ArrayIndexOutOfBoundsException ex)
            {
                throw new SdpException
                    ("Error spliting the \"des\" attribute into words", ex);
            }
        }
    }

    /**
     *
Set the value of the attributes with the name "des"
     * for desired precondition.

     *
- eg: a=des:qos mandatory remote sendrecv

     *
     *
There can be more than one desired precondition line
     * for a status-type, specially if strength-tag is different.

     *
     *
If there is an attribute "des" for the same status-type,
     * the strength-tag and direction-tag are updated with the
     * ones supplied.

     *
     *
IETF RFC4032: strength should only be downgraded within SDP offers

     *
     *
     * @param strength - (none, optional,
     * @param status - (local, remote, e2e)
     * @param direction - (none, send, recv, sendrecv)
     * @throws SdpParseException
     */
    public void setPreconditionDes(String strength, String status, String direction)
        throws SdpException
    {
        if (strength == null)
            throw new SdpException("The strength-tag is null");
        if (status == null)
            throw new SdpException("The status-type is null");
        if (direction == null)
            throw new SdpException("The direction-tag is null");

        if (preconditionAttributes == null)
            throw new SdpException("Precondition Attributes is null");

        int i = 0;
        // search for attributes "des"
        for (i = 0; i < preconditionAttributes.size(); i++)
        {
            AttributeField af =
                (AttributeField) this.preconditionAttributes.elementAt(i);

            // go to next attribute if this is not "des"
            if (!af.getAttribute().getName().equals("des"))
                continue;

            // if it is "des" attribute, check the status-type
            // if it match, update the strength-tag and direction-tag
            if (af.getValue().indexOf(status) != -1)
            {
                // attribute exists with same status-type,
                // strength-tag and direction-tag updated
                af.setValue("qos " + strength + " " + status + " " + direction);
                preconditionAttributes.setElementAt(af,i);

            }
        }

        // attribute "des" not found
        if (i == preconditionAttributes.size())
        {
            // create attribute for the status-type supplied
            // with the values strength-tag and direction-tag
            NameValue nv =
                new NameValue("des", "qos " + strength + " " + status + " " + direction);

            AttributeField newAF = new AttributeField();
            newAF.setAttribute(nv);
            preconditionAttributes.add(newAF);
        }
    }

    /**
     *
Set attribute line for confirmation precondition request, given
     * a string value encoded like the "conf" attribute value

     *
     * @param precondConfValue - a string with the value for a "conf" attribute
     * @throws SdpException
     */
    public void setPreconditionConfirmStatus(String precondConfValue)
        throws SdpException
    {
        if (precondConfValue == null || precondConfValue.length()==0)
            throw new SdpException("The Precondition \"conf\" attribute value is null");
        else if (preconditionAttributes == null)
            throw new SdpException("The Precondition Attributes is null");
        else
        {
            /* split the "conf" attribute value into words
             *      attributes[0] = "qos"
             *      attributes[1] = status-type   (e2e/local/remote)
             *      attributes[2] = direction-tag (none/send/recv/sendrecv)
             */
            try
            {
                String[] attributes = precondConfValue.split(" ");

                setPreconditionConfirmStatus(
                                    attributes[1],      // status-type
                                    attributes[2]       // direction-tag
                                );
            }
            catch (ArrayIndexOutOfBoundsException ex)
            {
                throw new SdpException
                    ("Error spliting the \"conf\" attribute into words", ex);
            }
        }
    }

    /**
     *
IETF RFC3312

     *
"The confirmation status attribute carries threshold conditions
     * for a media stream. When the status of network resources reach
     * these conditions, the peer UA will send an update of the
     * session description".

     *
     *
- eg: a=conf:qos remote sendrecv

     *
     * @param status - (e2e, local, remote)
     * @param direction - (none, send, recv, sendrecv)
     * @throws SdpException -- if param are null
     */
    public void setPreconditionConfirmStatus(String status, String direction)
        throws SdpException
    {
        if (status == null || direction.length()==0)
            throw new SdpException("The status-type is null");
        if (direction == null || direction.length()==0)
            throw new SdpException("The direction-tag is null");

        if (preconditionAttributes == null)
            throw new SdpException("Precondition Attributes is null");

        int i = 0;
        // search for attributes "conf"
        for (i = 0; i < preconditionAttributes.size(); i++)
        {
            AttributeField af =
                (AttributeField) this.preconditionAttributes.elementAt(i);

            //System.out.println("--> PreconditionField -> (i="+i+") > attribute field: " + af.toString());

            // go to next attribute if this is not "conf"
            if (!af.getAttribute().getName().equals("conf"))
                continue;

            // if it is "conf" attribute, check the status-type
            // if it matches, update the direction-tag
            // with the value supplied
            if (af.getValue().indexOf(status) != -1)
            {
                if (af.getValue().indexOf(direction) == -1)
                {
                    // attribute exists with same status, directionTag updated
                    af.setValue("qos " + status + " " + direction);
                    preconditionAttributes.setElementAt(af,i);
                }
                // else, exit and do nothing (attribute already exists)
                break;
            }
        }

        // attribute "conf" not found
        if (i == preconditionAttributes.size())
        {
            // create attribute for the status-type supplied
            // with the values strength-tag and direction-tag
            NameValue nv =
                new NameValue("conf", "qos " + status + " " + direction);

            AttributeField newAF = new AttributeField();
            newAF.setAttribute(nv);
            preconditionAttributes.add(newAF);

            //System.out.println("--> PreconditionField -> new \"conf\" attribute created: " + newAF.toString() );
        }
    }

    /**
     *
Get the attribute fields with the name "curr"
     * for current precondition.

     *
One attribute field per status-type.
     * (eg: a=curr:qos local none)

     *
     * @param status - (local, remote, e2e)
     * @return a vector with the attribute field that match status-type
     * (with only one element or null if none exists)
     * @throws SdpParseException
     */
    public Vector getPreconditionCurr(String status)
        throws SdpException, SdpParseException
    {
        if (status == null)
            throw new SdpException("The status-type is null");

        if (preconditionAttributes == null)
            return null;
        else
        {
            Vector vCurr = new Vector();
            for (int i=0; i < preconditionAttributes.size(); i++)
            {
                AttributeField af =
                    (AttributeField) this.preconditionAttributes.elementAt(i);

                // go to next attribute if this is not "curr"
                if (!af.getAttribute().getName().equals("curr"))
                    continue;

                // if it is "curr" attribute, check the status-type
                // and add the attribute value to the vector if it
                // matches the status desired
                if (af.getValue().indexOf(status) != -1)
                    vCurr.addElement(af);
            }

            // if none "curr" attribute found
            if (vCurr.size() == 0)
                return null;
            else
                return vCurr;
        }
    }

    /**
     *
Get the attribute fields with the name "des"
     * for desired precondition

     *
     *
There can be more than one current precondition line
     * for a status-type (with different direction-tag values),
     * specially if strength-tag is different

     *
     * @param status - (local, remote, e2e)
     * @return a vector with the attribute fields that match location-tag
     * @throws SdpParseException
     */
    public Vector getPreconditionDes(String status)
        throws SdpException, SdpParseException
    {
        if (status == null)
            throw new SdpException("The status-type is null");

        if (preconditionAttributes == null)
            return null;
        else
        {
            Vector vCurr = new Vector();
            for (int i=0; i < preconditionAttributes.size(); i++)
            {
                AttributeField af =
                    (AttributeField) this.preconditionAttributes.elementAt(i);

                // go to next attribute if this is not "des"
                if (!af.getAttribute().getName().equals("des"))
                    continue;

                // if it is "des" attribute, check the status-type
                // and add the attribute value to the vector if it
                // matches the status desired
                if (af.getValue().indexOf(status) != -1)
                    vCurr.addElement(af);
            }

            // if none "des" attribute found
            if (vCurr.size() == 0)
                return null;
            else
                return vCurr;
        }
    }

    /**
     *
Get the attribute fields with the name "conf"
     * for confirmation precondition.

     *
     *
IETF RFC3312

     *
"The confirmation status attribute carries threshold conditions
     * for a media stream. When the status of network resources reach
     * these conditions, the peer UA will send an update of the
     * session description".

     *
     *
(eg: a=conf:qos remote sendrecv)

     *
     * @return a vector with the "conf" attribute fields
     * @throws SdpException
     */
    public Vector getPreconditionConfirmStatus() throws SdpException
    {
        if (preconditionAttributes == null)
            return null;        // ignore or send SdpException?
        else
        {
            Vector vCurr = new Vector();
            for (int i=0; i < preconditionAttributes.size(); i++)
            {
                AttributeField af =
                    (AttributeField) this.preconditionAttributes.elementAt(i);

                // go to next attribute if this is not "conf"
                if (!af.getAttribute().getName().equals("conf"))
                    continue;
                else
                    // add the attribute value to the vector
                    vCurr.addElement(af);
            }

            // if none "conf" attribute found
            if (vCurr.size() == 0)
                return null;
            else
                return vCurr;
        }
    }

    /* strength-tag */
    public static final int STRENGTH_UNKNOWN    = 0;
    public static final int STRENGTH_FAILURE    = 1;
    public static final int STRENGTH_NONE       = 2;
    public static final int STRENGTH_OPTIONAL   = 3;
    public static final int STRENGTH_MANDATORY  = 4;
    public static final String[] STRENGTH = { "unknown",
                                                  "failure",
                                                  "none",
                                                  "optional",
                                                  "mandatory"
                                            };
    /* direction-tag */
    public static final int DIRECTION_NONE      = 0;
    public static final int DIRECTION_SEND      = 1;
    public static final int DIRECTION_RECV      = 2;
    public static final int DIRECTION_SENDRECV  = 3;
    public static final String[] DIRECTION = { "none",
                                                  "send",
                                                  "recv",
                                                  "sendrecv"
                                            };

    /* status-tag */
    public static final int STATUS_E2E      = 0;
    public static final int STATUS_LOCAL    = 1;
    public static final int STATUS_REMOTE   = 2;
    public static final String[] STATUS = { "e2e",
                                            "local",
                                            "remote"
                                            };

    /* precondition type */
    public static final int PRECONDITION_QOS    = 0;
    public static final String[] PRECONDITION   = { "qos"
                                                };

}


text:
require 'catmother/opcode_groups/no_operands'

module CatMother
  module Opcode
    class Aastore
      MNEMONIC = "aastore"
      OPCODE = 0x53
      OPERANDS = 0
      POPS = 3
      PUSHES = 0
      SHORT_DESCRIPTION = "Store into reference array"
      DESCRIPTION = ""

      include CatMother::OpcodeGroup::NoOperands

      def initialize(io, pc)
        parse_operands(io, pc)
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package hybrid

import (
	"errors"

	"circl/internal/sha3"
	"circl/kem"
	"circl/kem/kyber/kyber1024"
	"circl/kem/kyber/kyber512"
	"circl/kem/kyber/kyber768"
)

var ErrUninitialized = errors.New("public or private key not initialized")

// Returns the hybrid KEM of Kyber512 and X25519.
func Kyber512X25519() kem.Scheme { return kyber512X }

// Returns the hybrid KEM of Kyber768 and X25519.
func Kyber768X25519() kem.Scheme { return kyber768X }

// Returns the hybrid KEM of Kyber768 and X448.
func Kyber768X448() kem.Scheme { return kyber768X4 }

// Returns the hybrid KEM of Kyber1024 and X448.
func Kyber1024X448() kem.Scheme { return kyber1024X }

var kyber512X kem.Scheme = &scheme{
	"Kyber512-X25519",
	x25519Kem,
	kyber512.Scheme(),
}

var kyber768X kem.Scheme = &scheme{
	"Kyber768-X25519",
	x25519Kem,
	kyber768.Scheme(),
}

var kyber768X4 kem.Scheme = &scheme{
	"Kyber768-X448",
	x448Kem,
	kyber768.Scheme(),
}

var kyber1024X kem.Scheme = &scheme{
	"Kyber1024-X448",
	x448Kem,
	kyber1024.Scheme(),
}

// Public key of a hybrid KEM.
type publicKey struct {
	scheme *scheme
	first  kem.PublicKey
	second kem.PublicKey
}

// Private key of a hybrid KEM.
type privateKey struct {
	scheme *scheme
	first  kem.PrivateKey
	second kem.PrivateKey
}

// Scheme for a hybrid KEM.
type scheme struct {
	name   string
	first  kem.Scheme
	second kem.Scheme
}

func (sch *scheme) Name() string { return sch.name }
func (sch *scheme) PublicKeySize() int {
	return sch.first.PublicKeySize() + sch.second.PublicKeySize()
}

func (sch *scheme) PrivateKeySize() int {
	return sch.first.PrivateKeySize() + sch.second.PrivateKeySize()
}

func (sch *scheme) SeedSize() int {
	first := sch.first.SeedSize()
	second := sch.second.SeedSize()
	ret := second
	if first > second {
		ret = first
	}
	return ret
}

func (sch *scheme) SharedKeySize() int {
	return sch.first.SharedKeySize() + sch.second.SharedKeySize()
}

func (sch *scheme) CiphertextSize() int {
	return sch.first.CiphertextSize() + sch.second.CiphertextSize()
}

func (sch *scheme) EncapsulationSeedSize() int {
	first := sch.first.EncapsulationSeedSize()
	second := sch.second.EncapsulationSeedSize()
	ret := second
	if first > second {
		ret = first
	}
	return ret
}

func (sk *privateKey) Scheme() kem.Scheme { return sk.scheme }
func (pk *publicKey) Scheme() kem.Scheme  { return pk.scheme }

func (sk *privateKey) MarshalBinary() ([]byte, error) {
	if sk.first == nil || sk.second == nil {
		return nil, ErrUninitialized
	}
	first, err := sk.first.MarshalBinary()
	if err != nil {
		return nil, err
	}
	second, err := sk.second.MarshalBinary()
	if err != nil {
		return nil, err
	}
	return append(first, second...), nil
}

func (sk *privateKey) Equal(other kem.PrivateKey) bool {
	oth, ok := other.(*privateKey)
	if !ok {
		return false
	}
	if sk.first == nil && sk.second == nil && oth.first == nil && oth.second == nil {
		return true
	}
	if sk.first == nil || sk.second == nil || oth.first == nil || oth.second == nil {
		return false
	}
	return sk.first.Equal(oth.first) && sk.second.Equal(oth.second)
}

func (sk *privateKey) Public() kem.PublicKey {
	return &publicKey{sk.scheme, sk.first.Public(), sk.second.Public()}
}

func (pk *publicKey) Equal(other kem.PublicKey) bool {
	oth, ok := other.(*publicKey)
	if !ok {
		return false
	}
	if pk.first == nil && pk.second == nil && oth.first == nil && oth.second == nil {
		return true
	}
	if pk.first == nil || pk.second == nil || oth.first == nil || oth.second == nil {
		return false
	}
	return pk.first.Equal(oth.first) && pk.second.Equal(oth.second)
}

func (pk *publicKey) MarshalBinary() ([]byte, error) {
	if pk.first == nil || pk.second == nil {
		return nil, ErrUninitialized
	}
	first, err := pk.first.MarshalBinary()
	if err != nil {
		return nil, err
	}
	second, err := pk.second.MarshalBinary()
	if err != nil {
		return nil, err
	}
	return append(first, second...), nil
}

func (sch *scheme) GenerateKeyPair() (kem.PublicKey, kem.PrivateKey, error) {
	pk1, sk1, err := sch.first.GenerateKeyPair()
	if err != nil {
		return nil, nil, err
	}
	pk2, sk2, err := sch.second.GenerateKeyPair()
	if err != nil {
		return nil, nil, err
	}

	return &publicKey{sch, pk1, pk2}, &privateKey{sch, sk1, sk2}, nil
}

func (sch *scheme) DeriveKeyPair(seed []byte) (kem.PublicKey, kem.PrivateKey) {
	if len(seed) != sch.SeedSize() {
		panic(kem.ErrSeedSize)
	}
	h := sha3.NewShake256()
	_, _ = h.Write(seed)
	first := make([]byte, sch.first.SeedSize())
	second := make([]byte, sch.second.SeedSize())
	_, _ = h.Read(first)
	_, _ = h.Read(second)

	pk1, sk1 := sch.first.DeriveKeyPair(first)
	pk2, sk2 := sch.second.DeriveKeyPair(second)

	return &publicKey{sch, pk1, pk2}, &privateKey{sch, sk1, sk2}
}

func (sch *scheme) Encapsulate(pk kem.PublicKey) (ct, ss []byte, err error) {
	pub, ok := pk.(*publicKey)
	if !ok {
		return nil, nil, kem.ErrTypeMismatch
	}

	ct1, ss1, err := sch.first.Encapsulate(pub.first)
	if err != nil {
		return nil, nil, err
	}

	ct2, ss2, err := sch.second.Encapsulate(pub.second)
	if err != nil {
		return nil, nil, err
	}

	return append(ct1, ct2...), append(ss1, ss2...), nil
}

func (sch *scheme) EncapsulateDeterministically(
	pk kem.PublicKey, seed []byte,
) (ct, ss []byte, err error) {
	if len(seed) != sch.EncapsulationSeedSize() {
		return nil, nil, kem.ErrSeedSize
	}

	h := sha3.NewShake256()
	_, _ = h.Write(seed)
	first := make([]byte, sch.first.EncapsulationSeedSize())
	second := make([]byte, sch.second.EncapsulationSeedSize())
	_, _ = h.Read(first)
	_, _ = h.Read(second)

	pub, ok := pk.(*publicKey)
	if !ok {
		return nil, nil, kem.ErrTypeMismatch
	}

	ct1, ss1, err := sch.first.EncapsulateDeterministically(pub.first, first)
	if err != nil {
		return nil, nil, err
	}
	ct2, ss2, err := sch.second.EncapsulateDeterministically(pub.second, second)
	if err != nil {
		return nil, nil, err
	}
	return append(ct1, ct2...), append(ss1, ss2...), nil
}

func (sch *scheme) Decapsulate(sk kem.PrivateKey, ct []byte) ([]byte, error) {
	if len(ct) != sch.CiphertextSize() {
		return nil, kem.ErrCiphertextSize
	}

	priv, ok := sk.(*privateKey)
	if !ok {
		return nil, kem.ErrTypeMismatch
	}

	firstSize := sch.first.CiphertextSize()
	ss1, err := sch.first.Decapsulate(priv.first, ct[:firstSize])
	if err != nil {
		return nil, err
	}
	ss2, err := sch.second.Decapsulate(priv.second, ct[firstSize:])
	if err != nil {
		return nil, err
	}
	return append(ss1, ss2...), nil
}

func (sch *scheme) UnmarshalBinaryPublicKey(buf []byte) (kem.PublicKey, error) {
	if len(buf) != sch.PublicKeySize() {
		return nil, kem.ErrPubKeySize
	}
	firstSize := sch.first.PublicKeySize()
	pk1, err := sch.first.UnmarshalBinaryPublicKey(buf[:firstSize])
	if err != nil {
		return nil, err
	}
	pk2, err := sch.second.UnmarshalBinaryPublicKey(buf[firstSize:])
	if err != nil {
		return nil, err
	}
	return &publicKey{sch, pk1, pk2}, nil
}

func (sch *scheme) UnmarshalBinaryPrivateKey(buf []byte) (kem.PrivateKey, error) {
	if len(buf) != sch.PrivateKeySize() {
		return nil, kem.ErrPrivKeySize
	}
	firstSize := sch.first.PrivateKeySize()
	sk1, err := sch.first.UnmarshalBinaryPrivateKey(buf[:firstSize])
	if err != nil {
		return nil, err
	}
	sk2, err := sch.second.UnmarshalBinaryPrivateKey(buf[firstSize:])
	if err != nil {
		return nil, err
	}
	return &privateKey{sch, sk1, sk2}, nil
}


text:
<!doctype html>

    <title>Code coverage report for lib/reporter.js</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../prettify.css">
    <link rel="stylesheet" href="../base.css">

Code coverage report for lib/reporter.js

        Statements: 85% (85 / 100)
        Branches: 67.5% (27 / 40)
        Functions: 100% (19 / 19)
        Lines: 85% (85 / 100)
        Ignored: none

All files » lib/ » reporter.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226	1
1
1
1
1

1
19

1
1
1

1

1
8

8
8

1
8

8
8

8
8

1
21

21

21
21
2

19
19

19

19
19

19
19

19

19
19
78

19

19
19

19
19

19
19

19
19
19
19

19
19
19
19

19

19

19
19

1

92
92

92
28
223
223

92
8
8

92
74

92
92

92

92

1

27
27

27
27

27
27

27
27
87

27

27

var moment = require('moment');
var async = require('async');
var auth = require('./../webserver/routes/web-auth-route');
var utils = require('./utils');
var debug = require('debug')('reporter');

function Reporter (storage){
  this.storage = storage;
}

var HOUR = 1000 * 60 * 60;
var DAY = HOUR * 24;
var WEEK = DAY * 7;

exports = module.exports = Reporter;

/**
 * Basic report for services
 *
 * @param options
 * @param callback
 */

Reporter.prototype.getServices = function(options, callback){
  var storage = this.storage;

  debug('loading services');
  storage.getServices(options, function(err, services){

    function getInfo(service, cb){
      getGeneralServiceInfo(service, storage, cb);
    }

    async.mapSeries(services, getInfo, function(err, servicesData){
      Iif (err) {
        return callback(err);
      }
      debug('services loaded');
      callback(err, servicesData);
    });
  });
};

/**
 * Returns service reporting info
 *
 * @param serviceId
 * @param callback
 * @returns {*}
 */

Reporter.prototype.getService = function(serviceId, callback){
  var storage = this.storage;

  debug('loading service');

  storage.getService(serviceId, function(err, service){
    if (err || !service) {
      return callback(err, service);
    }

    getGeneralServiceInfo(service, storage, function(err, serviceData){
      Iif (err) {
        return callback(err);
      }

      Iif (!serviceData) {
        return callback(null, null);
      }

      var lastWeek = +new Date() - WEEK;
      var lastHour = +new Date() - HOUR;

      storage.getServiceOutagesSince(service, lastWeek, function(err, outagesLastWeek){
        Iif (err) {
          return callback(err);
        }

        var uptimeInfoLastWeek = getUptime(service, outagesLastWeek,
          serviceData.status.currentOutage, lastWeek);

        var now = +new Date();
        var outagesLastHour = outagesLastWeek.filter(function(outage){
          return outage.timestamp >= now - HOUR;
        });

        var uptimeInfoLastHour = getUptime(service, outagesLastHour,
            serviceData.status.currentOutage, lastHour);

        storage.getLatencySince(serviceData.service, +new Date() - WEEK, 'day', function(err, latencyLastWeek){
          Iif (err) {
            return callback(err);
          }

          storage.getLatencySince(serviceData.service, +new Date() - DAY, 'hour', function(err, latencyLast24Hours){
          Iif (err) {
            return callback(err);
          }

            storage.getLatencySince(serviceData.service, +new Date() - HOUR, 'minute', function(err, latencyLastHour) {
              Iif (err) {
                return callback(err);
              }

              serviceData.status.lastWeek = serviceData.status.lastWeek || {};
              serviceData.status.lastWeek.outages = outagesLastWeek;
              serviceData.status.lastWeek.latency = latencyLastWeek;
              serviceData.status.lastWeek.uptime = uptimeInfoLastWeek.uptime;

              serviceData.status.lastHour = serviceData.status.lastHour || {};
              serviceData.status.lastHour.outages = outagesLastHour;
              serviceData.status.lastHour.latency = latencyLastHour;
              serviceData.status.lastHour.uptime = uptimeInfoLastHour.uptime;

              // rest of the properties for the last 24h are populated in getGeneralServiceInfo
              serviceData.status.last24Hours.latency = latencyLast24Hours;

              serviceData.status.latestOutages = outagesLastWeek.slice(0, 10); // max 10

              debug('service loaded');
              callback(err, serviceData);
            });
          });
        });
      });
    });
  });
};

/**
 * Calculate uptime since a certain data based on a list of outages
 *
 * @param outages
 * @param currentOutage
 * @param since
 * @return {
 *    totalDownTime: <int> ms
 *    uptime: <int>
 * }
 */
function getUptime (service, outages, currentOutage, since) {

  var totalDownTime = 0;
  var now = +new Date();

  if (outages.length) {
    outages.forEach(function(outage) {
      Eif (outage.timestamp >= since) {
        totalDownTime += outage.downtime;
      }
    });
  }

  if (currentOutage) {
    Eif (currentOutage.timestamp >= since) {
      totalDownTime += (now - currentOutage.timestamp);
    } else {
      totalDownTime += (now - since);
    }
  }

  if (service.created > since){
    since = service.created;
  }

  var totalTime = now - since;
  var uptime = utils.round((totalTime - totalDownTime) * 100 / totalTime, 3);

  Iif (uptime < 0 || uptime > 100) {
    console.error('Invalid uptime:');
    console.error('totalTime:', totalTime);
    console.error('currentOutage:', currentOutage);
    console.error('uptime:', uptime);
    console.error('totalDownTime:', totalDownTime);
  }

  return {
    uptime: uptime,
    totalDownTime : totalDownTime
  }
}

function getGeneralServiceInfo(service, storage, callback) {

  storage.getCurrentOutage(service, function(err, currentOutage){
    Iif (err) {
      return callback(err);
    }

    var last24H = +new Date() - DAY;
    var lastWeek = +new Date() - WEEK;

    storage.getServiceOutagesSince(service, lastWeek, function(err, outagesLastWeek){
      Iif (err) {
        return callback(err);
      }

      var uptimeInfoLastWeek = getUptime(service, outagesLastWeek, currentOutage, lastWeek);
      var outagesLast24Hours = outagesLastWeek.filter(function(outage){
        return outage.timestamp >= last24H;
      });
      var uptimeInfoLast24Hours = getUptime(service, outagesLast24Hours, currentOutage, last24H);

      return callback(null, {
        service: service,
        status: {
          currentOutage: currentOutage,
          last24Hours: {
            outages: outagesLast24Hours,
            numberOutages: outagesLast24Hours.length,
            downtime: uptimeInfoLast24Hours.totalDownTime,
            uptime: uptimeInfoLast24Hours.uptime
          },
          lastWeek: {
            outages: outagesLastWeek,
            numberOutages: outagesLastWeek.length,
            downtime: uptimeInfoLastWeek.totalDownTime,
            uptime: uptimeInfoLastWeek.uptime
          }
        }
      });
    });
  });
}

Generated by istanbul at Sat Jul 04 2015 13:46:27 GMT+0200 (CEST)


text:
<?php

namespace ZendTest\Mvc\Controller\Plugin;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\Mvc\Controller\Plugin\Layout as LayoutPlugin;
use Zend\Mvc\MvcEvent;
use ZendTest\Mvc\Controller\TestAsset\SampleController;
use Zend\View\Model\ViewModel;

class LayoutTest extends TestCase
{
    public function setUp()
    {
        $this->event      = $event = new MvcEvent();
        $this->controller = new SampleController();
        $this->controller->setEvent($event);

        $this->plugin = $this->controller->plugin('layout');
    }

    public function testPluginWithoutControllerRaisesDomainException()
    {
        $plugin = new LayoutPlugin();
        $this->setExpectedException('Zend\Mvc\Exception\DomainException', 'requires a controller');
        $plugin->setTemplate('home');
    }

    public function testSetTemplateAltersTemplateInEventViewModel()
    {
        $model = new ViewModel();
        $model->setTemplate('layout');
        $this->event->setViewModel($model);

        $this->plugin->setTemplate('alternate/layout');
        $this->assertEquals('alternate/layout', $model->getTemplate());
    }

    public function testInvokeProxiesToSetTemplate()
    {
        $model = new ViewModel();
        $model->setTemplate('layout');
        $this->event->setViewModel($model);

        $plugin = $this->plugin;
        $plugin('alternate/layout');
        $this->assertEquals('alternate/layout', $model->getTemplate());
    }

    public function testCallingInvokeWithNoArgumentsReturnsViewModel()
    {
        $model = new ViewModel();
        $model->setTemplate('layout');
        $this->event->setViewModel($model);

        $plugin = $this->plugin;
        $result = $plugin();
        $this->assertSame($model, $result);
    }
}


text:
/* globals window $*/
/* eslint-disable no-var */
/* eslint-disable no-use-before-define */

var app = app || {};

/* eslint-enable no-var */
/* eslint-enable no-use-before-define */

$("#tb-update-profile").on("click", () => {
    const firstName = $("#tb-first-name").val();
    const lastName = $("#tb-last-name").val();
    const city = $("#tb-city").val();
    const email = $("#tb-email").val();
    const contact = $("#tb-contact").val();

    const data = {
        firstName,
        lastName,
        city,
        email,
        contact
    };

    if (app.validator.validateUpdateProfile(data)) {
        app.requester.put("/profile/update-info", data)
            .then(response => {
                let parsedResponce = JSON.parse(response);

                if (parsedResponce.success) {
                    app.notificator.showNotification(parsedResponce.success, "success");
                    setTimeout(() => {
                        window.location.href = "/profile";
                    }, 1500);
                } else if (parsedResponce.error) {
                    app.notificator.showNotification(parsedResponce.error, "error");
                }
            })
            .catch(err => {
                let parsedError = JSON.parse(err.responseJSON);
                app.notificator.showNotification(parsedError.error, "error");
            });
    }
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Tom Schuermans - GitHub - Version controlled user group meetups</title>
    <link rel="stylesheet" href="//cdn.jsdelivr.net/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha256-916EbMg70RQy9LHiGkXzG8hSg9EdNy97GazNG/aiY1w=" crossorigin="anonymous">
    <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Raleway:700|Sanchez">
    <link rel="stylesheet" href="/style.css">
    <link rel="canonical" href="https://tschuermans.be/github-version-controlled-user-group-meetups.html">
    <meta name="description" content="GitHub - Version controlled user group meetups" />
    <meta property="og:title" content="Tom Schuermans" />
    <meta property="og:description" content="GitHub - Version controlled user group meetups" />
    <meta property="og:url" content="https://tschuermans.be/github-version-controlled-user-group-meetups.html" />
    <meta property="og:type" content="blog" />

Tom Schuermans

GitHub - Version controlled user group meetups

At Nucleus (my employer), we try to host monthly user group meetups.
When I recently contacted the Fronteers user group to plan a meetup at
our office, I noticed that they were using GitHub issues to plan the
whole thing.

This concept was nice and easy to adapt, so we did. Currently, we are
using GitHub issues to plan every meetup at our office. Each issue
contains all details on the meetup (talks, links, rsvp rate, …) and a
list of tasks which have to be completed.

You might think this is a hassle, but using the new issue templates,
this process is a breeze. User groups can now create an issue to
plan/discuss future meetups at our office. One of the main advantages is
stepping away from email to communicate on all the details/logistics.
Everyone can track all communication as it's publicly available in the
issue.

Looking for a location?

Are you part of a tech related user group and are you still looking for
a location to host your next meetup? Go to our official repository
and create a new issue, it's that easy. We offer room for about 50
attendees and will provide food and drinks.

tschuermans.be


text:
#ifndef __SOLTRACK_H
#define __SOLTRACK_H

#include "stdio.h"
#include "math.h"

// Constants:
#define PI             3.14159265358979323846    // Pi
#define TWO_PI         6.28318530717958647693    // 2 pi
#define MPI            3.14159265358979323846e6  // One Megapi...
#define R2D            57.2957795130823208768    // Radians to degrees conversion factor
#define R2H            3.81971863420548805845    // Radians to hours conversion factor

// Structs:

/// @brief Date and time to compute the Sun's position for, in UT
struct Time {
  int year,month,day,  hour,minute;
  double second;
};

/// @brief Location to compute the Sun's position for
struct Location {
  double longitude, latitude;
  double sinLat, cosLat;
  double pressure, temperature;
};

/// @brief Position of the Sun
struct Position {
  double julianDay, tJD, tJC,tJC2;
  double longitude, distance;
  double obliquity,cosObliquity, nutationLon;
  double rightAscension,declination, hourAngle,agst;
  double altitude, altitudeRefract,azimuthRefract;
  double hourAngleRefract, declinationRefract;
};

/// @brief Rise and set data for the Sun
struct RiseSet {
  double riseTime, transitTime, setTime;
  double riseAzimuth, transitAltitude, setAzimuth;
};

// Function prototypes:
void SolTrack(struct Time time, struct Location location, struct Position *position,  int useDegrees, int useNorthEqualsZero, int computeRefrEquatorial, int computeDistance);
double computeJulianDay(int year, int month, int day,  int hour, int minute, double second);
void computeLongitude(int computeDistance, struct Position *position);
void convertEclipticToEquatorial(double longitude, double cosObliquity,  double *rightAscension, double *declination);
void convertEquatorialToHorizontal(struct Location location, struct Position *position);
void eq2horiz(double sinLat, double cosLat, double longitude,  double rightAscension, double declination,   double agst, double *azimuth, double *sinAlt);
void convertHorizontalToEquatorial(double sinLat, double cosLat, double azimuth, double altitude, double *hourAngle, double *declination);
void setNorthToZero(double *azimuth, double *hourAngle, int computeRefrEquatorial);
void convertRadiansToDegrees(double *longitude,  double *rightAscension, double *declination,  \
			     double *altitude, double *azimuthRefract, double *altitudeRefract,  \
			     double *hourAngle, double *declinationRefract, int computeRefrEquatorial);
double STatan2(double y, double x);

void SolTrack_RiseSet(struct Time time,  struct Location location, struct Position *position, struct RiseSet *riseSet, double sa0, int useDegrees, int useNorthEqualsZero);
double rev(double angle);
double rev2(double angle);
#endif


text:
 #define LCIM_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
#endif

#if LCIM_USE_PROTOBUF_FRAMEWORK_IMPORTS
 #import <Protobuf/LCIMProtocolBuffers.h>
#else
 #import "LCIMProtocolBuffers.h"
#endif

#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
#endif

// @@protoc_insertion_point(imports)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

CF_EXTERN_C_BEGIN

NS_ASSUME_NONNULL_BEGIN

#pragma mark - GPBDurationRoot

/// Exposes the extension registry for this file.
///
/// The base class provides:
/// @code
///   + (LCIMExtensionRegistry *)extensionRegistry;
/// @endcode
/// which is a @c LCIMExtensionRegistry that includes all the extensions defined by
/// this file and all files that it depends on.
@interface LCIMDurationRoot : LCIMRootObject
@end

#pragma mark - GPBDuration

typedef GPB_ENUM(GPBDuration_FieldNumber) {
  GPBDuration_FieldNumber_Seconds = 1,
  GPBDuration_FieldNumber_Nanos = 2,
};

/// A Duration represents a signed, fixed-length span of time represented
/// as a count of seconds and fractions of seconds at nanosecond
/// resolution. It is independent of any calendar and concepts like "day"
/// or "month". It is related to Timestamp in that the difference between
/// two Timestamp values is a Duration and it can be added or subtracted
/// from a Timestamp. Range is approximately +-10,000 years.
///
/// Example 1: Compute Duration from two Timestamps in pseudo code.
///
///     Timestamp start = ...;
///     Timestamp end = ...;
///     Duration duration = ...;
///
///     duration.seconds = end.seconds - start.seconds;
///     duration.nanos = end.nanos - start.nanos;
///
///     if (duration.seconds < 0 && duration.nanos > 0) {
///       duration.seconds += 1;
///       duration.nanos -= 1000000000;
///     } else if (durations.seconds > 0 && duration.nanos < 0) {
///       duration.seconds -= 1;
///       duration.nanos += 1000000000;
///     }
///
/// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
///
///     Timestamp start = ...;
///     Duration duration = ...;
///     Timestamp end = ...;
///
///     end.seconds = start.seconds + duration.seconds;
///     end.nanos = start.nanos + duration.nanos;
///
///     if (end.nanos < 0) {
///       end.seconds -= 1;
///       end.nanos += 1000000000;
///     } else if (end.nanos >= 1000000000) {
///       end.seconds += 1;
///       end.nanos -= 1000000000;
///     }
@interface LCIMDuration : LCIMMessage

/// Signed seconds of the span of time. Must be from -315,576,000,000
/// to +315,576,000,000 inclusive.
@property(nonatomic, readwrite) int64_t seconds;

/// Signed fractions of a second at nanosecond resolution of the span
/// of time. Durations less than one second are represented with a 0
/// `seconds` field and a positive or negative `nanos` field. For durations
/// of one second or more, a non-zero value for the `nanos` field must be
/// of the same sign as the `seconds` field. Must be from -999,999,999
/// to +999,999,999 inclusive.
@property(nonatomic, readwrite) int32_t nanos;

@end

NS_ASSUME_NONNULL_END

CF_EXTERN_C_END

#pragma clang diagnostic pop

// @@protoc_insertion_point(global_scope)


text:
<!--
 ! Copyright 2009-2013 by The Regents of the University of California
 ! Licensed under the Apache License, Version 2.0 (the "License");
 ! you may not use this file except in compliance with the License.
 ! you may obtain a copy of the License from
 !
 !     http://www.apache.org/licenses/LICENSE-2.0
 !
 ! Unless required by applicable law or agreed to in writing, software
 ! distributed under the License is distributed on an "AS IS" BASIS,
 ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ! See the License for the specific language governing permissions and
 ! limitations under the License.
 !-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>hyracks-storage-am-lsm-invertedindex</artifactId>

	<parent>
		<artifactId>hyracks</artifactId>
		<groupId>edu.uci.ics.hyracks</groupId>
		<version>0.2.16-SNAPSHOT</version>
		<relativePath>..</relativePath>
	</parent>

  <licenses>
    <license>
      <name>Apache License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
      <comments>A business-friendly OSS license</comments>
    </license>
  </licenses>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.0.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>edu.uci.ics.hyracks</groupId>
			<artifactId>hyracks-storage-am-btree</artifactId>
			<version>0.2.16-SNAPSHOT</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>edu.uci.ics.hyracks</groupId>
			<artifactId>hyracks-storage-am-lsm-common</artifactId>
			<version>0.2.16-SNAPSHOT</version>
			<type>jar</type>
			<scope>compile</scope>
	    </dependency>
	</dependencies>
</project>


text:
  Luitré est
      une ville localisée dans le département de l'Ille-et-Vilaine en Bretagne. Elle totalisait 1 261 habitants en 2008.

À proximité de Luitré sont situées les villes de
Châtillon-en-Vendelais située à 7 km, 1 649 habitants,
Beaucé localisée à 6 km, 1 148 habitants,
Fleurigné à 5 km, 997 habitants,
La Selle-en-Luitré à 3 km, 527 habitants,
Parcé localisée à 6 km, 636 habitants,
Saint-Pierre-des-Landes située à 6 km, 964 habitants,
 entre autres. De plus, Luitré est située à seulement neuf km de Fougères.

Le nombre de logements, à Luitré, se décomposait en 2011 en deux appartements et 554 maisons soit
 un marché plutôt équilibré.

À Luitré, la valorisation moyenne à l'achat d'un appartement se situe à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 989 € du m². À la location le prix moyen se situe à 8 € du m² mensuel.

La commune propose quelques  aménagements, elle dispose, entre autres, de deux terrains de sport.


text:
package com.wangshan.models;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.joda.time.DateTime;
import org.springframework.format.annotation.DateTimeFormat;

import java.sql.Timestamp;

/**
 * Created by Administrator on 2015/11/15.
 */

public class UserToken {
    private Long user;
    private String token;
    private Integer state;
    private Timestamp createon;
    private Timestamp updateon;

    public UserToken(){}

    public UserToken(Long user, String token, Integer state, DateTime createon, DateTime updateon){
        this.user = user;
        this.token = token;
        this.state = state;
        this.createon = new Timestamp(createon.getMillis());
        this.updateon = new Timestamp(updateon.getMillis());
    }

    public Long getUser() {
        return user;
    }

    public void setUser(Long user) {
        this.user = user;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    public Timestamp getCreateon() {
        return createon;
    }

    public void setCreateon(Timestamp createon) {
        this.createon = createon;
    }

    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    public Timestamp getUpdateon() {
        return updateon;
    }

    public void setUpdateon(Timestamp updateon) {
        this.updateon = updateon;
    }
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis

Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework
    Friend Module ExtensionMethods
        <Extension>
        Public Function HasMetadataReference(project As Project, path As String) As Boolean
            Return project.MetadataReferences.Cast(Of PortableExecutableReference).Any(Function(vsReference) String.Equals(vsReference.FilePath, path, StringComparison.OrdinalIgnoreCase))
        End Function
    End Module
End Namespace


text:
package Controleurs;

import java.util.ArrayList;

import Client.Batiment;
import Requetes.Requete;
import Requetes.RequeteExterne;
import AlgosTraitement.AlgoTraitementExterneStandard;
import AlgosTraitement.IAlgoTraitementExterne;

/**Controleur correspondant a celui du sujet. Il en existe un par {@link Batiment} et permet de traiter les {@link RequeteExterne}
 * en choisissant quel est le meilleur {@link ControleurInterne} (donc {@link Client.Ascenseur}) pour traiter la demande.
 * @author Thomas
 */
public class ControleurExterne extends Controleur{

	/**Liste des {@link ControleurInterne} (et donc des {@link Client.Ascenseur}) disponibles.
	 */
	private ArrayList<ControleurInterne> listeControleursInternes;

	/**Utilise pour connaitre le nombre d'etages. Utilise dans {@link AlgoTraitementExterneStandard#rechercheMoinsActif (ControleurExterne controleurExt)}
	 * @see AlgoTraitementExterneStandard#rechercheMoinsActif (ControleurExterne controleurExt)
	 */
	private int nbEtages;

	/**la strategie a appliquer pour traiter les {@link RequeteExterne} de ce ControleurExterne
	 */
	private IAlgoTraitementExterne strategieTraitement;

	/**Construit un ControleurExterne
	 * @param controleurs liste des {@link ControleurInterne} disponnibles
	 * @param nbEtages nombre d'etage du {@link Batiment} correspondant.
	 * @param strategie l'{@link IAlgoTraitementExterne} a appliquer pour traiter les {@link RequeteExterne} de ce ControleurExterne
	 * @see Batiment#Batiment(String, int, int)
	 */
	public ControleurExterne (ArrayList<ControleurInterne> controleurs, int nbEtages, IAlgoTraitementExterne strategie) {
		this.strategieTraitement = strategie;
		this.listeControleursInternes = controleurs;
		this.nbEtages = nbEtages;
	}

	/**Permet d'ajouter une {@link RequeteExterne} a {@link Controleur#listeRequetes}.
	 * @param etage l'etage a partir duquel vient la {@link RequeteExterne}
	 * @param direction {@link Requete#libelle} que prend la {@link RequeteExterne} : {@link Client.Constantes#HAUT} ou {@link Client.Constantes#BAS}.
	 * @see RequeteExterne
	 */
	public void addRequete (int etage, int direction) {
		getRequetes().add(new RequeteExterne(etage, direction));
	}

	/**Permet de traiter toutes les requetes de {@link Controleur#listeRequetes}
	 * en appliquant la {@link #strategieTraitement} de ce ControleurExterne.
	 *
	 */
	public void traiterRequetes () {
		strategieTraitement.traiterRequetes(this);
	}

	/**Permet d'obtenir le {@link #nbEtages} de ce ControleurExterne
	 * @return {@link #nbEtages} de ce ControleurExterne
	 */
	public int getNbEtage() {
		return nbEtages;
	}

	/**Permet d'obtenir les {@link #listeControleursInternes} de ce ControleurExterne.
	 * @return {@link #listeControleursInternes} de ce ControleurExterne.
	 */
	public ArrayList<ControleurInterne> getControleurs() {
		return listeControleursInternes;
	}
}


text:
#ifndef STEREO_H
#define STEREO_H

#include <string>

struct IValue;

typedef struct {
    float data[2];
} stereo_sample_t;

typedef void* stereo_state_t;

typedef stereo_state_t (*stereo_plugin_init_fn)(IValue* params);
typedef stereo_sample_t (*stereo_plugin_fn)(stereo_state_t state, float mono_sample);
typedef void (*stereo_plugin_dispose_fn)(stereo_state_t);

struct StereoInstance;

StereoInstance* NewStereoInstance(std::wstring name, IValue* params);

struct StereoInstance {
    stereo_sample_t operator()(float sample) { return fn(state, sample); }
    ~StereoInstance() { dispose(state); }

private:
    stereo_state_t state;
    stereo_plugin_fn fn;
    stereo_plugin_dispose_fn dispose;

private:
    StereoInstance(stereo_state_t state_,
            stereo_plugin_fn fn_,
            stereo_plugin_dispose_fn dispose_)
        : dispose(dispose_)
          , fn(fn_)
          , state(state_)
    {}

    friend StereoInstance* NewStereoInstance(std::wstring, IValue*);
};

#endif


text:
package com.uber.nullaway.fixserialization.location;

import com.sun.tools.javac.code.Symbol;
import javax.lang.model.element.ElementKind;

/** subtype of {@link AbstractSymbolLocation} targeting methods. */
public class MethodLocation extends AbstractSymbolLocation {

  /** Symbol of the targeted method. */
  protected final Symbol.MethodSymbol enclosingMethod;

  public MethodLocation(Symbol target) {
    super(ElementKind.METHOD, target);
    enclosingMethod = (Symbol.MethodSymbol) target;
  }

  @Override
  public String tabSeparatedToString() {
    return String.join(
        "\t",
        type.toString(),
        enclosingClass.flatName(),
        enclosingMethod.toString(),
        "null",
        "null",
        uri != null ? uri.toASCIIString() : "null");
  }
}


text:
var express         = require("express"),
    env             = require("./fy_env"),
    mongoose        = require("mongoose"),
    jade            = require("jade"),
    path            = require("path"),
    pkg             = require("./package.json"),
    errorhandler    = require('errorhandler'),
    serveStatic     = require('serve-static'),
    morgan          = require('morgan'),
    compression     = require('compression'),
    bodyParser      = require("body-parser"),
    cookieParser    = require("cookie-parser"),
    passport        = require("passport"),
    admin_auth      = require("./controllers/backend/auth"),
    send_result     = require("./util/send_result"),
    http_error      = require("./util/http_error"),
    app_router      = require("./routes/app").router,
    session         = require('express-session'),
    mongoStore      = require('connect-mongo')(session),
    app             = express();

// db connect ----------------------------------------------------------------------------------
function connect() {
    var options = { server: { socketOptions: { keepAlive: 1 } } }
    mongoose.connect(env.mongo_url, options)
}
connect()

mongoose.connection.on('open', function() {
    console.log('mongodb connected')
})

mongoose.connection.on('error', function(err) {
    console.log(err)
})

// Reconnect when closed
mongoose.connection.on('disconnected', function () {
    connect()
})

// app setting----------------------------------------------------------------------------------------
app.enabled('trust proxy');
app.set("title", pkg.name)
app.set("port", env.port);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set("session_backend_cookie_name", "fy.ecommerce.backend")

// middleware ----------------------------------------------------------------------------------------
app.use(morgan("dev"));
app.use(compression());
app.use("/static", serveStatic(path.join(__dirname,'bower_components')));
app.use("/static", serveStatic(path.join(__dirname,'public')));
app.use("/static", serveStatic(path.join(__dirname,'pro_ui')));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended : true}));

// parse application/json
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
    name: app.get("session_backend_cookie_name"),
    secret: env.cryptoKey,
    store: new mongoStore({ url: env.mongo_url })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(send_result);
app.use(app_router);

// 500 page
app.use(http_error.http500);

if (app.get("env") === "development") {
    app.use(errorhandler())
}

//setup admin passport
admin_auth(app, passport);

// run --------------------------------------------------------------------------------------------
app.listen(app.get('port'))
console.log(app.get("title") + " listen on " + app.get("port"))

// app.use(express.cookieSession({key : 'xiaoxiong'}))


text:
package com.twitter.inject.thrift.modules

import com.twitter.inject.TwitterModule

object FilteredThriftClientFlagsModule extends TwitterModule {
  flag("timeout.multiplier", 1, "Timeout multiplier to increase specified timeout durations by a common factor")
  flag("retry.multiplier", 1, "Retry multiplier to increase specified retry durations by a common factor")
}


text:
import { WorkItemCard } from './page_objects/user_profile.page';
import { PlannerPage } from 'planner-functional-test';
import { Header } from './page_objects/app/header';
import { $, browser } from 'protractor';
import * as logger from './support/logging';
import { screenshotManager } from './support/screenshot_manager';
import { newSpaceName } from './support/space_name';
import { SpaceSettings } from './page_objects/space_settings.page';
import { LoginInteractionsFactory } from './interactions/login_interactions';
import { AccountHomeInteractionsFactory } from './interactions/account_home_interactions';

describe('Planner EE tests adding Area and Collaborator', () => {
  let planner = new PlannerPage(browser.baseUrl),
    settingsPage = new SpaceSettings(),
    header = new Header($('f8-app')),
    workItemCard = new WorkItemCard(),
    spaceName = newSpaceName();

  beforeAll( async () => {
    logger.info('-------before All-------');
    browser.ignoreSynchronization = true;
    await browser.driver.manage().window().setSize(1920, 1080);
    let loginInteractions = LoginInteractionsFactory.create();
    await loginInteractions.login();
    let accountHomeInteractions = AccountHomeInteractionsFactory.create();
    await accountHomeInteractions.createEmptySpace(spaceName);
  });

  beforeEach(async() => {
    screenshotManager.nextTest();
  });

  afterEach(async () => {
    await screenshotManager.save('afterEach');
  });

  it('should Navigate to settings, add New Area and assign it to a workitem ', async () => {
    logger.specTitle('should add child area and Add it to a workitem');
    let areaName = 'New Area',
      area = '/' + spaceName + '/' + areaName;
    // Navigate to settings, add Area
    await settingsPage.clickSettings();
    await planner.waitUntilUrlContains('settings');
    expect(await browser.getCurrentUrl()).toContain('settings');
    await settingsPage.list.untilCount(1);
    expect(await settingsPage.list.getText()).toContain(spaceName);
    await settingsPage.addAreas(areaName);
    await settingsPage.clickShowAreas();
    expect(await settingsPage.list.getText()).toContain('New Area');

    // Click Plan tab, Create a new work Item and Add new Area
    let workitemname = {'title': 'area test'};
    await planner.planTab.untilClickable();
    await planner.planTab.clickWhenReady();
    await planner.waitUntilTitleContains('Plan');
    await planner.ready();
    await planner.createWorkItem(workitemname);
    expect(planner.workItemList.hasWorkItem(workitemname.title)).toBeTruthy();
    await planner.workItemList.clickWorkItem(workitemname.title);
    await planner.quickPreview.addArea(areaName);
    expect(planner.quickPreview.getArea()).toBe(area);
    await planner.quickPreview.close();
  });

  it('should Navigate to collaborators, add a new collaborator and assign it to a workitem ', async () => {
    logger.specTitle('should add collaborator and assign it to a workitem');
    await settingsPage.clickSettings();
    await planner.waitUntilUrlContains('settings');
    await settingsPage.clickCollaboratorsTab();
    await planner.waitUntilUrlContains('collaborators');
    expect(await browser.getCurrentUrl()).toContain('collaborators');
    await settingsPage.list.untilCount(1);
    await settingsPage.addCollaborators('Osio10');
    await settingsPage.list.untilCount(2);
    expect(await settingsPage.getCollaboratorList()).toContain('Osio10');

    // Click Plan tab, Create a new work Item and Assign it to Collaborator
    let workitemname = {'title': 'collaborator test'};
    await planner.planTab.untilClickable();
    await planner.planTab.clickWhenReady();
    await planner.ready();
    await planner.waitUntilTitleContains('Plan');
    await planner.createWorkItem(workitemname);
    expect(planner.workItemList.hasWorkItem(workitemname.title)).toBeTruthy();
    await planner.workItemList.clickWorkItem(workitemname.title);
    await planner.quickPreview.titleInput.untilTextIsPresentInValue(workitemname.title);
    await planner.quickPreview.addAssignee('Osio10');
    expect(planner.quickPreview.getAssignees()).toContain('Osio10');
    await planner.quickPreview.close();
  });

  it('should assign a workitem, open profile page, and navigate from my work item to detail page', async() => {
    logger.specTitle('should add collaborator and assign it to a workitem');
    // Create a workitem and self-assign it
    let workitem = {'title': 'My workitem tests from profile page'};
    await planner.clickPlanTab();
    await planner.createWorkItem(workitem);
    let userName = await settingsPage.getUserInfo();
    expect(await planner.workItemList.hasWorkItem(workitem.title)).toBeTruthy();
    await planner.workItemList.clickWorkItem(workitem.title);
    await planner.quickPreview.addAssignee(userName + ' (me)');
    expect(await planner.quickPreview.getAssignees()).toContain(userName);
    await planner.quickPreview.close();

    // Go to My work item in Profile page and click on a workitem to open detail page
    await header.profileDropdown.select('Profile');
    await planner.waitUntilUrlContains('_profile');
    await workItemCard.clickWorkItemTitle(workitem.title);
    await planner.waitUntilUrlContains('plan');
    await planner.waitUntilTitleContains('plan');
    expect(planner.detailPage.getAssignees()).toBe(userName);
  });
});


text: content1content2content3content4content5content6content7content8content9


text:
<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class RegistrationTest extends TestCase
{

	use DatabaseTransactions;

    /**
     * A basic test example.
     *
     * @return void
     */
    public function testNewUserRegistration()
    {
		$this->visit('auth/register')
			->type('John Doe', 'name')
			->type('hello1@in.com', 'email')
			->type('hello1', 'password')
			->type('hello1', 'password_confirmation')
			->press('SIGNUP')
			->seePageIs('/');
    }
}


text:
import axios from 'axios'
import fakedata from './messages'
import fakeloading from './emailsLoading'
import { getApiUrl, filterMessages } from '../modules/methods'

// ------------------------------------
// Constants
// ------------------------------------

export const MARK_READ = 'MARK_READ'
export const MARK_UNREAD = 'MARK_UNREAD'
export const LOAD_EMAILS_SUCCESS = 'LOAD_EMAILS_SUCCESS'
export const LOADING = 'LOADING'
export const DELETE_MAIL = 'DELETE_MAIL'

// ------------------------------------
// Actions
// ------------------------------------

export function loadEmailsSuccess (emails) {
  return {
    type: LOAD_EMAILS_SUCCESS,
    emails
  }
}

export function markRead (value = 1) {
  return function (dispatch, getState) {
    return axios.get(getApiUrl('put'), {})
      .then(function (response) {
        dispatch({
          type    : MARK_READ,
          payload : value
        })
      }).catch(function () {
        console.log(`ERROR: ${MARK_READ}`)
      })
  }
}

export function markUnread (value = 1) {
  return function (dispatch, getState) {
    return axios.get(getApiUrl('put'), {})
      .then(function (response) {
        dispatch({
          type    : MARK_UNREAD,
          payload : value
        })
      }).catch(function () {
        console.log(`ERROR: ${MARK_UNREAD}`)
      })
  }
}

export function deleteMail (value = 1) {
  return function (dispatch, getState) {
    return axios.get(getApiUrl('put'), {})
      .then(function (response) {
        dispatch({
          type    : DELETE_MAIL,
          payload : value
        })
      }).catch(function () {
        console.log(`ERROR: ${DELETE_MAIL}`)
      })
  }
}

export function loadEmails () {
  return (dispatch) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        dispatch({
          type: LOADING,
          payload: fakeloading.emails
        })
        resolve()
      }, 1)
    })
    .then(dispatch(getEmailData()))
    .catch(() => { console.log('ERROR: LOADING Promise') })
  }
}

export function getEmailData () {
  return function (dispatch) {
    return axios.get(getApiUrl('get'), {})
      .then(function (response) {
        dispatch(loadEmailsSuccess(response.data.emails))
      }).catch(function () {
        console.log(`ERROR: ${LOAD_EMAILS_SUCCESS}`)
      })
  }
}

// ------------------------------------
// Action Handlers
// ------------------------------------

const ACTION_HANDLERS = {
  [LOADING] : (state, action) => {
    return action.payload
  },
  [LOAD_EMAILS_SUCCESS] : (state, action) => {
    return filterMessages(action.emails)
  },
  [DELETE_MAIL] : (state, action) => {
    return state.filter((message) => {
      return message.id !== action.payload
    })
  },
  [MARK_READ] : (state, action) => {
    return state.map((message) => {
      if (message.id === action.payload) {
        message.unread = false
      }
      return message
    })
  },
  [MARK_UNREAD] : (state, action) => {
    return state.map((message) => {
      if (message.id === action.payload) {
        message.unread = true
      }
      return message
    })
  }
}

// ------------------------------------
// Reducer
// ------------------------------------

const initialState = [] || fakedata.emails
export default function emailReducer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}


text:
<app-navigation></app-navigation>

<app-carousel [model]="slides"></app-carousel>

<div class="container marketing">
  <app-three-columns [model]="cafes"></app-three-columns>

  <div *ngFor="let article of articles; let i = index">
    <app-featurette [model]="article" [imageOnRight]="i%2 == 0"></app-featurette>
  </div>
</div>

<app-footer></app-footer>


text:
function ShowPreview(ID,pageY,leftC)
{
            var sw = window.screen.width;
            var sh = window.screen.height;

            var top_position=0;

            if (navigator.appName == "Microsoft Internet Explorer")
            {
                y=document.documentElement.scrollTop ;
                mouseY=event.clientY;
                top_position=parseInt(y)+parseInt(mouseY);

            }
            else
            {
                y=window.pageYOffset;
                top_position=parseInt(pageY);
            }

            document.getElementById('test_div').style.position="absolute";
            document.getElementById('test_div').style.top=(y+220)+'px';

            document.getElementById('test_div').style.zIndex = "19999";

            if(leftC!=-1)
            document.getElementById('test_div').style.left=((sw/2)-300)+'px';

            document.getElementById('test_hr').innerHTML=document.getElementById('templateDiv').innerHTML;
            document.getElementById('test_div').style.display="";

            $.post("modules/qst_previwer.php", {  ajax: "yes", qst_id : ID, preview: "1" },
            function(data){
                 //alert(data);
                 document.getElementById('test_hr').innerHTML=data;
                            var templ_id= document.getElementById('hdnTempID').value;
                            if(templ_id=="2")
                            {
                                var video_file= document.getElementById('hdnVideoFile').value;
                                var rid= document.getElementById('hdnRID').value;
                                if(video_file!="")
                                {
                                        if(leftC!="-1")
                                        {
                                            flowplayer("p"+rid, "flowplayer/flowplayer-3.2.16.swf" , {
                                                     clip:  {
                                                            autoPlay: false,
                                                            autoBuffering: true
                                                        }
                                                    });
                                        }
                                        else
                                        {
                                            Uppod({m:"video",uid:"p"+rid,file:"video_files/"+video_file,poster:"link"});
                                        }

                                }
                            }

            });
}

function close_window()
{
    document.getElementById('test_hr').innerHTML="";
    document.getElementById('test_div').style.display="none";
}

function MoveCenter(mobjectID)
{

            var width = $( window ).width();
            var height = "100px";

            document.getElementById(mobjectID).style.position="absolute";
            document.getElementById(mobjectID).style.top=height;
            document.getElementById(mobjectID).style.left='250px';

}

function MoveCenterMobile(mobjectID)
{

            var width = $( window ).width();
            var height = "100px";

            document.getElementById(mobjectID).style.position="absolute";
            document.getElementById(mobjectID).style.top=height;
            document.getElementById(mobjectID).style.left='1px';

}

var loaded = false;
function LoadReports(mid)
{
    if(loaded) return;
    //dvRep
     $.post("modules/page_reports.php"+window.location.search+"&r_id="+mid, {  ajax: "yes" },
         function(data){
             document.getElementById('dvRep').innerHTML='

'+data.rhtml;
             exec_js(data.scripts);
        },"json");
    loaded = true;
}

function LoadReport(mid,rep_id,divRep,drowHead,drowMode)
{
	$.post("modules/page_reports.php"+window.location.search+"&r_id="+mid+"&rep_id="+rep_id+"&drow_head="+drowHead+"&drowMode="+drowMode, {  ajax: "yes" },
         function(data){
             document.getElementById(divRep).innerHTML='

'+data.rhtml;
             exec_js(data.scripts);
        },"json");
}

function querySt(ji) {
var res = "-1"
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
res = ft[1];
}
}
return res;
}

function get_checkbox_post()
{
    var chk_values = "";
    for(var i=0;i<document.form1.chkAns.length;i++)
    {
        if(document.form1.chkAns[i].checked)
        {
            chk_values+=encodeURIComponent(document.form1.chkAns[i].value)+";|";
        }
    }
    return chk_values;
}

function get_radio_post()
{
    var rd_val = "";

    for( i = 0; i < document.form1.rdAns.length; i++ )
    {
        if( document.form1.rdAns[i].checked == true )
        rd_val = document.form1.rdAns[i].value;
    }

    return rd_val;
}
//txtMultiAns
function get_free_text_post()
{
    return encodeURIComponent(document.getElementById('txtFreeId').value)+";|"+encodeURIComponent(document.getElementById('txtFree').value);
}

function get_text_post()
{
    var txt_values = "";
    for(var i=0;i<document.form1.txtMultiAns.length;i++)
    {
      //  if(document.form1.txtMultiAns[i].checked)
      //  {
            txt_values+=encodeURIComponent(document.form1.txtMultiAnsId[i].value)+":|"+encodeURIComponent(document.form1.txtMultiAns[i].value)+";|";
     //   }
    }
    return txt_values;
}

function get_post_string(qst_type)
{

    if(qst_type=="0")
    {
        post_string = get_checkbox_post();
    }
    else if(qst_type=="1")
    {
        post_string = get_radio_post();
    }
    else if(qst_type=="3")
    {
        post_string = get_free_text_post();
    }
      else if(qst_type=="4")
    {
        post_string = get_text_post();
    }
    return post_string;
}

function SearchInTable(search_control, tableid, search_columns) {

    var value = $.trim($("#"+search_control).val());

//table-tblgroups
    $("#"+tableid+" > tbody  > tr").each(function(index) {

        if (index != 0) {

            $row = $(this);

            var find = false;
            var results = search_columns.split(",");
            for(var y =0;y<results.length;y++)
            {
                var id = $row.find('td:eq('+results[y]+')').text().toLowerCase();;
                if (id.indexOf(value.toLowerCase()) > 0)
                {
                    find = true;
                }
            }

            if (!find) {
                $row.hide();
            }
            else {
               $row.show();
            }
        }
    });
}

function ShowAllTableRows(search_control,tableid)
{

    $("#"+search_control).val("");

    $("#"+tableid+" > tbody  > tr").each(function(index) {

    if (index != 0) {

        $row = $(this);

        $row.show();
    }
    });
}

var submitHandler = function() {
  // do stuff
  return false;
}

function disable_submit()
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

     if (keyCode == 13) return false;
     return true;
}

function onlyNumbers(evt) {
    var e = evt
    if(window.event){ // IE
    var charCode = e.keyCode;
    } else if (e.which) { // Safari 4, Firefox 3.0.4
    var charCode = e.which
    }

    if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
    return true;
}

function onlyDecs(evt) {
    var e = evt
    if(window.event){ // IE
    var charCode = e.keyCode;
    } else if (e.which) { // Safari 4, Firefox 3.0.4
    var charCode = e.which
    }

    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=46)
    return false;
    return true;
}


text:
{% if paginator.total_pages > 1 %}

      {% if paginator.previous_page %}

              Newer Posts

      {% endif %}

      {% if paginator.next_page %}

              Older Posts

      {% endif %}

{% endif %}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>3. Custom Editor</title>
    <link rel="stylesheet" type="text/css" href="./css/tui-example-style.css" />
    <link rel="stylesheet" type="text/css" href="../dist/tui-grid.css" />

      You can see the tutorial
      here.

      The example code can be slower than your environment because the code is transpiled by babel-standalone in runtime.


text:
<?php namespace App\Exceptions;

use Exception;
use Illuminate\Http\Response;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Whoops\Run as WhoopsRun;
use Whoops\Handler\JsonResponseHandler;
use Whoops\Handler\PrettyPageHandler;

class Handler extends ExceptionHandler {

	/**
	 * A list of the exception types that should not be reported.
	 *
	 * @var array
	 */
	protected $dontReport = [
		'Symfony\Component\HttpKernel\Exception\HttpException'
	];

	/**
	 * Report or log an exception.
	 *
	 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
	 *
	 * @param  \Exception  $e
	 * @return void
	 */
	public function report(Exception $e)
	{
		return parent::report($e);
	}

	/**
	 * Render an exception into an HTTP response.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Exception  $e
	 * @return Response
	 */
	public function render($request, Exception $e)
	{
		if (config('app.debug'))
		{
			$whoops = new WhoopsRun;

			if ($request->ajax())
			{
				$whoops->pushHandler(new JsonResponseHandler);
			}
			else
			{
				$whoops->pushHandler(new PrettyPageHandler);
			}

			return response($whoops->handleException($e),
				$e->getStatusCode(),
				$e->getHeaders()
			);
		}

		return parent::render($request, $e);
	}

}


text:
package com.gmind7.bakery.office;

import java.util.List;

import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

import com.gmind7.bakery.domain.Offices;

public interface OfficeRepository extends PagingAndSortingRepository<Offices, Long>, QueryDslPredicateExecutor<Offices>, OfficeRepositoryCustom {

	List<Offices> findBycountry(String country, Pageable pageable);

	List<Offices> findBycountry(String country);

	@Query(value = "SELECT * FROM offices WHERE city = ?1", nativeQuery = true)
	List<Offices> findByCity(String city);

	@Modifying
	@Query("UPDATE #{#entityName} SET territory = :territory WHERE officeCode = :officeCode")
	int setTerritory(@Param("officeCode") long officeCode, @Param("territory") String territory);

}


text:
package me.joeycumines.javapromises.v1.external;

import me.joeycumines.javapromises.core.PromiseApi;
import me.joeycumines.javapromises.core.PromiseApiTest;

public class PromiseJavacrumbsApiTest extends PromiseApiTest {
    @Override
    protected PromiseApi getApi() {
        return PromiseJavacrumbsFactory.getInstance();
    }
}


text:
<?php
namespace ARIPD\AdminBundle\Util\VPOS;

class YKB {

	public $XML_SERVICE_URL;
	public $mid;
	public $tid;

	// no-TDS
	public $tranDateRequired = 1;
	public $amount;
	public $ccno;
	public $currencyCode = 'YT';
	public $cvc;
	public $expDate;
	public $installment;
	public $XID;

	// TDS
	public $OOS_TDS_SERVICE_URL;
	public $posnetid;
	public $cardHolderName;
	public $tranType = 'Sale';

	public $bankData;
	public $merchantData;
	public $sign;

	public $wpAmount = 0;

	public function __construct() {
	}

	public function notds_xmldata1() {
		return "xmldata=" . "<posnetRequest>" . "<mid>$this->mid</mid>"
				. "<tid>$this->tid</tid>"
				. "<tranDateRequired>$this->tranDateRequired</tranDateRequired>"
				. "<sale>" . "<amount>$this->amount</amount>"
				. "<ccno>$this->ccno</ccno>"
				. "<currencyCode>$this->currencyCode</currencyCode>"
				. "<cvc>$this->cvc</cvc>" . "<expDate>$this->expDate</expDate>"
				. "<installment>$this->installment</installment>"
				. "<orderID>$this->XID</orderID>" . "</sale>"
				. "</posnetRequest>";
	}

	public function init_curl($request) {
		$ch = curl_init(); // initialize curl handle

		curl_setopt($ch, CURLOPT_URL, $this->XML_SERVICE_URL); // set url to post to
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $request/*$this->notds_xmldata1()*/); // add POST fields

		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable
		curl_setopt($ch, CURLOPT_TIMEOUT, 90); // times out after 90s

		$result = curl_exec($ch); // run the whole process

		if (curl_errno($ch)) {
			print curl_error($ch);
		} else {
			curl_close($ch);
		}
		return $result;
	}

	public function tds_xmldata1() {
		return "xmldata=" . "<posnetRequest>" . "<mid>$this->mid</mid>"
				. "<tid>$this->tid</tid>" . "<oosRequestData>"
				. "<posnetid>$this->posnetid</posnetid>"
				. "<ccno>$this->ccno</ccno>"
				. "<expDate>$this->expDate</expDate>" . "<cvc>$this->cvc</cvc>"
				. "<amount>$this->amount</amount>"
				. "<currencyCode>$this->currencyCode</currencyCode>"
				. "<installment>$this->installment</installment>"
				. "<XID>$this->XID</XID>"
				. "<cardHolderName>$this->cardHolderName</cardHolderName>"
				. "<tranType>$this->tranType</tranType>" . "</oosRequestData>"
				. "</posnetRequest>";
	}

	public function tds_xmldata2() {
		return "xmldata=" . "<posnetRequest>" . "<mid>$this->mid</mid>"
				. "<tid>$this->tid</tid>" . "<oosResolveMerchantData>"
				. "<bankData>$this->bankData</bankData>"
				. "<merchantData>$this->merchantData</merchantData>"
				. "<sign>$this->sign</sign>" . "</oosResolveMerchantData>"
				. "</posnetRequest>";
	}

	public function tds_xmldata3() {
		return "xmldata=" . "<posnetRequest>" . "<mid>$this->mid</mid>"
				. "<tid>$this->tid</tid>" . "<oosTranData>"
				. "<bankData>$this->bankData</bankData>"
				. "<wpAmount>$this->wpAmount</wpAmount>" . "</oosTranData>"
				. "</posnetRequest>";
	}

}


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Logic;

namespace Azure.ResourceManager.Logic.Models
{
    /// <summary> The list of workflow triggers. </summary>
    internal partial class LogicWorkflowTriggerListResult
    {
        /// <summary> Initializes a new instance of LogicWorkflowTriggerListResult. </summary>
        internal LogicWorkflowTriggerListResult()
        {
            Value = new ChangeTrackingList<LogicWorkflowTriggerData>();
        }

        /// <summary> Initializes a new instance of LogicWorkflowTriggerListResult. </summary>
        /// <param name="value"> A list of workflow triggers. </param>
        /// <param name="nextLink"> The URL to get the next set of results. </param>
        internal LogicWorkflowTriggerListResult(IReadOnlyList<LogicWorkflowTriggerData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> A list of workflow triggers. </summary>
        public IReadOnlyList<LogicWorkflowTriggerData> Value { get; }
        /// <summary> The URL to get the next set of results. </summary>
        public string NextLink { get; }
    }
}


text:
(function (window, document) {

    'use strict';

    //给hotcss开辟个命名空间,别问我为什么,我要给你准备你会用到的方法,免得用到的时候还要自己写。
    var hotcss = {};

    (function () {
        //根据devicePixelRatio自定计算scale
        //可以有效解决移动端1px这个世纪难题。
        var viewportEl = document.querySelector('meta[name="viewport"]'),
            hotcssEl = document.querySelector('meta[name="hotcss"]'),
            dpr = window.devicePixelRatio || 1,
            maxWidth = 540,
            designWidth = 0;

        dpr = dpr >= 3 ? 3 : (dpr >= 2 ? 2 : 1);

        //允许通过自定义name为hotcss的meta头,通过initial-dpr来强制定义页面缩放
        if (hotcssEl) {
            var hotcssCon = hotcssEl.getAttribute('content');
            if (hotcssCon) {
                var initialDprMatch = hotcssCon.match(/initial\-dpr=([\d\.]+)/);
                if (initialDprMatch) {
                    dpr = parseFloat(initialDprMatch[1]);
                }
                var maxWidthMatch = hotcssCon.match(/max\-width=([\d\.]+)/);
                if (maxWidthMatch) {
                    maxWidth = parseFloat(maxWidthMatch[1]);
                }
                var designWidthMatch = hotcssCon.match(/design\-width=([\d\.]+)/);
                if (designWidthMatch) {
                    designWidth = parseFloat(designWidthMatch[1]);
                }
            }
        }

        document.documentElement.setAttribute('data-dpr', dpr);
        hotcss.dpr = dpr;

        document.documentElement.setAttribute('max-width', maxWidth);
        hotcss.maxWidth = maxWidth;

        if (designWidth) {
            document.documentElement.setAttribute('design-width', designWidth);
            hotcss.designWidth = designWidth;
        }

        var scale = 1 / dpr,
            content = 'width=device-width, initial-scale=' + scale + ', minimum-scale=' + scale + ', maximum-scale=' + scale + ', user-scalable=no';

        if (viewportEl) {
            viewportEl.setAttribute('content', content);
        } else {
            viewportEl = document.createElement('meta');
            viewportEl.setAttribute('name', 'viewport');
            viewportEl.setAttribute('content', content);
            document.head.appendChild(viewportEl);
        }

    })();

    hotcss.px2rem = function (px, designWidth) {
        //预判你将会在JS中用到尺寸,特提供一个方法助你在JS中将px转为rem。就是这么贴心。
        if (!designWidth) {
            //如果你在JS中大量用到此方法,建议直接定义 hotcss.designWidth 来定义设计图尺寸;
            //否则可以在第二个参数告诉我你的设计图是多大。
            designWidth = parseInt(hotcss.designWidth, 10);
        }

        return parseInt(px, 10) * 320 / designWidth / 20;
    }

    hotcss.rem2px = function (rem, designWidth) {
        //新增一个rem2px的方法。用法和px2rem一致。
        if (!designWidth) {
            designWidth = parseInt(hotcss.designWidth, 10);
        }
        //rem可能为小数,这里不再做处理了
        return rem * 20 * designWidth / 320;
    }

    hotcss.mresize = function () {
        //对,这个就是核心方法了,给HTML设置font-size。
        var innerWidth = document.documentElement.getBoundingClientRect().width || window.innerWidth;

        if (hotcss.maxWidth && (innerWidth / hotcss.dpr > hotcss.maxWidth)) {
            innerWidth = hotcss.maxWidth * hotcss.dpr;
        }

        if (!innerWidth) {
            return false;
        }

        document.documentElement.style.fontSize = (innerWidth * 20 / 320) + 'px';

        hotcss.callback && hotcss.callback();

    };

    hotcss.mresize();
    //直接调用一次

    window.addEventListener('resize', function () {
        clearTimeout(hotcss.tid);
        hotcss.tid = setTimeout(hotcss.mresize, 33);
    }, false);
    //绑定resize的时候调用

    window.addEventListener('load', hotcss.mresize, false);
    //防止不明原因的bug。load之后再调用一次。

    setTimeout(function () {
        hotcss.mresize();
        //防止某些机型怪异现象,异步再调用一次
    }, 333)

    window.hotcss = hotcss;
    //命名空间暴露给你,控制权交给你,想怎么调怎么调。

})(window, document);