text:
#include "bson/bson.h"
#include "mongoc/mongoc.h"

#include <php.h>
#include <Zend/zend_interfaces.h>

#include "php_array_api.h"

#include "php_phongo.h"
#include "phongo_error.h"

#include "MongoDB/Server.h"
#include "MongoDB/WriteConcern.h"
#include "MongoDB/WriteConcernError.h"
#include "MongoDB/WriteError.h"

#define PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(iter, bson, key)                \
	if (bson_iter_init_find((iter), (bson), (key)) && BSON_ITER_HOLDS_INT32((iter))) { \
		RETURN_LONG(bson_iter_int32((iter)));                                          \
	}

zend_class_entry* php_phongo_writeresult_ce;

static bool php_phongo_writeresult_get_writeconcernerror(php_phongo_writeresult_t* intern, zval* return_value) /* {{{ */
{
	bson_iter_t iter, child;
	zval        writeconcernerror;

	ZVAL_NULL(return_value);

	if (bson_iter_init_find(&iter, intern->reply, "writeConcernErrors") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
		while (bson_iter_next(&child)) {
			bson_t         cbson;
			uint32_t       len;
			const uint8_t* data;

			if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
				continue;
			}

			bson_iter_document(&child, &len, &data);

			if (!bson_init_static(&cbson, data, len)) {
				continue;
			}

			if (!phongo_writeconcernerror_init(&writeconcernerror, &cbson)) {
				zval_ptr_dtor(&writeconcernerror);
				return false;
			}

			ZVAL_ZVAL(return_value, &writeconcernerror, 1, 1);

			return true;
		}
	}

	return true;
} /* }}} */

static bool php_phongo_writeresult_get_writeerrors(php_phongo_writeresult_t* intern, zval* return_value) /* {{{ */
{
	bson_iter_t iter, child;

	array_init(return_value);

	if (bson_iter_init_find(&iter, intern->reply, "writeErrors") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
		while (bson_iter_next(&child)) {
			bson_t         cbson;
			uint32_t       len;
			const uint8_t* data;
			zval           writeerror;

			if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
				continue;
			}

			bson_iter_document(&child, &len, &data);

			if (!bson_init_static(&cbson, data, len)) {
				continue;
			}

			if (!phongo_writeerror_init(&writeerror, &cbson)) {
				zval_ptr_dtor(&writeerror);
				continue;
			}

			add_next_index_zval(return_value, &writeerror);
		}
	}

	return true;
} /* }}} */

/* {{{ proto integer|null MongoDB\Driver\WriteResult::getInsertedCount()
   Returns the number of documents that were inserted */
static PHP_METHOD(WriteResult, getInsertedCount)
{
	zend_error_handling       error_handling;
	bson_iter_t               iter;
	php_phongo_writeresult_t* intern;

	intern = Z_WRITERESULT_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);
	if (zend_parse_parameters_none() == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nInserted");
} /* }}} */

/* {{{ proto integer|null MongoDB\Driver\WriteResult::getMatchedCount()
   Returns the number of documents that matched the update criteria */
static PHP_METHOD(WriteResult, getMatchedCount)
{
	zend_error_handling       error_handling;
	bson_iter_t               iter;
	php_phongo_writeresult_t* intern;

	intern = Z_WRITERESULT_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);
	if (zend_parse_parameters_none() == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nMatched");
} /* }}} */

/* {{{ proto integer|null MongoDB\Driver\WriteResult::getModifiedCount()
   Returns the number of documents that were actually modified by an update */
static PHP_METHOD(WriteResult, getModifiedCount)
{
	zend_error_handling       error_handling;
	bson_iter_t               iter;
	php_phongo_writeresult_t* intern;

	intern = Z_WRITERESULT_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);
	if (zend_parse_parameters_none() == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nModified");
} /* }}} */

/* {{{ proto integer|null MongoDB\Driver\WriteResult::getDeletedCount()
   Returns the number of documents that were deleted */
static PHP_METHOD(WriteResult, getDeletedCount)
{
	zend_error_handling       error_handling;
	bson_iter_t               iter;
	php_phongo_writeresult_t* intern;

	intern = Z_WRITERESULT_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);
	if (zend_parse_parameters_none() == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nRemoved");
} /* }}} */

/* {{{ proto integer|null MongoDB\Driver\WriteResult::getUpsertedCount()
   Returns the number of documents that were upserted */
static PHP_METHOD(WriteResult, getUpsertedCount)
{
	zend_error_handling       error_handling;
	bson_iter_t               iter;
	php_phongo_writeresult_t* intern;

	intern = Z_WRITERESULT_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);
	if (zend_parse_parameters_none() == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nUpserted");
} /* }}} */

/* {{{ proto MongoDB\Driver\Server MongoDB\Driver\WriteResult::getServer()
   Returns the Server from which the result originated */
static PHP_METHOD(WriteResult, getServer)
{
	zend_error_handling       error_handling;
	php_phongo_writeresult_t* intern;

	intern = Z_WRITERESULT_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);
	if (zend_parse_parameters_none() == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	phongo_server_init(return_value, &intern->manager, intern->server_id);
} /* }}} */

/* {{{ proto array MongoDB\Driver\WriteResult::getUpsertedIds()
   Returns the identifiers generated by the server for upsert operations. */
static PHP_METHOD(WriteResult, getUpsertedIds)
{
	zend_error_handling       error_handling;
	bson_iter_t               iter, child;
	php_phongo_writeresult_t* intern;

	intern = Z_WRITERESULT_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);
	if (zend_parse_parameters_none() == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	array_init(return_value);

	if (bson_iter_init_find(&iter, intern->reply, "upserted") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
		while (bson_iter_next(&child)) {
			uint32_t              data_len;
			const uint8_t*        data = NULL;
			php_phongo_bson_state state;

			/* Use PHONGO_TYPEMAP_NATIVE_ARRAY for the root type so we can
			 * easily access the "index" and "_id" fields. */
			PHONGO_BSON_INIT_STATE(state);
			state.map.root_type = PHONGO_TYPEMAP_NATIVE_ARRAY;

			if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
				continue;
			}

			bson_iter_document(&child, &data_len, &data);

			if (php_phongo_bson_to_zval_ex(data, data_len, &state)) {
				zval* zid = php_array_fetchc(&state.zchild, "_id");
				add_index_zval(return_value, php_array_fetchc_long(&state.zchild, "index"), zid);
				zval_add_ref(zid);
			}

			zval_ptr_dtor(&state.zchild);
		}
	}
} /* }}} */

/* {{{ proto WriteConcernError MongoDB\Driver\WriteResult::getWriteConcernError()
   Return any write concern error that occurred */
static PHP_METHOD(WriteResult, getWriteConcernError)
{
	zend_error_handling       error_handling;
	php_phongo_writeresult_t* intern;

	intern = Z_WRITERESULT_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);
	if (zend_parse_parameters_none() == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	php_phongo_writeresult_get_writeconcernerror(intern, return_value);
} /* }}} */

/* {{{ proto WriteError[] MongoDB\Driver\WriteResult::getWriteErrors()
   Returns any write errors that occurred */
static PHP_METHOD(WriteResult, getWriteErrors)
{
	zend_error_handling       error_handling;
	php_phongo_writeresult_t* intern;

	intern = Z_WRITERESULT_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);
	if (zend_parse_parameters_none() == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	php_phongo_writeresult_get_writeerrors(intern, return_value);
} /* }}} */

/* {{{ proto boolean MongoDB\Driver\WriteResult::isAcknowledged()
   Returns whether the write operation was acknowledged (based on the write
   concern). */
static PHP_METHOD(WriteResult, isAcknowledged)
{
	zend_error_handling       error_handling;
	php_phongo_writeresult_t* intern;

	intern = Z_WRITERESULT_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);
	if (zend_parse_parameters_none() == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	RETURN_BOOL(mongoc_write_concern_is_acknowledged(intern->write_concern));
} /* }}} */

/* {{{ MongoDB\Driver\WriteResult function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_WriteResult_void, 0, 0, 0)
ZEND_END_ARG_INFO()

static zend_function_entry php_phongo_writeresult_me[] = {
	/* clang-format off */
	PHP_ME(WriteResult, getInsertedCount, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(WriteResult, getMatchedCount, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(WriteResult, getModifiedCount, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(WriteResult, getDeletedCount, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(WriteResult, getUpsertedCount, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(WriteResult, getServer, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(WriteResult, getUpsertedIds, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(WriteResult, getWriteConcernError, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(WriteResult, getWriteErrors, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(WriteResult, isAcknowledged, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_WriteResult_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
	ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_FE_END
	/* clang-format on */
};
/* }}} */

/* {{{ MongoDB\Driver\WriteResult object handlers */
static zend_object_handlers php_phongo_handler_writeresult;

static void php_phongo_writeresult_free_object(zend_object* object) /* {{{ */
{
	php_phongo_writeresult_t* intern = Z_OBJ_WRITERESULT(object);

	zend_object_std_dtor(&intern->std);

	if (intern->reply) {
		bson_destroy(intern->reply);
	}

	if (intern->write_concern) {
		mongoc_write_concern_destroy(intern->write_concern);
	}

	if (!Z_ISUNDEF(intern->manager)) {
		zval_ptr_dtor(&intern->manager);
	}
} /* }}} */

static zend_object* php_phongo_writeresult_create_object(zend_class_entry* class_type) /* {{{ */
{
	php_phongo_writeresult_t* intern = zend_object_alloc(sizeof(php_phongo_writeresult_t), class_type);

	zend_object_std_init(&intern->std, class_type);
	object_properties_init(&intern->std, class_type);

	intern->std.handlers = &php_phongo_handler_writeresult;

	return &intern->std;
} /* }}} */

static HashTable* php_phongo_writeresult_get_debug_info(phongo_compat_object_handler_type* object, int* is_temp) /* {{{ */
{
	php_phongo_writeresult_t* intern;
	zval                      retval = ZVAL_STATIC_INIT;
	bson_iter_t               iter;

	intern   = Z_OBJ_WRITERESULT(PHONGO_COMPAT_GET_OBJ(object));
	*is_temp = 1;
	array_init_size(&retval, 9);

#define PHONGO_WRITERESULT_SCP(field)                                                         \
	if (bson_iter_init_find(&iter, intern->reply, (field)) && BSON_ITER_HOLDS_INT32(&iter)) { \
		ADD_ASSOC_LONG_EX(&retval, (field), bson_iter_int32(&iter));                          \
	} else {                                                                                \
		ADD_ASSOC_NULL_EX(&retval, (field));                                                  \
	}

	PHONGO_WRITERESULT_SCP("nInserted");
	PHONGO_WRITERESULT_SCP("nMatched");
	PHONGO_WRITERESULT_SCP("nModified");
	PHONGO_WRITERESULT_SCP("nRemoved");
	PHONGO_WRITERESULT_SCP("nUpserted");
#undef PHONGO_WRITERESULT_SCP

	if (bson_iter_init_find(&iter, intern->reply, "upserted") && BSON_ITER_HOLDS_ARRAY(&iter)) {
		uint32_t              len;
		const uint8_t*        data;
		php_phongo_bson_state state;

		PHONGO_BSON_INIT_DEBUG_STATE(state);
		bson_iter_array(&iter, &len, &data);
		if (!php_phongo_bson_to_zval_ex(data, len, &state)) {
			zval_ptr_dtor(&state.zchild);
			goto done;
		}

		ADD_ASSOC_ZVAL_EX(&retval, "upsertedIds", &state.zchild);
	} else {
		zval upsertedIds;
		array_init(&upsertedIds);
		ADD_ASSOC_ZVAL_EX(&retval, "upsertedIds", &upsertedIds);
	}

	{
		zval writeerrors;

		php_phongo_writeresult_get_writeerrors(intern, &writeerrors);
		ADD_ASSOC_ZVAL_EX(&retval, "writeErrors", &writeerrors);
	}

	{
		zval writeconcernerror;

		php_phongo_writeresult_get_writeconcernerror(intern, &writeconcernerror);
		ADD_ASSOC_ZVAL_EX(&retval, "writeConcernError", &writeconcernerror);
	}

	if (intern->write_concern) {
		zval write_concern;

		phongo_writeconcern_init(&write_concern, intern->write_concern);
		ADD_ASSOC_ZVAL_EX(&retval, "writeConcern", &write_concern);
	} else {
		ADD_ASSOC_NULL_EX(&retval, "writeConcern");
	}

done:
	return Z_ARRVAL(retval);
} /* }}} */
/* }}} */

void php_phongo_writeresult_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
	zend_class_entry ce;

	INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "WriteResult", php_phongo_writeresult_me);
	php_phongo_writeresult_ce                = zend_register_internal_class(&ce);
	php_phongo_writeresult_ce->create_object = php_phongo_writeresult_create_object;
	PHONGO_CE_FINAL(php_phongo_writeresult_ce);
	PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_writeresult_ce);

	memcpy(&php_phongo_handler_writeresult, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
	php_phongo_handler_writeresult.get_debug_info = php_phongo_writeresult_get_debug_info;
	php_phongo_handler_writeresult.free_obj       = php_phongo_writeresult_free_object;
	php_phongo_handler_writeresult.offset         = XtOffsetOf(php_phongo_writeresult_t, std);
} /* }}} */

php_phongo_writeresult_t* phongo_writeresult_init(zval* return_value, bson_t* reply, zval* manager, uint32_t server_id) /* {{{ */
{
	php_phongo_writeresult_t* writeresult;

	object_init_ex(return_value, php_phongo_writeresult_ce);

	writeresult            = Z_WRITERESULT_OBJ_P(return_value);
	writeresult->reply     = bson_copy(reply);
	writeresult->server_id = server_id;

	ZVAL_ZVAL(&writeresult->manager, manager, 1, 0);

	return writeresult;
} /* }}} */


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

<TITLE>
PhotoPlace (Flickr API-1.2 API)
</TITLE>

<META NAME="date" CONTENT="2009-07-24">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.aetrion.flickr.photos

Class PhotoPlace

java.lang.Object
  com.aetrion.flickr.photos.PhotoPlace

public class PhotoPlace
extends java.lang.Object

Represents either a photo pool or a photo set with it's id and title. Instances of this
 class are distinguished as set or pool by their kind property.
 There are two possible kinds represented as public int constants:

SET this is a photo set

POOL this is a groups photo pool

Version:

$Id: PhotoPlace.java,v 1.3 2009/07/12 22:43:07 x-mago Exp $

Author:

till (Till Krech) flickr:extranoise

Field Summary

static int
POOL

static int
SET

Constructor Summary

PhotoPlace(int kind,
           java.lang.String id,
           java.lang.String title)

          creates a new one.

PhotoPlace(java.lang.String kind,
           java.lang.String id,
           java.lang.String title)

          creates a new one where the kind may be specified as String "set" or "pool"

Method Summary

 boolean
equals(java.lang.Object obj)

          compares this to another object.

 java.lang.String
getId()

 int
getKind()

 java.lang.String
getKindAsString()

 java.lang.String
getTitle()

 int
hashCode()

          primitive hashCode.

protected  void
setKind(int kind)

protected  void
setKind(java.lang.String kindStr)

 java.lang.String
toString()

          returns a human readable but ugly representation of this object

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

SET

public static final int SET

See Also:
Constant Field Values

POOL

public static final int POOL

See Also:
Constant Field Values

Constructor Detail

PhotoPlace

public PhotoPlace(int kind,
                  java.lang.String id,
                  java.lang.String title)

creates a new one.

Parameters:
kind - either SET or POOL
id - id of the pool or set
title - name of the pool or set

Throws:

java.lang.IllegalArgumentException - if kind is invalid

PhotoPlace

public PhotoPlace(java.lang.String kind,
                  java.lang.String id,
                  java.lang.String title)

creates a new one where the kind may be specified as String "set" or "pool"

Parameters:
kind - either "set" or "pool"
id - id of the pool or set
title - name of the pool or set

Throws:

java.lang.IllegalArgumentException - if kind is invalid

Method Detail

getId

public java.lang.String getId()

Returns:
the pool or set id

getKind

public int getKind()

Returns:
what I am

setKind

protected void setKind(int kind)

setKind

protected void setKind(java.lang.String kindStr)

getTitle

public java.lang.String getTitle()

Returns:
the name of the pool or set

getKindAsString

public java.lang.String getKindAsString()

Returns:
what I am as String

equals

public boolean equals(java.lang.Object obj)

compares this to another object. Makes is possible to put PhotPlaces into a
 Java Set.

Overrides:
equals in class java.lang.Object

hashCode

public int hashCode()

primitive hashCode.
 Makes is possible to put PhotPlaces into a
 Java Set.

Overrides:
hashCode in class java.lang.Object

toString

public java.lang.String toString()

returns a human readable but ugly representation of this object

Overrides:
toString in class java.lang.Object

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (C) 2005-2008 Aetrion LLC.  All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text:
#import <KIF/KIF.h>

@interface PushSampleKIFTests : KIFTestCase

@end


text:
package noop.model;

import scala.collection.mutable.{ArrayBuffer, Buffer};

/**
 * A Noop source file.
 *
 * @author alexeagle@google.com (Alex Eagle)
 */
class SourceFile {

  var namespace: String = "";
  var imports: Buffer[String] = new ArrayBuffer[String];
  var classDef: ClassDefinition = null;
}


text:
using nlohmann::json;

namespace {

	BlockType charToBlockType(char key) {
		switch (key) {
			case 'z':
				// Fall through.
			case 'Z':
				return BlockType::Z;
			case 'w':
				// Fall through.
			case 'W':
				return BlockType::WALL;
			case 't':
				// Fall through.
			case 'T':
				return BlockType::T;
			case 's':
				// Fall through.
			case 'S':
				return BlockType::S;
			case 'o':
				// Fall through.
			case 'O':
				return BlockType::O;
			case 'l':
				// Fall through.
			case 'L':
				return BlockType::L;
			case 'j':
				// Fall through.
			case 'J':
				return BlockType::J;
			case 'I':
				// Fall through.
			case 'i':
				return BlockType::I;
			default:
				return BlockType::EMPTY;
		}
	}

	std::string blockTypeToString(BlockType blocktype) {
		switch (blocktype) {
			case BlockType::Z:
				return "Z";
			case BlockType::WALL:
				return "W";
			case BlockType::T:
				return "T";
			case BlockType::S:
				return "S";
			case BlockType::O:
				return "O";
			case BlockType::L:
				return "L";
			case BlockType::J:
				return "J";
			case BlockType::I:
				return "I";
			case BlockType::EMPTY:
				return "E";
			default:
				return "E";
		}
	}

}

namespace mw { // Must use the namespace color origin from.

	void from_json(const json& j, mw::Color& color) {
		std::stringstream stream(j.get<std::string>());
		if (!(stream >> color.red_)) {
			throw std::runtime_error("Red value invalid");
		}
		if (!(stream >> color.green_)) {
			throw std::runtime_error("Green value invalid");
		}
		if (!(stream >> color.blue_)) {
			throw std::runtime_error("Blue value invalid");
		}
		if (!stream.eof()) {
			if (!(stream >> color.alpha_)) {
				throw std::runtime_error("Alpha value invalid");
			}
		} else {
			color.alpha_ = 1;
		}
	}

}

void from_json(const json& j, Ai& ai) {
	ai = Ai(j.at("name").get<std::string>(), j.at("valueFunction").get<std::string>());
}

void from_json(const json& j, BlockType& blockType) {
	blockType = charToBlockType(j.get<std::string>()[0]);
}

void to_json(json& j, const BlockType& blockType) {
	j = json(blockTypeToString(blockType));
}

void from_json(const json& j, Block& block) {
	block = Block(j.at("blockType").get<BlockType>(), j.at("bottomRow").get<int>(), j.at("leftColumn").get<int>(), j.at("currentRotation").get<int>());
}

void to_json(json& j, const Block& block) {
	j = json({
		{"bottomRow", block.getLowestStartRow()},
		{"blockType", block.getBlockType()},
		{"leftColumn", block.getStartColumn()},
		{"currentRotation", block.getCurrentRotation()}
	});
}

std::string convertBlockTypesToString(const std::vector<BlockType>& board) {
	std::stringstream stream;
	for (BlockType chr : board) {
		stream << blockTypeToString(chr);
	}
	return stream.str();
}

std::vector<BlockType> convertStringToBlockTypes(std::string str) {
	std::vector<BlockType> blocktypes_;
	for (char key : str) {
		blocktypes_.push_back(charToBlockType(key));
	}
	return blocktypes_;
}

void from_json(const json& j, HighscoreRecord& highscoreRecord) {
	highscoreRecord.name_ = j.at("name").get<std::string>();
	highscoreRecord.date_ = j.at("date").get<std::string>();
	highscoreRecord.points_ = j.at("points").get<int>();
}

void to_json(json& j, const HighscoreRecord& highscoreRecord) {
	j = json{{"name", highscoreRecord.name_},{"date", highscoreRecord.date_},{"points", highscoreRecord.points_}};
}

TetrisData::TetrisData() : textureAtlas_(2048, 2048, []() {
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}) {
	std::ifstream stream(JSON_PATH);
	stream >> jsonObject_;
}

void TetrisData::save() {
	std::ofstream stream(JSON_PATH);
	stream << jsonObject_.dump(1);
}

mw::Font TetrisData::loadFont(std::string file, unsigned int fontSize) {
	unsigned int size = fonts_.size();
	std::string key = file;
	key += fontSize;
	mw::Font& font = fonts_[key];

	// Font not found?
	if (fonts_.size() > size) {
		font = mw::Font(file, fontSize);
	}

	return font;
}

mw::Sound TetrisData::loadSound(std::string file) {
	unsigned int size = sounds_.size();
	mw::Sound& sound = sounds_[file];

	// Sound not found?
	if (sounds_.size() > size) {
		sound = mw::Sound(file);
	}

	return sound;
}

mw::Music TetrisData::loadMusic(std::string file) {
	unsigned int size = musics_.size();
	mw::Music& music = musics_[file];

	// Music not found?
	if (musics_.size() > size) {
		music = mw::Music(file);
	}

	return music;
}

mw::Sprite TetrisData::loadSprite(std::string file) {
	return textureAtlas_.add(file, 1);;
}

mw::Sprite TetrisData::getSprite(BlockType blockType) {
	switch (blockType) {
		case BlockType::I:
			return loadSprite(jsonObject_["window"]["tetrisBoard"]["sprites"]["squareI"].get<std::string>());
		case BlockType::J:
			return loadSprite(jsonObject_["window"]["tetrisBoard"]["sprites"]["squareJ"].get<std::string>());
		case BlockType::L:
			return loadSprite(jsonObject_["window"]["tetrisBoard"]["sprites"]["squareL"].get<std::string>());
		case BlockType::O:
			return loadSprite(jsonObject_["window"]["tetrisBoard"]["sprites"]["squareO"].get<std::string>());
		case BlockType::S:
			return loadSprite(jsonObject_["window"]["tetrisBoard"]["sprites"]["squareS"].get<std::string>());
		case BlockType::T:
			return loadSprite(jsonObject_["window"]["tetrisBoard"]["sprites"]["squareT"].get<std::string>());
		case BlockType::Z:
			return loadSprite(jsonObject_["window"]["tetrisBoard"]["sprites"]["squareZ"].get<std::string>());
	}
	return mw::Sprite();
}

mw::Font TetrisData::getDefaultFont(int size) {
	return loadFont(jsonObject_["window"]["font"].get<std::string>(), size);
}

void TetrisData::bindTextureFromAtlas() const {
	textureAtlas_.getTexture().bindTexture();
}

mw::Color TetrisData::getOuterSquareColor() {
	return jsonObject_["window"]["tetrisBoard"]["outerSquareColor"].get<mw::Color>();
}

mw::Color TetrisData::getInnerSquareColor() {
	return jsonObject_["window"]["tetrisBoard"]["innerSquareColor"].get<mw::Color>();
}

mw::Color TetrisData::getStartAreaColor() {
	return jsonObject_["window"]["tetrisBoard"]["startAreaColor"].get<mw::Color>();
}

mw::Color TetrisData::getPlayerAreaColor() {
	return jsonObject_["window"]["tetrisBoard"]["playerAreaColor"].get<mw::Color>();
}

mw::Color TetrisData::getBorderColor() {
	return jsonObject_["window"]["tetrisBoard"]["borderColor"].get<mw::Color>();
}

float TetrisData::getTetrisSquareSize() {
	return jsonObject_["window"]["tetrisBoard"]["squareSize"].get<float>();
}

float TetrisData::getTetrisBorderSize() {
	return jsonObject_["window"]["tetrisBoard"]["borderSize"].get<float>();
}

int TetrisData::getWindowPositionX() {
	return jsonObject_["window"]["positionX"].get<int>();
}

int TetrisData::getWindowPositionY() {
	return jsonObject_["window"]["positionY"].get<int>();
}

void TetrisData::setWindowPositionX(int x) {
	jsonObject_["window"]["positionX"] = x;
}

void TetrisData::setWindowPositionY(int y) {
	jsonObject_["window"]["positionY"] = y;
}

int TetrisData::getWindowWidth() {
	return jsonObject_["window"]["width"].get<int>();
}

int TetrisData::getWindowHeight() {
	return jsonObject_["window"]["height"].get<int>();
}

void TetrisData::setWindowWidth(int width) {
	jsonObject_["window"]["width"] = width;
}

void TetrisData::setWindowHeight(int height) {
	jsonObject_["window"]["height"] = height;
}

bool TetrisData::isWindowResizable() {
	return jsonObject_["window"]["resizeable"].get<bool>();
}

void TetrisData::setWindowResizable(bool resizeable) {
	jsonObject_["window"]["resizeable"] = resizeable;
}

int TetrisData::getWindowMinWidth() {
	return jsonObject_["window"]["minWidth"].get<int>();
}

int TetrisData::getWindowMinHeight() {
	return jsonObject_["window"]["minHeight"].get<int>();
}

std::string TetrisData::getWindowIcon() {
	return jsonObject_["window"]["icon"].get<std::string>();
}

bool TetrisData::isWindowBordered() {
	return jsonObject_["window"]["border"].get<bool>();
}

void TetrisData::setWindowBordered(bool border) {
	jsonObject_["window"]["border"] = border;
}

bool TetrisData::isWindowMaximized() {
	return jsonObject_["window"]["maximized"].get<bool>();
}

void TetrisData::setWindowMaximized(bool maximized) {
	jsonObject_["window"]["maximized"] = maximized;
}

bool TetrisData::isWindowVsync() {
	return jsonObject_["window"]["vsync"].get<bool>();
}

void TetrisData::setWindowVsync(bool activate) {
	jsonObject_["window"]["vsync"] = activate;
}

int TetrisData::getMultiSampleBuffers() const {
	return jsonObject_["window"]["multiSampleBuffers"];
}

int TetrisData::getMultiSampleSamples() const {
	return jsonObject_["window"]["multiSampleSamples"];
}

float TetrisData::getRowFadingTime() const {
	return jsonObject_["window"]["rowFadingTime"].get<float>();
}

void TetrisData::setRowFadingTime(float time) {
	jsonObject_["window"]["rowFadingTime"] = time;
}

float TetrisData::getRowMovingTime() const {
	return jsonObject_["window"]["rowMovingTime"].get<float>();
}

void TetrisData::setRowMovingTime(float time) {
	jsonObject_["window"]["rowMovingTime"] = time;
}

mw::Sprite TetrisData::getBackgroundSprite() {
	return loadSprite(jsonObject_["window"]["sprites"]["background"].get<std::string>());
}

std::string TetrisData::getAi1Name() const {
	return jsonObject_["ai1"].get<std::string>();
}
std::string TetrisData::getAi2Name() const {
	return jsonObject_["ai2"].get<std::string>();
}
std::string TetrisData::getAi3Name() const {
	return jsonObject_["ai3"].get<std::string>();
}
std::string TetrisData::getAi4Name() const {
	return jsonObject_["ai4"].get<std::string>();
}

void TetrisData::setAi1Name(std::string name) {
	jsonObject_["ai1"] = name;
}

void TetrisData::setAi2Name(std::string name) {
	jsonObject_["ai2"] = name;
}

void TetrisData::setAi3Name(std::string name) {
	jsonObject_["ai3"] = name;
}

void TetrisData::setAi4Name(std::string name) {
	jsonObject_["ai4"] = name;
}

std::vector<Ai> TetrisData::getAiVector() {
	std::vector<Ai> ais;
	ais.push_back(Ai()); // Add default ai.
	ais.insert(ais.end(), jsonObject_["ais"].begin(), jsonObject_["ais"].end());
	return ais;
}

std::vector<HighscoreRecord> TetrisData::getHighscoreRecordVector() {
	return std::vector<HighscoreRecord>(jsonObject_["highscore"].begin(), jsonObject_["highscore"].end());
}

void TetrisData::setHighscoreRecordVector(const std::vector<HighscoreRecord>& highscoreVector) {
	jsonObject_["highscore"].clear();
	for (const HighscoreRecord& record : highscoreVector) {
		jsonObject_["highscore"].push_back(record);
	}
}

int TetrisData::getActiveLocalGameRows() {
	return jsonObject_["activeGames"]["localGame"]["rows"].get<int>();
}

int TetrisData::getActiveLocalGameColumns() {
	return jsonObject_["activeGames"]["localGame"]["columns"].get<int>();
}

bool TetrisData::isFullscreenOnDoubleClick() {
	return jsonObject_["window"]["fullscreenOnDoubleClick"].get<bool>();
}

void TetrisData::setFullscreenOnDoubleClick(bool activate) {
	jsonObject_["window"]["fullscreenOnDoubleClick"] = activate;
}

bool TetrisData::isMoveWindowByHoldingDownMouse() {
	return jsonObject_["window"]["moveWindowByHoldingDownMouse"].get<bool>();
}

void TetrisData::setMoveWindowByHoldingDownMouse(bool activate) {
	jsonObject_["window"]["moveWindowByHoldingDownMouse"] = activate;
}

int TetrisData::getPort() const {
	return jsonObject_["window"]["port"].get<int>();
}

void TetrisData::setPort(int port) {
	jsonObject_["window"]["port"] = port;
}

std::string TetrisData::getIp() const {
	return jsonObject_["window"]["ip"].get<std::string>();
}

void TetrisData::setIp(std::string ip) {
	jsonObject_["window"]["ip"] = ip;
}

float TetrisData::getWindowBarHeight() {
	return jsonObject_["window"]["bar"]["height"].get<float>();
}

mw::Color TetrisData::getWindowBarColor() {
	return jsonObject_["window"]["bar"]["color"].get<mw::Color>();
}

mw::Sprite TetrisData::getCheckboxBoxSprite() {
	return loadSprite(jsonObject_["window"]["checkBox"]["boxImage"].get<std::string>());
}

mw::Sprite TetrisData::getCheckboxCheckSprite() {
	return loadSprite(jsonObject_["window"]["checkBox"]["checkImage"].get<std::string>());
}

mw::Color TetrisData::getCheckboxTextColor() {
	return jsonObject_["window"]["checkBox"]["textColor"].get<mw::Color>();
}

mw::Color TetrisData::getCheckboxBackgroundColor() {
	return jsonObject_["window"]["checkBox"]["backgroundColor"].get<mw::Color>();
}

mw::Color TetrisData::getCheckboxBoxColor() {
	return jsonObject_["window"]["checkBox"]["boxColor"].get<mw::Color>();
}

mw::Color TetrisData::getChecboxCheckColor() {
	return jsonObject_["window"]["checkBox"]["checkColor"].get<mw::Color>();
}

mw::Sprite TetrisData::getRadioButtonBoxSprite() {
	return loadSprite(jsonObject_["window"]["radioButton"]["boxImage"].get<std::string>());
}

mw::Sprite TetrisData::getRadioButtonCheckSprite() {
	return loadSprite(jsonObject_["window"]["radioButton"]["checkImage"].get<std::string>());
}

mw::Color TetrisData::getRadioButtonTextColor() {
	return jsonObject_["window"]["radioButton"]["textColor"].get<mw::Color>();
}

mw::Color TetrisData::getRadioButtonBackgroundColor() {
	return jsonObject_["window"]["radioButton"]["backgroundColor"].get<mw::Color>();
}

mw::Color TetrisData::getRadioButtonBoxColor() {
	return jsonObject_["window"]["radioButton"]["boxColor"].get<mw::Color>();
}

mw::Color TetrisData::getRadioButtonCheckColor() {
	return jsonObject_["window"]["radioButton"]["checkColor"].get<mw::Color>();
}

mw::Color TetrisData::getLabelTextColor() {
	return jsonObject_["window"]["label"]["textColor"].get<mw::Color>();
}

mw::Color TetrisData::getLabelBackgroundColor() {
	return jsonObject_["window"]["label"]["backgroundColor"].get<mw::Color>();
}

mw::Color TetrisData::getButtonFocusColor() {
	return jsonObject_["window"]["button"]["focusColor"].get<mw::Color>();
}

mw::Color TetrisData::getButtonTextColor() {
	return jsonObject_["window"]["button"]["textColor"].get<mw::Color>();
}

mw::Color TetrisData::getButtonHoverColor() {
	return jsonObject_["window"]["button"]["hoverColor"].get<mw::Color>();
}

mw::Color TetrisData::getButtonPushColor() {
	return jsonObject_["window"]["button"]["pushColor"].get<mw::Color>();
}

mw::Color TetrisData::getButtonBackgroundColor() {
	return jsonObject_["window"]["button"]["backgroundColor"].get<mw::Color>();
}

mw::Color TetrisData::getButtonBorderColor() {
	return jsonObject_["window"]["button"]["borderColor"].get<mw::Color>();
}

mw::Color TetrisData::getComboBoxFocusColor() {
	return jsonObject_["window"]["comboBox"]["focusColor"].get<mw::Color>();
}

mw::Color TetrisData::getComboBoxTextColor() {
	return jsonObject_["window"]["comboBox"]["textColor"].get<mw::Color>();
}

mw::Color TetrisData::getComboBoxSelectedTextColor() {
	return jsonObject_["window"]["comboBox"]["selectedTextColor"].get<mw::Color>();
}

mw::Color TetrisData::getComboBoxSelectedBackgroundColor() {
	return jsonObject_["window"]["comboBox"]["selectedBackgroundColor"].get<mw::Color>();
}

mw::Color TetrisData::getComboBoxBackgroundColor() {
	return jsonObject_["window"]["comboBox"]["backgroundColor"].get<mw::Color>();
}

mw::Color TetrisData::getComboBoxBorderColor() {
	return jsonObject_["window"]["comboBox"]["borderColor"].get<mw::Color>();
}

mw::Color TetrisData::getComboBoxShowDropDownColor() {
	return jsonObject_["window"]["comboBox"]["showDropDownColor"].get<mw::Color>();
}

mw::Sprite TetrisData::getComboBoxShowDropDownSprite() {
	return loadSprite(jsonObject_["window"]["comboBox"]["showDropDownSprite"].get<std::string>());
}

mw::Sprite TetrisData::getHumanSprite() {
	return loadSprite(jsonObject_["window"]["sprites"]["human"].get<std::string>());
}

mw::Sprite TetrisData::getComputerSprite() {
	return loadSprite(jsonObject_["window"]["sprites"]["computer"].get<std::string>());
}

mw::Sprite TetrisData::getCrossSprite() {
	return loadSprite(jsonObject_["window"]["sprites"]["cross"].get<std::string>());
}

mw::Sprite TetrisData::getZoomSprite() {
	return loadSprite(jsonObject_["window"]["sprites"]["zoom"].get<std::string>());
}

void TetrisData::setActiveLocalGame(int rows, int columns, const std::vector<PlayerData>& playerDataVector) {
	jsonObject_["activeGames"]["localGame"]["rows"] = rows;
	jsonObject_["activeGames"]["localGame"]["columns"] = columns;

	nlohmann::json playerJson = nlohmann::json::array();
	for (const PlayerData& data : playerDataVector) {
		nlohmann::json test = nlohmann::json(data.board_);

		playerJson.push_back({
			{"name", data.name_},
			{"nextBlockType", data.next_},
			{"levelUpCounter", data.levelUpCounter_},
			{"ai", data.device_->isAi()},
			{"level", data.level_},
			{"points", data.points_},
			{"currentBlock", data.current_},
			{"board", convertBlockTypesToString(data.board_)},
			{"device",{
				{"name", data.device_->getName()},
				{"ai", data.device_->isAi()},
			}}
		});
	}
	jsonObject_["activeGames"]["localGame"]["players"] = playerJson;
}

std::vector<PlayerData> TetrisData::getActiveLocalGamePlayers() {
	nlohmann::json players = jsonObject_["activeGames"]["localGame"]["players"];

	std::vector<PlayerData> playerDataVector;
	for (nlohmann::json& player : players) {
		PlayerData playerData;
		playerData.name_ = player["name"].get<std::string>();
		playerData.next_ = player["nextBlockType"].get<BlockType>();
		playerData.levelUpCounter_ = player["levelUpCounter"].get<int>();
		playerData.level_ = player["level"].get<int>();
		playerData.points_ = player["points"].get<int>();
		playerData.current_ = player["currentBlock"].get<Block>();
		playerData.board_ = convertStringToBlockTypes(player["board"].get<std::string>());
		playerData.ai_ = player["ai"].get<bool>();
		playerData.deviceName_ = player["device"]["name"].get<std::string>();
		playerDataVector.push_back(playerData);
	}
	return playerDataVector;
}


text:
package pfg.kraken.display;

import java.awt.Color;
import java.awt.Graphics;
import java.io.Serializable;

/**
 * A printable with its color
 * @author pf
 *
 */

public class ColoredPrintable implements Serializable
{
	private static final long serialVersionUID = 1007485107824898388L;
	public final Printable p;
	public final Color c;
	public final int l;
	public final boolean temporary;

	public ColoredPrintable(Printable p, Color c, int l, boolean temporary)
	{
		this.p = p;
		this.c = c;
		this.l = l;
		this.temporary = temporary;
	}

	public void print(Graphics g, Display f)
	{
		if(c != null)
			g.setColor(c);
		p.print(g, f);
	}

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

	@Override
	public boolean equals(Object o)
	{
		return o == p;
	}

	@Override
	public String toString()
	{
		return p+" "+c+" "+l;
	}
}


text:
package org.apache.flink.table.types.logical;

import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.table.catalog.ObjectIdentifier;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.types.DataType;
import org.apache.flink.types.Row;
import org.apache.flink.util.Preconditions;

import javax.annotation.Nullable;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Logical type of a user-defined object structured type. Structured types contain zero, one or more
 * attributes. Each attribute consists of a name and a type. A type cannot be defined so that one of
 * its attribute types (transitively) uses itself.
 *
 *
There are two kinds of structured types. Types that are stored in a catalog and are identified
 * by an {@link ObjectIdentifier} or anonymously defined, unregistered types (usually reflectively
 * extracted) that are identified by an implementation {@link Class}.
 *
 *
Logical properties

 *
 *
A structured type can declare a super type and allows single inheritance for more complex type
 * hierarchies, similar to JVM-based languages.
 *
 *
A structured type can be declared {@code final} for preventing further inheritance (default
 * behavior) or {@code not final} for allowing subtypes.
 *
 *
A structured type can be declared {@code not instantiable} if a more specific type is required
 * or {@code instantiable} if instances can be created from this type (default behavior).
 *
 *
A structured type declares comparision properties of either {@code none} (no equality), {@code
 * equals} (only equality and inequality), or {@code full} (greater, equals, less).
 *
 *
NOTE: Compared to the SQL standard, this class is incomplete. We might add new features such
 * as method declarations in the future. Also ordering is not supported yet.
 *
 *
Physical properties

 *
 *
A structured type can be defined fully logically (e.g. by using a {@code CREATE TYPE} DDL).
 * The implementation class is optional and only used at the edges of the table ecosystem (e.g. when
 * bridging to a function or connector). Serialization and equality ({@code hashCode/equals}) are
 * handled by the runtime based on the logical type. In other words: {@code hashCode/equals} of an
 * implementation class are not used. Custom equality, casting logic, and further overloaded
 * operators will be supported once we allow defining methods on structured types.
 *
 *
An implementation class must offer a default constructor with zero arguments or a full
 * constructor that assigns all attributes. Other physical properties such as the conversion classes
 * of attributes are defined by a {@link DataType} when a structured type is used.
 */
@PublicEvolving
public final class StructuredType extends UserDefinedType {

    public static final String FORMAT = "*%s*";

    private static final Set<String> INPUT_OUTPUT_CONVERSION =
            conversionSet(Row.class.getName(), RowData.class.getName());

    private static final Class<?> FALLBACK_CONVERSION = Row.class;

    /** Defines an attribute of a {@link StructuredType}. */
    public static final class StructuredAttribute implements Serializable {

        private final String name;

        private final LogicalType type;

        private final @Nullable String description;

        public StructuredAttribute(String name, LogicalType type, @Nullable String description) {
            this.name = Preconditions.checkNotNull(name, "Attribute name must not be null.");
            this.type = Preconditions.checkNotNull(type, "Attribute type must not be null.");
            this.description = description;
        }

        public StructuredAttribute(String name, LogicalType type) {
            this(name, type, null);
        }

        public String getName() {
            return name;
        }

        public LogicalType getType() {
            return type;
        }

        public Optional<String> getDescription() {
            return Optional.ofNullable(description);
        }

        public StructuredAttribute copy() {
            return new StructuredAttribute(name, type.copy(), description);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            StructuredAttribute that = (StructuredAttribute) o;
            return name.equals(that.name)
                    && type.equals(that.type)
                    && Objects.equals(description, that.description);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name, type, description);
        }
    }

    /** Defines equality properties for scalar evaluation. */
    public enum StructuredComparision {
        EQUALS(true, false),
        FULL(true, true),
        NONE(false, false);
        private final boolean equality;
        private final boolean comparison;

        StructuredComparision(boolean equality, boolean comparison) {
            this.equality = equality;
            this.comparison = comparison;
        }

        public boolean isEquality() {
            return equality;
        }

        public boolean isComparison() {
            return comparison;
        }
    }

    /** A builder for a {@link StructuredType}. Intended for future extensibility. */
    public static final class Builder {

        private final @Nullable ObjectIdentifier objectIdentifier;

        private final @Nullable Class<?> implementationClass;

        private List<StructuredAttribute> attributes = new ArrayList<>();

        private boolean isNullable = true;

        private boolean isFinal = true;

        private boolean isInstantiable = true;

        private StructuredComparision comparision = StructuredComparision.NONE;

        private @Nullable StructuredType superType;

        private @Nullable String description;

        public Builder(Class<?> implementationClass) {
            this.objectIdentifier = null;
            this.implementationClass =
                    Preconditions.checkNotNull(
                            implementationClass, "Implementation class must not be null.");
        }

        public Builder(ObjectIdentifier objectIdentifier) {
            this.objectIdentifier =
                    Preconditions.checkNotNull(
                            objectIdentifier, "Object identifier must not be null.");
            this.implementationClass = null;
        }

        public Builder(ObjectIdentifier objectIdentifier, Class<?> implementationClass) {
            this.objectIdentifier =
                    Preconditions.checkNotNull(
                            objectIdentifier, "Object identifier must not be null.");
            this.implementationClass =
                    Preconditions.checkNotNull(
                            implementationClass, "Implementation class must not be null.");
        }

        public Builder attributes(List<StructuredAttribute> attributes) {
            this.attributes =
                    Collections.unmodifiableList(
                            new ArrayList<>(
                                    Preconditions.checkNotNull(
                                            attributes, "Attributes must not be null.")));
            return this;
        }

        public Builder setNullable(boolean isNullable) {
            this.isNullable = isNullable;
            return this;
        }

        public Builder description(String description) {
            this.description =
                    Preconditions.checkNotNull(description, "Description must not be null.");
            return this;
        }

        public Builder setFinal(boolean isFinal) {
            this.isFinal = isFinal;
            return this;
        }

        public Builder setInstantiable(boolean isInstantiable) {
            this.isInstantiable = isInstantiable;
            return this;
        }

        public Builder comparision(StructuredComparision comparision) {
            this.comparision =
                    Preconditions.checkNotNull(comparision, "Comparision must not be null.");
            return this;
        }

        public Builder superType(StructuredType superType) {
            this.superType = Preconditions.checkNotNull(superType, "Super type must not be null.");
            return this;
        }

        public StructuredType build() {
            return new StructuredType(
                    isNullable,
                    objectIdentifier,
                    attributes,
                    isFinal,
                    isInstantiable,
                    comparision,
                    superType,
                    description,
                    implementationClass);
        }
    }

    private final List<StructuredAttribute> attributes;

    private final boolean isInstantiable;

    private final StructuredComparision comparision;

    private final @Nullable StructuredType superType;

    private final @Nullable Class<?> implementationClass;

    private StructuredType(
            boolean isNullable,
            ObjectIdentifier objectIdentifier,
            List<StructuredAttribute> attributes,
            boolean isFinal,
            boolean isInstantiable,
            StructuredComparision comparision,
            @Nullable StructuredType superType,
            @Nullable String description,
            @Nullable Class<?> implementationClass) {
        super(isNullable, LogicalTypeRoot.STRUCTURED_TYPE, objectIdentifier, isFinal, description);

        Preconditions.checkArgument(
                objectIdentifier != null || implementationClass != null,
                "An identifier is missing.");

        this.attributes = attributes;
        this.isInstantiable = isInstantiable;
        this.comparision = comparision;
        this.superType = superType;
        this.implementationClass = implementationClass;
    }

    /**
     * Creates a builder for a {@link StructuredType} that has been stored in a catalog and is
     * identified by an {@link ObjectIdentifier}.
     */
    public static StructuredType.Builder newBuilder(ObjectIdentifier objectIdentifier) {
        return new StructuredType.Builder(objectIdentifier);
    }

    /**
     * Creates a builder for a {@link StructuredType} that has been stored in a catalog and is
     * identified by an {@link ObjectIdentifier}. The optional implementation class defines
     * supported conversions.
     */
    public static StructuredType.Builder newBuilder(
            ObjectIdentifier objectIdentifier, Class<?> implementationClass) {
        return new StructuredType.Builder(objectIdentifier, implementationClass);
    }

    /**
     * Creates a builder for a {@link StructuredType} that is not stored in a catalog and is
     * identified by an implementation {@link Class}.
     */
    public static StructuredType.Builder newBuilder(Class<?> implementationClass) {
        return new StructuredType.Builder(implementationClass);
    }

    public List<StructuredAttribute> getAttributes() {
        return attributes;
    }

    public boolean isInstantiable() {
        return isInstantiable;
    }

    public StructuredComparision getComparision() {
        return comparision;
    }

    public Optional<StructuredType> getSuperType() {
        return Optional.ofNullable(superType);
    }

    public Optional<Class<?>> getImplementationClass() {
        return Optional.ofNullable(implementationClass);
    }

    @Override
    public LogicalType copy(boolean isNullable) {
        return new StructuredType(
                isNullable,
                getObjectIdentifier().orElse(null),
                attributes,
                isFinal(),
                isInstantiable,
                comparision,
                superType == null ? null : (StructuredType) superType.copy(),
                getDescription().orElse(null),
                implementationClass);
    }

    @Override
    public String asSummaryString() {
        if (getObjectIdentifier().isPresent()) {
            return asSerializableString();
        }
        assert implementationClass != null;
        // we use *class* to make it visible that this type is unregistered and not confuse it
        // with catalog types
        return withNullability(FORMAT, implementationClass.getName());
    }

    @Override
    public boolean supportsInputConversion(Class<?> clazz) {
        return (implementationClass != null && implementationClass.isAssignableFrom(clazz))
                || INPUT_OUTPUT_CONVERSION.contains(clazz.getName());
    }

    @Override
    public boolean supportsOutputConversion(Class<?> clazz) {
        StructuredType currentType = this;
        while (currentType != null) {
            if (currentType.implementationClass != null
                    && clazz.isAssignableFrom(currentType.implementationClass)) {
                return true;
            }
            currentType = currentType.superType;
        }
        return INPUT_OUTPUT_CONVERSION.contains(clazz.getName());
    }

    @Override
    public Class<?> getDefaultConversion() {
        if (implementationClass != null) {
            return implementationClass;
        }
        return FALLBACK_CONVERSION;
    }

    @Override
    public List<LogicalType> getChildren() {
        final List<LogicalType> children = new ArrayList<>();
        // add super fields first
        if (superType != null) {
            children.addAll(superType.getChildren());
        }
        // then specific fields
        children.addAll(
                attributes.stream().map(StructuredAttribute::getType).collect(Collectors.toList()));
        return Collections.unmodifiableList(children);
    }

    @Override
    public <R> R accept(LogicalTypeVisitor<R> visitor) {
        return visitor.visit(this);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }
        StructuredType that = (StructuredType) o;
        return isInstantiable == that.isInstantiable
                && attributes.equals(that.attributes)
                && comparision == that.comparision
                && Objects.equals(superType, that.superType)
                && Objects.equals(implementationClass, that.implementationClass);
    }

    @Override
    public int hashCode() {
        return Objects.hash(
                super.hashCode(),
                attributes,
                isInstantiable,
                comparision,
                superType,
                implementationClass);
    }
}


text:
#ifndef TINYRTP_CONFIG_H
#define TINYRTP_CONFIG_H

#ifdef __SYMBIAN32__
#undef _WIN32 /* Because of WINSCW */
#endif

// Windows (XP/Vista/7/CE and Windows Mobile) macro definition.
#if defined(WIN32)|| defined(_WIN32) || defined(_WIN32_WCE)
#	define TRTP_UNDER_WINDOWS	1
#	if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP)
#		define TRTP_UNDER_WINDOWS_RT		1
#	endif
#endif

#if (TRTP_UNDER_WINDOWS || defined(__SYMBIAN32__)) && defined(TINYRTP_EXPORTS)
# 	define TINYRTP_API		__declspec(dllexport)
# 	define TINYRTP_GEXTERN __declspec(dllexport)
#elif (TRTP_UNDER_WINDOWS || defined(__SYMBIAN32__)) && !defined(TINYRTP_IMPORTS_IGNORE)
# 	define TINYRTP_API __declspec(dllimport)
# 	define TINYRTP_GEXTERN __declspec(dllimport)
#else
#	define TINYRTP_API
#	define TINYRTP_GEXTERN	extern
#endif

/* Guards against C++ name mangling
*/
#ifdef __cplusplus
#	define TRTP_BEGIN_DECLS extern "C" {
#	define TRTP_END_DECLS }
#else
#	define TRTP_BEGIN_DECLS
#	define TRTP_END_DECLS
#endif

/* Disable some well-known warnings
*/
#ifdef _MSC_VER
#	define _CRT_SECURE_NO_WARNINGS
#endif

/* Detecting C99 compilers
 */
#if (__STDC_VERSION__ == 199901L) && !defined(__C99__)
#	define __C99__
#endif

#define TRTP_RTP_VERSION 2

#include <stdint.h>
#ifdef __SYMBIAN32__
#   include <stdlib.h>
#endif

#if defined(__APPLE__)
#   include <TargetConditionals.h>
#endif

// http://code.google.com/p/idoubs/issues/detail?id=111
#if TARGET_IPHONE_SIMULATOR
#   undef HAVE_SRTP
#   define HAVE_SRTP 0
#endif

#if HAVE_CONFIG_H
	#include <config.h>
#endif

#endif // TINYRTP_CONFIG_H


text:
const fromSides = require('./fromSides')

/** Construct a Geom2 from a list of points (a polygon).
 * Like fromPoints() but does not check if the result is a valid polygon.
 * The points MUST rotate counter clockwise.
 * The points can define a convex or a concave polygon.
 * The polygon must not self intersect.
 * @param {Vec2[]} points - list of points in 2D space
 * @returns {Geom2} new Geom2 object
 */
const fromPointsNoCheck = points => {
  let prevPoint = points[points.length - 1]
  const sides = points.map(point => {
    const side = [prevPoint, point]
    prevPoint = point
    return side
  })
  return fromSides(sides)
}

module.exports = fromPointsNoCheck


text:
<component name="libraryTable">
  <library name="support-core-utils-25.3.0">
    <CLASSES>
      <root url="jar://$USER_HOME$/.android/build-cache/cd6244195fd087cccca63aeb7c0d5555ce23fad5/output/jars/classes.jar!/" />
      <root url="file://$USER_HOME$/.android/build-cache/cd6244195fd087cccca63aeb7c0d5555ce23fad5/output/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/support-core-utils/25.3.0/support-core-utils-25.3.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
{% extends "catalog/base_v2.html" %}
{% load static from staticfiles %}

{% block title %}Makeystreet | {{ makey.name }}{% endblock %}
{% block contentmeta %}
<meta property="og:title"  content="{{makey.name}}" />
<meta property="og:type"   content="makey_street:makey" />
<meta property="og:url"    content="{{makey_url}}" />
{% if makey.cover_pic %}
<meta property="og:image"  content="{{makey.cover_pic}}"/>
<meta property="og:image:url" content="{{makey.cover_pic}}" />
{% else %}
<meta property="og:image"  content="{{makey.images.all.0}}"/>
<meta property="og:image:url"  content="{{makey.images.all.0}}"/>
{% endif %}

<meta name="og:description" content="{{makey.about}}">
<meta name="og:author" content="{{makey.user}}">
{% endblock %}

{% block extra_js %}

{% load compress %}
{% compress js %}

{% endcompress %}
{% compress css %}
<link rel="stylesheet" href="{% static 'app/makey/insight_edit.css' %}" type="text/css">
<link rel="stylesheet" href="{% static 'app/common/typeahead.css' %}" type="text/css">
{% endcompress %}

{% endblock %}

{% block templates %}
{% verbatim %}

{% endverbatim %}
{% endblock %}

{% block content_full %}

{{makey.name}}

        {% if parents %}

          {% for parent in parents %}
          {{parent.name}}

          {% endfor %}

{{makey.name}}

        {% endif %}

           OVERVIEW

          {% if insights_count %}
          {{insights_count}}
          {% endif %}
          INSIGHTS

          {% if discussions_count %}
          {{discussions_count}}
          {% endif %}
          DISCUSSIONS

          {% if files_count %}
          {{files_count}}
          {% endif %}
          FILES

          {% if gallery_count %}
          {{gallery_count}}
          {% endif %}
          GALLERY

          {% if docs_count %}
          {{docs_count}}
          {% endif %}
          DOCS

              <input type="text" placeholder="Search this Makey..." class="search-input">

Update this insight

              Go back to all insights

Edit Insight

              <form action="/makey_action/" method="post" class="add-insight-form">

                    Title
                    <input type="text" placeholder="Title of your Insight" name="title" value="{{insight.title}}">

                    Description
                    <textarea placeholder="Describe your insight" name="description">{{insight.body}}</textarea>

                  <input type="hidden" name="action" value="edit-insight-image">
                  <input type="hidden" name="makey_id" value="{{makey.id}}">
                  <input type="hidden" name="insight_id" value="{{insight.id}}">
                  <input type="hidden" name="image_id" value="{% if insight.image %}{{insight.image.id}}{% endif %}" class="add-insight-image-id">
                  <input type="hidden" name="image_url" value="" class="add-insight-image-url">

              </form>

Add tags

                  {% for tag in insight.tags.all %}

{{tag.name}}

                  {% endfor %}

                  <input type="text" placeholder="Search for tags..." class="tags-search">

Link an image (optional)

                    Upload an image

                  <input type="file" accept="image/*" class="image-upload-selector" name="upload_image_input" id="upload_image_input" />

                {% if images %}

                  Or

Select an existing image

                  {% for img in images %}

                  {% endfor %}

                {% endif %}

{% endblock %}


text:
package org.scalatest

import org.scalactic.Equality
import org.scalactic.Explicitly
import collection.GenTraversable
import SharedHelpers._
import Matchers._

class NoneOfContainMatcherEqualitySpec extends Spec with Explicitly {

  class TrimEquality extends Equality[String] {
    def areEqual(left: String, right: Any) =
      left.trim == (right match {
        case s: String => s.trim
        case other => other
      })
  }

  class MapTrimEquality extends Equality[(Int, String)] {
    def areEqual(left: (Int, String), right: Any) =
      right match {
        case t2: Tuple2[_, _] =>
          left._1 == t2._1 &&
          left._2.trim == (t2._2 match {
            case s: String => s.trim
            case other => other
          })
        case right => left == right
      }
  }

  class FalseEquality extends Equality[Int] {
    def areEqual(left: Int, right: Any): Boolean = false
  }

  class MapFalseEquality extends Equality[(Int, String)] {
    def areEqual(left: (Int, String), right: Any): Boolean = false
  }

  class SetEquality(validLeft: Set[Int], validRight: Set[Any], returnValue: Boolean) extends Equality[Int] {
    def areEqual(left: Int, right: Any): Boolean =
      if (validLeft.contains(left) && validRight.contains(right))
        returnValue
      else
        !returnValue
  }

  class MapSetEquality(validLeft: Set[(Int, String)], validRight: Set[Any], returnValue: Boolean) extends Equality[(Int, String)] {
    def areEqual(left: (Int, String), right: Any): Boolean =
      if (validLeft.contains(left) && validRight.contains(right))
        returnValue
      else
        !returnValue
  }

  class JavaMapSetEquality(validLeft: Set[java.util.Map.Entry[Int, String]], validRight: Set[Any], returnValue: Boolean) extends Equality[java.util.Map.Entry[Int, String]] {
    def areEqual(left: java.util.Map.Entry[Int, String], right: Any): Boolean =
      if (validLeft.contains(left) && validRight.contains(right))
        returnValue
      else
        !returnValue
  }

  object `noneOf ` {

    def checkShouldContainStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int) {
      val leftText = FailureMessages.decorateToStringValue(left)
      e.message should be (Some(FailureMessages("containedAtLeastOneOf", left, UnquotedString(right.map(FailureMessages.decorateToStringValue).mkString(", ")))))
      e.failedCodeFileName should be (Some("NoneOfContainMatcherEqualitySpec.scala"))
      e.failedCodeLineNumber should be (Some(lineNumber))
    }

    def checkShouldNotContainStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int) {
      val leftText = FailureMessages.decorateToStringValue(left)
      e.message should be (Some(FailureMessages("didNotContainAtLeastOneOf", left, UnquotedString(right.map(FailureMessages.decorateToStringValue).mkString(", ")))))
      e.failedCodeFileName should be (Some("NoneOfContainMatcherEqualitySpec.scala"))
      e.failedCodeLineNumber should be (Some(lineNumber))
    }

    def `should take custom implicit equality in scope when 'should contain' is used` {
      implicit val equality = new FalseEquality
      List(1, 2, 3) should contain noneOf (1, 2, 3)
      Set(1, 2, 3) should contain noneOf (1, 2, 3)
      Array(1, 2, 3) should contain noneOf (1, 2, 3)
      javaList(1, 2, 3) should contain noneOf (1, 2, 3)
      javaSet(1, 2, 3) should contain noneOf (1, 2, 3)

      implicit val mapEquality = new MapSetEquality(Set(1 -> "one", 2 -> " two", 3 -> "three"), Set(1 -> "one", 2 -> " two", 3 -> "three"), false)
      Map(1 -> "one", 2 -> " two", 3 -> "three") should contain noneOf (1 -> "one", 2 -> " two", 3 -> "three")

      implicit val javaMapEquality = new JavaMapSetEquality(Set(Entry(1, "one"), Entry(2, " two"), Entry(3, "three")), Set(Entry(1, "one"), Entry(2, " two"), Entry(3, "three")), false)
      javaMap(Entry(1, "one"), Entry(2, " two"), Entry(3, "three")) should contain noneOf (Entry(1, "one"), Entry(2, " two"), Entry(3, "three"))
    }

    def `should take custom implicit equality in scope when 'should not contain' is used` {
      implicit val equality = new SetEquality(Set(1, 2, 3), Set(7, 8, 9), true)
      List(1, 2, 3) should not contain noneOf (7, 8, 9)
      Set(1, 2, 3) should not contain noneOf (7, 8, 9)
      Array(1, 2, 3) should not contain noneOf (7, 8, 9)
      javaList(1, 2, 3) should not contain noneOf (7, 8, 9)
      javaSet(1, 2, 3) should not contain noneOf (7, 8, 9)

      implicit val mapEquality = new MapSetEquality(Set(1 -> "one", 2 -> "two", 3 -> "three"), Set(7 -> "seven", 8 -> "eight", 9 -> "nine"), true)
      Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain noneOf (7 -> "seven", 8 -> "eight", 9 -> "nine")

      implicit val javaMapEquality = new JavaMapSetEquality(Set(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")), Set(Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine")), true)
      javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain noneOf (Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine"))
    }

    def `should throw TestFailedException with correct stack depth and message when 'should contain custom matcher' failed with custom implicit equality in scope` {
      implicit val equality = new SetEquality(Set(1, 2, 3), Set(6, 7, 8), true)

      val left1 = List(1, 2, 3)
      val e1 = intercept[exceptions.TestFailedException] {
        left1 should contain noneOf (6, 7, 8)
      }
      checkShouldContainStackDepth(e1, left1, Array(6, 7, 8).deep, thisLineNumber - 2)

      val left2 = Set(1, 2, 3)
      val e2 = intercept[exceptions.TestFailedException] {
        left2 should contain noneOf (6, 7, 8)
      }
      checkShouldContainStackDepth(e2, left2, Array(6, 7, 8).deep, thisLineNumber - 2)

      val left3 = Array(1, 2, 3)
      val e3 = intercept[exceptions.TestFailedException] {
        left3 should contain noneOf (6, 7, 8)
      }
        checkShouldContainStackDepth(e3, left3, Array(6, 7, 8).deep, thisLineNumber - 2)

      val left4 = javaList(1, 2, 3)
      val e4 = intercept[exceptions.TestFailedException] {
        left4 should contain noneOf (6, 7, 8)
      }
      checkShouldContainStackDepth(e4, left4, Array(6, 7, 8).deep, thisLineNumber - 2)

      implicit val mapEquality = new MapSetEquality(Set(1 -> "one", 2 -> "two", 3 -> "three"), Set(6 -> "six", 7 -> "seven", 8 -> "eight"), true)

      val left5 = Map(1 -> "one", 2 -> "two", 3 -> "three")
      val e5 = intercept[exceptions.TestFailedException] {
        left5 should contain noneOf (6 -> "six", 7 -> "seven", 8 -> "eight")
      }
      checkShouldContainStackDepth(e5, left5, Array(6 -> "six", 7 -> "seven", 8 -> "eight").deep, thisLineNumber - 2)

      implicit val javaMapEquality = new JavaMapSetEquality(Set(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")), Set(Entry(6, "six"), Entry(7, "seven"), Entry(8, "eight")), true)

      val left6 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
      val e6 = intercept[exceptions.TestFailedException] {
        left6 should contain noneOf (Entry(6, "six"), Entry(7, "seven"), Entry(8, "eight"))
      }
      checkShouldContainStackDepth(e6, left6, Array(Entry(6, "six"), Entry(7, "seven"), Entry(8, "eight")).deep, thisLineNumber - 2)
    }

    def `should throw TestFailedException with correct stack depth and message when 'should not contain custom matcher' failed with custom implicit equality in scope` {
      implicit val equality = new SetEquality(Set(1, 2, 3), Set(1, 2, 3), false)

      val left1 = List(1, 2, 3)
      val e1 = intercept[exceptions.TestFailedException] {
        left1 should not contain noneOf (1, 2, 3)
      }
      checkShouldNotContainStackDepth(e1, left1, Array(1, 2, 3).deep, thisLineNumber - 2)

      val left2 = Set(1, 2, 3)
      val e2 = intercept[exceptions.TestFailedException] {
        left2 should not contain noneOf (1, 2, 3)
      }
      checkShouldNotContainStackDepth(e2, left2, Array(1, 2, 3).deep, thisLineNumber - 2)

      val left3 = Array(1, 2, 3)
      val e3 = intercept[exceptions.TestFailedException] {
        left3 should not contain noneOf (1, 2, 3)
      }
      checkShouldNotContainStackDepth(e3, left3, Array(1, 2, 3).deep, thisLineNumber - 2)

      val left4 = javaList(1, 2, 3)
      val e4 = intercept[exceptions.TestFailedException] {
        left4 should not contain noneOf (1, 2, 3)
      }
      checkShouldNotContainStackDepth(e4, left4, Array(1, 2, 3).deep, thisLineNumber - 2)

      implicit val mapEquality = new MapSetEquality(Set(1 -> "one", 2 -> "two", 3 -> "three"), Set(1 -> "one", 2 -> "two", 3 -> "three"), false)

      val left5 = Map(1 -> "one", 2 -> "two", 3 -> "three")
      val e5 = intercept[exceptions.TestFailedException] {
        left5 should not contain noneOf (1 -> "one", 2 -> "two", 3 -> "three")
      }
      checkShouldNotContainStackDepth(e5, left5, Array(1 -> "one", 2 -> "two", 3 -> "three").deep, thisLineNumber - 2)

      implicit val javaMapEquality = new JavaMapSetEquality(Set(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")), Set(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")), false)

      val left6 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
      val e6 = intercept[exceptions.TestFailedException] {
        left6 should not contain noneOf (Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
      }
      checkShouldNotContainStackDepth(e6, left6, Array(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")).deep, thisLineNumber - 2)
    }

    def `should take custom explicit equality in scope when 'should contain' is used` {
      val equality = new FalseEquality
      (List(1, 2, 3) should contain noneOf (1, 2, 3)) (equality)
      (Set(1, 2, 3) should contain noneOf (1, 2, 3)) (equality)
      (Array(1, 2, 3) should contain noneOf (1, 2, 3)) (equality)
      (javaList(1, 2, 3) should contain noneOf (1, 2, 3)) (equality)
      (javaSet(1, 2, 3) should contain noneOf (1, 2, 3)) (equality)

      val mapEquality = new MapSetEquality(Set(1 -> "one", 2 -> " two", 3 -> "three"), Set(1 -> "one", 2 -> " two", 3 -> "three"), false)
      (Map(1 -> "one", 2 -> " two", 3 -> "three") should contain noneOf (1 -> "one", 2 -> " two", 3 -> "three")) (mapEquality)

      val javaMapEquality = new JavaMapSetEquality(Set(Entry(1, "one"), Entry(2, " two"), Entry(3, "three")), Set(Entry(1, "one"), Entry(2, " two"), Entry(3, "three")), false)
      (javaMap(Entry(1, "one"), Entry(2, " two"), Entry(3, "three")) should contain noneOf (Entry(1, "one"), Entry(2, " two"), Entry(3, "three"))) (javaMapEquality)
    }

    def `should take custom explicit equality in scope when 'should not contain' is used` {
      val equality = new SetEquality(Set(1, 2, 3), Set(7, 8, 9), true)
      (List(1, 2, 3) should not contain noneOf (7, 8, 9)) (equality)
      (Set(1, 2, 3) should not contain noneOf (7, 8, 9)) (equality)
      (Array(1, 2, 3) should not contain noneOf (7, 8, 9)) (equality)
      (javaList(1, 2, 3) should not contain noneOf (7, 8, 9)) (equality)
      (javaSet(1, 2, 3) should not contain noneOf (7, 8, 9)) (equality)

      val mapEquality = new MapSetEquality(Set(1 -> "one", 2 -> "two", 3 -> "three"), Set(7 -> "seven", 8 -> "eight", 9 -> "nine"), true)
      (Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain noneOf (7 -> "seven", 8 -> "eight", 9 -> "nine")) (mapEquality)

      val javaMapEquality = new JavaMapSetEquality(Set(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")), Set(Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine")), true)
      (javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain noneOf (Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine"))) (javaMapEquality)
    }

    def `should throw TestFailedException with correct stack depth and message when 'should contain custom matcher' failed with custom explicit equality in scope` {
      val equality = new SetEquality(Set(1, 2, 3), Set(6, 7, 8), true)

      val left1 = List(1, 2, 3)
      val e1 = intercept[exceptions.TestFailedException] {
        (left1 should contain noneOf (6, 7, 8)) (equality)
      }
      checkShouldContainStackDepth(e1, left1, Array(6, 7, 8).deep, thisLineNumber - 2)

      val left2 = Set(1, 2, 3)
      val e2 = intercept[exceptions.TestFailedException] {
        (left2 should contain noneOf (6, 7, 8)) (equality)
      }
      checkShouldContainStackDepth(e2, left2, Array(6, 7, 8).deep, thisLineNumber - 2)

      val left3 = Array(1, 2, 3)
      val e3 = intercept[exceptions.TestFailedException] {
        (left3 should contain noneOf (6, 7, 8)) (equality)
      }
        checkShouldContainStackDepth(e3, left3, Array(6, 7, 8).deep, thisLineNumber - 2)

      val left4 = javaList(1, 2, 3)
      val e4 = intercept[exceptions.TestFailedException] {
        (left4 should contain noneOf (6, 7, 8)) (equality)
      }
      checkShouldContainStackDepth(e4, left4, Array(6, 7, 8).deep, thisLineNumber - 2)

      val mapEquality = new MapSetEquality(Set(1 -> "one", 2 -> "two", 3 -> "three"), Set(6 -> "six", 7 -> "seven", 8 -> "eight"), true)

      val left5 = Map(1 -> "one", 2 -> "two", 3 -> "three")
      val e5 = intercept[exceptions.TestFailedException] {
        (left5 should contain noneOf (6 -> "six", 7 -> "seven", 8 -> "eight")) (mapEquality)
      }
      checkShouldContainStackDepth(e5, left5, Array(6 -> "six", 7 -> "seven", 8 -> "eight").deep, thisLineNumber - 2)

      val javaMapEquality = new JavaMapSetEquality(Set(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")), Set(Entry(6, "six"), Entry(7, "seven"), Entry(8, "eight")), true)
      val left6 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
      val e6 = intercept[exceptions.TestFailedException] {
        (left6 should contain noneOf (Entry(6, "six"), Entry(7, "seven"), Entry(8, "eight"))) (javaMapEquality)
      }
      checkShouldContainStackDepth(e6, left6, Array(Entry(6, "six"), Entry(7, "seven"), Entry(8, "eight")).deep, thisLineNumber - 2)
    }

    def `should throw TestFailedException with correct stack depth and message when 'should not contain custom matcher' failed with custom explicit equality in scope` {
      val equality = new SetEquality(Set(1, 2, 3), Set(1, 2, 3), false)

      val left1 = List(1, 2, 3)
      val e1 = intercept[exceptions.TestFailedException] {
        (left1 should not contain noneOf (1, 2, 3)) (equality)
      }
      checkShouldNotContainStackDepth(e1, left1, Array(1, 2, 3).deep, thisLineNumber - 2)

      val left2 = Set(1, 2, 3)
      val e2 = intercept[exceptions.TestFailedException] {
        (left2 should not contain noneOf (1, 2, 3)) (equality)
      }
      checkShouldNotContainStackDepth(e2, left2, Array(1, 2, 3).deep, thisLineNumber - 2)

      val left3 = Array(1, 2, 3)
      val e3 = intercept[exceptions.TestFailedException] {
        (left3 should not contain noneOf (1, 2, 3)) (equality)
      }
      checkShouldNotContainStackDepth(e3, left3, Array(1, 2, 3).deep, thisLineNumber - 2)

      val left4 = javaList(1, 2, 3)
      val e4 = intercept[exceptions.TestFailedException] {
        (left4 should not contain noneOf (1, 2, 3)) (equality)
      }
      checkShouldNotContainStackDepth(e4, left4, Array(1, 2, 3).deep, thisLineNumber - 2)

      val mapEquality = new MapSetEquality(Set(1 -> "one", 2 -> "two", 3 -> "three"), Set(1 -> "one", 2 -> "two", 3 -> "three"), false)

      val left5 = Map(1 -> "one", 2 -> "two", 3 -> "three")
      val e5 = intercept[exceptions.TestFailedException] {
        (left5 should not contain noneOf (1 -> "one", 2 -> "two", 3 -> "three")) (mapEquality)
      }
      checkShouldNotContainStackDepth(e5, left5, Array(1 -> "one", 2 -> "two", 3 -> "three").deep, thisLineNumber - 2)

      val javaMapEquality = new JavaMapSetEquality(Set(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")), Set(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")), false)

      val left6 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
      val e6 = intercept[exceptions.TestFailedException] {
        (left6 should not contain noneOf (Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))) (javaMapEquality)
      }
      checkShouldNotContainStackDepth(e6, left6, Array(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")).deep, thisLineNumber - 2)
    }
  }
}


text:
package com.ddmeng.zhihudaily.base;

public interface BaseView {
}


text:
layout: post
title: Program Profiling Using Systemtap
---

SystemTap (stap) is both scripting language and tool for profiling program on Linux kernel-based operation system. The most important feature is its ability to probe user-land function, different from tools like [strace](http://linux.die.net/man/1/strace) and [perf](http://en.wikipedia.org/wiki/Perf_%28Linux%29) which can only or partly support user-land probing. You can find what it can do in the latest Linux performance tools graph:

![linux_observability_tools](http://www.brendangregg.com/Perf/linux_observability_tools.png)

Stap supports c++ and c. For java, it may support it  from RHEL7 according to [this](http://developerblog.redhat.com/2014/01/10/probing-java-w-systemtap/). The key is the systemtap-runtime-java package, which I don't see it in RHEL6 repo.(Yeah, I use RHEL6.)

##Install Guide

* Make sure utrace is enabled in your OS. By default, RHEL should has this option open. But it's better to double check.
   ```
   grep CONFIG_UTRACE /boot/config-`uname -r`
   ```
* Install required kernel package, including kernel-debuginfo, kernel-debuginfo-common, kernel-devel (**Optional if you only use user-land probe**)

* Install debug info for program ls, which we will use as a test.
`` debuginfo-install `rpm -qf /bin/ls` ``
* Test whether the installation works and user-land probe is enabled. If succeed, it should print out a line "hello world!"
{% highlight bash %}
sudo stap -e 'probe process("ls").function("main") { printf("hello world!\n"); }' -c ls
{% endhighlight %}

##Usage Guide

You don't need to learn stap language very well to use it. There are many good resources on Github. I mainly use scripts from [agentzh](https://github.com/agentzh), who is pretty active on performance tuning using stap. Blow are his two repositories I use:

###[nginx-systemtap-toolkit](https://github.com/openresty/nginx-systemtap-toolkit)

Although this repo is mainly for nginx performance tuning, there are also many for general purpose usage. Here I use the [sample-bt](https://github.com/openresty/nginx-systemtap-toolkit/blob/master/sample-bt) and [sample-bt-off-cpu](https://github.com/openresty/nginx-systemtap-toolkit/blob/master/sample-bt-off-cpu) to generate the [FlameGraph](http://www.brendangregg.com/flamegraphs.html).

* **On-CPU Flame Graph**

sample-bt could be used to generate in-CPU graph. This graph shows how your program consume CPU cycles from the perspective of functions. Follow the instruction [here](https://github.com/openresty/nginx-systemtap-toolkit#sample-bt).

For example, below graph is got from profiling redis server. From the graph, you can clearly see what redis is doing and which funciton consume the most cpu cycles. Some of the functions may not be optimizable, but most of the time you are able to find the bottomneck or some program fault. Click that function, you can follow the stacktrace further.

{% highlight bash %}
# example used to show systemtap use case
# All the use cases use the same program and running paramaters.

# redis-server opens in localhost
# redis-benchmark runs like:
./redis-benchmark -r 10000000 -n 2000000 -t get -P 16 -q

# For more details about redis-benchmark commands please refer to http://redis.io/topics/benchmarks.
{% endhighlight %}

**ATTENTION**: For C++ program, we need to unmangle the .bt file. Please run `cat [bt file] | c++filt -n > [output bt file]`

![redis-on-cpu-get](/images/redis-on-cpu-get.svg)
[Download the svg file and open it in your browser to see the interactive graph](https://github.com/qqibrow/qqibrow.github.io/blob/master/images/redis-on-cpu-get.svg)

* **Off-CPU Flame Graph**

sample-bt-off-cpu could be used to generate off-CPU graph, which shows all the blocking(or latency) come from. Then running process is exactly the same with sample-bt.

The Off-CPU flame graph is a pretty good startpoint for latency analysis. Personally I have a user case here. After a newest feature been pushed to production, we notice the latency went pretty high. Then we got the off-cpu flame graph of the app and find out one specific funtion consumed most of the time. Following that, we found out there is some wrong with our cache layer once under high traffic and finally fixed that. The off-cpu flame graph really helps us quickly target the root casue and also give us a clear picture whether the application is doing the right thing.

Here is a flame graph of redis
![redis-on-cpu-get](/images/redis-on-cpu-get.svg)
[Download the svg file and open it in your browser to see the interactive graph](https://github.com/qqibrow/qqibrow.github.io/blob/master/images/redis-on-cpu-get.svg)

FlameGraph is pretty powerful in performance tuning, since it could give you a overview of the program without any domain-specific knowledge. Need to mention that FlameGraph is independent of stap, you can definitely use other tools to generate flameGraph. Please check following links.

1. [Nodejs in Flames](http://techblog.netflix.com/2014/11/nodejs-in-flames.html)
2. [Java Flame Graphs](http://www.brendangregg.com/blog/2014-06-12/java-flame-graphs.html)

###[stapxx](https://github.com/openresty/stapxx)

stapxx is a macro language built on top of stap, which provide more functionalities and easier to use. For more detail, please review the main page. Here I mainly use the func-latency-distr script. The usage is very clear here.https://github.com/openresty/stapxx#func-latency-distr

For example, below is a comparison I did using func-latency-distr.sxx to show how big the cross-colo latency is:

{% highlight bash %}
# the latency of lookupKeyRead function in redis codebase.
sudo ./func-latency-distr.sxx -x 10995 --arg func='@pfunc(lookupKeyRead)'

Start tracing 10995 (/home/lniu/redis-2.8.13/src/redis-server)
Hit Ctrl-C to end.
^CDistribution of lookupKeyRead latencies (in nanoseconds) for 1859762 samples
max/avg/min: 248455/6884/5955
 value |-------------------------------------------------- count
  1024 |                                                         0
  2048 |                                                         0
  4096 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  1764146
  8192 |@@                                                   80367
 16384 |                                                     14996
 32768 |                                                       228
 65536 |                                                        22
131072 |                                                         3
262144 |                                                         0
524288 |                                                         0

{% endhighlight %}

Please leave a message if you have any questions. I am glad to help :)


text:
(function($){
    $(function(){
        $('.button-collapse').sideNav();
        $('.parallax').parallax();
    })
})(jQuery);

$(document).ready(function(){
    $('.materialboxed').materialbox();
});

$('#bg1-arrow').addClass('animated fadeOutDown infinite')

// tooltips
$(document).ready(function(){
    $('.tooltipped').tooltip({delay: 50});
});

// scroll spy
$(document).ready(function(){
    $('.scrollspy').scrollSpy();
});

$(".sidenav").hide();
$(window).scroll(function() {
    if ($(this).scrollTop()>400)
    {
        $('.sidenav').fadeIn();
    }
    else
    {
        $('.sidenav').fadeOut();
    }
});

$(document).ready(function() {
    $(window).scroll(function() {
        if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
            $(".sidenav").fadeOut();
        }
    });
});

$(document).ready(function(){
    $('.slider').slider({full_width: true});
});