text:
package li.barter.fragments.dialogs;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;

import li.barter.utils.Logger;

/**
 * Single Choice Alert Dialog.
 *
 * @author Vinay S Shenoy
 */
public class SingleChoiceDialogFragment extends DialogFragment {

    private static final String TAG = "SingleChoiceDialogFragment";

    /** Res Id for the Dialog Title. */
    private int                 mTitleId;

    /** Click Listener for the Dialog buttons. */
    private OnClickListener     mClickListener;

    /** On Dismiss Listener for the Dialog */
    private OnDismissListener   mOnDismissListener;

    /** Resource Id for the icon to be be used in the alert dialog. */
    private int                 mIconId;

    /** Boolean flag to identify if the dialog is cancelable. */
    private boolean             isCancellable;

    /** {@linkplain AlertDialog}'s THEME constants for the dialog theme. */
    private int                 mTheme;

    /**
     * Resource Id for an array to be added to the dialog items
     */
    private int                 mItemsId;

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {

        if (savedInstanceState != null) {
            mTitleId = savedInstanceState.getInt(DialogKeys.TITLE_ID);
            isCancellable = savedInstanceState
                            .getBoolean(DialogKeys.CANCELLABLE);
            mIconId = savedInstanceState.getInt(DialogKeys.ICON_ID);
            mTheme = savedInstanceState.getInt(DialogKeys.THEME);
            mItemsId = savedInstanceState.getInt(DialogKeys.ITEMS_ID);
        }

        final Builder builder = new Builder(getActivity(), mTheme);

        if (mItemsId == 0) {
            throw new IllegalArgumentException("No items available to add");
        }

        builder.setItems(mItemsId, mClickListener);

        if (mIconId != 0) {
            builder.setIcon(mIconId);
        }
        if (mTitleId != 0) {
            builder.setTitle(mTitleId);
        }

        builder.setCancelable(isCancellable);
        setCancelable(isCancellable);
        return builder.create();
    }

    @Override
    public void onAttach(final Activity activity) {

        super.onAttach(activity);

        if (activity instanceof OnClickListener) {
            mClickListener = (OnClickListener) activity;
        }

        else {
            throw new IllegalStateException("Activity must implement DialogInterface.OnClickListener");
        }

        if (activity instanceof OnDismissListener) {
            mOnDismissListener = (OnDismissListener) activity;
        }
    }

    @Override
    public void onDismiss(final DialogInterface dialog) {
        super.onDismiss(dialog);
        if (mOnDismissListener != null) {
            mOnDismissListener.onDismiss(dialog);
        }
    }

    @Override
    public void onSaveInstanceState(final Bundle outState) {

        outState.putInt(DialogKeys.TITLE_ID, mTitleId);
        outState.putBoolean(DialogKeys.CANCELLABLE, isCancellable);
        outState.putInt(DialogKeys.ICON_ID, mIconId);
        outState.putInt(DialogKeys.THEME, mTheme);
        outState.putInt(DialogKeys.ITEMS_ID, mItemsId);
        super.onSaveInstanceState(outState);
    }

    public void show(final int theme, final int itemsId, final int iconId,
                    final int titleId, final FragmentManager manager,
                    final boolean cancellable, final String fragmentTag) {

        mTheme = theme;
        mItemsId = itemsId;
        mIconId = iconId;
        mTitleId = titleId;
        isCancellable = cancellable;

        try {
            super.show(manager, fragmentTag);
        } catch (final IllegalStateException e) {
            Logger.e(TAG, e, "Exception");
        }

    }

}


text:
class PartComponent {
  constructor() {
    this.index = 1;
    this.min = 1;
    this.max = 10;
  }

  static ddo() {
    return {
      restrict: 'E',
      templateUrl: 'components/routes/part.html',
      controller: PartComponent,
      controllerAs: 'part'
    }
  }

  prev() {
    if (!this.hasPrev()) return false;
    this.index --;
  }

  next() {
    if (!this.hasNext()) return false;
    this.index ++;
  }

  hasPrev() {
    return this.index > this.min;
  }

  hasNext() {
    return this.index < this.max;
  }
}

angular
  .module('PagingScroller')
  .directive('part', PartComponent.ddo);

redpajama_set_name: RedPajamaGithub


text: fork of the http://pogostack.com/


text:
require 'uri'
require 'net/http'
require 'net/https'
require 'yaml'
require 'active_support/core_ext/hash/keys'

module Travis
  class Buildable
    class Config < Hash
      def initialize(source)
        source = URI.parse(source)

        http = Net::HTTP.new(source.host, 443)
        http.use_ssl = true

        response, body = http.get(source.path, nil)
        replace(YAML.load(body).symbolize_keys) rescue nil if response.code == '200'
      rescue URI::InvalidURIError => e
        {}
      end
    end
  end
end


text:
package com.xeiam.xchange.examples.coinbase.account.merchant;

import java.io.IOException;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.coinbase.dto.merchant.CoinbaseButton;
import com.xeiam.xchange.coinbase.dto.merchant.CoinbaseButton.CoinbaseButtonBuilder;
import com.xeiam.xchange.coinbase.dto.merchant.CoinbaseButtonStyle;
import com.xeiam.xchange.coinbase.dto.merchant.CoinbaseButtonType;
import com.xeiam.xchange.coinbase.dto.merchant.CoinbaseOrder;
import com.xeiam.xchange.coinbase.service.polling.CoinbaseAccountService;
import com.xeiam.xchange.currency.Currencies;
import com.xeiam.xchange.examples.coinbase.CoinbaseDemoUtils;

/**
 * @author jamespedwards42
 */
public class CoinbaseButtonDemo {

  public static void main(String[] args) throws IOException {

    Exchange coinbase = CoinbaseDemoUtils.createExchange();
    CoinbaseAccountService accountService = (CoinbaseAccountService) coinbase.getPollingAccountService();

    CoinbaseButtonBuilder buttonBuilder = new CoinbaseButtonBuilder("Demo Button", Currencies.BTC, ".001");
    buttonBuilder.withDescription("Coinbase button demo for Coinbase.").withIncludeEmail(true).withStyle(CoinbaseButtonStyle.DONATION_LARGE).withType(CoinbaseButtonType.DONATION).withVariablePrice(
        true);

    CoinbaseButton createdButton = accountService.createCoinbaseButton(buttonBuilder.buildButton());
    System.out.println(createdButton);

    CoinbaseOrder createdOrder = accountService.createCoinbaseOrder(createdButton.getCode());
    System.out.println(createdOrder);

    createdOrder = accountService.createCoinbaseOrder(createdButton);
    System.out.println(createdOrder);
  }
}


text:
local access = require "kong.plugins.basic-auth.access"

local BasicAuthHandler = {}

function BasicAuthHandler:access(conf)
  access.execute(conf)
end

BasicAuthHandler.PRIORITY = 1001
BasicAuthHandler.VERSION = "2.1.0"

return BasicAuthHandler


text:
import React from 'react'
import { Image } from 'cloudinary-react'

export default () => (

    <Image
      style={{ margin: '20px 0' }}
      cloudName='ziro'
      width='40'
      publicId='ok-icon_bskbxm'
      version='1508212647'
      format='png'
      secure='true'
    />

Seu CNPJ foi validado com sucesso!

Agora, termine de preencher o formulário abaixo para acessar o aplicativo. É rapidinho ;)

)


text:
package org.apache.qpid.proton.amqp.transport;

import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.UnsignedInteger;

public final class Detach implements FrameBody
{
    private UnsignedInteger _handle;
    private boolean _closed;
    private ErrorCondition _error;

    public Detach() {}

    public Detach(Detach other)
    {
        this._handle = other._handle;
        this._closed = other._closed;
        if (other._error != null)
        {
            this._error = new ErrorCondition();
            this._error.copyFrom(other._error);
        }
    }

    public UnsignedInteger getHandle()
    {
        return _handle;
    }

    public void setHandle(UnsignedInteger handle)
    {
        if( handle == null )
        {
            throw new NullPointerException("the handle field is mandatory");
        }

        _handle = handle;
    }

    public boolean getClosed()
    {
        return _closed;
    }

    public void setClosed(boolean closed)
    {
        _closed = closed;
    }

    public ErrorCondition getError()
    {
        return _error;
    }

    public void setError(ErrorCondition error)
    {
        _error = error;
    }

    @Override
    public <E> void invoke(FrameBodyHandler<E> handler, Binary payload, E context)
    {
        handler.handleDetach(this, payload, context);
    }

    @Override
    public String toString()
    {
        return "Detach{" +
               "handle=" + _handle +
               ", closed=" + _closed +
               ", error=" + _error +
               '}';
    }

    @Override
    public Detach copy()
    {
        return new Detach(this);
    }
}


text:
// Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#pragma warning disable IDE1006 // Naming Styles

namespace NOpenCL
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using NOpenCL.SafeHandles;

    /// <content>
    /// Partitioning a device.
    /// </content>
    internal partial class UnsafeNativeMethods
    {
        [DllImport(ExternDll.OpenCL)]
        private static extern ErrorCode clCreateSubDevices(
            ClDeviceID device,
            [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] properties,
            uint numDevices,
            [Out, MarshalAs(UnmanagedType.LPArray)] ClDeviceID[] devices,
            out uint numDevicesRet);

        private static DisposableCollection<Device> CreateSubDevices(ClDeviceID device, IntPtr[] properties)
        {
            uint required;
            ErrorHandler.ThrowOnFailure(clCreateSubDevices(device, properties, 0, null, out required));

            ClDeviceID[] devices = new ClDeviceID[required];
            uint actual;
            ErrorHandler.ThrowOnFailure(clCreateSubDevices(device, properties, required, devices, out actual));

            var result = new DisposableCollection<Device>(false);
            for (int i = 0; i < actual; i++)
                result.Add(new Device(devices[i], new DeviceSafeHandle(devices[i])));

            return result;
        }

        public static DisposableCollection<Device> PartitionEqually(ClDeviceID device, int partitionSize)
        {
            IntPtr[] properties = { (IntPtr)PartitionProperty.PartitionEqually, (IntPtr)partitionSize, IntPtr.Zero };
            return CreateSubDevices(device, properties);
        }

        public static DisposableCollection<Device> PartitionByCounts(ClDeviceID device, int[] partitionSizes)
        {
            if (partitionSizes == null)
                throw new ArgumentNullException(nameof(partitionSizes));

            var propertiesList = new List<IntPtr>();
            propertiesList.Add((IntPtr)PartitionProperty.PartitionByCounts);
            foreach (int partitionSize in partitionSizes)
            {
                if (partitionSize < 0)
                    throw new ArgumentOutOfRangeException(nameof(partitionSizes), "Partition size cannot be negative.");

                propertiesList.Add((IntPtr)partitionSize);
            }

            propertiesList.Add((IntPtr)PartitionProperty.PartitionByCountsListEnd);
            propertiesList.Add(IntPtr.Zero);

            IntPtr[] properties = propertiesList.ToArray();
            return CreateSubDevices(device, properties);
        }

        public static DisposableCollection<Device> PartitionByAffinityDomain(ClDeviceID device, AffinityDomain affinityDomain)
        {
            IntPtr[] properties = { (IntPtr)PartitionProperty.PartitionByAffinityDomain, (IntPtr)affinityDomain, IntPtr.Zero };
            return CreateSubDevices(device, properties);
        }

        [DllImport(ExternDll.OpenCL)]
        private static extern ErrorCode clRetainDevice(DeviceSafeHandle device);

        [DllImport(ExternDll.OpenCL)]
        public static extern ErrorCode clReleaseDevice(IntPtr device);
    }
}


text:
<?php
namespace DreamFactory\Core\OAuth\Components;

use DreamFactory\Core\Utility\Session;
use Laravel\Socialite\One\AbstractProvider;
use League\OAuth1\Client\Credentials\TemporaryCredentials;
use Illuminate\Http\RedirectResponse;

trait DfOAuthOneProvider
{
    /**
     * Indicates if the session state should be utilized.
     *
     * @var bool
     */
    protected $stateless = false;

    /**
     * Determine if the provider is operating with state.
     *
     * @return bool
     */
    protected function usesState()
    {
        return ! $this->stateless;
    }

    /**
     * Determine if the provider is operating as stateless.
     *
     * @return bool
     */
    protected function isStateless()
    {
        return $this->stateless;
    }

    /**
     * Indicates that the provider should operate as stateless.
     *
     * @return $this
     */
    public function stateless()
    {
        $this->stateless = true;

        return $this;
    }

    /**
     * Redirect the user to the authentication page for the provider.
     *
     * @return RedirectResponse
     */
    public function redirect()
    {
        /** @type TemporaryCredentials $temp */
        $temp = $this->server->getTemporaryCredentials();

        if($this->usesState()) {
            $this->request->getSession()->set(
                'oauth.temp', $temp
            );
        }
        else{
            $identifier = $temp->getIdentifier();
            \Cache::put($identifier, $temp, 1);
        }

        return new RedirectResponse($this->server->getAuthorizationUrl($temp));
    }

    /**
     * Get the token credentials for the request.
     *
     * @return \League\OAuth1\Client\Credentials\TokenCredentials
     */
    protected function getToken()
    {
        $temp = null;

        if($this->usesState()) {
            $temp = $this->request->getSession()->get('oauth.temp');
        }
        else{
            $key = $this->request->get('oauth_token');
            $temp = \Cache::pull($key);
        }

        return $this->server->getTokenCredentials(
            $temp, $this->request->get('oauth_token'), $this->request->get('oauth_verifier')
        );
    }
}


text:
// Copyright 2018, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Florian Kramer (florian.kramer@netpun.uni-freiburg.de)
#pragma once

#include <array>
#include <vector>

#include "./Operation.h"
#include "./QueryExecutionTree.h"

class MultiColumnJoin : public Operation {
 public:
  MultiColumnJoin(QueryExecutionContext* qec,
                  std::shared_ptr<QueryExecutionTree> t1,
                  std::shared_ptr<QueryExecutionTree> t2,
                  const std::vector<std::array<Id, 2>>& joinCols);

  virtual string asString(size_t indent = 0) const override;

  virtual string getDescriptor() const override;

  virtual size_t getResultWidth() const override;

  virtual vector<size_t> resultSortedOn() const override;

  ad_utility::HashMap<string, size_t> getVariableColumns() const;

  virtual void setTextLimit(size_t limit) override {
    _left->setTextLimit(limit);
    _right->setTextLimit(limit);
  }

  virtual bool knownEmptyResult() override {
    return _left->knownEmptyResult() || _right->knownEmptyResult();
  }

  virtual float getMultiplicity(size_t col) override;

  virtual size_t getSizeEstimate() override;

  virtual size_t getCostEstimate() override;

  /**
   * @brief Joins a and b using the column defined int joinColumns, storing the
   *        result in result. R should have width resultWidth (or be a vector
   *        that should have resultWidth entries).
   *        This method is made public here for unit testing purposes.
   **/
  template <int A_WIDTH, int B_WIDTH, int OUT_WIDTH>
  static void computeMultiColumnJoin(const IdTable& a, const IdTable& b,
                                     const vector<array<Id, 2>>& joinColumns,
                                     IdTable* result);

 private:
  void computeSizeEstimateAndMultiplicities();

  std::shared_ptr<QueryExecutionTree> _left;
  std::shared_ptr<QueryExecutionTree> _right;

  std::vector<std::array<Id, 2>> _joinColumns;

  vector<float> _multiplicities;
  size_t _sizeEstimate;
  bool _multiplicitiesComputed;

  virtual void computeResult(ResultTable* result) override;
};


text:
package org.tamacat.httpd.exception;

import org.tamacat.httpd.core.BasicHttpStatus;

/**
 * <p>Throws 503 Service Unavailable.
 */
public class ServiceUnavailableException extends HttpException {

	private static final long serialVersionUID = 1L;

	public ServiceUnavailableException() {
		super(BasicHttpStatus.SC_SERVICE_UNAVAILABLE);
	}

	public ServiceUnavailableException(Throwable cause) {
		super(BasicHttpStatus.SC_SERVICE_UNAVAILABLE, cause);
	}

	public ServiceUnavailableException(String message) {
		super(BasicHttpStatus.SC_SERVICE_UNAVAILABLE, message);
	}

	public ServiceUnavailableException(String message, Throwable cause) {
		super(BasicHttpStatus.SC_SERVICE_UNAVAILABLE, message, cause);
	}
}


text:
package org.cloudfoundry.samples.music.config.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.cloudfoundry.samples.music.web.controllers.AlbumController;

@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = {AlbumController.class})
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/WEB-INF/");
        internalResourceViewResolver.setSuffix(".html");
        return internalResourceViewResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}


text:
/* Space out content a bit */
body {
  padding-top: 20px;
  padding-bottom: 20px;
}

/* Everything but the jumbotron gets side spacing for mobile first views */
.header,
.marketing,
.footer {
  padding-left: 15px;
  padding-right: 15px;
}

/* Custom page header */
.header {
  border-bottom: 1px solid #e5e5e5;
}
/* Make the masthead heading the same height as the navigation */
.header h3 {
  margin-top: 0;
  margin-bottom: 0;
  line-height: 40px;
  padding-bottom: 19px;
  font-family: 'Roboto Condensed', sans-serif;
}

/* Custom page footer */
.footer {
  padding-top: 19px;
  color: #777;
  border-top: 1px solid #e5e5e5;
}

/* Customize container */
@media (min-width: 768px) {
  .container {
    max-width: 730px;
  }
}
.container-narrow > hr {
  margin: 30px 0;
}

/* Main marketing message and sign up button */
.jumbotron {
  text-align: center;
  border-bottom: 1px solid #e5e5e5;
}
.jumbotron .btn {
  font-size: 21px;
  padding: 14px 24px;
}

/* Supporting marketing content */
.marketing {
  margin: 40px 0;
  font-family: 'Roboto Condensed', sans-serif;
}
.marketing p + h4 {
  margin-top: 28px;
}

/* Responsive: Portrait tablets and up */
@media screen and (min-width: 768px) {
  /* Remove the padding we set earlier */
  .header,
  .marketing,
  .footer {
    padding-left: 0;
    padding-right: 0;
  }
  /* Space out the masthead */
  .header {
    margin-bottom: 30px;
  }
  /* Remove the bottom border on the jumbotron for visual effect */
  .jumbotron {
    border-bottom: 0;
  }
}

.md-button {
  line-height: 26px;
}

md-toolbar.md-default-theme:not(.md-menu-toolbar), md-toolbar:not(.md-menu-toolbar) {
  background-color: #373F51;
  padding-left: 10px;
  padding-right: 10px;
}

.md-subheader.md-default-theme.md-primary, .md-subheader.md-primary {
  background-color: #CEE0DC;
}

.application-list {
  background-color: #CEE0DC;
  padding-bottom: 30px;
  padding-top: 30px;
}

.big-icon {
  font-size: 46px;
  padding: 20px;
}

.remove-sign-icon {
  color: #A5243D
}

.ok-sign-icon {
  color: #467657;
}

.question-sign-icon {
  color: #DCC48E;
}

.datetime {
  white-space: nowrap;
}

.commandList {
  padding-right: 10px;
}

md-toolbar.md-default-theme.searchbar, md-toolbar.searchbar {
  background-color: #467657;
  padding-left: 10px;
  padding-right: 10px;
}

md-toolbar.md-default-theme:not(.md-menu-toolbar) .md-button:not(.md-raised), md-toolbar:not(.md-menu-toolbar) .md-button:not(.md-raised) {
  color: 'black';
}

.md-toolbar-tools {
  margin-top: 30px;
}

#serach-bar md-input-container.md-default-theme:not(.md-input-invalid).md-input-focused .md-input, #search-bar md-input-container:not(.md-input-invalid).md-input-focused .md-input {
  border-color: #FFFFFF;
}

#search-bar md-input-container.md-default-theme:not(.md-input-invalid).md-input-focused label, #search-bar md-input-container:not(.md-input-invalid).md-input-focused label {
  color: #FFFFFF;
}

#search-bar md-input-container.md-default-theme .md-input, #search-bar md-input-container .md-input {
  color: #CEE0DC;
  margin-bottom: -20px;
}

.nav > li > a:hover, .nav > li > a:focus {
  background-color: #7A8293;
  color: #FFFFFF;
}

a {
  color: #373F51;
}

.nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus {
  background-color: #373F51;
  color: #FFFFFF;
}

.jumbotron, md-content.md-default-theme, md-content {
  background-color: #E1E2E4
}

#search-bar label {
  color: #CEE0DC;
}

#search-bar input {
  font-family: 'Roboto Condensed', sans-serif;
}


text:
use std::io::Write;

use byteorder_slice::byteorder::WriteBytesExt;
use byteorder_slice::result::ReadSlice;
use byteorder_slice::{BigEndian, ByteOrder, LittleEndian};

use crate::errors::*;
use crate::{DataLink, Endianness, TsResolution};

/// Pcap Global Header
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct PcapHeader {
    /// Major version number
    pub version_major: u16,

    /// Minor version number
    pub version_minor: u16,

    /// GMT to local timezone correction, should always be 0
    pub ts_correction: i32,

    /// Timestamp accuracy, should always be 0
    pub ts_accuracy: u32,

    /// Max length of captured packet, typically 65535
    pub snaplen: u32,

    /// DataLink type (first layer in the packet)
    pub datalink: DataLink,

    /// Timestamp resolution of the pcap (microsecond or nanosecond)
    pub ts_resolution: TsResolution,

    /// Endianness of the pcap (excluding the packet data)
    pub endianness: Endianness,
}

impl PcapHeader {
    /// Creates a new [`PcapHeader`] from a slice of bytes
    ///
    /// Returns an error if the reader doesn't contain a valid pcap
    /// or if there is a reading error.
    ///
    /// `PcapError::IncompleteBuffer` indicates that there is not enough data in the buffer
    pub fn from_slice(mut slice: &[u8]) -> PcapResult<(&[u8], PcapHeader)> {
        // Check that slice.len() > PcapHeader length
        if slice.len() < 24 {
            return Err(PcapError::IncompleteBuffer);
        }

        let magic_number = slice.read_u32::<BigEndian>().unwrap();

        match magic_number {
            0xA1B2C3D4 => return init_pcap_header::<BigEndian>(slice, TsResolution::MicroSecond, Endianness::Big),
            0xA1B23C4D => return init_pcap_header::<BigEndian>(slice, TsResolution::NanoSecond, Endianness::Big),
            0xD4C3B2A1 => return init_pcap_header::<LittleEndian>(slice, TsResolution::MicroSecond, Endianness::Little),
            0x4D3CB2A1 => return init_pcap_header::<LittleEndian>(slice, TsResolution::NanoSecond, Endianness::Little),
            _ => return Err(PcapError::InvalidField("PcapHeader: wrong magic number")),
        };

        // Inner function used for the initialisation of the `PcapHeader`.
        // Must check the srcclength before calling it.
        fn init_pcap_header<B: ByteOrder>(
            mut src: &[u8],
            ts_resolution: TsResolution,
            endianness: Endianness,
        ) -> PcapResult<(&[u8], PcapHeader)> {
            let header = PcapHeader {
                version_major: src.read_u16::<B>().unwrap(),
                version_minor: src.read_u16::<B>().unwrap(),
                ts_correction: src.read_i32::<B>().unwrap(),
                ts_accuracy: src.read_u32::<B>().unwrap(),
                snaplen: src.read_u32::<B>().unwrap(),
                datalink: DataLink::from(src.read_u32::<B>().unwrap()),
                ts_resolution,
                endianness,
            };

            Ok((src, header))
        }
    }

    /// Write a [`PcapHeader`] to a writer.
    ///
    /// Uses the endianness of the header.
    pub fn write_to<W: Write>(&self, writer: &mut W) -> PcapResult<usize> {
        return match self.endianness {
            Endianness::Big => write_header::<_, BigEndian>(self, writer),
            Endianness::Little => write_header::<_, LittleEndian>(self, writer),
        };

        fn write_header<W: Write, B: ByteOrder>(header: &PcapHeader, writer: &mut W) -> PcapResult<usize> {
            let magic_number = match header.ts_resolution {
                TsResolution::MicroSecond => 0xA1B2C3D4,
                TsResolution::NanoSecond => 0xA1B23C4D,
            };

            writer.write_u32::<B>(magic_number).map_err(|e| PcapError::IoError(e))?;
            writer.write_u16::<B>(header.version_major).map_err(|e| PcapError::IoError(e))?;
            writer.write_u16::<B>(header.version_minor).map_err(|e| PcapError::IoError(e))?;
            writer.write_i32::<B>(header.ts_correction).map_err(|e| PcapError::IoError(e))?;
            writer.write_u32::<B>(header.ts_accuracy).map_err(|e| PcapError::IoError(e))?;
            writer.write_u32::<B>(header.snaplen).map_err(|e| PcapError::IoError(e))?;
            writer.write_u32::<B>(header.datalink.into()).map_err(|e| PcapError::IoError(e))?;

            Ok(24)
        }
    }
}

/// Creates a new [`PcapHeader`] with the default parameters:
///
/// ```rust,ignore
/// PcapHeader {
///     version_major: 2,
///     version_minor: 4,
///     ts_correction: 0,
///     ts_accuracy: 0,
///     snaplen: 65535,
///     datalink: DataLink::ETHERNET,
///     ts_resolution: TsResolution::MicroSecond,
///     endianness: Endianness::Big
/// };
/// ```
impl Default for PcapHeader {
    fn default() -> Self {
        PcapHeader {
            version_major: 2,
            version_minor: 4,
            ts_correction: 0,
            ts_accuracy: 0,
            snaplen: 65535,
            datalink: DataLink::ETHERNET,
            ts_resolution: TsResolution::MicroSecond,
            endianness: Endianness::Big,
        }
    }
}


text:
/* This file was generated by syncqt. */
#ifndef QT_QTWEBSOCKETS_VERSION_H
#define QT_QTWEBSOCKETS_VERSION_H

#define QTWEBSOCKETS_VERSION_STR "5.5.1"

#define QTWEBSOCKETS_VERSION 0x050501

#endif // QT_QTWEBSOCKETS_VERSION_H


text:
'use strict';

const config = {
    'port': process.env.PORT,
    'fb_token': process.env.FB_TOKEN,
    'fb_verify': process.env.FB_VERIFY,
    'fb_secret': process.env.FB_SECRET,
    'fb_page_id': process.env.FB_PAGE_ID,
    'google_key': process.env.GOOGLE_KEY,
    'mixpanel_token': process.env.MIXPANEL_TOKEN,
    'redis_host': process.env.REDIS_HOST,
    'redis_port': process.env.REDIS_PORT,
    'redis_user': process.env.REDIS_USER,
    'redis_password': process.env.REDIS_PASSWORD,
    'ssl_key': process.env.SSL_KEY,
    'ssl_cert': process.env.SSL_CERT,
    'ssl_ca': process.env.SSL_CA
};

for (const key of Object.keys(config)) {
    if (!config[key]) {
        throw new Error(`Invalid configuration. Missing "${key}"`);
    }
}

module.exports = config;


text:
/**
 * This module is responsible for returning the currently displayed image for an element
 */

(function ($, cornerstone) {

    "use strict";

    /**
     * returns the currently displayed image for an element or undefined if no image has
     * been displayed yet
     *
     * @param element
     */
    function getImage(element) {
        var enabledElement = cornerstone.getEnabledElement(element);
        return enabledElement.image;
    }

    // Module exports
    cornerstone.getImage = getImage;
}($, cornerstone));


text:
//======================================================================
#include "ArrowLayer.h"
#include "Config.h"
#include "Hash.h"
#include "Iri.h"
#include "Layer.h"
#include "Select.h"
#include "State.h"
#include "ValueTools.h"
#include <engines/gis/Engine.h>
#include <engines/querydata/Q.h>
#include <macgyver/Exception.h>
#include <spine/Json.h>
#include <timeseries/ParameterFactory.h>
#include <timeseries/ParameterTools.h>
#ifndef WITHOUT_OBSERVATION
#include <engines/observation/Engine.h>
#endif
#include <boost/math/constants/constants.hpp>
#include <boost/move/make_unique.hpp>
#include <boost/timer/timer.hpp>
#include <ctpp2/CDT.hpp>
#include <engines/grid/Engine.h>
#include <fmt/format.h>
#include <fmt/printf.h>
#include <gis/Box.h>
#include <gis/CoordinateTransformation.h>
#include <gis/OGR.h>
#include <gis/Types.h>
#include <grid-content/queryServer/definition/QueryConfigurator.h>
#include <grid-files/common/GeneralFunctions.h>
#include <grid-files/common/ImagePaint.h>
#include <newbase/NFmiArea.h>
#include <newbase/NFmiPoint.h>
#include <iomanip>

const double pi = boost::math::constants::pi<double>();

namespace SmartMet
{
namespace Plugin
{
namespace Dali
{
// ----------------------------------------------------------------------
/*!
 * \brief Holder for data values
 */
// ----------------------------------------------------------------------

namespace
{
using PointValues = std::vector<WindArrowValue>;
}  // namespace

// ----------------------------------------------------------------------
/*!
 * \brief Forecast reader
 */
// ----------------------------------------------------------------------

PointValues read_forecasts(const ArrowLayer& layer,
                           const Engine::Querydata::Q& q,
                           const Fmi::SpatialReference& crs,
                           const Fmi::Box& box,
                           const boost::posix_time::time_period& time_period)
{
  try
  {
    NFmiMetTime met_time = time_period.begin();

    boost::optional<Spine::Parameter> dirparam;
    boost::optional<Spine::Parameter> speedparam;
    boost::optional<Spine::Parameter> uparam;
    boost::optional<Spine::Parameter> vparam;

    if (layer.direction)
      dirparam = TS::ParameterFactory::instance().parse(*layer.direction);
    if (layer.speed)
      speedparam = TS::ParameterFactory::instance().parse(*layer.speed);
    if (layer.u)
      uparam = TS::ParameterFactory::instance().parse(*layer.u);
    if (layer.v)
      vparam = TS::ParameterFactory::instance().parse(*layer.v);

    if (speedparam && !q->param(speedparam->number()))
      throw Fmi::Exception(
          BCP, "Parameter " + speedparam->name() + " not available in the arrow layer querydata");

    if (dirparam && !q->param(dirparam->number()))
      throw Fmi::Exception(
          BCP, "Parameter " + dirparam->name() + " not available in the arrow layer querydata");

    // WindUMS and WindVMS are metaparameters, cannot check their existence here

    // We may need to convert relative U/V components to true north

    std::shared_ptr<Fmi::CoordinateTransformation> uvtransformation;
    if (uparam && vparam && q->isRelativeUV())
      uvtransformation.reset(new Fmi::CoordinateTransformation("WGS84", q->SpatialReference()));

    // Generate the coordinates for the arrows

    const bool forecast_mode = true;
    auto points = layer.positions->getPoints(q, crs, box, forecast_mode);

    PointValues pointvalues;

    // Q API SUCKS
    boost::shared_ptr<Fmi::TimeFormatter> timeformatter(Fmi::TimeFormatter::create("iso"));
    boost::local_time::time_zone_ptr utc(new boost::local_time::posix_time_zone("UTC"));
    boost::local_time::local_date_time localdatetime(met_time, utc);
    std::string tmp;
    auto mylocale = std::locale::classic();
    NFmiPoint dummy;
    TS::LocalTimePoolPtr localTimePool = nullptr;

    if (speedparam && !q->param(speedparam->number()))
      throw Fmi::Exception(
          BCP, "Parameter " + speedparam->name() + " not available in the arrow layer querydata");

    if (dirparam && !q->param(dirparam->number()))
      throw Fmi::Exception(
          BCP, "Parameter " + dirparam->name() + " not available in the arrow layer querydata");

    for (const auto& point : points)
    {
      if (!layer.inside(box, point.x, point.y))
        continue;

      // printf("POS %d,%d  %f %f\n",point.x, point.y,point.latlon.X(), point.latlon.Y());

      // Arrow direction and speed
      double wdir = kFloatMissing;
      double wspd = 0;

      if (uparam && vparam)
      {
        Spine::Location loc(point.latlon.X(), point.latlon.Y());

        auto up = Engine::Querydata::ParameterOptions(*uparam,
                                                      tmp,
                                                      loc,
                                                      tmp,
                                                      tmp,
                                                      *timeformatter,
                                                      tmp,
                                                      tmp,
                                                      mylocale,
                                                      tmp,
                                                      false,
                                                      dummy,
                                                      dummy,
                                                      localTimePool);
        auto uresult = q->value(up, localdatetime);

        auto vp = Engine::Querydata::ParameterOptions(*vparam,
                                                      tmp,
                                                      loc,
                                                      tmp,
                                                      tmp,
                                                      *timeformatter,
                                                      tmp,
                                                      tmp,
                                                      mylocale,
                                                      tmp,
                                                      false,
                                                      dummy,
                                                      dummy,
                                                      localTimePool);
        auto vresult = q->value(vp, localdatetime);

        if (boost::get<double>(&uresult) != nullptr && boost::get<double>(&vresult) != nullptr)
        {
          auto uspd = *boost::get<double>(&uresult);
          auto vspd = *boost::get<double>(&vresult);

          if (uspd != kFloatMissing && vspd != kFloatMissing)
          {
            wspd = sqrt(uspd * uspd + vspd * vspd);
            if (uspd != 0 || vspd != 0)
            {
              // Note: qengine fixes orientation automatically
              wdir = fmod(180 + 180 / pi * atan2(uspd, vspd), 360);
            }
          }
        }
      }
      else
      {
        q->param(dirparam->number());
        wdir = q->interpolate(point.latlon, met_time, 180);
        if (speedparam)
        {
          q->param(speedparam->number());
          wspd = q->interpolate(point.latlon, met_time, 180);
        }
      }

      // Skip points with invalid values
      if (wdir == kFloatMissing || wspd == kFloatMissing)
        continue;

      WindArrowValue value{point, wdir, wspd};
      pointvalues.push_back(value);
    }

    return pointvalues;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "ArrowLayer failed to read observations from the database");
  }
}  // namespace Dali

PointValues read_gridForecasts(const ArrowLayer& layer,
                               const Engine::Grid::Engine* gridEngine,
                               QueryServer::Query& query,
                               boost::optional<std::string> dirParam,
                               boost::optional<std::string> speedParam,
                               boost::optional<std::string> uParam,
                               boost::optional<std::string> vParam,
                               const Fmi::SpatialReference& crs,
                               const Fmi::Box& box,
                               const boost::posix_time::time_period& /* time_period */)
{
  try
  {
    if (!gridEngine || !gridEngine->isEnabled())
      throw Fmi::Exception(BCP, "The grid-engine is disabled!");

    // Generate the coordinates for the symbols

    // const bool forecast_mode = true;
    // auto points = layer.positions->getPoints(nullptr, crs, box, forecast_mode);

    PointValues pointvalues;

    int width = 0;
    int height = 0;
    int originalWidth = 0;
    int originalHeight = 0;
    int relativeUV = 0;

    const char* widthStr = query.mAttributeList.getAttributeValue("grid.width");
    const char* heightStr = query.mAttributeList.getAttributeValue("grid.height");
    const char* originalCrs = query.mAttributeList.getAttributeValue("grid.original.crs");
    const char* originalRelativeUVStr =
        query.mAttributeList.getAttributeValue("grid.original.relativeUV");
    const char* originalWidthStr = query.mAttributeList.getAttributeValue("grid.original.width");
    const char* originalHeightStr = query.mAttributeList.getAttributeValue("grid.original.height");

    if (widthStr)
      width = Fmi::stoi(widthStr);

    if (heightStr)
      height = Fmi::stoi(heightStr);

    if (originalRelativeUVStr)
      relativeUV = Fmi::stoi(originalRelativeUVStr);

    if (originalWidthStr)
      originalWidth = Fmi::stoi(originalWidthStr);

    if (originalHeightStr)
      originalHeight = Fmi::stoi(originalHeightStr);

    T::ParamValue_vec* dirValues = nullptr;
    T::ParamValue_vec* speedValues = nullptr;
    T::ParamValue_vec* vValues = nullptr;
    T::ParamValue_vec* uValues = nullptr;
    uint originalGeometryId = 0;

    for (const auto& param : query.mQueryParameterList)
    {
      for (const auto& val : param.mValueList)
      {
        if (!val->mValueVector.empty())
        {
          originalGeometryId = val->mGeometryId;

          if (dirParam && param.mParameterKey == *dirParam)
            dirValues = &val->mValueVector;
          else if (speedParam && param.mParameterKey == *speedParam)
            speedValues = &val->mValueVector;
          else if (vParam && param.mParameterKey == *vParam)
            vValues = &val->mValueVector;
          else if (uParam && param.mParameterKey == *uParam)
            uValues = &val->mValueVector;
        }
      }
    }

    auto points = layer.positions->getPoints(
        originalCrs, originalWidth, originalHeight, originalGeometryId, crs, box);

    if (dirValues && !dirValues->empty())
    {
      for (const auto& point : points)
      {
        double wdir = ParamValueMissing;
        double wspeed = 0;
        if (layer.inside(box, point.x, point.y))
        {
          size_t pos = (height - point.y - 1) * width + point.x;

          if (pos < dirValues->size())
          {
            wdir = (*dirValues)[pos];
            if (speedValues)
              wspeed = (*speedValues)[pos];
            else
              wspeed = 10;

            if (wdir != ParamValueMissing && wspeed != ParamValueMissing)
            {
              WindArrowValue value{point, wdir, wspeed};
              pointvalues.push_back(value);
              // printf("POS %d,%d  %f %f\n",point.x, point.y,point.latlon.X(), point.latlon.Y());
            }
          }
        }
      }
      return pointvalues;
    }

    if (uValues && vValues && uValues->size() == vValues->size())
    {
      // We may need to convert relative U/V components to true north
      std::shared_ptr<Fmi::CoordinateTransformation> uvtransformation;

      if (relativeUV && originalCrs)
        uvtransformation.reset(new Fmi::CoordinateTransformation("WGS84", originalCrs));

      for (const auto& point : points)
      {
        double wdir = ParamValueMissing;
        double wspeed = 0;
        if (layer.inside(box, point.x, point.y))
        {
          size_t pos = (height - point.y - 1) * width + point.x;

          if (pos < vValues->size())
          {
            double v = (*vValues)[pos];
            double u = (*uValues)[pos];
            if (u != ParamValueMissing && v != ParamValueMissing)
            {
              wspeed = sqrt(u * u + v * v);

              if (!uvtransformation)
                wdir = fmod(180 + 180 / pi * atan2(u, v), 360);
              else
              {
                auto rot =
                    Fmi::OGR::gridNorth(*uvtransformation, point.latlon.X(), point.latlon.Y());
                if (!rot)
                  continue;
                wdir = fmod(180 - *rot + 180 / pi * atan2(u, v), 360);
              }
            }

            if (wdir != ParamValueMissing && wspeed != ParamValueMissing)
            {
              WindArrowValue value{point, wdir, wspeed};
              pointvalues.push_back(value);
            }
          }
        }
      }
      return pointvalues;
    }

    return pointvalues;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "ArrowLayer failed to read observations from the database");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Observation reader
 */
// ----------------------------------------------------------------------

#ifndef WITHOUT_OBSERVATION

PointValues read_all_observations(const ArrowLayer& layer,
                                  State& state,
                                  const Fmi::SpatialReference& crs,
                                  const Fmi::Box& box,
                                  const boost::posix_time::time_period& valid_time_period,
                                  const Fmi::CoordinateTransformation& transformation)
{
  try
  {
    Engine::Observation::Settings settings;
    settings.allplaces = false;
    settings.stationtype = *layer.producer;
    settings.latest = true;
    settings.timezone = "UTC";
    settings.numberofstations = 1;
    settings.maxdistance = layer.maxdistance * 1000;  // obsengine uses meters
    settings.localTimePool = state.getLocalTimePool();

    settings.timestep = 0;

    settings.starttimeGiven = true;

    settings.starttime = valid_time_period.begin();
    settings.endtime = valid_time_period.end();

    auto& obsengine = state.getObsEngine();
    settings.parameters.push_back(TS::makeParameter("stationlon"));
    settings.parameters.push_back(TS::makeParameter("stationlat"));

    bool use_uv_components = (layer.u && layer.v);

    if (use_uv_components)
    {
      settings.parameters.push_back(TS::makeParameter(*layer.u));
      settings.parameters.push_back(TS::makeParameter(*layer.v));
    }
    else
    {
      settings.parameters.push_back(TS::makeParameter(*layer.direction));
      if (layer.speed)
        settings.parameters.push_back(TS::makeParameter(*layer.speed));
      else
        settings.parameters.push_back(TS::makeParameter("WindSpeedMS"));
    }

    // Request intersection parameters too - if any
    auto iparams = layer.positions->intersections.parameters();

    int firstextraparam =
        settings.parameters.size();  // which column holds the first extra parameter

    for (const auto& extraparam : iparams)
      settings.parameters.push_back(TS::makeParameter(extraparam));

    // Coordinates or bounding box

    Engine::Observation::StationSettings stationSettings;
    stationSettings.bounding_box_settings = layer.getClipBoundingBox(box, crs);
    settings.taggedFMISIDs = obsengine.translateToFMISID(
        settings.starttime, settings.endtime, settings.stationtype, stationSettings);

    auto result = obsengine.values(settings);

    // Build the pointvalues

    if (!result)
      return {};

    const auto& values = *result;
    if (values.empty())
      return {};

    // We accept only the newest observation for each interval
    // obsengine returns the data sorted by fmisid and by time

    PointValues pointvalues;

    for (std::size_t row = 0; row < values[0].size(); ++row)
    {
      double lon = get_double(values.at(0).at(row));
      double lat = get_double(values.at(1).at(row));

      double wdir = kFloatMissing;
      double wspd = kFloatMissing;
      if (!use_uv_components)
      {
        wdir = get_double(values.at(2).at(row));
        wspd = get_double(values.at(3).at(row));
      }
      else
      {
        double uspd = get_double(values.at(2).at(row));
        double vspd = get_double(values.at(3).at(row));

        if (uspd != kFloatMissing && vspd != kFloatMissing)
        {
          wspd = sqrt(uspd * uspd + vspd * vspd);
          if (uspd != 0 || vspd != 0)
            wdir = fmod(180 + 180 / pi * atan2(uspd, vspd), 360);
        }
      }

      // Collect extra values used for filtering the input

      Intersections::IntersectValues ivalues;

      for (std::size_t i = 0; i < iparams.size(); i++)
        ivalues[iparams.at(i)] = get_double(values.at(firstextraparam + i).at(row));

      // Convert latlon to world coordinate if needed

      double x = lon;
      double y = lat;

      if (!crs.isGeographic())
        if (!transformation.transform(x, y))
          continue;

      // To pixel coordinate
      box.transform(x, y);

      // Skip if not inside desired area
      if (!layer.inside(box, x, y))
        continue;

      // Skip if not inside/outside desired shapes or limits of other parameters
      if (!layer.positions->inside(lon, lat, ivalues))
        continue;

      int xpos = lround(x);
      int ypos = lround(y);

      Positions::Point point{xpos, ypos, NFmiPoint(lon, lat)};
      WindArrowValue pv{point, wdir, wspd};
      pointvalues.push_back(pv);
    }

    return pointvalues;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "ArrowLayer failed to read observations from the database");
  }
}

PointValues read_station_observations(const ArrowLayer& layer,
                                      State& state,
                                      const Fmi::SpatialReference& crs,
                                      const Fmi::Box& box,
                                      const boost::posix_time::time_period& valid_time_period,
                                      const Fmi::CoordinateTransformation& transformation)
{
  try
  {
    Engine::Observation::Settings settings;
    settings.allplaces = false;
    settings.stationtype = *layer.producer;
    settings.latest = true;
    settings.timezone = "UTC";
    settings.numberofstations = 1;
    settings.maxdistance = layer.maxdistance * 1000;  // obsengine uses meters
    settings.localTimePool = state.getLocalTimePool();

    // settings.timestep = ?;

    settings.starttimeGiven = true;

    settings.starttime = valid_time_period.begin();
    settings.endtime = valid_time_period.end();

    auto& obsengine = state.getObsEngine();
    settings.parameters.push_back(TS::makeParameter("stationlon"));
    settings.parameters.push_back(TS::makeParameter("stationlat"));

    bool use_uv_components = (layer.u && layer.v);

    if (use_uv_components)
    {
      settings.parameters.push_back(TS::makeParameter(*layer.u));
      settings.parameters.push_back(TS::makeParameter(*layer.v));
    }
    else
    {
      settings.parameters.push_back(TS::makeParameter(*layer.direction));
      if (layer.speed)
        settings.parameters.push_back(TS::makeParameter(*layer.speed));
      else
        settings.parameters.push_back(TS::makeParameter("WindSpeedMS"));
    }

    // Request intersection parameters too - if any
    auto iparams = layer.positions->intersections.parameters();

    int firstextraparam =
        settings.parameters.size();  // which column holds the first extra parameter

    for (const auto& extraparam : iparams)
      settings.parameters.push_back(TS::makeParameter(extraparam));

    if (!layer.positions)
      throw Fmi::Exception(BCP, "Positions not defined for station-layout of numbers");

    // We must read the stations one at a time to preserve dx,dy values
    PointValues pointvalues;

    for (const auto& station : layer.positions->stations.stations)
    {
      // Copy Oracle settings
      auto opts = settings;

      Engine::Observation::StationSettings stationSettings;

      // Use an unique ID first if specified, ignoring the coordinates even if set
      if (station.fmisid)
        stationSettings.fmisids.push_back(*station.fmisid);
      else if (station.wmo)
        stationSettings.wmos.push_back(*station.wmo);
      else if (station.lpnn)
        stationSettings.lpnns.push_back(*station.lpnn);
      else if (station.geoid)
      {
        stationSettings.geoid_settings.geoids.push_back(*station.geoid);
        stationSettings.geoid_settings.maxdistance = opts.maxdistance;
        stationSettings.geoid_settings.numberofstations = opts.numberofstations;
        stationSettings.geoid_settings.language = opts.language;
      }
      else if (station.longitude && station.latitude)
      {
        stationSettings.nearest_station_settings.emplace_back(
            *station.longitude, *station.latitude, opts.maxdistance, opts.numberofstations, "");
      }
      else
        throw Fmi::Exception(BCP, "Station ID or coordinate missing");

      opts.taggedFMISIDs = obsengine.translateToFMISID(
          settings.starttime, settings.endtime, settings.stationtype, stationSettings);

      if (opts.taggedFMISIDs.empty())
        continue;

      auto result = obsengine.values(opts);

      if (!result || result->empty() || (*result)[0].empty())
        continue;

      const auto& values = *result;

      // We accept only the newest observation for each interval
      // obsengine returns the data sorted by fmisid and by time

      const int row = 0;

      double lon = get_double(values.at(0).at(row));
      double lat = get_double(values.at(1).at(row));

      double wdir = kFloatMissing;
      double wspd = kFloatMissing;
      if (!use_uv_components)
      {
        wdir = get_double(values.at(2).at(row));
        wspd = get_double(values.at(3).at(row));
      }
      else
      {
        double uspd = get_double(values.at(2).at(row));
        double vspd = get_double(values.at(3).at(row));

        if (uspd != kFloatMissing && vspd != kFloatMissing)
        {
          wspd = sqrt(uspd * uspd + vspd * vspd);
          if (uspd != 0 || vspd != 0)
            wdir = fmod(180 + 180 / pi * atan2(uspd, vspd), 360);
        }
      }

      // Collect extra values used for filtering the input

      Intersections::IntersectValues ivalues;

      for (std::size_t i = 0; i < iparams.size(); i++)
        ivalues[iparams.at(i)] = get_double(values.at(firstextraparam + i).at(row));

      // Convert latlon to world coordinate if needed

      double x = lon;
      double y = lat;

      if (!crs.isGeographic())
        if (!transformation.transform(x, y))
          continue;

      // To pixel coordinate
      box.transform(x, y);

      // Skip if not inside desired area
      if (!layer.inside(box, x, y))
        continue;

      // Skip if not inside/outside desired shapes or limits of other parameters
      if (!layer.positions->inside(lon, lat, ivalues))
        continue;

      int xpos = lround(x);
      int ypos = lround(y);

      int deltax = (station.dx ? *station.dx : 0);
      int deltay = (station.dy ? *station.dy : 0);

      Positions::Point point{xpos, ypos, NFmiPoint(lon, lat), deltax, deltay};
      WindArrowValue pv{point, wdir, wspd};
      pointvalues.push_back(pv);
    }

    return pointvalues;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "ArrowLayer failed to read observations from the database");
  }
}

PointValues read_latlon_observations(const ArrowLayer& layer,
                                     State& state,
                                     const Fmi::SpatialReference& crs,
                                     const Fmi::Box& box,
                                     const boost::posix_time::time_period& valid_time_period,
                                     const Fmi::CoordinateTransformation& transformation,
                                     const Positions::Points& points)
{
  try
  {
    Engine::Observation::Settings settings;
    settings.allplaces = false;
    settings.stationtype = *layer.producer;
    settings.timezone = "UTC";
    settings.numberofstations = 1;                    // we need only the nearest station
    settings.latest = true;                           // we need only the newest observation
    settings.maxdistance = layer.maxdistance * 1000;  // obsengine uses meters
    settings.localTimePool = state.getLocalTimePool();

    settings.starttimeGiven = true;

    settings.starttime = valid_time_period.begin();
    settings.endtime = valid_time_period.end();

    auto& obsengine = state.getObsEngine();
    settings.parameters.push_back(TS::makeParameter("stationlon"));
    settings.parameters.push_back(TS::makeParameter("stationlat"));
    settings.parameters.push_back(TS::makeParameter("fmisid"));

    bool use_uv_components = (layer.u && layer.v);

    if (use_uv_components)
    {
      settings.parameters.push_back(TS::makeParameter(*layer.u));
      settings.parameters.push_back(TS::makeParameter(*layer.v));
    }
    else
    {
      settings.parameters.push_back(TS::makeParameter(*layer.direction));
      if (layer.speed)
        settings.parameters.push_back(TS::makeParameter(*layer.speed));
      else
        settings.parameters.push_back(TS::makeParameter("WindSpeedMS"));
    }

    // Request intersection parameters too - if any
    auto iparams = layer.positions->intersections.parameters();

    int firstextraparam =
        settings.parameters.size();  // which column holds the first extra parameter

    for (const auto& extraparam : iparams)
      settings.parameters.push_back(TS::makeParameter(extraparam));

    // Process the points one at a time so that we can assign dx,dy values to them

    PointValues pointvalues;

    // We do not use the same station twice
    std::set<int> used_fmisids;

    for (const auto& point : points)
    {
      // Copy common Oracle settings
      auto opts = settings;

      Engine::Observation::StationSettings stationSettings;
      stationSettings.nearest_station_settings.emplace_back(
          point.latlon.X(), point.latlon.Y(), opts.maxdistance, opts.numberofstations, "");

      opts.taggedFMISIDs = obsengine.translateToFMISID(
          settings.starttime, settings.endtime, settings.stationtype, stationSettings);

      if (opts.taggedFMISIDs.empty())
        continue;

      auto result = obsengine.values(opts);

      if (!result || result->empty() || (*result)[0].empty())
        continue;

      const auto& values = *result;

      // We accept only the newest observation for each interval
      // obsengine returns the data sorted by fmisid and by time

      const int row = 0;

      double lon = get_double(values.at(0).at(row));
      double lat = get_double(values.at(1).at(row));
      int fmisid = get_fmisid(values.at(2).at(row));

      if (used_fmisids.find(fmisid) != used_fmisids.end())
        continue;
      used_fmisids.insert(fmisid);

      double wdir = kFloatMissing;
      double wspd = kFloatMissing;
      if (!use_uv_components)
      {
        wdir = get_double(values.at(3).at(row));
        wspd = get_double(values.at(4).at(row));
      }
      else
      {
        double uspd = get_double(values.at(3).at(row));
        double vspd = get_double(values.at(4).at(row));

        if (uspd != kFloatMissing && vspd != kFloatMissing)
        {
          wspd = sqrt(uspd * uspd + vspd * vspd);
          if (uspd != 0 || vspd != 0)
            wdir = fmod(180 + 180 / pi * atan2(uspd, vspd), 360);
        }
      }

      // Collect extra values used for filtering the input

      Intersections::IntersectValues ivalues;

      for (std::size_t i = 0; i < iparams.size(); i++)
        ivalues[iparams.at(i)] = get_double(values.at(firstextraparam + i).at(row));

      // Convert latlon to world coordinate if needed

      double x = lon;
      double y = lat;

      if (!crs.isGeographic())
        if (!transformation.transform(x, y))
          continue;

      // To pixel coordinate
      box.transform(x, y);

      // Skip if not inside desired area
      if (!layer.inside(box, x, y))
        continue;

      // Skip if not inside/outside desired shapes or limits of other parameters
      if (!layer.positions->inside(lon, lat, ivalues))
        continue;

      int xpos = lround(x);
      int ypos = lround(y);

      Positions::Point pp{xpos, ypos, NFmiPoint(lon, lat), point.dx, point.dy};
      WindArrowValue pv{pp, wdir, wspd};
      pointvalues.push_back(pv);
    }

    return pointvalues;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "ArrowLayer failed to read observations from the database");
  }
}

PointValues read_observations(const ArrowLayer& layer,
                              State& state,
                              const Fmi::SpatialReference& crs,
                              const Fmi::Box& box,
                              const boost::posix_time::time_period& valid_time_period)
{
  try
  {
    // Create the coordinate transformation from image world coordinates
    // to WGS84 coordinates

    Fmi::CoordinateTransformation transformation("WGS84", crs);

    if (Layer::isFlashOrMobileProducer(*layer.producer))
      throw Fmi::Exception(BCP, "Cannot use flash or mobile producer in ArrowLayer");

    if (layer.positions->layout == Positions::Layout::Station)
      return read_station_observations(layer, state, crs, box, valid_time_period, transformation);

    Engine::Querydata::Q q;
    const bool forecast_mode = false;
    auto points = layer.positions->getPoints(q, crs, box, forecast_mode);

    if (!points.empty())
      return read_latlon_observations(
          layer, state, crs, box, valid_time_period, transformation, points);

    return read_all_observations(layer, state, crs, box, valid_time_period, transformation);
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "ArrowLayer failed to read observations from the database");
  }
}
#endif

// ----------------------------------------------------------------------
/*!
 * \brief Initialize from JSON
 */
// ----------------------------------------------------------------------

void ArrowLayer::init(const Json::Value& theJson,
                      const State& theState,
                      const Config& theConfig,
                      const Properties& theProperties)
{
  try
  {
    if (!theJson.isObject())
      throw Fmi::Exception(BCP, "Arrow-layer JSON is not a JSON object");

    Layer::init(theJson, theState, theConfig, theProperties);

    // Extract member values

    Json::Value nulljson;

    auto json = theJson.get("direction", nulljson);
    if (!json.isNull())
      direction = json.asString();

    json = theJson.get("speed", nulljson);
    if (!json.isNull())
      speed = json.asString();

    json = theJson.get("u", nulljson);
    if (!json.isNull())
      u = json.asString();

    json = theJson.get("v", nulljson);
    if (!json.isNull())
      v = json.asString();

    json = theJson.get("symbol", nulljson);
    if (!json.isNull())
      symbol = json.asString();

    json = theJson.get("scale", nulljson);
    if (!json.isNull())
      scale = json.asDouble();

    json = theJson.get("southflop", nulljson);
    if (!json.isNull())
      southflop = json.asBool();

    json = theJson.get("northflop", nulljson);
    if (!json.isNull())
      northflop = json.asBool();

    json = theJson.get("flip", nulljson);
    if (!json.isNull())
      flip = json.asBool();

    json = theJson.get("positions", nulljson);
    if (!json.isNull())
    {
      positions = Positions{};
      positions->init(json, theConfig);
    }

    json = theJson.get("dx", nulljson);
    if (!json.isNull())
      dx = json.asInt();

    json = theJson.get("dy", nulljson);
    if (!json.isNull())
      dy = json.asInt();

    json = theJson.get("minvalues", nulljson);
    if (!json.isNull())
      minvalues = json.asInt();

    json = theJson.get("maxdistance", nulljson);
    if (!json.isNull())
      maxdistance = json.asDouble();

    json = theJson.get("unit_conversion", nulljson);
    if (!json.isNull())
      unit_conversion = json.asString();

    json = theJson.get("multiplier", nulljson);
    if (!json.isNull())
      multiplier = json.asDouble();

    json = theJson.get("offset", nulljson);
    if (!json.isNull())
      offset = json.asDouble();

    json = theJson.get("minrotationspeed", nulljson);
    if (!json.isNull())
      minrotationspeed = json.asDouble();

    json = theJson.get("arrows", nulljson);
    if (!json.isNull())
      Spine::JSON::extract_array("arrows", arrows, json, theConfig);

    point_value_options.init(theJson);
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Generate the layer details into the template hash
 */
// ----------------------------------------------------------------------

void ArrowLayer::generate(CTPP::CDT& theGlobals, CTPP::CDT& theLayersCdt, State& theState)
{
  try
  {
    // if (!validLayer(theState))
    //  return;

    if (source && *source == "grid")
      generate_gridEngine(theGlobals, theLayersCdt, theState);
    else
      generate_qEngine(theGlobals, theLayersCdt, theState);
  }
  catch (...)
  {
    Fmi::Exception exception(BCP, "Operation failed!", nullptr);
    if (producer)
      exception.addParameter("Producer", *producer);
    if (direction)
      exception.addParameter("Direction", *direction);
    if (speed)
      exception.addParameter("Speed", *speed);
    if (v)
      exception.addParameter("V", *v);
    if (u)
      exception.addParameter("U", *u);
    throw exception;
  }
}

void ArrowLayer::generate_gridEngine(CTPP::CDT& theGlobals,
                                     CTPP::CDT& theLayersCdt,
                                     State& theState)
{
  try
  {
    const auto* gridEngine = theState.getGridEngine();
    if (!gridEngine || !gridEngine->isEnabled())
      throw Fmi::Exception(BCP, "The grid-engine is disabled!");

    // Time execution

    std::string report = "ArrowLayer::generate finished in %t sec CPU, %w sec real\n";
    boost::movelib::unique_ptr<boost::timer::auto_cpu_timer> timer;
    if (theState.useTimer())
      timer = boost::movelib::make_unique<boost::timer::auto_cpu_timer>(2, report);

    // A symbol must be defined either globally or for speed ranges

    if (!symbol && arrows.empty())
      throw Fmi::Exception(
          BCP, "Must define arrow with 'symbol' or 'arrows' to define the symbol for arrows");

    // Make sure position generation is initialized

    if (!positions)
      positions = Positions{};

    // Add layer margins to position generation
    positions->addMargins(xmargin, ymargin);

    // Establish the parameters

    std::vector<std::string> paramList;

    boost::optional<std::string> dirparam;
    boost::optional<std::string> speedparam;
    boost::optional<std::string> uparam;
    boost::optional<std::string> vparam;

    if (direction)
      paramList.push_back(*direction);
    if (speed)
      paramList.push_back(*speed);
    if (u)
      paramList.push_back(*u);
    if (v)
      paramList.push_back(*v);

    std::shared_ptr<QueryServer::Query> originalGridQuery(new QueryServer::Query());
    QueryServer::QueryConfigurator queryConfigurator;
    T::AttributeList attributeList;

    std::string producerName = gridEngine->getProducerName(*producer);

    auto valid_time_period = getValidTimePeriod();

    // Do this conversion just once for speed:
    NFmiMetTime met_time = valid_time_period.begin();

    std::string wkt = *projection.crs;
    if (wkt != "data")
    {
      // Getting the bounding box and the WKT of the requested projection.

      if (strstr(wkt.c_str(), "+proj") != wkt.c_str())
      {
        auto crs = projection.getCRS();
        char* out = nullptr;
        crs.get()->exportToWkt(&out);
        wkt = out;
        CPLFree(out);
      }

      // std::cout << wkt << "\n";

      // Adding the bounding box information into the query.

      const auto& box = projection.getBox();
      const auto clipbox = getClipBox(box);

      auto bl = projection.bottomLeftLatLon();
      auto tr = projection.topRightLatLon();
      auto bbox = fmt::format("{},{},{},{}", bl.X(), bl.Y(), tr.X(), tr.Y());
      originalGridQuery->mAttributeList.addAttribute("grid.llbox", bbox);

      bbox = fmt::format("{},{},{},{}", clipbox.xmin(), clipbox.ymin(), clipbox.xmax(), clipbox.ymax());
      //bbox = fmt::format("{},{},{},{}", box.xmin(), box.ymin(), box.xmax(), box.ymax());
      originalGridQuery->mAttributeList.addAttribute("grid.bbox", bbox);
    }
    else
    {
      // The requested projection is the same as the projection of the requested data. This means
      // that we we do not know the actual projection yet and we have to wait that the grid-engine
      // delivers us the requested data and the projection information of the current data.
    }

    // Adding parameter information into the query.

    char paramBuf[1000];
    char* p = paramBuf;

    for (auto& pName : paramList)
    {
      auto pos = pName.find(".raw");
      if (pos != std::string::npos)
      {
        attributeList.addAttribute("areaInterpolationMethod",
                                   std::to_string(T::AreaInterpolationMethod::Linear));
        pName.erase(pos, 4);
      }

      std::string param = gridEngine->getParameterString(producerName, pName);

      if (!projection.projectionParameter)
        projection.projectionParameter = param;

      if (param == pName && originalGridQuery->mProducerNameList.empty())
      {
        gridEngine->getProducerNameList(producerName, originalGridQuery->mProducerNameList);
        if (originalGridQuery->mProducerNameList.empty())
          originalGridQuery->mProducerNameList.push_back(producerName);
      }

      if (p != paramBuf)
        p += sprintf(p, ",");

      p += sprintf(p, "%s", param.c_str());
    }

    attributeList.addAttribute("param", paramBuf);

    std::string forecastTime = Fmi::to_iso_string(*time);
    attributeList.addAttribute("startTime", forecastTime);
    attributeList.addAttribute("endTime", forecastTime);
    attributeList.addAttribute("timelist", forecastTime);
    attributeList.addAttribute("timezone", "UTC");

    if (origintime)
      attributeList.addAttribute("analysisTime", Fmi::to_iso_string(*origintime));

    // Tranforming information from the attribute list into the query object.
    queryConfigurator.configure(*originalGridQuery, attributeList);

    // Filling information into the query object.

    for (auto& param : originalGridQuery->mQueryParameterList)
    {
      param.mLocationType = QueryServer::QueryParameter::LocationType::Geometry;
      param.mType = QueryServer::QueryParameter::Type::Vector;
      param.mFlags = QueryServer::QueryParameter::Flags::ReturnCoordinates;

      if (geometryId)
        param.mGeometryId = *geometryId;

      if (levelId)
        param.mParameterLevelId = *levelId;

      if (level)
        param.mParameterLevel = C_INT(*level);

      if (forecastType)
        param.mForecastType = C_INT(*forecastType);

      if (forecastNumber)
        param.mForecastNumber = C_INT(*forecastNumber);
    }

    originalGridQuery->mSearchType = QueryServer::Query::SearchType::TimeSteps;
    originalGridQuery->mAttributeList.addAttribute("grid.crs", wkt);

    if (projection.size && *projection.size > 0)
    {
      originalGridQuery->mAttributeList.addAttribute("grid.size", std::to_string(*projection.size));
    }
    else
    {
      if (projection.xsize)
        originalGridQuery->mAttributeList.addAttribute("grid.width",
                                                       std::to_string(*projection.xsize));

      if (projection.ysize)
        originalGridQuery->mAttributeList.addAttribute("grid.height",
                                                       std::to_string(*projection.ysize));
    }

    if (wkt == "data" && projection.x1 && projection.y1 && projection.x2 && projection.y2)
    {
      auto bbox = fmt::format(
          "{},{},{},{}", *projection.x1, *projection.y1, *projection.x2, *projection.y2);
      originalGridQuery->mAttributeList.addAttribute("grid.bbox", bbox);
    }

    // The Query object before the query execution.
    // query.print(std::cout,0,0);

    // Executing the query.
    std::shared_ptr<QueryServer::Query> query = gridEngine->executeQuery(originalGridQuery);

    // The Query object after the query execution.
    // query.print(std::cout,0,0);

    // Extracting the projection information from the query result.

    if ((projection.size && *projection.size > 0) || (!projection.xsize && !projection.ysize))
    {
      const char* widthStr = query->mAttributeList.getAttributeValue("grid.width");
      const char* heightStr = query->mAttributeList.getAttributeValue("grid.height");

      if (widthStr != nullptr)
        projection.xsize = Fmi::stoi(widthStr);

      if (heightStr != nullptr)
        projection.ysize = Fmi::stoi(heightStr);
    }

    if (!projection.xsize && !projection.ysize)
      throw Fmi::Exception(BCP, "The projection size is unknown!");

    if (*projection.crs == "data")
    {
      const char* crsStr = query->mAttributeList.getAttributeValue("grid.crs");
      const char* proj4Str = query->mAttributeList.getAttributeValue("grid.proj4");
      if (proj4Str != nullptr && strstr(proj4Str, "+lon_wrap") != nullptr)
        crsStr = proj4Str;

      if (crsStr != nullptr)
      {
        projection.crs = crsStr;
        if (!projection.bboxcrs)
        {
          const char* bboxStr = query->mAttributeList.getAttributeValue("grid.bbox");
          if (bboxStr != nullptr)
          {
            std::vector<double> partList;
            splitString(bboxStr, ',', partList);

            if (partList.size() == 4)
            {
              projection.x1 = partList[0];
              projection.y1 = partList[1];
              projection.x2 = partList[2];
              projection.y2 = partList[3];
            }
          }
        }
      }
    }

    // Get projection details

    auto crs = projection.getCRS();
    const auto& box = projection.getBox();

    if (wkt == "data")
      return;

    // Initialize inside/outside shapes and intersection isobands

    positions->init(producer, projection, valid_time_period.begin(), theState);

    if (css)
    {
      std::string name = theState.getCustomer() + "/" + *css;
      theGlobals["css"][name] = theState.getStyle(*css);
    }

    // Clip if necessary

    addClipRect(theLayersCdt, theGlobals, box, theState);

    // Begin a G-group, put arrows into it as tags

    CTPP::CDT group_cdt(CTPP::CDT::HASH_VAL);
    group_cdt["start"] = "<g";
    group_cdt["end"] = "</g>";

    // Add layer attributes to the group, not to the arrows
    theState.addAttributes(theGlobals, group_cdt, attributes);

    // Establish the relevant numbers

    PointValues pointvalues = read_gridForecasts(
        *this, gridEngine, *query, direction, speed, u, v, crs, box, valid_time_period);

    // Coordinate transformation from WGS84 to output SRS so that we can rotate
    // winds according to map north

    Fmi::CoordinateTransformation transformation("WGS84", crs);

    // Alter units if requested

    if (!unit_conversion.empty())
    {
      auto conv = theState.getConfig().unitConversion(unit_conversion);
      multiplier = conv.multiplier;
      offset = conv.offset;
    }

    pointvalues = prioritize(pointvalues, point_value_options);

    // Render the collected values

    int valid_count = 0;

    for (const auto& pointvalue : pointvalues)
    {
      const auto& point = pointvalue.point;

      // Select arrow based on speed or U- and V-components, if available
      bool check_speeds = (!arrows.empty() && (speed || (u && v)));

      double wdir = pointvalue.direction;
      double wspd = pointvalue.speed;

      if (wdir == kFloatMissing)
        continue;

      if (check_speeds && wspd == kFloatMissing)
        continue;

      ++valid_count;

      // printf("POINT %d,%d %f,%f\n",point.x,point.y,wdir,wspd);

      // Unit transformation
      double xmultiplier = (multiplier ? *multiplier : 1.0);
      double xoffset = (offset ? *offset : 0.0);
      if (wspd != kFloatMissing)
        wspd = xmultiplier * wspd + xoffset;

      // Apply final rotation to output coordinate system
      auto fix = Fmi::OGR::gridNorth(transformation, point.latlon.X(), point.latlon.Y());
      if (!fix)
        continue;

      wdir = fmod(wdir + *fix, 360);

      // North wind blows, rotate 180 degrees
      double rotate = fmod(wdir + 180, 360);

      // Disable rotation for slow wind speeds if a limit is set
      int nrotate = lround(rotate);
      if (wspd != kFloatMissing && minrotationspeed && wspd < *minrotationspeed)
        nrotate = 0;

      CTPP::CDT tag_cdt(CTPP::CDT::HASH_VAL);
      tag_cdt["start"] = "<use";
      tag_cdt["end"] = "/>";

      // librsvg cannot handle scale + transform, must move former into latter

      boost::optional<double> rescale;

      // Determine the symbol to be used
      std::string iri;

      if (!check_speeds)
      {
        if (symbol)
          iri = *symbol;
      }
      else
      {
        auto selection = Select::attribute(arrows, wspd);
        if (selection)
        {
          if (selection->symbol)
            iri = *selection->symbol;
          else if (symbol)
            iri = *symbol;

          auto scaleattr = selection->attributes.remove("scale");
          if (scaleattr)
            rescale = Fmi::stod(*scaleattr);

          theState.addAttributes(theGlobals, tag_cdt, selection->attributes);
        }
      }

      if (!iri.empty())
      {
        std::string IRI = Iri::normalize(iri);
        bool flop =
            ((southflop && (point.latlon.Y() < 0)) || (northflop && (point.latlon.Y() > 0)));

        if (theState.addId(IRI))
          theGlobals["includes"][iri] = theState.getSymbol(iri);

        tag_cdt["attributes"]["xlink:href"] = "#" + IRI;

        // Using x and y attributes messes up rotation, hence we
        // must use the translate transformation instead.
        std::string transform;

        double yscale = (flip ? -1 : 1) * (scale ? *scale : 1.0);
        double xscale = (flop ? -yscale : yscale);

        if (rescale)
        {
          xscale *= *rescale;
          yscale *= *rescale;
        }

        int x = point.x + point.dx + (dx ? *dx : 0);
        int y = point.y + point.dy + (dy ? *dy : 0);

        // printf("-- POINT %d,%d %f,%f\n",x,y,wdir,wspd);

        if (nrotate == 0)
        {
          if (xscale == 1 && yscale == 1)
            transform = fmt::sprintf("translate(%d %d)", x, y);
          else if (xscale == yscale)
            transform = fmt::sprintf("translate(%d %d) scale(%g)", x, y, xscale);
          else
            transform = fmt::sprintf("translate(%d %d) scale(%g %g)", x, y, xscale, yscale);
        }
        else
        {
          if (xscale == 1 && yscale == 1)
            transform = fmt::sprintf("translate(%d %d) rotate(%d)", x, y, nrotate);
          else if (xscale == yscale)
            transform =
                fmt::sprintf("translate(%d %d) rotate(%d) scale(%g)", x, y, nrotate, xscale);
          else
            transform = fmt::sprintf(
                "translate(%d %d) rotate(%d) scale(%g %g)", x, y, nrotate, xscale, yscale);
        }

        tag_cdt["attributes"]["transform"] = transform;

        group_cdt["tags"].PushBack(tag_cdt);
      }
    }

    if (valid_count < minvalues)
      throw Fmi::Exception(BCP, "Too few valid values in arrow layer")
          .addParameter("valid values", std::to_string(valid_count))
          .addParameter("minimum count", std::to_string(minvalues));

    // We created only this one layer
    theLayersCdt.PushBack(group_cdt);
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

void ArrowLayer::generate_qEngine(CTPP::CDT& theGlobals, CTPP::CDT& theLayersCdt, State& theState)
{
  try
  {
    // Time execution

    std::string report = "ArrowLayer::generate finished in %t sec CPU, %w sec real\n";
    boost::movelib::unique_ptr<boost::timer::auto_cpu_timer> timer;
    if (theState.useTimer())
      timer = boost::movelib::make_unique<boost::timer::auto_cpu_timer>(2, report);

    // A symbol must be defined either globally or for speed ranges

    if (!symbol && arrows.empty())
      throw Fmi::Exception(
          BCP, "Must define arrow with 'symbol' or 'arrows' to define the symbol for arrows");

    // Establish the data

    bool use_observations = theState.isObservation(producer);
    Engine::Querydata::Q q = getModel(theState);

    // Make sure position generation is initialized

    if (!positions)
    {
      positions = Positions{};
      if (use_observations)
        positions->layout = Positions::Layout::Data;
    }

    // Add layer margins to position generation
    positions->addMargins(xmargin, ymargin);

    // Establish the valid time

    auto valid_time_period = getValidTimePeriod();

    // Establish the level

    if (level)
    {
      if (use_observations)
        throw std::runtime_error("Cannot set level value for observations in NumberLayer");

      bool match = false;
      for (q->resetLevel(); !match && q->nextLevel();)
        match = (q->levelValue() == *level);
      if (!match)
        throw Fmi::Exception(BCP, "Level value " + Fmi::to_string(*level) + " is not available");
    }

    // Get projection details

    projection.update(q);
    const auto& crs = projection.getCRS();
    const auto& box = projection.getBox();

    // Initialize inside/outside shapes and intersection isobands

    positions->init(producer, projection, valid_time_period.begin(), theState);

    // The parameters. TODO: Allow metaparameters, needs better Q API

    if ((u && (direction || speed)) || (v && (direction || speed)))
      throw Fmi::Exception(
          BCP, "ArrowLayer cannot define direction, speed and u- and v-components simultaneously");

    if ((u && !v) || (v && !u))
      throw Fmi::Exception(BCP, "ArrowLayer must define both U- and V-components");

    // Update the globals

    if (css)
    {
      std::string name = theState.getCustomer() + "/" + *css;
      theGlobals["css"][name] = theState.getStyle(*css);
    }

    // Clip if necessary

    addClipRect(theLayersCdt, theGlobals, box, theState);

    // Begin a G-group, put arrows into it as tags

    CTPP::CDT group_cdt(CTPP::CDT::HASH_VAL);
    group_cdt["start"] = "<g";
    group_cdt["end"] = "</g>";

    // Add layer attributes to the group, not to the arrows
    theState.addAttributes(theGlobals, group_cdt, attributes);

    // Establish the relevant numbers

    PointValues pointvalues;

    if (!use_observations)
      pointvalues = read_forecasts(*this, q, crs, box, valid_time_period);
#ifndef WITHOUT_OBSERVATION
    else
      pointvalues = read_observations(*this, theState, crs, box, valid_time_period);
#endif

    pointvalues = prioritize(pointvalues, point_value_options);

    // Coordinate transformation from WGS84 to output SRS so that we can rotate
    // winds according to map north

    Fmi::CoordinateTransformation transformation("WGS84", crs);

    // Alter units if requested

    if (!unit_conversion.empty())
    {
      auto conv = theState.getConfig().unitConversion(unit_conversion);
      multiplier = conv.multiplier;
      offset = conv.offset;
    }

    // Render the collected values

    int valid_count = 0;

    for (const auto& pointvalue : pointvalues)
    {
      const auto& point = pointvalue.point;

      // Select arrow based on speed or U- and V-components, if available
      bool check_speeds = (!arrows.empty() && (speed || (u && v)));

      double wdir = pointvalue.direction;
      double wspd = pointvalue.speed;

      if (wdir == kFloatMissing)
        continue;

      if (check_speeds && wspd == kFloatMissing)
        continue;

      ++valid_count;

      // Unit transformation
      double xmultiplier = (multiplier ? *multiplier : 1.0);
      double xoffset = (offset ? *offset : 0.0);
      if (wspd != kFloatMissing)
        wspd = xmultiplier * wspd + xoffset;

      // Apply final rotation to output coordinate system

      // TODO: Clean up the API on constness. GDAL is not properly const correct
      auto fix = Fmi::OGR::gridNorth(transformation, point.latlon.X(), point.latlon.Y());
      if (!fix)
        continue;
      wdir = fmod(wdir + *fix, 360);

      // North wind blows, rotate 180 degrees
      double rotate = fmod(wdir + 180, 360);

      // Disable rotation for slow wind speeds if a limit is set
      int nrotate = lround(rotate);
      if (wspd != kFloatMissing && minrotationspeed && wspd < *minrotationspeed)
        nrotate = 0;

      CTPP::CDT tag_cdt(CTPP::CDT::HASH_VAL);
      tag_cdt["start"] = "<use";
      tag_cdt["end"] = "/>";

      // librsvg cannot handle scale + transform, must move former into latter

      boost::optional<double> rescale;

      // Determine the symbol to be used
      std::string iri;

      if (!check_speeds)
      {
        if (symbol)
          iri = *symbol;
      }
      else
      {
        auto selection = Select::attribute(arrows, wspd);
        if (selection)
        {
          if (selection->symbol)
            iri = *selection->symbol;
          else if (symbol)
            iri = *symbol;

          auto scaleattr = selection->attributes.remove("scale");
          if (scaleattr)
            rescale = Fmi::stod(*scaleattr);

          theState.addAttributes(theGlobals, tag_cdt, selection->attributes);
        }
      }

      if (!iri.empty())
      {
        std::string IRI = Iri::normalize(iri);
        bool flop =
            ((southflop && (point.latlon.Y() < 0)) || (northflop && (point.latlon.Y() > 0)));

        if (theState.addId(IRI))
          theGlobals["includes"][iri] = theState.getSymbol(iri);

        tag_cdt["attributes"]["xlink:href"] = "#" + IRI;

        // Using x and y attributes messes up rotation, hence we
        // must use the translate transformation instead.
        std::string transform;

        double yscale = (flip ? -1 : 1) * (scale ? *scale : 1.0);
        double xscale = (flop ? -yscale : yscale);

        if (rescale)
        {
          xscale *= *rescale;
          yscale *= *rescale;
        }

        int x = point.x + point.dx + (dx ? *dx : 0);
        int y = point.y + point.dy + (dy ? *dy : 0);

        if (nrotate == 0)
        {
          if (xscale == 1 && yscale == 1)
            transform = fmt::sprintf("translate(%d %d)", x, y);
          else if (xscale == yscale)
            transform = fmt::sprintf("translate(%d %d) scale(%g)", x, y, xscale);
          else
            transform = fmt::sprintf("translate(%d %d) scale(%g %g)", x, y, xscale, yscale);
        }
        else
        {
          if (xscale == 1 && yscale == 1)
            transform = fmt::sprintf("translate(%d %d) rotate(%d)", x, y, nrotate);
          else if (xscale == yscale)
            transform =
                fmt::sprintf("translate(%d %d) rotate(%d) scale(%g)", x, y, nrotate, xscale);
          else
            transform = fmt::sprintf(
                "translate(%d %d) rotate(%d) scale(%g %g)", x, y, nrotate, xscale, yscale);
        }

        tag_cdt["attributes"]["transform"] = transform;

        group_cdt["tags"].PushBack(tag_cdt);
      }
    }

    if (valid_count < minvalues)
      throw Fmi::Exception(BCP, "Too few valid values in arrow layer")
          .addParameter("valid values", std::to_string(valid_count))
          .addParameter("minimum count", std::to_string(minvalues));

    // We created only this one layer
    theLayersCdt.PushBack(group_cdt);
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Extract information on used parameters
 */
// ----------------------------------------------------------------------

void ArrowLayer::addGridParameterInfo(ParameterInfos& infos, const State& theState) const
{
  if (theState.isObservation(producer))
    return;

  if (direction)
  {
    ParameterInfo info(*direction);
    info.producer = producer;
    info.level = level;
    add(infos, info);
  }
  if (speed)
  {
    ParameterInfo info(*speed);
    info.producer = producer;
    info.level = level;
    add(infos, info);
  }
  if (u)
  {
    ParameterInfo info(*u);
    info.producer = producer;
    info.level = level;
    add(infos, info);
  }
  if (v)
  {
    ParameterInfo info(*v);
    info.producer = producer;
    info.level = level;
    add(infos, info);
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Hash value for the layer
 */
// ----------------------------------------------------------------------

std::size_t ArrowLayer::hash_value(const State& theState) const
{
  try
  {
    // Disable caching of observation layers
    if (theState.isObservation(producer))
      return Fmi::bad_hash;

    auto hash = Layer::hash_value(theState);

    if (!(source && *source == "grid"))
    {
      auto q = getModel(theState);
      if (q)
        Fmi::hash_combine(hash, Engine::Querydata::hash_value(q));
    }

    Fmi::hash_combine(hash, Fmi::hash_value(direction));
    Fmi::hash_combine(hash, Fmi::hash_value(speed));
    Fmi::hash_combine(hash, Fmi::hash_value(u));
    Fmi::hash_combine(hash, Fmi::hash_value(v));
    Fmi::hash_combine(hash, Fmi::hash_value(unit_conversion));
    Fmi::hash_combine(hash, Fmi::hash_value(multiplier));
    Fmi::hash_combine(hash, Fmi::hash_value(offset));
    Fmi::hash_combine(hash, Fmi::hash_value(minrotationspeed));
    Fmi::hash_combine(hash, Dali::hash_symbol(symbol, theState));
    Fmi::hash_combine(hash, Fmi::hash_value(scale));
    Fmi::hash_combine(hash, Fmi::hash_value(southflop));
    Fmi::hash_combine(hash, Fmi::hash_value(northflop));
    Fmi::hash_combine(hash, Fmi::hash_value(flip));
    Fmi::hash_combine(hash, Dali::hash_value(positions, theState));
    Fmi::hash_combine(hash, Fmi::hash_value(dx));
    Fmi::hash_combine(hash, Fmi::hash_value(dy));
    Fmi::hash_combine(hash, Fmi::hash_value(minvalues));
    Fmi::hash_combine(hash, Fmi::hash_value(maxdistance));
    Fmi::hash_combine(hash, Dali::hash_value(arrows, theState));
    return hash;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

}  // namespace Dali
}  // namespace Plugin
}  // namespace SmartMet


text:
class NewFolderCommand :
	public CFolderViewCommand
{
	CFolderViewImplFolder *m_pFolderView;
public:
	NewFolderCommand(FVCOMMANDITEM *pfvci, CFolderViewImplFolder *pFolderView);
	IFACEMETHODIMP Invoke(IShellItemArray *psiItemArray, IBindCtx *pbc);
	~NewFolderCommand();
};


text:
package lr.core;

import org.apache.log4j.Logger;
import java.util.*;

/**
 * Created by luca on 24/02/16.
 */

public class ConsistentHash<T> {
    private static final Logger LOG = Logger.getLogger(ConsistentHash.class);

    private TreeMap<Long, T> _map;
    private int _replication;
    private Helper.IHash _hash;
    private final static int default_replication = 3;

    public ConsistentHash() {
        this(default_replication, Helper::MD5ToLong);
    }

    public ConsistentHash(int replication) {
        this(replication, Helper::MD5ToLong);
    }

    public ConsistentHash(int replication, Helper.IHash f) {
        _replication = replication;
        _map = new TreeMap<>();
        _hash = f;
    }

    public ConsistentHash(Collection<T> list, int replication) {
        this(replication);
        list.forEach(this::add);
    }

    public ConsistentHash(Collection<T> list) {
        this(list, default_replication);
    }

    synchronized public boolean add(T node) {
        boolean insert = true;

        getReplicaForKey(node.toString()).forEach(aLong -> _map.put(aLong, node));

        return true;
    }

    public Long doHash(String key) {
        return _hash.hash(key);
    }

    synchronized public TreeMap<Long, T> getMap() {
        //    System.out.println("MAP " + _map);
        return _map;
    }

    synchronized public void remove(T node) {
        getReplicaForKey(node.toString()).forEach(aLong -> _map.remove(aLong));
    }

    synchronized public T get(String key) {
        long hash = _hash.hash(key);
        Long res = _map.ceilingKey(hash);
        if (res != null) return _map.get(res);
        else
            return _map.firstEntry().getValue();
    }

    synchronized public ArrayList<Map.Entry<Long, T>> getNext(String key, int n) {
        long hash = _hash.hash(key);
        return getNext(hash, n);
    }

    synchronized public ArrayList<Map.Entry<Long, T>> getNext(long hash, int n) {
        ArrayList<Map.Entry<Long, T>> res = new ArrayList<>();
        Set<T> check = new HashSet<>();
        int index = 0;
        NavigableMap<Long, T> orderMap = _map.tailMap(hash, false);
        for (int num = 0; num < 2 && index < n; num++) {

            for (Map.Entry<Long, T> item : orderMap.entrySet()) {
                if (!check.contains(item.getValue())) {
                    res.add(item);
                    check.add(item.getValue());
                    index++;
                }
                if (index == n) break;
            }
            orderMap = _map.headMap(hash, false);
        }

        LOG.debug("getNext " + res);
        return res;
    }

    public List<Long> getReplicaForKey(String key) {
        List<Long> hashes = new ArrayList<>();
        for (int i = 0; i < _replication; i++) {
            hashes.add(_hash.hash(key + i));
        }
        return hashes;
    }

    synchronized public ArrayList<Map.Entry<Long, T>> getPrev(String key, int n) {
        long hash = _hash.hash(key);
        return getPrev(hash, n);
    }

    synchronized public ArrayList<Map.Entry<Long, T>> getPrev(long hash, int n) {
        ArrayList<Map.Entry<Long, T>> res = new ArrayList<>();
        Set<T> check = new HashSet<>();

        int index = 0;
        NavigableMap<Long, T> orderMap = _map.headMap(hash, false);
        for (int num = 0; num < 2 && index < n; num++) {

            for (Map.Entry<Long, T> item : orderMap.descendingMap().entrySet()) {
                if (!check.contains(item.getValue())) {
                    res.add(item);
                    check.add(item.getValue());
                    index++;
                }
                if (index == n) break;
            }
            orderMap = _map.tailMap(hash, false);
        }

        LOG.debug("getPrev " + res);
        return res;
    }

    public Map.Entry<Long, T> getPrev(String key) {
        return getPrev(key, 1).get(0);
    }

    public Map.Entry<Long, T> getPrev(long hash) {
        return getPrev(hash, 1).get(0);
    }

    public Map.Entry<Long, T> getNext(String key) {
        return getNext(key, 1).get(0);
    }

    public Map.Entry<Long, T> getNext(long hash) {
        return getNext(hash, 1).get(0);
    }

    @Override
    public String toString() {
        return "ConsistentHash{" +
                "_map=" + _map +
                ", _replication=" + _replication +
                ", _hash=" + _hash +
                '}';
    }

    synchronized public int size() {
        return _map.size();
    }

}


text:
image.setVisibility(View.VISIBLE);
image.getViewTreeObserver()
	.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        image.getViewTreeObserver()
		.removeOnPreDrawListener(this);
        image.animate().alpha(1f)
		.scaleY(1f).scaleX(1f)
                .rotation(720)
		.setInterpolator(new AccelerateInterpolator())
                .setDuration(1000);
        return false;
    }
});


text:
class AddDeletedToGameUser < ActiveRecord::Migration
  def change
    add_column :game_users, :deleted, :boolean, :default => false
  end
end


text:
Puppet module for installing
[Docker](https://github.com/dotcloud/docker) from the [official repository](http://docs.docker.io/en/latest/installation/ubuntulinux/) on Ubuntu or from [EPEL on RedHat](http://docs.docker.io/en/latest/installation/rhel/) based distributions.

This module is also available on the [Puppet
Forge](https://forge.puppetlabs.com/garethr/docker)

[![Build
Status](https://secure.travis-ci.org/garethr/garethr-docker.png)](http://travis-ci.org/garethr/garethr-docker)

## Support

This modules is currently tested on:

* Ubuntu 14.04
* Centos 6.5
* Ubuntu 12.04

It may work on other distros and other operating systems will be
supported in the future.

## Usage

The module includes a single class:

```puppet
include 'docker'
```

By default this sets up the docker hosted Apt repository and installs
the lxc-docker package and any required Kernel extensions.

If you don't want this module to mess about with your Kernel then you
can disable this feature like so:

```puppet
class { 'docker':
  manage_kernel => false,
}
```

If you want to configure your package sources independently,
inform this module to not auto-include upstream sources:

```puppet
class { 'docker':
  use_upstream_package_source => false,
}
```

By default the docker daemon will bind to a unix socket at
/var/run/docker.sock. This can be changed, as well as binding to a tcp
socket if required.

```puppet
class { 'docker':
  tcp_bind    => 'tcp://127.0.0.1:4243',
  socket_bind => 'unix:///var/run/docker.sock',
}
```

Unless specified this installs the latest version of docker from the
docker inc repository. However if you want to specify a specific version
you can do so:

```puppet
class { 'docker':
  version => '0.5.5',
}
```

In some cases dns resolution won't work well in the container unless you give a dns server to the docker daemon like this:

```puppet
class { 'docker':
  dns => '8.8.8.8',
}
```

The class contains lots of other options, please see the inline code
documentation for the full options.

### Images

The next step is probably to install a docker image, for this we have a defined type which can be used like so:

```puppet
docker::image { 'base': }
```

This is equivalent to running `docker pull base`. This is downloading a large binary so on first run can take a while. For that reason this define turns off the default 5 minute timeout for exec. Takes an optional parameter for installing image tags that is the equivalent to running `docker pull -t="precise" ubuntu`:

```puppet
docker::image { 'ubuntu':
  image_tag => 'precise'
}
```

Note: images will only install if an image of that name does not already exist.

You can also remove images you no longer need with:

```puppet
docker::image { 'base':
  ensure => 'absent'
}

docker::image { 'ubuntu':
  ensure    => 'absent',
  image_tag => 'precise'
}
```

### Containers

Now you have an image you can run commands within a container managed by docker.

```puppet
docker::run { 'helloworld':
  image   => 'base',
  command => '/bin/sh -c "while true; do echo hello world; sleep 1; done"',
}
```

This is equivalent to running the following under upstart:

    docker run -d base /bin/sh -c "while true; do echo hello world; sleep 1; done"

Run also contains a number of optional parameters:

```puppet
docker::run { 'helloworld':
  image           => 'base',
  command         => '/bin/sh -c "while true; do echo hello world; sleep 1; done"',
  ports           => ['4444', '4555'],
  expose          => ['4666', '4777'],
  links           => ['mysql:db'],
  use_name        => true,
  volumes         => ['/var/lib/couchdb', '/var/log'],
  volumes_from    => '6446ea52fbc9',
  memory_limit    => 10485760, # bytes
  username        => 'example',
  hostname        => 'example.com',
  env             => ['FOO=BAR', 'FOO2=BAR2'],
  dns             => ['8.8.8.8', '8.8.4.4'],
  restart_service => true,
  privileged      => false,
}
```

Ports, expose, env, dns and volumes can be set with either a single string or as above with an array of values.

To use an image tag just append the tag name to the image name separated by a semicolon:

```puppet
docker::run { 'helloworld':
  image   => 'ubuntu:precise',
  command => '/bin/sh -c "while true; do echo hello world; sleep 1; done"',
}
```