text:
//
//  NSError+MASPrivate.h
//  MASFoundation
//
//  Copyright (c) 2016 CA. All rights reserved.
//
//  This software may be modified and distributed under the terms
//  of the MIT license. See the LICENSE file for details.
//

@import Foundation;

#import "MASConstantsPrivate.h"

@interface NSError (MASPrivate)

///--------------------------------------
/// @name Create general errors
///--------------------------------------

# pragma mark - Create general errors

/**
 * Creates a MAS friendly NSError for the given API error code contained within an HTTP
 * response info NSDictionary, if any.  If not it will check the original NSError for
 * other types of errors, i.e. network issues.
 *
 * All errors will include the following standard keys with applicable values:
 *
 *    NSLocalizedDescriptionKey
 *
 * @param responseInfo The HTTP response info NSDictionary.
 * @param error The original NSError.
 * @returns Returns the MAS friendly NSError instance.
 */
+ (NSError *)errorFromApiResponseInfo:(NSDictionary *)responseInfo andError:(NSError *)error;

/**
 *  Creates a MAS friendly NSError for the given NSError with response info NSDictionary from the server.
 *  A NSError will be created based on response info's contents from MAS' standard format of MASResponseInfoHeaderInfoKey and MASResponseInfoBodyInfoKey.
 *  If the response does not contain sufficient information to create an error, the error will be created based on given NSError with given errorDomain.
 *
 *  @param responseInfo The HTTP response info NSDictionary.
 *  @param error        The original NSError.
 *  @param errorDomain  The error domain for this particular error.
 *
 *  @return Returns the MAS friendly NSError instance.
 */
+ (NSError *)errorForFoundationWithResponseInfo:(NSDictionary *)responseInfo error:(NSError *)error errorDomain:(NSString *)errorDomain;

/**
 * Creates an NSError for the given MASFoundationErrorCode.  These errors will fall
 * under the specified domain in parameter.
 *
 * This version is a convenience version without the info:(NSDictionary *)info
 * parameter for those that don't need to add any custom info.
 *
 * All errors will include the following standard keys with applicable values:
 *
 *    NSLocalizedDescriptionKey
 *
 * @param errorCode The MASFoundationErrorCode which identifies the error.
 * @param errorDomain The NSString of error domain.
 * @returns Returns the NSError instance.
 */
+ (NSError *)errorForFoundationCode:(MASFoundationErrorCode)errorCode errorDomain:(NSString *)errorDomain;

/**
 * Creates an NSError for the given MASFoundationErrorCode.  These errors will fall
 * under the sepcified domain in parameter.
 *
 * All errors will include the following standard keys with applicable values:
 *
 *    NSLocalizedDescriptionKey
 *
 * @param errorCode The MASFoundationErrorCode which identifies the error.
 * @param info An additional NSDictionary of custom values that can be included
 * in addition to the defaults included by this method.  Optional, nil is allowed.
 * @param errorDomain The NSString which identifies the domain of the error.
 * @returns Returns the NSError instance.
 */
+ (NSError *)errorForFoundationCode:(MASFoundationErrorCode)errorCode info:(NSDictionary *)info errorDomain:(NSString *)errorDomain;

///--------------------------------------
/// @name Create specific errors
///--------------------------------------

# pragma mark - Create specific error types

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeInvalidUserLoginBlock.
 *
 *  @return Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error code MASFoundationErrorCodeInvalidUserLoginBlock.
 */
+ (NSError *)errorInvalidUserLoginBlock;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeInvalidOTPChannelSelectionBlock.
 *
 *  @return Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error code MASFoundationErrorCodeInvalidOTPChannelSelectionBlock.
 */
+ (NSError *)errorInvalidOTPChannelSelectionBlock;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeInvalidOTPCredentialsBlock.
 *
 *  @return Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error code MASFoundationErrorCodeInvalidOTPCredentialsBlock.
 */
+ (NSError *)errorInvalidOTPCredentialsBlock;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeOTPNotProvided.
 *
 *  @return Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error code MASFoundationErrorCodeOTPNotProvided.
 */
+ (NSError *)errorOTPCredentialsNotProvided;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeInvalidOTPProvided.
 *
 *  @return Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error code MASFoundationErrorCodeInvalidOTPProvided.
 */
+ (NSError *)errorInvalidOTPCredentials;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeOTPExpired.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeOTPExpired.
 */
+ (NSError *)errorOTPCredentialsExpired;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeOTPRetryLimitExceeded.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeOTPRetryLimitExceeded.
 */
+ (NSError *)errorOTPRetryLimitExceeded:(NSString *)suspensionTime;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeOTPRetryBarred.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeOTPRetryBarred.
 */
+ (NSError *)errorOTPRetryBarred:(NSString *)suspensionTime;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeInvalidNSURL.
 *
 *  @return Retruns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error code MASFoundationErrorCodeInvalidNSURL.
 */
+ (NSError *)errorInvalidNSURL;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeInvalidNSDictionary.
 *
 *  @return Retruns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error code MASFoundationErrorCodeInvalidNSDictionary.
 */
+ (NSError *)errorInvalidNSDictionary;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeApplicationAlreadyRegistered.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomain and
 * error code MASFoundationErrorCodeApplicationAlreadyRegistered.
 */
+ (NSError *)errorApplicationAlreadyRegistered;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeApplicationNotRegistered.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomain and
 * error code MASFoundationErrorCodeApplicationNotRegistered.
 */
+ (NSError *)errorApplicationNotRegistered;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeApplicationRedirectUriInvalid.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomain and
 * error code MASFoundationErrorCodeApplicationRedirectUriInvalid.
 */
+ (NSError *)errorApplicationRedirectUriInvalid;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeConfigurationLoadingFailedFileNotFound.
 *
 * @param fileName The file name of the configuration file which could not be loaded.
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomain and
 * error code MASFoundationErrorCodeConfigurationLoadingFailedFileNotFound.
 */
+ (NSError *)errorConfigurationLoadingFailedFileNotFound:(NSString *)fileName;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeConfigurationLoadingFailedJsonSerialization.
 *
 * @param fileName The file name of the configuration file which could not be loaded.
 * @param description The json serialization error description.
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomain and
 * error code MASFoundationErrorCodeConfigurationLoadingFailedJsonSerialization.
 */
+ (NSError *)errorConfigurationLoadingFailedJsonSerialization:(NSString *)fileName description:(NSString *)description;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeConfigurationLoadingFailedJsonValidation.
 *
 *  @param description The json validation error description
 *
 *  @return Returns an NSerror instance with the domain MASFoundationErrorDomainLocal and error code MASFoundationErrorCodeConfigurationLoadingFailedJsonValidation.
 */
+ (NSError *)errorConfigurationLoadingFailedJsonValidationWithDescription:(NSString *)description;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeDeviceAlreadyRegistered.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeDeviceAlreadyRegistered.
 */
+ (NSError *)errorDeviceAlreadyRegistered;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeDeviceAlreadyRegisteredWithDifferentFlow.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeDeviceRegisteredWithDifferentFlow.
 */
+ (NSError *)errorDeviceAlreadyRegisteredWithDifferentFlow;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeDeviceCouldNotBeDeregistered.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeDeviceCouldNotBeDeregistered.
 */
+ (NSError *)errorDeviceCouldNotBeDeregistered;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeDeviceNotRegistered.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeDeviceNotRegistered.
 */
+ (NSError *)errorDeviceNotRegistered;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeDeviceNotLoggedIn
 *
 *  @return Returns an NSError instance with the domain MASFoundationErrorDomainLocal and error code MASFoundationErrorCodeDeviceNotLoggedIn.
 */
+ (NSError *)errorDeviceNotLoggedIn;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeDeviceRegistrationAttempedWithUnregisteredScope.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeDeviceRegistrationAttemptedWithUnregisteredScope.
 */
+ (NSError *)errorDeviceRegistrationAttemptedWithUnregisteredScope;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeDeviceRegistrationWithoutRequiredParameters.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeDeviceWithoutRequiredParameters.
 */
+ (NSError *)errorDeviceRegistrationWithoutRequiredParameters;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeDeviceDoesNotSupportLocalAuthentication.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeDeviceDoesNotSupportLocalAuthentication.
 */
+ (NSError *)errorDeviceDoesNotSupportLocalAuthentication;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeFlowIsNotActive.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeFlowIsNotActive.
 */
+ (NSError *)errorFlowIsNotActive;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeFlowIsNotImplemented.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeFlowIsNotImplemented.
 */
+ (NSError *)errorFlowIsNotImplemented;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeFlowTypeUnsupported.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeFlowTypeUnsupported.
 */
+ (NSError *)errorFlowTypeUnsupported;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeNetworkNotReachable.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeNetworkNotReachable.
 */
+ (NSError *)errorNetworkNotReachable;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeGeolocationIsInvalid.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeGeolocationIsInvalid.
 */
+ (NSError *)errorGeolocationIsInvalid;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeGeolocationIsMissing.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeGeolocationIsMissing.
 */
+ (NSError *)errorGeolocationIsMissing;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeGeolocationServicesAreUnauthorized.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeGeolocationServicesAreUnauthorized.
 */
+ (NSError *)errorGeolocationServicesAreUnauthorized;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeGeolocationIsNotConfigured.
 *
 *  @return Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error code MASFoundationErrorCodeGeolocationIsNotConfigured.
 */
+ (NSError *)errorGeolocationServiceIsNotConfigured;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeMasIsNotStarted.
 *
 *  @return Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error code MASFoundationErrorCodeMASIsNotStarted.
 */
+ (NSError *)errorMASIsNotStarted;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeNetworkNotStarted.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeNetworkNotStarted.
 */
+ (NSError *)errorNetworkNotStarted;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeInvalidAuthorization.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeInvalidAuthorization.
 */
+ (NSError *)errorInvalidAuthorization;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeUserAlreadyAuthenticated.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeUserAlreadyAuthenticated.
 */
+ (NSError *)errorUserAlreadyAuthenticated;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeUserBasicCredentialsNotValid.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeUserBasicCredentialsNotValid.
 */
+ (NSError *)errorUserBasicCredentialsNotValid;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeUserDoesNotExist.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeUserDoesNotExist.
 */
+ (NSError *)errorUserDoesNotExist;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeUserNotAuthenticated.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeUserNotAuthenticated.
 */
+ (NSError *)errorUserNotAuthenticated;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeLoginProcessCancel.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeLoginProcessCancel.
 */
+ (NSError *)errorLoginProcessCancelled;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeOTPChannelSelectionCancelled.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeOTPChannelSelectionCancelled.
 */
+ (NSError *)errorOTPChannelSelectionCancelled;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeOTPAuthenticationCancelled.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeOTPAuthenticationCancelled.
 */
+ (NSError *)errorOTPAuthenticationCancelled;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeUserSessionIsAlreadyLocked.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeUserSessionIsAlreadyLocked.
 */
+ (NSError *)errorUserSessionIsAlreadyLocked;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeUserSessionIsAlreadyUnlocked.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeUserSessionIsAlreadyUnlocked.
 */
+ (NSError *)errorUserSessionIsAlreadyUnlocked;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeUserSessionIsCurrentlyLocked.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error code MASFoundationErrorCodeUserSessionIsCurrentlyLocked.
 */
+ (NSError *)errorUserSessionIsCurrentlyLocked;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeTokenInvalidIdToken.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeTokenInvalidIdToken.
 */
+ (NSError *)errorInvalidIdToken;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeTokenIdTokenExpired.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeTokenIdTokenExpired.
 */
+ (NSError *)errorIdTokenExpired;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeTokenIdTokenInvalidSignature.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeTokenIdTokenInvalidSignature.
 */
+ (NSError *)errorIdTokenInvalidSignature;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeTokenIdTokenInvalidAzp.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeTokenIdTokenInvalidAzp.
 */
+ (NSError *)errorIdTokenInvalidAzp;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeTokenIdTokenInvalidAud.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeTokenIdTokenInvalidAud.
 */
+ (NSError *)errorIdTokenInvalidAud;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeTokenIdTokenNotExistForLockingUserSession.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeTokenIdTokenNotExistForLockingUserSession.
 */
+ (NSError *)errorIdTokenNotExistForLockingUserSession;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeEnterpriseBrowserWebAppInvalidURL.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeEnterpriseBrowserWebAppInvalidURL.
 */
+ (NSError *)errorEnterpriseBrowserWebAppInvalidURL;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeEnterpriseBrowserNativeAppDoesNotExist.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeEnterpriseBrowserNativeAppDoesNotExist.
 */
+ (NSError *)errorEnterpriseBrowserNativeAppDoesNotExist;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeEnterpriseBrowserNativeAppCannotOpen.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeEnterpriseBrowserNativeAppCannotOpen.
 */
+ (NSError *)errorEnterpriseBrowserNativeAppCannotOpen;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeEnterpriseBrowserAppDoesNotExist.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeEnterpriseBrowserAppDoesNotExist.
 */
+ (NSError *)errorEnterpriseBrowserAppDoesNotExist;

/**
 * Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeConfigurationInvalidEndpoint.
 *
 * @returns Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 * error MASFoundationErrorCodeConfigurationInvalidEndpoint.
 */
+ (NSError *)errorInvalidEndpoint;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeProximityLoginAuthorizationInProgress.
 *
 *  @return Returns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error MASFoundationErrorCodeProximityLoginAuthorizationInProgress.
 */
+ (NSError *)errorProximityLoginAuthorizationInProgress;

/**
 *  Create MASFoundationErrorDomainLocal NSError for MASFoundationErrorCodeProximityLoginInvalidAuthorizeURL.
 *
 *  @return REturns an NSError instance with the domain MASFoundationErrorDomainLocal and
 *  error MASFoundationErrorCodeProximityLoginInvalidAuthorizeURL
 */
+ (NSError *)errorProximityLoginInvalidAuthroizeURL;

@end

redpajama_set_name: RedPajamaGithub


text:
package storage

import (
	"appengine"
	"appengine/datastore"
)

type Datastore struct {
	AppEngineContext appengine.Context
	kind             string
}

func NewDatastore(appEngineContext appengine.Context, kind string) *Datastore {
	return &Datastore{
		AppEngineContext: appEngineContext,
		kind:             kind,
	}
}

func (self *Datastore) Save(entity interface{}) (int64, error) {
	incKey := datastore.NewIncompleteKey(self.AppEngineContext, self.kind, nil)
	key, err := datastore.Put(self.AppEngineContext, incKey, entity)
	if err != nil {
		return 0, err
	}

	return key.IntID(), nil
}

func (self *Datastore) Find(id int64, entity interface{}) (int64, error) {
	key := datastore.NewKey(self.AppEngineContext, self.kind, "", id, nil)
	if err := datastore.Get(self.AppEngineContext, key, entity); err != nil {
		return 0, err
	}

	return key.IntID(), nil
}

func (self *Datastore) FindAll(query *datastore.Query, entities interface{}) ([]int64, error) {
	keys, err := query.GetAll(self.AppEngineContext, entities)
	if err != nil {
		return nil, err
	}

	ids := make([]int64, len(keys))
	for i, key := range keys {
		ids[i] = key.IntID()
	}

	return ids, nil
}

func (self *Datastore) FindMulti(ids []int64, entities interface{}) error {
	keys := make([]*datastore.Key, len(ids))
	for i, id := range ids {
		keys[i] = datastore.NewKey(self.AppEngineContext, self.kind, "", id, nil)
	}

	return datastore.GetMulti(self.AppEngineContext, keys, entities)
}

func (self *Datastore) Update(id int64, entity interface{}) error {
	key := datastore.NewKey(self.AppEngineContext, self.kind, "", id, nil)
	if _, err := datastore.Put(self.AppEngineContext, key, entity); err != nil {
		return err
	}

	return nil
}

func (self *Datastore) Delete(id int64) error {
	key := datastore.NewKey(self.AppEngineContext, self.kind, "", id, nil)
	return datastore.Delete(self.AppEngineContext, key)
}


text:
namespace Atlas.Drawing.Conversion
{
	/// <summary>
	/// Endianness of a converter
	/// </summary>
	public enum Endianness
	{
		/// <summary>
		/// Little endian - least significant byte first
		/// </summary>
		LittleEndian,
		/// <summary>
		/// Big endian - most significant byte first
		/// </summary>
		BigEndian
	}
}


text:
layout: post
microblog: true
date: 2017-12-29 18:08 -0500
guid: http://ericalba.micro.blog/2017/12/29/bestnine-likes-to.html
---
#2017bestnine , 17,561 Likes to 255 posts.
I'm glad to see my two loves made the list; my nephew Wally and Ramen. Swipe to see Wally dancing, then not dancing (thanks @tracyherold ) .
ps I also love lasers 💥
Thank y'all for the likes. Have a Happy New Year! 🎉


text:
package com.delaru.worker;

import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

/**
 * Compares two documents by deciding if they are equal, not equal or different
 */
public class DiffComparator {

  private String left, right;

  /**
   * Adds a text to the comparator. Needs to be called at least twice.
   *
   * @param text to be compared
   */
  public void addText(String text) {
    if (left == null) this.left = text;
    else right = text;
  }

  /**
   * Compares the texts that has been set with {@code addText()}. Throws an {@link
   * IllegalArgumentException} if one of the texts is {@code null}.
   *
   * @return a {@link JsonObject} with the result
   */
  public JsonObject compare() {
    JsonObject jsonObject = new JsonObject();
    if (left == null || right == null) {
      throw new IllegalArgumentException("One of the texts is null");
    }
    if (left.equals(right)) {
      return jsonObject.put("result", "equal");
    } else if (left.length() != right.length()) {
      return jsonObject.put("result", "not of equal size");
    } else {
      JsonObject diff = new JsonObject();
      JsonArray jsonArray = new JsonArray();
      char[] leftChars = left.toCharArray();
      char[] rightChars = right.toCharArray();
      boolean differentSection = false;
      int offset = 0;

      for (int index = 0; index < leftChars.length; index++) {
        if (leftChars[index] != rightChars[index]) {
          offset += 1;
          if (!differentSection) {
            differentSection = true;
            diff = new JsonObject().put("position", index);
          }
        }
        if ((leftChars[index] == rightChars[index] && differentSection)
            || (index == leftChars.length - 1 && differentSection)) {
          diff.put("offset", offset);
          jsonArray.add(diff);
          differentSection = false;
          offset = 0;
        }
      }
      return jsonObject.put("result", jsonArray);
    }
  }
}


text:
#include <tinyb.hpp>

#include <vector>
#include <iostream>
#include <thread>
#include <atomic>
#include <csignal>

using namespace tinyb;

/** Converts a raw temperature read from the sensor to a Celsius value.
 * @param[in] raw_temp The temperature read from the sensor (two bytes)
 * @return The Celsius value of the temperature
 */
static float celsius_temp(uint16_t raw_temp)
{
    const float SCALE_LSB = 0.03125;
    return ((float)(raw_temp >> 2)) * SCALE_LSB;
}

std::atomic<bool> running(true);

void signal_handler(int signum)
{
    if (signum == SIGINT) {
        running = false;
    }
}

/** This program reads the temperature from a
 * TI Sensor Tag(http://www.ti.com/ww/en/wireless_connectivity/sensortag2015/?INTC=SensorTag&HQS=sensortag)
 * Pass the MAC address of the sensor as the first parameter of the program.
 */
int main(int argc, char **argv)
{
   BluetoothManager *manager = nullptr;
    try {
        manager = BluetoothManager::get_bluetooth_manager();
    } catch(const std::runtime_error& e) {
        std::cerr << "Error while initializing libtinyb: " << e.what() << std::endl;
        exit(1);
    }

    /* Start the discovery of devices */
    bool ret = manager->start_discovery();
    std::cout << "Started = " << (ret ? "true" : "false") << std::endl;

    BluetoothDevice *sensor_tag = NULL;
    BluetoothGattService *temperature_service = NULL;

    for (;;) {
        std::cout << "Discovered devices: " << std::endl;
        /* Get the list of devices */
        auto list = manager->get_devices();

        for (auto it = list.begin(); it != list.end(); ++it) {

            std::cout << "Class = " << (*it)->get_class_name() << " ";
            std::cout << "Path = " << (*it)->get_object_path() << " ";
            std::cout << "Name = " << (*it)->get_name() << " ";
            std::cout << "Connected = " << (*it)->get_connected() << " ";
            std::cout << std::endl;

            auto mfg = (*it)->get_manufacturer_data();

            if (!mfg.empty()) {
                std::cout << "MFG" << std::endl;
                for(auto it: mfg) {
                    std::cout << "\t" << it.first << " = [ ";
                    for (auto arr_it: it.second) {
                        std::cout << (int) arr_it << ", ";
                    }
                    std::cout << "]" << std::endl;
                }
            }

            auto service_data = (*it)->get_service_data();

            if (!service_data.empty()) {
                std::cout << "Service Data" << std::endl;
                for(auto it: service_data) {
                    std::cout << "\t" << it.first << " = [ ";
                    for (auto arr_it: it.second) {
                        std::cout << (int) arr_it << ", ";
                    }
                    std::cout << "]" << std::endl;
                }
            }

        }

        /* If not, wait and try again */
        std::this_thread::sleep_for(std::chrono::seconds(4));
        std::cout << std::endl;
    }
}


text:
.css-form input.ng-invalid.ng-touched {
    border: 1px solid red;
}
.css-form input.ng-valid.ng-touched {
    border: 1px solid green;
}
.fieldError {
    color: red;
    padding-left: 10px;
}
.fieldPending {

}


text:
<?php

declare(strict_types=1);

namespace RSSchermer\Tests\EntityModel\Type;

use RSSchermer\Tests\EntityModel\NamedModelElementTestCase;

use RSSchermer\EntityModel\Type\ComplexType;
use RSSchermer\EntityModel\Exception\InvalidArgumentException;
use RSSchermer\Tests\EntityModel\Stubs\StructuralPropertyDescriptionStub;

abstract class ComplexTypeTestCase extends NamedModelElementTestCase
{
    /**
     * @depends testConstructor
     */
    public function testAddStructuralProperty(ComplexType $complexType)
    {
        $propertyCount = $complexType->getPropertyDescriptions()->count();
        $someProperty = new StructuralPropertyDescriptionStub('SomeProperty');

        $complexType->addStructuralPropertyDescription($someProperty);

        $this->assertCount($propertyCount + 1, $complexType->getPropertyDescriptions());
        $this->assertContains($someProperty, $complexType->getPropertyDescriptions());

        return $complexType;
    }

    /**
     * @depends testAddStructuralProperty
     * @expectedException InvalidArgumentException
     */
    public function testExceptionOnAddStructuralPropertyWithSameName(ComplexType $complexType)
    {
        $complexType->addStructuralPropertyDescription(new StructuralPropertyDescriptionStub('SomeProperty'));
    }

    /**
     * @depends testAddStructuralProperty
     */
    public function testGetPropertyDescriptionByName(ComplexType $complexType)
    {
        $someProperty = new StructuralPropertyDescriptionStub('SomeOtherProperty');

        $complexType->addStructuralPropertyDescription($someProperty);

        $this->assertSame($someProperty, $complexType->getPropertyDescriptionByName('SomeOtherProperty')->get());
    }
}


text:
FROM php:5.6-apache

# Copy wivet's source code
COPY . /var/www/html/

# Make sure we can write to the stats directory
RUN chmod 777 /var/www/html/offscanpages/statistics/


text:
package org.apache.reef.runtime.common.driver.evaluator;

import org.apache.reef.annotations.audience.DriverSide;
import org.apache.reef.annotations.audience.Private;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Sanity checks for evaluator heartbeats.
 */
@DriverSide
@Private
final class EvaluatorHeartBeatSanityChecker {
  private static final Logger LOG = Logger.getLogger(EvaluatorHeartBeatSanityChecker.class.getName());
  private final Map<String, Long> knownTimeStamps = new HashMap<>(); // guarded by this

  @Inject
  EvaluatorHeartBeatSanityChecker() {
  }

  final synchronized void check(final String id, final long timeStamp) {
    if (knownTimeStamps.containsKey(id)) {
      final long oldTimeStamp = this.knownTimeStamps.get(id);
      LOG.log(Level.FINEST, "TIMESTAMP CHECKER: id [ " + id + " ], old timestamp [ " + oldTimeStamp + " ], new timestamp [ " + timeStamp + " ]");
      if (oldTimeStamp > timeStamp) {
        final String msg = "Received an old heartbeat with timestamp `" + timeStamp +
            "` while earlier receiving one with timestamp `" + oldTimeStamp + "`";
        LOG.log(Level.SEVERE, msg);
        throw new RuntimeException(msg);
      }
    }
    knownTimeStamps.put(id, timeStamp);
  }

}


text:
<?php
namespace HealthCareAbroad\MemcacheBundle\Key;

use HealthCareAbroad\MemcacheBundle\Exception\MemcacheCollectionException;

class MemcacheKeyCollection
{
    private $memcacheCollection = array();

    public function has($id)
    {
        return \array_key_exists($id, $this->memcacheCollection);
    }

    /**
     * @param string $id Key name
     * @return MemcacheKey
     */
    public function get($id)
    {
        if (!$this->has($id) || !$this->memcacheCollection[$id] instanceof MemcacheKey) {
            throw MemcacheCollectionException::invalidKey($id);
        }

        return $this->memcacheCollection[$id];
    }

    public function set($id, MemcacheKey $memcacheKey)
    {
        $this->memcacheCollection[$id] = $memcacheKey;

        return $this;
    }
}


text:
package message.validate.demo.service;

import lodsve.core.utils.StringUtils;
import lodsve.validate.exception.ErrorMessage;
import lodsve.validate.exception.ExceptionHandler;
import org.springframework.stereotype.Component;

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

/**
 * .
 *
 * @author sunhao(sunhao.java @ gmail.com)
 * @version 1.0 2017/12/12 15:24
 */
@Component
public class TestExceptionHandler extends ExceptionHandler {

    @Override
    public String getMessage(List<ErrorMessage> messages) {
        List<String> msgs = new ArrayList<>(messages.size());
        for (ErrorMessage em : messages) {
            msgs.add(em.getMessage());
        }

        return StringUtils.join(msgs, "####");
    }
}


text:
const Boom = require('boom');
const Router = require('koa-router');
const boolean = require('boolean');

const { passport, policies } = require('../../helpers');
const config = require('../../config');

const router = new Router({ prefix: '/auth' });

const catchError = async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    if (ctx.params.provider === 'google' && err.message === 'Consent required')
      return ctx.redirect('/auth/google/consent');
    ctx.flash('error', err.message);
    ctx.redirect('/login');
  }
};

router
  .param('provider', (provider, ctx, next) => {
    if (!boolean(process.env[`AUTH_${provider.toUpperCase()}_ENABLED`]))
      return ctx.throw(Boom.badRequest('Invalid provider'));
    return next();
  })
  .get('/:provider', policies.ensureLoggedOut, catchError, (ctx, next) =>
    passport.authenticate(ctx.params.provider, config.auth[ctx.params.provider])(ctx, next)
  )
  .get('/:provider/ok', policies.ensureLoggedOut, catchError, (ctx, next) => {
    const redirect = ctx.session.returnTo
      ? ctx.session.returnTo
      : `/${ctx.locale}${config.passportCallbackOptions.successReturnToOrRedirect}`;
    return passport.authenticate(ctx.params.provider, {
      ...config.passportCallbackOptions,
      successReturnToOrRedirect: redirect
    })(ctx, next);
  });

if (boolean(process.env.AUTH_GOOGLE_ENABLED))
  router.get(
    '/google/consent',
    policies.ensureLoggedOut,
    catchError,
    passport.authenticate('google', {
      accessType: 'offline',
      prompt: 'consent', // see google strategy in passport helper
      scope: []
    })
  );

module.exports = router;


text:
using System;

namespace XPlat.UI.Core.Extensions
{
    public static class CoreDispatcherPriorityExtensions
    {
#if WINDOWS_UWP
        public static CoreDispatcherPriority ToInternalCoreDispatcherPriority(
            this Windows.UI.Core.CoreDispatcherPriority priority)
        {
            switch (priority)
            {
                case Windows.UI.Core.CoreDispatcherPriority.Idle:
                case Windows.UI.Core.CoreDispatcherPriority.Low:
                    return CoreDispatcherPriority.Low;
                case Windows.UI.Core.CoreDispatcherPriority.Normal:
                    return CoreDispatcherPriority.Normal;
                case Windows.UI.Core.CoreDispatcherPriority.High:
                    return CoreDispatcherPriority.High;
                default:
                    throw new ArgumentOutOfRangeException(nameof(priority), priority, null);
            }
        }

        public static Windows.UI.Core.CoreDispatcherPriority ToWindowsCoreDispatcherPriority(
            this CoreDispatcherPriority priority)
        {
            switch (priority)
            {
                case CoreDispatcherPriority.Low:
                    return Windows.UI.Core.CoreDispatcherPriority.Low;
                case CoreDispatcherPriority.Normal:
                    return Windows.UI.Core.CoreDispatcherPriority.Normal;
                case CoreDispatcherPriority.High:
                    return Windows.UI.Core.CoreDispatcherPriority.High;
                default:
                    throw new ArgumentOutOfRangeException(nameof(priority), priority, null);
            }
        }
#endif
    }
}


text:
{% load content_edit_tags %}
{% load static %}

Below is a content area to play with. Click it!

    {% cms_content 'fun_content' %}


text:
using Content.Server.Flash.Components;
using Content.Server.Light.EntitySystems;
using Content.Server.Stunnable;
using Content.Shared.Examine;
using Content.Shared.Flash;
using Content.Shared.IdentityManagement;
using Content.Shared.Interaction;
using Content.Shared.Interaction.Events;
using Content.Shared.Inventory;
using Content.Shared.Physics;
using Content.Shared.Popups;
using Content.Shared.Tag;
using Content.Shared.Weapons.Melee.Events;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.Player;
using Robust.Shared.Timing;
using InventoryComponent = Content.Shared.Inventory.InventoryComponent;

namespace Content.Server.Flash
{
    internal sealed class FlashSystem : SharedFlashSystem
    {
        [Dependency] private readonly EntityLookupSystem _entityLookup = default!;
        [Dependency] private readonly IGameTiming _gameTiming = default!;
        [Dependency] private readonly StunSystem _stunSystem = default!;
        [Dependency] private readonly InventorySystem _inventorySystem = default!;
        [Dependency] private readonly MetaDataSystem _metaSystem = default!;
        [Dependency] private readonly SharedInteractionSystem _interactionSystem = default!;
        [Dependency] private readonly TagSystem _tagSystem = default!;

        public override void Initialize()
        {
            base.Initialize();
            SubscribeLocalEvent<FlashComponent, MeleeHitEvent>(OnFlashMeleeHit);
            SubscribeLocalEvent<FlashComponent, UseInHandEvent>(OnFlashUseInHand, before: new []{ typeof(HandheldLightSystem) });
            SubscribeLocalEvent<FlashComponent, ExaminedEvent>(OnFlashExamined);

            SubscribeLocalEvent<InventoryComponent, FlashAttemptEvent>(OnInventoryFlashAttempt);

            SubscribeLocalEvent<FlashImmunityComponent, FlashAttemptEvent>(OnFlashImmunityFlashAttempt);
        }

        private void OnFlashMeleeHit(EntityUid uid, FlashComponent comp, MeleeHitEvent args)
        {
            if (!args.IsHit)
                return;

            if (!UseFlash(comp, args.User))
                return;

            args.Handled = true;
            foreach (var e in args.HitEntities)
            {
                Flash(e, args.User, uid, comp.FlashDuration, comp.SlowTo);
            }
        }

        private void OnFlashUseInHand(EntityUid uid, FlashComponent comp, UseInHandEvent args)
        {
            if (args.Handled || !UseFlash(comp, args.User))
                return;

            args.Handled = true;
            FlashArea(uid, args.User, comp.Range, comp.AoeFlashDuration, comp.SlowTo, true);
        }

        private bool UseFlash(FlashComponent comp, EntityUid user)
        {
            if (comp.HasUses)
            {
                // TODO flash visualizer
                if (!EntityManager.TryGetComponent<SpriteComponent?>(comp.Owner, out var sprite))
                    return false;

                if (--comp.Uses == 0)
                {
                    sprite.LayerSetState(0, "burnt");

                    _tagSystem.AddTag(comp.Owner, "Trash");
                    comp.Owner.PopupMessage(user, Loc.GetString("flash-component-becomes-empty"));
                }
                else if (!comp.Flashing)
                {
                    int animLayer = sprite.AddLayerWithState("flashing");
                    comp.Flashing = true;

                    comp.Owner.SpawnTimer(400, () =>
                    {
                        sprite.RemoveLayer(animLayer);
                        comp.Flashing = false;
                    });
                }

                SoundSystem.Play(comp.Sound.GetSound(), Filter.Pvs(comp.Owner), comp.Owner, AudioParams.Default);

                return true;
            }

            return false;
        }

        public void Flash(EntityUid target, EntityUid? user, EntityUid? used, float flashDuration, float slowTo, bool displayPopup = true, FlashableComponent? flashable = null)
        {
            if (!Resolve(target, ref flashable, false)) return;

            var attempt = new FlashAttemptEvent(target, user, used);
            RaiseLocalEvent(target, attempt, true);

            if (attempt.Cancelled)
                return;

            flashable.LastFlash = _gameTiming.CurTime;
            flashable.Duration = flashDuration / 1000f; // TODO: Make this sane...
            Dirty(flashable);

            _stunSystem.TrySlowdown(target, TimeSpan.FromSeconds(flashDuration/1000f), true,
                slowTo, slowTo);

            if (displayPopup && user != null && target != user && EntityManager.EntityExists(user.Value))
            {
                user.Value.PopupMessage(target, Loc.GetString("flash-component-user-blinds-you",
                    ("user", Identity.Entity(user.Value, EntityManager))));
            }
        }

        public void FlashArea(EntityUid source, EntityUid? user, float range, float duration, float slowTo = 0.8f, bool displayPopup = false, SoundSpecifier? sound = null)
        {
            var transform = EntityManager.GetComponent<TransformComponent>(source);
            var mapPosition = transform.MapPosition;
            var flashableEntities = new List<EntityUid>();
            var flashableQuery = GetEntityQuery<FlashableComponent>();

            foreach (var entity in _entityLookup.GetEntitiesInRange(transform.Coordinates, range))
            {
                if (!flashableQuery.HasComponent(entity))
                    continue;

                flashableEntities.Add(entity);
            }

            foreach (var entity in flashableEntities)
            {
                // Check for unobstructed entities while ignoring the mobs with flashable components.
                if (!_interactionSystem.InRangeUnobstructed(entity, mapPosition, range, CollisionGroup.Opaque, (e) => flashableEntities.Contains(e) || e == source))
                    continue;

                // They shouldn't have flash removed in between right?
                Flash(entity, user, source, duration, slowTo, displayPopup, flashableQuery.GetComponent(entity));
            }
            if (sound != null)
            {
                SoundSystem.Play(sound.GetSound(), Filter.Pvs(transform), source);
            }
        }

        private void OnFlashExamined(EntityUid uid, FlashComponent comp, ExaminedEvent args)
        {
            if (!comp.HasUses)
            {
                args.PushText(Loc.GetString("flash-component-examine-empty"));
                return;
            }

            if (args.IsInDetailsRange)
            {
                args.PushMarkup(
                    Loc.GetString(
                        "flash-component-examine-detail-count",
                        ("count", comp.Uses),
                        ("markupCountColor", "green")
                    )
                );
            }
        }

        private void OnInventoryFlashAttempt(EntityUid uid, InventoryComponent component, FlashAttemptEvent args)
        {
            foreach (var slot in new string[]{"head", "eyes", "mask"})
            {
                if (args.Cancelled)
                    break;
                if (_inventorySystem.TryGetSlotEntity(uid, slot, out var item, component))
                    RaiseLocalEvent(item.Value, args, true);
            }
        }

        private void OnFlashImmunityFlashAttempt(EntityUid uid, FlashImmunityComponent component, FlashAttemptEvent args)
        {
            if(component.Enabled)
                args.Cancel();
        }
    }

    public sealed class FlashAttemptEvent : CancellableEntityEventArgs
    {
        public readonly EntityUid Target;
        public readonly EntityUid? User;
        public readonly EntityUid? Used;

        public FlashAttemptEvent(EntityUid target, EntityUid? user, EntityUid? used)
        {
            Target = target;
            User = user;
            Used = used;
        }
    }
}


text:
package com.speedment.test.connector;

import static org.junit.jupiter.api.Assertions.assertNotNull;

import com.speedment.common.injector.InjectBundle;
import org.junit.jupiter.api.Test;

/**
 * @author Mislav Milicevic
 * @since 3.2.9
 */
public interface ConnectorBundleMixin {

    InjectBundle getBundleInstance();

    @Test
    default void injectables() {
        assertNotNull(getBundleInstance().injectables());
    }
}


text:
namespace securegcm {

// A collection of static utility methods for the Device to Device communication
// (D2D) library.
//
// A class is used here in preference to a namespace to provide a closer
// correspondence with the Java equivalent class:
// //java/com/google/security/cryptauth/lib/securegcm/D2DCryptoOps.java
class D2DCryptoOps {
 public:
  // Encapsulates a payload type specifier, and a corresponding message as the
  // raw payload.
  //
  // Note: Type is defined in securegcm.proto.
  class Payload {
   public:
    Payload(Type type, const std::string& message);

    Type type() const { return type_; }

    const std::string& message() const { return message_; }

   private:
    const Type type_;
    const std::string message_;
  };

  // The salt, SHA256 of "D2D".
  static const uint8_t kSalt[];
  static const size_t kSaltLength;

  // Used by a device to send a secure |Payload| to another device.
  static std::unique_ptr<std::string> SigncryptPayload(
      const Payload& payload,
      const securemessage::CryptoOps::SecretKey& secret_key);

  // Used by a device to recover a secure |Payload| sent by another device.
  static std::unique_ptr<Payload> VerifyDecryptPayload(
      const std::string& signcrypted_message,
      const securemessage::CryptoOps::SecretKey& secret_key);

  // Used to derive a distinct key for each initiator and responder from the
  // |master_key|. Use a different |purpose| for each role.
  static std::unique_ptr<securemessage::CryptoOps::SecretKey>
  DeriveNewKeyForPurpose(const securemessage::CryptoOps::SecretKey& master_key,
                         const std::string& purpose);

 private:
  // Prevent instantiation.
  D2DCryptoOps();
};

}  // namespace securegcm

#endif  // SECURITY_CRYPTAUTH_LIB_SECUREGCM_D2D_CRYPTO_OPS_H_


text:
package worker

import (
	"errors"
	"sync/atomic"
	"time"

	"github.com/nuclio/logger"
)

// errors
var ErrNoAvailableWorkers = errors.New("No available workers")

type Allocator interface {

	// allocate a worker
	Allocate(timeout time.Duration) (*Worker, error)

	// release a worker
	Release(worker *Worker)

	// true if the several go routines can share this allocator
	Shareable() bool

	// get direct access to all workers for things like management / housekeeping
	GetWorkers() []*Worker

	// get number of workers available in the allocator
	GetNumWorkersAvailable() int

	// GetStatistics returns worker allocator statistics
	GetStatistics() *AllocatorStatistics
}

//
// Singleton worker
// Holds a single worker
//

type singleton struct {

	// accessed atomically, keep as first field for alignment
	statistics AllocatorStatistics

	logger logger.Logger
	worker *Worker
}

func NewSingletonWorkerAllocator(parentLogger logger.Logger, worker *Worker) (Allocator, error) {

	return &singleton{
		logger: parentLogger.GetChild("singelton_allocator"),
		worker: worker,
	}, nil
}

func (s *singleton) Allocate(timeout time.Duration) (*Worker, error) {
	return s.worker, nil
}

func (s *singleton) Release(worker *Worker) {
}

// true if the several go routines can share this allocator
func (s *singleton) Shareable() bool {
	return false
}

// get direct access to all workers for things like management / housekeeping
func (s *singleton) GetWorkers() []*Worker {
	return []*Worker{s.worker}
}

func (s *singleton) GetNumWorkersAvailable() int {
	return 1
}

// GetStatistics returns worker allocator statistics
func (s *singleton) GetStatistics() *AllocatorStatistics {
	return &s.statistics
}

//
// Fixed pool of workers
// Holds a fixed number of workers. When a worker is unavailable, caller is blocked
//

type fixedPool struct {

	// accessed atomically, keep as first field for alignment
	statistics AllocatorStatistics

	logger     logger.Logger
	workerChan chan *Worker
	workers    []*Worker
}

func NewFixedPoolWorkerAllocator(parentLogger logger.Logger, workers []*Worker) (Allocator, error) {

	newFixedPool := fixedPool{
		logger:     parentLogger.GetChild("fixed_pool_allocator"),
		workerChan: make(chan *Worker, len(workers)),
		workers:    workers,
		statistics: AllocatorStatistics{},
	}

	// iterate over workers, shove to pool
	for _, workerInstance := range workers {
		newFixedPool.workerChan <- workerInstance
	}

	return &newFixedPool, nil
}

func (fp *fixedPool) Allocate(timeout time.Duration) (*Worker, error) {

	// we don't want to completely lock here, but we'll use atomic to inc counters where possible
	atomic.AddUint64(&fp.statistics.WorkerAllocationCount, 1)

	// get total number of workers
	totalNumberWorkers := len(fp.workers)
	currentNumberOfAvailableWorkers := len(fp.workerChan)
	percentageOfAvailableWorkers := float64(currentNumberOfAvailableWorkers*100.0) / float64(totalNumberWorkers)

	// measure how many workers are available in the queue while we're allocating
	atomic.AddUint64(&fp.statistics.WorkerAllocationWorkersAvailablePercentage, uint64(percentageOfAvailableWorkers))

	// try to allocate a worker and fall back to default immediately if there's none available
	select {
	case workerInstance := <-fp.workerChan:
		atomic.AddUint64(&fp.statistics.WorkerAllocationSuccessImmediateTotal, 1)

		return workerInstance, nil
	default:

		// if there's no timeout, return now
		if timeout == 0 {
			atomic.AddUint64(&fp.statistics.WorkerAllocationTimeoutTotal, 1)
			return nil, ErrNoAvailableWorkers
		}

		waitStartAt := time.Now()

		// if there is a timeout, try to allocate while waiting for the time
		// to pass
		select {
		case workerInstance := <-fp.workerChan:
			atomic.AddUint64(&fp.statistics.WorkerAllocationSuccessAfterWaitTotal, 1)
			atomic.AddUint64(&fp.statistics.WorkerAllocationWaitDurationMilliSecondsSum,
				uint64(time.Since(waitStartAt).Nanoseconds()/1e6))
			return workerInstance, nil
		case <-time.After(timeout):
			atomic.AddUint64(&fp.statistics.WorkerAllocationTimeoutTotal, 1)
			return nil, ErrNoAvailableWorkers
		}
	}
}

func (fp *fixedPool) Release(worker *Worker) {
	fp.workerChan <- worker
}

// true if the several go routines can share this allocator
func (fp *fixedPool) Shareable() bool {
	return true
}

// get direct access to all workers for things like management / housekeeping
func (fp *fixedPool) GetWorkers() []*Worker {
	return fp.workers
}

func (fp *fixedPool) GetNumWorkersAvailable() int {
	return len(fp.workerChan)
}

// GetStatistics returns worker allocator statistics
func (fp *fixedPool) GetStatistics() *AllocatorStatistics {
	return &fp.statistics
}


text:
'''
    This module emails Windows event logs since the last saved time stamp. If no time stamp exists (1st time), last 10 events will be sent.
    This module can be attached as a task in Windows Event Viewer to be executed when certain event is logged.
    Configure the params below to macth the event that triggered the module, such as logger and severity level (in cmdSinceLastTimeStamp).
    All event details will be emailed. E.g: executing below test command on command line, will show last 10 messages in System log with Level = Critical, Error or Warning. This would be the eact content of the email.

    Test command: wevtutil qe "System" "/q:*[System [(Level<4)]]" /f:text /rd:true /c:10"

    Developed on Windows 8.1, using Python 2.7.8
'''

import os
import re
import time
import smtplib
import datetime

# Configure params
# In case using gmail for email, create a new App specific password to avoid entering your main password. https://support.google.com/mail/answer/1173270?hl=en
TIMESTAMP_DIR = 'C:\\EmailEventLog'
LOGGER = 'System'     # Get list of loggers by executing 'wevtutil el' on command line.
SMTP_HOST = 'smtp.gmail.com'
SMTP_PORT = 587
SEND_TO   = 'your_email@gmail.com'
USERNAME  = 'your_email@gmail.com'
PASSWORD  = 'your_passwd'

# Commands to query event log information. cmdSinceLastTimeStamp is querying events AFTER last timestamp and level (1-3) - Critical, Error, and Warning.
# To write a more custom wevtutil query, go to http://technet.microsoft.com/en-us/library/cc732848.aspx
cmdSinceLastTimeStamp = "wevtutil qe \"" + LOGGER + "\" \"/q:*[System [(Level<4) and TimeCreated[@SystemTime>'{0}']]]\" /f:text /rd:true"
cmdLast10 = "wevtutil qe \"" + LOGGER + "\" \"/q:*[System [(Level<4)]]\" /f:text /rd:true /c:10"

class EmailEventLog:
    def __init__(self):
        self._TIMESTAMP_FILE = TIMESTAMP_DIR + '\\' + 'timeStamp.txt'

    def __exit__(self):
        pass

    def handleEvent(self):
        lastEventTimeStamp = self._getLastEventTimeStamp()

        cmd = None
        # If no timestamp, query last 10.
        if None == lastEventTimeStamp:
            cmd = cmdLast10
        else:
            cmd = cmdSinceLastTimeStamp.format(lastEventTimeStamp)

        # Get events information from cmd line
        evtLog = os.popen(cmd).read()

        timeStamp = None
        # Find the latest time stamp
        for line in evtLog.split("\n"):
            if 0 == line.strip().find("Date:"):
                timeStamp = line.split(":", 1)[1].strip()
                break

        # If no timestamp, consider it as a false alarm
        if None == timeStamp:
            return

        # Send email
        self._sendEmail(evtLog)

        # Save new time stamp
        # NOTE: If send mail throws an exception, implying an error in sending email; timestamp won't be updated (intentionally).
        self._updateTimeStamp(timeStamp)

    def _getLastEventTimeStamp(self):
        ''' wevtutil expects the time stamp w/ UTC offset. Below logic adds that offset.
        '''
        try:
            timeStamp = open(self._TIMESTAMP_FILE, 'r').read().strip()
            # Ensure timestamp is in valid format, e.g: '2014-08-28T22:29:24.000'
            if None == re.match('^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}$', timeStamp):
                return

            timeStamp = timeStamp.split('T')
            date  = timeStamp[0].split('-')
            clock = timeStamp[1].replace('.', ':').split(':')
            offset = time.timezone if time.localtime().tm_isdst == 0 else time.altzone
            utcTimeStamp = datetime.datetime(int(date[0]), int(date[1]), int(date[2]), int(clock[0]), int(clock[1]), int(clock[2]), int(clock[3])*1000) + datetime.timedelta(0, offset)

            return utcTimeStamp.isoformat() if int(clock[3]) == 0 else utcTimeStamp.isoformat()[:-3]
        except IOError:
            pass

    def _updateTimeStamp(self, timeStamp):
        open(self._TIMESTAMP_FILE, 'w+').write(timeStamp)

    def _sendEmail(self, msg):
        smtpServer = smtplib.SMTP(SMTP_HOST, SMTP_PORT)
        smtpServer.ehlo()
        smtpServer.starttls()
        smtpServer.ehlo
        smtpServer.login(USERNAME, PASSWORD)
        header = 'To: {0}\nFrom: {1}\nSubject: {2} \n\n'.format(SEND_TO, USERNAME, 'Mail from EmailEventLog')
        smtpServer.sendmail(USERNAME, SEND_TO, header + msg)
        smtpServer.close()

if '__main__' == __name__:
    EmailEventLog().handleEvent()


text:
package org.apache.hadoop.hbase.client.replication;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Abortable;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.ReplicationPeerNotFoundException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.replication.ReplicationException;
import org.apache.hadoop.hbase.replication.ReplicationFactory;
import org.apache.hadoop.hbase.replication.ReplicationPeer;
import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
import org.apache.hadoop.hbase.replication.ReplicationPeerDescription;
import org.apache.hadoop.hbase.replication.ReplicationPeerZKImpl;
import org.apache.hadoop.hbase.replication.ReplicationPeers;
import org.apache.hadoop.hbase.replication.ReplicationQueuesClient;
import org.apache.hadoop.hbase.replication.ReplicationQueuesClientArguments;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;

import org.apache.hadoop.hbase.shaded.com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.hbase.shaded.com.google.common.collect.Lists;

/**
 *

 * This class provides the administrative interface to HBase cluster
 * replication.
 *

 *

 * Adding a new peer results in creating new outbound connections from every
 * region server to a subset of region servers on the slave cluster. Each
 * new stream of replication will start replicating from the beginning of the
 * current WAL, meaning that edits from that past will be replicated.
 *

 *

 * Removing a peer is a destructive and irreversible operation that stops
 * all the replication streams for the given cluster and deletes the metadata
 * used to keep track of the replication state.
 *

 *

 * To see which commands are available in the shell, type
 * replication.
 *

 *
 * @deprecated use {@link org.apache.hadoop.hbase.client.Admin} instead.
 */
@InterfaceAudience.Public
@Deprecated
public class ReplicationAdmin implements Closeable {
  private static final Log LOG = LogFactory.getLog(ReplicationAdmin.class);

  public static final String TNAME = "tableName";
  public static final String CFNAME = "columnFamilyName";

  // only Global for now, can add other type
  // such as, 1) no global replication, or 2) the table is replicated to this cluster, etc.
  public static final String REPLICATIONTYPE = "replicationType";
  public static final String REPLICATIONGLOBAL =
      Integer.toString(HConstants.REPLICATION_SCOPE_GLOBAL);
  public static final String REPLICATIONSERIAL =
      Integer.toString(HConstants.REPLICATION_SCOPE_SERIAL);

  private final Connection connection;
  // TODO: replication should be managed by master. All the classes except ReplicationAdmin should
  // be moved to hbase-server. Resolve it in HBASE-11392.
  private final ReplicationQueuesClient replicationQueuesClient;
  private final ReplicationPeers replicationPeers;
  /**
   * A watcher used by replicationPeers and replicationQueuesClient. Keep reference so can dispose
   * on {@link #close()}.
   */
  private final ZooKeeperWatcher zkw;

  private Admin admin;

  /**
   * Constructor that creates a connection to the local ZooKeeper ensemble.
   * @param conf Configuration to use
   * @throws IOException if an internal replication error occurs
   * @throws RuntimeException if replication isn't enabled.
   */
  public ReplicationAdmin(Configuration conf) throws IOException {
    this.connection = ConnectionFactory.createConnection(conf);
    admin = connection.getAdmin();
    try {
      zkw = createZooKeeperWatcher();
      try {
        this.replicationQueuesClient =
            ReplicationFactory.getReplicationQueuesClient(new ReplicationQueuesClientArguments(conf,
            this.connection, zkw));
        this.replicationQueuesClient.init();
        this.replicationPeers = ReplicationFactory.getReplicationPeers(zkw, conf,
          this.replicationQueuesClient, this.connection);
        this.replicationPeers.init();
      } catch (Exception exception) {
        if (zkw != null) {
          zkw.close();
        }
        throw exception;
      }
    } catch (Exception exception) {
      connection.close();
      if (exception instanceof IOException) {
        throw (IOException) exception;
      } else if (exception instanceof RuntimeException) {
        throw (RuntimeException) exception;
      } else {
        throw new IOException("Error initializing the replication admin client.", exception);
      }
    }
  }

  private ZooKeeperWatcher createZooKeeperWatcher() throws IOException {
    // This Abortable doesn't 'abort'... it just logs.
    return new ZooKeeperWatcher(connection.getConfiguration(), "ReplicationAdmin", new Abortable() {
      @Override
      public void abort(String why, Throwable e) {
        LOG.error(why, e);
        // We used to call system.exit here but this script can be embedded by other programs that
        // want to do replication stuff... so inappropriate calling System.exit. Just log for now.
      }

      @Override
      public boolean isAborted() {
        return false;
      }
    });
  }

  /**
   * Add a new remote slave cluster for replication.
   * @param id a short name that identifies the cluster
   * @param peerConfig configuration for the replication slave cluster
   * @param tableCfs the table and column-family list which will be replicated for this peer.
   * A map from tableName to column family names. An empty collection can be passed
   * to indicate replicating all column families. Pass null for replicating all table and column
   * families
   * @deprecated as release of 2.0.0, and it will be removed in 3.0.0,
   * use {@link #addPeer(String, ReplicationPeerConfig)} instead.
   */
  @Deprecated
  public void addPeer(String id, ReplicationPeerConfig peerConfig,
      Map<TableName, ? extends Collection<String>> tableCfs) throws ReplicationException,
      IOException {
    if (tableCfs != null) {
      peerConfig.setTableCFsMap(tableCfs);
    }
    this.admin.addReplicationPeer(id, peerConfig);
  }

  /**
   * Add a new remote slave cluster for replication.
   * @param id a short name that identifies the cluster
   * @param peerConfig configuration for the replication slave cluster
   * @deprecated use
   *             {@link org.apache.hadoop.hbase.client.Admin#addReplicationPeer(String, ReplicationPeerConfig)}
   *             instead
   */
  @Deprecated
  public void addPeer(String id, ReplicationPeerConfig peerConfig) throws ReplicationException,
      IOException {
    checkNamespacesAndTableCfsConfigConflict(peerConfig.getNamespaces(),
      peerConfig.getTableCFsMap());
    this.admin.addReplicationPeer(id, peerConfig);
  }

  /**
   *  @deprecated as release of 2.0.0, and it will be removed in 3.0.0
   * */
  @Deprecated
  public static Map<TableName, List<String>> parseTableCFsFromConfig(String tableCFsConfig) {
    return ReplicationSerDeHelper.parseTableCFsFromConfig(tableCFsConfig);
  }

  /**
   * @deprecated use
   *             {@link org.apache.hadoop.hbase.client.Admin#updateReplicationPeerConfig(String, ReplicationPeerConfig)}
   *             instead
   */
  @Deprecated
  public void updatePeerConfig(String id, ReplicationPeerConfig peerConfig) throws IOException {
    this.admin.updateReplicationPeerConfig(id, peerConfig);
  }

  /**
   * Removes a peer cluster and stops the replication to it.
   * @param id a short name that identifies the cluster
   * @deprecated use {@link org.apache.hadoop.hbase.client.Admin#removeReplicationPeer(String)} instead
   */
  @Deprecated
  public void removePeer(String id) throws IOException {
    this.admin.removeReplicationPeer(id);
  }

  /**
   * Restart the replication stream to the specified peer.
   * @param id a short name that identifies the cluster
   * @deprecated use {@link org.apache.hadoop.hbase.client.Admin#enableReplicationPeer(String)}
   *             instead
   */
  @Deprecated
  public void enablePeer(String id) throws IOException {
    this.admin.enableReplicationPeer(id);
  }

  /**
   * Stop the replication stream to the specified peer.
   * @param id a short name that identifies the cluster
   * @deprecated use {@link org.apache.hadoop.hbase.client.Admin#disableReplicationPeer(String)}
   *             instead
   */
  @Deprecated
  public void disablePeer(String id) throws IOException {
    this.admin.disableReplicationPeer(id);
  }

  /**
   * Get the number of slave clusters the local cluster has.
   * @return number of slave clusters
   * @throws IOException
   * @deprecated
   */
  @Deprecated
  public int getPeersCount() throws IOException {
    return this.admin.listReplicationPeers().size();
  }

  /**
   * @deprecated use {@link org.apache.hadoop.hbase.client.Admin#listReplicationPeers()} instead
   */
  @Deprecated
  public Map<String, ReplicationPeerConfig> listPeerConfigs() throws IOException {
    List<ReplicationPeerDescription> peers = this.admin.listReplicationPeers();
    Map<String, ReplicationPeerConfig> result = new TreeMap<>();
    for (ReplicationPeerDescription peer : peers) {
      result.put(peer.getPeerId(), peer.getPeerConfig());
    }
    return result;
  }

  /**
   * @deprecated use {@link org.apache.hadoop.hbase.client.Admin#getReplicationPeerConfig(String)}
   *             instead
   */
  @Deprecated
  public ReplicationPeerConfig getPeerConfig(String id) throws IOException {
    return admin.getReplicationPeerConfig(id);
  }

  /**
   * Get the replicable table-cf config of the specified peer.
   * @param id a short name that identifies the cluster
   * @deprecated as release of 2.0.0, and it will be removed in 3.0.0,
   * use {@link #getPeerConfig(String)} instead.
   * */
  @Deprecated
  public String getPeerTableCFs(String id) throws IOException {
    ReplicationPeerConfig peerConfig = admin.getReplicationPeerConfig(id);
    return ReplicationSerDeHelper.convertToString(peerConfig.getTableCFsMap());
  }

  /**
   * Append the replicable table-cf config of the specified peer
   * @param id a short that identifies the cluster
   * @param tableCfs table-cfs config str
   * @throws ReplicationException
   * @throws IOException
   * @deprecated as release of 2.0.0, and it will be removed in 3.0.0,
   * use {@link #appendPeerTableCFs(String, Map)} instead.
   */
  @Deprecated
  public void appendPeerTableCFs(String id, String tableCfs) throws ReplicationException,
      IOException {
    appendPeerTableCFs(id, ReplicationSerDeHelper.parseTableCFsFromConfig(tableCfs));
  }

  /**
   * Append the replicable table-cf config of the specified peer
   * @param id a short that identifies the cluster
   * @param tableCfs A map from tableName to column family names
   * @throws ReplicationException
   * @throws IOException
   */
  @Deprecated
  public void appendPeerTableCFs(String id, Map<TableName, ? extends Collection<String>> tableCfs)
      throws ReplicationException, IOException {
    if (tableCfs == null) {
      throw new ReplicationException("tableCfs is null");
    }
    ReplicationPeerConfig peerConfig = admin.getReplicationPeerConfig(id);
    Map<TableName, List<String>> preTableCfs = peerConfig.getTableCFsMap();
    if (preTableCfs == null) {
      setPeerTableCFs(id, tableCfs);
      return;
    }
    for (Map.Entry<TableName, ? extends Collection<String>> entry : tableCfs.entrySet()) {
      TableName table = entry.getKey();
      Collection<String> appendCfs = entry.getValue();
      if (preTableCfs.containsKey(table)) {
        List<String> cfs = preTableCfs.get(table);
        if (cfs == null || appendCfs == null || appendCfs.isEmpty()) {
          preTableCfs.put(table, null);
        } else {
          Set<String> cfSet = new HashSet<>(cfs);
          cfSet.addAll(appendCfs);
          preTableCfs.put(table, Lists.newArrayList(cfSet));
        }
      } else {
        if (appendCfs == null || appendCfs.isEmpty()) {
          preTableCfs.put(table, null);
        } else {
          preTableCfs.put(table, Lists.newArrayList(appendCfs));
        }
      }
    }
    updatePeerConfig(id, peerConfig);
  }

  /**
   * Remove some table-cfs from table-cfs config of the specified peer
   * @param id a short name that identifies the cluster
   * @param tableCf table-cfs config str
   * @throws ReplicationException
   * @throws IOException
   * @deprecated as release of 2.0.0, and it will be removed in 3.0.0,
   * use {@link #removePeerTableCFs(String, Map)} instead.
   */
  @Deprecated
  public void removePeerTableCFs(String id, String tableCf) throws ReplicationException,
      IOException {
    removePeerTableCFs(id, ReplicationSerDeHelper.parseTableCFsFromConfig(tableCf));
  }

  /**
   * Remove some table-cfs from config of the specified peer
   * @param id a short name that identifies the cluster
   * @param tableCfs A map from tableName to column family names
   * @throws ReplicationException
   * @throws IOException
   */
  @Deprecated
  public void removePeerTableCFs(String id, Map<TableName, ? extends Collection<String>> tableCfs)
      throws ReplicationException, IOException {
    if (tableCfs == null) {
      throw new ReplicationException("tableCfs is null");
    }
    ReplicationPeerConfig peerConfig = admin.getReplicationPeerConfig(id);
    Map<TableName, List<String>> preTableCfs = peerConfig.getTableCFsMap();
    if (preTableCfs == null) {
      throw new ReplicationException("Table-Cfs for peer" + id + " is null");
    }
    for (Map.Entry<TableName, ? extends Collection<String>> entry: tableCfs.entrySet()) {

      TableName table = entry.getKey();
      Collection<String> removeCfs = entry.getValue();
      if (preTableCfs.containsKey(table)) {
        List<String> cfs = preTableCfs.get(table);
        if (cfs == null && (removeCfs == null || removeCfs.isEmpty())) {
          preTableCfs.remove(table);
        } else if (cfs != null && (removeCfs != null && !removeCfs.isEmpty())) {
          Set<String> cfSet = new HashSet<>(cfs);
          cfSet.removeAll(removeCfs);
          if (cfSet.isEmpty()) {
            preTableCfs.remove(table);
          } else {
            preTableCfs.put(table, Lists.newArrayList(cfSet));
          }
        } else if (cfs == null && (removeCfs != null && !removeCfs.isEmpty())) {
          throw new ReplicationException("Cannot remove cf of table: " + table
              + " which doesn't specify cfs from table-cfs config in peer: " + id);
        } else if (cfs != null && (removeCfs == null || removeCfs.isEmpty())) {
          throw new ReplicationException("Cannot remove table: " + table
              + " which has specified cfs from table-cfs config in peer: " + id);
        }
      } else {
        throw new ReplicationException("No table: " + table + " in table-cfs config of peer: " + id);
      }
    }
    updatePeerConfig(id, peerConfig);
  }

  /**
   * Set the replicable table-cf config of the specified peer
   * @param id a short name that identifies the cluster
   * @param tableCfs the table and column-family list which will be replicated for this peer.
   * A map from tableName to column family names. An empty collection can be passed
   * to indicate replicating all column families. Pass null for replicating all table and column
   * families
   */
  @Deprecated
  public void setPeerTableCFs(String id, Map<TableName, ? extends Collection<String>> tableCfs)
      throws IOException {
    ReplicationPeerConfig peerConfig = getPeerConfig(id);
    peerConfig.setTableCFsMap(tableCfs);
    updatePeerConfig(id, peerConfig);
  }

  /**
   * Get the state of the specified peer cluster
   * @param id String format of the Short name that identifies the peer,
   * an IllegalArgumentException is thrown if it doesn't exist
   * @return true if replication is enabled to that peer, false if it isn't
   */
  @Deprecated
  public boolean getPeerState(String id) throws ReplicationException, IOException {
    List<ReplicationPeerDescription> peers = admin.listReplicationPeers(id);
    if (peers.isEmpty() || !id.equals(peers.get(0).getPeerId())) {
      throw new ReplicationPeerNotFoundException(id);
    }
    return peers.get(0).isEnabled();
  }

  @Override
  public void close() throws IOException {
    if (this.zkw != null) {
      this.zkw.close();
    }
    if (this.connection != null) {
      this.connection.close();
    }
    admin.close();
  }

  /**
   * Find all column families that are replicated from this cluster
   * @return the full list of the replicated column families of this cluster as:
   *        tableName, family name, replicationType
   *
   * Currently replicationType is Global. In the future, more replication
   * types may be extended here. For example
   *  1) the replication may only apply to selected peers instead of all peers
   *  2) the replicationType may indicate the host Cluster servers as Slave
   *     for the table:columnFam.
   * @deprecated use {@link org.apache.hadoop.hbase.client.Admin#listReplicatedTableCFs()} instead
   */
  @Deprecated
  public List<HashMap<String, String>> listReplicated() throws IOException {
    List<HashMap<String, String>> replicationColFams = new ArrayList<>();
    admin.listReplicatedTableCFs().forEach(
      (tableCFs) -> {
        String table = tableCFs.getTable().getNameAsString();
        tableCFs.getColumnFamilyMap()
            .forEach(
              (cf, scope) -> {
                HashMap<String, String> replicationEntry = new HashMap<>();
                replicationEntry.put(TNAME, table);
                replicationEntry.put(CFNAME, cf);
                replicationEntry.put(REPLICATIONTYPE,
                  scope == HConstants.REPLICATION_SCOPE_GLOBAL ? REPLICATIONGLOBAL
                      : REPLICATIONSERIAL);
                replicationColFams.add(replicationEntry);
              });
      });
    return replicationColFams;
  }

  /**
   * Enable a table's replication switch.
   * @param tableName name of the table
   * @throws IOException if a remote or network exception occurs
   * @deprecated use {@link org.apache.hadoop.hbase.client.Admin#enableTableReplication(TableName)}
   *             instead
   */
  @Deprecated
  public void enableTableRep(final TableName tableName) throws IOException {
    admin.enableTableReplication(tableName);
  }

  /**
   * Disable a table's replication switch.
   * @param tableName name of the table
   * @throws IOException if a remote or network exception occurs
   * @deprecated use {@link org.apache.hadoop.hbase.client.Admin#disableTableReplication(TableName)}
   *             instead
   */
  @Deprecated
  public void disableTableRep(final TableName tableName) throws IOException {
    admin.disableTableReplication(tableName);
  }

  @VisibleForTesting
  @Deprecated
  public void peerAdded(String id) throws ReplicationException {
    this.replicationPeers.peerConnected(id);
  }

  /**
   * @deprecated use {@link org.apache.hadoop.hbase.client.Admin#listReplicationPeers()} instead
   */
  @VisibleForTesting
  @Deprecated
  List<ReplicationPeer> listReplicationPeers() throws IOException {
    Map<String, ReplicationPeerConfig> peers = listPeerConfigs();
    if (peers == null || peers.size() <= 0) {
      return null;
    }
    List<ReplicationPeer> listOfPeers = new ArrayList<>(peers.size());
    for (Entry<String, ReplicationPeerConfig> peerEntry : peers.entrySet()) {
      String peerId = peerEntry.getKey();
      try {
        Pair<ReplicationPeerConfig, Configuration> pair = this.replicationPeers.getPeerConf(peerId);
        Configuration peerConf = pair.getSecond();
        ReplicationPeer peer = new ReplicationPeerZKImpl(zkw, pair.getSecond(),
          peerId, pair.getFirst(), this.connection);
        listOfPeers.add(peer);
      } catch (ReplicationException e) {
        LOG.warn("Failed to get valid replication peers. "
            + "Error connecting to peer cluster with peerId=" + peerId + ". Error message="
            + e.getMessage());
        LOG.debug("Failure details to get valid replication peers.", e);
        continue;
      }
    }
    return listOfPeers;
  }

  /**
   * Set a namespace in the peer config means that all tables in this namespace
   * will be replicated to the peer cluster.
   *
   * 1. If you already have set a namespace in the peer config, then you can't set any table
   *    of this namespace to the peer config.
   * 2. If you already have set a table in the peer config, then you can't set this table's
   *    namespace to the peer config.
   *
   * @param namespaces
   * @param tableCfs
   * @throws ReplicationException
   */
  private void checkNamespacesAndTableCfsConfigConflict(Set<String> namespaces,
      Map<TableName, ? extends Collection<String>> tableCfs) throws ReplicationException {
    if (namespaces == null || namespaces.isEmpty()) {
      return;
    }
    if (tableCfs == null || tableCfs.isEmpty()) {
      return;
    }
    for (Map.Entry<TableName, ? extends Collection<String>> entry : tableCfs.entrySet()) {
      TableName table = entry.getKey();
      if (namespaces.contains(table.getNamespaceAsString())) {
        throw new ReplicationException(
            "Table-cfs config conflict with namespaces config in peer");
      }
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using QueryHelper;

namespace DbSyncService.Models
{

    public static class TableInfoCache
    {
        private static List<TableInfo> tableInfoCache = new List<TableInfo>();

        //TODO: get foreign key info...

        public static TableInfo GetTableInfo(this QueryRunner database, string schema, string tableName)
        {
            var sql = @"SELECT distinct ISNULL(sch.name, '') 'SchemaName', tables.name 'TableName', c.name 'ColumnName', c.column_id 'ColumnID',
    t.Name 'Datatype', c.max_length 'MaxLength',  c.precision 'Precision' ,
	c.scale 'Scale', c.is_nullable 'Nullable',
	ISNULL((select is_primary_key from sys.indexes i inner join sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
			where ic.object_id = c.object_id AND ic.column_id = c.column_id and is_primary_key = 1),0) as 'PrimaryKey',
	ISNULL(c.is_identity, 0) 'IsIdentity'
	 FROM  sys.columns c INNER JOIN
	sys.types t ON c.user_type_id = t.user_type_id
	INNER JOIN sys.tables tables ON (tables.object_id = c.object_id)
	LEFT OUTER JOIN sys.schemas sch on (sch.schema_id = tables.schema_id)
	WHERE c.object_id = OBJECT_ID(@tableName) order by TableName, ColumnID;";

            var tableInfo = tableInfoCache.FirstOrDefault(t => t.ConnectionString == database.ConnectionString && t.SchemaName == schema && t.TableName == tableName);

            if (tableInfo == null)
            {
                var columnList = new List<ColumnInfo>();
                string actualSchemaName = string.Empty;
                string actualTableName  = string.Empty;

                var query = new SQLQuery(sql);
                var schemaTableName = string.IsNullOrEmpty(schema) ? tableName : schema + "." + tableName;
                query.Parameters.Add("tableName", schemaTableName);
                query.ProcessRow = reader =>
                {
                    columnList.Add(new ColumnInfo(
                        (string) reader["ColumnName"],
                        Convert.ToInt32(reader["ColumnID"]),
                        (string) reader["DataType"],
                        Convert.ToInt32(reader["MaxLength"]),
                        Convert.ToInt32(reader["Precision"]),
                        Convert.ToInt32(reader["Scale"]),
                        (bool) reader["Nullable"],
                        (bool) reader["PrimaryKey"],
                        (bool) reader["IsIdentity"]));
                    actualSchemaName = (string) reader["SchemaName"];
                    actualTableName = (string) reader["TableName"];
                    return true;
                };
                database.RunQuery(query);
                if (columnList.Count == 0)
                {
                    throw new ApplicationException("Couldn't find any columns for table " + schemaTableName);
                }
                tableInfo = new TableInfo(database.ConnectionString, actualTableName, actualSchemaName, columnList.ToArray());
                tableInfoCache.Add(tableInfo);
            }
            return tableInfo;
        }
    }
}


text:
#include <aws/ec2/model/VpnConnectionOptionsSpecification.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace EC2
{
namespace Model
{

VpnConnectionOptionsSpecification::VpnConnectionOptionsSpecification() :
    m_staticRoutesOnly(false),
    m_staticRoutesOnlyHasBeenSet(false)
{
}

VpnConnectionOptionsSpecification::VpnConnectionOptionsSpecification(const XmlNode& xmlNode) :
    m_staticRoutesOnly(false),
    m_staticRoutesOnlyHasBeenSet(false)
{
  *this = xmlNode;
}

VpnConnectionOptionsSpecification& VpnConnectionOptionsSpecification::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode staticRoutesOnlyNode = resultNode.FirstChild("staticRoutesOnly");
    if(!staticRoutesOnlyNode.IsNull())
    {
      m_staticRoutesOnly = StringUtils::ConvertToBool(StringUtils::Trim(staticRoutesOnlyNode.GetText().c_str()).c_str());
      m_staticRoutesOnlyHasBeenSet = true;
    }
  }

  return *this;
}

void VpnConnectionOptionsSpecification::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
  if(m_staticRoutesOnlyHasBeenSet)
  {
      oStream << location << index << locationValue << ".StaticRoutesOnly=" << m_staticRoutesOnly << "&";
  }

}

void VpnConnectionOptionsSpecification::OutputToStream(Aws::OStream& oStream, const char* location) const
{
  if(m_staticRoutesOnlyHasBeenSet)
  {
      oStream << location << ".StaticRoutesOnly=" << m_staticRoutesOnly << "&";
  }
}

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
class cmd_permissions : public LuaTestObject
{
	Q_OBJECT

private slots:
	void testArgs_data( void );
	void testArgs( void );

	void testArgs2_data( void );
	void testArgs2( void );

	void testArgs3_data( void );
	void testArgs3( void );
};

#endif // CMD_PERMISSIONS_H


text:
import Loadable from "react-loadable";
import LoadingComponent from "./LoadingComponent";

export default function LoadableComponent( opts ) {
    return Loadable( Object.assign( {loading: LoadingComponent}, opts ) );
}


text:
/**
 * @file MIP 页面预览组件,包括切换浏览模式、打开、关闭、处理嵌入页面的跳转
 * @author xuexb <fe.xiaowu@gmail.com>
 */

/* eslint-disable max-nested-callbacks */
define(function (require) {
    'use strict';
    var $ = require('zepto');
    var customElement = require('customElement').create();

    /**
     * 初始化后注册事件
     */
    customElement.prototype.build = function () {
        var self = this;
        var $element = $(self.element);

        self.addEventAction('open', function (event, url) {
            var $iframe = $element.find('[iframe] iframe');
            if (!$iframe.length) {
                $iframe = $('<iframe />').attr({
                    sandbox: 'allow-scripts allow-same-origin allow-forms allow-popups allow-modals'
                }).appendTo($element.find('[iframe]'));
                $iframe.on('load', function () {
                    var el = this;
                    if (el.src && el.src !== 'about:blank') {
                        $(el.contentWindow.document.body).on('click', 'a', function () {
                            el.contentWindow.location.href = this.href;
                            return false;
                        });
                    }
                });
            }

            $iframe.attr('src', url);
            $element.show();
            document.documentElement.classList.add('mip-mipengine-preview-v3-noscroll');
        });

        self.addEventAction('close', function () {
            $element.find('[iframe] iframe').attr('src', 'about:blank');
            $element.hide();
            document.documentElement.classList.remove('mip-mipengine-preview-v3-noscroll');
        });

        self.addEventAction('toggleMode', function (event, type) {
            $element.attr('mode', type);
        });
    };

    return customElement;
});
/* eslint-enable max-nested-callbacks */


text:
package mapping

import (
	"errors"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/omniscale/imposm3/config"
	"github.com/omniscale/imposm3/element"
	"github.com/omniscale/imposm3/geom"
	"github.com/omniscale/imposm3/logging"
	"github.com/omniscale/imposm3/parser/pbf"
)

var log = logging.NewLogger("mapping")

var AvailableFieldTypes map[string]FieldType

func init() {
	AvailableFieldTypes = map[string]FieldType{
		"bool":                 {"bool", "bool", Bool, nil, nil, false},
		"boolint":              {"boolint", "int8", BoolInt, nil, nil, false},
		"id":                   {"id", "int64", Id, nil, nil, false},
		"string":               {"string", "string", String, nil, nil, false},
		"direction":            {"direction", "int8", Direction, nil, nil, false},
		"integer":              {"integer", "int32", Integer, nil, nil, false},
		"mapping_key":          {"mapping_key", "string", KeyName, nil, nil, false},
		"mapping_value":        {"mapping_value", "string", ValueName, nil, nil, false},
		"member_id":            {"member_id", "int64", nil, nil, RelationMemberID, true},
		"member_role":          {"member_role", "string", nil, nil, RelationMemberRole, true},
		"member_type":          {"member_type", "int8", nil, nil, RelationMemberType, true},
		"member_index":         {"member_index", "int32", nil, nil, RelationMemberIndex, true},
		"geometry":             {"geometry", "geometry", Geometry, nil, nil, false},
		"validated_geometry":   {"validated_geometry", "validated_geometry", Geometry, nil, nil, false},
		"hstore_tags":          {"hstore_tags", "hstore_string", HstoreString, nil, nil, false},
		"wayzorder":            {"wayzorder", "int32", WayZOrder, nil, nil, false},
		"pseudoarea":           {"pseudoarea", "float32", PseudoArea, nil, nil, false},
		"zorder":               {"zorder", "int32", nil, MakeZOrder, nil, false},
		"enumerate":            {"enumerate", "int32", nil, MakeEnumerate, nil, false},
		"string_suffixreplace": {"string_suffixreplace", "string", nil, MakeSuffixReplace, nil, false},
		"pbf_timestamp":        {"pbf_timestamp", "timestamp", nil, MakePbfTimestamp, nil, false},
	}
}

type MakeValue func(string, *element.OSMElem, *geom.Geometry, Match) interface{}
type MakeMemberValue func(*element.Relation, *element.Member, Match) interface{}

type MakeMakeValue func(string, FieldType, Field) (MakeValue, error)

type Key string
type Value string

type FieldSpec struct {
	Key  Key
	Type FieldType
}

func (f *FieldSpec) Value(elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	if f.Type.Func != nil {
		return f.Type.Func(elem.Tags[string(f.Key)], elem, geom, match)
	}
	return nil
}

func (f *FieldSpec) MemberValue(rel *element.Relation, member *element.Member, geom *geom.Geometry, match Match) interface{} {
	if f.Type.Func != nil {
		if f.Type.FromMember {
			if member.Elem == nil {
				return nil
			}
			return f.Type.Func(member.Elem.Tags[string(f.Key)], member.Elem, geom, match)
		}
		return f.Type.Func(rel.Tags[string(f.Key)], &rel.OSMElem, geom, match)
	}
	if f.Type.MemberFunc != nil {
		return f.Type.MemberFunc(rel, member, match)
	}
	return nil
}

type TableFields struct {
	fields []FieldSpec
}

func (t *TableFields) MakeRow(elem *element.OSMElem, geom *geom.Geometry, match Match) []interface{} {
	var row []interface{}
	for _, field := range t.fields {
		row = append(row, field.Value(elem, geom, match))
	}
	return row
}

func (t *TableFields) MakeMemberRow(rel *element.Relation, member *element.Member, geom *geom.Geometry, match Match) []interface{} {
	var row []interface{}
	for _, field := range t.fields {
		row = append(row, field.MemberValue(rel, member, geom, match))
	}
	return row
}

func (field *Field) FieldType() *FieldType {
	if fieldType, ok := AvailableFieldTypes[field.Type]; ok {
		if fieldType.MakeFunc != nil {
			makeValue, err := fieldType.MakeFunc(field.Name, fieldType, *field)
			if err != nil {
				log.Print(err)
				return nil
			}
			fieldType = FieldType{fieldType.Name, fieldType.GoType, makeValue, nil, nil, fieldType.FromMember}
		}
		fieldType.FromMember = field.FromMember
		return &fieldType
	}
	return nil
}

func (t *Table) TableFields() *TableFields {
	result := TableFields{}

	for _, mappingField := range t.Fields {
		field := FieldSpec{}
		field.Key = mappingField.Key

		fieldType := mappingField.FieldType()
		if fieldType != nil {
			field.Type = *fieldType
		} else {
			log.Warn("unhandled type: ", mappingField.Type)
		}
		result.fields = append(result.fields, field)
	}
	return &result
}

type FieldType struct {
	Name       string
	GoType     string
	Func       MakeValue
	MakeFunc   MakeMakeValue
	MemberFunc MakeMemberValue
	FromMember bool
}

func Bool(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	if val == "" || val == "0" || val == "false" || val == "no" {
		return false
	}
	return true
}

func BoolInt(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	if val == "" || val == "0" || val == "false" || val == "no" {
		return 0
	}
	return 1
}

func String(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	return val
}

func Integer(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	v, err := strconv.ParseInt(val, 10, 32)
	if err != nil {
		return nil
	}
	return v
}

func Id(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	return elem.Id
}

func KeyName(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	return match.Key
}

func ValueName(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	return match.Value
}

func RelationMemberType(rel *element.Relation, member *element.Member, match Match) interface{} {
	return member.Type
}

func RelationMemberRole(rel *element.Relation, member *element.Member, match Match) interface{} {
	return member.Role
}

func RelationMemberID(rel *element.Relation, member *element.Member, match Match) interface{} {
	return member.Id
}

func RelationMemberIndex(rel *element.Relation, member *element.Member, match Match) interface{} {
	for i := range rel.Members {
		if rel.Members[i].Id == member.Id {
			return i
		}
	}
	return -1
}

func Direction(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	if val == "1" || val == "yes" || val == "true" {
		return 1
	} else if val == "-1" {
		return -1
	} else {
		return 0
	}
}

func Geometry(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	return string(geom.Wkb)
}

func PseudoArea(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	area := geom.Geom.Area()
	if area == 0.0 {
		return nil
	}
	return float32(area)
}

var hstoreReplacer = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")

func HstoreString(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	tags := make([]string, 0, len(elem.Tags))
	for k, v := range elem.Tags {
		tags = append(tags, `"`+hstoreReplacer.Replace(k)+`"=>"`+hstoreReplacer.Replace(v)+`"`)
	}
	return strings.Join(tags, ", ")
}

var wayRanks map[string]int

func init() {
	wayRanks = map[string]int{
		"minor":          3,
		"road":           3,
		"unclassified":   3,
		"residential":    3,
		"tertiary_link":  3,
		"tertiary":       4,
		"secondary_link": 3,
		"secondary":      5,
		"primary_link":   3,
		"primary":        6,
		"trunk_link":     3,
		"trunk":          8,
		"motorway_link":  3,
		"motorway":       9,
	}
}

func WayZOrder(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
	var z int32
	layer, _ := strconv.ParseInt(elem.Tags["layer"], 10, 64)
	z += int32(layer) * 10

	rank := wayRanks[match.Value]

	if rank == 0 {
		if _, ok := elem.Tags["railway"]; ok {
			rank = 7
		}
	}
	z += int32(rank)

	tunnel := elem.Tags["tunnel"]
	if tunnel == "true" || tunnel == "yes" || tunnel == "1" {
		z -= 10
	}
	bridge := elem.Tags["bridge"]
	if bridge == "true" || bridge == "yes" || bridge == "1" {
		z += 10
	}

	return z
}

func MakeZOrder(fieldName string, fieldType FieldType, field Field) (MakeValue, error) {
	log.Print("warn: zorder type is deprecated and will be removed. See enumerate type.")
	_rankList, ok := field.Args["ranks"]
	if !ok {
		return nil, errors.New("missing ranks in args for zorder")
	}

	rankList, ok := _rankList.([]interface{})
	if !ok {
		return nil, errors.New("ranks in args for zorder not a list")
	}

	var key string
	_key, ok := field.Args["key"]
	if ok {
		key, ok = _key.(string)
		if !ok {
			return nil, errors.New("key in args for zorder not a string")
		}
	}

	ranks := make(map[string]int)
	for i, rank := range rankList {
		rankName, ok := rank.(string)
		if !ok {
			return nil, errors.New("rank in ranks not a string")
		}

		ranks[rankName] = len(rankList) - i
	}

	zOrder := func(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
		if key != "" {
			if r, ok := ranks[elem.Tags[key]]; ok {
				return r
			}
			return 0
		}
		if r, ok := ranks[match.Value]; ok {
			return r
		}
		return 0
	}

	return zOrder, nil
}

func MakeEnumerate(fieldName string, fieldType FieldType, field Field) (MakeValue, error) {
	_valuesList, ok := field.Args["values"]
	if !ok {
		return nil, errors.New("missing values in args for enumerate")
	}

	valuesList, ok := _valuesList.([]interface{})
	if !ok {
		return nil, errors.New("values in args for enumerate not a list")
	}

	values := make(map[string]int)
	for i, value := range valuesList {
		valueName, ok := value.(string)
		if !ok {
			return nil, errors.New("value in values not a string")
		}

		values[valueName] = i + 1
	}
	enumerate := func(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
		if field.Key != "" {
			if r, ok := values[val]; ok {
				return r
			}
			return 0
		}
		if r, ok := values[match.Value]; ok {
			return r
		}
		return 0
	}

	return enumerate, nil
}

func MakeSuffixReplace(fieldName string, fieldType FieldType, field Field) (MakeValue, error) {
	_changes, ok := field.Args["suffixes"]
	if !ok {
		return nil, errors.New("missing suffixes in args for string_suffixreplace")
	}

	changes, ok := _changes.(map[interface{}]interface{})
	if !ok {
		return nil, errors.New("suffixes in args for string_suffixreplace not a dict")
	}
	strChanges := make(map[string]string, len(changes))
	for k, v := range changes {
		_, kok := k.(string)
		_, vok := v.(string)
		if !kok || !vok {
			return nil, errors.New("suffixes in args for string_suffixreplace not strings")
		}
		strChanges[k.(string)] = v.(string)
	}
	var suffixes []string
	for k, _ := range strChanges {
		suffixes = append(suffixes, k)
	}
	reStr := `(` + strings.Join(suffixes, "|") + `)\b`
	re := regexp.MustCompile(reStr)

	replFunc := func(match string) string {
		return strChanges[match]
	}

	suffixReplace := func(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
		if val != "" {
			return re.ReplaceAllStringFunc(val, replFunc)
		}
		return val
	}

	return suffixReplace, nil
}

func MakePbfTimestamp(fieldName string, fieldType FieldType, field Field) (MakeValue, error) {

	if config.ImportOptions.Read == "" {
		return nil, nil
	}

	pbfFile, err := pbf.Open(config.ImportOptions.Read)
	defer pbfFile.Close()

	if err != nil {
		return nil, err
	}

	timestamp := pbfFile.Header.Time.UTC().Format(time.RFC3339)
	pbfTimestamp := func(val string, elem *element.OSMElem, geom *geom.Geometry, match Match) interface{} {
		return timestamp
	}

	return pbfTimestamp, nil
}

func asHex(b []byte) string {
	digits := "0123456789ABCDEF"
	buf := make([]byte, 0, len(b)*2)
	n := len(b)

	for i := 0; i < n; i++ {
		c := b[i]
		buf = append(buf, digits[c>>4], digits[c&0xF])
	}
	return string(buf)
}


text:
import fadeDirection from './fade-direction';
export default function(opts={}) {
  return fadeDirection.call(this, 'x', 1, opts, opts.offset);
}


text:
<!--
id: 18699243
link: http://tumblr.atmos.org/post/18699243/macscripter-bbs-applescript-forums-scripting
slug: macscripter-bbs-applescript-forums-scripting
date: Wed Nov 07 2007 13:38:31 GMT-0800 (PST)
publish: 2007-11-07
tags:
title: MacScripter BBS | Applescript Forums / Scripting Terminal.app with tabs in Leopard
-->

MacScripter BBS | Applescript Forums / Scripting Terminal.app with tabs in Leopard
==================================================================================

[http://bbs.applescript.net/viewtopic.php?id=22935&action=new](http://bbs.applescript.net/viewtopic.php?id=22935&action=new)