text:
Inbox

        <input type="text" class="form-control input-sm" placeholder="Search Mail">

      <button type="button" class="btn btn-default btn-sm checkbox-toggle">
      </button>

        <button type="button" class="btn btn-default btn-sm"></button>
        <button type="button" class="btn btn-default btn-sm"></button>
        <button type="button" class="btn btn-default btn-sm"></button>

      <button type="button" class="btn btn-default btn-sm"></button>

        1-50/200

          <button type="button" class="btn btn-default btn-sm"></button>
          <button type="button" class="btn btn-default btn-sm"></button>

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          5 mins ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          28 mins ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          11 hours ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          15 hours ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          Yesterday

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          2 days ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          2 days ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          2 days ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          2 days ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          2 days ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          4 days ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          12 days ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          12 days ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          14 days ago

          <input type="checkbox">

          Alexander Pierce
          AdminLTE 2.0 Issue - Trying to find a solution to this problem...

          15 days ago

      <button type="button" class="btn btn-default btn-sm checkbox-toggle">
      </button>

        <button type="button" class="btn btn-default btn-sm"></button>
        <button type="button" class="btn btn-default btn-sm"></button>
        <button type="button" class="btn btn-default btn-sm"></button>

      <button type="button" class="btn btn-default btn-sm"></button>

        1-50/200

          <button type="button" class="btn btn-default btn-sm"></button>
          <button type="button" class="btn btn-default btn-sm"></button>


text:
package ca.paulshin.glass.bible.utils;

import android.util.Log;

/**
 * Simple debugging utils.
 */
public class DebugLog {
    private static final String DEFAULT_TAG = "log";
    private static long startTime;
    private static long previousTime;

    public static void d(Object text) {
        Log.d(DEFAULT_TAG, text.toString());
    }

    public static void e(Object text) {
        Log.e(DEFAULT_TAG, text.toString());
    }

    public static void i(Object text) {
        Log.i(DEFAULT_TAG, text.toString());
    }

    public static void t(String text) {
        if (startTime == 0) {
            startTime = System.currentTimeMillis();
            previousTime = startTime;
            d("------------------------------ starting time tracking: " + text);
        } else {
            long currentTime = System.currentTimeMillis();
            d(text + ": +" + (currentTime - previousTime) + " ms (total " + (currentTime - startTime) + " ms)");
            previousTime = currentTime;
        }
    }

    public static void w(Object text) {
        Log.w(DEFAULT_TAG, text.toString());
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <ngx_config.h>
#include <ngx_core.h>

u_char *
ngx_strerror(ngx_err_t err, u_char *errstr, size_t size)
{
    u_int          len;
    static u_long  lang = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);

    if (size == 0) {
        return errstr;
    }

    len = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                        NULL, err, lang, (char *) errstr, size, NULL);

    if (len == 0 && lang && GetLastError() == ERROR_RESOURCE_LANG_NOT_FOUND) {

        /*
         * Try to use English messages first and fallback to a language,
         * based on locale: non-English Windows have no English messages
         * at all.  This way allows to use English messages at least on
         * Windows with MUI.
         */

        lang = 0;

        len = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                            NULL, err, lang, (char *) errstr, size, NULL);
    }

    if (len == 0) {
        return ngx_snprintf(errstr, size,
                            "FormatMessage() error:(%d)", GetLastError());
    }

    /* remove ".\r\n\0" */
    while (errstr[len] == '\0' || errstr[len] == CR
           || errstr[len] == LF || errstr[len] == '.')
    {
        --len;
    }

    return &errstr[++len];
}

ngx_int_t
ngx_strerror_init(void)
{
    return NGX_OK;
}


text:
.class public final Landroid/media/TimedText$HyperText;
.super Ljava/lang/Object;
.source "TimedText.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/TimedText;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "HyperText"
.end annotation

# instance fields
.field public final URL:Ljava/lang/String;

.field public final altString:Ljava/lang/String;

.field public final endChar:I

.field public final startChar:I

# direct methods
.method public constructor <init>(IILjava/lang/String;Ljava/lang/String;)V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput p1, p0, Landroid/media/TimedText$HyperText;->startChar:I

    iput p2, p0, Landroid/media/TimedText$HyperText;->endChar:I

    iput-object p3, p0, Landroid/media/TimedText$HyperText;->URL:Ljava/lang/String;

    iput-object p4, p0, Landroid/media/TimedText$HyperText;->altString:Ljava/lang/String;

    return-void
.end method


text:
package org.apache.activemq.util;

import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.activemq.command.ActiveMQDestination;
import org.fusesource.hawtbuf.UTF8Buffer;

/**
 * Type conversion support for ActiveMQ.
 */
public final class TypeConversionSupport {

    private static final Converter IDENTITY_CONVERTER = new Converter() {
        @Override
        public Object convert(Object value) {
            return value;
        }
    };

    private static class ConversionKey {
        final Class<?> from;
        final Class<?> to;
        final int hashCode;

        public ConversionKey(Class<?> from, Class<?> to) {
            this.from = from;
            this.to = to;
            this.hashCode = from.hashCode() ^ (to.hashCode() << 1);
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            ConversionKey other = (ConversionKey) obj;
            if (from == null) {
                if (other.from != null)
                    return false;
            } else if (!from.equals(other.from))
                return false;
            if (to == null) {
                if (other.to != null)
                    return false;
            } else if (!to.equals(other.to))
                return false;
            return true;
        }

        @Override
        public int hashCode() {
            return hashCode;
        }
    }

    public interface Converter {
        Object convert(Object value);
    }

    private static final Map<ConversionKey, Converter> CONVERSION_MAP = new HashMap<ConversionKey, Converter>();
    static {
        Converter toStringConverter = new Converter() {
            @Override
            public Object convert(Object value) {
                return value.toString();
            }
        };
        CONVERSION_MAP.put(new ConversionKey(Boolean.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Byte.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Short.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Integer.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Long.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Float.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Double.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(UTF8Buffer.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(URI.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(BigInteger.class, String.class), toStringConverter);

        CONVERSION_MAP.put(new ConversionKey(String.class, Boolean.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return Boolean.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Byte.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return Byte.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Short.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return Short.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Integer.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return Integer.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Long.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return Long.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Float.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return Float.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Double.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return Double.valueOf((String)value);
            }
        });

        Converter longConverter = new Converter() {
            @Override
            public Object convert(Object value) {
                return Long.valueOf(((Number)value).longValue());
            }
        };
        CONVERSION_MAP.put(new ConversionKey(Byte.class, Long.class), longConverter);
        CONVERSION_MAP.put(new ConversionKey(Short.class, Long.class), longConverter);
        CONVERSION_MAP.put(new ConversionKey(Integer.class, Long.class), longConverter);
        CONVERSION_MAP.put(new ConversionKey(Date.class, Long.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return Long.valueOf(((Date)value).getTime());
            }
        });

        Converter intConverter = new Converter() {
            @Override
            public Object convert(Object value) {
                return Integer.valueOf(((Number)value).intValue());
            }
        };
        CONVERSION_MAP.put(new ConversionKey(Byte.class, Integer.class), intConverter);
        CONVERSION_MAP.put(new ConversionKey(Short.class, Integer.class), intConverter);

        CONVERSION_MAP.put(new ConversionKey(Byte.class, Short.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return Short.valueOf(((Number)value).shortValue());
            }
        });

        CONVERSION_MAP.put(new ConversionKey(Float.class, Double.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return new Double(((Number)value).doubleValue());
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, ActiveMQDestination.class), new Converter() {
            @Override
            public Object convert(Object value) {
                return ActiveMQDestination.createDestination((String)value, ActiveMQDestination.QUEUE_TYPE);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, URI.class), new Converter() {
            @Override
            public Object convert(Object value) {
                String text = value.toString();
                try {
                    return new URI(text);
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    private TypeConversionSupport() {
    }

    public static Object convert(Object value, Class<?> to) {
        if (value == null) {
            // lets avoid NullPointerException when converting to boolean for null values
            if (boolean.class.isAssignableFrom(to)) {
                return Boolean.FALSE;
            }
            return null;
        }

        // eager same instance type test to avoid the overhead of invoking the type converter
        // if already same type
        if (to.isInstance(value)) {
            return to.cast(value);
        }

        // lookup converter
        Converter c = lookupConverter(value.getClass(), to);
        if (c != null) {
            return c.convert(value);
        } else {
            return null;
        }
    }

    public static Converter lookupConverter(Class<?> from, Class<?> to) {
        // use wrapped type for primitives
        if (from.isPrimitive()) {
            from = convertPrimitiveTypeToWrapperType(from);
        }
        if (to.isPrimitive()) {
            to = convertPrimitiveTypeToWrapperType(to);
        }

        if (from.equals(to)) {
            return IDENTITY_CONVERTER;
        }

        return CONVERSION_MAP.get(new ConversionKey(from, to));
    }

    /**
     * Converts primitive types such as int to its wrapper type like
     * {@link Integer}
     */
    private static Class<?> convertPrimitiveTypeToWrapperType(Class<?> type) {
        Class<?> rc = type;
        if (type.isPrimitive()) {
            if (type == int.class) {
                rc = Integer.class;
            } else if (type == long.class) {
                rc = Long.class;
            } else if (type == double.class) {
                rc = Double.class;
            } else if (type == float.class) {
                rc = Float.class;
            } else if (type == short.class) {
                rc = Short.class;
            } else if (type == byte.class) {
                rc = Byte.class;
            } else if (type == boolean.class) {
                rc = Boolean.class;
            }
        }
        return rc;
    }
}


text:
import { SET_ERRORS_BY_COMPONENT } from 'actions/errors';
import { createActionHandlers } from 'utils/reducer/actions-handlers';

const actionHandlers = {};

export function setErrorsByComponent(state, { errors }) {}

actionHandlers[SET_ERRORS_BY_COMPONENT] = setErrorsByComponent;

export default createActionHandlers(actionHandlers);


text:
<?php

if (!@include __DIR__ . '/../../../vendor/autoload.php') {
    die("You must set up the project dependencies, run the following commands:
wget http://getcomposer.org/composer.phar
php composer.phar install
After that, a autoload.php file will be generated in the vendor directory. ");
}


text:
<?php

namespace Google\Service\ServiceNetworking;

class Control extends \Google\Model
{
  /**
   * @var string
   */
  public $environment;

  /**
   * @param string
   */
  public function setEnvironment($environment)
  {
    $this->environment = $environment;
  }
  /**
   * @return string
   */
  public function getEnvironment()
  {
    return $this->environment;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(Control::class, 'Google_Service_ServiceNetworking_Control');


text:
//@module

var PinsSimulators = require('PinsSimulators');
var gColor = { r : 1, g : 1, b : 1 }

var PWMLEDBehavior = Behavior.template({
	onCreate: function(column, data) {
		column.add(new spacer);
		column.add(new PWMLED(data));
		column.distribute("onChanged");
	},
})

var colorLEDTexture = new Texture('color-led.png', 1);
var colorLEDSkin = new Skin({ texture: colorLEDTexture, width: 150, height: 233, });
var redSkin = new Skin({ fill: 'red' });

var spacer = Container.template($ => ({ width: 150, height: 17 }));
var PWMLED = Container.template($ => ({
	width: 150, height: 233, skin: redSkin,
	contents: [
		Canvas($, {
			left: 0, right: 0, top: 0, bottom: 0,
			Behavior: class extends Behavior {
				onDisplaying(canvas) {
					this.draw(canvas);
				}
				draw(canvas) {
					var ctx = canvas.getContext("2d");
					ctx.beginPath();
					ctx.rect(0, 0, canvas.width, canvas.height);
					ctx.fillStyle = this.getColorString(canvas);
					ctx.fill();
				}
				getColorString(canvas) {
					var r = (1 - gColor.r), g = (1 - gColor.g), b = (1 - gColor.b);
					return "rgb(" + r + "," + g + "," + b + ")";
				}
			},
		}),
		Content($, { skin: colorLEDSkin, }),
	]
}));

exports.pins = {
	red: { type: "PWM", value: 1 },
	green: { type: "PWM", value: 1  },
	blue: { type: "PWM", value: 1  },
	anode: { type: "Digital", direction: "output", value: 1  }
};

var configure = exports.configure = function(configuration) {
	this.pinsSimulator = shell.delegate("addSimulatorPart", {
		behavior: PWMLEDBehavior,
		header : {
			label : "Tri Color LED",
			name : "PWM LED",
			iconVariant : PinsSimulators.SENSOR_LED
		}
	});
}

var close = exports.close = function() {
	shell.delegate("removeSimulatorPart", this.pinsSimulator);
}

var write = exports.write = function(parameters) {
	if ('red' in parameters)
		gColor.r = (1 - parameters.red);
	if ('green' in parameters)
		gColor.g = (1 - parameters.green);
	if ('blue' in parameters)
		gColor.b = (1 - parameters.blue);
	this.pinsSimulator.distribute("draw");
}

exports.metadata = {
	sinks: [
		{
			name: "write",
			params:
				{ type: "Object", name: "parameters", properties:
					[
						{ type: "Number", name: "red", defaultValue: 0, min: 0, max: 255, decimalPlaces: 0 },
						{ type: "Number", name: "green", defaultValue: 0, min: 0, max: 255, decimalPlaces: 0 },
						{ type: "Number", name: "blue", defaultValue: 0, min: 0, max: 255, decimalPlaces: 0 },
					]
				},
		},
	]
};


text:
<?php
/** 404.php
 *
 * The template for displaying 404 pages (Not Found).
 *
 * @author		Creiden
 * @package		Circleflip
 * @since		1.0.0 - 07.02.2012
 */

get_header(); ?>

					<img src="<?php echo esc_url( trailingslashit( images ) . 'error/error.png' ) ?>" alt="page not found"/>

404Error

Did you know that errors starting with 4xx mean Error at the client side? Please re-check the URL you entered and make sure it is typed correctly.

Or, Navigate to one of our pages above !

<?php
get_footer();
/* End of file 404.php */
/* Location: ./wp-content/themes/circleflip/404.php */


text:
Building Mbed TLS with PSA cryptoprocessor drivers
==================================================

**This is a specification of work in progress. The implementation is not yet merged into Mbed TLS.**

This document describes how to build Mbed TLS with additional cryptoprocessor drivers that follow the PSA cryptoprocessor driver interface.

The interface is not fully implemented in Mbed TLS yet and is disabled by default. You can enable the experimental work in progress by setting `MBEDTLS_PSA_CRYPTO_DRIVERS` in the compile-time configuration. Please note that the interface may still change: until further notice, we do not guarantee backward compatibility with existing driver code when `MBEDTLS_PSA_CRYPTO_DRIVERS` is enabled.

## Introduction

The PSA cryptography driver interface provides a way to build Mbed TLS with additional code that implements certain cryptographic primitives. This is primarily intended to support platform-specific hardware.

Note that such drivers are only available through the PSA cryptography API (crypto functions beginning with `psa_`, and X.509 and TLS interfaces that reference PSA types).

Concretely speaking, a driver consists of one or more **driver description files** in JSON format and some code to include in the build. The driver code can either be provided in binary form as additional object file to link, or in source form.

## How to build Mbed TLS with drivers

To build Mbed TLS with drivers:

1. Activate `MBEDTLS_PSA_CRYPTO_DRIVERS` in the library configuration.

    ```
    cd /path/to/mbedtls
    scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS
    ```

2. Pass the driver description files through the Make variable `PSA_DRIVERS` when building the library.

    ```
    cd /path/to/mbedtls
    make PSA_DRIVERS="/path/to/acme/driver.json /path/to/nadir/driver.json" lib
    ```

3. Link your application with the implementation of the driver functions.

    ```
    cd /path/to/application
    ld myapp.o -L/path/to/acme -lacmedriver -L/path/to/nadir -lnadirdriver -L/path/to/mbedtls -lmbedcrypto
    ```

<!-- TODO: what if the driver is provided as C source code? -->

<!-- TODO: what about additional include files? -->


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

<title>A-Index</title>
<meta name="date" content="2016-05-24">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M N P Q R S T U W

A

A380 - Class in asgn2Aircraft

Specialisation of the Aircraft class for the Airbus A380-800.

A380(String, int) - Constructor for class asgn2Aircraft.A380

Constructor for A380 uses default fare class capacities

A380(String, int, int, int, int, int) - Constructor for class asgn2Aircraft.A380

Constructor for A380 sets all fare class capacities

addPassenger(Passenger, int) - Method in class asgn2Simulators.Flights

Adds a Passenger to one of the aircraft in the flight list.

Aircraft - Class in asgn2Aircraft

The Aircraft class provides facilities for modelling a commercial jet
 aircraft with multiple travel classes.

Aircraft(String, int, int, int, int, int) - Constructor for class asgn2Aircraft.Aircraft

Constructor sets flight info and the basic size parameters.

AircraftException - Exception in asgn2Aircraft

This class represents exceptions generated during the
 simulation arising from the Aircraft hierarchy.

AircraftException(String) - Constructor for exception asgn2Aircraft.AircraftException

Creates a new instance of AircraftException.

asgn2Aircraft - package asgn2Aircraft

asgn2Passengers - package asgn2Passengers

asgn2Simulators - package asgn2Simulators

A B C D E F G H I L M N P Q R S T U W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package com.validation.manager.core.db;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.TableGenerator;
import javax.validation.constraints.NotNull;

/**
 *
 * @author Javier A. Ortiz Bultron javier.ortiz.78@gmail.com
 */
@Embeddable
public class RequirementSpecPK implements Serializable {

    @Basic(optional = false)
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "ReqSpecGen")
    @TableGenerator(name = "ReqSpecGen", table = "vm_id",
            pkColumnName = "table_name",
            valueColumnName = "last_id",
            pkColumnValue = "requirement_spec",
            allocationSize = 1,
            initialValue = 1_000)
    @NotNull
    @Column(name = "id")
    private int id;
    @Basic(optional = false)
    @NotNull
    @Column(name = "project_id")
    private int projectId;
    @Basic(optional = false)
    @NotNull
    @Column(name = "spec_level_id")
    private int specLevelId;

    public RequirementSpecPK() {
    }

    public RequirementSpecPK(int projectId, int specLevelId) {
        this.projectId = projectId;
        this.specLevelId = specLevelId;
    }

    public int getId() {
        return id;
    }

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

    public int getProjectId() {
        return projectId;
    }

    public void setProjectId(int projectId) {
        this.projectId = projectId;
    }

    public int getSpecLevelId() {
        return specLevelId;
    }

    public void setSpecLevelId(int specLevelId) {
        this.specLevelId = specLevelId;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (int) id;
        hash += (int) projectId;
        hash += (int) specLevelId;
        return hash;
    }

    @Override
    public boolean equals(Object object) {

        if (!(object instanceof RequirementSpecPK)) {
            return false;
        }
        RequirementSpecPK other = (RequirementSpecPK) object;
        if (this.id != other.id) {
            return false;
        }
        if (this.projectId != other.projectId) {
            return false;
        }
        return this.specLevelId == other.specLevelId;
    }

    @Override
    public String toString() {
        return "com.validation.manager.core.db.RequirementSpecPK[ id=" + id
                + ", projectId=" + projectId + ", specLevelId=" + specLevelId + " ]";
    }

}


text:
package com.imu.coursenet.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class Post implements Serializable {
	private static final long serialVersionUID = 48L;
	private Integer postId;
	private String title;
	private String content;
	private Date editDate;
	private Integer checkCounts;
	private Integer replyCounts;
	private Course course;
	private User user;
	private Set<PostReply> postReplys = new HashSet<PostReply>();

	public Post() {

	}

	public Integer getPostId() {
		return postId;
	}

	public Set<PostReply> getPostReplys() {
		return postReplys;
	}

	public void setPostReplys(Set<PostReply> postReplys) {
		this.postReplys = postReplys;
	}

	public void setPostId(Integer postId) {
		this.postId = postId;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getEditDate() {
		return editDate;
	}

	public void setEditDate(Date editDate) {
		this.editDate = editDate;
	}

	public Integer getCheckCounts() {
		return checkCounts;
	}

	public void setCheckCounts(Integer checkCounts) {
		this.checkCounts = checkCounts;
	}

	public Integer getReplyCounts() {
		return replyCounts;
	}

	public void setReplyCounts(Integer replyCounts) {
		this.replyCounts = replyCounts;
	}

	public Course getCourse() {
		return course;
	}

	public void setCourse(Course course) {
		this.course = course;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}


text:
package logprocessor.s3copy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.zip.GZIPInputStream;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;

public class S3CopyMapper extends MapReduceBase
	implements Mapper<LongWritable, Text, NullWritable, Text>
{
  public void map(LongWritable key, Text value,
				OutputCollector<NullWritable, Text> output, Reporter reporter)
		throws IOException
	{
    String fileName = value.toString();
		reporter.setStatus("Fetching file: " + fileName);

		NullWritable outputKey = NullWritable.get();
		FileSystem fs = FileSystem.get(URI.create(fileName), new JobConf());
		InputStream in = null;
		try {
	    in = fs.open(new Path(fileName));
	    if(fileName.endsWith(".gz")) {
        in = new GZIPInputStream(in);
	    }
	    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
	    try {
		    for (String line = reader.readLine(); line != null; line = reader.readLine()) {
	        // relying on short circuiting here to not get a null pointer
	        if(line == null || line.startsWith("#")) {
	            continue;
	        }
	        output.collect(outputKey, new Text(line));
		    }
	    } finally {
	      reader.close();
	    }
		} finally {
		  if (in != null) {
		    in.close();
		  }
	    fs.close();
	    reporter.setStatus("Finished downloading file: " + fileName);
		}
	}
}


text:
import { CookieDict, CookieOptions } from './cookie.model';

type EmptyArray = never[] & { length: 0 };
type EmptyObject = Record<any, never>;

export function isNil(obj: unknown): obj is undefined | null {
  return obj === undefined || obj === null;
}

export function isPresent(obj: unknown): obj is Exclude<typeof obj, undefined | null> {
  return !isNil(obj);
}

export function isString(obj: unknown): obj is string {
  return typeof obj === 'string';
}

// noinspection JSUnusedGlobalSymbols
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isEmpty(value: unknown): value is undefined | null | '' | EmptyArray | EmptyObject {
  if (isNil(value)) {
    return true;
  }
  if (value === {}) {
    return true;
  }
  if (isString(value) && value.length === 0) {
    return true;
  }
  if (Array.isArray(value) && value.length === 0) {
    return true;
  }
  if (typeof value !== 'boolean' && !value) {
    return true;
  }
  // noinspection RedundantIfStatementJS
  if (typeof value === 'object' && Object.keys(value).length === 0 && value.constructor === Object) {
    return true;
  }
  return false;
}

export function mergeOptions(oldOptions: CookieOptions, newOptions?: CookieOptions): CookieOptions {
  if (!newOptions) {
    return oldOptions;
  }
  return {
    path: isPresent(newOptions.path) ? newOptions.path : oldOptions.path,
    domain: isPresent(newOptions.domain) ? newOptions.domain : oldOptions.domain,
    expires: isPresent(newOptions.expires) ? newOptions.expires : oldOptions.expires,
    secure: isPresent(newOptions.secure) ? newOptions.secure : oldOptions.secure,
    sameSite: isPresent(newOptions.sameSite) ? newOptions.sameSite : oldOptions.sameSite,
    httpOnly: isPresent(newOptions.httpOnly) ? newOptions.httpOnly : oldOptions.httpOnly,
    storeUnencoded: isPresent(newOptions.storeUnencoded) ? newOptions.storeUnencoded : oldOptions.storeUnencoded
  };
}

export function parseCookieString(currentCookieString: string): CookieDict {
  let lastCookies: CookieDict = {};
  let lastCookieString = '';
  let cookieArray: string[];
  let cookie: string;
  let i: number;
  let index: number;
  let name: string;
  if (currentCookieString !== lastCookieString) {
    lastCookieString = currentCookieString;
    cookieArray = lastCookieString.split(';');
    lastCookies = {};
    for (i = 0; i < cookieArray.length; i++) {
      cookie = cookieArray[i];
      index = cookie.indexOf('=');
      if (index > 0) {  // ignore nameless cookies
        name = safeDecodeURIComponent((cookie.substring(0, index)).trim());
        // the first value that is seen for a cookie is the most
        // specific one.  values for the same cookie name that
        // follow are for less specific paths.
        if (isNil((lastCookies)[name])) {
          lastCookies[name] = safeDecodeURIComponent((cookie.substring(index + 1)).trim());
        }
      }
    }
  }
  return lastCookies;
}

export function buildCookieString(name: string, value: string | undefined, options?: CookieOptions): string {
  let expires: string | Date | undefined = options?.expires;
  let val: string;
  if (isNil(value)) {
    expires = 'Thu, 01 Jan 1970 00:00:00 GMT';
    val = '';
  } else {
    val = value as string;
  }
  if (isString(expires)) {
    expires = new Date(expires);
  }
  const cookieValue = options?.storeUnencoded ? value : encodeURIComponent(val);
  let str = encodeURIComponent(name) + '=' + cookieValue;
  str += options?.path ? ';path=' + options.path : '';
  str += options?.domain ? ';domain=' + options.domain : '';
  str += expires ? ';expires=' + expires.toUTCString() : '';
  str += options?.sameSite ? '; SameSite=' + options.sameSite : '';
  str += options?.secure ? ';secure' : '';
  str += options?.httpOnly ? '; HttpOnly' : '';

  // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  // - 300 cookies
  // - 20 cookies per unique domain
  // - 4096 bytes per cookie
  const cookieLength = str.length + 1;
  if (cookieLength > 4096) {
    console.log('Cookie \'' + name + '\' possibly not set or overflowed because it was too large (' + cookieLength + ' > 4096 bytes)!');
  }
  return str;
}

export function safeDecodeURIComponent(str: string): string {
  try {
    return decodeURIComponent(str);
  } catch (e) {
    return str;
  }
}


text:
angular.module('<%= appname %>').directive('<%= _.camelize(name) %>', <%= _.camelize(name) %>);
function <%= _.camelize(name) %>() {
    var directive = {
            restrict: 'EA',
            replace: true,
            scope: {

            },
            templateUrl: '<%= htmlPath %>',
            link: link,
            controller: <%= _.camelize(name) %>,
        controllerAs: 'vm',
        bindToController: true
    };

    return directive;

    function link(scope, element, attrs, fn) {

    }

}

/* @ngInject */
function <%= _.camelize(name) %> () {
    'use strict';
    /* jshint validthis: true */
    var vm = this;
}


text:
package org.apache.spark.scheduler

import java.io.{ByteArrayOutputStream, DataOutputStream, UTFDataFormatException}
import java.nio.ByteBuffer
import java.util.Properties

import scala.collection.mutable.HashMap

import org.apache.spark.ResourceInformation
import org.apache.spark.ResourceName.GPU
import org.apache.spark.SparkFunSuite

class TaskDescriptionSuite extends SparkFunSuite {
  test("encoding and then decoding a TaskDescription results in the same TaskDescription") {
    val originalFiles = new HashMap[String, Long]()
    originalFiles.put("fileUrl1", 1824)
    originalFiles.put("fileUrl2", 2)

    val originalJars = new HashMap[String, Long]()
    originalJars.put("jar1", 3)

    val originalProperties = new Properties()
    originalProperties.put("property1", "18")
    originalProperties.put("property2", "test value")
    // SPARK-19796 -- large property values (like a large job description for a long sql query)
    // can cause problems for DataOutputStream, make sure we handle correctly
    val sb = new StringBuilder()
    (0 to 10000).foreach(_ => sb.append("1234567890"))
    val largeString = sb.toString()
    originalProperties.put("property3", largeString)
    // make sure we've got a good test case
    intercept[UTFDataFormatException] {
      val out = new DataOutputStream(new ByteArrayOutputStream())
      try {
        out.writeUTF(largeString)
      } finally {
        out.close()
      }
    }

    val originalResources =
      Map(GPU -> new ResourceInformation(GPU, Array("1", "2", "3")))

    // Create a dummy byte buffer for the task.
    val taskBuffer = ByteBuffer.wrap(Array[Byte](1, 2, 3, 4))

    val originalTaskDescription = new TaskDescription(
      taskId = 1520589,
      attemptNumber = 2,
      executorId = "testExecutor",
      name = "task for test",
      index = 19,
      partitionId = 1,
      originalFiles,
      originalJars,
      originalProperties,
      originalResources,
      taskBuffer
    )

    val serializedTaskDescription = TaskDescription.encode(originalTaskDescription)
    val decodedTaskDescription = TaskDescription.decode(serializedTaskDescription)

    // Make sure that all of the fields in the decoded task description match the original.
    assert(decodedTaskDescription.taskId === originalTaskDescription.taskId)
    assert(decodedTaskDescription.attemptNumber === originalTaskDescription.attemptNumber)
    assert(decodedTaskDescription.executorId === originalTaskDescription.executorId)
    assert(decodedTaskDescription.name === originalTaskDescription.name)
    assert(decodedTaskDescription.index === originalTaskDescription.index)
    assert(decodedTaskDescription.partitionId === originalTaskDescription.partitionId)
    assert(decodedTaskDescription.addedFiles.equals(originalFiles))
    assert(decodedTaskDescription.addedJars.equals(originalJars))
    assert(decodedTaskDescription.properties.equals(originalTaskDescription.properties))
    assert(equalResources(decodedTaskDescription.resources, originalTaskDescription.resources))
    assert(decodedTaskDescription.serializedTask.equals(taskBuffer))

    def equalResources(original: Map[String, ResourceInformation],
        target: Map[String, ResourceInformation]): Boolean = {
      original.size == target.size && original.forall { case (name, info) =>
        target.get(name).exists { targetInfo =>
          info.name.equals(targetInfo.name) &&
            info.addresses.sameElements(targetInfo.addresses)
        }
      }
    }
  }
}


text:
title: Know Thy Option
author: vivekragunathan
layout: post
date: 2020-04-17
url: /2020/04/17/know-thy-option
categories:
  - Scala
  - Functional-Programming
summary: |
  Avoid `.get` at all costs. Forget there is even a `.get` function on `Option`. There is always a way out - better one, than using `.get`. Same applies to `.head`

  If you are going to have access the value in an `Option` in a test class, prefer extending your test class from `OptionValues`. Then you can use `.value` on an `Option`. Doing so establishes the presence of value as verification with meaningful error if value is not defined.
---

- Avoid `.get` at all costs. Forget there is even a `.get` function on `Option`. There is always a way out - better one, than using `.get`. Same applies to `.head`
- If you are going to have access the value in an `Option` in a test class[^1], prefer extending your test class from `OptionValues`. Then you can use `.value` on an `Option`. Doing so establishes the presence of value as verification with meaningful error if value is not defined.

<!-- more -->

## Did you know ?

- `Option` maybe viewed as a sequence (of zero or one element). This is for convenience when working with `Option`, which is why see a `.head` on an `Option`.

## The Different Options

Following are the different ways to _avoid the use of `.get` or `.head`_ to yield a value from an `Option`.

### **`map` and `flatMap`**

When you think of reaching into an `Option` for its value, `map` or `flatMap` is the defacto choice and is safe because they allow us to safely reach into `Option` only if there is a value inside. They may be chained back to back to attempt a series of transformations on the `Option`. Since the resultant type of the  transformations is still an `Option`, it is common for `map` or `flatMap` to end with one of the `getOrElse` , `fold` or is pattern `match`ed to resolve to a value.

```scala
val maybeGreeting: Option[String] = ...

def personalizeGreeting(g: String): String = ...

val mayBeGreetingBanner = maybeGreeting.map(personalizeGreeting)
```

```scala
val maybeGreetingKey: Option[String] = getGreetingKeyConfigName()

def readGreetingValue(g: String): Option[String] = ...

val maybeGreeting = maybeGreetingKey.flatMap(k => readGreetingValue(k))
```

### **`getOrElse`**

```scala
val maybeGreeting: Option[String] = ...

val g: String = maybeGreeting.getOrElse("Hello!")

val g: String = maybeGreeting.map(_.upperCase).getOrElse("HELLO!")
```

`getOrElse` provides a default or replacement value if the `Option` does not have a value. It is commonly used in cases where the intent is to resolve to a value by *optionally* running a sequence of transformations; a common default value if none of the transformations in the pipeline yields a value.

```scala
val maybeGreeting: Option[String] = maybeValueFromConfig()

val simpleStyleGreeting: String =
   maybeGreeting.getOrElse("Hello!")

val yelling: String =
  maybeGreeting
    .map(_.upperCase)
    .getOrElse("HELLO!")

val greetingAfterTransformations =
  mayBeGreeting
    .flatMap(maybeValueFromSource1)
    .flatMap(maybeValueFromSource2)
    .flatMap(maybeValueFromSource3)
    .getOrElse("Hello!")
```

`greetingAfterTransformations` may have one of the following values:

1. `maybeValueFromConfig`
2. Otherwise, `Hello!` even if one of the transformations (`flatMap`) does not yield non-empty `Option`
3. Otherwise, the string after running each of the transformations - `maybeValueFromSource1`, `maybeValueFromSource2`, `maybeValueFromSource3`.

   The subtlety in `greetingAfterTransformations` is that it is not explicit which transformation did not yield a value and was defaulted with `Hello!`.

### **`orElse`**

Consider `orElse` as the dual of `flatMap`. While `flatMap` runs when the `Option` has a value, `orElse` does the opposite. It runs when the `Option` does not have a value. Like `flatMap`, `orElse` expects an `Option` back from the evaluated expression.

```scala
import cats.syntax.option._
import cats.instances.functor._

val maybeG: Optional[String] =
  maybeGreeting.orElse("Hello!".some)
```

### **Pattern `match`**

One of the facilities that would have

```scala
val g: X =
  maybeGreeting match {
    case Some(g) => ...
    case None => ...
  }
```

where `X` is the type of value returned by the `match` expression.

```scala
import cats.syntax.option._
import cats.instances.functor._

val maybeGreeting: Option[String] = ...

val g: String = maybeGreeting.getOrElse("Hello!")

val g: String = maybeGreeting.map(_.upperCase).getOrElse("Hello!")

val maybeG: Optional[String] = maybeGreeting.orElse("Hello!".some)

val g: String =
  maybeGreeting match {
    case Some(g) => ...
    case None => ...
  }

val g: String =
  maybeGreeting.fold("Hello!") { g =>
  if (g.startsWith("How")) s"$g?"
  else s"$g!"
  }

val maybeG: Option[String] =
  maybeGreeting.innerMap {
    case Some(g) if g.startsWith("GG") => ...
    case Some("How are you?") => ...
  }
```

### **`fold`**

When you want to resolve to a value with explicit paths for the empty and

```scala
val g: String =
  maybeGreeting.fold("Hello!") { g =>
    if (g.startsWith("How")) s"$g?"
    else s"$g!"
  }
```

## Finally

As you can see, there is a myriad of options to avoid `.get` or `.head`, each with a different style and purpose and fitting different situations. You did not ask the question: _why should we avoid `.get` or `.head`?_

[^1]: Test code is real time code. It is used / executed several dozen times a day. Its quality is equally vital to a robust application. So, it is natural to develop a lot of classes and facilities to write better quality tests. It is recommended to reserve the use of `OptionalValues`.`value` in the tests themselves rather than in the facilities supporting the tests.


text:
package merry

import (
	errors "golang.org/x/xerrors"
)

// If using <go1.13, polyfill errors.Is/As with golang.org/x/xerrors
// xerrors can be removed once <go1.12 support is dropped

// implements Is by delegating to errors
var is = errors.Is

// implements As by delegating to errors
var as = errors.As


text:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';

import { SITE_HOST_URL } from '../../shared/index';
import { UserModel } from '../../shared/models/user.model';

@Injectable()
export class UserService {

    public isLogin:boolean = false;
    public userName:string = '';
    public userInfo:UserModel;
    private getUserInfoUrl = (api: string, userName: string) => `${api}user/get/${userName}`;

    constructor(private http: Http) { }

    getUser(){
        return new Observable((observer: Observer<any>) => {
            if(!this.userName) {
               observer.next('');
               observer.complete();
            } else {
                    this.http.get(this.getUserInfoUrl(SITE_HOST_URL, this.userName)).map(res=><UserModel>res.json().data).subscribe(data => {
                    this.isLogin = true;
                    this.userInfo = data;
                    observer.next(data);
                    observer.complete();
                }, err => {
                    this.isLogin = false;
                    this.userInfo = null;
                    observer.error(err);
                });
            }
        });
    }
}


text:
set -e

if [ `uname` = 'Linux' ] && [ `uname -m` = x86_64 ]; then
  echo "Installing Linux 64-bit packages"
  sudo apt-get update -qq
  sudo apt-get install -qq --force-yes libgd2-xpm ia32-libs ia32-libs-multiarch
fi


text:
package com.bjzy.qctt.dao;

import com.bjzy.qctt.CarPicListActivity;
import com.bjzy.qctt.CartypeActivity;
import com.bjzy.qctt.CommentCarActivity;
import com.bjzy.qctt.MapWebActivity;
import com.bjzy.qctt.SelectResultActivity;
import com.bjzy.qctt.WebActivity;
import com.bjzy.qctt.options.Constants;
import com.riven.utils.volley.CacheUtils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

public class JsInterface {

	private Context context;
	private String carid;
	public JsInterface(Context context, String carid) {
		this.context = context;
		this.carid = carid;
	}
	/**
	 * 获取配置的styleID
	 * @param styleID
	 */
	@android.webkit.JavascriptInterface
	public void getBtnStyleId(String styleID){
		CacheUtils.putString("styleid", styleID);
		((WebActivity)context).finish();
	}
	/**
	 * 从web获得电话号码 拨打电话
	 * @param number
	 */
	@android.webkit.JavascriptInterface
	public void getTel(String number){
		Intent intent=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+number));
		context.startActivity(intent);
	}
	/**
	 * 获取页面的分享信息
	 * @param objs
	 */
	@android.webkit.JavascriptInterface
	public void getStr(String objs){
		System.out.println(objs+"车的share_json");
		CacheUtils.putString( "share_json", objs);
	}
	/**
	 * 当web页的标签时根据不同标签跳转不同的页面
	 * @param title
	 * @param id
	 * @param name
	 * @param alt
	 */
	@android.webkit.JavascriptInterface
	public void getValue(String title, String id, String name, String alt) {
		int intId = Integer.parseInt(id);

		switch (intId) {
		case 1000:
			if (title.length()>10) {
				Intent intent = new Intent(context, WebActivity.class);
				intent.putExtra("carid", carid);
				intent.putExtra("jump", title);
				context.startActivity(intent);
			}else {
				Intent intent_1002 = new Intent(context, CartypeActivity.class);
				intent_1002.putExtra("carid", title);
				context.startActivity(intent_1002);
			}
			break;

		case 1001:
			//showToast("所有进入到一个完整的html页面"+title + "-id-" + id + "-name-" + name + "--alt" + alt);
			System.out.println(title);
			Intent intent = new Intent(context, WebActivity.class);
			intent.putExtra("carid", carid);
			intent.putExtra("jump", title);
			context.startActivity(intent);
			break;
		case 1002:
			Intent intent_1002 = new Intent(context, CartypeActivity.class);
			intent_1002.putExtra("carid", title);
			context.startActivity(intent_1002);
			break;
		case 1003:
			//showToast("车款详情头部图片"+title + "--" + id + "---" + name + "--alt" + alt);
			Intent intent_1003 = new Intent(context, CarPicListActivity.class);
			intent_1003.putExtra("carid",carid);
			context.startActivity(intent_1003);
			break;
		case 1004:
			//showToast("新闻内中的关键字"+title + "--" + id + "---" + name + "--alt" + alt);
			Intent intent_1004 = new Intent(context, SelectResultActivity.class);
			intent_1004.putExtra("keywords", title);
			context.startActivity(intent_1004);
			break;
		case 1005://车评论列表中我要点评
			Intent intent_1005 = new Intent(context, CommentCarActivity.class);
			System.out.println(title+"title:"+carid);
			intent_1005.putExtra("carid", carid);
			context.startActivity(intent_1005);
			break;
		case 1006:
			System.out.println(title+"title:");
			String[] split = title.split(",");
			//ScreenUtils.showtoast_OK(context, title);
			Intent intent1006 = new Intent(context, MapWebActivity.class);
			intent1006.putExtra("carid", "map");//如果carid是map则是一个地图
			intent1006.putExtra("shop_4s", split[0]);//店名
			intent1006.putExtra("location", split[1]);//地址
			intent1006.putExtra("longitude_shop", split[2]);//地址
			intent1006.putExtra("latitude_shop", split[3]);//地址
			intent1006.putExtra("jump", Constants.MAP_URL);
			context.startActivity(intent1006);
			break;
//		case 1007:
//			showToast("主题街"+title + "--" + id + "---" + name + "--alt" + alt);
//			break;
//		case 1008:
//			showToast("特色市场"+title + "--" + id + "---" + name + "--alt" + alt);
//			break;
//		case 1009:
//			showToast("今日推荐"+title + "--" + id + "---" + name + "--alt" + alt);
//			break;
		default:
			break;
		}

	}
}


text:
require "component/version"

module Component
  # Your code goes here...
end


text:
<?php

namespace Sylius\Component\Report\DataFetcher;

use Sylius\Component\Report\Model\ReportInterface;

/**
 * Delegating data fetcher.
 *
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
interface DelegatingDataFetcherInterface
{
    /**
     * Fetch data for given config.
     *
     * @param ReportInterface $report
     * @param array           $configuration
     *
     * @return array
     */
    public function fetch(ReportInterface $report, array $configuration = []);
}


text:
<?php
session_start();
if (empty($_SESSION['username'])){
	header('location:../index.php');
} else {
	include "../conn.php";
?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Aplikasi Penggajian Karyawan</title>
        <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
        <link href="../dist/css/bootstrap.css" rel="stylesheet" type="text/css" />
        <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

        <link href="//code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" rel="stylesheet" type="text/css" />

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

        <link href="../css/jvectormap/jquery-jvectormap-1.2.2.css" rel="stylesheet" type="text/css" />

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

        <link href="../css/daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css" />

        <link href="../css/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css" rel="stylesheet" type="text/css" />

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

        <link rel="stylesheet" href="datatables/dataTables.bootstrap.css"/>

                Admin APeK

                    Toggle navigation

                                <?php echo $_SESSION['fullname']; ?>

                                    <img src="<?php echo $_SESSION['gambar']; ?>" class="img-circle" alt="User Image" />

                                        <?php echo $_SESSION['fullname']; ?>

                                <?php
$timeout = 10; // Set timeout minutes
$logout_redirect_url = "../index.php"; // Set logout URL

$timeout = $timeout * 60; // Converts minutes to seconds
if (isset($_SESSION['start_time'])) {
    $elapsed_time = time() - $_SESSION['start_time'];
    if ($elapsed_time >= $timeout) {
        session_destroy();
        echo "";
    }
}
$_SESSION['start_time'] = time();
?>
<?php } ?>

                                <?php include "menu1.php"; ?>

                                        <a href="detail-admin.php?hal=edit&kd=<?php echo $_SESSION['user_id'];?>" class="btn btn-default btn-flat">Profil

                                         Keluar

                            <img src="<?php echo $_SESSION['gambar']; ?>" class="img-circle" alt="User Image" style="border: 2px solid #3C8DBC;" />

Selamat Datang,
<?php echo $_SESSION['fullname']; ?>

                             Online

                    <?php include "menu.php"; ?>

                        Karyawan
                        Aplikasi Penggajian Karyawan

 Karyawan

Edit Karyawan

                <?php
            $kd = $_GET['kd'];
			$sql = mysqli_query($koneksi, "SELECT * FROM karyawan WHERE nik='$kd'");
			if(mysqli_num_rows($sql) == 0){
				header("Location: karyawan.php");
			}else{
				$row = mysqli_fetch_assoc($sql);
			}
			if(isset($_POST['update'])){
				$nik	      = $_POST['nik'];
				$nama	      = $_POST['nama'];
				$alamat	    = $_POST['alamat'];
        $gender     = $_POST['gender'];
				$no_hp	    = $_POST['no_hp'];
        $departemen = $_POST['departemen'];
				$status	    = $_POST['status'];
				$gaji_pokok = $_POST['gaji_pokok'];
        $tunjangan  = $_POST['tunjangan'];

        $update = mysqli_query($koneksi, "UPDATE karyawan SET nama='$nama', alamat='$alamat', gender='$gender', no_hp='$no_hp', departemen='$departemen', status='$status', gaji_pokok='$gaji_pokok', tunjangan='$tunjangan' WHERE nik='$nik'") or die(mysqli_error());

        echo $update;
				if($update){
					echo '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Data berhasil disimpan.
';
				}else{
					echo '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Data gagal disimpan, silahkan coba lagi.
';
				}
			}

			//if(isset($_GET['pesan']) == 'sukses'){
			//	echo '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Data berhasil disimpan.
';
			//}
			?>

 Edit Data Departement

                      <form class="form-horizontal style-form" action="update-karyawan.php" method="post" enctype="multipart/form-data" name="form1" id="form1">

                              NIK

                                  <input name="nik" type="text" id="nik" value="<?php echo $row['nik']; ?>" class="form-control" readonly="readonly" />

                              Nama

                            <input name="nama" type="text" id="nama" value="<?php echo $row['nama']; ?>" class="form-control" autofocus="on" />

                              Alamat

                            <input name="alamat" type="text" id="alamat" value="<?php echo $row['alamat']; ?>" class="form-control" />

                              Gender

                                <select name="gender" id="gender" placeholder="Gender" class="form-control" required>
                                  <option value="0"<?=$row['gender'] == '0' ? ' selected="selected"' : '';?>>Laki Laki</option>
                                  <option value="1"<?=$row['gender'] == '1' ? ' selected="selected"' : '';?>>Perempuan</option>
                                </select>

                              No Handphone

                            <input name="no_hp" type="text" id="no_hp" value="<?php echo $row['no_hp']; ?>" class="form-control" />

                              Departement

                                  <select name="departemen" class="form-control" required>
                                    <option value=""> -- Pilih Departement -- </option>
                                    <option value="Warehouse"<?=$row['departemen'] == 'Warehouse' ? ' selected="selected"' : '';?>>Warehouse</option>
                                    <option value="Purchasing"<?=$row['departemen'] == 'Purchasing' ? ' selected="selected"' : '';?>>Purchasing</option>
                                    <option value="Accounting"<?=$row['departemen'] == 'Accounting' ? ' selected="selected"' : '';?>>Accounting</option>
                                    <option value="IT"<?=$row['departemen'] == 'IT' ? ' selected="selected"' : '';?>>IT</option>
                                    <option value="Production"<?=$row['departemen'] == 'Production' ? ' selected="selected"' : '';?>>Production</option>
                                    <option value="PPIC"<?=$row['departemen'] == 'PPIC' ? ' selected="selected"' : '';?>>PPIC</option>
                                    <option value="QC"<?=$row['departemen'] == 'QC' ? ' selected="selected"' : '';?>>QC</option>
                                    <option value="QA"<?=$row['departemen'] == 'QA' ? ' selected="selected"' : '';?>>QA</option>
                                    <option value="Exim"<?=$row['departemen'] == 'Exim' ? ' selected="selected"' : '';?>>Exim</option>
                                    <option value="HRD"<?=$row['departemen'] == 'HRD' ? ' selected="selected"' : '';?>>HRD</option>
                                    <option value="Marketing"<?=$row['departemen'] == 'Marketing' ? ' selected="selected"' : '';?>>Marketing</option>
                                    <option value="Lainnya"<?=$row['departemen'] == 'Lainnya' ? ' selected="selected"' : '';?>>Lainnya</option>
                                  </select>

                              Status

                                  <select name="status" class="form-control" required>
                                    <option value=""> -- Pilih Status Karyawan -- </option>
                                    <option value="tetap"<?=$row['status'] == 'tetap' ? ' selected="selected"' : '';?>>Tetap</option>
                                    <option value="kontrak"<?=$row['status'] == 'kontrak' ? ' selected="selected"' : '';?>>Kontrak</option>
                                    <option value="magang"<?=$row['status'] == 'magang' ? ' selected="selected"' : '';?>>Magang</option>
                                    <option value="outsource"<?=$row['status'] == 'outsource' ? ' selected="selected"' : '';?>>Outsourcing</option>
                                  </select>

                              Gaji Pokok

                                  <input name="gaji_pokok" type="text" id="gaji_pokok" value="<?php echo $row['gaji_pokok']; ?>" class="form-control" />

                              Tunjangan

                                  <input name="tunjangan" type="text" id="tunjangan" value="<?php echo $row['tunjangan']; ?>" class="form-control" />

                                  <input type="submit" name="input" value="Simpan" class="btn btn-sm btn-primary" />
                                Batal

                      </form>


text:
import sys  # For exit
import random  # For HOP_ADVANTAGE
import Critter  # To access enums (Actions/Neighbors)

class CritterModel:
    # Advantage given to an infect that follows a hop
    HOP_ADVANTAGE = 0.0  # 0 is hopping gives no benefit

    height = 0  # Height of the gameboard
    width = 0  # Width of the board
    debugView = False  # Whether debug view is on
    created = False

    # Constructor
    def __init__(self, width, height):
        # Disable multiple constructing of Model
        if (self.created):
            sys.exit("Only one world allowed!")
        self.created = True
        self.simulationCount = 0
        self.width = width
        self.height = height

        # A 2D array of Critters, dimensions width x height
        # Address grid as self.grid[X][Y] where 0<x<width and 0<y<height
        self.grid = [[None for i in range(height)] for i in range(width)]
        self.info = {} # A Dict from Critter to PrivateData so we can get a Critter's Neighbors, etc.
        self.critterCount = []  # A sorted list of tuples of Critter Names, and populations in this game
        self.critterColors = {}  # A mapping from class to color, modified when critters are added

    # Get c's location as a Class Point
    def getPoint(self, c):
        return info.get(c).p

    # Get c's color
    # Returns a 3-tuple (r, g, b) of values 0-1000
    # Although curses supports changing the background color of a critter aswell,
    # we limit ourselves to text color
    def getColor(self, c):
        return self.info.get(c).color

    # Get c's string field. (Typically a single character)
    def getString(self, c):
        return self.info.get(c).string;

    # Add number critter objects to the board randomly
    # critter must be a class object that extends Critter.Critter
    def add(self, number, critter):
        random.seed()  # We seed based on system time
        # List to randomly shoose directions from
        directions = [Critter.Critter.Direction.NORTH,
                      Critter.Critter.Direction.SOUTH,
                      Critter.Critter.Direction.EAST,
                      Critter.Critter.Direction.WEST]  # Get list of possible directions
        if (len(self.info) + number > self.width * self.height):
            sys.exit("adding too many critters")  # More critters then spaces!
        for i in range(number):  # Place each critter
            nxt = self.makeCritter(critter)
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)
            while (self.grid[x][y] is not None):  # Keep generating random spots until we get a blank one
                x = random.randint(0, self.width - 1)
                y = random.randint(0, self.height - 1)
            self.grid[x][y] = nxt  # Store our critter there
            # Make the Critter point a random direction
            d = directions[random.randint(0, len(directions) - 1)]
            self.info[nxt] =  self.PrivateData(self.Point(x, y), d)
        name = critter.__name__  # Critter is uninstantiated Class object
        if name not in [c[0] for c in self.critterCount]:
            # Add this critter's counts for the first time
            self.critterCount.append((name, number))
            self.critterColors[critter] = critter.color
        else:
            # Add more to this critter's count
            for idx, c in enumerate(self.critterCount):
                if c[0] == name:
                    self.critterCount[idx] = (name, self.critterCount[idx][1] + number)

    # A useful point class for descrbing critter locations
    class Point:
        x = None
        y = None

        def __init__(self, x, y):
            self.x = x
            self.y = y

    # Calls the constructor of critter
    def makeCritter(self, critter):
        return critter()

    def getColor(self, c):
        return c.getColor;

    # Get the sumbolic representation of c
    def getAppearance(self, c):
        if not self.debugView:
            return str(c)
        else:
            # If debug is on then we display arrows correspondiong to direction
            data = self.info[c]
            if (data.direction == Critter.Critter.Direction.NORTH):
                return '^'
            elif (data.direction == Critter.Critter.Direction.SOUTH):
                return 'v'
            elif (data.direction == Critter.Critter.Direction.EAST):
                return '>'
            else:
                return '<'

    # Toggle the debug view for this model
    def toggleDebug(self):
        self.debugView = not self.debugView

    # Return whether or not p is within the bounds of this board
    def inBounds(self, p):
        return (p.x >= 0 and
                p.x < self.width and
                p.y >= 0 and
                p.y < self.height)

    # Rotate the direction d 90 degrees to the right
    def rotate(self, d):
        if (d == Critter.Critter.Direction.NORTH):
            return Critter.Critter.Direction.EAST
        elif (d == Critter.Critter.Direction.SOUTH):
            return Critter.Critter.Direction.WEST
        elif (d == Critter.Critter.Direction.EAST):
            return Critter.Critter.Direction.SOUTH
        else:
            return Critter.Critter.Direction.NORTH

    # Get the point in front of this critter
    # We designate 0,0 to be the top-left corner of grid
    # and NORTH to be pointing "up", i.e. towards decreasing y
    # and EAST as increasing x
    def pointAt(self, p, d):
        if (d == Critter.Critter.Direction.NORTH):
            return self.Point(p.x, p.y - 1)
        elif (d == Critter.Critter.Direction.SOUTH):
            return self.Point(p.x, p.y + 1)
        elif (d == Critter.Critter.Direction.EAST):
            return self.Point(p.x + 1, p.y)
        else:
            return self.Point(p.x - 1, p.y)

    # Generate a CritterInfo for already added critter object "original"
    # with PrivateData data
    def getInfo(self, data, original):
        d = data.direction
        neighbors = []
        neighborThreats = []
        for i in range(4):  # Check font/right/back/left and get neighbors info
            neighbors.append(self.getStatus(self.pointAt(data.p, d), original))
            # Now that we know what the neighbor is, check if it is threatening
            if (neighbors[i] is Critter.Critter.Neighbor.OTHER):
                # Check if it a an enemeny who is staring at us and could infect
                p = self.pointAt(data.p, d)
                oldData = self.info.get(self.grid[p.x][p.y])
                # Append a boolean
                neighborThreats.append(d is self.rotate(self.rotate(oldData.direction)))
            d = self.rotate(d)
        return self.Info(neighbors, data.direction, neighborThreats)

    # Get whether the element p on the grid is wall/other/same/empty with
    # respect to the critter passed as "original"
    def getStatus(self, p, original):
        if not self.inBounds(p):  # If the point is out of bounds, then it is a wall
            return Critter.Critter.Neighbor.WALL
        elif (self.grid[p.x][p.y] is None):  # nothing there, the space is empty
            return Critter.Critter.Neighbor.EMPTY
        # Identify if this critter is one of your own by comparing class types
        elif (self.grid[p.x][p.y].__class__ == original.__class__):
            return Critter.Critter.Neighbor.SAME
        else:  # Otherwise it must be an enemy
            return Critter.Critter.Neighbor.OTHER

    # Update the board, applying each critters' moves
    def update(self):
        self.simulationCount = self.simulationCount + 1
        objList = self.info.keys()  # Get a list of each critter to move
        random.shuffle(objList)  # Handle them in random order

        # A list of critters that cannot be infected this step
        # (e.g. a critter cannot move to a place and be infected there
        # in the same turn)
        #locked = {}

        # Loop through each critter and perform their action
        for i, nxt in enumerate(objList):
            data = self.info.get(nxt)  # Current Critter's State
            if (data is None):
                continue  # Happens when this creature was infected earlier in round

            hadHopped = data.justHopped
            data.justHopped = False
            p = data.p  # This critter's current location
            p2 = self.pointAt(p, data.direction)  # Point in front of critter

            # Try to perform a critter's action
            move = nxt.getMove(self.getInfo(data, nxt))

            if (move is Critter.Critter.Action.LEFT):
                data.direction = self.rotate(self.rotate(self.rotate(data.direction)))
            elif (move is Critter.Critter.Action.RIGHT):
                data.direction = self.rotate(data.direction)
            elif (move is Critter.Critter.Action.HOP):
                # To perform a HOP, check that nothing prevents it from moving, and move
                if (self.inBounds(p2) and self.grid[p2.x][p2.y] == None):
                    self.grid[p2.x][p2.y] = self.grid[p.x][p.y]
                    self.grid[p.x][p.y] = None  # Erase old space
                    data.p = p2  # Set critter's point to point formely infront of it
                    #locked[nxt] = True  # Used =in conjunction with HOP_ADVANTAGE

                    data.justHopped = True  # Used in conjuction with HOP_ADVANTAGE
            elif (move == Critter.Critter.Action.INFECT):
                if (self.inBounds(p2) and
                    self.grid[p2.x][p2.y] is not None and
                    self.grid[p2.x][p2.y].__class__.__name__ is not
                        nxt.__class__.__name__ and
                    self.grid[p2.x][p2.y] and #not in locked and#  used in conjunction with HOP_ADVANTAGE
                    (hadHopped or random.random() >= self.HOP_ADVANTAGE)):
                    # INFECT: Replace victim with critter of nxt's type
                        other = self.grid[p2.x][p2.y]  # victim
                        oldData = self.info.get(other)

                        # Update scores by converting tuple-list to dict for a moment
                        c1 = other.__class__.__name__
                        c2 = nxt.__class__.__name__
                        critterScoreDict = dict(self.critterCount)
                        critterScoreDict[c1] = critterScoreDict[c1] - 1
                        critterScoreDict[c2] = critterScoreDict[c2] + 1
                        self.critterCount = list(critterScoreDict.items())  # Convert back to list and save updated

                        del self.info[other]  # Remove the data on the removed critter
                        # Make a critter of nxt's type
                        self.grid[p2.x][p2.y] = self.makeCritter(nxt.__class__)
                        # Give it old critter's data (so it points same direction, etc.)
                        self.info[self.grid[p2.x][p2.y]] = oldData
                        oldData.justHopped = False

    # Called when the CritterFrame closes the application
    # Save any necessary state
    def close(self):
        pass

    # Class holding data for a specific Critter in play
    class PrivateData:
        justHopped = False

        def __init__(self, p, d):
            self.p = p
            self.direction = d

    # Class passed to a Critter giving it information to make a move with
    class Info():
        def __init__(self, neighbors, d, neighborThreats):
            self.neighbors = neighbors
            self.direction = d
            self.neighborThreats = neighborThreats

        # Which element in neighbors is which neighbor depends on the method getInfo()
        def getFront(self):
            return self.neighbors[0]

        def getBack(self):
            return self.neighbors[2]

        def getLeft(self):
            return self.neighbors[3]

        def getRight(self):
            return self.neighbors[1]

        def getDirection(self):
            return self.direction

        def frontThreat(self):
            return self.neighborThreats[0]

        def backThreat(self):
            return self.neighborThreats[2]

        def leftThreat(self):
            return self.neighborThreats[3]

        def rightThreat(self):
            return self.neighborThreats[1]


text:
**NOTE: This project has been renamed [Maestro](https://github.com/toscanini/maestro) and development has moved under the Toscanini organization.** See the [Maestro project](https://github.com/toscanini/maestro) for the current source code.

dockermix
============

A command line tool to build and manage multi-container docker environments. Container sets are defined in a simple YAML format that mirrors the options available in the Docker API. The intention is to be able to easily launch, orchestrate and destroy complex multi-node envionments for testing and development.


text:
using Xamarin.Forms;

namespace MyVote.UI.Controls
{
	public sealed class ExtendedLabel : Label
	{
	    public static readonly BindableProperty LeftPaddingProperty = BindableProperty.Create<ExtendedLabel, int>(p => p.LeftPadding, 0);
        public int LeftPadding
        {
            get { return (int)this.GetValue(LeftPaddingProperty); }
            set { SetValue(LeftPaddingProperty, value); }
        }
	}
}


text:
#ifndef __sitkImageFileReader_h
#define __sitkImageFileReader_h

#include "sitkMacro.h"
#include "sitkImage.h"
#include "sitkImageReaderBase.h"
#include "sitkMemberFunctionFactory.h"

namespace itk {
  namespace simple {

    /** \class ImageFileReader
     * \brief Read a 2D or 3D image and return a smart pointer to a SimpleITK
     * image
     *
     * This reader handles scalar and vector images and returns an image with
     * the same type as the file on disk.
     *
     * \sa itk::simple::ReadImage for the procedural interface
     */
    class SITKIO_EXPORT ImageFileReader
      : public ImageReaderBase
    {
    public:
      typedef ImageFileReader Self;

      /** Print ourselves to string */
      virtual std::string ToString() const;

      /** return user readable name fo the filter */
      virtual std::string GetName() const { return std::string("ImageFileReader"); }

      Self& SetFileName ( std::string fn );
      std::string GetFileName() const;

      Image Execute();

      ImageFileReader();

    protected:

      template <class TImageType> Image ExecuteInternal ( void );

    private:

      // function pointer type
      typedef Image (Self::*MemberFunctionType)( void );

      // friend to get access to executeInternal member
      friend struct detail::MemberFunctionAddressor<MemberFunctionType>;
      std::auto_ptr<detail::MemberFunctionFactory<MemberFunctionType> > m_MemberFactory;

      std::string m_FileName;
    };

  SITKIO_EXPORT Image ReadImage ( std::string filename, PixelIDValueEnum outputPixelType = sitkUnknown );
  }
}

#endif


text:
package org.apache.helix.integration;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import com.google.common.collect.Lists;
import org.apache.helix.AccessOption;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.model.ClusterConstraints.ConstraintAttribute;
import org.apache.helix.model.ClusterConstraints.ConstraintType;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.IdealStateProperty;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.Message;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.model.builder.ConstraintItemBuilder;
import org.apache.helix.participant.statemachine.StateModel;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.zookeeper.zkclient.DataUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestPreferenceListAsQueue extends ZkUnitTestBase {
  private static final Logger LOG = LoggerFactory.getLogger(TestPreferenceListAsQueue.class);
  private static final int TRANSITION_TIME = 500;
  private static final int PARALLELISM = 1;

  private List<String> _instanceList;
  private Queue<List<String>> _prefListHistory;
  private String _clusterName;
  private String _stateModel;
  private ClusterSetup _clusterSetup;
  private HelixAdmin _admin;
  private CountDownLatch _onlineLatch;
  private CountDownLatch _offlineLatch;

  @BeforeMethod
  public void beforeMethod() {
    _instanceList = Lists.newLinkedList();
    _clusterSetup = new ClusterSetup(ZK_ADDR);
    _admin = _clusterSetup.getClusterManagementTool();
    _prefListHistory = Lists.newLinkedList();

    // Create cluster
    String className = TestHelper.getTestClassName();
    String methodName = TestHelper.getTestMethodName();
    _clusterName = className + "_" + methodName;
    _clusterSetup.addCluster(_clusterName, true);
  }

  @AfterClass
  public void afterClass() {
    deleteCluster(_clusterName);
  }

  /**
   * This test ensures successful creation when the state model has OFFLINE --> deprioritized and
   * a partition-level constraint enforces parallelism
   * @throws Exception
   */
  @Test
  public void testReprioritizedWithConstraint() throws Exception {
    _stateModel = "OnlineOfflineReprioritized";

    // Add a state model with the transition to ONLINE deprioritized
    _clusterSetup.addStateModelDef(_clusterName, _stateModel,
        createReprioritizedStateModelDef(_stateModel));

    // Add a constraint of one transition per partition
    ConstraintItemBuilder constraintItemBuilder = new ConstraintItemBuilder();
    constraintItemBuilder
        .addConstraintAttribute(ConstraintAttribute.MESSAGE_TYPE.toString(), "STATE_TRANSITION")
        .addConstraintAttribute(ConstraintAttribute.PARTITION.toString(), ".*")
        .addConstraintAttribute(ConstraintAttribute.CONSTRAINT_VALUE.toString(),
            String.valueOf(PARALLELISM));
    _admin.setConstraint(_clusterName, ConstraintType.MESSAGE_CONSTRAINT, "constraint_1",
        constraintItemBuilder.build());
    runTest();
  }

  /**
   * This test directly embeds the parallelism per partition directly into the upper bound for the
   * ONLINE state. This does not require the controller to support partition-level constraints.
   * @throws Exception
   */
  @Test
  public void testParallelismInStateModel() throws Exception {
    _stateModel = "OnlineOfflineBounded";

    // Add a state model with the parallelism implicit
    _clusterSetup.addStateModelDef(_clusterName, _stateModel,
        createEnforcedParallelismStateModelDef(_stateModel));
    runTest();
  }

  private void runTest() throws Exception {
    final int NUM_PARTITIONS = 1;
    final int NUM_REPLICAS = 2;
    final int NUM_INSTANCES = 2;
    final String RESOURCE_NAME = "MyResource";

    // Setup instances
    String[] instanceInfoArray = {
        "localhost_1", "localhost_2"
    };
    _clusterSetup.addInstancesToCluster(_clusterName, instanceInfoArray);

    // Add resource
    _clusterSetup.addResourceToCluster(_clusterName, RESOURCE_NAME, NUM_PARTITIONS, _stateModel,
        RebalanceMode.SEMI_AUTO.toString());

    // Update resource with empty preference lists
    IdealState idealState = _admin.getResourceIdealState(_clusterName, RESOURCE_NAME);
    for (int i = 0; i < NUM_PARTITIONS; i++) {
      String partitionName = RESOURCE_NAME + "_" + i;
      List<String> dummyPreferences = Lists.newArrayList();
      for (int j = 0; j < NUM_REPLICAS; j++) {
        // hack: need to have some dummy values in the preference list to pass validation
        dummyPreferences.add("");
      }
      idealState.getRecord().setListField(partitionName, dummyPreferences);
    }
    idealState.setReplicas(String.valueOf(NUM_REPLICAS));
    _admin.setResourceIdealState(_clusterName, RESOURCE_NAME, idealState);

    // Start some instances
    HelixManager[] participants = new HelixManager[NUM_INSTANCES];
    for (int i = 0; i < NUM_INSTANCES; i++) {
      participants[i] = HelixManagerFactory.getZKHelixManager(_clusterName, instanceInfoArray[i],
          InstanceType.PARTICIPANT, ZK_ADDR);
      participants[i].getStateMachineEngine().registerStateModelFactory(_stateModel,
          new PrefListTaskOnlineOfflineStateModelFactory());
      participants[i].connect();
    }

    // Start the controller
    HelixManager controller =
        HelixManagerFactory.getZKHelixManager(_clusterName, null, InstanceType.CONTROLLER, ZK_ADDR);
    controller.connect();

    // Disable controller immediately
    _admin.enableCluster(_clusterName, false);

    // This resource only has 1 partition
    String partitionName = RESOURCE_NAME + "_" + 0;

    // There should be no preference lists yet
    Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
        Arrays.asList("", "")));

    // Add one instance
    addInstanceToPreferences(participants[0].getHelixDataAccessor(),
        participants[0].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
    Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
        Arrays.asList("localhost_1", "")));

    // Add a second instance immediately; the first one should still exist
    addInstanceToPreferences(participants[1].getHelixDataAccessor(),
        participants[1].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
    Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
        Arrays.asList("localhost_1", "localhost_2")));

    // Add the first instance again; it should already exist
    addInstanceToPreferences(participants[0].getHelixDataAccessor(),
        participants[0].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
    Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
        Arrays.asList("localhost_1", "localhost_2")));

    // Prepare for synchronization
    _onlineLatch = new CountDownLatch(2);
    _offlineLatch = new CountDownLatch(2);
    _prefListHistory.clear();

    // Now reenable the controller
    _admin.enableCluster(_clusterName, true);

    // Now wait for both instances to be done
    boolean countReached = _onlineLatch.await(10000, TimeUnit.MILLISECONDS);
    Assert.assertTrue(countReached);
    List<String> top = _prefListHistory.poll();
    assert top != null;
    Assert.assertTrue(top.equals(Arrays.asList("localhost_1", ""))
        || top.equals(Arrays.asList("localhost_2", "")));
    Assert.assertEquals(_prefListHistory.poll(), Arrays.asList("", ""));

    // Wait for everything to be fully offline
    countReached = _offlineLatch.await(10000, TimeUnit.MILLISECONDS);
    Assert.assertTrue(countReached);

    // Add back the instances in the opposite order
    _admin.enableCluster(_clusterName, false);
    addInstanceToPreferences(participants[0].getHelixDataAccessor(),
        participants[1].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
    addInstanceToPreferences(participants[0].getHelixDataAccessor(),
        participants[0].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
    Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
        Arrays.asList("localhost_2", "localhost_1")));

    // Reset the latch
    _onlineLatch = new CountDownLatch(2);
    _prefListHistory.clear();
    _admin.enableCluster(_clusterName, true);

    // Now wait both to be done again
    countReached = _onlineLatch.await(10000, TimeUnit.MILLISECONDS);
    Assert.assertTrue(countReached);
    top = _prefListHistory.poll();
    assert top != null;
    Assert.assertTrue(top.equals(Arrays.asList("localhost_1", ""))
        || top.equals(Arrays.asList("localhost_2", "")));
    Assert.assertEquals(_prefListHistory.poll(), Arrays.asList("", ""));
    Assert.assertEquals(_instanceList.size(), 0);

    // Cleanup
    controller.disconnect();
    for (HelixManager participant : participants) {
      participant.disconnect();
    }
  }

  /**
   * Create a modified version of OnlineOffline where the transition to ONLINE is given lowest
   * priority
   * @param stateModelName
   * @return
   */
  private StateModelDefinition createReprioritizedStateModelDef(String stateModelName) {
    StateModelDefinition.Builder builder = new StateModelDefinition.Builder(stateModelName)
        .addState("ONLINE", 1).addState("OFFLINE").addState("DROPPED").addState("ERROR")
        .initialState("OFFLINE").addTransition("ERROR", "OFFLINE", 1)
        .addTransition("ONLINE", "OFFLINE", 2).addTransition("OFFLINE", "DROPPED", 3)
        .addTransition("OFFLINE", "ONLINE", 4).dynamicUpperBound("ONLINE", "R")
        .upperBound("OFFLINE", -1).upperBound("DROPPED", -1).upperBound("ERROR", -1);
    return builder.build();
  }

  /**
   * Create a modified version of OnlineOffline where the parallelism is enforced by the upper bound
   * of ONLINE
   * @param stateModelName
   * @return
   */
  private StateModelDefinition createEnforcedParallelismStateModelDef(String stateModelName) {
    StateModelDefinition.Builder builder =
        new StateModelDefinition.Builder(stateModelName).addState("ONLINE", 1).addState("OFFLINE")
            .addState("DROPPED").addState("ERROR").initialState("OFFLINE")
            .addTransition("ERROR", "OFFLINE", 1).addTransition("ONLINE", "OFFLINE", 2)
            .addTransition("OFFLINE", "DROPPED", 3).addTransition("OFFLINE", "ONLINE", 4)
            .dynamicUpperBound("ONLINE", String.valueOf(PARALLELISM)).upperBound("OFFLINE", -1)
            .upperBound("DROPPED", -1).upperBound("ERROR", -1);
    return builder.build();
  }

  /**
   * Check if the provided list matches the currently persisted preference list
   * @param admin
   * @param clusterName
   * @param resourceName
   * @param partitionName
   * @param expectPreferenceList
   * @return
   */
  private boolean preferenceListIsCorrect(HelixAdmin admin, String clusterName, String resourceName,
      String partitionName, List<String> expectPreferenceList) {
    IdealState idealState = admin.getResourceIdealState(clusterName, resourceName);
    List<String> preferenceList = idealState.getPreferenceList(partitionName);
    return expectPreferenceList.equals(preferenceList);
  }

  /**
   * Update an ideal state so that partitions will have an instance removed from their preference
   * lists
   * @param accessor
   * @param instanceName
   * @param resourceName
   * @param partitionName
   */
  private void removeInstanceFromPreferences(HelixDataAccessor accessor, final String instanceName,
      final String resourceName, final String partitionName) {
    PropertyKey.Builder keyBuilder = accessor.keyBuilder();
    String idealStatePath = keyBuilder.idealStates(resourceName).getPath();
    synchronized (_prefListHistory) {
      // Updater for ideal state
      final List<String> prefList = Lists.newLinkedList();
      DataUpdater<ZNRecord> idealStateUpdater = currentData -> {
        List<String> preferenceList = currentData.getListField(partitionName);
        int numReplicas =
            Integer.valueOf(currentData.getSimpleField(IdealStateProperty.REPLICAS.toString()));
        List<String> newPrefList =
            removeInstanceFromPreferenceList(preferenceList, instanceName, numReplicas);
        currentData.setListField(partitionName, newPrefList);
        prefList.clear();
        prefList.addAll(newPrefList);
        return currentData;
      };
      List<DataUpdater<ZNRecord>> updaters = Lists.newArrayList();
      updaters.add(idealStateUpdater);
      accessor.updateChildren(Collections.singletonList(idealStatePath), updaters,
          AccessOption.PERSISTENT);
      _prefListHistory.add(prefList);
    }
  }

  /**
   * Update an ideal state so that partitions will have a new instance at the tails of their
   * preference lists
   * @param accessor
   * @param instanceName
   * @param resourceName
   * @param partitions
   */
  private void addInstanceToPreferences(HelixDataAccessor accessor, final String instanceName,
      final String resourceName, final List<String> partitions) {
    PropertyKey.Builder keyBuilder = accessor.keyBuilder();
    String idealStatePath = keyBuilder.idealStates(resourceName).getPath();
    synchronized (_prefListHistory) {
      // Updater for ideal state
      final List<String> prefList = Lists.newLinkedList();
      DataUpdater<ZNRecord> idealStateUpdater = currentData -> {
        for (String partitionName : partitions) {
          List<String> preferenceList = currentData.getListField(partitionName);
          int numReplicas =
              Integer.valueOf(currentData.getSimpleField(IdealStateProperty.REPLICAS.toString()));
          List<String> newPrefList =
              addInstanceToPreferenceList(preferenceList, instanceName, numReplicas);
          currentData.setListField(partitionName, newPrefList);
          prefList.clear();
          prefList.addAll(newPrefList);
        }
        return currentData;
      };

      // Send update requests together
      List<DataUpdater<ZNRecord>> updaters = Lists.newArrayList();
      updaters.add(idealStateUpdater);
      accessor.updateChildren(Collections.singletonList(idealStatePath), updaters,
          AccessOption.PERSISTENT);
      _prefListHistory.add(prefList);
    }
  }

  /**
   * Add the instance to the preference list, removing padding as necessary
   * @param existPreferences
   * @param instanceName
   * @param numReplicas
   * @return A new preference list with the instance added to the end (if it did not already exist)
   */
  private static List<String> addInstanceToPreferenceList(List<String> existPreferences,
      String instanceName, int numReplicas) {
    if (existPreferences == null) {
      existPreferences = Lists.newArrayList();
    }
    List<String> newPreferences = Lists.newArrayListWithCapacity(numReplicas);
    for (String existInstance : existPreferences) {
      if (!existInstance.isEmpty()) {
        newPreferences.add(existInstance);
      }
    }
    if (!newPreferences.contains(instanceName)) {
      newPreferences.add(instanceName);
    }
    addDummiesToPreferenceList(newPreferences, numReplicas);
    return newPreferences;
  }

  /**
   * Remove an instance from a preference list, padding as necessary
   * @param existPreferences
   * @param instanceName
   * @param numReplicas
   * @return new preference list with the instance removed (if it existed)
   */
  private static List<String> removeInstanceFromPreferenceList(List<String> existPreferences,
      String instanceName, int numReplicas) {
    if (existPreferences == null) {
      existPreferences = Lists.newArrayList();
    }
    List<String> newPreferences = Lists.newArrayListWithCapacity(numReplicas);
    for (String existInstance : existPreferences) {
      if (!existInstance.isEmpty() && !existInstance.equals(instanceName)) {
        newPreferences.add(existInstance);
      }
    }
    addDummiesToPreferenceList(newPreferences, numReplicas);
    return newPreferences;
  }

  /**
   * Pad a preference list with empty strings to have it reach numReplicas size
   * @param preferences
   * @param numReplicas
   */
  private static void addDummiesToPreferenceList(List<String> preferences, int numReplicas) {
    int numRemaining = numReplicas - preferences.size();
    numRemaining = (numRemaining > 0) ? numRemaining : 0;
    for (int i = 0; i < numRemaining; i++) {
      preferences.add("");
    }
  }

  /**
   * A state model whose callbacks correspond to when to run a task. When becoming online, the task
   * should be run, and then the instance should be removed from the preference list for the task
   * (padded by spaces). All other transitions are no-ops.
   */
  public class PrefListTaskOnlineOfflineStateModel extends StateModel {
    /**
     * Run the task. The parallelism of this is dictated by the constraints that are set.
     * @param message
     * @param context
     * @throws InterruptedException
     */
    public void onBecomeOnlineFromOffline(final Message message, NotificationContext context)
        throws InterruptedException {
      // Do the work, and then finally remove the instance from the preference list for this
      // partition
      HelixManager manager = context.getManager();
      LOG.info("START onBecomeOnlineFromOffline for " + message.getPartitionName() + " on "
          + manager.getInstanceName());
      int oldSize;
      synchronized (_instanceList) {
        oldSize = _instanceList.size();
        _instanceList.add(manager.getInstanceName());
      }
      Assert.assertEquals(oldSize, 0); // ensure these transitions are fully synchronized

      Thread.sleep(TRANSITION_TIME); // a sleep simulates work

      // Need to disable in order to get the transition the next time
      HelixDataAccessor accessor = manager.getHelixDataAccessor();
      removeInstanceFromPreferences(accessor, manager.getInstanceName(), message.getResourceName(),
          message.getPartitionName());
      LOG.info("FINISH onBecomeOnlineFromOffline for " + message.getPartitionName() + " on "
          + manager.getInstanceName());

      int newSize;
      synchronized (_instanceList) {
        _instanceList.remove(_instanceList.size() - 1);
        newSize = _instanceList.size();
      }
      Assert.assertEquals(newSize, oldSize); // ensure nothing came in during this time
      _onlineLatch.countDown();
    }

    public void onBecomeOfflineFromOnline(Message message, NotificationContext context) {
      HelixManager manager = context.getManager();
      LOG.info("onBecomeOfflineFromOnline for " + message.getPartitionName() + " on "
          + manager.getInstanceName());
    }

    public void onBecomeDroppedFromOffline(Message message, NotificationContext context) {
      HelixManager manager = context.getManager();
      LOG.info("onBecomeDroppedFromOffline for " + message.getPartitionName() + " on "
          + manager.getInstanceName());
      _offlineLatch.countDown();
    }

    public void onBecomeOfflineFromError(Message message, NotificationContext context) {
      HelixManager manager = context.getManager();
      LOG.info("onBecomeOfflineFromError for " + message.getPartitionName() + " on "
          + manager.getInstanceName());
    }
  }

  public class PrefListTaskOnlineOfflineStateModelFactory
      extends StateModelFactory<PrefListTaskOnlineOfflineStateModel> {
    @Override
    public PrefListTaskOnlineOfflineStateModel createNewStateModel(String resource,
        String partitionName) {
      return new PrefListTaskOnlineOfflineStateModel();
    }
  }
}