text:
"""Tests for Vizio init."""
import pytest

from homeassistant.components.media_player.const import DOMAIN as MP_DOMAIN
from homeassistant.components.vizio.const import DOMAIN
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.setup import async_setup_component

from .const import MOCK_SPEAKER_CONFIG, MOCK_USER_VALID_TV_CONFIG, UNIQUE_ID

from tests.common import MockConfigEntry

async def test_setup_component(
    hass: HomeAssistantType,
    vizio_connect: pytest.fixture,
    vizio_update: pytest.fixture,
) -> None:
    """Test component setup."""
    assert await async_setup_component(
        hass, DOMAIN, {DOMAIN: MOCK_USER_VALID_TV_CONFIG}
    )
    await hass.async_block_till_done()
    assert len(hass.states.async_entity_ids(MP_DOMAIN)) == 1

async def test_tv_load_and_unload(
    hass: HomeAssistantType,
    vizio_connect: pytest.fixture,
    vizio_update: pytest.fixture,
) -> None:
    """Test loading and unloading TV entry."""
    config_entry = MockConfigEntry(
        domain=DOMAIN, data=MOCK_USER_VALID_TV_CONFIG, unique_id=UNIQUE_ID
    )
    config_entry.add_to_hass(hass)
    assert await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()
    assert len(hass.states.async_entity_ids(MP_DOMAIN)) == 1
    assert DOMAIN in hass.data

    assert await config_entry.async_unload(hass)
    await hass.async_block_till_done()
    assert len(hass.states.async_entity_ids(MP_DOMAIN)) == 0
    assert DOMAIN not in hass.data

async def test_speaker_load_and_unload(
    hass: HomeAssistantType,
    vizio_connect: pytest.fixture,
    vizio_update: pytest.fixture,
) -> None:
    """Test loading and unloading speaker entry."""
    config_entry = MockConfigEntry(
        domain=DOMAIN, data=MOCK_SPEAKER_CONFIG, unique_id=UNIQUE_ID
    )
    config_entry.add_to_hass(hass)
    assert await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()
    assert len(hass.states.async_entity_ids(MP_DOMAIN)) == 1
    assert DOMAIN in hass.data

    assert await config_entry.async_unload(hass)
    await hass.async_block_till_done()
    assert len(hass.states.async_entity_ids(MP_DOMAIN)) == 0
    assert DOMAIN not in hass.data


text: export { default } from '@datahub/shared/components/health/health-score-value';

redpajama_set_name: RedPajamaGithub


text:
<?php

if (!User::loggedIn())
{
	Common::responseCode(403);
	user_error('Forbidden access', ERROR);
}

if (API::action('modify_menu'))
{
	require_once('include/form.class.php');

	if (!API::has('menu'))
		user_error('No menu set', ERROR);

	$menu = API::get('menu');

	$errors = array();
	foreach ($menu as $item)
		if (($error = Form::validateItem($item['name'], array('regex' => '.*', 'min' => 1, 'max' => 25))) !== false)
			$errors[] = array('link_id' => $item['link_id'], 'error' => $error);

	if (!count($errors))
	{
		Db::exec("DELETE FROM module_menu;");
		foreach ($menu as $i => $item)
			Db::exec("INSERT INTO module_menu (link_id, position, level, name, enabled) VALUES (
				'" . Db::escape($item['link_id']) . "',
				'" . Db::escape($i) . "',
				'" . Db::escape($item['level']) . "',
				'" . Db::escape($item['name']) . "',
				'" . Db::escape($item['enabled']) . "'
			);");
	}

	API::set('errors', $errors);
	API::finish();
}
else if (API::action('get_menu'))
{
	$menu = array();
	$non_menu = array();
	$table = Db::query("SELECT *, link.link_id AS link_id FROM link
		LEFT JOIN module_menu ON link.link_id = module_menu.link_id
		ORDER BY module_menu.position ASC;");
	while ($row = $table->fetch())
	{
		if (!isset($row['module_menu_id']))
		{
			$row['level'] = 0;
			$row['name'] = htmlspecialchars($row['title']);
			$row['title'] = htmlspecialchars($row['title']);
			$row['enabled'] = 1;
			$non_menu[] = $row;
		}
		else
		{
			$row['name'] = htmlspecialchars($row['name']);
			$row['title'] = htmlspecialchars($row['title']);
			$menu[] = $row;
		}
	}
	$menu = array_merge($menu, $non_menu); // non_menu items come last

	API::set('menu', $menu);
	API::finish();
}


text:
'use strict';

const url = require('url');
const HttpError = require('@starefossen/http-error');

const ALLOW_CREDENTIALS = process.env.CORS_ALLOW_CREDENTIALS;
const ALLOW_HEADERS = process.env.CORS_ALLOW_HEADERS || 'Content-Type';
const ALLOW_METHODS = process.env.CORS_ALLOW_METHODS || 'GET, OPTIONS';
const ALLOW_ORIGINS = new Set(
    (process.env.CORS_ALLOW_ORIGINS || '')
      .split(',')
      .filter(s => s !== '')
      .map(s => (s === 'null' ? null : s))
);
const DENY_ORIGINS = new Set(
    (process.env.CORS_DENY_ORIGINS || '')
      .split(',')
      .filter(s => s !== '')
      .map(s => (s === 'null' ? null : s))
);
const EXPOSE_HEADERS = process.env.CORS_EXPOSE_HEADERS || '';
const MAX_AGE = parseInt(process.env.CORS_MAX_AGE, 10) || 0;
const REQUIRE_ORIGIN = process.env.CORS_REQUIRE_ORIGIN || false;

module.exports = (opts => {
  const allowCredentials = opts.allowCredentials || ALLOW_CREDENTIALS;
  const allowHeaders = opts.allowHeaders || ALLOW_HEADERS;
  const allowMethods = opts.allowMethods || ALLOW_METHODS;
  const allowOrigins = opts.allowOrigins || ALLOW_ORIGINS;
  const denyOrigins = opts.denyOrigins || DENY_ORIGINS;
  const exposeHeaders = opts.exposeHeaders || EXPOSE_HEADERS;
  const maxAge = opts.maxAge || MAX_AGE;
  const requireOrigin = opts.requireOrigin || REQUIRE_ORIGIN;

  return function coorsMiddleware(req, res, next) {
    const originRaw = req.get('Origin');

    if (originRaw || requireOrigin) {
      const origin = url.parse(originRaw || '');

      if ((allowOrigins.size && !allowOrigins.has(origin.hostname))
      || (denyOrigins.size && denyOrigins.has(origin.hostname))) {
        return next(new HttpError(`Bad Origin "${originRaw}"`, 403));
      }

      res.set('Access-Control-Allow-Headers', allowHeaders);
      res.set('Access-Control-Allow-Max-Age', maxAge);
      res.set('Access-Control-Allow-Methods', allowMethods);
      res.set('Access-Control-Allow-Origin', originRaw || '*');
      res.set('Access-Control-Expose-Headers', exposeHeaders);

      if (typeof allowCredentials !== 'undefined') {
        res.set('Access-Control-Allow-Credentials', allowCredentials);
      }
    }

    if (req.method === 'OPTIONS') {
      return res.status(200).end();
    }

    return next();
  };
});

module.exports.middleware = module.exports({});


text:
"""Manage evaluation tiling on SLURM+OpenMPI HPCs that lack srun.

This module provides support for tiling multiprocessor simulation runs in a
job allocation. As much information as possible is collected from SLURM
environment variables, including the number of nodes and processes per node.
(The terms processses and tasks are used interchangably.)

Static and dynamic scheduling are supported. Under a static scheduling model,
the launching function tiling_run_static should be used, and for dynamic,
tiling_run_dynamic. In static scheduling, tile availability is determined using
the Dakota evaluation number, which must be provided by the user. Dynamic
scheduling makes use of named pipes (FIFOs), which can be created atomically.
The pipes are used only as tokens to represent in-use tiles. Nothing is written
or read from them. This approach eliminates the need for pre-generating a set of
machine files. By default, named pipes are created in $HOME/.DakotaEvalTiling,
but the location (and pipe names) is customizable.

Other module features:
  * Dedicated Dakota node. When enabled, the first node is reserved for running
    Dakota and the user's analysis drivers, which may be desireable when the
    user's simulations are memory intensive.
  * MIMD model. The launcher functions expect a list of commands along with the
    number of processes for each.

Example Usage::

    from dakota.interfacing import parallel, read_parameters_file

    # Dynamic scheduling. On 4 processs, launch "my_sim" with the --verbose
    # option. Pass the "--bind-to none" option ot mpirun by including it
    # before the user's executable and its options.

    my_command = (4, ["--bind-to", "none", "my_sim", "--verbose"])
    parallel.tile_run_dynamic(commands=[my_command])

    # Static scheduling, same command. However, the eval number is needed.
    # Assumption: This script was forked by Dakota as analysis_driver,
    # and therefore read_parameters_file can acquire the names of the params
    # and results files from the command line arguments.

    params, results = read_parameters_file()
    parallel.tile_run_static(commands=[my_command], eval_num=params.eval_num)

    # MIMD model: mpirun -np 16 my_sim1 : -np 16 my_sim2

    my_commands = [ (16, ["my_sim1"]),
                 (16, ["my_sim2"])]
    parallel.tile_run_dynamic(commands=my_commands)

An operational example is located in
``examples/parallelism/Case3-EvaluationTiling/OpenMPI``.
"""
from __future__ import print_function, division
import os
import re
import sys
import subprocess
import time
from . import slurm
from .interfacing import read_parameters_file, UNNAMED

__author__ = 'J. Adam Stephens'
__copyright__ = 'Copyright 2014 Sandia Corporation'
__license__ = 'GNU Lesser General Public License'

# For now, only SLURM is supported, but next we can add PBS and a plugin
# capability so that users can define their own. A plugin will need to define:
# - detection (use me if these criteria are met)
# - extra required arguments to node_placement
# - a method/function that returns a nodelist
#
# Or, not. After all, how many resource managers are in common use?

## Constants
NODE = 0
TILE = 1

# TODO: Insert code to add plugin modules to this list
_user_mangers = []

# Built-in managers
_managers = [slurm]

class MgrEnvError(Exception):
    pass

class ResourceError(Exception):
    pass

def _get_job_info():
    """Determine the resource manager type and query the environment to
    return a tuple containing the number of nodes, MPI tasks per node, and
    job id.

    MgrEnvError is raised if the manager cannot be identified"""

    for plugin in _user_mangers + _managers:
        if plugin.is_me():
            return plugin.get_job_info()
    raise MgrEnvError("Unrecognized resource manager environment.")

def _get_node_list(tile=None, applic_tasks=None,
        tasks_per_node=None, dedicated_master=None):
    """Determine the relative node list

    Keyword Args:
        tile: Tile number, 0-based.
        applic_tasks: Number of MPI processes (tasks) per tile.
        tasks_per_node: Number of MPI tasks per node.
        dedicated_master: Reserve the first NODE or TILE for Dakota (default:
            no reserved node)

    Returns:
        A string containing the relative node list.

    """
    if dedicated_master == NODE:
        start_node = tile * applic_tasks//tasks_per_node + 1
    elif dedicated_master == TILE:
        start_node = (tile + 1) * applic_tasks//tasks_per_node
    else:
        start_node = tile * applic_tasks//tasks_per_node

    end_node = start_node + (applic_tasks-1)//tasks_per_node
    node_string = "+n" + ",+n".join([str(i) for i in range(start_node, end_node+1)])
    return node_string

def _calc_static_tile(eval_num=None, num_tiles=None):
    """For static scheduling, compute the static tile

    Keyword args:
        eval_num: Dakota evaluation number
        num_tiles: Number of tiles in the job
    """

    return (eval_num - 1) % num_tiles

class _TileLock(object):
    """Context manager to acquire and release tiles for dynamic scheduling.

    Currently based on creating FIFOs. Once a named FIFO has been created,
    attempts by other processes to create it again raise OSError with
    errno = 17. The FIFO is created by default in $HOME/.DakotaEvalTiling,
    but a different location can be specified.
    """

    def __init__(self, num_tiles=None, lock_id="", lock_dir=""):
        """_TileLock context manager

        Keyword args:
            num_tiles: Number of tiles in the allocation.
            lock_id: Unique identifer for lock files.
            lock_dir: Directory for lock files
        """
        self._num_tiles = num_tiles
        self._id = lock_id
        self._dir = lock_dir

        try:
            os.mkdir(self._dir)
        except OSError as e:
            if e.errno != 17:
                raise e

    def __enter__(self):
        for tile in range(self._num_tiles):
            try:
                self._name = self._dir + os.sep + self._id + "." + str(tile)
                os.mkfifo(self._name)
                return tile
            except OSError as e:
                if e.errno != 17:  # error code for already-existing file
                    raise e
        raise ResourceError("Run requested, but no available tiles.")

    def __exit__(self, *args):
        os.remove(self._name)

def _mpirun(node_list, user_commands, **kwargs):
    """Use mpirun to launch a command in parallel

    Args:
        node_list (string): Relative node list formatted for use with -host option
        commands (list): Each item is a tuple: (applic_procs, tokenized command
            to be run). len(commands) == 1 for SIMD model.
        **kwargs: optional keyword arguments to pass to suprocess.call. See
            subprocess documentation for available options.

    Returns:
        returncode (int) of mpirun.
    """
    mpi_command = ["mpirun"]
    host_args = ["-host", node_list]
    # construct a composite user_command from the list of provided commands.
    user_command = []
    for command in user_commands:
        user_command += ["-np", str(command[0])] + command[1] + [":"]
    user_command.pop() # remove the final :
    returncode = subprocess.call(mpi_command + host_args + user_command, **kwargs)
    sys.stdout.flush()
    return returncode

def _calc_num_tiles(applic_tasks=None, tasks_per_node=None, num_nodes=None,
        dedicated_master=None):
    """Compute the total number of tiles in the job, adjusting for a dedicated master

    Args:
        applic_tasks: Number of tasks for tile
        num_nodes: Total number of nodes in the allocation
        dedicated_master: Reserve a NODE or TILE for Dakota

    Returns:
        Number of tiles

    Raises:
        ResourseError: When a dedicated master takes up the entire allocation
    """
    if dedicated_master == NODE:
        if num_nodes == 1:
            raise ResourceError("Dedicated master node requested, but job has only one node.")
        num_tiles = (num_nodes-1)*tasks_per_node//applic_tasks
    elif dedicated_master == TILE:
        num_tiles = num_nodes*tasks_per_node//applic_tasks - 1
        if num_tiles == 0:
            raise ResourceError("Dedicated master tile requested, but job has only one tile.")
    else:
        num_tiles = num_nodes*tasks_per_node//applic_tasks
    return num_tiles

def tile_run_static(commands=[], dedicated_master=None, eval_num=None,
        parameters_file=None, **kwargs):
    """Run a command in parallel on an available tile assuming static scheduling

    Keyword args:
        commands (list): Each item is a tuple: (applic_procs, tokenized command
            to be run). len(commands) == 1 for SIMD model.
        dedicated_master (NODE or TILE, optional): Reserve the first NODE or TILE
            for Dakota (default: None).
        eval_num (int): Dakota evaluation number. Either eval_num or
            parameters_file is required. eval_num supercedes parameters_file.
        parameters_file (string): Extract an eval_num from this Dakota
            parameters_file.
        **kwargs: optional keyword arguments to eventually pass to suprocess.call.
            See subprocess documentation for available options.

    Returns:
        returncode (int) from mpirun

    Raises:
        ResourceError: When a dedicated master is requested but there is only
            one node in the job allocation.
    """
    # Determine the evaluation number
    if eval_num:
        pass
    elif parameters_file:
        params, results = read_parameters_file(parameters_file=parameters_file,
                results_file=UNNAMED)
        eval_num = params.eval_num
    else:
        raise
    # Sum up the total number of tasks for the launch from each of the commands
    applic_tasks = 0
    for command in commands:
        applic_tasks += command[0]
    # Get information about the job from the environment.
    num_nodes, tasks_per_node, job_id = _get_job_info()
    # Compute the total number of tiles in the allocation, adjusting for a dedicated master
    num_tiles = _calc_num_tiles(applic_tasks, tasks_per_node, num_nodes, dedicated_master)

    # Calculate the available tile based on the eval_num, calculate its list of nodes,
    # and mpirun the command(s) on these resources.
    tile = _calc_static_tile(eval_num, num_tiles)
    node_list = _get_node_list(tile, applic_tasks, tasks_per_node, dedicated_master)
    returncode = _mpirun(node_list, commands, **kwargs)
    return returncode

def tile_run_dynamic(commands=[], dedicated_master=None, lock_id=None,
        lock_dir=None, **kwargs):
    """Run a command in parallel on an available tile assuming dynamic scheduling

    Keyword args:
        commands (list): Each item is a tuple: (applic_procs, tokenized command
            to be run). len(commands) == 1 for SIMD model.
        dedicated_master (NODE or TILE, optional): Reserve the first NODE or TILE
            for Dakota (default: None).
        lock_id (str, optional): Unique prefix for lockfiles used to manage tiles.
        lock_dir (str, optional): Name of directory where lockfiles will be written.
        **kwargs: optional keyword arguments to eventually pass to suprocess.call.
            See subprocess documentation for available options.

    Returns:
        returncode (int) from mpirun

    Raises:
        ResourceError: When a dedicated master is requested but there is only
            one node in the job allocation, or when no available tiles were
            found.
    """
    # Sum up the total number of tasks for the launch from each of the commands
    applic_tasks = 0
    for command in commands:
        applic_tasks += command[0]
    # Get information about the job from the environment.
    num_nodes, tasks_per_node, job_id = _get_job_info()

    # Compute the total number of tiles in the allocation, adjusting for a dedicated master
    num_tiles = _calc_num_tiles(applic_tasks, tasks_per_node, num_nodes, dedicated_master)

    # Create default lock_id and lock_dir
    if lock_id is None:
        lock_id = job_id
    if lock_dir is None:
        lock_dir = os.environ["HOME"] + os.sep + ".DakotaEvalTiling"
    # Acquire an available tile, calculate its list of nodes, and mpirun the command(s)
    # on these resources.
    with _TileLock(num_tiles, lock_id, lock_dir) as tile:
        node_list = _get_node_list(tile, applic_tasks, tasks_per_node, dedicated_master)
        returncode = _mpirun(node_list, commands, **kwargs)
    sys.stdout.flush()
    return returncode


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using NRC_Code_Designer.src.UI.Class;

namespace NRC_Code_Designer.src.Core.Project
{
    /// <summary>
    /// Give capacity to display.
    /// </summary>
    interface IDisplayAble
    {
        /// <summary>
        /// Class absolute position in the parent grid.
        /// </summary>
        Point Position { get; set; }

        /// <summary>
        /// Event that is trigered when the position changes.
        /// </summary>
        event EventHandler Moved;

        /// <summary>
        /// User control to implement display.
        /// </summary>
        UserControlClass UserControl { get; set; }
    }
}


text:
package lombok.javac.handlers;

import static lombok.core.handlers.HandlerUtil.*;
import static lombok.javac.handlers.JavacHandlerUtil.*;
import static lombok.javac.Javac.*;
import lombok.Cleanup;
import lombok.ConfigurationKeys;
import lombok.core.AST.Kind;
import lombok.core.AnnotationValues;
import lombok.delombok.LombokOptionsFactory;
import lombok.javac.JavacAnnotationHandler;
import lombok.javac.JavacNode;
import lombok.javac.JavacTreeMaker;
import lombok.spi.Provides;

import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCAssign;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCCase;
import com.sun.tools.javac.tree.JCTree.JCCatch;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCIf;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCTypeCast;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;

/**
 * Handles the {@code lombok.Cleanup} annotation for javac.
 */
@Provides
public class HandleCleanup extends JavacAnnotationHandler<Cleanup> {
	@Override public void handle(AnnotationValues<Cleanup> annotation, JCAnnotation ast, JavacNode annotationNode) {
		handleFlagUsage(annotationNode, ConfigurationKeys.CLEANUP_FLAG_USAGE, "@Cleanup");

		if (inNetbeansEditor(annotationNode)) return;

		deleteAnnotationIfNeccessary(annotationNode, Cleanup.class);
		String cleanupName = annotation.getInstance().value();
		if (cleanupName.length() == 0) {
			annotationNode.addError("cleanupName cannot be the empty string.");
			return;
		}

		if (annotationNode.up().getKind() != Kind.LOCAL) {
			annotationNode.addError("@Cleanup is legal only on local variable declarations.");
			return;
		}

		JCVariableDecl decl = (JCVariableDecl)annotationNode.up().get();

		if (decl.init == null) {
			annotationNode.addError("@Cleanup variable declarations need to be initialized.");
			return;
		}

		JavacNode ancestor = annotationNode.up().directUp();
		JCTree blockNode = ancestor.get();

		final List<JCStatement> statements;
		if (blockNode instanceof JCBlock) {
			statements = ((JCBlock)blockNode).stats;
		} else if (blockNode instanceof JCCase) {
			statements = ((JCCase)blockNode).stats;
		} else if (blockNode instanceof JCMethodDecl) {
			statements = ((JCMethodDecl)blockNode).body.stats;
		} else {
			annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block.");
			return;
		}

		boolean seenDeclaration = false;
		ListBuffer<JCStatement> newStatements = new ListBuffer<JCStatement>();
		ListBuffer<JCStatement> tryBlock = new ListBuffer<JCStatement>();
		for (JCStatement statement : statements) {
			if (!seenDeclaration) {
				if (statement == decl) seenDeclaration = true;
				newStatements.append(statement);
			} else {
				tryBlock.append(statement);
			}
		}

		if (!seenDeclaration) {
			annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent.");
			return;
		}
		doAssignmentCheck(annotationNode, tryBlock.toList(), decl.name);

		JavacTreeMaker maker = annotationNode.getTreeMaker();
		JCFieldAccess cleanupMethod = maker.Select(maker.Ident(decl.name), annotationNode.toName(cleanupName));
		List<JCStatement> cleanupCall = List.<JCStatement>of(maker.Exec(
				maker.Apply(List.<JCExpression>nil(), cleanupMethod, List.<JCExpression>nil())));

		JCExpression preventNullAnalysis = preventNullAnalysis(maker, annotationNode, maker.Ident(decl.name));
		JCBinary isNull = maker.Binary(CTC_NOT_EQUAL, preventNullAnalysis, maker.Literal(CTC_BOT, null));

		JCIf ifNotNullCleanup = maker.If(isNull, maker.Block(0, cleanupCall), null);

		JCBlock finalizer = recursiveSetGeneratedBy(maker.Block(0, List.<JCStatement>of(ifNotNullCleanup)), annotationNode);

		newStatements.append(setGeneratedBy(maker.Try(setGeneratedBy(maker.Block(0, tryBlock.toList()), annotationNode), List.<JCCatch>nil(), finalizer), annotationNode));

		if (blockNode instanceof JCBlock) {
			((JCBlock)blockNode).stats = newStatements.toList();
		} else if (blockNode instanceof JCCase) {
			((JCCase)blockNode).stats = newStatements.toList();
		} else if (blockNode instanceof JCMethodDecl) {
			((JCMethodDecl)blockNode).body.stats = newStatements.toList();
		} else throw new AssertionError("Should not get here");

		ancestor.rebuild();
	}

	public JCExpression preventNullAnalysis(JavacTreeMaker maker, JavacNode node, JCExpression expression) {
		if (LombokOptionsFactory.getDelombokOptions(node.getContext()).getFormatPreferences().danceAroundIdeChecks()) {
			JCMethodInvocation singletonList = maker.Apply(List.<JCExpression>nil(), chainDotsString(node, "java.util.Collections.singletonList"), List.of(expression));
			JCMethodInvocation cleanedExpr = maker.Apply(List.<JCExpression>nil(), maker.Select(singletonList, node.toName("get")) , List.<JCExpression>of(maker.Literal(CTC_INT, 0)));
			return cleanedExpr;
		} else {
			return expression;
		}
	}

	public void doAssignmentCheck(JavacNode node, List<JCStatement> statements, Name name) {
		for (JCStatement statement : statements) doAssignmentCheck0(node, statement, name);
	}

	public void doAssignmentCheck0(JavacNode node, JCTree statement, Name name) {
		if (statement instanceof JCAssign) doAssignmentCheck0(node, ((JCAssign)statement).rhs, name);
		if (statement instanceof JCExpressionStatement) doAssignmentCheck0(node,
				((JCExpressionStatement)statement).expr, name);
		if (statement instanceof JCVariableDecl) doAssignmentCheck0(node, ((JCVariableDecl)statement).init, name);
		if (statement instanceof JCTypeCast) doAssignmentCheck0(node, ((JCTypeCast)statement).expr, name);
		if (statement instanceof JCIdent) {
			if (((JCIdent)statement).name.contentEquals(name)) {
				JavacNode problemNode = node.getNodeFor(statement);
				if (problemNode != null) problemNode.addWarning(
				"You're assigning an auto-cleanup variable to something else. This is a bad idea.");
			}
		}
	}
}


text:
module SteakFM
  module FeatureElement
    module Component
      module MetaInfo

        include SteakFM::FeatureElement::Component::MetaInfoExt::Comment
        include SteakFM::FeatureElement::Component::MetaInfoExt::Hash

        STATUS_COMPLETE = %w(done qa accepted)

        def meta_info
          @meta_info ||= fetch_meta_info
        end

        def tags= tags
          @tags = tags
        end

        def complete?
          STATUS_COMPLETE.include?(status)
        end

        def effort
          meta_info[:effort] ? meta_info[:effort].to_f : 0.0
        end

        def status
          meta_info[:status] || 'backlog'
        end

        private

        def fetch_meta_info
          feature_meta_info.merge(this_meta_info)
        end

        def this_meta_info
          comments_meta_info.merge(hash_meta_info)
        end

        def feature_meta_info
          respond_to?(:feature) ? feature.meta_info : {}
        end

        def method_missing(m, *args, &block)
          meta_info[m.to_sym] || super
        end
      end
    end
  end
end


text:
package org.atomify.model.syndication;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;

import org.atomify.model.AtomContractConstraint;
import org.atomify.model.common.AtomCommonAttributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

/**
 * Atom date construct.
 *
 * @author Stephan Schloepke
 */
public class AtomDate extends AtomCommonAttributes {
	/**
	 * <b>Required:</b> the xsd:date content.
	 */
	private final XMLGregorianCalendar value;

	public static AtomDateBuilder newBuilder() {
		return AtomDateBuilder.newInstance();
	}

	/**
	 * Creates a date with the given date content.
	 *
	 * @param date The date content.
	 */
	private AtomDate(final XMLGregorianCalendar date) {
		this.value = AtomContractConstraint.notNull("date", date);
	}

	/**
	 * Returns the date value.
	 *
	 * @return The date value
	 */
	public XMLGregorianCalendar getValue() {
		return this.value;
	}

	/**
	 * Returns the date value as a {@link Date} instance.
	 *
	 * @return The date value as date instance.
	 */
	public Date toDate() {
		return this.value.toGregorianCalendar().getTime();
	}

	public static AtomDate valueOf(String dateValue) {
		try {
			return new AtomDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(AtomContractConstraint.notNull("dateValue", dateValue)));
		} catch (DatatypeConfigurationException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * Creates a date construct with the given java date.
	 *
	 * @param date The java date.
	 */
	public static AtomDate valueOf(final Date date) {
		try {
			GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
			cal.setTime(date);
			return new AtomDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));
		} catch (DatatypeConfigurationException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result + ((this.value == null) ? 0 : this.value.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!super.equals(obj)) {
			return false;
		}
		if (!(obj instanceof AtomDate)) {
			return false;
		}
		AtomDate other = (AtomDate) obj;
		if (this.value == null) {
			if (other.value != null) {
				return false;
			}
		} else if (!this.value.equals(other.value)) {
			return false;
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return new StringBuilder().append("AtomDate [value=").append(this.value).append(", ").append(super.toString()).append("]").toString();
	}

	// FIXME: Write a much better way of serialization

	@SuppressWarnings("all")
	public void serialize(QName name, ContentHandler handler, AttributesImpl attributes) throws SAXException {
		attributes = initCommonAttributes(handler, attributes);
		String namespace = name.getNamespaceURI();
		String local = name.getLocalPart();
		String qName = (name.getPrefix() != null && name.getPrefix().length() > 0 ? name.getPrefix() + ":" : "") + local;
		handler.startElement(namespace, local, qName, attributes);
		char[] data = this.value.toXMLFormat().toCharArray();
		handler.characters(data, 0, data.length);
		handler.endElement(namespace, local, qName);
	}

}


text:
namespace extensions {

class ExtensionPrefs;

class ExtensionPrefsObserver {
 public:
  // Called when the reasons for an extension being disabled have changed.
  virtual void OnExtensionDisableReasonsChanged(const std::string& extension_id,
                                                int disabled_reasons) {}

  // Called when an extension is registered with ExtensionPrefs.
  virtual void OnExtensionRegistered(const std::string& extension_id,
                                     const base::Time& install_time,
                                     bool is_enabled) {}

  // Called when an extension's prefs have been loaded.
  virtual void OnExtensionPrefsLoaded(const std::string& extension_id,
                                      const ExtensionPrefs* prefs) {}

  // Called when an extension's prefs are deleted.
  virtual void OnExtensionPrefsDeleted(const std::string& extension_id) {}

  // Called when an extension's enabled state pref is changed.
  virtual void OnExtensionStateChanged(const std::string& extension_id,
                                       bool state) {}
};

}  // namespace extensions

#endif  // EXTENSIONS_BROWSER_EXTENSION_PREFS_OBSERVER_H_


text:
require 'active_support/all'
require 'savon'

module Pelokit
  module Transport
    module Soap
      extend ActiveSupport::Concern

      class Error < ArgumentError; end

      LOG = true
      attr_accessor :success
      attr_accessor :message

      private
      def options
        options = { }
        options.merge! Pelokit::api_args  # Merge in the base settings first.
        options.merge! self.to_hash       # Provide an override opportunity.

        # Camelize the hash keys for the request.
        options = options.inject({}) do |opts, (k,v)|
          opts[k.to_s.camelize] = v.to_s
          opts
        end
        options
      end

      def request(method, type)
        if self.respond_to?(:valid?) && !self.valid?
          raise Error.new self.errors.messages
        end
        # Invoke the method; include a request wrapper.
        response = client.call(method, message: { type => options })
        hash     = response.hash.try(:[], :envelope)
                                .try(:[], :body)
                                .try(:[], "#{method}_response".to_sym)
                                .try(:[], "#{method}_result".to_sym)
                                .with_indifferent_access
        self.success = hash[:success]
        self.message = hash[:message]
        hash
      rescue Savon::SOAPFault, Savon::HTTPError => error
        raise error
      end

      def client
        @client ||= Savon.client(pretty_print_xml: LOG) do
          wsdl(Pelokit.wsdl)
        end
      end

    end
  end
end


text:
Notification.requestPermission().then((permission) => {
  if (permission === 'granted') {
    console.log('Notification permission granted.');
    // TODO(developer): Retrieve a registration token for use with FCM.
    // ...
  } else {
    console.log('Unable to get permission to notify.');
  }
});
// [END messaging_request_permission_modular]


text:
package sbahjsic.interpreter.parser.syntaxtree;

import sbahjsic.interpreter.compiler.Instruction;
import sbahjsic.interpreter.parser.Node;
import sbahjsic.interpreter.parser.NodeType;

public final class EndWhileNode extends Node {

	public final static EndWhileNode INSTANCE = new EndWhileNode();

	private EndWhileNode() {}

	@Override
	public NodeType type() {
		return NodeType.ENDWHILE_NODE;
	}

	@Override
	public Instruction[] toInstructions() {
		return new Instruction[] { Instruction.endWhileStatement() };
	}

	@Override
	public String toString() {
		return "ENDWHILE";
	}

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

	@Override
	public int hashCode() {
		return -7878;
	}

}


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

<TITLE>
I-Index
</TITLE>

<META NAME="date" CONTENT="2010-02-03">

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

      Overview
      Package
      Class
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A C D E F G H I L M N P R S T W

I

InfoBox - Class in edu.jhu.nlp.wikipedia
A class abstracting Wiki infobox
InfoBoxTest - Class in <Unnamed>

InfoBoxTest() -
Constructor for class InfoBoxTest

isDisambiguationPage() -
Method in class edu.jhu.nlp.wikipedia.WikiPage

isDisambiguationPage() -
Method in class edu.jhu.nlp.wikipedia.WikiTextParser

isRedirect() -
Method in class edu.jhu.nlp.wikipedia.WikiPage

isRedirect() -
Method in class edu.jhu.nlp.wikipedia.WikiTextParser

isSpecialPage() -
Method in class edu.jhu.nlp.wikipedia.WikiPage

isStub() -
Method in class edu.jhu.nlp.wikipedia.WikiPage

isStub() -
Method in class edu.jhu.nlp.wikipedia.WikiTextParser

IteratorHandler - Class in edu.jhu.nlp.wikipedia

IteratorHandler(WikiXMLParser) -
Constructor for class edu.jhu.nlp.wikipedia.IteratorHandler

      Overview
      Package
      Class
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A C D E F G H I L M N P R S T W


text: This is a Microsoft add in you can add to your excel 2010 and it will mass query NPI numbers


text:
define(['exports', './busyconfiguration', './busy'], function (exports, _busyconfiguration, _busy) {
  'use strict';

  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  exports.Busy = undefined;
  exports.configure = configure;
  exports.Busy = _busy.Busy;
  function configure(aurelia, callback) {

    var config = new _busyconfiguration.BusyConfiguration();

    if (typeof callback === 'function') {
      callback(config);
    }
  }
});


text:
desk.com has released v2 of their REST API a few months ago and provides a lot more functionality. You should read up on the current progress of the [API](http://dev.desk.com/API/changelog). This library wraps all of it into an easy to use ruby module. We'll try to keep up with the changes of the API but things might still break unexpectedly.

## Example
This example shows you how to create a new client and establish a connection to the API. It shows the four request methods supported by the desk.com API (`GET`, `POST`, `PATCH` and `DELETE`).

```apex
// Basic Auth
DeskClient client = new DeskClient(new Map<String, String>{
  'username' => 'thomas@example.com',
  'password' => 'somepassword',
  'subdomain' => 'devel'
});

// OAuth
DeskClient client = new DeskClient(new Map<String, String>{
  'token' => 'TOKEN',
  'tokenSecret' => 'TOKEN_SECRET',
  'consumerKey' => 'CONSUMER_KEY',
  'consumerSecret' => 'CONSUMER_SECRET'
  'subdomain' => 'devel'
});

HTTPResponse rsp;

rsp = client.get('/api/v2/topics');
rsp = client.post('/api/v2/topics', '{"name":"My new Topic"}');
rsp = client.patch('/api/v2/topics/1', '{"name":"My updated Topic"}');
rsp = client.destroy('/api/v2/topics/1');
```

## Working with Resources and Collections

The API supports RESTful resources and so does this wrapper. These resources are automatically discovered, meaning you can navigate around without having to worry about anything. We also support two finder methods `findByPath()` and `find()`.

### Initial Collection

Using the client we created earlier you can easily request the initial collection you want to work with.

```apex
DeskResource res = client.getResource('cases');
```

### Finders

The method `find()` can be called on all `DeskResource` instances and will return a lazy loaded instance of the resource. _Gotcha:_ It will rebuild the base path based on the resource/collection it is called on. So if you call it on the cases collection `client.getResource('cases').find(1)` the path will look like this: `/api/v2/cases/:id`. The second method `findByPath()` can be called on all `DeskResource` and `DeskClient` instances.

| Method                                                                           | Path                        |
| -------------------------------------------------------------------------------- | --------------------------- |
| `client.getResource('cases').find(1)`                                            | `/api/v2/cases/1`           |
| `client.getResource('cases').search('Test').find(1)`                             | `/api/v2/cases/1`           |
| `client.getResource('cases').getEntries().get(0).getResource('replies').find(1)` | `/api/v2/cases/1/replies/1` |

### Pagination

As mentioned above you can also navigate between resources and pages of collections. However you'll have to request the `entries` before you can loop through all the records on the page.

```apex
DeskResource cases = client.getResource('cases');
for (DeskResource myCase : cases.getEntries()) {
  // do something with the case
}

// now move on to the next page
DeskResource nextPage = cases.getResource('next');
for (DeskResource myNextPageCase : nextPage.getEntries()) {
  // do something with the case
}

// go back to the previous page
DeskResource previousPage = nextPage.getResource('previous');

// or go to the last page
DeskResource lastPage = previousPage.getResource('last');

// or go to the first page
DeskResource firstPage = lastPage.getResource('first');
```

### Links

Pagination is pretty obvious but the cool part about pagination or rather resources is the auto-linking. As soon as the resource has a link defined, it'll be navigatable:

```apex
// get the customer of the first case of the first page
DeskResource customer = client.getResource('cases').getEntries().get(0).getResource('customer');
```

### Lazy loading

Collections and resources in general are lazily loaded, meaning if you request the cases `client.getResource('cases')` no actual request will be set off until you actually request data. Only necessary requests are sent which will keep the request count low - [desk.com rate limit](http://dev.desk.com/API/using-the-api/#rate-limits).

```apex
DeskResource cases = client.getResource('cases').page(10).perPage(50);
for (DeskResource myCase : cases.getEntries()) {
  // in this method chain `getEntries' is the first method that acutally sends a request
}

// however if you request the current page numer and the resource is not loaded
// it'll send a request
System.assertEquals(1, client.getResource('cases').page());
```

### Side loading

APIv2 has a lot of great new features but the one I'm most excited about is side loading or embedding resources. You basically request one resource and tell the API to embed sub resources, eg. you need cases but also want to have the `assigned_user` - instead of requesting all cases and the `assigned_user` for each of those cases (30 cases = 31 API requests) you can now embed `assigned_user` into your cases list view (1 API request).

Of course we had to bring this awesomeness into the API wrapper as soon as possible, so here you go:

```apex
// fetch cases with their respective customers and cases
DeskResource cases = client.getResource('cases').embed('customer,message');
DeskResource customer = cases.getEntries().get(0).getResource('customer');
// fetch a sepcific case with it's assigned user and group
DeskResource myCase = client.getResource('cases').find(3011, 'assigned_user,assigned_group');
DeskResource assignedUser = myCase.getResource('assigned_user');
```

### Create, Update and Delete

Of course we support creating, updating and deleting resources but not all resources can be deleted or updated or created, if that's the case for the resource you're trying to update, it'll throw a `DeskApi::Error::MethodNotAllowed` error. For ease of use and because we wanted to build as less business logic into the wrapper as possible, all of the methods are defined on each `DeskApi::Resource` and will be sent to desk.com. However the API might respond with an error if you do things that aren't supported.

```apex
// let's create an article
DeskResource newArticle = client.getResource('articles').create(new Map<String, Object>{
  'subject' => 'Some Subject',
  'body' => 'Some Body',
  '_links' => new Map<String, Object>{
    'topic' => new Map<String, Object>{
      'href' => '/api/v2/topics/1'
    }
  }
});

// updating the article
DeskResource updatedArticle = newArticle.update(new Map<String, Object>{
  'subject' => 'Updated Subject'
});

// deleting the article
if (updatedArticle.destroy()) {
  // article has been deleted
}
```

### Getter & Setter

As you have seen in prior examples we use the `getResource' getter to get links and embedded resources. For fields you can use `get' and `set' however you'll have to typecast the return value.

```apex
DeskResource customer = client.getResource('customers').find(1);

System.debug(customer.get('first_name'));
System.debug(customer.get('last_name'));
System.debug(customer.get('title'));

Map<String, String> customFields = (Map<String, String>)customer.get('custom_fields');

// for updates you can either use the setter or a map

customer.set('first_name', 'John');
customer.set('last_name', 'Doe');

DeskResource updatedCustomer = customer.update(new Map<String, Object>{
  'title' => 'Master of the Universe'
});
```

## License

(The MIT License)

Copyright (c) 2013 Thomas Stachl <thomas@desk.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
using System.Web.Mvc;
using Newtonsoft.Json;
using Sitecore.Mvc.Presentation;

namespace Sitecore.Feature.OpenDataMap.Controller
{
    public class OpenDataMapController : System.Web.Mvc.Controller
    {
        // GET: OpenDataMap
        public ActionResult OpenDataMap()
        {
            //var map = new Diversus.Feature.OpenDataMap.Models.Map(new Diversus.Hackathon2016.Foundation.OpenDataAgent.Models.Repository(RenderingContext.Current.Rendering.Item));
            //var items = JsonConvert.SerializeObject(map);
            var items = "";
            return this.View("OpenDataMapWidget", items);
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Peziza ancilis Pers., 1822

### Remarks
null


text:
<?php

namespace MatryoshkaModelWrapperMongoTest\Hydrator\Strategy;

use Matryoshka\Model\Wrapper\Mongo\Hydrator\Strategy\MongoDateStrategy;
use Matryoshka\Model\Exception\InvalidArgumentException;

/**
 * Class MongoDateStrategyTest
 */
class MongoDateStrategyTest extends \PHPUnit_Framework_TestCase
{
    public function testCtor()
    {
        //Test default format
        $strategy = new MongoDateStrategy();
        $this->assertSame(\DateTime::ISO8601, $strategy->getFormat());

        $strategy = new MongoDateStrategy(\DateTime::ATOM);
        $this->assertSame(\DateTime::ATOM, $strategy->getFormat());
    }

    public function testExtract()
    {
        $strategy = new MongoDateStrategy();
        $now = time();

        $result = $strategy->extract(\DateTime::createFromFormat('U', $now));
        $this->assertEquals(new \MongoDate($now), $result);

        $this->assertNull($strategy->extract(null));

        $this->setExpectedException(InvalidArgumentException::class);
        $result = $strategy->extract('test invalid value');
    }

    public function testHydrate()
    {
        $format   = \DateTime::ISO8601;
        $strategy = new MongoDateStrategy();
        $now = time();

        $result = $strategy->hydrate(new \MongoDate($now));
        $this->assertEquals(new \DateTime(date($format, $now)), $result);

        $this->assertNull($strategy->hydrate(null));

        $this->setExpectedException(InvalidArgumentException::class);
        $result = $strategy->hydrate('test invalid value');
    }

    public function testGetSetFormat()
    {
        $strategy = new MongoDateStrategy();
        $format   = \DateTime::W3C;

        $this->assertSame($strategy, $strategy->setFormat($format));

        $this->assertEquals($format, $strategy->getFormat());
    }
}


text:
function HSolidElement(data,parentContainer,globalData,comp, placeholder){
    this._parent.constructor.call(this,data,parentContainer,globalData,comp, placeholder);
}
createElement(HBaseElement, HSolidElement);

HSolidElement.prototype.createElements = function(){
    var parent = document.createElement('div');
    styleDiv(parent);
    var cont = document.createElementNS(svgNS,'svg');
    cont.setAttribute('width',this.data.sw);
    cont.setAttribute('height',this.data.sh);
    parent.appendChild(cont);
    this.layerElement = parent;
    //this.appendNodeToParent(parent);
    this.baseElement = parent;
    this.innerElem = parent;
    if(this.data.ln){
        this.innerElem.setAttribute('id',this.data.ln);
    }
    if(this.data.bm !== 0){
        this.setBlendMode();
    }
    var rect = document.createElementNS(svgNS,'rect');
    rect.setAttribute('width',this.data.sw);
    rect.setAttribute('height',this.data.sh);
    rect.setAttribute('fill',this.data.sc);
    cont.appendChild(rect);
    if(this.data.hasMask){
        this.maskedElement = rect;
    }
    this.checkParenting();
};

HSolidElement.prototype.hide = IImageElement.prototype.hide;
HSolidElement.prototype.renderFrame = IImageElement.prototype.renderFrame;
HSolidElement.prototype.destroy = IImageElement.prototype.destroy;


text:
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import url from 'url';
import * as encoding from '../libs/query_encoding';
import { Panel, PanelBody } from '../libs/ui/panel';
import { svgIcon } from '../libs/svg-icons';
import { tintColor, isLight } from './datacolors';
import { DataTable } from './datatable';
import { MatrixBadges, filterFacet } from './objectutils';
import { SearchControls, FacetList } from './search';
import QueryString from '../libs/query_string';
import * as globals from './globals';
import { drawTree, drawThumbnail, nodeKeyName } from '../libs/ui/node_graph';
import getSeriesData from './series_search.js';

const colorLegend = ['T cell', 'B cell', 'NK cell'];
const keepRows = ['T cell', 'B cell', 'NK cell', 'myeloid cell', 'mononuclear cell'];
const colorMap = {
    'T cell': '#2c9659',
    'CD4+ T cell': '#2c9659',
    'CD8+ T cell': '#2c9659',
    'B cell': '#2794bf',
    'NK cell': '#986ea4',
    monocyte: '#36586d',
    'myeloid cell': '#36586d',
    'mononuclear cell': '#36586d',
};

// Keep this constant in sync with $donor-cell-width in _matrix.scss.
const DONOR_CELL_WIDTH = 30;
const COL_CATEGORY = 'assay_title';
const COL_SUBCATEGORY = 'target.label';
const SUB_CATEGORY_SHORT_SIZE = 10000000;

const fullHeight = 1600;
const margin = { top: 80, right: 15, bottom: 140, left: 30 };

// Not all facets are displayed, these are the ones we want to keep
const keepFacets = [
    'replicates.library.biosample.disease_term_name',
];

const matrixAssaySortOrder = [
    'scRNA-seq',
    'Bru-seq',
    'total RNA-seq',
    'polyA plus RNA-seq',
    'polyA minus RNA-seq',
    'small RNA-seq',
    'microRNA-seq',
    'snATAC-seq',
    'ATAC-seq',
    'DNase-seq',
    'TF ChIP-seq',
    'Histone ChIP-seq',
    'Hi-C',
    'ChIA-PET',
    'WGBS',
];

const excludedAssays = [
    'Control ChIP-seq',
    'Control eCLIP',
    'DNAme array',
    'RNA microarray',
    'RRBS',
    'sc-RNAseq',
    'CAGE',
    'Repli-ChIP',
    'genotyping array',
    'DNAme array',
];

const collapsedAssays = [];

const nodeField = 'biosample_ontology.term_name';

// Find element or parent of element with matching tag or class name
const findElement = (el, name, key) => {
    while (el.parentElement) {
        el = el.parentElement;
        if ([...el[key]].includes(name)) {
            return true;
        }
    }
    return null;
};

const generateColMap = (context) => {
    const colCategory = context.matrix.x.group_by[0];
    const colSubcategory = context.matrix.x.group_by[1];
    const colMap = {};
    let targetAssays = [];
    let colIndex = 0;

    // Sort column categories according to a specified order, with any items not specified sorted
    // at the end in order of occurrence.
    const colCategoryBuckets = context.matrix.x[colCategory].buckets;
    const sortedColCategoryBuckets = _(colCategoryBuckets).sortBy((colCategoryBucket) => {
        const sortIndex = matrixAssaySortOrder.indexOf(colCategoryBucket.key);
        return sortIndex >= 0 ? sortIndex : colCategoryBuckets.length;
    });

    // Combining Histone and Mint columns into one column category
    const newBuckets = [];
    let histoneBuckets = [];
    let mintBuckets = [];
    let histoneKeys = [];
    let mintKeys = [];
    let histoneIdx = null;
    let mintIdx = null;
    colCategoryBuckets.forEach((sortBucket) => {
        if (sortBucket.key === 'Histone ChIP-seq') {
            histoneBuckets = sortBucket['target.label'].buckets;
            histoneKeys = histoneBuckets.map((b) => b.key);
        } else if (sortBucket.key === 'Mint-ChIP-seq') {
            mintBuckets = sortBucket['target.label'].buckets;
            mintKeys = mintBuckets.map((b) => b.key);
        }
    });
    sortedColCategoryBuckets.forEach((sortBucket, sortIdx) => {
        if (sortBucket.key === 'Histone ChIP-seq') {
            histoneIdx = sortIdx;
        }
        if (sortBucket.key === 'Mint-ChIP-seq') {
            mintIdx = sortIdx;
        }
    });

    if (!histoneIdx) {
        histoneIdx = mintIdx;
    }

    if (histoneIdx !== null) {
        const comboKeys = _.uniq([...histoneKeys, ...mintKeys]);
        let newIdx = 0;
        comboKeys.forEach((column) => {
            const mintKey = mintBuckets.filter((b) => b.key === column);
            const histoneKey = histoneBuckets.filter((b) => b.key === column);
            newBuckets[newIdx] =
                {
                    key: column,
                    doc_count: (mintKey.length > 0 ? mintKey[0].doc_count : 0) + (histoneKey.length > 0 ? histoneKey[0].doc_count : 0),
                };
            newIdx += 1;
        });

        sortedColCategoryBuckets[histoneIdx]['target.label'].buckets = newBuckets;
    }

    const colCol = sortedColCategoryBuckets.map((col) => col.key);
    // We want to exclude Mint experiments if there is Histone data and we're not already excluding it
    if ((colCol.indexOf('Histone ChIP-seq') > -1) && (excludedAssays.indexOf('Mint-ChIP-seq') === -1)) {
        excludedAssays.push('Mint-ChIP-seq');
    // We do not want to exclude Mint experiments if there is no Histone data
    } else if (colCol.indexOf('Histone ChIP-seq') === -1) {
        const mints = excludedAssays.indexOf('Mint-ChIP-seq');
        excludedAssays.splice(mints, 1);
    }

    // Generate the column map based on the sorted category buckets.
    sortedColCategoryBuckets.forEach((colCategoryBucket) => {
        if (!excludedAssays.includes(colCategoryBucket.key)) {
            const colSubcategoryBuckets = colCategoryBucket[colSubcategory].buckets;

            // Add the mapping of "assay" key string to column index.
            if (!(colSubcategoryBuckets.length > 0 && colSubcategoryBuckets[0].key !== 'no_target')) {
                // Assay doesn't have subcategories, so render the assay label into the column
                // header.
                colMap[colCategoryBucket.key] = {
                    col: colIndex,
                    category: colCategoryBucket.key,
                };
                targetAssays.push(null);
                colIndex += 1;
            } else {
                // Assay has subcategories, so generate information so we know how many columns the
                // assay's label should take up and which column it starts at so we can render the
                // assay label across several target columns.
                targetAssays.push({ col: colIndex, category: colCategoryBucket.key, subcategoryCount: colSubcategoryBuckets.length });
            }

            // Add the mapping of "<assay>|<target>"" key string to column index for those assays that
            // have targets and don't collapse their targets.
            if (!collapsedAssays.includes(colCategoryBucket.key)) {
                colSubcategoryBuckets.forEach((colSubcategoryBucket) => {
                    if (colSubcategoryBucket.key !== 'no_target') {
                        colMap[`${colCategoryBucket.key}|${colSubcategoryBucket.key}`] = {
                            col: colIndex,
                            category: colCategoryBucket.key,
                            subcategory: colSubcategoryBucket.key,
                        };
                        colIndex += 1;
                    }
                });
            }
        }
    });

    // If targetAssays only contains nulls, then just empty it so we can skip the targetAssay row.
    if (!targetAssays.some((assay) => assay !== null)) {
        targetAssays = [];
    }

    return { colMap, targetAssays };
};

const convertExperimentToDataTable = (context) => {
    const colCategory = context.matrix.x.group_by[0];
    const colSubcategory = context.matrix.x.group_by[1];
    const rowCategory = context.matrix.y.group_by[0];
    const rowSubcategory = context.matrix.y.group_by[1];
    const rowKeys = [];
    const headerRows = [];

    const colQuery = new QueryString(context.search_base.replace('&config=immune', ''));
    const query = colQuery.clone();

    colQuery.deleteKeyValue('biosample_ontology.cell_slims')
        .deleteKeyValue('biosample_ontology.classification')
        .deleteKeyValue('biosample_ontology.system_slims');
    const colSearchBase = `${colQuery.format()}`;

    query.deleteKeyValue('biosample_ontology.cell_slims')
        .deleteKeyValue('biosample_ontology.classification')
        .deleteKeyValue('biosample_ontology.system_slims')
        .deleteKeyValue(nodeField);
    const searchBase = `${query.format()}`;

    // Generate the mapping of column categories and subcategories.
    const { colMap, targetAssays } = generateColMap(context);
    const colCount = Object.keys(colMap).length;

    const colCat = Object.keys(colMap).map((key) => key.split('|')[0]);

    // Convert column map to an array of column map values sorted by column number for displaying
    // in the matrix header.
    const sortedCols = Object.keys(colMap).map((assayColKey) => colMap[assayColKey]).sort((colInfoA, colInfoB) => colInfoA.col - colInfoB.col);

    // Generate the matrix header row labels for the assays with targets. Need a max-width inline
    // style so that wide labels don't make the target columns expand.
    if (targetAssays.length > 0) {
        const targetAssayHeader = [{ css: 'matrix__col-category-targetassay-corner' }].concat(targetAssays.map(((targetAssayElement) => {
            if (targetAssayElement) {
                // Add cell with assay title and span for the number of targets it has.
                const categoryName = (targetAssayElement.category === 'Histone ChIP-seq') || (targetAssayElement.category === 'Mint-ChIP-seq') ? 'Histone and Mint ChIP-seq' : targetAssayElement.category;
                const categoryQuery = `${colCategory}=${encoding.encodedURIComponent(targetAssayElement.category)}`;
                let extraQuery = '';
                if (targetAssayElement.category === 'Histone ChIP-seq') {
                    extraQuery = `&${COL_CATEGORY}=${encoding.encodedURIComponent('Mint-ChIP-seq')}`;
                }
                if (targetAssayElement.category === 'Mint-ChIP-seq') {
                    extraQuery = `&${COL_CATEGORY}=${encoding.encodedURIComponent('Histone ChIP-seq')}`;
                }
                return {
                    header: <a href={`${colSearchBase}${extraQuery}&${categoryQuery}`}>{categoryName}
{categoryName}
,
                    colSpan: targetAssayElement.subcategoryCount,
                    css: 'matrix__col-category-targetassay',
                    style: { maxWidth: DONOR_CELL_WIDTH * targetAssayElement.subcategoryCount },
                };
            }

            // Render empty cell for assays with no targets.
            return { header: null };
        })));

        // Add the key and row content for the target assay labels.
        rowKeys.push('target-assay-categories');
        headerRows.push({ rowContent: targetAssayHeader, css: 'matrix__col-category-targetassay-header' });
    }

    // Generate array of names of assays that have targets and don't collapse their targets, for
    // rendering those columns as disabled.
    // const colCategoriesWithSubcategories = Object.keys(colMap).filter((colCategoryName) => colMap[colCategoryName].hasSubcategories && !collapsedAssays.includes(colCategoryName));

    // Generate the hierarchical top-row sideways header label cells. The first cell is null unless
    // it contains a link to clear the currently selected classification. At the end of this loop,
    // rendering `{header}` shows this header row. The `sortedCols` array gets mutated in this loop,
    // acquiring a `query` property in each of its objects that gets used later to generate cell
    // hrefs.
    let prevCategory;
    let prevSubcategory;
    const dividerCss = [];
    const header = [
        {
            header: null,
        },
    ].concat(sortedCols.map((colInfo) => {
        // Determine the CSS classes for the dividers in the columns of assay and target labels.
        const dividerCssAccumulator = [];
        if ((colInfo.category !== prevCategory) && (prevSubcategory || colInfo.subcategory)) {
            // Need divider on left edge of start of assays with targets.
            dividerCssAccumulator.push('divider--start');
        }
        if (colInfo.subcategory && colInfo.col === sortedCols.length - 1) {
            // Need divider on right edge if subcategory column is at right edge of matrix.
            dividerCssAccumulator.push('divider--end');
        }
        dividerCss[colInfo.col] = dividerCssAccumulator.join(' ');
        prevCategory = colInfo.category;
        prevSubcategory = colInfo.subcategory;

        const categoryQuery = `${COL_CATEGORY}=${encoding.encodedURIComponent(colInfo.category)}`;
        let extraQuery = '';
        if (colInfo.category === 'Histone ChIP-seq') {
            extraQuery = `&${COL_CATEGORY}=${encoding.encodedURIComponent('Mint-ChIP-seq')}`;
        }
        if (colInfo.category === 'Mint-ChIP-seq') {
            extraQuery = `&${COL_CATEGORY}=${encoding.encodedURIComponent('Histone ChIP-seq')}`;
        }
        const categoryName = colInfo.category === 'Histone ChIP-seq' ? 'Histone and Mint ChIP-seq' : colInfo.category;
        if (!colInfo.subcategory) {
            // Add the category column links.
            colInfo.query = categoryQuery;
            return {
                header: <a href={`${colSearchBase}&${categoryQuery}${extraQuery}`}>{categoryName}
{context.matrix.x.label}
,
                css: dividerCss[colInfo.col],
            };
        }

        // Add the subcategory column links.
        const subCategoryQuery = `${COL_SUBCATEGORY}=${encoding.encodedURIComponent(colInfo.subcategory)}`;
        colInfo.query = `${categoryQuery}&${subCategoryQuery}`;
        return {
            header: <a className="sub" href={`${colSearchBase}&${categoryQuery}${extraQuery}&${subCategoryQuery}`}>{colInfo.subcategory}
target for {categoryName} {context.matrix.x.label}
,
            css: `category-base${dividerCss[colInfo.col] ? ` ${dividerCss[colInfo.col]}` : ''}`,
        };
    }));

    // Generate the main table content including the data hierarchy, where the upper level of the
    // hierarchy gets referred to here as "rowCategory" and the lower-level gets referred to as
    // "rowSubcategory." Both these types of rows get collected into `dataTable` which gets passed
    // to <DataTable>. Also generate an array of React keys to use with <DataMatrix> by using an
    // array index that's independent of the reduce-loop index because of spacer/expander row
    // insertion.
    let matrixRow = 1;
    rowKeys.push('column-categories');
    headerRows.push({ rowContent: header, css: 'matrix__col-category-header' });
    const rowKeysInitialLength = rowKeys.length;
    const rowCategoryBuckets = context.matrix.y[rowCategory].buckets.filter((bucket) => keepRows.includes(bucket.key));
    const rowCategoryColors = rowCategoryBuckets.map((rowCategoryDatum) => colorMap[rowCategoryDatum.key]);
    const dataTable = rowCategoryBuckets.reduce((accumulatingTable, rowCategoryBucket, rowCategoryIndex) => {
        // Each loop iteration generates all the rows of the row subcategories (biosample term names)
        // under it.
        const rowSubcategoryBuckets = rowCategoryBucket[rowSubcategory].buckets;
        const rowCategoryQuery = `${rowCategory}=${encoding.encodedURIComponent(rowCategoryBucket.key)}`;
        rowKeys[rowCategoryIndex + rowKeysInitialLength] = rowCategoryBucket.key;

        const rowCategoryColor = rowCategoryColors[rowCategoryIndex];
        const rowSubcategoryColor = tintColor(rowCategoryColor, 0.5);
        const rowCategoryTextColor = isLight(rowCategoryColor) ? '#000' : '#fff';
        const expandableRowCategory = rowSubcategoryBuckets.length > SUB_CATEGORY_SHORT_SIZE;

        // Update the row key mechanism.
        rowKeys[matrixRow] = rowCategoryBucket.key;
        matrixRow += 1;

        // No rows are hidden
        const visibleRowSubcategoryBuckets = rowSubcategoryBuckets;

        const cells = Array(colCount);
        const subcategoryRows = visibleRowSubcategoryBuckets.map((rowSubcategoryBucket, rowSubcategoryIndex) => {
            const subCategoryQuery = `${rowSubcategory}=${encoding.encodedURIComponent(rowSubcategoryBucket.key)}`;
            let extraQuery = '';

            cells.fill(null);

            // Each biosample term name's row reuses the same `cells` array of cell components.
            // Until we fill it with actual data below, we initialize the row with empty cells,
            // with a CSS class to render a divider for columns of assays with targets.
            dividerCss.forEach((divider, colIndex) => {
                cells[colIndex] = { css: divider };
            });
            rowSubcategoryBucket[colCategory].buckets.forEach((rowSubcategoryColCategoryBucket) => {
                const tempExcludedAssays = [...excludedAssays];
                if (tempExcludedAssays.indexOf('Mint-ChIP-seq') > -1) {
                    const mints = excludedAssays.indexOf('Mint-ChIP-seq');
                    tempExcludedAssays.splice(mints, 1);
                }
                // Skip any excluded assay columns.
                if (!tempExcludedAssays.includes(rowSubcategoryColCategoryBucket.key)) {
                    const rowSubcategoryColSubcategoryBuckets = rowSubcategoryColCategoryBucket[colSubcategory].buckets;
                    if (rowSubcategoryColSubcategoryBuckets.length > 0 && !collapsedAssays.includes(rowSubcategoryColCategoryBucket.key)) {
                        // The assay has targets and doesn't collapse them, so put relevant colored
                        // cells in the subcategory columns. Each cell has no visible content, but
                        // has hidden text for screen readers.
                        rowSubcategoryColSubcategoryBuckets.forEach((cellData) => {
                            let colMapKey = `${rowSubcategoryColCategoryBucket.key}|${cellData.key}`;
                            if (rowSubcategoryColCategoryBucket.key === 'Mint-ChIP-seq' && colCat.indexOf('Mint-ChIP-seq') === -1) {
                                colMapKey = `Histone ChIP-seq|${cellData.key}`;
                            }

                            if (colMapKey.indexOf('Histone ChIP-seq') > -1) {
                                extraQuery = `&${COL_CATEGORY}=${encoding.encodedURIComponent('Mint-ChIP-seq')}`;
                            }
                            if (colMapKey.indexOf('Mint-ChIP-seq') > -1) {
                                extraQuery = `&${COL_CATEGORY}=${encoding.encodedURIComponent('Histone ChIP-seq')}`;
                            }
                            const colIndex = colMap[colMapKey].col;
                            cells[colIndex] = {
                                content: (
                                    <>
                                        <a href={`${searchBase}&${rowCategoryQuery}&${subCategoryQuery}${extraQuery}&${colMap[colMapKey].query}`}>
                                            Search {rowCategoryBucket.key}, {rowSubcategoryBucket.key} for {rowSubcategoryColCategoryBucket.key}, {cellData.key}

                                    </>
                                ),
                                css: dividerCss[colIndex],
                                style: { backgroundColor: rowSubcategoryColor },
                            };
                        });
                    } else if (colMap[rowSubcategoryColCategoryBucket.key]) {
                        const colIndex = colMap[rowSubcategoryColCategoryBucket.key].col;
                        cells[colIndex] = {
                            content: (
                                <>
                                    <a href={`${searchBase}&${rowCategoryQuery}&${subCategoryQuery}&${colMap[rowSubcategoryColCategoryBucket.key].query}`}>
                                        Search {rowCategoryBucket.key}, {rowSubcategoryBucket.key} for {rowSubcategoryColCategoryBucket.key}

                                </>
                            ),
                            css: dividerCss[colIndex],
                            style: { backgroundColor: rowSubcategoryColor },
                        };
                    }
                }
            });

            // Add a single term-name row's data and left header to the matrix.
            rowKeys[rowCategoryIndex + 1] = `${rowCategoryBucket.key}|${rowSubcategoryBucket.key}`;
            return {
                rowContent: [
                    {
                        header: (
                            <a href={`${searchBase}&${rowCategoryQuery}&${subCategoryQuery}`}>

{rowSubcategoryBucket.key}
{context.matrix.y.label}

                        ),
                    },
                ].concat(cells),
                css: `matrix__row-data${rowSubcategoryIndex === 0 ? ' matrix__row-data--first' : ''} ${nodeKeyName(rowSubcategoryBucket.key)}`,
            };
        });

        // Continue adding rendered rows to the matrix.
        rowKeys[matrixRow] = `${rowCategoryBucket.key}-spacer`;
        matrixRow += 1;
        const categoryId = globals.sanitizeId(rowCategoryBucket.key);
        return accumulatingTable.concat(
            [
                {
                    rowContent: [{
                        header: (

                                <a href={`${context['@id']}&${rowCategoryQuery}`} style={{ color: rowCategoryTextColor }}>{rowCategoryBucket.key}

                        ),
                    },
                    { content:
, colSpan: 0 }],
                    css: 'matrix__row-category',
                },
            ],
            subcategoryRows,
            [
                {
                    rowContent: [
                        {
                            content: null,
                        },
                        {
                            content: null,
                            colSpan: 0,
                        },
                    ],
                    css: `matrix__row-spacer${expandableRowCategory ? ' matrix__row-spacer--expander' : ''}`,
                },
            ],
        );
    }, headerRows);
    return { dataTable, rowKeys };
};

const MatrixHeader = ({ context }) => (

{context.title}

                    <MatrixBadges context={context} />

                        Epigenomic profiling of human immune cells at different cellular fates and states, including activation, stimulation, and disease (MS)

                <SearchControls context={context} visualizeDisabledTitle="" hideBrowserSelector showDownloadButton={false} dropConfig />

);

MatrixHeader.propTypes = {
    /** Matrix search result object */
    context: PropTypes.object.isRequired,
};

MatrixHeader.contextTypes = {
    navigate: PropTypes.func,
    fetch: PropTypes.func,
};

class MatrixPresentation extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            /** True if matrix scrolled all the way to the right; used for flashing arrow */
            scrolledRight: false,
        };
        this.handleOnScroll = this.handleOnScroll.bind(this);
        this.handleScrollIndicator = this.handleScrollIndicator.bind(this);
        this.getClearClassificationsLink = this.getClearClassificationsLink.bind(this);
    }

    componentDidMount() {
        this.handleScrollIndicator(this.scrollElement);
    }

    /* eslint-disable react/no-did-update-set-state */
    componentDidUpdate(prevProps) {
        // If URI changed, we need close any expanded rowCategories in case the URI change results
        // in a huge increase in displayed data. Also update the scroll indicator if needed.
        if (prevProps.context['@id'] !== this.props.context['@id']) {
            this.handleScrollIndicator(this.scrollElement);
        }
    }
    /* eslint-enable react/no-did-update-set-state */

    /**
     * Called when the user scrolls the matrix horizontally within its div to handle scroll
     * indicators.
     * @param {object} e React synthetic scroll event
     */
    handleOnScroll(e) {
        this.handleScrollIndicator(e.target);
    }

    /**
     * Show a scroll indicator depending on current scrolled position.
     * @param {object} element DOM element to apply shading to
     */
    handleScrollIndicator(element) {
        // Have to use a "roughly equal to" test because of an MS Edge bug mentioned here:
        // https://stackoverflow.com/questions/30900154/workaround-for-issue-with-ie-scrollwidth
        const scrollDiff = Math.abs((element.scrollWidth - element.scrollLeft) - element.clientWidth);
        if (scrollDiff < 2 && !this.state.scrolledRight) {
            // Right edge of matrix scrolled into view.
            this.setState({ scrolledRight: true });
        } else if (scrollDiff >= 2 && this.state.scrolledRight) {
            // Right edge of matrix scrolled out of view.
            this.setState({ scrolledRight: false });
        }
    }

    getClearClassificationsLink() {
        if (this.hasRequestedClassifications) {
            const parsedUrl = url.parse(this.props.context['@id']);
            const query = new QueryString(parsedUrl.query);
            query.deleteKeyValue('biosample_ontology.classification');
            parsedUrl.search = null;
            parsedUrl.query = null;
            const baseMatrixUrl = url.format(parsedUrl);
            return `${baseMatrixUrl}?${query.format()}`;
        }
        return null;
    }

    render() {
        const { context } = this.props;
        const { scrolledRight } = this.state;
        const clearClassifications = this.getClearClassificationsLink();

        // Convert encode matrix data to a DataTable object.
        const { dataTable, rowKeys } = convertExperimentToDataTable(context, clearClassifications);
        const matrixConfig = {
            rows: dataTable,
            rowKeys,
            tableCss: 'matrix',
        };

        return (

                <div className={`matrix__label matrix__label--horz${!scrolledRight ? ' horz-scroll' : ''}`}>
                    {context.matrix.x.label}
                    {svgIcon('largeArrow')}

{svgIcon('largeArrow')}{context.matrix.y.label}

 { this.scrollElement = element; }}>
                            <DataTable tableData={matrixConfig} />

        );
    }
}

MatrixPresentation.propTypes = {
    /** Matrix search result object */
    context: PropTypes.object.isRequired,
    presentationKey: PropTypes.number.isRequired,
};

class MatrixGraph extends React.Component {
    constructor(props) {
        super(props);

        const immuneCells = require('./node_graph_data/immune_cells.json');
        this.immuneCells = immuneCells[0];

        this.state = {
            windowWidth: 0,
            selectedNodes: props.selectedNodes,
            isThumbnailExpanded: (this.props.context.search_base.indexOf('openModal') > -1),
        };

        this.updateWindowWidth = this.updateWindowWidth.bind(this);
        this.setSelectedNodes = this.setSelectedNodes.bind(this);
        this.toggleThumbnail = this.toggleThumbnail.bind(this);
    }

    componentDidMount() {
        this.updateWindowWidth();
        window.addEventListener('resize', this.updateWindowWidth);

        this.setState({ isThumbnailExpanded: (this.context.location_href.indexOf('openModal') > -1) }, () => {
            require.ensure(['d3v7'], (require) => {
                // eslint-disable-next-line import/no-unresolved
                this.d3 = require('d3v7');

                const chartWidth = this.state.windowWidth;
                const nodesRenamed = this.state.selectedNodes.map((node) => nodeKeyName(node));
                if (!this.state.isThumbnailExpanded) {
                    drawThumbnail(this.d3, '.vertical-node-graph-thumbnail', this.immuneCells, chartWidth, fullHeight, margin, nodesRenamed, this.setSelectedNodes, this.props.availableNodes, 'immune');
                } else {
                    drawTree(this.d3, '.vertical-node-graph-full-width', this.immuneCells, chartWidth, fullHeight, margin, nodesRenamed, this.setSelectedNodes, this.props.availableNodes, 'immune');
                }
            });
        });
    }

    setSelectedNodes(newNode, activeBool) {
        this.setState((prevState) => {
            let tempNodes = [];
            if (document.getElementsByClassName('active-cell').length > 0) {
                tempNodes = prevState.selectedNodes;
            }
            if (activeBool) {
                return { selectedNodes: tempNodes.filter((s) => s !== newNode) };
            }
            return { selectedNodes: [...tempNodes, newNode] };
        }, () => {
            this.props.setFilters(this.state.selectedNodes);
        });
    }

    updateWindowWidth() {
        const windowWidth = document.getElementById('navbar').offsetWidth > 1500 ? document.getElementById('navbar').offsetWidth : 1500;
        this.setState({
            windowWidth,
        }, () => {
            require.ensure(['d3v7'], (require) => {
                // eslint-disable-next-line import/no-unresolved
                this.d3 = require('d3v7');

                const chartWidth = this.state.windowWidth;
                const nodesRenamed = this.state.selectedNodes.map((node) => nodeKeyName(node));
                if (!this.state.isThumbnailExpanded) {
                    drawThumbnail(this.d3, '.vertical-node-graph-thumbnail', this.immuneCells, chartWidth, fullHeight, margin, nodesRenamed, this.setSelectedNodes, this.props.availableNodes, 'immune');
                } else {
                    drawTree(this.d3, '.vertical-node-graph-full-width', this.immuneCells, chartWidth, fullHeight, margin, nodesRenamed, this.setSelectedNodes, this.props.availableNodes, 'immune');
                }
            });
        });
    }

    toggleThumbnail() {
        this.setState((prevState) => ({ isThumbnailExpanded: !prevState.isThumbnailExpanded }), () => {
            require.ensure(['d3v7'], (require) => {
                // eslint-disable-next-line import/no-unresolved
                this.d3 = require('d3v7');
                const chartWidth = this.state.windowWidth;
                const nodesRenamed = this.state.selectedNodes.map((node) => nodeKeyName(node));
                if (!this.state.isThumbnailExpanded) {
                    drawThumbnail(this.d3, '.vertical-node-graph-thumbnail', this.immuneCells, chartWidth, fullHeight, margin, nodesRenamed, this.setSelectedNodes, this.props.availableNodes, 'immune');
                } else {
                    drawTree(this.d3, '.vertical-node-graph-full-width', this.immuneCells, chartWidth, fullHeight, margin, nodesRenamed, this.setSelectedNodes, this.props.availableNodes, 'immune');
                }
            });
        });
    }

    render() {
        return (

                <button
                    type="button"
                    className="body-image-thumbnail"
                    onClick={() => this.toggleThumbnail()}
                >

Filter results by cell lineage

                    {svgIcon('expandArrows')}

                </button>
                {this.state.isThumbnailExpanded ?

                        <div className={`body-map-container-pop-up immune-cells-graph ${this.state.isThumbnailExpanded ? 'expanded' : 'collapsed'}`}>
                            <button type="button" className="collapse-body-map" onClick={() => this.toggleThumbnail()}>
                                {svgIcon('collapseArrows')}

Hide cell lineage

                            </button>

                                <button type="button" className="btn btn-sm btn-info" id="showall-popup">Show all</button>
                                <button type="button" className="btn btn-sm btn-info" id="hideall-popup">Hide all</button>

                                {colorLegend.map((legendEntry) => (
                                    <div className={`layer-element ${legendEntry.replace(/\s/g, '').toLowerCase()}`} key={legendEntry}>
                                        <div className={`layer-bubble ${legendEntry.replace(/\s/g, '').toLowerCase()}`} />

{legendEntry}

                                ))}

Other

ϟ Activated

☆ Stimulated

                : null}

                    <button type="button" className="btn btn-sm btn-info">Show all</button>
                    <button type="button" className="btn btn-sm btn-info">Hide all</button>

        );
    }
}

MatrixGraph.propTypes = {
    context: PropTypes.object.isRequired,
    setFilters: PropTypes.func.isRequired,
    availableNodes: PropTypes.array.isRequired,
    selectedNodes: PropTypes.array.isRequired,
};

MatrixGraph.contextTypes = {
    navigate: PropTypes.func,
    fetch: PropTypes.func,
    location_href: PropTypes.string.isRequired, // Should be context.location_href from parent
};

/**
 * View component for the experiment matrix page.
 */
class ImmuneCells extends React.Component {
    constructor(props) {
        super(props);

        this.baseUrl = '?type=Experiment&replicates.library.biosample.donor.organism.scientific_name=Homo+sapiens&biosample_ontology.cell_slims=hematopoietic+cell&biosample_ontology.classification=primary+cell&biosample_ontology.cell_slims=myeloid+cell&control_type!=*&status=released&biosample_ontology.system_slims=immune+system&biosample_ontology.system_slims=circulatory+system&config=immune';

        const originalNodes = this.props.context.facets.filter((f) => f.field === 'biosample_ontology.term_name')[0].terms.map((term) => term.key);

        this.originalNodes = originalNodes;

        const query = new QueryString(this.baseUrl);
        query.deleteKeyValue(nodeField);
        originalNodes.forEach((node) => {
            query.addKeyValue(nodeField, node);
        });
        this.defaultUrl = `${query.format()}`;

        const availableNodes = this.props.context.facets.filter((f) => f.field === 'biosample_ontology.term_name')[0].terms.map((term) => term.key);

        this.state = {
            pageContext: this.props.context,
            nodes: originalNodes,
            hiddenUrl: this.defaultUrl,
            availableNodes,
            facetsOpen: true,
        };

        this.getRowCategories = this.getRowCategories.bind(this);
        this.getRowSubCategories = this.getRowSubCategories.bind(this);
        this.setNodeFilters = this.setNodeFilters.bind(this);
        this.redirectClick = this.redirectClick.bind(this);
        this.refreshContext = this.refreshContext.bind(this);
        this.toggleFacets = this.toggleFacets.bind(this);
    }

    componentDidMount() {
        this.refreshContext();
    }

    getRowCategories() {
        const rowCategory = this.context.matrix.y.group_by[0];
        const rowCategoryData = this.context.matrix.y[rowCategory].buckets;
        const rowCategoryColors = globals.biosampleTypeColors.colorList(rowCategoryData.map((rowCategoryDatum) => rowCategoryDatum.key));
        const rowCategoryNames = {};
        rowCategoryData.forEach((datum) => {
            rowCategoryNames[datum.key] = datum.key;
        });
        return {
            rowCategoryData,
            rowCategoryColors,
            rowCategoryNames,
        };
    }

    getRowSubCategories(rowCategoryBucket) {
        const subCategoryName = this.context.matrix.y.group_by[1];
        return rowCategoryBucket[subCategoryName].buckets;
    }

    setNodeFilters(newNodes) {
        this.setState((prevState) => {
            const query = new QueryString(prevState.hiddenUrl);
            query.deleteKeyValue(nodeField);
            newNodes.forEach((node) => {
                const nodeIdx = this.state.availableNodes.indexOf(node);
                if (nodeIdx !== -1) {
                    query.addKeyValue(nodeField, node);
                }
            });
            return {
                hiddenUrl: `${query.format()}`,
            };
        });
    }

    refreshContext() {
        getSeriesData(this.state.hiddenUrl, this.context.fetch).then((response) => {
            const termIds = response.filters.filter((f) => f.field === 'biosample_ontology.term_name');
            const selectedNodes = termIds.length > 0 ? termIds.map((term) => term.term) : [];

            let availableNodes = [];
            if (response.facets.filter((f) => f.field === 'biosample_ontology.term_name')[0].terms.length > this.originalNodes.length) {
                availableNodes = selectedNodes;
            } else {
                availableNodes = response.facets.filter((f) => f.field === 'biosample_ontology.term_name')[0].terms.map((term) => term.key);
            }
            const availableSelectedNodes = selectedNodes.filter((node) => (availableNodes.indexOf(node) > -1));

            this.setState({
                pageContext: response,
                nodes: availableSelectedNodes,
                availableNodes,
            });
        });
    }

    toggleFacets() {
        this.setState((prevState) => ({ facetsOpen: !prevState.facetsOpen }));
    }

    redirectClick(e) {
        const clickedLink = e.target.closest('a');
        const isCollapseButton = findElement(e.target, 'collapse-body-map', 'classList');
        e.preventDefault();
        if (clickedLink && clickedLink.href && ((clickedLink.href.indexOf('/search/') > -1) || (clickedLink.href.indexOf('/report/') > -1))) {
            this.context.navigate(clickedLink.href.replace('&config=immune', ''));
        } else if (clickedLink && clickedLink.href) {
            getSeriesData(clickedLink.href, this.context.fetch).then((response) => {
                const termIds = response.filters.filter((f) => f.field === 'biosample_ontology.term_name');
                const selectedNodes = termIds.length > 0 ? termIds.map((term) => term.term) : [];
                this.setState({
                    pageContext: response,
                    nodes: selectedNodes,
                    hiddenUrl: clickedLink.href,
                }, () => {
                    this.refreshContext();
                });
            });
        } else if (isCollapseButton) {
            this.refreshContext();
        } else if (e.target.id === 'hideall-popup') {
            this.setNodeFilters([]);
            const cells = document.querySelectorAll('.js-cell');
            cells.forEach((cell) => cell.classList.remove('active-cell'));
        } else if (e.target.id === 'showall-popup') {
            this.setNodeFilters(this.state.availableNodes);
            const cells = document.querySelectorAll('.js-cell');
            cells.forEach((cell) => cell.classList.add('active-cell'));
        } else if (e.target.innerHTML === 'Hide all') {
            this.setState((prevState) => {
                const query = new QueryString(prevState.hiddenUrl);
                query.deleteKeyValue(nodeField);
                return {
                    hiddenUrl: `${query.format()}`,
                    nodes: [],
                };
            }, () => {
                this.refreshContext();
            });
        } else if (e.target.innerHTML === 'Show all') {
            this.setState((prevState) => {
                const query = new QueryString(prevState.hiddenUrl);
                query.deleteKeyValue(nodeField);
                prevState.availableNodes.forEach((node) => {
                    query.addKeyValue(nodeField, node);
                });
                return {
                    hiddenUrl: `${query.format()}`,
                    nodes: prevState.availableNodes,
                };
            }, () => {
                this.refreshContext();
            });
        }
    }

    render() {
        const { context } = this.props;
        const itemClass = globals.itemClass(context, 'view-item');
        const newFacets = filterFacet(this.state.pageContext.facets.filter((facet) => facet.field !== 'assembly'), keepFacets);
        const emptyNodeSelections = this.state.nodes.length < 1;

        if (context.total > 0) {
            return (
                <Panel addClasses={itemClass} onClick={(e) => this.redirectClick(e)}>
                    <PanelBody>
                        <MatrixHeader context={this.state.pageContext} />

                            <div className={`file-gallery-facets ${this.state.facetsOpen ? 'expanded' : 'collapsed'}`}>
                                <button type="button" className="show-hide-facets" onClick={this.toggleFacets}>
                                    <i className={`${this.state.facetsOpen ? 'icon icon-chevron-left' : 'icon icon-chevron-right'}`} />
                                </button>
                                {(this.state.facetsOpen && newFacets.length > 0) ?
                                    <FacetList
                                        context={this.state.pageContext}
                                        facets={newFacets}
                                        filters={this.state.pageContext.filters}
                                        searchBase={this.state.hiddenUrl ? `${this.state.hiddenUrl}&` : `${this.state.hiddenUrl}?`}
                                        hideDocType
                                        additionalFacet={
                                            <MatrixGraph context={this.state.pageContext} setFilters={this.setNodeFilters} availableNodes={this.state.availableNodes} key={this.state.nodes.length} selectedNodes={this.state.nodes} />
                                        }
                                        key={this.state.availableNodes.length}
                                    />
                                : (this.state.facetsOpen) ?
                                    <MatrixGraph context={this.state.pageContext} setFilters={this.setNodeFilters} availableNodes={this.state.availableNodes} key={this.state.nodes.length} selectedNodes={this.state.nodes} />
                                : null}

                            {!emptyNodeSelections ?

                                    <MatrixPresentation context={this.state.pageContext} presentationKey={this.state.pageContext.total} />

                            :

                                    Select a node from the graph to see results.

                            }

                    </PanelBody>
                </Panel>
            );
        }
        return
No results found
;
    }
}

ImmuneCells.propTypes = {
    context: PropTypes.object.isRequired,
};

ImmuneCells.contextTypes = {
    biosampleTypeColors: PropTypes.object, // DataColor instance for experiment project
    fetch: PropTypes.func,
    location_href: PropTypes.string,
    navigate: PropTypes.func,
};

globals.contentViews.register(ImmuneCells, 'ImmuneCells');


text:
using ParkingSpace.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ParkingSpace.Web.Controllers {
  public class TicketsController : Controller {
    private App app = new App();

    protected override void Dispose(bool disposing) {
      if (disposing) {
        app.Dispose();
      }
      base.Dispose(disposing);
    }

    // GET: Tickets
    public ActionResult Index() {
      var tickets = app.ParkingTickets.ActiveTickets;
      return View(tickets);
    }
  }
}


text:
/* The side navigation menu */
.sidenav {
    height: 100%; /* 100% Full-height */
    width: 0; /* 0 width - change this with JavaScript */
    position: fixed; /* Stay in place */
    z-index: 1; /* Stay on top */
    top: 0;
    left: 0;
    background-color: #111; /* Black*/
    overflow-x: hidden; /* Disable horizontal scroll */
    padding-top: 60px; /* Place content 60px from the top */
    transition: 0.5s; /* 0.5 second transition effect to slide in the sidenav */
}

/* The navigation menu links */
.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
    transition: 0.3s
}

/* When you mouse over the navigation links, change their color */
.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}

/* Position and style the close button (top right corner) */
.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

/* Style page content - use this if you want to push the page content to the right when you open the side navigation */
#main {
    transition: margin-left .5s;
    padding: 0px;
}

/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
    .sidenav {padding-top: 15px;}
    .sidenav a {font-size: 18px;}
}

/*Search Page*/
#searchWord {
	color: #827717
}

.section {
	padding-top: 0px;
}

.card {
	border-radius: 15px;
}

/*The original stuff*/
.icon-block {
  padding: 0 0px;
}
.icon-block .material-icons {
	font-size: inherit;
}


text:
To configure the sample with a Google OAuth client, first visit
https://console.developers.google.com/apis/credentials?project=_ and create a
new project. Then tap "Create credentials" and select "OAuth client ID".

Follow the instructions to configure the consent screen (just the Product Name
is needed).

Then follow the instructions for your platform:

## iOS

Select "iOS" as the application type, and enter your Bundle ID.

Then, setup the example with your configuration:

| Configuration | Description      |
|---------------|------------------|
| Issuer        | `https://accounts.google.com`|
| Client ID     | The value named `Client ID` in the console, has the format `IDENTIFIER.apps.googleusercontent.com`.|
| Client Secret | Google's iOS clients do not have a secret.|
| Redirect URI  | The value for `iOS URL scheme` wil be the scheme of your redirect URI. This is the Client ID in reverse domain name notation, e.g. `	com.googleusercontent.apps.IDENTIFIER`. To construct the redirect URI, add your own path component. E.g. `	com.googleusercontent.apps.IDENTIFIER:/oauth2redirect/google`. Note that there is only a single slash (`/`) after the scheme.|

## macOS

Select "Other" as the application type.

Then, setup the example with your configuration:

| Configuration | Description      |
|---------------|------------------|
| Issuer        | `https://accounts.google.com`|
| Client ID     | The value named `Client ID` in the console, has the format `IDENTIFIER.apps.googleusercontent.com`.|
| Client Secret | The value named `Client secret` in the console.|
| Redirect URI  | For macOS, you can use either the loopback interface (where AppAuth will generate the redirect URI for you), or a custom scheme. To create a custom scheme redirect URI, reverse the client id to get the URI scheme, for example `	com.googleusercontent.apps.IDENTIFIER` and, add your own path component. E.g. `com.googleusercontent.apps.IDENTIFIER:/oauth2redirect/google`. Note that there is only a single slash (`/`) after the scheme.|

## tvOS

Select "TVs and Limited Input devices" as the application type.

Then, setup the example with your configuration.

| Configuration             | Description      |
|---------------------------|------------------|
| Issuer                    | `https://accounts.google.com` |
| Client ID                 | The value named `Client ID` in the console, has the format `IDENTIFIER.apps.googleusercontent.com`.|
| Client Secret             | The value named `Client secret` in the console.|


text:
from __future__ import unicode_literals, division, absolute_import

import logging
from builtins import *  # noqa pylint: disable=unused-import, redefined-builtin
from datetime import datetime, timedelta

from sqlalchemy import Column, String, Unicode, Boolean, Integer, DateTime

from flexget import db_schema
from flexget.event import event
from flexget.utils.database import entry_synonym

log = logging.getLogger('pending_approval')
Base = db_schema.versioned_base('pending_approval', 0)

class PendingEntry(Base):
    __tablename__ = 'pending_entries'

    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    task_name = Column(Unicode)
    title = Column(Unicode)
    url = Column(String)
    approved = Column(Boolean)
    _json = Column('json', Unicode)
    entry = entry_synonym('_json')
    added = Column(DateTime, default=datetime.now)

    def __init__(self, task_name, entry):
        self.task_name = task_name
        self.title = entry['title']
        self.url = entry['url']
        self.approved = False
        self.entry = entry

    def __repr__(self):
        return '<PendingEntry(task_name={},title={},url={},approved={})>'.format(
            self.task_name, self.title, self.url, self.approved
        )

    def to_dict(self):
        return {
            'id': self.id,
            'task_name': self.task_name,
            'title': self.title,
            'url': self.url,
            'approved': self.approved,
            'added': self.added,
        }

@event('manager.db_cleanup')
def db_cleanup(manager, session):
    # Clean unapproved entries older than 1 year
    deleted = (
        session.query(PendingEntry)
        .filter(PendingEntry.added < datetime.now() - timedelta(days=365))
        .delete()
    )
    if deleted:
        log.info('Purged %i pending entries older than 1 year', deleted)

def list_pending_entries(
    session, task_name=None, approved=None, start=None, stop=None, sort_by='added', descending=True
):
    log.debug('querying pending entries')
    query = session.query(PendingEntry)
    if task_name:
        query = query.filter(PendingEntry.task_name == task_name)
    if approved is not None:
        query = query.filter(PendingEntry.approved == approved)
    if descending:
        query = query.order_by(getattr(PendingEntry, sort_by).desc())
    else:
        query = query.order_by(getattr(PendingEntry, sort_by))
    return query.slice(start, stop).all()

def get_entry_by_id(session, entry_id):
    return session.query(PendingEntry).filter(PendingEntry.id == entry_id).one()