text:
namespace lldb_private {
namespace platform_freebsd {

class PlatformFreeBSD : public PlatformPOSIX {
public:
  PlatformFreeBSD(bool is_host);

  ~PlatformFreeBSD() override;

  static void Initialize();

  static void Terminate();

  //------------------------------------------------------------
  // lldb_private::PluginInterface functions
  //------------------------------------------------------------
  static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch);

  static ConstString GetPluginNameStatic(bool is_host);

  static const char *GetPluginDescriptionStatic(bool is_host);

  ConstString GetPluginName() override;

  uint32_t GetPluginVersion() override { return 1; }

  //------------------------------------------------------------
  // lldb_private::Platform functions
  //------------------------------------------------------------
  const char *GetDescription() override {
    return GetPluginDescriptionStatic(IsHost());
  }

  void GetStatus(Stream &strm) override;

  bool GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) override;

  bool CanDebugProcess() override;

  size_t GetSoftwareBreakpointTrapOpcode(Target &target,
                                         BreakpointSite *bp_site) override;

  Status LaunchProcess(ProcessLaunchInfo &launch_info) override;

  lldb::ProcessSP Attach(ProcessAttachInfo &attach_info, Debugger &debugger,
                         Target *target, Status &error) override;

  void CalculateTrapHandlerSymbolNames() override;

  MmapArgList GetMmapArgumentList(const ArchSpec &arch, lldb::addr_t addr,
                                  lldb::addr_t length, unsigned prot,
                                  unsigned flags, lldb::addr_t fd,
                                  lldb::addr_t offset) override;

private:
  DISALLOW_COPY_AND_ASSIGN(PlatformFreeBSD);
};

} // namespace platform_freebsd
} // namespace lldb_private

#endif // liblldb_PlatformFreeBSD_h_


text:
var glContext = null;
var c_width = 0;
var c_height = 0;
var prg = null;

function degToRad(degrees) {
    return (degrees * Math.PI / 180.0);
}

/**
 * Allow to initialize Shaders.
 */
function getShader(gl, id) {
    var script = document.getElementById(id);
    if (!script) {
        return null;
    }

    var str = "";
    var k = script.firstChild;
    while (k) {
        if (k.nodeType == 3) {
            str += k.textContent;
        }
        k = k.nextSibling;
    }

    var shader;
    if (script.type == "x-shader/x-fragment") {
        shader = glContext.createShader(glContext.FRAGMENT_SHADER);
    } else if (script.type == "x-shader/x-vertex") {
        shader = glContext.createShader(glContext.VERTEX_SHADER);
    } else {
        return null;
    }

    glContext.shaderSource(shader, str);
    glContext.compileShader(shader);

    if (!glContext.getShaderParameter(shader, glContext.COMPILE_STATUS)) {
        alert(glContext.getShaderInfoLog(shader));
        return null;
    }
    return shader;
}

/**
 * The program contains a series of instructions that tell the Graphic Processing Unit (GPU)
 * what to do with every vertex and fragment that we transmit.
 * The vertex shader and the fragment shaders together are called through that program.
 */
function initProgram() {
    var fgShader = getShader(glContext, "shader-fs");
    var vxShader = getShader(glContext, "shader-vs");

    prg = glContext.createProgram();
    glContext.attachShader(prg, vxShader);
    glContext.attachShader(prg, fgShader);
    glContext.linkProgram(prg);

    if (!glContext.getProgramParameter(prg, glContext.LINK_STATUS)) {
        alert("Could not initialise shaders");
    }

    glContext.useProgram(prg);

    initShaderParameters(prg);

}

function requestAnimFrame(o) {
    requestAnimFrame(o);
}

/**
 * Provides requestAnimationFrame in a cross browser way.
 */
requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
            window.setTimeout(callback, 1000.0 / 60.0);
        };
})();

/**
 * Render Loop: frame rate and scene drawing.
 */
function renderLoop() {
    requestAnimFrame(renderLoop);
    drawScene();
}

/**
 * Verify that WebGL is supported by your machine
 */
function getGLContext(canvasName) {
    var canvas = document.getElementById(canvasName);
    if (canvas == null) {
        alert("there is no canvas on this page");
        return;
    } else {
        c_width = canvas.width;
        c_height = canvas.height;
    }

    var gl = null;
    var names = ["webgl",
        "experimental-webgl",
        "webkit-3d",
        "moz-webgl"
    ];

    for (var i = 0; i < names.length; i++) {
        try {
			gl = canvas.getContext(names[i]); // no blending

			//*** for transparency (Blending) ***
            //gl = canvas.getContext(names[i], {premultipliedAlpha: false});
            //gl.enable(gl.BLEND);
            //gl.blendEquation(gl.FUNC_ADD);
            //gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
        } catch (e) {}

        if (gl) break;
    }

    if (gl == null) {
        alert("WebGL is not available");
    } else {
        //alert("We got a WebGL context: "+names[i]);
        return gl;
    }
}

/**
 * The following code snippet creates a vertex buffer and binds the vertices to it.
 */
function getVertexBufferWithVertices(vertices) {
    var vBuffer = glContext.createBuffer();
    glContext.bindBuffer(glContext.ARRAY_BUFFER, vBuffer);
    glContext.bufferData(glContext.ARRAY_BUFFER, new Float32Array(vertices), glContext.STATIC_DRAW);
    glContext.bindBuffer(glContext.ARRAY_BUFFER, null);

    return vBuffer;
}

/**
 * The following code snippet creates a vertex buffer and binds the indices to it.
 */
function getIndexBufferWithIndices(indices) {
    var iBuffer = glContext.createBuffer();
    glContext.bindBuffer(glContext.ELEMENT_ARRAY_BUFFER, iBuffer);
    glContext.bufferData(glContext.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), glContext.STATIC_DRAW);
    glContext.bindBuffer(glContext.ELEMENT_ARRAY_BUFFER, null);

    return iBuffer;
}

function getArrayBufferWithArray(values) {
    //The following code snippet creates an array buffer and binds the array values to it
    var vBuffer = glContext.createBuffer();
    glContext.bindBuffer(glContext.ARRAY_BUFFER, vBuffer);
    glContext.bufferData(glContext.ARRAY_BUFFER, new Float32Array(values), glContext.STATIC_DRAW);
    glContext.bindBuffer(glContext.ARRAY_BUFFER, null);

    return vBuffer;
}

function initTextureWithImage(sFilename, texturen) {
    var anz = texturen.length;
    texturen[anz] = glContext.createTexture();

    texturen[anz].image = new Image();
    texturen[anz].image.onload = function() {
        glContext.bindTexture(glContext.TEXTURE_2D, texturen[anz]);
        glContext.pixelStorei(glContext.UNPACK_FLIP_Y_WEBGL, true);
        glContext.texImage2D(glContext.TEXTURE_2D, 0, glContext.RGBA, glContext.RGBA, glContext.UNSIGNED_BYTE, texturen[anz].image);
        glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_MIN_FILTER, glContext.NEAREST);
        glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_MAG_FILTER, glContext.NEAREST);

        glContext.generateMipmap(glContext.TEXTURE_2D);

        glContext.bindTexture(glContext.TEXTURE_2D, null);
    }

    texturen[anz].image.src = sFilename;

    // let's use a canvas to make textures, with by default a random color (red, green, blue)
    function rnd() {
        return Math.floor(Math.random() * 256);
    }

    var c = document.createElement("canvas");
    c.width = 64;
    c.height = 64;
    var ctx = c.getContext("2d");
    var red = rnd();
    var green = rnd();
    var blue = rnd();
    ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + ")";

    ctx.fillRect(0, 0, 64, 64);

    glContext.bindTexture(glContext.TEXTURE_2D, texturen[anz]);
    glContext.texImage2D(glContext.TEXTURE_2D, 0, glContext.RGBA, glContext.RGBA, glContext.UNSIGNED_BYTE, c);
    glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_MIN_FILTER, glContext.NEAREST);
    glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_MAG_FILTER, glContext.NEAREST);
    glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_WRAP_S, glContext.CLAMP_TO_EDGE);
    glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_WRAP_T, glContext.CLAMP_TO_EDGE);
}

function calculateTangents(vs, tc, ind) {
    var i;
    var tangents = [];
    for (i = 0; i < vs.length / 3; i++) {
        tangents[i] = [0, 0, 0];
    }
    // Calculate tangents
    var a = [0, 0, 0],
        b = [0, 0, 0];
    var triTangent = [0, 0, 0];
    for (i = 0; i < ind.length; i += 3) {

        var i0 = ind[i + 0];
        var i1 = ind[i + 1];
        var i2 = ind[i + 2];

        var pos0 = [vs[i0 * 3], vs[i0 * 3 + 1], vs[i0 * 3 + 2]];
        var pos1 = [vs[i1 * 3], vs[i1 * 3 + 1], vs[i1 * 3 + 2]];
        var pos2 = [vs[i2 * 3], vs[i2 * 3 + 1], vs[i2 * 3 + 2]];

        var tex0 = [tc[i0 * 2], tc[i0 * 2 + 1]];
        var tex1 = [tc[i1 * 2], tc[i1 * 2 + 1]];
        var tex2 = [tc[i2 * 2], tc[i2 * 2 + 1]];

        vec3.subtract(pos1, pos0, a);
        vec3.subtract(pos2, pos0, b);

        var c2c1t = tex1[0] - tex0[0];
        var c2c1b = tex1[1] - tex0[1];
        var c3c1t = tex2[0] - tex0[0];
        var c3c1b = tex2[0] - tex0[1];

        triTangent = [c3c1b * a[0] - c2c1b * b[0], c3c1b * a[1] - c2c1b * b[1], c3c1b * a[2] - c2c1b * b[2]];

        vec3.add(tangents[i0], triTangent);
        vec3.add(tangents[i1], triTangent);
        vec3.add(tangents[i2], triTangent);
    }

    // Normalize tangents
    var ts = [];
    for (i = 0; i < tangents.length; i++) {
        var tan = tangents[i];
        vec3.normalize(tan);

        ts.push(tan[0]);
        ts.push(tan[1]);
        ts.push(tan[2]);

    }

    return ts;
}

redpajama_set_name: RedPajamaGithub


text:
Tentang

Tim Kami

Kata Mereka


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Revenj.DatabasePersistence.Postgres.Converters;
using Revenj.Utility;

namespace Revenj.DatabasePersistence.Postgres
{
	public static class PostgresTypedArray
	{
		public static string ToArray<T>(IEnumerable<T> data, Func<T, string> converter)
		{
			if (data == null)
				return "NULL";
			using (var cms = ChunkedMemoryStream.Create())
			{
				Func<T, IPostgresTuple> toTuple = v => new ValueTuple(converter(v), false, true);
				var writer = cms.GetWriter();
				ToArray(writer, cms.SmallBuffer, data, toTuple);
				writer.Flush();
				cms.Position = 0;
				return cms.GetReader().ReadToEnd();
			}
		}

		public static void ToArray<T>(TextWriter sw, char[] buf, IEnumerable<T> data, Func<T, IPostgresTuple> converter)
		{
			if (data == null)
			{
				sw.Write("NULL");
				return;
			}
			var count = data.Count();
			var tuples = new IPostgresTuple[count];
			int i = 0;
			foreach (var item in data)
				tuples[i++] = converter(item);
			sw.Write('\'');
			var arr = ArrayTuple.From(tuples);
			arr.InsertRecord(sw, buf, string.Empty, PostgresTuple.EscapeQuote);
			sw.Write('\'');
		}

		public static void ToArray<T>(TextWriter sw, char[] buf, T[] data, Func<T, IPostgresTuple> converter)
		{
			if (data == null)
			{
				sw.Write("NULL");
				return;
			}
			var arr = new IPostgresTuple[data.Length];
			for (int i = 0; i < data.Length; i++)
				arr[i] = converter(data[i]);
			sw.Write('\'');
			var tuple = ArrayTuple.From(arr);
			tuple.InsertRecord(sw, buf, string.Empty, PostgresTuple.EscapeQuote);
			sw.Write('\'');
		}

		public static List<T> ParseCollection<T>(BufferedTextReader reader, int context, IServiceProvider locator, Func<BufferedTextReader, int, int, IServiceProvider, T> parseItem)
		{
			var cur = reader.Read();
			if (cur == ',' || cur == ')')
				return null;
			var escaped = cur != '{';
			if (escaped)
				reader.Read(context);
			cur = reader.Peek();
			if (cur == '}')
			{
				if (escaped)
					reader.Read(context + 2);
				else
					reader.Read(2);
				return new List<T>(0);
			}
			var list = new List<T>();
			var arrayContext = Math.Max(context << 1, 1);
			var recordContext = arrayContext << 1;
			while (cur != -1 && cur != '}')
			{
				cur = reader.Read();
				if (cur == 'N')
				{
					cur = reader.Read(4);
					list.Add(default(T));
				}
				else
				{
					var innerEscaped = cur != '(';
					if (innerEscaped)
						reader.Read(arrayContext);
					list.Add(parseItem(reader, 0, recordContext, locator));
					if (innerEscaped)
						cur = reader.Read(arrayContext + 1);
					else
						cur = reader.Read();
				}
			}
			if (escaped)
				reader.Read(context + 1);
			else
				reader.Read();
			return list;
		}
	}
}


text:
/****************************************************************************
 * mm/mm_heap/mm_heapinfo_parse_heap.c
 *
 *   Copyright (C) 2007, 2009, 2013-2014 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/
/****************************************************************************
 * Included Files
 ****************************************************************************/
#include <tinyara/config.h>
#include <tinyara/sched.h>
#include <tinyara/mm/mm.h>
#include <stdint.h>
#include <stdio.h>

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/
#define HEAPINFO_INT INT16_MAX
#define HEAPINFO_NONSCHED (INT16_MAX - 1)

/****************************************************************************
 * Public Functions
 ****************************************************************************/

#ifdef CONFIG_DEBUG_MM_HEAPINFO

/****************************************************************************
 * Name: heapinfo_parse
 *
 * Description:
 *   This function walk through heap and displays alloc info.
 ****************************************************************************/
void heapinfo_parse_heap(FAR struct mm_heap_s *heap, int mode, pid_t pid)
{
	struct mm_allocnode_s *node;
	size_t mxordblk = 0;
	int    ordblks  = 0;		/* Number of non-inuse chunks */
	size_t fordblks = 0;		/* Total non-inuse space */
	size_t heap_resource;
	size_t stack_resource;
	size_t nonsched_resource;
	int nonsched_idx;
	struct sched_param sched_data;
	size_t heap_size;

	/* This nonsched can be 3 types : group resources, freed when child task finished, leak */
	pid_t nonsched_list[CONFIG_MAX_TASKS];
	size_t nonsched_size[CONFIG_MAX_TASKS];

#if CONFIG_KMM_REGIONS > 1
	int region;
#else
#define region 0
#endif

#ifdef CONFIG_DEBUG_CHECK_FRAGMENTATION
	int ndx;
	int nodelist_cnt[MM_NNODES] = {0, };
	size_t nodelist_size[MM_NNODES] = {0, };
	FAR struct mm_freenode_s *fnode;
#endif

	ASSERT(mm_check_heap_corruption(heap) == OK);

	/* initialize the heap, stack and nonsched resource */
	nonsched_resource = 0;
	heap_resource = 0;
	stack_resource = 0;
	for (nonsched_idx = 0; nonsched_idx < CONFIG_MAX_TASKS; nonsched_idx++) {
		nonsched_list[nonsched_idx] = HEAPINFO_NONSCHED;
		nonsched_size[nonsched_idx] = 0;
	}

	/* Visit each region */

#if CONFIG_KMM_REGIONS > 1
	for (region = 0; region < heap->mm_nregions; region++)
#endif
	{
		/* Visit each node in the region
		 * Retake the semaphore for each region to reduce latencies
		 */
		mm_takesemaphore(heap);

		if (mode != HEAPINFO_SIMPLE) {
			printf("****************************************************************\n");
			printf("REGION #%d Start=0x%p, End=0x%p, Size=%d\n",
				region,
				heap->mm_heapstart[region],
				heap->mm_heapend[region],
				(int)heap->mm_heapend[region] - (int)heap->mm_heapstart[region] + SIZEOF_MM_ALLOCNODE);
			printf("****************************************************************\n");
			printf("  MemAddr |   Size   | Status |    Owner   |  Pid  |\n");
			printf("----------|----------|--------|------------|-------|\n");
		}

		for (node = heap->mm_heapstart[region]; node < heap->mm_heapend[region]; node = (struct mm_allocnode_s *)((char *)node + node->size)) {

			/* Check if the node corresponds to an allocated memory chunk */
			if ((pid == HEAPINFO_PID_ALL || node->pid == pid) && (node->preceding & MM_ALLOC_BIT) != 0) {
				if (mode == HEAPINFO_DETAIL_ALL || mode == HEAPINFO_DETAIL_PID || mode == HEAPINFO_DETAIL_SPECIFIC_HEAP) {
					if (node->pid >= 0) {
						printf("0x%x | %8u |   %c    | 0x%8x | %3d   |\n", node, node->size, 'A', node->alloc_call_addr, node->pid);
					} else {
						printf("0x%x | %8u |   %c    | 0x%8x | %3d(S)|\n", node, node->size, 'A', node->alloc_call_addr, -(node->pid));
					}
				}

#if CONFIG_TASK_NAME_SIZE > 0
				if (node->pid == HEAPINFO_INT && mode != HEAPINFO_SIMPLE) {
					printf("INT Context\n");
				} else if (node->pid < 0 && sched_getparam((-1) * (node->pid), &sched_data) != ERROR) {
					stack_resource += node->size;
				} else if (sched_getparam(node->pid, &sched_data) == ERROR) {
					nonsched_list[PIDHASH(node->pid)] = node->pid;
					nonsched_size[PIDHASH(node->pid)] += node->size;
					nonsched_resource += node->size;
				} else {
					heap_resource += node->size;
				}
#else
				if (mode != HEAPINFO_SIMPLE) {
					printf("\n");
				}
#endif
			} else {
				ordblks++;
				fordblks += node->size;
				if (node->size > mxordblk) {
					mxordblk = node->size;
				}
				if (mode == HEAPINFO_DETAIL_ALL || mode == HEAPINFO_DETAIL_FREE || mode == HEAPINFO_DETAIL_SPECIFIC_HEAP) {
					printf("0x%x | %8d |   %c    |            |       |\n", node, node->size, 'F');
				}
			}
		}

		if (mode != HEAPINFO_SIMPLE) {
			printf("** PID(S) in Pid colum means that mem is used for stack of PID\n\n");
		}
		mm_givesemaphore(heap);
	}
#undef region

	printf("\n****************************************************************\n");
	printf("     Summary of Heap Usages (Size in Bytes)\n");
	printf("****************************************************************\n");
	heap_size = heap->mm_heapsize;

	printf("Total                           : %u (100%%)\n", heap_size);
	printf("  - Allocated (Current / Peak)  : %u (%d%%) / %u (%d%%)\n",\
		heap->total_alloc_size, (size_t)((uint64_t)(heap->total_alloc_size) * 100 / heap_size),\
		heap->peak_alloc_size,  (size_t)((uint64_t)(heap->peak_alloc_size) * 100 / heap_size));
	printf("  - Free (Current)              : %u (%d%%)\n", fordblks, (size_t)((uint64_t)fordblks * 100 / heap_size));
	printf("  - Reserved                    : %u\n", SIZEOF_MM_ALLOCNODE * 2);

	printf("\n****************************************************************\n");
	printf("     Details of Heap Usages (Size in Bytes)\n");
	printf("****************************************************************\n");
	printf("< Free >\n");
	printf("  - Number of Free Node               : %d\n", ordblks);
	printf("  - Largest Free Node Size            : %u\n", mxordblk);
	printf("\n< Allocation >\n");
	printf("  - Current Size (Alive Allocation) = (1) + (2) + (3)\n");
	printf("     . by Dead Threads (*) (1)        : %u\n", nonsched_resource);
	printf("     . by Alive Threads\n");
	printf("        - Sum of \"STACK\"(**) (2)      : %u\n", stack_resource);
	printf("        - Sum of \"CURR_HEAP\" (3)      : %u\n", heap_resource - SIZEOF_MM_ALLOCNODE);	// Because of above for loop (node < heap->mm_heapend[region];),
													// one of SIZEOF_MM_ALLOCNODE is subtracted.
	printf("** NOTE **\n");
	printf("(*)  Alive allocation by dead threads might be used by others or might be a leakage.\n");
	printf("(**) Only Idle task has a separate stack region,\n");
	printf("  rest are all allocated on the heap region.\n");

#ifdef CONFIG_DEBUG_CHECK_FRAGMENTATION
	printf("\nAvailable fragmented memory segments in heap memory\n");

	mm_takesemaphore(heap);

	for (ndx = 0; ndx < MM_NNODES; ++ndx) {
		for (fnode = heap->mm_nodelist[ndx].flink; fnode && fnode->size; fnode = fnode->flink) {
			++nodelist_cnt[ndx];
			nodelist_size[ndx] += fnode->size;
		}
	}

	mm_givesemaphore(heap);

	for (ndx = 0; ndx < MM_NNODES; ++ndx) {
		printf("Nodelist[%d] ranging [%u, %u] : num %d, size %u [Bytes]\n", ndx, ((ndx > 0 ? (1 << (ndx + MM_MIN_SHIFT)) : 0) + 1), 1 << (ndx + MM_MIN_SHIFT + 1), nodelist_cnt[ndx], nodelist_size[ndx]);
	}
#endif

	if (mode != HEAPINFO_SIMPLE) {
		printf("\n< by Dead Threads >\n");
		printf(" Pid | Size \n");
		printf("-----|------\n");
		for (nonsched_idx = 0; nonsched_idx < CONFIG_MAX_TASKS; nonsched_idx++) {
			if (nonsched_list[nonsched_idx] != HEAPINFO_NONSCHED) {
				printf("%4d | %5u\n", nonsched_list[nonsched_idx], nonsched_size[nonsched_idx]);
			}
		}
	}

	return;
}
#endif


text:
package io.github.greyp9.arwo.core.env.test;

import io.github.greyp9.arwo.core.charset.UTF8Codec;
import io.github.greyp9.arwo.core.codec.hex.HexCodec;
import io.github.greyp9.arwo.core.ff.DataSplitter;
import io.github.greyp9.arwo.core.hash.secure.HashU;
import io.github.greyp9.arwo.core.jce.AES;
import io.github.greyp9.arwo.core.jce.KeyCodec;
import io.github.greyp9.arwo.core.jce.KeyU;
import io.github.greyp9.arwo.core.jce.KeyX;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.logging.Logger;

public class EnvironmentKeyGenerateTest {
    private final Logger logger = Logger.getLogger(getClass().getName());

    @Before
    public void setUp() throws Exception {
        logger.finest("setup()");
    }

    @Test
    public void testGenerateKey() throws NoSuchAlgorithmException {
        final KeyGenerator keyGenerator = KeyGenerator.getInstance(AES.Const.ALGORITHM);
        keyGenerator.init(AES.Const.KEY_BITS);
        final SecretKey key = keyGenerator.generateKey();
        final byte[] keyBytes = key.getEncoded();
        Assert.assertEquals(AES.Const.KEY_BYTES, keyBytes.length);
    }

    @Test
    public void testGenerateRecoverSecret() throws GeneralSecurityException {
        // generate the secret to be protected
        final KeyGenerator keyGenerator = KeyGenerator.getInstance(AES.Const.ALGORITHM);
        keyGenerator.init(AES.Const.KEY_BITS);
        final SecretKey keyGenerate = keyGenerator.generateKey();
        final byte[] keyBytes = keyGenerate.getEncoded();
        logger.finest(HexCodec.encode(keyBytes));
        // split the secret
        final int shareCount = 3;
        final int thresholdCount = 3;
        final Random random = new Random(0L);
        final DataSplitter dataSplitter = new DataSplitter(shareCount, thresholdCount, random);
        final byte[][] shares = dataSplitter.split(keyBytes);
        // protect the shares
        final String[] pbkdfData = {
                "abcdefghijklmnopqrst",
                "01234567890123456789",
                "abcdefghijklmnopqrst01234567890123456789",
        };
        Assert.assertEquals(shareCount, pbkdfData.length);
        final byte[][] sharesWrapped = new byte[pbkdfData.length][];
        for (int i = 0; (i < shareCount); ++i) {
            final String password = pbkdfData[i];
            final byte[] salt = HashU.sha256(UTF8Codec.toBytes(password));
            final SecretKey key = KeyU.toKeyPBE(password.toCharArray(), salt);
            final KeyCodec keyCodec = new KeyCodec(key, KeyX.Const.TRANSFORM_CTR, KeyX.Const.PARAM_SPEC_IV, random);
            final byte[] shareWrapped = keyCodec.encode(shares[i]);
            logger.finest(HexCodec.encode(shareWrapped));
            sharesWrapped[i] = shareWrapped;
            Assert.assertEquals(shares[i].length + AES.Const.IV_BYTES_CTR, sharesWrapped[i].length);
        }
        // recover the shares
        final byte[][] sharesUnwrapped = new byte[pbkdfData.length][];
        for (int i = 0; (i < shareCount); ++i) {
            final String password = pbkdfData[i];
            final byte[] salt = HashU.sha256(UTF8Codec.toBytes(password));
            final SecretKey key = KeyU.toKeyPBE(password.toCharArray(), salt);
            final KeyCodec keyCodec = new KeyCodec(key, KeyX.Const.TRANSFORM_CTR, KeyX.Const.PARAM_SPEC_IV, random);
            final byte[] shareUnwrapped = keyCodec.decode(sharesWrapped[i]);
            sharesUnwrapped[i] = shareUnwrapped;
            Assert.assertEquals(shares[i].length, sharesUnwrapped[i].length);
        }
        // reconstitute the secret
        final DataSplitter dataSplitterRecover = new DataSplitter(shareCount, thresholdCount, null);
        final byte[] keyBytesRecover = dataSplitterRecover.join(sharesUnwrapped);
        logger.finest(HexCodec.encode(keyBytesRecover));
        Assert.assertArrayEquals(keyBytes, keyBytesRecover);
    }
}


text:
using System;

namespace InTheHand.Net.Bluetooth.AttributeIds
{
    ///
    /// Service Attribute IDs defined by the OBEX related specifications,
    /// i.e. Object Push and Synchronization Profiles specifications.
    ///
    public static class ObexAttributeId
    {
        ///
        /// GOEP L2Cap PSM
        ///
        /// <remarks>
        /// New in GOEP v2.0 but not numbered there.
        /// New in OPP v1.2, FTP v1.2, and BIP v1.1.
        /// <para>[<c>UInt16</c>]</para>
        /// </remarks>
        public const ServiceAttributeId GoepL2capPsm = (ServiceAttributeId)0x0200;

        ///
        /// Supported Data Stores List (Synchronization Profile)
        ///
        /// <remarks>
        /// Synchronization Profile —
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.IrMCSync"/>
        /// service class.
        /// <para>[<c>Data Element Sequence of UInt8</c>]</para>
        /// <list type="table">
        /// Values
        /// <listheader><term>Value</term><description>Meaning</description></listheader>
        /// <item><term>0x01</term><description>Phonebook</description></item>
        /// <item><term>0x03</term><description>Calendar</description></item>
        /// <item><term>0x05</term><description>Notes</description></item>
        /// <item><term>0x06</term><description>Message</description></item>
        /// </list>
        /// </remarks>
        public const ServiceAttributeId SupportedDataStoresList = (ServiceAttributeId)0x0301;

        ///
        /// Supported Formats List (Object Push Profile)
        ///
        /// <remarks>
        /// Object Push Profile —
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ObexObjectPush"/>
        /// service class.
        /// <para>[<c>Data Element Sequence of UInt8</c>]</para>
        /// <list type="table">
        /// Values
        /// <listheader><term>Value</term><description>Meaning</description></listheader>
        /// <item><term>0x01</term><description>vCard 2.1</description></item>
        /// <item><term>0x02</term><description>vCard 3.0</description></item>
        /// <item><term>0x03</term><description>vCard 2.1</description></item>
        /// <item><term>0x04</term><description>vCal 1.0</description></item>
        /// <item><term>0x05</term><description>vNote</description></item>
        /// <item><term>0x06</term><description>vMessage</description></item>
        /// <item><term>0xFF</term><description>any type of object</description></item>
        /// </list>
        /// </remarks>
        public const ServiceAttributeId SupportedFormatsList = (ServiceAttributeId)0x0303;

        // -- BIP --

        ///
        /// Supported Capabilities (BIP)
        ///
        /// <remarks>
        /// Basic Imaging Profile —
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.Imaging"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingResponder"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingAutomaticArchive"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingReferenceObjects"/>
        /// service classes.
        /// <para>[<c>UInt8</c>]</para>
        /// <list type="table">
        /// Values
        /// <listheader><term>Value</term><description>Meaning</description></listheader>
        /// <item><term>Bit 0</term><description>Generic imaging</description></item>
        /// <item><term>Bit 1</term><description>Capturing</description></item>
        /// <item><term>Bit 2</term><description>Printing</description></item>
        /// <item><term>Bit 3</term><description>Displaying</description></item>
        /// <item><term>Bit 4..7</term><description>Reserved</description></item>
        /// </list>
        /// </remarks>
        public const ServiceAttributeId SupportedCapabilities = (ServiceAttributeId)0x0310;

        ///
        /// Supported Features (BIP)
        ///
        /// <remarks>
        /// Basic Imaging Profile —
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.Imaging"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingResponder"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingAutomaticArchive"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingReferenceObjects"/>
        /// service classes.
        /// <para>[<c>UInt16</c>]</para>
        /// <list type="table">
        /// Values
        /// <listheader><term>Value</term><description>Meaning</description></listheader>
        /// <item><term>Bit 0</term><description>ImagePush</description></item>
        /// <item><term>Bit 1</term><description>ImagePush-Store</description></item>
        /// <item><term>Bit 2</term><description>ImagePush-Print</description></item>
        /// <item><term>Bit 3</term><description>ImagePush-Display</description></item>
        /// <item><term>Bit 4</term><description>ImagePull</description></item>
        /// <item><term>Bit 5</term><description>AdvancedImagePrinting</description></item>
        /// <item><term>Bit 6</term><description>AutomaticArchive</description></item>
        /// <item><term>Bit 7</term><description>RemoteCamera</description></item>
        /// <item><term>Bit 8</term><description>RemoteDisplay</description></item>
        /// <item><term>Bit 9..15</term><description>Reserved</description></item>
        /// </list>
        /// </remarks>
        public const ServiceAttributeId SupportedFeatures = (ServiceAttributeId)0x0311;

        ///
        /// Supported Functions (BIP)
        ///
        /// <remarks>
        /// Basic Imaging Profile —
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.Imaging"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingResponder"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingAutomaticArchive"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingReferenceObjects"/>
        /// service classes.
        /// <para>[<c>UInt32</c>]</para>
        /// <list type="table">
        /// Values
        /// <listheader><term>Value</term><description>Meaning</description></listheader>
        /// <item><term>Bit 0</term><description>GetCapabilities</description></item>
        /// <item><term>Bit 1</term><description>PutImage</description></item>
        /// <item><term>Bit 2</term><description>PutLinkedAttachment</description></item>
        /// <item><term>Bit 3</term><description>PutLinkedThumbnail</description></item>
        /// <item><term>Bit 4</term><description>RemoteDisplay</description></item>
        /// <item><term>Bit 5</term><description>GetImagesList</description></item>
        /// <item><term>Bit 6</term><description>GetImageProperties</description></item>
        /// <item><term>Bit 7</term><description>GetImage</description></item>
        /// <item><term>Bit 8</term><description>GetLinkedThumbnail</description></item>
        /// <item><term>Bit 9</term><description>GetLinkedAttachment</description></item>
        /// <item><term>Bit 10</term><description>DeleteImage</description></item>
        /// <item><term>Bit 11</term><description>StartPrint</description></item>
        /// <item><term>Bit 12</term><description>Reserved</description></item>
        /// <item><term>Bit 13</term><description>StartArchive</description></item>
        /// <item><term>Bit 14</term><description>GetMonitoringImage</description></item>
        /// <item><term>Bit 16</term><description>GetStatus</description></item>
        /// <item><term>Bit 15, 17..31</term><description>Reserved</description></item>
        /// </list>
        /// </remarks>
        public const ServiceAttributeId SupportedFunctions = (ServiceAttributeId)0x0312;

        ///
        /// Total Imaging Data Capacity (BIP)
        ///
        /// <remarks>
        /// Basic Imaging Profile —
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.Imaging"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingResponder"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingAutomaticArchive"/>,
        /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.ImagingReferenceObjects"/>
        /// service classes.
        /// <para>[<c>UInt64</c>]</para>
        /// </remarks>
        public const ServiceAttributeId TotalImagingDataCapacity = (ServiceAttributeId)0x0313;

    }//class

    ///
    /// Service Attribute IDs defined by the Basic Printing Profile specification.
    ///
    public
#if ! V1
 static
#endif
 class BasicPrintingProfileAttributeId
    {
#if V1
        private BasicPrintingProfileAttributeId() { }
#endif
        ///
        /// Document Formats Supported
        ///
        /// <remarks>[<c>String</c>]</remarks>
        public const ServiceAttributeId DocumentFormatsSupported = (ServiceAttributeId)0x0350;

        ///
        /// Character Repertoires Supported
        ///
        /// <remarks>[<c>UInt128</c>]</remarks>
        public const ServiceAttributeId CharacterRepertoiresSupported = (ServiceAttributeId)0x0352;

        ///
        /// XHTML-Print Image Formats Supported
        ///
        /// <remarks>[<c>String</c>]</remarks>
        public const ServiceAttributeId XhtmlPrintImageFormatsSupported = (ServiceAttributeId)0x0354;

        ///
        /// Color Supported
        ///
        /// <remarks>[<c>Boolean</c>]</remarks>
        public const ServiceAttributeId ColorSupported = (ServiceAttributeId)0x0356;

        ///
        /// 1284ID
        ///
        /// <remarks>[<c>String</c>]</remarks>
        public const ServiceAttributeId Model1284Id = (ServiceAttributeId)0x0358;

        ///
        /// Printer Name
        ///
        /// <remarks>[<c>String</c>]</remarks>
        public const ServiceAttributeId PrinterName = (ServiceAttributeId)0x035A;

        ///
        /// Printer Location
        ///
        /// <remarks>[<c>String</c>]</remarks>
        public const ServiceAttributeId PrinterLocation = (ServiceAttributeId)0x035C;

        ///
        /// Duplex Supported
        ///
        /// <remarks>[<c>Boolean</c>]</remarks>
        public const ServiceAttributeId DuplexSupported = (ServiceAttributeId)0x035E;

        ///
        /// Media Types Supported
        ///
        /// <remarks>[<c>String</c>]</remarks>
        public const ServiceAttributeId MediaTypesSupported = (ServiceAttributeId)0x0360;

        ///
        /// MaxMediaWidth
        ///
        /// <remarks>[<c>UInt16</c>]</remarks>
        public const ServiceAttributeId MaxMediaWidth = (ServiceAttributeId)0x0362;

        ///
        /// MaxMediaLength
        ///
        /// <remarks>[<c>UInt16</c>]</remarks>
        public const ServiceAttributeId MaxMediaLength = (ServiceAttributeId)0x0364;

        ///
        /// Enhanced Layout Supported
        ///
        /// <remarks>[<c>Boolean</c>]</remarks>
        public const ServiceAttributeId EnhancedLayoutSupported = (ServiceAttributeId)0x0366;

        ///
        /// RUI Formats Supported
        ///
        /// <remarks>[<c>String</c>]</remarks>
        public const ServiceAttributeId RuiFormatsSupported = (ServiceAttributeId)0x0368;

        ///
        /// Reference Printing RUI Supported
        ///
        /// <remarks>[<c>Boolean</c>]</remarks>
        public const ServiceAttributeId ReferencePrintingRuiSupported = (ServiceAttributeId)0x0370;

        ///
        /// Direct Printing RUI Supported
        ///
        /// <remarks>[<c>Boolean</c>]</remarks>
        public const ServiceAttributeId DirectPrintingRuiSupported = (ServiceAttributeId)0x0372;

        ///
        /// Reference Printing Top URL
        ///
        /// <remarks>[<c>URL</c>]</remarks>
        public const ServiceAttributeId ReferencePrintingTopUrl = (ServiceAttributeId)0x0374;

        ///
        /// Direct Printing Top URL
        ///
        /// <remarks>[<c>URL</c>]</remarks>
        public const ServiceAttributeId DirectPrintingTopUrl = (ServiceAttributeId)0x0376;

        ///
        /// Printer Admin RUI Top URL
        ///
        /// <remarks>[<c>URL</c>]</remarks>
        public const ServiceAttributeId PrinterAdminRuiTopUrl = (ServiceAttributeId)0x0378;

        ///
        /// Device Name
        ///
        /// <remarks>[<c>String</c>]</remarks>
        public const ServiceAttributeId DeviceName = (ServiceAttributeId)0x037A;
    }//class

    ///
    /// Service Attribute IDs defined by the Personal Area Networking Profile specification.
    /// PersonalAreaNetworkingProfile
    public
#if ! V1
 static
#endif
 class PersonalAreaNetworkingProfileAttributeId
    {
#if V1
        private PersonalAreaNetworkingProfileAttributeId() { }
#endif
        ///
        /// Security Description
        ///
        /// <remarks>“Security Description” [<c>UInt16</c>]</remarks>
        public const ServiceAttributeId SecurityDescription = (ServiceAttributeId)0x030A;

        ///
        /// NetAccessType
        ///
        /// <remarks>“Type of Network Access Available” [<c>UInt16</c>]</remarks>
        public const ServiceAttributeId NetAccessType = (ServiceAttributeId)0x030B;

        ///
        /// MaxNetAccessRate
        ///
        /// <remarks>“Maximum possible Network Access Data Rate” [<c>UInt32</c>]</remarks>
        public const ServiceAttributeId MaxNetAccessRate = (ServiceAttributeId)0x030C;

        ///
        /// IPv4Subnet
        ///
        /// <remarks>[<c>String</c>]</remarks>
        public const ServiceAttributeId IPv4Subnet = (ServiceAttributeId)0x030D;

        ///
        /// IPv6Subnet
        ///
        /// <remarks>[<c>String</c>]</remarks>
        public const ServiceAttributeId IPv6Subnet = (ServiceAttributeId)0x030E;
    }//class

    ///
    /// Service Attribute IDs defined by the Headset Profile specification.
    ///
    public static class HeadsetProfileAttributeId
    {
        ///
        /// Remote audio volume control
        ///
        /// <remarks>[<c>Boolean</c>]</remarks>
        public const ServiceAttributeId RemoteAudioVolumeControl = (ServiceAttributeId)0x0302;
    }//class

    ///
    /// Service Attribute IDs defined by the Hand-Free Profile specification.
    /// HandFreeProfile
    public static class HandsFreeProfileAttributeId
    {
        //moved from above
        //[AttributeIdsOfServiceClass(HandsFreeProfileAttributeId.Handsfree)]
        //[AttributeIdsOfServiceClass(HandsFreeProfileAttributeId.GenericAudio)]
        //[AttributeIdsOfServiceClass(HandsFreeProfileAttributeId.HandsfreeAudioGateway)]

        ///
        /// Network
        ///
        /// <remarks>
        /// <para>“The "Network" attribute states, if the AG has the capability
        /// to reject incoming calls[4]. This attribute is not encoded as a data element
        /// sequence; it is simply an 8-bit unsigned integer. The information given
        /// in the "Network" attribute shall be the same as the information given
        /// in Bit 5 of the unsolicited result code +BRSF (see Section 4.24.3). An
        /// attribute value of 0x00 is translated to a bit value of 0; an attribute
        /// value of 0x01 is translated to a bit value of 1.”
        /// </para>
        /// [<c>UInt8</c>]
        /// </remarks>
        public const ServiceAttributeId Network = (ServiceAttributeId)0x301;

        ///
        /// SupportedFeatures
        ///
        /// <remarks>
        /// <para>“The attribute “SupportedFeatures” states the features
        /// supported in each device. …
        /// The set of features supported in each case is bit-wise defined in this
        /// attribute on a yes/no basis. The mapping between the features and their
        /// corresponding bits within the attribute is listed below in for the HF
        /// and in for the AG. …
        ///
        /// Bit     Feature                                                     Default in HF
        /// (0=LSB)
        /// 0       EC and/or NR function (yes/no, 1 = yes, 0 = no)             0
        /// 1       Call waiting and three way calling(yes/no, 1 = yes, 0 = no) 0
        /// 2       CLI presentation capability (yes/no, 1 = yes, 0 = no)       0
        /// 3       Voice recognition activation (yes/no, 1= yes, 0 = no)       0
        /// 4       Remote volume control (yes/no, 1 = yes, 0 = no)             0
        ///
        /// <para>Table 5.2 "SupportedFeatures" attribute bit mapping for the HF</para>
        ///
        /// Bit     Feature                                             Default in AG
        /// (0=LSB)
        /// 0       Three-way calling (yes/no, 1 = yes, 0 = no)         1
        /// 1       EC and/or NR function (yes/no, 1 = yes, 0 = no)     0
        /// 2       Voice recognition function (yes/no, 1 = yes, 0 = no)    0
        /// 3       In-band ring tone capability (yes/no, 1 = yes, 0 = no)  1
        /// 4       Attach a phone number to a voice tag (yes/no, 1 = yes, 0 = no)  0
        ///
        /// Table 5.4 "SupportedFeatures" attribute bit mapping for the AG”
        /// </para>
        /// [<c>UInt16</c>]</remarks>
        public const ServiceAttributeId SupportedFeatures = (ServiceAttributeId)0x0311;

        //internal const Int16 Handsfree = 0x111E;
        //internal const Int16 GenericAudio = 0x1203;
        //internal const Int16 HandsfreeAudioGateway = 0x111F;
    }//class

    ///
    /// Service Attribute IDs defined by the Health Device Profile specification.
    ///
public static class HealthDeviceAttributeId
    {
        ///
        /// SupportFeaturesList
        ///
        /// -
        /// <remarks>
        /// <para>"This is a sequence for which each element is a sequence that
        /// describes a single application data end-point on the device. The
        /// Supported Features attribute (MDEP List) provides an indication of
        /// the data types that an MDEP supports.",
        /// "...each description is itself a sequence of three or more elements."
        /// </para>
        /// <c>[Sequence]</c>
        /// </remarks>
        public const ServiceAttributeId SupportFeaturesList = (ServiceAttributeId)0x0200;
        ///
        /// DataExchangeSpecification
        ///
        /// -
        /// <remarks>
        /// <para>"This attribute is a one-byte reference, with the value taken
        /// from the Bluetooth Assigned Numbers [3] to identify the Data Exchange
        /// Protocol used (e.g. ISO/IEEE 11073-20601 specification)."
        /// e.g. value 0x01 is ISO/IEEE 11073-20601, "Health informatics - Personal
        /// health device communication - Application profile - Optimized exchange
        /// protocol"
        /// </para>
        /// <c>[UInt8]</c>
        /// </remarks>
        public const ServiceAttributeId DataExchangeSpecification = (ServiceAttributeId)0x0301;
        ///
        /// MCAP Supported Procedures
        ///
        /// -
        /// <remarks>
        /// <para>"This attribute is a one byte bit-mask that indicates the MCAP
        /// procedures that are supported by this HDP service."
        /// </para>
        ///
        /// 0x02  Supports Reconnect Initiation 3
        /// 0x04  Supports Reconnect Acceptance 4
        /// 0x08  Supports Clock Synchronization Protocol (includes support for at least Sync-Slave Role)
        /// 0x10  Supports Sync-Master Role
        ///
        /// <c>[UInt8]</c>
        /// </remarks>
        public const ServiceAttributeId McapSupportedProcedures = (ServiceAttributeId)0x0302;
    }
}


text:
package com.faforever.client.login;

public class TokenRetrievalException extends Exception {

  public TokenRetrievalException(String message) {
    super(message);
  }
}


text:
module IEK
  class Xpresso
    class MixResultItem
      attr_accessor :kind
      attr_accessor :id
      attr_accessor :number

      def initialize(kind, id, number)
        @kind, @id, @number = kind, id, number
      end

      def item
        case @kind
        when 0
          nil
        when 1
          $data_items[id]
        when 2
          $data_weapons[id]
        when 3
          $data_armors[id]
        when 4
          $data_skills[id]
        end
      end
    end

    class MixResult
      attr_accessor :items    # Array<MixResultItem>
      attr_accessor :message  # String

      def initialize(items, message)
        @items = items
        @message = message
      end

      def valid?
        !@items.empty?
      end

      def gain_items(target)
        @items.each do |mix_result_item|
          target.gain_item mix_result_item.item, number
        end
      end
    end

    attr_reader :mix_table

    def initialize
      @mix_table = {}
    end

    def mix(item1, item2)
      if !item1 || !item2
        return MixResult.new([], 'Invalid items')
      end

      key = [item1.to_mix_key, item2.to_mix_key]
      mix_results = @mix_table[key]

      if mix_results
        return MixResult.new(mix_results, 'Mixed!')
      end

      MixResult.new([], 'No mix result')
    end
  end
end


text:
namespace Envoy {
namespace Extensions {
namespace Matching {
namespace InputMatchers {
namespace Hyperscan {

Envoy::Matcher::InputMatcherFactoryCb
Config::createInputMatcherFactoryCb(const Protobuf::Message& config,
                                    Server::Configuration::ServerFactoryContext& factory_context) {
  const auto hyperscan_config = MessageUtil::downcastAndValidate<
      const envoy::extensions::matching::input_matchers::hyperscan::v3alpha::Hyperscan&>(
      config, factory_context.messageValidationVisitor());

#ifdef HYPERSCAN_DISABLED
  throw EnvoyException("X86_64 architecture is required for Hyperscan.");
#else
  // Hyperscan's API requires vectors of expressions, flags and IDs for matching database
  // compilation.
  return [hyperscan_config, &factory_context]() {
    int size = hyperscan_config.regexes().size();
    std::vector<const char*> expressions;
    std::vector<unsigned int> flags;
    std::vector<unsigned int> ids;
    expressions.reserve(size);
    flags.reserve(size);
    ids.reserve(size);
    for (const auto& regex : hyperscan_config.regexes()) {
      expressions.push_back(regex.regex().c_str());
      unsigned int flag = 0;
      if (regex.caseless()) {
        flag |= HS_FLAG_CASELESS;
      }
      if (regex.dot_all()) {
        flag |= HS_FLAG_DOTALL;
      }
      if (regex.multiline()) {
        flag |= HS_FLAG_MULTILINE;
      }
      if (regex.allow_empty()) {
        flag |= HS_FLAG_ALLOWEMPTY;
      }
      if (regex.utf8()) {
        flag |= HS_FLAG_UTF8;
        if (regex.ucp()) {
          flag |= HS_FLAG_UCP;
        }
      }
      if (regex.combination()) {
        flag |= HS_FLAG_COMBINATION;
      }
      if (regex.quiet()) {
        flag |= HS_FLAG_QUIET;
      }
      flags.push_back(flag);
      ids.push_back(regex.id());
    }

    return std::make_unique<Matcher>(expressions, flags, ids, factory_context.threadLocal(), false);
  };
#endif
}

REGISTER_FACTORY(Config, Envoy::Matcher::InputMatcherFactory);

} // namespace Hyperscan
} // namespace InputMatchers
} // namespace Matching
} // namespace Extensions
} // namespace Envoy


text:
TextMarker
===========

Gem that mark string in a text. It is possible mark the text with html tags.

Installation
============

Gemfile
-------

1) add in your Gemfile

    gem 'text-marker'

2) run this line in your prompt

    $ bundle install text-marker

RubyGems
-------

    $ gem install text-marker

Usage
=====

```ruby
require 'TextMarker'

snippet_to_be_marked = "text"
text = "Some text to be marked. After used TextMaker in this text it will return this text with desired text marked."

text_marked = TextMarker::Marker.new(text).mark_first_ocurrence_of(snippet_to_be_marked)

tm = TextMarker.Marker.new "Text"
tm_tag1 = TextMarker::Tag.new :tag, :background_color, :text_color

text_with_all_ocurrence_of_snipped_marked = tm.mark_all_ocurrence_of(
  "snippet-to-be-marked", tm_tag1)

text_with_all_ocurrences_of_snipped_marked = tm.mark_all_ocurrence_of(
  "snippet-to-be-marked", TextMarker::Tag.new :span)

text_with_first_ocurrence_of_snipped_marked = tm.mark_first_ocurrence_of(
  "snippet-to-be-marked", TextMarker::Tag.new :span, :yellow)
```

Author
======

#### Created and maintained by
Geison Felipe Goes Flores

geisonfgf@gmail.com

@geisonfgfg

## Contributing

1. Fork it ( https://github.com/[my-github-username]/text-marker/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

License
=======

TextMarker is licensed under the MIT license.

See LICENSE for the full license text.


text:
import {expect, should }  from 'chai';
import assert from 'assert';
import DCube from '../src/index';

let sampleCube;

describe('Properties', function() {
  beforeEach(function(done) {
    sampleCube = DCube();
    done();
  });

  describe('DCube.dimensions() Get and Set', function () {
    it('Should return the supplied dimension array when no parameter is present', function (done) {
      sampleCube.dimensions(['a', 'b', 'c']);

      let result = sampleCube.dimensions();
      expect(result).to.eql(['a', 'b', 'c']);
      done();
    });
  });

  describe('DCube.facts() Get and Set', function () {
    it('Should return the supplied dimension array when no parameter is present', function (done) {
      sampleCube.facts(['a', 'b', 'c']);

      let result = sampleCube.facts();
      expect(result).to.eql(['a', 'b', 'c']);
      done();
    });
  });
});


text:
package cascading.flapi.pipe;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;

import cascading.operation.Identity;
import cascading.operation.Insert;
import cascading.operation.NoOp;
import cascading.operation.aggregator.Count;
import cascading.operation.expression.ExpressionFunction;
import cascading.operation.filter.FilterNull;
import cascading.pipe.Each;
import cascading.pipe.Every;
import cascading.pipe.GroupBy;
import cascading.pipe.Pipe;
import cascading.pipe.assembly.Discard;
import cascading.pipe.assembly.Rename;
import cascading.pipe.assembly.Retain;
import cascading.pipe.assembly.Unique;
import cascading.tuple.Fields;

/**
 * Tests for all the global operations on {@link PipeBuilder}.
 *
 * @see EachBuilderTest
 * @see EveryBuilderTest
 * @see GroupByBuilderTest
 */
public class PipeBuilderTest {

    @Test
    public void empty() throws Exception {
        Pipe pipe = PipeBuilder.start()
                .pipe();

        assertThat(pipe).isNotNull();
        assertThat(pipe.getName()).isEqualTo("start");
    }

    @Test
    public void emptyWithName() throws Exception {
        Pipe pipe = PipeBuilder.start("toto")
                .pipe();

        assertThat(pipe.getName()).isEqualTo("toto");
    }

    @Test
    public void withName() throws Exception {
        Pipe pipe = PipeBuilder.start()
                .withName("toto")
                .pipe();

        assertThat(pipe.getName()).isEqualTo("toto");
    }

    @Test
    public void from() throws Exception {
        Pipe initialPipe = new Pipe("initial");

        Pipe pipe = PipeBuilder.from(initialPipe)
                .pipe();

        assertThat(pipe).isEqualTo(initialPipe);
    }

    @Test
    public void fromWithName() throws Exception {
        Pipe initialPipe = new Pipe("initial");

        Pipe pipe = PipeBuilder.from(initialPipe)
                .withName("new pipe")
                .pipe();

        assertThat(pipe.getName()).isEqualTo("new pipe");
        assertThat(pipe.getPrevious()).hasSize(1);
        assertThat(pipe.getPrevious()).containsExactly(initialPipe);
    }

    @Test
    public void retain() throws Exception {
        Pipe pipe = PipeBuilder.start()
                .retain("url")
                .pipe();

        assertThat(pipe).isInstanceOf(Retain.class);

        Retain retain = (Retain) pipe;
        assertThat(retain.getTails()).hasSize(1);
        assertThat(retain.getTails()[0]).isInstanceOf(Each.class);

        Each each = (Each)retain.getTails()[0];
        assertThat(each.getArgumentSelector()).isEqualTo(new Fields("url"));
    }

    @Test
    public void discard() throws Exception {
        Pipe pipe = PipeBuilder.start()
                .discard("url")
                .pipe();

        assertThat(pipe).isInstanceOf(Discard.class);

        Discard discard = (Discard) pipe;
        assertThat(discard.getTails()).hasSize(1);
        assertThat(discard.getTails()[0]).isInstanceOf(Each.class);

        Each each = (Each)discard.getTails()[0];
        assertThat(each.getArgumentSelector()).isEqualTo(new Fields("url"));
    }

    @Test
    public void unique() throws Exception {
        Pipe pipe = PipeBuilder.start()
                .unique()
                .pipe();

        assertThat(pipe).isInstanceOf(Unique.class);
    }

    @Test
    public void count() throws Exception {
        Pipe pipe = PipeBuilder.start()
                .count("myCount")
                .pipe();

        assertThat(pipe).isInstanceOf(Every.class);

        Every every = (Every) pipe;
        assertThat(every.getAggregator()).isInstanceOf(Count.class);
        assertThat(every.getAggregator().getFieldDeclaration()).isEqualTo(new Fields("myCount"));
    }

    @Test
    public void complexPipe() throws Exception {
        Pipe pipe = PipeBuilder.start()
                .each().select("data").filterOut().nullValues()
                .each().insertField("processingDate").withValue(System.currentTimeMillis())
                .renameField("domains").to("oldDomains")
                .each().select("url").applyFunction(new ExpressionFunction(new Fields("isRelativeUrl"), "url.startsWith(\"http\")", String.class))
                .compressOutput().forThisStepOnly().withGzipCodec().withType("BLOCK").ofTheMappers()
                .discard("data")
                .groupBy().withSortOnFields("url").onFields("domain")
                .count("domains")
                .pipe();

        // count
        assertThat(pipe).isInstanceOf(Every.class);
        assertThat(((Every)pipe).getOperation()).isInstanceOf(Count.class);

        // groupBy
        pipe = pipe.getPrevious()[0];
        assertThat(pipe).isInstanceOf(GroupBy.class);

        // discard
        pipe = pipe.getPrevious()[0];
        assertThat(pipe).isInstanceOf(Discard.class);
        pipe = pipe.getPrevious()[0];
        assertThat(pipe).isInstanceOf(Each.class);
        assertThat(((Each)pipe).getOperation()).isInstanceOf(NoOp.class);

        // expression
        pipe = pipe.getPrevious()[0];
        assertThat(pipe).isInstanceOf(Each.class);
        assertThat(((Each)pipe).getOperation()).isInstanceOf(ExpressionFunction.class);

        // rename
        pipe = pipe.getPrevious()[0];
        assertThat(pipe).isInstanceOf(Rename.class);
        pipe = pipe.getPrevious()[0];
        assertThat(pipe).isInstanceOf(Each.class);
        assertThat(((Each)pipe).getOperation()).isInstanceOf(Identity.class);

        // insert
        pipe = pipe.getPrevious()[0];
        assertThat(pipe).isInstanceOf(Each.class);
        assertThat(((Each)pipe).getOperation()).isInstanceOf(Insert.class);

        // filter null
        pipe = pipe.getPrevious()[0];
        assertThat(pipe).isInstanceOf(Each.class);
        assertThat(((Each)pipe).getOperation()).isInstanceOf(FilterNull.class);

        // initial pipe
        pipe = pipe.getPrevious()[0];
        assertThat(pipe.getClass()).isEqualTo(Pipe.class);
    }

}


text: ./gradlew updateLock saveLock --refresh-dependencies -PdependencyLock.updateDependencies=*


text:
NSLocalizedStringFromTable(key, @"DBPrivacyHelperLocalizable", nil)
#endif

@interface DBPrivateHelperController () <UITableViewDataSource, UITableViewDelegate> {
    DBPrivacyType _type;
    UIImageView *_backgroundImage;
    UITableView *_tableView;
    NSDictionary *_typeNames, *_cellAttributes;
    NSArray *_cellData;
}
@end

@implementation DBPrivateHelperController

+ (instancetype) helperForType:(DBPrivacyType)type {
    return [[[self class] alloc] initWithPrivacyType:type];
}

- (id) initWithPrivacyType:(DBPrivacyType)type {
    self = [super init];
    if ( self ) {
        _type = type;
        _canRotate = NO;
        _statusBarStyle = UIStatusBarStyleLightContent;

        _typeNames = @{ @(DBPrivacyTypePhoto):@{ @"title":DBPrivacyHelperLocalizableStrings(@"Photos"), @"icon":@"dbph_photoIcon" },
                        @(DBPrivacyTypeCamera):@{ @"title":DBPrivacyHelperLocalizableStrings(@"Camera"), @"icon":@"dbph_cameraIcon" },
                        @(DBPrivacyTypeLocation):@{ @"title":DBPrivacyHelperLocalizableStrings(@"Location Services"), @"icon":@"dbph_localizationIcon" },
                        @(DBPrivacyTypeHealth):@{ @"title":DBPrivacyHelperLocalizableStrings(@"Health"), @"icon":@"dbph_healthIcon" },
                        @(DBPrivacyTypeHomeKit):@{ @"title":DBPrivacyHelperLocalizableStrings(@"HomeKit"), @"icon":@"dbph_homekitIcon" },
                        @(DBPrivacyTypeMotionActivity):@{ @"title":DBPrivacyHelperLocalizableStrings(@"Motion Activity"), @"icon":@"dbph_motionIcon" }};

        NSString *titleText = DBPrivacyHelperLocalizableStrings(@"Tap on \"%@\"");
        NSString *allowText = DBPrivacyHelperLocalizableStrings(@"Allow your application to use \"%@\"");
        NSString *allowIcon = (_type == DBPrivacyTypeLocation) ? @"dbph_checkIcon" : @"dbph_switchIcon";
        _cellData = @[ @{ @"desc":DBPrivacyHelperLocalizableStrings(@"Open device settings"), @"icon":@"dbph_settingsIcon" },
                       @{ @"desc":DBPrivacyHelperLocalizableStrings(@"Tap on Privacy"), @"icon":@"dbph_privacyIcon" },
                       @{ @"desc":[NSString stringWithFormat:titleText, _typeNames[@(_type)][@"title"]], @"icon":_typeNames[@(_type)][@"icon"] },
                       @{ @"desc":[NSString stringWithFormat:allowText, _typeNames[@(_type)][@"title"]], @"icon":allowIcon }];

        NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        paragraphStyle.alignment = NSTextAlignmentLeft;

        _cellAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:12.0], NSParagraphStyleAttributeName:paragraphStyle };
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    _backgroundImage = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _backgroundImage.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_backgroundImage];

    if ( IS_IOS_8 ) {
        _backgroundImage.image = self.snapshot;

        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
        UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        blurEffectView.frame = _backgroundImage.bounds;
        blurEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//        [_backgroundImage addSubview:blurEffectView];

        UIVibrancyEffect *vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
        UIVisualEffectView *vibrancyEffectView = [[UIVisualEffectView alloc] initWithEffect:vibrancyEffect];
        vibrancyEffectView.frame = _backgroundImage.bounds;
        vibrancyEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

        [blurEffectView.contentView addSubview:vibrancyEffectView];
        [_backgroundImage addSubview:blurEffectView];
    } else {
        _backgroundImage.image = [self.snapshot applyDarkEffect];
    }

    NSString *titleText = DBPrivacyHelperLocalizableStrings(@"Allow access to \"%@\"\nwith these steps:");

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:(CGRect){ 0, 0, CGRectGetWidth([[UIScreen mainScreen] bounds]), 80 }];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:14.0];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    titleLabel.text = [NSString stringWithFormat:titleText, _typeNames[@(_type)][@"title"]];
    titleLabel.numberOfLines = 2;

    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView registerClass:[DBPrivateHelperCell class] forCellReuseIdentifier:[DBPrivateHelperCell identifier]];
    _tableView.translatesAutoresizingMaskIntoConstraints = NO;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView = nil;
    _tableView.separatorColor = [UIColor clearColor];
    _tableView.tableHeaderView = titleLabel;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.scrollEnabled = NO;
    [self.view addSubview:_tableView];

    _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _closeButton.translatesAutoresizingMaskIntoConstraints = NO;
    _closeButton.titleLabel.font = [UIFont boldSystemFontOfSize:12.0];
    _closeButton.backgroundColor = [UIColor clearColor];
    [_closeButton setTitle:DBPrivacyHelperLocalizableStrings(@"Close").uppercaseString forState:UIControlStateNormal];
    [_closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_closeButton addTarget:self action:@selector(dismissHelper:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_closeButton];

    NSDictionary *views = NSDictionaryOfVariableBindings(_tableView, _closeButton);

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[_closeButton]-20-|" options:0 metrics:nil views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_tableView]-0-|" options:0 metrics:nil views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[_closeButton(30)]-0-[_tableView]-0-|" options:0 metrics:nil views:views]];
}

- (void) dismissHelper:(UIButton *)button {
    [self dismissViewControllerAnimated:YES completion:self.didDismissViewController];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNeedsStatusBarAppearanceUpdate];
}

- (void) viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.snapshot = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat) cellHeightForText:(NSString *)text {
    CGFloat width = CGRectGetWidth(_tableView.frame) - 120.0;
    CGRect bounds = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:_cellAttributes context:NULL];

    CGFloat height = roundf(CGRectGetHeight(bounds) + 20);
    return ( height > 60.0 ) ? height + 10 : 60.0;
}

#pragma mark - UITableViewDataSource

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _cellData.count;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DBPrivateHelperCell *cell = [tableView dequeueReusableCellWithIdentifier:[DBPrivateHelperCell identifier]];
    [cell setIcon:_cellData[indexPath.row][@"icon"] text:_cellData[indexPath.row][@"desc"] row:indexPath.row + 1];
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self cellHeightForText:_cellData[indexPath.row][@"desc"]];
}

#pragma mark - Status Bar Style

- (UIStatusBarStyle) preferredStatusBarStyle {
    return self.statusBarStyle;
}

#pragma mark - ViewController Rotation

- (BOOL) shouldAutorotate {
    return self.canRotate;
}

- (NSUInteger) supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

@end


text:
layout: page
title: "Jacob Lionel Segil"
comments: true
description: "blanks"
keywords: "Jacob Lionel Segil,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Engineering and Applied Science

**Classes taught**: GEEN 1400, GEEN 3400, MCEN 3025, MCEN 3208, MCEN 4037, MCEN 4047

#### GEEN 1400: Engineering Projects

**Terms taught**: Fall 2013, Fall 2014, Fall 2015

**Instructor rating**: 5.31

**Standard deviation in instructor rating**: 0.13

**Average grade** (4.0 scale): 3.61

**Standard deviation in grades** (4.0 scale): 0.07

**Average workload** (raw): 3.42

**Standard deviation in workload** (raw): 0.24

#### GEEN 3400: Invention and Innovation

**Terms taught**: Fall 2016, Spring 2017

**Instructor rating**: 5.25

**Standard deviation in instructor rating**: 0.29

**Average grade** (4.0 scale): 3.22

**Standard deviation in grades** (4.0 scale): 0.08

**Average workload** (raw): 3.62

**Standard deviation in workload** (raw): 0.12

#### MCEN 3025: Component Design

**Terms taught**: Spring 2015, Spring 2015, Spring 2016, Spring 2016, Fall 2016

**Instructor rating**: 4.54

**Standard deviation in instructor rating**: 0.57

**Average grade** (4.0 scale): 2.94

**Standard deviation in grades** (4.0 scale): 0.13

**Average workload** (raw): 3.86

**Standard deviation in workload** (raw): 0.51

#### MCEN 3208: Special Topics in Mechanical Engineering

**Terms taught**: Fall 2015

**Instructor rating**: 4.62

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 2.91

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 3.37

**Standard deviation in workload** (raw): 0.0

#### MCEN 4037: Measurements Lab

**Terms taught**: Fall 2014

**Instructor rating**: 5.09

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.61

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.43

**Standard deviation in workload** (raw): 0.0

#### MCEN 4047: Measurements 2

**Terms taught**: Spring 2013

**Instructor rating**: 4.71

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.47

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.67

**Standard deviation in workload** (raw): 0.0


text:
class RoundStatistics {

    constructor(attackGroup, defenseGroup){
        this.results = [];
        this.attackGroup = attackGroup;
        this.defenseGroup = defenseGroup;
    }

    init(){
        this.update(0);
    }

    update(round){
        var ft,
            attCompressed = [],
            dfCompressed = [],
            i,
            stats;

        for(i=0; i < this.attackGroup.fleets.length; i++ ){
            ft = this.attackGroup.fleets[i];
            stats = ft.getStats();
            attCompressed.push( stats );
        }

        for(i=0; i < this.defenseGroup.fleets.length; i++ ){
            ft = this.defenseGroup.fleets[i];
            stats = ft.getStats();
            dfCompressed.push( stats );
        }

        this.results.push({
            "attack_fleet" : {
                "current": attCompressed,
                "attack_points": this.attackGroup.ap,
                "shield_defense": this.attackGroup.sp,
                "number_of_shoots" : this.attackGroup.sh
            },
            "defense_fleet" : {
                "current": dfCompressed,
                "attack_points": this.defenseGroup.ap,
                "shield_defense": this.defenseGroup.sp,
                "number_of_shoots" : this.defenseGroup.sh
            },
            "round" : round
        } ) ;
    }
}

export default RoundStatistics;


text:
package org.knowm.xchange.enigma.dto.trade;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public final class EnigmaLimitOrderRequest {

  @JsonProperty("product_id")
  private int productId;

  @JsonProperty("side_id")
  private int sideId;

  @JsonInclude(Include.NON_NULL)
  @JsonProperty("quantity")
  private BigDecimal quantity;

  @JsonInclude(Include.NON_NULL)
  @JsonProperty("nominal")
  private BigDecimal nominal;

  @JsonInclude(Include.NON_NULL)
  @JsonProperty("limitPrice")
  private BigDecimal limitPrice;

  @JsonProperty("infra")
  private String infrastructure;
}


text:
package org.elasticsearch.xpack.core.searchablesnapshots;

import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.support.master.MasterNodeRequest;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshotsConstants;

import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;

import static org.elasticsearch.action.ValidateActions.addValidationError;
import static org.elasticsearch.common.settings.Settings.readSettingsFromStream;
import static org.elasticsearch.common.settings.Settings.writeSettingsToStream;
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg;

public class MountSearchableSnapshotRequest extends MasterNodeRequest<MountSearchableSnapshotRequest> {

    public static final ConstructingObjectParser<MountSearchableSnapshotRequest, RestRequest> PARSER = new ConstructingObjectParser<>(
        "mount_searchable_snapshot", true,
        (a, request) -> new MountSearchableSnapshotRequest(
            Objects.requireNonNullElse((String)a[1], (String)a[0]),
            Objects.requireNonNull(request.param("repository")),
            Objects.requireNonNull(request.param("snapshot")),
            (String)a[0],
            Objects.requireNonNullElse((Settings)a[2], Settings.EMPTY),
            Objects.requireNonNullElse((String[])a[3], Strings.EMPTY_ARRAY),
            request.paramAsBoolean("wait_for_completion", false),
            Storage.valueOf(request.param("storage", Storage.FULL_COPY.toString()).toUpperCase(Locale.ROOT))));

    private static final ParseField INDEX_FIELD = new ParseField("index");
    private static final ParseField RENAMED_INDEX_FIELD = new ParseField("renamed_index");
    private static final ParseField INDEX_SETTINGS_FIELD = new ParseField("index_settings");
    private static final ParseField IGNORE_INDEX_SETTINGS_FIELD = new ParseField("ignore_index_settings");

    static {
        PARSER.declareField(constructorArg(), XContentParser::text, INDEX_FIELD, ObjectParser.ValueType.STRING);
        PARSER.declareField(optionalConstructorArg(), XContentParser::text, RENAMED_INDEX_FIELD, ObjectParser.ValueType.STRING);
        PARSER.declareField(optionalConstructorArg(), Settings::fromXContent, INDEX_SETTINGS_FIELD, ObjectParser.ValueType.OBJECT);
        PARSER.declareField(optionalConstructorArg(),
            p -> p.list().stream().map(s -> (String) s).collect(Collectors.toList()).toArray(Strings.EMPTY_ARRAY),
            IGNORE_INDEX_SETTINGS_FIELD, ObjectParser.ValueType.STRING_ARRAY);
    }

    private final String mountedIndexName;
    private final String repositoryName;
    private final String snapshotName;
    private final String snapshotIndexName;
    private final Settings indexSettings;
    private final String[] ignoredIndexSettings;
    private final boolean waitForCompletion;
    private final Storage storage;

    /**
     * Constructs a new mount searchable snapshot request, restoring an index with the settings needed to make it a searchable snapshot.
     */
    public MountSearchableSnapshotRequest(
            String mountedIndexName,
            String repositoryName,
            String snapshotName,
            String snapshotIndexName,
            Settings indexSettings,
            String[] ignoredIndexSettings,
            boolean waitForCompletion,
            Storage storage) {
        this.mountedIndexName = Objects.requireNonNull(mountedIndexName);
        this.repositoryName = Objects.requireNonNull(repositoryName);
        this.snapshotName = Objects.requireNonNull(snapshotName);
        this.snapshotIndexName = Objects.requireNonNull(snapshotIndexName);
        this.indexSettings = Objects.requireNonNull(indexSettings);
        this.ignoredIndexSettings = Objects.requireNonNull(ignoredIndexSettings);
        this.waitForCompletion = waitForCompletion;
        this.storage = storage;
    }

    public MountSearchableSnapshotRequest(StreamInput in) throws IOException {
        super(in);
        this.mountedIndexName = in.readString();
        this.repositoryName = in.readString();
        this.snapshotName = in.readString();
        this.snapshotIndexName = in.readString();
        this.indexSettings = readSettingsFromStream(in);
        this.ignoredIndexSettings = in.readStringArray();
        this.waitForCompletion = in.readBoolean();
        if (in.getVersion().onOrAfter(SearchableSnapshotsConstants.SHARED_CACHE_VERSION)) {
            this.storage = Storage.readFromStream(in);
        } else {
            this.storage = Storage.FULL_COPY;
        }
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeString(mountedIndexName);
        out.writeString(repositoryName);
        out.writeString(snapshotName);
        out.writeString(snapshotIndexName);
        writeSettingsToStream(indexSettings, out);
        out.writeStringArray(ignoredIndexSettings);
        out.writeBoolean(waitForCompletion);
        if (out.getVersion().onOrAfter(SearchableSnapshotsConstants.SHARED_CACHE_VERSION)) {
            storage.writeTo(out);
        } else if (storage != Storage.FULL_COPY) {
            throw new UnsupportedOperationException(
                    "storage type [" + storage + "] is not supported on version [" + out.getVersion() + "]");
        }
    }

    @Override
    public ActionRequestValidationException validate() {
        ActionRequestValidationException validationException = null;
        if (IndexMetadata.INDEX_DATA_PATH_SETTING.exists(indexSettings)) {
            validationException = addValidationError( "setting [" + IndexMetadata.SETTING_DATA_PATH
                + "] is not permitted on searchable snapshots", validationException);
        }
        return validationException;
    }

    /**
     * @return the name of the index that will be created
     */
    public String mountedIndexName() {
        return mountedIndexName;
    }

    /**
     * @return the name of the repository
     */
    public String repositoryName() {
        return this.repositoryName;
    }

    /**
     * @return the name of the snapshot.
     */
    public String snapshotName() {
        return this.snapshotName;
    }

    /**
     * @return the name of the index contained in the snapshot
     */
    public String snapshotIndexName() {
        return snapshotIndexName;
    }

    /**
     * @return true if the operation will wait for completion
     */
    public boolean waitForCompletion() {
        return waitForCompletion;
    }

    /**
     * @return settings that should be added to the index when it is mounted
     */
    public Settings indexSettings() {
        return this.indexSettings;
    }

    /**
     * @return the names of settings that should be removed from the index when it is mounted
     */
    public String[] ignoreIndexSettings() {
        return ignoredIndexSettings;
    }

    /**
     * @return how nodes will use their local storage to accelerate searches of this snapshot
     */
    public Storage storage() {
        return storage;
    }

    @Override
    public String getDescription() {
        return "mount snapshot [" + repositoryName + ":" + snapshotName + ":" + snapshotIndexName + "] as [" + mountedIndexName + "]";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MountSearchableSnapshotRequest that = (MountSearchableSnapshotRequest) o;
        return waitForCompletion == that.waitForCompletion &&
            storage == that.storage &&
            Objects.equals(mountedIndexName, that.mountedIndexName) &&
            Objects.equals(repositoryName, that.repositoryName) &&
            Objects.equals(snapshotName, that.snapshotName) &&
            Objects.equals(snapshotIndexName, that.snapshotIndexName) &&
            Objects.equals(indexSettings, that.indexSettings) &&
            Arrays.equals(ignoredIndexSettings, that.ignoredIndexSettings) &&
            Objects.equals(masterNodeTimeout, that.masterNodeTimeout);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(mountedIndexName, repositoryName, snapshotName, snapshotIndexName, indexSettings, waitForCompletion,
            masterNodeTimeout, storage);
        result = 31 * result + Arrays.hashCode(ignoredIndexSettings);
        return result;
    }

    @Override
    public String toString() {
        return getDescription();
    }

    /**
     * Enumerates the different ways that nodes can use their local storage to accelerate searches of a snapshot.
     */
    public enum Storage implements Writeable {
        FULL_COPY,
        SHARED_CACHE;

        public static Storage fromString(String type) {
            if ("full_copy".equals(type)) {
                return FULL_COPY;
            } else if ("shared_cache".equals(type)) {
                return SHARED_CACHE;
            } else {
                throw new IllegalArgumentException("unknown searchable snapshot storage type [" + type + "], valid types are: " +
                    Strings.arrayToCommaDelimitedString(Storage.values()));
            }
        }

        @Override
        public String toString() {
            return super.toString().toLowerCase(Locale.ROOT);
        }

        public static Storage readFromStream(StreamInput in) throws IOException {
            return in.readEnum(Storage.class);
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            out.writeEnum(this);
        }
    }
}


text:
package org.apache.camel.test.infra.kafka.services;

import org.apache.camel.test.infra.common.services.ContainerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.KafkaContainer;

public class ContainerLocalKafkaService implements KafkaService, ContainerService<KafkaContainer> {
    private static final Logger LOG = LoggerFactory.getLogger(ContainerLocalKafkaService.class);
    private KafkaContainer kafka = new KafkaContainer().withEmbeddedZookeeper();

    public String getBootstrapServers() {
        return kafka.getBootstrapServers();
    }

    @Override
    public void initialize() {
        kafka.start();

        LOG.info("Kafka bootstrap server running at address {}", kafka.getBootstrapServers());
    }

    @Override
    public void shutdown() {
        kafka.stop();
    }

    @Override
    public KafkaContainer getContainer() {
        return kafka;
    }
}


text:
package de.olafdietsche.android.samples.contacts_database;

import android.database.sqlite.SQLiteOpenHelper;
import de.olafdietsche.android.database.TableHelper;

public class ContactsTableHelper extends TableHelper {
	private static final String TABLE_NAME = "contacts";

	public static final String COLUMN_NAME_NAME = "name";
	public static final String COLUMN_NAME_CONTACT = "contact";

	public ContactsTableHelper(SQLiteOpenHelper dbHelper) {
		super(dbHelper, TABLE_NAME);
	}
}


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

<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Basic Configuration</title>

<link type="text/css" rel="stylesheet" href="../../build/cssfonts/fonts-min.css" />

Basic Configuration

	This example provides an introduction to the Attribute utility, showing how you can use it to add attribute support to your own custom classes.


text:
/* Browser Resets */
.flex-container a, .flexslider a, .flex-container a:active, .flexslider a:active, .flex-container a:focus, .flexslider a:focus {
	outline: none;
}
.slides, .flex-control-nav, .flex-direction-nav {
	margin: 0;
	padding: 0;
	list-style: none;
}
/* FlexSlider Necessary Styles
*********************************/
.flexslider {
	margin: 0;
	padding: 0;
}
.flexslider .slides > li {
	display: none;
	-webkit-backface-visibility: hidden;
} /* Hide the slides before the JS is loaded. Avoids image jumping */
.flexslider .slides img {
	max-width: 100%;
	display: block;
    box-shadow: #000 0em 0em 0em !important;
}
.flex-pauseplay span {
	text-transform: capitalize;
}
/* Clearfix for the .slides element */
.slides:after {
	content: ".";
	display: block;
	clear: both;
	visibility: hidden;
	line-height: 0;
	height: 0;
}
html[xmlns] .slides {
	display: block;
}
* html .slides {
	height: 1%;
}
/* No JavaScript Fallback */
/* If you are not using another script, such as Modernizr, make sure you
 * include js that eliminates this class on page load */
.no-js .slides > li:first-child {
	display: block;
}
/* FlexSlider Default Theme
*********************************/
.flexslider {
	background: #fff;
	position: relative;
	zoom: 1;
}
.flexslider .slides {
	zoom: 1;
}
.flexslider .slides > li {
	position: relative;
}
/* Suggested container for "Slide" animation setups. Can replace this with your own, if you wish */
.flex-container {
	zoom: 1;
	position: relative;
}
/* Caption style */
/* IE rgba() hack */
.flex-caption {
	background:none;
-ms-filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000, endColorstr=#4C000000);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000, endColorstr=#4C000000);
	zoom: 1;
}
.flex-caption {
	width: 96%;
	padding: 2%;
	margin: 0;
	position: absolute;
	left: 0;
	bottom: 0;
	background: rgba(0,0,0,.3);
	color: #fff;
	text-shadow: 0 -1px 0 rgba(0,0,0,.3);
	font-size: 14px;
	line-height: 18px;
}
/* Direction Nav */
.flex-direction-nav {
	height: 0;
}

.flex-direction-nav li {
	margin:0;
	line-height:0;
}

.flex-direction-nav a {
	width: 32px;
	height: 32px;
	margin: 0;
	display: block;
	position: absolute;
	top: 45%;
	cursor: pointer;
	background-repeat: no-repeat;
	background-position: 3px 4px;
	transition: all 0.2s linear;
	-moz-transition: all 0.2s linear;
	-webkit-transition: all 0.2s linear;
	-o-transition: all 0.2s linear;
	text-indent: -999em;
	background-image: url('../images/camera/slider-navigation.png');
}
.flex-direction-nav a:hover {
	opacity:1;
	background-color:#111111;
}
.flex-direction-nav .flex-next {
	background-position: 4px -23px;
	right: 0;
}
.flex-direction-nav .flex-prev {
	left: 0;
}
.flex-direction-nav .flex-disabled {
	opacity: .3;
	filter:alpha(opacity=30);
	cursor: default;
}

/* Control Nav */
.flex-control-nav {
	width: 100%;
	position: absolute;
	bottom: -30px;
	text-align: center;
	display:none;
}
.flex-control-nav li {
	margin: 0 0 0 5px;
	display: inline-block;
	zoom: 1;
*display: inline;
}
.flex-control-nav li:first-child {
	margin: 0;
}
.flex-control-nav a {
	width: 13px;
	height: 13px;
	display: block;
	background: url(theme/bg_control_nav.png) no-repeat;
	cursor: pointer;
	text-indent: -999em;
}
.flex-control-nav a:hover {
	background-position: 0 -13px;
}
.flex-control-nav a.flex-active {
	background-position: 0 -26px;
	cursor: default;
}
ul.slides {
	margin-left:0;
	list-style:none;
}
ul.slides li {
	margin:0;
}


text:
let model;
let info;
let canvas;
let image1;
let mask1;
let perf;
let pad;
const src_images = [image1, mask1];
const WIDTH = 256;
const HEIGHT = 384;

const state = {
  backend: 'webgl'
};

const gui = new dat.GUI();
gui.add(state, 'backend', ['webgl', 'wasm']).onChange(async backend => {
  await tf.setBackend(backend);
});

function changeImage(input, image_id) {
  if (input.files && input.files.length > 0) {
    const reader = new FileReader();
    reader.onload = function(e) {
      const originalImg = document.getElementById(image_id);
      originalImg.setAttribute('src', e.target.result);
      originalImg.setAttribute('width', WIDTH);
      originalImg.setAttribute('height', HEIGHT);
    };
    if (image_id.indexOf('mask') < 0) {
      loadMask('blank.png', 'im1_mask');
    }
    reader.readAsDataURL(input.files[0]);
  }
};

// Loads an image to the img element.
function loadImage(filename, element_id) {
  let _img = document.getElementById(element_id);
  let newImg = new Image;
  newImg.onload = function() {
    _img.src = this.src;
  }
  newImg.src = 'example_data/' + filename;
}

// Loads a mask into the mask canvas.
function loadMask(filename, element_id) {
  let _mask = document.getElementById(element_id).getContext('2d');
  let _img = new Image;
  _img.onload = function() {
    console.log(_img.width, _img.height, WIDTH, HEIGHT);
    _mask.drawImage(_img, 0, 0, _img.width, _img.height, 0, 0, WIDTH, HEIGHT);
  }
  _img.src = 'example_data/' + filename;
}

function loadPreset(preset_id) {
  loadImage('im' + preset_id + '.jpg', 'im1');
  loadMask('im' + preset_id + '_mask.png', 'im1_mask');
}

function predict() {
  // Tests if the model is loaded.
  if (model == null) {
    alert('Model is not available!');
    return;
  }

  // Tests if an image is missing.
  for (let src_image in src_images) {
    if (src_image.height === 0 || src_image.width === 0) {
      alert('You need to upload an image!');
      return;
    }
  }

  predictButton.textContent = 'Running...';
  predictButton.disabled = true;

  // Sets timeout = 0 to force reload the UI.
  setTimeout(function() {
    const start = Date.now();
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    tf.tidy(() => {
      // TODO: Resize images to [384, 256]; tf.image.resize...

      // Normalizes the values from [0, 255] to [-1, 1], same ranged used during training.
      const transform = transformValueRange(0, 255, -1, 1);

      // Converts the input image into a 3D tensor with shape [h, w, colorChannel].
      const image1Tensor = tf.browser.fromPixels(image1);
      const mask1Tensor = tf.browser.fromPixels(mask1);
      const image1Float = tf.cast(image1Tensor, 'float32');
      const mask1Float = tf.cast(mask1Tensor, 'float32');

      const matting1 = tf.sum(mask1Float, /*axis=*/-1, /*keepdims=*/true);
      const threshold = tf.fill(matting1.shape, 150 * 3);
      const mask1Bool = tf.greater(matting1, threshold);

      // Masks the image
      let image1Foreground = tf.where(
        tf.tile(mask1Bool, [1, 1, 3]),
        image1Float,
        tf.zerosLike(image1Float)
      );
      image1Foreground = tf.add(
        tf.mul(image1Foreground, transform.scale),
        transform.offset);

      // Runs the model.
      const input = [
        tf.expandDims(mask1Bool),
        tf.expandDims(image1Foreground)
      ];

      const result = model.predict(input);
      const resultSqueezed = tf.squeeze(result[0]);

      // Adds background.
      const rgbAndBackground = tf.where(
        tf.tile(mask1Bool, [1, 1, 3]),
        resultSqueezed,
        image1Float
      );

      // Renders the result on a canvas.
      const transformBack = transformValueRange(0, 255, 0, 1);

      // Converts back to 0-1.
      const rgbFinal = tf.add(tf.mul(rgbAndBackground, transformBack.scale), transformBack.offset);
      tf.browser.toPixels(rgbFinal, canvas);
    });

    const end = Date.now();
    const time = end - start;
    perf.textContent = time + ' ms';
    predictButton.textContent = 'Process';
    predictButton.disabled = false;
  }, 0);
};

function transformValueRange(
    fromMin, fromMax, toMin, toMax) {
  const fromRange = fromMax - fromMin;
  const ToRange = toMax - toMin;
  const scale = ToRange / fromRange;
  const offset = toMin - fromMin * scale;
  return {scale, offset};
}

function SetPen() {
  pad.minWidth = 3;
  pad.maxWidth = 5;
  pad.penColor = "rgb(255, 255, 255)";
  mask1.classList.add("penpad");
  mask1.classList.remove("eraserpad");
}

function SetBrush() {
  pad.minWidth = 10;
  pad.maxWidth = 15;
  pad.penColor = "rgb(255, 255, 255)";
  mask1.classList.add("penpad");
  mask1.classList.remove("eraserpad");
}

function SetEraser() {
  pad.minWidth = 10;
  pad.maxWidth = 15;
  pad.penColor = "rgb(0, 0, 0)";
  mask1.classList.remove("penpad");
  mask1.classList.add("eraserpad");
}

function ClearBtn() {
  loadMask('blank.png', 'im1_mask');
}

async function setupPage() {
  predictButton = document.getElementById('predict');
  canvas = document.getElementById('result');
  image1 = document.getElementById('im1');
  mask1 = document.getElementById('im1_mask');
  perf = document.getElementById('perf');
  predictButton.textContent = 'Loading...';
  loadMask('im3_mask.png', 'im1_mask');
  if (pad == null) pad = new SignaturePad(mask1);
  SetPen();

  try {
    model = await tf.loadGraphModel('./model/model.json');
  } catch(e)  {
    predictButton.textContent = 'Error in loading model.';
  }
  predictButton.textContent = 'Process';
  predictButton.disabled = false;
};

setupPage();


text:
@import url('/static/comp_a.css');

body {
    background-image: url(/static/img/a.png);
}

body {
    _filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/static/img/a.png');
}


text:
using System;
using NLog.Common;
using NLog.Config;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.UnitTests.Common;
using NLog.UnitTests.Targets.Wrappers;

#if !SILVERLIGHT

namespace NLog.UnitTests.LayoutRenderers
{
    using System.Security.Principal;
    using System.Threading;
    using Xunit;

    public class IdentityTests : NLogTestBase
    {
        [Fact]
        public void IdentityTest1()
        {
            var oldPrincipal = Thread.CurrentPrincipal;

            Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("SOMEDOMAIN\\SomeUser", "CustomAuth"), new[] { "Role1", "Role2" });
            try
            {
                AssertLayoutRendererOutput("${identity}", "auth:CustomAuth:SOMEDOMAIN\\SomeUser");
                AssertLayoutRendererOutput("${identity:authtype=false}", "auth:SOMEDOMAIN\\SomeUser");
                AssertLayoutRendererOutput("${identity:authtype=false:isauthenticated=false}", "SOMEDOMAIN\\SomeUser");
                AssertLayoutRendererOutput("${identity:fsnormalize=true}", "auth_CustomAuth_SOMEDOMAIN_SomeUser");
            }
            finally
            {
                Thread.CurrentPrincipal = oldPrincipal;
            }
        }

        /// <summary>
        /// Test writing ${identity} async
        /// </summary>
        [Fact]
        public void IdentityTest1Async()
        {
            var oldPrincipal = Thread.CurrentPrincipal;

            try
            {

                ConfigurationItemFactory.Default.Targets
                            .RegisterDefinition("CSharpEventTarget", typeof(CSharpEventTarget));

                LogManager.Configuration = this.CreateConfigurationFromString(@"<?xml version='1.0' encoding='utf-8' ?>
<nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd'
      xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'

      internalLogLevel='Debug'
      throwExceptions='true' >

  <targets async='true'>
    <target name='target1' xsi:type='CSharpEventTarget' layout='${identity}' />
  </targets>

  <rules>
    <logger name='*' writeTo='target1' />
  </rules>
</nlog>
");

                try
                {
                    var continuationHit = new ManualResetEvent(false);
                    string rendered = null;
                    var threadId = Thread.CurrentThread.ManagedThreadId;
                    var asyncThreadId = threadId;
                    LogEventInfo lastLogEvent = null;

                    var asyncTarget = LogManager.Configuration.FindTargetByName<AsyncTargetWrapper>("target1");
                    Assert.NotNull(asyncTarget);
                    var target = asyncTarget.WrappedTarget as CSharpEventTarget;
                    Assert.NotNull(target);
                    target.BeforeWrite += (logevent, rendered1, asyncThreadId1) =>
                    {
                        //clear in current thread before write
                        Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("ANOTHER user", "type"),null);
                    };

                     target.EventWritten += (logevent, rendered1, asyncThreadId1) =>
                    {
                        rendered = rendered1;
                        asyncThreadId = asyncThreadId1;
                        lastLogEvent = logevent;
                        continuationHit.Set();
                    };

                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("SOMEDOMAIN\\SomeUser", "CustomAuth"), new[] { "Role1", "Role2" });

                    var logger = LogManager.GetCurrentClassLogger();
                    logger.Debug("test write");

                    Assert.True(continuationHit.WaitOne());
                    Assert.NotNull(lastLogEvent);
                    //should be written in another thread.
                    Assert.NotEqual(threadId, asyncThreadId);

                    Assert.Equal("auth:CustomAuth:SOMEDOMAIN\\SomeUser", rendered);

                }
                finally
                {
                    LogManager.Configuration.Close();
                }
            }
            finally
            {
                Thread.CurrentPrincipal = oldPrincipal;
            }
        }

        [Fact]
        public void IdentityTest2()
        {
            var oldPrincipal = Thread.CurrentPrincipal;

            Thread.CurrentPrincipal = new GenericPrincipal(new NotAuthenticatedIdentity(), new[] { "role1" });
            try
            {
                AssertLayoutRendererOutput("${identity}", "notauth::");
            }
            finally
            {
                Thread.CurrentPrincipal = oldPrincipal;
            }
        }

        /// <summary>
        /// Mock object for IsAuthenticated property.
        /// </summary>
        private class NotAuthenticatedIdentity : GenericIdentity
        {

            public NotAuthenticatedIdentity()
                : base("")
            {
            }

            #region Overrides of GenericIdentity

            /// <summary>
            /// Gets a value indicating whether the user has been authenticated.
            /// </summary>
            /// <returns>
            /// true if the user was has been authenticated; otherwise, false.
            /// </returns>
            public override bool IsAuthenticated
            {
                get { return false; }
            }

            #endregion
        }
    }
}

#endif