text:
/* Includes ------------------------------------------------------------------*/
#include "usb_lib.h"
#include "usb_conf.h"
#include "usb_pwr.h"
#include "hw_config.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
__IO uint32_t bDeviceState = UNCONNECTED; /* USB device status */
__IO bool fSuspendEnabled = TRUE;  /* true when suspend is possible */
__IO uint32_t EP[8];

struct
{
  __IO RESUME_STATE eState;
  __IO uint8_t bESOFcnt;
}
ResumeS;

__IO uint32_t remotewakeupon=0;

/* Extern variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Extern function prototypes ------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/*******************************************************************************
* Function Name  : PowerOn
* Description    :
* Input          : None.
* Output         : None.
* Return         : USB_SUCCESS.
*******************************************************************************/
RESULT PowerOn(void)
{
  uint16_t wRegVal;

  /*** cable plugged-in ? ***/
  USB_Cable_Config(ENABLE);

  /*** CNTR_PWDN = 0 ***/
  wRegVal = CNTR_FRES;
  _SetCNTR(wRegVal);

  /*** CNTR_FRES = 0 ***/
  wInterrupt_Mask = 0;
  _SetCNTR(wInterrupt_Mask);
  /*** Clear pending interrupts ***/
  _SetISTR(0);
  /*** Set interrupt mask ***/
  wInterrupt_Mask = CNTR_RESETM | CNTR_SUSPM | CNTR_WKUPM;
  _SetCNTR(wInterrupt_Mask);

  return USB_SUCCESS;
}

/*******************************************************************************
* Function Name  : PowerOff
* Description    : handles switch-off conditions
* Input          : None.
* Output         : None.
* Return         : USB_SUCCESS.
*******************************************************************************/
RESULT PowerOff()
{
  /* disable all interrupts and force USB reset */
  _SetCNTR(CNTR_FRES);
  /* clear interrupt status register */
  _SetISTR(0);
  /* Disable the Pull-Up*/
  USB_Cable_Config(DISABLE);
  /* switch-off device */
  _SetCNTR(CNTR_FRES + CNTR_PDWN);
  /* sw variables reset */
  /* ... */

  return USB_SUCCESS;
}

/*******************************************************************************
* Function Name  : Suspend
* Description    : sets suspend mode operating conditions
* Input          : None.
* Output         : None.
* Return         : USB_SUCCESS.
*******************************************************************************/
void Suspend(void)
{
    uint32_t i =0;
    uint16_t wCNTR;
    uint32_t tmpreg = 0;
  __IO uint32_t savePWR_CR=0;
    /* suspend preparation */
    /* ... */

    /*Store CNTR value */
    wCNTR = _GetCNTR();

    /* This a sequence to apply a force RESET to handle a robustness case */

    /*Store endpoints registers status */
    for (i=0;i<8;i++) EP[i] = _GetENDPOINT(i);

    /* unmask RESET flag */
    wCNTR|=CNTR_RESETM;
    _SetCNTR(wCNTR);

    /*apply FRES */
    wCNTR|=CNTR_FRES;
    _SetCNTR(wCNTR);

    /*clear FRES*/
    wCNTR&=~CNTR_FRES;
    _SetCNTR(wCNTR);

    /*poll for RESET flag in ISTR*/
    while((_GetISTR()&ISTR_RESET) == 0);

    /* clear RESET flag in ISTR */
    _SetISTR((uint16_t)CLR_RESET);

    /*restore Enpoints*/
    for (i=0;i<8;i++)
    _SetENDPOINT(i, EP[i]);

    /* Now it is safe to enter macrocell in suspend mode */
    wCNTR |= CNTR_FSUSP;
    _SetCNTR(wCNTR);

    /* force low-power mode in the macrocell */
    wCNTR = _GetCNTR();
    wCNTR |= CNTR_LPMODE;
    _SetCNTR(wCNTR);

    /*prepare entry in low power mode (STOP mode)*/
    /* Select the regulator state in STOP mode*/
    savePWR_CR = PWR->CR;
    tmpreg = PWR->CR;
    /* Clear PDDS and LPDS bits */
    tmpreg &= ((uint32_t)0xFFFFFFFC);
    /* Set LPDS bit according to PWR_Regulator value */
//!!!!!!!!    tmpreg |= PWR_Regulator_LowPower;
    /* Store the new value */
    PWR->CR = tmpreg;
    /* Set SLEEPDEEP bit of Cortex System Control Register */
#if defined (STM32F30X) || defined (STM32F37X)
        SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
#else
        SCB->SCR |= SCB_SCR_SLEEPDEEP;
#endif
    /* enter system in STOP mode, only when wakeup flag in not set */
    if((_GetISTR()&ISTR_WKUP)==0)
    {
        __WFI();
        /* Reset SLEEPDEEP bit of Cortex System Control Register */
#if defined (STM32F30X) || defined (STM32F37X)
                SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk);
#else
                SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP);
#endif
    }
    else
    {
        /* Clear Wakeup flag */
        _SetISTR(CLR_WKUP);
        /* clear FSUSP to abort entry in suspend mode  */
        wCNTR = _GetCNTR();
        wCNTR&=~CNTR_FSUSP;
        _SetCNTR(wCNTR);

        /*restore sleep mode configuration */
        /* restore Power regulator config in sleep mode*/
        PWR->CR = savePWR_CR;

        /* Reset SLEEPDEEP bit of Cortex System Control Register */
#if defined (STM32F30X) || defined (STM32F37X)
                SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk);
#else
                SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP);
#endif

    }
}

/*******************************************************************************
* Function Name  : Resume_Init
* Description    : Handles wake-up restoring normal operations
* Input          : None.
* Output         : None.
* Return         : USB_SUCCESS.
*******************************************************************************/
void Resume_Init(void)
{
  uint16_t wCNTR;

  /* ------------------ ONLY WITH BUS-POWERED DEVICES ---------------------- */
  /* restart the clocks */
  /* ...  */

  /* CNTR_LPMODE = 0 */
  wCNTR = _GetCNTR();
  wCNTR &= (~CNTR_LPMODE);
  _SetCNTR(wCNTR);

  /* restore full power */
  /* ... on connected devices */
  Leave_LowPowerMode();

  /* reset FSUSP bit */
  _SetCNTR(IMR_MSK);

  /* reverse suspend preparation */
  /* ... */

}

/*******************************************************************************
* Function Name  : Resume
* Description    : This is the state machine handling resume operations and
*                 timing sequence. The control is based on the Resume structure
*                 variables and on the ESOF interrupt calling this subroutine
*                 without changing machine state.
* Input          : a state machine value (RESUME_STATE)
*                  RESUME_ESOF doesn't change ResumeS.eState allowing
*                  decrementing of the ESOF counter in different states.
* Output         : None.
* Return         : None.
*******************************************************************************/
void Resume(RESUME_STATE eResumeSetVal)
{
  uint16_t wCNTR;

  if (eResumeSetVal != RESUME_ESOF)
    ResumeS.eState = eResumeSetVal;
  switch (ResumeS.eState)
  {
    case RESUME_EXTERNAL:
      if (remotewakeupon ==0)
      {
        Resume_Init();
        ResumeS.eState = RESUME_OFF;
      }
      else /* RESUME detected during the RemoteWAkeup signalling => keep RemoteWakeup handling*/
      {
        ResumeS.eState = RESUME_ON;
      }
      break;
    case RESUME_INTERNAL:
      Resume_Init();
      ResumeS.eState = RESUME_START;
      remotewakeupon = 1;
      break;
    case RESUME_LATER:
      ResumeS.bESOFcnt = 2;
      ResumeS.eState = RESUME_WAIT;
      break;
    case RESUME_WAIT:
      ResumeS.bESOFcnt--;
      if (ResumeS.bESOFcnt == 0)
        ResumeS.eState = RESUME_START;
      break;
    case RESUME_START:
      wCNTR = _GetCNTR();
      wCNTR |= CNTR_RESUME;
      _SetCNTR(wCNTR);
      ResumeS.eState = RESUME_ON;
      ResumeS.bESOFcnt = 10;
      break;
    case RESUME_ON:
      ResumeS.bESOFcnt--;
      if (ResumeS.bESOFcnt == 0)
      {
        wCNTR = _GetCNTR();
        wCNTR &= (~CNTR_RESUME);
        _SetCNTR(wCNTR);
        ResumeS.eState = RESUME_OFF;
        remotewakeupon = 0;
      }
      break;
    case RESUME_OFF:
    case RESUME_ESOF:
    default:
      ResumeS.eState = RESUME_OFF;
      break;
  }
}

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
"""Manage finite-dimensional transition and time matrices throughout a
simulation.

"""

__all__ = ['Matrices', 'make_stochastic_matrix', 'make_time_matrix']

import logging
import sys
from typing import Optional

import scipy.io
import scipy.sparse as sparse
import numpy as np

from miles import (Milestones, Transition, dominant_eigenvector)

class Matrices:
    """Finite-dimensional operators estimated during simulations.

    Each entry in the matrix A counts the number of transitions
    between the corresponding milestones. Each entry in the matrix B
    contains the aggregated lag times for the corresponding
    transitions.

    """

    A = None                 # type: Optional[scipy.sparse.dok_matrix]
    B = None                 # type: Optional[scipy.sparse.dok_matrix]
    _K = None                # type: Optional[scipy.sparse.csr_matrix]
    _T = None                # type: Optional[scipy.sparse.csr_matrix]
    _q = None                # type: Optional[np.array]
    _t = None                # type: Optional[np.array]
    _p = None                # type: Optional[np.array]
    _eigval = None           # type: Optional[float]
    _mfpt = None             # type: Optional[float]

    def __init__(self, milestones: Milestones) -> None:
        self.milestones = milestones

        num_milestones = milestones.max_milestones
        M = num_milestones
        self.A = sparse.dok_matrix((M, M), dtype=np.int32)
        self.B = sparse.dok_matrix((M, M), dtype=np.float64)

        self.product_indices = [p.index for p in milestones.products]

        self._connect_products_to_reactants(milestones)

        self._reset_computed_quantities()

    def _reset_computed_quantities(self) -> None:
        """Reset computed quantities.

        Set computed quantities to None so that they are explicitly
        recomputed in the future when they are needed.

        """
        self._K = None
        self._T = None
        self._q = None
        self._t = None
        self._p = None
        self._eigval = None
        self._mfpt = None

    # XXX Think about eliminating these property methods.
    @property
    def K(self) -> np.array:
        """Transition matrix."""
        if self._K is None:
            self._K = make_stochastic_matrix(self.A)
        return self._K

    @property
    def T(self) -> np.array:
        """Lag time matrix."""
        if self._T is None:
            self._T = make_time_matrix(self.A, self.B)
        return self._T

    @property
    def q(self) -> np.array:
        """Stationary flux vector."""
        # if self._q is None:
        #     self.compute()
        assert self._q is not None
        return self._q

    @property
    def t(self) -> np.array:
        """Vector of local mean first passage times."""
        # if self._t is None:
        #     self.compute()
        assert self._t is not None
        return self._t

    @property
    def p(self) -> np.array:
        """Vector of stationary probabilities."""
        # if self._p is None:
        #     self.compute()
        assert self._p is not None
        return self._p

    @property
    def eigval(self) -> float:
        """Dominant eigenvalue (should be one or very close to it)."""
        # if self._eigval is None:
        #     self.compute()
        return self._eigval

    @property
    def mfpt(self) -> float:
        """Global mean first passage time."""
        # if self._mfpt is None:
        #     self.compute()
        assert self._mfpt is not None
        return self._mfpt

    def compute(self, prev_q: Optional[np.array] = None) -> float:
        """Compute observables.

        Obtain the stationary flux, local mean first passage times,
        global mean first passage time, and stationary probability.

        Parameters
        ----------
        prev_q : np.array, optional
            A guess for the stationary flux vector

        Returns
        -------
        mfpt : float
            The value of the mean first passage time if the
            computation was successful, None otherwise.

        Raises
        ------
        ValueError
            If something goes wrong with the eigenvalue computation.

        """
        self._K = make_stochastic_matrix(self.A)
        self._T = make_time_matrix(self.A, self.B)
        K, T = self._K, self._T

        if prev_q is not None:
            logging.debug('Computing matrix-vector product.')
            self._eigval = None
            self._q = K.T.dot(prev_q)
            self._q /= np.sum(self._q)  # Normalize (K could be substochastic)
        else:
            # The dominant_eigenvector method may raise an exception if
            # the transition matrix is not valid.  We simply let the
            # exception propagate.
            logging.debug('Solving eigenvalue problem.')
            self._eigval, self._q = dominant_eigenvector(K.T)

        # Compute vector of local MFPTs.
        M = self.A.shape[0]
        e = np.ones(M, dtype=np.float64)
        KT = K.multiply(T).toarray()
        self._t = KT.dot(e)

        # Compute vector of stationary probabilities.
        p = np.multiply(self.q, self.t)
        self._p = p / np.linalg.norm(p, 1)

        # Compute MFPT.
        if self.product_indices:
            sum_products = self.q[self.product_indices].sum()
            self._mfpt = self.q.dot(self.t) / sum_products

        return self._mfpt

    def update(self, transition: Transition) -> None:
        """Update matrices with a transition.

        Transitions are assumed to be from a trajectory fragment
        started and stopped at two different milestones.  No
        consistency checks are done in this method.

        """
        initial = transition.initial_milestone
        if initial not in self.milestones.products:
            final = transition.final_milestone
            i, j = initial.index, final.index
            self.A[i, j] += 1
            self.B[i, j] += transition.lag_time
            self._reset_computed_quantities()

    def save(self, transition_matrix: str, lag_time_matrix: str,
             stationary_flux: str, local_mfpts: str,
             stationary_probability: str) -> None:
        """Save matrices to files."""
        scipy.io.mmwrite('A.mtx', self.A)
        scipy.io.mmwrite('B.mtx', self.B)

        logging.debug('Saving transition matrix to {!r}.'
                      .format(transition_matrix))
        scipy.io.mmwrite(transition_matrix, self.K)

        logging.debug('Saving lag time matrix to {!r}.'
                      .format(lag_time_matrix))
        scipy.io.mmwrite(lag_time_matrix, self.T)

        logging.debug('Saving stationary flux vector to {!r}.'
                      .format(stationary_flux))
        np.savetxt(stationary_flux, self.q)

        logging.debug('Saving vector of local MFPTs to {!r}.'
                      .format(local_mfpts))
        np.savetxt(local_mfpts, self.t)

        logging.debug('Saving vector of stationary probabilities {!r}.'
                      .format(stationary_probability))
        np.savetxt(stationary_probability, np.multiply(self.q, self.t))

    def _connect_products_to_reactants(self, milestones: Milestones) -> None:
        """Modify matrices so that the product goes to the reactant."""

        if not milestones.products or not milestones.reactants:
            return

        # XXX Add support for multiple reactants and products.
        i = milestones.products[0].index
        j = milestones.reactants[0].index

        A = self.A
        B = self.B

        # If we come across the result from an equilibrium simulation,
        # where the product milestone is sending trajectories to other
        # neighbors (instead of to the product), then we zero out all
        # the entries from the product to its neighbors before
        # connecting it to the reactant.
        _, k = A[i, :].nonzero()
        A[i, k] = 0

        # Now connect the product to the reactant.
        A[i, j] = 1

        # We add a very small value to B.  Setting B[j, i] to zero
        # would not work because these are sparse matrices and zeros
        # are not stored.
        B[i, j] = sys.float_info.epsilon

def make_stochastic_matrix(A: np.array) -> np.array:
    """Convert to row-stochastic matrix.

    Normalizes (in the 1-norm) each row of the matrix A and returns
    the result.
    """
    K = sparse.csr_matrix(A, dtype=np.float64)

    for i in range(K.shape[0]):
        l = K.indptr[i:i + 2]
        if l[0] == l[1]:
            continue
        data = K.data[l[0]:l[1]]
        norm1 = np.sum(data)
        assert norm1 > 0.0
        data = data / norm1
        K.data[l[0]:l[1]] = data

    return K

def make_time_matrix(A: np.array, B: np.array) -> np.array:
    """Compute matrix of average local lag times."""
    assert A.shape == B.shape

    AA = sparse.csr_matrix(A, dtype=np.float64)
    T = sparse.csr_matrix(B, dtype=np.float64)

    for i in range(T.shape[0]):
        lt = T.indptr[i:i+2]
        if lt[0] == lt[1]:
            continue

        la = AA.indptr[i:i+2]

        Tdata = T.data[lt[0]:lt[1]]
        AAdata = AA.data[la[0]:la[1]]
        data = np.divide(Tdata, AAdata)
        T.data[lt[0]:lt[1]] = data

    return T

redpajama_set_name: RedPajamaGithub


text:
/*globals JSDOC, Opt */

/**
	@overview
	@date $Date: 2008-06-08 22:57:25 +0100 (Sun, 08 Jun 2008) $
	@version $Revision: 638 $
	@location $HeadURL: https://jsdoc-toolkit.googlecode.com/svn/tags/jsdoc_toolkit-2.0.1/jsdoc-toolkit/app/lib/JSDOC.js $
 */

/**
	This is the main container for the JSDOC application.
	@namespace
*/
JSDOC = {
};

/**
	@requires Opt
 */
//if (typeof arguments == "undefined") arguments = [];
JSDOC.opt = Opt.get(
	[],
	{
		d: "directory",
		c: "conf",
		t: "template",
		r: "recurse",
		x: "ext",
		p: "private",
		a: "allfunctions",
		e: "encoding",
		n: "nocode",
		o: "out",
		s: "suppress",
		T: "testmode",
		h: "help",
		v: "verbose",
		"D[]": "define",
		"H[]": "handler"
	}
);

/** The current version string of this application. */
JSDOC.VERSION = "2.0.3";

/** Print out usage information and quit. */
JSDOC.usage = function() {
	print("USAGE: java -jar jsrun.jar app/run.js [OPTIONS] <SRC_DIR> <SRC_FILE> ...");
	print("");
	print("OPTIONS:");
	print("  -a or --allfunctions\n          Include all functions, even undocumented ones.\n");
	print("  -c or --conf\n          Load a configuration file.\n");
	print("  -d=<PATH> or --directory=<PATH>\n          Output to this directory (defaults to \"out\").\n");
	print("  -D=\"myVar:My value\" or --define=\"myVar:My value\"\n          Multiple. Define a variable, available in JsDoc as JSDOC.opt.D.myVar\n");
	print("  -e=<ENCODING> or --encoding=<ENCODING>\n          Use this encoding to read and write files.\n");
	print("  -h or --help\n          Show this message and exit.\n");
	//print("  -H=ext:handler or --handler=ext:handler\n          Multiple. Load handlers/handler.js to handle files with .ext names.\n");
	print("  -n or --nocode\n          Ignore all code, only document comments with @name tags.\n");
	print("  -o=<PATH> or --out=<PATH>\n          Print log messages to a file (defaults to stdout).\n");
	print("  -p or --private\n          Include symbols tagged as private, underscored and inner symbols.\n");
	print("  -r=<DEPTH> or --recurse=<DEPTH>\n          Descend into src directories.\n");
	print("  -s or --suppress\n          Suppress source code output.\n");
	print("  -t=<PATH> or --template=<PATH>\n          Required. Use this template to format the output.\n");
	print("  -T or --test\n          Run all unit tests and exit.\n");
	print("  -v or --verbose\n          Provide verbose feedback about what is happening.\n");
	print("  -x=<EXT>[,EXT]... or --ext=<EXT>[,EXT]...\n          Scan source files with the given extension/s (defaults to js).\n");

//	quit();
};

/*t:
	plan(4, "Testing JSDOC namespace.");

	is(
		typeof JSDOC,
		"object",
		"JSDOC.usage is a function."
	);

	is(
		typeof JSDOC.VERSION,
		"string",
		"JSDOC.VERSION is a string."
	);

	is(
		typeof JSDOC.usage,
		"function",
		"JSDOC.usage is a function."
	);

	is(
		typeof JSDOC.opt,
		"object",
		"JSDOC.opt is a object."
	);
 */

// if (this.IO) IO.includeDir("lib/JSDOC/");


text:
extern "C" {
#pragma  warning(disable:4200)     // zero-sized array in struct/union
#include <usbdrivr.h>
#pragma  warning(default:4200)

#include <wdfusb.h>
#include <wdfminiport.h>
#include "FxDynamics.h"
#include "VfFxDynamics.h"
}


text:
package org.keycloak.keys;

import org.keycloak.component.ComponentModel;
import org.keycloak.models.RealmModel;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.List;

/**
 * @author Stian Thorgersen
 */
public abstract class AbstractRsaKeyProvider implements KeyProvider {

    private final boolean enabled;

    private final boolean active;

    private final ComponentModel model;

    private final Keys keys;

    public AbstractRsaKeyProvider(RealmModel realm, ComponentModel model) {
        this.model = model;

        this.enabled = model.get(Attributes.ENABLED_KEY, true);
        this.active = model.get(Attributes.ACTIVE_KEY, true);

        if (model.hasNote(Keys.class.getName())) {
            keys = model.getNote(Keys.class.getName());
        } else {
            keys = loadKeys(realm, model);
            model.setNote(Keys.class.getName(), keys);
        }
    }

    protected abstract Keys loadKeys(RealmModel realm, ComponentModel model);

    @Override
    public final String getKid() {
        return isActive() ? keys.getKid() : null;
    }

    @Override
    public final PrivateKey getPrivateKey() {
        return isActive() ? keys.getKeyPair().getPrivate() : null;
    }

    @Override
    public final PublicKey getPublicKey(String kid) {
        return isEnabled() && kid.equals(keys.getKid()) ? keys.getKeyPair().getPublic() : null;
    }

    @Override
    public X509Certificate getCertificate(String kid) {
        return isEnabled() && kid.equals(keys.getKid()) ? keys.getCertificate() : null;
    }

    @Override
    public final List<KeyMetadata> getKeyMetadata() {
        String kid = keys.getKid();
        PublicKey publicKey = keys.getKeyPair().getPublic();
        if (kid != null && publicKey != null) {
            KeyMetadata k = new KeyMetadata();
            k.setProviderId(model.getId());
            k.setProviderPriority(model.get(Attributes.PRIORITY_KEY, 0l));
            k.setKid(kid);
            if (isActive()) {
                k.setStatus(KeyMetadata.Status.ACTIVE);
            } else if (isEnabled()) {
                k.setStatus(KeyMetadata.Status.PASSIVE);
            } else {
                k.setStatus(KeyMetadata.Status.DISABLED);
            }
            k.setType(KeyMetadata.Type.RSA);
            k.setPublicKey(publicKey);
            k.setCertificate(keys.getCertificate());
            return Collections.singletonList(k);
        } else {
            return Collections.emptyList();
        }
    }

    @Override
    public void close() {
    }

    private boolean isEnabled() {
        return keys != null && enabled;
    }

    private boolean isActive() {
        return isEnabled() && active;
    }

    public static class Keys {
        private String kid;
        private KeyPair keyPair;
        private X509Certificate certificate;

        public Keys(String kid, KeyPair keyPair, X509Certificate certificate) {
            this.kid = kid;
            this.keyPair = keyPair;
            this.certificate = certificate;
        }

        public String getKid() {
            return kid;
        }

        public KeyPair getKeyPair() {
            return keyPair;
        }

        public X509Certificate getCertificate() {
            return certificate;
        }
    }

}


text:
#include <osc/reader/types/OscInteger.h>
#include <tools/ByteBuffer.h>
#include <osc/exceptions/CharConversionException.h>
#include <limits>

OscInteger::OscInteger(ByteBuffer* packet, qint32 pos)
: OscValue('i', packet, pos)
{
	mPacket->getInt();
}

qint32 OscInteger::get()
{
	return mPacket->getInt(mPos);
}

bool OscInteger::toBoolean()
{
	return (get() != 0);
}

QByteArray OscInteger::toBytes()
{
	qint32 i = get();
	QByteArray bytes(4, 0);
	bytes.insert(0, (char*)&i, 4);
	return bytes;
}

char OscInteger::toChar()
{
	qint32 i = get();
	if (i > std::numeric_limits<char>::min() && i < std::numeric_limits<char>::max())
		return (char)get();
	else
		throw CharConversionException();
}

double OscInteger::toDouble()
{
	return get();
}

qint64 OscInteger::toLong()
{
	return get();
}

Midi OscInteger::toMIDI()
{
	return Midi(toBytes());
}

RGBA OscInteger::toRGBA()
{
	return RGBA(toBytes());
}

QString OscInteger::toString()
{
	return QString::number(get());
}


text:
"""Provides tools to manage iterable types."""

from __future__ import absolute_import

__all__ = [
    'isiterable', 'ensureiterable', 'first', 'last', 'itemat', 'sliceit',
    'hashiter'
]

from collections import Iterable

def isiterable(element, exclude=None):
    """Check whatever or not if input element is an iterable.

    :param element: element to check among iterable types.
    :param type/tuple exclude: not allowed types in the test.

    :Example:

    >>> isiterable({})
    True
    >>> isiterable({}, exclude=dict)
    False
    >>> isiterable({}, exclude=(dict,))
    False
    """

    # check for allowed type
    allowed = exclude is None or not isinstance(element, exclude)
    result = allowed and isinstance(element, Iterable)

    return result

def ensureiterable(value, iterable=list, exclude=None):
    """Convert a value into an iterable if it is not.

    :param object value: object to convert
    :param type iterable: iterable type to apply (default: list)
    :param type/tuple exclude: types to not convert

    :Example:

    >>> ensureiterable([])
    []
    >>> ensureiterable([], iterable=tuple)
    ()
    >>> ensureiterable('test', exclude=str)
    ['test']
    >>> ensureiterable('test')
    ['t', 'e', 's', 't']
    """

    result = value

    if not isiterable(value, exclude=exclude):
        result = [value]
        result = iterable(result)

    else:
        result = iterable(value)

    return result

def first(iterable, default=None):
    """Try to get input iterable first item or default if iterable is empty.

    :param Iterable iterable: iterable to iterate on. Must provide the method
        __iter__.
    :param default: default value to get if input iterable is empty.
    :raises TypeError: if iterable is not an iterable value.

    :Example:

    >>> first('tests')
    't'
    >>> first('', default='test')
    'test'
    >>> first([])
    None
    """

    result = default

    # start to get the iterable iterator (raises TypeError if iter)
    iterator = iter(iterable)
    # get first element
    try:
        result = next(iterator)
    except StopIteration: # if no element exist, result equals default
        pass

    return result

def last(iterable, default=None):
    """Try to get the last iterable item by successive iteration on it.

    :param Iterable iterable: iterable to iterate on. Must provide the method
        __iter__.
    :param default: default value to get if input iterable is empty.
    :raises TypeError: if iterable is not an iterable value.

    :Example:

    >>> last('tests')
    's'
    >>> last('', default='test')
    'test'
    >>> last([])
    None"""

    result = default

    iterator = iter(iterable)

    while True:
        try:
            result = next(iterator)

        except StopIteration:
            break

    return result

def itemat(iterable, index):
    """Try to get the item at index position in iterable after iterate on
    iterable items.

    :param iterable: object which provides the method __getitem__ or __iter__.
    :param int index: item position to get.
    """

    result = None

    handleindex = True

    if isinstance(iterable, dict):
        handleindex = False

    else:
        try:
            result = iterable[index]
        except TypeError:
            handleindex = False

    if not handleindex:
        iterator = iter(iterable)

        if index < 0:  # ensure index is positive
            index += len(iterable)

        while index >= 0:
            try:
                value = next(iterator)

            except StopIteration:
                raise IndexError(
                    "{0} index {1} out of range".format(
                        iterable.__class__, index
                    )
                )

            else:
                if index == 0:
                    result = value
                    break
                index -= 1

    return result

def sliceit(iterable, lower=0, upper=None):
    """Apply a slice on input iterable.

    :param iterable: object which provides the method __getitem__ or __iter__.
    :param int lower: lower bound from where start to get items.
    :param int upper: upper bound from where finish to get items.
    :return: sliced object of the same type of iterable if not dict, or specific
        object. otherwise, simple list of sliced items.
    :rtype: Iterable
    """

    if upper is None:
        upper = len(iterable)

    try:
        result = iterable[lower: upper]

    except TypeError:  # if iterable does not implement the slice method
        result = []

        if lower < 0:  # ensure lower is positive
            lower += len(iterable)

        if upper < 0:  # ensure upper is positive
            upper += len(iterable)

        if upper > lower:
            iterator = iter(iterable)

            for index in range(upper):
                try:
                    value = next(iterator)

                except StopIteration:
                    break

                else:
                    if index >= lower:
                        result.append(value)

    iterablecls = iterable.__class__
    if not(isinstance(result, iterablecls) or issubclass(iterablecls, dict)):
        try:
            result = iterablecls(result)

        except TypeError:
            pass

    return result

def hashiter(iterable):
    """Try to hash input iterable in doing the sum of its content if not
    hashable.

    Hash method on not iterable depends on type:

    hash(iterable.__class__) + ...

        - dict: sum of (hash(key) + 1) * (hash(value) + 1).
        - Otherwise: sum of (pos + 1) * (hash(item) + 1)."""

    result = 0

    try:
        result = hash(iterable)

    except TypeError:

        result = hash(iterable.__class__)

        isdict = isinstance(iterable, dict)

        for index, entry in enumerate(list(iterable)):
            entryhash = hashiter(entry) + 1

            if isdict:
                entryhash *= hashiter(iterable[entry]) + 1

            else:
                entryhash *= index + 1

            result += entryhash

    return result


text:
@implementation UUMessage
- (void)setWithDict:(NSDictionary *)dict{

    self.strIcon = dict[@"strIcon"];
    self.strName = dict[@"strName"];
    self.strId = dict[@"strId"];
    self.strTime = [self changeTheDateString:dict[@"strTime"]];
    self.from = [dict[@"from"] intValue];

    switch ([dict[@"type"] integerValue]) {

        case 0:
            self.type = UUMessageTypeText;
            self.strContent = dict[@"strContent"];
            break;

        case 1:
            self.type = UUMessageTypePicture;
            self.picture = dict[@"picture"];
            break;

        case 2:
            self.type = UUMessageTypeVoice;
            self.voice = dict[@"voice"];
            self.strVoiceTime = dict[@"strVoiceTime"];
            break;

        default:
            break;
    }
}

//"08-10 晚上08:09:41.0" ->
//"昨天 上午10:09"或者"2012-08-10 凌晨07:09"
- (NSString *)changeTheDateString:(NSString *)Str
{
    NSString *subString = [Str substringWithRange:NSMakeRange(0, 19)];
    NSDate *lastDate = [NSDate dateFromString:subString withFormat:@"yyyy-MM-dd HH:mm:ss"];
	NSTimeZone *zone = [NSTimeZone systemTimeZone];
	NSInteger interval = [zone secondsFromGMTForDate:lastDate];
	lastDate = [lastDate dateByAddingTimeInterval:interval];

    NSString *dateStr;  //年月日
    NSString *period;   //时间段
    NSString *hour;     //时

    if ([lastDate year]==[[NSDate date] year]) {
        NSInteger days = [NSDate daysOffsetBetweenStartDate:lastDate endDate:[NSDate date]];
        if (days <= 2) {
            dateStr = [lastDate stringYearMonthDayCompareToday];
        }else{
            dateStr = [lastDate stringMonthDay];
        }
    }else{
        dateStr = [lastDate stringYearMonthDay];
    }

    if ([lastDate hour]>=5 && [lastDate hour]<12) {
        period = @"AM";
        hour = [NSString stringWithFormat:@"%02d",(int)[lastDate hour]];
    }else if ([lastDate hour]>=12 && [lastDate hour]<=18){
        period = @"PM";
        hour = [NSString stringWithFormat:@"%02d",(int)[lastDate hour]-12];
    }else if ([lastDate hour]>18 && [lastDate hour]<=23){
        period = @"Night";
        hour = [NSString stringWithFormat:@"%02d",(int)[lastDate hour]-12];
    } else {
        period = @"Dawn";
        hour = [NSString stringWithFormat:@"%02d",(int)[lastDate hour]];
    }
    return [NSString stringWithFormat:@"%@ %@ %@:%02d",dateStr,period,hour,(int)[lastDate minute]];
}

- (void)minuteOffSetStart:(NSString *)start end:(NSString *)end
{
    if (!start) {
        self.showDateLabel = YES;
        return;
    }

    NSString *subStart = [start substringWithRange:NSMakeRange(0, 19)];
    NSDate *startDate = [NSDate dateFromString:subStart withFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSString *subEnd = [end substringWithRange:NSMakeRange(0, 19)];
    NSDate *endDate = [NSDate dateFromString:subEnd withFormat:@"yyyy-MM-dd HH:mm:ss"];

    //这个是相隔的秒数
    NSTimeInterval timeInterval = [startDate timeIntervalSinceDate:endDate];

    //相距5分钟显示时间Label
    if (fabs (timeInterval) > 5*60) {
        self.showDateLabel = YES;
    }else{
        self.showDateLabel = NO;
    }

}
@end


text:
namespace ash::cloud_upload {

bool CloudUploadUIConfig::IsWebUIEnabled(
    content::BrowserContext* browser_context) {
  return ash::features::IsUploadOfficeToCloudEnabled();
}

CloudUploadUI::CloudUploadUI(content::WebUI* web_ui)
    : ui::MojoWebDialogUI{web_ui} {
  content::WebUIDataSource* source = content::WebUIDataSource::CreateAndAdd(
      Profile::FromWebUI(web_ui), chrome::kChromeUICloudUploadHost);

  static constexpr webui::LocalizedString kStrings[] = {
      {"cancel", IDS_CANCEL},
  };
  source->AddLocalizedStrings(kStrings);
  webui::SetupWebUIDataSource(
      source, base::make_span(kCloudUploadResources, kCloudUploadResourcesSize),
      IDR_CLOUD_UPLOAD_MAIN_HTML);
}

CloudUploadUI::~CloudUploadUI() = default;

void CloudUploadUI::SetDialogArgs(mojom::DialogArgsPtr args) {
  dialog_args_ = std::move(args);
}

void CloudUploadUI::BindInterface(
    mojo::PendingReceiver<mojom::PageHandlerFactory> pending_receiver) {
  if (factory_receiver_.is_bound()) {
    factory_receiver_.reset();
  }
  factory_receiver_.Bind(std::move(pending_receiver));
}

void CloudUploadUI::CreatePageHandler(
    mojo::PendingReceiver<mojom::PageHandler> receiver) {
  page_handler_ = std::make_unique<CloudUploadPageHandler>(
      Profile::FromWebUI(web_ui()), std::move(dialog_args_),
      std::move(receiver),
      // base::Unretained() because |page_handler_| will not out-live |this|.
      base::BindOnce(&CloudUploadUI::RespondAndCloseDialog,
                     base::Unretained(this)));
}

void CloudUploadUI::RespondAndCloseDialog(mojom::UserAction action) {
  base::Value::List args;
  switch (action) {
    case mojom::UserAction::kCancel:
      args.Append(kUserActionCancel);
      break;
    case mojom::UserAction::kSetUpGoogleDrive:
      args.Append(kUserActionSetUpGoogleDrive);
      break;
    case mojom::UserAction::kSetUpOneDrive:
      args.Append(kUserActionSetUpOneDrive);
      break;
    case mojom::UserAction::kUploadToGoogleDrive:
      args.Append(kUserActionUploadToGoogleDrive);
      break;
    case mojom::UserAction::kUploadToOneDrive:
      args.Append(kUserActionUploadToOneDrive);
      break;
    case mojom::UserAction::kConfirmOrUploadToGoogleDrive:
      args.Append(kUserActionConfirmOrUploadToGoogleDrive);
      break;
    case mojom::UserAction::kConfirmOrUploadToOneDrive:
      args.Append(kUserActionConfirmOrUploadToOneDrive);
      break;
  }
  ui::MojoWebDialogUI::CloseDialog(args);
}

WEB_UI_CONTROLLER_TYPE_IMPL(CloudUploadUI)

}  // namespace ash::cloud_upload


text:
from django.template import Library
from django.urls import reverse
from django.shortcuts import get_object_or_404

from video.models import TaggedVideo
from video.forms import VideoUploadForm, VideoUploadTagForm

register = Library()

@register.inclusion_tag("video/uploadform.html")
def uploadform(identifier=None, redirect='/'):
    """
    Generate a form to upload a new video.
    """

    if identifier is None:
        form = VideoUploadTagForm(initial={'tag': identifier, 'redirect': redirect})
    else:
        form = VideoUploadForm(initial={'redirect': redirect})

    return {
     'form': form,
    }

@register.inclusion_tag("video/player.html")
def videoplayer(elementid, category, tag, width=300, height=200):
    """
    Generate an HTML video player for a video given the category and tag
    """

    try:
        video = TaggedVideo.objects.get(category=category, tag=tag)
    except:
        video = None

    return {
        'elementid': elementid,
        'video': video,
        'width': width,
        'height': height,
    }


text:
package org.locationtech.geogig.model.impl;

import static com.google.common.base.Objects.equal;
import static com.google.common.base.Preconditions.checkNotNull;

import org.locationtech.geogig.model.ObjectId;
import org.locationtech.geogig.model.RevCommit;
import org.locationtech.geogig.model.RevPerson;

import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;

/**
 * A reference to a commit in the DAG.
 *
 */
class RevCommitImpl extends AbstractRevObject implements RevCommit {

    private ObjectId treeId;

    private ImmutableList<ObjectId> parentIds;

    private RevPerson author;

    private RevPerson committer;

    private String message;

    /**
     * Constructs a new {@code RevCommit} with the given {@link ObjectId}.
     *
     * @param id the object id to use
     */
    public RevCommitImpl(final ObjectId id) {
        super(id);
    }

    @Override
    public TYPE getType() {
        return TYPE.COMMIT;
    }

    /**
     * Constructs a new {@code RevCommit} with the given parameters.
     *
     * @param id the {@link ObjectId} to use
     * @param treeId the {@link ObjectId} of the tree this commit points to
     * @param parentIds a list of parent commits' {@link ObjectId}s
     * @param author the author of this commit
     * @param committer the committer of this commit
     * @param message the message for this commit
     */
    public RevCommitImpl(final ObjectId id, ObjectId treeId, ImmutableList<ObjectId> parentIds,
            RevPerson author, RevPerson committer, String message) {
        this(id);
        checkNotNull(treeId);
        checkNotNull(parentIds);
        checkNotNull(author);
        checkNotNull(committer);
        checkNotNull(message);
        this.treeId = treeId;
        this.parentIds = parentIds;
        this.author = author;
        this.committer = committer;
        this.message = message;
    }

    @Override
    public ObjectId getTreeId() {
        return treeId;
    }

    @Override
    public ImmutableList<ObjectId> getParentIds() {
        return this.parentIds;
    }

    @Override
    public Optional<ObjectId> parentN(int parentIndex) {
        Optional<ObjectId> parent = Optional.absent();
        if (parentIds.size() > parentIndex) {
            parent = Optional.of(parentIds.get(parentIndex));
        }
        return parent;
    }

    @Override
    public RevPerson getAuthor() {
        return author;
    }

    @Override
    public RevPerson getCommitter() {
        return committer;
    }

    @Override
    public String getMessage() {
        return message;
    }

    /**
     * @return the {@code RevCommit} as a readable string
     */
    @Override
    public String toString() {
        return "Commit[" + getId() + ", '" + message + "']";
    }

    /**
     * Equality is based on author, committer, message, parent ids, and tree id.
     *
     * @see AbstractRevObject#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof RevCommit) && !super.equals(o)) {
            return false;
        }
        RevCommit c = (RevCommit) o;
        return equal(getAuthor(), c.getAuthor()) && equal(getCommitter(), c.getCommitter())
                && equal(getMessage(), c.getMessage()) && equal(getParentIds(), c.getParentIds())
                && equal(getTreeId(), c.getTreeId());
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(getId(), getTreeId(), getParentIds(), getAuthor(), getCommitter(),
                getMessage());
    }
}


text:
{-# LANGUAGE DeriveGeneric     #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell   #-}

module Service.Wechat.Internal where

import           Base

import           Control.Exception (SomeException)
import           Control.Lens
import qualified Data.Map          as Map
import           Text.XML

data WechatMessageReply = WechatMessageReply
  { _wechatMessageReply_FromUserName ::       Text --是 开发者微信号
  , _wechatMessageReply_ToUserName   ::       Text --是 接收方帐号(收到的OpenID)
  , _wechatMessageReply_CreateTime   ::        Int --是 消息创建时间 (整型)
  , _wechatMessageReply_MsgType      :: Maybe Text --是 image music news text video 语音,voice
  , _wechatMessageReply_ArticleCount :: Maybe Text --是 图文消息个数,限制为8条以内
  , _wechatMessageReply_Articles     :: Maybe Text --是 多条图文消息信息,默认第一个item为大图,注意,如果图文数超过8,则将会无响应
  , _wechatMessageReply_Content      :: Maybe Text --是 回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示)
  , _wechatMessageReply_Description  :: Maybe Text --否 视频消息的描述 否 音乐描述 是 图文消息描述
  , _wechatMessageReply_HQMusicUrl   :: Maybe Text --否 高质量音乐链接,WIFI环境优先使用该链接播放音乐
  , _wechatMessageReply_MediaId      :: Maybe Text --是 通过素材管理中的接口上传多媒体文件,得到的id
  , _wechatMessageReply_MusicURL     :: Maybe Text --否 音乐链接
  , _wechatMessageReply_PicUrl       :: Maybe Text --是 图片链接,支持JPG、PNG格式,较好的效果为大图360*200,小图200*200
  , _wechatMessageReply_ThumbMediaId :: Maybe Text --是 缩略图的媒体id,通过素材管理中的接口上传多媒体文件,得到的id
  , _wechatMessageReply_Title        :: Maybe Text --否 视频消息的标题 否 音乐标题 是 图文消息标题
  , _wechatMessageReply_Url          :: Maybe Text --是 点击图文消息跳转链接
  } deriving (Show,Generic)
$(deriveJSON prefixOptions ''WechatMessageReply)
makeLenses ''WechatMessageReply

data WechatMessage = WechatMessage
  { _wechatMessage_FromUserName ::       Text --发送方微信号,若为普通用户,则是一个OpenID
  , _wechatMessage_ToUserName   ::       Text --接收方微信号
  , _wechatMessage_CreateTime   ::       Int  --消息创建时间 (整型)
  , _wechatMessage_MsgType      ::       Text --image location text 小视频为shortvideo 消息类型,link 视频为video 语音为voice
  , _wechatMessage_Content      :: Maybe Text --文本消息内容
  , _wechatMessage_Description  :: Maybe Text --消息描述
  , _wechatMessage_Format       :: Maybe Text --语音格式,如amr,speex等
  , _wechatMessage_Label        :: Maybe Text --地理位置信息
  , _wechatMessage_Location_X   :: Maybe Text --地理位置维度
  , _wechatMessage_Location_Y   :: Maybe Text --地理位置经度
  , _wechatMessage_MediaId      :: Maybe Text --图片消息媒体id,可以调用多媒体文件下载接口拉取数据。
  , _wechatMessage_MsgId        :: Maybe Int  --消息id,64位整型
  , _wechatMessage_PicUrl       :: Maybe Text --图片链接(由系统生成)
  , _wechatMessage_Recognition  :: Maybe Text --语音识别结果,UTF8编码
  , _wechatMessage_Scale        :: Maybe Text --地图缩放大小
  , _wechatMessage_ThumbMediaId :: Maybe Text --视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
  , _wechatMessage_Title        :: Maybe Text --消息标题
  , _wechatMessage_Url          :: Maybe Text --消息链接
  , _wechatMessage_Event        :: Maybe Text --事件类型,subscribe(订阅)、unsubscribe(取消订阅)
  , _wechatMessage_EventKey     :: Maybe Text --事件KEY值,qrscene_为前缀,后面为二维码的参数值
  , _wechatMessage_Ticket       :: Maybe Text --二维码的ticket,可用来换取二维码图片
  , _wechatMessage_Latitude     :: Maybe Text --地理位置纬度
  , _wechatMessage_Longitude    :: Maybe Text --地理位置经度
  , _wechatMessage_Precision    :: Maybe Text --地理位置精度
  } deriving (Show,Generic)
$(deriveJSON prefixOptions ''WechatMessage)
makeLenses ''WechatMessage

toWechatMessage :: Text -> Either SomeException WechatMessage
toWechatMessage xml = case parseText def (cs xml) of
  Left    e -> Left e
  Right doc -> toM $ Map.fromList $ fmap to $ filter isElem $ elementNodes $ documentRoot doc
  where isElem (NodeElement _) = True
        isElem _               = False
        isCont (NodeContent _) = True
        isCont _               = False
        mayH (NodeContent n:_) = Just n
        mayH _                 = Nothing
        to     (NodeElement e) = (nameLocalName $ elementName e, mayH $ filter isCont $ elementNodes e)
        toM    map             =
          let find  k = join $ Map.lookup k map
              get   k = fromMaybe "" $ find k
              findI   = fmap (read.cs) . find
              getI    = fromMaybe 0  . findI
          in  Right $ WechatMessage
                (get   "FromUserName")
                (get   "ToUserName")
                (getI  "CreateTime")
                (get   "MsgType")
                (find  "Content")
                (find  "Description")
                (find  "Format")
                (find  "Label")
                (find  "Location_X")
                (find  "Location_Y")
                (find  "MediaId")
                (findI "MsgId")
                (find  "PicUrl")
                (find  "Recognition")
                (find  "Scale")
                (find  "ThumbMediaId")
                (find  "Title")
                (find  "Url")
                (find  "Event")
                (find  "EventKey")
                (find  "Ticket")
                (find  "Latitude")
                (find  "Longitude")
                (find  "Precision")

replyWechatMessage' :: (MonadIO m, MonadThrow m)
                   => Text -> (WechatMessage -> WechatMessageReply -> AppM m (Maybe WechatMessageReply)) -> AppM m Text
replyWechatMessage' body router = do
  infoLn $ "Wechat Request "  <> body
  a <- action body
  infoLn $ "Wechat Response " <> a
  return a
  where action body = case toWechatMessage body of
            Left  e -> throwM e
            Right a -> replyMessage a >>= router a >>= renderMessage
        renderMessage :: (MonadIO m, MonadThrow m) => Maybe WechatMessageReply -> AppM m Text
        renderMessage Nothing  = return "success"
        renderMessage (Just a) = return
                               $ cs
                               $ renderText def
                               $ Document (Prologue [] Nothing []) (Element "xml" Map.empty (nodes a)) []
        node n (Just v) = Just $ NodeElement $ Element n Map.empty [NodeContent v]
        node _ Nothing  = Nothing
        nodes a         = catMaybes
                        [ node "FromUserName" (Just $ _wechatMessageReply_FromUserName a)
                        , node "ToUserName"   (Just $ _wechatMessageReply_ToUserName   a)
                        , node "CreateTime"   (Just $ showText $ _wechatMessageReply_CreateTime   a)
                        , node "MsgType"             (_wechatMessageReply_MsgType      a)
                        , node "ArticleCount"        (_wechatMessageReply_ArticleCount a)
                        , node "Articles"            (_wechatMessageReply_Articles     a)
                        , node "Content"             (_wechatMessageReply_Content      a)
                        , node "Description"         (_wechatMessageReply_Description  a)
                        , node "HQMusicUrl"          (_wechatMessageReply_HQMusicUrl   a)
                        , node "MediaId"             (_wechatMessageReply_MediaId      a)
                        , node "MusicURL"            (_wechatMessageReply_MusicURL     a)
                        , node "PicUrl"              (_wechatMessageReply_PicUrl       a)
                        , node "ThumbMediaId"        (_wechatMessageReply_ThumbMediaId a)
                        , node "Title"               (_wechatMessageReply_Title        a)
                        , node "Url"                 (_wechatMessageReply_Url          a)
                        ]
        replyMessage :: (MonadIO m, MonadThrow m) => WechatMessage -> AppM m WechatMessageReply
        replyMessage msg = return $ WechatMessageReply
                          (_wechatMessage_ToUserName   msg)
                          (_wechatMessage_FromUserName msg)
                          (_wechatMessage_CreateTime   msg)
                          Nothing Nothing Nothing Nothing
                          Nothing Nothing Nothing Nothing
                          Nothing Nothing Nothing Nothing


text:
export = Recorder;

declare class Recorder {
    constructor(audioContext: AudioContext, config?: Recorder.RecorderConfig);
    static download(blob: Blob, filename: string): void;
    init(stream: MediaStream): Promise<void>;
    start(): Promise<MediaStream | undefined>;
    stop(): Promise<Recorder.RecorderResult>;
}

declare namespace Recorder {
    type OnAnalysedHandler = (data: number[], lastNonZero: number) => void;

    interface RecorderConfig {
        onAnalysed?: OnAnalysedHandler | undefined;
    }

    interface RecorderResult {
        blob: Blob;
        buffer: Float32Array[];
    }
}


text:
function wechatShare() {
    const {
        shareTitle,
        shareSubstr,
        shareImgSrc
    } = {
            shareTitle: $.trim($('title').text()),
            shareSubstr: $.trim($('.part-pc-abs-box-in .abs').text()),
            shareImgSrc: $.trim($('.part-video img').attr('src')),
        }
    $('body').append(`

${shareTitle}

${shareSubstr}

    `);
}
wechatShare();


text:
<?php

namespace Drupal\entity_browser;

use Drupal\Core\Plugin\DefaultLazyPluginCollection;

/**
 * A collection of entity browser widgets.
 */
class WidgetsLazyPluginCollection extends DefaultLazyPluginCollection {

  /**
   * Provides uasort() callback to sort plugins.
   */
  public function sortHelper($a, $b) {
    $weight_a = $this->get($a)->getWeight();
    $weight_b = $this->get($b)->getWeight();

    return $weight_a < $weight_b ? -1 : 1;
  }

}


text:
package com.mapswithme.maps.location;

import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;

import com.mapswithme.util.LocationUtils;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.SimpleLogger;

abstract class BaseLocationProvider implements LocationListener
{
  private static final double DEFAULT_SPEED_MPS = 5;

  protected static final Logger sLogger = SimpleLogger.get(BaseLocationProvider.class.getName());
  protected static final long UPDATE_INTERVAL_MS = 500;

  protected abstract void startUpdates();

  protected abstract void stopUpdates();

  protected boolean isLocationBetterThanLast(Location newLocation, Location lastLocation)
  {
    double speed = Math.max(DEFAULT_SPEED_MPS, (newLocation.getSpeed() + lastLocation.getSpeed()) / 2.0);
    double lastAccuracy = (lastLocation.getAccuracy() + speed * LocationUtils.getDiffWithLastLocation(lastLocation, newLocation));
    return (newLocation.getAccuracy() < lastAccuracy);
  }

  protected final boolean isLocationBetterThanLast(Location newLocation)
  {
    if (newLocation == null)
      return false;

    final Location lastLocation = LocationHelper.INSTANCE.getLastLocation();
    return (lastLocation == null || isLocationBetterThanLast(newLocation, lastLocation));
  }

  @Override
  public void onLocationChanged(Location location)
  {
    // Completely ignore locations without lat and lon
    if (location.getAccuracy() <= 0.0)
      return;

    if (isLocationBetterThanLast(location))
    {
      LocationHelper.INSTANCE.initMagneticField(location);
      LocationHelper.INSTANCE.setLastLocation(location);
    }
  }

  @Override
  public void onProviderDisabled(String provider)
  {
    sLogger.d("Disabled location provider: ", provider);
  }

  @Override
  public void onProviderEnabled(String provider)
  {
    sLogger.d("Enabled location provider: ", provider);
  }

  @Override
  public void onStatusChanged(String provider, int status, Bundle extras)
  {
    sLogger.d("Status changed for location provider: ", provider, status);
  }
}


text:
A minimalistic framework for creating modular, composable apps.

# License

MIT


text:
var glpPixelInspector = function (gl) {
  this.gl = gl;

  this.blendProp = null;
  this.blendFuncSFactor = null;
  this.blendFuncDFactor = null;
  this.depthTest = null;
  this.clearColor = null;
  this.vertexShaders = {};
  this.fragmentShaders = {};
  this.programs = [];
  this.programsMap = {};
  this.programUniformLocations = {};
  this.originalPrograms = {};
  this.locationMap = {};
  this.enabled = false;
}

/**
 * Applies uniform to WebGL context
 */
glpPixelInspector.prototype.applyUniform = function (uniform) {
  var loc = uniform.loc;
  var type = uniform.type;
  var value = uniform.value;
  if (type == this.gl.FLOAT) {
    this.gl.uniform1f(loc, value);
    return;
  }
  if (type == this.gl.FLOAT_VEC2) {
    this.gl.uniform2fv(loc, value);
    return;
  }
  if (type == this.gl.FLOAT_VEC3) {
    this.gl.uniform3fv(loc, value);
    return;
  }
  if (type == this.gl.FLOAT_VEC4) {
    this.gl.uniform4fv(loc, value);
    return;
  }
  if (type == this.gl.INT) {
    this.gl.uniform1i(loc, value);
    return;
  }
  if (type == this.gl.INT_VEC2) {
    this.gl.uniform2iv(loc, value);
    return;
  }
  if (type == this.gl.INT_VEC3) {
    this.gl.uniform3iv(loc, value);
    return;
  }
  if (type == this.gl.INT_VEC4) {
    this.gl.uniform4iv(loc, value);
    return;
  }
  if (type == this.gl.BOOL) {
    this.gl.uniform1i(loc, value);
    return;
  }
  if (type == this.gl.BOOL_VEC2) {
    this.gl.uniform2iv(loc, value);
    return;
  }
  if (type == this.gl.BOOL_VEC3) {
    this.gl.uniform3iv(loc, value);
    return;
  }
  if (type == this.gl.BOOL_VEC4) {
    this.gl.uniform4iv(loc, value);
    return;
  }
  if (type == this.gl.FLOAT_MAT2) {
    this.gl.uniformMatrix2fv(loc, false, value);
    return;
  }
  if (type == this.gl.FLOAT_MAT3) {
    this.gl.uniformMatrix3fv(loc, false, value);
    return;
  }
  if (type == this.gl.FLOAT_MAT4) {
    this.gl.uniformMatrix4fv(loc, false, value);
    return;
  }
  if (type == this.gl.SAMPLER_2D || type == this.gl.SAMPLER_CUBE) {
    this.gl.uniform1i(loc, value);
    return;
  }
}

/**
 * Enables the pixel inspector and returns the appropriate fragment shader
 * @return {WebGLShader} Pixel Inspector Shader
 */
glpPixelInspector.prototype.enable = function() {
    this.blendProp = this.gl.getParameter(this.gl.BLEND);
    this.gl.enable(this.gl.BLEND);

    this.blendFuncSFactor = this.gl.getParameter(this.gl.BLEND_SRC_RGB);
    this.blendFuncDFactor = this.gl.getParameter(this.gl.BLEND_DST_RGB);
    this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA);

    this.depthTest = this.gl.getParameter(this.gl.DEPTH_TEST);
    this.gl.disable(this.gl.DEPTH_TEST);

    this.clearColor = this.gl.getParameter(this.gl.COLOR_CLEAR_VALUE);
    this.gl.clearColor(0.0, 1.0, 0.0, 1.0);

    this.switchToProgram();

    this.enabled = true;
}

/**
 * Disable the pixel inspector and returns the appropriate fragment shader
 * @return {WebGLShader} Pixel Inspector Shader
 */
glpPixelInspector.prototype.disable = function() {
    if (!this.enabled) {
      return;
    }
    this.enabled = false;

    if (!this.blendProp) {
      this.gl.disable(this.gl.BLEND);
    } else {
      if (this.blendFuncSFactor && this.blendFuncDFactor) {
        this.gl.blendFunc(this.blendFuncSFactor, this.blendFuncDFactor);
      }
    }

    if (this.depthTest) {
      this.gl.enable(this.gl.DEPTH_TEST);
    }

    if (this.clearColor) {
      this.gl.clearColor.apply(this.gl, this.clearColor);
    }

    var currentProgram = this.gl.getParameter(this.gl.CURRENT_PROGRAM);
    if (currentProgram.__uuid in this.originalPrograms) {
      var newProgram = this.originalPrograms[currentProgram.__uuid];
      this.gl.useProgram(newProgram);
      this.copyUniforms(currentProgram, newProgram);
    }
}

/**
 * Copies uniforms from oldProgram to newProgram
 */
glpPixelInspector.prototype.copyUniforms = function(oldProgram, program) {
  var activeUniforms = this.gl.getProgramParameter(program, this.gl.ACTIVE_UNIFORMS);
  this.locationMap[program.__uuid] = {};

  for (var i=0; i < activeUniforms; i++) {
      var uniform = this.gl.getActiveUniform(program, i);
      var oldLocation = this.gl.getUniformLocation(oldProgram, uniform.name);
      var newLocation = this.gl.getUniformLocation(program, uniform.name);
      if (!oldLocation) {
        continue;
      }
      this.locationMap[program.__uuid][oldLocation.__uuid] = newLocation;

      uniform.loc = newLocation;
      uniform.value = this.gl.getUniform(oldProgram, oldLocation);
      if (uniform.value != null) {
        this.applyUniform(uniform);
      }
  }
}

/**
 * Copies attributes from oldProgram to newProgram
 */
glpPixelInspector.prototype.copyAttributes = function(oldProgram, program) {
  var activeAttributes = this.gl.getProgramParameter(oldProgram, this.gl.ACTIVE_ATTRIBUTES);

  for (var i=0; i < activeAttributes; i++) {
      var attribute = this.gl.getActiveAttrib(oldProgram, i);

      this.gl.bindAttribLocation(program, attribute.index, attribute.name);
      if (attribute.size > 1) {
        this.gl.vertexAttribPointer(
          attribute.index,
          attribute.size,
          attribute.type,
          attribute.normalized,
          attribute.stride,
          attribute.offset
        );
      }

      this.gl.enableVertexAttribArray(attribute.index);
  }
}

/**
 * Switches the current program to the pixel inspector program
 */
glpPixelInspector.prototype.switchToProgram = function() {
  var oldProgram = this.gl.getParameter(this.gl.CURRENT_PROGRAM);
  var program = this.getProgram(oldProgram);
  this.originalPrograms[program.__uuid] = oldProgram;
  this.switchProgram(oldProgram, program);
}

/**
 * Switches the current program and copies over location and attribute data
 */
glpPixelInspector.prototype.switchProgram = function(oldProgram, program) {
  if (!this.enabled) {
    return;
  }
  this.gl.useProgram(program);
  this.copyUniforms(oldProgram, program);
  this.copyAttributes(oldProgram, program);
}

glpPixelInspector.prototype.hasProgram = function(program) {
  return this.programs.indexOf(program.__uuid) >= 0;
}

/**
 * Returns the pixel inspector fragment shader
 * @return {WebGLShader} Pixel Inspector Fragment Shader
 */
glpPixelInspector.prototype.getFragShader = function() {
    var fragShader = this.gl.createShader(this.gl.FRAGMENT_SHADER);
    var shaderStr = 'precision mediump float;' +
        'void main(void) {' +
            'gl_FragColor = vec4(1.0, 0.0, 0.0, 0.10);' +
        '}';

    this.gl.shaderSource(fragShader, shaderStr);
    this.gl.compileShader(fragShader);

    return fragShader;
}

/**
 * Returns the appropriate pixel inspector program
 * @param {WebGLProgram} Original Program
 * @return {WebGLProgram.__uuid} Pixel Inspector Progam
 */
glpPixelInspector.prototype.getProgram = function(originalProgram) {
    if (originalProgram.__uuid in this.programsMap) {
        return this.programsMap[originalProgram.__uuid];
    }

    var program = this.gl.createProgram();

    const attachedShaders = this.gl.getAttachedShaders(originalProgram);
    attachedShaders.forEach(shader => {
      this.storeShaders(program, shader);
    });

    this.gl.attachShader(program, this.vertexShaders[originalProgram.__uuid]);
    this.gl.attachShader(program, this.getFragShader());
    this.gl.linkProgram(program);
    this.gl.validateProgram(program);

    this.programs.push(program.__uuid);
    this.programsMap[originalProgram.__uuid] = program;

    return program;
}

glpPixelInspector.prototype.storeShaders = function(program, shader) {
  var shaderType = this.gl.getShaderParameter(shader, this.gl.SHADER_TYPE);

  // TODO: verify valid input
  // store vertex shaders associated with program
  if (shaderType == this.gl.VERTEX_SHADER) {
    this.vertexShaders[program.__uuid] = shader;
  } else {
    this.fragmentShaders[program.__uuid] = shader;
  }
}

glpPixelInspector.prototype.saveStates = function(arg, truth) {
  if (this.enabled) {
    if (arg == this.gl.DEPTH_TEST) {
      this.depthTest = truth;
      return true;
    } else if (arg == this.gl.BLEND) {
      this.blendProp = truth;
      return true;
    }
  }
  return this.enabled;
}

glpPixelInspector.prototype.storeBlendStates = function(sFactor, dFactor) {
  if (this.enabled) {
    this.blendFuncSFactor = sFactor;
    this.blendFuncDFactor = dFactor;
  }
  return this.enabled;
}

glpPixelInspector.prototype.storeClearColorStates = function(args) {
  // TODO: verify valid input
  if (this.enabled) {
    this.clearColor = args;
  }
  return this.enabled;
}

glpPixelInspector.prototype.uniforms = function(args) {
  if (this.enabled) {
    var program = args[0];
    var location = args[1];
    if (this.programs.indexOf(program.__uuid) >= 0) {
      if (location in this.locationMap[program.__uuid]) {
        // the program is the pixel inspector version and we're using the original location
        args[1] = this.locationMap[program.__uuid][location.__uuid];
      } else {
      }
    } else {
      // the program is not a pixel inspector
      // if they're using the wrong location, lets just swap programs
      args[0] = this.gl.getParameter(this.gl.CURRENT_PROGRAM);
    }
  }
  return args;
}

glpPixelInspector.prototype.hasUniformLocation = function(program, name) {
  if (!(program.__uuid in this.programUniformLocations)) {
    this.programUniformLocations[program.__uuid] = {}
  }
  return (name in this.programUniformLocations[program.__uuid]);
}

glpPixelInspector.prototype.getUniformLocation = function(program, name) {
  if (!(program.__uuid in this.programUniformLocations)) {
    this.programUniformLocations[program.__uuid] = {}
  }
  return this.programUniformLocations[program.__uuid][name];
}

glpPixelInspector.prototype.setUniformLocation = function(program, name, location) {
  location.__uuid = glpHelpers.guid();
  if (!(program.__uuid in this.programUniformLocations)) {
    this.programUniformLocations[program.__uuid] = {}
  }
  this.programUniformLocations[program.__uuid][name] = location;
  return location;
}

glpPixelInspector.prototype.remapLocations = function(args) {
  if (this.enabled) {
    if (args[0] &&
        this.programs.indexOf(this.gl.getParameter(this.gl.CURRENT_PROGRAM).__uuid) >= 0) {
      args[0] =
        this.locationMap[this.gl.getParameter(this.gl.CURRENT_PROGRAM).__uuid][args[0].__uuid];
    }
  }
  return args
}


text:
<?php

    \application\components\EventManager::registerBehaviour(
        '\\application\\components\\UserIdentity',
        new \application\addons\extrasecurity\behaviours\MorePersistedStates
    );

    return array(
        'components' => array(
            'user' => array(
                'behaviors' => array(
                    '\\application\\addons\\extrasecurity\\behaviours\\CheckExtraParams',
                ),
            ),
        ),
    );


text:
module Stalactoast::Conversions

  def convert_background_view(origin, destination)
    dk = KCRToastBackgroundViewKey
    value = origin[:background_view] || origin[:bg_view]
    return unless value
    destination[dk] = value
  end

end


text:
using System;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Umbraco.Core.Exceptions;

namespace Umbraco.Tests.Testing
{
    public abstract class TestOptionAttributeBase : Attribute
    {
        public static TOptions GetTestOptions<TOptions>(MethodInfo method)
            where TOptions : TestOptionAttributeBase, new()
        {
            var attr = ((TOptions[]) method.GetCustomAttributes(typeof (TOptions), true)).FirstOrDefault();
            var type = method.DeclaringType;
            return Get(type, attr);
        }

        public static TOptions GetFixtureOptions<TOptions>(Type type)
            where TOptions : TestOptionAttributeBase, new()
        {
            return Get<TOptions>(type, null);
        }

        public static TOptions GetTestOptions<TOptions>()
            where TOptions : TestOptionAttributeBase, new()
        {
            var test = TestContext.CurrentContext.Test;
            var typeName = test.ClassName;
            var methodName = test.MethodName;
            var type = Type.GetType(typeName, true);
            if (type == null)
                throw new PanicException($"Could not resolve the type from type name {typeName}"); // makes no sense
            var methodInfo = type.GetMethod(methodName); // what about overloads?
            var options = GetTestOptions<TOptions>(methodInfo);
            return options;
        }

        private static TOptions Get<TOptions>(Type type, TOptions attr)
            where TOptions : TestOptionAttributeBase, new()
        {
            while (type != null && type != typeof(object))
            {
                var attr2 = ((TOptions[]) type.GetCustomAttributes(typeof (TOptions), true)).FirstOrDefault();
                if (attr2 != null)
                    attr = attr == null ? attr2 : attr2.Merge(attr);
                type = type.BaseType;
            }
            return attr ?? new TOptions();
        }

        private TOptions Merge<TOptions>(TOptions other)
            where TOptions : TestOptionAttributeBase
        {
            if (other == null) throw new ArgumentNullException(nameof(other));
            if (!(Merge((TestOptionAttributeBase) other) is TOptions merged))
                throw new PanicException("Could not merge test options");
            return merged;
        }

        protected virtual TestOptionAttributeBase Merge(TestOptionAttributeBase other)
        {
            return this;
        }
    }
}


text:
%%%feattype
setting.feattype = {'llc', 'color'};
setting.overlap = [0,0];
setting.stride = [8, 8];
setting.swin = [8, 8];
setting.descriptor = {'c','c'};
%%%color
setting.featsetting.color.descriptor = 1;

%%%for llc
setting.ncluster = 512;
setting.knn = 5;
setting.patchsize = 16;
setting.sampling = 100000;
setting.codesampleR = 0;
setting.pyramid = [1, 2, 4];
% setting.featsize = sum(setting.ncluster*setting.pyramid.^2);
setting.featsizellc = sum(setting.ncluster*setting.pyramid.^2);

setting.gridSpacing = 3;
setting.patchSize = 8;


text:
var TileRequest = require('../lib/TileRequest.js');
var TileRequestHandler = require('../lib/TileRequestHandler.js');
var TileServer = require('../lib/TileServer.js');
var TileLayer = require('../lib/TileLayer.js');
var assert = require('chai').assert;
var tilestrata = require('../index.js');
var version = require('../package.json').version;

describe('require("tilestrata")', function() {
	it('should have "TileServer" property', function() {
		assert.equal(tilestrata.TileServer, TileServer);
	});
	it('should have "TileRequest" property', function() {
		assert.equal(tilestrata.TileRequest, TileRequest);
	});
	it('should have "TileRequestHandler" property', function() {
		assert.equal(tilestrata.TileRequestHandler, TileRequestHandler);
	});
	it('should have "TileLayer" property', function() {
		assert.equal(tilestrata.TileLayer, TileLayer);
	});
	describe('createServer()', function() {
		it('should return TileServer instance', function() {
			assert.instanceOf(tilestrata.createServer(), TileServer);
		});
	});
	describe('middleware()', function() {
		function testMiddleware(middleware, requrl, expect_next, expected_details, callback) {
			var next = function(err) {
				assert.isFalse(!!err);
				if (expect_next) callback();
				else throw new Error('Unexpected "next" call');
			};
			var _write_called = false;
			var _writeHead_called = false;

			var httpReq = {url: requrl, method: 'GET'};
			var httpRes = {
				writeHead: function(status, headers) {
					if (expect_next) throw new Error('Unexpected "writeHead" call');
					_writeHead_called = true;
					assert.equal(status, expected_details.status);
					assert.deepEqual(headers, expected_details.headers);
				},
				write: function(buffer) {
					if (expect_next) throw new Error('Unexpected "write" call');
					_write_called = true;
					assert.isTrue(_writeHead_called);
					assert.instanceOf(buffer, Buffer);
					assert.equal(buffer.toString('utf8'), expected_details.buffer.toString('utf8'));
				},
				end: function() {
					if (expect_next) throw new Error('Unexpected "end" call');
					assert.isTrue(_writeHead_called);
					assert.isTrue(_write_called);
					callback();
				}
			};

			middleware(httpReq, httpRes, next);
		};

		it('should return 200 when tile matches', function(done) {
			var reqhook_called = false;
			var reshook_called = false;

			var expected_headers = {
				'X-Test':'1',
				'X-Powered-By': 'TileStrata/' + version,
				'Content-Length': 4,
				'Cache-Control': 'max-age=60',
				'ETag': '"4-ExgdjMAeOQv2TJ5LDXp58w"'
			};

			var server = new TileServer();
			server.layer('basemap').route('file.txt')
				.use({
					reqhook: function(_server, _tile, _req, _res, callback) {
						reqhook_called = true;
						assert.equal(_server, server);
						assert.instanceOf(_tile, TileRequest);
						assert.equal(_req.url, '/tiles/basemap/3/2/1/file.txt');
						assert.isFunction(_res.writeHead);
						callback();
					}
				})
				.use({
					reshook: function(_server, _tile, _req, _res, _result, callback) {
						reshook_called = true;
						assert.equal(_server, server);
						assert.deepEqual(_result.headers, {
							'X-Test':'1',
							'X-Powered-By': 'TileStrata/' + version,
							'Cache-Control': 'max-age=60'
						});
						assert.instanceOf(_result.buffer, Buffer);
						assert.instanceOf(_tile, TileRequest);
						assert.equal(_req.url, '/tiles/basemap/3/2/1/file.txt');
						assert.isFunction(_res.writeHead);
						callback();
					}
				})
				.use({serve: function(server, req, callback) {
					callback(null, new Buffer('tile', 'utf8'), {'X-Test':'1'});
				}});

			var middleware = tilestrata.middleware({server: server, prefix: '/tiles'});
			testMiddleware(middleware, '/tiles/basemap/3/2/1/file.txt', false, {status: 200, headers: expected_headers, buffer: new Buffer('tile', 'utf8')}, function() {
				assert.isTrue(reqhook_called, 'Request hook called');
				assert.isTrue(reshook_called, 'Response hook called');
				done();
			});
		});
		it('should call next() when route url doesn\'t match', function(done) {
			var server = new TileServer();
			server.layer('basemap').route('file.txt').use({serve: function(server, req, callback) {
				callback(null, new Buffer('tile', 'utf8'), {'X-Test':'1'});
			}});
			var middleware = tilestrata.middleware({server: server, prefix: '/tiles'});
			testMiddleware(middleware, '/basemap/3/2/1/file.txt', true, null, done);
		});
	});
});