text:
import pickle
import theano
import theano.tensor as T
from pylearn2.models import mlp
from pylearn2.training_algorithms import sgd
from pylearn2.training_algorithms.learning_rule import AdaGrad
from pylearn2.training_algorithms.learning_rule import Momentum
from pylearn2.training_algorithms.sgd import ExponentialDecay
from pylearn2.training_algorithms.sgd import LinearDecay
from pylearn2.training_algorithms.learning_rule import AdaDelta

from pylearn2.termination_criteria import EpochCounter
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.costs.cost import Cost
from pylearn2.costs.cost import DefaultDataSpecsMixin
import numpy as np
from random import randint
import os
import matplotlib.pyplot as plt
from features import logfbank

class XOR(DenseDesignMatrix):
    def __init__(self):
        self.class_names = ['0', '1']
        X = [[randint(0, 1), randint(0, 1)] for _ in range(1000)]
        y = []
        for a, b in X:
            if a + b == 1:
                y.append([0, 1])
            else:
                y.append([1, 0])
        X = np.array(X)
        y = np.array(y)
        super(XOR, self).__init__(X=X, y=y)

class NegativeLogLikelihoodCost(DefaultDataSpecsMixin, Cost):
    supervised = True

    def expr(self, model, data, **kwargs):
        space, source = self.get_data_specs(model)
        space.validate(data)

        inputs, targets = data

        outputs = model.fprop(inputs)

        loss = -(targets * T.log(outputs)).sum(axis=1)

        return loss.mean()

left_context = 10
right_context = 5
keywords = ["she", "had"]

def getDataForFrames(data, X, y):
    fbanks = data[0]
    segments = data[1]
    feat_cnt = len(fbanks[0])
    for start, end, class_id in segments:

        if randint(0, 1) == 0:
            for i in xrange(start, end):
                features = np.empty(0)
                for j in xrange(-left_context, right_context):
                    if i + j < 0 or i + j >= len(fbanks):
                        features = np.append(features, np.zeros(feat_cnt))
                    else:
                        features = np.append(features, fbanks[i + j])
                result = np.zeros(len(keywords) + 1)
                result[class_id] = 1.0

                X.append(features)
                y.append(result)

        if randint(0, 1) == 0:
            for i in xrange(start, end):
                features = np.empty(0)
                for j in xrange(-left_context, right_context):
                    if i + j < start or i + j >= end:
                        features = np.append(features, np.zeros(feat_cnt))
                    else:
                        features = np.append(features, fbanks[i + j])
                result = np.zeros(len(keywords) + 1)
                result[class_id] = 1.0

                X.append(features)
                y.append(result)

def getWindowedFeats(fbanks):
    X = []
    feat_cnt = len(fbanks[0])
    for i in xrange(len(fbanks)):
        features = np.empty(0)
        for j in xrange(-left_context, right_context):
            if i + j < 0 or i + j >= len(fbanks):
                features = np.append(features, np.zeros(feat_cnt))
            else:
                features = np.append(features, fbanks[i + j])
        X.append(features)
    return X

def getDataFromPath(path, maxFiles = 1e9):
    X = []
    y = []
    for file in os.listdir(path):
        maxFiles -= 1
        if maxFiles < 0:
            break
        data = np.load(path + "/" + file)
        getDataForFrames(data, X, y)

    X = np.array(X)
    y = np.array(y)

    return X, y

class SHEHAD(DenseDesignMatrix):
    feat_cnt = 0

    def __init__(self, path):
        self.class_names = ["she", "had", "filler"]
        X, y = getDataFromPath(path)
        # print X.shape
        self.feat_cnt = len(X[0])
        super(SHEHAD, self).__init__(X=X, y=y)

def test(model):
    X, y = getDataFromPath("/Users/evgeny/data/TEST")

    confusion = np.zeros([3, 3])

    ypred = np.log(model.fprop(theano.shared(np.array(X), name='inputs')).eval())

    cnt = np.zeros(3)

    for a, b in zip(ypred, y):
        pos = np.argmax(b)
        i = np.argmax(a)
        #for i in xrange(3):
        confusion[pos][i] += 1
        # cnt[pos] += 1

    for i in xrange(3):
        for j in xrange(3):
            print "%.0f" % confusion[i][j],
        print   # confusion[i][j] /= cnt[i]
    print confusion

# create hidden layer with 2 nodes, init weights in range -0.1 to 0.1 and add
# a bias with value 1

rng = 0.001

modelName = "2x128relu50epochs-v7-momentum.mdl"
debug = True

if debug or not os.path.exists(modelName):
    ds = SHEHAD("/Users/evgeny/data/TRAIN")
    vds = SHEHAD("/Users/evgeny/data/TEST")
    hidden_layer = mlp.RectifiedLinear(layer_name='hidden', dim=128, irange=0.001, init_bias=0)
    hidden_layer2 = mlp.RectifiedLinear(layer_name='hidden2', dim=128, irange=0.01, init_bias=0)
    hidden_layer3 = mlp.RectifiedLinear(layer_name='hidden3', dim=128, irange=0.01, init_bias=0)
    # create Softmax output layer
    output_layer = mlp.Softmax(3, 'output', irange=.1)
    # create Stochastic Gradient Descent trainer that runs for 400 epochs
    cost = NegativeLogLikelihoodCost()
    rule = Momentum(0.9)
    # rule = Momentum(0.9, True)
    # update_callbacks=ExponentialDecay(1 + 1e-5, 0.001)
    trainer = sgd.SGD(learning_rate=0.01, cost=cost,  batch_size=128, termination_criterion=EpochCounter(1000),
                      monitoring_dataset=vds, learning_rule=rule)
    layers = [hidden_layer, hidden_layer2, output_layer]
    # create neural net that takes two inputs
    ann = mlp.MLP(layers, nvis=ds.feat_cnt)

    trainer.setup(ann, ds)
    print trainer.cost
    # train neural net until the termination criterion is true

    iteration = 0

    while True:
        trainer.train(dataset=ds)
        ann.monitor.report_epoch()
        ann.monitor()
        if iteration % 10 == 0:
            if not debug:
                with open(modelName, 'wb') as f:
                    pickle.dump(ann, f)
        if not trainer.continue_learning(ann):
            break

        iteration += 1

    if not debug:
        with open(modelName, 'wb') as f:
            pickle.dump(ann, f)

else:
    with open(modelName) as f:
        ann = pickle.load(f)

#test(ann)

#exit(0)

window = 0.025
step = 0.01
nfilt = 40
fftsize = 512

def extractLogFBank(rate, sig):
    feats = logfbank(sig, rate, window, step, nfilt, fftsize, 0, None, 0)
    return feats

#sph2pipe = "/Users/evgeny/kaldi3/tools/sph2pipe_v2.5/sph2pipe"

#os.system(sph2pipe + " -f wav " + "SA1.WAV" + " tmp.wav")

def computeFile(model, path):
    # import extractFeats
    import scipy.io.wavfile as wav

    (rate, sig) = wav.read(path)

    fbanks = extractLogFBank(rate, sig)

    X = getWindowedFeats(fbanks)

    ypred = np.log(model.fprop(theano.shared(np.array(X), name='inputs')).eval())

    ypred = np.transpose(ypred)

    ig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True)
    ax1.plot(ypred[0])
    ax2.plot(ypred[1])
    ax3.plot(ypred[2])
    plt.show()

computeFile(ann, "tmp2.wav")


text:
/*
 * IteratorTypeDefJUnitTest.java
 *
 * Created on April 7, 2005, 12:40 PM
 */
package org.apache.geode.cache.query.functional;

import static org.junit.Assert.fail;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.cache.Region;
import org.apache.geode.cache.query.CacheUtils;
import org.apache.geode.cache.query.Query;
import org.apache.geode.cache.query.SelectResults;
import org.apache.geode.cache.query.data.Portfolio;
import org.apache.geode.test.junit.categories.OQLQueryTest;

@Category({OQLQueryTest.class})
public class IteratorTypeDefJUnitTest {

  @Before
  public void setUp() throws java.lang.Exception {
    CacheUtils.startCache();
    Region region = CacheUtils.createRegion("portfolios", Portfolio.class);
    for (int i = 0; i < 4; i++) {
      region.put("" + i, new Portfolio(i));
    }
    CacheUtils.log(region);
  }

  @After
  public void tearDown() throws java.lang.Exception {
    CacheUtils.closeCache();
  }

  @Test
  public void testIteratorDefSyntax() throws Exception {
    String queries[] = {
        "IMPORT org.apache.geode.cache.\"query\".data.Position;"
            + "SELECT DISTINCT secId FROM /portfolios,  positions.values pos TYPE Position WHERE iD > 0",
        "IMPORT org.apache.geode.cache.\"query\".data.Position;"
            + "SELECT DISTINCT secId FROM /portfolios, positions.values AS pos TYPE Position WHERE iD > 0",
        "IMPORT org.apache.geode.cache.\"query\".data.Position;"
            + "SELECT DISTINCT pos.secId FROM /portfolios, pos IN positions.values TYPE Position WHERE iD > 0",
        "SELECT DISTINCT pos.secId FROM /portfolios,  positions.values AS pos  WHERE iD > 0",
        "SELECT DISTINCT pos.secId FROM /portfolios, pos IN positions.values  WHERE iD > 0",};
    for (int i = 0; i < queries.length; i++) {
      Query q = null;
      try {
        q = CacheUtils.getQueryService().newQuery(queries[i]);
        Object r = q.execute();
      } catch (Exception e) {
        e.printStackTrace();
        fail(q.getQueryString());
      }
    }
    CacheUtils.log("TestCase:testIteratorDefSyntax PASS");
  }

  @Test
  public void testIteratorDefSyntaxForObtainingResultBag() throws Exception {
    String queries[] = {"IMPORT org.apache.geode.cache.\"query\".data.Position;"
        + "SELECT DISTINCT secId FROM /portfolios, (set<Position>)positions.values WHERE iD > 0",};
    for (int i = 0; i < queries.length; i++) {
      Query q = null;
      try {
        q = CacheUtils.getQueryService().newQuery(queries[i]);
        Object r = q.execute();
        if (!(r instanceof SelectResults))
          fail(
              "testIteratorDefSyntaxForObtainingResultBag: Test failed as obtained Result Data not an instance of SelectResults. Query= "
                  + q.getQueryString());
        if (((SelectResults) r).getCollectionType().allowsDuplicates())
          fail(
              "testIteratorDefSyntaxForObtainingResultBag: results of query should not allow duplicates, but says it does");
      } catch (Exception e) {
        e.printStackTrace();
        fail(q.getQueryString());
      }
    }
    CacheUtils.log("TestCase:testIteratorDefSyntaxForObtainingResultSet PASS");
  }

  @Test
  public void testNOValueconstraintInCreatRegion() throws Exception {
    CacheUtils.createRegion("pos", null);
    String queries[] = {"IMPORT org.apache.geode.cache.\"query\".data.Portfolio;"
        + "SELECT DISTINCT * FROM (set<Portfolio>)/pos where iD > 0"};
    for (int i = 0; i < queries.length; i++) {
      Query q = null;
      try {
        q = CacheUtils.getQueryService().newQuery(queries[i]);
        Object r = q.execute();
      } catch (Exception e) {
        e.printStackTrace();
        fail(q.getQueryString());
      }
    }
    CacheUtils.log("TestCase: testNOValueconstraintInCreatRegion PASS");
  }

  @Test
  public void testNOConstraintOnRegion() throws Exception {
    Region region = CacheUtils.createRegion("portfl", null);
    for (int i = 0; i < 4; i++) {
      region.put("" + i, new Portfolio(i));
    }
    CacheUtils.log(region);
    String queries[] = {"IMPORT org.apache.geode.cache.\"query\".data.Position;"
        + "IMPORT org.apache.geode.cache.\"query\".data.Portfolio;"
        + "SELECT DISTINCT secId FROM (set<Portfolio>)/portfl, (set<Position>)positions.values WHERE iD > 0",};
    for (int i = 0; i < queries.length; i++) {
      Query q = null;
      try {
        q = CacheUtils.getQueryService().newQuery(queries[i]);
        Object r = q.execute();
      } catch (Exception e) {
        e.printStackTrace();
        fail(q.getQueryString());
      }
    }
    CacheUtils.log("TestCase: testNOConstraintOnRegion PASS");
  }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __DRIVERS__FRAME_BUFFER_H
#define __DRIVERS__FRAME_BUFFER_H

#include <types_ext.h>

enum frame_buffer_bpp {
	FB_24BPP,
};

struct frame_buffer {
	size_t width;
	size_t height;
	size_t width_dpi;
	size_t height_dpi;
	enum frame_buffer_bpp bpp;
	void *base;
};

size_t frame_buffer_get_image_size(struct frame_buffer *fb, size_t width,
			size_t height);
void frame_buffer_clear(struct frame_buffer *fb, uint32_t color);
void frame_buffer_set_image(struct frame_buffer *fb, size_t xpos, size_t ypos,
			size_t width, size_t height, const void *image);

#endif /*__DRIVERS__FRAME_BUFFER_H*/


text:
layout: codex_page
title: Tools Development Know-how
permalink: /codex/tools_development_wisdom/tools_development_knowhow
codex_page_type: lvl2
nav_tag: knowhow
---

{% assign tools_development_knowhow = site.data.tools_development_knowhow | sort: 'caption' %}

{% for knowhow in tools_development_knowhow %}

{{knowhow.caption}}

by {{knowhow.author}}

{% endfor %}


text:
using System;

//Problem 11. Bitwise: Extract Bit #3

//    -Using bitwise operators, write an expression for finding the value of the bit #3 of a given unsigned integer.
//    -The bits are counted from right to left, starting from bit #0.
//    -The result of the expression should be either 1 or 0.

namespace _11.ExtractBit3
{
    class Program
    {
        static void Main()
        {
            Console.Write("Number: ");
            string input = Console.ReadLine();

            int number;
            bool isNumber = int.TryParse(input, out number);
            if (isNumber)
            {
                int position = 3;
                int mask = 1 << position;
                Console.WriteLine("Number");
                Console.WriteLine(Convert.ToString(number, 2).PadLeft(16, '0'));
                Console.WriteLine("Mask");
                Console.WriteLine(Convert.ToString(mask, 2).PadLeft(16, '0'));
                int nAndMask = number & mask;
                int bit = nAndMask >> position;
                Console.WriteLine("Bit: {0}", bit);
            }
            else
            {
                Console.WriteLine("Input string was not in a correct format");
            }

        }
    }
}


text:
package ch.ethz.inf.vs.californium.test.lockstep;

import static ch.ethz.inf.vs.californium.coap.CoAP.Code.GET;
import static ch.ethz.inf.vs.californium.coap.CoAP.Code.POST;
import static ch.ethz.inf.vs.californium.coap.CoAP.Code.PUT;
import static ch.ethz.inf.vs.californium.coap.CoAP.OptionRegistry.OBSERVE;
import static ch.ethz.inf.vs.californium.coap.CoAP.ResponseCode.CHANGED;
import static ch.ethz.inf.vs.californium.coap.CoAP.ResponseCode.CONTENT;
import static ch.ethz.inf.vs.californium.coap.CoAP.ResponseCode.CONTINUE;
import static ch.ethz.inf.vs.californium.coap.CoAP.Type.ACK;
import static ch.ethz.inf.vs.californium.coap.CoAP.Type.CON;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Random;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import ch.ethz.inf.vs.californium.coap.BlockOption;
import ch.ethz.inf.vs.californium.coap.CoAP.Code;
import ch.ethz.inf.vs.californium.coap.Request;
import ch.ethz.inf.vs.californium.coap.Response;
import ch.ethz.inf.vs.californium.network.CoAPEndpoint;
import ch.ethz.inf.vs.californium.network.Endpoint;
import ch.ethz.inf.vs.californium.network.EndpointManager.ClientMessageDeliverer;
import ch.ethz.inf.vs.californium.network.config.NetworkConfig;
import ch.ethz.inf.vs.californium.network.config.NetworkConfigDefaults;

/**
 * This test implements all examples from the blockwise draft 14 for a client.
 */
public class BlockwiseClientSide {

	private static boolean RANDOM_PAYLOAD_GENERATION = true;

	private LockstepEndpoint server;

	private Endpoint client;
	private int clientPort;

	private int mid = 8000;

	private String respPayload;
	private String reqtPayload;

	private ClientBlockwiseInterceptor clientInterceptor = new ClientBlockwiseInterceptor();

	@Before
	public void setupServer() throws IOException {
		System.out.println("\nStart "+getClass().getSimpleName());

		NetworkConfig config = new NetworkConfig()
			.setInt(NetworkConfigDefaults.MAX_MESSAGE_SIZE, 128)
			.setInt(NetworkConfigDefaults.DEFAULT_BLOCK_SIZE, 128)
			.setInt(NetworkConfigDefaults.ACK_TIMEOUT, 200) // client retransmits after 200 ms
			.setInt(NetworkConfigDefaults.ACK_RANDOM_FACTOR, 1);

		client = new CoAPEndpoint(new InetSocketAddress(0), config);
		client.setMessageDeliverer(new ClientMessageDeliverer());
		client.addInterceptor(clientInterceptor);
		client.start();
		clientPort = client.getAddress().getPort();
		System.out.println("Client binds to port "+clientPort);
	}

	@After
	public void shutdownServer() {
		System.out.println();
		client.destroy();
		System.out.println("End "+getClass().getSimpleName());
	}

	@Test
	public void test() throws Throwable {
		try {
			testGET();
			testGET2();
			testGETEarlyNegotion();
			testGETLateNegotionalLostACK();
			testSimpleAtomicBlockwisePUT();
			testAtomicBlockwisePOSTWithBlockwiseResponse();
			testRandomAccessGET();
			testObserveWithBlockwiseResponseEarlyNegotiation();
			testObserveWithBlockwiseResponse();

		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Make sure you did not forget a .go() at the end of a line.");
			throw e;
		} catch (Throwable t) {
			System.err.println(t);
			throw t;
		}
	}

	/**
	 * The first example shows a GET request that is split into three blocks.
	 * The server proposes a block size of 128, and the client agrees. The first
	 * two ACKs contain 128 bytes of payload each, and third ACK contains
	 * between 1 and 128 bytes.
	 *

	 * CLIENT                                                     SERVER
     * |                                                            |
     * | CON [MID=1234], GET, /status                       ------> |
     * |                                                            |
     * | <------   ACK [MID=1234], 2.05 Content, 2:0/1/128          |
     * |                                                            |
     * | CON [MID=1235], GET, /status, 2:1/0/128            ------> |
     * |                                                            |
     * | <------   ACK [MID=1235], 2.05 Content, 2:1/1/128          |
     * |                                                            |
     * | CON [MID=1236], GET, /status, 2:2/0/128            ------> |
     * |                                                            |
     * | <------   ACK [MID=1236], 2.05 Content, 2:2/0/128          |
     *

	 */
	private void testGET() throws Exception {
		System.out.println("Simple blockwise GET:");
		respPayload = generatePayload(300);
		String path = "test";
		server = createLockstepEndpoint();

		Request request = createRequest(GET, path);
		client.sendRequest(request);

		server.expectRequest(CON, GET, path).storeBoth("A").go();
		server.sendResponse(ACK, CONTENT).loadBoth("A").block2(0, true, 128).payload(respPayload.substring(0, 128)).go();
		server.expectRequest(CON, GET, path).storeBoth("B").block2(1, false, 128).go();
		server.sendResponse(ACK, CONTENT).loadBoth("B").block2(1, true, 128).payload(respPayload.substring(128, 256)).go();
		server.expectRequest(CON, GET, path).storeBoth("C").block2(2, false, 128).go();
		server.sendResponse(ACK, CONTENT).loadBoth("C").block2(2, false, 128).payload(respPayload.substring(256, 300)).go();

		Response response = request.waitForResponse(1000);
		Assert.assertNotNull("Client received no response", response);
		Assert.assertEquals("Client received wrong response code:", CONTENT, response.getCode());
		Assert.assertEquals("Client received wrong payload:", respPayload, response.getPayloadString());

		printServerLog();
	}

	private void testGET2() throws Exception {
		System.out.println("Simple blockwise GET:");
		respPayload = generatePayload(10);
		String path = "test";
		server = createLockstepEndpoint();

		Request request = createRequest(GET, path);
		client.sendRequest(request);

		server.expectRequest(CON, GET, path).storeMID("A").storeToken("B").go();
		server.sendEmpty(ACK).loadMID("A").go();
		Thread.sleep(50);
		server.sendResponse(CON, CONTENT).loadToken("B").payload(respPayload).mid(++mid).go();
		server.expectEmpty(ACK, mid).mid(mid).go(); // lost
		clientInterceptor.log(" // lost");
		server.sendResponse(CON, CONTENT).loadToken("B").payload(respPayload).mid(mid).go();
		server.expectEmpty(ACK, mid).mid(mid).go(); // lost

		Response response = request.waitForResponse(1000);
		Assert.assertNotNull("Client received no response", response);
		Assert.assertEquals("Client received wrong response code:", CONTENT, response.getCode());
		Assert.assertEquals("Client received wrong payload:", respPayload, response.getPayloadString());

		printServerLog();
	}

	/**
	 * In the second example, the client anticipates the blockwise transfer
	 * (e.g., because of a size indication in the link- format description
	 * [RFC6690]) and sends a size proposal. All ACK messages except for the
	 * last carry 64 bytes of payload; the last one carries between 1 and 64
	 * bytes.
	 *

	 * CLIENT                                                     SERVER
	 * |                                                          |
	 * | CON [MID=1234], GET, /status, 2:0/0/64           ------> |
	 * |                                                          |
	 * | <------   ACK [MID=1234], 2.05 Content, 2:0/1/64         |
	 * |                                                          |
	 * | CON [MID=1235], GET, /status, 2:1/0/64           ------> |
	 * |                                                          |
	 * | <------   ACK [MID=1235], 2.05 Content, 2:1/1/64         |
	 * :                                                          :
	 * :                          ...                             :
	 * :                                                          :
	 * | CON [MID=1238], GET, /status, 2:4/0/64           ------> |
	 * |                                                          |
	 * | <------   ACK [MID=1238], 2.05 Content, 2:4/1/64         |
	 * |                                                          |
	 * | CON [MID=1239], GET, /status, 2:5/0/64           ------> |
	 * |                                                          |
	 * | <------   ACK [MID=1239], 2.05 Content, 2:5/0/64         |
	 *

	 */
	private void testGETEarlyNegotion() throws Exception {
		System.out.println("Blockwise GET with early negotiation: (low priority for Cf client)");
		respPayload = generatePayload(350);
		String path = "test";
		server = createLockstepEndpoint();

		Request request = createRequest(GET, path);
		request.getOptions().setBlock2(BlockOption.size2Szx(64), false, 0);
		client.sendRequest(request);

		server.expectRequest(CON, GET, path).storeBoth("A").block2(0, false, 64).go();
		server.sendResponse(ACK, CONTENT).loadBoth("A").block2(0, true, 64).payload(respPayload.substring(0, 64)).go();
		server.expectRequest(CON, GET, path).storeBoth("B").block2(1, false, 64).go();
		server.sendResponse(ACK, CONTENT).loadBoth("B").block2(1, true, 64).payload(respPayload.substring(64, 128)).go();
		server.expectRequest(CON, GET, path).storeBoth("C").block2(2, false, 64).go();
		server.sendResponse(ACK, CONTENT).loadBoth("C").block2(2, true, 64).payload(respPayload.substring(128, 192)).go();
		server.expectRequest(CON, GET, path).storeBoth("D").block2(3, false, 64).go();
		server.sendResponse(ACK, CONTENT).loadBoth("D").block2(3, true, 64).payload(respPayload.substring(192, 256)).go();
		server.expectRequest(CON, GET, path).storeBoth("E").block2(4, false, 64).go();
		server.sendResponse(ACK, CONTENT).loadBoth("E").block2(4, true, 64).payload(respPayload.substring(256, 320)).go();
		server.expectRequest(CON, GET, path).storeBoth("F").block2(5, false, 64).go();
		server.sendResponse(ACK, CONTENT).loadBoth("F").block2(5, false, 64).payload(respPayload.substring(320, 350)).go();

		Response response = request.waitForResponse(1000);
		Assert.assertNotNull("Client received no response", response);
		Assert.assertEquals("Client received wrong response code:", CONTENT, response.getCode());
		Assert.assertEquals("Client received wrong payload:", respPayload, response.getPayloadString());

		printServerLog();
	}

	/**
	 *

	 * CLIENT                                                     SERVER
     * |                                                          |
     * | CON [MID=1234], GET, /status                     ------> |
     * |                                                          |
     * | <------   ACK [MID=1234], 2.05 Content, 2:0/1/128        |
     * |                                                          |
     * | CON [MID=1235], GET, /status, 2:2/0/64           ------> |
     * |                                                          |
     * | //////////////////////////////////tent, 2:2/1/64         |
     * |                                                          |
     * | (timeout)                                                |
     * |                                                          |
     * | CON [MID=1235], GET, /status, 2:2/0/64           ------> |
     * |                                                          |
     * | <------   ACK [MID=1235], 2.05 Content, 2:2/1/64         |
     * :                                                          :
     * :                          ...                             :
     * :                                                          :
     * | CON [MID=1238], GET, /status, 2:5/0/64           ------> |
     * |                                                          |
     * | <------   ACK [MID=1238], 2.05 Content, 2:5/0/64         |
     *

	 */
	private void testGETLateNegotionalLostACK() throws Exception {
		System.out.println("Blockwise GET with late negotiation and lost ACK:");
		respPayload = generatePayload(300);
		String path = "test";
		server = createLockstepEndpoint();

		Request request = createRequest(GET, path);
		client.sendRequest(request);

		server.expectRequest(CON, GET, path).storeBoth("A").go();
		server.sendResponse(ACK, CONTENT).loadBoth("A").block2(0, true, 128).payload(respPayload.substring(0, 128)).go();
		server.expectRequest(CON, GET, path).storeBoth("B").block2(1, false, 128).go();

		// We lose this ACK, and therefore the client retransmits the CON
		clientInterceptor.log(" // lost");
		server.expectRequest(CON, GET, path).storeBoth("C").block2(1, false, 128).go();
		Object[] req1 = (Object[]) server.get("B");
		Object[] req2 = (Object[]) server.get("C");
		Assert.assertEquals("Retramsmitted MID must be the same", req1[0], req2[0]);
		org.junit.Assert.assertArrayEquals(
				"Retramsmitted Token must be the same", (byte[]) req1[1], (byte[]) req2[1]);

		server.sendResponse(ACK, CONTENT).loadBoth("C").block2(1, true, 128).payload(respPayload.substring(128, 256)).go();
		server.expectRequest(CON, GET, path).storeBoth("D").block2(2, false, 128).go();
		server.sendResponse(ACK, CONTENT).loadBoth("D").block2(2, false, 128).payload(respPayload.substring(256, 300)).go();

		Response response = request.waitForResponse(1000);
		Assert.assertNotNull("Client received no response", response);
		Assert.assertEquals("Client received wrong response code:", CONTENT, response.getCode());
		Assert.assertEquals("Client received wrong payload:", respPayload, response.getPayloadString());

		printServerLog();
	}

	/**
	 * The following examples demonstrate a PUT exchange; a POST exchange looks
	 * the same, with different requirements on atomicity/idempotence. Note
	 * that, similar to GET, the responses to the requests that have a more bit
	 * in the request Block1 Option are provisional and carry the response code
	 * 2.31 (Continue); only the final response tells the client that the PUT
	 * did succeed.
	 *

	 * CLIENT                                                     SERVER
     * |                                                          |
     * | CON [MID=1234], PUT, /options, 1:0/1/128    ------>      |
     * |                                                          |
     * | <------   ACK [MID=1234], 2.31 Continue, 1:0/1/128       |
     * |                                                          |
     * | CON [MID=1235], PUT, /options, 1:1/1/128    ------>      |
     * |                                                          |
     * | <------   ACK [MID=1235], 2.31 Continue, 1:1/1/128       |
     * |                                                          |
     * | CON [MID=1236], PUT, /options, 1:2/0/128    ------>      |
     * |                                                          |
     * | <------   ACK [MID=1236], 2.04 Changed, 1:2/0/128        |
	 *

	 */
	private void testSimpleAtomicBlockwisePUT() throws Exception {
		System.out.println("Simple atomic blockwise PUT");
		reqtPayload = generatePayload(300);
		respPayload = generatePayload(50);
		String path = "test";
		server = createLockstepEndpoint();

		Request request = createRequest(PUT, path);
		request.setPayload(reqtPayload);
		client.sendRequest(request);

		server.expectRequest(CON, PUT, path).storeBoth("A").block1(0, true, 128).payload(reqtPayload.substring(0, 128)).go();
		server.sendResponse(ACK, CONTINUE).loadBoth("A").block1(0, true, 128).go();

		server.expectRequest(CON, PUT, path).storeBoth("B").block1(1, true, 128).payload(reqtPayload.substring(128, 256)).go();
		server.sendResponse(ACK, CONTINUE).loadBoth("B").block1(1, true, 128).go();

		server.expectRequest(CON, PUT, path).storeBoth("C").block1(2, false, 128).go();
		server.sendResponse(ACK, CHANGED).loadBoth("C").block1(2, false, 128).payload(respPayload).go();

		Response response = request.waitForResponse(1000);
		Assert.assertNotNull("Client received no response", response);
		Assert.assertEquals("Client received wrong response code:", CHANGED, response.getCode());
		Assert.assertEquals("Client received wrong payload:", respPayload, response.getPayloadString());

		printServerLog();
	}

	/**
	 * Block options may be used in both directions of a single exchange. The
	 * following example demonstrates a blockwise POST request, resulting in a
	 * separate blockwise response.
	 *

	 * CLIENT                                                     SERVER
     * |                                                              |
     * | CON [MID=1234], POST, /soap, 1:0/1/128      ------>          |
     * |                                                              |
     * | <------   ACK [MID=1234], 2.31 Continue, 1:0/1/128           |
     * |                                                              |
     * | CON [MID=1235], POST, /soap, 1:1/1/128      ------>          |
     * |                                                              |
     * | <------   ACK [MID=1235], 2.31 Continue, 1:1/1/128           |
     * |                                                              |
     * | CON [MID=1236], POST, /soap, 1:2/0/128      ------>          |
     * |                                                              |
     * | <------   ACK [MID=1236], 2.04 Changed, 2:0/1/128, 1:2/0/128 |
     * |                                                              |
     * | CON [MID=1237], POST, /soap, 2:1/0/128      ------>          |
     * |                                                              |
     * | <------   ACK [MID=1237], 2.04 Changed, 2:1/1/128            |
     * |                                                              |
     * | CON [MID=1238], POST, /soap, 2:2/0/128      ------>          |
     * |                                                              |
     * | <------   ACK [MID=1238], 2.04 Changed, 2:2/1/128            |
     * |                                                              |
     * | CON [MID=1239], POST, /soap, 2:3/0/128      ------>          |
     * |                                                              |
     * | <------   ACK [MID=1239], 2.04 Changed, 2:3/0/128            |
	 *

	 */
	private void testAtomicBlockwisePOSTWithBlockwiseResponse() throws Exception {
		System.out.println("Atomic blockwise POST with blockwise response:");
		reqtPayload = generatePayload(300);
		respPayload = generatePayload(500);
		String path = "test";
		server = createLockstepEndpoint();

		Request request = createRequest(POST, path);
		request.setPayload(reqtPayload);
		client.sendRequest(request);

		server.expectRequest(CON, POST, path).storeBoth("A").block1(0, true, 128).payload(reqtPayload.substring(0, 128)).go();
		server.sendResponse(ACK, CONTINUE).loadBoth("A").block1(0, true, 128).go();

		server.expectRequest(CON, POST, path).storeBoth("B").block1(1, true, 128).payload(reqtPayload.substring(128, 256)).go();
		server.sendResponse(ACK, CONTINUE).loadBoth("B").block1(1, true, 128).go();

		server.expectRequest(CON, POST, path).storeBoth("C").block1(2, false, 128).payload(reqtPayload.substring(256, 300)).go();
		server.sendResponse(ACK, CHANGED).loadBoth("C").block1(2, false, 128).block2(0, true, 128).payload(respPayload.substring(0, 128)).go();

		server.expectRequest(CON, POST, path).storeBoth("D").block2(1, false, 128).go();
		server.sendResponse(ACK, CHANGED).loadBoth("D").block2(1, true, 128).payload(respPayload.substring(128, 256)).go();

		server.expectRequest(CON, POST, path).storeBoth("E").block2(2, false, 128).go();
		server.sendResponse(ACK, CHANGED).loadBoth("E").block2(2, true, 128).payload(respPayload.substring(256, 384)).go();

		server.expectRequest(CON, POST, path).storeBoth("F").block2(3, false, 128).go();
		server.sendResponse(ACK, CHANGED).loadBoth("F").block2(3, false, 128).payload(respPayload.substring(384, 500)).go();

		Response response = request.waitForResponse(1000);
		Assert.assertNotNull("Client received no response", response);
		Assert.assertEquals("Client received wrong response code:", CHANGED, response.getCode());
		Assert.assertEquals("Client received wrong payload:", respPayload, response.getPayloadString());

		printServerLog();
	}

	private void testRandomAccessGET() throws Exception {
		System.out.println("TODO: Random access GET: (low priority for Cf client)");
		// TODO: has low priority
	}

	private void testObserveWithBlockwiseResponse() throws Exception {
		System.out.println("Observe sequence with blockwise response:");
		respPayload = generatePayload(300);
		String path = "test1";
		server = createLockstepEndpoint();

		Request request = createRequest(GET, path);
		request.setObserve();
		client.sendRequest(request);

		System.out.println("Establish observe relation to "+path);

		server.expectRequest(CON, GET, path).storeToken("At").storeMID("Am").observe(0).go();
		server.sendResponse(ACK, CONTENT).loadToken("At").loadMID("Am").observe(62350).block2(0, true, 128).payload(respPayload.substring(0, 128)).go();

		server.expectRequest(CON, GET, path).storeBoth("B").noOption(OBSERVE).block2(1, false, 128).go();
		server.sendResponse(ACK, CONTENT).loadBoth("B").block2(1, true, 128).payload(respPayload.substring(128, 256)).go();

		// TODO: Is is mandatory that token C is the same as B?
		server.expectRequest(CON, GET, path).storeBoth("C").noOption(OBSERVE).block2(2, false, 128).go();
		server.sendResponse(ACK, CONTENT).loadBoth("C").block2(2, false, 128).payload(respPayload.substring(256, 300)).go();

		Response response = request.waitForResponse(1000);
		Assert.assertNotNull("Client received no response", response);
		Assert.assertEquals("Client received wrong response code:", CONTENT, response.getCode());
		Assert.assertEquals("Client received wrong payload length", respPayload.length(), response.getPayloadSize());
		Assert.assertEquals("Client received wrong payload:", respPayload, response.getPayloadString());

		System.out.println("Send first notification");
		clientInterceptor.log("\n... time passes ...");
		respPayload = generatePayload(280);

		server.sendResponse(CON, CONTENT).loadToken("At").mid(++mid).observe(62354).block2(0, true, 128).payload(respPayload.substring(0, 128)).go();
		server.expectEmpty(ACK, mid).go();

		server.expectRequest(CON, GET, path).storeBoth("D").noOption(OBSERVE).block2(1, false, 128).go();
		server.sendResponse(ACK, CONTENT).loadBoth("D").block2(1, true, 128).payload(respPayload.substring(128, 256)).go();

		server.expectRequest(CON, GET, path).storeBoth("E").noOption(OBSERVE).block2(2, false, 128).go();
		server.sendResponse(ACK, CONTENT).loadBoth("E").block2(2, false, 128).payload(respPayload.substring(256, 280)).go();

		Response notification1 = request.waitForResponse(1000);
		Assert.assertNotNull("Client received first notification", notification1);
		Assert.assertEquals("Client received wrong notification code:", CONTENT, notification1.getCode());
		Assert.assertEquals("Client received wrong notification length", respPayload.length(), notification1.getPayloadSize());
		Assert.assertEquals("Client received wrong notification payload:", respPayload, notification1.getPayloadString());

		System.out.println("Send second notification");
		clientInterceptor.log("\n... time passes ...");
		respPayload = generatePayload(290);

		server.sendResponse(CON, CONTENT).loadToken("At").mid(++mid).observe(17).block2(0, true, 128).payload(respPayload.substring(0, 128)).go();
		server.expectEmpty(ACK, mid).go();

		server.expectRequest(CON, GET, path).storeBoth("F").noOption(OBSERVE).block2(1, false, 128).go();
		server.sendResponse(ACK, CONTENT).loadBoth("F").block2(1, true, 128).payload(respPayload.substring(128, 256)).go();

		server.expectRequest(CON, GET, path).storeBoth("G").noOption(OBSERVE).block2(2, false, 128).go();
		server.sendResponse(ACK, CONTENT).loadBoth("G").block2(2, false, 128).payload(respPayload.substring(256, 290)).go();

		Response notification2 = request.waitForResponse(1000);
		Assert.assertNotNull("Client received first notification", notification2);
		Assert.assertEquals("Client received wrong notification code:", CONTENT, notification2.getCode());
		Assert.assertEquals("Client received wrong notification length", respPayload.length(), notification2.getPayloadSize());
		Assert.assertEquals("Client received wrong notification payload:", respPayload, notification2.getPayloadString());

		printServerLog();
	}

	private void testObserveWithBlockwiseResponseEarlyNegotiation() throws Exception {
		System.out.println("TODO: Observe sequence with early negotiation: (low priority for Cf client)");
		// TODO: This is not really a problem for the Cf client because it has
		// no block size preference. We might only allow a developer to enforce
		// a specific block size but this currently has low priority.
	}

	private LockstepEndpoint createLockstepEndpoint() {
		try {
			LockstepEndpoint endpoint = new LockstepEndpoint();
			endpoint.setDestination(new InetSocketAddress(InetAddress.getByName("localhost"), clientPort));
			return endpoint;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private Request createRequest(Code code, String path) throws Exception {
		Request request = new Request(code);
		String uri = "coap://localhost:"+(server.getPort())+"/"+path;
		request.setURI(uri);
		return request;
	}

	private void printServerLog() {
		System.out.println(clientInterceptor.toString());
		clientInterceptor.clear();
	}

	private static String generatePayload(int length) {
		StringBuffer buffer = new StringBuffer();
		if (RANDOM_PAYLOAD_GENERATION) {
			Random rand = new Random();
			while(buffer.length() < length) {
				buffer.append(rand.nextInt());
			}
		} else { // Deterministic payload
			int n = 1;
			while(buffer.length() < length) {
				buffer.append(n++);
			}
		}
		return buffer.substring(0, length);
	}
}


text:
<config>
	<server>bigfix</server>
	<operator>
		<username>Extract</username>
		<password>Extract</password>
	</operator>
	<sites>
		<site>
			<name>MySite</name>
			<path>.\Output\MySite</path>
		</site>
	</sites>
</config>


text:
define(['jquery', 'backbone'], function($, Backbone){

var SettingsView = Backbone.View.extend({

		templateName: 'SettingsTemplate',

		subViews: [],

		initialize: function(options){
			this.isFaculty = options.page=='faculty';
			this.userid = options.userid;
			this.render();
		},

		render: function(){
			var template = _.template(Core.templates[this.templateName]);
			this.$el.html(template());
			$('#contactSettingsForm table td').eq(1).text(this.userid);
		},

		renderSettingsInfo: function(){

		},

		cleanUpEvents: function(){

		}
	});

	return SettingsView;

});


text:
<?php

use app\models\general\GeneralLabel;

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\RefPegawaiPerubatanRehabilitasi */

$this->title = GeneralLabel::updateTitle.' '.GeneralLabel::pegawai_perubatan_rehabilitasi.': ' . ' ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => GeneralLabel::pegawai_perubatan_rehabilitasi, 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = GeneralLabel::updateTitle;
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>


text:
package mirror;

import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;

public class IntegrationTest {

  static {
    LoggingConfig.init();
  }

  private static final Logger log = LoggerFactory.getLogger(IntegrationTest.class);
  private static final File integrationTestDir = new File("./build/IntegrationTest");
  private static final File root1 = new File(integrationTestDir, "root1");
  private static final File root2 = new File(integrationTestDir, "root2");
  private static int nextPort = 10_000;
  private Server rpc;
  private MirrorClient client;

  @Before
  public void clearFiles() throws Exception {
    deleteDirectory(integrationTestDir);
    integrationTestDir.mkdirs();
    root1.mkdirs();
    root2.mkdirs();
    // FileUtils.touch(new File(root1, ".watchmanconfig"));
    // FileUtils.touch(new File(root2, ".watchmanconfig"));
  }

  @After
  public void shutdown() throws Exception {
    // rpc.awaitTermination();
    if (client != null) {
      log.info("stopping client");
      client.stop();
    }
    if (rpc != null) {
      log.info("stopping server");
      rpc.shutdown();
    }
    rpc.shutdown();
    rpc.awaitTermination();
  }

  @Test
  public void testSimpleFile() throws Exception {
    startMirror();
    writeFile(new File(root1, "foo.txt"), "abc");
    sleep();
    assertThat(readFile(new File(root2, "foo.txt")), is("abc"));
  }

  @Test
  public void testSimpleDirectory() throws Exception {
    startMirror();
    new File(root1, "foo").mkdir();
    sleep();
    assertThat(new File(root2, "foo").exists(), is(true));
    assertThat(new File(root2, "foo").isDirectory(), is(true));
  }

  @Test
  public void testDeleteSimpleFile() throws Exception {
    // given a file that exists in both root1/root2
    writeFile(new File(root1, "foo.txt"), "abc");
    writeFile(new File(root2, "foo.txt"), "abc");
    startMirror();
    // when one file is deleted
    new File(root1, "foo.txt").delete();
    sleep();
    // then it's also deleted remotely
    assertThat(new File(root2, "foo.txt").exists(), is(false));
  }

  @Test
  public void testRestoreSimpleFile() throws Exception {
    // given a file that exists in both root1/root2
    writeFile(new File(root1, "foo.txt"), "abc");
    writeFile(new File(root2, "foo.txt"), "abc");
    startMirror();
    // when one file is moved out of the tree
    File fooOriginal = new File(root1, "foo.txt");
    File fooBuild = new File("./build", "foo.txt");
    move(fooOriginal.toString(), fooBuild.toString());
    sleep();
    // then it's also deleted remotely
    assertThat(new File(root2, "foo.txt").exists(), is(false));
    // then when its moved back
    move(fooBuild.toString(), fooOriginal.toString());
    sleep();
    // then it's also restored remotely
    assertThat(new File(root2, "foo.txt").exists(), is(true));
    assertThat(readFile(new File(root1, "foo.txt")), is("abc"));
    assertThat(readFile(new File(root2, "foo.txt")), is("abc"));
  }

  @Test
  public void testDeleteDirectory() throws Exception {
    // given a file within a directory that exists in both root1/root2
    for (File root : new File[] { root1, root2 }) {
      new File(root, "dir").mkdir();
      writeFile(new File(root, "dir/foo.txt"), "abc");
    }
    startMirror();
    // when the directory is deleted
    deleteDirectory(new File(root1, "dir"));
    sleep();
    // then the child was also deleted
    assertThat(new File(root2, "dir/foo.txt").exists(), is(false));
  }

  @Test
  public void testDeleteDirectoryThatWasJustCreated() throws Exception {
    // given no files exist on either side
    startMirror();
    // and after starting some files were created on root1
    writeFile(new File(root1, "dir/foo.txt"), "abc");
    sleep();
    // and they were synced to root2
    assertThat(new File(root2, "dir/foo.txt").exists(), is(true));
    // when the directory is are deleted from root1
    deleteDirectory(new File(root1, "dir"));
    sleep();
    // then the directory is deleted from root2 as well
    assertThat(new File(root2, "dir").exists(), is(false));
  }

  @Test
  public void testCreateNestedFile() throws Exception {
    startMirror();
    // given a file that is created in a sub directory
    new File(root1, "dir").mkdir();
    writeFile(new File(root1, "dir/foo.txt"), "abc");
    sleep();
    // then it's copied remotely
    assertThat(readFile(new File(root2, "dir/foo.txt")), is("abc"));
  }

  @Test
  public void testCreateExecutableFile() throws Exception {
    // given a file that is executable
    writeFile(new File(root1, "foo.sh"), "abc");
    NativeFileAccessUtils.setExecutable(root1.toPath().resolve("foo.sh"));
    startMirror();
    sleep();
    // then it's copied remotely
    assertThat(readFile(new File(root2, "foo.sh")), is("abc"));
    // and made executable
    assertThat(NativeFileAccessUtils.isExecutable(root2.toPath().resolve("foo.sh")), is(true));
  }

  @Test
  public void testTwoWay() throws Exception {
    startMirror();
    // given a root1 change
    writeFile(new File(root1, "foo.txt"), "abc");
    sleep();
    // and it is replicated to root2
    assertThat(readFile(new File(root2, "foo.txt")), is("abc"));
    // and it then changes on root2
    writeFile(new File(root2, "foo.txt"), "abcd");
    sleep();
    // then it is also replicated back to root1
    assertThat(readFile(new File(root1, "foo.txt")), is("abcd"));
  }

  @Test
  public void testSeveralFilesFromServerToClient() throws Exception {
    startMirror();
    // given a root1 change
    int i = 0;
    for (; i < 100; i++) {
      writeFile(new File(root2, "foo" + i + ".txt"), "abc");
    }
    sleep();
    sleep();
    // and it is replicated to root2
    assertThat(readFile(new File(root1, "foo0.txt")), is("abc"));
    assertThat(readFile(new File(root1, "foo" + (i - 1) + ".txt")), is("abc"));
  }

  @Test
  public void testFileSymlinks() throws Exception {
    // given a file that exists in both remotes
    writeFile(new File(root1, "foo.txt"), "abc");
    writeFile(new File(root2, "foo.txt"), "abc");
    startMirror();
    // when a symlink is created on root1
    Files.createSymbolicLink(root1.toPath().resolve("foo2"), Paths.get("foo.txt"));
    sleep();
    // then it is replicated to root2 as a symlink
    assertThat(Files.readSymbolicLink(root2.toPath().resolve("foo2")).toString(), is("foo.txt"));
    assertThat(readFile(new File(root2, "foo2")), is("abc"));
  }

  @Test
  public void testFileSymlinksThatAreUpdatedAfterInitialSync() throws Exception {
    // given a file that exists in both remotes, and has a symlink to it
    for (File root : new File[] { root1, root2 }) {
      writeFile(new File(root, "foo1.txt"), "abc1");
      writeFile(new File(root, "foo2.txt"), "abc2");
      Files.createSymbolicLink(new File(root, "foo").toPath(), Paths.get("foo1.txt"));
    }
    sleep();
    startMirror();
    sleep();
    // when the symlink is updated on root1
    new File(root1, "foo").delete();
    Files.createSymbolicLink(root1.toPath().resolve("foo"), Paths.get("foo2.txt"));
    sleep();
    // then it is replicated to root2 as a symlink
    assertThat(Files.readSymbolicLink(root2.toPath().resolve("foo")).toString(), is("foo2.txt"));
    assertThat(readFile(new File(root2, "foo")), is("abc2"));
  }

  @Test
  public void testFileSymlinksThatAreUpdatedDuringInitialSync() throws Exception {
    // given a file that exists in both remotes, and has a symlink to it
    for (File root : new File[] { root1, root2 }) {
      writeFile(new File(root, "foo1.txt"), "abc1");
      writeFile(new File(root, "foo2.txt"), "abc2");
    }
    // and root1 has a symlink to foo1
    Files.createSymbolicLink(new File(root1, "foo").toPath(), Paths.get("foo1.txt"));
    // and root2 has a symlink to foo2 which is newer
    Thread.sleep(1000);
    Files.createSymbolicLink(new File(root2, "foo").toPath(), Paths.get("foo2.txt"));
    // when we start
    startMirror();
    sleep();
    // then we update the link on root1
    assertThat(Files.readSymbolicLink(root1.toPath().resolve("foo")).toString(), is("foo2.txt"));
  }

  @Test
  public void testFileSymlinksThatAreAbsolutePaths() throws Exception {
    // given a file that exists in both remotes
    writeFile(new File(root1, "foo.txt"), "abc");
    writeFile(new File(root2, "foo.txt"), "abc");
    startMirror();
    // when a symlink is created on root1
    Files.createSymbolicLink(root1.toPath().resolve("foo2"), root1.toPath().resolve("foo.txt").toAbsolutePath());
    sleep();
    // then it is replicated to root2 as a symlink
    assertThat(Files.readSymbolicLink(root2.toPath().resolve("foo2")).toString(), is("foo.txt"));
    assertThat(readFile(new File(root2, "foo2")), is("abc"));
  }

  @Test
  public void testFileSymlinksToADifferentDirectory() throws Exception {
    // given a file in a/ that exists in both remotes
    for (File root : new File[] { root1, root2 }) {
      new File(root, "a").mkdir();
      new File(root, "b").mkdir();
      writeFile(new File(root, "a/foo.txt"), "abc");
    }
    startMirror();
    // when a symlink to b/ is created on root1
    Files.createSymbolicLink(root1.toPath().resolve("b/foo2"), Paths.get("../a/foo.txt"));
    sleep();
    // then it is replicated to root2 as a symlink
    assertThat(Files.readSymbolicLink(root2.toPath().resolve("b/foo2")).toString(), is("../a/foo.txt"));
    assertThat(readFile(new File(root2, "b/foo2")), is("abc"));
  }

  @Test
  public void testDirectorySymlinks() throws Exception {
    // given a file that exists in both remotes
    writeFile(new File(root1, "a/foo.txt"), "abc");
    writeFile(new File(root2, "a/foo.txt"), "abc");
    startMirror();
    // when a symlink for it's directory is created on root1
    Files.createSymbolicLink(root1.toPath().resolve("b"), Paths.get("a"));
    sleep();
    // then it is replicated to root2 as a symlink
    assertThat(Files.readSymbolicLink(root2.toPath().resolve("b")).toString(), is("a"));
    assertThat(readFile(new File(root2, "b/foo.txt")), is("abc"));
  }

  @Test
  public void testInitialSyncDirectorySymlinkFromServerToClient() throws Exception {
    // given a file that exists in both remotes
    writeFile(new File(root1, "a/foo.txt"), "abc");
    writeFile(new File(root2, "a/foo.txt"), "abc");
    // and it is also symlinked on root1
    new File(root1, "b").mkdir();
    Files.createSymbolicLink(new File(root1, "b/foo.txt").toPath(), new File(root1, "a/foo.txt").getAbsoluteFile().toPath());
    // when mirror is started
    startMirror();
    sleep();
    // then the symlink is replicated to root2
    assertThat(Files.readSymbolicLink(root2.toPath().resolve("b/foo.txt")).toString(), is("../a/foo.txt"));
    assertThat(readFile(new File(root2, "b/foo.txt")), is("abc"));
  }

  @Test
  public void testInitialSyncDirectorySymlinkFromClientToServer() throws Exception {
    // given a file that exists in both remotes
    writeFile(new File(root1, "a/foo.txt"), "abc");
    writeFile(new File(root2, "a/foo.txt"), "abc");
    // and it is also symlinked on root2
    Files.createSymbolicLink(new File(root2, "b").toPath(), new File(root2, "a/foo.txt").getAbsoluteFile().toPath());
    // when mirror is started
    startMirror();
    sleep();
    // then the symlink is replicated to root1
    assertThat(Files.readSymbolicLink(root1.toPath().resolve("b")).toString(), is("a/foo.txt"));
    assertThat(readFile(new File(root1, "b")), is("abc"));
  }

  @Test
  public void testInitialSyncMissingFileFromServerToClient() throws Exception {
    // given root1 has an existing file
    writeFile(new File(root1, "foo.txt"), "abc");
    // when mirror is started
    startMirror();
    sleep();
    // then the file is created in root2
    assertThat(readFile(new File(root2, "foo.txt")), is("abc"));
  }

  @Test
  public void testInitialSyncMissingFileFromClientToServer() throws Exception {
    // given root2 has an existing file
    writeFile(new File(root2, "foo.txt"), "abc");
    // when mirror is started
    startMirror();
    sleep();
    // then the file is created in root1
    assertThat(readFile(new File(root1, "foo.txt")), is("abc"));
  }

  @Test
  public void testInitialSyncStaleFileFromServerToClient() throws Exception {
    // given both roots have an existing file
    writeFile(new File(root1, "foo.txt"), "abc");
    writeFile(new File(root2, "foo.txt"), "abcd");
    // and root1's file is newer
    new File(root1, "foo.txt").setLastModified(2000);
    new File(root2, "foo.txt").setLastModified(1000);
    // when mirror is started
    startMirror();
    sleep();
    // then the file is updated in root2
    assertThat(readFile(new File(root2, "foo.txt")), is("abc"));
  }

  @Test
  public void testInitialSyncStaleFileFromClientToServer() throws Exception {
    // given both roots have an existing file
    writeFile(new File(root1, "foo.txt"), "abc");
    writeFile(new File(root2, "foo.txt"), "abcd");
    // and root2's file is newer
    new File(root1, "foo.txt").setLastModified(2000);
    new File(root2, "foo.txt").setLastModified(3000);
    // when mirror is started
    startMirror();
    sleep();
    // then the file is updated in root1
    assertThat(readFile(new File(root1, "foo.txt")), is("abcd"));
  }

  @Test
  public void testSkipIgnoredDirectories() throws Exception {
    // given a file that exists within an ignored directory
    writeFile(new File(root1, "target/foo.txt"), "abc");
    // when mirror is started
    startMirror();
    sleep();
    // then it is not replicated to root2
    assertThat(new File(root2, "target/foo.txt").exists(), is(false));
  }

  @Test
  public void testIncludeWithinExcludedDirectories() throws Exception {
    // given a file that exists within an included directory
    writeFile(new File(root1, "tmp/src_managed/foo.txt"), "abc");
    // when mirror is started
    startMirror();
    sleep();
    // then it is replicated to root2
    assertThat(new File(root2, "tmp/src_managed/foo.txt").exists(), is(true));
  }

  @Test
  public void testIncludeWithPatternWithinExcludedDirectories() throws Exception {
    // given a file that exists within an included directory
    writeFile(new File(root1, "target/foo/includedDirectory/foo.txt"), "abc");
    // when mirror is started
    startMirror();
    sleep();
    // then it is replicated to root2
    assertThat(new File(root2, "target/foo/includedDirectory/foo.txt").exists(), is(true));
  }

  @Test
  public void testDontRecurseIntoSymlink() throws Exception {
    // given that both roots have a symlink from src to target
    Files.createSymbolicLink(root1.toPath().resolve("src"), Paths.get("target"));
    // and target only exists on root1
    new File(root1, "target").mkdirs();
    writeFile(new File(root1, "target/output"), "output");
    // when mirror is started
    startMirror();
    sleep();
    // then the symlink on root1 works
    assertThat(readFile(new File(root1, "src/output")), is("output"));
    // but we didn't copy it over to root2
    assertThat(new File(root2, "src/output").exists(), is(false));
  }

  @Test
  public void testSymlinkThatIsNowARealPath() throws Exception {
    // given that root2 thought src was a symlink
    Files.createSymbolicLink(root2.toPath().resolve("src"), Paths.get("target"));
    NativeFileAccessUtils.setModifiedTimeForSymlink(root2.toPath().resolve("src"), 1000);
    // but now on root1 it's actually a real directory
    new File(root1, "src").mkdir();
    writeFile(new File(root1, "src/foo.txt"), "foo");
    new File(root1, "src/foo.txt").setLastModified(2000);
    // when mirror is started
    startMirror();
    sleep();
    // then root2's src directory is not a real path
    assertThat(Files.isSymbolicLink(root2.toPath().resolve("src")), is(false));
    // and root1 stays a real patha s well
    assertThat(Files.isSymbolicLink(root1.toPath().resolve("src")), is(false));
  }

  @Test
  public void testRealPathThatIsNowASymlink() throws Exception {
    // given that root2 thought src was a real path
    new File(root2, "src").mkdir();
    writeFile(new File(root2, "src/foo.txt"), "foo");
    sleep();
    // but now it's a symlink
    Files.createSymbolicLink(root1.toPath().resolve("src"), Paths.get("target"));
    // when mirror is started
    startMirror();
    sleep();
    // then root2's src directory is not a real path
    assertThat(Files.isSymbolicLink(root2.toPath().resolve("src")), is(true));
  }

  @Test
  public void testRespectsGitIgnoreFile() throws Exception {
    // given that root1 has a .gitignore file
    writeFile(new File(root1, ".gitignore"), "foo.txt");
    // and a file that would be ignored
    writeFile(new File(root1, "foo.txt"), "foo");
    // when mirror is started
    startMirror();
    sleep();
    // then we don't sync it
    assertThat(new File(root2, "foo.txt").exists(), is(false));
  }

  @Test
  public void testRespectsGitIgnoreFileInNestedDirectories() throws Exception {
    // given that root1 has a .gitignore file
    writeFile(new File(root1, "foo/.gitignore"), "dir1/*");
    // and a file that would be ignored
    writeFile(new File(root1, "foo/dir1/foo.txt"), "foo");
    // when mirror is started
    startMirror();
    sleep();
    // then we don't sync it
    assertThat(new File(root2, "foo/dir1/foo.txt").exists(), is(false));
  }

  @Test
  public void testUpdateFileThatWasMarkedReadOnlyByCodeGenerator() throws Exception {
    // given two files exist
    writeFile(new File(root1, "foo.txt"), "abc1");
    writeFile(new File(root2, "foo.txt"), "abc2");
    // and root1's file is newer
    new File(root1, "foo.txt").setLastModified(2000);
    new File(root2, "foo.txt").setLastModified(1000);
    // but root2's file is read only (e.g. due to overzealous code generators marking it read-only)
    NativeFileAccessUtils.setReadOnly(new File(root2, "foo.txt").toPath());
    // when mirror is started
    startMirror();
    sleep();
    // then we can successfully update root2
    assertThat(readFile(new File(root2, "foo.txt")), is("abc1"));
  }

  @Test
  public void testSimpleFileThatIsEmpty() throws Exception {
    startMirror();
    writeFile(new File(root1, "foo.txt"), "");
    sleep();
    assertThat(readFile(new File(root2, "foo.txt")), is(""));
  }

  private void startMirror() throws Exception {
    // server
    int port = nextPort++;
    TaskFactory serverTaskFactory = new ThreadBasedTaskFactory();
    FileWatcherFactory watcherFactory = FileWatcherFactory.newFactory(serverTaskFactory);
    FileAccessFactory accessFactory = new NativeFileAccessFactory();
    MirrorServer server = new MirrorServer(serverTaskFactory, accessFactory, watcherFactory);
    // rpc = NettyServerBuilder.forPort(port).addService(server).build();
    rpc = InProcessServerBuilder.forName("mirror" + port).addService(server).build();
    rpc.start();
    log.info("started server");
    // client
    PathRules includes = new PathRules("includedDirectory");
    PathRules excludes = new PathRules("target/");
    // ChannelFactory cf = () -> NettyChannelBuilder.forAddress("localhost", port).negotiationType(NegotiationType.PLAINTEXT).build();
    ChannelFactory cf = () -> InProcessChannelBuilder.forName("mirror" + port).build();
    TaskFactory clientTaskFactory = new ThreadBasedTaskFactory();
    client = new MirrorClient(//
      new MirrorPaths(root2.toPath(), root1.toPath(), includes, excludes, false, new ArrayList<>()),
      clientTaskFactory,
      new ConnectionDetector.Impl(cf),
      watcherFactory,
      new NativeFileAccess(root2.toPath().toAbsolutePath()),
      cf);
    client.startSession();
    log.info("started client");
  }

  private static void sleep() throws InterruptedException {
    Thread.sleep(1500);
  }
}


text:
package org.jruby.java.invokers;

import java.lang.reflect.Field;
import org.jruby.RubyModule;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;

public class StaticFieldGetter extends FieldMethodZero {

    public StaticFieldGetter(String name, RubyModule host, Field field) {
        super(name, host, field);
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name) {
        try {
            return JavaUtil.convertJavaToUsableRubyObject(context.getRuntime(), field.get(null));
        } catch (IllegalAccessException iae) {
            throw context.getRuntime().newTypeError("illegal access getting variable: " + iae.getMessage());
        }
    }
}


text:
require "rails_helper"

RSpec.describe ApplicationController do
  it "works" do
  end
end


text:
restify-example
===============

An example Restify web service


text:
<?php

/**
 *
 * @author  Joel Hart @mediotype
 */
class Mediotype_EnhancedEcommerce_Block_Checkout_AfterSuccessMulti extends Mage_Core_Block_Template
{

    /**
     * Returns customer's placed orders in a multi shipping senario
     *
     * @return Mage_Sales_Model_Order
     */
    public function getOrders()
    {
        $ids = Mage::getSingleton('core/session')->getOrderIds(true);

        $orders = array();
        if ($ids && is_array($ids)) {
            foreach ($ids as $id => $incrementalId) {
                /** @var $orders[] Mage_Sales_Model_Order */
                $orders[] = Mage::getModel('sales/order')->load($id);
            }
            return $orders;
        }
        return false;
    }

    /**
     * Returns data to send to Google Analytics
     *
     * @param $order Mage_Sales_Model_Order
     *
     * @return Varien_Object
     */
    public function getTotals($order)
    {

        $totals = new Varien_Object();
        $totals->setData('amount', number_format($order->getGrandTotal(), 2,'.',''));
        $totals->setData('tax', number_format($order->getBaseTaxAmount(), 2,'.',''));
        $totals->setData('shipping', number_format($order->getShippingAmount(), 2,'.',''));

        return $totals;
    }

    /**
     * Returns all items in the order
     *
     * @param $order Mage_Sales_Model_Order
     *
     * @return array
     */
    public function getItems($order)
    {
        $items = $order->getAllItems();
        return $items;
    }

    protected function _toHtml()
    {
        //check to make sure ee is enabled
        if($this->getMediotypeEEHelper()->getEnabled()) {
            return parent::_toHtml();
        }
        return '';
    }

    public function getMediotypeEEHelper()
    {
        return Mage::helper('mediotype_ee');
    }
}


text:
"""Unit tests for learning_rate.py."""

from absl.testing import absltest
import ml_collections
from scenic.train_lib_deprecated import lr_schedules
import tensorflow as tf

class LearningRateTest(absltest.TestCase):
  """Tests different learning rate schedules ."""

  def test_constant(self):
    """Test constant schedule works correctly."""
    config = ml_collections.ConfigDict(
        dict(
            lr_configs={
                'learning_rate_schedule': 'compound',
                'factors': 'constant',
                'base_learning_rate': .1,
            }))
    lr_fn = lr_schedules.get_learning_rate_fn(config)
    config = config.lr_configs
    for step in range(400):
      expected_learning_rate = config.base_learning_rate
      self.assertAlmostEqual(lr_fn(step), expected_learning_rate)

  def test_constant_linear_warmup(self):
    """Test that linear warmup schedule works correctly."""
    warmup_steps = 100
    warmup_alpha = 0.1
    config = ml_collections.ConfigDict(
        dict(
            lr_configs={
                'learning_rate_schedule': 'compound',
                'factors': 'constant*linear_warmup',
                'base_learning_rate': 1.0,
                'warmup_steps': warmup_steps,
                'warmup_alpha': warmup_alpha
            }))
    lr_fn = lr_schedules.get_learning_rate_fn(config)
    for step in range(400):
      if step == 0:
        self.assertEqual(lr_fn(step), warmup_alpha)
      if step > 0 and step < warmup_steps:
        self.assertGreater(lr_fn(step), lr_fn(step - 1))
      if step >= warmup_steps:
        self.assertEqual(lr_fn(step), 1.0)

  def test_polynomial_decay(self):
    """Test polynomial schedule works correctly."""
    config = ml_collections.ConfigDict(
        dict(
            lr_configs={
                'learning_rate_schedule': 'compound',
                'factors': 'constant*polynomial',
                'decay_steps': 200,
                'power': 2.0,
                'base_learning_rate': .1,
                'end_factor': .01
            }))
    lr_fn = lr_schedules.get_learning_rate_fn(config)
    config = config.lr_configs
    tf_polynomial_decay = tf.keras.optimizers.schedules.PolynomialDecay(
        initial_learning_rate=config['base_learning_rate'],
        decay_steps=config['decay_steps'],
        end_learning_rate=config['end_factor'] * config['base_learning_rate'],
        power=config['power'])
    for step in range(400):
      expected_learning_rate = tf_polynomial_decay(step=step).numpy()
      self.assertAlmostEqual(lr_fn(step), expected_learning_rate)

  def test_cosine_decay(self):
    """Test cosine schedule works correctly."""
    config = ml_collections.ConfigDict(
        dict(
            lr_configs={
                'learning_rate_schedule': 'compound',
                'factors': 'cosine_decay',
                'steps_per_cycle': 100,
                't_mul': 2.,
                'm_mul': .5,
                'alpha': 0.3,
                'base_learning_rate': 1.,
            }))
    lr_fn = lr_schedules.get_learning_rate_fn(config)
    config = config.lr_configs
    tf_cosine_decay = tf.keras.experimental.CosineDecayRestarts(
        initial_learning_rate=config['base_learning_rate'],
        first_decay_steps=config['steps_per_cycle'],
        t_mul=config['t_mul'],
        m_mul=config['m_mul'],
        alpha=config['alpha'],
    )
    for step in range(400):
      expected_learning_rate = tf_cosine_decay(step=step).numpy()
      self.assertAlmostEqual(lr_fn(step), expected_learning_rate)

if __name__ == '__main__':
  absltest.main()


text:
package com.graphhopper.routing;

import com.graphhopper.routing.util.FlagEncoder;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.Graph;
import com.graphhopper.util.EdgeIterator;

/**
 * This class creates a Path from a DijkstraOneToMany algorithm
 *
 * @author Peter Karich
 */
public class PathNative extends Path {
    private final int[] parentNodes;
    private final int[] parentEdges;

    public PathNative(Graph g, Weighting weighting, int[] parentNodes, int[] parentEdges) {
        super(g, weighting);
        this.parentNodes = parentNodes;
        this.parentEdges = parentEdges;
    }

    @Override
    public Path extract() {
        if (endNode < 0)
            return this;

        int prevEdge = EdgeIterator.NO_EDGE;
        while (true) {
            int edgeId = parentEdges[endNode];
            if (!EdgeIterator.Edge.isValid(edgeId))
                break;

            processEdge(edgeId, endNode, prevEdge);
            prevEdge = edgeId;
            endNode = parentNodes[endNode];
        }
        reverseOrder();
        return setFound(true);
    }
}


text:
package gov.nih.nci.cagrid.opensaml;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.xml.namespace.QName;

import org.w3c.dom.*;

/**
 * Represents a SAML authorization decision statement.
 *
 * @author      Helen Rehn, Scott Cantor
 * @created     September 23, 2002
 */

public class SAMLAuthorizationDecisionStatement extends SAMLSubjectStatement implements Cloneable {

    protected String resource = null;
    protected String decision = null;
    protected ArrayList actions = new ArrayList();
    protected ArrayList evidence = new ArrayList();

    /**
     *  Default constructor
     */
    public SAMLAuthorizationDecisionStatement() {
    }

    /**
     *  Builds an AuthorizationDecisionStatement out of its component parts
     *
     * @param  subject     subject of the statement
     * @param  resource    URI of the resource being accessed at the time of
     *                           the statement
     * @param  actions     specific actions the decision applies to, must be SAMLAction objects
     * @param  evidence    evidence which may be considered, must be String or SAMLAssertion objects
     * @exception  SAMLException  Raised if an AuthorizationDecisionStatement
     *             cannot be constructed from the supplied information
     */
    public SAMLAuthorizationDecisionStatement(
            SAMLSubject subject,
            String resource,
            String decision,
            Collection actions,
            Collection evidence
            ) throws SAMLException {

        super(subject);

        this.resource = XML.assign(resource);
        this.decision = XML.assign(decision);

        if (actions != null) {
            for (Iterator i=actions.iterator(); i.hasNext(); )
                this.actions.add(((SAMLAction)i.next()).setParent(this));
        }

        if (evidence != null) {
            for (Iterator i=evidence.iterator(); i.hasNext(); ) {
                Object o = i.next();
                if (o instanceof SAMLAssertion)
                    this.evidence.add(((SAMLAssertion)o).setParent(this));
                else if (o instanceof String && ((String)o).length() > 0)
                    this.evidence.add(o);
            }
        }
    }

    /**
     *  Reconstructs a statement from a DOM tree
     *
     * @param  e                  The root of a DOM tree
     * @exception  SAMLException  Thrown if the object cannot be constructed
     */
    public SAMLAuthorizationDecisionStatement(Element e) throws SAMLException {
        fromDOM(e);
    }

    /**
     *  Reconstructs a statement from a stream
     *
     * @param  in                   A stream containing XML
     * @exception  SAMLException  Raised if an exception occurs while constructing
     *                              the object.
     */
    public SAMLAuthorizationDecisionStatement(InputStream in) throws SAMLException {
        fromDOM(fromStream(in));
    }

    /**
     * @see gov.nih.gov.nih.nci.cagrid.opensaml.SAMLObject#fromDOM(org.w3c.dom.Element)
     */
    public void fromDOM(Element e) throws SAMLException {
        super.fromDOM(e);

        if (config.getBooleanProperty("gov.nih.nci.cagrid.opensaml.strict-dom-checking") && !XML.isElementNamed(e,XML.SAML_NS,"AuthorizationDecisionStatement"))
        {
            QName q = XML.getQNameAttribute(e, XML.XSI_NS, "type");
            if (!XML.isElementNamed(e,XML.SAML_NS,"Statement") || !XML.isElementNamed(e,XML.SAML_NS,"SubjectStatement") ||
                q == null || !XML.SAML_NS.equals(q.getNamespaceURI()) || !"AuthorizationDecisionStatementType".equals(q.getLocalPart()))
                throw new MalformedException(SAMLException.REQUESTER, "SAMLAuthorizationDecisionStatement.fromDOM() requires saml:AuthorizationDecisionStatement at root");
        }

        resource = XML.assign(e.getAttributeNS(null, "Resource"));
        decision = XML.assign(e.getAttributeNS(null, "Decision"));

        Element n = XML.getFirstChildElement(e, XML.SAML_NS, "Action");
        while (n != null) {
            actions.add(new SAMLAction(n).setParent(this));
            n = XML.getNextSiblingElement(n, XML.SAML_NS, "Action");
        }

        n = XML.getFirstChildElement(e, XML.SAML_NS, "Evidence");
        if (n != null) {
            Element n2 = XML.getFirstChildElement(n);
            while (n2 != null) {
                if (XML.isElementNamed(n2, XML.SAML_NS, "Assertion"))
                    evidence.add(new SAMLAssertion(n2).setParent(this));
                else if (XML.isElementNamed(n2, XML.SAML_NS, "AssertionIDReference") && n2.hasChildNodes())
                    evidence.add(n2.getFirstChild().getNodeValue());
                n2 = XML.getNextSiblingElement(n2);
            }
        }

        checkValidity();
    }

    /**
     *  Gets the resource URI inside the statement
     *
     * @return    the resource URI
     */
    public String getResource() {
        return resource;
    }

    /**
     *  Sets the resource URI inside the statement
     *
     * @param   resource    The resource URI
     */
    public void setResource(String resource) {
        if (XML.isEmpty(resource))
            throw new IllegalArgumentException("resource cannot be null");
        this.resource = resource;
        setDirty(true);
    }

    /**
     * Gets the decision from inside the statement
     *
     * @return    The decision
     */
    public String getDecision() {
        return decision;
    }

    /**
     *  Sets the decision inside the statement
     *
     * @param   decision    The decision
     */
    public void setDecision(String decision) {
        if (XML.isEmpty(decision))
            throw new IllegalArgumentException("decision cannot be null");
        this.decision = decision;
        setDirty(true);
    }

    /**
     * Gets the actions inside the statement
     *
     * @return    An iterator over the actions
     */
    public Iterator getActions() {
        return actions.iterator();
    }

    /**
     *  Sets the actions to include in the statement
     *
     * @param   actions  The actions to include
     * @exception SAMLException     Raised if the actions are invalid
     */
    public void setActions(Collection actions) throws SAMLException {
        this.actions.clear();
        if (actions != null) {
            for (Iterator i = actions.iterator(); i.hasNext(); )
                this.actions.add(((SAMLAction)i.next()).setParent(this));
        }
        setDirty(true);
    }

    /**
     *  Adds an action to the statement
     * @param   action  The action to add
     * @exception SAMLException     Raised if the action if invalid
     */
    public void addAction(SAMLAction action) throws SAMLException {
        if (action != null) {
            actions.add(action.setParent(this));
            setDirty(true);
        }
        else
            throw new IllegalArgumentException("action cannot be null");
    }

    /**
     *  Removes an action by position (zero-based)
     *
     * @param   index   The position of the action to remove
     */
    public void removeAction(int index) {
        actions.remove(index);
        setDirty(true);
    }

    /**
     * Gets the evidence inside the statement
     *
     * @return     An iterator over the evidence
     */
    public Iterator getEvidence() {
        return evidence.iterator();
    }

    /**
     *  Sets the evidence to include in the statement
     *
     * @param   evidence  The evidence to include
     * @exception SAMLException     Raised if the evidence is invalid
     */
    public void setEvidence(Collection evidence) throws SAMLException {
        this.evidence.clear();
        if (evidence != null) {
            for (Iterator i = evidence.iterator(); i.hasNext(); )
                addEvidence(i.next());
        }
        setDirty(true);
    }

    /**
     *  Adds an evidence element
     *
     * @param   evidence    a String or SAMLAssertion
     * @exception SAMLException     Raised if an invalid kind of object is provided
     */
    public void addEvidence(Object evidence) throws SAMLException {
        if (evidence != null && (evidence instanceof String || evidence instanceof SAMLAssertion)) {
            if (evidence instanceof SAMLAssertion)
                this.evidence.add(((SAMLAssertion)evidence).setParent(this));
            else if (((String)evidence).length() > 0)
                this.evidence.add(evidence);
            setDirty(true);
        }
        else
            throw new IllegalArgumentException("can only add Strings or SAMLAssertions");
    }

    /**
     *  Removes an evidence element by position (zero-based)
     *
     * @param   index   The position of the element to remove
     */
    public void removeEvidence(int index) throws IndexOutOfBoundsException {
        evidence.remove(index);
        setDirty(true);
    }

    /**
     *  @see gov.nih.gov.nih.nci.cagrid.opensaml.SAMLObject#buildRoot(org.w3c.dom.Document,boolean)
     */
    protected Element buildRoot(Document doc, boolean xmlns) {
        Element s = doc.createElementNS(XML.SAML_NS, "AuthorizationDecisionStatement");
        if (xmlns)
            s.setAttributeNS(XML.XMLNS_NS, "xmlns", XML.SAML_NS);
        return s;
    }

    /**
     *  @see gov.nih.gov.nih.nci.cagrid.opensaml.SAMLObject#toDOM(org.w3c.dom.Document,boolean)
     */
    public Node toDOM(Document doc, boolean xmlns) throws SAMLException {
        // Let the base build/verify the DOM root.
        super.toDOM(doc, xmlns);
        Element s = (Element)root;

        if (dirty) {
            s.setAttributeNS(null, "Resource", resource);
            s.setAttributeNS(null, "Decision", decision);

            Iterator i = actions.iterator();
            while (i.hasNext())
                s.appendChild(((SAMLAction)i.next()).toDOM(doc, false));

            if (evidence.size()>0) {
                Element ev = doc.createElementNS(XML.SAML_NS, "Evidence");
                i = evidence.iterator();
                while (i.hasNext()) {
                    Object o = i.next();
                    if (o instanceof SAMLAssertion)
                        ev.appendChild(((SAMLAssertion)o).toDOM(doc, false));
                    else if (o instanceof String && !XML.isEmpty((String)o))
                        ev.appendChild(doc.createElementNS(XML.SAML_NS,"AssertionIDReference")).appendChild(doc.createTextNode((String)o));
                }
                s.appendChild(ev);
            }

            setDirty(false);
        }
        else if (xmlns) {
        	s.setAttributeNS(XML.XMLNS_NS, "xmlns", XML.SAML_NS);
        }
        return root;
    }

    /**
     * @see gov.nih.gov.nih.nci.cagrid.opensaml.SAMLObject#checkValidity()
     */
    public void checkValidity() throws SAMLException {
        super.checkValidity();
        if (XML.isEmpty(resource) || XML.isEmpty(decision) || actions.size() == 0)
            throw new MalformedException("AuthorizationDecisionStatement is invalid, must have Resource, Decision, and at least one Action");
    }

    /**
     *  Copies a SAML object such that no dependencies exist between the original
     *  and the copy
     *
     * @return      The new object
     * @see java.lang.Object#clone()
     */
    public Object clone() throws CloneNotSupportedException {
        SAMLAuthorizationDecisionStatement dup=(SAMLAuthorizationDecisionStatement)super.clone();

        // Clone the embedded objects.
        try {
            dup.actions = new ArrayList();
            for (Iterator i=actions.iterator(); i.hasNext(); )
                dup.actions.add(((SAMLAction)((SAMLAction)i.next()).clone()).setParent(dup));

            dup.evidence = new ArrayList();
            for (Iterator i=evidence.iterator(); i.hasNext(); ) {
                Object o = i.next();
                if (o instanceof SAMLAssertion)
                    dup.evidence.add(((SAMLAssertion)((SAMLAssertion)o).clone()).setParent(dup));
                else if (o instanceof String)
                    dup.evidence.add(o);
            }
        }
        catch (SAMLException e) {
            throw new CloneNotSupportedException(e.getMessage());
        }

        return dup;
    }
}


text:
    <form name="outerForm" novalidate>

{{'category'| translate}}

                        {{'entity_type'| translate}}

                        <select class="form-control"
                                ng-model="trackedEntities.selected"
                                ng-options="trackedEntity.displayName for trackedEntity in trackedEntities.available | orderBy: 'displayName'">
                        </select>

    </form>

    <form name="outerDataEntryForm" novalidate>

                {{'data_entry'| translate}}

    </form>

        <button type="button" class="btn btn-primary small-horizontal-spacing" ng-click="registerEntity(null)">{{'save'| translate}}</button>
        <button type="button" class="btn btn-default small-horizontal-spacing" ng-click="cancelRegistrationWarning(cancel)">{{'cancel'| translate}}</button>

        <button type="button" class="btn btn-primary" ng-click="registerEntity(null)">{{'enroll'| translate}}</button>
        <button type="button" class="btn btn-default" ng-click="cancelRegistrationWarning(showNewEnrollment)">{{'cancel'| translate}}</button>

        <button type="button" class="btn btn-primary" ng-click="registerEntity('DASHBOARD')">{{'save_and_continue'| translate}}</button>
        <button type="button" class="btn btn-success small-horizontal-spacing" ng-click="registerEntity('SELF')">{{'save_and_add_new'| translate}}</button>
        <button type="button" class="btn btn-primary" onclick="javascript:window.print()">{{'print_form'| translate}}</button>
        <button type="button" class="btn btn-default small-horizontal-spacing" ng-click="cancelRegistrationWarning(showRegistration)">{{'cancel'| translate}}</button>

 0" style="margin-top:18px" ng-class="{true: 'col-sm-4'} [registrationMode === 'REGISTRATION']">


text:
import { ActiveRecord } from 'lib'
import { include } from 'lib/meta'
import { Callbacks } from 'lib/callbacks'
import { CallbackManager } from 'lib/callbacks'
import { spy } from 'sinon'

describe('Callbacks', () => {
  describe('#callback_manager', () => {
    it('can return a callback manager', () => {
      @include(Callbacks)
      class A {}
      expect(A.callback_manager).to.be.instanceof(CallbackManager)
    })

    it('returns a different manager for a different class', () => {
      @include(Callbacks)
      class A {}

      @include(Callbacks)
      class B {}

      expect(A.callback_manager).to.not.eq(B.callback_manager)
    })

    it('returns a different manager for different extended classes', () => {
      class A extends ActiveRecord.Base {}
      class B extends ActiveRecord.Base {}

      expect(A.callback_manager).to.not.eq(B.callback_manager)
    })
  })

  describe('inheritable callbacks', () => {
    it('calls the callbacks of an inherited class', () => {
      @include(Callbacks)
      class A {}
      A.prototype.a = spy()
      A.set_callback('test_cb', 'a')

      @include(Callbacks)
      class B extends A {}

      const b = new B()
      B.run_callbacks('test_cb', b)

      expect(b.a.called).to.eq(true)
      expect(b.a.callCount).to.eq(1)
    })
  })
})


text:
import React from "react"
import sinon from "sinon"
import { mount } from "enzyme"

xdescribe("App", () => {
  let props
  let App

  beforeEach(() => {
    window.history.pushState = sinon.stub()
    App = require("desktop/apps/editorial_features/components/gucci/components/App.tsx")
      .App
    props = {
      activeSection: null,
      curation: {
        name: "Artists For Gender Equality",
        sections: [
          { title: "Past" },
          { title: "Present" },
          { title: "Future" },
        ],
        partner_logo_primary: "http://partner.com/logo.jpg",
        partner_link_url: "http://partner.com",
      },
      isMobile: false,
    }
    document.documentElement.scrollTop = 200
  })

  it("#onEnterSection", () => {
    const component = mount(<App {...props} />)
    component.instance().onEnterSection(0, {
      previousPosition: "above",
      currentPosition: "inside",
    })
    document.title.should.equal("Past")
    window.history.pushState.args[0][1].should.equal("Past")
    component.state("activeSection").should.equal(0)
    component.instance().onEnterSection(1, {
      previousPosition: "above",
      currentPosition: "inside",
    })
    document.title.should.equal("Present")
    window.history.pushState.args[1][1].should.equal("Present")
    component.state("activeSection").should.equal(1)
  })

  it("#onLeaveSection", () => {
    const component = mount(<App {...props} />)
    component.instance().onLeaveSection(0, {
      previousPosition: "inside",
      currentPosition: "above",
    })
    document.title.should.equal("Present")
    window.history.pushState.args[0][1].should.equal("Present")
    component.state("activeSection").should.equal(1)
    component.instance().onLeaveSection(1, {
      previousPosition: "inside",
      currentPosition: "above",
    })
    document.title.should.equal("Future")
    window.history.pushState.args[1][1].should.equal("Future")
    component.state("activeSection").should.equal(2)
  })
})


text:
<?php
/**
 * The content part for displaying subscribe and donate components.
 *
 * @author Julian Dawson <julian@juliandawson.co.uk>
 * @license MIT License
 * @link https://github.com/carlislephoto/carlislephoto-org-uk-theme
 *
 * @package WordPress
 * @subpackage CarlislePhoto
 */
?>

Newsletter

Stay up to date with our latest news.

        <form action="https://carlislephotofestival.us8.list-manage.com/subscribe/post" method="post">
          <input type="hidden" name="u" value="f3e0b49052df8c835dec9c01d">
          <input type="hidden" name="id" value="d14157e627">
          <input aria-required="true" autocapitalize="off" autocorrect="off" class="c-newsletter__input c-input" id="MERGE0" name="MERGE0" placeholder="email address" type="email" value="">
          <button class="c-newsletter__button c-button" type="submit">

              <svg class="c-newsletter__arrow c-button__arrow">
                <use xlink:href="#icon-arrow" xmlns:xlink="http://www.w3.org/1999/xlink"></use>
              </svg>

          </button>
        </form>

Support Carlisle Photo

We are a not for profit organisation, run by volunteers. Your donations help us support artists and bring photography to the community.

        <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
          <input type="hidden" name="cmd" value="_s-xclick">
          <input type="hidden" name="hosted_button_id" value="KKCGL9JWFKBL2">
          <input class="c-donate__button c-button" type="submit" value="Donate" alt="PayPal – The safer, easier way to pay online!">
        </form>

        <img class="c-partners__logo" src="<?php echo get_template_directory_uri() . '/images/sponsors-2.png' ?>" alt="Arts Council England">

        <img class="c-partners__logo" src="<?php echo get_template_directory_uri() . '/images/sponsors-1.png' ?>" alt="Arts Council England">

        <img class="c-partners__logo" src="<?php echo get_template_directory_uri() . '/images/sponsors-3.png' ?>" alt="Arts Council England">

        <img class="c-partners__logo" src="<?php echo get_template_directory_uri() . '/images/sponsors-4.png' ?>" alt="Arts Council England">


text:
#ifndef __AUInputFormatConverter_h__
#define __AUInputFormatConverter_h__

#include "FormatConverterClient.h"
#include "AUTimestampGenerator.h"

// ____________________________________________________________________________
// AUInputFormatConverter
//
// Subclass of FormatConverterClient that applies a format conversion
// to an input of an AudioUnit.
	/*! @class AUInputFormatConverter */
class AUInputFormatConverter : public FormatConverterClient {
public:
	/*! @ctor AUInputFormatConverter */
	AUInputFormatConverter(AUBase *hostAU, int inputBus) :
		mHost(hostAU),
		mHostBus(inputBus),
		mPreviousSilentFrames(0x1000)
	{
#if DEBUG
		mTimestampGenerator.mVerbosity = 0;
		strcpy(mTimestampGenerator.mDebugName, "AUConverter");
#endif
	}

	// need to subsequently call Initialize, with the desired formats

	/*! @dtor ~AUInputFormatConverter */
	~AUInputFormatConverter()
	{
	}

	virtual OSStatus Initialize(const AudioStreamBasicDescription &src, const AudioStreamBasicDescription &dest)
	{
		OSStatus err = FormatConverterClient::Initialize(src, dest);
		if (err) return err;
		mIsPCMToPCM = (src.mFormatID == kAudioFormatLinearPCM) && (dest.mFormatID == kAudioFormatLinearPCM);
		mHasSRC = (fnonzero(src.mSampleRate) && fnonzero(dest.mSampleRate) && fnotequal(src.mSampleRate, dest.mSampleRate));
		return ca_noErr;
	}

	virtual OSStatus	Reset()
	{
		mPreviousSilentFrames = 0x1000;
		mTimestampGenerator.Reset();
		return FormatConverterClient::Reset();
	}

	void	SetStartInputTimeAtZero(bool b)
	{
		mTimestampGenerator.SetStartInputAtZero(b);
	}

	/*! @method FillComplexBuffer */
	OSStatus	AUFillComplexBuffer(const AudioTimeStamp &				inTimeStamp,
									UInt32 &							ioOutputDataPacketSize,
									AudioBufferList &					outOutputData,
									AudioStreamPacketDescription*		outPacketDescription,
									bool&								outSilence)
	{
		mTimestampGenerator.AddOutputTime(inTimeStamp, ioOutputDataPacketSize, mOutputFormat.mSampleRate);
		mSilentOutput = true;
		OSStatus err = FillComplexBuffer(ioOutputDataPacketSize, outOutputData, outPacketDescription);
		if (mSilentOutput) {
			if (!mIsPCMToPCM || (mHasSRC && mPreviousSilentFrames < 32))
				mSilentOutput = false;
			mPreviousSilentFrames += ioOutputDataPacketSize;
 		} else
			mPreviousSilentFrames = 0;
		outSilence = mSilentOutput;
		return err;
	}

	/*! @method FormatConverterInputProc */
	virtual OSStatus	FormatConverterInputProc(
								UInt32 &						ioNumberDataPackets,
								AudioBufferList &				ioData,
								AudioStreamPacketDescription**	outDataPacketDescription)
	{
		OSStatus err = ca_noErr;

		AudioUnitRenderActionFlags actionFlags = 0;
		AUInputElement *input = mHost->GetInput(mHostBus);
		*ioNumberDataPackets = std::min(*ioNumberDataPackets, This->mHost->GetMaxFramesPerSlice());
		const AudioTimeStamp &inputTime = mTimestampGenerator.GenerateInputTime(ioNumberDataPackets, mInputFormat.mSampleRate);
		err = input->PullInput(actionFlags, inputTime, mHostBus, ioNumberDataPackets);
		if (!err) {
			input->CopyBufferListTo(ioData);
			if (!(actionFlags & kAudioUnitRenderAction_OutputIsSilence))
				mSilentOutput = false;
		}
		return err;
	}

protected:
	/*! @var mHost */
	AUBase *				mHost;
	/*! @var mHostBus */
	int						mHostBus;

	AUTimestampGenerator	mTimestampGenerator;
	bool					mIsPCMToPCM;
	bool					mHasSRC;
	bool					mSilentOutput;
	UInt32					mPreviousSilentFrames;
};

#endif // __AUInputFormatConverter_h__


text:
docker stop $(docker ps -a -q --filter 'label=environment=slack_weather_integration_test')
docker rm $(docker ps -a -q --filter 'label=environment=slack_weather_integration_test')


text:
const mdns = require('multicast-dns');
const Eventful = require('./eventful');

const __bind = function(fn, me) {
  return function() {
    return fn.apply(me, arguments);
  };
};

module.exports = class ChromecastScanner extends Eventful {
  constructor(opts) {
    super();
    this.options = {
      ttl: 10000,
      serviceName: '_googlecast._tcp.local',
      serviceType: 'PTR',
      mdns: {}
    };
    if (opts) {
      this.options.name = opts.name;
    }
    this.chromecastIPs = [];
    this.onResponse = __bind(this.onResponse, this);
  }

  findChromecasts() {
    this.m = mdns(this.options.mdns);
    this.timer = setTimeout(() => {
      if (this.chromecastIPs.length < 1) {
        this.emit('error', 'no Chromecasts were found');
      } else {
        this.emit('finished', 'stopped searching for Chromecasts');
      }
      this.close();
    }, this.options.ttl);
    this.m.on('response', this.onResponse);
    this.m.query({
      questions: [{
        name: this.options.serviceName,
        type: this.options.serviceType
      }]
    });
  }

  onResponse(response) {
    const answer = response.answers.filter((a) => {
      return a.name === this.options.serviceName &&
             a.type === this.options.serviceType;
    })[0];
    if (!answer) {
      return;
    }
    const info = response.additionals.filter(entry => entry.type === 'A')[0];
    if (!info || (this.options.name && this.options.name !== info.name)) {
      return;
    }
    if (this.chromecastIPs.indexOf(info.data) < 0) {
      this.chromecastIPs.push(info.data);
      this.emit('chromecast', info);
    }
  }

  close() {
    this.m.removeListener('response', this.onResponse);
    clearTimeout(this.timer);
    this.m.destroy();
  }
};


text:
<?php

namespace yiiunit\framework\db;

use yii\caching\FileCache;
use yii\db\Schema;

/**
 * @group db
 * @group mysql
 */
class SchemaTest extends DatabaseTestCase
{
	public function testGetTableNames()
	{
		/** @var Schema $schema */
		$schema = $this->getConnection()->schema;

		$tables = $schema->getTableNames();
		$this->assertTrue(in_array('tbl_customer', $tables));
		$this->assertTrue(in_array('tbl_category', $tables));
		$this->assertTrue(in_array('tbl_item', $tables));
		$this->assertTrue(in_array('tbl_order', $tables));
		$this->assertTrue(in_array('tbl_order_item', $tables));
		$this->assertTrue(in_array('tbl_type', $tables));
	}

	public function testGetTableSchemas()
	{
		/** @var Schema $schema */
		$schema = $this->getConnection()->schema;

		$tables = $schema->getTableSchemas();
		$this->assertEquals(count($schema->getTableNames()), count($tables));
		foreach($tables as $table) {
			$this->assertInstanceOf('yii\db\TableSchema', $table);
		}
	}

	public function testGetNonExistingTableSchema()
	{
		$this->assertNull($this->getConnection()->schema->getTableSchema('nonexisting_table'));
	}

	public function testSchemaCache()
	{
		/** @var Schema $schema */
		$schema = $this->getConnection()->schema;

		$schema->db->enableSchemaCache = true;
		$schema->db->schemaCache = new FileCache();
		$noCacheTable = $schema->getTableSchema('tbl_type', true);
		$cachedTable = $schema->getTableSchema('tbl_type', true);
		$this->assertEquals($noCacheTable, $cachedTable);
	}

	public function testCompositeFk()
	{
		/** @var Schema $schema */
		$schema = $this->getConnection()->schema;

		$table = $schema->getTableSchema('tbl_composite_fk');

		$this->assertCount(1, $table->foreignKeys);
		$this->assertTrue(isset($table->foreignKeys[0]));
		$this->assertEquals('tbl_order_item', $table->foreignKeys[0][0]);
		$this->assertEquals('order_id', $table->foreignKeys[0]['order_id']);
		$this->assertEquals('item_id', $table->foreignKeys[0]['item_id']);
	}

	public function testGetPDOType()
	{
		$values = [
			[null, \PDO::PARAM_NULL],
			['', \PDO::PARAM_STR],
			['hello', \PDO::PARAM_STR],
			[0, \PDO::PARAM_INT],
			[1, \PDO::PARAM_INT],
			[1337, \PDO::PARAM_INT],
			[true, \PDO::PARAM_BOOL],
			[false, \PDO::PARAM_BOOL],
			[$fp=fopen(__FILE__, 'rb'), \PDO::PARAM_LOB],
		];

		/** @var Schema $schema */
		$schema = $this->getConnection()->schema;

		foreach($values as $value) {
			$this->assertEquals($value[1], $schema->getPdoType($value[0]));
		}
		fclose($fp);
	}
}