text:
package wich.semantics;

import org.antlr.symtab.Type;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.TerminalNode;
import wich.parser.WichParser;
import wich.parser.WichParser.ExprContext;
import wich.semantics.symbols.WBuiltInTypeSymbol;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

import static wich.parser.WichParser.ADD;
import static wich.parser.WichParser.AND;
import static wich.parser.WichParser.DIV;
import static wich.parser.WichParser.EQUAL_EQUAL;
import static wich.parser.WichParser.GE;
import static wich.parser.WichParser.GT;
import static wich.parser.WichParser.LE;
import static wich.parser.WichParser.LT;
import static wich.parser.WichParser.MUL;
import static wich.parser.WichParser.NOT_EQUAL;
import static wich.parser.WichParser.OR;
import static wich.parser.WichParser.SUB;
import static wich.semantics.SymbolTable._boolean;
import static wich.semantics.SymbolTable._float;
import static wich.semantics.SymbolTable._int;
import static wich.semantics.SymbolTable._string;
import static wich.semantics.SymbolTable._vector;

public class TypeHelper {
	protected static final WBuiltInTypeSymbol[][][] opResultTypeMap =
		new WBuiltInTypeSymbol[WichParser.tokenNames.length+1][][];
	protected static final WBuiltInTypeSymbol[][][] operandPromotionMap =
		new WBuiltInTypeSymbol[WichParser.tokenNames.length+1][][];

	// ---------------------------- Result Type Table ----------------------------
	// *, / -
	protected static final WBuiltInTypeSymbol[][] arithmeticResultTable = new WBuiltInTypeSymbol[][] {
	/*           int        float       string      vector      boolean */
	/*int*/	    {_int,      _float,     null,       _vector,    null},
	/*float*/	{_float,    _float,     null,       _vector,    null},
	/*string*/	{null,      null,       null,       null,       null},
	/*vector*/	{_vector,   _vector,    null,       _vector,    null},
	/*boolean*/	{null,      null,       null,       null,       null}
	};
	// +
	protected static final WBuiltInTypeSymbol[][] arithmeticStrResultTable = new WBuiltInTypeSymbol[][] {
	/*           int        float       string      vector      boolean */
	/*int*/	    {_int,      _float,     _string,    _vector,    null},
	/*float*/	{_float,    _float,     _string,    _vector,    null},
	/*string*/	{_string,   _string,    _string,    _string,    null},
	/*vector*/	{_vector,   _vector,    _string,    _vector,    null},
	/*boolean*/	{null,      null,       null,       null,       null}
	};
	// <, <=, >, >=
	protected static final WBuiltInTypeSymbol[][] relationalResultTable = new WBuiltInTypeSymbol[][] {
	/*           int        float       string      vector      boolean */
	/*int*/	    {_boolean,  _boolean,   null,       null,       null},
	/*float*/	{_boolean,  _boolean,   null,       null,       null},
	/*string*/	{null,      null,       _boolean,   null,       null},
	/*vector*/	{null,      null,       null,       null,       null},
	/*boolean*/	{null,      null,       null,       null,       null}
	};
	// ==, != (also assign =)
	protected static final WBuiltInTypeSymbol[][] equalityResultTable = new WBuiltInTypeSymbol[][] {
	/*           int        float       string      vector      boolean */
	/*int*/	    {_boolean,  _boolean,   null,       null,       null},
	/*float*/	{_boolean,  _boolean,   null,       null,       null},
	/*string*/	{null,      null,       _boolean,   null,       null},
	/*vector*/	{null,      null,       null,       _boolean,   null},
	/*boolean*/	{null,      null,       null,       null,       _boolean}
	};
	// and, or
	protected static final WBuiltInTypeSymbol[][] logicalResultTable = new WBuiltInTypeSymbol[][] {
	/*           int        float       string      vector      boolean */
	/*int*/	    {null,      null,       null,       null,       null},
	/*float*/	{null,      null,       null,       null,       null},
	/*string*/	{null,      null,       null,       null,       null},
	/*vector*/	{null,      null,       null,       null,       null},
	/*boolean*/	{null,      null,       null,       null,       _boolean}
	};

	// ---------------------------- Type Promotion Table ----------------------------
	// *, /, -
	protected static final WBuiltInTypeSymbol[][] arithmeticPromoteFromTo = new WBuiltInTypeSymbol[][] {
	/*           int        float       string      vector      boolean */
	/*int*/	    {null,      _float,     null,       _vector,    null},
	/*float*/	{null,      null,       null,       _vector,    null},
	/*string*/	{null,      null,       null,       null,       null},
	/*vector*/	{null,      null,       null,       null,       null},
	/*boolean*/	{null,      null,       null,       null,       null}
	};
	// +
	protected static final WBuiltInTypeSymbol[][] arithmeticStrPromoteFromTo = new WBuiltInTypeSymbol[][] {
	/*           int        float       string      vector      boolean */
	/*int*/	    {null,      _float,     _string,    _vector,    null},
	/*float*/	{null,      null,       _string,    _vector,    null},
	/*string*/	{null,      null,       null,       null,       null},
	/*vector*/	{null,      null,       _string,    null,       null},
	/*boolean*/	{null,      null,       null,       null,       null}
	};
	// <, <=, >, >=
	protected static final WBuiltInTypeSymbol[][] relationalPromoteFromTo = new WBuiltInTypeSymbol[][] {
	/*           int        float       string      vector      boolean */
	/*int*/	    {null,      _float,     null,       null,       null},
	/*float*/	{null,      null,       null,       null,       null},
	/*string*/	{null,      null,       null,       null,       null},
	/*vector*/	{null,      null,       null,       null,       null},
	/*boolean*/	{null,      null,       null,       null,       null}
	};
	// ==, != (also assign =)
	protected static final WBuiltInTypeSymbol[][] equalityPromoteFromTo = new WBuiltInTypeSymbol[][] {
	/*           int        float       string      vector      boolean */
	/*int*/	    {null,      _float,     null,       null,       null},
	/*float*/	{null,      null,       null,       null,       null},
	/*string*/	{null,      null,       null,       null,       null},
	/*vector*/	{null,      null,       null,       null,       null},
	/*boolean*/	{null,      null,       null,       null,       null}
	};
	// and, or
	protected static final WBuiltInTypeSymbol[][] logicalPromoteFromTo = new WBuiltInTypeSymbol[][] {
	/*           int        float       string      vector      boolean */
	/*int*/	    {null,      null,       null,       null,       null},
	/*float*/	{null,      null,       null,       null,       null},
	/*string*/	{null,      null,       null,       null,       null},
	/*vector*/	{null,      null,       null,       null,       null},
	/*boolean*/	{null,      null,       null,       null,       null}
	};

	static {
		// register result tables.
		opResultTypeMap[MUL] = arithmeticResultTable;
		opResultTypeMap[SUB] = arithmeticResultTable;
		opResultTypeMap[DIV] = arithmeticResultTable;
		opResultTypeMap[ADD] = arithmeticStrResultTable;

		opResultTypeMap[LT]  = relationalResultTable;
		opResultTypeMap[LE]  = relationalResultTable;
		opResultTypeMap[GT]  = relationalResultTable;
		opResultTypeMap[GE]  = relationalResultTable;

		opResultTypeMap[EQUAL_EQUAL] = equalityResultTable;
		opResultTypeMap[NOT_EQUAL]   = equalityResultTable;

		opResultTypeMap[AND] = logicalResultTable;
		opResultTypeMap[OR]  = logicalResultTable;
		// register promote tables.
		operandPromotionMap[MUL] = arithmeticPromoteFromTo;
		operandPromotionMap[SUB] = arithmeticPromoteFromTo;
		operandPromotionMap[DIV] = arithmeticPromoteFromTo;
		operandPromotionMap[ADD] = arithmeticStrPromoteFromTo;

		operandPromotionMap[LT]  = relationalPromoteFromTo;
		operandPromotionMap[LE]  = relationalPromoteFromTo;
		operandPromotionMap[GT]  = relationalPromoteFromTo;
		operandPromotionMap[GE]  = relationalPromoteFromTo;

		operandPromotionMap[EQUAL_EQUAL] = equalityPromoteFromTo;
		operandPromotionMap[NOT_EQUAL]   = equalityPromoteFromTo;

		operandPromotionMap[AND] = logicalPromoteFromTo;
		operandPromotionMap[OR]  = logicalPromoteFromTo;
	}

	/** This method is the general helper method used to calculate result type.
	 *  You should use the method in SymbolTable based on this method.
	 */
	public static Type getResultType(int op, ExprContext le, ExprContext re)
	{
		int li = le.exprType.getTypeIndex();
		int ri = re.exprType.getTypeIndex();
		Type resultType = opResultTypeMap[op][li][ri];
		if (resultType == null) {
			return SymbolTable.INVALID_TYPE;
		}
		le.promoteToType = operandPromotionMap[op][li][ri];
		re.promoteToType = operandPromotionMap[op][ri][li];
		return resultType;
	}

	/** This method is used to promote type in assignment.
	 *  Returns a boolean indicating whether the assignment is legal.
	 *  The expr type info must be available before this method works.
	 */
	public static boolean isLegalAssign(Type ltype, ExprContext expr) {
		return ltype==expr.exprType || ltype==expr.promoteToType;
	}

	/** This method is used to promote type during type annotation */
	public static void promote(ExprContext elem, Type targetType) {
		if (elem.exprType != null ) {  // elem.exprType may not be known
			int selfIndex = elem.exprType.getTypeIndex();
			elem.promoteToType = equalityPromoteFromTo[selfIndex][targetType.getTypeIndex()];
		}
	}

	public static String dumpWithType(ParserRuleContext tree) {
		if (tree == null) return "";
		return String.valueOf(process(tree.children, (t) -> t instanceof TerminalNode, (t) -> "",
		                              (t) -> dumpNonTerminal((ParserRuleContext) t)));
	}

	private static String dumpNonTerminal(ParserRuleContext ctx) {
		StringBuilder sb = new StringBuilder();
		if (ctx instanceof ExprContext || ctx instanceof WichParser.Call_exprContext) {
			sb.append(dumpExprWithType(ctx));
		}
		else {
			sb.append(dumpWithType(ctx));
		}
		return sb.toString();
	}

	protected static String dumpExprWithType(ParserRuleContext ctx) {
		StringBuilder sb = new StringBuilder();
		if (ctx instanceof WichParser.AtomContext) {
			sb.append(dumpPrimaryWithType((WichParser.AtomContext) ctx));
		}
		else if (ctx instanceof WichParser.OpContext) {
			sb.append(dumpOpWithType((WichParser.OpContext) ctx));
		}
		else if (ctx instanceof WichParser.CallContext) {
			sb.append(dumpCallWithType((WichParser.CallContext) ctx));
		}
		else if (ctx instanceof WichParser.Call_exprContext){
			sb.append(dumpCallWithType((WichParser.Call_exprContext) ctx));
		}
		else {
			ExprContext exprCtx = (ExprContext) ctx;
			sb.append(exprCtx.getText()).append(":").append(getPrintType(exprCtx)).append("\n");
			sb.append(process(exprCtx.children, (t)->t instanceof ExprContext,
			                  (t)->dumpExprWithType((ParserRuleContext) t),
			                  (t)->""));
		}
		return sb.toString();
	}

	protected static String dumpOpWithType(WichParser.OpContext ctx) {
		return String.valueOf(process(ctx.children,
		                              (t) -> t instanceof ExprContext,
		                              (t) -> dumpExprWithType((ParserRuleContext) t),
		                              (t) -> "")) + ctx.operator().getText() + ":" + getPrintType(ctx) + "\n";
	}

	protected static String dumpCallWithType(WichParser.CallContext ctx) {
		WichParser.Expr_listContext args = ctx.call_expr().expr_list();
		return ctx.getText() + ":" + getPrintType(ctx) + "\n" +
				String.valueOf(process(args!=null ? args.children : Collections.emptyList(),
				                       (t) -> t instanceof ExprContext,
				                       (t) -> dumpExprWithType((ParserRuleContext) t),
				                       (t) -> ""));
	}

	//overloading to dump call statement with type
	protected static String dumpCallWithType(WichParser.Call_exprContext ctx) {
		WichParser.Expr_listContext args = ctx.expr_list();
		return ctx.getText() + ":" + getPrintType(ctx) + "\n" +
				String.valueOf(process(args!=null ? args.children : Collections.emptyList(),
						(t) -> t instanceof ExprContext,
						(t) -> dumpExprWithType((ParserRuleContext) t),
						(t) -> ""));
	}

	protected static String dumpPrimaryWithType(WichParser.AtomContext ctx) {
		StringBuilder sb = new StringBuilder();
		sb.append(ctx.getText()).append(":").append(getPrintType(ctx)).append("\n");
		if (ctx.primary() instanceof WichParser.VectorContext) {
			WichParser.VectorContext vectorContext = (WichParser.VectorContext) ctx.primary();
			sb.append(process(vectorContext.expr_list().expr(), (t) -> true, TypeHelper::dumpExprWithType, (t) -> ""));
		}
		return sb.toString();
	}

	protected static String getPrintType(ExprContext ctx) {
		StringBuilder sb = new StringBuilder();
		sb.append(ctx.exprType.getName());
		if (ctx.promoteToType != null) {
			sb.append(" => ").append(ctx.promoteToType);
		}
		return sb.toString();
	}

	//overloading to get print type for call statement
	protected static String getPrintType(WichParser.Call_exprContext ctx) {
		StringBuilder sb = new StringBuilder();
		sb.append(ctx.exprType.getName());
		if (ctx.promoteToType != null) {
			sb.append(" => ").append(ctx.promoteToType);
		}
		return sb.toString();
	}

	protected static <T, R> StringBuilder process(List<T> children,
	                                              Predicate<T> pred,
	                                              Function<T, R> func1,
	                                              Function<T, R> func2)
	{
		StringBuilder sb = new StringBuilder();
		for (T child : children) {
			if (pred.test(child)) {
				sb.append(func1.apply(child));
			}
			else {
				sb.append(func2.apply(child));
			}
		}
		return sb;
	}

	public static boolean typesAreCompatible(ExprContext elem, Type type) {
		return elem.exprType == type || elem.promoteToType == type;
	}
}


text:
qc::safe_attributes_check
===========

part of [Safe HTML](../safe-html-markdown.md)

Usage
-----
`safe_attributes_check node`

Description
-----------
Checks the node and all of it's children for unsafe attributes.
Returns true if all elements are safe otherwise false.

Examples
--------
```tcl

% set doc [dom parse -html "<p foo=\"bar\">Hello world</p>"]
domDoc0x43046b0
% set root [$doc documentElement]
domNode0x377c310
%
% safe_attributes_check $root
false

```

----------------------------------
*[Qcode Software Limited] [qcode]*

[qcode]: http://www.qcode.co.uk "Qcode Software"

redpajama_set_name: RedPajamaGithub


text:
.. _verification_and_processing:

Verification and Processing
========================================

Since ``sklearn`` is defined in terms of :class:`numpy.ndarray` (and not :class:`pandas.DataFrame`), Ibex estimators perform verification and processing on their inputs and outputs.

In this chapter we'll use a ``DataFrame`` ``X``, with columns ``'a'`` and ``'b'``, and (implied) index ``1, 2, 3``.

    >>> import pandas as pd
    >>> X = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})

a scaling transformer ``trn`` which is ``fit``-ted on ``X``

    >>> from ibex.sklearn import preprocessing as pd_preprocessing
    >>> trn = pd_preprocessing.StandardScaler().fit(X)

and a linear-regression predictor ``prd`` which is also ``fit``-ted on ``X``

    >>> from ibex.sklearn import linear_model as pd_linear_model
    >>> prd = pd_linear_model.LinearRegression().fit(X, pd.Series([3, 4]))

Input Verification
------------------

Following the call to ``fit``, we can apply further methods of ``trn`` to any ``DataFrame`` with the same column-set. For example, this is OK

    >>> X_1 = pd.DataFrame({'a': [1, 2, 3], 'b': [3, 4, 5]})
    >>> trn.transform(X_1)
          a    b
    0 -1... -1...
    1  1...  1...
    2  3...  3...

but this is not

    >>> X_2 = X_1.rename(columns={'b': 'c'})
    >>> trn.transform(X_2)
    Traceback (most recent call last):
    ...
    KeyError: "...'b'...not in index"

|

Once an estimator has been ``fit``-ed, the order of columns of further inputs no longer matters:

    >>> trn.transform(X_1[['a', 'b']])
          a    b
    0 -1... -1...
    1  1...  1...
    2  3...  3...

    >>> trn.transform(X_1[['b', 'a']])
          a    b
    0 -1... -1...
    1  1...  1...
    2  3...  3...

The ``step`` will reorder the ``DataFrame`` to the same order of columns seen by ``fit``.

.. _verification_and_processing_output:

Output Processing
-----------------

Indexes
~~~~~~~

The index of a returned ``DataFrame`` or ``Series`` objects, is that of the input:

    >>> X_1 = pd.DataFrame({'a': [1, 2, 3], 'b': [3, 4, 5]}, index=[10, 20, 30])
    >>> trn.transform(X_1)
          a    b
    10 -1... -1...
    20  1...  1...
    30  3...  3...
    >>>
    >>> prd.predict(X_1)
    10    3...
    20    4...
    30    5...
    dtype: ...

.. _verification_and_processing_output_dataframe_columns:

``DataFrame`` Columns
~~~~~~~~~~~~~~~~~~~~~

In general, the columns of an outputted ``DataFrame`` object are those on which the estimator was ``fit``-ted:

    >>> trn.transform(X_1[['a', 'b']])
          a    b
    10 -1... -1...
    20  1...  1...
    30  3...  3...

    >>> trn.transform(X_1[['b', 'a']])
          a    b
    10 -1... -1...
    20  1...  1...
    30  3...  3...

Some outputted ``DataFrame`` objects have a number of columns that is different from that of the input. If this is the case, the resulting ``DataFrame``'s columns will all be blank strings (``''``):

# Tmp Ami

    >>> from ibex.sklearn import decomposition as pd_decomposition
    >>> pd_decomposition.PCA(n_components=1).fit(X).transform(X)
      comp_0
    0 -0.707107
    1  0.707107

.. note::

    In some cases, we might want greater control over the naming of output columns. For example, when transforming a 2-component PCA, we might want to name the ``DataFrame`` columns ``'pc1'`` and ``'pc2'``. :ref:`function_transformer_specifying_output_columns` in :ref:`function_transformer` shows how to do this.


text:
namespace Envoy {

void H1FuzzIntegrationTest::replay(const test::integration::CaptureFuzzTestCase& input) {
  initialize();
  fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
  IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("http"));
  FakeRawConnectionPtr fake_upstream_connection;
  for (int i = 0; i < input.events().size(); ++i) {
    const auto& event = input.events(i);
    ENVOY_LOG_MISC(debug, "Processing event: {}", event.DebugString());
    // If we're disconnected, we fail out.
    if (!tcp_client->connected()) {
      ENVOY_LOG_MISC(debug, "Disconnected, no further event processing.");
      break;
    }
    switch (event.event_selector_case()) {
    case test::integration::Event::kDownstreamSendBytes:
      tcp_client->write(event.downstream_send_bytes(), false, false);
      break;
    case test::integration::Event::kDownstreamRecvBytes:
      // TODO(htuch): Should we wait for some data?
      break;
    case test::integration::Event::kUpstreamSendBytes:
      if (fake_upstream_connection == nullptr) {
        if (!fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection, max_wait_ms_)) {
          // If we timed out, we fail out.
          tcp_client->close();
          return;
        }
      }
      // If we're no longer connected, we're done.
      if (!fake_upstream_connection->connected()) {
        tcp_client->close();
        return;
      }
      {
        AssertionResult result = fake_upstream_connection->write(event.upstream_send_bytes());
        RELEASE_ASSERT(result, result.message());
      }
      break;
    case test::integration::Event::kUpstreamRecvBytes:
      // TODO(htuch): Should we wait for some data?
      break;
    default:
      // Maybe nothing is set?
      break;
    }
  }
  if (fake_upstream_connection != nullptr) {
    if (fake_upstream_connection->connected()) {
      AssertionResult result = fake_upstream_connection->close();
      RELEASE_ASSERT(result, result.message());
    }
    AssertionResult result = fake_upstream_connection->waitForDisconnect(true);
    RELEASE_ASSERT(result, result.message());
  }
  tcp_client->close();
}

} // namespace Envoy


text:
package com.mgmtp.jfunk.core.step.base;

import java.util.Map;

import javax.inject.Inject;

import com.mgmtp.jfunk.data.DataSet;

/**
 * Base class for steps that need {@link DataSet}s. Gets the current data sets injected.
 *
 * @author rnaegele
 */
public abstract class DataSetsStep extends BaseStep {

	private Map<String, DataSet> dataSets;

	/**
	 * the data set key, which used by method {@link #getDataSet()}
	 */
	private final String dataSetKey;

	/**
	 * @param dataSetKey
	 *            the key used by the method {@link #getDataSet()} for retrieving the data set from
	 *            the map of all available data sets
	 */
	public DataSetsStep(final String dataSetKey) {
		this(null, dataSetKey);
	}

	/**
	 * @param name
	 *            the step's name
	 * @param dataSetKey
	 *            the key used by the method {@link #getDataSet()} for retrieving the data set from
	 *            the map of all available data sets
	 */
	public DataSetsStep(final String name, final String dataSetKey) {
		super(name);
		this.dataSetKey = dataSetKey;
	}

	/**
	 * @return the dataSets
	 */
	public Map<String, DataSet> getDataSets() {
		return dataSets;
	}

	/**
	 * @param dataSets
	 *            the dataSets to set
	 */
	@Inject
	public void setDataSets(final Map<String, DataSet> dataSets) {
		this.dataSets = dataSets;
	}

	/**
	 * @return the dataSets
	 */
	public DataSet getDataSet(final String dsKey) {
		return dataSets.get(dsKey);
	}

	/**
	 * Returns the step's default {@link DataSet}.
	 *
	 * @return the step's default {@link DataSet}
	 */
	public DataSet getDataSet() {
		return dataSetKey != null ? dataSets.get(dataSetKey) : null;
	}

	/**
	 * @return the dataSetKey
	 */
	public String getDataSetKey() {
		return dataSetKey;
	}
}


text:
#include <src/opencl_filter_manager.h>
#include <reco/utils/cpp_exception_util.h>
#include <GL/glew.h>
#include <GL/glut.h>

#include <thread>
#include <regex>

namespace reco {
namespace stereo_workbench {

#ifndef GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX
#define GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX 0x9049
#endif

#ifndef GL_VBO_FREE_MEMORY_ATI
#define GL_VBO_FREE_MEMORY_ATI 0x87FB
#endif

const std::vector<int> opencl_filter_manager::nvidia_vendor_ids({4318});
const std::vector<int> opencl_filter_manager::amd_vendor_ids({4130,4098});

opencl_filter_manager::opencl_filter_manager(
		cv::Size image_size, cv::Size cell_size, int num_channels,
		std::string platform_keyword,
		cl_device_type device_type, std::string device_keyword, int device_index) :
				cell_size(cell_size),
				image_size(image_size),
				num_channels(num_channels){

	this->device = opencl_filter_manager::select_device(platform_keyword, device_type,
			device_keyword, device_index);

	device_type = device.getInfo<CL_DEVICE_TYPE>();

	float avail_memory_divisor;

	switch(device_type){
	case CL_DEVICE_TYPE_CPU:
		//we have lots of memory, but we probably need a good portion of it for other applications
		avail_memory_divisor = 4.0F;
		break;
	case CL_DEVICE_TYPE_GPU:
		//we don't have as much memory, but we'll only need about a third for all other processes
		avail_memory_divisor = 1.5;
		break;
	default:
		//arbitrary accelerator -- use 1/3, adjust as necessary
		avail_memory_divisor = 3;
		break;
	}

	context = cl::Context(device);
#ifdef NEED_GLOBAL_MEM
	int global_mem = device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>();
	int local_mem = device.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>();
	int work_group_size = device.getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>();
#endif
	//number of streaming multiprocessors
	int num_SMs = device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
	max_threads = opencl_filter_manager::estimate_num_processors_per_SM(device) * num_SMs;
	opencl_filter_manager::determine_image_types(context, uint8_format, int16_format, uint32_format);

	warp_size = determine_warp_size(device,context);
	half_warp_size = warp_size >> 1;
	int avail_mem = estimate_available_cl_device_memory(device);
	const int channel_num = 4;

	if(cell_size.height == 0 && cell_size.width == 0){

		int memory_bound = std::pow(2,int(std::log2(std::sqrt(avail_mem / avail_memory_divisor / channel_num))));
		int max_width = device.getInfo<CL_DEVICE_IMAGE2D_MAX_WIDTH>();
		int max_height = device.getInfo<CL_DEVICE_IMAGE2D_MAX_HEIGHT>();
		int cell_lateral_size = std::min({memory_bound, max_width, max_height});
		cell_size.height = cell_size.width = cell_lateral_size;
	}

	cells_per_image = cv::Size(image_size.width / cell_size.width, image_size.height / cell_size.height);
	group_dims = cv::Size(
			(cell_size.width + max_threads - 1) / max_threads,
			(cell_size.height + max_threads - 1) / max_threads);
	block_dims = cv::Size(cell_size.height, cell_size.width);
	max_warps = max_threads / warp_size;
	schedule_optimized_n_warps = max_warps - 1;
	input_stride = cell_size.width * schedule_optimized_n_warps;
	queue = cl::CommandQueue(context, device);
}

opencl_filter_manager::~opencl_filter_manager(){

}

cl::Device opencl_filter_manager::select_device(std::string platform_keyword,
		cl_device_type device_type, std::string device_keyword, int device_index){
	std::vector<cl::Platform> all_platforms;
	cl::Platform::get(&all_platforms);
	if(all_platforms.size() == 0){
		err2(std::runtime_error, "No OpenCL platforms detected");
	}
	cl::Platform selected_platform;
	bool platform_found = false;
	std::regex platform_keyword_regex(platform_keyword, std::regex_constants::icase);
	for(cl::Platform platform : all_platforms){
		std::string platform_name = platform.getInfo<CL_PLATFORM_NAME>();
		if(std::regex_search(platform_name, platform_keyword_regex)){
			selected_platform = platform;
			platform_found = true;
			break;
		}
	}
	if(!platform_found){
		err2(std::runtime_error, "No OpenCL platform found matching keyword \"" <<
						platform_keyword << "\"");
	}
	std::vector<cl::Device> devices;
	selected_platform.getDevices(device_type,&devices);
	if(devices.size()  == 0){
		err2(std::runtime_error, "No OpenCL device on platform " <<
				selected_platform.getInfo<CL_PLATFORM_NAME>());
	}

	if(device_keyword.length() > 0){
		std::regex device_keyword_regex(device_keyword, std::regex_constants::icase);
		for(cl::Device device : devices){
			std::string device_name = device.getInfo<CL_DEVICE_NAME>();
			if(std::regex_search(device_name, device_keyword_regex)){
				return device;
			}
		}
	}
	if(device_index > (int)devices.size()){
		err2(std::runtime_error, "OpenCL device index out of range. Got " << device_index
				<< ", acceptable values should be in [0, " << devices.size() << "] for platform "
				<< selected_platform.getInfo<CL_PLATFORM_NAME>());
	}
	return devices[device_index];

}

bool opencl_filter_manager::have_opengl_extension(std::string extension){
	int win = glutCreateWindow("test");
	GLint num_extensions = 0;
	bool found = false;
	glGetIntegerv( GL_NUM_EXTENSIONS, &num_extensions);
	for (int i = 0; i < num_extensions && !found; ++i) {
		std::string extension_string = std::string((const char*) glGetStringi( GL_EXTENSIONS, i));
		if(extension_string == extension){
			found = true;
		}
	}
	glutDestroyWindow(win);
	return found;
}

int opencl_filter_manager::estimate_num_processors_per_SM(cl::Device device){
	switch(device.getInfo<CL_DEVICE_TYPE>()){
	case CL_DEVICE_TYPE_CPU:
		{
			int num_SMs = device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
			return std::thread::hardware_concurrency() / num_SMs;
		}
	case CL_DEVICE_TYPE_GPU:
		{
			int vendor_id = device.getInfo<CL_DEVICE_VENDOR_ID>();
			if(std::find(nvidia_vendor_ids.begin(),nvidia_vendor_ids.end(), vendor_id) !=
					nvidia_vendor_ids.end()){
				return 8;
			}else if(std::find(amd_vendor_ids.begin(),amd_vendor_ids.end(), vendor_id) !=
					amd_vendor_ids.end()){
				return 4;
			}
		}
		return 1;
	default:
		return 1;
	}
}

void opencl_filter_manager::determine_image_types(cl::Context context, cl::ImageFormat& uint8_format,
			cl::ImageFormat& int16_format,cl::ImageFormat& uint32_format){
	std::vector<cl::ImageFormat> formats;
	context.getSupportedImageFormats(CL_MEM_READ_WRITE, CL_MEM_OBJECT_IMAGE2D,&formats);
	bool uint8_picked, int16_picked, uint32_picked;
	uint8_picked = int16_picked = uint32_picked = false;

	for (cl::ImageFormat format : formats){
		cl_channel_type channel_type = format.image_channel_data_type;
		cl_channel_order channel_order = format.image_channel_order;
		switch(channel_type){
		case CL_UNSIGNED_INT8:
			if(channel_order == CL_RGB){
				uint8_format = format; //ideal case;
				uint8_picked = true;
			}else if(!uint8_picked && channel_order == CL_RGBA){
				uint8_format = format; //second best
				uint8_picked = true;
			}
			break;
		case CL_SIGNED_INT16:
			if(channel_order == CL_RGB){
				int16_format = format; //ideal case;
				int16_picked = true;
			}else if(!int16_picked && channel_order == CL_RGBA){
				int16_format = format; //second best
				int16_picked = true;
			}
			break;
		case CL_UNSIGNED_INT32:
			if(channel_order == CL_RGB){
				uint32_format = format; //ideal case;
				uint32_picked = true;
			}else if(!uint32_picked && channel_order == CL_RGBA){
				uint32_format = format; //second best
				uint32_picked = true;
			}
			break;
		}

	}
}

int opencl_filter_manager::estimate_available_cl_device_memory(cl::Device device){
	int mb_estimated = 500;
	int b_in_mb = 1048576; //2^20
	int b_in_kb = 1024; //2^10
	int bytes_estimated = b_in_mb * mb_estimated;
	//bool success = false;

	switch(device.getInfo<CL_DEVICE_TYPE>()){
	case CL_DEVICE_TYPE_CPU:
		{
			//assume we are unbounded or, say, 1 GB
			bytes_estimated = 1073741824;
		}
		break;
	case CL_DEVICE_TYPE_GPU:
		{
			int vendor_id = device.getInfo<CL_DEVICE_VENDOR_ID>();

			if(std::find(nvidia_vendor_ids.begin(),nvidia_vendor_ids.end(), vendor_id) !=
					nvidia_vendor_ids.end() && have_opengl_extension("GL_NVX_gpu_memory_info")){
				char *fake_argv [1];
				int fake_argc=1;
				fake_argv[0] = strdup ("dummy_app_name");
				glutInit(&fake_argc, fake_argv);
				glewExperimental = GL_TRUE;
				int win = glutCreateWindow("test");
				GLenum glewError = glewInit();
				if(glewError != GLEW_OK){
					err2(std::runtime_error,"Was unable to initialize glew in order to retrieve available GPU memory.");
				}
				GLint available_memory_in_kb = 0;
				glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX,
									   &available_memory_in_kb);
				if(available_memory_in_kb > 0){
					bytes_estimated = b_in_kb * available_memory_in_kb;
				}
				glutDestroyWindow(win);
			}else if(std::find(amd_vendor_ids.begin(),amd_vendor_ids.end(), vendor_id) !=
					amd_vendor_ids.end() && have_opengl_extension("GL_ATI_meminfo")){
				GLint bytes_estimated = 0;
				glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, &bytes_estimated);
			}
		}
		break;
	default:
		break;
	}

	return bytes_estimated;
}

int opencl_filter_manager::determine_warp_size(cl::Device device, cl::Context context){
	std::string test_kernel_code =
			"__kernel \n"
			"void testKernel(){}";
	cl::Program::Sources sources;
	sources.push_back({test_kernel_code.c_str(), test_kernel_code.length()});
	cl::Program program(context,sources);
	if(program.build({device})!= CL_SUCCESS){
		err2(std::runtime_error," Error building test kernel: "
				<< program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << "\n");
	}
	std::vector<cl::Kernel> kernels;
	program.createKernels(&kernels);
	cl::Kernel test_kernel = kernels[0];
	return static_cast<int>(test_kernel.getWorkGroupInfo<CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE>(device));
}

} /* namespace stereo_workbench */
} /* namespace reco */


text:
scrap-me-a-cave
===============

A naive scrapper for mail you new apartments

UPDATE:
-------
* Status: WIP
* In the next cave searching I'll finish it :(


text:
// $Id$
/**
 * Date: 27.10.2004
 */
package ru.ifmo.neerc.chat.client;

import ru.ifmo.neerc.chat.Chat;
import ru.ifmo.neerc.task.Task;
import ru.ifmo.neerc.task.TaskActions;
import ru.ifmo.neerc.task.TaskRegistry;
import ru.ifmo.neerc.task.TaskRegistryListener;
import ru.ifmo.neerc.task.TaskStatus;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author Matvey Kazakov
 */
public class AdminTaskPanel extends JPanel {

    private Frame owner;
    private AdminTaskList taskList;
    private JButton btnAssignTask;
    private JButton btnRemoveTask;

    private AbstractButton btnActionDone;
    private AbstractButton btnActionStart;
    private AbstractButton btnActionFail;

    public Component adminToolBar;
    public Component userToolBar;
    public Component toolBar;

    private Chat chat;
    private String username;

    public AdminTaskPanel(Frame owner, TaskRegistry taskRegistry, Chat chat, String username) {
        super(new BorderLayout());
        this.owner = owner;
        this.chat = chat;
        this.username = username;
        taskList = new AdminTaskList(taskRegistry, username);

        taskList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                enableButtons();
            }
        });
        taskRegistry.addListener(new TaskRegistryListener() {
            public void taskChanged(Task task) {
                enableButtons();
            }
            public void tasksReset() {
                enableButtons();
            }
        });

        taskList.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() % 2 == 0) {
                    performDefaultAction();
                }
            }
        });

        toolBar = createToolBar();

        add(new JScrollPane(taskList), BorderLayout.CENTER);
        add(toolBar, BorderLayout.NORTH);
        enableButtons();

        adminToolBar.setVisible(false);
    }

    private void enableButtons() {
        boolean enable = taskList.getSelectedRow() != -1;
        enableButton(enable, btnAssignTask);
        enableButton(enable, btnRemoveTask);

        Task task = getSelectedTask();
        enableButton(
                TaskActions.isActionSupported(task, username, TaskActions.ACTION_FAIL),
                btnActionFail
        );
        enableButton(
                TaskActions.isActionSupported(task, username, TaskActions.ACTION_START),
                btnActionStart
        );
        enableButton(
                TaskActions.isActionSupported(task, username, TaskActions.ACTION_DONE),
                btnActionDone
        );
    }

    private void enableButton(boolean enable, Component btn) {
        if (btn != null) {
            btn.setEnabled(enable);
        }
    }

    private Component createToolBar() {
        JToolBar toolBar = new JToolBar();

        toolBar.setBorderPainted(false);
        toolBar.setMargin(new Insets(0, 0, 0, 0));
        toolBar.setFloatable(false);
        toolBar.setRollover(true);

        adminToolBar = createAdminToolBar();
        userToolBar = createUserToolBar();

        toolBar.add(userToolBar);
        toolBar.add(Box.createHorizontalStrut(20));
        toolBar.add(adminToolBar);

        return toolBar;
    }

    private Component createAdminToolBar() {
        JToolBar toolBar = new JToolBar();

        toolBar.setBorderPainted(false);
        toolBar.setMargin(new Insets(0, 0, 0, 0));
        toolBar.setFloatable(false);
        toolBar.setRollover(true);

        toolBar.add(createAddTaskButton(TaskActions.TYPE_TODO, "Add TODO (@todo)"));
        toolBar.add(createAddTaskButton(TaskActions.TYPE_TODOFAIL, "Add TODOFAIL (@todofail)"));
        toolBar.add(createAddTaskButton(TaskActions.TYPE_CONFIRM, "Add Confirmation (@confirm)"));
        toolBar.add(createAddTaskButton(TaskActions.TYPE_REASON, "Add Ok/Fail Reason (@okfail)"));
        toolBar.add(createAddTaskButton(TaskActions.TYPE_QUESTION, "Add Question (@q)"));

        btnAssignTask = createButton(TaskIcon.iconTaskAssign, "Assign Task");
        btnAssignTask.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Task[] tasks = getSelectedTasks();
                new AssignTaskDialog(owner, chat, tasks).setVisible(true);
                enableButtons();
            }
        });
        toolBar.add(btnAssignTask);

        btnRemoveTask = createButton(TaskIcon.iconTaskRemove, "Delete task");
        btnRemoveTask.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Task[] tasks = getSelectedTasks();
                for (Task task : tasks) {
                    Task remove = new Task(task.getId(), "remove", "");
                    remove.schedule(task.getScheduleType(), task.getScheduleTime());
                    chat.sendTask(remove);
                }
                enableButtons();
            }
        });
        toolBar.add(btnRemoveTask);

        JButton btnHelp = createButton(new ImageIcon(AdminTaskPanel.class.getResource("res/btn_about.gif")), "Help");
        btnHelp.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new AboutBox(owner, "res/tasks.html").setVisible(true);
            }
        });
        toolBar.add(btnHelp);

        return toolBar;
    }

    private Component createUserToolBar() {
        JToolBar toolBar = new JToolBar();

        toolBar.setBorderPainted(false);
        toolBar.setMargin(new Insets(0, 0, 0, 0));
        toolBar.setFloatable(false);
        toolBar.setRollover(true);

        btnActionDone = createButton(TaskActions.ACTION_DONE, "Task is done");
        btnActionFail = createButton(TaskActions.ACTION_FAIL, "Task is failed due to...");
        btnActionStart = createButton(TaskActions.ACTION_START, "Task is started");
        toolBar.add(btnActionStart);
        toolBar.add(btnActionDone);
        toolBar.add(btnActionFail);
        return toolBar;
    }

    private Component createAddTaskButton(final String type, final String message) {
        JButton btnCreateTask = createButton(
                TaskIcon.TYPE.get(type),
                message
        );
        btnCreateTask.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String taskDescription = JOptionPane.showInputDialog(AdminTaskPanel.this, message);
                if (taskDescription != null && taskDescription.trim().length() > 0) {
                    Task task = new Task(type, taskDescription);
                    chat.sendTask(task);
                }
                enableButtons();
            }
        });
        return btnCreateTask;
    }

    private JButton createButton(final ImageIcon icon, final String toolTipText) {
        JButton btn = new JButton(icon);
        btn.setFocusable(false);
        btn.setBorderPainted(false);
        btn.setToolTipText(toolTipText);
        btn.setMargin(new Insets(0, 0, 0, 0));
        return btn;
    }

    private JButton createButton(final int action, final String toolTipText) {
        JButton btn = createButton(TaskIcon.ACTION.get(action), toolTipText);
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                performAction(action);
            }
        });
        return btn;
    }

    private Task[] getSelectedTasks() {
        int[] selectedIndices = taskList.getSelectedRows();
        Task[] tasks = new Task[selectedIndices.length];
        for (int i = 0; i < selectedIndices.length; i++) {
            tasks[i] = (Task) taskList.getModel().getValueAt(taskList.convertRowIndexToModel(selectedIndices[i]), 0);
        }
        return tasks;
    }

    private Task getSelectedTask() {
        int selectedRow = taskList.getSelectedRow();
        return selectedRow != -1 ? (Task) taskList.getModel().getValueAt(taskList.convertRowIndexToModel(selectedRow), 0) : null;
    }

    private void performDefaultAction() {
        Task task = getSelectedTask();
        if (task == null) {
            return;
        }
        TaskStatus taskStatus = task.getStatuses().get(username);
        if (taskStatus == null) {
            return;
        }
        String type = task.getType();
        String status = taskStatus.getType();

        int action = TaskActions.ACTION_DONE;
        if (type.equals(TaskActions.TYPE_TODO) || type.equals(TaskActions.TYPE_TODOFAIL)) {
            action = status.equals(TaskActions.STATUS_RUNNING) ? TaskActions.ACTION_DONE : TaskActions.ACTION_START;
        }
        else if (type.equals(TaskActions.TYPE_REASON)) {
            action = TaskActions.ACTION_FAIL;
        }
        performAction(action);
    }

    private void performAction(int action) {
        Task task = getSelectedTask();
        if (task == null) {
            return;
        }
        TaskStatus taskStatus = task.getStatuses().get(username);
        if (taskStatus == null) {
            return;
        }
        String value = "";
        if (action == TaskActions.ACTION_FAIL) {
            String message = "Give the reason";
            value = JOptionPane.showInputDialog(
                    SwingUtilities.getWindowAncestor(this),
                    message,
                    taskStatus.getValue()
            );
            if (value == null) {
                return;
            }
            if (value.equals("")) {
                action = TaskActions.ACTION_DONE;
            }
        }
        if (task.getType().equals(TaskActions.TYPE_QUESTION)) {
            String message = "Your answer";
            value = JOptionPane.showInputDialog(
                    SwingUtilities.getWindowAncestor(this),
                    message,
                    taskStatus.getValue()
            );
            if (value == null) {
                return;
            }
        }

        String status = TaskActions.getNewStatus(task, username, action);
        try {
            chat.sendTaskStatus(task, new TaskStatus(status, value));
        } catch (IllegalStateException e) {
            JOptionPane.showMessageDialog(
                SwingUtilities.getWindowAncestor(this),
                "Not connected to server",
                "Error",
                JOptionPane.WARNING_MESSAGE
            );
        }
        enableButtons();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/bg_dialog_button_unfocus" android:state_enabled="false" />
    <item android:drawable="@drawable/bg_dialog_start_chamfer" android:state_focused="true" />
    <item android:drawable="@drawable/bg_dialog_start_chamfer" android:state_selected="true" />
    <item android:drawable="@drawable/bg_dialog_start_chamfer" android:state_pressed="true" />
    <item android:drawable="@drawable/bg_dialog_start_chamfer" />
</selector>


text:
// Copyright 2015 Esri
//
// 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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Core.CIM;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using Microsoft.Win32;
using System.Xml.Linq;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Core.Data;

namespace arcgis_pro_import_feature_templates
{
    internal class ImportFeaturesTemplateButton : Button
    {
        private JointMilitarySymbologyLibrary.Librarian _librarian = null;

        protected async override void OnClick()
        {
            CIMFeatureTemplate cimFT;
            List<CIMFeatureTemplate> list = new List<CIMFeatureTemplate>();

            var ps = new ArcGIS.Desktop.Framework.Threading.Tasks.CancelableProgressorSource("Importing feature templates", "Canceled");

            await QueuedTask.Run(() =>
            {
                InitializeLibrarian();

                // browse file dialog

                var ofd = new OpenFileDialog
                {
                    Filter = "xml files (*.xml)|*.xml",
                    RestoreDirectory = true,
                    Multiselect = false
                };

                if (ofd.ShowDialog() == true)
                {
                    var doc = XDocument.Load(ofd.FileName);

                    var elements = from el in doc.Descendants("Children").Descendants("Children").Where(node => node.Elements("Name").Any())
                                   select new
                                   {
                                       eName = el.Element("Name").Value,
                                       eSIC = el.Element("SIC").Value
                                   };

                    foreach (var item in elements)
                    {
                        var s = _librarian.MakeSymbol("2525C", item.eSIC);

                        cimFT = new CIMFeatureTemplate();
                        switch(s.GeometryType)
                        {
                            case JointMilitarySymbologyLibrary.GeometryType.POINT:
                                cimFT.Tags = "Point";
                                cimFT.ToolProgID = "2a8b3331-5238-4025-972e-452a69535b06";
                                break;
                            case JointMilitarySymbologyLibrary.GeometryType.LINE:
                                // JointMilitarySymbologyLibrary only works with points
                                cimFT.Tags = "Line";
                                break;
                            case JointMilitarySymbologyLibrary.GeometryType.AREA:
                                // JointMilitarySymbologyLibrary only work with points
                                cimFT.Tags = "Polygon";
                                break;
                            default:
                                break;
                        }
                        cimFT.Name = item.eName;
                        cimFT.DefaultValues = new Dictionary<string, object>
                            {
                                {"identity",s.SIDC.PartAString.Substring(2,2)},
                                {"context", s.SIDC.PartAString.Substring(6,1)},
                                {"symbolset", s.SIDC.PartAString.Substring(4,2)},
                                {"entity", s.SIDC.PartBString.Substring(0,6)}
                            };

                        list.Add(cimFT);
                    }
                }
            });

            if (MapView.Active != null && list.Any())
            {
                // get toc highlighted layers
                var selLayers = MapView.Active.GetSelectedLayers();
                // retrieve the first one
                Layer layer = selLayers.FirstOrDefault();
                if (layer != null)
                {
                    // find the CIM and serialize it
                    await QueuedTask.Run(() =>
                    {
                        if (layer is FeatureLayer)
                        {
                            AddMatchingSymbolSetsToLayer(layer, list);
                        }
                        else if (layer is GroupLayer)
                        {
                            var gl = layer as GroupLayer;
                            var layerList = gl.GetLayersAsFlattenedList();

                            foreach (var layerItem in layerList)
                            {
                                if (layerItem is FeatureLayer)
                                {
                                    AddMatchingSymbolSetsToLayer(layerItem, list);
                                }
                            }
                        }
                    }, ps.Progressor);
                }
            }
        }

        private void AddMatchingSymbolSetsToLayer(Layer layer, List<CIMFeatureTemplate> list)
        {
            // get layer symbol codes, "symbolset"
            var symbolCodeList = new List<string>();
            var fl = layer as FeatureLayer;

            if (fl.GetTable().GetDatastore() is UnknownDatastore)
                return;
            using (var table = fl.GetTable())
            {
                IReadOnlyList<ArcGIS.Core.Data.Subtype> readOnlyList;
                try
                {
                    var tableDef = table.GetDefinition();
                    readOnlyList = tableDef.GetSubtypes();
                    var fieldIndex = tableDef.FindField("symbolset");
                    if (fieldIndex >= 0)
                    {
                        var fieldValue = tableDef.GetFields().ElementAt(fieldIndex).GetDefaultValue();
                        if (fieldValue != null)
                        {
                            symbolCodeList.Add(fieldValue.ToString());
                        }
                    }
                }
                catch (Exception e)
                {
                    return;
                }
                foreach (var subtype in readOnlyList)
                {
                    //var name = subtype.GetName();
                    var code = subtype.GetCode().ToString();
                    if (!symbolCodeList.Contains(code))
                    {
                        symbolCodeList.Add(code);
                    }
                }
            }

            var filteredList = list.Where(t => symbolCodeList.Contains(t.DefaultValues["symbolset"].ToString()));

            if (filteredList != null && filteredList.Any())
            {
                CIMBaseLayer cim = layer.GetDefinition();

                var cimFL = ((CIMFeatureLayer)cim);

                if (cimFL != null)
                {
                    if (cimFL.FeatureTemplates != null && cimFL.FeatureTemplates.Any())
                    {
                        var tempList = cimFL.FeatureTemplates.ToList();
                        tempList.AddRange(filteredList);
                        cimFL.FeatureTemplates = tempList.ToArray();
                    }
                    else
                    {
                        cimFL.FeatureTemplates = filteredList.ToArray();
                    }

                    layer.SetDefinition(cim);
                }
            }

        }

        private void InitializeLibrarian()
        {
            if (_librarian == null)
            {
                _librarian = new JointMilitarySymbologyLibrary.Librarian();
                //_librarian.IsLogging = true;
            }
        }
    }
}


text:
"""Properties and its collections."""

__author__ = 'Abhinav Khandelwal (abhinavk@google.com)'

import collections

class Property(object):
    """Property."""

    def __init__(
        self, name, label, property_type, select_data=None, description=None,
        optional=False, extra_schema_dict_values=None):
        self._name = name
        self._label = label
        self._property_type = property_type
        self._select_data = select_data
        self._description = description
        self._optional = optional
        self._extra_schema_dict_values = extra_schema_dict_values

    @property
    def name(self):
        return self._name

class Registry(object):
    """Registry is a collection of Property's."""

    def __init__(self, title, description=None, extra_schema_dict_values=None):
        self._title = title
        self._registry = {'id': title, 'type': 'object'}
        self._description = description
        if description:
            self._registry['description'] = description
        self._extra_schema_dict_values = extra_schema_dict_values
        self._properties = []
        self._sub_registories = collections.OrderedDict()

    @property
    def title(self):
        return self._title

    def add_property(self, schema_field):
        """Add a Property to this Registry."""
        self._properties.append(schema_field)

    def add_sub_registry(
        self, name, title=None, description=None, registry=None):
        """Add a sub registry to for this Registry."""
        if not registry:
            registry = Registry(title, description)
        self._sub_registories[name] = registry
        return registry

    def has_subregistries(self):
        return True if self._sub_registories else False


text:
(function () {
    'use strict';

    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
    if (!String.prototype.endsWith) {
        String.prototype.endsWith = function(searchString, position) {
            var subjectString = this.toString();
            if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
                position = subjectString.length;
            }
            position -= searchString.length;
            var lastIndex = subjectString.lastIndexOf(searchString, position);
            return lastIndex !== -1 && lastIndex === position;
        };
    }

    var StoreApp = angular.module('storeit_app', [
        'angularMoment',
        'ngAria',
        'ngCookies',
        'ngFilesizeFilter',
        'ngFileUpload',
        'ngResource',
        'ngSanitize',
        'ui.bootstrap',
        'ui.router',
    ]);

    StoreApp.directive('autolowercase', function() {
        return {
            require: 'ngModel',
            link: function(scope, element, attrs, modelCtrl) {
                modelCtrl.$parsers.push(function(input) {
                    return input ? input.toLowerCase() : "";
                });

                element.css("text-transform", "lowercase");
            }
        };
    });

    StoreApp.factory('Files', ['$resource', '$rootScope', function ($resource, $rootScope) {
        return $resource($rootScope.restUrl + 'file/:fileId', {}, {
            options: {method: 'OPTIONS', params: {format: 'json'}},
            update: {
                method: 'PUT',
                headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}
            },
        });
    }]).factory('Folders', ['$resource', '$rootScope', function ($resource, $rootScope) {
        return $resource($rootScope.restUrl + 'folder/:folderId', {}, {
            options: {method: 'OPTIONS', params: {format: 'json'}},
            update: {
                method: 'PUT',
                headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}
            },
        });
    }]).factory('Images', ['$resource', '$rootScope', function ($resource, $rootScope) {
        return $resource($rootScope.restUrl + 'image/:imageId', {}, {
            options: {method: 'OPTIONS', params: {format: 'json'}},
            update: {
                method: 'PUT',
                headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}
            },
        });
    }]).factory('Users', ['$resource', '$rootScope', function ($resource, $rootScope) {
        return $resource($rootScope.restUrl + 'user/:userId', {}, {
            options: {method: 'OPTIONS', params: {format: 'json'}},
            update: {
                method: 'PUT',
                headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}
            },
        });
    }]);

    StoreApp.service('credentialsService', function ($rootScope, $http) {
        $rootScope.loggedIn = false;

        return {
            checkLogin: function(result) {
                $http({
                    url: '/auth/login/',
                    method: 'POST'
                }).then(function success(response) {
                    $rootScope.loggedIn = true;
                    result(true);
                }, function error(response) {
                    $rootScope.loggedIn = false;
                    result(false);
                });
            },
            setToken: function(token) {
                if (token) {
                    $rootScope.token = token;
                    localStorage.setItem('token', token);
                    $http.defaults.headers.common['Authorization'] = "Token " + token;

                    $rootScope.loggedIn = true;
                }
            },
            clearAuth: function() {
                delete $rootScope.token;
                localStorage.removeItem('token');
                delete $http.defaults.headers.common['Authorization'];

                delete $rootScope.user;
                localStorage.removeItem('user');

                $rootScope.loggedIn = false;
            },
            setUser: function(user) {
                if (user) {
                    $rootScope.user = user;
                    localStorage.setItem('user', JSON.stringify(user));
                }
            },
            getUser: function() {
                if ($rootScope.user) {
                    return $rootScope.user;
                }

                return null;
            },
        };
    });

    StoreApp.config(['$stateProvider', '$urlRouterProvider', '$httpProvider', function($stateProvider, $urlRouterProvider, $httpProvider) {

        $urlRouterProvider.otherwise('/');

        $stateProvider.state('main', {
            name: 'main',
            url: '/',
            templateUrl: 'partials/main.html',
            controller: 'indexCtrl',
        }).state('login', {
            name: 'login',
            url: '/login',
            templateUrl: 'partials/login.html',
            controller: 'loginCtrl',
        }).state('folder', {
            name: 'folder',
            url: '/folder/{folderId}',
            templateUrl: 'partials/folder.html',
            controller: 'folderCtrl',
        });

        /* XXX: Deal with this later.
        //http://stackoverflow.com/questions/23720003/angularjs-handling-401s-for-entire-app
        $httpProvider.interceptors.push(function($q) {
            return {
                'responseError': function(rejection) {
                    var defer = $q.defer();

                    if (rejection.status === 401) {
                        if (rejection.config.url === '/auth/login/') {
                            // you've gotten a 401 on the auth check.
                        } else {
                            console.dir(rejection);
                            $location.url('/login');
                        }
                    }

                    defer.reject(rejection);
                    return defer.promise;
                }
            };
        });
        */
    }]);

    /* App.run, lets you initialize global stuff. */
    StoreApp.run(function($rootScope, $state, credentialsService) {
        $rootScope.$on('$stateChangeError', console.log.bind(console));

        $rootScope.restUrl = '/api/v1/';

        credentialsService.setToken(localStorage.getItem('token'));
        credentialsService.setUser(JSON.parse(localStorage.getItem('user')));
    });

    StoreApp.controller('indexCtrl', ['$scope', 'credentialsService', function($scope, credentialsService) {
        $scope.currentlyLoggedIn = false;
        $scope.rootDir = 0;

        var loginStatus = function(state) {
            if (state) {
                $scope.currentlyLoggedIn = true;
                var user = credentialsService.getUser();
                $scope.rootDir = user.root;
            }
        };

        credentialsService.checkLogin(loginStatus);
    }]);

    StoreApp.controller('loginCtrl',
                        ['$scope', '$http', '$state', 'credentialsService', function($scope, $http, $state, credentialsService) {

        $scope.tryLogin = function() {
            var u = $scope.username;
            var p = $scope.password;

            function b64EncodeUnicode(str) {
                return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
                    return String.fromCharCode('0x' + p1);
                }));
            }

            $http({
                url: '/auth/login/',
                method: 'POST',
                headers: {
                    'Authorization': 'Basic ' + b64EncodeUnicode(u + ':' + p)
                }
            }).then(function success(response) {
                console.log('Logged in!', new Date());
                console.log('response: ' + JSON.stringify(response, null, 2));

                credentialsService.setUser(response.data.user);
                credentialsService.setToken(response.data.token);

                $state.go('folder', {folderId: response.data.user.root});
            });
        };
    }]);

    StoreApp.controller('folderCtrl',
                        ['$scope', '$state', '$uibModal', '$cookies', 'credentialsService', 'Files', 'Folders', 'Images', 'Upload',
                         function($scope, $state, $uibModal, $cookies, credentialsService, Files, Folders, Images, Upload) {

        $scope.folder_name = '';
        $scope.folder = {};
        $scope.hasParent = false;
        $scope.layout = 'grid';
        $scope.selected = {};
        /* interestingly, I can access this from the UI without it being attachd to the $scope... */
        var user = credentialsService.getUser();

        if ($state.params.folderId) {
            /* good. */
            console.log('folderId: ' + $state.params.folderId);
        } else {
            /* no folder specified; send them to their root. */
            $state.go('folder', {folderId: user.root});
            return;
        }

        var uploadStuff = function(files, type) {
            var url = '/api/v1/' + type;

            if (files && files.length) {
                for (var i = 0; i < files.length; i++) {
                    var f = files[i];

                    Upload.upload({
                        url: url,
                        data: {
                            file: f,
                            name: f.name,
                            folder: $scope.folder.id,
                        }
                    }).then(function(resp) {
                        var item = {
                            name: resp.data.name,
                            id: resp.data.id,
                            updated: resp.data.updated,
                            size: resp.data.size,
                        };

                        if (type === 'image') {
                            item['thumbnail'] = resp.data.thumbnail;
                            $scope.folder.images.push(item);
                        } else {
                            $scope.folder.files.push(item);
                        }
                    }, function(resp) {
                        console.log('Error status: ' + resp.status);
                    });
                }
            }
        };

        function initialize() {
            var savedlayout = $cookies.get('layout');
            console.log('layout cookie value: ' + savedlayout);
            if (savedlayout) {
                /* just in case they've changed the value to be funny. */
                $scope.layout = (savedlayout === 'grid') ? 'grid' : 'table';
            }

            Folders.get({folderId: $state.params.folderId}).$promise
                .then(function(result) {
                    console.log('result: ' + JSON.stringify(result, null, 2));
                    $scope.folder_name = result.name;
                    angular.copy(result, $scope.folder);
                    $scope.folder.condensed = [];

                    if ($scope.folder.folder) {
                        $scope.hasParent = true;
                    }
                });
        }

        initialize();

        $scope.loadNewFolder = function(event) {
            var modal = $uibModal.open({
                animation: true,
                ariaLabelledBy: 'modal-title-top',
                ariaDescribedBy: 'modal-body-top',
                templateUrl: 'partials/createfolder.html',
                size: 'sm',
                controller: 'createFolderCtrl',
                resolve: {
                    parentFolder: function() {
                        return $state.params.folderId;
                    },
                },
            });

            event.target.blur();

            modal.result.then(function success(result) {
                console.log('result: ' + JSON.stringify(result, null, 2));

                $scope.folder.folders.push({
                    name: result.name,
                    id: result.id,
                    updated: result.updated
                });
                // new folder created.
            }, function dismissed(result) {
                console.log('result: ' + result);
                console.log('modal dismissed.');
                // new folder canceled
            });
        };

        $scope.deselectAll = function(event) {
            event.target.blur();
            var items = Object.keys($scope.selected);
            for (var i = 0; i < items.length; i++) {
                delete $scope.selected[items[i]];
            }
            console.log('deselected all');
        };

        $scope.selectGrid = function(event, item, type) {
            event.stopPropagation();
            event.preventDefault();
            event.target.blur();

            // stopping this propogation doesn't work...
            var mashup = type + ',' + item.id;
            var nitem = {
                name: item.name,
                type: type,
                id: item.id,
            };

            console.log('mashup: ' + JSON.stringify(mashup, null, 2));

            if ($scope.selected[mashup]) {
                delete $scope.selected[mashup];
            } else {
                $scope.selected[mashup] = nitem;
            }
        };

        $scope.selectItem = function(event, item) {
            var mashup = item.type + ',' + item.id;
            var nitem = {
                name: item.name,
                type: item.type,
                id: item.id,
            };
            if ($scope.selected[mashup]) {
                delete $scope.selected[mashup];
            } else {
                $scope.selected[mashup] = nitem;
            }
        };

        $scope.filesToTrash = function(event) {
            event.target.blur();

            var toTrash = Object.keys($scope.selected);
            console.log('toTrash: ' + JSON.stringify(toTrash, null, 2));
            var files = [];
            var folders = [];
            var images = [];
            for (var i = 0; i < toTrash.length; i++) {
                var item = $scope.selected[toTrash[i]];
                var update = {
                    owner: user.id,
                    name: item.name,
                    folder: user.trash
                };

                if (item.type === 'file') {
                    Files.update({fileId: item.id}, update).$promise
                        .then(function(result) {
                            console.log('File deleted');

                            for (var j = 0; j < $scope.folder.files.length; j++) {
                                if ($scope.folder.files[j].id === item.id) {
                                    $scope.folder.files.splice(j, 1);
                                    break;
                                }
                            }
                        });
                } else if (item.type === 'folder') {
                    Folders.update({folderId: item.id}, update).$promise
                        .then(function(result) {
                            console.log('Folder deleted');

                             for (var j = 0; j < $scope.folder.folders.length; j++) {
                                if ($scope.folder.folders[j].id === item.id) {
                                    $scope.folder.folders.splice(j, 1);
                                    break;
                                }
                            }
                        });
                } else if (item.type === 'image') {
                    Images.update({imageId: item.id}, update).$promise
                        .then(function(result) {
                            console.log('Image deleted');

                             for (var j = 0; j < $scope.folder.images.length; j++) {
                                if ($scope.folder.images[j].id === item.id) {
                                    $scope.folder.images.splice(j, 1);
                                    break;
                                }
                            }
                        });
                }
            }
        };

        $scope.previewImage = function(event, image) {
            event.target.blur();
            event.stopPropagation();

            var modal = $uibModal.open({
                animation: true,
                ariaLabelledBy: 'modal-title-top',
                ariaDescribedBy: 'modal-body-top',
                templateUrl: 'partials/preview.html',
                size: 'lg',
                controller: 'previewImageCtrl',
                resolve: {
                    data: function() {
                        return image;
                    },
                },
            });

            modal.result.then(function success(result) {
                console.log('result: ' + JSON.stringify(result, null, 2));
            }, function dismissed(result) {
                console.log('result: ' + result);
                console.log('modal dismissed.');
            });
        };

        $scope.loadFolder = function(folderId) {
            $state.go('folder', {folderId: folderId});
        };

        $scope.parent = function() {
            $state.go('folder', {folderId: $scope.folder.folder});
        };

        $scope.uploadImages = function(files) {
            $('#imageupload').blur();
            uploadStuff(files, 'image');
        };

        $scope.uploadFiles = function(files) {
            $('#fileupload').blur();
            uploadStuff(files, 'file');
        };

        $scope.changeLayout = function() {
            /* simple toggle method for now. */
            $scope.layout = ($scope.layout === 'grid') ? 'table' : 'grid';
            $cookies.put('layout', $scope.layout);
        };

        $scope.fileType = function(name) {
            /* I should implement this file icon lookup as a  service or something. */

            // fa-file-video-o
            // fa-file-powerpoint-o
            // fa-file-audio-o
            // fa-file-excel-o
            // fa-file-text-o

            if (name.endsWith('.c') || name.endsWith('.py') || name.endsWith('.pl') || name.endsWith('.h')) {
                return 'fa-file-code-o';
            } else if (name.endsWith('.zip') || name.endsWith('.gz') || name.endsWith('.tgz') || name.endsWith('.bz2')) {
                return 'fa-file-archive-o';
            } else if (name.endsWith('.doc') || name.endsWith('.docx')) {
                return 'fa-file-word-o';
            } else if (name.endsWith('.pdf')) {
                return 'fa-file-pdf-o';
            } else {
                return 'fa-file-o';
            }
        };

        $scope.condensed = function() {
            if ($scope.folder.condensed) {
                var cnt = $scope.folder.folders.length + $scope.folder.images.length + $scope.folder.files.length;
                if ($scope.folder.condensed.length === cnt) {
                    return $scope.folder.condensed;
                }

                $scope.folder.condensed.length = 0;
                for (var i = 0; i < $scope.folder.folders.length; i++) {
                    $scope.folder.condensed.push({
                        name: $scope.folder.folders[i].name,
                        id: $scope.folder.folders[i].id,
                        updated: $scope.folder.folders[i].updated,
                        type: 'folder',
                    });
                }

                for (var i = 0; i < $scope.folder.images.length; i++) {
                    $scope.folder.condensed.push({
                        name: $scope.folder.images[i].name,
                        id: $scope.folder.images[i].id,
                        updated: $scope.folder.images[i].updated,
                        size: $scope.folder.images[i].size,
                        type: 'image',
                    });
                }

                for (var i = 0; i < $scope.folder.files.length; i++) {
                    $scope.folder.condensed.push({
                        name: $scope.folder.files[i].name,
                        id: $scope.folder.files[i].id,
                        updated: $scope.folder.files[i].updated,
                        size: $scope.folder.files[i].size,
                        type: 'file',
                    });
                }

                console.log('condensed size: ' + $scope.folder.condensed.length);
                return $scope.folder.condensed;
            }

            //angular.extend($scope.actions.data, data);
        };
    }]);

    StoreApp.controller('previewImageCtrl', ['$scope', '$uibModalInstance', 'Images', 'data',
                                             function($scope, $uibModalInstance, Images, data) {
        $scope.image = {};

        Images.get({imageId: data.id}).$promise
            .then(function(result) {
                angular.copy(result, $scope.image);
                console.log('result: ' + JSON.stringify(result, null, 2));
            });
    }]);

    StoreApp.controller('createFolderCtrl', ['$scope', '$uibModalInstance', 'Folders', 'parentFolder',
                                             function($scope, $uibModalInstance, Folders, parentFolder) {

        $scope.config = {};

        function initialize() {
            Folders.options().$promise
                .then(function(result) {
                    $scope.config = result.actions.POST;
                    $scope.config.name.pattern = new RegExp($scope.config.name.pattern);
                });
        }

        initialize();

        $scope.createFolder = function() {
            /* Try to create a new folder. */
            var newFolder = {
                folder: parentFolder,
                name: $scope.name,
            };

            Folders.save(newFolder).$promise
                .then(function(result) {
                    $uibModalInstance.close(result);
                });
        };

        $scope.cancel = function() {
            $uibModalInstance.dismiss('cancel');
        };
    }]);

})();


text:
<?php
/**
 *
 */

namespace Mvc5\Route\Router;

interface RouteDispatch
{
    /**
     *
     */
    const DISPATCH = 'Route\Dispatch';

    /**
     * @param callable $callable
     * @param array $args
     * @param callable $callback
     * @return mixed
     */
    function __invoke(callable $callable, array $args = [], callable $callback = null);
}


text:
#import "QuickDialogTableView.h"

@interface QuickDialogDataSource : NSObject<UITableViewDataSource> {

@private
    __unsafe_unretained QuickDialogTableView *_tableView;
}
- (id <UITableViewDataSource, NSObject>)initForTableView:(QuickDialogTableView *)view;

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;

@end


text:
function sendMsg(){
    var id_to1 = document.getElementById("id_to").value;
    var letter1 = document.getElementById("usermsg").value;

    $.get("sendMsg.php",
        {id_from:getcookie("id_user"), id_to:id_to1, tema:"", letter:letter1},
        function(data){
            document.getElementById("usermsg").value = "";
        }
    );
}
function onEnterCtrlPr(){
    //alert(event.keyCode);
    if(event.keyCode==13 && event.ctrlKey)
        sendMsg();
}
function removeMsg(id_msg){
    $.get("removeMsg.php",
        {id:id_msg},
        function(data){
            document.getElementById("listdiv").removeChild(document.getElementById("d"+id_msg));
        }
    );
}

var f='true';//ôëàã=òðó îçíà÷àåò ïîëó÷èòü âñå ñîîáùåíèÿ, êîòîðûå åñòü. ôýëñ - ïîëó÷àòü ñîîáùåíèÿ çà ïðîøåäøèå 5 ñåêóíä
var user_name="";
var user_name_with="";

$(document).ready(function() {
    $.getJSON("getNames.php",
        {id1:getcookie("id_user"), id2: document.getElementById("id_to").value},
        function(data){
            user_name = data[0];
            user_name_with = data[1];

            $("#sendMsgBtn").button();
            getMsgs();
        }
    );
});

function getMsgs(){
    //alert(1);

    $.getJSON("getMessages.php", {all:f, id_user: getcookie("id_user"), id_user_with: document.getElementById("id_to").value},
        function(data){
            //alert(data[0]);
            var kol = data[0];
            var i=1;
            for(i=1;i<=kol;i++){
                var msgdiv = document.createElement("div");
                var fname = document.createElement("div");
                var msg_close_theme = document.createElement("div");
                var theme_close = document.createElement("div");
                var theme_msg = document.createElement("div");
                var close = document.createElement("div");

                msgdiv.className = "msgdiv";
                fname.className = "fname";
                msg_close_theme.className = "msg_close_theme";
                theme_close.className = "theme_close";
                theme_msg.className = "theme_msg";
                close.className = "close";

                if(data[i].id_from == getcookie("id_user")) fname.innerHTML = user_name+":";
                else fname.innerHTML = user_name_with+":";
                if(data[i].tema != "") theme_msg.innerHTML = data[i].tema+"<br>"+data[i].letter;
                else theme_msg.innerHTML = data[i].letter;
                close.innerHTML = 'x';
                msgdiv.id = "d"+data[i].id_msg;
                close.id = "c"+data[i].id_msg;
                close.onclick="removeMsg("+data[i].id_msg+");";

                msgdiv.appendChild(fname);
                msgdiv.appendChild(msg_close_theme);
                msg_close_theme.appendChild(theme_close);
                theme_close.appendChild(theme_msg);
                theme_close.appendChild(close);
                document.getElementById("listdiv").appendChild(msgdiv);
            }
            if(kol){
                var vm=document.getElementById("listdiv");
                vm.scrollTop = vm.scrollHeight;
            }
        });
    f='false';

    setTimeout(getMsgs, 5000);
}


text:
module Tufy
  module Fields
    module Account
      class BuildCurrencyCodeField < BuildField
        expects :raw_data
        promises :transformed_data

        executed do |ctx|
          ctx.transformed_data =
            ctx.transformed_data +
            transform(ctx).upcase
        end

        private

        def self.transform(ctx)
          raw_data = ctx.raw_data

          BuildAccountSegment::Constants::CURRENCY_CODE_TAG +
            FormatStrings::F2TS % raw_data[:currency_code].size + raw_data[:currency_code]
        end
      end
    end
  end
end


text:
package org.keycloak.saml;

import java.security.SecureRandom;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class RandomSecret {
    /**
     *

     * Creates a random {@code byte[]} secret of the specified size.
     *

     *
     * @param size the size of the secret to be created, in bytes.
     *
     * @return a {@code byte[]} containing the generated secret.
     */
    public static byte[] createRandomSecret(final int size) {
        SecureRandom random = new SecureRandom();
        byte[] secret = new byte[size];
        random.nextBytes(secret);
        return secret;
    }
}


text:
import {Files} from '/lib/collections';
import {check} from 'meteor/check';

export function files_search(filterText, limit){
  check(filterText, String);
  check(limit, Number);

  var selector = {$or: [
    {_id: {$regex: filterText}},
    {'metadata.name': {$regex: filterText}}
  ]};
  var options = {sort: {uploadedAt: -1}, limit: limit}

  return Files.find(selector, options);
};

export function files_list(selector, options) {
  check(selector, Match.Optional(Object));
  check(options, Match.Optional(Object));

  if(!selector){
    var selector = {};
  }
  if(!options){
    var options = {sort: {uploadedAt: -1}};
  }
  return Files.find(selector, options);
};


text:
#ifndef PropertyStorage_h
#define PropertyStorage_h

#include "WriteBarrier.h"

namespace JSC {

typedef WriteBarrierBase<Unknown>* PropertyStorage;
typedef const WriteBarrierBase<Unknown>* ConstPropertyStorage;

} // namespace JSC

#endif // PropertyStorage_h