text:
#ifndef GDBSTUB_H
#define GDBSTUB_H

#define DEFAULT_GDBSTUB_PORT "1234"

/* GDB breakpoint/watchpoint types */
#define GDB_BREAKPOINT_SW        0
#define GDB_BREAKPOINT_HW        1
#define GDB_WATCHPOINT_WRITE     2
#define GDB_WATCHPOINT_READ      3
#define GDB_WATCHPOINT_ACCESS    4

#ifdef NEED_CPU_H
typedef void (*gdb_syscall_complete_cb)(CPUState *cpu,
                                        target_ulong ret, target_ulong err);

void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...);
int use_gdb_syscalls(void);
void gdb_set_stop_cpu(CPUState *cpu);
void gdb_exit(CPUArchState *, int);
#ifdef CONFIG_USER_ONLY
int gdb_queuesig (void);
int gdb_handlesig(CPUState *, int);
void gdb_signalled(CPUArchState *, int);
void gdbserver_fork(CPUArchState *);
#endif
/* Get or set a register.  Returns the size of the register.  */
typedef int (*gdb_reg_cb)(CPUArchState *env, uint8_t *buf, int reg);
void gdb_register_coprocessor(CPUState *cpu,
                              gdb_reg_cb get_reg, gdb_reg_cb set_reg,
                              int num_regs, const char *xml, int g_pos);

static inline int cpu_index(CPUState *cpu)
{
#if defined(CONFIG_USER_ONLY)
    return cpu->host_tid;
#else
    return cpu->cpu_index + 1;
#endif
}

/* The GDB remote protocol transfers values in target byte order.  This means
 * we can use the raw memory access routines to access the value buffer.
 * Conveniently, these also handle the case where the buffer is mis-aligned.
 */

static inline int gdb_get_reg8(uint8_t *mem_buf, uint8_t val)
{
    stb_p(mem_buf, val);
    return 1;
}

static inline int gdb_get_reg16(uint8_t *mem_buf, uint16_t val)
{
    stw_p(mem_buf, val);
    return 2;
}

static inline int gdb_get_reg32(uint8_t *mem_buf, uint32_t val)
{
    stl_p(mem_buf, val);
    return 4;
}

static inline int gdb_get_reg64(uint8_t *mem_buf, uint64_t val)
{
    stq_p(mem_buf, val);
    return 8;
}

#if TARGET_LONG_BITS == 64
#define gdb_get_regl(buf, val) gdb_get_reg64(buf, val)
#define ldtul_p(addr) ldq_p(addr)
#else
#define gdb_get_regl(buf, val) gdb_get_reg32(buf, val)
#define ldtul_p(addr) ldl_p(addr)
#endif

#endif

#ifdef CONFIG_USER_ONLY
int gdbserver_start(int);
#else
int gdbserver_start(const char *port);
#endif

/**
 * gdb_has_xml:
 * This is an ugly hack to cope with both new and old gdb.
 * If gdb sends qXfer:features:read then assume we're talking to a newish
 * gdb that understands target descriptions.
 */
extern bool gdb_has_xml;

/* in gdbstub-xml.c, generated by scripts/feature_to_c.sh */
extern const char *const xml_builtin[][2];

#endif


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta name="keywords" content="jquery,ui,easy,easyui,web">
	<meta name="description" content="easyui help you build your web page easily!">
	<title>jQuery EasyUI CRUD Demo</title>
	<link rel="stylesheet" type="text/css" href="http://www.w3cschool.cc/try/jeasyui/themes/default/easyui.css">
	<link rel="stylesheet" type="text/css" href="http://www.w3cschool.cc/try/jeasyui/themes/icon.css">
	<link rel="stylesheet" type="text/css" href="http://www.w3cschool.cc/try/jeasyui/demo/demo.css">

Basic CRUD Application

Click the buttons on datagrid toolbar to do crud actions.

				First Name
				Last Name
				Phone
				Email

		New User
		Edit User
		Remove User

User Information

		<form id="fm" method="post" novalidate>

				First Name:
				<input name="firstname" class="easyui-validatebox" required="true">

				Last Name:
				<input name="lastname" class="easyui-validatebox" required="true">

				Phone:
				<input name="phone">

				Email:
				<input name="email" class="easyui-validatebox" validType="email">

		</form>

		Save
		Cancel

redpajama_set_name: RedPajamaGithub


text:
package net.dv8tion.jda.core.hooks;

import java.lang.annotation.*;

/**
 * Annotation used by the {@link net.dv8tion.jda.core.hooks.AnnotatedEventManager AnnotatedEventManager}
 * this is only picked up if the event manager implementation has been set to use the {@link net.dv8tion.jda.core.hooks.AnnotatedEventManager AnnotatedEventManager}
 * via {@link net.dv8tion.jda.core.JDABuilder#setEventManager(IEventManager) JDABuilder.setEventManager(IEventManager)}
 *
 * @see net.dv8tion.jda.core.hooks.AnnotatedEventManager
 * @see net.dv8tion.jda.core.JDABuilder
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface SubscribeEvent
{
}


text:
'use strict';

// Authentication service for user variables
angular.module('users').factory('AdminAuthService', ['$window', 'Authentication',
  function ($window, Authentication) {

    if (Authentication.user !== '') {

      var isAdmin = {
        user: $window.user.roles[0]
      };
      //console.log('isAdmin.user', isAdmin.user);
      return isAdmin;

    } else {

      isAdmin = {
        user: 'notAdmin'
      };
      //console.log('!isAdmin.user', isAdmin.user);
      return isAdmin;
    }
  }
]);


text:
import {Component, EventEmitter, Input, Output, OnChanges, ChangeDetectionStrategy} from '@angular/core';
import {getValueInRange, toInteger, toBoolean} from '../util/util';

/**
 * A directive that will take care of visualising a pagination bar and enable / disable buttons correctly!
 */
@Component({
  selector: 'ngb-pagination',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `

            ««
            First

            «
            Previous

          ...
          {{pageNumber}}

            »
            Next

            »»
            Last

  `
})
export class NgbPagination implements OnChanges {
  private _boundaryLinks: boolean = false;
  private _collectionSize;
  private _directionLinks: boolean = true;
  private _ellipses: boolean = true;
  private _maxSize = 0;
  private _page = 0;
  private _pageCount = 0;
  private _pageSize = 10;
  private _rotate: boolean = false;
  pages: number[] = [];

  /**
   *  Whether to show the "First" and "Last" page links
   */
  @Input()
  set boundaryLinks(value: boolean) {
    this._boundaryLinks = toBoolean(value);
  }

  get boundaryLinks(): boolean { return this._boundaryLinks; }

  /**
   *  Whether to show the "Next" and "Previous" page links
   */
  @Input()
  set directionLinks(value: boolean) {
    this._directionLinks = toBoolean(value);
  }

  get directionLinks(): boolean { return this._directionLinks; }

  /**
   *  Whether to show ellipsis symbols and first/last page numbers when maxSize > number of pages
   */
  @Input()
  set ellipses(value: boolean) {
    this._ellipses = toBoolean(value);
  }

  get ellipses(): boolean { return this._ellipses; }

  /**
   *  Number of items in collection.
   */
  @Input()
  set collectionSize(value: number | string) {
    this._collectionSize = toInteger(value);
  }

  get collectionSize(): number | string { return this._collectionSize; }

  /**
   *  Maximum page numbers to be displayed
   */
  @Input()
  set maxSize(value: number | string) {
    this._maxSize = toInteger(value);
  }

  get maxSize(): number | string { return this._maxSize; }

  /**
   *  Current page.
   */
  @Input()
  set page(value: number | string) {
    this._page = parseInt(`${value}`, 10);
  }

  get page(): number | string { return this._page; }

  /**
   *  Number of items per page.
   */
  @Input()
  set pageSize(value: number | string) {
    this._pageSize = toInteger(value);
  }

  get pageSize(): number | string { return this._pageSize; }

  /**
   *  An event fired when the page is changed.
   *  Event's payload equals the current page.
   */
  @Output() pageChange = new EventEmitter();

  /**
   *  Whether to rotate pages when maxSize > number of pages.
   *  Current page will be in the middle
   */
  @Input()
  set rotate(value: boolean) {
    this._rotate = toBoolean(value);
  }

  get rotate(): boolean { return this._rotate; }

  /**
   * Pagination display size: small or large
   */
  @Input() size: 'sm' | 'lg';

  hasPrevious(): boolean { return this.page > 1; }

  hasNext(): boolean { return this.page < this._pageCount; }

  selectPage(pageNumber: number): void {
    let prevPageNo = this.page;
    this._page = this._getPageNoInRange(pageNumber);

    if (this.page !== prevPageNo) {
      this.pageChange.emit(this.page);
    }

    this.ngOnChanges();
  }

  ngOnChanges(): void {
    // re-calculate new length of pages
    this._pageCount = Math.ceil(this._collectionSize / this._pageSize);

    // fill-in model needed to render pages
    this.pages.length = 0;
    for (let i = 1; i <= this._pageCount; i++) {
      this.pages.push(i);
    }

    // get selected page
    this._page = this._getPageNoInRange(this.page);

    // apply maxSize if necessary
    if (this._maxSize > 0 && this._pageCount > this._maxSize) {
      let start = 0;
      let end = this._pageCount;

      // either paginating or rotating page numbers
      if (this._rotate) {
        [start, end] = this._applyRotation();
      } else {
        [start, end] = this._applyPagination();
      }

      this.pages = this.pages.slice(start, end);

      // adding ellipses
      this._applyEllipses(start, end);
    }
  }

  /**
   * Appends ellipses and first/last page number to the displayed pages
   */
  private _applyEllipses(start: number, end: number) {
    if (this._ellipses) {
      if (start > 0) {
        this.pages.unshift(-1);
        this.pages.unshift(1);
      }
      if (end < this._pageCount) {
        this.pages.push(-1);
        this.pages.push(this._pageCount);
      }
    }
  }

  /**
   * Rotates page numbers based on maxSize items visible.
   * Currently selected page stays in the middle:
   *
   * Ex. for selected page = 6:
   * [5,*6*,7] for maxSize = 3
   * [4,5,*6*,7] for maxSize = 4
   */
  private _applyRotation(): [number, number] {
    let start = 0;
    let end = this._pageCount;
    let leftOffset = Math.floor(this._maxSize / 2);
    let rightOffset = this._maxSize % 2 === 0 ? leftOffset - 1 : leftOffset;

    if (this._page <= leftOffset) {
      // very beginning, no rotation -> [0..maxSize]
      end = this._maxSize;
    } else if (this._pageCount - this._page < leftOffset) {
      // very end, no rotation -> [len-maxSize..len]
      start = this._pageCount - this._maxSize;
    } else {
      // rotate
      start = this._page - leftOffset - 1;
      end = this._page + rightOffset;
    }

    return [start, end];
  }

  /**
   * Paginates page numbers based on maxSize items per page
   */
  private _applyPagination(): [number, number] {
    let page = Math.ceil(this._page / this._maxSize) - 1;
    let start = page * this._maxSize;
    let end = start + this._maxSize;

    return [start, end];
  }

  private _isEllipsis(pageNumber): boolean { return pageNumber === -1; }

  private _getPageNoInRange(newPageNo): number { return getValueInRange(newPageNo, this._pageCount, 1); }
}

export const NGB_PAGINATION_DIRECTIVES = [NgbPagination];


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Jb. nassau. Ver. Naturk. 23-24: 166 (1870)

#### Original name
null

### Remarks
null


text:
/**
 * The actual Sign In view, with the login form
 */

import assign from 'object-assign';
import classnames from 'classnames';
import React from 'react';
import xhr from 'xhr';

import Alert from './components/Alert';
import Brand from './components/Brand';
import UserInfo from './components/UserInfo';
import LoginForm from './components/LoginForm';

var SigninView = React.createClass({
	getInitialState () {
		return {
			email: '',
			password: '',
			isAnimating: false,
			isInvalid: false,
			invalidMessage: '',
			signedOut: window.location.search === '?signedout',
		};
	},
	componentDidMount () {
		// Focus the email field when we're mounted
		if (this.refs.email) {
			this.refs.email.select();
		}
	},
	handleInputChange (e) {
		// Set the new state when the input changes
		const newState = {};
		newState[e.target.name] = e.target.value;
		this.setState(newState);
	},
	handleSubmit (e) {
		e.preventDefault();
		// If either password or mail are missing, show an error
		if (!this.state.email || !this.state.password) {
			return this.displayError('Digite seu email e senha para entrar.');
		}

		xhr({
			url: `${Keystone.adminPath}/api/session/signin`,
			method: 'post',
			json: {
				email: this.state.email,
				password: this.state.password,
			},
			headers: assign({}, Keystone.csrf.header),
		}, (err, resp, body) => {
			if (err || body && body.error) {
				return body.error === 'invalid csrf'
					? this.displayError('Algo deu errado; atualize a página e tente novamente.')
					: this.displayError('O email e senha digitados são inválidos.');
			} else {
				// Redirect to where we came from or to the default admin path
				if (Keystone.redirect) {
					top.location.href = Keystone.redirect;
				} else {
					top.location.href = this.props.from ? this.props.from : Keystone.adminPath;
				}
			}
		});
	},
	/**
	 * Display an error message
	 *
	 * @param  {String} message The message you want to show
	 */
	displayError (message) {
		this.setState({
			isAnimating: true,
			isInvalid: true,
			invalidMessage: message,
		});
		setTimeout(this.finishAnimation, 750);
	},
	// Finish the animation and select the email field
	finishAnimation () {
		// TODO isMounted was deprecated, find out if we need this guard
		if (!this.isMounted()) return;
		if (this.refs.email) {
			this.refs.email.select();
		}
		this.setState({
			isAnimating: false,
		});
	},
	render () {
		const boxClassname = classnames('auth-box', {
			'auth-box--has-errors': this.state.isAnimating,
		});
		return (

				<Alert
					isInvalid={this.state.isInvalid}
					signedOut={this.state.signedOut}
					invalidMessage={this.state.invalidMessage}
				/>

{this.props.brand ? this.props.brand : 'Keystone'} Entrar

						<Brand
							logo={this.props.logo}
							brand={this.props.brand}
						/>
						{this.props.user ? (
							<UserInfo
								adminPath={this.props.from ? this.props.from : Keystone.adminPath}
								signoutPath={`${Keystone.adminPath}/signout`}
								userCanAccessKeystone={this.props.userCanAccessKeystone}
								userName={this.props.user.name}
							/>
						) : (
							<LoginForm
								email={this.state.email}
								handleInputChange={this.handleInputChange}
								handleSubmit={this.handleSubmit}
								isAnimating={this.state.isAnimating}
								password={this.state.password}
							/>
						)}

					Powered by
					KeystoneJS

		);
	},
});

module.exports = SigninView;


text:
using Newtonsoft.Json;

namespace HalowerHub.JqGrid
{
    public class Formatoption
    {
        /// <summary>
        /// 千分位分隔符 [currency,integer,number]
        /// </summary>
        [JsonProperty("thousandsSeparator")]
        public string ThousandsSeparator { get; set; }
        /// <summary>
        /// 默认值 [integer,number]
        /// </summary>
        [JsonProperty("defaulValue")]
        public string DefaulValue { get; set; }
        /// <summary>
        /// 小数分隔符 [currency,number]
        /// </summary>
        [JsonProperty("decimalSeparator")]
        public string DecimalSeparator { get; set; }
        /// <summary>
        /// 小数保留位数 [currency,number]
        /// </summary>
        [JsonProperty("decimalPlaces")]
        public string DecimalPlaces { get; set; }
        /// <summary>
        /// 前缀 currency
        /// </summary>
        [JsonProperty("prefix")]
        public string Prefix { get; set; }
        /// <summary>
        /// 后缀
        /// </summary>
        [JsonProperty("suffix")]
        public string Suffix { get; set; }
        /// <summary>
        /// 本来格式 [date]
        /// </summary>
        [JsonProperty("srcformat")]
        public string Srcformat { get; set; }
        /// <summary>
        /// 新格式 [date]
        /// </summary>
        [JsonProperty("newformat")]
        public string Newformat { get; set; }
        /// <summary>
        /// 在当前cell中加入link的url [showlink]
        /// </summary>
        [JsonProperty("baseLinkUrl")]
        public string BaseLinkUrl { get; set; }

        /// <summary>
        /// /在baseLinkUrl后加入额外的参数,如&name=aaaa [showlink]
        /// </summary>
        [JsonProperty("addParam")]
        public string addParam { get; set; }
        /// <summary>
        /// 默认会在baseLinkUrl后加入,如".action?id=1″[showlink]
        /// </summary>
        [JsonProperty("idName")]
        public string IdName { get; set; }

        /// <summary>
        ///  默认为true此时的checkbox不能编辑 [checkbox]
        /// </summary>
        [JsonProperty("disabled ")]
        public bool Disabled { get; set; }
    }
}


text:
package predicates

import (
	"fmt"

	"k8s.io/api/core/v1"
)

var (
	// The predicateName tries to be consistent as the predicate name used in DefaultAlgorithmProvider defined in
	// defaults.go (which tend to be stable for backward compatibility)

	// NOTE: If you add a new predicate failure error for a predicate that can never
	// be made to pass by removing pods, or you change an existing predicate so that
	// it can never be made to pass by removing pods, you need to add the predicate
	// failure error in nodesWherePreemptionMightHelp() in scheduler/core/generic_scheduler.go

	// ErrDiskConflict is used for NoDiskConflict predicate error.
	ErrDiskConflict = newPredicateFailureError("NoDiskConflict", "node(s) had no available disk")
	// ErrVolumeZoneConflict is used for NoVolumeZoneConflict predicate error.
	ErrVolumeZoneConflict = newPredicateFailureError("NoVolumeZoneConflict", "node(s) had no available volume zone")
	// ErrNodeSelectorNotMatch is used for MatchNodeSelector predicate error.
	ErrNodeSelectorNotMatch = newPredicateFailureError("MatchNodeSelector", "node(s) didn't match node selector")
	// ErrPodAffinityNotMatch is used for MatchInterPodAffinity predicate error.
	ErrPodAffinityNotMatch = newPredicateFailureError("MatchInterPodAffinity", "node(s) didn't match pod affinity/anti-affinity")
	// ErrPodAffinityRulesNotMatch is used for PodAffinityRulesNotMatch predicate error.
	ErrPodAffinityRulesNotMatch = newPredicateFailureError("PodAffinityRulesNotMatch", "node(s) didn't match pod affinity rules")
	// ErrPodAntiAffinityRulesNotMatch is used for PodAntiAffinityRulesNotMatch predicate error.
	ErrPodAntiAffinityRulesNotMatch = newPredicateFailureError("PodAntiAffinityRulesNotMatch", "node(s) didn't match pod anti-affinity rules")
	// ErrExistingPodsAntiAffinityRulesNotMatch is used for ExistingPodsAntiAffinityRulesNotMatch predicate error.
	ErrExistingPodsAntiAffinityRulesNotMatch = newPredicateFailureError("ExistingPodsAntiAffinityRulesNotMatch", "node(s) didn't satisfy existing pods anti-affinity rules")
	// ErrTaintsTolerationsNotMatch is used for PodToleratesNodeTaints predicate error.
	ErrTaintsTolerationsNotMatch = newPredicateFailureError("PodToleratesNodeTaints", "node(s) had taints that the pod didn't tolerate")
	// ErrPodNotMatchHostName is used for HostName predicate error.
	ErrPodNotMatchHostName = newPredicateFailureError("HostName", "node(s) didn't match the requested hostname")
	// ErrPodNotFitsHostPorts is used for PodFitsHostPorts predicate error.
	ErrPodNotFitsHostPorts = newPredicateFailureError("PodFitsHostPorts", "node(s) didn't have free ports for the requested pod ports")
	// ErrNodeLabelPresenceViolated is used for CheckNodeLabelPresence predicate error.
	ErrNodeLabelPresenceViolated = newPredicateFailureError("CheckNodeLabelPresence", "node(s) didn't have the requested labels")
	// ErrServiceAffinityViolated is used for CheckServiceAffinity predicate error.
	ErrServiceAffinityViolated = newPredicateFailureError("CheckServiceAffinity", "node(s) didn't match service affinity")
	// ErrMaxVolumeCountExceeded is used for MaxVolumeCount predicate error.
	ErrMaxVolumeCountExceeded = newPredicateFailureError("MaxVolumeCount", "node(s) exceed max volume count")
	// ErrNodeUnderMemoryPressure is used for NodeUnderMemoryPressure predicate error.
	ErrNodeUnderMemoryPressure = newPredicateFailureError("NodeUnderMemoryPressure", "node(s) had memory pressure")
	// ErrNodeUnderDiskPressure is used for NodeUnderDiskPressure predicate error.
	ErrNodeUnderDiskPressure = newPredicateFailureError("NodeUnderDiskPressure", "node(s) had disk pressure")
	// ErrNodeOutOfDisk is used for NodeOutOfDisk predicate error.
	ErrNodeOutOfDisk = newPredicateFailureError("NodeOutOfDisk", "node(s) were out of disk space")
	// ErrNodeNotReady is used for NodeNotReady predicate error.
	ErrNodeNotReady = newPredicateFailureError("NodeNotReady", "node(s) were not ready")
	// ErrNodeNetworkUnavailable is used for NodeNetworkUnavailable predicate error.
	ErrNodeNetworkUnavailable = newPredicateFailureError("NodeNetworkUnavailable", "node(s) had unavailable network")
	// ErrNodeUnschedulable is used for NodeUnschedulable predicate error.
	ErrNodeUnschedulable = newPredicateFailureError("NodeUnschedulable", "node(s) were unschedulable")
	// ErrNodeUnknownCondition is used for NodeUnknownCondition predicate error.
	ErrNodeUnknownCondition = newPredicateFailureError("NodeUnknownCondition", "node(s) had unknown conditions")
	// ErrVolumeNodeConflict is used for VolumeNodeAffinityConflict predicate error.
	ErrVolumeNodeConflict = newPredicateFailureError("VolumeNodeAffinityConflict", "node(s) had volume node affinity conflict")
	// ErrVolumeBindConflict is used for VolumeBindingNoMatch predicate error.
	ErrVolumeBindConflict = newPredicateFailureError("VolumeBindingNoMatch", "node(s) didn't find available persistent volumes to bind")
	// ErrFakePredicate is used for test only. The fake predicates returning false also returns error
	// as ErrFakePredicate.
	ErrFakePredicate = newPredicateFailureError("FakePredicateError", "Nodes failed the fake predicate")
)

// InsufficientResourceError is an error type that indicates what kind of resource limit is
// hit and caused the unfitting failure.
type InsufficientResourceError struct {
	// resourceName is the name of the resource that is insufficient
	ResourceName v1.ResourceName
	requested    int64
	used         int64
	capacity     int64
}

// NewInsufficientResourceError returns an InsufficientResourceError.
func NewInsufficientResourceError(resourceName v1.ResourceName, requested, used, capacity int64) *InsufficientResourceError {
	return &InsufficientResourceError{
		ResourceName: resourceName,
		requested:    requested,
		used:         used,
		capacity:     capacity,
	}
}

func (e *InsufficientResourceError) Error() string {
	return fmt.Sprintf("Node didn't have enough resource: %s, requested: %d, used: %d, capacity: %d",
		e.ResourceName, e.requested, e.used, e.capacity)
}

// GetReason returns the reason of the InsufficientResourceError.
func (e *InsufficientResourceError) GetReason() string {
	return fmt.Sprintf("Insufficient %v", e.ResourceName)
}

// GetInsufficientAmount returns the amount of the insufficient resource of the error.
func (e *InsufficientResourceError) GetInsufficientAmount() int64 {
	return e.requested - (e.capacity - e.used)
}

// PredicateFailureError describes a failure error of predicate.
type PredicateFailureError struct {
	PredicateName string
	PredicateDesc string
}

func newPredicateFailureError(predicateName, predicateDesc string) *PredicateFailureError {
	return &PredicateFailureError{PredicateName: predicateName, PredicateDesc: predicateDesc}
}

func (e *PredicateFailureError) Error() string {
	return fmt.Sprintf("Predicate %s failed", e.PredicateName)
}

// GetReason returns the reason of the PredicateFailureError.
func (e *PredicateFailureError) GetReason() string {
	return e.PredicateDesc
}

// FailureReason describes a failure reason.
type FailureReason struct {
	reason string
}

// NewFailureReason creates a FailureReason with message.
func NewFailureReason(msg string) *FailureReason {
	return &FailureReason{reason: msg}
}

// GetReason returns the reason of the FailureReason.
func (e *FailureReason) GetReason() string {
	return e.reason
}


text:
package com.amazonaws.services.ssoadmin.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.ssoadmin.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * PermissionSetProvisioningStatus JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PermissionSetProvisioningStatusJsonUnmarshaller implements Unmarshaller<PermissionSetProvisioningStatus, JsonUnmarshallerContext> {

    public PermissionSetProvisioningStatus unmarshall(JsonUnmarshallerContext context) throws Exception {
        PermissionSetProvisioningStatus permissionSetProvisioningStatus = new PermissionSetProvisioningStatus();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Status", targetDepth)) {
                    context.nextToken();
                    permissionSetProvisioningStatus.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("RequestId", targetDepth)) {
                    context.nextToken();
                    permissionSetProvisioningStatus.setRequestId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("AccountId", targetDepth)) {
                    context.nextToken();
                    permissionSetProvisioningStatus.setAccountId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("PermissionSetArn", targetDepth)) {
                    context.nextToken();
                    permissionSetProvisioningStatus.setPermissionSetArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("FailureReason", targetDepth)) {
                    context.nextToken();
                    permissionSetProvisioningStatus.setFailureReason(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("CreatedDate", targetDepth)) {
                    context.nextToken();
                    permissionSetProvisioningStatus.setCreatedDate(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return permissionSetProvisioningStatus;
    }

    private static PermissionSetProvisioningStatusJsonUnmarshaller instance;

    public static PermissionSetProvisioningStatusJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new PermissionSetProvisioningStatusJsonUnmarshaller();
        return instance;
    }
}


text:
package management.operations.events.impl;

import static management.util.HydraUtil.logInfo;

import java.util.List;
import java.util.Map;

import management.operations.OperationEvent;
import management.operations.OperationPrms;
import management.operations.events.EntryOperationEvents;

public class EntryEvents extends AbstractEvents implements EntryOperationEvents {

  public EntryEvents(){

  }

  public EntryEvents(Map<String, List<OperationEvent>> eventMap) {
    super(eventMap);
    // TODO Auto-generated constructor stub
  }

  @Override
  public void entryAdded(String regionName, String key, Object value) {
    if (OperationPrms.recordEntryOperations()) {
      OperationEvent event = new OperationEvent();
      event.name = EVENT_ENTRY_ADDED;
      event.data = key;
      addEvent(event);
    }
    logInfo("EntryOperations: region:" + regionName + " Finished with adding entry : " + key);
  }

  @Override
  public void entryInvalidated(String regionName, String key) {
    if (OperationPrms.recordEntryOperations()) {
      OperationEvent event = new OperationEvent();
      event.name = EVENT_ENTRY_INVALIDATED;
      event.data = key;
      addEvent(event);
    }
    logInfo("EntryOperations: region:" + regionName + " Finished with invalidating entry : " + key);
  }

  @Override
  public void entryDestroyed(String regionName, String key) {
    if (OperationPrms.recordEntryOperations()) {
      OperationEvent event = new OperationEvent();
      event.name = EVENT_ENTRY_DESTROYED;
      event.data = key;
      addEvent(event);
    }
    logInfo("EntryOperations: region:" + regionName + " Finished with destroying entry : " + key);
  }

  @Override
  public void entryUpdated(String regionName, String key, Object value) {
    if (OperationPrms.recordEntryOperations()) {
      OperationEvent event = new OperationEvent();
      event.name = EVENT_ENTRY_UPDATED;
      event.data = key;
      addEvent(event);
    }
    logInfo("EntryOperations: region:" + regionName + " Finished with updating entry : " + key);
  }

  @Override
  public void entryRead(String regionName, String key) {
    if (OperationPrms.recordEntryOperations()) {
      OperationEvent event = new OperationEvent();
      event.name = EVENT_ENTRY_READ;
      event.data = key;
      addEvent(event);
    }
    logInfo("EntryOperations: region:" + regionName + " Finished with reading entry : " + key);
  }

  @Override
  public void entryInvalidatedLocal(String regionName, String key) {
    if (OperationPrms.recordEntryOperations()) {
      OperationEvent event = new OperationEvent();
      event.name = EVENT_ENTRY_INVALIDATEDLOCAL;
      event.data = key;
      addEvent(event);
    }
    logInfo("EntryOperations: region:" + regionName + " Finished with invalidating locally entry : " + key);
  }

  @Override
  public void entryDestroyedLocal(String regionName, String key) {
    if (OperationPrms.recordEntryOperations()) {
      OperationEvent event = new OperationEvent();
      event.name = EVENT_ENTRY_DESTROYEDLOCAL;
      event.data = key;
      addEvent(event);
    }
    logInfo("EntryOperations: region:" + regionName + " Finished with destroying locally entry : " + key);
  }

  @Override
  public void entryPutIfAbsent(String regionName, String key, Object value) {
    if (OperationPrms.recordEntryOperations()) {
      OperationEvent event = new OperationEvent();
      event.name = EVENT_ENTRY_PUTIFABSENT;
      event.data = key;
      addEvent(event);
    }
    logInfo("EntryOperations: region:" + regionName + " Finished with puting IFAbsent entry : " + key);
  }

  @Override
  public void entryRemoved(String regionName, String key) {
    if (OperationPrms.recordEntryOperations()) {
      OperationEvent event = new OperationEvent();
      event.name = EVENT_ENTRY_REMOVED;
      event.data = key;
      addEvent(event);
    }
    logInfo("EntryOperations: region:" + regionName + " Finished with removing entry : " + key);
  }

  @Override
  public void entryReplaced(String regionName, String key, Object value) {
    if (OperationPrms.recordEntryOperations()) {
      OperationEvent event = new OperationEvent();
      event.name = EVENT_ENTRY_REPLACED;
      event.data = key;
      addEvent(event);
    }
    logInfo("EntryOperations: region:" + regionName + " Finished with replacing entry : " + key);
  }

}


text:
//
//  LYWaterflowLyaout.h
//  27-瀑布流
//
//  Created by cailingyun on 15-7-25.
//  Copyright (c) 2015年 cailingyun. All rights reserved.
//

#import <UIKit/UIKit.h>

@class LYWaterflowLyaout;

@protocol LYWaterflowLyaoutDelegate <NSObject>

@optional

- (CGFloat)waterflowLayout:(LYWaterflowLyaout *)waterflowLayout heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath;

@end

@interface LYWaterflowLyaout : UICollectionViewLayout
@property (nonatomic, assign) UIEdgeInsets sectionInset;
/** 每一列之间的间距 */
@property (nonatomic, assign) CGFloat columnMargin;
/** 每一行之间的间距 */
@property (nonatomic, assign) CGFloat rowMargin;
/** 显示多少列 */
@property (nonatomic, assign) int columnsCount;

@property (nonatomic, weak) id<LYWaterflowLyaoutDelegate> delegate;

@end


text:
class ErrorsController < Flame::Controller
	def foo(first, second, third = nil, fourth = nil); end
end

shared_examples 'error with correct output' do
	describe '#message' do
		subject { super().message }

		it { is_expected.to eq correct_message }
	end

	describe '#inspect' do
		subject { super().inspect }

		it { is_expected.to eq "#<#{error.class}: #{correct_message}>" }
	end
end


text:
import React from 'react';
import Layout from 'focus-components/components/layout';

import MenuLeft from '../views/menu/menu-left';
import Footer from '../views/footer';

const CustomLayout = (props) => (
    <div>
        <Layout
            Footer={Footer}
            MenuLeft={MenuLeft}
        >
            {props.children}
        </Layout>
    </div>
);
CustomLayout.displayName = 'CustomAppLayout';

export default CustomLayout;


text:
package to.cwa.trocado.upload.om;

/**
 * @author krico
 * @since 08/05/16.
 */
public class UploadResult {
    private String id;
    private String name;
    private int size;
    private String type;
    private long lastModified;

    public UploadResult() {
    }

    public UploadResult(String id, Upload origin) {
        this.id = id;
        this.name = origin.getName();
        this.size = origin.getSize();
        this.type = origin.getType();
        this.lastModified = origin.getLastModified();
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public long getLastModified() {
        return lastModified;
    }

    public void setLastModified(long lastModified) {
        this.lastModified = lastModified;
    }
}


text:
'use strict';

describe('myApp.topReddit module', function() {

    beforeEach(module('myApp.topReddit'));

    describe('myApp.topReddit controller', function(){
        var scope, data, createController;
        beforeEach(inject(function($controller, $rootScope){
            scope = $rootScope.$new();
            scope.subreddit = 'programming';
            createController = function() {
                return $controller('topRedditController', {
                    $scope : scope
                });
            };

        }));

        it('should set subreddit context',function(){
            createController();
            expect(scope.url()).toBe('http://www.reddit.com/r/programming.json?limit=5');
            expect(scope.modifier).toBe(".json");
            expect(scope.time).toBe("");
            expect(scope.count).toBe(5);
        });

        describe("data retrieval",function(){
            var httpBackend, hotChildren, topChildren;
            beforeEach(inject(function($httpBackend){
                hotChildren = [];
                topChildren = [];
                $httpBackend.when('GET','http://www.reddit.com/r/programming.json?limit=5')
                                                    .respond({ data : {
                        children : hotChildren
                    }});

                $httpBackend.when('GET','http://www.reddit.com/r/programming/top.json?limit=5')
                    .respond({ data : {
                        children : topChildren
                    }});

                $httpBackend.when('GET','http://www.reddit.com/r/programming.json?t=year&limit=5')
                    .respond({ data : {
                        children : topChildren
                    }});

                httpBackend = $httpBackend;
            }));

            it('should request for data',function(){
                httpBackend.expectGET('http://www.reddit.com/r/programming.json?limit=5');
                createController();
                httpBackend.flush();
            });

            it('should set link data per response',function(){
                hotChildren.push({ url: "test1", title: "title1"});
                hotChildren.push({ url: "test2", title: "title2"});

                createController();
                httpBackend.flush();
                expect(scope.topLinks.length).toBe(2);
            });

            it('should refresh data when modifier changes',function(){
                hotChildren.push({ url: "hot1", title: "title1"});

                topChildren.push({ url: "top2", title: "title2"});
                topChildren.push({ url: "top3", title: "title3"});
                topChildren.push({ url: "top4", title: "title4"});

                createController();
                httpBackend.flush();
                expect(scope.topLinks.length).toBe(1);

                scope.modifier = "/top.json";
                scope.$digest();
                httpBackend.flush();
                expect(scope.topLinks.length).toBe(3);
                expect(JSON.stringify(scope.topLinks)).toBe(JSON.stringify(topChildren));
            });

            it('should refresh data when date mod changes',function(){
                hotChildren.push({ url: "hot1", title: "title1"});

                topChildren.push({ url: "top2", title: "title2"});
                topChildren.push({ url: "top3", title: "title3"});
                topChildren.push({ url: "top4", title: "title4"});

                createController();
                httpBackend.flush();
                expect(scope.topLinks.length).toBe(1);

                scope.time = "t=year";
                scope.$digest();
                httpBackend.flush();
                expect(scope.topLinks.length).toBe(3);
                expect(JSON.stringify(scope.topLinks)).toBe(JSON.stringify(topChildren));
            });
        });
    });

});


text:
package com.sam.gamestates;

import com.sam.managers.GameStateManager;

public abstract class GameState {

protected GameStateManager gsm;

	protected GameState(GameStateManager gsm){
		this.gsm = gsm;
		init();
	}

	public abstract void init();
	public abstract void update(float dt);
	public abstract void draw();
	public abstract void handleInput();
	public abstract void dispose();
}


text:
**1)** Add `django_web_secure` in `settings.py`, INSTALLED_APPS:

```
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.flatpages',

    'django_web_secure',
)
```

**2)** Add `django_web_secure.middleware.WebSecureMiddleware` in `settings.py`, MIDDLEWARE_CLASSES

It must be added before `CommonMiddleware`!

```
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',

    'django_web_secure.middleware.WebSecureMiddleware'

    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
```

3) Add and set the following settings in `settings.py`:

* `SECURE_ENFORCE_SSL` = True/False (recommended True)
* `SECURE_SSL_HOST` = 'example.com' (recommended your HTTPS host)
* `SECURE_EXEMPT_HOSTS` = 'regex string' containing any malicious (according to you) hosts
* `SECURE_HSTS_MAX_AGE` = integer seconds (recommended `31536000` which equals 1 year).
* `SECURE_HSTS_INCLUDE_SUBDOMAINS` = True/False, if you want subdomains-wide HSTS
* `SECURE_HSTS_PRELOAD` = True/False, if you want to take advantage of HSTS preloading on Chrome and Firefox. However it requires some extra work, read more here ->  https://hstspreload.appspot.com/
* `SECURE_CONTENT_POLICY` = 'directives' as seen in w3's site, [here](http://www.w3.org/TR/CSP2/#sec-directives)
* `SECURE_CONTENT_TYPE_NOSNIFF` = True/False to prevent MIME-sniffing a response in most browsers.
* `SECURE_XSS_FILTER` = True/False to force enable Cross-site-scripting filter.

**4)** Restart your Django web app.


text:
import VueComponent from '../../vue/VueComponent';
import templateFn from './template.pug';

class SelfAdjustingIframeComponent extends VueComponent {

  props() {
    return {
      props: {
        url: {
          type: String
        },
        modifierClass: {
          type: String,
          required: true,
          default: ''
        }
      },
      watch: {
        url: {
          handler: 'onUrlChange'
        }
      },
      template: templateFn({})
    };
  }

  data() {
    return {
      timeouts: []
    };
  }

  mounted() {
    this.onUrlChange();
    window.addEventListener('resize', this.updateHeight, {passive: false});
  }

  beforeDestroy() {
    window.removeEventListener('resize', this.updateHeight);
    this.clearTimeouts();
  }

  getHeightFromChildNodes(document) {
    return [...document.body.childNodes]
      .filter((child) => child.offsetHeight)
      .map((child) => this.getHeightWithMargin(child))
      .sort((a, b) => a > b)
      .shift();
  }

  getHeightWithMargin(element) {
    const {marginBottom, marginTop} = getComputedStyle(element);
    return Number.parseInt(marginTop) + Number.parseInt(marginBottom) + Number.parseInt(element.offsetHeight);
  }

  onUrlChange() {
    const {[this.url]: {height = 0} = {height: 0}} = this.$store.getters.iframeStates;
    this.setHeight(height);
  }

  setHeight(height = 0) {
    this.height = height;
    this.$refs.iframe.style.height = `${height}px`;
  }

  updateHeight() {
    const {iframe: {contentWindow: {document, document: {body} = {}} = {}} = {}} = this.$refs;

    if (body) {
      let height = this.getHeightFromChildNodes(document) || 200;

      if (this.height === height) {
        this.$store.commit('setIframeState', {url: this.url, height});
        return;
      }
      this.setHeight(height);
    }

    this.timeouts = [
      setTimeout(this.updateHeight, 100),
      setTimeout(this.updateHeight, 500),
      setTimeout(this.updateHeight, 1000),
      setTimeout(this.updateHeight, 2000)
    ];
  }

  clearTimeouts() {
    this.timeouts.forEach(clearTimeout);
  }
}

SelfAdjustingIframeComponent.register('self-adjusting-iframe', SelfAdjustingIframeComponent);

export default SelfAdjustingIframeComponent;


text:
package org.jvmmonitor.internal.ui.properties.mbean;

import javax.management.Notification;

import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Tree;

/**
 * The notification comparator.
 */
public class NotificationComparator extends ViewerComparator {

    /** the sort direction */
    private int sortDirection;

    /** the column index */
    private int columnIndex;

    /**
     * The constructor.
     *
     * @param columnIndex
     *            the column index
     */
    public NotificationComparator(int columnIndex) {
        this.columnIndex = columnIndex;
        sortDirection = SWT.DOWN;
    }

    /*
     * @see ViewerComparator#compare(Viewer, Object, Object)
     */
    @Override
    public int compare(Viewer treeViewer, Object e1, Object e2) {
        int result = 0;

        if (!(e1 instanceof Notification) || !(e2 instanceof Notification)
                || !(treeViewer instanceof TreeViewer)) {
            return result;
        }

        Notification element1 = (Notification) e1;
        Notification element2 = (Notification) e2;

        Tree tree = ((TreeViewer) treeViewer).getTree();
        if (columnIndex == getColumnIndex(tree, NotificationColumn.MESSAGE)) {
            result = super.compare(treeViewer, element1.getMessage(), element2
                    .getMessage());
        } else if (columnIndex == getColumnIndex(tree, NotificationColumn.DATE)) {
            result = element1.getTimeStamp() > element2.getTimeStamp() ? 1 : -1;
        } else if (columnIndex == getColumnIndex(tree, NotificationColumn.TYPE)) {
            result = super.compare(treeViewer, element1.getType(), element2
                    .getType());
        } else if (columnIndex == getColumnIndex(tree,
                NotificationColumn.SEQUENCE_NUMBER)) {
            result = element1.getSequenceNumber() > element2
                    .getSequenceNumber() ? 1 : -1;
        }

        if (sortDirection == SWT.DOWN) {
            result *= -1;
        }
        return result;
    }

    /**
     * Reverses the sort direction.
     */
    protected void reverseSortDirection() {
        sortDirection = (sortDirection == SWT.UP) ? SWT.DOWN : SWT.UP;
    }

    /**
     * Gets the sort direction.
     *
     * @return the sort direction
     */
    protected int getSortDirection() {
        return sortDirection;
    }

    /**
     * Gets the column index.
     *
     * @return the column index
     */
    protected int getColumnIndex() {
        return columnIndex;
    }

    /**
     * Gets the column index corresponding to the given column.
     *
     * @param tree
     *            The tree
     * @param column
     *            The notification column
     * @return The column index
     */
    private static int getColumnIndex(Tree tree, NotificationColumn column) {
        for (int i = 0; i < tree.getColumnCount(); i++) {
            if (tree.getColumn(i).getText().equals(column.label)) {
                return i;
            }
        }
        return -1;
    }
}


text:
package org.jbpm.process.audit.strategy;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TransactionRequiredException;
import javax.transaction.Status;
import javax.transaction.UserTransaction;

import org.jbpm.process.audit.JPAWorkingMemoryDbLogger;
import org.kie.api.runtime.KieSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This strategy is used by instances that are

 *
used outside the {@link KieSession}

 *
use their own {@link EntityManager} instance per operation

 *

 */
public class StandaloneLocalStrategy implements PersistenceStrategy {

    protected EntityManagerFactory emf;

    public StandaloneLocalStrategy(EntityManagerFactory emf) {
        this.emf = emf;
    }

    @Override
    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    @Override
    public Object joinTransaction(EntityManager em) {
       em.getTransaction().begin();
       return true;
    }

    @Override
    public void leaveTransaction(EntityManager em, Object transaction) {
        em.getTransaction().commit();
        em.close();
    }

    @Override
    public void dispose() {
        // NEVER close the emf, you don't know what it is also being used for!
        emf = null;
    }
}


text:
package org.apache.pulsar.functions.worker;

import com.google.common.annotations.VisibleForTesting;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.distributedlog.api.namespace.Namespace;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Reader;
import org.apache.pulsar.common.functions.WorkerInfo;
import org.apache.pulsar.common.policies.data.ErrorData;
import org.apache.pulsar.common.policies.data.FunctionStats;
import org.apache.pulsar.functions.instance.AuthenticationConfig;
import org.apache.pulsar.functions.proto.Function;
import org.apache.pulsar.functions.proto.Function.Assignment;
import org.apache.pulsar.functions.runtime.KubernetesRuntimeFactory;
import org.apache.pulsar.functions.runtime.ProcessRuntimeFactory;
import org.apache.pulsar.functions.runtime.RuntimeFactory;
import org.apache.pulsar.functions.runtime.RuntimeSpawner;
import org.apache.pulsar.functions.runtime.ThreadRuntimeFactory;
import org.apache.pulsar.functions.secretsprovider.ClearTextSecretsProvider;
import org.apache.pulsar.functions.secretsproviderconfigurator.DefaultSecretsProviderConfigurator;
import org.apache.pulsar.functions.secretsproviderconfigurator.SecretsProviderConfigurator;
import org.apache.pulsar.functions.utils.Reflections;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * This class managers all aspects of functions assignments and running of function assignments for this worker
 */
@Slf4j
public class FunctionRuntimeManager implements AutoCloseable{

    // all assignments
    // WorkerId -> Function Fully Qualified InstanceId -> List<Assignments>
    @VisibleForTesting
    Map<String, Map<String, Assignment>> workerIdToAssignments = new ConcurrentHashMap<>();

    // All the runtime info related to functions executed by this worker
    // Fully Qualified InstanceId - > FunctionRuntimeInfo
    @VisibleForTesting
    Map<String, FunctionRuntimeInfo> functionRuntimeInfoMap = new ConcurrentHashMap<>();

    @VisibleForTesting
    @Getter
    final WorkerConfig workerConfig;

    private FunctionAssignmentTailer functionAssignmentTailer;

    @Setter
    @Getter
    private FunctionActioner functionActioner;

    @Getter
    private RuntimeFactory runtimeFactory;

    private MembershipManager membershipManager;

    private final PulsarAdmin functionAdmin;

    @Getter
    private WorkerService workerService;

    @Setter
    @Getter
    boolean isInitializePhase = false;

    private final FunctionMetaDataManager functionMetaDataManager;

    public FunctionRuntimeManager(WorkerConfig workerConfig, WorkerService workerService, Namespace dlogNamespace,
                                  MembershipManager membershipManager, ConnectorsManager connectorsManager,
                                  FunctionMetaDataManager functionMetaDataManager) throws Exception {
        this.workerConfig = workerConfig;
        this.workerService = workerService;
        this.functionAdmin = workerService.getFunctionAdmin();

        SecretsProviderConfigurator secretsProviderConfigurator;
        if (!StringUtils.isEmpty(workerConfig.getSecretsProviderConfiguratorClassName())) {
            secretsProviderConfigurator = (SecretsProviderConfigurator) Reflections.createInstance(workerConfig.getSecretsProviderConfiguratorClassName(), ClassLoader.getSystemClassLoader());
        } else {
            secretsProviderConfigurator = new DefaultSecretsProviderConfigurator();
        }
        secretsProviderConfigurator.init(workerConfig.getSecretsProviderConfiguratorConfig());

        AuthenticationConfig authConfig = AuthenticationConfig.builder()
                .clientAuthenticationPlugin(workerConfig.getClientAuthenticationPlugin())
                .clientAuthenticationParameters(workerConfig.getClientAuthenticationParameters())
                .tlsTrustCertsFilePath(workerConfig.getTlsTrustCertsFilePath())
                .useTls(workerConfig.isUseTls()).tlsAllowInsecureConnection(workerConfig.isTlsAllowInsecureConnection())
                .tlsHostnameVerificationEnable(workerConfig.isTlsHostnameVerificationEnable()).build();

        if (workerConfig.getThreadContainerFactory() != null) {
            this.runtimeFactory = new ThreadRuntimeFactory(
                    workerConfig.getThreadContainerFactory().getThreadGroupName(),
                    workerConfig.getPulsarServiceUrl(),
                    workerConfig.getStateStorageServiceUrl(),
                    authConfig,
                    new ClearTextSecretsProvider(),
                     null);
        } else if (workerConfig.getProcessContainerFactory() != null) {
            this.runtimeFactory = new ProcessRuntimeFactory(
                    workerConfig.getPulsarServiceUrl(),
                    workerConfig.getStateStorageServiceUrl(),
                    authConfig,
                    workerConfig.getProcessContainerFactory().getJavaInstanceJarLocation(),
                    workerConfig.getProcessContainerFactory().getPythonInstanceLocation(),
                    workerConfig.getProcessContainerFactory().getLogDirectory(),
                    workerConfig.getProcessContainerFactory().getExtraFunctionDependenciesDir(),
                    secretsProviderConfigurator);
        } else if (workerConfig.getKubernetesContainerFactory() != null){
            this.runtimeFactory = new KubernetesRuntimeFactory(
                    workerConfig.getKubernetesContainerFactory().getK8Uri(),
                    workerConfig.getKubernetesContainerFactory().getJobNamespace(),
                    workerConfig.getKubernetesContainerFactory().getPulsarDockerImageName(),
                    workerConfig.getKubernetesContainerFactory().getImagePullPolicy(),
                    workerConfig.getKubernetesContainerFactory().getPulsarRootDir(),
                    workerConfig.getKubernetesContainerFactory().getSubmittingInsidePod(),
                    workerConfig.getKubernetesContainerFactory().getInstallUserCodeDependencies(),
                    workerConfig.getKubernetesContainerFactory().getPythonDependencyRepository(),
                    workerConfig.getKubernetesContainerFactory().getPythonExtraDependencyRepository(),
                    workerConfig.getKubernetesContainerFactory().getExtraFunctionDependenciesDir(),
                    workerConfig.getKubernetesContainerFactory().getCustomLabels(),
                    workerConfig.getKubernetesContainerFactory().getPercentMemoryPadding(),
                    StringUtils.isEmpty(workerConfig.getKubernetesContainerFactory().getPulsarServiceUrl()) ? workerConfig.getPulsarServiceUrl() : workerConfig.getKubernetesContainerFactory().getPulsarServiceUrl(),
                    StringUtils.isEmpty(workerConfig.getKubernetesContainerFactory().getPulsarAdminUrl()) ? workerConfig.getPulsarWebServiceUrl() : workerConfig.getKubernetesContainerFactory().getPulsarAdminUrl(),
                    workerConfig.getStateStorageServiceUrl(),
                    authConfig,
                    workerConfig.getKubernetesContainerFactory().getExpectedMetricsCollectionInterval() == null ? -1 : workerConfig.getKubernetesContainerFactory().getExpectedMetricsCollectionInterval(),
                    workerConfig.getKubernetesContainerFactory().getChangeConfigMap(),
                    workerConfig.getKubernetesContainerFactory().getChangeConfigMapNamespace(),
                    workerConfig.getFunctionInstanceMinResources(),
                    secretsProviderConfigurator);
        } else {
            throw new RuntimeException("Either Thread, Process or Kubernetes Container Factory need to be set");
        }

        this.functionActioner = new FunctionActioner(this.workerConfig, runtimeFactory,
                dlogNamespace, connectorsManager, workerService.getBrokerAdmin());

        this.membershipManager = membershipManager;
        this.functionMetaDataManager = functionMetaDataManager;
    }

    /**
     * Initializes the FunctionRuntimeManager.  Does the following:
     * 1. Consume all existing assignments to establish existing/latest set of assignments
     * 2. After current assignments are read, assignments belonging to this worker will be processed
     */
    public void initialize() {
        log.info("/** Initializing Runtime Manager **/");
        try {
            Reader<byte[]> reader = this.getWorkerService().getClient().newReader()
                    .topic(this.getWorkerConfig().getFunctionAssignmentTopic()).readCompacted(true)
                    .startMessageId(MessageId.earliest).create();

            this.functionAssignmentTailer = new FunctionAssignmentTailer(this, reader);
            // read all existing messages
            this.setInitializePhase(true);
            while (reader.hasMessageAvailable()) {
                this.functionAssignmentTailer.processAssignment(reader.readNext());
            }
            this.setInitializePhase(false);
            // realize existing assignments
            Map<String, Assignment> assignmentMap = workerIdToAssignments.get(this.workerConfig.getWorkerId());
            if (assignmentMap != null) {
                for (Assignment assignment : assignmentMap.values()) {
                    if (needsStart(assignment)) {
                        startFunctionInstance(assignment);
                    }
                }
            }
            // start assignment tailer
            this.functionAssignmentTailer.start();

        } catch (Exception e) {
            log.error("Failed to initialize function runtime manager: ", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Starts the function runtime manager
     */
    public void start() {
        log.info("/** Starting Function Runtime Manager **/");
        log.info("Initialize metrics sink...");
        log.info("Starting function assignment tailer...");
        this.functionAssignmentTailer.start();
    }

    /**
     * Public methods
     */

    /**
     * Get current assignments
     * @return a map of current assignments in the follwing format
     * {workerId : {FullyQualifiedInstanceId : Assignment}}
     */
    public synchronized Map<String, Map<String, Assignment>> getCurrentAssignments() {
        Map<String, Map<String, Assignment>> copy = new HashMap<>();
        for (Map.Entry<String, Map<String, Assignment>> entry : this.workerIdToAssignments.entrySet()) {
            Map<String, Assignment> tmp = new HashMap<>();
            tmp.putAll(entry.getValue());
            copy.put(entry.getKey(), tmp);
        }
        return copy;
    }

    /**
     * Find a assignment of a function
     * @param tenant the tenant the function belongs to
     * @param namespace the namespace the function belongs to
     * @param functionName the function name
     * @return the assignment of the function
     */
    public synchronized Assignment findFunctionAssignment(String tenant, String namespace,
                                                          String functionName, int instanceId) {
        return this.findAssignment(tenant, namespace, functionName, instanceId);
    }

    /**
     * Find all instance assignments of function
     * @param tenant
     * @param namespace
     * @param functionName
     * @return
     */
    public synchronized Collection<Assignment> findFunctionAssignments(String tenant,
                                                                       String namespace, String functionName) {
        return findFunctionAssignments(tenant, namespace, functionName, this.workerIdToAssignments);
    }

    public static Collection<Assignment> findFunctionAssignments(String tenant,
                                                                 String namespace, String functionName,
                                                                 Map<String, Map<String, Assignment>> workerIdToAssignments) {

        Collection<Assignment> assignments = new LinkedList<>();

        for (Map<String, Assignment> entryMap : workerIdToAssignments.values()) {
            assignments.addAll(entryMap.values().stream()
                    .filter(
                            assignment ->
                                    (tenant.equals(assignment.getInstance()
                                            .getFunctionMetaData().getFunctionDetails()
                                            .getTenant())
                                            && namespace.equals((assignment.getInstance()
                                            .getFunctionMetaData().getFunctionDetails()
                                            .getNamespace()))
                                            && functionName.equals(assignment.getInstance()
                                            .getFunctionMetaData().getFunctionDetails()
                                            .getName())))
                    .collect(Collectors.toList()));
        }

        return assignments;
    }

    /**
     * Removes a collection of assignments
     * @param assignments assignments to remove
     */
    public synchronized void removeAssignments(Collection<Assignment> assignments) {
        for (Assignment assignment : assignments) {
            this.deleteAssignment(assignment);
        }
    }

    public void restartFunctionInstance(String tenant, String namespace, String functionName, int instanceId,
            URI uri) throws Exception {
        if (runtimeFactory.externallyManaged()) {
            throw new WebApplicationException(Response.serverError().status(Status.NOT_IMPLEMENTED)
                    .type(MediaType.APPLICATION_JSON)
                    .entity(new ErrorData("Externally managed schedulers can't do per instance stop")).build());
        }
        Assignment assignment = this.findAssignment(tenant, namespace, functionName, instanceId);
        final String fullFunctionName = String.format("%s/%s/%s/%s", tenant, namespace, functionName, instanceId);
        if (assignment == null) {
            throw new WebApplicationException(Response.serverError().status(Status.BAD_REQUEST)
                    .type(MediaType.APPLICATION_JSON)
                    .entity(new ErrorData(fullFunctionName + " doesn't exist")).build());
        }

        final String assignedWorkerId = assignment.getWorkerId();
        final String workerId = this.workerConfig.getWorkerId();

        if (assignedWorkerId.equals(workerId)) {
            stopFunction(org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(assignment.getInstance()), true);
            return;
        } else {
            // query other worker
            List<WorkerInfo> workerInfoList = this.membershipManager.getCurrentMembership();
            WorkerInfo workerInfo = null;
            for (WorkerInfo entry : workerInfoList) {
                if (assignment.getWorkerId().equals(entry.getWorkerId())) {
                    workerInfo = entry;
                }
            }
            if (workerInfo == null) {
                throw new WebApplicationException(Response.serverError().status(Status.BAD_REQUEST)
                        .type(MediaType.APPLICATION_JSON)
                        .entity(new ErrorData(fullFunctionName + " has not been assigned yet")).build());
            }

            if (uri == null) {
                throw new WebApplicationException(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
            } else {
                URI redirect = UriBuilder.fromUri(uri).host(workerInfo.getWorkerHostname()).port(workerInfo.getPort()).build();
                throw new WebApplicationException(Response.temporaryRedirect(redirect).build());
            }
        }
    }

    public void restartFunctionInstances(String tenant, String namespace, String functionName)
            throws Exception {
        final String fullFunctionName = String.format("%s/%s/%s", tenant, namespace, functionName);
        Collection<Assignment> assignments = this.findFunctionAssignments(tenant, namespace, functionName);

        if (assignments.isEmpty()) {
            throw new WebApplicationException(Response.serverError().status(Status.BAD_REQUEST)
                    .type(MediaType.APPLICATION_JSON)
                    .entity(new ErrorData(fullFunctionName + " has not been assigned yet")).build());
        }
        if (runtimeFactory.externallyManaged()) {
            Assignment assignment = assignments.iterator().next();
            final String assignedWorkerId = assignment.getWorkerId();
            final String workerId = this.workerConfig.getWorkerId();
            String fullyQualifiedInstanceId = org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(assignment.getInstance());
            if (assignedWorkerId.equals(workerId)) {
                stopFunction(fullyQualifiedInstanceId, true);
            } else {
                List<WorkerInfo> workerInfoList = this.membershipManager.getCurrentMembership();
                WorkerInfo workerInfo = null;
                for (WorkerInfo entry : workerInfoList) {
                    if (assignment.getWorkerId().equals(entry.getWorkerId())) {
                        workerInfo = entry;
                    }
                }
                if (workerInfo == null) {
                    if (log.isDebugEnabled()) {
                        log.debug("[{}] has not been assigned yet", fullyQualifiedInstanceId);
                    }
                    throw new WebApplicationException(Response.serverError().status(Status.BAD_REQUEST)
                            .type(MediaType.APPLICATION_JSON)
                            .entity(new ErrorData(fullFunctionName + " has not been assigned yet")).build());
                }
                this.functionAdmin.functions().restartFunction(tenant, namespace, functionName);
            }
        } else {
            for (Assignment assignment : assignments) {
                final String assignedWorkerId = assignment.getWorkerId();
                final String workerId = this.workerConfig.getWorkerId();
                String fullyQualifiedInstanceId = org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(assignment.getInstance());
                if (assignedWorkerId.equals(workerId)) {
                    stopFunction(fullyQualifiedInstanceId, true);
                } else {
                    List<WorkerInfo> workerInfoList = this.membershipManager.getCurrentMembership();
                    WorkerInfo workerInfo = null;
                    for (WorkerInfo entry : workerInfoList) {
                        if (assignment.getWorkerId().equals(entry.getWorkerId())) {
                            workerInfo = entry;
                        }
                    }
                    if (workerInfo == null) {
                        if (log.isDebugEnabled()) {
                            log.debug("[{}] has not been assigned yet", fullyQualifiedInstanceId);
                        }
                        continue;
                    }
                    this.functionAdmin.functions().restartFunction(tenant, namespace, functionName,
                                assignment.getInstance().getInstanceId());
                }
            }
        }
        return;
    }

    /**
     * It stops all functions instances owned by current worker
     * @throws Exception
     */
    public void stopAllOwnedFunctions() {
        if (runtimeFactory.externallyManaged()) {
            log.warn("Will not stop any functions since they are externally managed");
            return;
        }
        final String workerId = this.workerConfig.getWorkerId();
        Map<String, Assignment> assignments = workerIdToAssignments.get(workerId);
        if (assignments != null) {
            assignments.values().forEach(assignment -> {
                String fullyQualifiedInstanceId = org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(assignment.getInstance());
                try {
                    stopFunction(fullyQualifiedInstanceId, false);
                } catch (Exception e) {
                    log.warn("Failed to stop function {} - {}", fullyQualifiedInstanceId, e.getMessage());
                }
            });
        }
    }

    private void stopFunction(String fullyQualifiedInstanceId, boolean restart) throws Exception {
        log.info("[{}] {}..", restart ? "restarting" : "stopping", fullyQualifiedInstanceId);
        FunctionRuntimeInfo functionRuntimeInfo = this.getFunctionRuntimeInfo(fullyQualifiedInstanceId);
        if (functionRuntimeInfo != null) {
            this.conditionallyStopFunction(functionRuntimeInfo);
            try {
                if(restart) {
                    this.conditionallyStartFunction(functionRuntimeInfo);
                }
            } catch (Exception ex) {
                log.info("{} Error re-starting function", fullyQualifiedInstanceId, ex);
                functionRuntimeInfo.setStartupException(ex);
                throw ex;
            }
        }
    }

    /**
     * Get stats of a function instance.  If this worker is not running the function instance,
     * @param tenant the tenant the function belongs to
     * @param namespace the namespace the function belongs to
     * @param functionName the function name
     * @param instanceId the function instance id
     * @return jsonObject containing stats for instance
     */
    public FunctionStats.FunctionInstanceStats.FunctionInstanceStatsData getFunctionInstanceStats(String tenant, String namespace,
                                                                        String functionName, int instanceId, URI uri) {
        Assignment assignment;
        if (runtimeFactory.externallyManaged()) {
            assignment = this.findAssignment(tenant, namespace, functionName, -1);
        } else {
            assignment = this.findAssignment(tenant, namespace, functionName, instanceId);
        }

        if (assignment == null) {
            return new FunctionStats.FunctionInstanceStats.FunctionInstanceStatsData();
        }

        final String assignedWorkerId = assignment.getWorkerId();
        final String workerId = this.workerConfig.getWorkerId();

        // If I am running worker
        if (assignedWorkerId.equals(workerId)) {
            FunctionRuntimeInfo functionRuntimeInfo = this.getFunctionRuntimeInfo(
                    org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(assignment.getInstance()));
            RuntimeSpawner runtimeSpawner = functionRuntimeInfo.getRuntimeSpawner();
            if (runtimeSpawner != null) {
                return Utils.getFunctionInstanceStats(org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(assignment.getInstance()), functionRuntimeInfo, instanceId).getMetrics();
            }
            return new FunctionStats.FunctionInstanceStats.FunctionInstanceStatsData();
        } else {
            // query other worker

            List<WorkerInfo> workerInfoList = this.membershipManager.getCurrentMembership();
            WorkerInfo workerInfo = null;
            for (WorkerInfo entry: workerInfoList) {
                if (assignment.getWorkerId().equals(entry.getWorkerId())) {
                    workerInfo = entry;
                }
            }
            if (workerInfo == null) {
                return new FunctionStats.FunctionInstanceStats.FunctionInstanceStatsData();
            }

            if (uri == null) {
                throw new WebApplicationException(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
            } else {
                URI redirect = UriBuilder.fromUri(uri).host(workerInfo.getWorkerHostname()).port(workerInfo.getPort()).build();
                throw new WebApplicationException(Response.temporaryRedirect(redirect).build());
            }
        }
    }

    /**
     * Get stats of all function instances.
     * @param tenant the tenant the function belongs to
     * @param namespace the namespace the function belongs to
     * @param functionName the function name
     * @return a list of function statuses
     * @throws PulsarAdminException
     */
    public FunctionStats getFunctionStats(String tenant, String namespace, String functionName, URI uri) throws PulsarAdminException {
        Collection<Assignment> assignments = this.findFunctionAssignments(tenant, namespace, functionName);

        FunctionStats functionStats = new FunctionStats();
        if (assignments.isEmpty()) {
            return functionStats;
        }

        if (runtimeFactory.externallyManaged()) {
            Assignment assignment = assignments.iterator().next();
            boolean isOwner = this.workerConfig.getWorkerId().equals(assignment.getWorkerId());
            if (isOwner) {
                int parallelism = assignment.getInstance().getFunctionMetaData().getFunctionDetails().getParallelism();
                for (int i = 0; i < parallelism; ++i) {

                    FunctionStats.FunctionInstanceStats.FunctionInstanceStatsData functionInstanceStatsData = getFunctionInstanceStats(tenant, namespace,
                            functionName, i, null);

                    FunctionStats.FunctionInstanceStats functionInstanceStats = new FunctionStats.FunctionInstanceStats();
                    functionInstanceStats.setInstanceId(i);
                    functionInstanceStats.setMetrics(functionInstanceStatsData);
                    functionStats.addInstance(functionInstanceStats);
                }
            } else {
                // find the hostname/port of the worker who is the owner

                List<WorkerInfo> workerInfoList = this.membershipManager.getCurrentMembership();
                WorkerInfo workerInfo = null;
                for (WorkerInfo entry: workerInfoList) {
                    if (assignment.getWorkerId().equals(entry.getWorkerId())) {
                        workerInfo = entry;
                    }
                }
                if (workerInfo == null) {
                    return functionStats;
                }

                if (uri == null) {
                    throw new WebApplicationException(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
                } else {
                    URI redirect = UriBuilder.fromUri(uri).host(workerInfo.getWorkerHostname()).port(workerInfo.getPort()).build();
                    throw new WebApplicationException(Response.temporaryRedirect(redirect).build());
                }
            }
        } else {
            for (Assignment assignment : assignments) {
                boolean isOwner = this.workerConfig.getWorkerId().equals(assignment.getWorkerId());

                FunctionStats.FunctionInstanceStats.FunctionInstanceStatsData functionInstanceStatsData;
                if (isOwner) {
                    functionInstanceStatsData = getFunctionInstanceStats(tenant, namespace, functionName,
                            assignment.getInstance().getInstanceId(), null);
                } else {
                    functionInstanceStatsData = this.functionAdmin.functions().getFunctionStats(
                            assignment.getInstance().getFunctionMetaData().getFunctionDetails().getTenant(),
                            assignment.getInstance().getFunctionMetaData().getFunctionDetails().getNamespace(),
                            assignment.getInstance().getFunctionMetaData().getFunctionDetails().getName(),
                            assignment.getInstance().getInstanceId());
                }

                FunctionStats.FunctionInstanceStats functionInstanceStats = new FunctionStats.FunctionInstanceStats();
                functionInstanceStats.setInstanceId(assignment.getInstance().getInstanceId());
                functionInstanceStats.setMetrics(functionInstanceStatsData);
                functionStats.addInstance(functionInstanceStats);
            }
        }
        return functionStats.calculateOverall();
    }

    /**
     * Process an assignment update from the assignment topic
     * @param newAssignment the assignment
     */
    public synchronized void processAssignment(Assignment newAssignment) {

        Map<String, Assignment> existingAssignmentMap = new HashMap<>();
        for (Map<String, Assignment> entry : this.workerIdToAssignments.values()) {
            existingAssignmentMap.putAll(entry);
        }

        if (existingAssignmentMap.containsKey(org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(newAssignment.getInstance()))) {
            updateAssignment(newAssignment);
        } else {
            addAssignment(newAssignment);
        }
    }

    private void updateAssignment(Assignment assignment) {
        String fullyQualifiedInstanceId = org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(assignment.getInstance());
        Assignment existingAssignment = this.findAssignment(assignment);
        // potential updates need to happen

        if (!existingAssignment.equals(assignment)) {
            FunctionRuntimeInfo functionRuntimeInfo = _getFunctionRuntimeInfo(fullyQualifiedInstanceId);

            // for externally managed functions we don't really care about which worker the function instance is assigned to
            // and we don't really need to stop and start the function instance because the worker its assigned to changed
            // we just need to update the locally cached assignment info.  We only need to stop and start when there are
            // changes to the function meta data of the instance

            if (runtimeFactory.externallyManaged()) {

                // change in metadata thus need to potentially restart
                if (!assignment.getInstance().equals(existingAssignment.getInstance())) {
                    //stop function
                    if (functionRuntimeInfo != null) {
                        this.conditionallyStopFunction(functionRuntimeInfo);
                    }
                    // still assigned to me, need to restart
                    if (assignment.getWorkerId().equals(this.workerConfig.getWorkerId())) {
                        if (needsStart(assignment)) {
                            //start again
                            FunctionRuntimeInfo newFunctionRuntimeInfo = new FunctionRuntimeInfo();
                            newFunctionRuntimeInfo.setFunctionInstance(assignment.getInstance());

                            this.conditionallyStartFunction(newFunctionRuntimeInfo);
                            this.functionRuntimeInfoMap.put(fullyQualifiedInstanceId, newFunctionRuntimeInfo);
                        }
                    } else {
                        this.functionRuntimeInfoMap.remove(fullyQualifiedInstanceId);
                    }
                } else {
                    // if assignment got transferred to me just set function runtime
                    if (assignment.getWorkerId().equals(this.workerConfig.getWorkerId())) {
                        FunctionRuntimeInfo newFunctionRuntimeInfo = new FunctionRuntimeInfo();
                        newFunctionRuntimeInfo.setFunctionInstance(assignment.getInstance());
                        RuntimeSpawner runtimeSpawner = functionActioner.getRuntimeSpawner(
                                assignment.getInstance(),
                                assignment.getInstance().getFunctionMetaData().getPackageLocation().getPackagePath());
                        newFunctionRuntimeInfo.setRuntimeSpawner(runtimeSpawner);

                        this.functionRuntimeInfoMap.put(fullyQualifiedInstanceId, newFunctionRuntimeInfo);
                    } else {
                        this.functionRuntimeInfoMap.remove(fullyQualifiedInstanceId);
                    }
                }
            } else {
                //stop function
                if (functionRuntimeInfo != null) {
                    this.conditionallyStopFunction(functionRuntimeInfo);
                }
                // still assigned to me, need to restart
                if (assignment.getWorkerId().equals(this.workerConfig.getWorkerId())) {
                    if (needsStart(assignment)) {
                        //start again
                        FunctionRuntimeInfo newFunctionRuntimeInfo = new FunctionRuntimeInfo();
                        newFunctionRuntimeInfo.setFunctionInstance(assignment.getInstance());
                        this.conditionallyStartFunction(newFunctionRuntimeInfo);
                        this.functionRuntimeInfoMap.put(fullyQualifiedInstanceId, newFunctionRuntimeInfo);
                    }
                } else {
                    this.functionRuntimeInfoMap.remove(fullyQualifiedInstanceId);
                }
            }

            // find existing assignment
            Assignment existing_assignment = this.findAssignment(assignment);
            if (existing_assignment != null) {
                // delete old assignment that could have old data
                this.deleteAssignment(existing_assignment);
            }
            // set to newest assignment
            this.setAssignment(assignment);
        }
    }

    public synchronized void deleteAssignment(String fullyQualifiedInstanceId) {
        FunctionRuntimeInfo functionRuntimeInfo = _getFunctionRuntimeInfo(fullyQualifiedInstanceId);
        if (functionRuntimeInfo != null) {
            Function.FunctionDetails functionDetails = functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().getFunctionDetails();

            // check if this is part of a function delete operation or update operation
            // TODO could be a race condition here if functionMetaDataTailer somehow does not receive the functionMeta prior to the functionAssignmentsTailer gets the assignment for the function.
            if (this.functionMetaDataManager.containsFunction(functionDetails.getTenant(), functionDetails.getNamespace(), functionDetails.getName())) {
                // function still exists thus probably an update or stop operation
                this.conditionallyStopFunction(functionRuntimeInfo);
            } else {
                // function doesn't exist anymore thus we should terminate
                this.conditionallyTerminateFunction(functionRuntimeInfo);
            }
            this.functionRuntimeInfoMap.remove(fullyQualifiedInstanceId);
        }

        String workerId = null;
        for(Entry<String, Map<String, Assignment>> workerAssignments : workerIdToAssignments.entrySet()) {
            if(workerAssignments.getValue().remove(fullyQualifiedInstanceId)!=null) {
                workerId = workerAssignments.getKey();
                break;
            }
        }
        Map<String, Assignment> worker;
        if (workerId != null && ((worker = workerIdToAssignments.get(workerId)) != null && worker.isEmpty())) {
            this.workerIdToAssignments.remove(workerId);
        }
    }

    @VisibleForTesting
    void deleteAssignment(Assignment assignment) {
        String fullyQualifiedInstanceId = org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(assignment.getInstance());
        Map<String, Assignment> assignmentMap = this.workerIdToAssignments.get(assignment.getWorkerId());
        if (assignmentMap != null) {
            if (assignmentMap.containsKey(fullyQualifiedInstanceId)) {
                assignmentMap.remove(fullyQualifiedInstanceId);
            }
            if (assignmentMap.isEmpty()) {
                this.workerIdToAssignments.remove(assignment.getWorkerId());
            }
        }
    }

    private void addAssignment(Assignment assignment) {
        //add new function
        this.setAssignment(assignment);

        //Assigned to me
        if (assignment.getWorkerId().equals(workerConfig.getWorkerId()) && needsStart(assignment)) {
            startFunctionInstance(assignment);
        }
    }

    private void startFunctionInstance(Assignment assignment) {
        String fullyQualifiedInstanceId = org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(assignment.getInstance());
        FunctionRuntimeInfo functionRuntimeInfo = _getFunctionRuntimeInfo(fullyQualifiedInstanceId);

        if (functionRuntimeInfo == null) {
            functionRuntimeInfo = new FunctionRuntimeInfo()
                    .setFunctionInstance(assignment.getInstance());
            this.functionRuntimeInfoMap.put(fullyQualifiedInstanceId, functionRuntimeInfo);
        } else {
            //Somehow this function is already started
            log.warn("Function {} already running. Going to restart function.",
                    functionRuntimeInfo);
            this.conditionallyStopFunction(functionRuntimeInfo);
        }
        this.conditionallyStartFunction(functionRuntimeInfo);
    }

    public Map<String, FunctionRuntimeInfo> getFunctionRuntimeInfos() {
        return this.functionRuntimeInfoMap;
    }

    /**
     * Private methods for internal use.  Should not be used outside of this class
     */
    private Assignment findAssignment(String tenant, String namespace, String functionName, int instanceId) {
        String fullyQualifiedInstanceId
                = org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(tenant, namespace, functionName, instanceId);
        for (Map.Entry<String, Map<String, Assignment>> entry : this.workerIdToAssignments.entrySet()) {
            Map<String, Assignment> assignmentMap = entry.getValue();
            Assignment existingAssignment = assignmentMap.get(fullyQualifiedInstanceId);
            if (existingAssignment != null) {
                return existingAssignment;
            }
        }
        return null;
    }

    private Assignment findAssignment(Assignment assignment) {
        return findAssignment(
                assignment.getInstance().getFunctionMetaData().getFunctionDetails().getTenant(),
                assignment.getInstance().getFunctionMetaData().getFunctionDetails().getNamespace(),
                assignment.getInstance().getFunctionMetaData().getFunctionDetails().getName(),
                assignment.getInstance().getInstanceId()
        );
    }

    @VisibleForTesting
    void setAssignment(Assignment assignment) {
        if (!this.workerIdToAssignments.containsKey(assignment.getWorkerId())) {
            this.workerIdToAssignments.put(assignment.getWorkerId(), new HashMap<>());
        }
        this.workerIdToAssignments.get(assignment.getWorkerId()).put(
                org.apache.pulsar.functions.utils.Utils.getFullyQualifiedInstanceId(assignment.getInstance()),
                assignment);
    }

    @Override
    public void close() throws Exception {
        this.functionAssignmentTailer.close();

        stopAllOwnedFunctions();

        if (runtimeFactory != null) {
            runtimeFactory.close();
        }
    }

    public synchronized FunctionRuntimeInfo getFunctionRuntimeInfo(String fullyQualifiedInstanceId) {
        return _getFunctionRuntimeInfo(fullyQualifiedInstanceId);
    }

    private FunctionRuntimeInfo _getFunctionRuntimeInfo(String fullyQualifiedInstanceId) {
        FunctionRuntimeInfo functionRuntimeInfo = this.functionRuntimeInfoMap.get(fullyQualifiedInstanceId);

        // sanity check to make sure assignments and runtimeinfo is in sync
        if (functionRuntimeInfo == null) {
            if (this.workerIdToAssignments.containsValue(workerConfig.getWorkerId())
                    && this.workerIdToAssignments.get(workerConfig.getWorkerId()).containsValue(fullyQualifiedInstanceId)) {
                log.error("Assignments and RuntimeInfos are inconsistent. FunctionRuntimeInfo missing for " + fullyQualifiedInstanceId);
            }
        }
        return functionRuntimeInfo;
    }

    private boolean needsStart(Assignment assignment) {
        boolean toStart = false;
        Function.FunctionMetaData functionMetaData = assignment.getInstance().getFunctionMetaData();
        if (functionMetaData.getInstanceStatesMap() == null || functionMetaData.getInstanceStatesMap().isEmpty()) {
            toStart = true;
        } else {
            if (assignment.getInstance().getInstanceId() < 0) {
                // for externally managed functions, insert the start only if there is atleast one
                // instance that needs to be started
                for (Function.FunctionState state : functionMetaData.getInstanceStatesMap().values()) {
                    if (state == Function.FunctionState.RUNNING) {
                        toStart = true;
                    }
                }
            } else {
                if (functionMetaData.getInstanceStatesOrDefault(assignment.getInstance().getInstanceId(), Function.FunctionState.RUNNING) == Function.FunctionState.RUNNING) {
                    toStart = true;
                }
            }
        }
        return toStart;
    }

    private void conditionallyStartFunction(FunctionRuntimeInfo functionRuntimeInfo) {
        if (!this.isInitializePhase) {
            this.functionActioner.startFunction(functionRuntimeInfo);
        }
    }

    private void conditionallyStopFunction(FunctionRuntimeInfo functionRuntimeInfo) {
        if (!this.isInitializePhase) {
            this.functionActioner.stopFunction(functionRuntimeInfo);
        }
    }

    private void conditionallyTerminateFunction(FunctionRuntimeInfo functionRuntimeInfo) {
        if (!this.isInitializePhase) {
            this.functionActioner.terminateFunction(functionRuntimeInfo);
        }
    }
}


text:
// This file is automatically generated.

package adila.db;

/*
 * LG
 *
 * DEVICE: bproj_222-88
 * MODEL: LG-P970
 */
final class bproj5f2222d88 {
    public static final String DATA = "LG||";
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GoPro.Hero.Commands;
using GoPro.Hero.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace GoPro.Hero.Browser.Media
{
    public class GoProMediaBrowser:MediaBrowser
    {
        static GoProMediaBrowser()
        {
#if WINDOWS
            WindowsSpecific.UseUnsafeHeaderParsing();
#endif
        }

        public override async Task<IEnumerable<IMedia>> ContentsAsync()
        {
            var response = await Camera.PrepareCommand<CommandGoProMediaList>(8080).SendAsync(checkStatus:false);
            var jsonStream = response.GetResponseStream();

            return Parse(jsonStream);
        }

        protected virtual IEnumerable<IMedia> Parse(Stream jsonStream)
        {
            using (var jsonReader = new JsonTextReader(new StreamReader(jsonStream)))
            {
                var mediaList = JObject.Load(jsonReader);

                Id = mediaList["id"].Value<string>();

                var media = mediaList["media"].ElementAt(0);

                Destination = media["d"].Value<string>();

                var fs = media["fs"].Select<JToken,IMedia>(j =>
                {
                    if (j["ls"] != null)//unique to video media
                        return MediaBuilder<VideoParameters>.Create<Video>(VideoParameters(j), this);

                    if (j["b"] != null)//unique to burst mode
                        return MediaBuilder<TimeLapsedImageParameters>.Create<TimeLapsedImage>(TimeLapsedParameters(j), this);

                    if (j["n"] != null)
                        return MediaBuilder<ImageParameters>.Create<Image>(ImageParameters(j), this);

                    return null;
                }
                );

                return fs.ToList();
            }
        }

        private VideoParameters VideoParameters(JToken token)
        {
            var video = new VideoParameters
            {
                Name = token["n"].Value<string>(),
                Size = token["s"].Value<long>(),
                LowResolutionSize = token["ls"].Value<long>()
            };

            return video;
        }

        private ImageParameters ImageParameters(JToken token)
        {
            var image = new ImageParameters
            {
                Name = token["n"].Value<string>(),
                Size = token["s"].Value<long>()
            };

            return image;
        }

        private TimeLapsedImageParameters TimeLapsedParameters(JToken token)
        {
            var timeLapsed = new TimeLapsedImageParameters
            {
                Name = token["n"].Value<string>(),
                Size = token["s"].Value<long>(),
                Group = token["g"].Value<int>(),
                Start = token["b"].Value<int>(),
                End = token["l"].Value<int>()
            };

            return timeLapsed;
        }
    }
}


text:
package com.greghaskins.bankocr.ui;

import com.greghaskins.bankocr.control.AccountEntryLexer;
import com.greghaskins.bankocr.control.AccountEntryParser;
import com.greghaskins.bankocr.control.GlyphScanner;
import com.greghaskins.bankocr.model.ChecksumCalculator;

class ConsoleApplicationFactory implements ApplicationFactory {

    @Override
    public ConsoleApplication buildApplication() {
        final AccountEntryLexer lexer = new AccountEntryLexer(new GlyphScanner());
        final AccountEntryParser parser = new AccountEntryParser();
        final ChecksumCalculator checksumCalculator = new ChecksumCalculator();
        return new ConsoleApplication(lexer, parser, checksumCalculator);
    }

}


text:
package ca.gc.agr.mbb.hostpathogen.web.util;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.DecimalFormat;
import java.text.ParseException;

/**
 * This class is converts a Double to a double-digit String
 * (and vise-versa) by BeanUtils when copying properties.
 *
 * @author Matt Raible
 */
public class CurrencyConverter implements Converter {
    private final Log log = LogFactory.getLog(CurrencyConverter.class);
    private DecimalFormat formatter = new DecimalFormat("###,###.00");

    public void setDecimalFormatter(DecimalFormat df) {
        this.formatter = df;
    }

    /**
     * Convert a String to a Double and a Double to a String
     *
     * @param type the class type to output
     * @param value the object to convert
     * @return object the converted object (Double or String)
     */
    public final Object convert(final Class type, final Object value) {
        // for a null value, return null
        if (value == null) {
            return null;
        } else {
            if (value instanceof String) {
                if (log.isDebugEnabled()) {
                    log.debug("value (" + value + ") instance of String");
                }

                try {
                    if (StringUtils.isBlank(String.valueOf(value))) {
                        return null;
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("converting '" + value + "' to a decimal");
                    }

                    //formatter.setDecimalSeparatorAlwaysShown(true);
                    Number num = formatter.parse(String.valueOf(value));

                    return num.doubleValue();
                } catch (ParseException pe) {
                    pe.printStackTrace();
                }
            } else if (value instanceof Double) {
                if (log.isDebugEnabled()) {
                    log.debug("value (" + value + ") instance of Double");
                    log.debug("returning double: " + formatter.format(value));
                }

                return formatter.format(value);
            }
        }

        throw new ConversionException("Could not convert " + value + " to " + type.getName() + "!");
    }
}