text:
#ifndef TRC_STREAMING_PORT_H
#define TRC_STREAMING_PORT_H

#ifdef __cplusplus
extern "C" {
#endif

/*******************************************************************************
 * TRC_RECORDER_TRANSFER_METHOD_TCPIP
 *
 * This stream port for TCP/IP uses a temporary buffer consisting of multiple
 * pages, that are transmitted periodically by the TzCtrl task. You can modify
 * the supporting functions to match your system. See trcStreamingPort.c
 ******************************************************************************/

int32_t trcTcpWrite(void* data, uint32_t size, int32_t *ptrBytesWritten);
int32_t trcTcpRead(void* data, uint32_t size, int32_t *ptrBytesRead);

#if TRC_CFG_RECORDER_BUFFER_ALLOCATION == TRC_RECORDER_BUFFER_ALLOCATION_STATIC
#define TRC_STREAM_PORT_ALLOCATE_FIELDS() static char _TzTraceData[TRC_CFG_PAGED_EVENT_BUFFER_PAGE_COUNT * TRC_CFG_PAGED_EVENT_BUFFER_PAGE_SIZE];       /* Static allocation. */
#define TRC_STREAM_PORT_MALLOC() /* Static allocation. Not used. */
#else
#define TRC_STREAM_PORT_ALLOCATE_FIELDS() static char* _TzTraceData = NULL;     /* Dynamic allocation. */
#define TRC_STREAM_PORT_MALLOC() _TzTraceData = TRC_PORT_MALLOC(TRC_CFG_PAGED_EVENT_BUFFER_PAGE_COUNT * TRC_CFG_PAGED_EVENT_BUFFER_PAGE_SIZE);
#endif

#define TRC_STREAM_PORT_INIT() \
        TRC_STREAM_PORT_MALLOC(); /*Dynamic allocation or empty if static */ \
        prvPagedEventBufferInit(_TzTraceData);

#define TRC_STREAM_PORT_ALLOCATE_EVENT(_type, _ptrData, _size) _type* _ptrData; _ptrData = (_type*)prvPagedEventBufferGetWritePointer(_size);
#define TRC_STREAM_PORT_ALLOCATE_DYNAMIC_EVENT(_type, _ptrData, _size) TRC_STREAM_PORT_ALLOCATE_EVENT(_type, _ptrData, _size) /* We do the same thing as for non-dynamic event sizes */
#define TRC_STREAM_PORT_COMMIT_EVENT(_ptrData, _size) /* Not needed since we write immediately into the buffer received above by TRC_STREAM_PORT_ALLOCATE_EVENT, and the TRC_STREAM_PORT_PERIODIC_SEND_DATA defined below will take care of the actual trace transfer. */
#define TRC_STREAM_PORT_READ_DATA(_ptrData, _size, _ptrBytesRead) trcTcpRead(_ptrData, _size, _ptrBytesRead);
#define TRC_STREAM_PORT_PERIODIC_SEND_DATA(_ptrBytesSent) prvPagedEventBufferTransfer(trcTcpWrite, _ptrBytesSent);

#define TRC_STREAM_PORT_ON_TRACE_BEGIN() prvPagedEventBufferInit(_TzTraceData);
#define TRC_STREAM_PORT_ON_TRACE_END() /* Do nothing */

#ifdef __cplusplus
}
#endif

#endif /* TRC_STREAMING_PORT_H */


text:
namespace Microsoft.Azure.Management.WebSites.Models
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Microsoft.Rest.Azure;

    /// <summary>
    /// SlowRequestsBasedTrigger
    /// </summary>
    public partial class SlowRequestsBasedTrigger
    {
        /// <summary>
        /// Initializes a new instance of the SlowRequestsBasedTrigger class.
        /// </summary>
        public SlowRequestsBasedTrigger() { }

        /// <summary>
        /// Initializes a new instance of the SlowRequestsBasedTrigger class.
        /// </summary>
        public SlowRequestsBasedTrigger(string timeTaken = default(string), int? count = default(int?), string timeInterval = default(string))
        {
            TimeTaken = timeTaken;
            Count = count;
            TimeInterval = timeInterval;
        }

        /// <summary>
        /// TimeTaken
        /// </summary>
        [JsonProperty(PropertyName = "timeTaken")]
        public string TimeTaken { get; set; }

        /// <summary>
        /// Count
        /// </summary>
        [JsonProperty(PropertyName = "count")]
        public int? Count { get; set; }

        /// <summary>
        /// TimeInterval
        /// </summary>
        [JsonProperty(PropertyName = "timeInterval")]
        public string TimeInterval { get; set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
import './command-box.html';

import { Hotkeys } from 'meteor/flowkey:hotkeys';

import { displayError } from '../lib/errors.js';

import {
  removeWire,
} from '../../api/wires/methods.js';

Template.Command_box.helpers({
});

Template.Command_box.events({
  'click .command_box' (event, instance) {
    event.preventDefault();
    console.log( 'click .command_box');

    const $cli = instance.$('input[name=command-line]');
    $cli.focus();
  },

});


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#d3ff0004"
    android:gravity="center"
    android:padding="3dp">
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:gravity="center"
        android:id="@+id/errorFrame"
        android:layout_marginStart="25dp">

        <androidx.appcompat.widget.AppCompatImageView
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:src="@drawable/error" />
    </RelativeLayout>

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/tvErrorMessage"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:fontFamily="sans-serif"
        android:gravity="center"
        android:text="@string/error_message"
        android:textColor="#f5f2f2"
        android:textIsSelectable="false"
        android:textSize="18sp"
        android:typeface="serif"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="15dp"
        android:layout_toEndOf="@+id/errorFrame" />

</RelativeLayout>


text:
请选择需要上传的附件

<form action="demo/database/db_attachmentBrightBack.html" method="post" enctype="multipart/form-data" class="pageForm required-validate" onsubmit="return iframeCallback(this, $.bringBack)">

附件:

<input type="file" name="image" class="required" size="30" />

<button type="submit">上传</button>

<button class="close" type="button">关闭</button>

</form>


text:
set -e

echo "Add clear containers sources to apt list"
sudo sh -c "echo 'deb http://download.opensuse.org/repositories/home:/clearlinux:/preview:/clear-containers-2.1/xUbuntu_16.10/ /' >> /etc/apt/sources.list.d/cc-oci-runtime.list"

echo "Install chronic"
sudo apt-get install -y moreutils

echo "Install rpm2cpio"
chronic sudo apt-get install -y rpm2cpio

echo "Update apt repositories"
chronic sudo apt-get update

echo "Install linux-container kernel"
chronic sudo apt-get install -y --force-yes linux-container

echo "Install qemu-lite binary"
chronic sudo apt-get install -y --force-yes qemu-lite

echo "Download clear containers image"
latest_version=$(curl -sL https://download.clearlinux.org/latest)
curl -LO "https://download.clearlinux.org/current/clear-${latest_version}-containers.img.xz"

echo "Validate clear containers image checksum"
curl -LO "https://download.clearlinux.org/current/clear-${latest_version}-containers.img.xz-SHA512SUMS"
sha512sum -c clear-${latest_version}-containers.img.xz-SHA512SUMS

echo "Extract clear containers image"
unxz clear-${latest_version}-containers.img.xz

cc_img_path="/usr/share/clear-containers"
cc_img_link_name="clear-containers.img"
sudo mkdir -p ${cc_img_path}
echo "Install clear containers image"
sudo install --owner root --group root --mode 0755 clear-${latest_version}-containers.img ${cc_img_path}

echo -e "Create symbolic link ${cc_img_path}/${cc_img_link_name}"
sudo ln -fs ${cc_img_path}/clear-${latest_version}-containers.img ${cc_img_path}/${cc_img_link_name}

bug_url="https://github.com/clearcontainers/runtime/issues/91"
kernel_version="4.5-50"
cc_kernel_link_name="vmlinux.container"
echo -e "\nWARNING:"
echo "WARNING: Using backlevel kernel version ${kernel_version} due to bug ${bug_url}"
echo -e "WARNING:\n"
echo -e "Install clear containers kernel ${kernel_version}"
curl -LO "https://download.clearlinux.org/releases/12760/clear/x86_64/os/Packages/linux-container-${kernel_version}.x86_64.rpm"
rpm2cpio linux-container-${kernel_version}.x86_64.rpm | cpio -ivdm
sudo install --owner root --group root --mode 0755 .${cc_img_path}/vmlinux-${kernel_version}.container ${cc_img_path}

echo -e "Create symbolic link ${cc_img_path}/${cc_kernel_link_name}"
sudo ln -fs ${cc_img_path}/vmlinux-${kernel_version}.container ${cc_img_path}/${cc_kernel_link_name}

echo "Install nsenter"
util_linux_path="util-linux"
chronic sudo apt-get install -y autopoint
git clone git://git.kernel.org/pub/scm/utils/util-linux/util-linux.git
pushd ${util_linux_path}
./autogen.sh
./configure --without-python --disable-all-programs --enable-nsenter
make
sudo cp nsenter /usr/bin/
popd
rm -rf ${util_linux_path}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LoginWebsite
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<merge
    xmlns:latin="http://schemas.android.com/apk/res-auto"
>
    <Row
        latin:keyWidth="9.0%p"
        latin:backgroundType="functional"
    >
        <Key
            latin:keyStyle="toSymbolKeyStyle"
            latin:keyWidth="10.0%p" />
        <include
            latin:keyboardLayout="@xml/key_comma" />
        <!-- Space key. -->
        <include
            latin:keyboardLayout="@xml/key_space_7kw"
            latin:backgroundType="normal" />
        <include
            latin:keyboardLayout="@xml/key_period" />
        <Spacer
            latin:keyWidth="9%p" />
    </Row>
</merge>


text:
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>{% block title %} {% endblock %}</title>
	{% block head %}
	{% endblock %}
  <style>
    @import url(http://fonts.googleapis.com/css?family=Raleway);
  </style>l
</head>
<body>
	{% block content %}
	{% endblock %}
</body>
</html>


text:
#include "pch.h"
#include "scenes/scenes.h"

#if defined _DEBUG
#define new ANG_DEBUG_NEW()
#endif

using namespace ang;
using namespace ang::graphics;
using namespace ang::graphics::scenes;

template<> inline ang::maths::float2 ang::xml::xml_value::as<ang::maths::float2>()const
{
	if (get() == null)
		return{ 0,0 };
	streams::itext_input_stream_t stream = new streams::text_buffer_input_stream(get());
	float temp[2];
	stream >> "[" >> temp[0] >> "," >> temp[1];
	return{ temp[0], temp[1] };
}

template<> inline ang::maths::float3 ang::xml::xml_value::as<ang::maths::float3>()const
{
	if (get() == null)
		return{ 0,0,0 };
	streams::itext_input_stream_t stream = new streams::text_buffer_input_stream(get());
	float temp[3];
	stream >> "[" >> temp[0] >> "," >> temp[1] >> "," >> temp[2];
	return{ temp[0], temp[1], temp[2] };
}

template<> inline ang::maths::float4 ang::xml::xml_value::as<ang::maths::float4>()const
{
	if (get() == null)
		return{ 0,0,0,0 };
	streams::itext_input_stream_t stream = new streams::text_buffer_input_stream(get());
	float temp[4];
	stream >> "[" >> temp[0] >> "," >> temp[1] >> "," >> temp[2] >> "," >> temp[2];
	return{ temp[0], temp[1], temp[2], temp[3] };
}

#define M_PI 3.141592f

model::model()
{

}

model::~model()
{

}

ANG_IMPLEMENT_BASIC_INTERFACE(ang::graphics::scenes::model, scene_object);

bool model::load(scene_t scene, xml::xml_node_t node)
{
	if (scene.is_empty() || node.is_empty() || !node->xml_has_children())
		return false;

	auto pos = node["position"];
	if (pos.is_empty())
		_position = { 0, 0, 0, 1 };
	else
		_position = { pos->xml_value().as<maths::float3>() , 1 };

	auto rot = node["rotation"];
	if (rot.is_empty())
		_rotation = { 0, 0, 0, 1 };
	else
		_rotation = { rot->xml_value().as<maths::float3>() , 1 };

	auto scale = node["scale"];
	if (scale.is_empty())
		_scale = { 0, 0, 0, 1 };
	else
		_scale = { scale->xml_value().as<maths::float3>() , 1 };

	auto source = node["source"];
	if (!source.is_empty())
	{
		wstring filename = source->xml_value();
		auto _filename = scene->find_file(filename);
		core::files::input_text_file_t _txt_file;
		core::files::input_binary_file_t _bin_file;
		if (_filename.is_empty())
		{
			_txt_file = new core::files::input_text_file(filename);
			_bin_file = new core::files::input_binary_file(filename);
		}
		else
		{
			_txt_file = new core::files::input_text_file(_filename);
			_bin_file = new core::files::input_binary_file(_filename);
		}

		auto type = source->xml_attributes()["type"].as<cwstr_t>();

		if (type == "indexed")
		{
			if (_bin_file->is_valid())
			{
				//TODO
			}
			try {

				if (_txt_file->is_valid())
				{
					indexed_model_t _loader = new indexed_model();
					xml::xml_document_t doc = new xml::xml_document(_txt_file);
					_loader->load_async(doc->xml_root().get()).then<bool>([this, _loader, scene](core::async::iasync<collections::vector<indexed_model::model_element>>* task)->bool
					{
						textures::itexture_loader_t texloader = scene->texture_loader();
						effects::ieffect_library_t fxlibrary = scene->effect_library();
						idriver_t driver = scene->driver();

						collections::vector<indexed_model::model_element> data;
						try
						{
							data = ang::move(task->result());
						}
						catch (exception_t)
						{
							return false;
						}

						model_element element;

						foreach(data, [&](indexed_model::model_element& _element)
						{
							if (_element.vertex_data.is_empty() || _element.vertex_data->buffer_size() == 0)
								return;
							//if (_element.material == "_ea80e0f_dds"_s)
							//	return;
							auto stride = reflect::attribute_desc::get_size_in_bytes(_element.vertex_desc);
							element.vertex_buffer = driver->create_vertex_buffer(
								graphics::buffers::buffer_usage::dynamic,
								_element.vertex_desc,
								_element.vertex_data->buffer_size() / stride,
								static_array<byte>((byte*)_element.vertex_data->buffer_ptr(), _element.vertex_data->buffer_size()));

							element.index_buffer = driver->create_index_buffer(
								graphics::buffers::buffer_usage::dynamic,
								_element.index_type,
								_element.index_data->buffer_size() / reflect::variable_desc(_element.index_type, reflect::var_class::scalar).get_size_in_bytes(),
								static_array<byte>((byte*)_element.index_data->buffer_ptr(), _element.index_data->buffer_size()));

							element.technique = fxlibrary->find_technique(_element.technique_name);

							foreach(_element.textures, [&](string& texture)
							{
								auto res = texloader->load_texture(texture);
								driver->execute_on_thread_safe([&]()
								{
									if (!res.is_empty()) element.textures += res;
								});

							});

							driver->execute_on_thread_safe([&]()
							{
								model_elements += element;
							});

							//index idx = model_elements->counter() - 1;
							/*texloader->load_texture_async(_element.material).then<bool>([=](core::async::iasync<graphics::textures::itexture_t>* result)
							{
							driver->execute_on_thread_safe([&]()
							{
							try {
							auto res = result->result();
							if (!res.is_empty())
							model_elements[idx].textures += res;
							}
							catch (exception_t)
							{

							}
							});
							return true;
							});*/
						});
						return true;
					});
					return true;
				}

			}
			catch (exception_t e)
			{
				printf("%s\n", cstr_t(e->what()).cstr());
			}
		}

		ordered_model_t _loader = new ordered_model();

		if (_bin_file->is_valid() && null != _loader->load_async(_bin_file).then<bool>([this, _loader, scene, _bin_file, _txt_file](core::async::iasync<collections::vector<ordered_model::model_element>>* task)->bool
			{
				textures::itexture_loader_t texloader = scene->texture_loader();
				effects::ieffect_library_t fxlibrary = scene->effect_library();
				idriver_t driver = scene->driver();

				collections::vector<ordered_model::model_element> data;
				try
				{
					data = ang::move(task->result());
				}
				catch (exception_t)
				{
					data = null;
				}

				if (data.get() == null)
				{
					if (_txt_file->is_valid() && null != _loader.get()->load_async(_txt_file).then<bool>([this, _loader, scene, _bin_file, _txt_file](core::async::iasync<collections::vector<ordered_model::model_element>>* task)->bool
					{
						textures::itexture_loader_t texloader = scene->texture_loader();
						effects::ieffect_library_t fxlibrary = scene->effect_library();
						idriver_t driver = scene->driver();

						collections::vector<ordered_model::model_element> data;
						try
						{
							data = ang::move(task->result());
						}
						catch (exception_t)
						{
							return false;
						}

						model_element element;
						reflect::attribute_desc desc[3] =
						{
							{ reflect::var_type::f32, reflect::var_class::vec4, "position"_s, reflect::var_semantic::position, 0 },
							{ reflect::var_type::f32, reflect::var_class::vec4, "normal"_s, reflect::var_semantic::normal, 0 },
							{ reflect::var_type::f32, reflect::var_class::vec2, "texcoord"_s, reflect::var_semantic::tex_coord, 0 }
						};

						foreach(data, [&](ordered_model::model_element& _element)
						{
							if (_element.vertices.is_empty() || _element.vertices->counter() == 0)
								return;

							element.vertex_buffer = driver->create_vertex_buffer(
								graphics::buffers::buffer_usage::dynamic,
								static_array<reflect::attribute_desc>(desc, 3),
								_element.vertices->counter(),
								static_array<byte>((byte*)_element.vertices->data(), _element.vertices->counter() * sizeof(ordered_model::vertex)));

							element.technique = fxlibrary->find_technique("character_lighting_fx"_s);

							driver->execute_on_thread_safe([&]()
							{
								model_elements += element;
							});

							index idx = model_elements->counter() - 1;
							texloader->load_texture_async(_element.material).then<bool>([=](core::async::iasync<graphics::textures::itexture_t>* result)
							{
								driver->execute_on_thread_safe([&]()
								{
									try {
										auto res = result->result();
										if (!res.is_empty())
											model_elements[idx].textures = { res };
									}
									catch (exception_t)
									{

									}
								});
								return true;
							});
						});
						return true;
					}))
						return true;
					return false;
				}
				else
				{
					model_element element;
					reflect::attribute_desc desc[3] =
					{
						{ reflect::var_type::f32, reflect::var_class::vec4, "position"_s, reflect::var_semantic::position, 0 },
						{ reflect::var_type::f32, reflect::var_class::vec4, "normal"_s, reflect::var_semantic::normal, 0 },
						{ reflect::var_type::f32, reflect::var_class::vec2, "texcoord"_s, reflect::var_semantic::tex_coord, 0 }
					};

					foreach(data, [&](ordered_model::model_element& _element)
					{
						if (_element.vertices.is_empty() || _element.vertices->counter() == 0)
							return;

						element.vertex_buffer = driver->create_vertex_buffer(
							graphics::buffers::buffer_usage::dynamic,
							static_array<reflect::attribute_desc>(desc, 3),
							_element.vertices->counter(),
							static_array<byte>((byte*)_element.vertices->data(), _element.vertices->counter() * sizeof(ordered_model::vertex)));

						element.technique = fxlibrary->find_technique("character_lighting_fx"_s);

						driver->execute_on_thread_safe([&]()
						{
							model_elements += element;
						});

						index idx = model_elements->counter() - 1;
						texloader->load_texture_async(_element.material).then<bool>([=](core::async::iasync<graphics::textures::itexture_t>* result)
						{
							driver->execute_on_thread_safe([&]()
							{
								try {
									auto res = result->result();
									if (!res.is_empty())
										model_elements[idx].textures = { res };
								}
								catch (exception_t)
								{

								}
							});
							return true;
						});
					});
					return true;
				}
			}))
			return true;
	}
	return true;
}

bool model::load(idriver_t driver, effects::ieffect_library_t fxlibrary, textures::itexture_loader_t _texloader, core::files::input_text_file_t file)
{
	_position = { 0,0,-3,0 };
	_rotation = { 0,0,0,0 };
	_scale = { .30f,.30f,.30f,.30f };
	ordered_model_t _loader = new ordered_model();
	//_loader->add_ref();
	_loader->load_async(file).then<bool>([this, _loader, driver, fxlibrary, _texloader, file](core::async::iasync<collections::vector<ordered_model::model_element>>* task)->bool
	{
		textures::itexture_loader_t texloader = _texloader.get();
		collections::vector<ordered_model::model_element> data;
		try
		{
			data = ang::move(task->result());
		}
		catch (exception_t)
		{
			return false;
		}

		model_element element;
		reflect::attribute_desc desc[3] =
		{
			{ reflect::var_type::f32, reflect::var_class::vec4, "position"_s, reflect::var_semantic::position, 0 },
			{ reflect::var_type::f32, reflect::var_class::vec4, "normal"_s, reflect::var_semantic::normal, 0 },
			{ reflect::var_type::f32, reflect::var_class::vec2, "texcoord"_s, reflect::var_semantic::tex_coord, 0 }
		};

		foreach(data, [&](ordered_model::model_element& _element)
		{
			if (_element.vertices.is_empty() || _element.vertices->counter() == 0)
				return;
			//if (_element.material == "_ea80e0f_dds"_s)
			//	return;

			element.vertex_buffer = driver->create_vertex_buffer(
				graphics::buffers::buffer_usage::dynamic,
				static_array<reflect::attribute_desc>(desc, 3),
				_element.vertices->counter(),
				static_array<byte>((byte*)_element.vertices->data(), _element.vertices->counter() * sizeof(ordered_model::vertex)));

			element.technique = fxlibrary->find_technique("character_lighting_fx"_s);

			driver->execute_on_thread_safe([&]()
			{
				model_elements += element;
			});

			index idx = model_elements->counter() - 1;
			texloader->load_texture_async(_element.material).then<bool>([=](core::async::iasync<graphics::textures::itexture_t>* result)
			{
				driver->execute_on_thread_safe([&]()
				{
					try {
						auto res = result->result();
						if (!res.is_empty())
							model_elements[idx].textures += res;
					}
					catch (exception_t)
					{

					}
				});
				return true;
			});
		});

		return true;
	});

	return true;
}

bool model::load(idriver_t driver, effects::ieffect_library_t fxlibrary, textures::itexture_loader_t texloader, xml::xml_node_t model_info)
{

	return true;
}

inline float XMConvertToRadians(float fDegrees) { return fDegrees * (3.141592f / 180.0f); }
inline float XMConvertToDegrees(float fRadians) { return fRadians * (180.0f / 3.141592f); }

void model::update(float total, float delta)
{
	float radiansPerSecond = XMConvertToRadians(45);
	double totalRotation = total * radiansPerSecond / 1000.0f;
	float radians = static_cast<float>(fmod(totalRotation, 3.141592f * 2));

//	_rotation.set<1>(radians);

}

struct light_data_global
{
	maths::float4 ambient_color;
	uint light_count;
	float specular_power;
	struct {
		maths::float4 color;
		maths::unaligned_float3 position;
		uint type;
	}light_data[10];
} _light_data;

void model::draw(scene_t scene) {
	idriver_t driver = scene->driver();
	camera_t cam = scene->camera();
	driver->execute_on_thread_safe([&]()
	{
		effects::ishaders_t shaders = null;
		foreach(model_elements, [&](model_element& _element)
		{
			if (shaders.get() != _element.technique.get())
			{
				shaders = _element.technique;
				auto uniform = shaders->map_vs_uniform(driver, 0 /*"wvp"*/);
				uniform[0 /*"world"*/].cast<maths::float4x4>() = ang::maths::matrix::transpose(world_matrix());
				uniform[1 /*"view"*/].cast<maths::float4x4>() = ang::maths::matrix::transpose(cam->view_matrix());
				uniform[2 /*"proj"*/].cast<maths::float4x4>() = ang::maths::matrix::transpose(cam->projection_matrix());
				shaders->unmap_vs_uniform(driver, uniform);

				auto lights_info = shaders->map_ps_uniform(driver, 0 /*"lights"*/);
				if (lights_info.raw_data().get() != null)
				{
					auto scene_lights = scene->ligths();

					lights_info[0 /*"ambient"*/].cast<maths::float4>() = { scene->ambient_color(), 0.5f };
					lights_info[1 /*"lights_count"*/].cast<uint>() = scene_lights.size();
					lights_info[2 /*"specular_power"*/].cast<float>() = 10;
					auto lights = lights_info[3 /*"lights"*/].cast<static_array<reflect::variable>>();
					for (index i = 0; i < scene_lights.size(); ++i)
					{
						lights[i][0 /*"color"*/].cast<maths::float4>() = maths::float4(scene_lights[i].color, 1.0f);
						lights[i][1 /*"position"*/].cast<maths::float3>() = scene_lights[i].pos_dir;
						lights[i][2 /*"type"*/].cast<uint>() = scene_lights[i].type.get();
					}
					shaders->unmap_ps_uniform(driver, lights_info);

				}

				driver->bind_shaders(shaders);
			}

			index i = 0;
			foreach(_element.textures, [&](textures::itexture_t& tex)
			{
				driver->bind_texture(tex, i++);
			});

			driver->bind_vertex_buffer(_element.vertex_buffer);
			if (_element.index_buffer.is_empty())
			{
				driver->bind_index_buffer(null);
				driver->draw(_element.vertex_buffer->block_counter(), primitive::triangle);
			}
			else
			{
				driver->bind_index_buffer(_element.index_buffer);
				driver->draw_indexed(_element.index_buffer->counter(), primitive::triangle);
			}

			for(index i = 0, c = _element.textures.is_empty()? 1 : _element.textures->counter(); i < c; ++i)
				driver->bind_texture(null, i);
		});
		driver->bind_vertex_buffer(null);
		driver->bind_shaders(null);
	});
}

void model::close() {
	model_elements = null;

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License. See accompanying LICENSE file.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-project</artifactId>
    <version>3.4.0-SNAPSHOT</version>
    <relativePath>../../../hadoop-project</relativePath>
  </parent>
  <artifactId>hadoop-dynamometer-blockgen</artifactId>
  <version>3.4.0-SNAPSHOT</version>
  <description>Apache Hadoop Dynamometer Block Listing Generator</description>
  <name>Apache Hadoop Dynamometer Block Listing Generator</name>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-client</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-minicluster</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <configuration>
          <attach>true</attach>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>dist</id>
      <activation>
        <activeByDefault>false</activeByDefault>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <dependencies>
              <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-assemblies</artifactId>
                <version>${project.version}</version>
              </dependency>
            </dependencies>
            <executions>
              <execution>
                <id>dist</id>
                <phase>prepare-package</phase>
                <goals>
                  <goal>single</goal>
                </goals>
                <configuration>
                  <appendAssemblyId>false</appendAssemblyId>
                  <attach>false</attach>
                  <finalName>${project.artifactId}-${project.version}</finalName>
                  <descriptorRefs>
                    <descriptorRef>hadoop-dynamometer-blockgen</descriptorRef>
                  </descriptorRefs>
                </configuration>
              </execution>
            </executions>
          </plugin>
       <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <id>deplist</id>
            <phase>compile</phase>
            <goals>
              <goal>list</goal>
            </goals>
            <configuration>
              <!-- referenced by a built-in command -->
              <outputFile>${project.basedir}/target/hadoop-tools-deps/${project.artifactId}.tools-builtin.txt</outputFile>
            </configuration>
          </execution>
        </executions>
      </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>


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

namespace ClosedXML.Excel
{
    internal class XLCellsCollection
    {

        private readonly Dictionary<int, Dictionary<int, XLCell>> rowsCollection = new Dictionary<int, Dictionary<int, XLCell>>();
        public readonly Dictionary<Int32, Int32> ColumnsUsed = new Dictionary<int, int>();
        public readonly Dictionary<Int32, HashSet<Int32>> deleted = new Dictionary<int, HashSet<int>>();

        internal Dictionary<int, Dictionary<int, XLCell>> RowsCollection
        {
            get { return rowsCollection; }
        }

        public Int32 MaxColumnUsed;
        public Int32 MaxRowUsed;
        public Dictionary<Int32, Int32> RowsUsed = new Dictionary<int, int>();

        public XLCellsCollection()
        {
            Clear();
        }

        public Int32 Count { get; private set; }

        public void Add(XLSheetPoint sheetPoint, XLCell cell)
        {
            Add(sheetPoint.Row, sheetPoint.Column, cell);
        }

        public void Add(Int32 row, Int32 column, XLCell cell)
        {
            Count++;

            IncrementUsage(RowsUsed, row);
            IncrementUsage(ColumnsUsed, column);

            Dictionary<int, XLCell> columnsCollection;
            if (!rowsCollection.TryGetValue(row, out columnsCollection))
            {
                columnsCollection = new Dictionary<int, XLCell>();
                rowsCollection.Add(row, columnsCollection);
            }
            columnsCollection.Add(column, cell);
            if (row > MaxRowUsed) MaxRowUsed = row;
            if (column > MaxColumnUsed) MaxColumnUsed = column;

            HashSet<Int32> delHash;
            if (deleted.TryGetValue(row, out delHash))
                delHash.Remove(column);
        }

        private static void IncrementUsage(Dictionary<int, int> dictionary, Int32 key)
        {
            if (dictionary.ContainsKey(key))
                dictionary[key]++;
            else
                dictionary.Add(key, 1);
        }

        private static void DecrementUsage(Dictionary<int, int> dictionary, Int32 key)
        {
            Int32 count;
            if (!dictionary.TryGetValue(key, out count)) return;

            if (count > 0)
                dictionary[key]--;
            else
                dictionary.Remove(key);
        }

        public void Clear()
        {
            Count = 0;
            RowsUsed.Clear();
            ColumnsUsed.Clear();

            rowsCollection.Clear();
            MaxRowUsed = 0;
            MaxColumnUsed = 0;
        }

        public void Remove(XLSheetPoint sheetPoint)
        {
            Remove(sheetPoint.Row, sheetPoint.Column);
        }

        public void Remove(Int32 row, Int32 column)
        {
            Count--;
            DecrementUsage(RowsUsed, row);
            DecrementUsage(ColumnsUsed, row);

            HashSet<Int32> delHash;
            if (deleted.TryGetValue(row, out delHash))
            {
                if (!delHash.Contains(column))
                    delHash.Add(column);
            }
            else
            {
                delHash = new HashSet<int>();
                delHash.Add(column);
                deleted.Add(row, delHash);
            }

            Dictionary<int, XLCell> columnsCollection;
            if (rowsCollection.TryGetValue(row, out columnsCollection))
            {
                columnsCollection.Remove(column);
                if (columnsCollection.Count == 0)
                {
                    rowsCollection.Remove(row);
                }
            }

        }

        internal IEnumerable<XLCell> GetCells(Int32 rowStart, Int32 columnStart,
                                            Int32 rowEnd, Int32 columnEnd,
                                            Func<IXLCell, Boolean> predicate = null)
        {
            int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
            int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
            for (int ro = rowStart; ro <= finalRow; ro++)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(ro, out columnsCollection))
                {
                    for (int co = columnStart; co <= finalColumn; co++)
                    {
                        XLCell cell;
                        if (columnsCollection.TryGetValue(co, out cell)
                            && (predicate == null || predicate(cell)))
                            yield return cell;
                    }
                }
            }
        }

        internal HashSet<Int32> GetStyleIds(Int32 initial)
        {
            HashSet<Int32> ids = new HashSet<int>();
            ids.Add(initial);
            foreach (var row in rowsCollection)
            {
                foreach (var column in row.Value)
                {
                    var id = column.Value.GetStyleId();
                    if (!ids.Contains(id))
                    {
                        ids.Add(id);
                    }
                }
            }
            return ids;
        }

        internal IEnumerable<XLCell> GetCellsUsed(Int32 rowStart, Int32 columnStart,
                                    Int32 rowEnd, Int32 columnEnd,
                                    Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
        {
            int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
            int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
            for (int ro = rowStart; ro <= finalRow; ro++)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(ro, out columnsCollection))
                {
                    for (int co = columnStart; co <= finalColumn; co++)
                    {
                        XLCell cell;
                        if (columnsCollection.TryGetValue(co, out cell)
                        && !cell.IsEmpty(includeFormats)
                        && (predicate == null || predicate(cell)))
                            yield return cell;
                    }
                }
            }

        }

        public XLSheetPoint FirstPointUsed(Int32 rowStart, Int32 columnStart,
                                    Int32 rowEnd, Int32 columnEnd, Boolean includeFormats = false, Func<IXLCell, Boolean> predicate = null)
        {
            int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
            int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;

            var firstRow = FirstRowUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
            if (firstRow == 0) return new XLSheetPoint(0, 0);

            var firstColumn = FirstColumnUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
            if (firstColumn == 0) return new XLSheetPoint(0, 0);

            return new XLSheetPoint(firstRow, firstColumn);
        }

        public XLSheetPoint LastPointUsed(Int32 rowStart, Int32 columnStart,
                            Int32 rowEnd, Int32 columnEnd, Boolean includeFormats = false, Func<IXLCell, Boolean> predicate = null)
        {
            int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
            int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;

            var firstRow = LastRowUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
            if (firstRow == 0) return new XLSheetPoint(0, 0);

            var firstColumn = LastColumnUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
            if (firstColumn == 0) return new XLSheetPoint(0, 0);

            return new XLSheetPoint(firstRow, firstColumn);
        }

        public int FirstRowUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats,
            Func<IXLCell, Boolean> predicate = null)
        {
            int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
            int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
            for (int ro = rowStart; ro <= finalRow; ro++)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(ro, out columnsCollection))
                {
                    for (int co = columnStart; co <= finalColumn; co++)
                    {
                        XLCell cell;
                        if (columnsCollection.TryGetValue(co, out cell)
                        && !cell.IsEmpty(includeFormats)
                        && (predicate == null || predicate(cell)))
                            return ro;
                    }
                }
            }

            return 0;
        }

        public int FirstColumnUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
        {
            int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
            int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
            for (int ro = rowStart; ro <= finalRow; ro++)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(ro, out columnsCollection))
                {
                    for (int co = columnStart; co <= finalColumn; co++)
                    {
                        XLCell cell;
                        if (columnsCollection.TryGetValue(co, out cell)
                        && !cell.IsEmpty(includeFormats)
                        && (predicate == null || predicate(cell)))
                            return co;
                    }
                }
            }

            return 0;
        }

        public int LastRowUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
        {
            int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
            int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
            for (int ro = finalRow; ro >= rowStart; ro--)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(ro, out columnsCollection))
                {
                    for (int co = finalColumn; co >= columnStart; co--)
                    {
                        XLCell cell;
                        if (columnsCollection.TryGetValue(co, out cell)
                         && !cell.IsEmpty(includeFormats)
                        && (predicate == null || predicate(cell)))
                            return ro;
                    }
                }
            }
            return 0;
        }

        public int LastColumnUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
        {
            int maxCo = 0;
            int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
            int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
            for (int ro = finalRow; ro >= rowStart; ro--)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(ro, out columnsCollection))
                {
                    for (int co = finalColumn; co >= columnStart && co > maxCo; co--)
                    {
                        XLCell cell;
                        if (columnsCollection.TryGetValue(co, out cell)
                         && !cell.IsEmpty(includeFormats)
                        && (predicate == null || predicate(cell)))
                            maxCo = co;
                    }
                }
            }
            return maxCo;
        }

        public void RemoveAll(Int32 rowStart, Int32 columnStart,
                              Int32 rowEnd, Int32 columnEnd)
        {
            int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
            int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
            for (int ro = rowStart; ro <= finalRow; ro++)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(ro, out columnsCollection))
                {
                    for (int co = columnStart; co <= finalColumn; co++)
                    {
                        if (columnsCollection.ContainsKey(co))
                            Remove(ro, co);
                    }
                }
            }
        }

        public IEnumerable<XLSheetPoint> GetSheetPoints(Int32 rowStart, Int32 columnStart,
                                                        Int32 rowEnd, Int32 columnEnd)
        {
            int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
            int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
            for (int ro = rowStart; ro <= finalRow; ro++)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(ro, out columnsCollection))
                {
                    for (int co = columnStart; co <= finalColumn; co++)
                    {
                        if (columnsCollection.ContainsKey(co))
                            yield return new XLSheetPoint(ro, co);
                    }
                }
            }
        }

        public XLCell GetCell(Int32 row, Int32 column)
        {
            if (row > MaxRowUsed || column > MaxColumnUsed)
                return null;
            Dictionary<int, XLCell> columnsCollection;
            if (rowsCollection.TryGetValue(row, out columnsCollection))
            {
                XLCell cell;
                return columnsCollection.TryGetValue(column, out cell) ? cell : null;
            }
            return null;
        }

        public XLCell GetCell(XLSheetPoint sp)
        {
            return GetCell(sp.Row, sp.Column);
        }

        internal void SwapRanges(XLSheetRange sheetRange1, XLSheetRange sheetRange2, XLWorksheet worksheet)
        {
            Int32 rowCount = sheetRange1.LastPoint.Row - sheetRange1.FirstPoint.Row + 1;
            Int32 columnCount = sheetRange1.LastPoint.Column - sheetRange1.FirstPoint.Column + 1;
            for (int row = 0; row < rowCount; row++)
            {
                for (int column = 0; column < columnCount; column++)
                {
                    var sp1 = new XLSheetPoint(sheetRange1.FirstPoint.Row + row, sheetRange1.FirstPoint.Column + column);
                    var sp2 = new XLSheetPoint(sheetRange2.FirstPoint.Row + row, sheetRange2.FirstPoint.Column + column);
                    var cell1 = GetCell(sp1);
                    var cell2 = GetCell(sp2);

                    if (cell1 == null) cell1 = worksheet.Cell(sp1.Row, sp1.Column);
                    if (cell2 == null) cell2 = worksheet.Cell(sp2.Row, sp2.Column);

                    //if (cell1 != null)
                    //{
                    cell1.Address = new XLAddress(cell1.Worksheet, sp2.Row, sp2.Column, false, false);
                    Remove(sp1);
                    //if (cell2 != null)
                    Add(sp1, cell2);
                    //}

                    //if (cell2 == null) continue;

                    cell2.Address = new XLAddress(cell2.Worksheet, sp1.Row, sp1.Column, false, false);
                    Remove(sp2);
                    //if (cell1 != null)
                    Add(sp2, cell1);
                }
            }
        }

        internal IEnumerable<XLCell> GetCells()
        {
            return GetCells(1, 1, MaxRowUsed, MaxColumnUsed);
        }

        internal IEnumerable<XLCell> GetCells(Func<IXLCell, Boolean> predicate)
        {
            for (int ro = 1; ro <= MaxRowUsed; ro++)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(ro, out columnsCollection))
                {
                    for (int co = 1; co <= MaxColumnUsed; co++)
                    {
                        XLCell cell;
                        if (columnsCollection.TryGetValue(co, out cell)
                            && (predicate == null || predicate(cell)))
                            yield return cell;
                    }
                }
            }

        }

        public Boolean Contains(Int32 row, Int32 column)
        {
            Dictionary<int, XLCell> columnsCollection;
            return rowsCollection.TryGetValue(row, out columnsCollection) && columnsCollection.ContainsKey(column);
        }

        public Int32 MinRowInColumn(Int32 column)
        {
            for (int row = 1; row <= MaxRowUsed; row++)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(row, out columnsCollection))
                {
                    if (columnsCollection.ContainsKey(column))
                        return row;
                }
            }

            return 0;
        }

        public Int32 MaxRowInColumn(Int32 column)
        {
            for (int row = MaxRowUsed; row >= 1; row--)
            {
                Dictionary<int, XLCell> columnsCollection;
                if (rowsCollection.TryGetValue(row, out columnsCollection))
                {
                    if (columnsCollection.ContainsKey(column))
                        return row;
                }
            }

            return 0;
        }

        public Int32 MinColumnInRow(Int32 row)
        {
            Dictionary<int, XLCell> columnsCollection;
            if (rowsCollection.TryGetValue(row, out columnsCollection))
            {
                if (columnsCollection.Count > 0)
                    return columnsCollection.Keys.Min();
            }

            return 0;
        }

        public Int32 MaxColumnInRow(Int32 row)
        {
            Dictionary<int, XLCell> columnsCollection;
            if (rowsCollection.TryGetValue(row, out columnsCollection))
            {
                if (columnsCollection.Count > 0)
                    return columnsCollection.Keys.Max();
            }

            return 0;
        }

        public IEnumerable<XLCell> GetCellsInColumn(Int32 column)
        {
            return GetCells(1, column, MaxRowUsed, column);
        }

        public IEnumerable<XLCell> GetCellsInRow(Int32 row)
        {
            return GetCells(row, 1, row, MaxColumnUsed);
        }
    }
}


text:
'use strict';

angular.module('meanappApp')
  .controller('ProfileCtrl', function ($scope, $data, $state, User, Auth) {
    $scope.getCurrentUser = Auth.getCurrentUser;

//AD: for state name
    $scope.getStateName = function() {
        if($state.current.name === 'profile.edit') { return 'Edit'; }
        if($state.current.name === 'profile.new') { return 'Create'; }
        return 'View';
      };

//AD: this is to control angular forms
  $scope.disableFunctions = $data.disableFunctions;
  $scope.dataEventFunctions = $data.dataEventFunctions;
  $scope.record = $data.record;

  $scope.dataEventFunctions.onAfterCreate = function (data) {
    Auth.addProfileID(data._id)
    .then( function() {
      //add this in the cached current user object as well
      Auth.getCurrentUser().details = data._id;
      $state.go('main');//profile.edit, toParams, {notify: false});
    })
    .catch( function() {
        console.log('some issue');
    });
  };
  $scope.dataEventFunctions.onAfterUpdate = function (){//data, old) {
//    alert('Here is an example onAfterUpdate event. ' + JSON.stringify(data));
    $state.go('main');//profile.edit, toParams, {notify: false});
  };

//})
////AD: this hack allows us to stop BaseCtrl from redirecting to another state
//  .run(function($rootScope, $state, User, Auth) {
//    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
//        if(fromState.templateUrl === "components/forms/edit-form.html"){
//          if(toState.url==='/:model/:form/:id/edit' && toParams.form === 'profile') {
////            console.log(fromState);
////            console.log(fromParams);
////            console.log(toState);
////            console.log(toParams);
//            event.preventDefault();
//            //set the details id of user
//            Auth.addProfileID(toParams.id)
//            .then( function() {
//              //add this in the cached current user object as well
//              Auth.getCurrentUser().details = toParams.id;
//              $state.go('main');//profile.edit, toParams, {notify: false});
//            })
//            .catch( function() {
//                console.log('some issue');
//            });
//          }
//        }
//  });
});


text:
namespace blink {

class PropertyRegistryTest : public PageTestBase {
 public:
  PropertyRegistry& Registry() {
    return GetDocument().EnsurePropertyRegistry();
  }

  const PropertyRegistration* Registration(AtomicString name) {
    return Registry().Registration(name);
  }

  const CSSValue* MaybeParseInitialValue(String syntax, String value) {
    if (value.IsNull()) {
      DCHECK_EQ(syntax, "*");
      return nullptr;
    }
    return css_test_helpers::ParseValue(GetDocument(), syntax, value);
  }

  const PropertyRegistration* RegisterProperty(
      AtomicString name,
      String syntax = "*",
      String initial_value = g_null_atom) {
    auto* registration = css_test_helpers::CreatePropertyRegistration(
        name, syntax, MaybeParseInitialValue(syntax, initial_value));
    Registry().RegisterProperty(name, *registration);
    return registration;
  }

  const PropertyRegistration* DeclareProperty(
      AtomicString name,
      String syntax = "*",
      String initial_value = g_null_atom) {
    auto* registration = css_test_helpers::CreatePropertyRegistration(
        name, syntax, MaybeParseInitialValue(syntax, initial_value));
    Registry().DeclareProperty(name, *registration);
    return registration;
  }

  HeapVector<Member<const PropertyRegistration>> AllRegistrations() {
    HeapVector<Member<const PropertyRegistration>> vector;
    for (auto entry : Registry())
      vector.push_back(entry.value);
    return vector;
  }
};

TEST_F(PropertyRegistryTest, EnsurePropertyRegistry) {
  EXPECT_FALSE(GetDocument().GetPropertyRegistry());
  PropertyRegistry* registry = &GetDocument().EnsurePropertyRegistry();
  EXPECT_EQ(registry, GetDocument().GetPropertyRegistry());
}

TEST_F(PropertyRegistryTest, RegisterProperty) {
  EXPECT_FALSE(Registration("--x"));

  auto* registered = RegisterProperty("--x");
  EXPECT_EQ(registered, Registration("--x"));
}

TEST_F(PropertyRegistryTest, DeclareProperty) {
  EXPECT_FALSE(Registration("--x"));

  auto* declared = DeclareProperty("--x");
  EXPECT_EQ(declared, Registration("--x"));
}

TEST_F(PropertyRegistryTest, DeclareThenRegisterProperty) {
  auto* declared = DeclareProperty("--x");
  EXPECT_EQ(declared, Registration("--x"));

  auto* registered = RegisterProperty("--x");
  EXPECT_EQ(registered, Registration("--x"));
}

TEST_F(PropertyRegistryTest, RegisterThenDeclareProperty) {
  auto* registered = RegisterProperty("--x");
  EXPECT_EQ(registered, Registration("--x"));

  DeclareProperty("--x");
  EXPECT_EQ(registered, Registration("--x"));
}

TEST_F(PropertyRegistryTest, RegisterAndDeclarePropertyNonOverlapping) {
  auto* registered = RegisterProperty("--x");
  EXPECT_EQ(registered, Registration("--x"));

  auto* declared = DeclareProperty("--y");
  EXPECT_EQ(declared, Registration("--y"));
  EXPECT_EQ(registered, Registration("--x"));
}

TEST_F(PropertyRegistryTest, DeclareTwice) {
  auto* declared1 = DeclareProperty("--x");
  EXPECT_EQ(declared1, Registration("--x"));

  auto* declared2 = DeclareProperty("--x");
  EXPECT_EQ(declared2, Registration("--x"));
}

TEST_F(PropertyRegistryTest, IsInRegisteredPropertySet) {
  EXPECT_FALSE(Registry().IsInRegisteredPropertySet("--x"));

  RegisterProperty("--x");
  EXPECT_TRUE(Registry().IsInRegisteredPropertySet("--x"));
  EXPECT_FALSE(Registry().IsInRegisteredPropertySet("--y"));

  DeclareProperty("--y");
  EXPECT_TRUE(Registry().IsInRegisteredPropertySet("--x"));
  EXPECT_FALSE(Registry().IsInRegisteredPropertySet("--y"));

  RegisterProperty("--y");
  EXPECT_TRUE(Registry().IsInRegisteredPropertySet("--y"));
  EXPECT_TRUE(Registry().IsInRegisteredPropertySet("--y"));
}

TEST_F(PropertyRegistryTest, EmptyIterator) {
  EXPECT_EQ(0u, AllRegistrations().size());
}

TEST_F(PropertyRegistryTest, IterateSingleRegistration) {
  auto* reg1 = RegisterProperty("--x");
  auto registrations = AllRegistrations();
  EXPECT_EQ(1u, registrations.size());
  EXPECT_TRUE(registrations.Contains(reg1));
}

TEST_F(PropertyRegistryTest, IterateDoubleRegistration) {
  auto* reg1 = RegisterProperty("--x");
  auto* reg2 = RegisterProperty("--y");

  auto registrations = AllRegistrations();
  EXPECT_EQ(2u, registrations.size());
  EXPECT_TRUE(registrations.Contains(reg1));
  EXPECT_TRUE(registrations.Contains(reg2));
}

TEST_F(PropertyRegistryTest, IterateSingleDeclaration) {
  auto* reg1 = DeclareProperty("--x");
  auto registrations = AllRegistrations();
  EXPECT_EQ(1u, registrations.size());
  EXPECT_TRUE(registrations.Contains(reg1));
}

TEST_F(PropertyRegistryTest, IterateDoubleDeclaration) {
  auto* reg1 = DeclareProperty("--x");
  auto* reg2 = DeclareProperty("--y");

  auto registrations = AllRegistrations();
  EXPECT_EQ(2u, registrations.size());
  EXPECT_TRUE(registrations.Contains(reg1));
  EXPECT_TRUE(registrations.Contains(reg2));
}

TEST_F(PropertyRegistryTest, IterateRegistrationAndDeclaration) {
  auto* reg1 = RegisterProperty("--x");
  auto* reg2 = DeclareProperty("--y");

  auto registrations = AllRegistrations();
  EXPECT_EQ(2u, registrations.size());
  EXPECT_TRUE(registrations.Contains(reg1));
  EXPECT_TRUE(registrations.Contains(reg2));
}

TEST_F(PropertyRegistryTest, IterateRegistrationAndDeclarationConflict) {
  auto* reg1 = RegisterProperty("--x");
  auto* reg2 = RegisterProperty("--y");
  auto* reg3 = DeclareProperty("--y");
  auto* reg4 = DeclareProperty("--z");

  auto registrations = AllRegistrations();
  EXPECT_EQ(3u, registrations.size());
  EXPECT_TRUE(registrations.Contains(reg1));
  EXPECT_TRUE(registrations.Contains(reg2));
  EXPECT_FALSE(registrations.Contains(reg3));
  EXPECT_TRUE(registrations.Contains(reg4));
}

TEST_F(PropertyRegistryTest, IterateFullOverlapSingle) {
  auto* reg1 = DeclareProperty("--x");
  auto* reg2 = RegisterProperty("--x");

  auto registrations = AllRegistrations();
  EXPECT_EQ(1u, registrations.size());
  EXPECT_FALSE(registrations.Contains(reg1));
  EXPECT_TRUE(registrations.Contains(reg2));
}

TEST_F(PropertyRegistryTest, IterateFullOverlapMulti) {
  auto* reg1 = DeclareProperty("--x");
  auto* reg2 = DeclareProperty("--y");
  auto* reg3 = RegisterProperty("--x");
  auto* reg4 = RegisterProperty("--y");

  auto registrations = AllRegistrations();
  EXPECT_EQ(2u, registrations.size());
  EXPECT_FALSE(registrations.Contains(reg1));
  EXPECT_FALSE(registrations.Contains(reg2));
  EXPECT_TRUE(registrations.Contains(reg3));
  EXPECT_TRUE(registrations.Contains(reg4));
}

TEST_F(PropertyRegistryTest, IsEmptyUntilRegisterProperty) {
  EXPECT_TRUE(Registry().IsEmpty());
  RegisterProperty("--x");
  EXPECT_FALSE(Registry().IsEmpty());
}

TEST_F(PropertyRegistryTest, IsEmptyUntilDeclareProperty) {
  EXPECT_TRUE(Registry().IsEmpty());
  DeclareProperty("--x");
  EXPECT_FALSE(Registry().IsEmpty());
}

TEST_F(PropertyRegistryTest, Version) {
  EXPECT_EQ(0u, Registry().Version());

  RegisterProperty("--a");
  EXPECT_EQ(1u, Registry().Version());

  RegisterProperty("--b");
  EXPECT_EQ(2u, Registry().Version());

  DeclareProperty("--c");
  EXPECT_EQ(3u, Registry().Version());

  DeclareProperty("--c");
  EXPECT_EQ(4u, Registry().Version());

  DeclareProperty("--d");
  EXPECT_EQ(5u, Registry().Version());

  Registry().RemoveDeclaredProperties();
  EXPECT_EQ(6u, Registry().Version());

  Registry().RemoveDeclaredProperties();
  EXPECT_EQ(6u, Registry().Version());
}

TEST_F(PropertyRegistryTest, RemoveDeclaredProperties) {
  DeclareProperty("--a");
  DeclareProperty("--b");
  RegisterProperty("--c");
  RegisterProperty("--d");

  EXPECT_TRUE(Registration("--a"));
  EXPECT_TRUE(Registration("--b"));
  EXPECT_TRUE(Registration("--c"));
  EXPECT_TRUE(Registration("--d"));

  Registry().RemoveDeclaredProperties();

  EXPECT_FALSE(Registration("--a"));
  EXPECT_FALSE(Registration("--b"));
  EXPECT_TRUE(Registration("--c"));
  EXPECT_TRUE(Registration("--d"));
}

TEST_F(PropertyRegistryTest, MarkReferencedRegisterProperty) {
  css_test_helpers::RegisterProperty(GetDocument(), "--x", "<length>", "0px",
                                     false);

  UpdateAllLifecyclePhasesForTest();
  EXPECT_FALSE(Registry().WasReferenced("--x"));

  GetDocument().documentElement()->setInnerHTML(R"HTML(

Test

  )HTML");

  UpdateAllLifecyclePhasesForTest();
  EXPECT_TRUE(Registry().WasReferenced("--x"));
}

TEST_F(PropertyRegistryTest, MarkReferencedAtProperty) {
  UpdateAllLifecyclePhasesForTest();
  EXPECT_FALSE(Registry().WasReferenced("--x"));

  GetDocument().documentElement()->setInnerHTML(R"HTML(

Test

  )HTML");

  UpdateAllLifecyclePhasesForTest();
  EXPECT_TRUE(Registry().WasReferenced("--x"));

  css_test_helpers::RegisterProperty(GetDocument(), "--x", "<length>", "1px",
                                     false);

  // Check that the registration was successful, and did overwrite the
  // declaration.
  ASSERT_TRUE(Registration("--x"));
  ASSERT_TRUE(Registration("--x")->Initial());
  EXPECT_EQ("1px", Registration("--x")->Initial()->CssText());

  // --x should still be marked as referenced, even though RegisterProperty
  // now takes precedence over @property.
  UpdateAllLifecyclePhasesForTest();
  EXPECT_TRUE(Registry().WasReferenced("--x"));
}

TEST_F(PropertyRegistryTest, GetViewportUnitFlagsRegistered) {
  ScopedCSSViewportUnits4ForTest scoped_feature(true);

  EXPECT_EQ(
      0u, RegisterProperty("--px", "<length>", "1px")->GetViewportUnitFlags());
  EXPECT_EQ(
      static_cast<unsigned>(ViewportUnitFlag::kStatic),
      RegisterProperty("--vh", "<length>", "1vh")->GetViewportUnitFlags());
  EXPECT_EQ(
      static_cast<unsigned>(ViewportUnitFlag::kStatic),
      RegisterProperty("--svh", "<length>", "1svh")->GetViewportUnitFlags());
  EXPECT_EQ(
      static_cast<unsigned>(ViewportUnitFlag::kStatic),
      RegisterProperty("--lvh", "<length>", "1lvh")->GetViewportUnitFlags());
  EXPECT_EQ(
      static_cast<unsigned>(ViewportUnitFlag::kDynamic),
      RegisterProperty("--dvh", "<length>", "1dvh")->GetViewportUnitFlags());
  EXPECT_EQ(static_cast<unsigned>(ViewportUnitFlag::kStatic) |
                static_cast<unsigned>(ViewportUnitFlag::kDynamic),
            RegisterProperty("--mixed", "<length>", "calc(1dvh + 1svh)")
                ->GetViewportUnitFlags());
}

TEST_F(PropertyRegistryTest, GetViewportUnitFlagsDeclared) {
  ScopedCSSViewportUnits4ForTest scoped_feature(true);

  EXPECT_EQ(0u,
            DeclareProperty("--px", "<length>", "1px")->GetViewportUnitFlags());
  EXPECT_EQ(static_cast<unsigned>(ViewportUnitFlag::kStatic),
            DeclareProperty("--vh", "<length>", "1vh")->GetViewportUnitFlags());
  EXPECT_EQ(
      static_cast<unsigned>(ViewportUnitFlag::kStatic),
      DeclareProperty("--svh", "<length>", "1svh")->GetViewportUnitFlags());
  EXPECT_EQ(
      static_cast<unsigned>(ViewportUnitFlag::kStatic),
      DeclareProperty("--lvh", "<length>", "1lvh")->GetViewportUnitFlags());
  EXPECT_EQ(
      static_cast<unsigned>(ViewportUnitFlag::kDynamic),
      DeclareProperty("--dvh", "<length>", "1dvh")->GetViewportUnitFlags());
  EXPECT_EQ(static_cast<unsigned>(ViewportUnitFlag::kStatic) |
                static_cast<unsigned>(ViewportUnitFlag::kDynamic),
            DeclareProperty("--mixed", "<length>", "calc(1dvh + 1svh)")
                ->GetViewportUnitFlags());
}

TEST_F(PropertyRegistryTest, GetViewportUnitFlagsRegistry) {
  ScopedCSSViewportUnits4ForTest scoped_feature(true);

  EXPECT_EQ(0u, Registry().GetViewportUnitFlags());

  RegisterProperty("--vh", "<length>", "1vh");
  EXPECT_EQ(static_cast<unsigned>(ViewportUnitFlag::kStatic),
            Registry().GetViewportUnitFlags());

  DeclareProperty("--dvh", "<length>", "1dvh");
  EXPECT_EQ(static_cast<unsigned>(ViewportUnitFlag::kStatic) |
                static_cast<unsigned>(ViewportUnitFlag::kDynamic),
            Registry().GetViewportUnitFlags());

  Registry().RemoveDeclaredProperties();
  EXPECT_EQ(static_cast<unsigned>(ViewportUnitFlag::kStatic),
            Registry().GetViewportUnitFlags());
}

}  // namespace blink


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Jonas Colmsjö's blog</title>
    <meta name="viewport"    content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author"      content="Jonas Colmsjö">

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

    <link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
    <link href="assets/css/bs-styles.css"            rel="stylesheet">

    <link rel="shortcut icon" href="assets/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72"   href="assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed"                 href="assets/ico/apple-touch-icon-57-precomposed.png">

Home

NoSQL DB with REST API

NoSQL DB with REST API

I played around with Cassandra which was really easy to install and to get started with.
BUT it don't have a REST API and is likely difficult to access directly from JavaScript
in a browser (something I'd like to do).

This article has a nice summary of NoSQL DBs:

http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis

Riak, CouchDB, HBase and Neo4j have REST API:s. I'd also like to have Haddop support so I'll
test HBase.

Install HBase from source

wget http://apache.mirror3.ip-only.net/hbase/stable/hbase-0.94.5.tar.gz
tar -xzf hbase-0.94.5.tar.gz
cd hbase-0.94.5

cat README.txt

nano conf/hbase-site.xml

  <property>
    <name>hbase.rootdir</name>
    <value>file:///tmp/hbase</value>
  </property>
  <property>
    <name>hbase.zookeeper.property.dataDir</name>
    <value>/tmp/zookeeper</value>
  </property>

Let's try to start:

./bin/start-hbase.sh

Check the log file:

cat  /Users/jonas/local/hbase-0.94.5/bin/../logs/hbase-jonas-master-Gizur-Laptop-5.local.out
2013-03-12 13:59:26.806 java[5294:217] Unable to load realm info from SCDynamicStore

Install HBase using brew

http://jamil.fluidsoul.net/2011/06/28/getting-hbase-and-thrift-running-on-a-mac

brew install hbase

ls /usr/local/Cellar/hbase/0.94.4
ls /usr/local/bin/hbase*

nano /usr/local/Cellar/hbase/0.94.4/libexec/conf/hbase-site.xml

  <property>
    <name>hbase.rootdir</name>
    <value>file:///tmp/hbase</value>
  </property>
  <property>
    <name>hbase.zookeeper.property.dataDir</name>
    <value>/tmp/zookeeper</value>
  </property>

Now start hbase:

export HADOOP_OPTS="-Djava.security.krb5.realm= -Djava.security.krb5.kdc="
/usr/local/Cellar/hbase/0.94.4/bin/start-hbase.sh

/usr/local/Cellar/hbase/0.94.4/bin/stop-hbase.sh

I'm getting the same error as above. This seams to be a Java/Kerberos related problem.
OSX has JRE 1.6 and this is fixed in JRE 1.7.

This don't work either

HBase on Elastic Map Reduce (EMR)

AWS has a Hadoop and HBase service. This makes it easy to start a EC2-cluster with HBase.

See separate post from 130227 regarding howto get started with EMR. All that is needed in
addition is --hbase flag.

# Start new job
elastic-mapreduce --create --hbase --instance-type m1.large --alive

# Login using ssh
elastic-mapreduce --ssh --jobflow <JOBFLOWID>

# Start hbase shell
./bin/hbase shell

Example using hbase

Start the hbase shell and run:

```
create 'table', 'column'

put 'table', 'key', 'column', 'value'

scan 'table'

get 'table', 'key'

``

About the author

Jonas Colmsjö

          colmsjo

          colmsjo

Gothenburg, Sweden

About this article

Date Released:

Tuesday, March 12, 2013

        (c) Jonas Colmsjö 2012
        Follow @colmsjo
 View Jonas Colmsjö's profile


text:
class EventsController < ApplicationController
  before_action :set_course
  before_action :set_event, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, only: [:new, :edit, :create, :update, :destroy]
  after_action :verify_authorized

  # GET /events
  # GET /events.json
  def index
    @events = policy_scope(@course.events.all)
    authorize Event
  end

  # GET /events/1
  # GET /events/1.json
  def show
    authorize @event
  end

  # GET /events/new
  def new
    @event = Event.new
    authorize @event
  end

  # GET /events/1/edit
  def edit
    authorize @event
  end

  # POST /events
  # POST /events.json
  def create
    @event = @course.events.build(event_params)
    @event.user = current_user
    authorize @event

    respond_to do |format|
      if @event.save
        format.html { redirect_to [@course, @event], notice: 'Event was successfully created.' }
        format.json { render :show, status: :created, location: [@course, @event] }
      else
        format.html { render :new }
        format.json { render json: @event.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /events/1
  # PATCH/PUT /events/1.json
  def update
    authorize @event
    respond_to do |format|
      if @event.update(event_params)
        format.html { redirect_to [@course, @event], notice: 'Event was successfully updated.' }
        format.json { render :show, status: :ok, location: [@course, @event] }
      else
        format.html { render :edit }
        format.json { render json: @event.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /events/1
  # DELETE /events/1.json
  def destroy
    authorize @event
    @event.destroy
    respond_to do |format|
      format.html { redirect_to course_events_url, notice: 'Event was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    def set_course
      @course = Course.find(params[:course_id])
    end
    # Use callbacks to share common setup or constraints between actions.
    def set_event
      @event = @course.events.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def event_params
      params.require(:event).permit(:title, :description, :starts_at, :ends_at, :user_id, :location, course_attributes: [:id])
    end
end


text:
import unittest
from . import util
import time
import json

from biokbase.narrative.common.narrative_logger import NarrativeLogger
from biokbase.narrative.common.url_config import URLS
from biokbase.narrative.common.util import kbase_env

class NarrativeLoggerTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.log_host = 'localhost'
        # self.log_port = 34567
        self.poll_interval = 0.5
        self.real_log_host = URLS.log_host
        self.real_log_port = URLS.log_port
        URLS.log_host = self.log_host
        # URLS.log_port = self.log_port
        # self.logger = NarrativeLogger()

    @classmethod
    def tearDownClass(self):
        URLS.log_host = self.real_log_host
        URLS.log_port = self.real_log_port

    @classmethod
    def start_log_stack(self):
        # start up a dummy listener on the (hopefully dev) host and port, etc.
        log_port = util.find_free_port()
        URLS.log_port = log_port
        self.log_recv, self.log_recv_thread = util.start_tcp_server(
            self.log_host, log_port, self.poll_interval, bufferer=util.NarrativeMessageBufferer
        )

    @classmethod
    def stop_log_stack(self):
        # shut down docker compose, etc.
        util.stop_tcp_server(self.log_recv, self.log_recv_thread)

    def test_logger_init(self):
        logger = NarrativeLogger()
        self.assertEqual(logger.host, URLS.log_host)
        self.assertEqual(logger.port, URLS.log_port)
        self.assertEqual(logger.env, kbase_env.env)

    def test_null_logger(self):
        URLS.log_host = None
        URLS.log_port = None
        null_logger = NarrativeLogger()
        self.start_log_stack()
        null_logger.narrative_open("12345/67", 8)
        time.sleep(self.poll_interval * 4)
        data = self.log_recv.get_data()
        self.stop_log_stack()
        self.assertFalse(data)
        URLS.log_host = self.log_host

    def test_open_narr(self):
        narrative = "12345/67"
        version = 8
        self.start_log_stack()
        logger = NarrativeLogger()
        logger.narrative_open(narrative, version)
        time.sleep(self.poll_interval * 4)
        self.assert_log_msg(self.log_recv.get_data(), "open", narrative, version)
        self.stop_log_stack()

    def test_save_narr(self):
        narrative = "67890/12"
        version = 3
        self.start_log_stack()
        logger = NarrativeLogger()
        logger.narrative_save(narrative, version)
        time.sleep(self.poll_interval * 4)
        self.assert_log_msg(self.log_recv.get_data(), "save", narrative, version)
        self.stop_log_stack()

    def test_failed_message(self):
        """
        Test that we don't throw an exception if we try to write a log without a receiving server.
        i.e. - don't start the log stack.
        """
        try:
            logger = NarrativeLogger()
            logger.narrative_save("12345/67", 8)
        except:
            self.fail('Log writing threw an unexpected exception without a live socket!')

    def assert_log_msg(self, msg, event, narrative, version):
        data = json.loads(msg)
        self.assertEqual(data["type"], "narrative")
        self.assertEqual(data["user"], "anonymous")
        self.assertEqual(data["env"], "dev")
        self.assertEqual(data["narr_ver"], version)
        self.assertEqual(data["narrative"], narrative)
        self.assertEqual(data["operation"], event)

if __name__ == "__main__":
    unittest.main()


text:
package com.balonbal.slybot.config;

import com.balonbal.slybot.Main;
import com.balonbal.slybot.commands.Command;
import com.balonbal.slybot.lib.Reference;

import java.io.File;
import java.util.HashMap;
import java.util.regex.Pattern;

public class ChannelConfig implements Config{

    File file;

    String channelName;
    String trigger;
    Pattern triggerRegex;

    HashMap<String, Integer> permissionsMap;
    HashMap<String, String> strings;

    public ChannelConfig(String channel) {
        channelName = channel;

        trigger = "";
        permissionsMap = new HashMap<>();
        strings = new HashMap<>();

        buildDefaults();
    }

    @Override
    public void updateSetting(String key, Object value) {
        try {
            switch (key) {
                case Reference.CONFIG_CHANNEL_NAME:
                    channelName = String.valueOf(value);
                    break;
                case Reference.CONFIG_CHANNEL_PERMISSIONS:
                    HashMap<String, Integer> map = (HashMap<String, Integer>) value;
                    for (String k: map.keySet()) {
                        permissionsMap.put(k, map.get(k));
                    }
                    break;
                case Reference.CONFIG_CHANNEL_STRINGS:
                    strings = (HashMap<String, String>) value;
                    break;
                case Reference.CONFIG_CHANNEL_TRIGGERS:
                    trigger = String.valueOf(value);
                    triggerRegex = Pattern.compile(trigger.replaceAll("\\$BOTNICK", Main.getBot().getNick()), Pattern.CASE_INSENSITIVE);
                    break;
            }
        } catch (ClassCastException e) {
            System.out.println("Loaded illegal value for key " + key + ": " + e.toString());
        }
    }

    @Override
    public void appendSetting(String key, Object value) {

    }

    @Override
    public void removeSetting(String key, Object value) {

    }

    @Override
    public HashMap<String, Object> getSaveValues() {
        HashMap<String, Object> map = new HashMap<>();

        map.put(Reference.CONFIG_CHANNEL_NAME, channelName);
        map.put(Reference.CONFIG_CHANNEL_TRIGGERS, trigger);
        map.put(Reference.CONFIG_CHANNEL_PERMISSIONS, permissionsMap);
        map.put(Reference.CONFIG_CHANNEL_STRINGS, strings);

        return map;
    }

    @Override
    public void setSaveLocation(File file) {
        this.file = file;
    }

    @Override
    public File getSaveLocation() {
        return file;
    }

    public void buildDefaults() {
        //Build permission defaults
        for (Command c: Main.getCommandListener().getCommandHandler().getCommands()) {
            if (!permissionsMap.containsKey(c.getTrigger())) {
                permissionsMap.put(c.getTrigger(), c.requiresOP());
            }
        }
        //Build trigger defaults
        if (trigger.equals("")) {
            trigger = Reference.PREFIX_REGEX;
            triggerRegex = Pattern.compile(trigger.replaceAll("\\$BOTNICK", Main.getBot().getNick()), Pattern.CASE_INSENSITIVE);
        }
    }

    public String getChannelName() {
        return channelName;
    }

    public void setChannelName(String channelName) {
        this.channelName = channelName;
    }

    public void updatePermission(String command, int value) {
        //This will also override previous values
        permissionsMap.put(command, value);
    }

    public int getPermission(String command) {
        return permissionsMap.containsKey(command) ? permissionsMap.get(command) : -1;
    }

    public HashMap<String, Integer> getPermissionsMap() {
        return permissionsMap;
    }

    public void updateString(String string, String value) {
        strings.put(string, value);
    }

    public String getString(String string) {
        return strings.containsKey(string) ? strings.get(string) : "";
    }

    public Pattern getTrigger() {
        return triggerRegex;
    }

    public String getTriggerString() {
        return trigger;
    }

    public void setTrigger(String trigger) {
        System.out.println("Building trigger for nick: " + Main.getBot().getNick());
        this.trigger = trigger;
        triggerRegex = Pattern.compile(trigger.replaceAll("\\$BOTNICK", Main.getBot().getNick()), Pattern.CASE_INSENSITIVE);
    }

    public void setPermission(String trigger, int level) {
        //Also overrides any previous value, be careful
        permissionsMap.put(trigger, level);
    }
}


text:
const _ = require('lodash');
const logging = require('@tryghost/logging');
const membersService = require('./service');
const urlUtils = require('../../../shared/url-utils');
const ghostVersion = require('@tryghost/version');
const settingsCache = require('../../../shared/settings-cache');
const {formattedMemberResponse} = require('./utils');
const labsService = require('../../../shared/labs');
const config = require('../../../shared/config');

// @TODO: This piece of middleware actually belongs to the frontend, not to the member app
// Need to figure a way to separate these things (e.g. frontend actually talks to members API)
const loadMemberSession = async function (req, res, next) {
    try {
        const member = await membersService.ssr.getMemberDataFromSession(req, res);
        Object.assign(req, {member});
        res.locals.member = req.member;
        next();
    } catch (err) {
        Object.assign(req, {member: null});
        next();
    }
};

const getIdentityToken = async function (req, res) {
    try {
        const token = await membersService.ssr.getIdentityTokenForMemberFromSession(req, res);
        res.writeHead(200);
        res.end(token);
    } catch (err) {
        res.writeHead(204);
        res.end();
    }
};

const deleteSession = async function (req, res) {
    try {
        await membersService.ssr.deleteSession(req, res);
        res.writeHead(204);
        res.end();
    } catch (err) {
        res.writeHead(err.statusCode);
        res.end(err.message);
    }
};

const getMemberData = async function (req, res) {
    try {
        const member = await membersService.ssr.getMemberDataFromSession(req, res);
        if (member) {
            res.json(formattedMemberResponse(member));
        } else {
            res.json(null);
        }
    } catch (err) {
        res.writeHead(204);
        res.end();
    }
};

const updateMemberData = async function (req, res) {
    try {
        const data = _.pick(req.body, 'name', 'subscribed');
        const member = await membersService.ssr.getMemberDataFromSession(req, res);
        if (member) {
            const options = {
                id: member.id,
                withRelated: ['stripeSubscriptions', 'stripeSubscriptions.customer', 'stripeSubscriptions.stripePrice']
            };
            const updatedMember = await membersService.api.members.update(data, options);

            res.json(formattedMemberResponse(updatedMember.toJSON()));
        } else {
            res.json(null);
        }
    } catch (err) {
        res.writeHead(err.statusCode);
        res.end(err.message);
    }
};

const getPortalProductPrices = async function () {
    const page = await membersService.api.productRepository.list({
        withRelated: ['monthlyPrice', 'yearlyPrice', 'benefits']
    });

    const products = page.data.map((productModel) => {
        const product = productModel.toJSON();
        const productPrices = [];
        if (product.monthlyPrice) {
            productPrices.push(product.monthlyPrice);
        }
        if (product.yearlyPrice) {
            productPrices.push(product.yearlyPrice);
        }
        return {
            id: product.id,
            name: product.name,
            description: product.description || '',
            monthlyPrice: product.monthlyPrice,
            yearlyPrice: product.yearlyPrice,
            benefits: product.benefits,
            prices: productPrices
        };
    });
    const defaultProduct = products[0];
    const defaultPrices = defaultProduct ? defaultProduct.prices : [];
    let portalProducts = defaultProduct ? [defaultProduct] : [];
    if (labsService.isSet('multipleProducts')) {
        portalProducts = products;
    }

    return {
        prices: defaultPrices,
        products: portalProducts
    };
};

const getMemberSiteData = async function (req, res) {
    const isStripeConfigured = membersService.config.isStripeConnected();
    const domain = urlUtils.urlFor('home', true).match(new RegExp('^https?://([^/:?#]+)(?:[/:?#]|$)', 'i'));
    const firstpromoterId = settingsCache.get('firstpromoter') ? settingsCache.get('firstpromoter_id') : '';
    const blogDomain = domain && domain[1];
    let supportAddress = settingsCache.get('members_support_address') || 'noreply';
    if (!supportAddress.includes('@')) {
        supportAddress = `${supportAddress}@${blogDomain}`;
    }
    const {products = [], prices = []} = await getPortalProductPrices() || {};
    const portalVersion = config.get('portal:version');

    const response = {
        title: settingsCache.get('title'),
        description: settingsCache.get('description'),
        logo: settingsCache.get('logo'),
        icon: settingsCache.get('icon'),
        accent_color: settingsCache.get('accent_color'),
        url: urlUtils.urlFor('home', true),
        version: ghostVersion.safe,
        portal_version: portalVersion,
        free_price_name: settingsCache.get('members_free_price_name'),
        free_price_description: settingsCache.get('members_free_price_description'),
        allow_self_signup: membersService.config.getAllowSelfSignup(),
        members_signup_access: settingsCache.get('members_signup_access'),
        is_stripe_configured: isStripeConfigured,
        portal_button: settingsCache.get('portal_button'),
        portal_name: settingsCache.get('portal_name'),
        portal_plans: settingsCache.get('portal_plans'),
        portal_button_icon: settingsCache.get('portal_button_icon'),
        portal_button_signup_text: settingsCache.get('portal_button_signup_text'),
        portal_button_style: settingsCache.get('portal_button_style'),
        firstpromoter_id: firstpromoterId,
        members_support_address: supportAddress,
        prices,
        products
    };
    if (labsService.isSet('multipleProducts')) {
        response.portal_products = settingsCache.get('portal_products');
    }
    if (config.get('portal_sentry') && !config.get('portal_sentry').disabled) {
        response.portal_sentry = {
            dsn: config.get('portal_sentry').dsn,
            env: config.get('env')
        };
    }
    res.json({site: response});
};

const createSessionFromMagicLink = async function (req, res, next) {
    if (!req.url.includes('token=')) {
        return next();
    }

    // req.query is a plain object, copy it to a URLSearchParams object so we can call toString()
    const searchParams = new URLSearchParams('');
    Object.keys(req.query).forEach((param) => {
        // don't copy the token param
        if (param !== 'token') {
            searchParams.set(param, req.query[param]);
        }
    });

    try {
        const member = await membersService.ssr.exchangeTokenForSession(req, res);
        const subscriptions = member && member.subscriptions || [];

        const action = req.query.action;

        if (action === 'signup') {
            let customRedirect = '';
            if (subscriptions.find(sub => ['active', 'trialing'].includes(sub.status))) {
                customRedirect = settingsCache.get('members_paid_signup_redirect') || '';
            } else {
                customRedirect = settingsCache.get('members_free_signup_redirect') || '';
            }

            if (customRedirect && customRedirect !== '/') {
                const baseUrl = urlUtils.getSiteUrl();
                const ensureEndsWith = (string, endsWith) => (string.endsWith(endsWith) ? string : string + endsWith);
                const removeLeadingSlash = string => string.replace(/^\//, '');

                const redirectUrl = new URL(removeLeadingSlash(ensureEndsWith(customRedirect, '/')), ensureEndsWith(baseUrl, '/'));

                return res.redirect(redirectUrl.href);
            }
        }

        // Do a standard 302 redirect to the homepage, with success=true
        searchParams.set('success', true);
        res.redirect(`${urlUtils.getSubdir()}/?${searchParams.toString()}`);
    } catch (err) {
        logging.warn(err.message);

        // Do a standard 302 redirect to the homepage, with success=false
        searchParams.set('success', false);
        res.redirect(`${urlUtils.getSubdir()}/?${searchParams.toString()}`);
    }
};

// Set req.member & res.locals.member if a cookie is set
module.exports = {
    loadMemberSession,
    createSessionFromMagicLink,
    getIdentityToken,
    getMemberData,
    updateMemberData,
    getMemberSiteData,
    deleteSession,
    stripeWebhooks: (req, res, next) => membersService.api.middleware.handleStripeWebhook(req, res, next)
};


text:
'use strict';

const fs     = require('fs');
const yaml   = require('js-yaml');

var stat_cache = {};

function stat(pathname) {
  if (!Object.prototype.hasOwnProperty.call(stat_cache, pathname)) {
    try {
      stat_cache[pathname] = fs.statSync(pathname);
    } catch (err) {
      if (err.code !== 'ENOENT') throw err;
      stat_cache[pathname] = null;
    }
  }

  return stat_cache[pathname];
}

var dir_cache = {};

function dir(dirname) {
  if (!Object.prototype.hasOwnProperty.call(dir_cache, dirname)) {
    try {
      dir_cache[dirname] = fs.readdirSync(dirname);
    } catch (__) {
      dir_cache[dirname] = null;
    }
  }

  return dir_cache[dirname];
}

var file_cache = {};

function file(filename, encoding) {
  encoding = encoding || null;

  if (!file_cache[encoding]) {
    file_cache[encoding] = {};
  }

  if (!Object.prototype.hasOwnProperty.call(file_cache[encoding], filename)) {
    try {
      file_cache[encoding][filename] = fs.readFileSync(filename, encoding);
    } catch (__) {
      file_cache[encoding][filename] = null;
    }
  }

  return file_cache[encoding][filename];
}

function reset() {
  stat_cache = {};
  dir_cache  = {};
  file_cache = {};
}

module.exports.stat  = stat;
module.exports.dir   = dir;
module.exports.file  = file;
module.exports.reset = reset;

module.exports.yaml = function (filename) {
  let content = file(filename, 'utf8');

  if (content === null) throw new Error(`Can't find file ${filename}`);

  return yaml.load(content, { filename });
};


text:
package net.sourceforge.myvd.test.Server;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import net.sourceforge.myvd.chain.AddInterceptorChain;
import net.sourceforge.myvd.chain.BindInterceptorChain;
import net.sourceforge.myvd.chain.DeleteInterceptorChain;
import net.sourceforge.myvd.chain.ExetendedOperationInterceptorChain;
import net.sourceforge.myvd.chain.ModifyInterceptorChain;
import net.sourceforge.myvd.chain.RenameInterceptorChain;
import net.sourceforge.myvd.chain.SearchInterceptorChain;
import net.sourceforge.myvd.core.NameSpace;
import net.sourceforge.myvd.inserts.Insert;
import net.sourceforge.myvd.inserts.extensions.PasswordChangeOperation;
import net.sourceforge.myvd.inserts.ldap.LDAPInterceptor;
import net.sourceforge.myvd.router.Router;
import net.sourceforge.myvd.server.Server;
import net.sourceforge.myvd.test.chain.TestChain;
import net.sourceforge.myvd.test.util.OpenLDAPUtils;
import net.sourceforge.myvd.test.util.StartMyVD;
import net.sourceforge.myvd.test.util.StartOpenLDAP;
import net.sourceforge.myvd.test.util.Util;
import net.sourceforge.myvd.types.Attribute;
import net.sourceforge.myvd.types.Bool;
import net.sourceforge.myvd.types.DistinguishedName;
import net.sourceforge.myvd.types.Entry;
import net.sourceforge.myvd.types.EntrySet;
import net.sourceforge.myvd.types.ExtendedOperation;
import net.sourceforge.myvd.types.Filter;
import net.sourceforge.myvd.types.Int;
import net.sourceforge.myvd.types.Password;
import net.sourceforge.myvd.types.Result;
import net.sourceforge.myvd.types.Results;
import net.sourceforge.myvd.types.SessionVariables;

import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPAttributeSet;
import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPConstraints;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPExtendedOperation;
import com.novell.ldap.LDAPJSSESecureSocketFactory;
import com.novell.ldap.LDAPModification;
import com.novell.ldap.LDAPSearchConstraints;
import com.novell.ldap.LDAPSearchResult;
import com.novell.ldap.LDAPSearchResults;
import com.novell.ldap.LDAPSocketFactory;
import com.novell.ldap.asn1.ASN1Identifier;
import com.novell.ldap.asn1.ASN1OctetString;
import com.novell.ldap.asn1.ASN1Sequence;
import com.novell.ldap.asn1.ASN1Tagged;
import com.novell.ldap.asn1.LBEREncoder;
import com.novell.ldap.util.DN;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import static org.junit.Assert.*;

public class TestVirtualMemberOfLocal {

	// Insert[] globalChain;
	// Router router;
	private static StartOpenLDAP baseServer;
	private static StartOpenLDAP internalServer;
	private static StartOpenLDAP externalServer;
	private static StartMyVD server;
	// private Server server;

	@BeforeClass
	public static void setUp() throws Exception {
		OpenLDAPUtils.killAllOpenLDAPS();
		baseServer = new StartOpenLDAP();
		baseServer.startServer(System.getenv("PROJ_DIR") + "/test/Base", 10983, "cn=admin,dc=domain,dc=com", "manager");

		internalServer = new StartOpenLDAP();
		internalServer.startServer(System.getenv("PROJ_DIR") + "/test/InternalUsers", 11983,
				"cn=admin,ou=internal,dc=domain,dc=com", "manager");

		externalServer = new StartOpenLDAP();
		externalServer.startServer(System.getenv("PROJ_DIR") + "/test/ExternalUsers", 12983,
				"cn=admin,ou=external,dc=domain,dc=com", "manager");

		server = new StartMyVD();
		server.startServer(System.getenv("PROJ_DIR") + "/test/TestServer/testVirtualMemberOf-local.props", 50983);

		// server = new Server(System.getenv("PROJ_DIR") +
		// "/test/TestServer/testconfig.props");
		// server.startServer();

		// globalChain = server.getGlobalChain();
		// router = server.getRouter();

		System.setProperty("javax.net.ssl.trustStore", System.getenv("PROJ_DIR") + "/test/TestServer/testconfig.jks");

	}

	@Test
	public void testStartServer() throws Exception {

		LDAPConnection con = new LDAPConnection();
		con.connect("127.0.0.1", 50983);
		// con.bind(3,"ou=internal,o=mycompany","secret".getBytes());

		LDAPSearchResults res = con.search("ou=internal,o=mycompany,c=us", 2, "(objectClass=*)", new String[0], false);
		while (res.hasMore()) {
			System.out.println(res.next().getDN());
		}

		con.disconnect();

	}

	@Test
	public void testSearchSubtreeResults() throws LDAPException {

		LDAPAttributeSet attribs = new LDAPAttributeSet();
		attribs.add(new LDAPAttribute("objectClass", "inetOrgPerson"));
		attribs.add(new LDAPAttribute("cn", "Test User"));
		attribs.add(new LDAPAttribute("sn", "User"));

		attribs.add(new LDAPAttribute("uid", "testUser"));
		attribs.add(new LDAPAttribute("userPassword", "secret"));

		LDAPEntry entry2 = new LDAPEntry("cn=Test User,ou=internal,o=mycompany,c=us", attribs);

		attribs = new LDAPAttributeSet();
		attribs.add(new LDAPAttribute("objectClass", "inetOrgPerson"));
		attribs.add(new LDAPAttribute("cn", "Test Cust"));
		attribs.add(new LDAPAttribute("sn", "Cust"));
		attribs.add(new LDAPAttribute("uid", "testCust"));
		attribs.add(new LDAPAttribute("userPassword", "secret"));
		attribs.add(new LDAPAttribute("memberOf", "cn=Test Group,ou=external,o=mycompany,c=us"));

		LDAPEntry entry1 = new LDAPEntry("cn=Test Cust,ou=external,o=mycompany,c=us", attribs);

		LDAPConnection con = new LDAPConnection();
		con.connect("127.0.0.1", 50983);
		// con.bind(3,"cn=admin,o=mycompany","manager".getBytes());
		LDAPSearchResults res = con.search("o=mycompany,c=us", 2, "(objectClass=inetOrgPerson)", new String[] {},
				false);

		int size = 0;

		while (res.hasMore()) {

			LDAPEntry fromDir = res.next();

			LDAPEntry controlEntry = null;// control.get(fromDir.getEntry().getDN());

			if (size == 0) {
				controlEntry = entry1;
			} else if (size == 1) {
				controlEntry = entry2;
			} else {
				controlEntry = null;
			}

			if (controlEntry == null) {
				fail("Entry " + fromDir.getDN() + " should not be returned");
				return;
			}

			if (!Util.compareEntry(fromDir, controlEntry)) {
				fail("The entry was not correct : \n" + Util.toLDIF(fromDir) + "\nfrom control:\n"
						+ Util.toLDIF(controlEntry));
				return;
			}

			size++;
		}

		if (size != 2) {
			fail("Not the correct number of entries : " + size);
		}

		con.disconnect();
	}

	@Test
	public void testSearchSubtreeByMemberof() throws LDAPException {

		LDAPAttributeSet attribs = new LDAPAttributeSet();
		attribs.add(new LDAPAttribute("objectClass", "inetOrgPerson"));
		attribs.add(new LDAPAttribute("cn", "Test Cust"));
		attribs.add(new LDAPAttribute("sn", "Cust"));
		attribs.add(new LDAPAttribute("uid", "testCust"));
		attribs.add(new LDAPAttribute("userPassword", "secret"));
		attribs.add(new LDAPAttribute("memberOf", "cn=Test Group,ou=external,o=mycompany,c=us"));

		LDAPEntry entry1 = new LDAPEntry("cn=Test Cust,ou=external,o=mycompany,c=us", attribs);

		LDAPConnection con = new LDAPConnection();
		con.connect("127.0.0.1", 50983);
		// con.bind(3,"cn=admin,o=mycompany","manager".getBytes());
		LDAPSearchResults res = con.search("o=mycompany,c=us", 2, "(memberOf=cn=Test Group,ou=external,o=mycompany,c=us)", new String[] {},
				false);

		int size = 0;
		boolean found = false;
		while (res.hasMore()) {
			found = true;
			LDAPEntry fromDir = res.next();

			LDAPEntry controlEntry = null;// control.get(fromDir.getEntry().getDN());

			if (size == 0) {
				controlEntry = entry1;
			} else  {
				fail("Too many results");
			}

			assertTrue(Util.compareEntry(fromDir, controlEntry));

			size++;
		}

		con.disconnect();
		assertTrue(found);
	}

	@Test
	public void testSearchSubtreeMemberOfPlusFilter() throws LDAPException {

		LDAPAttributeSet attribs = new LDAPAttributeSet();
		attribs.add(new LDAPAttribute("objectClass", "inetOrgPerson"));
		attribs.add(new LDAPAttribute("cn", "Test User"));
		attribs.add(new LDAPAttribute("sn", "User"));

		attribs.add(new LDAPAttribute("uid", "testUser"));
		attribs.add(new LDAPAttribute("userPassword", "secret"));

		LDAPEntry entry2 = new LDAPEntry("cn=Test User,ou=internal,o=mycompany,c=us", attribs);

		attribs = new LDAPAttributeSet();
		attribs.add(new LDAPAttribute("objectClass", "inetOrgPerson"));
		attribs.add(new LDAPAttribute("cn", "Test Cust"));
		attribs.add(new LDAPAttribute("sn", "Cust"));
		attribs.add(new LDAPAttribute("uid", "testCust"));
		attribs.add(new LDAPAttribute("userPassword", "secret"));
		attribs.add(new LDAPAttribute("memberOf", "cn=Test Group,ou=external,o=mycompany,c=us"));

		LDAPEntry entry1 = new LDAPEntry("cn=Test Cust,ou=external,o=mycompany,c=us", attribs);

		LDAPConnection con = new LDAPConnection();
		con.connect("127.0.0.1", 50983);
		// con.bind(3,"cn=admin,o=mycompany","manager".getBytes());
		LDAPSearchResults res = con.search("o=mycompany,c=us", 2, "(|(memberOf=cn=Test Group,ou=external,o=mycompany,c=us)(uid=testUser))", new String[] {},
				false);

		int size = 0;

		while (res.hasMore()) {

			LDAPEntry fromDir = res.next();

			LDAPEntry controlEntry = null;// control.get(fromDir.getEntry().getDN());

			if (size == 0) {
				controlEntry = entry1;
			} else if (size == 1) {
				controlEntry = entry2;
			} else {
				controlEntry = null;
			}

			if (controlEntry == null) {
				fail("Entry " + fromDir.getDN() + " should not be returned");
				return;
			}

			if (!Util.compareEntry(fromDir, controlEntry)) {
				fail("The entry was not correct : \n" + Util.toLDIF(fromDir) + "\nfrom control:\n"
						+ Util.toLDIF(controlEntry));
				return;
			}

			size++;
		}

		if (size != 2) {
			fail("Not the correct number of entries : " + size);
		}

		con.disconnect();
	}

	@AfterClass
	public static void tearDown() throws Exception {

		baseServer.stopServer();
		internalServer.stopServer();
		externalServer.stopServer();
		server.stopServer();
		// server.stopServer();
	}

}


text:
    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import JdbcManagment.JsonConvert;
import static com.sun.corba.se.spi.presentation.rmi.StubAdapter.request;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sys.db;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.sql.ResultSet;
import org.json.JSONArray;
import org.json.JSONObject;
import sys.choronic;

/**
 *
 * @author Admin
 */
@WebServlet(name = "cordis", urlPatterns = {"/cordis"})
public class cordis extends HttpServlet {

     @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

          ResultSet rs = db.getdb("select * from chronic_disease");

        resp.getWriter().print(JsonConvert.getJSONFromResultSet(rs, "chronic_disease"));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        String json = "";
        if(br != null){
            json = br.readLine();

    }
        try{
             final JSONObject obj = new JSONObject(json);

      choronic c  = new choronic(obj.get("name").toString(),obj.get("note").toString().toString(), obj.get("type").toString());
       c.addtodb(c);

       }
       catch(Exception e){
       resp.getWriter().print(e);
              }
       resp.getWriter().print("success");
    }

}