text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Dapper;
using DapperExtensions;
using MvcMusicStore.Domain.Entities;
using MvcMusicStore.Domain.Interfaces.Repository.ReadOnly;

namespace MvcMusicStore.Data.Repository.Dapper
{
    public class UserDapperRepository : Common.Repository, IUserReadOnlyRepository
    {
        public User Get(int id)
        {
            using (var cn = MusicStoreConnection)
            {
                var user = cn.Query<User>("SELECT * FROM AspNetUsers WHERE ArtistId = @Id",
                    new { Id = id }).FirstOrDefault();
                return user;
            }
        }

        public IEnumerable<User> All()
        {
            using (var cn = MusicStoreConnection)
            {
                var user = cn.Query<User>("SELECT * FROM AspNetUsers");
                return user;
            }
        }

        public IEnumerable<User> Find(Expression<Func<User, bool>> predicate)
        {
            using (var cn = MusicStoreConnection)
            {
                var user = cn.GetList<User>(predicate);
                return user;
            }
        }
    }
}


text:
namespace android_webview {
namespace {

// Calls through to WebMessageListenerInfo.
class AwWebMessageHost : public js_injection::WebMessageHost {
 public:
  AwWebMessageHost(js_injection::WebMessageReplyProxy* reply_proxy,
                   const base::android::ScopedJavaGlobalRef<jobject>& listener,
                   const std::string& origin_string,
                   bool is_main_frame)
      : reply_proxy_(reply_proxy),
        listener_(listener),
        origin_string_(origin_string),
        is_main_frame_(is_main_frame) {}

  ~AwWebMessageHost() override = default;

  // js_injection::WebMessageHost:
  void OnPostMessage(
      std::unique_ptr<js_injection::WebMessage> message) override {
    JNIEnv* env = base::android::AttachCurrentThread();
    base::android::ScopedJavaGlobalRef<jobjectArray> jports =
        content::AppWebMessagePort::WrapJavaArray(env,
                                                  std::move(message->ports));
    Java_WebMessageListenerHolder_onPostMessage(
        env, listener_,
        base::android::ConvertUTF16ToJavaString(env, message->message),
        base::android::ConvertUTF8ToJavaString(env, origin_string_),
        is_main_frame_, jports, reply_proxy_.GetJavaPeer());
  }

 private:
  JsReplyProxy reply_proxy_;
  base::android::ScopedJavaGlobalRef<jobject> listener_;
  const std::string origin_string_;
  const bool is_main_frame_;
};

}  // namespace

AwWebMessageHostFactory::AwWebMessageHostFactory(
    const base::android::JavaParamRef<jobject>& listener)
    : listener_(listener) {}

AwWebMessageHostFactory::~AwWebMessageHostFactory() = default;

// static
base::android::ScopedJavaLocalRef<jobjectArray>
AwWebMessageHostFactory::GetWebMessageListenerInfo(
    js_injection::JsCommunicationHost* host,
    JNIEnv* env,
    const base::android::JavaParamRef<jclass>& clazz) {
  auto factories = host->GetWebMessageHostFactories();
  jobjectArray joa =
      env->NewObjectArray(factories.size(), clazz.obj(), nullptr);
  base::android::CheckException(env);

  for (size_t i = 0; i < factories.size(); ++i) {
    const auto& factory = factories[i];
    const std::vector<std::string> rules =
        factory.allowed_origin_rules.Serialize();
    base::android::ScopedJavaLocalRef<jobject> object =
        Java_WebMessageListenerInfo_create(
            env, base::android::ConvertUTF16ToJavaString(env, factory.js_name),
            base::android::ToJavaArrayOfStrings(env, rules),
            static_cast<AwWebMessageHostFactory*>(factory.factory)->listener_);
    env->SetObjectArrayElement(joa, i, object.obj());
  }
  return base::android::ScopedJavaLocalRef<jobjectArray>(env, joa);
}

std::unique_ptr<js_injection::WebMessageHost>
AwWebMessageHostFactory::CreateHost(const std::string& origin_string,
                                    bool is_main_frame,
                                    js_injection::WebMessageReplyProxy* proxy) {
  return std::make_unique<AwWebMessageHost>(proxy, listener_, origin_string,
                                            is_main_frame);
}

}  // namespace android_webview

redpajama_set_name: RedPajamaGithub


text:
echo "export PATH=$PATH:/usr/local/bin" > /etc/profile.d/local_bin.sh

source /etc/profile.d/local_bin.sh

gem install --no-ri --no-rdoc puppet

puppet module install garethr-erlang

puppet apply /vagrant/erlang.pp

puppet module install puppetlabs-rabbitmq

puppet apply /vagrant/rabbit.pp


text:
<?php

namespace CakeDC\Enum\Model\Behavior\Strategy;

interface StrategyInterface
{

    /**
     * @param mixed $config Strategy's configuration.
     * @return array
     */
    public function enum(array $config = []);

    /**
     * @param array $config Configuration.
     * @return \CakeDC\Enum\Model\Behavior\Strategy\StrategyInterface
     */
    public function initialize($config);

    /**
     * @param string|array|null $key The key to get/set, or a complete array of configs.
     * @param mixed|null $value The value to set.
     * @param bool $merge Whether to recursively merge or overwrite existing config, defaults to true.
     * @return mixed Config value being read, or the object itself on write operations.
     * @throws \Cake\Core\Exception\Exception When trying to set a key that is invalid.
     */
    public function config($key = null, $value = null, $merge = true);
}


text:
/* invalid input */
.bvalidator-gray4-invalid {
    background-color: rgba(208,26,15,0.80) !important;
    color: #FFF;
}
/* tooltip */
.bvalidator-gray4-tooltip {
    background-color: #333;
    font-size: 13px;
    border: 1px solid #999;
    color: #FFF;
    border-radius: 4px;
    border-bottom-left-radius: 0;
    border-top-left-radius: 0;
    -webkit-box-shadow: 0 0 6px #ddd;
            box-shadow: 0 0 6px #ddd;
    white-space: nowrap;
    padding-top: 2px;
    padding-right: 15px;
    padding-bottom: 2px;
    padding-left: 6px;
    opacity: 0.9;
    line-height: 20px;
    position:absolute;
    z-index: 1;
}
.bvalidator-gray4-tooltip-noclose {
    padding-right: 6px;
}
/* message */
.bvalidator-gray4-tooltip .bvalidator-gray4-msg {
    position: relative;
}
/* close icon */
.bvalidator-gray4-tooltip .bvalidator-gray4-close {
    font-family: Arial, Helvetica, sans-serif;
    font-weight: bold;
    color: #F96;
    cursor: pointer;
    position:absolute;
    right: 5px;
    top: 2px;
}
.bvalidator-gray4-tooltip .bvalidator-gray4-close:hover, .bvalidator-gray4-tooltip .bvalidator-gray4-close:focus{
    color: #FC6;
}
/* arrow */
.bvalidator-gray4-tooltip .bvalidator-gray4-arrow {
    border-color: #333 transparent transparent;
    border-style: solid;
    border-width: 10px 10px 0;
    height: 0;
    width: 0;
    position: absolute;
    bottom: -9px;
    left: 5px
}


text:
layout: post
title: Superstar Tory Lane has a weird pink toy up her ass!
titleinfo: pornvd
desc: Watch Superstar Tory Lane has a weird pink toy up her ass!. Pornhub is the ultimate xxx porn and sex site.
---

Superstar Tory Lane has a weird pink toy up her ass!

Watch Superstar Tory Lane has a weird pink toy up her ass!. Pornhub is the ultimate xxx porn and sex site.


text:
require 'google/api_client'

class Youtube
  def self.search(arg)
    client, youtube = configure_client

    begin
      # Call the search.list method to retrieve results matching the specified
      # query term.
      search_response = client.execute!(
        :api_method => youtube.search.list,
        :parameters => {
          :part => 'snippet',
          :q => arg,
          :maxResults => 25
        }
      )

      videos = []

      # Add each result to the appropriate list, and then display the lists of
      # matching videos, channels, and playlists.
      search_response.data.items.each do |search_result|
        case search_result.id.kind
          when 'youtube#video'
            videos << "#{search_result.snippet.title} (#{search_result.id.videoId})"
        end
      end

      return videos

    rescue Google::APIClient::TransmissionError => e
      puts e.result.body
    end
  end

  private

    def self.configure_client
      client = Google::APIClient.new(
        :key => ENV['YOUTUBE_DEVELOPER_KEY'],
        :authorization => nil,
        :application_name => ENV['PROGRAM_NAME'],
        :application_version => '1.0.0'
      )

      youtube = client.discovered_api(ENV['YOUTUBE_API_SERVICE_NAME'], ENV['YOUTUBE_API_VERSION'])

      return client, youtube
    end
end


text:
toc_export HAVE_EDITLINE=0
toc_export LIBEDITLINE_LDADD=

configure_with_libeditline=${configure_with_libeditline-1}
test "x${configure_with_libeditline}" = "x0" && {
    echo "libeditline has been explictely disabled with --without-libeditline."
    return 0
}

_libpath=/usr/lib:/usr/local/lib:${prefix}/lib:/lib
_do=0
for L in libeditline.so libeditline.a; do
    toc_find $L "$_libpath" && {
        _do=1
        break
    }
done
test x$_do = x0 && {
    echo "libeditline library file not found."
    unset _do
    unset _libpath
    return 0
}
rllib=${TOC_FIND_RESULT}

rlincpath=/usr/include:/usr/include/editline:/usr/local/include:/usr/local/include/editline:${prefix}/include:${prefix}/include/editline
for inc in editline.h; do
    toc_find $inc $rlincpath || {
        err=$?
        echo "Header file $inc not found in path [$rlincpath]"
        unset rlincpath
        unset rllib
        return $err
    }
done
unset rlincpath

LIBEDITLINE_LDADD="-leditline"

# odd: lineedit sources never included curses.h, but do use curses functions,
# leading to an unknown symbol in your app if we don't tell you that you need
# to link against curses:
#if ldd $rllib 2> /dev/null | grep ncurses &>/dev/null ; then
#    echo "It seems that libeditline also requires linking against -lncurses."
LIBEDITLINE_LDADD="${LIBEDITLINE_LDADD} -lncurses"
#fi

toc_export HAVE_EDITLINE=1
toc_export LIBEDITLINE_LDADD="${LIBEDITLINE_LDADD}"
unset nc
return 0


text:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class lab05_VowelCount {

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		String input = scanner.nextLine();
		scanner.close();

		Pattern pattern = Pattern.compile("[AUEIOYaueioy]");
		Matcher matcher = pattern.matcher(input);

		Integer counter = 0;
		while (matcher.find()) {
			counter++;
		}

		System.out.println("Vowels: " + counter);

	}

}


text:
(function(servicesModule) {
    'use strict';
    servicesModule.value('version', '0.0.1');

    servicesModule.value('backendUrl', 'http://api.veganaut.net');
})(window.monkeyFace.servicesModule);


text:
<!DOCTYPE html>

    <link href="css/awsdocs.css" rel="stylesheet" type="text/css">

    <meta charset="utf-8">

Route 53 Record Set GeoLocation Property

The GeoLocation property is part of the AWS::Route53::RecordSet resource that describes how Route 53 responds to DNS queries based on the geographic
                        location
                        of the query. This property is not compatible with the Region
                        property.

Syntax

JSON

{
  "ContinentCode" : String,
  "CountryCode" : String,
  "SubdivisionCode" : String
}

YAML

ContinentCode: String
CountryCode: String
SubdivisionCode: String

Properties

ContinentCode

All DNS queries from the continent that you specified are routed to this
                                 resource record set. If you specify this property, omit the
                                 CountryCode and SubdivisionCode properties.

For valid values, see GeoLocation in the
                                 Amazon Route 53 API Reference.

Type: String

Required: Conditional. You must specify this or the CountryCode
                                 property.

CountryCode

All DNS queries from the country that you specified are routed to this resource
                                 record set. If you specify this property, omit the ContinentCode
                                 property. To specify the default location, use * for this property.

For valid values, see GeoLocation in the
                                 Amazon Route 53 API Reference.

Type: String

Required: Conditional. You must specify this or the ContinentCode
                                 property.

SubdivisionCode

If you specified US for the country code, you can specify a state
                                 in the United States. All DNS queries from the state that you specified are routed
                                 to this resource record set. If you specify this property, you must specify
                                 US for the CountryCode and omit the
                                 ContinentCode property.

For valid values, see GeoLocation in the
                                 Amazon Route 53 API Reference.

Type: String

Required: No


text:
// Copyright 2014 Goodow.com. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//
//  GDSModel.h
//  GDStore
//
//  Created by Larry Tin.
//

#import <Foundation/Foundation.h>

@protocol GDCRegistration;
@protocol GDSUndoRedoStateChangedEvent;
@protocol GDSCollaborativeList;
@protocol GDSCollaborativeMap;
@protocol GDSCollaborativeString;

/**
 * The collaborative model is the data model for a Realtime document. The document's object graph
 * should be added to the model under the root object. All objects that are part of the model must
 * be accessible from this root.
 *

 * The model class is also used to create instances of built in and custom collaborative objects via
 * the appropriate create method.
 *

 * Listen on the model for the following events:
 *

 *
{@link GDSEventType#UNDO_REDO_STATE_CHANGED}
 *

 *

 * This class should not be instantiated directly. The collaborative model is generated during the
 * document load process. The model can be initialized by passing an initializer function to
 * {@link GDSStore#load:(NSString)
 *             onLoaded:(void (^)(id<GDSDocument>))
 *      opt_initializer:(void (^)(id<GDSModel>))
 *            opt_error:(void (^)(id<GDSError>))}.
 */
@protocol GDSModel

- (id<GDCRegistration>)onUndoRedoStateChanged:(void (^)(id<GDSUndoRedoStateChangedEvent>))handler;

/**
 * Creates a collaborative list.
 *
 * @param opt_initialValue Initial value for the list.
 * @return A collaborative list.
 */
- (id<GDSCollaborativeList>)createList:(NSArray *)opt_initialValue;

/**
 * Creates a collaborative map.
 *
 * @param opt_initialValue Initial value for the map.
 * @return A collaborative map.
 */
- (id<GDSCollaborativeMap>)createMap:(NSDictionary *)opt_initialValue;

/**
 * Creates a collaborative string.
 *
 * @param opt_initialValue Sets the initial value for this string.
 * @return A collaborative string.
 */
- (id<GDSCollaborativeString>)createString:(NSString *)opt_initialValue;

/**
 * @return The root of the object model.
 */
- (id<GDSCollaborativeMap>)getRoot;

/**
 * Redo the last thing the active collaborator undid.
 */
- (void)redo;

/**
 * Undo the last thing the active collaborator did.
 */
- (void)undo;

/**
 * @return True if the model can currently redo.
 */
- (BOOL)canRedo;

/**
 * @return True if the model can currently undo.
 */
- (BOOL)canUndo;

@end


text:
/**
 * @prettier
 */
import { BigNumber } from 'bignumber.js';
import { bip32 } from '@bitgo/utxo-lib';
import Keccak from 'keccak';
import * as secp256k1 from 'secp256k1';
import * as _ from 'lodash';
import { BaseCoin as StaticsBaseCoin, CoinFamily, coins, ethGasConfigs } from '@bitgo/statics';
import {
  BaseCoin,
  BaseTransaction,
  BitGoBase,
  common,
  FeeEstimateOptions,
  FullySignedTransaction,
  getIsUnsignedSweep,
  InvalidAddressError,
  IWallet,
  KeyPair,
  ParsedTransaction,
  ParseTransactionOptions,
  Recipient,
  TransactionExplanation,
  Util,
  VerifyAddressOptions,
} from '@bitgo/sdk-core';
import {
  GetSendMethodArgsOptions,
  optionalDeps,
  RecoverOptions,
  RecoveryInfo,
  SendMethodArgs,
  TransactionBuilder as EthTransactionBuilder,
  TransactionPrebuild,
} from '@bitgo/sdk-coin-eth';
import { isValidEthAddress } from './lib/utils';
import { KeyPair as AvaxcKeyPair, TransactionBuilder } from './lib';
import request from 'superagent';
import { bufferToHex } from 'ethereumjs-util';
import { Buffer } from 'buffer';
import {
  AvaxSignTransactionOptions,
  BuildOptions,
  ExplainTransactionOptions,
  FeeEstimate,
  HopParams,
  HopPrebuild,
  HopTransactionBuildOptions,
  OfflineVaultTxInfo,
  PrecreateBitGoOptions,
  PresignTransactionOptions,
  SignedTransaction,
  SignFinalOptions,
  VerifyAvaxcTransactionOptions,
} from './iface';
import { AvaxpLib } from '@bitgo/sdk-coin-avaxp';

export class AvaxC extends BaseCoin {
  static hopTransactionSalt = 'bitgoHopAddressRequestSalt';

  protected readonly _staticsCoin: Readonly<StaticsBaseCoin>;

  protected constructor(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>) {
    super(bitgo);

    if (!staticsCoin) {
      throw new Error('missing required constructor parameter staticsCoin');
    }

    this._staticsCoin = staticsCoin;
  }

  static createInstance(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>): BaseCoin {
    return new AvaxC(bitgo, staticsCoin);
  }

  getBaseFactor(): number {
    return Math.pow(10, this._staticsCoin.decimalPlaces);
  }

  getChain() {
    return this._staticsCoin.name;
  }

  /**
   * Get the base chain that the coin exists on.
   */
  getBaseChain() {
    return this.getChain();
  }

  getFamily(): CoinFamily {
    return this._staticsCoin.family;
  }

  getFullName() {
    return this._staticsCoin.fullName;
  }

  valuelessTransferAllowed(): boolean {
    return true;
  }

  isValidAddress(address: string): boolean {
    return !!address && isValidEthAddress(address);
  }

  isToken(): boolean {
    return false;
  }

  generateKeyPair(seed?: Buffer): KeyPair {
    const avaxKeyPair = seed ? new AvaxcKeyPair({ seed }) : new AvaxcKeyPair();
    const extendedKeys = avaxKeyPair.getExtendedKeys();
    return {
      pub: extendedKeys.xpub,
      prv: extendedKeys.xprv!,
    };
  }

  async parseTransaction(params: ParseTransactionOptions): Promise<ParsedTransaction> {
    return {};
  }

  async verifyAddress({ address }: VerifyAddressOptions): Promise<boolean> {
    if (!this.isValidAddress(address)) {
      throw new InvalidAddressError(`invalid address: ${address}`);
    }
    return true;
  }

  /**
   * Verify that a transaction prebuild complies with the original intention
   *
   * @param params
   * @param params.txParams params object passed to send
   * @param params.txPrebuild prebuild object returned by server
   * @param params.wallet Wallet object to obtain keys to verify against
   * @returns {boolean}
   */
  async verifyTransaction(params: VerifyAvaxcTransactionOptions): Promise<boolean> {
    const { txParams, txPrebuild, wallet } = params;
    if (!txParams?.recipients || !txPrebuild?.recipients || !wallet) {
      throw new Error(`missing params`);
    }
    if (txParams.hop && txParams.recipients.length > 1) {
      throw new Error(`tx cannot be both a batch and hop transaction`);
    }
    if (txPrebuild.recipients.length !== 1) {
      throw new Error(`txPrebuild should only have 1 recipient but ${txPrebuild.recipients.length} found`);
    }
    if (txParams.hop && txPrebuild.hopTransaction) {
      // Check recipient amount for hop transaction
      if (txParams.recipients.length !== 1) {
        throw new Error(`hop transaction only supports 1 recipient but ${txParams.recipients.length} found`);
      }
      // Check tx sends to hop address
      let expectedHopAddress;
      if (txPrebuild.hopTransaction.type === 'Export') {
        const decodedHopTx = await this.explainAtomicTransaction(txPrebuild.hopTransaction.tx);
        expectedHopAddress = optionalDeps.ethUtil.stripHexPrefix(decodedHopTx.inputs[0].address);
      } else {
        const decodedHopTx = optionalDeps.EthTx.TransactionFactory.fromSerializedData(
          optionalDeps.ethUtil.toBuffer(txPrebuild.hopTransaction.tx)
        );
        expectedHopAddress = optionalDeps.ethUtil.stripHexPrefix(decodedHopTx.getSenderAddress().toString());
      }
      const actualHopAddress = optionalDeps.ethUtil.stripHexPrefix(txPrebuild.recipients[0].address);
      if (expectedHopAddress.toLowerCase() !== actualHopAddress.toLowerCase()) {
        throw new Error('recipient address of txPrebuild does not match hop address');
      }

      // Convert TransactionRecipient array to Recipient array
      const recipients: Recipient[] = txParams.recipients.map((r) => {
        return {
          address: r.address,
          amount: typeof r.amount === 'number' ? r.amount.toString() : r.amount,
        };
      });

      // Check destination address and amount
      await this.validateHopPrebuild(wallet, txPrebuild.hopTransaction, { recipients });
    } else if (txParams.recipients.length > 1) {
      // Check total amount for batch transaction
      let expectedTotalAmount = new BigNumber(0);
      for (let i = 0; i < txParams.recipients.length; i++) {
        expectedTotalAmount = expectedTotalAmount.plus(txParams.recipients[i].amount);
      }
      if (!expectedTotalAmount.isEqualTo(txPrebuild.recipients[0].amount)) {
        throw new Error(
          'batch transaction amount in txPrebuild received from BitGo servers does not match txParams supplied by client'
        );
      }
    } else {
      // Check recipient address and amount for normal transaction
      if (txParams.recipients.length !== 1) {
        throw new Error(`normal transaction only supports 1 recipient but ${txParams.recipients.length} found`);
      }
      const expectedAmount = new BigNumber(txParams.recipients[0].amount);
      if (!expectedAmount.isEqualTo(txPrebuild.recipients[0].amount)) {
        throw new Error(
          'normal transaction amount in txPrebuild received from BitGo servers does not match txParams supplied by client'
        );
      }
      if (
        AvaxC.isAVAXCAddress(txParams.recipients[0].address) &&
        txParams.recipients[0].address !== txPrebuild.recipients[0].address
      ) {
        throw new Error('destination address in normal txPrebuild does not match that in txParams supplied by client');
      }
    }
    // Check coin is correct for all transaction types
    if (!this.verifyCoin(txPrebuild)) {
      throw new Error(`coin in txPrebuild did not match that in txParams supplied by client`);
    }
    return true;
  }

  private static isAVAXCAddress(address: string): boolean {
    return !!address.match(/0x[a-fA-F0-9]{40}/);
  }

  verifyCoin(txPrebuild: TransactionPrebuild): boolean {
    return txPrebuild.coin === this.getChain();
  }

  isValidPub(pub: string): boolean {
    let valid = true;
    try {
      new AvaxcKeyPair({ pub });
    } catch (e) {
      valid = false;
    }
    return valid;
  }

  /**
   * Check whether gas limit passed in by user are within our max and min bounds
   * If they are not set, set them to the defaults
   * @param {number} userGasLimit - user defined gas limit
   * @returns {number} the gas limit to use for this transaction
   */
  setGasLimit(userGasLimit?: number): number {
    if (!userGasLimit) {
      return ethGasConfigs.defaultGasLimit;
    }
    const gasLimitMax = ethGasConfigs.maximumGasLimit;
    const gasLimitMin = ethGasConfigs.minimumGasLimit;
    if (userGasLimit < gasLimitMin || userGasLimit > gasLimitMax) {
      throw new Error(`Gas limit must be between ${gasLimitMin} and ${gasLimitMax}`);
    }
    return userGasLimit;
  }

  /**
   * Check whether the gas price passed in by user are within our max and min bounds
   * If they are not set, set them to the defaults
   * @param {number} userGasPrice - user defined gas price
   * @returns the gas price to use for this transaction
   */
  setGasPrice(userGasPrice?: number): number {
    if (!userGasPrice) {
      return ethGasConfigs.defaultGasPrice;
    }

    const gasPriceMax = ethGasConfigs.maximumGasPrice;
    const gasPriceMin = ethGasConfigs.minimumGasPrice;
    if (userGasPrice < gasPriceMin || userGasPrice > gasPriceMax) {
      throw new Error(`Gas price must be between ${gasPriceMin} and ${gasPriceMax}`);
    }
    return userGasPrice;
  }

  /**
   * Make a query to Snowtrace for information such as balance, token balance, solidity calls
   * @param {Object} query — key-value pairs of parameters to append after /api
   * @returns {Promise<Object>} response from Snowtrace
   */
  async recoveryBlockchainExplorerQuery(query: Record<string, string>): Promise<any> {
    const token = common.Environments[this.bitgo.getEnv()].snowtraceApiToken;
    if (token) {
      query.apikey = token;
    }
    const response = await request.get(common.Environments[this.bitgo.getEnv()].snowtraceBaseUrl + '/api').query(query);

    if (!response.ok) {
      throw new Error('could not reach Snowtrace');
    }

    if (response.body.status === '0' && response.body.message === 'NOTOK') {
      throw new Error('Snowtrace rate limit reached');
    }
    return response.body;
  }

  /**
   * Queries public block explorer to get the next nonce that should be used for
   * the given AVAXC address
   * @param {string} address — address to fetch for
   * @returns {number} address nonce
   */
  async getAddressNonce(address: string): Promise<number> {
    // Get nonce for backup key (should be 0)
    let nonce = 0;

    const result = await this.recoveryBlockchainExplorerQuery({
      module: 'account',
      action: 'txlist',
      address,
    });
    if (!result || !Array.isArray(result.result)) {
      throw new Error('Unable to find next nonce from Snowtrace, got: ' + JSON.stringify(result));
    }
    const backupKeyTxList = result.result;
    if (backupKeyTxList.length > 0) {
      // Calculate last nonce used
      const outgoingTxs = backupKeyTxList.filter((tx) => tx.from === address);
      nonce = outgoingTxs.length;
    }
    return nonce;
  }

  /**
   * Queries Snowtrace for the balance of an address
   * @param {string} address - the AVAXC address
   * @returns {Promise<BigNumber>} address balance
   */
  async queryAddressBalance(address: string): Promise<any> {
    const result = await this.recoveryBlockchainExplorerQuery({
      module: 'account',
      action: 'balance',
      address: address,
    });
    // throw if the result does not exist or the result is not a valid number
    if (!result || !result.result || isNaN(result.result)) {
      throw new Error(`Could not obtain address balance for ${address} from Snowtrace, got: ${result.result}`);
    }
    return new optionalDeps.ethUtil.BN(result.result, 10);
  }

  /**
   * Queries the contract (via Snowtrace) for the next sequence ID
   * @param {string} address - address of the contract
   * @returns {Promise<number>} sequence ID
   */
  async querySequenceId(address: string): Promise<number> {
    // Get sequence ID using contract call
    const sequenceIdMethodSignature = optionalDeps.ethAbi.methodID('getNextSequenceId', []);
    const sequenceIdArgs = optionalDeps.ethAbi.rawEncode([], []);
    const sequenceIdData = Buffer.concat([sequenceIdMethodSignature, sequenceIdArgs]).toString('hex');
    const result = await this.recoveryBlockchainExplorerQuery({
      module: 'proxy',
      action: 'eth_call',
      to: address,
      data: sequenceIdData,
      tag: 'latest',
    });
    if (!result || !result.result) {
      throw new Error('Could not obtain sequence ID from Snowtrace, got: ' + result.result);
    }
    const sequenceIdHex = result.result;
    return new optionalDeps.ethUtil.BN(sequenceIdHex.slice(2), 16).toNumber();
  }

  /**
   * @param {Object} recipient - recipient info
   * @param {number} expireTime - expiry time
   * @param {number} contractSequenceId - sequence id
   * @returns {(string|Array)} operation array
   */
  getOperation(recipient: Recipient, expireTime: number, contractSequenceId: number): (string | Buffer)[][] {
    return [
      ['string', 'address', 'uint', 'bytes', 'uint', 'uint'],
      [
        'ETHER',
        new optionalDeps.ethUtil.BN(optionalDeps.ethUtil.stripHexPrefix(recipient.address), 16),
        recipient.amount,
        Buffer.from(optionalDeps.ethUtil.stripHexPrefix(optionalDeps.ethUtil.padToEven(recipient.data || '')), 'hex'),
        expireTime,
        contractSequenceId,
      ],
    ];
  }

  /**
   * Calculate the operation hash in the same way solidity would
   * @param {Recipient[]} recipients - tx recipients
   * @param {number} expireTime - expiration time
   * @param {number} contractSequenceId - contract sequence id
   * @returns {string} operation hash
   */
  getOperationSha3ForExecuteAndConfirm(
    recipients: Recipient[],
    expireTime: number,
    contractSequenceId: number
  ): string {
    if (!recipients || !Array.isArray(recipients)) {
      throw new Error('expecting array of recipients');
    }

    // Right now we only support 1 recipient
    if (recipients.length !== 1) {
      throw new Error('must send to exactly 1 recipient');
    }

    if (!_.isNumber(expireTime)) {
      throw new Error('expireTime must be number of seconds since epoch');
    }

    if (!_.isNumber(contractSequenceId)) {
      throw new Error('contractSequenceId must be number');
    }

    // Check inputs
    recipients.forEach(function (recipient) {
      if (
        !_.isString(recipient.address) ||
        !optionalDeps.ethUtil.isValidAddress(optionalDeps.ethUtil.addHexPrefix(recipient.address))
      ) {
        throw new Error('Invalid address: ' + recipient.address);
      }

      let amount;
      try {
        amount = new BigNumber(recipient.amount);
      } catch (e) {
        throw new Error('Invalid amount for: ' + recipient.address + ' - should be numeric');
      }

      recipient.amount = amount.toFixed(0);

      if (recipient.data && !_.isString(recipient.data)) {
        throw new Error('Data for recipient ' + recipient.address + ' - should be of type hex string');
      }
    });

    const recipient = recipients[0];
    return optionalDeps.ethUtil.bufferToHex(
      optionalDeps.ethAbi.soliditySHA3(...this.getOperation(recipient, expireTime, contractSequenceId))
    );
  }

  /**
   * Default expire time for a contract call (1 week)
   * @returns {number} Time in seconds
   */
  getDefaultExpireTime(): number {
    return Math.floor(new Date().getTime() / 1000) + 60 * 60 * 24 * 7;
  }

  /**
   * Build arguments to call the send method on the wallet contract
   * @param {Object} txInfo - data for send method args
   * @returns {SendMethodArgs[]}
   */
  getSendMethodArgs(txInfo: GetSendMethodArgsOptions): SendMethodArgs[] {
    // Method signature is
    // sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature)
    return [
      {
        name: 'toAddress',
        type: 'address',
        value: txInfo.recipient.address,
      },
      {
        name: 'value',
        type: 'uint',
        value: txInfo.recipient.amount,
      },
      {
        name: 'data',
        type: 'bytes',
        value: optionalDeps.ethUtil.toBuffer(optionalDeps.ethUtil.addHexPrefix(txInfo.recipient.data || '')),
      },
      {
        name: 'expireTime',
        type: 'uint',
        value: txInfo.expireTime,
      },
      {
        name: 'sequenceId',
        type: 'uint',
        value: txInfo.contractSequenceId,
      },
      {
        name: 'signature',
        type: 'bytes',
        value: optionalDeps.ethUtil.toBuffer(optionalDeps.ethUtil.addHexPrefix(txInfo.signature)),
      },
    ];
  }

  /**
   * Builds a funds recovery transaction without BitGo
   * Steps:
   * 1) Node query - how much money is in the account
   * 2) Build transaction - build our transaction for the amount
   * 3) Send signed build - send our signed build to a public node
   * @param {Object} params The options with which to recover
   * @param {string} params.userKey - [encrypted] xprv
   * @param {string} params.backupKey - [encrypted] xprv or xpub if the xprv is held by a KRS provider
   * @param {string} params.walletPassphrase - used to decrypt userKey and backupKey
   * @param {string} params.walletContractAddress - the AVAXC address of the wallet contract
   * @param {string} params.recoveryDestination - target address to send recovered funds to
   * @returns {Promise<RecoveryInfo>} - recovery tx info
   */
  async recover(params: RecoverOptions): Promise<RecoveryInfo | OfflineVaultTxInfo> {
    if (_.isUndefined(params.userKey)) {
      throw new Error('missing userKey');
    }

    if (_.isUndefined(params.backupKey)) {
      throw new Error('missing backupKey');
    }

    if (_.isUndefined(params.walletPassphrase) && !params.userKey.startsWith('xpub')) {
      throw new Error('missing wallet passphrase');
    }

    if (_.isUndefined(params.walletContractAddress) || !this.isValidAddress(params.walletContractAddress)) {
      throw new Error('invalid walletContractAddress');
    }

    if (_.isUndefined(params.recoveryDestination) || !this.isValidAddress(params.recoveryDestination)) {
      throw new Error('invalid recoveryDestination');
    }

    // TODO (BG-56531): add support for krs
    const isUnsignedSweep = getIsUnsignedSweep(params);

    // Clean up whitespace from entered values
    let userKey = params.userKey.replace(/\s/g, '');
    const backupKey = params.backupKey.replace(/\s/g, '');

    // Set new tx fees (using default config values from platform)
    const gasLimit = new optionalDeps.ethUtil.BN(this.setGasLimit(params.gasLimit));
    const gasPrice = params.eip1559
      ? new optionalDeps.ethUtil.BN(params.eip1559.maxFeePerGas)
      : new optionalDeps.ethUtil.BN(this.setGasPrice(params.gasPrice));
    if (!userKey.startsWith('xpub') && !userKey.startsWith('xprv')) {
      try {
        userKey = this.bitgo.decrypt({
          input: userKey,
          password: params.walletPassphrase,
        });
      } catch (e) {
        throw new Error(`Error decrypting user keychain: ${e.message}`);
      }
    }

    let backupKeyAddress;
    let backupSigningKey;
    if (isUnsignedSweep) {
      const backupKeyPair = new AvaxcKeyPair({ pub: backupKey });
      backupKeyAddress = backupKeyPair.getAddress();
    } else {
      // Decrypt backup private key and get address
      let backupPrv;

      try {
        backupPrv = this.bitgo.decrypt({
          input: backupKey,
          password: params.walletPassphrase,
        });
      } catch (e) {
        throw new Error(`Error decrypting backup keychain: ${e.message}`);
      }

      const keyPair = new AvaxcKeyPair({ prv: backupPrv });
      backupSigningKey = keyPair.getKeys().prv;
      if (!backupSigningKey) {
        throw new Error('no private key');
      }
      backupKeyAddress = keyPair.getAddress();
    }
    const backupKeyNonce = await this.getAddressNonce(backupKeyAddress);

    // get balance of backupKey to ensure funds are available to pay fees
    const backupKeyBalance = await this.queryAddressBalance(backupKeyAddress);

    const totalGasNeeded = gasPrice.mul(gasLimit);
    const weiToGwei = 10 ** 9;
    if (backupKeyBalance.lt(totalGasNeeded)) {
      throw new Error(
        `Backup key address ${backupKeyAddress} has balance ${(backupKeyBalance / weiToGwei).toString()} Gwei.` +
          `This address must have a balance of at least ${(totalGasNeeded / weiToGwei).toString()}` +
          ` Gwei to perform recoveries. Try sending some AVAX to this address then retry.`
      );
    }

    // get balance of wallet and deduct fees to get transaction amount
    const txAmount = await this.queryAddressBalance(params.walletContractAddress);

    // build recipients object
    const recipients = [
      {
        address: params.recoveryDestination,
        amount: txAmount.toString(10),
      },
    ];

    // Get sequence ID using contract call
    // we need to wait between making two snowtrace calls to avoid getting banned
    await new Promise((resolve) => setTimeout(resolve, 1000));
    const sequenceId = await this.querySequenceId(params.walletContractAddress);

    let operationHash, signature;
    // Get operation hash and sign it
    if (!isUnsignedSweep) {
      operationHash = this.getOperationSha3ForExecuteAndConfirm(recipients, this.getDefaultExpireTime(), sequenceId);
      signature = Util.ethSignMsgHash(operationHash, Util.xprvToEthPrivateKey(userKey));

      try {
        Util.ecRecoverEthAddress(operationHash, signature);
      } catch (e) {
        throw new Error('Invalid signature');
      }
    }

    const txInfo = {
      recipient: recipients[0],
      expireTime: this.getDefaultExpireTime(),
      contractSequenceId: sequenceId,
      operationHash,
      signature,
      gasLimit: gasLimit.toString(10),
    };

    // calculate send data
    const sendMethodArgs = this.getSendMethodArgs(txInfo);
    const sendMethodName = 'sendMultiSig';
    const methodSignature = optionalDeps.ethAbi.methodID(sendMethodName, _.map(sendMethodArgs, 'type'));
    const encodedArgs = optionalDeps.ethAbi.rawEncode(_.map(sendMethodArgs, 'type'), _.map(sendMethodArgs, 'value'));
    const sendData = Buffer.concat([methodSignature, encodedArgs]);

    const txBuilder = this.getTransactionBuilder() as TransactionBuilder;
    txBuilder.counter(backupKeyNonce);
    txBuilder.contract(params.walletContractAddress);
    let txFee;
    if (params.eip1559) {
      txFee = {
        eip1559: {
          maxPriorityFeePerGas: params.eip1559.maxPriorityFeePerGas,
          maxFeePerGas: params.eip1559.maxFeePerGas,
        },
      };
    } else {
      txFee = { fee: gasPrice.toString() };
    }
    txBuilder.fee({
      ...txFee,
      gasLimit: gasLimit.toString(),
    });
    txBuilder
      .transfer()
      .amount(recipients[0].amount)
      .contractSequenceId(sequenceId)
      .expirationTime(this.getDefaultExpireTime())
      .to(params.recoveryDestination)
      .data(bufferToHex(sendData as Buffer));

    if (isUnsignedSweep) {
      const tx = await txBuilder.build();
      const response: OfflineVaultTxInfo = {
        txHex: tx.toBroadcastFormat(),
        userKey,
        backupKey,
        coin: this.getChain(),
        gasPrice: optionalDeps.ethUtil.bufferToInt(gasPrice).toFixed(),
        gasLimit,
        recipients: [txInfo.recipient],
        walletContractAddress: tx.toJson().to,
        amount: txInfo.recipient.amount,
        backupKeyNonce,
        eip1559: params.eip1559,
      };
      _.extend(response, txInfo);
      response.nextContractSequenceId = response.contractSequenceId;
      return response;
    }

    const userKeyPair = new AvaxcKeyPair({ prv: userKey });
    txBuilder.transfer().key(userKeyPair.getKeys().prv!);
    txBuilder.sign({ key: backupSigningKey });
    const signedTx = await txBuilder.build();

    return {
      id: signedTx.toJson().id,
      tx: signedTx.toBroadcastFormat(),
    };
  }

  /**
   * Create a new transaction builder for the current chain
   * @return a new transaction builder
   */
  protected getTransactionBuilder(): EthTransactionBuilder {
    return new TransactionBuilder(coins.get(this.getBaseChain()));
  }

  protected getAtomicBuilder(): AvaxpLib.TransactionBuilderFactory {
    return new AvaxpLib.TransactionBuilderFactory(coins.get(this.getAvaxP()));
  }

  /**
   * Explain a transaction from txHex, overriding BaseCoins
   * transaction can be either atomic or eth txn.
   * @param params The options with which to explain the transaction
   */
  async explainTransaction(params: ExplainTransactionOptions): Promise<TransactionExplanation> {
    const txHex = params.txHex || (params.halfSigned && params.halfSigned.txHex);
    if (!txHex) {
      throw new Error('missing txHex in explain tx parameters');
    }
    if (params.crossChainType) {
      return this.explainAtomicTransaction(txHex);
    }
    if (!params.feeInfo) {
      throw new Error('missing feeInfo in explain tx parameters');
    }
    const txBuilder = this.getTransactionBuilder();
    txBuilder.from(txHex);
    const tx = await txBuilder.build();
    return Object.assign(this.explainEVMTransaction(tx), { fee: params.feeInfo });
  }

  /**
   * Explains an atomic transaction using atomic builder.
   * @param txHex
   * @private
   */
  private async explainAtomicTransaction(txHex: string) {
    const txBuilder = this.getAtomicBuilder().from(txHex);
    const tx = await txBuilder.build();
    return tx.explainTransaction();
  }

  /**
   * Explains an EVM transaction using regular eth txn builder
   * @param tx
   * @private
   */
  private explainEVMTransaction(tx: BaseTransaction) {
    const outputs = tx.outputs.map((output) => {
      return {
        address: output.address,
        amount: output.value,
      };
    });
    const displayOrder = ['id', 'outputAmount', 'changeAmount', 'outputs', 'changeOutputs', 'fee'];
    return {
      displayOrder,
      id: tx.id,
      outputs: outputs,
      outputAmount: outputs
        .reduce((accumulator, output) => accumulator.plus(output.amount), new BigNumber('0'))
        .toFixed(0),
      changeOutputs: [], // account based does not use change outputs
      changeAmount: '0', // account base does not make change
    };
  }

  /**
   * Above is standard BaseCoins functions
   * ================================================================================================================
   * ================================================================================================================
   * Below is transaction functions
   */

  /**
   * Coin-specific things done before signing a transaction, i.e. verification
   * @param params
   */
  async presignTransaction(params: PresignTransactionOptions): Promise<PresignTransactionOptions> {
    if (!_.isUndefined(params.hopTransaction) && !_.isUndefined(params.wallet) && !_.isUndefined(params.buildParams)) {
      await this.validateHopPrebuild(params.wallet, params.hopTransaction);
    }
    return params;
  }

  /**
   * Modify prebuild after receiving it from the server. Add things like nlocktime
   */
  async postProcessPrebuild(params: TransactionPrebuild): Promise<TransactionPrebuild> {
    if (!_.isUndefined(params.hopTransaction) && !_.isUndefined(params.wallet) && !_.isUndefined(params.buildParams)) {
      await this.validateHopPrebuild(params.wallet, params.hopTransaction, params.buildParams);
    }
    return params;
  }

  /**
   * Validates that the hop prebuild from the HSM is valid and correct
   * @param wallet The wallet that the prebuild is for
   * @param hopPrebuild The prebuild to validate
   * @param originalParams The original parameters passed to prebuildTransaction
   * @returns void
   * @throws Error if The prebuild is invalid
   */
  async validateHopPrebuild(
    wallet: IWallet,
    hopPrebuild: HopPrebuild,
    originalParams?: { recipients: Recipient[] }
  ): Promise<void> {
    const { tx, id, signature } = hopPrebuild;

    // first, validate the HSM signature
    const serverXpub = common.Environments[this.bitgo.getEnv()].hsmXpub;
    const serverPubkeyBuffer: Buffer = bip32.fromBase58(serverXpub).publicKey;
    const signatureBuffer: Buffer = Buffer.from(optionalDeps.ethUtil.stripHexPrefix(signature), 'hex');
    const messageBuffer: Buffer =
      hopPrebuild.type === 'Export'
        ? Buffer.from(AvaxpLib.Utils.cb58Decode(id))
        : Buffer.from(optionalDeps.ethUtil.stripHexPrefix(id), 'hex');

    const sig = new Uint8Array(signatureBuffer.length === 64 ? signatureBuffer : signatureBuffer.slice(1));
    const isValidSignature: boolean = secp256k1.ecdsaVerify(sig, messageBuffer, serverPubkeyBuffer);
    if (!isValidSignature) {
      throw new Error(`Hop txid signature invalid`);
    }

    if (hopPrebuild.type === 'Export') {
      const explainHopExportTx = await this.explainAtomicTransaction(tx);
      // If original params are given, we can check them against the transaction prebuild params
      if (!_.isNil(originalParams)) {
        const { recipients } = originalParams;

        // Then validate that the tx params actually equal the requested params to nano avax plus import tx fee.
        const originalAmount = new BigNumber(recipients[0].amount).div(1e9).plus(1e6).toFixed(0);
        const originalDestination: string | undefined = recipients[0].address;
        const hopAmount = explainHopExportTx.outputAmount;
        const hopDestination = explainHopExportTx.outputs[0].address;
        if (originalAmount !== hopAmount) {
          throw new Error(`Hop amount: ${hopAmount} does not equal original amount: ${originalAmount}`);
        }
        if (originalDestination && hopDestination.toLowerCase() !== originalDestination.toLowerCase()) {
          throw new Error(
            `Hop destination: ${hopDestination} does not equal original recipient: ${originalDestination}`
          );
        }
      }
      // TODO(BG-59774): Implement verifySignature without using Private Key
      if (explainHopExportTx.id !== id) {
        throw new Error(`Signed hop txid does not equal actual txid`);
      }
    } else {
      const builtHopTx = optionalDeps.EthTx.TransactionFactory.fromSerializedData(optionalDeps.ethUtil.toBuffer(tx));
      // If original params are given, we can check them against the transaction prebuild params
      if (!_.isNil(originalParams)) {
        const { recipients } = originalParams;

        // Then validate that the tx params actually equal the requested params
        const originalAmount = new BigNumber(recipients[0].amount);
        const originalDestination: string = recipients[0].address;

        const hopAmount = new BigNumber(optionalDeps.ethUtil.bufferToHex(builtHopTx.value as unknown as Buffer));
        if (!builtHopTx.to) {
          throw new Error(`Transaction does not have a destination address`);
        }
        const hopDestination = builtHopTx.to.toString();
        if (!hopAmount.eq(originalAmount)) {
          throw new Error(`Hop amount: ${hopAmount} does not equal original amount: ${originalAmount}`);
        }
        if (hopDestination.toLowerCase() !== originalDestination.toLowerCase()) {
          throw new Error(`Hop destination: ${hopDestination} does not equal original recipient: ${hopDestination}`);
        }
      }

      if (!builtHopTx.verifySignature()) {
        // We dont want to continue at all in this case, at risk of AVAX being stuck on the hop address
        throw new Error(`Invalid hop transaction signature, txid: ${id}`);
      }
      if (optionalDeps.ethUtil.addHexPrefix(builtHopTx.hash().toString('hex')) !== id) {
        throw new Error(`Signed hop txid does not equal actual txid`);
      }
    }
  }

  /**
   * Helper function for signTransaction for the rare case that SDK is doing the second signature
   * Note: we are expecting this to be called from the offline vault
   * @param params.txPrebuild
   * @param params.prv
   * @returns {{txHex: string}}
   */
  async signFinal(params: SignFinalOptions): Promise<FullySignedTransaction> {
    const keyPair = new AvaxcKeyPair({ prv: params.prv });
    const signingKey = keyPair.getKeys().prv;
    if (_.isUndefined(signingKey)) {
      throw new Error('missing private key');
    }

    const txBuilder = this.getTransactionBuilder() as TransactionBuilder;
    try {
      txBuilder.from(params.txPrebuild!.halfSigned!.txHex);
    } catch (e) {
      throw new Error('invalid half-signed transaction');
    }

    txBuilder.sign({ key: signingKey });
    const tx = await txBuilder.build();
    return {
      txHex: tx.toBroadcastFormat(),
    };
  }

  /**
   * Assemble half-sign prebuilt transaction
   * @param params
   */
  async signTransaction(params: AvaxSignTransactionOptions): Promise<SignedTransaction> {
    // Normally the SDK provides the first signature for an AVAXC tx,
    // but for unsigned sweep recoveries it can provide the second and final one.
    if (params.isLastSignature) {
      // In this case when we're doing the second (final) signature, the logic is different.
      return await this.signFinal(params as unknown as SignFinalOptions);
    }

    const txBuilder = this.getTransactionBuilder() as TransactionBuilder;
    txBuilder.from(params.txPrebuild.txHex);
    txBuilder.transfer().key(new AvaxcKeyPair({ prv: params.prv }).getKeys().prv!);
    const transaction = await txBuilder.build();

    const recipients = transaction.outputs.map((output) => ({ address: output.address, amount: output.value }));

    const txParams = {
      eip1559: params.txPrebuild.eip1559,
      txHex: transaction.toBroadcastFormat(),
      recipients: recipients,
      expireTime: params.txPrebuild.expireTime,
      hopTransaction: params.txPrebuild.hopTransaction,
      custodianTransactionId: params.custodianTransactionId,
    };

    return { halfSigned: txParams };
  }

  /**
   * Modify prebuild before sending it to the server. Add things like hop transaction params
   * @param buildParams The whitelisted parameters for this prebuild
   * @param buildParams.hop True if this should prebuild a hop tx, else false
   * @param buildParams.recipients The recipients array of this transaction
   * @param buildParams.wallet The wallet sending this tx
   * @param buildParams.walletPassphrase the passphrase for this wallet
   */
  async getExtraPrebuildParams(buildParams: BuildOptions): Promise<BuildOptions> {
    if (
      !_.isUndefined(buildParams.hop) &&
      buildParams.hop &&
      !_.isUndefined(buildParams.wallet) &&
      !_.isUndefined(buildParams.recipients) &&
      !_.isUndefined(buildParams.walletPassphrase)
    ) {
      if (this.isToken()) {
        throw new Error(
          `Hop transactions are not enabled for AVAXC tokens, nor are they necessary. Please remove the 'hop' parameter and try again.`
        );
      }
      return (await this.createHopTransactionParams({
        wallet: buildParams.wallet,
        recipients: buildParams.recipients,
        walletPassphrase: buildParams.walletPassphrase,
        type: buildParams.type,
      })) as any;
    }
    return {};
  }

  /**
   * Creates the extra parameters needed to build a hop transaction
   * @param buildParams The original build parameters
   * @returns extra parameters object to merge with the original build parameters object and send to the platform
   */
  async createHopTransactionParams({
    wallet,
    recipients,
    walletPassphrase,
    type,
  }: HopTransactionBuildOptions): Promise<HopParams> {
    if (!recipients || !Array.isArray(recipients)) {
      throw new Error('expecting array of recipients');
    }

    // Right now we only support 1 recipient
    if (recipients.length !== 1) {
      throw new Error('must send to exactly 1 recipient');
    }
    const recipientAddress = recipients[0].address;
    const recipientAmount = recipients[0].amount;
    const feeEstimateParams = {
      recipient: recipientAddress,
      amount: recipientAmount,
      hop: true,
      type,
    };
    const feeEstimate: FeeEstimate = await this.feeEstimate(feeEstimateParams);

    const gasLimit = feeEstimate.gasLimitEstimate;
    const gasPrice = Math.round(feeEstimate.feeEstimate / gasLimit);
    const gasPriceMax = gasPrice * 5;
    // Payment id a random number so its different for every tx
    const paymentId = Math.floor(Math.random() * 10000000000).toString();

    // TODO(BG-62671): after completed [Wallet-platform] Remove use of userReqSig for avaxc hop transaction
    const userReqSig = '0x';

    return {
      hopParams: {
        userReqSig,
        gasPriceMax,
        paymentId,
      },
      gasLimit,
    };
  }

  /**
   * Fetch fee estimate information from the server
   * @param {Object} params The params passed into the function
   * @param {Boolean} [params.hop] True if we should estimate fee for a hop transaction
   * @param {String} [params.recipient] The recipient of the transaction to estimate a send to
   * @param {String} [params.data] The ETH tx data to estimate a send for
   * @returns {Object} The fee info returned from the server
   */
  async feeEstimate(params: FeeEstimateOptions): Promise<FeeEstimate> {
    const query: FeeEstimateOptions = {};
    if (params && params.hop) {
      query.hop = params.hop;
    }
    if (params && params.recipient) {
      query.recipient = params.recipient;
    }
    if (params && params.data) {
      query.data = params.data;
    }
    if (params && params.amount) {
      query.amount = params.amount;
    }
    if (params && params.type) {
      query.type = params.type;
    }

    return await this.bitgo.get(this.url('/tx/fee')).query(query).result();
  }

  /**
   * Gets the hop digest for the user to sign. This is validated in the HSM to prove that the user requested this tx
   * @param paramsArr The parameters to hash together for the digest
   */
  static getHopDigest(paramsArr: string[]): Buffer {
    const hash = Keccak('keccak256');
    hash.update([AvaxC.hopTransactionSalt, ...paramsArr].join('$'));
    return hash.digest();
  }

  async isWalletAddress(params: VerifyAddressOptions): Promise<boolean> {
    // TODO: Fix this later
    return true;
  }

  /**
   * Ensure either enterprise or newFeeAddress is passed, to know whether to create new key or use enterprise key
   * @param params
   * @param params.enterprise {String} the enterprise id to associate with this key
   * @param params.newFeeAddress {Boolean} create a new fee address (enterprise not needed in this case)
   */
  preCreateBitGo(params: PrecreateBitGoOptions): void {
    // We always need params object, since either enterprise or newFeeAddress is required
    if (!_.isObject(params)) {
      throw new Error(`preCreateBitGo must be passed a params object. Got ${params} (type ${typeof params})`);
    }

    if (_.isUndefined(params.enterprise) && _.isUndefined(params.newFeeAddress)) {
      throw new Error(
        'expecting enterprise when adding BitGo key. If you want to create a new AVAX bitgo key, set the newFeeAddress parameter to true.'
      );
    }

    // Check whether key should be an enterprise key or a BitGo key for a new fee address
    if (!_.isUndefined(params.enterprise) && !_.isUndefined(params.newFeeAddress)) {
      throw new Error(`Incompatible arguments - cannot pass both enterprise and newFeeAddress parameter.`);
    }

    if (!_.isUndefined(params.enterprise) && !_.isString(params.enterprise)) {
      throw new Error(`enterprise should be a string - got ${params.enterprise} (type ${typeof params.enterprise})`);
    }

    if (!_.isUndefined(params.newFeeAddress) && !_.isBoolean(params.newFeeAddress)) {
      throw new Error(
        `newFeeAddress should be a boolean - got ${params.newFeeAddress} (type ${typeof params.newFeeAddress})`
      );
    }
  }

  getAvaxP(): string {
    return this.getChain().toString() === 'avaxc' ? 'avaxp' : 'tavaxp';
  }
}


text:
import React from 'react'
import test from 'tape'
import { shallow } from 'enzyme'
import Title from '../../src/components/Title';

test('<Title /> component', t => {
  t.plan(1)
  const text = 'Welcome to My World'
  const title = shallow(<Title title={text} />)
  t.equal(text, title.find('h3').text(), 'renders title prop in h3')
})


text:
import bisect

from torch.utils.data.dataset import ConcatDataset as _ConcatDataset

class ConcatDataset(_ConcatDataset):
    """
    Same as torch.utils.data.dataset.ConcatDataset, but exposes an extra
    method for querying the sizes of the image
    """

    def get_idxs(self, idx):
        dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)
        if dataset_idx == 0:
            sample_idx = idx
        else:
            sample_idx = idx - self.cumulative_sizes[dataset_idx - 1]
        return dataset_idx, sample_idx

    def get_img_info(self, idx):
        dataset_idx, sample_idx = self.get_idxs(idx)
        return self.datasets[dataset_idx].get_img_info(sample_idx)


text:
using System;
using System.Threading.Tasks;

using Microsoft.AspNet.Identity;

using Moq;

using NUnit.Framework;

using Ploeh.AutoFixture;

using RememBeer.Business.Services;
using RememBeer.Models.Factories;
using RememBeer.Models.Identity.Contracts;
using RememBeer.Tests.Utils;

namespace RememBeer.Tests.Business.Services.UserServiceTests
{
    [TestFixture]
    public class EnableUser_Should : TestClassBase
    {
        [Test]
        public void CallUserManagerSetLockoutEndDateAsyncMethodOnceWithCorrectParams()
        {
            var expectedId = this.Fixture.Create<string>();
            var userManager = new Mock<IApplicationUserManager>();
            userManager.Setup(m => m.SetLockoutEndDateAsync(expectedId, DateTimeOffset.MinValue))
                       .Returns(Task.FromResult(IdentityResult.Success));

            var signInManager = new Mock<IApplicationSignInManager>();
            var modelFactory = new Mock<IModelFactory>();

            var service = new UserService(userManager.Object,
                                          signInManager.Object,
                                          modelFactory.Object);

            var result = service.EnableUser(expectedId);

            userManager.Verify(m => m.SetLockoutEndDateAsync(expectedId, DateTimeOffset.MinValue), Times.Once);
        }

        [Test]
        public void ReturnResultFrom_UserManagerSetLockoutEndDateAsyncMethod()
        {
            var expectedResult = IdentityResult.Success;
            var id = this.Fixture.Create<string>();

            var userManager = new Mock<IApplicationUserManager>();
            userManager.Setup(m => m.SetLockoutEndDateAsync(It.IsAny<string>(), It.IsAny<DateTimeOffset>()))
                       .Returns(Task.FromResult(expectedResult));

            var signInManager = new Mock<IApplicationSignInManager>();
            var modelFactory = new Mock<IModelFactory>();

            var service = new UserService(userManager.Object,
                                          signInManager.Object,
                                          modelFactory.Object);

            var result = service.EnableUser(id);

            Assert.AreSame(expectedResult, result);
        }
    }
}


text:
#ifndef ANDROID_BPBINDER_H
#define ANDROID_BPBINDER_H

#include <binder/IBinder.h>
#include <utils/KeyedVector.h>
#include <utils/Mutex.h>
#include <utils/threads.h>

#include <unordered_map>

// ---------------------------------------------------------------------------
namespace android {

using binder_proxy_limit_callback = void(*)(int);

class BpBinder : public IBinder
{
public:
    static BpBinder*    create(int32_t handle);

    inline  int32_t     handle() const { return mHandle; }

    virtual const String16&    getInterfaceDescriptor() const;
    virtual bool        isBinderAlive() const;
    virtual status_t    pingBinder();
    virtual status_t    dump(int fd, const Vector<String16>& args);

    // NOLINTNEXTLINE(google-default-arguments)
    virtual status_t    transact(   uint32_t code,
                                    const Parcel& data,
                                    Parcel* reply,
                                    uint32_t flags = 0);

    // NOLINTNEXTLINE(google-default-arguments)
    virtual status_t    linkToDeath(const sp<DeathRecipient>& recipient,
                                    void* cookie = nullptr,
                                    uint32_t flags = 0);

    // NOLINTNEXTLINE(google-default-arguments)
    virtual status_t    unlinkToDeath(  const wp<DeathRecipient>& recipient,
                                        void* cookie = nullptr,
                                        uint32_t flags = 0,
                                        wp<DeathRecipient>* outRecipient = nullptr);

    virtual void        attachObject(   const void* objectID,
                                        void* object,
                                        void* cleanupCookie,
                                        object_cleanup_func func);
    virtual void*       findObject(const void* objectID) const;
    virtual void        detachObject(const void* objectID);

    virtual BpBinder*   remoteBinder();

            status_t    setConstantData(const void* data, size_t size);
            void        sendObituary();

    static uint32_t     getBinderProxyCount(uint32_t uid);
    static void         getCountByUid(Vector<uint32_t>& uids, Vector<uint32_t>& counts);
    static void         enableCountByUid();
    static void         disableCountByUid();
    static void         setCountByUidEnabled(bool enable);
    static void         setLimitCallback(binder_proxy_limit_callback cb);
    static void         setBinderProxyCountWatermarks(int high, int low);

    class ObjectManager
    {
    public:
                    ObjectManager();
                    ~ObjectManager();

        void        attach( const void* objectID,
                            void* object,
                            void* cleanupCookie,
                            IBinder::object_cleanup_func func);
        void*       find(const void* objectID) const;
        void        detach(const void* objectID);

        void        kill();

    private:
                    ObjectManager(const ObjectManager&);
        ObjectManager& operator=(const ObjectManager&);

        struct entry_t
        {
            void* object;
            void* cleanupCookie;
            IBinder::object_cleanup_func func;
        };

        KeyedVector<const void*, entry_t> mObjects;
    };

protected:
                        BpBinder(int32_t handle,int32_t trackedUid);
    virtual             ~BpBinder();
    virtual void        onFirstRef();
    virtual void        onLastStrongRef(const void* id);
    virtual bool        onIncStrongAttempted(uint32_t flags, const void* id);

private:
    const   int32_t             mHandle;

    struct Obituary {
        wp<DeathRecipient> recipient;
        void* cookie;
        uint32_t flags;
    };

            void                reportOneDeath(const Obituary& obit);
            bool                isDescriptorCached() const;

    mutable Mutex               mLock;
            volatile int32_t    mAlive;
            volatile int32_t    mObitsSent;
            Vector<Obituary>*   mObituaries;
            ObjectManager       mObjects;
            Parcel*             mConstantData;
    mutable String16            mDescriptorCache;
            int32_t             mTrackedUid;

    static Mutex                                sTrackingLock;
    static std::unordered_map<int32_t,uint32_t> sTrackingMap;
    static int                                  sNumTrackedUids;
    static std::atomic_bool                     sCountByUidEnabled;
    static binder_proxy_limit_callback          sLimitCallback;
    static uint32_t                             sBinderProxyCountHighWatermark;
    static uint32_t                             sBinderProxyCountLowWatermark;
    static bool                                 sBinderProxyThrottleCreate;
};

}; // namespace android

// ---------------------------------------------------------------------------

#endif // ANDROID_BPBINDER_H


text:
require "chingu"
include Chingu
include Gosu

Dir["#{File.dirname(__FILE__)}/../lib/*.rb"].each {|f| require f}

require "rspec"

#RSpec.configure do |config|
#  config.mock_with :rspec
#end


text:
package com.redpois0n.gscrot.ui.settings;

@SuppressWarnings("serial")
public class ImageSettingsPanel extends AbstractSettingsPanel {

	public ImageSettingsPanel() {

	}

}


text:
// ------------------------------------------------------------
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace xray.Common
{
    using System;
    using System.Fabric;

    public class ServiceUriBuilder
    {
        public ServiceUriBuilder(string serviceInstance)
        {
            this.ServiceInstance = serviceInstance;
        }

        public ServiceUriBuilder(string applicationInstance, string serviceInstance)
        {
            this.ApplicationInstance = applicationInstance;
            this.ServiceInstance = serviceInstance;
        }

        /// <summary>
        /// The name of the application instance that contains he service.
        /// </summary>
        public string ApplicationInstance { get; set; }

        /// <summary>
        /// The name of the service instance.
        /// </summary>
        public string ServiceInstance { get; set; }

        public Uri Build()
        {
            string applicationInstance = this.ApplicationInstance;

            if (String.IsNullOrEmpty(applicationInstance))
            {
                try
                {
                    // the ApplicationName property here automatically prepends "fabric:/" for us
                    applicationInstance = FabricRuntime.GetActivationContext().ApplicationName.Replace("fabric:/", String.Empty);
                }
                catch (InvalidOperationException)
                {
                    // FabricRuntime is not available.
                    // This indicates that this is being called from somewhere outside the Service Fabric cluster.
                    applicationInstance = "xray";
                }
            }

            return new Uri("fabric:/" + applicationInstance + "/" + this.ServiceInstance);
        }
    }
}


text:
package Mod.Gui;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;

import org.lwjgl.opengl.GL11;

import Mod.Container.ContainerElectricFurnace;
import Mod.TileEntity.TileEntityElectricFurnace;

public class GuiElectricFurnace extends GuiContainer{

	private TileEntityElectricFurnace tile;
	private final ResourceLocation Texture = new ResourceLocation("miscitems" , "textures/gui/ElectricFurnaceGui.png");

	public GuiElectricFurnace(InventoryPlayer InvPlayer, TileEntityElectricFurnace tile) {
		super(new ContainerElectricFurnace(InvPlayer, tile));

		this.xSize = 176;
		this.ySize = 166;

		this.tile = tile;
	}

  @Override
  protected void drawGuiContainerForegroundLayer(int param1, int param2) {

          fontRenderer.drawString(StatCollector.translateToLocal("container.inventory"), 8, ySize - 96 + 2, 4210752);
          fontRenderer.drawString(StatCollector.translateToLocal("gui.electricfurnace"), 2, 3, 4210752);

  }

	@Override
	protected void drawGuiContainerBackgroundLayer(float f, int X, int Y)
	{
	    GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

	    Minecraft.getMinecraft().renderEngine.bindTexture(Texture);

	         int x = (this.width - this.xSize) / 2;
	         int y = (this.height - this.ySize) / 2;
	         drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);

	         int WorkTime = this.tile.GetWorkTime();

	         if(WorkTime > 0)
	             this.drawTexturedModalRect(x + 85, y + 35, 176, 0, WorkTime / 4, 17);

	         int Power = this.tile.GetPower();
	         fontRenderer.drawString(StatCollector.translateToLocal("words.power") + ": " + Power + "/" + tile.PowerMax, x + 5, y + 39, 4210752);

	}

}


text:
package org.drools.karaf.itest;

import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.scanFeatures;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.inject.Inject;

import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.options.MavenArtifactProvisionOption;
import org.ops4j.pax.exam.options.UrlReference;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext;

public class KieSpringIntegrationTestSupport {

    protected static final transient Logger LOG = LoggerFactory.getLogger(KieSpringIntegrationTestSupport.class);
    protected static final String DroolsVersion;
    static {
        Properties testProps = new Properties();
        try {
            testProps.load(KieSpringIntegrationTestSupport.class.getResourceAsStream("/test.properties"));
        } catch (Exception e) {
            throw new RuntimeException("Unable to initialize DroolsVersion property: " + e.getMessage(), e);
        }
        DroolsVersion = testProps.getProperty("project.version");
        LOG.info("Drools Project Version : " + DroolsVersion);
    }

    protected OsgiBundleXmlApplicationContext applicationContext;

    @Inject
    protected BundleContext bc;

    protected void refresh() {
        applicationContext.setBundleContext(bc);
        applicationContext.refresh();
    }

    public static MavenArtifactProvisionOption getFeaturesUrl(String groupId, String artifactId, String version) {
        MavenArtifactProvisionOption mapo =  mavenBundle().groupId(groupId).artifactId(artifactId);
        mapo.type("xml");
        mapo.classifier("features");

        if (version == null) {
            mapo.versionAsInProject();
        } else {
            mapo.version(version);
        }

        LOG.info("Features URL : " + mapo.getURL());

        return mapo;
    }

    public static UrlReference getCamelKarafFeaturesUrl(String version) {
        MavenArtifactProvisionOption mapo = getFeaturesUrl("org.apache.camel.karaf", "apache-camel", version);
        return mapo;
    }

    public static Option loadDroolsKieFeatures(String... features) {
        List<String> result = new ArrayList<String>();
        result.add("drools-module");
        for (String feature : features) {
            result.add(feature);
        }

        return scanFeatures(getFeaturesUrl("org.drools","drools-karaf-features",DroolsVersion), result.toArray(new String[4 + features.length]));
    }

}


text:
// Copyright 2012 Mark Cavage, Inc.  All rights reserved.

var assert = require('assert-plus');

// The following two functions are courtesy of expressjs
// as is req.accepts(), and req.is() below.
//
// https://github.com/visionmedia/express

function quality(str) {
        var parts = str.split(/ *; */);
        var val = parts[0];
        var q = parts[1] ? parseFloat(parts[1].split(/ *= */)[1]) : 1;

        return ({value: val, quality: q});
}

/**
 * Parses an HTTP header string with quality values into a sorted array
 *
 * @param {String} str header value
 */
function parseQuality(str) {
        /* JSSTYLED */
        str = str.split(/ *, */).map(quality).filter(function (obj) {
                return (obj.quality);
        }).sort(function (a, b) {
                return (b.quality - a.quality);
        });

        return (str);
}

/**
 * Cleans up sloppy URL paths, like /foo////bar/// to /foo/bar.
 *
 * @param {String} path the HTTP resource path.
 * @return {String} Cleaned up form of path.
 */
function sanitizePath(path) {
        assert.ok(path);

        // Be nice like apache and strip out any //my//foo//bar///blah
        path = path.replace(/\/\/+/g, '/');

        // Kill a trailing '/'
        if (path.lastIndexOf('/') === (path.length - 1) && path.length > 1)
                path = path.substr(0, path.length - 1);

        return (path);
}

///--- Exports

module.exports = {
        parseQuality: parseQuality,
        sanitizePath: sanitizePath
};


text:
***KBase Metrics repo***

This repo contains code for gathering/loading KBase usage metrics.

**Usage**

Before being able to run this docker container
a ".env" file needs to be made. It should be called .env (nothing before the dot).
cp the example.env to .env
Then alter the file to include the correct information.

The script in hooks/build is used to build a docker image named "metrics" from the current contents of the repo. You can simply run it by
~~~
hooks/build
~~~
It fulls in import metadata about the docker image, and is used by the dockerhub and travis automated build machinery.

After the image is built, you can use the docker-compose command to run the image using the environment variables defined in the .env file mentioned above:

~~~
docker-compose run --rm metrics
~~~

That will take you into t150ca6f61fb2411e607f15fb91407a83305daaf6he docker environment (source folder of the metrics repo).
From there you can run any program in that folder.

------------------

If want to run a shell script. Here is an exmple with capturing the redirect in the environment that called Docker.

docker-compose > user_info_dump.txt run metrics ../bin/custom_scripts/dump_query_results.sh

Put executables in the bin directory we will call scripts this way for the CRON jobs
The cron jobs should run the following:
docker-compose run --rm metrics ../bin/master_cron_shell.sh

this under the hood calls
source/daily/upload_user_stats.py
source/daily/upload_app_stats.py
source//daily/upload_app_category_mappings.py
source/daily/upload_public_narratives_count.py
source/daily/make_reporting_tables.py

-------------------

CRON Jobs are run from mysql-metrics

They are stored at: crontab -e on mysql-metrics

There are nightly CRON jobs that get run are located in bin/master_cron_shell.sh
which runs scripts from the source/daily directory

Then there are also monthly CRON jobs that get run are located in bin/upload_workspace_stats.sh
It used to be workspaces (user info needed first for FK potential issues), but now it also conatins scripts for
DOI metrics.)
Runs scripts from source/monthly directory

These create Logs to keep track of (note nightly metrics is calling master_cron_shell
01 17 * * * /root/metrics/nightly_metrics.sh >>/mnt/metrics_logs/crontab_nightly 2>&1
01 0  1 * * /root/metrics/monthly_metrics.sh >>/mnt/metrics_logs/crontab_monthly 2>&1
01 0  15 * * /root/metrics/monthly_metrics.sh >>/mnt/metrics_logs/crontab_doi_monthly 2>&1
01 07 * * * /root/metrics/nightly_errorlogs.sh >>/mnt/metrics_logs/crontab_errorlogs 2>&1

From Docker03 the logs can be checked by going doing the following. (Note no y at end of monthly)
cat /mnt/nfs3/data1/metrics/crontab_logs/crontab_nightly
cat /mnt/nfs3/data1/metrics/crontab_logs/crontab_monthly
cat /mnt/nfs3/data1/metrics/crontab_logs/crontab_doi_monthly

Can also confirm things ran by looking in the database (if not need to do backfills).
Example: (should be first of each month)
select DATE_FORMAT(`record_date`,'%Y-%m') as narrative_cron_month, count(*) as narrative_count from metrics.workspaces ws group by narrative_cron_month;

For elastic Search session information: (this is daily numbers)
select record_date, count(*) from session_info group by record_date;

--------------------
**Note on old contents**

The old contents of the metrics repo have been deleted from the current tree. The final commit containing
them was 150ca6f, if you need access to them, you can rollback your local copy of the repo to that commit,
or else just go to the following link:

   https://github.com/kbase/metrics/tree/150ca6f61fb2411e607f15fb91407a83305daaf6


text:
<?php return array (
  'Title Size' => 'Titel formaat',
  'Muted' => '',
  'Main Style' => '',
  'H3' => 'H3',
  'Full viewport height' => 'Volledige viewport hoogte',
  'Alignment' => 'Uitlijning',
  'Show the sidebar before the content.' => 'Weergeef de zijbalk voor de inhoud.',
  'Center the title and content.' => 'Centreer de titel en de inhoud',
  'Read more' => 'Lees meer',
  'Select an alternative logo which looks great on images.' => 'Selecteer een alternatief logo voor over afbeeldingen',
  'Box Secondary' => 'Secundaire blok',
  'Select a background image for the hero position.' => 'Selecteer een achtergrondafbeelding als uitgelichte afbeelding.',
  'Transparent navbar as overlay' => 'Doorzichtige navigatiebalk op voorgrond',
  'H1' => 'H1',
  'Theme' => 'Thema',
  'None' => '',
  'Sidebar' => 'Zijbalk',
  'Default' => 'Standaard',
  'Top Style' => '',
  'Written by %name% on %date%' => 'Geschreven door %name% op %date%',
  'HTML Class' => 'HTML class',
  'Logo Contrast' => 'Logo contrast',
  'Invert colors' => 'Negatieve kleuren',
  'Box Primary' => 'Primaire blok',
  'Logo Off-canvas' => '',
  'Save' => 'Opslaan',
  'Hero Image' => 'Uitgelichte afbeelding',
  'Title' => 'Titel',
  'H2' => 'H2',
  'Header' => 'Header',
  'Panel Style' => 'Paneel stijl',
  'Hide Title' => 'Verberg titel',
  'Bottom Style' => '',
  '{0} No comments|{1} %num% Comment|]1,Inf[ %num% Comments' => '{0} Geen reacties|{1} %num% Reactie|]1,Inf[ %num% Reacties',
  'Enable parallax effect' => '',
  'Extra large title.' => 'Extra grote titel.',
  'H4' => 'H4',
  'Select an optional logo for the off-canvas menu.' => '',
  'Box' => 'Blok',
);


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="UnityThemeSelector" parent="android:Theme.Holo.Light.NoActionBar.Fullscreen">
</style>
</resources>


text:
/**
 * Client
 */

var events = require('events');
var crypto = require('crypto');
var inherits = require('util').inherits;
var Promise = require('bluebird').Promise;

var Schema = require('./schema');
Schema.Connection = require('./connection').Connection;

var DEFAULT_HOST = 'api.schema.io';
var DEFAULT_PORT = 8443;
var DEFAULT_VERIFY_CERT = true;
var DEFAULT_VERSION = 1;

/**
 * Client constructor
 *
 * @param  string clientId
 * @param  string clientKey
 * @param  object options
 * @param  function callback
 */
var Client = function(clientId, clientKey, options, callback) {

  events.EventEmitter.call(this);

  this.server = null;

  if (clientId) {
    this.init(clientId, clientKey, options);
  }
  if (callback) {
    this.connect(callback);
  }
};

inherits(Client, events.EventEmitter);

/**
 * Initialize client parameters
 *
 * @param  string clientId
 * @param  string clientKey
 * @param  object options
 */
Client.prototype.init = function(clientId, clientKey, options) {

  options = options || {};

  if (typeof clientKey === 'object') {
    options = clientKey;
    clientKey = undefined;
  } else if (typeof clientId === 'object') {
    options = clientId;
    clientId = undefined;
  }

  this.params = {
    clientId: clientId || options.id,
    clientKey: clientKey || options.key,
    host: options.host || DEFAULT_HOST,
    port: options.port || DEFAULT_PORT,
    verifyCert: options.verifyCert !== undefined ? options.verifyCert : DEFAULT_VERIFY_CERT,
    version: options.version || DEFAULT_VERSION,
    session: options.session,
    route: options.route,
    routeClientId: options.route && options.route.client
  };

  if (!this.params.clientId) {
    throw new Error('Schema client `id` is required to initialize');
  }
  if (!this.params.clientKey) {
    throw new Error('Schema client `key` is required to initialize');
  }
};

/**
 * Connect to server
 *
 * @param  function callback
 */
Client.prototype.connect = function(callback) {

  var self = this;
  this.server = new Schema.Connection(
    this.params.host,
    this.params.port,
    {
      verifyCert: this.params.verifyCert
    },
    function() {
      callback && callback(self);
      self.emit('connect', self);
    }
  );
  this.server.on('close', function() {
    self.emit('close');
  });
  this.server.on('error', function(err) {
    if (events.EventEmitter.listenerCount(self, 'error')) {
      self.emit('error', 'Error: '+err);
    }
  });
  this.server.on('error.network', function(err) {
    if (events.EventEmitter.listenerCount(self, 'error')) {
      self.emit('error', 'Network Error: '+err, 'network');
    }
  });
  this.server.on('error.protocol', function(err) {
    if (events.EventEmitter.listenerCount(self, 'error')) {
      self.emit('error', 'Protocol Error: '+err, 'protocol');
    }
  });
  this.server.on('error.server', function(err) {
    if (events.EventEmitter.listenerCount(self, 'error')) {
      self.emit('error', 'Server Error: '+err, 'server');
    }
  });
};

/**
 * Client request handler
 *
 * @param  string method
 * @param  string url
 * @param  mixed data
 * @param  function callback
 */
Client.prototype.request = function(method, url, data, callback) {

  if (typeof data === 'function') {
    callback = data;
    data = null;
  }

  // TODO: implement $cached

  if (!this.server) {
    this.connect();
  }

  // Resolve data as promised
  var promises = this.promisifyData(data);
  if (promises.length) {
    return Promise.all(promises).bind(this).then(function() {
      this.request(method, url, data, callback);
    });
  }

  // Prepare url and data for request
  url = url && url.toString ? url.toString() : '';
  data = {$data: data};

  if (this.authed !== true) {
    data.$client = this.params.clientId;
    data.$key = this.params.clientKey;

    if (this.params.route) {
      data.$route = this.params.route;
    }
  }

  var self = this;
  return new Promise(function(resolve, reject) {
    var responder = function(err, data, response) {
      if (callback) {
        callback(err, data, response);
      }
      if (err) {
        reject(err);
      } else {
        resolve(data, response);
      }
    };
    self.server.request(method, url, data, function(response) {
      if (response.$auth) {
        if (response.$end) {
          // Connection ended, retry auth
          return self.request(method, url, data.$data, callback);
        } else {
          self.authed = true;
          return self.auth(response.$auth, function(response) {
            return self.respond(method, url, response, responder);
          });
        }
      } else {
        return self.respond(method, url, response, responder);
      }
    });
  });
};

/**
 * Resolve and return promises array from data
 * Only resolve top level object keys
 *
 * @param  object data
 * @return array
 */
Client.prototype.promisifyData = function(data) {

  if (!data) {
    return [];
  }

  function thenResolvePromisedValue(data, key) {
    data[key].then(function(val) {
      data[key] = val;
    });
  }

  var promises = [];
  if (typeof data === 'object') {
    var keys = Object.keys(data);
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];
      if (data[key] && data[key].then) {
        promises.push(data[key]);
        thenResolvePromisedValue(data, key);
      }
    }
  } else if (data instanceof Array) {
    for (var i = 0; i < data.length; i++) {
      if (data[i] && data[i].then) {
        promises.push(data[i]);
        thenResolvePromisedValue(data, i);
      }
    }
  }

  return promises;
};

/**
 * Client response handler
 *
 * @param  string method
 * @param  string url
 * @param  mixed response
 * @param  function callback
 */
Client.prototype.respond = function(method, url, response, callback) {

  var err = undefined;
  var data = undefined;

  if (response) {
    if (response.$error) {
      err = response.$error;
    }
    if (response.$data && (typeof response.$data === 'object')) {
      data = Client.createResource(response.$url || url, response, this);
    } else {
      data = response.$data;
    }
  } else {
    response = {$error: 'Empty response from server', $status: 500};
    err = response.$error;
  }
  return callback.call(this, err, data, response);
};

/**
 * Client GET request
 *
 * @param  string url
 * @param  object data
 * @param  function callback
 * @return mixed
 */
Client.prototype.get = function(url, data, callback) {
  return this.request('get', url, data, callback);
};

/**
 * Client PUT request
 */
Client.prototype.put = function(url, data, callback) {
  return this.request('put', url, data, callback);
};

/**
 * Client POST request
 */
Client.prototype.post = function(url, data, callback) {
  return this.request('post', url, data, callback);
};

/**
 * Client DELETE request
 */
Client.prototype.delete = function(url, data, callback) {
  return this.request('delete', url, data, callback);
};

/**
 * Client auth request
 *
 * @param  object params
 * @param  function callback
 * @return mixed;
 */
Client.prototype.auth = function(nonce, callback) {

  var self = this;
  var clientId = this.params.clientId;
  var clientKey = this.params.clientKey;

  if (typeof nonce === 'function') {
    callback = nonce;
    nonce = null;
  }

  if (!this.server) {
    this.connect();
  }

  // 1) Get nonce
  if (!nonce) {
    return this.server.request('auth', function(nonce) {
      self.auth(nonce, callback);
    });
  }

  // 2) Create key hash
  var keyHash = crypto.createHash('md5')
    .update(clientId + "::" + clientKey)
    .digest('hex');

  // 3) Create auth key
  var authKey = crypto.createHash('md5')
    .update(nonce + clientId + keyHash)
    .digest('hex');

  // 4) Authenticate with client creds and options
  var creds = {
    client: clientId,
    key: authKey
  };
  if (this.params.version) {
    creds.$v = this.params.version;
  }
  if (this.params.session) {
    creds.$session = this.params.session;
  }
  if (this.params.route) {
    creds.$route = this.params.route;
  }

  // TODO: send local $ip address

  return this.server.request('auth', creds, callback);
};

/**
 * Close server connection
 *
 * @return void
 */
Client.prototype.close = function() {

  if (this.server) {
    this.server.close();
  }
};

/**
 * Client create/init helper
 *
 * @param  string clientId
 * @param  string clientKey
 * @param  object options
 * @param  function callback
 * @return Client
 */
Client.create = function(clientId, clientKey, options, callback) {
  return new Client(clientId, clientKey, options, callback);
};

/**
 * Create a resource from response data
 *
 * @param  string url
 * @param  mixed response
 * @param  Client client
 * @return Resource
 */
Client.createResource = function(url, response, client) {
  if (response && response.$data && 'count' in response.$data && response.$data.results) {
    return new Schema.Collection(url, response, client);
  }
  return new Schema.Record(url, response, client);
};

// Exports
module.exports = Schema;
module.exports.Client = Client;
module.exports.createClient = Client.create;