text:
@interface Buzz : AKNote
@property AKNoteProperty *normalFrequency;
@property AKNoteProperty *excitedFrequency;
@end

@interface Swarm : AKInstrument
@property AKInstrumentProperty *amplitude;
@property AKInstrumentProperty *excitationLevel;
@end

@implementation Swarm

- (instancetype)initWithNumber:(NSUInteger)instrumentNumber
{
    self = [super initWithNumber:instrumentNumber];
    if (self) {

        Buzz *buzz = [[Buzz alloc] init];
        _amplitude = [self createPropertyWithValue:0.0 minimum:0.0 maximum:0.1];
        _excitationLevel = [self createPropertyWithValue:0 minimum:0 maximum:1];

        AKJitter *frequencyJitter = [[AKJitter alloc] initWithAmplitude:akp(30)
                                                       minimumFrequency:akp(1)
                                                       maximumFrequency:akp(3)];

        AKMix *excitedFrequency = [[AKMix alloc] initWithInput1:[buzz.normalFrequency plus:frequencyJitter]
                                                         input2:buzz.excitedFrequency
                                                        balance:_excitationLevel];

        AKVCOscillator *soundSource = [AKVCOscillator oscillator];
        soundSource.frequency = excitedFrequency;
        soundSource.amplitude = _amplitude;

        AKMoogVCF *filter = [AKMoogVCF presetDefaultFilterWithInput:soundSource];
        filter.cutoffFrequency = akp(1000);
        filter.resonance = akp(0.1);

        [self setAudioOutput:filter];
    }
    return self;
}
@end

@implementation Buzz

- (instancetype)init
{
    self = [super init];
    if (self) {
        _normalFrequency  = [self createPropertyWithValue:300
                                                  minimum:200
                                                  maximum:400];
        _excitedFrequency = [self createPropertyWithValue:(powf(2.0,(arc4random() % 3))
                                                           * 150.0f + boris_random(0, 5))
                                                  minimum:0
                                                  maximum:8000];
    }
    return self;
}
@end

@implementation Playground

- (void)run
{
    [super run];

    Swarm *swarm = [[Swarm alloc] initWithNumber:1];
    [AKOrchestra addInstrument:swarm];

    for (int i = 1; i <= 30; i++) {
        Buzz *buzz = [[Buzz alloc] init];
        [buzz.normalFrequency randomize];
        [swarm playNote:buzz];
    }

    [self addSliderForProperty:swarm.amplitude title:@"Amplitude"];
    [self addSliderForProperty:swarm.excitationLevel title:@"Excitation"];
    [self addButtonWithTitle:@"Stop" block:^{
        [swarm stop];
    }];

}
@end


text:
import { Entity } from "../../../../../../src"
import { PrimaryColumn } from "../../../../../../src"
import { Column } from "../../../../../../src"

@Entity()
export class Post {
    @PrimaryColumn()
    id: number

    @Column()
    name: string

    // -------------------------------------------------------------------------
    // Numeric Types
    // -------------------------------------------------------------------------

    @Column("integer")
    integer: string

    @Column("int4")
    int4: number

    @Column("int")
    int: string

    @Column("smallint")
    smallint: number

    @Column("int2")
    int2: number

    @Column("bigint")
    bigint: string

    @Column("int8")
    int8: string

    @Column("int64")
    int64: string

    @Column("double precision")
    doublePrecision: number

    @Column("float4")
    float4: number

    @Column("float8")
    float8: number

    @Column("real")
    real: number

    @Column("numeric")
    numeric: string

    @Column("decimal")
    decimal: string

    @Column("dec")
    dec: string

    // -------------------------------------------------------------------------
    // Character Types
    // -------------------------------------------------------------------------

    @Column("char")
    char: string

    @Column("character")
    character: string

    @Column("varchar")
    varchar: string

    @Column("character varying")
    characterVarying: string

    @Column("char varying")
    charVarying: string

    @Column("string")
    string: string

    @Column("text")
    text: string

    // -------------------------------------------------------------------------
    // Binary Data Types
    // -------------------------------------------------------------------------

    @Column("bytes")
    bytes: Buffer

    @Column("bytea")
    bytea: Buffer

    @Column("blob")
    blob: Buffer

    // -------------------------------------------------------------------------
    // Date/Time Types
    // -------------------------------------------------------------------------

    @Column("date")
    date: string

    @Column("interval")
    interval: any

    @Column("time")
    time: string

    @Column("time without time zone")
    timeWithoutTimeZone: string

    @Column("timestamp")
    timestamp: Date

    @Column("timestamp with time zone")
    timestampWithTimeZone: Date

    @Column("timestamp without time zone")
    timestampWithoutTimeZone: Date

    @Column("timestamptz")
    timestamptz: Date

    // -------------------------------------------------------------------------
    // Boolean Type
    // -------------------------------------------------------------------------

    @Column("boolean")
    boolean: boolean

    @Column("bool")
    bool: boolean

    // -------------------------------------------------------------------------
    // Network Address Type
    // -------------------------------------------------------------------------

    @Column("inet")
    inet: string

    // -------------------------------------------------------------------------
    // UUID Type
    // -------------------------------------------------------------------------

    @Column("uuid")
    uuid: string

    // -------------------------------------------------------------------------
    // JSON Type
    // -------------------------------------------------------------------------

    @Column("jsonb")
    jsonb: Object

    @Column("json")
    json: Object

    // -------------------------------------------------------------------------
    // Array Type
    // -------------------------------------------------------------------------

    @Column("int", { array: true })
    array: string[]

    // -------------------------------------------------------------------------
    // TypeOrm Specific Types
    // -------------------------------------------------------------------------

    @Column("simple-array")
    simpleArray: string[]

    @Column("simple-json")
    simpleJson: { param: string }
}

redpajama_set_name: RedPajamaGithub


text:
from django import template
from django.template import Context

register = template.Library()

class TableNode(template.Node):
    template_name = "table/table.html"

    def __init__(self, table):
        self.table = template.Variable(table)

    def render(self, context):
        table = self.table.resolve(context)
        t = template.loader.get_template(
            table.opts.template_name or self.template_name)
        context = {'table': table}
        return t.render(context)

class SimpleTableNode(TableNode):
    template_name = "table/simple_table.html"

@register.tag
def render_table(parser, token):
    try:
        tag, table = token.split_contents()
    except ValueError:
        msg = '%r tag requires a single arguments' % token.split_contents()[0]
        raise template.TemplateSyntaxError(msg)
    return TableNode(table)

@register.tag
def render_simple_table(parser, token):
    try:
        tag, table = token.split_contents()
    except ValueError:
        msg = '%r tag requires a single arguments' % token.split_contents()[0]
        raise template.TemplateSyntaxError(msg)
    return SimpleTableNode(table)


text:
//
//  Pendulum.hpp
//  NumCH
//
//  Created by Christian J Howard on 12/25/15.
//  Copyright © 2015 Christian Howard. All rights reserved.
//

#ifndef Pendulum_hpp
#define Pendulum_hpp

#include <stdio.h>
#include "DynamicModel.hpp"
#include "SimState.hpp"
#include <math.h>
#include "Constants.hpp"

/*!
 * These dynamics represent a simple 1D nonlinear Pendulum model
 */
class PendulumModel : public DynamicModel {

public:

    PendulumModel(){
        model_name = "pendulum";
    }

    /*!
     * This method is used to do initialization
     * that needs to be done every time a sim is run
     * but could benefit from occuring after all the
     * proper model constructions and linking has occurred.
     * A good example could be initializing this model
     * based on data in other models in the simulation.
     * Another use of this function is to ensure each
     * monte carlo sim run is initialized properly
     *
     * \params None
     * \returns None
     */
    virtual void initialize(){
        mass            = 0*generator->rand() * 50 + 50;
        dampening       = 0*generator->rand() * 15 + 15;
        lengthPendulum  = 0*generator->rand() * 10 + 1;
        gravity         = 9.81;
        state[0]        = Constants::pi/3;
        state[1]        = Constants::pi/12;
        theta           = state[0];
        thetaDot        = state[1];
    }

    /*!
     *
     * Method that allows a model to have some
     * data saved to a sim history file
     *
     */
    virtual void setupPrintData(){
        simState->dataPrinter.addVariableToPrint(&state[0],    "Theta");
        simState->dataPrinter.addVariableToPrint(&state[1], "ThetaDot");
    }

    /*!
     * In the event this model
     * is based on differential
     * equations, this method returns
     * the number of dimensions
     * in the ODE equations
     *
     * \params None
     * \returns Number of Dimensions in System of ODEs
     */
    virtual int numDims() const { return 2; }

    /*!
     * This is a method that represents
     * the system of differential equations
     * and outputs the rate of change of the
     * variables in the equations
     *
     * \params dxdt A vector that will hold the rate of hange
     of the diffeq variables. This vector
     will be modified in this method and in
     turn make this input also the output
     * \returns None
     */
    virtual void operator()( double time , ModelState & dqdt ){
        theta    = state[0];
        thetaDot = state[1];
        dqdt[0] = thetaDot;
        dqdt[1] = -( dampening*thetaDot/mass + gravity * sin(theta)/ lengthPendulum);
    }

private:
    double theta, thetaDot;
    double mass;            // in kg
    double dampening;       //
    double gravity;         // m/s^2
    double lengthPendulum;  // in meters

};

#endif /* Pendulum_hpp */


text:
import { setState, getState, IState, ICursor } from './store';

let render: () => void = null;

export let bootstrap = (renderCallback: () => void) => {
    render = renderCallback;
};

export interface IAction<T> {
    (param?: T): void;
}

export function createAction<TState extends IState, TParam>(
    cursor: ICursor<TState>,
    handler: (state: TState, t?: TParam) => TState
): IAction<TParam> {
    if (render === null)
        throw 'RenderCallback must be set before first usage through bootstrap(() => { yourRenderCallback(); }).';
    return <IAction<TParam>>((param?: TParam): void => {
        let oldState = getState(cursor);
        let newState = handler(oldState, param);
        if (oldState !== newState) {
            setState(cursor, newState);
            render();
        }
    });
}


text:
$(function(){

	// Pagination dropdown that updates url + directs to
	// corresponding page.
	$('select.page-list').change(function(){
		var url = $(this).val();
		window.location = url;
	});

});


text:
window.project_title = "CLEWS Mauritius";

window.project_settings = {
  "variable": {
    "unique": false,
    "iparam": true,
    "preselect": [
      "electricity_generation_diff",
      "electricity_generation",
      "emissions",
      "coal",
      "water",
      "land_use_sugarcane"
    ]
  },

  "eth": {
    "unique": true,
    "preselect": [50]
  },

  "rps": {
    "unique": true,
    "preselect": [50]
  },

  "climate": {
    "unique": true,
    "preselect": ["CC2"]
  },
};

window.project_extra_graphs = ['electricity_generation', 'electricity_generation_diff'];

window.project_callback = (scope, sources, selection) => {
  var ref = selection_selection('reference');
  var alt = selection_selection('alternative');

  var rs = tada.f(...ref);
  var as = tada.f(...alt);

  var pair = [
    rs.results.group_p('id'),
    as.results.group_p('id')
  ];

  if (!Object.keys(pair[1]).length) return;

  ui_clear_graphs('reference', 'area-stacked');
  var eid = 'electricity_generation';

  if (selection_graphs_list().includes(eid)) {
    var rg = area_stacked_draw({
      id: eid,
      scope: 'reference',
      container: '#reference-svgs',
      domain: tada.data.domain,
      x: 'time',
      y: 'value',
      sources: rs.results.filter((e) => e.query[tada.f(null)].match(/^electricity_/)),
      colors: d3.schemeCategory10,
    });

    graph_set_title(rg.container, (tada.dict[eid] + " - Reference" || eid));
    graph_add_controls(rg.id, rg.container, sources);

    var ag = area_stacked_draw({
      id: eid + '-alternative',
      scope: 'reference',
      container: '#reference-svgs',
      domain: tada.data.domain,
      x: 'time',
      y: 'value',
      sources: as.results.filter((e) => e.query[tada.f(null)].match(/^electricity_/)),
      colors: d3.schemeCategory10,
    });

    graph_set_title(ag.container, (tada.dict[eid] + " - Alternative" || eid));
    graph_add_controls(ag.id, ag.container, sources);
  }

  ui_clear_graphs('reference', 'bar-stacked');
  var sid = 'electricity_generation_diff';

  if (selection_graphs_list().includes(sid)) {
    var both = ref.map((x,i) => ref[i].concat(alt[i]).unique());

    var b = tada.f(...both).results
      .filter((i) => i.id.match(/^electricity_/));

    var sg = bar_stacked_diff_draw({
      id: sid,
      scope: 'reference',
      container: '#reference-svgs',
      domain: tada.data.domain,
      range: [-3000, 3000],
      sources: b,
      colors: d3.schemeCategory10,
      x_tick: (d,i) => ((i%2) ? d3.timeFormat('%Y')(d) : ''),
    });

    if (sg) {
      graph_set_title(sg.container, (tada.dict[sid] || sid));
      graph_add_controls(sg.id, sg.container, sources);
    }
  }

  ui_clear_graphs('reference', 'line');
  Object.keys(pair[0]).intersection(selection_graphs_list()).forEach((k,i) => {
    var sources = pair.map((r) => query_descriptive_objects(r[k][0], tada.data.domain));

    var ld = line_draw({
      id:    k,
      scope: 'reference',
      container: '#reference-svgs',
      domain: tada.data.domain,
      colors: d3.schemeCategory10,
      x:     'time',
      y:     'value',

      mode: { type: 'percent' },

      sources: sources_format(
        sources,
        '--',
        { y: 'value' }
      )
    });

    graph_set_title(ld.container, (tada.dict[k] || k));
    graph_add_controls(ld.id, ld.container, sources.results);
  });

  var ps = tada.f();
  var ss = ['reference', 'alternative'];

  var c = document.querySelector('#currents');
  if (!c) return;

  [ref,alt].forEach((p,j) => {
    p.forEach((s,i) => {
      var t = ps[i];
      var v = c.querySelector(`td[bind="${ss[j]}-${t}"]`);
      if (v) v.innerText = s[0];
    });
  });
};

window.project_init = () => {
  ui_compare_mode();

  var p = document.querySelector('#panes-container');
  var c = document.createElement('div');
  c.id = 'currents';

  c.innerHTML = `

  Renewable Ethanol
  Renewable Electricity
  Rainfall

  Reference

  Alternative

`;

  c.style = `
flex: 1 100%;
max-width: calc(100% - 4em);
display: flex;
text-align: center;
margin: 1em auto;`;

  p.insertBefore(c, p.firstChild);

  document.querySelector('.column-title').remove();
  document.querySelector('#alternative-column').remove();
  document.querySelector('#sidebar li:nth-of-type(3)').remove();

  _checkbox_set(document.querySelector('input#rps-reference-20'), true);
};


text:
<?php
namespace Changelog\Model\Entity;

use Cake\ORM\Entity;

/**
 * ChangelogColumn Entity
 *
 * @property int $id
 * @property int $changelog_id
 * @property string $column
 * @property string|resource $before
 * @property string|resource $after
 * @property \Cake\I18n\Time $created
 * @property \Cake\I18n\Time $modified
 *
 * @property \Changelog\Model\Entity\Changelog $changelog
 */
class ChangelogColumn extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        '*' => true,
        'id' => false
    ];

}


text:
module BootstrapForm
  module Inputs
    module DateSelect
      extend ActiveSupport::Concern
      include Base

      included do
        bootstrap_select_group :date_select
      end
    end
  end
end


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.execution;

import com.intellij.debugger.impl.DebuggerManagerImpl;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.execution.CantRunException;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.application.ApplicationConfiguration;
import com.intellij.execution.configurations.*;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ExecutionEnvironmentBuilder;
import com.intellij.execution.util.ExecutionErrorDialog;
import com.intellij.execution.util.JavaParametersUtil;
import com.intellij.execution.util.ProgramParametersUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdkType;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkTypeId;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.task.ExecuteRunConfigurationTask;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.execution.build.MavenExecutionEnvironmentProvider;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.intellij.openapi.util.io.FileUtil.toSystemDependentName;
import static com.intellij.openapi.util.text.StringUtil.isEmpty;
import static com.intellij.openapi.util.text.StringUtil.isNotEmpty;
import static com.intellij.util.containers.ContainerUtil.indexOf;

/**
 * @author ibessonov
 */
public class MavenApplicationConfigurationExecutionEnvironmentProvider implements MavenExecutionEnvironmentProvider {

  @Override
  public boolean isApplicable(@NotNull ExecuteRunConfigurationTask task) {
    return task.getRunProfile() instanceof ApplicationConfiguration;
  }

  @Override
  @Nullable
  public ExecutionEnvironment createExecutionEnvironment(@NotNull Project project, @NotNull ExecuteRunConfigurationTask task,
                                                         @Nullable Executor executor) {
    ConfigurationFactory configurationFactory = MavenRunConfigurationType.getInstance().getConfigurationFactories()[0];
    ApplicationConfiguration applicationConfiguration = (ApplicationConfiguration)task.getRunProfile();
    String mainClassName = applicationConfiguration.getMainClassName();
    if (isEmpty(mainClassName)) {
      return null;
    }

    Module module = applicationConfiguration.getConfigurationModule().getModule();
    if (module == null) {
      return null;
    }

    MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(module);
    if (mavenProject == null) {
      return null;
    }

    MavenRunConfiguration mavenRunConfiguration = new MyExecRunConfiguration(project, configurationFactory, applicationConfiguration);

    mavenRunConfiguration.setBeforeRunTasks(applicationConfiguration.getBeforeRunTasks());
    copyLogParameters(applicationConfiguration, mavenRunConfiguration);

    MavenRunnerParameters runnerParameters = mavenRunConfiguration.getRunnerParameters();
    runnerParameters.setWorkingDirPath(mavenProject.getDirectory());
    runnerParameters.setPomFileName(mavenProject.getFile().getName());

    JavaParameters javaParameters = new JavaParameters();
    JavaParametersUtil.configureConfiguration(javaParameters, applicationConfiguration);

    ParametersList execArgs = new ParametersList();
    execArgs.addAll(javaParameters.getVMParametersList().getList());
    execArgs.add("-classpath");
    execArgs.add("%classpath");
    execArgs.add(mainClassName);
    execArgs.addParametersString(applicationConfiguration.getProgramParameters());

    String execExecutable = getJdkExecPath(applicationConfiguration);
    if (execExecutable == null) {
      throw new RuntimeException(ExecutionBundle.message("run.configuration.cannot.find.vm.executable"));
    }

    String workingDirectory = ProgramParametersUtil.getWorkingDir(applicationConfiguration, project, module);

    List<String> goals = runnerParameters.getGoals();
    if (isNotEmpty(workingDirectory)) {
      goals.add("-Dexec.workingdir=" + workingDirectory);
    }
    goals.add("-Dexec.args=" + execArgs.getParametersString());
    goals.add("-Dexec.executable=" + toSystemDependentName(execExecutable));
    goals.add("exec:exec");

    if (executor == null) {
      executor = DefaultRunExecutor.getRunExecutorInstance();
    }
    return new ExecutionEnvironmentBuilder(project, executor).runProfile(mavenRunConfiguration).build();
  }

  private static String getJdkExecPath(@NotNull ApplicationConfiguration applicationConfiguration) {
    Project project = applicationConfiguration.getProject();
    try {
      Sdk jdk = JavaParametersUtil.createProjectJdk(project, applicationConfiguration.getAlternativeJrePath());
      if (jdk == null) {
        throw new RuntimeException(ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
      }

      SdkTypeId type = jdk.getSdkType();
      if (!(type instanceof JavaSdkType)) {
        throw new RuntimeException(ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
      }

      return ((JavaSdkType)type).getVMExecutablePath(jdk);
    }
    catch (CantRunException e) {
      ExecutionErrorDialog.show(e, "Cannot use specified JRE", project);
    }
    return null;
  }

  private static void copyLogParameters(ApplicationConfiguration applicationConfiguration, MavenRunConfiguration mavenRunConfiguration) {
    for (PredefinedLogFile file: applicationConfiguration.getPredefinedLogFiles()) {
      mavenRunConfiguration.addPredefinedLogFile(file);
    }

    for (LogFileOptions op: applicationConfiguration.getLogFiles()) {
      mavenRunConfiguration.addLogFile(op.getPathPattern(), op.getName(), op.isEnabled(), op.isSkipContent(), op.isShowAll());
    }

    mavenRunConfiguration.setFileOutputPath(applicationConfiguration.getOutputFilePath());
    mavenRunConfiguration.setSaveOutputToFile(applicationConfiguration.isSaveOutputToFile());

    mavenRunConfiguration.setShowConsoleOnStdOut(applicationConfiguration.isShowConsoleOnStdOut());
    mavenRunConfiguration.setShowConsoleOnStdErr(applicationConfiguration.isShowConsoleOnStdErr());
  }

  public static List<String> patchVmParameters(ParametersList vmParameters) {
    List<String> patchedVmParameters = new ArrayList<>(vmParameters.getList());
    for (Iterator<String> iterator = patchedVmParameters.iterator(); iterator.hasNext(); ) {
      String parameter = iterator.next();
      if (parameter.contains("suspend=n,server=y")) {
        iterator.remove();
        patchedVmParameters.add(StringUtil.replace(parameter, "suspend=n,server=y", "suspend=y,server=y"));
        break;
      }
    }
    return patchedVmParameters;
  }

  private static class MyExecRunConfiguration extends MavenRunConfiguration {

    private final ApplicationConfiguration myApplicationConfiguration;

    MyExecRunConfiguration(Project project, ConfigurationFactory configurationFactory,
                                  ApplicationConfiguration applicationConfiguration) {
      super(project, configurationFactory, applicationConfiguration.getName());
      myApplicationConfiguration = applicationConfiguration;
    }

    @NotNull
    @Override
    public RemoteConnectionCreator createRemoteConnectionCreator(JavaParameters javaParameters) {
      return new RemoteConnectionCreator() {

        @Override
        public RemoteConnection createRemoteConnection(ExecutionEnvironment environment) {
          try {
            JavaParameters parameters = new JavaParameters();
            parameters.setJdk(JavaParametersUtil.createProjectJdk(getProject(), myApplicationConfiguration.getAlternativeJrePath()));
            RemoteConnection connection = DebuggerManagerImpl.createDebugParameters(
              parameters, false, DebuggerSettings.getInstance().DEBUGGER_TRANSPORT, "", false);

            ParametersList programParametersList = javaParameters.getProgramParametersList();

            String execArgsPrefix = "-Dexec.args=";
            int execArgsIndex = indexOf(programParametersList.getList(), s -> s.startsWith(execArgsPrefix));
            String execArgsStr = programParametersList.get(execArgsIndex);

            ParametersList execArgs = new ParametersList();
            execArgs.addAll(patchVmParameters(parameters.getVMParametersList()));

            execArgs.addParametersString(execArgsStr.substring(execArgsPrefix.length()));

            String classPath = toSystemDependentName(parameters.getClassPath().getPathsString());
            execArgs.replaceOrPrepend("%classpath", "%classpath" + File.pathSeparator + classPath);

            programParametersList.set(execArgsIndex, execArgsPrefix + execArgs.getParametersString());
            return connection;
          }
          catch (ExecutionException e) {
            throw new RuntimeException("Cannot create debug connection", e);
          }
        }

        @Override
        public boolean isPollConnection() {
          return true;
        }
      };
    }
  }
}


text:
<?php
namespace Chamilo\Application\Weblcms\Tool\Implementation\ExamAssignment\Component;

use Chamilo\Application\Weblcms\Tool\Implementation\ExamAssignment\Manager;
use Chamilo\Libraries\Architecture\Interfaces\DelegateComponent;

/**
 * CategoryManager component for the assignment tool.
 *
 * @author Bert De Clercq (Hogeschool Gent)
 * @author Anthony Hurst (Hogeschool Gent)
 */
class CategoryManagerComponent extends Manager implements DelegateComponent
{

    /**
     * #Override Returns additional parameters as an array.
     *
     * @return array The additional parameters
     */
    public function get_additional_parameters()
    {
        return array(\Chamilo\Configuration\Category\Manager::PARAM_CATEGORY_ID);
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EntityInfo.cs" company="">
//
// </copyright>
// <summary>
//   The entity info.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

#region using directives

using System;
using System.Collections.Generic;

using RabbitDB.Contracts.Entity;
using RabbitDB.Entity.ChangeRecorder;

#endregion

namespace RabbitDB.Entity.Entity
{
    /// <summary>
    ///     The entity info.
    /// </summary>
    internal class EntityInfo : IEntityInfo,
                                IChangeRecorder
    {
        #region Fields

        /// <summary>
        ///     The _change tracer.
        /// </summary>
        private readonly IChangeRecorder _changeTracer;

        /// <summary>
        ///     The _disposed.
        /// </summary>
        private bool _disposed;

        #endregion

        #region Construction

        /// <summary>
        ///     Initializes a new instance of the <see cref="EntityInfo" /> class.
        /// </summary>
        /// <param name="changeTracer">
        ///     The change tracer.
        /// </param>
        internal EntityInfo(IChangeRecorder changeTracer)
            : this()
        {
            _changeTracer = changeTracer;
        }

        /// <summary>
        ///     Prevents a default instance of the <see cref="EntityInfo" /> class from being created.
        /// </summary>
        private EntityInfo()
        {
            EntityState = EntityState.None;
            LastCallTime = DateTime.Now;
        }

        #endregion

        #region  Properties

        /// <summary>
        ///     Gets or sets the entity state.
        /// </summary>
        public EntityState EntityState { get; set; }

        /// <summary>
        ///     Gets a value indicating whether can be removed.
        /// </summary>
        internal bool CanBeRemoved => DateTime.Now.Subtract(LastCallTime) > TimeSpan.FromMinutes(2);

        /// <summary>
        ///     Gets or sets the last call time.
        /// </summary>
        internal DateTime LastCallTime { get; set; }

        #endregion

        #region Public Methods

        /// <summary>
        ///     The clear changes.
        /// </summary>
        public void ClearChanges()
        {
            _changeTracer.ClearChanges();
        }

        /// <summary>
        ///     The compute snapshot.
        /// </summary>
        /// <param name="entity">
        ///     The entity.
        /// </param>
        /// <typeparam name="TEntity">
        /// </typeparam>
        public void ComputeSnapshot<TEntity>(TEntity entity)
        {
            _changeTracer.ComputeSnapshot(entity);
        }

        /// <summary>
        ///     The compute values to update.
        /// </summary>
        /// <returns>
        ///     The
        ///     <see>
        ///         <cref>KeyValuePair</cref>
        ///     </see>
        ///     .
        /// </returns>
        public KeyValuePair<string, object>[] ComputeValuesToUpdate()
        {
            return _changeTracer.ComputeValuesToUpdate();
        }

        /// <summary>
        ///     The dispose.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }

        /// <summary>
        ///     The has changes.
        /// </summary>
        /// <returns>
        ///     The <see cref="bool" />.
        /// </returns>
        public bool HasChanges()
        {
            KeyValuePair<string, object>[] valuesToUpdate = ComputeValuesToUpdate();

            return valuesToUpdate.Length > 0
                   || EntityState == EntityState.Deleted
                   || EntityState == EntityState.None;
        }

        /// <summary>
        ///     The merge changes.
        /// </summary>
        public void MergeChanges()
        {
            _changeTracer.MergeChanges();
        }

        #endregion

        #region Internal Methods

        /// <summary>
        ///     The update entity info last call time.
        /// </summary>
        internal void UpdateLastCallTime()
        {
            LastCallTime = DateTime.Now;
        }

        #endregion

        #region Private Methods

        /// <summary>
        ///     The dispose.
        /// </summary>
        /// <param name="dispose">
        ///     The dispose.
        /// </param>
        private void Dispose(bool dispose)
        {
            if (!dispose || _disposed)
            {
                return;
            }

            _changeTracer.Dispose();

            _disposed = true;
        }

        #endregion
    }
}


text:
package org.apache.ivy.plugins.matcher;

import static org.junit.Assert.assertTrue;

import java.util.regex.PatternSyntaxException;

import org.junit.Before;
import org.junit.Test;

/**
 * @see RegexpPatternMatcher
 */
public class RegexpPatternMatcherTest extends AbstractPatternMatcherTest {

    @Before
    public void setUp() {
        setUp(new RegexpPatternMatcher());
    }

    protected String[] getExactExpressions() {
        return new String[] {"abc", "123", "abc-123", "abc_123"};
    }

    protected String[] getInexactExpressions() {
        return new String[] {"abc+", "12.3", "abc-123*", "abc_123\\d"};
    }

    @Test(expected = PatternSyntaxException.class)
    public void testImplementation() {
        Matcher matcher = patternMatcher.getMatcher(".*");
        assertTrue(matcher.matches(".*"));
        assertTrue(matcher.matches(""));
        assertTrue(matcher.matches("a"));
        assertTrue(matcher.matches("aa"));

        matcher = patternMatcher.getMatcher("(");
    }
}


text:
package com.querydsl.spatial;

import javax.annotation.Nullable;

import org.geolatte.geom.LineString;
import org.geolatte.geom.Point;

import com.querydsl.core.types.ConstantImpl;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.NumberExpression;

/**
 * A LineString is a Curve with linear interpolation between Points. Each consecutive pair of Points defines a Line
 * segment.
 *
 * @author tiwe
 *
 * @param <T>
 */
public abstract class LineStringExpression<T extends LineString> extends CurveExpression<T> {

    private static final long serialVersionUID = -6572984614863252657L;

    @Nullable
    private transient volatile NumberExpression<Integer> numPoints;

    public LineStringExpression(Expression<T> mixin) {
        super(mixin);
    }

    /**
     * The number of Points in this LineString.
     *
     * @return number of points
     */
    public NumberExpression<Integer> numPoints() {
        if (numPoints == null) {
            numPoints = Expressions.numberOperation(Integer.class, SpatialOps.NUM_POINTS, mixin);
        }
        return numPoints;
    }

    /**
     * Returns the specified Point N in this LineString.
     *
     * @param idx one basedindex of element
     * @return matched element
     */
    public PointExpression<Point> pointN(int idx) {
        return GeometryExpressions.pointOperation(SpatialOps.POINTN, mixin, ConstantImpl.create(idx));
    }

}


text:
package org.apache.river.discovery;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import net.jini.core.constraint.InvocationConstraints;

/**
 * Utility class used by implementations which want to perform unicast
 * discovery on possibly multiple IP addresses for a given host name.
 * This class supports unicast discovery constraints as specified in
 * DiscoveryConstraints.
 */
public abstract class MultiIPDiscovery {
    // Default value for unicast socket timeout
    public final static int DEFAULT_TIMEOUT = 60 * 1000;

    public UnicastResponse getResponse(String scheme, String host, int port, InvocationConstraints constraints)
	throws IOException, ClassNotFoundException
    {
	InetAddress addrs[] = null;
	try {
	    addrs = InetAddress.getAllByName(host);
	} catch (UnknownHostException uhe) {
	    // Name resolution failed.
	    // We'll just try to use the host name later anyway.
	}

	DiscoveryConstraints dc = DiscoveryConstraints.process(constraints);
	int pv = dc.chooseProtocolVersion();
	Discovery disco;
        /*
         * https is not a jini discovery protocol, it is the https protocol,
         * therefore we cannot perform a handshake to select the discovery
         * provider, or the version.  This is only provided to allow
         * Unicast Discovery to transit through a https proxy server or firewall.
         */
        if ("https".equals(scheme)){
            disco = Discovery.getUnicastHttps(null);
        } else {
            switch (pv) {
                case Discovery.PROTOCOL_VERSION_1:
                    disco = Discovery.getProtocol1();
                    break;
                case Discovery.PROTOCOL_VERSION_2:
                    disco = Discovery.getProtocol2(null);
                    break;
                default:
                    throw new AssertionError(pv);
            }
        }

	long deadline = dc.getConnectionDeadline(Long.MAX_VALUE);
	long connectionTimeout = getTimeout(deadline);

	if (addrs == null) {
	    return getSingleResponse(host, connectionTimeout, port, dc, disco);
	}

	IOException ioEx = null;
	SecurityException secEx = null;
	ClassNotFoundException cnfEx = null;
	for (int i = 0, l = addrs.length; i < l; i++) {
	    try {
		return getSingleResponse(addrs[i].getHostAddress(),
				     connectionTimeout, port, dc, disco);
	    } catch (ClassNotFoundException ex) {
		cnfEx = ex;
		singleResponseException(ex, addrs[i], port);
	    } catch (IOException ex) {
		ioEx = ex;
		singleResponseException(ex, addrs[i], port);
	    } catch (SecurityException ex) {
		secEx = ex;
		singleResponseException(ex, addrs[i], port);
	    }

	    try {
		connectionTimeout = getTimeout(deadline);
	    } catch (SocketTimeoutException ex) {
		if (ioEx == null) {
		    ioEx = ex;
		}
		// Out of time.
		break;
	    }
	}
	if (cnfEx != null) {
	    throw cnfEx;
	}
	if (ioEx != null) {
	    throw ioEx;
	}
	assert (secEx != null);
	throw secEx;
    }

    private long getTimeout(long deadline) throws SocketTimeoutException {
	long now = System.currentTimeMillis();
	if (now >= deadline) {
	    throw new SocketTimeoutException("timeout expired before"
					     + " connection attempted");
	}
	return deadline - now;
    }

    private UnicastResponse getSingleResponse(String host,
					      long connectionTimeout,
					      int port,
					      DiscoveryConstraints dc,
					      Discovery disco)
	throws IOException, ClassNotFoundException
    {
	Socket s = new Socket();
        boolean discoveryAttempted = false;
        try {
            if (connectionTimeout > Integer.MAX_VALUE) {
                s.connect(new InetSocketAddress(host, port));
            } else {
                s.connect(new InetSocketAddress(host, port),
                          (int) connectionTimeout);
            }
            try {
                s.setTcpNoDelay(true);
            } catch (SocketException e) {
                // ignore possible failures and proceed anyway
            }
            try {
                s.setKeepAlive(true);
            } catch (SocketException e) {
                // ignore possible failures and proceed anyway
            }
            s.setSoTimeout(dc.getUnicastSocketTimeout(
                            getDefaultUnicastSocketTimeout()));
            discoveryAttempted = true;
            return performDiscovery(disco, dc, s);
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                if (discoveryAttempted) {
                    socketCloseException(e);
                }
            }
        }
    }

    /*
     * Subclasses may override this method to supply their own default
     * timeout. This class implements this method to return a value of
     * DEFAULT_TIMEOUT.
     */
    protected int getDefaultUnicastSocketTimeout() {
	return DEFAULT_TIMEOUT;
    }

    /*
     * Called when doing unicast discovery on a single IP results in a
     * ClassNotFoundException, IOException or SecurityException. The subclass
     * may perform any action it pleases, like logging. This class implements
     * this method to by default do nothing.
     */
    protected void singleResponseException(Exception ex,
					   InetAddress addr,
					   int port)
    { // do nothing
    }

    /*
     * Called when close of a socket on which discovery has been attempted
     * fails. This class implements this method to do nothing by default.
     */
    protected void socketCloseException(IOException ex) {}

    /*
     * Called to actually perform the discovery operation. All other protected
     * methods have default implementations, this one must be implemented.
     */
    protected abstract UnicastResponse performDiscovery(Discovery disco,
							DiscoveryConstraints dc,
							Socket s)
	throws IOException, ClassNotFoundException;

}


text:
require 'coveralls'
require 'sweatpants'
Coveralls.wear!


text:
import datetime
from datetime import timedelta

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.sites.models import Site
from django.db import models
from django.db.models import Q, Sum, When, Case, Value, Subquery, OuterRef, Exists
from django.db.models.functions import Cast
from django.test import RequestFactory
from django.urls.base import reverse
from django.views import View
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from djmoney.models.fields import MoneyField

from hordak.models.core import Account, Transaction, Leg
from swiftwind.billing_cycle.models import BillingCycle
from swiftwind.settings.models import Settings
from swiftwind.costs.models import RecurringCostSplit
from swiftwind.housemates.models import Housemate
from swiftwind.utilities.emails import EmailViewMixin
from swiftwind.utilities.site import get_site_root

class OverviewView(LoginRequiredMixin, ListView):
    template_name = 'accounts/overview.html'
    context_object_name = 'accounts'

    def get_queryset(self):
        housemate_income = Account.objects.get(name='Housemate Income')
        expenses = Account.objects.get(name='Expenses')
        current_billing_cycle = BillingCycle.objects.as_of(datetime.date.today())

        return Account.objects.filter(

            # We want any account under 'Housemate Income' or 'Expenses'
            Q(lft__gt=housemate_income.lft, rght__lt=housemate_income.rght, tree_id=housemate_income.tree_id)
            |
            Q(lft__gt=expenses.lft, rght__lt=expenses.rght, tree_id=expenses.tree_id)

        ).filter(
            # We only want leaf accounts (no accounts that contain other accounts)
            children__isnull=True

        ).annotate(
            # Is this an expense or housemate account?
            display_type=Case(
                When(housemate__isnull=True, then=Value('expense')),
                default=Value('housemate'),
                output_field=models.CharField()
            )

        ).annotate(
            # When was the last transaction
            latest_transaction_date=Subquery(
                Transaction.objects.filter(legs__account=OuterRef('pk')).order_by('-date').values('date')[:1]
            )

        ).annotate(
            # Has there been a payment during this billing cycle
            payment_since_last_bill=Exists(
                Transaction.objects.filter(
                    legs__amount__gt=0,
                    legs__account=OuterRef('pk'),
                    date__gte=current_billing_cycle.date_range.lower
                )
            )

        )\
            .order_by('-display_type')\
            .select_related('housemate')

class AbstractHousemateStatementView(DetailView):
    template_name = 'accounts/housemate_statement.html'
    slug_url_kwarg = 'uuid'
    slug_field = 'uuid'
    context_object_name = 'housemate'
    queryset = Housemate.objects.all().select_related('account', 'user')

    def get_context_data(self, **kwargs):
        housemate = self.object
        date = self.kwargs.get('date')

        billing_cycle = BillingCycle.objects.as_of(
            date=datetime.date(*map(int, date.split('-'))) if date else datetime.date.today()
        )

        legs = Leg.objects.filter(
            transaction__recurred_cost__billing_cycle=billing_cycle,
            account=housemate.account,
        ).order_by('-transaction__date', '-pk').select_related(
            'transaction',
            'transaction__recurred_cost__recurring_cost__to_account',
        )
        recurring_legs = [l for l in legs if not l.transaction.recurred_cost.recurring_cost.is_one_off()]
        one_off_legs = [l for l in legs if l.transaction.recurred_cost.recurring_cost.is_one_off()]
        other_legs = Leg.objects.filter(
            transaction__date__gte=billing_cycle.date_range.lower,
            transaction__date__lt=billing_cycle.date_range.upper,
            account=housemate.account,
        ).exclude(
            pk__in=[l.pk for l in legs]
        ).order_by('-transaction__date', '-pk').select_related('transaction')

        recurring_total = sum(l.amount for l in recurring_legs)
        one_off_total = sum(l.amount for l in one_off_legs)

        # Previous & next URLs
        # Not a pretty way to generate URLs, but parsing the date to reverse the
        # historical URL would be pretty onerous.
        previous = billing_cycle.get_previous()
        next = billing_cycle.get_next()

        if previous:
            previous_url = '{}{}/'.format(reverse('accounts:housemate_statement', args=[housemate.uuid]), str(previous.start_date))
        else:
            previous_url = ''

        if next and next.start_date <= datetime.date.today():
            next_url = '{}{}/'.format(reverse('accounts:housemate_statement', args=[housemate.uuid]), str(next.start_date))
        else:
            next_url = ''

        return super().get_context_data(
            billing_cycle=billing_cycle,
            start_date=billing_cycle.date_range.lower,
            end_date=billing_cycle.date_range.upper - timedelta(days=1),
            recurring_legs=recurring_legs,
            one_off_legs=one_off_legs,
            other_legs=other_legs,
            recurring_total=recurring_total,
            one_off_total=one_off_total,
            total=recurring_total + one_off_total,
            payment_history=housemate.account.legs.all().order_by('-transaction__date', '-transaction__pk'),
            payment_information=Settings.objects.get().payment_information,
            next_url=next_url,
            previous_url=previous_url,
            **kwargs
        )

class HousemateStatementView(LoginRequiredMixin, AbstractHousemateStatementView):
    pass

class StatementEmailView(EmailViewMixin, AbstractHousemateStatementView):
    template_name = 'accounts/statement_email.html'

class ReconciliationRequiredEmailView(EmailViewMixin, TemplateView):
    template_name = 'accounts/reconciliation_required_email.html'


text:
package org.apache.camel.processor;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

import org.apache.camel.AsyncCallback;
import org.apache.camel.CamelContext;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.NamedNode;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.event.AbstractExchangeEvent;
import org.apache.camel.model.PipelineDefinition;
import org.apache.camel.spi.InterceptStrategy;
import org.apache.camel.support.processor.DelegateAsyncProcessor;
import org.apache.camel.support.service.ServiceSupport;
import org.apache.camel.util.StopWatch;
import org.junit.Test;

/**
 * Test showing how you can use pipeline to group together statistics and implement your own event listener.
 */
public class PipelineStepWithEventTest extends ContextTestSupport {

    private final MyStepEventListener listener = new MyStepEventListener();

    @Test
    public void testPipelineStep() throws Exception {
        getMockEndpoint("mock:a").expectedMessageCount(1);
        getMockEndpoint("mock:a2").expectedMessageCount(1);
        getMockEndpoint("mock:b").expectedMessageCount(1);
        getMockEndpoint("mock:b2").expectedMessageCount(1);
        getMockEndpoint("mock:result").expectedMessageCount(1);

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();

        assertEquals(4, listener.getEvents().size());

        BeforeStepEvent event = (BeforeStepEvent) listener.getEvents().get(0);
        assertEquals("step-a", event.getId());
        AfterStepEvent event2 = (AfterStepEvent) listener.getEvents().get(1);
        assertEquals("step-a", event2.getId());
        assertTrue("Should take a little time", event2.getTimeTaken() > 0);
        BeforeStepEvent event3 = (BeforeStepEvent) listener.getEvents().get(2);
        assertEquals("step-b", event3.getId());
        AfterStepEvent event4 = (AfterStepEvent) listener.getEvents().get(3);
        assertEquals("step-b", event4.getId());
        assertTrue("Should take a little time", event4.getTimeTaken() > 0);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .pipeline().id("step-a")
                        .to("mock:a")
                        .delay(constant(10)).end() // a bit ugly by need to end delay
                        .to("mock:a2")
                    .end()
                    .pipeline().id("step-b")
                        .to("mock:b")
                        .delay(constant(20)).end()  // a bit ugly by need to end delay
                        .to("mock:b2")
                    .end()
                    .to("mock:result");
            }
        };
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        CamelContext context = super.createCamelContext();
        context.adapt(ExtendedCamelContext.class).addInterceptStrategy(new MyInterceptStrategy());
        // register the event listener
        context.addService(listener);
        return context;
    }

    private interface StepEventListener {

        void beforeStep(BeforeStepEvent event);

        void afterStep(AfterStepEvent event);

    }

    private class MyStepEventListener extends ServiceSupport implements StepEventListener {

        private final List<EventObject> events = new ArrayList<>();

        @Override
        public void beforeStep(BeforeStepEvent event) {
            events.add(event);
        }

        @Override
        public void afterStep(AfterStepEvent event) {
            events.add(event);
        }

        public List<EventObject> getEvents() {
            return events;
        }

        @Override
        protected void doStart() throws Exception {
            // noop
        }

        @Override
        protected void doStop() throws Exception {
            // noop
        }
    }

    private class MyInterceptStrategy implements InterceptStrategy {

        @Override
        public Processor wrapProcessorInInterceptors(CamelContext context, NamedNode definition, Processor target, Processor nextTarget) throws Exception {
            // grab the listener
            StepEventListener listener = context.hasService(StepEventListener.class);

            // wrap the pipelines so we can emit events
            if (definition instanceof PipelineDefinition) {
                return new MyStepEventProcessor(definition.getId(), target, listener);
            } else {
                return target;
            }
        }
    }

    private class MyStepEventProcessor extends DelegateAsyncProcessor {

        private final StepEventListener listener;
        private final String id;

        public MyStepEventProcessor(String id, Processor processor, StepEventListener listener) {
            super(processor);
            this.id = id;
            this.listener = listener;
        }

        @Override
        public boolean process(final Exchange exchange, final AsyncCallback callback) {
            final StopWatch watch = new StopWatch();
            if (listener != null) {
                listener.beforeStep(new BeforeStepEvent(exchange, id));
            }
            return super.process(exchange, doneSync -> {
                if (listener != null) {
                    listener.afterStep(new AfterStepEvent(exchange, id, watch.taken()));
                }
                callback.done(doneSync);
            });
        }

    }
    private class BeforeStepEvent extends AbstractExchangeEvent {

        private final String id;

        public BeforeStepEvent(Exchange source, String id) {
            super(source);
            this.id = id;
        }

        @Override
        public Type getType() {
            return Type.Custom;
        }

        public String getId() {
            return id;
        }
    }

    private class AfterStepEvent extends AbstractExchangeEvent {

        private final String id;
        private final long timeTaken;

        public AfterStepEvent(Exchange source, String id, long timeTaken) {
            super(source);
            this.id = id;
            this.timeTaken = timeTaken;
        }

        @Override
        public Type getType() {
            return Type.Custom;
        }

        public String getId() {
            return id;
        }

        public long getTimeTaken() {
            return timeTaken;
        }
    }
}


text:
/**
 * HashMap - HashMap JavaScript class inspired by JDK 8 HashMap class
 * @author Francis Desjardins <me@francisdesjardins.ca>
 * @version 0.0.2
 * Homepage: https://github.com/francisdesjardins/hashmap
 *
 * Key hashing, tests and 'did not knew that' highly inspired by
 * - HashMap by Ariel Flesler https://github.com/flesler/hashmap
 *
 * Implementation and Documentation highly inspired by OpenJDK
 * - http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/HashMap.java#HashMap
 * - http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Map.java#Map
 */
(function(f) {
    if (typeof exports === "object" && typeof module !== "undefined") {
        module.exports = f();
    } else if (typeof define === "function" && define.amd) {
        define([], f);
    } else {
        var g;
        if (typeof window !== "undefined") {
            g = window;
        } else if (typeof global !== "undefined") {
            g = global;
        } else if (typeof self !== "undefined") {
            g = self;
        } else {
            g = this;
        }
        g.HashMap = f();
    }
})(function() {
    var define, module, exports;
    return function e(t, n, r) {
        function s(o, u) {
            if (!n[o]) {
                if (!t[o]) {
                    var a = typeof require == "function" && require;
                    if (!u && a) return a(o, !0);
                    if (i) return i(o, !0);
                    var f = new Error("Cannot find module '" + o + "'");
                    throw f.code = "MODULE_NOT_FOUND", f;
                }
                var l = n[o] = {
                    exports: {}
                };
                t[o][0].call(l.exports, function(e) {
                    var n = t[o][1][e];
                    return s(n ? n : e);
                }, l, l.exports, e, t, n, r);
            }
            return n[o].exports;
        }
        var i = typeof require == "function" && require;
        for (var o = 0; o < r.length; o++) s(r[o]);
        return s;
    }({
        1: [ function(require, module, exports) {
            module.exports = require("./lib/hashmap");
        }, {
            "./lib/hashmap": 2
        } ],
        2: [ function(require, module, exports) {
            (function(global) {
                "use strict";
                var ArrayIterator = require("./hashmap/iterator/array");
                var extend = require("xtend");
                var is = require("./utils/is");
                var isNot = require("./utils/isNot");
                var requireDefined = require("./utils/requireDefined");
                var requireFunction = require("./utils/requireFunction");
                var requireInstanceOf = require("./utils/requireInstanceOf");
                var hash = require("./utils/hash");
                var hasOwnProperty = Object.prototype.hasOwnProperty;
                var defaultOptions = {};
                var pk = {};
                var previousHashMap = global.HashMap;
                function HashMap(map, options) {
                    var privates = {
                        map: {},
                        settings: extend({}, defaultOptions, options)
                    };
                    this.privates = function(key) {
                        if (key === pk) {
                            return privates;
                        }
                    };
                    switch (arguments.length) {
                      case 0:
                        break;

                      case 1:
                        this.putAll(map);
                        break;

                      default:
                        throw new Error();
                    }
                }
                HashMap.noConflict = function() {
                    global.HashMap = previousHashMap;
                    return HashMap;
                };
                HashMap.prototype.clear = function() {
                    this.privates(pk).map = {};
                };
                HashMap.prototype.clone = function() {
                    return new HashMap(this);
                };
                HashMap.prototype.compute = function(key, remappingFunction, context) {
                    requireFunction(remappingFunction, '"remappingFunction" is not a function');
                    context = context || this;
                    var oldValue = this.get(key), newValue = remappingFunction.apply(context, [ key, oldValue ]);
                    requireDefined(newValue, '"newValue" is undefined');
                    if (newValue === null) {
                        if (oldValue !== null || this.containsKey(key)) {
                            this.remove(key);
                        }
                        return null;
                    }
                    this.put(key, newValue);
                    return newValue;
                };
                HashMap.prototype.computeIfAbsent = function(k, mappingFunction, context) {
                    requireFunction(mappingFunction, '"mappingFunction" is not a function');
                    context = context || this;
                    var newValue, oldValue = this.get(k);
                    if (oldValue === null) {
                        newValue = mappingFunction.apply(context, [ k ]);
                        requireDefined(newValue, '"newValue" is undefined');
                        if (newValue !== null) {
                            this.put(k, newValue);
                            return newValue;
                        }
                    }
                    return oldValue;
                };
                HashMap.prototype.computeIfPresent = function(key, remappingFunction, context) {
                    requireFunction(remappingFunction, '"remappingFunction" is not a function');
                    context = context || this;
                    var oldValue = this.get(key), newValue;
                    if (oldValue !== null) {
                        newValue = remappingFunction.apply(context, [ key, oldValue ]);
                        requireDefined(newValue, '"newValue" is undefined');
                        if (newValue !== null) {
                            this.put(key, newValue);
                            return newValue;
                        }
                        this.remove(key);
                    }
                    return null;
                };
                HashMap.prototype.containsKey = function(key) {
                    var hashCode = hash(key), map = this.privates(pk).map;
                    return hasOwnProperty.call(map, hashCode);
                };
                HashMap.prototype.containsValue = function(value) {
                    var found = false;
                    this.forEach(function(k, v) {
                        if (is(value, v)) {
                            found = true;
                            return !found;
                        }
                    });
                    return found;
                };
                HashMap.prototype.entries = function() {
                    var entries = [];
                    this.forEach(function(k, v) {
                        entries.push({
                            key: k,
                            value: v
                        });
                    });
                    return new ArrayIterator(entries);
                };
                HashMap.prototype.equals = function(o) {
                    if (o === this) {
                        return true;
                    }
                    if (!(o instanceof HashMap)) {
                        return false;
                    }
                    if (this.size() !== o.size()) {
                        return false;
                    }
                    var entries = this.entries(), entry;
                    while (entries.hasNext()) {
                        entry = entries.next();
                        if (entry.value === null) {
                            if (!(entry.key === null && o.containsKey(entry.key))) {
                                return false;
                            }
                        } else if (isNot(entry.value, o.get(entry.key))) {
                            return false;
                        }
                    }
                    return true;
                };
                HashMap.prototype.forEach = function(action, context) {
                    requireFunction(action, '"action" is not a function');
                    context = context || this;
                    var key, map = this.privates(pk).map;
                    for (key in map) {
                        if (hasOwnProperty.call(map, key)) {
                            if (action.apply(context, map[key]) === false) {
                                break;
                            }
                        }
                    }
                };
                HashMap.prototype.get = function(key) {
                    var hashCode = hash(key), map = this.privates(pk).map;
                    if (hasOwnProperty.call(map, hashCode)) {
                        return map[hashCode][1];
                    }
                    return null;
                };
                HashMap.prototype.getOrDefault = function(key, value) {
                    return this.containsKey(key) ? this.get(key) : value;
                };
                HashMap.prototype.isEmpty = function() {
                    return !this.size();
                };
                HashMap.prototype.keys = function() {
                    var keys = [];
                    this.forEach(function(k) {
                        keys.push(k);
                    });
                    return new ArrayIterator(keys);
                };
                HashMap.prototype.merge = function(key, value, remappingFunction, context) {
                    requireFunction(remappingFunction, '"remappingFunction" is not a function');
                    context = context || this;
                    var newValue, oldValue;
                    oldValue = this.get(key);
                    newValue = oldValue === null ? value : remappingFunction.apply(context, [ oldValue, value ]);
                    requireDefined(newValue, '"newValue" is undefined');
                    if (newValue === null) {
                        this.remove(key);
                    } else {
                        return this.put(key, newValue);
                    }
                    return newValue;
                };
                HashMap.prototype.put = function(key, value) {
                    requireDefined(value, '"value" is undefined');
                    var hashCode = hash(key), map = this.privates(pk).map;
                    map[hashCode] = [ key, value ];
                    return value;
                };
                HashMap.prototype.putAll = function(map) {
                    requireInstanceOf(map, HashMap, '"map" is not an instance of HashMap');
                    var entries = map.entries(), entry;
                    while (entries.hasNext()) {
                        entry = entries.next();
                        this.put(entry.key, entry.value);
                    }
                };
                HashMap.prototype.putIfAbsent = function(key, value) {
                    var currentValue = this.get(key);
                    if (currentValue === null) {
                        currentValue = this.put(key, value);
                    }
                    return currentValue;
                };
                HashMap.prototype.remove = function(key) {
                    var currentValue = this.get(key), map = this.privates(pk).map;
                    delete map[hash(key)];
                    return currentValue;
                };
                HashMap.prototype.removeIfPresent = function(key, value) {
                    var currentValue = this.get(key);
                    if (isNot(currentValue, value) || currentValue === null && !this.containsKey(key)) {
                        return false;
                    }
                    this.remove(key);
                    return true;
                };
                HashMap.prototype.replace = function(key, value) {
                    var currentValue = this.get(key);
                    if (currentValue !== null) {
                        return this.put(key, value);
                    }
                    return currentValue;
                };
                HashMap.prototype.replaceIfPresent = function(key, value, newValue) {
                    var currentValue = this.get(key);
                    if (isNot(currentValue, value) || currentValue === null && !this.containsKey(key)) {
                        return false;
                    }
                    this.put(key, newValue);
                    return true;
                };
                HashMap.prototype.replaceAll = function(replacingFunction, context) {
                    requireFunction(replacingFunction, '"replacingFunction" is not a function');
                    context = context || this;
                    var entries = this.entries(), entry, newValue;
                    while (entries.hasNext()) {
                        entry = entries.next();
                        newValue = replacingFunction.apply(context, [ entry.key, entry.value ]);
                        if (newValue !== undefined) {
                            if (newValue === null) {
                                this.remove(entry.key);
                            } else {
                                this.put(entry.key, newValue);
                            }
                        }
                    }
                };
                HashMap.prototype.size = function() {
                    return this.keys().length;
                };
                HashMap.prototype.values = function() {
                    var values = [];
                    this.forEach(function(k, v) {
                        values.push(v);
                    });
                    return new ArrayIterator(values);
                };
                module.exports = HashMap;
            }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
        }, {
            "./hashmap/iterator/array": 4,
            "./utils/hash": 7,
            "./utils/is": 8,
            "./utils/isNot": 10,
            "./utils/requireDefined": 11,
            "./utils/requireFunction": 12,
            "./utils/requireInstanceOf": 13,
            xtend: 15
        } ],
        3: [ function(require, module, exports) {
            "use strict";
            var requireFunction = require("../../utils/requireFunction");
            var Iterator = {
                forEachRemaining: function(action, context) {
                    requireFunction(action, '"action" is not a function');
                    context = context || this;
                    while (this.hasNext()) {
                        action.apply(context, [ this.next() ]);
                    }
                },
                hasNext: function() {},
                next: function() {},
                remove: function() {
                    throw new Error('"remove" is not supported');
                }
            };
            module.exports = Iterator;
        }, {
            "../../utils/requireFunction": 12
        } ],
        4: [ function(require, module, exports) {
            "use strict";
            var IteratorInterface = require("../interface/iterator");
            var create = require("../../utils/create");
            var requireInstanceOf = require("../../utils/requireInstanceOf");
            var pk = {};
            var ArrayIterator = function(target) {
                requireInstanceOf(target, Array, '"target" must be an Array');
                var privates = {
                    current: null,
                    currentIndex: -1,
                    target: target,
                    targetIndex: target.length - 1
                };
                this.length = target.length;
                this.privates = function(key) {
                    if (key === pk) {
                        return privates;
                    }
                };
            };
            ArrayIterator.prototype = create(IteratorInterface);
            ArrayIterator.prototype.hasNext = function() {
                var privates = this.privates(pk);
                return privates.currentIndex < privates.targetIndex;
            };
            ArrayIterator.prototype.next = function() {
                var privates = this.privates(pk);
                if (!this.hasNext()) {
                    throw new RangeError("the iteration has no more elements");
                }
                privates.currentIndex += 1;
                privates.current = privates.target[privates.currentIndex];
                return privates.current;
            };
            module.exports = ArrayIterator;
        }, {
            "../../utils/create": 5,
            "../../utils/requireInstanceOf": 13,
            "../interface/iterator": 3
        } ],
        5: [ function(require, module, exports) {
            "use strict";
            var create = Object.create;
            if (typeof create !== "function") {
                create = function() {
                    function Temp() {}
                    var hasOwn = Object.prototype.hasOwnProperty;
                    return function(O) {
                        if (typeof O != "object") {
                            throw new TypeError("Object prototype may only be an Object or null");
                        }
                        Temp.prototype = O;
                        var obj = new Temp();
                        Temp.prototype = null;
                        if (arguments.length > 1) {
                            var Properties = Object(arguments[1]);
                            for (var prop in Properties) {
                                if (hasOwn.call(Properties, prop)) {
                                    obj[prop] = Properties[prop];
                                }
                            }
                        }
                        return obj;
                    };
                }();
            }
            module.exports = create;
        }, {} ],
        6: [ function(require, module, exports) {
            "use strict";
            var defineProperty = Object.defineProperty;
            if (typeof defineProperty !== "function") {
                defineProperty = function(obj, prop, descriptor) {
                    obj[prop] = descriptor.value;
                };
            }
            module.exports = defineProperty;
        }, {} ],
        7: [ function(require, module, exports) {
            "use strict";
            var defineProperty = require("./defineProperty");
            var hasOwnProperty = Object.prototype.hasOwnProperty;
            var isExtensible = require("./isExtensible");
            var typeOf = require("./type");
            var hash = function() {
                var identity = 0, identityProperty = "__hash_201506172259__", immutableTypeTest = {
                    undefined: 1,
                    "null": 1,
                    "boolean": 1,
                    nan: 1,
                    number: 1,
                    regexp: 1
                };
                function nextIdentity() {
                    identity += 1;
                    return identity;
                }
                return function(target) {
                    var hashes, i, length, type = typeOf(target);
                    if (hasOwnProperty.call(immutableTypeTest, type)) {
                        return String(target);
                    }
                    switch (type) {
                      case "date":
                        return "♣" + target.getTime();

                      case "string":
                        return "♠" + target;

                      case "array":
                        hashes = [];
                        for (i = 0, length = target.length; i < length; i += 1) {
                            hashes[i] = hash(target[i]);
                        }
                        return "♥" + hashes.join("⁞");

                      default:
                        if (!hasOwnProperty.call(target, identityProperty)) {
                            if (isExtensible(target)) {
                                try {
                                    defineProperty(target, identityProperty, {
                                        value: nextIdentity(),
                                        writable: false,
                                        configurable: false,
                                        enumerable: false
                                    });
                                } catch (e) {
                                    target[identityProperty] = nextIdentity();
                                }
                            } else {
                                throw new TypeError("Cannot use the given key, object is not extensible");
                            }
                        }
                        return "♦" + target[identityProperty];
                    }
                };
            }();
            module.exports = hash;
        }, {
            "./defineProperty": 6,
            "./isExtensible": 9,
            "./type": 14
        } ],
        8: [ function(require, module, exports) {
            "use strict";
            module.exports = function(x, y) {
                if (x === y) {
                    return x !== 0 || 1 / x === 1 / y;
                }
                return x !== x;
            };
        }, {} ],
        9: [ function(require, module, exports) {
            "use strict";
            var isExtensible = Object.isExtensible;
            if (typeof isExtensible !== "function") {
                isExtensible = function() {
                    return true;
                };
            }
            module.exports = isExtensible;
        }, {} ],
        10: [ function(require, module, exports) {
            "use strict";
            var is = require("./is");
            module.exports = function(x, y) {
                return !is(x, y);
            };
        }, {
            "./is": 8
        } ],
        11: [ function(require, module, exports) {
            "use strict";
            module.exports = function(o, m) {
                if (o === undefined) {
                    throw new ReferenceError(m);
                }
            };
        }, {} ],
        12: [ function(require, module, exports) {
            "use strict";
            module.exports = function(o, m) {
                if (typeof o !== "function") {
                    throw new TypeError(m);
                }
            };
        }, {} ],
        13: [ function(require, module, exports) {
            "use strict";
            module.exports = function(o, c, m) {
                if (!(o instanceof c)) {
                    throw new TypeError(m);
                }
            };
        }, {} ],
        14: [ function(require, module, exports) {
            "use strict";
            var toString = Object.prototype.toString;
            var typeRegEx = /\[object (\S*)\]/gi;
            module.exports = function(target) {
                var type = toString.apply(target).replace(typeRegEx, "$1").toLowerCase();
                if (type === "number" && isNaN(target)) {
                    return "nan";
                }
                if (type === "object") {
                    switch (target) {
                      case null:
                        return "null";

                      case undefined:
                        return "undefined";

                      default:
                        return type;
                    }
                }
                return type;
            };
        }, {} ],
        15: [ function(require, module, exports) {
            module.exports = extend;
            function extend() {
                var target = {};
                for (var i = 0; i < arguments.length; i++) {
                    var source = arguments[i];
                    for (var key in source) {
                        if (source.hasOwnProperty(key)) {
                            target[key] = source[key];
                        }
                    }
                }
                return target;
            }
        }, {} ]
    }, {}, [ 1 ])(1);
});


text:
    <meta charset="UTF-8">
    <meta name="author" content="Jori Lytter">
    <meta name="description" content="Kotio home automation">
    <link rel="stylesheet" href="./font-awesome-4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="./style/fonts/leaguegothic/stylesheet.css">
    <link rel="stylesheet" href="./style/fonts/opensans/stylesheet.css">
    <title>Kotio</title>

          <ruuvitag v-if="tag.data" :tag="tag"></ruuvitag>

          <tdsensor v-if="sensor.id" :sensor="sensor"></tdsensor>

          <tdswitch v-if="device.id" :device="device"></tdswitch>

          <tdswitch v-if="group.id" :device="group"></tdswitch>

          <hueswitch :group="group"/>


text:
layout: page
title: Mitchell Bolt Global Award Ceremony
date: 2016-05-24
author: Wayne Solomon
tags: weekly links, java
status: published
summary: Curabitur ut neque ut lorem vehicula.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 12/14/2018
  endDate: 12/16/2018
  ctyhocn: DGOHXHX
  groupCode: MBGAC
published: true
---
Curabitur ac eleifend massa, quis elementum nunc. Donec hendrerit ante dictum, auctor augue vel, accumsan odio. Nunc iaculis felis et turpis condimentum, sed sodales nisi placerat. Nullam feugiat lacinia aliquam. Phasellus scelerisque sodales nibh. Etiam pharetra risus eros, sed dictum felis porta ac. Donec condimentum sodales lorem, et auctor odio tristique vel.

* Phasellus dapibus lectus eget metus pellentesque rutrum
* Donec faucibus ligula quis iaculis luctus.

Nullam feugiat dui eu ante facilisis imperdiet. Praesent at vehicula tellus. Integer at odio lorem. Suspendisse gravida quam eu dui fringilla venenatis. Nunc volutpat eros felis, eget molestie ligula bibendum quis. Vestibulum sit amet metus lacinia, fermentum massa eget, pellentesque eros. Nulla facilisi. Nam vitae sem at leo placerat eleifend vitae eu tortor. Cras dolor magna, tincidunt a pretium a, fringilla eget felis. Cras mollis purus nec mattis laoreet. Suspendisse a dui finibus, sollicitudin quam in, vehicula nisi. Donec lobortis eu urna a ultrices. Integer sapien sem, interdum id purus ac, sodales rutrum libero. Duis dignissim risus a augue tempor aliquam. Pellentesque sed laoreet dui. Ut vitae vestibulum nibh, vitae elementum mauris.


text:
var ToneGen = function() {
  /**
  * Initializes tone generator.
   */
  this.init = function() {
    this.audioContext = new AudioContext();
  }

  /**
   * Sets sample rate
   * @param {int} sample rate
   */
  this.setSampleRate = function(sampleRate) {
    this.sampleRate = sampleRate;
  }

  /**
   * Sets start/end frequencies and logarithmic sweep
   * @param {int} start frequency
   * @param {int} end frequency
   * @param {boolean} logarithmic sweep or not
   */
  this.setFreq = function(freqStart, freqEnd, sweepLog) {
    this.freqStart = freqStart;
    this.freqEnd = freqEnd;
    this.sweepLog = sweepLog;
  }

  /**
   * Sets tone duration
   * @param {float} duration in seconds
   */
  this.setDuration = function(duration) {
    this.duration = parseFloat(duration);
  }

  /**
   * Sets left and right gain value
   * @param {float} left gain between 0 and 1
   * @param {float} right gain between 0 and 1
   */
  this.setGain = function(leftGain, rightGain) {
    this.leftGain = parseFloat(leftGain);
    this.rightGain = parseFloat(rightGain);
  }

  /**
   * Generates sine tone buffer
   */
  this.genBuffer = function() {
    this.buffer = this.audioContext.createBuffer(2,
        this.sampleRate * this.duration, this.sampleRate);
    var leftChannel = this.buffer.getChannelData(0);
    var rightChannel = this.buffer.getChannelData(1);
    var phi;
    var k = this.freqEnd / this.freqStart;
    var beta = this.duration / Math.log(k);
    for (var i = 0; i < leftChannel.length; i++) {
      if (this.sweepLog) {
        phi = 2 * Math.PI * this.freqStart * beta *
            (Math.pow(k, i / leftChannel.length) - 1.0);
      } else {
        var f = this.freqStart + (this.freqEnd - this.freqStart) *
            i / leftChannel.length / 2;
        phi = f * 2 * Math.PI * i / this.sampleRate;
      }
      leftChannel[i] = this.leftGain * Math.sin(phi);
      rightChannel[i] = this.rightGain * Math.sin(phi);
    }
  }

  /**
   * Returns generated sine tone buffer
   * @return {AudioBuffer} audio buffer
   */
  this.getBuffer = function() {
    return this.buffer;
  }

  /**
   * Returns append buffer
   * @return {AudioBuffer} append audio buffer
   */
  this.getAppendTone = function(sampleRate) {
    var tone_freq = 1000, duration = 0.5;
    this.setFreq(tone_freq, tone_freq, false);
    this.setDuration(duration);
    this.setGain(1, 1);
    this.setSampleRate(sampleRate);
    this.genBuffer();
    return this.getBuffer();
  }

  this.init();
}

window.ToneGen = ToneGen;

var AudioPlay = function() {
  var playCallback = null;
  var sampleRate;
  var playing = false;

  /**
   * Initializes audio play object
   */
  this.init = function() {
    this.audioContext = new AudioContext();
    this.genChannel();
    this.buffer = null;
    sampleRate = this.audioContext.sampleRate;
  }

  /**
   * Loads audio file
   * @param {blob} audio file
   * @param {function} callback function when file loaded
   */
  this.loadFile = function(file_blob, done_cb) {
    if (file_blob) {
      var audioContext = this.audioContext;
      reader = new FileReader();
      reader.onloadend = function(e) {
        audioContext.decodeAudioData(e.target.result,
            function(buffer) {
              done_cb(file_blob.name, buffer);
            });
      };
      reader.readAsArrayBuffer(file_blob);
    }
  }

  /**
   * Sets audio path
   */
  this.genChannel = function() {
    this.node = (this.audioContext.createScriptProcessor ||
        this.audioContext.createJavaScriptNode).call(
        this.audioContext, 4096, 2, 2);
    this.splitter = this.audioContext.createChannelSplitter(2);
    this.merger = this.audioContext.createChannelMerger(2);
    this.node.connect(this.splitter);
    this.splitter.connect(this.merger, 0, 0);
    this.splitter.connect(this.merger, 1, 1);
    this.merger.connect(this.audioContext.destination);

    this.node.onaudioprocess = function(e) {
      for (var i = 0; i < e.inputBuffer.numberOfChannels; i++) {
        e.outputBuffer.getChannelData(i).set(
            e.inputBuffer.getChannelData(i), 0);
      }
      if (!playing) return;
      if (playCallback) {
        var tmpLeft = e.inputBuffer.getChannelData(0).subarray(
            -FFT_SIZE-1, -1);
        var tmpRight = e.inputBuffer.getChannelData(1).subarray(
            -FFT_SIZE-1, -1);
        playCallback(tmpLeft, tmpRight, sampleRate);
      }
    }
  }

  /**
   * Plays audio
   * @param {function} callback function when audio end
   * @param {function} callback function to get current buffer
   */
  this.play = function(done_cb, play_cb) {
    playCallback = play_cb;
    this.source = this.audioContext.createBufferSource();
    this.source.buffer = this.buffer;
    this.source.onended = function(e) {
      playing = false;
      this.disconnect();
      if (done_cb) {
        done_cb();
      }
    }
    this.source.connect(this.node);
    this.source.start(0);
    playing = true;
  }

  /**
   * Stops audio
   */
  this.stop = function() {
    playing = false;
    this.source.stop();
    this.source.disconnect();
  }

  /**
   * Sets audio buffer
   * @param {AudioBuffer} audio buffer
   * @param {boolean} append tone or not
   */
  this.setBuffer = function(buffer, append) {
    if (append) {
      function copyBuffer(src, dest, offset) {
        for (var i = 0; i < dest.numberOfChannels; i++) {
          dest.getChannelData(i).set(src.getChannelData(i), offset);
        }
      }
      var appendTone = tonegen.getAppendTone(buffer.sampleRate);
      var bufferLength = appendTone.length * 2 + buffer.length;
      var newBuffer = this.audioContext.createBuffer(buffer.numberOfChannels,
          bufferLength, buffer.sampleRate);
      copyBuffer(appendTone, newBuffer, 0);
      copyBuffer(buffer, newBuffer, appendTone.length);
      copyBuffer(appendTone, newBuffer, appendTone.length + buffer.length);
      this.buffer = newBuffer;
    } else {
      this.buffer = buffer;
    }
  }

  this.init();
}

window.AudioPlay = AudioPlay;


text:
package nats

import (
	"fmt"
	"os"
	"sync"
	"testing"
	"time"

	"github.com/go-log/log"
	"github.com/micro/go-micro/v2/registry"
	"github.com/nats-io/nats.go"
)

var addrTestCases = []struct {
	name        string
	description string
	addrs       map[string]string // expected address : set address
}{
	{
		"registryOption",
		"set registry addresses through a registry.Option in constructor",
		map[string]string{
			"nats://192.168.10.1:5222": "192.168.10.1:5222",
			"nats://10.20.10.0:4222":   "10.20.10.0:4222"},
	},
	{
		"natsOption",
		"set registry addresses through the nats.Option in constructor",
		map[string]string{
			"nats://192.168.10.1:5222": "192.168.10.1:5222",
			"nats://10.20.10.0:4222":   "10.20.10.0:4222"},
	},
	{
		"default",
		"check if default Address is set correctly",
		map[string]string{
			"nats://localhost:4222": ""},
	},
}

func TestInitAddrs(t *testing.T) {

	for _, tc := range addrTestCases {
		t.Run(fmt.Sprintf("%s: %s", tc.name, tc.description), func(t *testing.T) {

			var reg registry.Registry
			var addrs []string

			for _, addr := range tc.addrs {
				addrs = append(addrs, addr)
			}

			switch tc.name {
			case "registryOption":
				// we know that there are just two addrs in the dict
				reg = NewRegistry(registry.Addrs(addrs[0], addrs[1]))
			case "natsOption":
				nopts := nats.GetDefaultOptions()
				nopts.Servers = addrs
				reg = NewRegistry(Options(nopts))
			case "default":
				reg = NewRegistry()
			}

			// if err := reg.Register(dummyService); err != nil {
			// 	t.Fatal(err)
			// }

			natsRegistry, ok := reg.(*natsRegistry)
			if !ok {
				t.Fatal("Expected registry to be of types *natsRegistry")
			}
			// check if the same amount of addrs we set has actually been set
			if len(natsRegistry.addrs) != len(tc.addrs) {
				t.Errorf("Expected Addr count = %d, Actual Addr count = %d",
					len(natsRegistry.addrs), len(tc.addrs))
			}

			for _, addr := range natsRegistry.addrs {
				_, ok := tc.addrs[addr]
				if !ok {
					t.Errorf("Expected '%s' has not been set", addr)
				}
			}
		})

	}
}

func TestWatchQueryTopic(t *testing.T) {

	natsURL := os.Getenv("NATS_URL")
	if natsURL == "" {
		log.Logf("NATS_URL is undefined - skipping tests")
		return
	}

	watchTopic := "custom.test.watch"
	queryTopic := "custom.test.query"
	wt := WatchTopic(watchTopic)
	qt := QueryTopic(queryTopic)

	// connect to NATS and subscribe to the Watch & Query topics where the
	// registry will publish a msg
	nopts := nats.GetDefaultOptions()
	nopts.Servers = setAddrs([]string{natsURL})
	conn, err := nopts.Connect()
	if err != nil {
		t.Fatal(err)
	}

	wg := sync.WaitGroup{}
	wg.Add(2)

	okCh := make(chan struct{})

	// Wait until we have received something on both topics
	go func() {
		wg.Wait()
		close(okCh)
	}()

	// handler just calls wg.Done()
	rcvdHdlr := func(m *nats.Msg) {
		wg.Done()
	}

	_, err = conn.Subscribe(queryTopic, rcvdHdlr)
	if err != nil {
		t.Fatal(err)
	}

	_, err = conn.Subscribe(watchTopic, rcvdHdlr)
	if err != nil {
		t.Fatal(err)
	}

	dummyService := &registry.Service{
		Name:    "TestInitAddr",
		Version: "1.0.0",
	}

	reg := NewRegistry(qt, wt, registry.Addrs(natsURL))

	// trigger registry to send out message on watchTopic
	if err := reg.Register(dummyService); err != nil {
		t.Fatal(err)
	}

	// trigger registry to send out message on queryTopic
	if _, err := reg.ListServices(); err != nil {
		t.Fatal(err)
	}

	// make sure that we received something on tc.topic
	select {
	case <-okCh:
		// fine - we received on both topics a message from the registry
	case <-time.After(time.Millisecond * 200):
		t.Fatal("timeout - no data received on watch topic")
	}
}


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yiic message' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE, this file must be saved in UTF-8 encoding.
 */
return array (
  'Maximum number of sticked items reached!

You can stick only two items at once.
To however stick this item, unstick another before!' => '',
  'Maximum number of sticked items reached!

You can stick only two items at once.
To however stick this item, unstick another before!' => '@@Nombre maximum d\'éléments collées atteint !

Vous pouvez coller seulement deux éléments à la fois.
Pour Toutefois coller cet article, décoller l\'autre avant !@@',
  'Could not load requested object!' => 'Impossible de charger l\'objet demandé !',
);


text:
# Linked Blocking Multi Queue

_Linked Blocking Multi Queue_ is a concurrent collection that extends the existing [Java concurrent collection library](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html), offering an optionally-bounded blocking "multi-queue" based on linked nodes. That is, essentially, a data structure with several tails but one head, that allows a reader, crucially, to block on more than one queue.

[![Build Status](https://github.com/marianobarrios/linked-blocking-multi-queue/actions/workflows/main.yml/badge.svg)](https://github.com/marianobarrios/linked-blocking-multi-queue/actions)

[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.marianobarrios/linked-blocking-multi-queue/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.marianobarrios/linked-blocking-multi-queue)
[![javadoc](https://javadoc.io/badge2/com.github.marianobarrios/linked-blocking-multi-queue/javadoc.svg)](https://javadoc.io/doc/com.github.marianobarrios/linked-blocking-multi-queue)

## Rationale

 A notorious limitation of Java blocking primitives is that a given thread can only block on one synchronizing object at a time. Blocking on several resources is a generally useful technique, already available in selectors (for channels) in Java. It is also common in other languages. This library offers a collection that can be used when a queue consumer (or consumers) needs to block on several queues.

Features:

- Priorities for different sub-queues
- Customizable priority evaluation (by default, fair (round-robin) selection of elements among same-priority sub-queues).
- Mid-flight addition and removal of sub-queues.
- Mid-flight change of sub-queue status (enabled/disabled).

## Use case

As mentioned, this class essentially allows a consumer to efficiently block a single thread on a set of queues, until one becomes available.

Multiple queues (instead of just one collecting everything) are usually necessary when:

- Not all elements need the same capacity limit.
- Not all elements have the same priority.
- Among the same priority, round-robin (fair) consumption is desired (avoiding that prolific producers starve occasional ones).
- Some subset of enqueued elements may need to be discarded or suspended, while keeping the rest.

## Example

The multi-queue has a no-argument constructor. The class as two type arguments. The first one is the type of the queue key, that is, the type of the values used as keys to identify each sub-queue. The second is the element type. Sub-queues are created from it in a second step:

```java
LinkedBlockingMultiQueue<Int, String> q = new LinkedBlockingMultiQueue<>();
q.addSubQueue(1 /* key */, 10 /* priority */);
q.addSubQueue(2 /* key */, 10 /* priority */, 10000 /* capacity */);
LinkedBlockingMultiQueue<Int, String>.SubQueue sq1 = q.getSubQueue(1);
LinkedBlockingMultiQueue<Int, String>.SubQueue sq2 = q.getSubQueue(2);
```

Then it is possible to offer and poll:

```java
sq1.offer("x1");
q.poll(); // "x1"
sq2.offer("x2");
q.poll(); // "x2"
```

## Features

_Linked Blocking Multi Queue_ is an optionally-bounded blocking "multi-queue" based on linked nodes, defining multi-queue as a set of queues that are connected at the heads and have independent tails (the head of the queue is that element that has been on the queue the longest time, the tail of the queue is that element that has been on the queue the shortest time). New elements are added at the tail of one of the queues, and the queue retrieval operations obtain elements from the head of some of the queues, according to a policy that is described below.

The factory method for sub-queues has an optional capacity argument, as a way to prevent excessive queue expansion. The capacity, if unspecified, is equal to `Integer.MAX_VALUE`. Linked nodes are dynamically created upon each insertion unless this would bring the queue above capacity.

### Priorities

Sub-queues can have different priorities, meaning that elements from higher priority queues will be offered first to consumers. Inside the same priority queues are drained round-robin.

### Enabling, disabling, adding and removing queues
``
A special feature is that individual queues can be enabled or disabled. A disabled queue is not considered for polling (in the event that all the queue are disabled, any blocking operation would do so trying to read, as if all the queues were empty). Elements are taken from the set of enabled queues ()obeying the established priority).

A disabled queue accepts new elements normally until it reaches the maximum capacity (if any).

Individual queues can be enabled or disabled (and also added or removed) at any time.

## Compatibility

Not being actually a linear queue, this class does not implement the `Collection` or `Queue` interfaces. The traditional queue interface is split in the traits: `Offerable` and `Pollable`. Sub-queues do however implement Collection.

## Implementation notes

This implementation is inspired by the
[LinkedBlockingQueue](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/LinkedBlockingQueue.html), made by Doug Lea with assistance from members of [JCP JSR-166 Expert Group](https://jcp.org/en/jsr/detail?id=166).

Each sub-queue uses, as does the `LinkedBlockingQueue`, a variant of the "two lock queue" algorithm. The `putLock` gates entry to `put` (and `offer`), and has an associated condition for waiting puts. The `takeLock`, on the other hand, is unique and shared among all the sub-queues.

Each subqueue has a "count" field, that is maintained as an atomic to avoid needing to get both locks in most cases. Also, to minimize need for puts to get takeLock and vice-versa, cascading notifies are used. When a put notices that it has enabled at  least one take, it signals taker. That taker in turn signals others if more items have been entered since the signal. And symmetrically for takes signaling puts.

The possibility of disabling sub-queues introduces the necessity of an additional centralized atomic count field, which is also updated in every operation and represents, at any time, how many elements can be taken before exhausting the queue.

Operations such as `remove(Object)` and iterators acquire both the corresponding putLock and the takeLock.

Visibility between writers and readers is provided as follows:

Whenever an element is enqueued, the `putLock` is acquired and count updated. A subsequent reader guarantees visibility to the enqueued Node by either acquiring the `putLock` (via `fullyLock`) or by acquiring the `takeLock`, and then reading
`n = count.get()`; this gives visibility to the first `n` items.

To implement weakly consistent iterators, it appears we need to keep all Nodes GC-reachable from a predecessor dequeued Node. That would cause two problems:

- Allow a rogue Iterator to cause unbounded memory retention

- Cause cross-generational linking of old Nodes to new Nodes if a Node was tenured while live, which generational garbage collectors have a hard time dealing with, causing repeated major collections. However, only non-deleted Nodes need to be reachable from dequeued Nodes, and reachability does not necessarily have to be of the kind understood by the garbage collector. We use the trick of linking a Node that has just been dequeued to itself. Such a self-link implicitly means to advance to
`head.next`.

### Requirements

Linked Blocking Multi Queue requires Java 8 or newer.

### Size and Dependencies

The library has no dependencies. The main jar file size is below 20 KB.