text:
require './lib/expresspigeon-ruby'
require 'pigeon_helper'

describe 'transactional messages integration test' do

  include PigeonSpecHelper

  #def test_sending_message_and_report_without_params(self):
  #    res = self.api.messages.send_message(template_id=-1, to="", reply_to="", from="", subject="")
  #    self.assertEqual(res.code, 400)
  #    self.assertEqual(res.status, "error")
  #    self.assertEqual(res.message, "Required fields: template_id, reply_to, from, to, and subject")
  #
  #def test_sending_message_and_report_with_wrong_email_in_to(self):
  #    res = self.api.messages.send_message(template_id=-1, to="e", reply_to="a@a.a", from="me", subject="Hi")
  #    self.assertEqual(res.code, 400)
  #    self.assertEqual(res.status, "error")
  #    self.assertEqual(res.message, "Email in the 'to' field is not valid")
  #
  #def test_sending_message_and_report_with_wrong_email_in_reply_to(self):
  #    res = self.api.messages.send_message(template_id=-1, to="e@e.e", reply_to="a", from="me", subject="Hi")
  #    self.assertEqual(res.code, 400)
  #    self.assertEqual(res.status, "error")
  #    self.assertEqual(res.message, "Email in the 'reply_to' field is not valid")
  #
  #def test_sending_message_and_report_with_wrong_template_id(self):
  #    res = self.api.messages.send_message(template_id=-1, to="e@e.e", reply_to="a@a.a", from="me", subject="Hi")
  #    self.assertEqual(res.code, 400)
  #    self.assertEqual(res.status, "error")
  #    self.assertEqual(res.message, "template=-1 not found")

  #TODO: complete the spec
  it 'sends a single transactional message' do
    message_response = ExpressPigeon::API.messages.send_message 115, ENV['TARGET_EMAIL'], ENV['TARGET_EMAIL'], "Team ExpressPigeon", "Hi there!",
                                                              :first_name => "Igor"
    validate_response message_response, 200, 'success', /email queued/
    report = ExpressPigeon::API.messages.report(message_response.id)
    report.id.should eq message_response.id
  end

  #
  #def test_reports_with_bad_dates(self):
  #    res = self.api.messages.reports("abc", "")
  #    self.assertEquals(res.code, 400)
  #    self.assertEquals(res.status, "error")
  #    self.assertEquals(res.message, "invalid 'start_date' or 'end_date'")
  #
  #def test_reports_with_start_date_only(self):
  #    res = self.api.messages.reports("2013-03-16T11:22:23.210+0000", "")
  #    self.assertEquals(res.code, 400)
  #    self.assertEquals(res.status, "error")
  #    self.assertEquals(res.message, "'start_date' and 'end_date' should be provided together")
  #
  #def test_reports_with_end_date_only(self):
  #    res = self.api.messages.reports("", "2013-03-16T11:22:23.210+0000")
  #    self.assertEquals(res.code, 400)
  #    self.assertEquals(res.status, "error")
  #    self.assertEquals(res.message, "'start_date' and 'end_date' should be provided together")
  #
  #def test_sending_multiple_messages_and_get_reports(self):
  #    message_response = self.api.messages.send_message(template_id=self.template_id,
  #                                                      to=os.environ['EXPRESSPIGEON_API_USER'],
  #                                                      reply_to="a@a.a", from="me", subject="Hi",
  #                                                      merge_fields={"first_name": "Gleb"})
  #    self.assertEqual(message_response.code, 200)
  #    self.assertEqual(message_response.status, "success")
  #    self.assertEqual(message_response.message, "email queued")
  #    self.assertTrue(message_response.id is not None and message_response.id != "")
  #
  #    message_response_2 = self.api.messages.send_message(template_id=self.template_id,
  #                                                        to=os.environ['EXPRESSPIGEON_API_USER'],
  #                                                        reply_to="a@a.a", from="me", subject="Hi 2",
  #                                                        merge_fields={"first_name": "Gleb"})
  #    self.assertEqual(message_response_2.code, 200)
  #    self.assertEqual(message_response_2.status, "success")
  #    self.assertEqual(message_response_2.message, "email queued")
  #    self.assertTrue(message_response_2.id is not None and message_response.id != "")
  #
  #    report = self.__get_report_by_id__(message_response.id)
  #
  #    self.assertEquals(report.id, message_response.id)
  #    self.assertEquals(report.email, os.environ['EXPRESSPIGEON_API_USER'])
  #    self.assertTrue(report.in_transit is not None)
  #
  #    report2 = self.__get_report_by_id__(message_response_2.id)
  #
  #    self.assertEquals(report2.id, message_response_2.id)
  #    self.assertEquals(report2.email, os.environ['EXPRESSPIGEON_API_USER'])
  #    self.assertTrue(report2.in_transit is not None)
  #
  it 'should send multiple messages and get reports for today' do

    start = Time.now.utc - 60 # one minute ago

    message_response = ExpressPigeon::API.messages.send_message 4905, ENV['TARGET_EMAIL'], ENV['TARGET_EMAIL'],
                                                              'Team EP', "Hi, there!", :first_name => "Bob"

    validate_response message_response, 200, 'success', /email queued/
    message_response.id should_not be_nil

    message_response2 = ExpressPigeon::API.messages.send_message 4905, ENV['TARGET_EMAIL'], ENV['TARGET_EMAIL'],
                                                               'Team EP', "Hi, there!", :first_name => "Bob"
    validate_response message_response2, 200, 'success', /email queued/
    message_response2.id should_not be_nil

    finish = start + 120 # two minutes after start
    reports = ExpressPigeon::API.messages.reports (message_response.id - 1), start, finish

    reports.size.should eq 2
    reports[0]['id'].should eq message_response.id
    reports[1]['id'].should eq message_response2.id

    reports[0]['email'].should eq ENV['TARGET_EMAIL']
    reports[1]['email'].should eq ENV['TARGET_EMAIL']
  end

  #
  #def __get_report_by_id__(self, message_id, start_date=None, end_date=None):
  #    reports = self.api.messages.reports() if start_date is None and end_date is None else \
  #        self.api.messages.reports(start_date, end_date)
  #    report = [r for r in reports if r.id == message_id]
  #    self.assertEquals(len(report), 1)
  #    return report[0]

  it 'should prepare payload hash' do

     payload = ExpressPigeon::API.messages.prepare_payload(123, #template_id
                                                         'john@doe.com',
                                                         'jane@doe.com',
                                                         'Jane Doe',
                                                         'Hello, Dolly!',
                                                         {eye_color: 'blue', body_shape:'pear'},
                                                         false, true, false,
                                                         %w(spec/resources/attachment1.txt spec/resources/attachment2.txt), {}, nil, nil)

     payload[:multipart].should eq true
     payload[:template_id].should eq 123
     payload[:to].should eq 'john@doe.com'
     payload[:reply_to].should eq 'jane@doe.com'
     payload[:from].should eq 'Jane Doe'
     payload[:subject].should eq 'Hello, Dolly!'
     payload[:template_id].should eq 123
     payload[:view_online].should eq false
     payload[:click_tracking].should eq true
     payload[:suppress_address].should eq false
     payload['attachment1.txt'].class.should eq File

     payload[:merge_fields].class.should eq String
     merge_fields = JSON.parse payload[:merge_fields]
     merge_fields['eye_color'].should eq "blue"
     merge_fields['body_shape'].should eq "pear"

     File.basename(payload['attachment1.txt']).should eq 'attachment1.txt'
     File.basename(payload['attachment2.txt']).should eq 'attachment2.txt'
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.concrete5.org/doctrine-xml/0.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.concrete5.org/doctrine-xml/0.5 http://concrete5.github.io/doctrine-xml/doctrine-xml-0.5.xsd">
    <table name="btCustomizableTwitterFeed">
        <field name="bID" type="integer">
            <unsigned/>
            <key/>
        </field>
        <field name="userName" type="string" size="255" />
        <field name="feedTitle" type="string" size="255" />
        <field name="feedTitleColor" type="string" size="255" />
        <field name="feedTitleTextSize" type="integer">
            <unsigned/>
        </field>
        <field name="maxTweets" type="integer">
            <unsigned/>
        </field>
        <field name="showUser" type="integer">
            <unsigned/>
        </field>
        <field name="showTime" type="integer">
            <unsigned/>
        </field>
        <field name="showInteraction" type="integer">
            <unsigned/>
        </field>
        <field name="showRetweet" type="integer">
            <unsigned/>
        </field>
        <field name="showImages" type="integer">
            <unsigned/>
        </field>
        <field name="linksInNewWindow" type="integer">
            <unsigned/>
        </field>
        <field name="maxWidth" type="integer">
            <unsigned/>
        </field>
        <field name="feedPadding" type="integer">
            <unsigned/>
        </field>
        <field name="feedBackgroundColor" type="string" size="255" />
        <field name="feedTheme" type="string" size="255" />
        <field name="tweetDivider" type="integer" />
        <field name="tweetDividerColor" type="string" size="255" />
        <field name="nameTextColor" type="string" size="255" />
        <field name="nameTextSize" type="integer">
            <unsigned/>
        </field>
        <field name="atNameTextSize" type="integer">
            <unsigned/>
        </field>
        <field name="feedTextColor" type="string" size="255" />
        <field name="feedTextSize" type="integer">
            <unsigned/>
        </field>
        <field name="feedLinkColor" type="string" size="255" />
        <field name="feedLinkHoverColor" type="string" size="255" />
        <field name="timePostedColor" type="string" size="255" />
        <field name="timePostedTextSize" type="integer">
            <unsigned/>
        </field>
        <field name="interactTextSize" type="integer">
            <unsigned/>
        </field>
    </table>
</schema>

redpajama_set_name: RedPajamaGithub


text:
import crypto, { isCryptoKey } from './webcrypto.js';
import { checkSigCryptoKey } from '../lib/crypto_key.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
export default function getCryptoKey(alg, key, usage) {
    if (isCryptoKey(key)) {
        checkSigCryptoKey(key, alg, usage);
        return key;
    }
    if (key instanceof Uint8Array) {
        if (!alg.startsWith('HS')) {
            throw new TypeError(invalidKeyInput(key, ...types));
        }
        return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.substr(-3)}`, name: 'HMAC' }, false, [usage]);
    }
    throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
}


text:
import { subMinutes } from 'date-fns/fp'
export default subMinutes


text:
package com.cleveroad.wallpaper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.larswerkman.holocolorpicker.ColorPicker;
import com.larswerkman.holocolorpicker.SVBar;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Color picker
 */
public class ColorPickerDialogFragment extends DialogFragment {

    public static final String KEY_INDEX = "INDEX";
    public static final String KEY_COLOR = "COLOR";
    @Bind(R.id.picker)
    ColorPicker colorPicker;
    @Bind(R.id.svbar)
    SVBar svBar;
    @Bind(R.id.btn_save)
    Button btnSave;

    public static ColorPickerDialogFragment instance(int index, @ColorInt int color) {
        Bundle args = new Bundle();
        args.putInt(KEY_COLOR, color);
        args.putInt(KEY_INDEX, index);
        ColorPickerDialogFragment fragment = new ColorPickerDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_color_picker, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        colorPicker.addSVBar(svBar);
        colorPicker.setColor(getArguments().getInt(KEY_COLOR));
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent data = new Intent();
                data.putExtra(KEY_INDEX, getArguments().getInt(KEY_INDEX));
                data.putExtra(KEY_COLOR, colorPicker.getColor());
                getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, data);
                dismiss();
            }
        });
    }
}


text:
[CmdletBinding()]
param()

# Arrange.
. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
$env:msBuildDir = 'C:\Some msbuild dir'
$msBuildPath = "%msBuildDir%"
$expectedMSBuildPath = "C:\Some msbuild dir\msbuild.exe"
$expectedLoggerPath = ([System.IO.Path]::GetFullPath("$PSScriptRoot\..\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll"))
Register-Mock Assert-VstsPath
Register-Mock Get-VstsTaskVariable { "C:\Some agent home directory" } -- -Name Agent.HomeDirectory -Require
Register-Mock Invoke-VstsTool { $global:LASTEXITCODE = 0 ; 'Some output 1', 'Some output 2' }
Register-Mock Write-VstsSetResult

# Act.
$actual = & $module Invoke-MSBuild -ProjectFile 'Some project file' -NoTimelineLogger -MSBuildPath $msBuildPath

# Assert.
Assert-WasCalled Assert-VstsPath -- -LiteralPath $expectedMSBuildPath -PathType Leaf
Assert-WasCalled Assert-VstsPath -- -LiteralPath $expectedLoggerPath -PathType Leaf
Assert-WasCalled Invoke-VstsTool -- -FileName $expectedMSBuildPath -Arguments "`"Some project file`" /nologo /nr:false /dl:CentralLogger,`"$expectedLoggerPath`";`"RootDetailId=|SolutionDir=|enableOrphanedProjectsLogs=true`"*ForwardingLogger,`"$expectedLoggerPath`"" -RequireExitCodeZero
Assert-WasCalled Write-VstsSetResult -Times 0
Assert-AreEqual -Expected @(
        'Some output 1'
        'Some output 2'
    ) -Actual $actual


text:
package de.linearbits.jhpl.test;

import java.util.Arrays;
import java.util.Iterator;

import de.linearbits.jhpl.Lattice;

/**
 * Test class
 * @author Fabian Prasser
 *
 */
public class Test11 {

    /**
     * Main
     * @param args
     */
    public static void main(String[] args) {
        test11();
    }

    /**
     * Test method
     */
    private static void test11() {

        System.out.println("");
        System.out.println("**************************");
        System.out.println("* TEST    11             *");
        System.out.println("**************************");
        System.out.println("");
        System.out.println("Testing space mappings");
        System.out.println("");

        // Elements per dimension
        String[][] elements = new String[][]{ {"A", "B", "C"},
                                              {"A", "B"},
                                              {"A", "B", "C", "D"}};

        // Create lattice with String-keys and Integer-values
        Lattice<String, Integer> lattice = new Lattice<String, Integer>(elements);

        Iterator<int[]> iter = lattice.unsafe().listAllNodes();
        while (iter.hasNext()) {
            int[] node = iter.next();
            System.out.println("Node: " + Arrays.toString(node));
            System.out.println(" - source: " + Arrays.toString(lattice.space().toSource(node)) + " / " + Arrays.toString(lattice.space().toIndex(lattice.space().toSource(node))));
            System.out.println(" - id    : " + lattice.space().toId(node) + " / " + Arrays.toString(lattice.space().toIndex(lattice.space().toId(node))));
        }
    }
}


text:
using System.Threading.Tasks;

namespace WemManagementStudio.Utilities.Wmi
{
    public sealed partial class WmiService
    {
        public static Task StartAsync(string service, string host, string user, string pass)
        {
            return new WmiService(service, host, user, pass).StartAsync();
        }

        public static Task StopAsync(string service, string host, string user, string pass)
        {
            return new WmiService(service, host, user, pass).StopAsync();
        }
    }
}


text:
layout: global
title: Running Spark on EC2
redirect: https://github.com/amplab/spark-ec2#readme
---

This document has been superseded and replaced by documentation at https://github.com/amplab/spark-ec2#readme


text:
namespace mdsdinput
{
    constexpr uint32_t MAX_MESSAGE_SIZE = 64 * 1024;

    class eof_exception : public std::runtime_error {
    public:
        eof_exception()
            : std::runtime_error("Connection Closed")
        {}
    };

    class msg_too_large_error : public std::runtime_error {
    public:
        explicit msg_too_large_error(const std::string& msg)
            : std::runtime_error(msg)
        {}
    };

    class FDIO
    {
    public:
        explicit FDIO(int fd)
            : _fd(fd)
        {}

        // Read overload(s) for arithmetic types
        template <typename T>
        typename boost::enable_if<boost::is_arithmetic<T> >::type
        Read(T& value)
        {
            Read(reinterpret_cast<void*>(&value), sizeof(value));
        }

        // Write overload(s) for arithmetic types
        template <typename T>
        typename boost::enable_if<boost::is_arithmetic<T> >::type
        Write(T value)
        {
            Write(reinterpret_cast<const void*>(&value), sizeof(value));
        }

        // Read into a memory blob
        void Read(bond::blob& blob, uint32_t size);

        // Write a memory blob
        void Write(const bond::blob& blob);

        // Read into a memory buffer
        void Read(void *buffer, uint32_t size);

        // Write a memory buffer
        void Write(const void *buffer, uint32_t size);
    protected:
        int _fd;
    };

    extern template void FDIO::Read(bool&);
    extern template void FDIO::Read(int32_t&);
    extern template void FDIO::Read(int64_t&);
    extern template void FDIO::Read(double&);

    extern template void FDIO::Write(bool);
    extern template void FDIO::Write(int32_t);
    extern template void FDIO::Write(int64_t);
    extern template void FDIO::Write(double);

    template<typename IO>
    class MessageIO
    {
    public:
        MessageIO(IO& io)
            : _io(io)
        {}

        void ReadMessage(Message& msg)
        {
            uint32_t size = 0;
            _io.Read(size);
            if (size > MAX_MESSAGE_SIZE)
            {
                throw msg_too_large_error("");
            }
            bond::blob data;
            _io.Read(data, size);
            bond::SimpleBinaryReader<bond::InputBuffer> input(data);
            bond::Deserialize(input, msg);
        }

        void WriteMessage(const Message& msg)
        {
            bond::OutputBuffer obuf;
            bond::SimpleBinaryWriter<bond::OutputBuffer> output(obuf);
            bond::Serialize(msg, output);
            bond::blob data = obuf.GetBuffer();
            uint32_t size = data.size();
            _io.Write(size);
            _io.Write(data);
        }

        void ReadAck(Ack& ack)
        {
            _io.Read(ack.msgId);
            uint32_t code = 0;
            _io.Read(code);
            ack.code = static_cast<mdsdinput::ResponseCode>(code);
        }

        void WriteAck(const Ack& ack)
        {
            _io.Write(ack.msgId);
            _io.Write(static_cast<uint32_t>(ack.code));
        }

    protected:
        IO _io;
    };

    extern template class MessageIO<FDIO>;
}


text:
package com.arpnetworking.metrics.yammer;

import com.arpnetworking.metrics.Metrics;
import com.arpnetworking.metrics.MetricsFactory;
import com.arpnetworking.metrics.impl.FileSink;
import com.arpnetworking.metrics.impl.TsdMetricsFactory;
import com.yammer.metrics.core.Clock;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.Metric;
import com.yammer.metrics.core.MetricName;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

import java.io.File;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;

/**
 * The replacement class for the MetricsRegistry.  In the case of using the shaded library
 * which replaces your Yammer dependency this class will serve as the provided MetricsRegistry.
 * In the case of using the supplementary library, you should use this class instead of the
 * Yammer-provided MetricsRegistry in your code.
 *
 * @author Brandon Arp (barp at groupon dot com)
 */
@SuppressFBWarnings("NM_SAME_SIMPLE_NAME_AS_SUPERCLASS")
public class MetricsRegistry extends com.yammer.metrics.core.MetricsRegistry {

    /**
     * Public constructor.
     */
    @SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME")
    public MetricsRegistry() {
        // TODO(barp): Read the settings from a config file [#2]
        this(
                new TsdMetricsFactory.Builder()
                        .setClusterName(System.getProperty("METRICS_YAMMER_EXTRA_CLUSTER", "YammerCluster"))
                        .setServiceName(System.getProperty("METRICS_YAMMER_EXTRA_SERVICE", "YammerService"))
                        .setSinks(Collections.singletonList(
                                new FileSink.Builder()
                                        .setDirectory(
                                                new File(System.getProperty("METRICS_YAMMER_EXTRA_DIRECTORY", "/tmp")))
                                        .build()))
                        .build(),
                Clock.defaultClock());
    }

    /**
     * Public constructor.
     *
     * @param metricsFactory The metrics factory to use to create metrics.
     * @param clock    a {@link Clock} instance
     */
    public MetricsRegistry(final MetricsFactory metricsFactory, final Clock clock) {
        super(clock);
        _openMetrics.set(metricsFactory.create());
        _clock = clock;
        _closingExecutor = Executors.newSingleThreadScheduledExecutor(
                (r) -> {
                    final Thread thread = new Thread(r, "metrics-closer");
                    thread.setDaemon(true);
                    return thread;
                });
        _closingExecutor.scheduleAtFixedRate(
                new Closer(_lock, metricsFactory, _openMetrics, this),
                CLOSER_PERIOD_MILLIS,
                CLOSER_PERIOD_MILLIS,
                TimeUnit.MILLISECONDS);
    }

    /**
     * Public constructor.
     *
     * @param clock    a {@link Clock} instance
     */
    public MetricsRegistry(final Clock clock) {
        // TODO(barp): Read the settings from a config file [#2]
        this(
                new TsdMetricsFactory.Builder()
                        .setSinks(Collections.singletonList(new FileSink.Builder().build()))
                        .build(),
                clock);
    }

    @Override
    public Counter newCounter(final MetricName metricName) {
        final Counter counter = getOrCreate(metricName.getName(), _counterBuilder);
        getOrAdd(metricName, counter);
        return counter;
    }

    @Override
    public Histogram newHistogram(final MetricName metricName, final boolean biased) {
        final Histogram histogram = getOrCreate(metricName.getName(), (n) -> new Histogram(n, _lock, biased));
        getOrAdd(metricName, histogram);
        return histogram;
    }

    @Override
    public Timer newTimer(
            final MetricName metricName,
            final TimeUnit durationUnit,
            final TimeUnit rateUnit) {
        final Timer timer = getOrCreate(metricName.getName(), (n) -> new Timer(n, _lock, tickPool(), durationUnit, rateUnit, _clock));
        getOrAdd(metricName, timer);
        return timer;

    }

    @Override
    public Meter newMeter(final MetricName metricName, final String eventType, final TimeUnit unit) {
        final Meter meter = getOrCreate(metricName.getName(), (n) -> new Meter(n, _lock, tickPool(), eventType, unit, _clock));
        getOrAdd(metricName, meter);
        return meter;
    }

    @Override
    public <T> Gauge<T> newGauge(final MetricName metricName, final Gauge<T> metric) {
        _gauges.put(metricName.getName(), metric);
        getOrAdd(metricName, metric);
        return metric;
    }

    /**
     * Writes the gauges to the metric instance.
     * NOTE: This is public to allow use from the Closer when shaded.
     *
     * @param metrics the metrics instance to write the gauges to
     */
    public void writeGauges(final Metrics metrics) {
        try {
            for (final Map.Entry<String, Gauge<?>> entry : _gauges.entrySet()) {
                final Object value = entry.getValue().value();
                if (value instanceof Number) {
                    metrics.setGauge(entry.getKey(), ((Number) value).doubleValue());
                }
            }
            //CHECKSTYLE.OFF: IllegalCatch - we need to catch everything
        } catch (final Exception ex) {
            //CHECKSTYLE.ON: IllegalCatch
            System.err.println(ex);
            ex.printStackTrace();

        }
    }

    private ScheduledExecutorService tickPool() {
        return newScheduledThreadPool(2, "meter-tick");
    }

    private <T extends Metric> T getOrCreate(final String name, final Function<String, T> builder) {
        @SuppressWarnings("unchecked")
        final T metric = (T) _metrics.computeIfAbsent(name, builder);
        return metric;
    }

    private final ScheduledExecutorService _closingExecutor;
    private final ConcurrentMap<String, Metric> _metrics = new ConcurrentHashMap<>();
    private final AtomicReference<Metrics> _openMetrics = new AtomicReference<>();
    private final SafeRefLock<Metrics> _lock = new SafeRefLock<>(_openMetrics, new ReentrantReadWriteLock(false));
    private final ConcurrentMap<String, Gauge<?>> _gauges = new ConcurrentHashMap<>();
    private final Clock _clock;

    // These are Functions instead of Suppliers so that we don't have to close over them in the getOrCreate function
    private final Function<String, Counter> _counterBuilder = (n) -> new Counter(n, _lock);

    private static final int CLOSER_PERIOD_MILLIS = 500;

    /**
     * Closes a metric instance in a MetricsRegistry.  Public to allow cross-package use after shading.
     *
     * @author Brandon Arp (barp at groupon dot com)
     */
    public static class Closer implements Runnable {
        /**
         * Public constructor.
         *
         * @param lock lock to acquire
         * @param factory the metrics factory
         * @param metricsRef atomic reference to the open metrics instance
         * @param registry the registry to operate on
         */
        public Closer(
                final SafeRefLock<Metrics> lock,
                final MetricsFactory factory,
                final AtomicReference<Metrics> metricsRef,
                final MetricsRegistry registry) {
            _lock = lock;
            _factory = factory;
            _metricsRef = metricsRef;
            _registry = registry;
        }

        @Override
        public void run() {
            final Metrics metrics = _metricsRef.get();
            _lock.writeLocked(ignored -> _metricsRef.set(_factory.create()));
            _registry.writeGauges(metrics);
            metrics.close();
        }

        private final SafeRefLock<Metrics> _lock;
        private final MetricsFactory _factory;
        private final AtomicReference<Metrics> _metricsRef;
        private final MetricsRegistry _registry;
    }
}


text:
angular.module('standardData', ['ngResource', 'standardControls', 'standardAnimation'])
    .factory('MongoMetadata', ['$resource', function ($resource) {
        return $resource("api/mongo-metadata/:instanceName/:collectionName", {
                instanceName: '@instanceName',
                collectionName: '@collectionName'
            },
            {
                'getInstances': {method: 'GET', isArray: true},
                'getInstance': {method: 'GET'},
                'getCollection': {method: 'GET'}
            }
        );
    }])
    .factory('ChartConfiguration', function () {
        var chartSpecifications = {
            'scatter': {
                dynamicAttributes: ['x', 'y'],
                fixedAttributes: false,
                fixedRangeAttributes: [{name: 'x'}],
                equation: false
            },
            'line': {
                dynamicAttributes: false,
                fixedAttributes: ['m', 'b'],
                fixedRangeAttributes: [{name: 'x'}],
                equation: function (m, b, x) {
                    return m * x + b;
                }
            },
            'bar': {
                dynamicAttributes: ['x', 'y'],
                fixedAttributes: false,
                fixedRangeAttributes: [{name: 'x'}],
                equation: false
            },
            'pie': {},
            'funnel': {},
            'area': {},
            'ohlc': {},
            'candlestick': {}
        };

        function ChartConfiguration(instanceName, collectionName) {
            this.instanceName = instanceName;
            this.collectionName = collectionName;
            this.chartName = this.generateChartName();
            this.chartType = 'scatter';
            this.attributes = {x: null, y: null}; //TODO: MAKE THIS SHIT MORE DYNAMIC (pull from chartspecification
            this.attributeMappings = null;
            this.staticData = null;
            this.flags = {
                supportsMultiple: false
            }
        }

        ChartConfiguration.prototype.generateChartName = function () {
            return Math.random().toString(36).substr(2, 5);
        };
        ChartConfiguration.prototype.getChartTypes = function () {
            return Object.keys(chartSpecifications);
        };
        ChartConfiguration.prototype.getChartSpecifications = function (chartType) {
            return chartSpecifications[chartType];
        };
        ChartConfiguration.prototype.addAttribute = function (name, metadata) {
            if (!this.attributeMappings) {
                this.attributeMappings = {};
            }
            this.attributeMappings[name] = metadata;
            for (var attributeName in this.attributes) {
                if (!this.attributes[attributeName]) {
                    this.attributes[attributeName] = name;
                    return;
                }
            }
        };
        return ChartConfiguration;
    })
    .factory('ChartMetadata', ['ChartConfiguration', function (ChartConfiguration) {
        var _chart = null,
            processSchemaElement = function (element) {
                for (var property in element) {
                    var exists = _chart.schema[property],
                        schemaElement = exists ? angular.copy(_chart.schema[property]) : {values: [], types: []},
                        value = element[property],
                        type = _chart.getSelectedType(value);
                    schemaElement.values.push(value);
                    if (schemaElement.types.indexOf(type) == -1) {
                        schemaElement.types.push(type);
                    }
                    _chart.schema[property] = schemaElement;
                }
            };

        function ChartMetadata() {
            this.instances = null;
            this.instanceName = null;
            this.instanceMetadata = null;
            this.collectionName = null;
            this.collectionMetadata = null;
            this.schema = null;
            this.activeConfig = null;
            this.configs = [];
            _chart = this;
        }

        ChartMetadata.prototype.getAvailableTypes = function () {
            return ['string', 'datetime', 'integer', 'double', 'decimal'];
        };
        ChartMetadata.prototype.addConfig = function () {
            var config = this.createConfig();
            this.configs.push(config);
            this.setActiveConfig(config);
        };
        ChartMetadata.prototype.createConfig = function () {
            return new ChartConfiguration(this.instanceName, this.collectionName);
        };
        ChartMetadata.prototype.deleteConfig = function (config) {
            var keyToDelete = -1;
            this.configs.some(function (currentConfig, i) {
                if (currentConfig === config) {
                    keyToDelete = i;
                    return true;
                }
                return false;
            });
            if (keyToDelete != -1) {
                this.configs.splice(keyToDelete, 1);
            }
        };
        ChartMetadata.prototype.isActiveConfig = function (config) {
            return this.activeConfig === config;
        };
        ChartMetadata.prototype.setActiveConfig = function (config) {
            this.activeConfig = config;
        };
        ChartMetadata.prototype.getSelectedType = function (value) {
            var typeName = typeof value,
                availableTypes = this.getAvailableTypes();
            switch (typeName) {
                case 'number':
                    if (value % 1 === 0) {
                        return availableTypes[1];
                    }
                    return availableTypes[2];
                case 'string':
                default:
                    return availableTypes[0];
            }
        };
        ChartMetadata.prototype.reset = function (options) {
            options = angular.extend({}, {
                instanceName: true,
                instanceMetadata: true,
                collectionName: true,
                collectionMetadata: true,
                schema: true
            }, options);
            for (var prop in options) {
                if (options.hasOwnProperty(prop) && options[prop] && this.hasOwnProperty(prop)) {
                    this[prop] = null;
                }
            }
        };
        ChartMetadata.prototype.extractSchema = function () {
            this.reset({
                instanceName: false,
                instanceMetadata: false,
                collectionName: false,
                collectionMetadata: false,
                schema: false
            });
            this.schema = {};
            this.collectionMetadata.sample.forEach(processSchemaElement);
        };
        return ChartMetadata;
    }])
    .directive('standardData', function () {
        return {
            restrict: 'E',
            scope: {
                instanceName: '@',
                instanceMetadata: '@',
                collectionName: '@',
                collectionMetadata: '@'
            },
            templateUrl: 'templates/standard-data.html',
            controller: ['$scope', 'MongoMetadata', 'ChartConfiguration', 'ChartMetadata', function ($scope, MongoMetadata, ChartConfiguration, ChartMetadata) { // standard-data
                $scope.configs = [];
                $scope.chart = new ChartMetadata();
                $scope.activeConfig = null;

                $scope.getInstances = function () {
                    MongoMetadata.getInstances(function (instances) {
                        $scope.chart.reset();
                        $scope.chart.instances = instances;
                    });
                };
                $scope.drillInstance = function (instanceName) {
                    $scope.chart.reset({instanceName: false});
                    $scope.chart.instanceName = instanceName;
                    MongoMetadata.getInstance({instanceName: instanceName}, function (instanceMetadata) {
                        $scope.chart.instanceMetadata = instanceMetadata;
                    });
                };
                $scope.drillCollection = function (collectionName) {
                    $scope.chart.reset({instanceName: false, instanceMetadata: false, collectionName: false});
                    $scope.chart.collectionName = collectionName;
                    MongoMetadata.getCollection({
                        instanceName: $scope.chart.instanceName,
                        collectionName: collectionName
                    }, function (collectionMetadata) {
                        $scope.chart.collectionMetadata = collectionMetadata;
                        $scope.chart.extractSchema();
                    });
                };

            }],
            link: function (scope) {
                scope.getInstances();
            }
        }
    })
    .directive('standardDataConfig', function () {
        return {
            restrict: 'E',
            scope: {
                chart: '=',
                config: '=',
                preview: '@'
            },
            templateUrl: 'templates/standard-data-config.html',
            require: '^standardData',
            controller: ['$scope', function ($scope) {
                $scope.preview = false;
                $scope.togglePreview = function () {
                    $scope.preview = !$scope.preview;
                }
            }],
            link: function (scope, element, attrs, standardDataCtrl) {
            }
        };
    });


text:
module DeliveryTruck
  module Helpers
    module Lint
      extend self

      # Based on the properties in the Delivery Config, create the tags string
      # that will be passed into the foodcritic command.
      #
      # @param node [Chef::Node] Chef Node object
      # @return [String]
      def foodcritic_tags(node)
        begin
          config = node['delivery']['config']['delivery-truck']['lint']['foodcritic']
          case
          when config['only_rules'] && !config['only_rules'].empty?
            "-t " + config['only_rules'].join(" -t ")
          when config['ignore_rules'] && !config['ignore_rules'].empty?
            "-t ~" + config['ignore_rules'].join(" -t ~")
          else
            ""
          end
        rescue
          ""
        end
      end
    end
  end

  module DSL

    # Return the applicable tags for foodcritic runs
    def foodcritic_tags
      DeliveryTruck::Helpers::Lint.foodcritic_tags(node)
    end
  end
end


text:
/**
 * Spring Framework configuration files.
 */
package com.josedab.eventmanager.config;


text:
import * as React from 'react';
import styled, {createGlobalStyle} from 'styled-components';

import Header from '/component/partial/Header';
import Footer from '/component/partial/Footer';
import Template from '/component/amp/Template';
import Loader from '/component/base/Loader';

import Container from '/component/base/Container';
import Button from '/component/base/Button';
import Icon from '/component/base/Icon';

import SeatPickerSidebar from '/component/sidebar/SeatPickerSidebar';
import LocationPickerSidebar from '/component/sidebar/LocationPickerSidebar';

import handleAmpBindClassName from '/util/handleAmpBindClassName';
import {below, above} from '/util/css';

const City = styled.div`
  color: #000;
  font-size: 80px;
  font-weight: 500;
  line-height: 1.5;
  display: flex;
  align-items: baseline;
  ${below.phone`
    font-size: 40px;
  `}
`;

const Details = styled.div`
  display: none;
`;

const CityButton = styled((props) => <button {...props} />)`
  display: flex;
  align-items: baseline;
  ${Icon} {
    opacity: 0;
    position: relative;
    bottom: -10px;
  }
  &:hover {
    cursor: pointer;
    ${City} {
      color: #4c2f9b;
    }
    ${Icon} {
      opacity: 1;
    }
  }
  &:active,
  &:focus {
    outline: none;
    border: none;
    border-color: transparent;
  }
`;

class AutoSuggest extends React.Component {
  render() {
    return (

        <amp-state
          id="currentLocationsList"
          src="/api/cities.json"
          data-amp-bind-src={`query ?
            "/api/cities.json?query=" + query :
            "/api/cities.json"`}
        />
        <amp-list
          layout="fixed-height"
          height="500"
          src="/api/cities.json"
          data-amp-bind-src={`query ?
            "/api/cities.json?query=" + query :
            "/api/cities.json"`}
          id="autosuggest-list"
          noloading=""
        >

            <Loader />

Failed to load data.

          <Template>
            <CityButton
              on={`
              tap:
                AMP.setState({
                  ticketCount: 0,
                  currentLocationIndex: {{index}},
                  currentLocation: "{{id}}",
                  currentShow: "{{shows.0.id}}"
                }),
                ${SeatPickerSidebar.id}.open
              `}
            >
              <City>
                <Template.Token id="city" />{' '}
                <Icon name="arrow-top-right" size="1.2em" />
              </City>

                <Template.Token id="administrative" />{' '}
                <Template.Token id="country" />

            </CityButton>
          </Template>
        </amp-list>

    );
  }
}

const CalloutText = styled.div`
  color: #4c2f9b;
  font-family: Limelight;
  font-size: 110px;
  line-height: 110px;
  ${below.phone`
    display: none;
  `}
`;

const CalloutTextMobile = styled.div`
  font-size: 54px;
  line-height: 1.11;
  color: #4c2f9b;
  font-family: Limelight;
  ${above.phone`
    display: none;
  `}
`;

const TourInfo = styled.div`
  margin-top: 32px;
  color: #4c2f9b;
  font-size: 24px;
  line-height: 1.458333333333333;
  ${below.phone`
    font-size: 16px;
    margin-top: 16px;
  `}
`;

const Emphasis = styled.strong`
  font-weight: bold;
`;

const CalloutButton = styled(Button)`
  margin-top: 24px;
  pointer-events: auto;
`;

const GlobalStyles = createGlobalStyle`
  body {
    background: #FDBCA8;
  }
`;

const BandContainer = styled((props) => {
  return
;
})`
  flex: auto;
  align-self: stretch;
  position: relative;
  margin: -90px -90px 0 -90px;
  ${below.bandFailure`
    margin: 0 0 0 -400px;
  `}
  ${below.phone`
    margin: -40px -40px 0 -40px;
    min-height: 100vw;
  `}
`;

const BandStaticWrapper = styled((props) =>
)`
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
`;
const BandInner = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  left: -50px;
  right: -50px;
  bottom: -50px;
  top: -50px;
  ${below.phone`
    left: -85px;
    right: -85px;
    bottom: -85px;
    top: -85px;
  `}
`;

const BandStatic = (props) => {
  return (
    <BandStaticWrapper {...props}>
      <BandInner>
        <amp-img
          src="/static/static-band.jpg"
          layout="intrinsic"
          width="2098"
          height="1664"
        />
      </BandInner>
    </BandStaticWrapper>
  );
};

class Band extends React.Component {
  render() {
    return (
      <BandContainer {...this.props}>
        <amp-3d-gltf
          layout="fill"
          width="100"
          height="100"
          alpha="true"
          antialiasing="true"
          autoRotate="true"
          enableZoom="false"
          src="https://s3.us-west-2.amazonaws.com/amp-demo-static-resources/viking-band.glb"
        >
          <BandStatic placeholder="" />
          <BandStatic fallback="" />
        </amp-3d-gltf>
      </BandContainer>
    );
  }
}

const Content = styled((props) => {
  return
;
})`
  pointer-events: none;
  z-index: 22;
  position: relative;
  ${below.phone`
    text-align: center;
  `}
`;

const MainLayout = styled.section`
  padding: 2rem 0;
  display: flex;
  flex-direction: column;
  flex: auto;
`;

const BetterContainer = styled(Container)`
  flex: auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  ${below.phone`
    margin-top: 32px;
    flex-direction: column;
  `}
`;

class LandingView extends React.Component {
  render() {
    return (
      <React.Fragment>
        <GlobalStyles />

        <MainLayout>

          <BetterContainer>
            <Content data-amp-bind-class="query ? 'magic-hidden' : ''">
              <CalloutText>
                Olga

 And The

 Kings
              </CalloutText>
              <CalloutTextMobile>
                Olga &

 The Kings
              </CalloutTextMobile>
              <TourInfo>
                <Emphasis>On Tour</Emphasis>

                All over the World

                Oct. 20 - May 24
              </TourInfo>

              <CalloutButton
                on={`tap:AMP.setState({}),${LocationPickerSidebar.id}.open`}
              >
                Get Tickets Now
              </CalloutButton>
            </Content>

            <Band data-amp-bind-class="query ? 'magic-hidden' : ''" />
          </BetterContainer>

        </MainLayout>

          <AutoSuggest />

      </React.Fragment>
    );
  }
}

export default LandingView;


text:
package poi.ss.examples;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * A business plan demo
 * Usage:
 *  BusinessPlan -xls|xlsx
 *
 * @author Yegor Kozlov
 */
public class BusinessPlan {

    private static SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM");

    private static final String[] titles = {
            "ID", "Project Name", "Owner", "Days", "Start", "End"};

    //sample data to fill the sheet.
    private static final String[][] data = {
            {"1.0", "Marketing Research Tactical Plan", "J. Dow", "70", "9-Jul", null,
                "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"},
            null,
            {"1.1", "Scope Definition Phase", "J. Dow", "10", "9-Jul", null,
                "x", "x", null, null,  null, null, null, null, null, null, null},
            {"1.1.1", "Define research objectives", "J. Dow", "3", "9-Jul", null,
                    "x", null, null, null,  null, null, null, null, null, null, null},
            {"1.1.2", "Define research requirements", "S. Jones", "7", "10-Jul", null,
                "x", "x", null, null,  null, null, null, null, null, null, null},
            {"1.1.3", "Determine in-house resource or hire vendor", "J. Dow", "2", "15-Jul", null,
                "x", "x", null, null,  null, null, null, null, null, null, null},
            null,
            {"1.2", "Vendor Selection Phase", "J. Dow", "19", "19-Jul", null,
                null, "x", "x", "x",  "x", null, null, null, null, null, null},
            {"1.2.1", "Define vendor selection criteria", "J. Dow", "3", "19-Jul", null,
                null, "x", null, null,  null, null, null, null, null, null, null},
            {"1.2.2", "Develop vendor selection questionnaire", "S. Jones, T. Wates", "2", "22-Jul", null,
                null, "x", "x", null,  null, null, null, null, null, null, null},
            {"1.2.3", "Develop Statement of Work", "S. Jones", "4", "26-Jul", null,
                null, null, "x", "x",  null, null, null, null, null, null, null},
            {"1.2.4", "Evaluate proposal", "J. Dow, S. Jones", "4", "2-Aug", null,
                null, null, null, "x",  "x", null, null, null, null, null, null},
            {"1.2.5", "Select vendor", "J. Dow", "1", "6-Aug", null,
                null, null, null, null,  "x", null, null, null, null, null, null},
            null,
            {"1.3", "Research Phase", "G. Lee", "47", "9-Aug", null,
                null, null, null, null,  "x", "x", "x", "x", "x", "x", "x"},
            {"1.3.1", "Develop market research information needs questionnaire", "G. Lee", "2", "9-Aug", null,
                null, null, null, null,  "x", null, null, null, null, null, null},
            {"1.3.2", "Interview marketing group for market research needs", "G. Lee", "2", "11-Aug", null,
                null, null, null, null,  "x", "x", null, null, null, null, null},
            {"1.3.3", "Document information needs", "G. Lee, S. Jones", "1", "13-Aug", null,
                null, null, null, null,  null, "x", null, null, null, null, null},
    };

    public static void main(String[] args) throws Exception {
        Workbook wb;

        if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook();
        else wb = new XSSFWorkbook();

        Map<String, CellStyle> styles = createStyles(wb);

        Sheet sheet = wb.createSheet("Business Plan");

        //turn off gridlines
        sheet.setDisplayGridlines(false);
        sheet.setPrintGridlines(false);
        sheet.setFitToPage(true);
        sheet.setHorizontallyCenter(true);
        PrintSetup printSetup = sheet.getPrintSetup();
        printSetup.setLandscape(true);

        //the following three statements are required only for HSSF
        sheet.setAutobreaks(true);
        printSetup.setFitHeight((short)1);
        printSetup.setFitWidth((short)1);

        //the header row: centered text in 48pt font
        Row headerRow = sheet.createRow(0);
        headerRow.setHeightInPoints(12.75f);
        for (int i = 0; i < titles.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(styles.get("header"));
        }
        //columns for 11 weeks starting from 9-Jul
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);

        calendar.setTime(fmt.parse("9-Jul"));
        calendar.set(Calendar.YEAR, year);
        for (int i = 0; i < 11; i++) {
            Cell cell = headerRow.createCell(titles.length + i);
            cell.setCellValue(calendar);
            cell.setCellStyle(styles.get("header_date"));
            calendar.roll(Calendar.WEEK_OF_YEAR, true);
        }
        //freeze the first row
        sheet.createFreezePane(0, 1);

        Row row;
        Cell cell;
        int rownum = 1;
        for (int i = 0; i < data.length; i++, rownum++) {
            row = sheet.createRow(rownum);
            if(data[i] == null) continue;

            for (int j = 0; j < data[i].length; j++) {
                cell = row.createCell(j);
                String styleName;
                boolean isHeader = i == 0 || data[i-1] == null;
                switch(j){
                    case 0:
                        if(isHeader) {
                            styleName = "cell_b";
                            cell.setCellValue(Double.parseDouble(data[i][j]));
                        } else {
                            styleName = "cell_normal";
                            cell.setCellValue(data[i][j]);
                        }
                        break;
                    case 1:
                        if(isHeader) {
                            styleName = i == 0 ? "cell_h" : "cell_bb";
                        } else {
                            styleName = "cell_indented";
                        }
                        cell.setCellValue(data[i][j]);
                        break;
                    case 2:
                        styleName = isHeader ? "cell_b" : "cell_normal";
                        cell.setCellValue(data[i][j]);
                        break;
                    case 3:
                        styleName = isHeader ? "cell_b_centered" : "cell_normal_centered";
                        cell.setCellValue(Integer.parseInt(data[i][j]));
                        break;
                    case 4: {
                        calendar.setTime(fmt.parse(data[i][j]));
                        calendar.set(Calendar.YEAR, year);
                        cell.setCellValue(calendar);
                        styleName = isHeader ? "cell_b_date" : "cell_normal_date";
                        break;
                    }
                    case 5: {
                        int r = rownum + 1;
                        String fmla = "IF(AND(D"+r+",E"+r+"),E"+r+"+D"+r+",\"\")";
                        cell.setCellFormula(fmla);
                        styleName = isHeader ? "cell_bg" : "cell_g";
                        break;
                    }
                    default:
                        styleName = data[i][j] != null ? "cell_blue" : "cell_normal";
                }

                cell.setCellStyle(styles.get(styleName));
            }
        }

        //group rows for each phase, row numbers are 0-based
        sheet.groupRow(4, 6);
        sheet.groupRow(9, 13);
        sheet.groupRow(16, 18);

        //set column widths, the width is measured in units of 1/256th of a character width
        sheet.setColumnWidth(0, 256*6);
        sheet.setColumnWidth(1, 256*33);
        sheet.setColumnWidth(2, 256*20);
        sheet.setZoom(3, 4);

        // Write the output to a file
        String file = "businessplan.xls";
        if(wb instanceof XSSFWorkbook) file += "x";
        FileOutputStream out = new FileOutputStream(file);
        wb.write(out);
        out.close();
    }

    /**
     * create a library of cell styles
     */
    private static Map<String, CellStyle> createStyles(Workbook wb){
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        DataFormat df = wb.createDataFormat();

        CellStyle style;
        Font headerFont = wb.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(headerFont);
        styles.put("header", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(headerFont);
        style.setDataFormat(df.getFormat("d-mmm"));
        styles.put("header_date", style);

        Font font1 = wb.createFont();
        font1.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_LEFT);
        style.setFont(font1);
        styles.put("cell_b", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFont(font1);
        styles.put("cell_b_centered", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_RIGHT);
        style.setFont(font1);
        style.setDataFormat(df.getFormat("d-mmm"));
        styles.put("cell_b_date", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_RIGHT);
        style.setFont(font1);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setDataFormat(df.getFormat("d-mmm"));
        styles.put("cell_g", style);

        Font font2 = wb.createFont();
        font2.setColor(IndexedColors.BLUE.getIndex());
        font2.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_LEFT);
        style.setFont(font2);
        styles.put("cell_bb", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_RIGHT);
        style.setFont(font1);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setDataFormat(df.getFormat("d-mmm"));
        styles.put("cell_bg", style);

        Font font3 = wb.createFont();
        font3.setFontHeightInPoints((short)14);
        font3.setColor(IndexedColors.DARK_BLUE.getIndex());
        font3.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_LEFT);
        style.setFont(font3);
        style.setWrapText(true);
        styles.put("cell_h", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_LEFT);
        style.setWrapText(true);
        styles.put("cell_normal", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setWrapText(true);
        styles.put("cell_normal_centered", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_RIGHT);
        style.setWrapText(true);
        style.setDataFormat(df.getFormat("d-mmm"));
        styles.put("cell_normal_date", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_LEFT);
        style.setIndention((short)1);
        style.setWrapText(true);
        styles.put("cell_indented", style);

        style = createBorderedStyle(wb);
        style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        styles.put("cell_blue", style);

        return styles;
    }

    private static CellStyle createBorderedStyle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        return style;
    }
}


text:
Meteor.startup(function () {

  // compile the email templates for the blog's locale
  var locale = Meteor.settings.public.blog.defaultLocale;
  SSR.compileTemplate('publishEmail',
    Assets.getText('publish_email_' + locale + '.html'));
});


text:
from __future__ import absolute_import
from __future__ import division

import logging
import math
import random
import unittest
from builtins import object
from builtins import range

from apache_beam import coders
from apache_beam.runners.worker import opcounters
from apache_beam.runners.worker import statesampler
from apache_beam.runners.worker.opcounters import OperationCounters
from apache_beam.transforms.window import GlobalWindows
from apache_beam.utils import counters
from apache_beam.utils.counters import CounterFactory

# Classes to test that we can handle a variety of objects.
# These have to be at top level so the pickler can find them.

class OldClassThatDoesNotImplementLen(object):  # pylint: disable=old-style-class

  def __init__(self):
    pass

class ObjectThatDoesNotImplementLen(object):

  def __init__(self):
    pass

class TransformIoCounterTest(unittest.TestCase):

  def test_basic_counters(self):
    counter_factory = CounterFactory()
    sampler = statesampler.StateSampler('stage1', counter_factory)
    sampler.start()

    with sampler.scoped_state('step1', 'stateA'):
      counter = opcounters.SideInputReadCounter(counter_factory, sampler,
                                                declaring_step='step1',
                                                input_index=1)
    with sampler.scoped_state('step2', 'stateB'):
      with counter:
        counter.add_bytes_read(10)

      counter.update_current_step()

    sampler.stop()
    sampler.commit_counters()

    actual_counter_names = set([c.name for c in counter_factory.get_counters()])
    expected_counter_names = set([
        # Counter names for STEP 1
        counters.CounterName('read-sideinput-msecs',
                             stage_name='stage1',
                             step_name='step1',
                             io_target=counters.side_input_id('step1', 1)),
        counters.CounterName('read-sideinput-byte-count',
                             step_name='step1',
                             io_target=counters.side_input_id('step1', 1)),

        # Counter names for STEP 2
        counters.CounterName('read-sideinput-msecs',
                             stage_name='stage1',
                             step_name='step1',
                             io_target=counters.side_input_id('step2', 1)),
        counters.CounterName('read-sideinput-byte-count',
                             step_name='step1',
                             io_target=counters.side_input_id('step2', 1)),
    ])
    self.assertTrue(actual_counter_names.issuperset(expected_counter_names))

class OperationCountersTest(unittest.TestCase):

  def verify_counters(self, opcounts, expected_elements, expected_size=None):
    self.assertEqual(expected_elements, opcounts.element_counter.value())
    if expected_size is not None:
      if math.isnan(expected_size):
        self.assertTrue(math.isnan(opcounts.mean_byte_counter.value()[0]))
      else:
        self.assertEqual(expected_size, opcounts.mean_byte_counter.value()[0])

  def test_update_int(self):
    opcounts = OperationCounters(CounterFactory(), 'some-name',
                                 coders.PickleCoder(), 0)
    self.verify_counters(opcounts, 0)
    opcounts.update_from(GlobalWindows.windowed_value(1))
    opcounts.update_collect()
    self.verify_counters(opcounts, 1)

  def test_update_str(self):
    coder = coders.PickleCoder()
    opcounts = OperationCounters(CounterFactory(), 'some-name',
                                 coder, 0)
    self.verify_counters(opcounts, 0, float('nan'))
    value = GlobalWindows.windowed_value('abcde')
    opcounts.update_from(value)
    opcounts.update_collect()
    estimated_size = coder.estimate_size(value)
    self.verify_counters(opcounts, 1, estimated_size)

  def test_update_old_object(self):
    coder = coders.PickleCoder()
    opcounts = OperationCounters(CounterFactory(), 'some-name',
                                 coder, 0)
    self.verify_counters(opcounts, 0, float('nan'))
    obj = OldClassThatDoesNotImplementLen()
    value = GlobalWindows.windowed_value(obj)
    opcounts.update_from(value)
    opcounts.update_collect()
    estimated_size = coder.estimate_size(value)
    self.verify_counters(opcounts, 1, estimated_size)

  def test_update_new_object(self):
    coder = coders.PickleCoder()
    opcounts = OperationCounters(CounterFactory(), 'some-name',
                                 coder, 0)
    self.verify_counters(opcounts, 0, float('nan'))

    obj = ObjectThatDoesNotImplementLen()
    value = GlobalWindows.windowed_value(obj)
    opcounts.update_from(value)
    opcounts.update_collect()
    estimated_size = coder.estimate_size(value)
    self.verify_counters(opcounts, 1, estimated_size)

  def test_update_multiple(self):
    coder = coders.PickleCoder()
    total_size = 0
    opcounts = OperationCounters(CounterFactory(), 'some-name',
                                 coder, 0)
    self.verify_counters(opcounts, 0, float('nan'))
    value = GlobalWindows.windowed_value('abcde')
    opcounts.update_from(value)
    opcounts.update_collect()
    total_size += coder.estimate_size(value)
    value = GlobalWindows.windowed_value('defghij')
    opcounts.update_from(value)
    opcounts.update_collect()
    total_size += coder.estimate_size(value)
    self.verify_counters(opcounts, 2, (float(total_size) / 2))
    value = GlobalWindows.windowed_value('klmnop')
    opcounts.update_from(value)
    opcounts.update_collect()
    total_size += coder.estimate_size(value)
    self.verify_counters(opcounts, 3, (float(total_size) / 3))

  def test_should_sample(self):
    # Order of magnitude more buckets than highest constant in code under test.
    buckets = [0] * 300
    # The seed is arbitrary and exists just to ensure this test is robust.
    # If you don't like this seed, try your own; the test should still pass.
    random.seed(1720)
    # Do enough runs that the expected hits even in the last buckets
    # is big enough to expect some statistical smoothing.
    total_runs = 10 * len(buckets)

    # Fill the buckets.
    for _ in range(total_runs):
      opcounts = OperationCounters(CounterFactory(), 'some-name',
                                   coders.PickleCoder(), 0)
      for i in range(len(buckets)):
        if opcounts.should_sample():
          buckets[i] += 1

    # Look at the buckets to see if they are likely.
    for i in range(10):
      self.assertEqual(total_runs, buckets[i])
    for i in range(10, len(buckets)):
      self.assertTrue(buckets[i] > 7 * total_runs / i,
                      'i=%d, buckets[i]=%d, expected=%d, ratio=%f' % (
                          i, buckets[i],
                          10 * total_runs / i,
                          buckets[i] / (10.0 * total_runs / i)))
      self.assertTrue(buckets[i] < 14 * total_runs / i,
                      'i=%d, buckets[i]=%d, expected=%d, ratio=%f' % (
                          i, buckets[i],
                          10 * total_runs / i,
                          buckets[i] / (10.0 * total_runs / i)))

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)
  unittest.main()


text:
namespace device_orientation {

// Create a AccelerometerMac object and return NULL if no valid sensor found.
DataFetcher* AccelerometerMac::Create() {
  scoped_ptr<AccelerometerMac> accelerometer(new AccelerometerMac);
  return accelerometer->Init() ? accelerometer.release() : NULL;
}

AccelerometerMac::~AccelerometerMac() {
}

AccelerometerMac::AccelerometerMac() {
}

//  Retrieve per-axis orientation values.
//
//  Axes and angles are defined according to the W3C DeviceOrientation Draft.
//  See here: http://dev.w3.org/geo/api/spec-source-orientation.html
//
//  Note: only beta and gamma angles are provided. Alpha is set to zero.
//
//  Returns false in case of error.
//
bool AccelerometerMac::GetOrientation(Orientation* orientation) {
  DCHECK(sudden_motion_sensor_.get());

  // Retrieve per-axis calibrated values.
  float axis_value[3];
  if (!sudden_motion_sensor_->ReadSensorValues(axis_value))
    return false;

  // Transform the accelerometer values to W3C draft angles.
  //
  // Accelerometer values are just dot products of the sensor axes
  // by the gravity vector 'g' with the result for the z axis inverted.
  //
  // To understand this transformation calculate the 3rd row of the z-x-y
  // Euler angles rotation matrix (because of the 'g' vector, only 3rd row
  // affects to the result). Note that z-x-y matrix means R = Ry * Rx * Rz.
  // Then, assume alpha = 0 and you get this:
  //
  // x_acc = sin(gamma)
  // y_acc = - cos(gamma) * sin(beta)
  // z_acc = cos(beta) * cos(gamma)
  //
  // After that the rest is just a bit of trigonometry.
  //
  // Also note that alpha can't be provided but it's assumed to be always zero.
  // This is necessary in order to provide enough information to solve
  // the equations.
  //
  const double kRad2deg = 180.0 / M_PI;

  orientation->set_beta(kRad2deg * atan2(-axis_value[1], axis_value[2]));
  orientation->set_gamma(kRad2deg * asin(axis_value[0]));
  // TODO(aousterh): should absolute_ be set to false here?
  // See crbug.com/136010.

  // Make sure that the interval boundaries comply with the specification. At
  // this point, beta is [-180, 180] and gamma is [-90, 90], but the spec has
  // the upper bound open on both.
  if (orientation->beta() == 180.0) {
    orientation->set_beta(-180.0);  // -180 == 180 (upside-down)
  }
  if (orientation->gamma() == 90.0) {
    static double just_less_than_90 = nextafter(90, 0);
    orientation->set_gamma(just_less_than_90);
  }

  // At this point, DCHECKing is paranoia. Never hurts.
  DCHECK_GE(orientation->beta(), -180.0);
  DCHECK_LT(orientation->beta(),  180.0);
  DCHECK_GE(orientation->gamma(), -90.0);
  DCHECK_LT(orientation->gamma(),  90.0);

  return true;
}

bool AccelerometerMac::Init() {
  sudden_motion_sensor_.reset(SuddenMotionSensor::Create());
  return sudden_motion_sensor_.get() != NULL;
}

}  // namespace device_orientation


text:
package com.rdfgroup.example.common.model;

public class SettingModel {

	private String UUID, name, value, description, id, environment;
	boolean oAuth;

	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public String getEnvironment() {
		return environment;
	}

	public void setEnvironment(String environment) {
		this.environment = environment;
	}

	public boolean isoAuth() {
		return oAuth;
	}

	public void setoAuth(boolean oAuth) {
		this.oAuth = oAuth;
	}

	public void setUUID(String uUID) {
		UUID = uUID;
	}

	public String getUUID() {
		return UUID;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getDescription() {
		return description;
	}

}


text:
.. _internalminimalmodbus:

Internal documentation for MinimalModbus
========================================

.. automodule:: minimalmodbus
   :noindex:
   :members:
   :undoc-members:
   :private-members:
   :special-members:


text:
using Autofac;
using Xpressive.Home.Contracts.Automation;
using Xpressive.Home.Contracts.Gateway;
using Xpressive.Home.Contracts.Messaging;

namespace Xpressive.Home.Plugins.PhilipsHue
{
    public class PhilipsHueModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<PhilipsHueScriptObjectProvider>().As<IScriptObjectProvider>();

            builder.RegisterType<PhilipsHueGateway>()
                .As<IGateway>()
                .As<IPhilipsHueGateway>()
                .As<IMessageQueueListener<CommandMessage>>()
                .SingleInstance();

            builder.RegisterType<PhilipsHueDeviceDiscoveringService>()
                .As<IPhilipsHueDeviceDiscoveringService>()
                .SingleInstance();

            builder.RegisterType<PhilipsHueBridgeDiscoveringService>()
                .As<IPhilipsHueBridgeDiscoveringService>()
                .As<IMessageQueueListener<NetworkDeviceFoundMessage>>()
                .SingleInstance();

            base.Load(builder);
        }
    }
}


text:
package com.xeiam.xchange.itbit.v1;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import com.xeiam.xchange.currency.Currency;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.dto.Order.OrderType;
import com.xeiam.xchange.dto.account.AccountInfo;
import com.xeiam.xchange.dto.marketdata.Ticker;
import com.xeiam.xchange.dto.marketdata.Trade;
import com.xeiam.xchange.dto.marketdata.Trades;
import com.xeiam.xchange.dto.marketdata.Trades.TradeSortType;
import com.xeiam.xchange.dto.trade.LimitOrder;
import com.xeiam.xchange.dto.trade.OpenOrders;
import com.xeiam.xchange.dto.trade.UserTrade;
import com.xeiam.xchange.dto.trade.UserTrades;
import com.xeiam.xchange.dto.trade.Wallet;
import com.xeiam.xchange.itbit.v1.dto.account.ItBitAccountBalance;
import com.xeiam.xchange.itbit.v1.dto.account.ItBitAccountInfoReturn;
import com.xeiam.xchange.itbit.v1.dto.marketdata.ItBitTicker;
import com.xeiam.xchange.itbit.v1.dto.marketdata.ItBitTrade;
import com.xeiam.xchange.itbit.v1.dto.trade.ItBitOrder;
import com.xeiam.xchange.utils.DateUtils;

public final class ItBitAdapters {

  private static final OpenOrders noOpenOrders = new OpenOrders(Collections.<LimitOrder> emptyList());
  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
  private static final DecimalFormat cryptoFormat;
  private static final DecimalFormat fiatFormat;

  static {
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    cryptoFormat = new DecimalFormat();
    cryptoFormat.setMaximumFractionDigits(4);
    cryptoFormat.setGroupingUsed(false);
    cryptoFormat.setRoundingMode(RoundingMode.HALF_UP);

    fiatFormat = new DecimalFormat();
    fiatFormat.setMaximumFractionDigits(2);
    fiatFormat.setGroupingUsed(false);
    fiatFormat.setRoundingMode(RoundingMode.HALF_UP);
  }

  /**
   * private Constructor
   */
  private ItBitAdapters() {

  }

  private static Date parseDate(String date) {

    Date parse;
    try {
      /**
       * "date" is sent with microsecond precision in UTC time. This is not supported by Java natively.
       */
      parse = dateFormat.parse(date.substring(0, 23) + 'Z');
    } catch (ParseException e) {
      return null;
    }

    return parse;
  }

  public static Trades adaptTrades(ItBitTrade[] trades, CurrencyPair currencyPair) {

    List<Trade> tradesList = new ArrayList<Trade>(trades.length);
    long lastTradeId = 0;
    for (int i = 0; i < trades.length; i++) {
      ItBitTrade trade = trades[i];
      long tradeId = trade.getTid();
      if (tradeId > lastTradeId)
        lastTradeId = tradeId;
      tradesList.add(adaptTrade(trade, currencyPair));
    }
    return new Trades(tradesList, lastTradeId, TradeSortType.SortByID);
  }

  public static Trade adaptTrade(ItBitTrade trade, CurrencyPair currencyPair) {

    Date date = DateUtils.fromMillisUtc(trade.getDate() * 1000L);
    final String tradeId = String.valueOf(trade.getTid());

    return new Trade(null, trade.getAmount(), currencyPair, trade.getPrice(), date, tradeId);
  }

  public static List<LimitOrder> adaptOrders(List<BigDecimal[]> orders, CurrencyPair currencyPair, OrderType orderType) {

    List<LimitOrder> limitOrders = new ArrayList<LimitOrder>(orders.size());

    for (int i = 0; i < orders.size(); i++) {
      BigDecimal[] level = orders.get(i);

      limitOrders.add(adaptOrder(level[1], level[0], currencyPair, null, orderType, null));
    }

    return limitOrders;

  }

  private static LimitOrder adaptOrder(BigDecimal amount, BigDecimal price, CurrencyPair currencyPair, String orderId, OrderType orderType,
      Date timestamp) {

    return new LimitOrder(orderType, amount, currencyPair, orderId, timestamp, price);
  }

  public static AccountInfo adaptAccountInfo(ItBitAccountInfoReturn[] info) {

    List<Wallet> wallets = new ArrayList<Wallet>();
    String userId = "";

    for (int i = 0; i < info.length; i++) {
      ItBitAccountInfoReturn itBitAccountInfoReturn = info[i];
      ItBitAccountBalance[] balances = itBitAccountInfoReturn.getBalances();

      userId = itBitAccountInfoReturn.getUserId();

      for (int j = 0; j < balances.length; j++) {
        ItBitAccountBalance itBitAccountBalance = balances[j];

        Wallet wallet = new Wallet(itBitAccountBalance.getCurrency(), itBitAccountBalance.getTotalBalance(),
            itBitAccountBalance.getAvailableBalance(), itBitAccountInfoReturn.getName());
        wallets.add(wallet);
      }
    }

    return new AccountInfo(userId, wallets);
  }

  public static OpenOrders adaptPrivateOrders(ItBitOrder[] orders) {

    if (orders.length <= 0) {
      return noOpenOrders;
    }

    List<LimitOrder> limitOrders = new ArrayList<LimitOrder>(orders.length);

    for (int i = 0; i < orders.length; i++) {
      ItBitOrder itBitOrder = orders[i];
      String instrument = itBitOrder.getInstrument();

      CurrencyPair currencyPair = new CurrencyPair(instrument.substring(0, 3), instrument.substring(3, 6));
      OrderType orderType = itBitOrder.getSide().equals("buy") ? OrderType.BID : OrderType.ASK;
      Date timestamp = parseDate(itBitOrder.getCreatedTime());
      limitOrders.add(adaptOrder(itBitOrder.getAmount(), itBitOrder.getPrice(), currencyPair, itBitOrder.getId(), orderType, timestamp));
    }

    return new OpenOrders(limitOrders);
  }

  public static UserTrades adaptTradeHistory(ItBitOrder[] orders) {

    List<UserTrade> trades = new ArrayList<UserTrade>(orders.length);

    for (int i = 0; i < orders.length; i++) {
      ItBitOrder itBitOrder = orders[i];
      String instrument = itBitOrder.getInstrument();

      OrderType orderType = itBitOrder.getSide().equals("buy") ? OrderType.BID : OrderType.ASK;
      CurrencyPair currencyPair = new CurrencyPair(instrument.substring(0, 3), instrument.substring(3, 6));
      Date timestamp = parseDate(itBitOrder.getCreatedTime());

      trades.add(new UserTrade(orderType, itBitOrder.getAmount(), currencyPair, itBitOrder.getPrice(), timestamp, itBitOrder.getId(),
          itBitOrder.getId(), null, (Currency)null));
    }

    return new UserTrades(trades, TradeSortType.SortByTimestamp);
  }

  public static Ticker adaptTicker(CurrencyPair currencyPair, ItBitTicker itBitTicker) {

    BigDecimal bid = itBitTicker.getBid();
    BigDecimal ask = itBitTicker.getAsk();
    BigDecimal high = itBitTicker.getHighToday();
    BigDecimal low = itBitTicker.getLowToday();
    BigDecimal last = itBitTicker.getLastPrice();
    BigDecimal volume = itBitTicker.getVolume24h();
    Date timestamp = itBitTicker.getTimestamp() != null ? parseDate(itBitTicker.getTimestamp()) : null;

    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp)
        .build();
  }

  public static String formatFiatAmount(BigDecimal amount) {
    return fiatFormat.format(amount);
  }

  public static String formatCryptoAmount(BigDecimal amount) {
    return cryptoFormat.format(amount);
  }
}


text:
using System;
using System.Linq;
using System.ServiceModel;

using System.Runtime.Remoting.Messaging;
using SE.DSP.Foundation.Infrastructure.Utils;
using SE.DSP.Foundation.Infrastructure.Enumerations;
using SE.DSP.Foundation.Infrastructure.Constant;

namespace SE.DSP.Foundation.Infrastructure.Interception
{
    /// <summary>
    /// Represents the app service api context
    ///
    ///
    /// modified by mike 20140526 add "Language" property
    /// </summary>
    public static class ServiceContext
    {
        [ThreadStatic]
        private static Guid _requestId;

        [ThreadStatic]
        private static User _currentUser;

        private static Language _language;

        /// <summary>
        ///  added by mike on 20140526
        /// </summary>
        public static Language Language
        {
            get
            {
                if (OperationContext.Current == null)
                    return Language.ZH_CN;
                bool res = OperationContext.Current.IncomingMessageHeaders.Any(temp => temp.Name.Equals(ServiceContextConstant.LANGUAGE));
                if (!res)
                    return Language.ZH_CN;
                _language = OperationContext.Current.IncomingMessageHeaders.GetHeader<Language>(ServiceContextConstant.LANGUAGE, ServiceContextConstant.HEADERNAMESPACE);
                return _language;
            }
        }

        /// <summary>
        /// Set RequestId, CurrentUser.
        /// </summary>
        /// <param name="requestId">Request id.</param>
        /// <param name="currentUser">Current user.</param>
        public static void SetServiceContext(Guid requestId, User currentUser)
        {
            _requestId = requestId;
            _currentUser = currentUser;
        }

        /// <summary>
        /// Gets the request id of this invoking.
        /// </summary>
        public static Guid RequestId
        {
            get
            {
                if (OperationContext.Current == null) //UT invoke
                {
                    return _requestId;
                }
                else //WCF invoke
                {
                   _requestId= OperationContext.Current.IncomingMessageHeaders.Any(header => header.Name == ServiceContextConstant.REQUESTID) ? OperationContext.Current.IncomingMessageHeaders.GetHeader<Guid>(ServiceContextConstant.REQUESTID, ServiceContextConstant.HEADERNAMESPACE) : Guid.Empty;

                   return _requestId;
                }
            }
        }

        /// <summary>
        /// Gets the current user.
        /// </summary>
        public static User CurrentUser
        {
            get
            {
                if (OperationContext.Current == null) //UT invoke
                {
                    var user = CallContext.LogicalGetData(ServiceContextConstant.CURRENTUSER);

                     if (user == null)
                     {
                         if (_currentUser == null)
                         {
                             _currentUser = new User
                             {
                                 SPId = 1,
                                 Name = "",
                             };
                         }
                     }
                    else
                     {
                         _currentUser = (User)user;
                     }

                    return _currentUser;
                }
                else //WCF invoke
                {
                    _currentUser= (User)OperationContext.Current.IncomingMessageHeaders.GetHeader<User>(ServiceContextConstant.CURRENTUSER, ServiceContextConstant.HEADERNAMESPACE);

                    return _currentUser;
                }
            }
        }
    }
}


text:
'use strict';

let gulp = require('gulp');
let watch = require('gulp-watch');
let config = require('../config');
let reload = require('../browser-sync').reload;

class Base {
  constructor(dist, src) {
    this.gulp = gulp;
    this.dist = dist;
    this.src = src;
  }

  createStream(src) {
    src = src || this.src;

    return this.gulp.src(src);
  }

  createWatchStream(src, options) {
    src = src || this.src;
    options = options || {verbose: true};

    return watch(src, options);
  }

  dest(dist) {
    dist = dist || this.dist;

    return this.gulp.dest(dist);
  }

  reload(options) {
    options = options || {stream: true};

    return reload(options);
  }

  getStream() {
    return this.createStream()
      .pipe(this.dest());
  }

  getStreamWithWatch() {
    return this.createWatchStream()
      .pipe(this.dest())
      .pipe(this.reload());
  }

  static getTask(dist, isWatch) {
    switch (dist) {
      case 'tmp':
        dist = config.destDir;
        break;
      case 'release':
        dist = config.getReleasePath();
        break;
    }

    return () => {
      let inst = new this(dist);
      return isWatch ? inst.getStreamWithWatch() : inst.getStream();
    }
  }

}

module.exports = Base;