text:
package org.apache.cassandra.tools.nodetool;

import org.junit.BeforeClass;
import org.junit.Test;

import org.apache.cassandra.config.DataRateSpec;
import org.apache.cassandra.cql3.CQLTester;

import static org.assertj.core.api.Assertions.withPrecision;

import static org.apache.cassandra.streaming.StreamManager.StreamRateLimiter;
import static org.apache.cassandra.tools.ToolRunner.ToolResult;
import static org.apache.cassandra.tools.ToolRunner.invokeNodetool;
import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@code nodetool setstreamthroughput} and {@code nodetool getstreamthroughput}.
 */
public class SetGetStreamThroughputTest extends CQLTester
{
    private static final int MAX_INT_CONFIG_VALUE_IN_MBIT = Integer.MAX_VALUE - 1;
    private static final double BYTES_PER_MEGABIT = 125_000;
    private static final int MAX_INT_CONFIG_VALUE_MIB = (int) (MAX_INT_CONFIG_VALUE_IN_MBIT * BYTES_PER_MEGABIT) / 1024 / 1024;
    private static final double INTEGER_MAX_VALUE_MEGABITS_IN_BYTES = DataRateSpec.LongBytesPerSecondBound
                                                                      .megabitsPerSecondInBytesPerSecond(MAX_INT_CONFIG_VALUE_IN_MBIT)
                                                                      .toBytesPerSecond();
    private static final double MEBIBYTES_PER_MEGABIT = 0.11920928955078125;

    @BeforeClass
    public static void setup() throws Exception
    {
        startJMXServer();
    }

    @Test
    public void testNull()
    {
        assertSetInvalidThroughput(null, "Required parameters are missing: stream_throughput");
    }

    @Test
    public void testPositive()
    {
        assertSetGetValidThroughput(7, 7 * BYTES_PER_MEGABIT);
        assertSetGetValidThroughputMiB(7, 7 * StreamRateLimiter.BYTES_PER_MEBIBYTE);
        assertSetMbitGetMibValidThroughput(7, 7 * BYTES_PER_MEGABIT);
    }

    @Test
    public void testSmallPositive()
    {
        // As part of CASSANDRA-15234 we had to do some tweaks with precision. This test has to ensure no regressions
        // happen, hopefully. Internally data rate parameters values and rate limitter are set in double. Users can set
        // and get only integers
        assertSetGetValidThroughput(1, 1 * BYTES_PER_MEGABIT);
        assertSetGetValidThroughputMiB(1, 1 * StreamRateLimiter.BYTES_PER_MEBIBYTE);
        assertSetMbitGetMibValidThroughput(1, 1 * BYTES_PER_MEGABIT);
    }

    @Test
    public void testMaxValue()
    {
        assertSetGetValidThroughput(MAX_INT_CONFIG_VALUE_IN_MBIT, INTEGER_MAX_VALUE_MEGABITS_IN_BYTES);
        assertSetGetValidThroughputMiB(MAX_INT_CONFIG_VALUE_MIB, MAX_INT_CONFIG_VALUE_MIB * StreamRateLimiter.BYTES_PER_MEBIBYTE);
        assertSetMbitGetMibValidThroughput(MAX_INT_CONFIG_VALUE_IN_MBIT, INTEGER_MAX_VALUE_MEGABITS_IN_BYTES);
    }

    @Test
    public void testUpperBound()
    {
        assertSetInvalidThroughputMib(String.valueOf(Integer.MAX_VALUE));
        assertSetInvalidThroughputMbit(String.valueOf(Integer.MAX_VALUE));
    }

    @Test
    public void testZero()
    {
        assertSetGetValidThroughput(0, Double.MAX_VALUE);
        assertSetGetValidThroughputMiB(0, Double.MAX_VALUE);
        assertSetMbitGetMibValidThroughput(0, Double.MAX_VALUE);
    }

    @Test
    public void testUnparseable()
    {
        assertSetInvalidThroughput("1.2", "stream_throughput: can not convert \"1.2\" to a int");
        assertSetInvalidThroughput("value", "stream_throughput: can not convert \"value\" to a int");
        assertSetGetMoreFlagsIsInvalid();
        assertDFlagNeeded();
        assertSetGetMoreFlagsIsInvalid();
    }

    private static void assertSetGetValidThroughput(int throughput, double rateInBytes)
    {
        ToolResult tool = invokeNodetool("setstreamthroughput", String.valueOf(throughput));
        tool.assertOnCleanExit();
        assertThat(tool.getStdout()).isEmpty();

        assertGetThroughput(throughput);

        assertThat(StreamRateLimiter.getRateLimiterRateInBytes()).isEqualTo(rateInBytes, withPrecision(0.04));
    }

    private static void assertSetGetValidThroughputMiB(int throughput, double rateInBytes)
    {
        ToolResult tool = invokeNodetool("setstreamthroughput", "-m", String.valueOf(throughput));
        tool.assertOnCleanExit();
        assertThat(tool.getStdout()).isEmpty();

        assertGetThroughputMiB(throughput);

        assertThat(StreamRateLimiter.getRateLimiterRateInBytes()).isEqualTo(rateInBytes, withPrecision(0.01));
    }

    private static void assertDFlagNeeded()
    {
        ToolResult tool = invokeNodetool("setstreamthroughput", "-m", String.valueOf(1));
        tool.assertOnCleanExit();
        assertThat(tool.getStdout()).isEmpty();

        tool = invokeNodetool("getstreamthroughput");
        assertThat(tool.getExitCode()).isEqualTo(2);
        assertThat(tool.getStderr()).contains("Use the -d flag to quiet this error and get the exact throughput in megabits/s");
    }

    private static void assertSetMbitGetMibValidThroughput(int throughput, double rateInBytes)
    {
        ToolResult tool = invokeNodetool("setstreamthroughput", String.valueOf(throughput));
        tool.assertOnCleanExit();
        assertThat(tool.getStdout()).isEmpty();

        assertGetThroughputMiB(throughput * MEBIBYTES_PER_MEGABIT);

        assertThat(StreamRateLimiter.getRateLimiterRateInBytes()).isEqualTo(rateInBytes, withPrecision(0.01));
    }

    private static void assertSetInvalidThroughput(String throughput, String expectedErrorMessage)
    {
        ToolResult tool = throughput == null ? invokeNodetool("setstreamthroughput")
                                             : invokeNodetool("setstreamthroughput", throughput);
        assertThat(tool.getExitCode()).isEqualTo(1);
        assertThat(tool.getStdout()).contains(expectedErrorMessage);
    }

    private static void assertSetInvalidThroughputMib(String throughput)
    {
        ToolResult tool = invokeNodetool("setstreamthroughput", "-m", throughput);
        assertThat(tool.getExitCode()).isEqualTo(1);
        assertThat(tool.getStdout()).contains("stream_throughput_outbound: 2147483647 is too large; it should be less " +
                                              "than 2147483647 in megabits/s");
    }

    private static void assertSetInvalidThroughputMbit(String throughput)
    {
        ToolResult tool = invokeNodetool("setstreamthroughput", throughput);
        assertThat(tool.getExitCode()).isEqualTo(1);
        assertThat(tool.getStdout()).contains("Invalid data rate: 2147483647 megabits per second; stream_throughput_outbound " +
                                              "and inter_dc_stream_throughput_outbound should be between 0 and 2147483646 in megabits per second");
    }

    private static void assertSetGetMoreFlagsIsInvalid()
    {
        ToolResult tool = invokeNodetool("setstreamthroughput", "-m", "5", "-e", "5");
        assertThat(tool.getExitCode()).isEqualTo(1);
        assertThat(tool.getStdout()).contains("You cannot use -e and -m at the same time");

        tool = invokeNodetool("getstreamthroughput", "-m", "-e");
        assertThat(tool.getExitCode()).isEqualTo(1);
        assertThat(tool.getStdout()).contains("You cannot use more than one flag with this command");

        tool = invokeNodetool("getstreamthroughput", "-m", "-d");
        assertThat(tool.getExitCode()).isEqualTo(1);
        assertThat(tool.getStdout()).contains("You cannot use more than one flag with this command");

        tool = invokeNodetool("getstreamthroughput", "-d", "-e");
        assertThat(tool.getExitCode()).isEqualTo(1);
        assertThat(tool.getStdout()).contains("You cannot use more than one flag with this command");

        tool = invokeNodetool("getstreamthroughput", "-m", "-e", "-d");
        assertThat(tool.getExitCode()).isEqualTo(1);
        assertThat(tool.getStdout()).contains("You cannot use more than one flag with this command");
    }

    private static void assertGetThroughput(int expected)
    {
        ToolResult tool = invokeNodetool("getstreamthroughput");
        tool.assertOnCleanExit();

        if (expected > 0)
            assertThat(tool.getStdout()).contains("Current stream throughput: " + expected + " Mb/s");
        else
            assertThat(tool.getStdout()).contains("Current stream throughput: unlimited");
    }

    private static void assertGetThroughputMiB(double expected)
    {
        ToolResult tool = invokeNodetool("getstreamthroughput", "-m");
        tool.assertOnCleanExit();

        if (expected > 0)
            assertThat(tool.getStdout()).contains("Current stream throughput: " + expected + " MiB/s");
        else
            assertThat(tool.getStdout()).contains("Current stream throughput: unlimited");
    }
}


text:
namespace OCIO_NAMESPACE
{

class GradingPrimaryOpData;
typedef OCIO_SHARED_PTR<GradingPrimaryOpData> GradingPrimaryOpDataRcPtr;
typedef OCIO_SHARED_PTR<const GradingPrimaryOpData> ConstGradingPrimaryOpDataRcPtr;

class GradingPrimaryOpData : public OpData
{
public:

    explicit GradingPrimaryOpData(GradingStyle style);
    GradingPrimaryOpData() = delete;
    GradingPrimaryOpData(const GradingPrimaryOpData & rhs);
    GradingPrimaryOpData & operator=(const GradingPrimaryOpData & rhs);
    virtual ~GradingPrimaryOpData();

    GradingPrimaryOpDataRcPtr clone() const;

    void validate() const override;

    Type getType() const override { return GradingPrimaryType; }

    bool isNoOp() const override;
    bool isIdentity() const override;
    OpDataRcPtr getIdentityReplacement() const override;

    bool hasChannelCrosstalk() const override;

    bool isInverse(ConstGradingPrimaryOpDataRcPtr & r) const;
    GradingPrimaryOpDataRcPtr inverse() const;

    std::string getCacheID() const override;

    GradingStyle getStyle() const noexcept { return m_style; }
    void setStyle(GradingStyle style) noexcept;

    const GradingPrimary & getValue() const { return m_value->getValue(); }
    void setValue(const GradingPrimary & values) { m_value->setValue(values); }

    TransformDirection getDirection() const noexcept;
    void setDirection(TransformDirection dir) noexcept;

    bool isDynamic() const noexcept;
    DynamicPropertyRcPtr getDynamicProperty() const noexcept;
    void replaceDynamicProperty(DynamicPropertyGradingPrimaryImplRcPtr prop) noexcept;
    void removeDynamicProperty() noexcept;

    DynamicPropertyGradingPrimaryImplRcPtr getDynamicPropertyInternal() const noexcept
    {
        return m_value;
    }

    bool equals(const OpData & other) const override;

private:
    GradingStyle                           m_style;
    DynamicPropertyGradingPrimaryImplRcPtr m_value;
};

bool operator==(const GradingPrimaryOpData & lhs, const GradingPrimaryOpData & rhs);

} // namespace OCIO_NAMESPACE

#endif

redpajama_set_name: RedPajamaGithub


text:
builder do
  name :multi_job
  plugin_id 'jenkins-multijob-plugin'
  description 'This plugin, created by Tikal ALM team, gives the option to define complex and hierarchical jobs structure in Jenkins.'
  jenkins_name 'MultiJob Phase'
  announced false

  xml do |params|
    params[:phases].each do |name, content|
      send('com.tikal.jenkins.plugins.multijob.MultiJobBuilder') do
        phaseName name
        phaseJobs do
          content[:jobs].each do |job|
            send('com.tikal.jenkins.plugins.multijob.PhaseJobsConfig') do
              jobName job[:name]
              currParams job[:current_params] || false
              exposedSCM job[:exposed_scm] || false
              if job[:config]
                configs do
                  if job[:config].key? :predefined_build_parameters
                    send('hudson.plugins.parameterizedtrigger.PredefinedBuildParameters') do
                      properties job[:config][:predefined_build_parameters]
                    end
                  end
                  if job[:config].key? :properties_file
                    send('hudson.plugins.parameterizedtrigger.FileBuildParameters') do
                      propertiesFile job[:config][:properties_file][:file]
                      failTriggerOnMissing job[:config][:properties_file][:skip_if_missing] || 'false'
                    end
                  end
                end
              end
              killPhaseOnJobResultCondition job[:kill_phase_on] || 'FAILURE'
            end
          end
        end
        continuationCondition content[:continue_condition] || 'SUCCESSFUL'
      end
    end
  end
end

builder do
  name :maven3
  plugin_id 'maven-plugin'
  description 'Jenkins plugin for building Maven 2/3 jobs via a special project type.'
  jenkins_name 'Invoke Maven 3'
  announced false
  parameters [
    :mavenName,
    :rootPom,
    :goals,
    :options
  ]

  xml do |helper|
    send('org.jfrog.hudson.maven3.Maven3Builder') do
      mavenName helper.mavenName
      rootPom helper.rootPom
      goals helper.goals
      mavenOpts helper.options
    end
  end
end

builder do
  name :shell_command
  plugin_id 'builtin'
  description 'Lets you run shell commands as a build step.'
  jenkins_name 'Execute shell'
  announced false

  xml do |param|
    send('hudson.tasks.Shell') do
      command param
    end
  end
end

builder do
  name :inject_vars_file
  plugin_id 'envinject'
  description 'This plugin makes it possible to have an isolated environment for your jobs.'
  jenkins_name 'Inject environment variables'
  announced false

  xml do |params|
    EnvInjectBuilder do
      info do
        propertiesFilePath params
      end
    end
  end
end

builder do
  name :blocking_downstream
  plugin_id 'parameterized-trigger'
  description 'This plugin lets you trigger new builds when your build has completed, with various ways of specifying parameters for the new build.'
  jenkins_name 'Trigger/call builds on other projects'
  announced false
  parameters [
    :data,
    :project,
    :trigger_with_no_parameters,
    :fail,
    :mark_fail,
    :mark_unstable
  ]

  xml do |helper|
    send('hudson.plugins.parameterizedtrigger.TriggerBuilder', 'plugin' => 'parameterized-trigger') do
      configs do
        send('hudson.plugins.parameterizedtrigger.BlockableBuildTriggerConfig') do
          configs do
            helper.data
            helper.data.each do |config|
              if config[:params]
                send('hudson.plugins.parameterizedtrigger.PredefinedBuildParameters') do
                  properties config[:params]
                end
              end
              if config[:file]
                send('hudson.plugins.parameterizedtrigger.FileBuildParameters') do
                  propertiesFile config[:file]
                  failTriggerOnMissing false
                end
              end
            end
          end
          projects helper[:project]
          condition 'ALWAYS'
          triggerWithNoParameters helper.trigger_with_no_parameters
          block do
            if helper.fail && helper.colors.include?(helper.fail)
              buildStepFailureThreshold do
                name helper.fail
                ordinal helper.colors[helper.fail][:ordinal]
                color helper.colors[helper.fail][:color]
                completeBuild 'true'
              end
            end
            if helper.mark_fail && helper.colors.include?(helper.mark_fail)
              failureThreshold do
                name helper.mark_fail
                ordinal helper.colors[helper.mark_fail][:ordinal]
                color helper.colors[helper.mark_fail][:color]
                completeBuild 'true'
              end
            end
            if helper.mark_unstable && helper.colors.include?(helper.mark_unstable)
              unstableThreshold do
                name helper.mark_unstable
                ordinal helper.colors[helper.mark_unstable][:ordinal]
                color helper.colors[helper.mark_unstable][:color]
                completeBuild 'true'
              end
            end
          end
          buildAllNodesWithLabel false
        end
      end
    end
  end
end

builder do
  name :remote_job
  plugin_id 'Parameterized-Remote-Trigger'
  description 'A plugin for Jenkins CI that gives you the ability to trigger parameterized builds on a remote Jenkins server as part of your build.'
  jenkins_name 'Trigger a remote parameterized job'
  announced false

  xml do |params|
    param_list = params[:parameters][:content].split("\n") if params[:parameters] && params[:parameters][:content]
    send(
      'org.jenkinsci.plugins.ParameterizedRemoteTrigger.RemoteBuildConfiguration',
      'plugin' => 'Parameterized-Remote-Trigger'
    ) do
      remoteJenkinsName params[:server]
      job params[:job_name]
      shouldNotFailBuild params[:continue_on_remote_failure] if params[:continue_on_remote_failure]
      pollInterval params[:polling_interval] if params[:polling_interval]
      blockBuildUntilComplete params[:blocking] if params[:blocking]
      token
      if params[:parameters] && params[:parameters][:content]
        parameters params[:parameters][:content]
        parameterList do
          param_list.each do |p|
            string p
          end
        end
      elsif params[:parameters] && params[:parameters][:file]
        loadParamsFromFile 'true'
        parameterFile params[:parameters][:file]
      else
        # This was here for some reason?
        # parameters
        parameterList do
          string
        end
      end
      if params[:credentials] && params[:credentials][:type]
        overrideAuth 'true'
        auth do
          send('org.jenkinsci.plugins.ParameterizedRemoteTrigger.Auth') do
            if params[:credentials][:type] == 'api_token'
              authType 'apiToken'
              username params[:credentials][:username]
              API__TOKEN params[:credentials][:api_token]
            else
              authType 'none'
            end
          end
        end
      end
    end
  end
end

builder do
  name :copy_artifact
  plugin_id 'copyartifact'
  description 'Adds a build step to copy artifacts from another project. The plugin lets you specify which build to copy artifacts from (e.g. the last successful/stable build, by build number, or by a build parameter). You can also control the copying process by filtering the files being copied, specifying a destination directory within the target project, etc. Click the help icon on each field to learn the details, such as selecting Maven or multiconfiguration projects or using build parameters. You can also copy from the workspace of the latest completed build of the source project, instead of its artifacts. All artifacts copied are automatically fingerprinted for you.'
  jenkins_name 'Copy artifacts from another project'
  announced false

  xml do |params|
    send('hudson.plugins.copyartifact.CopyArtifact', 'plugin' => 'copyartifact') do
      project params[:project]
      filter params[:artifacts]
      target params[:target_directory]
      parameters params[:filter] if params[:filter]
      if params[:selector] && params[:selector][:type]
        case params[:selector][:type]
        when 'saved'
          send('selector', 'class' => 'hudson.plugins.copyartifact.SavedBuildSelector')
        when 'triggered'
          send('selector', 'class' => 'hudson.plugins.copyartifact.TriggeredBuildSelector') do
            fallbackToLastSuccessful params[:selector][:fallback] if params[:selector][:fallback]
          end
        when 'permalink'
          send('selector', 'class' => 'hudson.plugins.copyartifact.PermalinkBuildSelector') do
            id params[:selector][:id] if params[:selector][:id]
          end
        when 'specific'
          send('selector', 'class' => 'hudson.plugins.copyartifact.SpecificBuildSelector') do
            buildNumber params[:selector][:number] if params[:selector][:number]
          end
        when 'workspace'
          send('selector', 'class' => 'hudson.plugins.copyartifact.WorkspaceSelector')
        when 'parameter'
          send('selector', 'class' => 'hudson.plugins.copyartifact.ParameterizedBuildSelector') do
            parameterName params[:selector][:param] if params[:selector][:param]
          end
        else
          send('selector', 'class' => 'hudson.plugins.copyartifact.StatusBuildSelector') do
            stable params[:selector][:stable] if params[:selector][:stable]
          end
        end
      else
        send('selector', 'class' => 'hudson.plugins.copyartifact.StatusBuildSelector')
      end
      if params[:fingerprint].nil?
        doNotFingerprintArtifacts false
      else
        if params[:fingerprint].to_s == 'true'
          doNotFingerprintArtifacts false
        else
          doNotFingerprintArtifacts true
        end
      end
      flatten true if params[:flatten]
      optional true if params[:optional]
    end
  end
end

builder do
  name :system_groovy
  plugin_id 'groovy'
  description 'Lets you run groovy scripts as a build step.'
  jenkins_name 'System Groovy'
  announced false

  xml do |params|
    send('hudson.plugins.groovy.SystemGroovy', 'plugin' => 'groovy@1.24') do
      if params.key?(:script) && params.key?(:file)
        fail 'Configuration invalid. Both \'script\' and \'file\' keys can not be specified'
      end
      unless params.key?(:script) || params.key?(:file)
        fail 'Configuration invalid. At least one of \'script\' and \'file\' keys must be specified'
      end

      scriptSource('class' => 'hudson.plugins.groovy.StringScriptSource') do
        command params[:script]
      end if params.key? :script

      scriptSource('class' => 'hudson.plugins.groovy.FileScriptSource') do
        scriptFile params[:file]
      end if params.key? :file

      bindings params[:bindings]
      classpath params[:classpath]
    end
  end
end

builder do
  name :checkmarx_scan
  plugin_id 'checkmarx'
  description 'Jenkins plugin for checkmarx security audit'
  jenkins_name 'Trigger a checkmarx security audit of your build'
  announced false
  parameters [
    :serverUrl,
    :useOwnServerCredentials,
    :username,
    :password,
    :incremental,
    :isThisBuildIncremental,
    :projectName,
    :groupId,
    :skipSCMTriggers,
    :waitForResultsEnabled,
    :vulnerabilityThresholdEnabled,
    :highThreshold,
    :mediumThreshold,
    :lowThreshold,
    :preset,
    :presetSpecified,
    :generatePdfReport,
    :excludeFolders,
    :fullScansScheduled,
    :filterPattern
  ]

  xml do |params|
    send('com.checkmarx.jenkins.CxScanBuilder', 'plugin' => 'checkmarx@7.1.8-24') do
      useOwnServerCredentials params[:useOwnServerCredentials]
      serverUrl params[:serverUrl]
      useOwnServerCredentials params[:useOwnServerCredentials]
      username params[:username]
      password params[:password]
      incremental params[:incremental]
      isThisBuildIncremental params[:isThisBuildIncremental]
      projectName params[:projectName]
      groupId params[:groupId]
      skipSCMTriggers params[:skipSCMTriggers]
      waitForResultsEnabled params[:waitForResultsEnabled]
      vulnerabilityThresholdEnabled params[:vulnerabilityThresholdEnabled]
      highThreshold params[:highThreshold]
      mediumThreshold params[:mediumThreshold]
      lowThreshold params[:lowThreshold]
      generatePdfReport params[:generatePdfReport]
      excludeFolders params[:excludeFolders]
      presetSpecified params[:presetSpecified]
      preset params[:preset]
      fullScansScheduled params[:fullScansScheduled]
      filterPattern params[:filterPattern]
    end
  end
end


text:
package de.iss.mv2.logging;

import java.util.Arrays;

/**
 * A helper class to retrieve the current stack trace.
 * @author Marcel Singer
 *
 */
public final class StackTracer {

	/**
	 * Prevents this class from being instantiated.
	 */
	private StackTracer() {
	}

	/**
	 * Retrieves the current stack trace.
	 * @param ignore the amount of stack levels to ignore.
	 * @return The retrieved stack trace.
	 * @throws IllegalArgumentException Is thrown if the given amount of stack levels to ignore is negative.
	 */
	public static StackTraceElement[] getStackTrace(int ignore) throws IllegalArgumentException{
		if(ignore < 0) throw new IllegalArgumentException("The amount of levels to must not be negative.");
		StackTraceElement[] elements = Thread.currentThread().getStackTrace();
		if(elements.length == 0) return elements;
		return Arrays.copyOfRange(elements, 2 + ignore, elements.length);
	}

	/**
	 * Retrieves the current stack trace.
	 * @return The retrieved stack trace.
	 */
	public static StackTraceElement[] getStackTrace() {
		return getStackTrace(1);
	}

}


text:
license: Licensed to the Apache Software Foundation (ASF) under one
         or more contributor license agreements.  See the NOTICE file
         distributed with this work for additional information
         regarding copyright ownership.  The ASF licenses this file
         to you under the Apache License, Version 2.0 (the
         "License"); you may not use this file except in compliance
         with the License.  You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

         Unless required by applicable law or agreed to in writing,
         software distributed under the License is distributed on an
         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
         KIND, either express or implied.  See the License for the
         specific language governing permissions and limitations
         under the License.
---

# Plugin di Windows

In questa sezione vengono fornite informazioni dettagliate per come implementare un plugin da utilizzare in un'applicazione Windows Store. Prima di leggere questo, vedere applicazione plugin per una panoramica della struttura del plugin e la sua interfaccia JavaScript comune. Questa sezione continua a dimostrare il plugin di esempio *eco* che comunica da Cordova webview alla piattaforma nativa e ritorno.

È importante notare che Windows supporta lo sviluppo direttamente in Javascript, che significa sviluppare le porzioni 'native' solo richiesto in casi particolari.

## Creazione di un Plugin di Windows in JavaScript

Queste istruzioni sono per creare un plugin JavaScript puro. Questa comprensione è fondamentale per capire come aggiungere i bit nativo/gestito.

Windows Cordova plugin sono essenzialmente un wrapper sottile esistente WinJS fornito di funzioni, ma supponendo che si desidera definire un'interfaccia comune JS per più dispositivi, in genere avrete 1 file JS che fornisce le API.

    // inside file echoplugin.js
    var EchoPlugin = {
        // the echo function calls successCallback with the provided text in strInput
        // if strInput is empty, it will call the errorCallback
        echo:function(successCallback, errorCallback, strInput) {
            cordova.exec(successCallback,errorCallback,"EchoPlugin","echo",[strInput]);
        }
    }

## Exec all'interno di Cordova su Windows

La funzione cordova.exec è definita in modo diverso su ogni piattaforma, questo è perché ogni piattaforma ha il proprio modo di comunicare tra il codice js di applicazione e il codice wrapper nativo. Ma nel caso di Windows, non non c'è nessun wrapper nativo, quindi la chiamata exec c'è coerenza. Si potrebbe fare il tuo lavoro di unico plugin js direttamente in EchoPlugin.echo, qualcosa come:

    // inside file echoplugin.js ( this is what NOT to do if you want to reuse the JS API cross platform )
    var EchoPlugin = {
        echo:function(successCallback,errorCallback,strInput) {
            if(!strInput || !strInput.length) {
                errorCallback("Error, something was wrong with the input string. =>" + strInput);
            }
            else {
                successCallback(strInput + "echo");
            }
        }
    }

Questo sarebbe/potrebbe funzionare bene, però significa che avrete bisogno di diverse versioni di echoPlugin.js per diverse piattaforme, e forse si potrebbero avere problemi con incongruenze nelle implementazioni. Come best practice, abbiamo deciso di simulare un'API nativa all'interno cordova.exec su Windows, quindi potremmo eseguire lo stesso codice JS e non dover riscriverlo per la piattaforma e anche di approfittare di qualsiasi parametro di controllo, o altri comune codice fornito dagli sviluppatori che stavano lavorando su altre piattaforme.

## Il proxy di exec Cordova

Su Windows, cordova fornisce un proxy che è possibile utilizzare per registrare un oggetto che consente di gestire tutte le chiamate di cordova.exec a un'API.

Ad esempio se si desidera fornire l'implementazione dell'API di accelerometro, si dovrebbe fare questo:

cordova.commandProxy.add ("Accelerometro", {start: funzione () {/ / il tuo codice qui...} / /... e il resto dell'API qui});

Così nel nostro caso, si presuppone che il codice in echoplugin.js è gestione multipiattaforma pertinenti JavaScript e si può scrivere semplicemente un proxy per Windows

    // in file echopluginProxy.js
    cordova.commandProxy.add("EchoPlugin",{
        echo:function(successCallback,errorCallback,strInput) {
            if(!strInput || !strInput.length) {
                errorCallback("Error, something was wrong with the input string. =>" + strInput);
            }
            else {
                successCallback(strInput + "echo");
            }
        }
    });

La definizione di plugin

Se vogliamo che gli utenti del nostro plugin per poter installare facilmente il nostro plugin, dobbiamo definirlo secondo come PlugMan definisce plugin. Ulteriori informazioni su questo nel [Plugin Spec][1]

 [1]: plugin_ref_spec.md.html#Plugin%20Specification

    <?xml version="1.0" encoding="UTF-8"?>
    <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
        id="com.risingj.echoplugin"
        version="0.1.0">

        <js-module src="www/echoplugin.js" name="echoplugin">
            <clobbers target="window.echoplugin" />
        </js-module>

        <!-- windows -->
        <platform name="windows">
            <js-module src="src/windows/echopluginProxy.js" name="EchoProxy">
                <merges target="" />
            </js-module>
        </platform>

        <!-- other platforms -->

    </plugin>

Questo ci dà un lavoro Windows JavaScript plugin che utilizza un file comune (echoplugin.js) e utilizza un proxy per fornire l'unica porzione di Windows di implementazione (echopluginProxy.js). Quindi, come possiamo aggiungere il codice nativo/gestito a questo? Bene, stiamo per iniziare lo stesso, l'unica differenza sarà quello che facciamo dentro nei metodi echopluginProxy.

# Come WinJS accede nativo/gestito

In Windows, WinJS apps creati sono in grado di interagire con codice nativo, questa Inter-op è disponibile per i componenti di Runtime di Windows. I dettagli sono numerosi, e questa guida riguarderà solo le basi. Microsoft fornisce informazioni molto più [qui][2].

 [2]: http://msdn.microsoft.com/en-us/library/windows/apps/hh441569.aspx

Quando si crea il componente di Windows Runtime, qualsiasi classe che viene definito come 'pubblici rif classe sealed' è considerato una 'attivabile classe' e sarà richiamabile da JavaScript.

    // in your header file .h
    namespace EchoRuntimeComponent
    {
        public ref class EchoPluginRT sealed
        {
            public:
            static Platform::String^ Echo(Platform::String^ input);
        }
    }

    // in the implementation file .cpp
    using namespace EchoRuntimeComponent;
    using namespace Platform;

    Platform::String^ EchoPluginRT::Echo(Platform::String^ input)
    {
        if(input->IsEmpty())
        {
            return "Error: input string is empty.";
        }
        else
        {
            return input->ToString() + "echo";
        }
    }

Ora in modo per noi di chiamare il codice nativo, usiamo il namespace e classname lowerCamelCase il metodo che stiamo chiedendo.

var res = EchoRuntimeComponent.EchoPluginRT.echo("boom"); Questo movimento al nostro file echopluginProxy.js, otteniamo questo:

    // in file echopluginProxy.js
    cordova.commandProxy.add("EchoPlugin",{
        echo:function(successCallback,errorCallback,strInput) {
            var res = EchoRuntimeComponent.EchoPluginRT.echo(strInput);
            if(res.indexOf("Error") == 0) {
                errorCallback(res);
            }
            else {
                successCallback(res);
            }
        }
    });

E questo è tutto, abbiamo un'estremità C++ sostenuta js plugin richiamabile per uso in Apache Cordova Windows!

# Alcune note tecniche:

*   il callback è tipicamente async, quindi chiamando il callback subito probabilmente non è previsto dal chiamante. In pratica, se la chiamata non è asincrona, si dovrebbe almeno utilizzare un timeout di javascript per forzare il callback chiamata async.
*   Classi attivabili possono fare tutti i generi di impressionante, come evento dispacciamento, callback asincrono, passando i propri tipi di oggetto, matrici, collezioni, metodi di overload e molto altro ancora. Vi consiglio di che fare il vostro lavoro.
*   Se attacchi ai comuni 8.0 di Windows Phone e Windows SDK API chiamate, sarete in grado di utilizzare lo stesso componente runtime (bit nativo o gestito) in un plugin di Windows Phone 8.0 Apache Cordova. ~ Rimanete sintonizzati per quel post.

# Definendo il tuo plugin

Ora che abbiamo un plugin di lavoro, abbiamo bisogno di rivedere la definizione di plugin da precedenza così noi possiamo pubblicarlo. Ora possiamo aggiungere il componente runtime come un quadro. Si noti che il tipo di output di un WindowsRuntimeComponent può essere winmd o. dll

    <?xml version="1.0" encoding="UTF-8"?>
    <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
        id="com.risingj.echoplugin"
        version="0.2.0">

        <js-module src="www/echoplugin.js" name="echoplugin">
            <clobbers target="window.echoplugin" />
        </js-module>

        <!-- windows -->
        <platform name="windows">
            <js-module src="src/windows/echopluginProxy.js" name="EchoProxy">
                <merges target="" />
            </js-module>
            <framework src="src/windows/EchoRuntimeComponent.winmd" custom="true"/>
        </platform>

        <!-- other platforms -->

    </plugin>

Ecco, ora avete un plugin distribuibile che puoi condividere con il mondo! Una cosa da notare, solo recentemente è stato aggiunto il supporto per l'aggiunta di quadri al progetto Windows Cordova quindi sarà necessario assicurarsi che il vostro cordova utensileria corrente. Cordova-cli e cordova-plugman entrambi supportano l'aggiunta rimozione plugin backup nativo.

> cordova plugin add com.risingj.echoplugin

o

> plugman install --platform windows --plugin com.risingj.echoplugin --project .

https://github.com/purplecabbage/cordova-runtimecomp-echoplug


text:
<?php

namespace Chromabits\Nucleus\Testing\Traits;

use Chromabits\Nucleus\Exceptions\LackOfCoffeeException;
use Chromabits\Nucleus\Support\Std;
use Chromabits\Nucleus\Testing\Impersonator;
use Chromabits\Nucleus\Testing\Mocking\CallAndThrowExpectation;
use Chromabits\Nucleus\Testing\Mocking\CallExpectation;
use Closure;
use Mockery\MockInterface;

/**
 * Trait ImpersonationTrait.
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Nucleus\Testing\Traits
 */
trait ImpersonationTrait
{
    /**
     * Shortcut for an Impersonator instance.
     *
     * @return Impersonator
     */
    public function impersonator()
    {
        return Impersonator::define();
    }

    /**
     * @return array<string, array<CallExpectation|Closure>>
     */
    protected function getCommonProvisions()
    {
        return [];
    }

    /**
     * Build an instance of an Impersonator included common dependencies
     * defined in the map returned by getCommonProvisions().
     *
     * @return Impersonator
     * @throws LackOfCoffeeException
     */
    public function impersonatorWithCommon()
    {
        $impersonator = $this->impersonator();

        Std::map(function ($value, $key) use ($impersonator) {
            if (is_array($value) || $value instanceof Closure) {
                $impersonator->mock($key, $value);

                return;
            }

            $impersonator->provide($value);
        }, $this->getCommonProvisions());

        return $impersonator;
    }

    /**
     * Shortcut for constructing an instance of a CallExpectation.
     *
     * @param string $methodName
     * @param array $arguments
     * @param mixed|null $return
     * @param int $times
     *
     * @return CallExpectation
     */
    public function on(
        $methodName,
        array $arguments,
        $return = null,
        $times = 1
    ) {
        return Impersonator::on($methodName, $arguments, $return, $times);
    }

    /**
     * Shortcut for constructing an instance of a CallAndThrowExpectation.
     *
     * @param string $methodName
     * @param array $arguments
     * @param string $exceptionClass
     * @param string $exceptionMessage
     * @param int $exceptionCode
     *
     * @return CallAndThrowExpectation
     */
    public function throwOn(
        $methodName,
        array $arguments,
        $exceptionClass,
        $exceptionMessage = '',
        $exceptionCode = 0
    ) {
        return Impersonator::throwOn(
            $methodName,
            $arguments,
            $exceptionClass,
            $exceptionMessage,
            $exceptionCode
        );
    }

    /**
     * Build a mock from an array of CallExpectations.
     *
     * @param string $type
     * @param CallExpectation[] $expectations
     *
     * @return MockInterface
     */
    public function expectationsToMock($type, $expectations)
    {
        return $this->impersonator()->expectationsToMock($type, $expectations);
    }
}


text:
layout: page
title: Velasquez 50th Anniversary
date: 2016-05-24
author: Jason Arellano
tags: weekly links, java
status: published
summary: Nam iaculis congue pulvinar. In velit augue, commodo quis egestas.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 11/11/2018
  endDate: 11/13/2018
  ctyhocn: RICEMHX
  groupCode: V5A
published: true
---
Aenean eget quam ligula. In malesuada nunc tincidunt magna eleifend, eget dignissim elit laoreet. Nunc consequat sapien ac velit sodales sagittis. Suspendisse ut ante fringilla libero porttitor tristique. Maecenas nec scelerisque nibh. Vestibulum ac leo vitae quam sollicitudin pretium. Nulla facilisi.

* Morbi at dui ut lacus fringilla dictum
* Phasellus ac nibh sit amet lorem hendrerit malesuada sed non orci.

Ut non bibendum enim, auctor vestibulum nulla. Ut auctor pellentesque eleifend. In quam erat, porttitor at convallis sed, eleifend sed velit. Etiam quis eros neque. Morbi fringilla est nec tellus suscipit pellentesque. Praesent sed posuere justo. Sed consectetur nulla ut eros iaculis, a cursus nulla imperdiet. Donec vitae lorem nec felis pretium placerat.
Etiam fermentum interdum dapibus. Nulla facilisi. Ut non tellus sed lacus pharetra ultricies nec ac dolor. Quisque ut sagittis justo. Etiam erat leo, tempus eget ante et, lobortis faucibus libero. Vestibulum eu efficitur erat. Suspendisse enim sem, sodales vel quam eu, ultrices laoreet nisl. Aliquam erat volutpat. Nam eu facilisis quam, sed gravida elit. Mauris eleifend nibh magna, eu fermentum nulla varius nec. Donec purus libero, facilisis in nunc at, congue consectetur magna. Cras auctor condimentum ultricies. Phasellus cursus non lectus et tempus. Pellentesque vitae lectus iaculis, ultricies nisl eget, bibendum lorem.


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using FlashCards.Core;
using FlashCards.Core.Model;
using FlashCards.Core.ViewModel;
using FlashCards.NavigationModels;
using Microsoft.Azure.Engagement;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace FlashCards
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainView ViewModel { get; set; }
        public ObservableCollection<NavigationLink> NavigationLinks { get; private set; }

        public MainPage()
        {
            this.ViewModel = new MainView(App.DataStore);
            this.NavigationLinks = new ObservableCollection<NavigationLink>();
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            ViewModel.Load();
            BuildLocalizedMenu();
            EngagementAgent.Instance.StartActivity("MainPage");
        }

        private void BuildLocalizedMenu()
        {
            NavigationLinks.Add(new NavigationLink
            {
                Label = "Start",
                Symbol = Symbol.Play,
                Action = () =>
                {
                    var cardCollection = (CollectionPivot.SelectedItem as CollectionView).CardCollection;

                    if (cardCollection != null)
                    {
                        Navigation.Service.Navigate<MemorizationPage>(new MemorizationNavigationModel { CardCollection = cardCollection });
                    }
                }
            });
        }

        private void NavLinkItemClick(object sender, ItemClickEventArgs e)
        {
            var navLink = e.ClickedItem as NavigationLink;
            if (navLink != null)
            {
                navLink.Action();
            }
        }

        private void GoToSettings(object sender, TappedRoutedEventArgs e)
        {

        }

        private void HamburgerButtonClick(object sender, RoutedEventArgs e)
        {
            MainSplitView.IsPaneOpen = !MainSplitView.IsPaneOpen;
        }

        private void CardClicked(object sender, TappedRoutedEventArgs e)
        {
            e.Handled = true;
            var cardView = (e.OriginalSource as FrameworkElement).DataContext as CardView;
            var cardCollection = (CollectionPivot.SelectedItem as CollectionView).CardCollection;

            if (cardView != null && cardCollection != null)
            {
                var parameter = new CardNavigationModel
                {
                    Card = cardCollection.Cards.FirstOrDefault(c => c.Id == cardView.Id),
                    CardCollection = (CollectionPivot.SelectedItem as CollectionView).CardCollection
                };
                Navigation.Service.Navigate<CardEditPage>(parameter);
            }
        }

        private async void DeleteCollection(object sender, RoutedEventArgs e)
        {
            var cardCollection = (CollectionPivot.SelectedItem as CollectionView).CardCollection;
            if (cardCollection == null)
            {
                return;
            }

            if (await Utils.ShowQuestionMessageBox("Are you sure you want to delete the entire collection?", "Delete Collection"))
            {
                App.DataStore.RemoveCollection(cardCollection);
                ViewModel.Load();
                Bindings.Update();
            }
        }

        private void AddCollection(object sender, RoutedEventArgs e)
        {
            var newCollection = new CardCollection
            {
                Id = Guid.NewGuid(),
                Name = "new",
                Description = "New collection"
            };
            App.DataStore.SaveCollection(newCollection);
            ViewModel.Load();
            Bindings.Update();
        }
    }
}


text:
require 'spec_helper'

describe HappyTime::ViewHelpers do
  include ActionView::Helpers
  include HappyTime::ViewHelpers

  before do
    @original_zone = Time.zone
    Time.zone = "UTC"
  end

  after do
    Time.zone = @original_zone
  end

  it 'should render js_timezone select' do
    html = js_timezone_select
    expect(html).to match(/value='UTC'/m), "Didn't find London"
    expect(html).to match(/data-abbreviation='UTC'/m), "Didn't find abbreviation GMT"
    offset = /data-offset='0'/m
    expect(html).to match(offset), "Didn't find offset 0"
    expect(html.scan(offset).count).to eq(1)
    expect(html).to match(/\(GMT\+00:00\) Etc - UTC/m), "Didn't find GMT+00:00"
  end

  it 'should output moment-ready span by default' do
    html = format_time(Time.now)
    expect(html).to match(/span/)
    expect(html).to match(/data-moment-format/)
    expect(html).to match(/data-moment/)
  end

  it 'should not output moment-ready span if specified' do
    html = format_time(Time.now, html: false)
    expect(html).to_not match(/span/)
    expect(html).to_not match(/data-moment-format/)
    expect(html).to_not match(/data-moment/)
  end

end


text:
'use strict';

/* jshint ignore:start */
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */
/* jshint ignore:end */

var _ = require('lodash');  /* jshint ignore:line */
var Holodeck = require('../../../holodeck');  /* jshint ignore:line */
var Request = require(
    '../../../../../lib/http/request');  /* jshint ignore:line */
var Response = require(
    '../../../../../lib/http/response');  /* jshint ignore:line */
var RestException = require(
    '../../../../../lib/base/RestException');  /* jshint ignore:line */
var Twilio = require('../../../../../lib');  /* jshint ignore:line */

var client;
var holodeck;

describe('Command', function() {
  beforeEach(function() {
    holodeck = new Holodeck();
    client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', {
      httpClient: holodeck
    });
  });
  it('should generate valid fetch request',
    function() {
      holodeck.mock(new Response(500, '{}'));

      var promise = client.wireless.v1.commands('DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
      promise = promise.then(function() {
        throw new Error('failed');
      }, function(error) {
        expect(error.constructor).toBe(RestException.prototype.constructor);
      });
      promise.done();

      var solution = {sid: 'DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'};
      var url = _.template('https://wireless.twilio.com/v1/Commands/<%= sid %>')(solution);

      holodeck.assertHasRequest(new Request({
        method: 'GET',
        url: url
      }));
    }
  );
  it('should generate valid fetch_command_sms response',
    function() {
      var body = JSON.stringify({
          'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'command': 'command',
          'command_mode': 'text',
          'date_created': '2015-07-30T20:00:00Z',
          'date_updated': '2015-07-30T20:00:00Z',
          'delivery_receipt_requested': true,
          'sim_sid': 'DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'direction': 'from_sim',
          'sid': 'DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'status': 'queued',
          'transport': 'sms',
          'url': 'https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
      });

      holodeck.mock(new Response(200, body));

      var promise = client.wireless.v1.commands('DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
  it('should generate valid fetch_command_ip response',
    function() {
      var body = JSON.stringify({
          'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'command': 'command',
          'command_mode': 'text',
          'date_created': '2015-07-30T20:00:00Z',
          'date_updated': '2015-07-30T20:00:00Z',
          'delivery_receipt_requested': false,
          'sim_sid': 'DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'direction': 'to_sim',
          'sid': 'DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'status': 'queued',
          'transport': 'ip',
          'url': 'https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
      });

      holodeck.mock(new Response(200, body));

      var promise = client.wireless.v1.commands('DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
  it('should treat the first each arg as a callback',
    function(done) {
      var body = JSON.stringify({
          'commands': [
              {
                  'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'command': 'command',
                  'command_mode': 'text',
                  'date_created': '2015-07-30T20:00:00Z',
                  'date_updated': '2015-07-30T20:00:00Z',
                  'delivery_receipt_requested': true,
                  'sim_sid': 'DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'direction': 'from_sim',
                  'sid': 'DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'status': 'queued',
                  'transport': 'sms',
                  'url': 'https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
              }
          ],
          'meta': {
              'first_page_url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0',
              'key': 'commands',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0'
          }
      });
      holodeck.mock(new Response(200, body));
      client.wireless.v1.commands.each(() => done());
    }
  );
  it('should treat the second arg as a callback',
    function(done) {
      var body = JSON.stringify({
          'commands': [
              {
                  'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'command': 'command',
                  'command_mode': 'text',
                  'date_created': '2015-07-30T20:00:00Z',
                  'date_updated': '2015-07-30T20:00:00Z',
                  'delivery_receipt_requested': true,
                  'sim_sid': 'DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'direction': 'from_sim',
                  'sid': 'DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'status': 'queued',
                  'transport': 'sms',
                  'url': 'https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
              }
          ],
          'meta': {
              'first_page_url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0',
              'key': 'commands',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0'
          }
      });
      holodeck.mock(new Response(200, body));
      client.wireless.v1.commands.each({pageSize: 20}, () => done());
      holodeck.assertHasRequest(new Request({
          method: 'GET',
          url: 'https://wireless.twilio.com/v1/Commands',
          params: {PageSize: 20},
      }));
    }
  );
  it('should find the callback in the opts object',
    function(done) {
      var body = JSON.stringify({
          'commands': [
              {
                  'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'command': 'command',
                  'command_mode': 'text',
                  'date_created': '2015-07-30T20:00:00Z',
                  'date_updated': '2015-07-30T20:00:00Z',
                  'delivery_receipt_requested': true,
                  'sim_sid': 'DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'direction': 'from_sim',
                  'sid': 'DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'status': 'queued',
                  'transport': 'sms',
                  'url': 'https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
              }
          ],
          'meta': {
              'first_page_url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0',
              'key': 'commands',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0'
          }
      });
      holodeck.mock(new Response(200, body));
      client.wireless.v1.commands.each({callback: () => done()}, () => fail('wrong callback!'));
    }
  );
  it('should generate valid list request',
    function() {
      holodeck.mock(new Response(500, '{}'));

      var promise = client.wireless.v1.commands.list();
      promise = promise.then(function() {
        throw new Error('failed');
      }, function(error) {
        expect(error.constructor).toBe(RestException.prototype.constructor);
      });
      promise.done();

      var url = 'https://wireless.twilio.com/v1/Commands';

      holodeck.assertHasRequest(new Request({
        method: 'GET',
        url: url
      }));
    }
  );
  it('should generate valid read_empty response',
    function() {
      var body = JSON.stringify({
          'commands': [],
          'meta': {
              'first_page_url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0',
              'key': 'commands',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0'
          }
      });

      holodeck.mock(new Response(200, body));

      var promise = client.wireless.v1.commands.list();
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
  it('should generate valid read_full response',
    function() {
      var body = JSON.stringify({
          'commands': [
              {
                  'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'command': 'command',
                  'command_mode': 'text',
                  'date_created': '2015-07-30T20:00:00Z',
                  'date_updated': '2015-07-30T20:00:00Z',
                  'delivery_receipt_requested': true,
                  'sim_sid': 'DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'direction': 'from_sim',
                  'sid': 'DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'status': 'queued',
                  'transport': 'sms',
                  'url': 'https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
              }
          ],
          'meta': {
              'first_page_url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0',
              'key': 'commands',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0'
          }
      });

      holodeck.mock(new Response(200, body));

      var promise = client.wireless.v1.commands.list();
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
  it('should generate valid read_ip response',
    function() {
      var body = JSON.stringify({
          'commands': [
              {
                  'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'command': 'command',
                  'command_mode': 'not_confirmable',
                  'date_created': '2015-07-30T20:00:00Z',
                  'date_updated': '2015-07-30T20:00:00Z',
                  'delivery_receipt_requested': true,
                  'sim_sid': 'DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'direction': 'to_sim',
                  'sid': 'DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'status': 'queued',
                  'transport': 'ip',
                  'url': 'https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
              }
          ],
          'meta': {
              'first_page_url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0',
              'key': 'commands',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0'
          }
      });

      holodeck.mock(new Response(200, body));

      var promise = client.wireless.v1.commands.list();
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
  it('should generate valid create request',
    function() {
      holodeck.mock(new Response(500, '{}'));

      var opts = {command: 'command'};
      var promise = client.wireless.v1.commands.create(opts);
      promise = promise.then(function() {
        throw new Error('failed');
      }, function(error) {
        expect(error.constructor).toBe(RestException.prototype.constructor);
      });
      promise.done();

      var url = 'https://wireless.twilio.com/v1/Commands';

      var values = {Command: 'command', };
      holodeck.assertHasRequest(new Request({
          method: 'POST',
          url: url,
          data: values
      }));
    }
  );
  it('should generate valid create_command_sms response',
    function() {
      var body = JSON.stringify({
          'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'command': 'command',
          'command_mode': 'text',
          'date_created': '2015-07-30T20:00:00Z',
          'date_updated': '2015-07-30T20:00:00Z',
          'delivery_receipt_requested': true,
          'sim_sid': 'DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'direction': 'from_sim',
          'sid': 'DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'status': 'queued',
          'transport': 'sms',
          'url': 'https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
      });

      holodeck.mock(new Response(201, body));

      var opts = {command: 'command'};
      var promise = client.wireless.v1.commands.create(opts);
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
  it('should generate valid create_command_ip response',
    function() {
      var body = JSON.stringify({
          'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'command': 'command',
          'command_mode': 'binary',
          'date_created': '2015-07-30T20:00:00Z',
          'date_updated': '2015-07-30T20:00:00Z',
          'delivery_receipt_requested': true,
          'direction': 'to_sim',
          'sid': 'DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'sim_sid': 'DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'status': 'queued',
          'transport': 'ip',
          'url': 'https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
      });

      holodeck.mock(new Response(201, body));

      var opts = {command: 'command'};
      var promise = client.wireless.v1.commands.create(opts);
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
});


text:
package so.ontolog.formula.ast.factory;

import so.ontolog.data.type.TypeSpec;
import so.ontolog.formula.ast.ASTContext;
import so.ontolog.formula.ast.ASTExpr;
import so.ontolog.formula.ast.ASTFactory.MapExprFactory;
import so.ontolog.formula.ast.ASTToken;

/**
 *

 * @author Ikchan Kwon
 *
 */
public class SimpleMapExprFactory implements MapExprFactory{

	@Override
	public ASTExpr createMap(ASTContext context, ASTToken token) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ASTExpr mapEntry(ASTContext context, ASTToken token, ASTExpr map,
			TypeSpec type, String name, ASTExpr value) {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
<?php

namespace Hateoas\Tests\Representation;

use Hateoas\Representation\CollectionRepresentation;
use Hateoas\Representation\OffsetRepresentation;
use Hateoas\Tests\Fixtures\UsersRepresentation;

class OffsetRepresentationTest extends RepresentationTestCase
{
    public function testSerialize()
    {
        $collection = new OffsetRepresentation(
            new CollectionRepresentation(
                array(
                    'Adrien',
                    'William',
                ),
                'authors',
                'users'
            ),
            '/authors',
            array(
                'query' => 'willdurand/Hateoas',
            ),
            44,
            20,
            95,
            null,
            null,
            false
        );

        $this
            ->string($this->hateoas->serialize($collection, 'xml'))
            ->isEqualTo(
                <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<collection offset="44" limit="20" total="95">
  <users rel="authors">
    <entry><![CDATA[Adrien]]></entry>
    <entry><![CDATA[William]]></entry>
  </users>
  <link rel="self" href="/authors?query=willdurand%2FHateoas&offset=44&limit=20"/>
  <link rel="first" href="/authors?query=willdurand%2FHateoas&limit=20"/>
  <link rel="last" href="/authors?query=willdurand%2FHateoas&offset=80&limit=20"/>
  <link rel="next" href="/authors?query=willdurand%2FHateoas&offset=64&limit=20"/>
  <link rel="previous" href="/authors?query=willdurand%2FHateoas&offset=24&limit=20"/>
</collection>

XML
            )
            ->string($this->halHateoas->serialize($collection, 'xml'))
            ->isEqualTo(
                <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<collection offset="44" limit="20" total="95" href="/authors?query=willdurand%2FHateoas&offset=44&limit=20">
  <resource rel="authors"><![CDATA[Adrien]]></resource>
  <resource rel="authors"><![CDATA[William]]></resource>
  <link rel="first" href="/authors?query=willdurand%2FHateoas&limit=20"/>
  <link rel="last" href="/authors?query=willdurand%2FHateoas&offset=80&limit=20"/>
  <link rel="next" href="/authors?query=willdurand%2FHateoas&offset=64&limit=20"/>
  <link rel="previous" href="/authors?query=willdurand%2FHateoas&offset=24&limit=20"/>
</collection>

XML
            )
            ->string($this->hateoas->serialize(new UsersRepresentation($collection), 'xml'))
            ->isEqualTo(
                <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<users offset="44" limit="20" total="95">
  <users rel="authors">
    <entry><![CDATA[Adrien]]></entry>
    <entry><![CDATA[William]]></entry>
  </users>
  <link rel="self" href="/authors?query=willdurand%2FHateoas&offset=44&limit=20"/>
  <link rel="first" href="/authors?query=willdurand%2FHateoas&limit=20"/>
  <link rel="last" href="/authors?query=willdurand%2FHateoas&offset=80&limit=20"/>
  <link rel="next" href="/authors?query=willdurand%2FHateoas&offset=64&limit=20"/>
  <link rel="previous" href="/authors?query=willdurand%2FHateoas&offset=24&limit=20"/>
</users>

XML
            )
            ->string($this->halHateoas->serialize(new UsersRepresentation($collection), 'xml'))
            ->isEqualTo(
                <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<users offset="44" limit="20" total="95" href="/authors?query=willdurand%2FHateoas&offset=44&limit=20">
  <resource rel="authors"><![CDATA[Adrien]]></resource>
  <resource rel="authors"><![CDATA[William]]></resource>
  <link rel="first" href="/authors?query=willdurand%2FHateoas&limit=20"/>
  <link rel="last" href="/authors?query=willdurand%2FHateoas&offset=80&limit=20"/>
  <link rel="next" href="/authors?query=willdurand%2FHateoas&offset=64&limit=20"/>
  <link rel="previous" href="/authors?query=willdurand%2FHateoas&offset=24&limit=20"/>
</users>

XML
            )
            ->string($this->halHateoas->serialize($collection, 'json'))
            ->isEqualTo(
                '{'
                    .'"offset":44,'
                    .'"limit":20,'
                    .'"total":95,'
                    .'"_links":{'
                        .'"self":{'
                            .'"href":"\/authors?query=willdurand%2FHateoas&offset=44&limit=20"'
                        .'},'
                        .'"first":{'
                            .'"href":"\/authors?query=willdurand%2FHateoas&limit=20"'
                        .'},'
                        .'"last":{'
                            .'"href":"\/authors?query=willdurand%2FHateoas&offset=80&limit=20"'
                        .'},'
                        .'"next":{'
                            .'"href":"\/authors?query=willdurand%2FHateoas&offset=64&limit=20"'
                        .'},'
                        .'"previous":{'
                            .'"href":"\/authors?query=willdurand%2FHateoas&offset=24&limit=20"'
                        .'}'
                    .'},'
                    .'"_embedded":{'
                        .'"authors":['
                            .'"Adrien",'
                            .'"William"'
                        .']'
                    .'}'
                .'}'
            )
        ;
    }

    public function testGenerateAbsoluteURIs()
    {
        $collection = new OffsetRepresentation(
            new CollectionRepresentation(
                array(
                    'Adrien',
                    'William',
                ),
                'authors',
                'users'
            ),
            '/authors',
            array(
                'query' => 'willdurand/Hateoas',
            ),
            44,
            20,
            95,
            null,
            null,
            true // force absolute URIs
        );

        $this
            ->string($this->hateoas->serialize($collection, 'xml'))
            ->isEqualTo(
                <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<collection offset="44" limit="20" total="95">
  <users rel="authors">
    <entry><![CDATA[Adrien]]></entry>
    <entry><![CDATA[William]]></entry>
  </users>
  <link rel="self" href="http://example.com/authors?query=willdurand%2FHateoas&offset=44&limit=20"/>
  <link rel="first" href="http://example.com/authors?query=willdurand%2FHateoas&limit=20"/>
  <link rel="last" href="http://example.com/authors?query=willdurand%2FHateoas&offset=80&limit=20"/>
  <link rel="next" href="http://example.com/authors?query=willdurand%2FHateoas&offset=64&limit=20"/>
  <link rel="previous" href="http://example.com/authors?query=willdurand%2FHateoas&offset=24&limit=20"/>
</collection>

XML
            )
            ->string($this->halHateoas->serialize($collection, 'xml'))
            ->isEqualTo(
                <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<collection offset="44" limit="20" total="95" href="http://example.com/authors?query=willdurand%2FHateoas&offset=44&limit=20">
  <resource rel="authors"><![CDATA[Adrien]]></resource>
  <resource rel="authors"><![CDATA[William]]></resource>
  <link rel="first" href="http://example.com/authors?query=willdurand%2FHateoas&limit=20"/>
  <link rel="last" href="http://example.com/authors?query=willdurand%2FHateoas&offset=80&limit=20"/>
  <link rel="next" href="http://example.com/authors?query=willdurand%2FHateoas&offset=64&limit=20"/>
  <link rel="previous" href="http://example.com/authors?query=willdurand%2FHateoas&offset=24&limit=20"/>
</collection>

XML
            )
            ->string($this->halHateoas->serialize($collection, 'json'))
            ->isEqualTo(
                '{'
                    .'"offset":44,'
                    .'"limit":20,'
                    .'"total":95,'
                    .'"_links":{'
                        .'"self":{'
                            .'"href":"http:\/\/example.com\/authors?query=willdurand%2FHateoas&offset=44&limit=20"'
                        .'},'
                        .'"first":{'
                            .'"href":"http:\/\/example.com\/authors?query=willdurand%2FHateoas&limit=20"'
                        .'},'
                        .'"last":{'
                            .'"href":"http:\/\/example.com\/authors?query=willdurand%2FHateoas&offset=80&limit=20"'
                        .'},'
                        .'"next":{'
                            .'"href":"http:\/\/example.com\/authors?query=willdurand%2FHateoas&offset=64&limit=20"'
                        .'},'
                        .'"previous":{'
                            .'"href":"http:\/\/example.com\/authors?query=willdurand%2FHateoas&offset=24&limit=20"'
                        .'}'
                    .'},'
                    .'"_embedded":{'
                        .'"authors":['
                            .'"Adrien",'
                            .'"William"'
                        .']'
                    .'}'
                .'}'
            )
        ;
    }

    public function testExclusion()
    {
        $inline = new CollectionRepresentation(
            array(
                'Adrien',
                'William',
            ),
            'authors',
            'users'
        );

        /*
         * no last entry since `total` is missing
         * no previous only when offset is 0/null
         */
        $collection = new OffsetRepresentation(
            $inline,
            '/authors',
            array(
                'query' => 'willdurand/Hateoas',
            ),
            null,
            20
        );

        $this
            ->string($this->hateoas->serialize($collection, 'xml'))
            ->isEqualTo(
                <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<collection limit="20">
  <users rel="authors">
    <entry><![CDATA[Adrien]]></entry>
    <entry><![CDATA[William]]></entry>
  </users>
  <link rel="self" href="/authors?query=willdurand%2FHateoas&limit=20"/>
  <link rel="first" href="/authors?query=willdurand%2FHateoas&limit=20"/>
  <link rel="next" href="/authors?query=willdurand%2FHateoas&offset=20&limit=20"/>
</collection>

XML
            )
        ;

        /*
         * no next since on last block
         */
        $collection = new OffsetRepresentation(
            $inline,
            '/authors',
            array(
                'query' => 'willdurand/Hateoas',
            ),
            80,
            20,
            100
        );

        $this
            ->string($this->hateoas->serialize($collection, 'xml'))
            ->isEqualTo(
                <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<collection offset="80" limit="20" total="100">
  <users rel="authors">
    <entry><![CDATA[Adrien]]></entry>
    <entry><![CDATA[William]]></entry>
  </users>
  <link rel="self" href="/authors?query=willdurand%2FHateoas&offset=80&limit=20"/>
  <link rel="first" href="/authors?query=willdurand%2FHateoas&limit=20"/>
  <link rel="last" href="/authors?query=willdurand%2FHateoas&offset=80&limit=20"/>
  <link rel="previous" href="/authors?query=willdurand%2FHateoas&offset=60&limit=20"/>
</collection>

XML
            )
        ;
    }
}


text:
var stream    = require('stream');
var util      = require('util');
var Tokenizer = require('../lib/ConfluenceTokenizer.js');
var Confluence2Markdown = require('../lib/Confluence2Markdown')

tokenizer = new Tokenizer();

c2m = new Confluence2Markdown();

process.stdin.pipe(tokenizer)
             .pipe(c2m)
             .pipe(process.stdout)


text:
package net.brord.plugins.menuapi;

import org.bukkit.plugin.java.JavaPlugin;

/**
 * Project menuapi

 * Class net.brord.plugins.menuapi.MenuAPI.java

 * @author Brord
 * @since 3 jun. 2014, 03:04:12
 */
public class MenuAPI extends JavaPlugin {

	private static MenuAPI plugin;

	/**
	 * @return
	 */
	public static MenuAPI getInstance() {
		return plugin;
	}

	/**
	  * @see org.bukkit.plugin.java.JavaPlugin#onEnable()
	  */
	@Override
	public void onEnable() {
		plugin = this;
	}

}


text:
var util = require('util'),
    exec = require('child_process').exec,
    applescript = require('applescript');

// Apple scripts
// ----------------------------------------------------------------------------

var scripts = {
    state: {
        file: 'get_state.applescript'
    },
    track: {
        file: 'get_track.applescript'
    },
    artwork: {
        file: 'get_artwork.applescript'
    },
    volumeUp:
        'tell application "Spotify" to set sound volume to (sound volume + 10)',
    volumeDown:
        'tell application "Spotify" to set sound volume to (sound volume - 10)',
    setVolume:
        'tell application "Spotify" to set sound volume to %s',
    play:
        'tell application "Spotify" to play',
    playTrack:
        'tell application "Spotify" to play track "%s"',
    playPause:
        'tell application "Spotify" to playpause',
    pause:
        'tell application "Spotify" to pause',
    next:
        'tell application "Spotify" to next track',
    previous:
        'tell application "Spotify" to previous track',
    jumpTo:
        'tell application "Spotify" to set player position to %s',
    isRunning:
        'get running of application "Spotify"'
};

// Apple script execution
// ----------------------------------------------------------------------------

var scriptsPath = __dirname + '/scripts/';

var execScript = function(scriptName, param, callback){
    if (arguments.length === 2 && typeof param === 'function'){
        // second argument is the callback
        callback = param;
        param = undefined;
    }

    // applescript lib needs a callback, but callback is not always useful
    if (!callback) callback = function(){};

    var script = scripts[scriptName];

    if (typeof script === 'string'){
        if (typeof param !== 'undefined') script = util.format(script, param);
        return applescript.execString(script, callback);
    } else if (script.file){
        return applescript.execFile(scriptsPath + script.file, callback);
    }
};

var createJSONResponseHandler = function(callback){
    if (!callback) return null;
    return function(error, result){
        if (!error){
            try {
                result = JSON.parse(result);
            } catch(e){
                return callback(e);
            }
            return callback(null, result);
        } else {
            return callback(error);
        }
    };
};

// API
// ----------------------------------------------------------------------------

// Open track

exports.open = function(uri, callback){
    return exec('open "'+uri+'"', callback);
};

exports.playTrack = function(track, callback){
    return execScript('playTrack', track, callback);
};

// Playback control

exports.play = function(callback){
    return execScript('play', callback);
};

exports.pause = function(callback){
    return execScript('pause', callback);
};

exports.playPause = function(callback){
    return execScript('playPause', callback);
};

exports.next = function(callback){
    return execScript('next', callback);
};

exports.previous = function(callback){
    return execScript('previous', callback);
};

exports.jumpTo = function(position, callback){
    return execScript('jumpTo', position, callback);
};

// Volume control

var mutedVolume = null;

exports.volumeUp = function(callback){
    mutedVolume = null;
    return execScript('volumeUp', callback);
};

exports.volumeDown = function(callback){
    mutedVolume = null;
    return execScript('volumeDown', callback);
};

exports.setVolume = function(volume, callback){
    mutedVolume = null;
    return execScript('setVolume', volume, callback);
};

exports.muteVolume = function(callback){
    return execScript('state', createJSONResponseHandler(function(err, state) {
        exports.setVolume(0, callback);
        mutedVolume = state.volume;
    }));
};

exports.unmuteVolume = function(callback){
    if (mutedVolume !== null) {
        return exports.setVolume(mutedVolume, callback);
    }
};

// State retrieval

exports.getTrack = function(callback){
    return execScript('track', createJSONResponseHandler(callback));
};

exports.getState = function(callback){
    return execScript('state', createJSONResponseHandler(callback));
};

exports.isRunning = function(callback) {
    return execScript('isRunning', function(error, response) {
        if (!error) {
            return callback(null, response === 'true' ? true : false);
        } else {
            return callback(error);
        }
    });
};

exports.getArtwork = function(callback){
    return execScript('artwork', callback);
};


text:
<?php

/**
 * Base class that represents a query for the 'editorial_lang' table.
 *
 *
 *
 * @method     Oops_Db_EditorialLangQuery orderByIdEditorial($order = Criteria::ASC) Order by the id_editorial column
 * @method     Oops_Db_EditorialLangQuery orderByIdLang($order = Criteria::ASC) Order by the id_lang column
 * @method     Oops_Db_EditorialLangQuery orderByBodyTitle($order = Criteria::ASC) Order by the body_title column
 * @method     Oops_Db_EditorialLangQuery orderByBodySubheading($order = Criteria::ASC) Order by the body_subheading column
 * @method     Oops_Db_EditorialLangQuery orderByBodyParagraph($order = Criteria::ASC) Order by the body_paragraph column
 * @method     Oops_Db_EditorialLangQuery orderByBodyLogoSubheading($order = Criteria::ASC) Order by the body_logo_subheading column
 *
 * @method     Oops_Db_EditorialLangQuery groupByIdEditorial() Group by the id_editorial column
 * @method     Oops_Db_EditorialLangQuery groupByIdLang() Group by the id_lang column
 * @method     Oops_Db_EditorialLangQuery groupByBodyTitle() Group by the body_title column
 * @method     Oops_Db_EditorialLangQuery groupByBodySubheading() Group by the body_subheading column
 * @method     Oops_Db_EditorialLangQuery groupByBodyParagraph() Group by the body_paragraph column
 * @method     Oops_Db_EditorialLangQuery groupByBodyLogoSubheading() Group by the body_logo_subheading column
 *
 * @method     Oops_Db_EditorialLangQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
 * @method     Oops_Db_EditorialLangQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
 * @method     Oops_Db_EditorialLangQuery innerJoin($relation) Adds a INNER JOIN clause to the query
 *
 * @method     Oops_Db_EditorialLang findOne(PropelPDO $con = null) Return the first Oops_Db_EditorialLang matching the query
 * @method     Oops_Db_EditorialLang findOneOrCreate(PropelPDO $con = null) Return the first Oops_Db_EditorialLang matching the query, or a new Oops_Db_EditorialLang object populated from the query conditions when no match is found
 *
 * @method     Oops_Db_EditorialLang findOneByIdEditorial(int $id_editorial) Return the first Oops_Db_EditorialLang filtered by the id_editorial column
 * @method     Oops_Db_EditorialLang findOneByIdLang(int $id_lang) Return the first Oops_Db_EditorialLang filtered by the id_lang column
 * @method     Oops_Db_EditorialLang findOneByBodyTitle(string $body_title) Return the first Oops_Db_EditorialLang filtered by the body_title column
 * @method     Oops_Db_EditorialLang findOneByBodySubheading(string $body_subheading) Return the first Oops_Db_EditorialLang filtered by the body_subheading column
 * @method     Oops_Db_EditorialLang findOneByBodyParagraph(string $body_paragraph) Return the first Oops_Db_EditorialLang filtered by the body_paragraph column
 * @method     Oops_Db_EditorialLang findOneByBodyLogoSubheading(string $body_logo_subheading) Return the first Oops_Db_EditorialLang filtered by the body_logo_subheading column
 *
 * @method     array findByIdEditorial(int $id_editorial) Return Oops_Db_EditorialLang objects filtered by the id_editorial column
 * @method     array findByIdLang(int $id_lang) Return Oops_Db_EditorialLang objects filtered by the id_lang column
 * @method     array findByBodyTitle(string $body_title) Return Oops_Db_EditorialLang objects filtered by the body_title column
 * @method     array findByBodySubheading(string $body_subheading) Return Oops_Db_EditorialLang objects filtered by the body_subheading column
 * @method     array findByBodyParagraph(string $body_paragraph) Return Oops_Db_EditorialLang objects filtered by the body_paragraph column
 * @method     array findByBodyLogoSubheading(string $body_logo_subheading) Return Oops_Db_EditorialLang objects filtered by the body_logo_subheading column
 *
 * @package    propel.generator.prestashop.om
 */
abstract class Oops_Db_Propel_EditorialLangQuery extends ModelCriteria
{

	/**
	 * Initializes internal state of Oops_Db_Propel_EditorialLangQuery object.
	 *
	 * @param     string $dbName The dabase name
	 * @param     string $modelName The phpName of a model, e.g. 'Book'
	 * @param     string $modelAlias The alias for the model in this query, e.g. 'b'
	 */
	public function __construct($dbName = 'prestashop', $modelName = 'Oops_Db_EditorialLang', $modelAlias = null)
	{
		parent::__construct($dbName, $modelName, $modelAlias);
	}

	/**
	 * Returns a new Oops_Db_EditorialLangQuery object.
	 *
	 * @param     string $modelAlias The alias of a model in the query
	 * @param     Criteria $criteria Optional Criteria to build the query from
	 *
	 * @return    Oops_Db_EditorialLangQuery
	 */
	public static function create($modelAlias = null, $criteria = null)
	{
		if ($criteria instanceof Oops_Db_EditorialLangQuery) {
			return $criteria;
		}
		$query = new Oops_Db_EditorialLangQuery();
		if (null !== $modelAlias) {
			$query->setModelAlias($modelAlias);
		}
		if ($criteria instanceof Criteria) {
			$query->mergeWith($criteria);
		}
		return $query;
	}

	/**
	 * Find object by primary key.
	 * Propel uses the instance pool to skip the database if the object exists.
	 * Go fast if the query is untouched.
	 *
	 *
	 * $obj = $c->findPk(array(12, 34), $con);
	 *
	 *
	 * @param     array[$id_editorial, $id_lang] $key Primary key to use for the query
	 * @param     PropelPDO $con an optional connection object
	 *
	 * @return    Oops_Db_EditorialLang|array|mixed the result, formatted by the current formatter
	 */
	public function findPk($key, $con = null)
	{
		if ($key === null) {
			return null;
		}
		if ((null !== ($obj = Oops_Db_EditorialLangPeer::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) {
			// the object is alredy in the instance pool
			return $obj;
		}
		if ($con === null) {
			$con = Propel::getConnection(Oops_Db_EditorialLangPeer::DATABASE_NAME, Propel::CONNECTION_READ);
		}
		$this->basePreSelect($con);
		if ($this->formatter || $this->modelAlias || $this->with || $this->select
		 || $this->selectColumns || $this->asColumns || $this->selectModifiers
		 || $this->map || $this->having || $this->joins) {
			return $this->findPkComplex($key, $con);
		} else {
			return $this->findPkSimple($key, $con);
		}
	}

	/**
	 * Find object by primary key using raw SQL to go fast.
	 * Bypass doSelect() and the object formatter by using generated code.
	 *
	 * @param     mixed $key Primary key to use for the query
	 * @param     PropelPDO $con A connection object
	 *
	 * @return    Oops_Db_EditorialLang A model object, or null if the key is not found
	 */
	protected function findPkSimple($key, $con)
	{
		$sql = 'SELECT `ID_EDITORIAL`, `ID_LANG`, `BODY_TITLE`, `BODY_SUBHEADING`, `BODY_PARAGRAPH`, `BODY_LOGO_SUBHEADING` FROM `' . _DB_PREFIX_ . 'editorial_lang` WHERE `ID_EDITORIAL` = :p0 AND `ID_LANG` = :p1';
		try {
			$stmt = $con->prepare($sql);
			$stmt->bindValue(':p0', $key[0], PDO::PARAM_INT);
			$stmt->bindValue(':p1', $key[1], PDO::PARAM_INT);
			$stmt->execute();
		} catch (Exception $e) {
			Propel::log($e->getMessage(), Propel::LOG_ERR);
			throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), $e);
		}
		$obj = null;
		if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
			$obj = new Oops_Db_EditorialLang();
			$obj->hydrate($row);
			Oops_Db_EditorialLangPeer::addInstanceToPool($obj, serialize(array((string) $row[0], (string) $row[1])));
		}
		$stmt->closeCursor();

		return $obj;
	}

	/**
	 * Find object by primary key.
	 *
	 * @param     mixed $key Primary key to use for the query
	 * @param     PropelPDO $con A connection object
	 *
	 * @return    Oops_Db_EditorialLang|array|mixed the result, formatted by the current formatter
	 */
	protected function findPkComplex($key, $con)
	{
		// As the query uses a PK condition, no limit(1) is necessary.
		$criteria = $this->isKeepQuery() ? clone $this : $this;
		$stmt = $criteria
			->filterByPrimaryKey($key)
			->doSelect($con);
		return $criteria->getFormatter()->init($criteria)->formatOne($stmt);
	}

	/**
	 * Find objects by primary key
	 *
	 * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con);
	 *
	 * @param     array $keys Primary keys to use for the query
	 * @param     PropelPDO $con an optional connection object
	 *
	 * @return    PropelObjectCollection|array|mixed the list of results, formatted by the current formatter
	 */
	public function findPks($keys, $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
		}
		$this->basePreSelect($con);
		$criteria = $this->isKeepQuery() ? clone $this : $this;
		$stmt = $criteria
			->filterByPrimaryKeys($keys)
			->doSelect($con);
		return $criteria->getFormatter()->init($criteria)->format($stmt);
	}

	/**
	 * Filter the query by primary key
	 *
	 * @param     mixed $key Primary key to use for the query
	 *
	 * @return    Oops_Db_EditorialLangQuery The current query, for fluid interface
	 */
	public function filterByPrimaryKey($key)
	{
		$this->addUsingAlias(Oops_Db_EditorialLangPeer::ID_EDITORIAL, $key[0], Criteria::EQUAL);
		$this->addUsingAlias(Oops_Db_EditorialLangPeer::ID_LANG, $key[1], Criteria::EQUAL);

		return $this;
	}

	/**
	 * Filter the query by a list of primary keys
	 *
	 * @param     array $keys The list of primary key to use for the query
	 *
	 * @return    Oops_Db_EditorialLangQuery The current query, for fluid interface
	 */
	public function filterByPrimaryKeys($keys)
	{
		if (empty($keys)) {
			return $this->add(null, '1<>1', Criteria::CUSTOM);
		}
		foreach ($keys as $key) {
			$cton0 = $this->getNewCriterion(Oops_Db_EditorialLangPeer::ID_EDITORIAL, $key[0], Criteria::EQUAL);
			$cton1 = $this->getNewCriterion(Oops_Db_EditorialLangPeer::ID_LANG, $key[1], Criteria::EQUAL);
			$cton0->addAnd($cton1);
			$this->addOr($cton0);
		}

		return $this;
	}

	/**
	 * Filter the query on the id_editorial column
	 *
	 * Example usage:
	 *
	 * $query->filterByIdEditorial(1234); // WHERE id_editorial = 1234
	 * $query->filterByIdEditorial(array(12, 34)); // WHERE id_editorial IN (12, 34)
	 * $query->filterByIdEditorial(array('min' => 12)); // WHERE id_editorial > 12
	 *
	 *
	 * @param     mixed $idEditorial The value to use as filter.
	 *              Use scalar values for equality.
	 *              Use array values for in_array() equivalent.
	 *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
	 * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
	 *
	 * @return    Oops_Db_EditorialLangQuery The current query, for fluid interface
	 */
	public function filterByIdEditorial($idEditorial = null, $comparison = null)
	{
		if (is_array($idEditorial) && null === $comparison) {
			$comparison = Criteria::IN;
		}
		return $this->addUsingAlias(Oops_Db_EditorialLangPeer::ID_EDITORIAL, $idEditorial, $comparison);
	}

	/**
	 * Filter the query on the id_lang column
	 *
	 * Example usage:
	 *
	 * $query->filterByIdLang(1234); // WHERE id_lang = 1234
	 * $query->filterByIdLang(array(12, 34)); // WHERE id_lang IN (12, 34)
	 * $query->filterByIdLang(array('min' => 12)); // WHERE id_lang > 12
	 *
	 *
	 * @param     mixed $idLang The value to use as filter.
	 *              Use scalar values for equality.
	 *              Use array values for in_array() equivalent.
	 *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
	 * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
	 *
	 * @return    Oops_Db_EditorialLangQuery The current query, for fluid interface
	 */
	public function filterByIdLang($idLang = null, $comparison = null)
	{
		if (is_array($idLang) && null === $comparison) {
			$comparison = Criteria::IN;
		}
		return $this->addUsingAlias(Oops_Db_EditorialLangPeer::ID_LANG, $idLang, $comparison);
	}

	/**
	 * Filter the query on the body_title column
	 *
	 * Example usage:
	 *
	 * $query->filterByBodyTitle('fooValue');   // WHERE body_title = 'fooValue'
	 * $query->filterByBodyTitle('%fooValue%'); // WHERE body_title LIKE '%fooValue%'
	 *
	 *
	 * @param     string $bodyTitle The value to use as filter.
	 *              Accepts wildcards (* and % trigger a LIKE)
	 * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
	 *
	 * @return    Oops_Db_EditorialLangQuery The current query, for fluid interface
	 */
	public function filterByBodyTitle($bodyTitle = null, $comparison = null)
	{
		if (null === $comparison) {
			if (is_array($bodyTitle)) {
				$comparison = Criteria::IN;
			} elseif (preg_match('/[\%\*]/', $bodyTitle)) {
				$bodyTitle = str_replace('*', '%', $bodyTitle);
				$comparison = Criteria::LIKE;
			}
		}
		return $this->addUsingAlias(Oops_Db_EditorialLangPeer::BODY_TITLE, $bodyTitle, $comparison);
	}

	/**
	 * Filter the query on the body_subheading column
	 *
	 * Example usage:
	 *
	 * $query->filterByBodySubheading('fooValue');   // WHERE body_subheading = 'fooValue'
	 * $query->filterByBodySubheading('%fooValue%'); // WHERE body_subheading LIKE '%fooValue%'
	 *
	 *
	 * @param     string $bodySubheading The value to use as filter.
	 *              Accepts wildcards (* and % trigger a LIKE)
	 * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
	 *
	 * @return    Oops_Db_EditorialLangQuery The current query, for fluid interface
	 */
	public function filterByBodySubheading($bodySubheading = null, $comparison = null)
	{
		if (null === $comparison) {
			if (is_array($bodySubheading)) {
				$comparison = Criteria::IN;
			} elseif (preg_match('/[\%\*]/', $bodySubheading)) {
				$bodySubheading = str_replace('*', '%', $bodySubheading);
				$comparison = Criteria::LIKE;
			}
		}
		return $this->addUsingAlias(Oops_Db_EditorialLangPeer::BODY_SUBHEADING, $bodySubheading, $comparison);
	}

	/**
	 * Filter the query on the body_paragraph column
	 *
	 * Example usage:
	 *
	 * $query->filterByBodyParagraph('fooValue');   // WHERE body_paragraph = 'fooValue'
	 * $query->filterByBodyParagraph('%fooValue%'); // WHERE body_paragraph LIKE '%fooValue%'
	 *
	 *
	 * @param     string $bodyParagraph The value to use as filter.
	 *              Accepts wildcards (* and % trigger a LIKE)
	 * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
	 *
	 * @return    Oops_Db_EditorialLangQuery The current query, for fluid interface
	 */
	public function filterByBodyParagraph($bodyParagraph = null, $comparison = null)
	{
		if (null === $comparison) {
			if (is_array($bodyParagraph)) {
				$comparison = Criteria::IN;
			} elseif (preg_match('/[\%\*]/', $bodyParagraph)) {
				$bodyParagraph = str_replace('*', '%', $bodyParagraph);
				$comparison = Criteria::LIKE;
			}
		}
		return $this->addUsingAlias(Oops_Db_EditorialLangPeer::BODY_PARAGRAPH, $bodyParagraph, $comparison);
	}

	/**
	 * Filter the query on the body_logo_subheading column
	 *
	 * Example usage:
	 *
	 * $query->filterByBodyLogoSubheading('fooValue');   // WHERE body_logo_subheading = 'fooValue'
	 * $query->filterByBodyLogoSubheading('%fooValue%'); // WHERE body_logo_subheading LIKE '%fooValue%'
	 *
	 *
	 * @param     string $bodyLogoSubheading The value to use as filter.
	 *              Accepts wildcards (* and % trigger a LIKE)
	 * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
	 *
	 * @return    Oops_Db_EditorialLangQuery The current query, for fluid interface
	 */
	public function filterByBodyLogoSubheading($bodyLogoSubheading = null, $comparison = null)
	{
		if (null === $comparison) {
			if (is_array($bodyLogoSubheading)) {
				$comparison = Criteria::IN;
			} elseif (preg_match('/[\%\*]/', $bodyLogoSubheading)) {
				$bodyLogoSubheading = str_replace('*', '%', $bodyLogoSubheading);
				$comparison = Criteria::LIKE;
			}
		}
		return $this->addUsingAlias(Oops_Db_EditorialLangPeer::BODY_LOGO_SUBHEADING, $bodyLogoSubheading, $comparison);
	}

	/**
	 * Exclude object from result
	 *
	 * @param     Oops_Db_EditorialLang $editorialLang Object to remove from the list of results
	 *
	 * @return    Oops_Db_EditorialLangQuery The current query, for fluid interface
	 */
	public function prune($editorialLang = null)
	{
		if ($editorialLang) {
			$this->addCond('pruneCond0', $this->getAliasedColName(Oops_Db_EditorialLangPeer::ID_EDITORIAL), $editorialLang->getIdEditorial(), Criteria::NOT_EQUAL);
			$this->addCond('pruneCond1', $this->getAliasedColName(Oops_Db_EditorialLangPeer::ID_LANG), $editorialLang->getIdLang(), Criteria::NOT_EQUAL);
			$this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR);
		}

		return $this;
	}

} // Oops_Db_Propel_EditorialLangQuery


text:
package com.fasterxml.jackson.databind.util;

import java.util.*;

import com.fasterxml.jackson.databind.BaseMapTest;

public class TestObjectBuffer
    extends BaseMapTest
{
    /**
     * First a test that treats results as plain old Object[]
     */
    public void testUntyped()
    {
        _testObjectBuffer(null);
    }

    public void testTyped()
    {
        _testObjectBuffer(Integer.class);
    }

    /*
    /**********************************************************
    /* Helper methods
    /**********************************************************
     */

    private void _testObjectBuffer(Class<?> clz)
    {
        int[] SIZES = new int[] {
            3, 19, 99, 1007, 19999, 99001
        };

        // Let's loop separately for reused instance, new instance
        for (int reuse = 0; reuse < 2; ++reuse) {
            ObjectBuffer buf = (reuse == 0) ? null : new ObjectBuffer();

            // then distinct sizes
            for (int sizeIndex = 0; sizeIndex < SIZES.length; ++sizeIndex) {
                int size = SIZES[sizeIndex];
                Random r = new Random(size);
                ObjectBuffer thisBuf = (buf == null) ? new ObjectBuffer() : buf;
                Object[] chunk = thisBuf.resetAndStart();
                int ix = 0;

                for (int i = 0; i < size; ++i) {
                    if (ix >= chunk.length) {
                        chunk = thisBuf.appendCompletedChunk(chunk);
                        ix = 0;
                    }
                    chunk[ix++] = Integer.valueOf(r.nextInt());
                }

                Object[] result;

                if (clz == null) {
                    result = thisBuf.completeAndClearBuffer(chunk, ix);
                } else {
                    result = thisBuf.completeAndClearBuffer(chunk, ix, clz);
                }
                assertEquals(size, result.length);

                r = new Random(size);
                for (int i = 0; i < size; ++i) {
                    assertEquals(r.nextInt(), ((Integer) result[i]).intValue());
                }
            }
        }
    }
}


text:
import React, { Component, PropTypes } from 'react'
import classNames from 'classnames'
import { getThemes } from '../../utils/theme'

export default class CardHeader extends Component {

  static propTypes = {
    children: PropTypes.node,
    cover: PropTypes.bool,
    className: PropTypes.string,
    theme: PropTypes.oneOf(getThemes())
  };

  static defaultProps = {
    cover: false
  };

  render () {
    const { children, cover, className, theme, ...props } = this.props
    const classes = classNames({
      'card-header': true,
      'no-border': !!cover,
      [`color-${theme}`]: theme
    }, className)
    return (
      <div className={classes} {...props}>
        {children}
      </div>
    )
  }
}


text:
using System;

namespace SiteCore
{
	/// <summary>
	/// Provides data for the <see cref="DataInstrumentationProvider.commandExecuted"/> event.
	/// </summary>
    public class CommandExecutedEventArgs : EventArgs
    {
        private DateTime startTime;

		/// <summary>
		/// Gets the time the command started its execution.
		/// </summary>
        public DateTime StartTime
        {
            get { return startTime; }
        }

		/// <summary>
		/// Initializes a new instance of the <see cref="CommandExecutedEventArgs"/> class.
		/// </summary>
		/// <param name="startTime">The time the command started its execution.</param>
        public CommandExecutedEventArgs(DateTime startTime)
        {
            this.startTime = startTime;
        }
    }
}