text:
import type { flags } from '@oclif/command';
import type { Output as ParserOutput } from '@oclif/parser';

import Command from '../../command';
import * as cf from '../../utils/common-flags';
import * as ca from '../../utils/common-args';
import { getBalenaSdk, stripIndent } from '../../utils/lazy';
import {
	applicationIdInfo,
	appToFleetCmdMsg,
	warnify,
} from '../../utils/messages';

interface FlagsDef {
	help: void;
}

interface ArgsDef {
	fleet: string;
}

export class FleetRestartCmd extends Command {
	public static description = stripIndent`
		Restart a fleet.

		Restart all devices belonging to a fleet.

		${applicationIdInfo.split('\n').join('\n\t\t')}
	`;

	public static examples = [
		'$ balena fleet restart MyFleet',
		'$ balena fleet restart myorg/myfleet',
	];

	public static args = [ca.fleetRequired];

	public static usage = 'fleet restart <fleet>';

	public static flags: flags.Input<FlagsDef> = {
		help: cf.help,
	};

	public static authenticated = true;

	public async run(parserOutput?: ParserOutput<FlagsDef, ArgsDef>) {
		const { args: params } =
			parserOutput || this.parse<FlagsDef, ArgsDef>(FleetRestartCmd);

		const { getApplication } = await import('../../utils/sdk');

		const balena = getBalenaSdk();

		// Disambiguate application (if is a number, it could either be an ID or a numerical name)
		const application = await getApplication(balena, params.fleet);

		await balena.models.application.restart(application.id);
	}
}

export default class AppRestartCmd extends FleetRestartCmd {
	public static description = stripIndent`
		DEPRECATED alias for the 'fleet restart' command

		${appToFleetCmdMsg
			.split('\n')
			.map((l) => `\t\t${l}`)
			.join('\n')}

		For command usage, see 'balena help fleet restart'
	`;
	public static examples = [];
	public static usage = 'app restart <fleet>';
	public static args = FleetRestartCmd.args;
	public static flags = FleetRestartCmd.flags;
	public static authenticated = FleetRestartCmd.authenticated;
	public static primary = FleetRestartCmd.primary;

	public async run() {
		// call this.parse() before deprecation message to parse '-h'
		const parserOutput = this.parse<FlagsDef, ArgsDef>(AppRestartCmd);
		if (process.stderr.isTTY) {
			console.error(warnify(appToFleetCmdMsg));
		}
		await super.run(parserOutput);
	}
}


text:
using System;
using System.Collections.Generic;
using SystemsRx.Infrastructure.Dependencies;
using SystemsRx.Infrastructure.Plugins;
using SystemsRx.Systems;

namespace EcsRx.Plugins.Views
{
    public class ViewsPlugin : ISystemsRxPlugin
    {
        public string Name => "Views Plugin";
        public Version Version { get; } = new Version("1.0.0");

        public void SetupDependencies(IDependencyContainer container)
        {
            // Nothing needs registering
        }

        public IEnumerable<ISystem> GetSystemsForRegistration(IDependencyContainer container) => Array.Empty<ISystem>();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.axis2.jaxws.description.feature;

import junit.framework.TestCase;
import org.apache.axis2.jaxws.description.DescriptionFactory;
import org.apache.axis2.jaxws.description.EndpointDescription;
import org.apache.axis2.jaxws.description.ServiceDescription;
import org.apache.axis2.jaxws.description.builder.DescriptionBuilderComposite;
import org.apache.axis2.jaxws.description.builder.converter.JavaClassToDBCConverter;
import org.apache.axis2.jaxws.util.WSDL4JWrapper;

import javax.jws.WebService;
import javax.xml.namespace.QName;
import javax.xml.ws.RespectBinding;
import javax.xml.ws.soap.Addressing;

import java.net.URL;
import java.util.HashMap;
import java.util.List;

public class RespectBindingFeatureTests extends TestCase {

    private static final String ns = "http://jaxws.axis2.apache.org/metadata/feature/respectbinding";

    private static final String serviceName = "EchoMessageService";
    private static final String portTypeName = "EchoMessagePortType";

    private static final String plainServicePortName = "PlainServicePort";
    private static final String disabledServicePortName = "DisabledServicePort";
    private static final String defaultServicePortName = "DefaultServicePort";
    private static final String completeServicePortName = "CompleteServicePort";

    private static final String wsdlLocation = "test-resources/wsdl/RespectBinding.wsdl";

    /*
     * RespectBinding processing should fail because a WSDL file was not included.
     */

    public void testPlain() throws Exception {
        JavaClassToDBCConverter converter = new JavaClassToDBCConverter(PlainService.class);
        HashMap<String, DescriptionBuilderComposite> map = converter.produceDBC();

        DescriptionBuilderComposite composite = map.get(PlainService.class.getName());

        URL wsdlUrl = new URL("file:./" + wsdlLocation);
        WSDL4JWrapper wrapper = new WSDL4JWrapper(wsdlUrl, false, 0);

        composite.setwsdlURL(wsdlUrl);
        composite.setWsdlDefinition(wrapper.getDefinition());

        List<ServiceDescription> sdList = null;
        try {
            sdList = DescriptionFactory.createServiceDescriptionFromDBCMap(map);
        }
        catch (Exception e) {
            // An exception is expected.
        }

        assertTrue("The ServiceDescriptions should not have been built.", sdList == null);
    }

    public void testRespectBindingDisabled() throws Exception {
        JavaClassToDBCConverter converter = new JavaClassToDBCConverter(DisabledService.class);
        HashMap<String, DescriptionBuilderComposite> map = converter.produceDBC();

        DescriptionBuilderComposite composite = map.get(DisabledService.class.getName());

        URL wsdlUrl = new URL("file:./" + wsdlLocation);
        WSDL4JWrapper wrapper = new WSDL4JWrapper(wsdlUrl, false, 0);

        composite.setwsdlURL(wsdlUrl);
        composite.setWsdlDefinition(wrapper.getDefinition());

        List<ServiceDescription> sdList = DescriptionFactory.createServiceDescriptionFromDBCMap(map);
        ServiceDescription sd = sdList.get(0);

        EndpointDescription ed = sd.getEndpointDescription(new QName(ns, disabledServicePortName));
        assertTrue("The EndpointDescription should not be null.", ed != null);

        boolean respect = ed.respectBinding();
        assertFalse("Strict binding support should be DISABLED.", respect);
    }

    public void testRespectBindingDefault() throws Exception {
        JavaClassToDBCConverter converter = new JavaClassToDBCConverter(DefaultService.class);
        HashMap<String, DescriptionBuilderComposite> map = converter.produceDBC();

        DescriptionBuilderComposite composite = map.get(DefaultService.class.getName());

        URL wsdlUrl = new URL("file:./" + wsdlLocation);
        WSDL4JWrapper wrapper = new WSDL4JWrapper(wsdlUrl, false, 0);

        composite.setwsdlURL(wsdlUrl);
        composite.setWsdlDefinition(wrapper.getDefinition());

        List<ServiceDescription> sdList = null;
        try {
            sdList = DescriptionFactory.createServiceDescriptionFromDBCMap(map);
        }
        catch (Exception e) {
            // An exception is expected.
        }

        assertTrue("The ServiceDescriptions should not have been built.", sdList == null);
    }

    public void testRespectBindingComplete() throws Exception {
        JavaClassToDBCConverter converter = new JavaClassToDBCConverter(CompleteService.class);
        HashMap<String, DescriptionBuilderComposite> map = converter.produceDBC();

        DescriptionBuilderComposite composite = map.get(CompleteService.class.getName());

        URL wsdlUrl = new URL("file:./" + wsdlLocation);
        WSDL4JWrapper wrapper = new WSDL4JWrapper(wsdlUrl, false, 0);

        composite.setwsdlURL(wsdlUrl);
        composite.setWsdlDefinition(wrapper.getDefinition());

        List<ServiceDescription> sdList = DescriptionFactory.createServiceDescriptionFromDBCMap(map);
        ServiceDescription sd = sdList.get(0);

        EndpointDescription ed = sd.getEndpointDescription(new QName(ns, completeServicePortName));
        assertTrue("The EndpointDescription should not be null.", ed != null);

        boolean respect = ed.respectBinding();
        assertTrue("Strict binding support should be ENABLED.", respect);
    }

    @WebService(targetNamespace=ns, portName=plainServicePortName)
    @RespectBinding
    class PlainService {
        public String echo(String input) {
            return "";
        }
    }

    @WebService(targetNamespace=ns,
        serviceName=serviceName,
        portName=defaultServicePortName,
        name=portTypeName,
        wsdlLocation=wsdlLocation)
    @RespectBinding
    class DefaultService {
        public String echo(String input) {
            return "";
        }
    }

    @WebService(targetNamespace=ns,
        serviceName=serviceName,
        portName=disabledServicePortName,
        name=portTypeName,
        wsdlLocation=wsdlLocation)
    @RespectBinding(enabled=false)
    class DisabledService {
        public String echo(String input) {
            return "";
        }
    }

    @WebService(targetNamespace=ns,
        serviceName=serviceName,
        portName=completeServicePortName,
        name=portTypeName,
        wsdlLocation=wsdlLocation)
    @RespectBinding
    @Addressing
    class CompleteService {
        public String echo(String input) {
            return "";
        }
    }
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

// Network topology
//
//       n0    n1
//       |     |
//       =======
//         LAN
//
// - UDP flows from n0 to n1

#include <fstream>
#include "ns3/core-module.h"
#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/internet-module.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("UdpClientServerExample");

int
main (int argc, char *argv[])
{
//
// Enable logging for UdpClient and
//
  LogComponentEnable ("UdpClient", LOG_LEVEL_INFO);
  LogComponentEnable ("UdpServer", LOG_LEVEL_INFO);

  bool useV6 = false;
  Address serverAddress;

  CommandLine cmd;
  cmd.AddValue ("useIpv6", "Use Ipv6", useV6);
  cmd.Parse (argc, argv);

//
// Explicitly create the nodes required by the topology (shown above).
//
  NS_LOG_INFO ("Create nodes.");
  NodeContainer n;
  n.Create (2);

  InternetStackHelper internet;
  internet.Install (n);

  NS_LOG_INFO ("Create channels.");
//
// Explicitly create the channels required by the topology (shown above).
//
  CsmaHelper csma;
  csma.SetChannelAttribute ("DataRate", DataRateValue (DataRate (5000000)));
  csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
  csma.SetDeviceAttribute ("Mtu", UintegerValue (1400));
  NetDeviceContainer d = csma.Install (n);

//
// We've got the "hardware" in place.  Now we need to add IP addresses.
//
  NS_LOG_INFO ("Assign IP Addresses.");
  if (useV6 == false)
    {
      Ipv4AddressHelper ipv4;
      ipv4.SetBase ("10.1.1.0", "255.255.255.0");
      Ipv4InterfaceContainer i = ipv4.Assign (d);
      serverAddress = Address (i.GetAddress (1));
    }
  else
    {
      Ipv6AddressHelper ipv6;
      ipv6.SetBase ("2001:0000:f00d:cafe::", Ipv6Prefix (64));
      Ipv6InterfaceContainer i6 = ipv6.Assign (d);
      serverAddress = Address(i6.GetAddress (1,1));
    }

  NS_LOG_INFO ("Create Applications.");
//
// Create one udpServer applications on node one.
//
  uint16_t port = 4000;
  UdpServerHelper server (port);
  ApplicationContainer apps = server.Install (n.Get (1));
  apps.Start (Seconds (1.0));
  apps.Stop (Seconds (10.0));

//
// Create one UdpClient application to send UDP datagrams from node zero to
// node one.
//
  uint32_t MaxPacketSize = 1024;
  Time interPacketInterval = Seconds (0.05);
  uint32_t maxPacketCount = 320;
  UdpClientHelper client (serverAddress, port);
  client.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
  client.SetAttribute ("Interval", TimeValue (interPacketInterval));
  client.SetAttribute ("PacketSize", UintegerValue (MaxPacketSize));
  apps = client.Install (n.Get (0));
  apps.Start (Seconds (2.0));
  apps.Stop (Seconds (10.0));

//
// Now, do the actual simulation.
//
  NS_LOG_INFO ("Run Simulation.");
  Simulator::Run ();
  Simulator::Destroy ();
  NS_LOG_INFO ("Done.");
}


text:
using leBlog.MarkupParser.Renderer;

namespace leBlog.MarkupParser
{
    public class Parser
    {
        private readonly Config.Configurator _configurator = new Config.Configurator();

        public string CreateHtml(string markup)
        {
            var parserCore = new ParserCore(_configurator.TagPool);
            var rendererCore = new RendererCore(_configurator.TransformerPool);

            var document = parserCore.CreateDocument(markup);
            var html = rendererCore.CreateHtml(document);

            return html;
        }

        public override string ToString()
        {
            return "Parser";
        }
    }
}


text:
'''
New Integration Test for create root volume ceph pool.

@author: Lei Liu
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.zstack_test.zstack_test_vm as test_vm
import zstackwoodpecker.operations.primarystorage_operations as ps_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operations.vm_operations as vm_ops
import zstackwoodpecker.header.vm as vm_header
import apibinding.inventory as inventory
import zstacklib.utils.ssh as ssh
import os

_config_ = {
        'timeout' : 1000,
        'noparallel' : True
        }

test_obj_dict = test_state.TestStateDict()
ps_uuid = None
host_uuid = None
vr_uuid = None

def test():
    test_util.test_dsc('create ceph pool')
    try:
        ps = res_ops.query_resource(res_ops.CEPH_PRIMARY_STORAGE)[0]
    except Exception as e:
        test_util.test_dsc(str(e))
        test_util.test_skip('Skip for not finding ceph ps')
    ps_uuid = ps.uuid
    try:
        ceph_node_ip = ps.mons[0].monAddr
    except Exception as e:
        test_util.test_dsc(str(e))
        test_util.test_fail('Fail to get mon ip')
    create_pool_cmd = 'ceph osd pool create test_create_root_ssd_pool 4'
    try:
        (ret, out, eout) = ssh.execute(create_pool_cmd, ceph_node_ip, 'root', 'password')
    except Exception as e:
        test_util.test_dsc(str(e))
        test_util.test_fail('Fail to create pool by using ceph command')
    aliasName = 'test_aliasName_new'
    poolName = 'test_create_root_sas_pool'
    description = 'test_description'
    isCreate = 'true'
    test_util.test_dsc('add new pool by zstack')
    ps_ops.add_ceph_primary_storage_pool(ps_uuid, poolName, aliasName, isCreate, poolType="Root")
    cond = res_ops.gen_query_conditions('aliasName', '=', aliasName)
    pool = res_ops.query_resource(res_ops.CEPH_PRIMARY_STORAGE_POOL, cond)[0]
    print pool
    test_util.test_dsc("poolName: " + str(pool.poolName))
    if pool.poolName != poolName:
        test_util.test_fail('Find wrong pool should find: ' + str(poolName) + 'But find: ' + str(pool.poolName))

    test_util.test_dsc('add exist pool by zstack')
    aliasName = 'test_aliasName_exist'
    ps_ops.add_ceph_primary_storage_pool(ps_uuid, 'test_create_root_ssd_pool', aliasName, poolType="Root")
    cond = res_ops.gen_query_conditions('aliasName', '=', aliasName)
    pool = res_ops.query_resource(res_ops.CEPH_PRIMARY_STORAGE_POOL, cond)[0]
    test_util.test_dsc("poolName: " + str(pool.poolName))
    if pool.poolName != 'test_create_root_ssd_pool':
        test_util.test_fail('Find wrong pool should find: test_create_root_ssd_pool But find: ' + str(pool.poolName))

    #create vm on sas pool
    instance_offering_uuid = test_lib.lib_get_instance_offering_by_name(
       os.environ.get('instanceOfferingName_s')).uuid
    cond = res_ops.gen_query_conditions('mediaType', '!=', 'ISO')
    cond = res_ops.gen_query_conditions('platform', '=', 'Linux', cond)
    image_uuid = test_lib.lib_get_image_by_name(
        os.environ.get('imageName_s')).uuid

    l3net_uuid = test_lib.lib_get_l3_by_name(
        os.environ.get('l3PublicNetworkName')).uuid

    vm_creation_option = test_util.VmOption()
    vm_creation_option.set_instance_offering_uuid(instance_offering_uuid)
    vm_creation_option.set_image_uuid(image_uuid)
    vm_creation_option.set_l3_uuids([l3net_uuid])
    vm_creation_option.set_rootVolume_systemTags(["ceph::rootPoolName::test_create_root_sas_pool"])
    vm = test_vm.ZstackTestVm()
    vm.set_creation_option(vm_creation_option)
    vm.create()
    test_util.test_dsc('Create sas VM Test Success')

    vm_creation_option.set_rootVolume_systemTags(["ceph::rootPoolName::test_create_root_ssd_pool"])
    vm = test_vm.ZstackTestVm()
    vm.set_creation_option(vm_creation_option)
    vm.create()
    test_util.test_dsc('Create ssd VM Test Success')

    vm_creation_option.set_rootVolume_systemTags([])
    vm = test_vm.ZstackTestVm()
    vm.set_creation_option(vm_creation_option)
    vm.create()
    test_util.test_pass('Create ssd VM Test Success')

#Will be called only if exception happens in test().
def error_cleanup():
    global ps_uuid
    if ps_uuid != None:
        ps_ops.change_primary_storage_state(ps_uuid, 'Enabled')
    global host_uuid
    if host_uuid != None:
        host_ops.reconnect_host(host_uuid)
    global vr_uuid
    if vr_uuid != None:
        vm_ops.reconnect_vr(vr_uuid)
    global test_obj_dict
    test_lib.lib_error_cleanup(test_obj_dict)


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

<objects xmlns="http://www.springframework.net"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd">
  <!-- not a fully specified name -->
  <!-- <object id="connection" type="System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.5000.0, Culture=neutral"> -->
  <object id="connectionNotFullySpecified" type="System.Data.OleDb.OleDbConnection, System.Data">
    <property name="connectionstring">
      <value>Provider=SQLOLEDB</value>
    </property>
  </object>
</objects>


text:
import os
import sys
import numpy as np
import h5py

if __name__ == '__main__':
    # Parse arguments
    args = sys.argv[1:]
    dataset_name = args.pop(0)
    num_dims = int(args.pop(0))
    full_sizes = np.array([int(args.pop(0)) for i in range(num_dims)])[::-1]  # Matlab HDF5!
    input_files = args[:-1]
    output_path = args[-1]

    print "Reassembling", " ".join(input_files)
    print "Into", output_path

    # Create temporary output
    temp_path = output_path + '_partial'
    outf = h5py.File(temp_path, 'w')
    out_dataset = None

    # Loop over inputs
    for path in input_files:
        print "Reading", path, "..."
        infile = h5py.File(path)
        original_coords = infile['original_coords'][...]
        diced_data = infile[dataset_name]

        if out_dataset is None:
            # Chunk by block size
            full_sizes = [(s if s > 0 else diced_data.shape[idx]) for idx, s in enumerate(full_sizes)]
            chunksize = np.array(diced_data.shape)
            out_dataset = \
                outf.create_dataset(dataset_name,
                                    full_sizes,
                                    dtype=diced_data.dtype,
                                    chunks=tuple(chunksize),
                                    shuffle=True,
                                    compression='gzip')

        # compute destination coordinates
        lovals = original_coords[:num_dims]
        hivals = original_coords[num_dims:]
        dst_coords = [np.s_[lo:hi] for lo, hi in zip(lovals, hivals)][::-1]  # Matlab HDF5 reorders coords
        out_dataset[tuple(dst_coords)] = diced_data
    outf.close()

    # move to final location
    if os.path.exists(output_path):
        os.unlink(output_path)

    os.rename(temp_path, output_path)
    print "Success"


text:
/* This file was generated by upbc (the upb compiler) from the input
 * file:
 *
 *     envoy/config/trace/v3/opentelemetry.proto
 *
 * Do not edit -- your changes will be discarded when the file is
 * regenerated. */

#ifndef ENVOY_CONFIG_TRACE_V3_OPENTELEMETRY_PROTO_UPB_H_
#define ENVOY_CONFIG_TRACE_V3_OPENTELEMETRY_PROTO_UPB_H_

#include "upb/msg_internal.h"
#include "upb/decode.h"
#include "upb/decode_fast.h"
#include "upb/encode.h"

#include "upb/port_def.inc"

#ifdef __cplusplus
extern "C" {
#endif

struct envoy_config_trace_v3_OpenTelemetryConfig;
typedef struct envoy_config_trace_v3_OpenTelemetryConfig envoy_config_trace_v3_OpenTelemetryConfig;
extern const upb_MiniTable envoy_config_trace_v3_OpenTelemetryConfig_msginit;
struct envoy_config_core_v3_GrpcService;
extern const upb_MiniTable envoy_config_core_v3_GrpcService_msginit;

/* envoy.config.trace.v3.OpenTelemetryConfig */

UPB_INLINE envoy_config_trace_v3_OpenTelemetryConfig* envoy_config_trace_v3_OpenTelemetryConfig_new(upb_Arena* arena) {
  return (envoy_config_trace_v3_OpenTelemetryConfig*)_upb_Message_New(&envoy_config_trace_v3_OpenTelemetryConfig_msginit, arena);
}
UPB_INLINE envoy_config_trace_v3_OpenTelemetryConfig* envoy_config_trace_v3_OpenTelemetryConfig_parse(const char* buf, size_t size, upb_Arena* arena) {
  envoy_config_trace_v3_OpenTelemetryConfig* ret = envoy_config_trace_v3_OpenTelemetryConfig_new(arena);
  if (!ret) return NULL;
  if (upb_Decode(buf, size, ret, &envoy_config_trace_v3_OpenTelemetryConfig_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) {
    return NULL;
  }
  return ret;
}
UPB_INLINE envoy_config_trace_v3_OpenTelemetryConfig* envoy_config_trace_v3_OpenTelemetryConfig_parse_ex(const char* buf, size_t size,
                           const upb_ExtensionRegistry* extreg,
                           int options, upb_Arena* arena) {
  envoy_config_trace_v3_OpenTelemetryConfig* ret = envoy_config_trace_v3_OpenTelemetryConfig_new(arena);
  if (!ret) return NULL;
  if (upb_Decode(buf, size, ret, &envoy_config_trace_v3_OpenTelemetryConfig_msginit, extreg, options, arena) !=
      kUpb_DecodeStatus_Ok) {
    return NULL;
  }
  return ret;
}
UPB_INLINE char* envoy_config_trace_v3_OpenTelemetryConfig_serialize(const envoy_config_trace_v3_OpenTelemetryConfig* msg, upb_Arena* arena, size_t* len) {
  char* ptr;
  (void)upb_Encode(msg, &envoy_config_trace_v3_OpenTelemetryConfig_msginit, 0, arena, &ptr, len);
  return ptr;
}
UPB_INLINE char* envoy_config_trace_v3_OpenTelemetryConfig_serialize_ex(const envoy_config_trace_v3_OpenTelemetryConfig* msg, int options,
                                 upb_Arena* arena, size_t* len) {
  char* ptr;
  (void)upb_Encode(msg, &envoy_config_trace_v3_OpenTelemetryConfig_msginit, options, arena, &ptr, len);
  return ptr;
}
UPB_INLINE bool envoy_config_trace_v3_OpenTelemetryConfig_has_grpc_service(const envoy_config_trace_v3_OpenTelemetryConfig* msg) {
  return _upb_hasbit(msg, 1);
}
UPB_INLINE void envoy_config_trace_v3_OpenTelemetryConfig_clear_grpc_service(const envoy_config_trace_v3_OpenTelemetryConfig* msg) {
  *UPB_PTR_AT(msg, UPB_SIZE(4, 8), const upb_Message*) = NULL;
}
UPB_INLINE const struct envoy_config_core_v3_GrpcService* envoy_config_trace_v3_OpenTelemetryConfig_grpc_service(const envoy_config_trace_v3_OpenTelemetryConfig* msg) {
  return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), const struct envoy_config_core_v3_GrpcService*);
}

UPB_INLINE void envoy_config_trace_v3_OpenTelemetryConfig_set_grpc_service(envoy_config_trace_v3_OpenTelemetryConfig *msg, struct envoy_config_core_v3_GrpcService* value) {
  _upb_sethas(msg, 1);
  *UPB_PTR_AT(msg, UPB_SIZE(4, 8), struct envoy_config_core_v3_GrpcService*) = value;
}
UPB_INLINE struct envoy_config_core_v3_GrpcService* envoy_config_trace_v3_OpenTelemetryConfig_mutable_grpc_service(envoy_config_trace_v3_OpenTelemetryConfig* msg, upb_Arena* arena) {
  struct envoy_config_core_v3_GrpcService* sub = (struct envoy_config_core_v3_GrpcService*)envoy_config_trace_v3_OpenTelemetryConfig_grpc_service(msg);
  if (sub == NULL) {
    sub = (struct envoy_config_core_v3_GrpcService*)_upb_Message_New(&envoy_config_core_v3_GrpcService_msginit, arena);
    if (!sub) return NULL;
    envoy_config_trace_v3_OpenTelemetryConfig_set_grpc_service(msg, sub);
  }
  return sub;
}

extern const upb_MiniTable_File envoy_config_trace_v3_opentelemetry_proto_upb_file_layout;

#ifdef __cplusplus
}  /* extern "C" */
#endif

#include "upb/port_undef.inc"

#endif  /* ENVOY_CONFIG_TRACE_V3_OPENTELEMETRY_PROTO_UPB_H_ */


text:
package com.baolian.json;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;

import java.util.*;

/**
 * Created by tomxie on 2017/4/18 21:45.
 */
public class JSONTest {
    private static String jsonStr = "{\"name\":\"test\",\"ip\":\"192.168.1.1\",\"city_man\":\"西安市\",\"county\":\"莲湖区\",\"useruid\":\"123\",\"sysuuid\":\"111111\",\"testgroup_name\":\"视频类测试\",\"model\":\"aaa\",\"brasname\":\"bras1\"}";

    @Test
    public void RunJSONTest() {
        JSONObject json = JSONObject.parseObject(jsonStr);
        Map<String, Object> jsonMap = jsonToMap(json);
        for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
            System.out.println(String.format("%s:%s", entry.getKey(), entry.getValue()));
        }
    }

    public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if (json != null) {
            retMap = toMap(json);
        }
        return retMap;
    }

    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keySet().iterator();
        while (keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            } else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }

    private static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for (Object value : array) {
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            } else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}


text:
package com.intellij.openapi.vcs.changes.patch;

import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.DiffManager;
import com.intellij.diff.actions.impl.GoToChangePopupBuilder;
import com.intellij.diff.chains.DiffRequestChain;
import com.intellij.diff.chains.DiffRequestProducer;
import com.intellij.icons.AllIcons;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diff.impl.patch.*;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.ObjectsConvertor;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.ChangesUtil;
import com.intellij.openapi.vcs.changes.LocalChangeList;
import com.intellij.openapi.vcs.changes.actions.diff.ChangeGoToChangePopupAction;
import com.intellij.openapi.vcs.changes.shelf.ShelvedBinaryFilePatch;
import com.intellij.openapi.vcs.changes.ui.*;
import com.intellij.openapi.vfs.*;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.SimpleColoredComponent;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.Alarm;
import com.intellij.util.Consumer;
import com.intellij.util.NullableConsumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.Convertor;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

public class ApplyPatchDifferentiatedDialog extends DialogWrapper {
  private final ZipperUpdater myLoadQueue;
  private final TextFieldWithBrowseButton myPatchFile;

  private final List<AbstractFilePatchInProgress> myPatches;
  private final List<ShelvedBinaryFilePatch> myBinaryShelvedPatches;
  @NotNull private final MyChangeTreeList myChangesTreeList;
  @Nullable private final Collection<Change> myPreselectedChanges;

  private JComponent myCenterPanel;
  protected final Project myProject;

  private final AtomicReference<FilePresentation> myRecentPathFileChange;
  private final ApplyPatchDifferentiatedDialog.MyUpdater myUpdater;
  private final Runnable myReset;
  private final ChangeListChooserPanel myChangeListChooser;
  private final ChangesLegendCalculator myInfoCalculator;
  private final CommitLegendPanel myCommitLegendPanel;
  private final ApplyPatchExecutor myCallback;
  private final List<ApplyPatchExecutor> myExecutors;

  private boolean myContainBasedChanges;
  private JLabel myPatchFileLabel;
  private PatchReader myReader;
  private VirtualFileAdapter myListener;
  private final boolean myCanChangePatchFile;
  private String myHelpId = "reference.dialogs.vcs.patch.apply";
  private final LocalChangeList myLocalChangeList;
  private final String myCommitMessage; //may be provided externally; todo: parse with Additional Info Reader from patch meta information

  public ApplyPatchDifferentiatedDialog(final Project project, final ApplyPatchExecutor callback, final List<ApplyPatchExecutor> executors,
                                        @NotNull final ApplyPatchMode applyPatchMode, @NotNull final VirtualFile patchFile) {
    this(project, callback, executors, applyPatchMode, patchFile, null, null, null, null, null);
  }

  public ApplyPatchDifferentiatedDialog(final Project project,
                                        final ApplyPatchExecutor callback,
                                        final List<ApplyPatchExecutor> executors,
                                        @NotNull final ApplyPatchMode applyPatchMode,
                                        @NotNull final List<TextFilePatch> patches,
                                        @Nullable final LocalChangeList defaultList) {
    this(project, callback, executors, applyPatchMode, null, patches, defaultList, null, null, null);
  }

  public ApplyPatchDifferentiatedDialog(final Project project,
                                        final ApplyPatchExecutor callback,
                                        final List<ApplyPatchExecutor> executors,
                                        @NotNull final ApplyPatchMode applyPatchMode,
                                        @Nullable final VirtualFile patchFile,
                                        @Nullable final List<TextFilePatch> patches,
                                        @Nullable final LocalChangeList defaultList,
                                        @Nullable List<ShelvedBinaryFilePatch> binaryShelvedPatches,
                                        @Nullable Collection<Change> preselectedChanges, @Nullable String externalCommitMessage) {
    super(project, true);
    myCallback = callback;
    myExecutors = executors;
    setModal(false);
    setTitle(applyPatchMode.getTitle());

    final FileChooserDescriptor descriptor = createSelectPatchDescriptor();
    descriptor.setTitle(VcsBundle.message("patch.apply.select.title"));

    myProject = project;
    myPatches = new LinkedList<AbstractFilePatchInProgress>();
    myRecentPathFileChange = new AtomicReference<FilePresentation>();
    myBinaryShelvedPatches = binaryShelvedPatches;
    myPreselectedChanges = preselectedChanges;
    myChangesTreeList = new MyChangeTreeList(project, Collections.<AbstractFilePatchInProgress.PatchChange>emptyList(),
                                             new Runnable() {
                                               public void run() {
                                                 final NamedTrinity includedTrinity = new NamedTrinity();
                                                 final Collection<AbstractFilePatchInProgress.PatchChange> includedChanges =
                                                   myChangesTreeList.getIncludedChanges();
                                                 final Set<Couple<String>> set = new HashSet<Couple<String>>();
                                                 for (AbstractFilePatchInProgress.PatchChange change : includedChanges) {
                                                   final FilePatch patch = change.getPatchInProgress().getPatch();
                                                   final Couple<String> pair = Couple.of(patch.getBeforeName(), patch.getAfterName());
                                                   if (set.contains(pair)) continue;
                                                   set.add(pair);
                                                   acceptChange(includedTrinity, change);
                                                 }
                                                 myInfoCalculator.setIncluded(includedTrinity);
                                                 myCommitLegendPanel.update();
                                                 updateOkActions();
                                               }
                                             }, new MyChangeNodeDecorator());
    myChangesTreeList.setDoubleClickHandler(new Runnable() {
      @Override
      public void run() {
        new MyShowDiff().showDiff();
      }
    });

    myUpdater = new MyUpdater();
    myPatchFile = new TextFieldWithBrowseButton();
    myPatchFile.addBrowseFolderListener(VcsBundle.message("patch.apply.select.title"), "", project, descriptor);
    myPatchFile.getTextField().getDocument().addDocumentListener(new DocumentAdapter() {
      protected void textChanged(DocumentEvent e) {
        setPathFileChangeDefault();
        queueRequest();
      }
    });

    myCommitMessage = externalCommitMessage;
    myLocalChangeList = defaultList;
    myLoadQueue = new ZipperUpdater(500, Alarm.ThreadToUse.POOLED_THREAD, getDisposable());
    myCanChangePatchFile = applyPatchMode.isCanChangePatchFile();
    myReset = myCanChangePatchFile ? new Runnable() {
      public void run() {
        reset();
      }
    } : EmptyRunnable.getInstance();

    myChangeListChooser = new ChangeListChooserPanel(project, new NullableConsumer<String>() {
      public void consume(final @Nullable String errorMessage) {
        setOKActionEnabled(errorMessage == null);
        setErrorText(errorMessage);
      }
    });
    ChangeListManager changeListManager = ChangeListManager.getInstance(project);
    myChangeListChooser.setChangeLists(changeListManager.getChangeListsCopy());
    myChangeListChooser.setDefaultSelection(myLocalChangeList != null ? myLocalChangeList : changeListManager.getDefaultChangeList());
    myChangeListChooser.init();

    myInfoCalculator = new ChangesLegendCalculator();
    myCommitLegendPanel = new CommitLegendPanel(myInfoCalculator);

    init();

    if (patchFile != null && patchFile.isValid()) {
      init(patchFile);
    }
    else if (patches != null) {
      init(patches);
    }

    myPatchFileLabel.setVisible(myCanChangePatchFile);
    myPatchFile.setVisible(myCanChangePatchFile);

    if (myCanChangePatchFile) {
      myListener = new VirtualFileAdapter() {
        @Override
        public void contentsChanged(@NotNull VirtualFileEvent event) {
          if (myRecentPathFileChange.get() != null && myRecentPathFileChange.get().getVf() != null &&
              event.getFile().equals(myRecentPathFileChange.get().getVf())) {
            queueRequest();
          }
        }
      };
      final VirtualFileManager fileManager = VirtualFileManager.getInstance();
      fileManager.addVirtualFileListener(myListener);
      Disposer.register(getDisposable(), new Disposable() {
        @Override
        public void dispose() {
          fileManager.removeVirtualFileListener(myListener);
        }
      });
    }
    updateOkActions();
  }

  private void updateOkActions() {
    setOKActionEnabled(!myChangesTreeList.getIncludedChanges().isEmpty());
  }

  private void queueRequest() {
    paintBusy(true);
    myLoadQueue.queue(myUpdater);
  }

  private void init(List<? extends FilePatch> patches) {
    final List<AbstractFilePatchInProgress> matchedPatches = new MatchPatchPaths(myProject).execute(patches);
    //todo add shelved binary patches
    ApplicationManager.getApplication().invokeLater(new Runnable() {
      public void run() {
        myPatches.clear();
        myPatches.addAll(matchedPatches);
        updateTree(true);
      }
    });
  }

  public static FileChooserDescriptor createSelectPatchDescriptor() {
    return new FileChooserDescriptor(true, false, false, false, false, false) {
      @Override
      public boolean isFileSelectable(VirtualFile file) {
        return file.getFileType() == StdFileTypes.PATCH || file.getFileType() == FileTypes.PLAIN_TEXT;
      }
    };
  }

  @NotNull
  @Override
  protected Action[] createActions() {
    if (myExecutors.isEmpty()) {
      return super.createActions();
    }
    final List<Action> actions = new ArrayList<Action>(4);
    actions.add(getOKAction());
    for (int i = 0; i < myExecutors.size(); i++) {
      final ApplyPatchExecutor executor = myExecutors.get(i);
      final int finalI = i;
      actions.add(new AbstractAction(executor.getName()) {
        @Override
        public void actionPerformed(ActionEvent e) {
          runExecutor(executor);
          close(NEXT_USER_EXIT_CODE + finalI);
        }
      });
    }
    actions.add(getCancelAction());
    actions.add(getHelpAction());
    return actions.toArray(new Action[actions.size()]);
  }

  @CalledInAwt
  private void runExecutor(ApplyPatchExecutor executor) {
    final Collection<AbstractFilePatchInProgress> included = getIncluded();
    if (included.isEmpty()) return;
    final MultiMap<VirtualFile, AbstractFilePatchInProgress> patchGroups = new MultiMap<VirtualFile, AbstractFilePatchInProgress>();
    for (AbstractFilePatchInProgress patchInProgress : included) {
      patchGroups.putValue(patchInProgress.getBase(), patchInProgress);
    }
    final LocalChangeList selected = getSelectedChangeList();
    FilePresentation presentation = myRecentPathFileChange.get();
    VirtualFile vf = presentation != null ? presentation.getVf() : null;
    executor.apply(patchGroups, selected, vf == null ? null : vf.getName(),
                   myReader == null ? null : myReader.getAdditionalInfo(ApplyPatchDefaultExecutor.pathsFromGroups(patchGroups)));
  }

  @Override
  @NonNls
  protected String getDimensionServiceKey() {
    return "vcs.ApplyPatchDifferentiatedDialog";
  }

  @Override
  protected String getHelpId() {
    return myHelpId;
  }

  private void setPathFileChangeDefault() {
    myRecentPathFileChange.set(new FilePresentation(myPatchFile.getText()));
  }

  private void init(final VirtualFile patchFile) {
    myPatchFile.setText(patchFile.getPresentableUrl());
    myRecentPathFileChange.set(new FilePresentation(patchFile));
    queueRequest();
  }

  public void setHelpId(String s) {
    myHelpId = s;
  }

  private class MyUpdater implements Runnable {
    public void run() {
      final FilePresentation filePresentation = myRecentPathFileChange.get();
      if ((filePresentation == null) || (filePresentation.getVf() == null)) {
        ApplicationManager.getApplication().invokeLater(myReset);
        return;
      }
      final VirtualFile file = filePresentation.getVf();

      final PatchReader patchReader = loadPatches(filePresentation);
      if (patchReader == null) return;

      List<FilePatch> filePatches = ContainerUtil.<FilePatch>newArrayList(patchReader.getPatches());
      if (!ContainerUtil.isEmpty(myBinaryShelvedPatches)) {
        filePatches.addAll(myBinaryShelvedPatches);
      }
      final List<AbstractFilePatchInProgress> matchedPatches = new MatchPatchPaths(myProject).execute(filePatches);

      ApplicationManager.getApplication().invokeLater(new Runnable() {
        public void run() {
          myChangeListChooser
            .setDefaultName(myCommitMessage != null ? myCommitMessage : file.getNameWithoutExtension().replace('_', ' ').trim());
          myPatches.clear();
          myPatches.addAll(matchedPatches);
          myReader = patchReader;
          updateTree(true);
          paintBusy(false);
        }
      });
    }
  }

  @Nullable
  private static PatchReader loadPatches(final FilePresentation filePresentation) {
    final VirtualFile patchFile = filePresentation.getVf();
    if (patchFile == null) return null;
    patchFile.refresh(false, false);
    if (!patchFile.isValid()) {
      return null;
    }

    PatchReader reader;
    try {
      reader = PatchVirtualFileReader.create(patchFile);
    }
    catch (IOException e) {
      return null;
    }
    try {
      reader.parseAllPatches();
    }
    catch (PatchSyntaxException e) {
      return null;
    }

    return reader;
  }

  private static class FilePresentation {
    private final VirtualFile myVf;
    private final String myPath;

    private FilePresentation(VirtualFile vf) {
      myVf = vf;
      myPath = null;
    }

    private FilePresentation(String path) {
      myPath = path;
      myVf = null;
    }

    @Nullable
    public VirtualFile getVf() {
      if (myVf != null) {
        return myVf;
      }
      final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(myPath);
      return (file != null) && (!file.isDirectory()) ? file : null;
    }
  }

  private void reset() {
    myPatches.clear();
    myChangesTreeList.setChangesToDisplay(Collections.<AbstractFilePatchInProgress.PatchChange>emptyList());
    myChangesTreeList.repaint();
    myContainBasedChanges = false;
    paintBusy(false);
  }

  @Override
  protected JComponent createCenterPanel() {
    if (myCenterPanel == null) {
      myCenterPanel = new JPanel(new GridBagLayout());
      final GridBagConstraints gb =
        new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0);

      myPatchFileLabel = new JLabel(VcsBundle.message("patch.apply.file.name.field"));
      myPatchFileLabel.setLabelFor(myPatchFile);
      myCenterPanel.add(myPatchFileLabel, gb);

      gb.fill = GridBagConstraints.HORIZONTAL;
      ++gb.gridy;
      myCenterPanel.add(myPatchFile, gb);

      final DefaultActionGroup group = new DefaultActionGroup();
      final AnAction[] treeActions = myChangesTreeList.getTreeActions();
      group.addAll(treeActions);
      group.add(new MapDirectory());

      final MyShowDiff diffAction = new MyShowDiff();
      diffAction.registerCustomShortcutSet(CommonShortcuts.getDiff(), getRootPane());
      group.add(diffAction);

      group.add(new StripUp());
      group.add(new StripDown());
      group.add(new ResetStrip());
      group.add(new ZeroStrip());
      if (myCanChangePatchFile) {
        group.add(new AnAction("Refresh", "Refresh", AllIcons.Actions.Refresh) {
          @Override
          public void actionPerformed(AnActionEvent e) {
            queueRequest();
          }
        });
      }

      final ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("APPLY_PATCH", group, true);
      ++gb.gridy;
      gb.fill = GridBagConstraints.HORIZONTAL;
      myCenterPanel.add(toolbar.getComponent(), gb);

      ++gb.gridy;
      gb.weighty = 1;
      gb.fill = GridBagConstraints.BOTH;
      myCenterPanel.add(myChangesTreeList, gb);

      ++gb.gridy;
      gb.weighty = 0;
      gb.fill = GridBagConstraints.NONE;
      gb.insets.bottom = UIUtil.DEFAULT_VGAP;
      myCenterPanel.add(myCommitLegendPanel.getComponent(), gb);

      ++gb.gridy;
      gb.fill = GridBagConstraints.HORIZONTAL;
      myCenterPanel.add(myChangeListChooser, gb);
    }
    return myCenterPanel;
  }

  private void paintBusy(final boolean requestPut) {
    if (requestPut) {
      myChangesTreeList.setPaintBusy(true);
    }
    else {
      myChangesTreeList.setPaintBusy(!myLoadQueue.isEmpty());
    }
  }

  private static class MyChangeTreeList extends ChangesTreeList<AbstractFilePatchInProgress.PatchChange> {
    private MyChangeTreeList(Project project,
                             Collection<AbstractFilePatchInProgress.PatchChange> initiallyIncluded,
                             @Nullable Runnable inclusionListener,
                             @Nullable ChangeNodeDecorator decorator) {
      super(project, initiallyIncluded, true, false, inclusionListener, decorator);
    }

    @Override
    protected DefaultTreeModel buildTreeModel(List<AbstractFilePatchInProgress.PatchChange> changes,
                                              ChangeNodeDecorator changeNodeDecorator) {
      TreeModelBuilder builder = new TreeModelBuilder(myProject, false);
      return builder.buildModel(ObjectsConvertor.convert(changes,
                                                         new Convertor<AbstractFilePatchInProgress.PatchChange, Change>() {
                                                           public Change convert(AbstractFilePatchInProgress.PatchChange o) {
                                                             return o;
                                                           }
                                                         }), changeNodeDecorator);
    }

    @Override
    protected List<AbstractFilePatchInProgress.PatchChange> getSelectedObjects(ChangesBrowserNode<AbstractFilePatchInProgress.PatchChange> node) {
      final List<Change> under = node.getAllChangesUnder();
      return ObjectsConvertor.convert(under, new Convertor<Change, AbstractFilePatchInProgress.PatchChange>() {
        public AbstractFilePatchInProgress.PatchChange convert(Change o) {
          return (AbstractFilePatchInProgress.PatchChange)o;
        }
      });
    }

    @Override
    protected AbstractFilePatchInProgress.PatchChange getLeadSelectedObject(ChangesBrowserNode node) {
      final Object o = node.getUserObject();
      if (o instanceof AbstractFilePatchInProgress.PatchChange) {
        return (AbstractFilePatchInProgress.PatchChange)o;
      }
      return null;
    }
  }

  private class MapDirectory extends AnAction {
    private final NewBaseSelector myNewBaseSelector;

    private MapDirectory() {
      super("Map base directory", "Map base directory", AllIcons.Vcs.MapBase);
      myNewBaseSelector = new NewBaseSelector();
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();
      if ((selectedChanges.size() >= 1) && (sameBase(selectedChanges))) {
        final AbstractFilePatchInProgress.PatchChange patchChange = selectedChanges.get(0);
        final AbstractFilePatchInProgress patch = patchChange.getPatchInProgress();
        final List<VirtualFile> autoBases = patch.getAutoBasesCopy();
        if (autoBases.isEmpty() || (autoBases.size() == 1 && autoBases.get(0).equals(patch.getBase()))) {
          myNewBaseSelector.run();
        }
        else {
          autoBases.add(null);
          final MapPopup step = new MapPopup(autoBases, myNewBaseSelector);
          JBPopupFactory.getInstance().createListPopup(step).showCenteredInCurrentWindow(myProject);
        }
      }
    }

    @Override
    public void update(AnActionEvent e) {
      final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();
      e.getPresentation().setEnabled((selectedChanges.size() >= 1) && (sameBase(selectedChanges)));
    }
  }

  private static boolean sameBase(final List<AbstractFilePatchInProgress.PatchChange> selectedChanges) {
    VirtualFile base = null;
    for (AbstractFilePatchInProgress.PatchChange change : selectedChanges) {
      final VirtualFile changeBase = change.getPatchInProgress().getBase();
      if (base == null) {
        base = changeBase;
      }
      else if (!base.equals(changeBase)) {
        return false;
      }
    }
    return true;
  }

  private void updateTree(boolean doInitCheck) {
    final List<AbstractFilePatchInProgress> patchesToSelect = changes2patches(myChangesTreeList.getSelectedChanges());
    final List<AbstractFilePatchInProgress.PatchChange> changes = getAllChanges();
    final Collection<AbstractFilePatchInProgress.PatchChange> included = getIncluded(doInitCheck, changes);

    myChangesTreeList.setChangesToDisplay(changes);
    myChangesTreeList.setIncludedChanges(included);
    if (doInitCheck) {
      myChangesTreeList.expandAll();
    }
    myChangesTreeList.repaint();
    if ((!doInitCheck) && patchesToSelect != null) {
      final List<AbstractFilePatchInProgress.PatchChange> toSelect =
        new ArrayList<AbstractFilePatchInProgress.PatchChange>(patchesToSelect.size());
      for (AbstractFilePatchInProgress.PatchChange change : changes) {
        if (patchesToSelect.contains(change.getPatchInProgress())) {
          toSelect.add(change);
        }
      }
      myChangesTreeList.select(toSelect);
    }

    myContainBasedChanges = false;
    for (AbstractFilePatchInProgress patch : myPatches) {
      if (patch.baseExistsOrAdded()) {
        myContainBasedChanges = true;
        break;
      }
    }
  }

  private List<AbstractFilePatchInProgress.PatchChange> getAllChanges() {
    return ObjectsConvertor.convert(myPatches,
                                    new Convertor<AbstractFilePatchInProgress, AbstractFilePatchInProgress.PatchChange>() {
                                      public AbstractFilePatchInProgress.PatchChange convert(AbstractFilePatchInProgress o) {
                                        return o.getChange();
                                      }
                                    });
  }

  private static void acceptChange(final NamedTrinity trinity, final AbstractFilePatchInProgress.PatchChange change) {
    final AbstractFilePatchInProgress patchInProgress = change.getPatchInProgress();
    if (FilePatchStatus.ADDED.equals(patchInProgress.getStatus())) {
      trinity.plusAdded();
    }
    else if (FilePatchStatus.DELETED.equals(patchInProgress.getStatus())) {
      trinity.plusDeleted();
    }
    else {
      trinity.plusModified();
    }
  }

  private Collection<AbstractFilePatchInProgress.PatchChange> getIncluded(boolean doInitCheck,
                                                                          List<AbstractFilePatchInProgress.PatchChange> changes) {
    final NamedTrinity totalTrinity = new NamedTrinity();
    final NamedTrinity includedTrinity = new NamedTrinity();

    final Collection<AbstractFilePatchInProgress.PatchChange> included = new LinkedList<AbstractFilePatchInProgress.PatchChange>();
    if (doInitCheck) {
      for (AbstractFilePatchInProgress.PatchChange change : changes) {
        acceptChange(totalTrinity, change);
        final AbstractFilePatchInProgress abstractFilePatchInProgress = change.getPatchInProgress();
        if (abstractFilePatchInProgress.baseExistsOrAdded() && (myPreselectedChanges == null || myPreselectedChanges.contains(change))) {
          acceptChange(includedTrinity, change);
          included.add(change);
        }
      }
    }
    else {
      // todo maybe written pretty
      final Collection<AbstractFilePatchInProgress.PatchChange> includedNow = myChangesTreeList.getIncludedChanges();
      final Set<AbstractFilePatchInProgress> toBeIncluded = new HashSet<AbstractFilePatchInProgress>();
      for (AbstractFilePatchInProgress.PatchChange change : includedNow) {
        final AbstractFilePatchInProgress patch = change.getPatchInProgress();
        toBeIncluded.add(patch);
      }
      for (AbstractFilePatchInProgress.PatchChange change : changes) {
        final AbstractFilePatchInProgress patch = change.getPatchInProgress();
        acceptChange(totalTrinity, change);
        if (toBeIncluded.contains(patch) && patch.baseExistsOrAdded()) {
          acceptChange(includedTrinity, change);
          included.add(change);
        }
      }
    }
    myInfoCalculator.setTotal(totalTrinity);
    myInfoCalculator.setIncluded(includedTrinity);
    myCommitLegendPanel.update();
    return included;
  }

  private class NewBaseSelector implements Runnable {
    public void run() {
      final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
      VirtualFile selectedFile = FileChooser.chooseFile(descriptor, myProject, null);
      if (selectedFile == null) {
        return;
      }

      final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();
      if (selectedChanges.size() >= 1) {
        for (AbstractFilePatchInProgress.PatchChange patchChange : selectedChanges) {
          final AbstractFilePatchInProgress patch = patchChange.getPatchInProgress();
          patch.setNewBase(selectedFile);
        }
        updateTree(false);
      }
    }
  }

  private static List<AbstractFilePatchInProgress> changes2patches(final List<AbstractFilePatchInProgress.PatchChange> selectedChanges) {
    return ObjectsConvertor.convert(selectedChanges, new Convertor<AbstractFilePatchInProgress.PatchChange, AbstractFilePatchInProgress>() {
      public AbstractFilePatchInProgress convert(AbstractFilePatchInProgress.PatchChange o) {
        return o.getPatchInProgress();
      }
    });
  }

  private class MapPopup extends BaseListPopupStep<VirtualFile> {
    private final Runnable myNewBaseSelector;

    private MapPopup(final @NotNull List<? extends VirtualFile> aValues, Runnable newBaseSelector) {
      super("Select base directory for a path", aValues);
      myNewBaseSelector = newBaseSelector;
    }

    @Override
    public boolean isSpeedSearchEnabled() {
      return true;
    }

    @Override
    public PopupStep onChosen(final VirtualFile selectedValue, boolean finalChoice) {
      if (selectedValue == null) {
        myNewBaseSelector.run();
        return null;
      }
      final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();
      if (selectedChanges.size() >= 1) {
        for (AbstractFilePatchInProgress.PatchChange patchChange : selectedChanges) {
          final AbstractFilePatchInProgress patch = patchChange.getPatchInProgress();
          patch.setNewBase(selectedValue);
        }
        updateTree(false);
      }
      return null;
    }

    @NotNull
    @Override
    public String getTextFor(VirtualFile value) {
      return value == null ? "Select base for a path" : value.getPath();
    }
  }

  private static class NamedTrinity {
    private int myAdded;
    private int myModified;
    private int myDeleted;

    public NamedTrinity() {
      myAdded = 0;
      myModified = 0;
      myDeleted = 0;
    }

    public void plusAdded() {
      ++myAdded;
    }

    public void plusModified() {
      ++myModified;
    }

    public void plusDeleted() {
      ++myDeleted;
    }

    public int getAdded() {
      return myAdded;
    }

    public int getModified() {
      return myModified;
    }

    public int getDeleted() {
      return myDeleted;
    }
  }

  private static class ChangesLegendCalculator implements CommitLegendPanel.InfoCalculator {
    private NamedTrinity myTotal;
    private NamedTrinity myIncluded;

    private ChangesLegendCalculator() {
      myTotal = new NamedTrinity();
      myIncluded = new NamedTrinity();
    }

    public void setTotal(final NamedTrinity trinity) {
      myTotal = trinity;
    }

    public void setIncluded(final NamedTrinity trinity) {
      myIncluded = trinity;
    }

    public int getNew() {
      return myTotal.getAdded();
    }

    public int getModified() {
      return myTotal.getModified();
    }

    public int getDeleted() {
      return myTotal.getDeleted();
    }

    public int getIncludedNew() {
      return myIncluded.getAdded();
    }

    public int getIncludedModified() {
      return myIncluded.getModified();
    }

    public int getIncludedDeleted() {
      return myIncluded.getDeleted();
    }
  }

  private static class MyChangeNodeDecorator implements ChangeNodeDecorator {
    public void decorate(Change change, SimpleColoredComponent component, boolean isShowFlatten) {
      if (change instanceof AbstractFilePatchInProgress.PatchChange) {
        final AbstractFilePatchInProgress.PatchChange patchChange = (AbstractFilePatchInProgress.PatchChange)change;
        if (!isShowFlatten) {
          // add change sub path
          final FilePatch filePatch = patchChange.getPatchInProgress().getPatch();
          final String patchPath = filePatch.getAfterName() == null ? filePatch.getBeforeName() : filePatch.getAfterName();
          component.append("   ");
          component.append("[" + patchPath + "]", SimpleTextAttributes.GRAY_ATTRIBUTES);
        }
        if (patchChange.getPatchInProgress().getCurrentStrip() > 0) {
          component.append(" stripped " + patchChange.getPatchInProgress().getCurrentStrip(), SimpleTextAttributes.GRAY_ITALIC_ATTRIBUTES);
        }
        final String text;
        if (FilePatchStatus.ADDED.equals(patchChange.getPatchInProgress().getStatus())) {
          text = "(Added)";
        }
        else if (FilePatchStatus.DELETED.equals(patchChange.getPatchInProgress().getStatus())) {
          text = "(Deleted)";
        }
        else {
          text = "(Modified)";
        }
        component.append("   ");
        component.append(text, SimpleTextAttributes.GRAY_ATTRIBUTES);
      }
    }

    public List<Pair<String, Stress>> stressPartsOfFileName(final Change change, final String parentPath) {
      if (change instanceof AbstractFilePatchInProgress.PatchChange) {
        final AbstractFilePatchInProgress.PatchChange patchChange = (AbstractFilePatchInProgress.PatchChange)change;
        final String basePath = patchChange.getPatchInProgress().getBase().getPath();
        final String basePathCorrected = basePath.trim().replace('/', File.separatorChar);
        if (parentPath.startsWith(basePathCorrected)) {
          return Arrays.asList(Pair.create(basePathCorrected, Stress.BOLD),
                               Pair.create(StringUtil.tail(parentPath, basePathCorrected.length()), Stress.PLAIN));
        }
      }
      return null;
    }

    public void preDecorate(Change change, ChangesBrowserNodeRenderer renderer, boolean showFlatten) {
    }
  }

  private Collection<AbstractFilePatchInProgress> getIncluded() {
    return ObjectsConvertor.convert(myChangesTreeList.getIncludedChanges(),
                                    new Convertor<AbstractFilePatchInProgress.PatchChange, AbstractFilePatchInProgress>() {
                                      public AbstractFilePatchInProgress convert(AbstractFilePatchInProgress.PatchChange o) {
                                        return o.getPatchInProgress();
                                      }
                                    });
  }

  @Nullable
  private LocalChangeList getSelectedChangeList() {
    return myChangeListChooser.getSelectedList(myProject);
  }

  @Override
  protected void doOKAction() {
    super.doOKAction();
    runExecutor(myCallback);
  }

  private class ZeroStrip extends AnAction {
    private ZeroStrip() {
      super("Remove Directories", "Remove Directories", AllIcons.Vcs.StripNull);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();
      for (AbstractFilePatchInProgress.PatchChange change : selectedChanges) {
        change.getPatchInProgress().setZero();
      }
      updateTree(false);
    }
  }

  private class StripDown extends AnAction {
    private StripDown() {
      super("Restore Directory", "Restore Directory", AllIcons.Vcs.StripDown);
    }

    @Override
    public void update(AnActionEvent e) {
      e.getPresentation().setEnabled(isEnabled());
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      if (!isEnabled()) return;
      final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();
      for (AbstractFilePatchInProgress.PatchChange change : selectedChanges) {
        change.getPatchInProgress().down();
      }
      updateTree(false);
    }

    private boolean isEnabled() {
      final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();
      if (selectedChanges.isEmpty()) return false;
      for (AbstractFilePatchInProgress.PatchChange change : selectedChanges) {
        if (!change.getPatchInProgress().canDown()) return false;
      }
      return true;
    }
  }

  private class StripUp extends AnAction {
    private StripUp() {
      super("Strip Directory", "Strip Directory", AllIcons.Vcs.StripUp);
    }

    @Override
    public void update(AnActionEvent e) {
      e.getPresentation().setEnabled(isEnabled());
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      if (!isEnabled()) return;
      final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();
      for (AbstractFilePatchInProgress.PatchChange change : selectedChanges) {
        change.getPatchInProgress().up();
      }
      updateTree(false);
    }

    private boolean isEnabled() {
      final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();
      if (selectedChanges.isEmpty()) return false;
      for (AbstractFilePatchInProgress.PatchChange change : selectedChanges) {
        if (!change.getPatchInProgress().canUp()) return false;
      }
      return true;
    }
  }

  private class ResetStrip extends AnAction {
    private ResetStrip() {
      super("Reset Directories", "Reset Directories", AllIcons.Vcs.ResetStrip);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();
      for (AbstractFilePatchInProgress.PatchChange change : selectedChanges) {
        change.getPatchInProgress().reset();
      }
      updateTree(false);
    }
  }

  private class MyShowDiff extends AnAction {
    private final MyChangeComparator myMyChangeComparator;

    private MyShowDiff() {
      super("Show Diff", "Show Diff", AllIcons.Actions.Diff);
      myMyChangeComparator = new MyChangeComparator();
    }

    public void update(AnActionEvent e) {
      e.getPresentation().setEnabled((!myPatches.isEmpty()) && myContainBasedChanges);
    }

    public void actionPerformed(AnActionEvent e) {
      showDiff();
    }

    private void showDiff() {
      if (ChangeListManager.getInstance(myProject).isFreezedWithNotification(null)) return;
      if (myPatches.isEmpty() || (!myContainBasedChanges)) return;
      final List<AbstractFilePatchInProgress.PatchChange> changes = getAllChanges();
      Collections.sort(changes, myMyChangeComparator);
      List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges();

      int selectedIdx = 0;
      final List<DiffRequestProducer> diffRequestPresentableList = new ArrayList<DiffRequestProducer>(changes.size());
      final List<Change> diffRequestChangeList = new ArrayList<Change>(changes.size());
      if (selectedChanges.isEmpty()) {
        selectedChanges = changes;
      }
      if (!selectedChanges.isEmpty()) {
        final AbstractFilePatchInProgress.PatchChange c = selectedChanges.get(0);
        for (AbstractFilePatchInProgress.PatchChange change : changes) {
          final AbstractFilePatchInProgress patchInProgress = change.getPatchInProgress();
          if (!patchInProgress.baseExistsOrAdded()) continue;
          diffRequestPresentableList.add(patchInProgress.getDiffRequestProducers(myProject, myReader));
          diffRequestChangeList.add(change);
          if (change.equals(c)) {
            selectedIdx = diffRequestPresentableList.size() - 1;
          }
        }
      }
      if (diffRequestPresentableList.isEmpty()) return;
      MyDiffRequestChain chain = new MyDiffRequestChain(diffRequestPresentableList, diffRequestChangeList, selectedIdx);
      DiffManager.getInstance().showDiff(myProject, chain, DiffDialogHints.DEFAULT);
    }
  }

  private static class MyDiffRequestChain extends UserDataHolderBase implements DiffRequestChain, GoToChangePopupBuilder.Chain {
    private final List<DiffRequestProducer> myRequests;
    private final List<Change> myChanges;
    private int myIndex;

    public MyDiffRequestChain(@NotNull List<DiffRequestProducer> requests, @NotNull List<Change> changes, int index) {
      myRequests = requests;
      myChanges = changes;

      myIndex = index >= 0 ? index : 0;
    }

    @NotNull
    @Override
    public List<? extends DiffRequestProducer> getRequests() {
      return myRequests;
    }

    @Override
    public int getIndex() {
      return myIndex;
    }

    @Override
    public void setIndex(int index) {
      assert index >= 0 && index < myRequests.size();
      myIndex = index;
    }

    @NotNull
    @Override
    public AnAction createGoToChangeAction(@NotNull Consumer<Integer> onSelected) {
      return new ChangeGoToChangePopupAction.Fake<MyDiffRequestChain>(this, myIndex, onSelected) {
        @NotNull
        @Override
        protected FilePath getFilePath(int index) {
          return ChangesUtil.getFilePath(myChanges.get(index));
        }

        @NotNull
        @Override
        protected FileStatus getFileStatus(int index) {
          return myChanges.get(index).getFileStatus();
        }
      };
    }
  }

  private class MyChangeComparator implements Comparator<AbstractFilePatchInProgress.PatchChange> {
    public int compare(AbstractFilePatchInProgress.PatchChange o1, AbstractFilePatchInProgress.PatchChange o2) {
      if (PropertiesComponent.getInstance(myProject).isTrueValue("ChangesBrowser.SHOW_FLATTEN")) {
        return o1.getPatchInProgress().getIoCurrentBase().getName().compareTo(o2.getPatchInProgress().getIoCurrentBase().getName());
      }
      return FileUtil.compareFiles(o1.getPatchInProgress().getIoCurrentBase(), o2.getPatchInProgress().getIoCurrentBase());
    }
  }
}


text:
'use strict';

var test = require('tape');
var isDate = require('../');
var hasToStringTag = require('has-tostringtag/shams')();

test('not Dates', function (t) {
	t.notOk(isDate(), 'undefined is not Date');
	t.notOk(isDate(null), 'null is not Date');
	t.notOk(isDate(false), 'false is not Date');
	t.notOk(isDate(true), 'true is not Date');
	t.notOk(isDate(42), 'number is not Date');
	t.notOk(isDate('foo'), 'string is not Date');
	t.notOk(isDate([]), 'array is not Date');
	t.notOk(isDate({}), 'object is not Date');
	t.notOk(isDate(function () {}), 'function is not Date');
	t.notOk(isDate(/a/g), 'regex literal is not Date');
	t.notOk(isDate(new RegExp('a', 'g')), 'regex object is not Date');
	t.end();
});

test('@@toStringTag', { skip: !hasToStringTag }, function (t) {
	var realDate = new Date();
	var fakeDate = {
		toString: function () { return String(realDate); },
		valueOf: function () { return realDate.getTime(); }
	};
	fakeDate[Symbol.toStringTag] = 'Date';
	t.notOk(isDate(fakeDate), 'fake Date with @@toStringTag "Date" is not Date');
	t.end();
});

test('Dates', function (t) {
	t.ok(isDate(new Date()), 'new Date() is Date');
	t.end();
});


text:
import TempNode from './TempNode.js';

class FunctionCallNode extends TempNode {

	constructor( functionNode = null, parameters = {} ) {

		super();

		this.functionNode = functionNode;
		this.parameters = parameters;

	}

	setParameters( parameters ) {

		this.parameters = parameters;

		return this;

	}

	getParameters() {

		return this.parameters;

	}

	getNodeType( builder ) {

		return this.functionNode.getNodeType( builder );

	}

	generate( builder ) {

		const params = [];

		const functionNode = this.functionNode;

		const inputs = functionNode.getInputs( builder );
		const parameters = this.parameters;

		if ( Array.isArray( parameters ) ) {

			for ( let i = 0; i < parameters.length; i ++ ) {

				const inputNode = inputs[ i ];
				const node = parameters[ i ];

				params.push( node.build( builder, inputNode.type ) );

			}

		} else {

			for ( const inputNode of inputs ) {

				const node = parameters[ inputNode.name ];

				if ( node !== undefined ) {

					params.push( node.build( builder, inputNode.type ) );

				} else {

					throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );

				}

			}

		}

		const functionName = functionNode.build( builder, 'property' );

		return `${functionName}( ${params.join( ', ' )} )`;

	}

}

export default FunctionCallNode;


text:
/**
 * Package: MAG - VistA Imaging
 * WARNING: Per VHA Directive 2004-038, this routine should not be modified.
 * @date Jul 20, 2010
 * Site Name:  Washington OI Field Office, Silver Spring, MD
 * @author vhaiswbeckec
 * @version 1.0
 *
 * ----------------------------------------------------------------
 * Property of the US Government.
 * No permission to copy or redistribute this software is given.
 * Use of unreleased versions of this software requires the user
 * to execute a written test agreement with the VistA Imaging
 * Development Office of the Department of Veterans Affairs,
 * telephone (301) 734-0100.
 *
 * The Food and Drug Administration classifies this software as
 * a Class II medical device.  As such, it may not be changed
 * in any way.  Modifications to this software may result in an
 * adulterated medical device under 21CFR820, the use of which
 * is considered to be a violation of US Federal Statutes.
 * ----------------------------------------------------------------
 */

package gov.va.med.imaging;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * This is a list of the protocols currently known and used by VISA applications.
 * This enumeration is a convenience only and is not a definitive list of protocols.
 * Repeat, this is NOT a complete enumeration and should NEVER be depended on to be a complete
 * enumeration.  New protocols may be added without being added to this enumeration.
 * In addition, the existence of a protocol within this list DOES NOT guarantee that the
 * corresponding protocol handler is installed.
 *
 * @author vhaiswbeckec
 *
 */
public enum KnownProtocols
{
	EXCHANGE("exchange", 80, "Image exchange protocol used between the VIX and BIA", "VaImagingExchange", "/ImageMetadataService.asmx", "/RetrieveImage.ashx"),
	VFTP("vftp", 443, "VIX federation transport protocol, used between VIXEN", "VixFederation", "/webservices/ImageMetadataService", "/wai/images"),
	CDTP("cdtp", 80, "Clinical Display Transport Protocol, used between Clinical Display and a VIX", "ClinicalDisplayWebApp", "/webservices/ImageMetadataService", "/wai/images"),
	AWIV("awiv", 80, "AWIV Protocol, used between the AWIV viewer and a VIX", "AWIVWebApp", "/webservices/ImageMetadataService", "/wai/images"),
	VISTA("vista", 9300, "Used between the VIX and a VISTA installation", "", "", ""),
	VISTAIMAGING("vistaimaging", 9300, "Used between the VIX and a VISTA Imaging installation", "", "", ""),
	XCA("xca", 443, "Cross-Community Access, defined by IHE", "", "", "");

	private final String protocol;
	private final int defaultPort;
	private final String description;
	private final String defaultApplication;
	private final String defaultMetadataPath;
	private final String defaultArtifactPath;

	/**
	 * @param protocol
	 * @param defaultApplication
	 * @param defaultMetadataPath
	 * @param defaultArtifactPath
	 */
	private KnownProtocols(
		String protocol,
		int defaultPort,
		String description,
		String defaultApplication,
		String defaultMetadataPath,
		String defaultArtifactPath)
	{
		this.protocol = protocol;
		this.defaultPort = defaultPort;
		this.description = description;
		this.defaultApplication = defaultApplication;
		this.defaultMetadataPath = defaultMetadataPath;
		this.defaultArtifactPath = defaultArtifactPath;
	}

	/**
	 * @return the protocol
	 */
	public String getProtocol()
	{
		return this.protocol;
	}

	/**
	 * @return
	 */
	private int getDefaultPort()
	{
		return defaultPort;
	}

	/**
	 * @return the description
	 */
	public String getDescription()
	{
		return this.description;
	}

	/**
	 * @return the defaultApplication
	 */
	public String getDefaultApplication()
	{
		return this.defaultApplication;
	}

	/**
	 * @return the defaultMetadataPath
	 */
	public String getDefaultMetadataPath()
	{
		return this.defaultMetadataPath;
	}

	/**
	 * @return the defaultArtifactPath
	 */
	public String getDefaultArtifactPath()
	{
		return this.defaultArtifactPath;
	}

	public String getDefaultLocalMetadataURL()
	{
		return getProtocol() + "://localhost:" + getDefaultPort() + "/" + getDefaultApplication() + getDefaultMetadataPath();
	}

	public String getDefaultLocalArtifactURL()
	{
		return getProtocol() + "://localhost:" + getDefaultPort() + "/" + getDefaultApplication() + getDefaultArtifactPath();
	}

	/**
	 * Makes a "best guess" as to whether the protocol handlers are installed
	 * by building a URL from the default metadata path.  If the URL can be constructed
	 * then the protocol handlers are installed, else false.
	 * This algorithm may fail if the URL is not in the "normal" format, but at this time all
	 * of the known protocols work.
	 *
	 * @return
	 */
	public boolean isInstalled()
	{
		try
		{
			URL url = new URL( getProtocol(), "127.0.0.1", getDefaultApplication() + getDefaultMetadataPath() );
			return url != null;
		}
		catch (MalformedURLException x)
		{
			return false;
		}
	}
}


text:
using System;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Audio;

namespace Minalear
{
    public class Game : IDisposable
    {
        private GameWindow gameWindow;
        private ContentManager content;
        private GameTime gameTime;
        //private AudioContext audioContext;
        private Color4 clearColor = Color4.Black;

        public Game() : this(800, 450) { }
        public Game(int width, int height) : this(width, height, "VisualNovel") { }
        public Game(int width, int height, string title)
        {
            gameWindow = new GameWindow(width, height, new GraphicsMode(32, 24, 8, 4), title, GameWindowFlags.FixedWindow);
            gameWindow.UpdateFrame += (sender, e) => updateFrame(e);
            gameWindow.RenderFrame += (sender, e) => renderFrame(e);
            gameWindow.Resize += (sender, e) => Resize();

            //Enable Alpha blending
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

            gameTime = new GameTime();
            content = new ContentManager();
            //audioContext = new AudioContext();
        }

        public void Run()
        {
            Initialize();
            LoadContent();

            gameWindow.Run();
        }
        public void Resize()
        {
            GL.ClearColor(clearColor);
            GL.Viewport(0, 0, gameWindow.Width, gameWindow.Height);
        }

        public virtual void Initialize() { }
        public virtual void LoadContent() { }
        public virtual void UnloadContent() { }
        public virtual void Update(GameTime gameTime) { }
        public virtual void Draw(GameTime gameTime) { }
        public virtual void Dispose()
        {
            UnloadContent();
        }

        protected virtual void updateFrame(FrameEventArgs e)
        {
            if (Window.Focused)
            {
                gameTime.ElapsedTime = TimeSpan.FromSeconds(e.Time);
                gameTime.TotalTime.Add(TimeSpan.FromSeconds(e.Time));

                Update(gameTime);
            }
        }
        protected virtual void renderFrame(FrameEventArgs e)
        {
            GL.Clear(ClearBufferMask.ColorBufferBit);

            Draw(gameTime);
            gameWindow.SwapBuffers();
        }

        public GameWindow Window { get { return this.gameWindow; } }
        public ContentManager Content { get { return this.content; } }
        //public AudioContext AudioContext { get { return this.audioContext; } }
        public Color4 ClearColor { get { return this.clearColor; } set { this.clearColor = value; } }
    }
}


text:
package com.github.hburgmeier.jerseyoauth2.rs.impl.rs2.filter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.apache.commons.io.IOUtils;

import com.github.hburgmeier.jerseyoauth2.api.protocol.IHttpRequest;
import com.github.hburgmeier.jerseyoauth2.rs.impl.rs2.filter.util.FormParser;
import com.github.hburgmeier.jerseyoauth2.rs.impl.rs2.filter.util.FormParserException;

public class HttpRequestAdapter implements IHttpRequest {

	protected ContainerRequestContext context;
	protected Map<String,String> queryParameters = new HashMap<>();
	protected Form form;

	public HttpRequestAdapter(ContainerRequestContext ctx) {
		this.context = ctx;

		MultivaluedMap<String, String> queryParams = ctx.getUriInfo().getQueryParameters();
		for (Entry<String, List<String>> entry : queryParams.entrySet())
		{
			StringBuffer values = new StringBuffer();
			for (String val : entry.getValue())
			{
				if (values.length()>0) {
					values.append(",");
				}
				values.append(val);
			}
			this.queryParameters.put(entry.getKey(), values.toString());
		}
	}

	@Override
	public String getMethod() {
		return context.getMethod();
	}

	@Override
	public String getHeaderField(String field) {
		return context.getHeaderString(field);
	}

	@Override
	public String getQueryParameter(String queryParameter) {
		return queryParameters.get(queryParameter);
	}

	@Override
	public String getFormParameterValue(String formParameter) {
		if (form==null)
			form = getForm();
		return form.asMap().getFirst(formParameter);
	}

	protected Form getForm()
	{
		if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.equals(context.getMediaType()) && context.hasEntity())
		{
            try {
				InputStream inputStream = context.getEntityStream();
				if (inputStream.getClass() != ByteArrayInputStream.class) {
				    // Buffer input
				    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				    try {
				        IOUtils.copy(inputStream, byteArrayOutputStream);
				    } catch (IOException e) {
				        throw new IllegalArgumentException(e);
				    }

				    inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
				    context.setEntityStream(inputStream);
				}

				ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream) inputStream;
				FormParser formParser = new FormParser();
				Form f = formParser.parseForm(byteArrayInputStream);
				byteArrayInputStream.reset();
				return f;
			} catch (FormParserException e) {
				return new Form();
			}
        } else {
            return new Form();
        }
	}

}


text:
require 'rubygems'
require 'bundler/setup'

require 'ait_connect' # and any other gems you need

RSpec.configure do |config|
  # some (optional) config here

  def invalid_api_client
    ActiveInTime::Base.new("bollocks key","pizza is goood")
  end

  def valid_api_client
    #ActiveInTime::Base.new("EvVqRnFW4R53IUvcjP4uPjXzaQxNhNMCMZ2G5j5l","iE8iBM7tVXGlqF179qdr7UWhyPFIBROQ2tjtmE8M") #production
    ActiveInTime::Base.new("aayGdj3fyoSFPzGjNQg7WEOxFs7WGfyMGbx0CnI8","iE8iBM7tVXGlqF179qdr7UWhyPFIBROQ2tjtmE8M") #localhost

  end

end


text:
/// <reference path="../js/facepunch.webgame.d.ts"/>

namespace SourceUtils {
    import WebGame = Facepunch.WebGame;

    export enum CameraMode {
        Fixed = 0,
        CanLook = 1,
        CanMove = 2,
        FreeCam = CanLook | CanMove
    }

    export interface IPositionHash {
        x?: number;
        y?: number;
        z?: number;
        r?: number;
        s?: number;
    }

    export class MapViewer extends WebGame.Game {
        mainCamera: Entities.Camera;
        debugPanel: HTMLElement;

        readonly map = new Map(this);
        readonly visLoader = this.addLoader(new VisLoader());
        readonly bspModelLoader = this.addLoader(new BspModelLoader(this));
        readonly mapMaterialLoader = this.addLoader(new MapMaterialLoader(this));
        readonly leafGeometryLoader = this.addLoader(new LeafGeometryLoader(this));
        readonly dispGeometryLoader = this.addLoader(new DispGeometryLoader(this));
        readonly studioModelLoader = this.addLoader(new StudioModelLoader(this));
        readonly vertLightingLoader = this.addLoader(new VertexLightingLoader(this));
        readonly ambientLoader = this.addLoader(new AmbientLoader());

        private debugPanelVisible: boolean;

        cameraMode = CameraMode.Fixed;
        saveCameraPosInHash = false;
        showDebugPanel = false;

        totalLoadProgress = 0;

        avgFrameTime: number;
        avgFrameRate: number;

        notMovedTime: number;

        constructor(container: HTMLElement) {
            super(container);

            container.classList.add("map-viewer");
        }

        loadMap(url: string): void {
            this.map.load(url);
        }

        protected onInitialize(): void {
            this.canLockPointer = true;

            this.mainCamera = new Entities.Camera(this, 75);

            const deltaAngles = new Facepunch.Vector3();
            let lastRotationSampleTime = new Date().getTime() / 1000;

            const deviceRotate = (x: number, y: number, z: number, period: number, toRadians: number) => {
                x *= toRadians / period;
                y *= toRadians / period;
                z *= toRadians / period;

                const sampleTime = new Date().getTime() / 1000;
                const deltaTime = sampleTime - lastRotationSampleTime;
                lastRotationSampleTime = sampleTime;

                deltaAngles.x = x * deltaTime;
                deltaAngles.y = y * deltaTime;
                deltaAngles.z = z * deltaTime;

                this.onDeviceRotate(deltaAngles);
            };

            const wind: any = window;
            if (wind.DeviceMotionEvent) {
                window.addEventListener("devicemotion",
                    evnt => {
                        const rate = evnt.rotationRate;
                        //deviceRotate(rate.beta, rate.gamma, rate.alpha, 1.0, 1.0);
                    },
                    true);
            }

            if (window.location.hash != null && window.location.hash.length > 1) {
                this.hashChange();
            }

            window.onhashchange = ev => this.hashChange();

            super.onInitialize();
        }

        private static readonly hashKeyRegex = /^[a-z_]+$/i;
        private static readonly hashObjectRegex = /^#((?:[a-z_]+)(?:-?[0-9]+(?:\.[0-9]+)?))+$/i;

        protected setHash(value: string | Object): void {
            if (typeof value === "string") {
                this.oldHash = value;
                window.location.hash = value;
                return;
            }

            let hash = "#";
            for (let key in value) {
                if (!value.hasOwnProperty(key)) continue;
                if (!MapViewer.hashKeyRegex.test(key)) {
                    console.warn(`Invalid hash object key: ${key}`);
                    continue;
                }

                const val = value[key];
                if (typeof val !== "number" && (typeof val !== "string" || isNaN(parseFloat(val)))) {
                    console.warn(`Invalid hash object value: ${val}`);
                    continue;
                }

                hash += key;
                hash += val;
            }

            this.setHash(hash);
        }

        private oldHash: string;

        private hashChange(): void {
            const hash = window.location.hash;
            if (hash === this.oldHash) return;
            this.oldHash = hash;

            if (!MapViewer.hashObjectRegex.test(hash)) {
                this.onHashChange(hash);
                return;
            }

            const obj = {};

            const keyValRegex = /([a-z_]+)(-?[0-9]+(?:\.[0-9]+)?)/ig;

            let match: RegExpExecArray;
            while ((match = keyValRegex.exec(hash)) != null) {
                obj[match[1]] = parseFloat(match[2]);
            }

            this.onHashChange(obj);
        }

        private readonly onHashChange_temp = new Facepunch.Vector3();

        protected onHashChange(value: string | Object): void {
            if (typeof value === "string") return;
            if (!this.saveCameraPosInHash) return;

            const posHash = value as IPositionHash;

            const pos = this.mainCamera.getPosition(this.onHashChange_temp);

            if (posHash.x !== undefined) {
                pos.x = posHash.x;
            }

            if (posHash.y !== undefined) {
                pos.y = posHash.y;
            }

            if (posHash.z !== undefined) {
                pos.z = posHash.z;
            }

            this.mainCamera.setPosition(pos);

            if (posHash.r !== undefined) {
                this.lookAngs.x = posHash.r / 180 * Math.PI;
            }

            if (posHash.s !== undefined) {
                this.lookAngs.y = posHash.s / 180 * Math.PI;
            }

            this.updateCameraAngles();
        }

        protected onCreateDebugPanel(): HTMLElement {
            const panel = document.createElement("div");
            panel.classList.add("side-panel");
            panel.innerHTML = `
                Frame time: 0 ms

                Frame rate: 0 fps

                Draw calls: 0

                    Map loaded: 0%

`;

            this.container.appendChild(panel);
            return panel;
        }

        protected onDeviceRotate(deltaAngles: Facepunch.Vector3): void {
            if ((this.cameraMode & CameraMode.CanLook) === 0) return;
            if (window.innerWidth > window.innerHeight) {
                this.lookAngs.x += deltaAngles.z;
                this.lookAngs.y -= deltaAngles.x;
            } else {
                this.lookAngs.x += deltaAngles.x;
                this.lookAngs.y += deltaAngles.z;
            }
            this.notMovedTime = 0;
            this.updateCameraAngles();
        }

        protected onResize(): void {
            super.onResize();

            if (this.mainCamera != null) {
                this.mainCamera.setAspect(this.getWidth() / this.getHeight());
            }
        }

        private readonly lookAngs = new Facepunch.Vector2();
        private readonly tempQuat = new Facepunch.Quaternion();
        private readonly lookQuat = new Facepunch.Quaternion();

        setCameraAngles(yaw: number, pitch: number): void {
            this.lookAngs.x = yaw;
            this.lookAngs.y = pitch;
            this.updateCameraAngles();
        }

        private updateCameraAngles(): void {
            if (this.lookAngs.y < -Math.PI * 0.5) this.lookAngs.y = -Math.PI * 0.5;
            if (this.lookAngs.y > Math.PI * 0.5) this.lookAngs.y = Math.PI * 0.5;

            this.lookQuat.setAxisAngle(Facepunch.Vector3.unitZ, this.lookAngs.x);
            this.tempQuat.setAxisAngle(Facepunch.Vector3.unitX, this.lookAngs.y + Math.PI * 0.5);
            this.lookQuat.multiply(this.tempQuat);

            this.mainCamera.setRotation(this.lookQuat);
        }

        protected onMouseLook(delta: Facepunch.Vector2): void {
            super.onMouseLook(delta);

            if ((this.cameraMode & CameraMode.CanLook) === 0) return;
            if (Math.abs(delta.x) === 0 && Math.abs(delta.y) === 0) return;

            this.lookAngs.sub(delta.multiplyScalar(1 / 800));
            this.notMovedTime = 0;
            this.updateCameraAngles();
        }

        toggleFullscreen(): void {
            const container = this.container;
            const cont = container as any;
            const doc = document as any;

            if (doc.fullscreenElement === container || doc.webkitFullscreenElement === container || doc.mozFullScreenElement === container) {
                if (document.exitFullscreen) document.exitFullscreen();
                else if (doc.webkitExitFullscreen) doc.webkitExitFullscreen();
                else if (doc.mozCancelFullScreen) doc.mozCancelFullScreen();
            } else if (container.requestFullscreen) {
                container.requestFullscreen();
            } else if (cont.webkitRequestFullscreen) {
                cont.webkitRequestFullscreen();
            } else if (cont.mozRequestFullScreen) {
                cont.mozRequestFullScreen();
            }
        }

        protected onKeyDown(key: WebGame.Key): boolean {
            super.onKeyDown(key);

            switch (key) {
                case WebGame.Key.F:
                    this.toggleFullscreen();
                    return true;
                case WebGame.Key.W:
                case WebGame.Key.A:
                case WebGame.Key.S:
                case WebGame.Key.D:
                case WebGame.Key.Shift:
                case WebGame.Key.Alt:
                    return this.isPointerLocked() && (this.cameraMode & CameraMode.CanMove) !== 0;
                default:
                    return false;
            }
        }

        private lastProfileTime: number;
        private frameCount = 0;
        private lastDrawCalls: number;
        private allLoaded = false;

        protected onSetDebugText(className: string, value: string): void {
            const elem = this.debugPanel.getElementsByClassName(className)[0] as HTMLElement;
            if (elem == null) return;

            elem.innerText = value;

            if (className === "debug-loadpercent" && parseInt(value) >= 100) {
                const loading = this.debugPanel.getElementsByClassName("debug-loading")[0] as HTMLElement;
                if (loading != null) {
                    loading.style.display = "none";
                }
            }
        }

        private readonly onUpdateFrame_temp = new Facepunch.Vector3();

        protected onUpdateFrame(dt: number): void {
            super.onUpdateFrame(dt);

            this.map.update(dt);

            if (this.showDebugPanel !== this.debugPanelVisible) {
                this.debugPanelVisible = this.showDebugPanel;

                if (this.showDebugPanel && this.debugPanel === undefined) {
                    this.debugPanel = this.onCreateDebugPanel();
                }

                if (this.debugPanel != null) {
                    if (this.showDebugPanel) this.debugPanel.style.display = null;
                    else this.debugPanel.style.display = "none";
                }
            }

            const savePosPeriod = 1;
            const wasBeforeSavePosPeriod = this.notMovedTime < savePosPeriod;

            if ((this.cameraMode & CameraMode.CanMove) !== 0 && this.isPointerLocked() && this.map.isReady()) {
                const move = this.onUpdateFrame_temp;

                move.set(0, 0, 0);
                const moveSpeed = 512 * dt
                    * (this.isKeyDown(WebGame.Key.Shift) ? 4 : 1)
                    * (this.isKeyDown(WebGame.Key.Alt) ? 0.333 : 1);

                if (this.isKeyDown(WebGame.Key.W)) move.z -= moveSpeed;
                if (this.isKeyDown(WebGame.Key.S)) move.z += moveSpeed;
                if (this.isKeyDown(WebGame.Key.A)) move.x -= moveSpeed;
                if (this.isKeyDown(WebGame.Key.D)) move.x += moveSpeed;

                if (move.lengthSq() > 0) {
                    this.mainCamera.applyRotationTo(move);
                    this.mainCamera.translate(move);
                    this.notMovedTime = 0;
                }
            }

            this.notMovedTime += dt;

            if (this.saveCameraPosInHash && wasBeforeSavePosPeriod && this.notMovedTime >= savePosPeriod) {
                const pos = this.mainCamera.getPosition(this.onUpdateFrame_temp);
                const pitch = this.lookAngs.x * 180.0 / Math.PI;
                const yaw = this.lookAngs.y * 180.0 / Math.PI;

                this.setHash({
                    x: pos.x.toFixed(1),
                    y: pos.y.toFixed(1),
                    z: pos.z.toFixed(1),
                    r: pitch.toFixed(1),
                    s: yaw.toFixed(1)
                });
            }

            // Diagnostics

            const drawCalls = this.mainCamera.getDrawCalls();
            if (drawCalls !== this.lastDrawCalls && this.showDebugPanel) {
                this.lastDrawCalls = drawCalls;
                this.onSetDebugText("debug-drawcalls", drawCalls.toString());
            }

            ++this.frameCount;
            const time = performance.now();

            if (this.lastProfileTime === undefined) {
                this.lastProfileTime = time;
            } else if (time - this.lastProfileTime >= 500) {
                const timeDiff = (time - this.lastProfileTime) / 1000;
                this.avgFrameTime = timeDiff * 1000 / this.frameCount;
                this.avgFrameRate = this.frameCount / timeDiff;

                if (this.showDebugPanel) {
                    this.onSetDebugText("debug-frametime", this.avgFrameTime.toPrecision(4));
                    this.onSetDebugText("debug-framerate", this.avgFrameRate.toPrecision(4));
                }

                if (!this.allLoaded) {
                    const visLoaded = this.visLoader.getLoadProgress();
                    const bspLoaded = this.bspModelLoader.getLoadProgress();
                    const lightmapLoaded = this.map.getLightmapLoadProgress();
                    const materialsLoaded = this.mapMaterialLoader.getLoadProgress();

                    const geomLoaded = this.leafGeometryLoader.getLoadProgress() * 0.5
                        + this.dispGeometryLoader.getLoadProgress() * 0.5;

                    const propsLoaded = this.vertLightingLoader.getLoadProgress() * 0.25
                        + this.studioModelLoader.getLoadProgress() * 0.75;

                    this.totalLoadProgress = (visLoaded + bspLoaded + lightmapLoaded + materialsLoaded + geomLoaded + propsLoaded) / 6;

                    if (this.showDebugPanel) {
                        this.onSetDebugText("debug-loadpercent", (this.totalLoadProgress * 100).toPrecision(3));
                    }

                    if (this.totalLoadProgress >= 1) {
                        this.allLoaded = true;
                    }
                }

                this.lastProfileTime = time;
                this.frameCount = 0;
            }
        }

        protected onRenderFrame(dt: number): void {
            super.onRenderFrame(dt);

            const gl = this.context;

            gl.clear(gl.DEPTH_BUFFER_BIT);
            gl.depthFunc(gl.LEQUAL);
            gl.cullFace(gl.FRONT);

            if (this.mainCamera != null) {
                this.mainCamera.render();
            }
        }

        populateCommandBufferParameters(buf: WebGame.CommandBuffer): void {
            super.populateCommandBufferParameters(buf);

            this.map.populateCommandBufferParameters(buf);
        }
    }
}