text:
//usar los nuevos tipos de variables y características de EMC6
'use strict'

//Para usar el modelo hay q importarlo
const Concurso = require('../Model/Concurso')

/*************************************** GET ******************************/
//Obtener concursos
function ObtenerConcursos(objrequest, objresponse){
    Concurso.findAll().then((_Concursos) => {
        if(!_Concursos){
            objresponse.status(404).send({mensaje: 'No existen concursos'})
        }
        if(_Concursos.length <= 0)
            objresponse.status(404).send({mensaje: 'No existen concursos registrados.'})
        else
        {
            objresponse.status(200).send({concurso: _Concursos})
        }
      }).catch((err) => {
          console.log(`Error generado al consultar todos los concursos: ${err}`)
          objresponse.status(500).send({mensaje: 'Error interno del servicio'})
      })
}
//Obtener concurso por Id
function ObtenerConcursoPorId(objrequest, objresponse){
    var _idConcurso = objrequest.params.id
    Concurso.findOne({ where: {id: _idConcurso} }).then((_concurso)=>{
        if(!_concurso){
            objresponse.status(404).send({mensaje: 'El concurso no existe'})
        }
        else{
            if(_concurso.activo){
                objresponse.status(200).send({concurso: _concurso})
            }
            else{
                objresponse.status(200).send({mensaje: 'El concurso ha caducado'})
            }
        }
    }).catch((err) => {
        console.log(`Error generado el consultar el concurso por id: ${err}`)
        return objresponse.status(500).send({mensaje: 'Error interno del servicio'})
    })
}

//Obtener concursos por id de usuario
function ObtenerConcursosPorIdUsuario(objrequest, objresponse){
    var _idUsuario = objrequest.params.id
    Concurso.findAll({ where: {userId: _idUsuario, activo: true} }).then((_concurso)=>{
        if(!_concurso){
            objresponse.status(404).send({mensaje: 'El usuario no tiene concursos asociados'})
        }
        else{
            objresponse.status(200).send({concurso: _concurso})
        }
    }).catch((err) => {
        return objresponse.status(500).send({mensaje: 'Error interno del servicio'})
    })
}
/*************************************** POST ******************************/
//Crear concurso
function CrearConcurso(objrequest, objresponse){
    var _concurso = new Concurso()
    _concurso.userId = objrequest.body.userId
    _concurso.nombre = objrequest.body.nombre
    _concurso.imagen = objrequest.body.imagen
    _concurso.url = objrequest.body.url,
    _concurso.fechaInicio = objrequest.body.fechaInicio
    _concurso.fechaFin = objrequest.body.fechaFin
    _concurso.premio = objrequest.body.premio
    //_concurso.activo = objrequest.body.activo
    //Se almacena el concurso
    _concurso.save(_concurso).then((_ConcursoGuardado)=>{
        if(!_ConcursoGuardado){
            objresponse.status(400).send({mensaje: "Error al crear el concurso"})
        }
        else
        {
            console.log(`::::::::::::::::::::::::: usuario guardado ok :::::::::::::::::::::::`)
            var idConcurso = _ConcursoGuardado.id
            Concurso.findOne({ where: {id: idConcurso} }).then((_concursoActualizadoOk)=> {
                if(!_concursoActualizadoOk){
                    objresponse.status(400).send({mensaje: `Error al consultar el concurso creado`})
                }
                else
                {
                    objresponse.status(200).send({concurso: _concursoActualizadoOk})
                }
            }).catch((err)=>{
                objresponse.status(500).send({mensaje: "Error consultando el concurso creado."})
            })
        }
    }).catch((err)=>{
        console.log(`Error creando el concurso: ${err}`)
        objresponse.status(500).send({mensaje: "Error creando el concurso"})
    })
}
/*************************************** UPDATE ******************************/
//Actualizar Concurso
function ActualizarConcurso(objrequest, objresponse){
    var idConcurso = objrequest.params.id
    var concursoFromBody = objrequest.body
    Concurso.update(concursoFromBody, {where:{id:idConcurso} }).then((_concursoActualizado)=>{
        if(!_concursoActualizado){
            objresponse.status(400).send({mensaje: "Error al Actualizar el concurso "})
        }
        else{
            objresponse.status(200).send({mensaje: "Concurso actualizado correctamente"})
        }
    }).catch((err)=>{
        console.log(`Error actualizando el concurso ${err}`)
        objresponse.status(500).send({mensaje: "Error interno del servicio "})
    })
}
/*************************************** DELETE ******************************/
//Eliminar concurso
function EliminarConcurso(objrequest, objresponse){
    var idConcurso = objrequest.params.id
    Concurso.update({activo: false}, {where:{id:idConcurso} }).then((_concursoActualizado)=>{
        if(!_concursoActualizado){
            objresponse.status(400).send({mensaje: "Error al eliminar el concurso "})
        }
        else{
            objresponse.status(200).send({mensaje: "Concurso eliminado correctamente"})
        }
    }).catch((err)=>{
        console.log(`Error actualizando el concurso ${err}`)
        objresponse.status(500).send({mensaje: "Error interno del servicio "})
    })
}

//Se exporta el controlador
module.exports ={
    ObtenerConcursos,
    ObtenerConcursoPorId,
    ObtenerConcursosPorIdUsuario,
    CrearConcurso,
    ActualizarConcurso,
    EliminarConcurso
}


text:
using Microsoft.Practices.Unity;
using System;
using Urasandesu.Prig.VSPackage.Infrastructure;

namespace Urasandesu.Prig.VSPackage.Shell
{
    abstract class ConsoleCommand : ApplicationCommand
    {
        [Dependency]
        public ConsoleController Controller { protected get; set; }

        [Dependency]
        public ConsoleActivityLog ActivityLog { protected get; set; }

        protected ConsoleViewModel ViewModel { get { return (ConsoleViewModel)ApplicationViewModel; } }

        protected ConsoleCommand(ConsoleViewModel vm)
            : base(vm)
        { }

        protected ConsoleCommand(ConsoleViewModel vm, IObservable<bool> canExecuteSource)
            : base(vm, canExecuteSource)
        { }

        protected override void OnBegin(object parameter)
        {
            if (ActivityLog != null)
                ActivityLog.Info(string.Format("Begin {0}...", this));
        }

        protected override void OnError(object parameter, Exception e)
        {
            if (ActivityLog != null)
                ActivityLog.Error(string.Format("Error {0}...", e));
        }

        protected override void OnEnd(object parameter)
        {
            if (ActivityLog != null)
                ActivityLog.Info(string.Format("End {0}...", this));
        }
    }

    class RegisterPrigCommand : ConsoleCommand
    {
        public RegisterPrigCommand(ConsoleViewModel vm)
            : base(vm)
        { }

        protected override void InvokeCore(object parameter)
        {
            Controller.PrepareRegisteringPrig(ViewModel);
        }
    }

    class UnregisterPrigCommand : ConsoleCommand
    {
        public UnregisterPrigCommand(ConsoleViewModel vm)
            : base(vm)
        { }

        protected override void InvokeCore(object parameter)
        {
            Controller.PrepareUnregisteringPrig(ViewModel);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
cask "quickhue" do
  version "1.3.3"
  sha256 :no_check

  url "https://github.com/danparsons/QuickHue/raw/master/QuickHue.zip"
  name "QuickHue"
  desc "Menu bar utility for controlling the Philips Hue lighting system"
  homepage "https://github.com/danparsons/QuickHue"

  app "QuickHue.app"

  zap trash: [
    "~/Library/Application Support/QuickHue",
    "~/Library/Caches/cat.moo.QuickHue",
    "~/Library/Preferences/cat.moo.QuickHue.plist",
  ]
end


text:
/**
 * User
 *
 * @module      :: Model
 * @description :: This is the base user model
 * @docs        :: http://waterlock.ninja/documentation
 */

module.exports = {

  attributes: require('waterlock').models.user.attributes({
    username:{
      type:"string",
      required:true,
      unique:true
    },
    //Password is not needed here
    //password: {
    //  type: "string",
    //  required: true
    //},
    firstname:{
      type: "string",
      required: true
    },
    lastname:{
      type: "string",
      required: true
    },
    email:{
      type: "string",
      email: true,
      required: true,
      unique: true
    },
    jsonWebTokens: {
      collection: 'jwt',
      via: 'owner'
    },
    enabled:{
      type:'boolean',
      defaultsTo:true
    },
    role:{
      type:"string",
      enum:['normal','admin','teacher'],
      required:true,
      defaultsTo:"normal" //could be admin, normal
    }

  }),

  beforeCreate: require('waterlock').models.user.beforeCreate,
  beforeUpdate: require('waterlock').models.user.beforeUpdate
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.

namespace Microsoft.Azure.Batch
{
    public partial class VirtualMachineConfiguration
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="VirtualMachineConfiguration"/> class.
        /// </summary>
        /// <param name='imageReference'>A reference to the Azure Virtual Machines Marketplace image to use.</param>
        /// <param name='nodeAgentSkuId'>The SKU of Batch Node Agent to be provisioned on the compute node.</param>
        /// <param name='windowsConfiguration'>Windows operating system settings on the virtual machine. This property must not be specified if the ImageReference
        /// property specifies a Linux OS image.</param>
        public VirtualMachineConfiguration(
            ImageReference imageReference,
            string nodeAgentSkuId,
            WindowsConfiguration windowsConfiguration = default(WindowsConfiguration)) :
            this(nodeAgentSkuId, imageReference: imageReference, windowsConfiguration: windowsConfiguration)
        {
        }
    }
}


text:
package com.zavtech.morpheus.reference;

import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;

import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
import org.apache.commons.math3.stat.regression.SimpleRegression;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import static com.zavtech.morpheus.util.Asserts.assertEquals;

import com.zavtech.morpheus.frame.DataFrame;
import com.zavtech.morpheus.frame.DataFrameLeastSquares;
import com.zavtech.morpheus.frame.DataFrameLeastSquares.Field;
import com.zavtech.morpheus.index.Index;
import com.zavtech.morpheus.range.Range;

/**
 * Unit tests for Ordinary Least Squares Regression Analysis
 *
 * @author  Xavier Witdouck
 *
 *
This is open source software released under the Apache 2.0 License

 */
public class OLSTests {

    @DataProvider(name="thresholds")
    public Object[][] thresholds() {
        return new Object[][] { {0d}, {0.1d}};
    }

    @DataProvider(name="solver")
    public Object[][] solver() {
        return new Object[][] {
            { DataFrameLeastSquares.Solver.INV },
            { DataFrameLeastSquares.Solver.QR }
        };
    }

    /**
     * Returns a DataFrame of motor vehicles features
     * @return  the frame of motor vehicle features
     */
    private static DataFrame<Integer,String> loadCarDataset() {
        return DataFrame.read().csv(options -> {
            options.setResource("/csv/cars93.csv");
            options.setExcludeColumnIndexes(0);
        });
    }

    @Test(dataProvider = "solver")
    public void ols2(DataFrameLeastSquares.Solver solver) throws Exception {
        DataFrame<Integer,String> frame = loadCarDataset();
        final String regressand = "Horsepower";
        final String regressor = "EngineSize";
        frame.regress().ols(regressand, regressor, true, model -> {
            model.withSolver(solver);
            assert (model.getRegressand().equals(regressand));
            assert (model.getRegressors().size() == 1);
            assertEquals(model.getRSquared(), 0.5359992996664269, 0.00001);
            assertEquals(model.getRSquaredAdj(), 0.5309003908715525, 0.000001);
            assertEquals(model.getStdError(), 35.87167658782274, 0.00001);
            assertEquals(model.getFValue(), 105.120393642, 0.00001);
            assertEquals(model.getFValueProbability(), 0, 0.00001);
            assertEquals(model.getBetaValue("EngineSize", Field.PARAMETER), 36.96327914, 0.0000001);
            assertEquals(model.getBetaValue("EngineSize", Field.STD_ERROR), 3.60518041, 0.0000001);
            assertEquals(model.getBetaValue("EngineSize", Field.T_STAT), 10.25282369, 0.0000001);
            assertEquals(model.getBetaValue("EngineSize", Field.P_VALUE), 0.0000, 0.0000001);
            assertEquals(model.getBetaValue("EngineSize", Field.CI_LOWER), 29.80203113, 0.0000001);
            assertEquals(model.getBetaValue("EngineSize", Field.CI_UPPER), 44.12452714, 0.0000001);
            assertEquals(model.getInterceptValue(Field.PARAMETER), 45.21946716, 0.0000001);
            assertEquals(model.getInterceptValue(Field.STD_ERROR), 10.31194906, 0.0000001);
            assertEquals(model.getInterceptValue(Field.T_STAT), 4.3851523, 0.0000001);
            assertEquals(model.getInterceptValue(Field.P_VALUE), 0.00003107, 0.0000001);
            assertEquals(model.getInterceptValue(Field.CI_LOWER), 24.73604714, 0.0000001);
            assertEquals(model.getInterceptValue(Field.CI_UPPER), 65.70288719, 0.0000001);
            System.out.println(model);
            return Optional.of(model);
        });
    }

    @Test(dataProvider = "solver")
    public void ols3(DataFrameLeastSquares.Solver solver) throws Exception {
        DataFrame<Integer,String> frame = loadCarDataset();
        final String regressand = "Horsepower";
        final String regressor = "EngineSize";
        frame.regress().ols(regressand, regressor, false, model -> {
            model.withSolver(solver);
            assert (model.getRegressand().equals(regressand));
            assert (model.getRegressors().size() == 1);
            assertEquals(model.getRSquared(), 0.934821940829, 0.00001);
            assertEquals(model.getRSquaredAdj(), 0.9341134836, 0.000001);
            assertEquals(model.getStdError(), 39.26510834, 0.00001);
            assertEquals(model.getFValue(), 1319.517942852, 0.00001);
            assertEquals(model.getFValueProbability(), 0, 0.00001);
            assertEquals(model.getBetaValue("EngineSize", Field.PARAMETER), 51.708176166, 0.0000001);
            assertEquals(model.getBetaValue("EngineSize", Field.STD_ERROR), 1.4234806556, 0.0000001);
            assertEquals(model.getBetaValue("EngineSize", Field.T_STAT), 36.32516955, 0.0000001);
            assertEquals(model.getBetaValue("EngineSize", Field.P_VALUE), 5.957E-56, 0.0000001);
            assertEquals(model.getBetaValue("EngineSize", Field.CI_LOWER), 48.880606712, 0.0000001);
            assertEquals(model.getBetaValue("EngineSize", Field.CI_UPPER), 54.53574562, 0.0000001);
            System.out.println(model);
            return Optional.of(model);
        });
    }

    @Test()
    public void testSLR() {
        final Index<String> rowKeys = Range.of(0, 5000).map(i -> "R" + i).toIndex(String.class);
        final DataFrame<String,String> frame = DataFrame.of(rowKeys, String.class, columns -> {
            columns.add("Y", Double.class).applyDoubles(v -> v.rowOrdinal() + 1d + (Math.random() * 2));
            columns.add("X", Double.class).applyDoubles(v -> v.rowOrdinal() + 1d + (Math.random() * 3));
        });
        final SimpleRegression benchmark = new SimpleRegression(true);
        frame.rows().forEach(row -> benchmark.addData(row.getDouble(1), row.getDouble(0)));
        frame.regress().ols("Y", "X", true, model -> {
            assertResultsMatch(frame, model, benchmark);
            return Optional.empty();
        });
    }

    @Test(dataProvider = "thresholds")
    public void testMLR(double threshold) {
        final Range<String> rowKeys = Range.of(0, 5000).map(i -> "R" + i);
        final DataFrame<String,String> frame = DataFrame.of(rowKeys, String.class, columns -> {
            columns.add("Y", Double.class).applyDoubles(v -> v.rowOrdinal() + 1d + (Math.random() * 2));
            columns.add("X1", Double.class).applyDoubles(v -> v.rowOrdinal() + 1d + (Math.random() * 3));
            columns.add("X2", Double.class).applyDoubles(v -> v.rowOrdinal() + 1d + (Math.random() * 4));
            columns.add("X3", Double.class).applyDoubles(v -> v.rowOrdinal() + 1d + (Math.random() * 5));
            columns.add("X4", Double.class).applyDoubles(v -> v.rowOrdinal() + 1d + (Math.random() * 6));
        });

        final OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(threshold);
        final double[] dependent = frame.col("Y").toDoubleStream().toArray();
        final double[][] independent = new double[frame.rows().count()][3];
        frame.rows().forEach(row -> {
            independent[row.ordinal()][0] = row.getDouble("X1");
            independent[row.ordinal()][1] = row.getDouble("X2");
            independent[row.ordinal()][2] = row.getDouble("X3");
        });
        model.newSampleData(dependent, independent);
        frame.regress().ols("Y", Arrays.asList("X1", "X2", "X3"), true, mlr -> {
            System.out.println(mlr);
            assertResultsMatch(mlr, model);
            return Optional.empty();
        });
    }

    @Test(description = "Tests whether a Simple regression results matches a Multiple regression result with one parameter")
    public void testSLRvsMLR() {
        final Range<String> rowKeys = Range.of(0, 5000).map(i -> "R" + i);
        final DataFrame<String,String> frame = DataFrame.of(rowKeys, String.class, columns -> {
            columns.add("Y", Double.class).applyDoubles(v -> v.rowOrdinal() + 1d + (Math.random() * 2));
            columns.add("X", Double.class).applyDoubles(v -> v.rowOrdinal() + 1d + (Math.random() * 3));
        });

        frame.regress().ols("Y", "X", true, slr -> {
            frame.regress().ols("Y", Collections.singletonList("X"), true, mlr -> {
                Assert.assertEquals(slr.getResidualSumOfSquares(), mlr.getResidualSumOfSquares(), 0.0000001, "Residual sum of squares matches");
                Assert.assertEquals(slr.getTotalSumOfSquares(), mlr.getTotalSumOfSquares(), 0.1, "Total sum of squares matches");
                Assert.assertEquals(slr.getRSquared(), mlr.getRSquared(), 0.0000001, "R^2 values match");
                Assert.assertEquals(slr.getStdError(), mlr.getStdError(),  0.0000001, "Std error matches");
                Assert.assertEquals(slr.getBetaValue("X", Field.PARAMETER), mlr.getBetaValue("X", Field.PARAMETER), 0.00000001, "Beta parameters match");
                Assert.assertEquals(slr.getBetaValue("X", Field.STD_ERROR), mlr.getBetaValue("X", Field.STD_ERROR), 0.000000001, "Beta standard errors match");
                Assert.assertEquals(slr.getInterceptValue(Field.STD_ERROR), mlr.getInterceptValue(Field.STD_ERROR), 0.00000001, "Intercept standard errors match");

                final DataFrame<String,String> residuals1 = slr.getResiduals();
                final DataFrame<String,String> residuals2 = mlr.getResiduals();

                Assert.assertEquals(residuals1.rows().count(), residuals2.rows().count(), "Same number of residuals");
                residuals1.rows().forEach(row -> {
                    final double v1 = row.getDouble(0);
                    final double v2 = residuals2.data().getDouble(row.ordinal(), 0);
                    Assert.assertEquals(v1, v2, 0.0000001, "Residuals match for index " + row.ordinal());
                });
                return Optional.empty();
            });
            return Optional.empty();
        });
    }

    /**
     * Checks that the Morpheus OLS model yields the same results as Apache Math
     * @param actual    the Morpheus results
     * @param expected  the Apache results
     */
    private <R,C> void assertResultsMatch(DataFrameLeastSquares<R,C> actual, OLSMultipleLinearRegression expected) {

        Assert.assertEquals(actual.getResidualSumOfSquares(), expected.calculateResidualSumOfSquares(), 0.0000001, "Residual sum of squares matches");
        Assert.assertEquals(actual.getTotalSumOfSquares(), expected.calculateTotalSumOfSquares(), actual.getTotalSumOfSquares() * 0.000001, "Total sum of squares matches");
        Assert.assertEquals(actual.getRSquared(), expected.calculateRSquared(), 0.0000001, "R^2 values match");
        Assert.assertEquals(actual.getStdError(), expected.estimateRegressionStandardError(),  0.0000001, "Std error matches");

        final DataFrame<C,Field> params1 = actual.getBetas();
        final double[] params2 = expected.estimateRegressionParameters();
        Assert.assertEquals(params1.rows().count(), params2.length-1, "Same number of parameters");
        for (int i=0; i<params1.rows().count(); ++i) {
            final double actualParam = params1.data().getDouble(i, Field.PARAMETER);
            final double expectedParam = params2[i+1];
            Assert.assertEquals(actualParam, expectedParam, 0.000000001, "Parameters match at index " + i);
        }

        final double intercept = expected.estimateRegressionParameters()[0];
        final double interceptStdError = expected.estimateRegressionParametersStandardErrors()[0];
        Assert.assertEquals(actual.getInterceptValue(Field.PARAMETER), intercept,  0.0000001, "The intercepts match");
        Assert.assertEquals(actual.getInterceptValue(Field.STD_ERROR), interceptStdError, 0.000000001, "The intercept std errors match");

        final DataFrame<R,String> residuals1 = actual.getResiduals();
        final double[] residuals2 = expected.estimateResiduals();
        Assert.assertEquals(residuals1.rows().count(), residuals2.length, "Same number of residuals");
        for (int i=0; i<residuals1.rows().count(); ++i) {
            Assert.assertEquals(residuals1.data().getDouble(i, 0), residuals2[i], 0.00000001, "Residuals match at index " + i);
        }

        final DataFrame<C,Field> stdErrs1 = actual.getBetas().cols().select(c -> c.key() == Field.STD_ERROR);
        final double[] stdErrs2 = expected.estimateRegressionParametersStandardErrors();
        Assert.assertEquals(stdErrs1.rows().count(), stdErrs2.length-1, "Same number of parameter standard errors");
        for (int i=0; i<stdErrs1.cols().count(); ++i) {
            Assert.assertEquals(stdErrs1.data().getDouble(0, i), stdErrs2[i+1], 0.00000001, "Standard errors match at index " + i);
        }
    }

    /**
     * Checks that the Morpheus OLS model yields the same results as Apache Math
     * @param frame      the data for regression
     * @param actual    the Morpheus results
     * @param expected  the Apache results
     */
    private <R> void assertResultsMatch(DataFrame<String,String> frame, DataFrameLeastSquares<String,String> actual, SimpleRegression expected) {

        final double tss1 = actual.getTotalSumOfSquares();
        final double tss2 = expected.getTotalSumSquares();
        final double threshold = ((tss1 + tss2) / 2d) * 0.00001d;

        Assert.assertEquals(actual.getTotalSumOfSquares(), expected.getTotalSumSquares(), threshold, "Total sum of squares matches");
        Assert.assertEquals(actual.getRSquared(), expected.getRSquare(), 0.0000001, "R^2 values match");

        final double beta1 = actual.getBetaValue("X", Field.PARAMETER);
        final double beta2 = expected.getSlope();
        Assert.assertEquals(beta1, beta2, 0.000001, "Beta parameters match");

        final double intercept = expected.getIntercept();
        final double interceptStdError = expected.getInterceptStdErr();
        Assert.assertEquals(actual.getInterceptValue(Field.PARAMETER), intercept,  0.0000001, "The intercepts match");
        Assert.assertEquals(actual.getInterceptValue(Field.STD_ERROR), interceptStdError, 0.000000001, "The intercept std errors match");

        final double betaStdErr1 = actual.getBetaValue("X", Field.STD_ERROR);
        final double betaStdErr2 = expected.getSlopeStdErr();
        Assert.assertEquals(betaStdErr1, betaStdErr2, 0.00000001, "Beta Standard errors match");

        final DataFrame<String,String> residuals = actual.getResiduals();
        Assert.assertEquals(residuals.rows().count(), frame.rows().count(), "There are expected number of residuals");
        residuals.rows().forEach(row -> {
            final double x = frame.data().getDouble(row.ordinal(), "X");
            final double y = frame.data().getDouble(row.ordinal(), "Y");
            final double residual = row.getDouble(0);
            final double expect = y - expected.predict(x);
            Assert.assertEquals(residual, expect, 0.0000001, "Residual matches for x=" + x + " at row index " + row.ordinal());
        });
    }

}


text:
package com.threeandahalfroses.frs.lambda.payment;

import com.threeandahalfroses.frs.lambda.BaseRequest;

public class PaymentRequest extends BaseRequest {
}


text:
import { expect } from 'chai';

import insert from 'Src/operations/insert';

it('should export row function', () => {
  expect(insert.row).to.be.a('function');
});


text:
module.exports = function () {
  var builtinLibs = require('repl')._builtinLibs;
  return [].slice.call(arguments).reduce(function (acc, key) {
    var path = builtinLibs.indexOf(key) > -1 ? key : __dirname.replace('modmod', '') + key;
    acc[key] = require(path);
    return acc;
  }, {});
};


text:
package exp

import (
	"encoding/json"
	"fmt"
	"gopkg.in/sensorbee/sensorbee.v0/data"
	"io"
	"io/ioutil"
	"os"
	"time"
)

// CacheEntry has an cache information of a specific BQL statement.
type CacheEntry struct {
	NodeName  string    `json:"node_name,omitempty"`
	Hash      string    `json:"hash"`
	Stmt      string    `json:"stmt"`
	States    []string  `json:"states"`
	Timestamp time.Time `json:"timestamp"`
}

// Cache has information of cached results generated from each BQL statement.
type Cache struct {
	Seed     string                 `json:"seed"`
	Applied  []*CacheEntry          `json:"applied"`
	Outdated []*CacheEntry          `json:"outdated"`
	nodes    map[string]*CacheEntry `json:"-"`
}

// LoadCacheFromFile loads Cache from a file.
func LoadCacheFromFile(filename string) (*Cache, error) {
	body, err := ioutil.ReadFile(filename)
	if err != nil {
		if os.IsNotExist(err) {
			return &Cache{
				Seed:  data.Timestamp(time.Now()).String(),
				nodes: map[string]*CacheEntry{},
			}, nil
		}
		return nil, err
	}
	return LoadCache(body)
}

// LoadCache loads a cache from in-memory data.
func LoadCache(body []byte) (*Cache, error) {
	c := &Cache{}
	if err := json.Unmarshal(body, c); err != nil {
		return nil, err
	}
	c.nodes = make(map[string]*CacheEntry, len(c.Applied))
	for _, e := range c.Applied {
		if e.NodeName == "" {
			continue
		}
		c.nodes[e.NodeName] = e
	}
	return c, nil
}

// SaveCacheToFile saves Cache to a file.
func SaveCacheToFile(cache *Cache, filename string) error {
	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		return fmt.Errorf("cannot create a cache file '%v': %v", filename, err)
	}
	defer f.Close()
	if err := cache.Save(f); err != nil {
		return fmt.Errorf("cannot save a cache file '%v': %v", filename, err)
	}
	return nil
}

// CacheFilename computes the filename from a cache entry.
func CacheFilename(ent *CacheEntry) string {
	return CacheFilenameWithName(ent, ent.NodeName, "jsonl")
}

func StateCacheFilename(ent *CacheEntry, stateName string) string {
	return CacheFilenameWithName(ent, stateName, "state")
}

// CacheFilenameWithNodeName computes the filename from a cache entry with a
// custom node name.
func CacheFilenameWithName(ent *CacheEntry, name, ext string) string {
	return fmt.Sprintf("%v-%v-%v.%v", name, ent.Timestamp.Format("20060102150405"), ent.Hash[:8], ext)
}

// Add adds a CacheEntry.
func (c *Cache) Add(e *CacheEntry) {
	c.Applied = append(c.Applied, e)
	if e.NodeName != "" {
		c.nodes[e.NodeName] = e
	}
}

// Get returns i-th CacheEntry in the cache. It returns nil if the index is
// out of bounds.
func (c *Cache) Get(i int) *CacheEntry {
	if i < 0 || i >= len(c.Applied) {
		return nil
	}
	return c.Applied[i]
}

// TruncateAfter removes all cache information after i-th position. For
// example, if the cache has three entries [a, b, c], TruncateAfter(0) removes
// b and c, and only a remains.
func (c *Cache) TruncateAfter(i int) {
	if i >= len(c.Applied)-1 {
		return
	}
	if i < 0 {
		i = -1
	}
	c.Outdated = append(c.Outdated, c.Applied[i+1:]...)
	c.Applied = c.Applied[:i+1]
}

// Node returns a CacheEntry of a data source node (a source or a stream)
// having the name.
func (c *Cache) Node(name string) *CacheEntry {
	return c.nodes[name]
}

// Save saves the Cache.
func (c *Cache) Save(w io.Writer) error {
	e := json.NewEncoder(w)
	return e.Encode(c)
}


text:
<?php

namespace Dwo\FlaggingVoters\Tests;

use Dwo\Flagging\Context\Context;
use Dwo\FlaggingVoters\Voters\EnabledVoter;

class EnabledTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provider
     */
    public function test($result, $config)
    {
        $voter = new EnabledVoter();

        self::assertEquals($result, $voter->vote($config, new Context()), $config);
    }

    public function provider()
    {
        return array(
            array(true, true),
            array(true, 'true'),
            array(true, 1),
            array(true, '1'),

            array(false, false),
            array(false, 'false'),
            array(false, 0),
            array(false, '0'),

            array(false, null),
            array(false, 'null'),
            array(false, 'foo'),
        );
    }
}


text:
<?php
/**
 * ilfate.net
 * @autor Ilya Rubinchik ilfate@gmail.com
 * 2014
 */

namespace Tcg;

abstract class Location {

    /**
     * Player Id
     *
     * @var int
     */
    public $owner;

    public $cards = array();

    public function __construct($playerId)
    {
        $this->owner = $playerId;
    }

    public static function import($data)
    {
        $location = new static($data['owner']);
        $location->cards = $data['cards'];

        return $location;
    }

    public function addCards(array $cards)
    {
        foreach ($cards as $card) {
            $this->cards[$card->id] = $card->id;
        }
    }

    public function addCardIds(array $cards)
    {
        foreach ($cards as $cardId) {
            $this->cards[$cardId] = $cardId;
        }
    }

    public function count()
    {
        return count($this->cards);
    }

    public function export()
    {
        $location = [
            'cards' => $this->cards,
            'owner' => $this->owner
        ];
        return $location;
    }

    public function getRandom($num = 1)
    {
        return array_rand($this->cards, $num);
    }

    public function remove($cardIds = array())
    {
        foreach ($cardIds as $cardId) {
            unset($this->cards[$cardId]);
        }
    }

    public function hasCard($cardId)
    {
        return isset($this->cards[$cardId]);
    }
}


text:
package net.hagander.mailinglistmoderator.glue;

import java.util.Vector;

import net.hagander.mailinglistmoderator.R;
import net.hagander.mailinglistmoderator.backend.ListServer;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

/**
 * @author Magnus Hagander <magnus@hagander.net>
 *
 */
public class ListServerAdapter extends ArrayAdapter<ListServer> {
	private Vector<ListServer> items;

	public ListServerAdapter(Context context, int textViewResourceId,
			Vector<ListServer> servers) {
		super(context, textViewResourceId, servers);

		items = servers;
	}

	/**
	 * Create a view that contains the information we want to show about each
	 * list.
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;

		if (v == null) {
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.main_item, null);
		}
		ListServer o = items.get(position);
		if (o != null) {
			TextView n = (TextView) v.findViewById(R.id.TextView_ServerName);
			TextView s = (TextView) v.findViewById(R.id.TextView_ServerStatus);

			n.setText(o.getName());
			s.setText(o.getStatus());
		}
		return v;
	}
}


text:
"""Interpolation functions in a 2-dimensional space."""

import tensorflow.compat.v2 as tf

from tf_quant_finance import types
from tf_quant_finance.math.interpolation import cubic
from tf_quant_finance.math.interpolation import linear

class Interpolation2D:
  """Performs interpolation in a 2-dimensional space.

  For input `x_data` in x-direction we assume that values in y-direction are
  given by `y_data` and the corresponding function values by `z_data`.
  For given `x` and `y` along x- and y- direction respectively,
  the interpolated function values are computed on grid `[x, y]`.
  The interpolation is first performed along y-direction for every `x_data`
  point and all `y` using 1-d cubic spline interpolation. Next, for
  each interpolated `y_value` point, the function values are interpolated along
  x-direction for `x` using 1-d cubic spline interpolation.
  Constant extrapolation is used for the linear interpolation and natural
  boundary conditions are used for the cubic spline.

  ### Example. Volatility surface interpolation

  ```python
  dtype = np.float64
  times = tf.constant([2., 2.5, 3, 4.5], dtype=dtype)
  strikes = tf.constant([16, 22, 35], dtype=dtype)

  times_data = tf.constant([1.5, 2.5, 3.5, 4.5, 5.5], dtype=dtype)
  # Corresponding squared volatility values
  sigma_square_data = tf.constant(
      [[0.15, 0.25, 0.35, 0.4, 0.45, 0.4],
       [0.2, 0.35, 0.55, 0.45, 0.4, 0.6],
       [0.3, 0.45, 0.25, 0.4, 0.5, 0.65],
       [0.25, 0.25, 0.45, 0.25, 0.5, 0.55],
       [0.35, 0.35, 0.25, 0.4, 0.55, 0.65]], dtype=dtype)
  # Interpolation is done for the total variance
  total_variance = tf.expand_dims(times_data, -1) * sigma_square_data
  # Corresponding strike values. Notice we need to broadcast to the shape of
  # `sigma_square_data`
  strike_data = tf.broadcast_to(
      tf.constant([15, 25, 35, 40, 50, 55], dtype=dtype), [5, 6])
  # Interpolate total variance on for coordinates `(times, strikes)`
  interpolator = Interpolation2D(times_data, strike_data, total_variance,
                                 dtype=dtype)
  interpolated_values = interpolator.interpolate(times, strikes)
  ```
  """

  def __init__(self,
               x_data: types.RealTensor,
               y_data: types.RealTensor,
               z_data: types.RealTensor,
               dtype: tf.DType = None,
               name: str = None):
    """Initialize the 2d-interpolation object.

    Args:
      x_data: A `Tensor` of real `dtype` and shape
        `batch_shape + [num_x_data_points]`.
        Defines the x-coordinates of the input data. `num_x_data_points` should
        be >= 2. The elements of `x_data` should be in a non-decreasing order.
      y_data: A `Tensor` of the same `dtype` as `x_data` and shape
        `batch_shape + [num_x_data_points, num_y_data_points]`. Defines the
        y-coordinates of the input data. `num_y_data_points` should be >= 2.
        The elements of `y_data` should be in a non-decreasing order along last
        dimension.
      z_data: A `Tensor` of the same shape and `dtype` as `y_data`. Defines the
        z-coordinates of the input data (i.e., the function values).
      dtype: Optional dtype for the input `Tensor`s.
        Default value: `None` which maps to the default dtype inferred by
        TensorFlow.
      name: Python `str` name prefixed to ops created by this class.
        Default value: `None` which is mapped to the default name
        `interpolation_2d`.
    """

    name = name or "interpolation_2d"
    with tf.name_scope(name):
      self._xdata = tf.convert_to_tensor(x_data, dtype=dtype, name="x_data")
      self._dtype = dtype or self._xdata.dtype
      self._ydata = tf.convert_to_tensor(
          y_data, dtype=self._dtype, name="y_data")
      self._zdata = tf.convert_to_tensor(
          z_data, dtype=self._dtype, name="z_data")
      self._name = name

      # For each `x_data` point, build a spline in y-direction
      self._spline_yz = cubic.build_spline(
          self._ydata, self._zdata, name="spline_y_direction")

  def interpolate(self,
                  x: types.RealTensor,
                  y: types.RealTensor,
                  name: str = None):
    """Performs 2-D interpolation on a specified set of points.

    Args:
      x: Real-valued `Tensor` of shape `batch_shape + [num_points]`.
        Defines the x-coordinates at which the interpolation should be
        performed. Note that `batch_shape` should be the same as in the
        underlying data.
      y: A `Tensor` of the same shape and `dtype` as `x`.
        Defines the y-coordinates at which the interpolation should be
        performed.
      name: Python `str` name prefixed to ops created by this function.
        Default value: `None` which is mapped to the default name
        `interpolate`.

    Returns:
      A `Tensor` of the same shape and `dtype` as `x`. Represents the
      interpolated values of the function on for the coordinates
      `(x, y)`.
    """
    name = name or self._name + "_interpolate"
    with tf.name_scope(name):
      x = tf.convert_to_tensor(
          x, dtype=self._dtype, name="x")
      y = tf.convert_to_tensor(
          y, dtype=self._dtype, name="y")

      # Broadcast `y` to the number of `x_data` points
      y = tf.expand_dims(y, axis=-2)
      # For each `x_data` point interpolate values of the function at the
      # y. Shape of `xy` is
      # batch_shape + `[num_x_data_points, num_points]`.
      xy = cubic.interpolate(
          y, self._spline_yz, name="interpolation_in_y_direction")
      # Interpolate the value of the function along x-direction
      # Prepare xy for linear interpolation. Put the batch dims in front
      xy_rank = xy.shape.rank
      perm = [xy_rank - 1] + list(range(xy_rank - 1))
      # Shape [num_points] + batch_shape + [num_x_data_points]
      yx = tf.transpose(xy, perm=perm)
      # Get the permutation to the original shape
      perm_original = list(range(1, xy_rank)) + [0]
      # Reshape to [num_points] + batch_shape + [1]
      x = tf.expand_dims(tf.transpose(
          x, [xy_rank - 2] + list(range(xy_rank - 2))), axis=-1)
      # Interpolation takes care of braodcasting
      z_values = linear.interpolate(x, self._xdata, yx)
      return tf.squeeze(tf.transpose(z_values, perm=perm_original), axis=-2)


text:
{{ site.description | escape }}

{% include icon-github.svg %}

{% include icon-twitter.svg %}

graph-labs


text:
var config = require('../config.js');
var s3Fetcher = require('./s3Fetcher.js');
var promised = require("promised-io/promise");
var csvWriter = require('./csvWriter.js');
var convertor = {};

/**
 * Convertor takes S3 Fetcher and Config. On invocation of getS3Data returns
 * object of type S3Data
 */
convertor.Convertor = function(s3Fetcher, config){
    this.s3Fetcher = s3Fetcher;
    this.config = config;
    getS3Data = function(callback){
        s3Fetcher.init(config.s3Params);
        s3Fetcher.listObjects(config.dataset, 1, []).then(function(keyArray){
            var promises = [];
            for(var key of keyArray){
                promises.push(s3Fetcher.getObject(config.dataset.Bucket, key));
            }
            //Need to wait for all promises to be resolved
            promised.all(promises).then(function(dataArray){
                callback(null, new convertor.S3Data(dataArray));
            }, function(err){
                callback(err);
            });
        },
        function(err){
            callback(err);
        });
    }
    return{
        getS3Data
    }
}

/**
 * Basically an array of DynamoDB JSON files. On invocation of convertToTableData it converts
 * dynamodb json to a flattened out normal json.
 */
convertor.S3Data = function(s3Data){
    this.s3Data = s3Data;
    tableData = [];
    fields = [];

    convertToTableData = function(filter){
        var filteredArray = [];
        for(var data of s3Data){
            if(data == null || data === '')
                continue;
            var obj = JSON.parse(data);
            if(filter && filter.key && filter.value){
                var filterValue = obj[filter.key];
                if(filterValue && filterValue['S'] && filterValue['S'] == filter.value)
                    filteredArray.push(obj);
            }
            else{
                filteredArray.push(obj);
            }
        }
        for(var data of filteredArray){
            addRow(data);
        }
        return new convertor.Table(tableData, fields);
    }

    addRow = function(data){
        tableData.push({});
        var basicJson = parseDynamoDbJson("", data);
    }

    /**
     * Add a field if not already added
     */
    addField = function(key, value){
        if(key == null)
            return;
        tableData[tableData.length -1][key] = value;
        if(fields.indexOf(key) == -1)
            fields.push(key);
    }

    /**
     * Parses DynamoDB json to normal json format. Nested fields are flattened out. For example a nested field
     * innerData in data is kept as data.innerData.
     * The functionality is limited to types S, N, L and M dynamodb types.
     * @TODO: Extend for other types
     * Please read: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.ResponseFormat
     */
    parseDynamoDbJson = function(prefixKey, dynamodbJson){
        var basicJson = {};
        for(var key in dynamodbJson){
            switch(key){
                case 'S' : {
                    addField(prefixKey, dynamodbJson[key]);
                    return dynamodbJson[key];
                }
                case 'N' : {
                    addField(prefixKey, dynamodbJson[key]);
                    return dynamodbJson[key];
                }
                case 'L' : {
                    var lArray = [];
                    for(var lValue of dynamodbJson[key]){
                        lArray.push(parseDynamoDbJson(null, lValue));
                    }
                    var arrayAsStr = JSON.stringify(lArray);
                    arrayAsStr = arrayAsStr.replace(/"/g, "'");
                    addField(prefixKey, '"' + arrayAsStr+ '"');
                    return arrayAsStr;
                }
                case 'M' : {
                    return parseDynamoDbJson(prefixKey, dynamodbJson[key]);
                }
                default : {
                    var newKey = key;
                    if(prefixKey && prefixKey != "")
                        newKey = prefixKey + "." + key;
                    basicJson[key] = parseDynamoDbJson(newKey, dynamodbJson[key]);
                }
            }
        }
        return basicJson;
    }
    return{
        convertToTableData,
        addRow,
        addField,
        parseDynamoDbJson,
        tableData,
        fields
    }
}

/**
 * Converts TableData to CSV sring. delimiter can be specified (not necessarily comma)
 */
convertor.Table = function(tableData, fields){
    this.tableData = tableData;
    this.fields = fields;
    mergeAsRowData = function(delimiter){
        var rowData = "";
        for(var index in fields){
            var key = fields[index];
            rowData += key;
            if(index < fields.length - 1)
                rowData += delimiter ;
        }
        rowData += '\n';
        for(var row of tableData){
            rowData += "";
            for(var index in fields){
                var key = fields[index];
                if(!row[key])
                    rowData += "";
                else
                    rowData += row[key] ;
                if(index < fields.length - 1)
                    rowData += delimiter ;
            }
            rowData += '\n';
        }
        return rowData;
    }

    return{
        mergeAsRowData
    }
}

module.exports = convertor;


text:
/* 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 at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.activiti.compatibility.spring;

import org.activiti.spring.SpringProcessEngineConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.flowable.compatibility.DefaultFlowable5CompatibilityHandler;
import org.flowable.compatibility.DefaultProcessEngineFactory;

/**
 * @author Joram Barrez
 * @author Tijs Rademakers
 */
public class DefaultFlowable5SpringCompatibilityHandler extends DefaultFlowable5CompatibilityHandler {

    @Override
    public DefaultProcessEngineFactory getProcessEngineFactory() {
        if (processEngineFactory == null) {
            processEngineFactory = new DefaultSpringProcessEngineFactory();
        }
        return processEngineFactory;
    }

    @Override
    public Object getCamelContextObject(String camelContextValue) {
        SpringProcessEngineConfiguration springConfiguration = (SpringProcessEngineConfiguration) getProcessEngine().getProcessEngineConfiguration();
        if (StringUtils.isEmpty(camelContextValue)) {
            camelContextValue = springConfiguration.getDefaultCamelContext();
        }

        // Get the CamelContext object and set the super's member variable.
        Object ctx = springConfiguration.getApplicationContext().getBean(camelContextValue);
        return ctx;
    }
}


text:
<Layout xmlns="urn:speedata.de:2009/publisher/en"
  xmlns:sd="urn:speedata:2009/publisher/functions/en"
  version="3.1.10">

  <SetVariable variable="hashead" select="true()"/>

  <Record element="data">
    <PlaceObject>

        <ForAll select="row">
          <Switch>
            <Case test="position() = 1 and $hashead">
              <Tablehead>

                  <ForAll select="cell">

                      <Paragraph color="white">
                        <Value select="."/>
                      </Paragraph>

                  </ForAll>

              </Tablehead>
            </Case>
            <Otherwise>

                <ForAll select="cell">

                    <Paragraph>
                      <Value select="."/>
                    </Paragraph>

                </ForAll>

            </Otherwise>
          </Switch>
        </ForAll>

    </PlaceObject>
  </Record>
</Layout>


text:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS Positioned Layout Module Level 3: parsing bottom with invalid values</title>
<link rel="help" href="https://drafts.csswg.org/css-position/#propdef-bottom">
<meta name="assert" content="bottom supports only the grammar 'auto | <length-percentage>'.">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/css/support/parsing-testcommon.js"></script>
</head>
<body>
<script>
test_invalid_value("bottom", "min-content");

test_invalid_value("bottom", "60");
test_invalid_value("bottom", "10px 20%");
</script>
</body>
</html>


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import six
import warnings

import logging

import pymongo

import numpy as np

from ..utils import format_time as _format_time
from .core import (doc_or_uid_to_uid,   # noqa
                   NoRunStart, NoRunStop, NoEventDescriptors,
                   _cache_run_start, _cache_run_stop, _cache_descriptor,
                   run_start_given_uid, run_stop_given_uid,
                   descriptor_given_uid, stop_by_start, descriptors_by_start,
                   get_events_table, insert_run_start, insert_run_stop,
                   insert_descriptor, insert_event, BAD_KEYS_FMT)
from ..utils import sanitize_np, apply_to_dict_recursively
from event_model import MismatchedDataKeys

logger = logging.getLogger(__name__)

def get_events_generator(descriptor, event_col, descriptor_col,
                         descriptor_cache, run_start_col,
                         run_start_cache, convert_arrays=True):
    """A generator which yields all events from the event stream

    Parameters
    ----------
    descriptor : dict or str
        The EventDescriptor to get the Events for.  Can be either
        a dict with a 'uid' key or a uid string
    convert_arrays: boolean, optional
        convert 'array' type to numpy.ndarray; True by default

    Yields
    ------
    event : dict
        All events for the given EventDescriptor from oldest to
        newest
    """
    descriptor_uid = doc_or_uid_to_uid(descriptor)
    descriptor = descriptor_given_uid(descriptor_uid, descriptor_col,
                                      descriptor_cache)
    col = event_col
    ev_cur = col.find({'descriptor': descriptor_uid},
                      sort=[('descriptor', pymongo.DESCENDING),
                            ('time', pymongo.ASCENDING)])

    data_keys = descriptor['data_keys']
    external_keys = [k for k in data_keys if 'external' in data_keys[k]]
    for ev in ev_cur:
        # ditch the ObjectID
        del ev['_id']

        # replace descriptor with the defererenced descriptor
        ev['descriptor'] = descriptor_uid
        for k, v in ev['data'].items():
            try:
                _dk = data_keys[k]
            except KeyError as err:
                raise MismatchedDataKeys(
                    "The documents are not valid.  Either because they "
                    "were recorded incorrectly in the first place, "
                    "corrupted since, or exercising a yet-undiscovered "
                    "bug in a reader. event['data'].keys() "
                    "must equal descriptor['data_keys'].keys(). "
                    f"event['data'].keys(): {ev['data'].keys()}, "
                    "descriptor['data_keys'].keys(): "
                    f"{descriptor['data_keys'].keys()}") from err
            # convert any arrays stored directly in mds into ndarray
            if convert_arrays:
                if _dk['dtype'] == 'array' and not _dk.get('external', False):
                    ev['data'][k] = np.asarray(ev['data'][k])

        # note which keys refer to dereferences (external) data
        ev['filled'] = {k: False for k in external_keys}

        yield ev

# database INSERTION ###################################################

def bulk_insert_events(event_col, descriptor, events, validate):
    """Bulk insert many events

    Parameters
    ----------
    event_descriptor : dict or str
        The Descriptor to insert event for.  Can be either
        a dict with a 'uid' key or a uid string
    events : iterable
       iterable of dicts matching the bs.Event schema
    validate : bool
       If it should be checked that each pair of data/timestamps
       dicts has identical keys

    Returns
    -------
    ret : dict
        dictionary of details about the insertion
    """
    descriptor_uid = doc_or_uid_to_uid(descriptor)

    def event_factory():
        for ev in events:
            data = dict(ev['data'])
            # Replace any filled data with the datum_id stashed in 'filled'.
            for k, v in six.iteritems(ev.get('filled', {})):
                if v:
                    data[k] = v
            # Convert any numpy types to native Python types.
            apply_to_dict_recursively(data, sanitize_np)
            timestamps = dict(ev['timestamps'])
            apply_to_dict_recursively(timestamps, sanitize_np)
            # check keys, this could be expensive
            if validate:
                if data.keys() != timestamps.keys():
                    raise ValueError(
                        BAD_KEYS_FMT.format(data.keys(),
                                            timestamps.keys()))

            ev_out = dict(descriptor=descriptor_uid, uid=ev['uid'],
                          data=data, timestamps=timestamps,
                          time=ev['time'],
                          seq_num=ev['seq_num'])
            yield ev_out

    bulk = [pymongo.InsertOne(ev) for ev in event_factory()]
    return event_col.bulk_write(bulk, ordered=True)

# DATABASE RETRIEVAL ##########################################################

def find_run_starts(run_start_col, run_start_cache, tz, **kwargs):
    """Given search criteria, locate RunStart Documents.

    Parameters
    ----------
    since : time-like, optional
        time-like representation of the earliest time that a RunStart
        was created. Valid options are:
           - timestamps --> time.time()
           - '2015'
           - '2015-01'
           - '2015-01-30'
           - '2015-03-30 03:00:00'
           - datetime.datetime.now()
    until : time-like, optional
        timestamp of the latest time that a RunStart was created. See
        docs for `since` for examples.
    beamline_id : str, optional
        String identifier for a specific beamline
    project : str, optional
        Project name
    owner : str, optional
        The username of the logged-in user when the scan was performed
    scan_id : int, optional
        Integer scan identifier

    Returns
    -------
    rs_objects : iterable of dicts

    Examples
    --------
    >>> find_run_starts(scan_id=123)
    >>> find_run_starts(owner='arkilic')
    >>> find_run_starts(since=1421176750.514707, until=time.time()})
    >>> find_run_starts(since=1421176750.514707, until=time.time())

    >>> find_run_starts(owner='arkilic', since=1421176750.514707,
    ...                until=time.time())

    """
    # now try rest of formatting
    _format_time(kwargs, tz)
    rs_objects = run_start_col.find(kwargs,
                                    sort=[('time', pymongo.DESCENDING)])

    for rs in rs_objects:
        yield _cache_run_start(rs, run_start_cache)

def find_run_stops(stop_col, stop_cache, tz,
                   run_start=None, **kwargs):
    """Given search criteria, locate RunStop Documents.

    Parameters
    ----------
    run_start : dict or str, optional
        The RunStart document or uid to get the corresponding run end for
    since : time-like, optional
        time-like representation of the earliest time that a RunStop
        was created. Valid options are:
           - timestamps --> time.time()
           - '2015'
           - '2015-01'
           - '2015-01-30'
           - '2015-03-30 03:00:00'
           - datetime.datetime.now()
    until : time-like, optional
        timestamp of the latest time that a RunStop was created. See
        docs for `since` for examples.
    exit_status : {'success', 'fail', 'abort'}, optional
        provides information regarding the run success.
    reason : str, optional
        Long-form description of why the run was terminated.
    uid : str, optional
        Globally unique id string provided to metadatastore

    Yields
    ------
    run_stop : dict
        The requested RunStop documents
    """
    # if trying to find by run_start, there can be only one
    # normalize the input and get the run_start oid
    if run_start:
        run_start_uid = doc_or_uid_to_uid(run_start)
        kwargs['run_start'] = run_start_uid

    _format_time(kwargs, tz)
    col = stop_col
    run_stop = col.find(kwargs, sort=[('time', pymongo.ASCENDING)])

    for rs in run_stop:
        yield _cache_run_stop(rs, stop_cache)

def find_descriptors(descriptor_col, descriptor_cache,
                     tz,
                     run_start=None, **kwargs):
    """Given search criteria, locate EventDescriptor Documents.

    Parameters
    ----------
    run_start : dict or str, optional
        The RunStart document or uid to get the corresponding run end for
    since : time-like, optional
        time-like representation of the earliest time that an EventDescriptor
        was created. Valid options are:
           - timestamps --> time.time()
           - '2015'
           - '2015-01'
           - '2015-01-30'
           - '2015-03-30 03:00:00'
           - datetime.datetime.now()
    until : time-like, optional
        timestamp of the latest time that an EventDescriptor was created. See
        docs for `since` for examples.
    uid : str, optional
        Globally unique id string provided to metadatastore

    Yields
    -------
    descriptor : dict
        The requested EventDescriptor
    """
    if run_start:
        run_start_uid = doc_or_uid_to_uid(run_start)
        kwargs['run_start'] = run_start_uid

    _format_time(kwargs, tz)

    col = descriptor_col
    event_descriptor_objects = col.find(kwargs,
                                        sort=[('time', pymongo.ASCENDING)])

    for event_descriptor in event_descriptor_objects:
        yield _cache_descriptor(event_descriptor, descriptor_cache)

def find_events(start_col, start_cache,
                descriptor_col, descriptor_cache,
                event_col, tz, descriptor=None, **kwargs):
    """Given search criteria, locate Event Documents.

    Parameters
    -----------
    since : time-like, optional
        time-like representation of the earliest time that an Event
        was created. Valid options are:
           - timestamps --> time.time()
           - '2015'
           - '2015-01'
           - '2015-01-30'
           - '2015-03-30 03:00:00'
           - datetime.datetime.now()
    until : time-like, optional
        timestamp of the latest time that an Event was created. See
        docs for `since` for examples.
    descriptor : dict or str, optional
       Find events for a given EventDescriptor
    uid : str, optional
        Globally unique id string provided to metadatastore

    Returns
    -------
    events : iterable of dict objects
    """
    # Some user-friendly error messages for an easy mistake to make
    if 'event_descriptor' in kwargs:
        raise ValueError("Use 'descriptor', not 'event_descriptor'.")

    if descriptor:
        descriptor_uid = doc_or_uid_to_uid(descriptor)
        kwargs['descriptor'] = descriptor_uid

    _format_time(kwargs, tz)
    col = event_col
    events = col.find(kwargs,
                      sort=[('descriptor', pymongo.DESCENDING),
                            ('time', pymongo.ASCENDING)],
                      no_cursor_timeout=True)

    try:
        for ev in events:
            ev.pop('_id', None)
            # pop the descriptor oid
            desc_uid = ev.pop('descriptor')
            # replace it with the defererenced descriptor
            ev['descriptor'] = descriptor_given_uid(desc_uid, descriptor_col,
                                                    descriptor_cache)

            yield ev
    finally:
        events.close()

def find_last(start_col, start_cache, num):
    """Locate the last `num` RunStart Documents

    Parameters
    ----------
    num : integer, optional
        number of RunStart documents to return, default 1

    Yields
    ------
    run_start : dict
       The requested RunStart documents
    """
    col = start_col
    for rs in col.find().sort('time', pymongo.DESCENDING).limit(num):
        yield _cache_run_start(rs, start_cache)


text:
title: SingleAssignmentDisposable.Dispose()
---
# SingleAssignmentDisposable.Dispose Method

Disposes the underlying disposable.

**Namespace:**  [System.Reactive.Disposables](System.Reactive.Disposables/System.Reactive.Disposables)
**Assembly:**  System.Reactive (in System.Reactive.dll)

## Syntax

```vb
'Declaration
Public Sub Dispose
```

```vb
'Usage
Dim instance As SingleAssignmentDisposable

instance.Dispose()
```

```csharp
public void Dispose()
```

```c++
public:
virtual void Dispose() sealed
```

```fsharp
abstract Dispose : unit -> unit
override Dispose : unit -> unit
```

```javascript
public final function Dispose()
```

#### Implements

[IDisposable.Dispose()](https://msdn.microsoft.com/en-us/library/es4s3w1d)

## See Also

#### Reference

[SingleAssignmentDisposable Class](SingleAssignmentDisposable/SingleAssignmentDisposable)

[System.Reactive.Disposables Namespace](System.Reactive.Disposables/System.Reactive.Disposables)


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:locale="en">
    <string name="app" translatable="false">Application</string>
    <string name="file">File</string><!-- file label -->
    <string name="percent" translatable="false" formatted="false">%d %s</string>
    <string name="empty"></string>
    <plurals name="cow">
        <item quantity="other">cows</item><!-- comment -->
        <item quantity="one">cow</item>
    </plurals>
    <string-array name="days" translatable="false">
        <item>monday</item>
        <item>tuesday</item>
        <item>wednesday</item>
    </string-array>
</resources>


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

#include "../Core/CoreEvents.h"
#include "../Core/Profiler.h"
#include "../Core/EventProfiler.h"
#include "../Core/Context.h"
#include "../Engine/DebugHud.h"
#include "../Engine/Engine.h"
#include "../Graphics/Graphics.h"
#include "../Graphics/Renderer.h"
#include "../Resource/ResourceCache.h"
#include "../IO/Log.h"
#include "../UI/Font.h"
#include "../UI/Text.h"
#include "../UI/UI.h"

#include "../DebugNew.h"

namespace Urho3D
{

static const char* qualityTexts[] =
{
    "Low",
    "Med",
    "High",
    "High+"
};

static const char* shadowQualityTexts[] =
{
    "16bit Simple",
    "24bit Simple",
    "16bit PCF",
    "24bit PCF",
    "VSM",
    "Blurred VSM"
};

DebugHud::DebugHud(Context* context) :
    Object(context),
    profilerMaxDepth_(M_MAX_UNSIGNED),
    profilerInterval_(1000),
    useRendererStats_(false),
    mode_(DEBUGHUD_SHOW_NONE)
{
    auto* ui = GetSubsystem<UI>();
    UIElement* uiRoot = ui->GetRoot();

    statsText_ = new Text(context_);
    statsText_->SetAlignment(HA_LEFT, VA_TOP);
    statsText_->SetPriority(100);
    statsText_->SetVisible(false);
    uiRoot->AddChild(statsText_);

    modeText_ = new Text(context_);
    modeText_->SetAlignment(HA_LEFT, VA_BOTTOM);
    modeText_->SetPriority(100);
    modeText_->SetVisible(false);
    uiRoot->AddChild(modeText_);

    profilerText_ = new Text(context_);
    profilerText_->SetAlignment(HA_RIGHT, VA_TOP);
    profilerText_->SetPriority(100);
    profilerText_->SetVisible(false);
    uiRoot->AddChild(profilerText_);

    memoryText_ = new Text(context_);
    memoryText_->SetAlignment(HA_LEFT, VA_BOTTOM);
    memoryText_->SetPriority(100);
    memoryText_->SetVisible(false);
    uiRoot->AddChild(memoryText_);

    eventProfilerText_ = new Text(context_);
    eventProfilerText_->SetAlignment(HA_RIGHT, VA_TOP);
    eventProfilerText_->SetPriority(100);
    eventProfilerText_->SetVisible(false);
    uiRoot->AddChild(eventProfilerText_);

    SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(DebugHud, HandlePostUpdate));
}

DebugHud::~DebugHud()
{
    statsText_->Remove();
    modeText_->Remove();
    profilerText_->Remove();
    memoryText_->Remove();
    eventProfilerText_->Remove();
}

void DebugHud::Update()
{
    auto* graphics = GetSubsystem<Graphics>();
    auto* renderer = GetSubsystem<Renderer>();
    if (!renderer || !graphics)
        return;

    // Ensure UI-elements are not detached
    if (!statsText_->GetParent())
    {
        auto* ui = GetSubsystem<UI>();
        UIElement* uiRoot = ui->GetRoot();
        uiRoot->AddChild(statsText_);
        uiRoot->AddChild(modeText_);
        uiRoot->AddChild(profilerText_);
    }

    if (statsText_->IsVisible())
    {
        unsigned primitives, batches;
        if (!useRendererStats_)
        {
            primitives = graphics->GetNumPrimitives();
            batches = graphics->GetNumBatches();
        }
        else
        {
            primitives = renderer->GetNumPrimitives();
            batches = renderer->GetNumBatches();
        }

        String stats;
        stats.AppendWithFormat("Triangles %u\nBatches %u\nViews %u\nLights %u\nShadowmaps %u\nOccluders %u",
            primitives,
            batches,
            renderer->GetNumViews(),
            renderer->GetNumLights(true),
            renderer->GetNumShadowMaps(true),
            renderer->GetNumOccluders(true));

        if (!appStats_.Empty())
        {
            stats.Append("\n");
            for (HashMap<String, String>::ConstIterator i = appStats_.Begin(); i != appStats_.End(); ++i)
                stats.AppendWithFormat("\n%s %s", i->first_.CString(), i->second_.CString());
        }

        statsText_->SetText(stats);
    }

    if (modeText_->IsVisible())
    {
        String mode;
        mode.AppendWithFormat("Tex:%s Mat:%s Spec:%s Shadows:%s Size:%i Quality:%s Occlusion:%s Instancing:%s API:%s",
            qualityTexts[renderer->GetTextureQuality()],
            qualityTexts[Min(renderer->GetMaterialQuality(), 3)],
            renderer->GetSpecularLighting() ? "On" : "Off",
            renderer->GetDrawShadows() ? "On" : "Off",
            renderer->GetShadowMapSize(),
            shadowQualityTexts[renderer->GetShadowQuality()],
            renderer->GetMaxOccluderTriangles() > 0 ? "On" : "Off",
            renderer->GetDynamicInstancing() ? "On" : "Off",
            graphics->GetApiName().CString());

        modeText_->SetText(mode);
    }

    auto* profiler = GetSubsystem<Profiler>();
    auto* eventProfiler = GetSubsystem<EventProfiler>();
    if (profiler)
    {
        if (profilerTimer_.GetMSec(false) >= profilerInterval_)
        {
            profilerTimer_.Reset();

            if (profilerText_->IsVisible())
                profilerText_->SetText(profiler->PrintData(false, false, profilerMaxDepth_));

            profiler->BeginInterval();

            if (eventProfiler)
            {
                if (eventProfilerText_->IsVisible())
                    eventProfilerText_->SetText(eventProfiler->PrintData(false, false, profilerMaxDepth_));

                eventProfiler->BeginInterval();
            }
        }
    }

    if (memoryText_->IsVisible())
        memoryText_->SetText(GetSubsystem<ResourceCache>()->PrintMemoryUsage());
}

void DebugHud::SetDefaultStyle(XMLFile* style)
{
    if (!style)
        return;

    statsText_->SetDefaultStyle(style);
    statsText_->SetStyle("DebugHudText");
    modeText_->SetDefaultStyle(style);
    modeText_->SetStyle("DebugHudText");
    profilerText_->SetDefaultStyle(style);
    profilerText_->SetStyle("DebugHudText");
    memoryText_->SetDefaultStyle(style);
    memoryText_->SetStyle("DebugHudText");
    eventProfilerText_->SetDefaultStyle(style);
    eventProfilerText_->SetStyle("DebugHudText");
}

void DebugHud::SetMode(unsigned mode)
{
    statsText_->SetVisible((mode & DEBUGHUD_SHOW_STATS) != 0);
    modeText_->SetVisible((mode & DEBUGHUD_SHOW_MODE) != 0);
    profilerText_->SetVisible((mode & DEBUGHUD_SHOW_PROFILER) != 0);
    memoryText_->SetVisible((mode & DEBUGHUD_SHOW_MEMORY) != 0);
    eventProfilerText_->SetVisible((mode & DEBUGHUD_SHOW_EVENTPROFILER) != 0);

    memoryText_->SetPosition(0, modeText_->IsVisible() ? modeText_->GetHeight() * -2 : 0);

#ifdef URHO3D_PROFILING
    // Event profiler is created on engine initialization if "EventProfiler" parameter is set
    auto* eventProfiler = GetSubsystem<EventProfiler>();
    if (eventProfiler)
        EventProfiler::SetActive((mode & DEBUGHUD_SHOW_EVENTPROFILER) != 0);
#endif

    mode_ = mode;
}

void DebugHud::SetProfilerMaxDepth(unsigned depth)
{
    profilerMaxDepth_ = depth;
}

void DebugHud::SetProfilerInterval(float interval)
{
    profilerInterval_ = Max((unsigned)(interval * 1000.0f), 0U);
}

void DebugHud::SetUseRendererStats(bool enable)
{
    useRendererStats_ = enable;
}

void DebugHud::Toggle(unsigned mode)
{
    SetMode(GetMode() ^ mode);
}

void DebugHud::ToggleAll()
{
    Toggle(DEBUGHUD_SHOW_ALL);
}

XMLFile* DebugHud::GetDefaultStyle() const
{
    return statsText_->GetDefaultStyle(false);
}

float DebugHud::GetProfilerInterval() const
{
    return (float)profilerInterval_ / 1000.0f;
}

void DebugHud::SetAppStats(const String& label, const Variant& stats)
{
    SetAppStats(label, stats.ToString());
}

void DebugHud::SetAppStats(const String& label, const String& stats)
{
    bool newLabel = !appStats_.Contains(label);
    appStats_[label] = stats;
    if (newLabel)
        appStats_.Sort();
}

bool DebugHud::ResetAppStats(const String& label)
{
    return appStats_.Erase(label);
}

void DebugHud::ClearAppStats()
{
    appStats_.Clear();
}

void DebugHud::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
{
    using namespace PostUpdate;

    Update();
}

}


text:
import { Range, window, TextEditor } from 'vscode';
import { getCssPropertyFromRule, getCssPropertyFromDocument } from './util';
import { Property, Rule } from 'EmmetNode';

const vendorPrefixes = ['-webkit-', '-moz-', '-ms-', '-o-', ''];

export function reflectCssValue(): Thenable<boolean> {
	let editor = window.activeTextEditor;
	if (!editor) {
		window.showInformationMessage('No editor is active.');
		return;
	}

	let node = getCssPropertyFromDocument(editor, editor.selection.active);
	if (!node) {
		return;
	}

	return updateCSSNode(editor, node);
}

function updateCSSNode(editor: TextEditor, property: Property): Thenable<boolean> {
	const rule: Rule = property.parent;
	let currentPrefix = '';

	// Find vendor prefix of given property node
	for (let i = 0; i < vendorPrefixes.length; i++) {
		if (property.name.startsWith(vendorPrefixes[i])) {
			currentPrefix = vendorPrefixes[i];
			break;
		}
	}

	const propertyName = property.name.substr(currentPrefix.length);
	const propertyValue = property.value;

	return editor.edit(builder => {
		// Find properties with vendor prefixes, update each
		vendorPrefixes.forEach(prefix => {
			if (prefix === currentPrefix) {
				return;
			}
			let vendorProperty = getCssPropertyFromRule(rule, prefix + propertyName);
			if (vendorProperty) {
				builder.replace(new Range(vendorProperty.valueToken.start, vendorProperty.valueToken.end), propertyValue);
			}
		});
	});
}


text:
Ext.define('devilry.extjshelpers.SortByLastnameColumn', {
    extend: 'Ext.grid.column.Column',
    alias: 'widget.sortbylastnamecolumn',

    doSort: function(direction) {
        var store = this.up('tablepanel').store;
        store.sort(Ext.create('Ext.util.Sorter', {
            direction: direction,
            sorterFn: Ext.bind(this._sorter, this)
        }));
    },

    _getLastName: function(fullname) {
        var sp = fullname.split(' ');
        return sp[sp.length - 1];
    },

    compare: function(afull, bfull) {
        var alast = this._getLastName(afull);
        var blast = this._getLastName(bfull);
        return alast.localeCompare(blast);
    },

    _sorter: function(a, b) {
        afull = a.get(this.dataIndex);
        bfull = b.get(this.dataIndex);
        if(Ext.typeOf(afull) != 'string') {
            return 1;
        } else if(Ext.typeOf(bfull) != 'string') {
            return -1;
        } else {
            return this.compare(afull, bfull);
        }
    }
});


text:
using System.ComponentModel;

namespace LinqAn.Google.Metrics
{
	/// <summary>
	/// 	The name of the requested custom metric, where 40 refers the number/index of the custom metric. Note that the data type of ga:metric40 can be INTEGER, CURRENCY or TIME.
	/// </summary>
	[Description("The name of the requested custom metric, where 40 refers the number/index of the custom metric. Note that the data type of ga:metric40 can be INTEGER, CURRENCY or TIME.")]
	public class Metric40: Metric<float>
	{
		/// <summary>
		/// 	Instantiates a <seealso cref="Metric40" />.
		/// </summary>
		public Metric40(): base("Custom Metric 40 Value",true,"ga:metric40")
		{

		}
	}
}


text:
define(['locale/cn'], function(_dict) {

  function tran(input){
    var _q = input.toLowerCase();
    if (_q in _dict){
      return _dict[_q];
    }

    return input;
  }

  return tran;
});


text:
In LORIOT go to the **Output** menu and click on **Add new output.**

{% include images-gallery.html imageCollection="loriot_output" preview="false" %}

Then we select HTTP Push and specify the target, which is taken from the integration.

{% include images-gallery.html imageCollection="endpoint" preview="false" %}


text:
<?php

declare(strict_types=1);

namespace GrumPHP\Event;

use GrumPHP\Collection\TaskResultCollection;
use GrumPHP\Collection\TasksCollection;
use GrumPHP\Task\Context\ContextInterface;

class RunnerEvent extends Event
{
    /**
     * @var TasksCollection
     */
    private $tasks;

    /**
     * @var ContextInterface
     */
    private $context;

    /**
     * @var TaskResultCollection
     */
    private $taskResults;

    public function __construct(TasksCollection $tasks, ContextInterface $context, TaskResultCollection $taskResults)
    {
        $this->tasks = $tasks;
        $this->context = $context;
        $this->taskResults = $taskResults;
    }

    public function getTasks(): TasksCollection
    {
        return $this->tasks;
    }

    public function getContext(): ContextInterface
    {
        return $this->context;
    }

    public function getTaskResults(): TaskResultCollection
    {
        return $this->taskResults;
    }
}


text:
import json
import xlrd
from lxml import etree

testfile = 'city.xls'
savename = 'city.xml'
sheetname = 'big city'

def to_xml(data):
    root = etree.Element('root')
    stu = etree.SubElement(root, 'cities')
    comm = etree.Comment(u'城市信息')
    stu.append(comm)

    stu.text = data
    tree = etree.ElementTree(root)
    tree.write(savename, encoding = 'utf-8', pretty_print = True, \
               xml_declaration = True)

def read_excel(testfile):
    book = xlrd.open_workbook(testfile)
    sheet = book.sheet_by_name(sheetname)
    data = {}
    rows = sheet.nrows
    cols = sheet.ncols
    for i in range(rows):
        data[str(int(sheet.cell_value(i, 0)))] = sheet.cell_value(i, 1)
    #The ensure_ascii param is very important for Chinese character, see the
    #document
    return json.dumps(data, ensure_ascii = False)

if __name__ == '__main__':
    data = read_excel(testfile)
    to_xml(data)


text:
package jp.yattom.research.android.hello;

public interface Whereabout {
	enum Type {
		HOME,
		METRO_STATION_HOME,
	}

	String name();
	String id();
	Type type();
	String[] bssids();
}


text:
package com.ilivoo.xag.model.player.facade;

import org.springframework.stereotype.Component;

@Component
public class PlayerFacade {

}


text:
'use strict';

module.exports = function (item) {
  item.iWasHere = true;
};


text:
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.

using System;

namespace UnitsNet
{
    public partial struct RotationalSpeed
    {
        /// Get <see cref="Angle"/> from <see cref="RotationalSpeed"/> times <see cref="TimeSpan"/>.
        public static Angle operator *(RotationalSpeed rotationalSpeed, TimeSpan timeSpan)
        {
            return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * timeSpan.TotalSeconds);
        }

        /// Get <see cref="Angle"/> from <see cref="TimeSpan"/> times <see cref="RotationalSpeed"/>.
        public static Angle operator *(TimeSpan timeSpan, RotationalSpeed rotationalSpeed)
        {
            return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * timeSpan.TotalSeconds);
        }

        /// Get <see cref="Angle"/> from <see cref="RotationalSpeed"/> times <see cref="Duration"/>.
        public static Angle operator *(RotationalSpeed rotationalSpeed, Duration duration)
        {
            return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * duration.Seconds);
        }

        /// Get <see cref="Angle"/> from <see cref="Duration"/> times <see cref="RotationalSpeed"/>.
        public static Angle operator *(Duration duration, RotationalSpeed rotationalSpeed)
        {
            return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * duration.Seconds);
        }
    }
}


text:
'use strict';

(function () {

  var app = angular.module('UnifiedApiSpa');

  app.factory("unifiedApiService", [ '$http', createServiceObject]);

  function createServiceObject($http) {
    // create service object
    var service = {};

    var apiRoot = "https://graph.microsoft.com/beta/";
    $http.defaults.useXDomain = true;

    // set default headers for $http service
    var config = {
      headers: {
        'Accept': 'application/json; odata.metadata=none',
      }
    };

    service.getUsers = function () {
      var restUrl = apiRoot + "myOrganization/users/";
      return $http.get(restUrl);
    };

    service.getMessages = function () {
      var restUrl = apiRoot + "me/messages/?$top=10";
      return $http.get(restUrl);
    };

    service.getCalendarEvents = function () {
      var restUrl = apiRoot + "me/calendarview/?startdatetime=2015-05-01&enddatetime=2015-07-01";
      return $http.get(restUrl);
    };

    service.getFiles = function () {
      var restUrl = apiRoot + "me/files/";
      return $http.get(restUrl);
    };

    service.getTenantDetails = function () {
      var restUrl = apiRoot + "myOrganization/tenantDetails/";
      return $http.get(restUrl);
    };

    // return service object to angular framework
    return service;
  }

})();


text:
App.UsersRoute = App.AuthenticatedRoute.extend({
  model: function() {
    //return this.store.find('user');
  }
});

// Get user by id
App.UserRoute = App.AuthenticatedRoute.extend({
  model: function(params) {
    return this.store.find('user', params.user_id);
  },
  setupController: function(controller, model) {
    if (model.get('id') == App.AuthManager.get('apiKey.user')) {
      this.transitionTo('myaccount');
    }
    else {
      this.controller.set('model', model);
    }
  }
});

// user controller
App.UserController = Ember.ObjectController.extend({
});


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <parent>
    <artifactId>project</artifactId>
    <groupId>org.mortbay.jetty</groupId>
    <version>6.1.26</version>
    <relativePath>../../pom.xml</relativePath>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>jetty-util</artifactId>
  <name>Jetty Utilities</name>
  <description>Utility classes for Jetty</description>
  <build>
    <testResources>
      <testResource>
        <directory>src/test/java</directory>
        <includes>
          <include>**/*Test.java</include>
          <include>org/mortbay/**/*.xml</include>
        </includes>
        <excludes>
          <exclude>**/Abstract*.java</exclude>
        </excludes>
      </testResource>
    </testResources>
    <plugins>
      <plugin>
        <artifactId>maven-antrun-plugin</artifactId>
        <executions>
          <execution>
            <id>clean</id>
            <phase>clean</phase>
            <goals>
              <goal>run</goal>
            </goals>
            <configuration>
              <tasks>
                <delete failonerror="false" file="../../lib/${project.artifactId}-${project.version}.${project.packaging}" />
                <delete failonerror="false" file="../../etc/jetty-logging.xml" />
              </tasks>
            </configuration>
          </execution>
          <execution>
            <id>copyjar</id>
            <phase>install</phase>
            <goals>
              <goal>run</goal>
            </goals>
            <configuration>
              <tasks>
                <copy failonerror="false" file="target/${project.artifactId}-${project.version}.${project.packaging}" todir="../../lib/" />
                <copy failonerror="false" file="src/main/config/etc/jetty-logging.xml" todir="../../etc" />
              </tasks>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>${maven-bundle-plugin-version}</version>
        <extensions>true</extensions>
        <executions>
          <execution>
            <goals>
              <goal>manifest</goal>
            </goals>
            <configuration>
              <instructions>
                <Bundle-SymbolicName>org.mortbay.jetty.util</Bundle-SymbolicName>
                <Bundle-RequiredExecutionEnvironment>J2SE-1.4</Bundle-RequiredExecutionEnvironment>
                <Import-Package>!org.mortbay.*,org.slf4j;resolution:=optional,*</Import-Package>
                <Bundle-DocURL>http://jetty.mortbay.org</Bundle-DocURL>
              </instructions>
            </configuration>
           </execution>
        </executions>
      </plugin>
      <plugin>
        <!--
        Required for OSGI
        -->
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servlet-version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <optional>true</optional>
    </dependency>
  </dependencies>
</project>


text:
'use strict';

Ngl.HtmlCanvas = function(host, config) {
  this.host = $(host);
  this.top = $(this.host.children().get(0));

  this.config = config;

  this.canvasInitialized = false;
  this.updateRequired = false;
  this.mouseOverElements = [];
  this.updateCanvas = undefined;
};

Ngl.HtmlCanvas.nextCanvasElementNum = 0;

Ngl.HtmlCanvas.prototype.setPanel = function(panel) {
  this.panel = panel;
}

Ngl.HtmlCanvas.prototype.load = function(gl) {
  var _this = this;
  var deferred = $.Deferred();

  this.sizeElements(this.host, this.top);
  this.buildLayoutTree();

  var start = new Date();
  html2canvas(this.host.get(0), {
    //background: undefined,
    onrendered: function(canvas) {
      var element = $('.html2canvas-canvas').get(0);
      _this.updateCanvas = canvas;
      //element.appendChild(canvas);
      _this.createTexturemap(gl, canvas);
      var end = new Date();
      Ngl.log("*** Time = "+(end.getTime()-start.getTime()));

      _this.watchDomChanges();
      deferred.resolve();
    },
    onclone: function(element) {
      $(element).find('.wr3d-host').css('visibility', 'visible');
      //$(element).find('.html2canvas-container').css('background-color', 'green').css('top', '0px');
    }
  });

  return deferred;
};

Ngl.HtmlCanvas.prototype.watchDomChanges = function() {

  var _this = this;
  this.inWatchDom = false;
  // Create an observer instance and get callbacks
  var observer = new MutationObserver(function(mutations) {

    if(_this.inWatchDom) {
      return;
    } else {
      _this.inWatchDom = true;
      mutations.forEach(function (mutation) {
        console.log(mutation.type);
        _this.setUpdateRequired(true);
        _this.inWatchDom = false;
      });
    }
  });

  // configuration of the observer:
  var config = {attributes: true, childList: true, characterData: true, subtree: true };

  // pass in the target node, as well as the observer options
  observer.observe(this.host.get(0), config);

  // later, you can stop observing
  //////////observer.disconnect();
};

Ngl.HtmlCanvas.prototype.sizeElements = function() {
  var primarySurface = this.panel.surfaces[0];
  var texturemapInfo = primarySurface.configureHTML(this, this.host, this.top);
  _.assign(this, texturemapInfo);
};

Ngl.HtmlCanvas.prototype.createTexturemap = function(gl, image) {
  this.texture = gl.createTexture();
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.bindTexture(gl.TEXTURE_2D, this.texture);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.updateCanvas);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
  gl.generateMipmap(gl.TEXTURE_2D);
  gl.bindTexture(gl.TEXTURE_2D, null);
  this.updateCanvas = undefined;
};

Ngl.HtmlCanvas.prototype.bindTexturemap = function(gl) {
  if(this.texture) {
    gl.activeTexture(gl.TEXTURE0+0);
    gl.bindTexture(gl.TEXTURE_2D, this.texture);

    var required = this.getUpdateRequired();
    if(required && this.updateCanvas) {
      gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.updateCanvas);
      gl.generateMipmap(gl.TEXTURE_2D);
      this.updateAvailable = false;
    }
  }
};

Ngl.HtmlCanvas.prototype.getUpdateRequired = function() {
  return this.updateRequired;
};

Ngl.HtmlCanvas.prototype.setUpdateRequired = function(required) {
  if(this.updateAvailable) {
    return;
  }

  this.updateRequired = required;
  this.updateCanvas = undefined;
  var _this = this;

  var start = new Date();
  this.updateAvailable = true;

  html2canvas(this.host.get(0), {
    canvas: this.updateCanvas,
    onrendered: function(canvas) {
      var element = $('.html2canvas-canvas').get(0);
      //element.appendChild(canvas);
      _this.updateCanvas = canvas;
      var end = new Date();
      Ngl.log("*** Time = "+(end.getTime()-start.getTime()));
    },
    onclone: function(element) {
      $(element).find('.wr3d-host').css('visibility', 'visible');
    }
  });

};

Ngl.HtmlCanvas.prototype.dispatchMouseEvent = function(scene, targetData, event) {
  if(_.isUndefined(event.offsetX)) {
    event.offsetX  = event.clientX - $(targetData.target).offset().left;
    event.offsetY  = event.clientY - $(targetData.target).offset().top;
  }

  targetData.target.dispatchEvent(event);
};

Ngl.HtmlCanvas.prototype.findElementUnderXyPosition = function(scene, x, y) {
  var mouseOvers = [];
  var target = this.layoutTree.findTarget(x, y, mouseOvers);

  var e = {
    target: target,
    screenX: $(target.element).offset().top + window.screenY,
    screenY: $(target.element).offset().left + window.screenX,
    clientX: x-target.x,
    clientY: y-target.y
  };

  var loggedLine = false;
  var leaving = _.without(this.mouseOverElements, mouseOvers);
  if(leaving.length) {
    _.forEach(leaving, function (layout) {
      //if(!loggedLine) { loggedLine = true; Ngl.log('********************************'); }
      Ngl.log('Leaving '+layout.element.className);
      var eLeave = {
        eventType: 'mouseleave',
        clientX: e.clientX,
        clientY: e.clientY,
        screenX: e.screenX,
        screenY: e.screenY
      };
      scene.addMouseEvent(this.panel, {target: layout.element}, eLeave);
    }, this);
  }

  var entering = _.xor(this.mouseOverElements, mouseOvers);
  _.forEach(entering, function(layout) {
    var eEnter = { eventType: 'mouseenter', clientX: e.clientX, clientY: e.clientY, screenX: e.screenX, screenY: e.screenY };
    scene.addMouseEvent(this.panel, { target: layout.element }, eEnter);
  }, this);

  this.mouseOverElements = mouseOvers;
  return { target: target.element, canvasX: x, canvasY: y, targetX: x-target.x, targetY: y-target.y };
};

Ngl.HtmlCanvas.prototype.buildLayoutTree = function() {
  this.layoutTree = new Ngl.LayoutTree(this.top.get(0), 0, 0);
};

Ngl.HtmlCanvas.prototype.hasCanvas = function() {
  return this.canvasInitialized;
};

Ngl.HtmlCanvas.prototype.getCanvasElement = function() {
  return this.canvasElement;
};


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Int. Organ. Succ. Pl. Stud. Bull. 3:96. 1974

#### Original name
null

### Remarks
null


text:
namespace Finsternis {
    using UnityEngine;
    using System.Collections;
    using UnityQuery;

    public class CameraController : MonoBehaviour
    {
        [SerializeField]
        private Follow follow;

        [SerializeField]
        [Range(1, 100)]
        private float shakeDamping = 4;

        [SerializeField]
        [Range(1, 20)]
        private float shakeFrequency = 20;

        [SerializeField]
        [Range(1, 100)]
        private float shakeAmplitude = 20;

        [SerializeField][Range(1, 100)]
        private float maxDistanceForOcclusion = 5f;

        [SerializeField, Range(.01f, 1), Tooltip("1 = every fixed update")]
        private float occlusionTestFrequency = .5f;

        private bool shaking;

        private Vector3 lastTarget;
        private Coroutine shakeHandle;

        [SerializeField]
        private bool reactToOcclusion = true;

        private float elapsedSinceLastCheck;

        private int wallLayer;
        private bool occlusionHappened;

        public bool ReactToOcclusion {
            get {return this.reactToOcclusion; }
            set { this.reactToOcclusion = value; }
        }

        void Awake()
        {
            if (!this.follow)
                this.follow = GetComponentInParent<Follow>();
            shaking = false;
            if (GameManager.Instance)
                GameManager.Instance.SubscribeToEvent("ShakeCamera", this, OnCameraShake);

            this.wallLayer = 1 << LayerMask.NameToLayer("Wall");
        }

        void FixedUpdate()
        {
            if (!this.follow)
                return;
            if (!this.follow.Target)
                return;

            if (reactToOcclusion)
                UpdateOcclusion();

            if (!this.shaking)
                this.follow.ResetOffset(!this.occlusionHappened);

        }

        private void UpdateOcclusion()
        {
            RaycastHit hit;
            if (elapsedSinceLastCheck > Time.fixedDeltaTime / this.occlusionTestFrequency)
            {
                elapsedSinceLastCheck = 0;
                if (WouldBeOccluded(out hit))
                {
                    float distanceDampening = 1f - hit.distance / maxDistanceForOcclusion;
                    this.follow.MemorizeOffset(this.follow.OriginalOffset + (Vector3.up * 2.5f + Vector3.forward * 4f) * distanceDampening);
                    this.occlusionHappened = true;
                }
                else
                {
                    this.occlusionHappened = false;
                }
            }
            else
                this.elapsedSinceLastCheck += Time.fixedDeltaTime;
        }

        private bool WouldBeOccluded(out RaycastHit hit)
        {
            Vector3 origin = this.follow.Target.position;

            Ray ray = new Ray(origin + new Vector3(0, .5f, 0), origin.Towards(origin+this.follow.OriginalOffset));
            float radius = 0.25f;

            return (Physics.SphereCast(ray, radius, out hit, maxDistanceForOcclusion, wallLayer)) ;
        }

        private void FinishedInterpolating()
        {
            this.follow.TranslationInterpolation = 0.1f;
            this.follow.MemorizeOffset(this.follow.OriginalOffset);
            this.follow.OnTargetReached.RemoveListener(FinishedInterpolating);
        }

        private void OnCameraShake(params object[] parameters)
        {
            Vector3? explosionPoint = null;
            if(parameters.Length > 0)
            {
                explosionPoint = parameters[0] as Vector3?;
            }
            if (explosionPoint == null)
                return;

            Vector3 relativePosition = transform.position;
            if (GameManager.Instance.Player)
                relativePosition = GameManager.Instance.Player.transform.position;

            float dist = Vector3.Distance(
                new Vector3(relativePosition.x, ((Vector3)explosionPoint).y, relativePosition.z),
                ((Vector3)explosionPoint));
            if (dist <= 0)
                dist = 1;
            if(parameters.Length > 2)
                Shake(
                    (float)parameters[2],
                    (float)parameters[3],
                    (float)parameters[4] / dist,
                    (float)parameters[5],
                    (bool)parameters[1]);
            else
               Shake(0.75f, 4, 20 / dist, 20);
        }

        internal void Shake(float time, float damping, float amplitude, float frequency, bool overrideShake = true)
        {
            if (overrideShake && this.shaking)
            {
                this.shaking = false;
                StopCoroutine(this.shakeHandle);
            }

            if (!this.shaking)
            {
                this.shakeDamping = damping;
                this.shakeFrequency = frequency;
                this.shakeAmplitude = amplitude;
                this.shakeHandle = StartCoroutine(_Shake(time));
            }
        }

        IEnumerator _Shake(float shakeTime)
        {
            this.shaking = true;
            float amplitude = this.shakeAmplitude;
            while (shakeTime > 0)
            {
                float waitTime = 1 / this.shakeFrequency;
                yield return Wait.Sec(waitTime);
                shakeTime -= Time.deltaTime + waitTime;

                Vector3 shakeOffset = Random.insideUnitSphere / 10;

                shakeOffset.z = 0;
                transform.localPosition = shakeOffset * amplitude;
                transform.localRotation = Quaternion.Euler(new Vector3(Random.value, Random.value, Random.value) * amplitude / 5);
                amplitude /= this.shakeDamping;
            }

            transform.localPosition = Vector3.zero;
            transform.localRotation = Quaternion.identity;
            this.shaking = false;
        }
    }
}


text:
{{obj.name}}

                {{obj.description}}

                <button class="btn btn-sm btn-default"> Show</button>
                <button class="btn btn-sm btn-primary"> Buy</button>


text:
package uk.gov.hmrc.ct.computations.lowEmissionCars

import uk.gov.hmrc.ct.box.{Calculated, CtBoolean, CtBoxIdentifier}
import uk.gov.hmrc.ct.computations.calculations.LowEmissionCarsCalculator
import uk.gov.hmrc.ct.computations.retriever.ComputationsBoxRetriever

case class LEC13(value: Boolean) extends CtBoxIdentifier("Disposals Less Than Main Rate Pool") with CtBoolean

object LEC13 extends Calculated[LEC13, ComputationsBoxRetriever] with LowEmissionCarsCalculator  {

  override def calculate(fieldValueRetriever: ComputationsBoxRetriever): LEC13 =
    LEC13(disposalsLessThanMainRatePool(fieldValueRetriever.lec01(),
      fieldValueRetriever.cp78(),
      fieldValueRetriever.cp82(),
      fieldValueRetriever.cp672()
    ))
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Deprecatable (DependencyFinder)
</TITLE>

<META NAME="keywords" CONTENT="com.jeantessier.classreader.Deprecatable interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.jeantessier.classreader

Interface Deprecatable

All Known Subinterfaces:
Classfile, Feature_info, Field_info, Method_info

All Known Implementing Classes:
Classfile, Feature_info, Field_info, Method_info

public interface Deprecatable

Method Summary

 boolean
isDeprecated()

Method Detail

isDeprecated

boolean isDeprecated()

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Dependency Finder 1.2.1-beta1 © 2001-2008 Jean Tessier.


text:
'use strict';

describe('SuiteApi', function() {

  var fakeWindow;
  var suiteApi;

  beforeEach(function() {
    fakeWindow = require('../mocks/fake_window').create();
    suiteApi = require('./suite_api').create(fakeWindow);
  });

  describe('#messageToService', function() {
    var testMessage = {
      event: 'test'
    };

    it('should look for the iframe addressed', function() {
      suiteApi.messageToService(testMessage, 1234);
      expect(fakeWindow.$).to.be.calledWith('#integration-1234');
    });

    it('should send a post message to the iframe with proper data', function() {
      suiteApi.messageToService(testMessage, 1234);
      expect(fakeWindow.$('foo')[0].contentWindow.postMessage).to.be.calledWith(testMessage, '*');
    });
  });

  describe('#messageToSuite', function() {
    it('should call window.postMessage', function() {
      var testMessage = {
        event: 'foo'
      };

      suiteApi.messageToSuite(testMessage);
      expect(fakeWindow.postMessage).to.have.been.calledWith(testMessage, '*');
    });
  });

});


text:
package org.gradle.openapi.wrappers.ui;

import org.gradle.gradleplugin.userinterface.swing.generic.tabs.GradleTab;
import org.gradle.openapi.external.ui.GradleTabVersion1;

import java.awt.*;

/**
 * Wrapper to shield version changes in GradleTab from an external user of the gradle open API.
 */
public class GradleTabVersionWrapper implements GradleTab {
    private GradleTabVersion1 gradleTabVersion1;

    GradleTabVersionWrapper(GradleTabVersion1 gradleTabVersion1) {
        this.gradleTabVersion1 = gradleTabVersion1;

        //when future versions are added, doing the following and then delegating
        //the new functions to GradleTabVersion2 keeps things compatible.
        //if( gradleTabVersion1 instanceof GradleTabVersion2 )
        //   gradleTabVersion2 = (GradleTabVersion2) gradleTabVersion1;
    }

    public String getName() {
        return gradleTabVersion1.getName();
    }

    public Component createComponent() {
        return gradleTabVersion1.createComponent();
    }

    public void aboutToShow() {
        gradleTabVersion1.aboutToShow();
    }
}