text:
#include <climits>
#include <fstream>
#include <ios>
#include <string>

#include <libport/debug.hh>
#include <libport/bind.hh>

#include <libport/export.hh>
#include <libport/hierarchy.hh>
#include <libport/unit-test.hh>

#include <serialize/serialize.hh>

using libport::test_suite;
using namespace libport::serialize;

#define BASE "tests/serialize/"

#define SERIALIZE(Type, Value)                                  \
    BOOST_CHECK_NO_THROW(ser.serialize<Type>("test", Value))

#define UNSERIALIZE(Type, Value)                                \
    BOOST_CHECK_EQUAL(ser.unserialize<Type>("test"), Value);

#define CHECK(Type, Value)                      \
  do {                                          \
    {                                           \
      std::ofstream f(fn);                      \
      BinaryOSerializer ser(f);                 \
      SERIALIZE(Type, (Type) (Value));          \
    }                                           \
    {                                           \
      std::ifstream f(fn);                      \
      BOOST_CHECK(f.good());                    \
      BinaryISerializer ser(f);                 \
      UNSERIALIZE(Type, (Type) (Value));        \
      f.peek();                                 \
      BOOST_CHECK(f.eof());                     \
    }                                           \
  } while (false)

GD_INIT();

void binary_pod()
{
  const char *fn = BASE "binary_pod";

  // Try isolated first, but also check when several values are
  // serialized in a row.
  CHECK(int, 42);
  CHECK(bool, true);
  CHECK(bool, false);
  CHECK(std::string, "string ");
  CHECK(float, 0.);
  CHECK(float, -1.);
  CHECK(float, 1234.567);
  CHECK(double, 0.);
  CHECK(double, -1.);
  CHECK(double, 1234.567);

  {
    std::ofstream f(fn);
    BinaryOSerializer ser(f);

    SERIALIZE(int, 42);
    SERIALIZE(bool, true);
    SERIALIZE(bool, false);
    SERIALIZE(std::string, "string ");
    int* p1 = new int(51);
    int* p2 = new int(69);
    SERIALIZE(int*, p1);
    SERIALIZE(int*, p2);
    SERIALIZE(int*, p2);
    SERIALIZE(int*, p1);
    SERIALIZE(int*, NULL);
  }
  {
    std::ifstream f(fn);
    BOOST_CHECK(f.good());
    BinaryISerializer ser(f);

    UNSERIALIZE(int, 42);
    UNSERIALIZE(bool, true);
    UNSERIALIZE(bool, false);
    UNSERIALIZE(std::string, "string ");
    int* p1 = ser.unserialize<int*>("test");
    int* p2 = ser.unserialize<int*>("test");
    int* p3 = ser.unserialize<int*>("test");
    int* p4 = ser.unserialize<int*>("test");
    int* p5 = ser.unserialize<int*>("test");
    BOOST_CHECK_EQUAL(*p1, 51);
    BOOST_CHECK_EQUAL(*p2, 69);
    BOOST_CHECK_EQUAL(p1, p4);
    BOOST_CHECK_EQUAL(p2, p3);
    BOOST_CHECK_EQUAL(p5, reinterpret_cast<int*>(NULL));
  }
}

void binary_integers_size()
{
  const char *fn = BASE "binary_integers_size";

#define CHECK_MAX(Type)                                 \
  CHECK(Type, std::numeric_limits<Type>::max() / 2)

  CHECK_MAX(unsigned short);
  CHECK_MAX(unsigned int);
  CHECK_MAX(unsigned long);
  CHECK_MAX(unsigned long long);
#undef CHECK_MAX
}

void binary_integers_size_portability()
{
  const char *fn = BASE "binary_integers_size";
  // Simulate fancy short size.
  {
    std::ofstream f(fn);
    BinaryOSerializer ser(f);

    // Change integers size.
    char sizes[] = {0x4, 0x4, 0x4, 0x8,};
    f.flush();
    f.seekp(std::ios_base::beg);
    f.write(sizes, sizeof(sizes));
    f.flush();

    SERIALIZE(uint32_t, 0);
    SERIALIZE(uint32_t, 42);
    SERIALIZE(uint32_t, USHRT_MAX + 1);
    SERIALIZE(uint32_t, USHRT_MAX);
    f.flush();
    f.close();
  }
  {
    std::ifstream f(fn);
    BOOST_CHECK(f.good());
    BinaryISerializer ser(f);
    UNSERIALIZE(unsigned short, 0);
    UNSERIALIZE(unsigned short, 42);
    BOOST_CHECK_THROW(ser.unserialize<unsigned short>(),
                      libport::serialize::Exception);
    UNSERIALIZE(unsigned short, USHRT_MAX);
  }
}

struct Person
{
  Person(const std::string& name, const std::string& surname)
    : name_(name)
    , surname_(surname)
  {}

  template <typename S>
  Person(ISerializer<S>& input)
    : name_(input.template unserialize<std::string>("name"))
    , surname_(input.template unserialize<std::string>("surname"))
  {

  }

  template <typename S>
  void serialize(OSerializer<S>& output) const
  {
    output.serialize<std::string>("name", name_);
    output.serialize<std::string>("surname", surname_);
  }

  std::string name_, surname_;
};

void binary_class()
{
  const char *fn = BASE "binary_class";

  {
    std::ofstream f(fn);
    BinaryOSerializer ser(f);

    Person ed("Draven", "Eric");
    Person cs("Slade", "Cutter");
    ser.serialize<Person>("test", ed);
    ser.serialize<Person>("test", cs);
  }
  {
    std::ifstream f(fn);
    BinaryISerializer ser(f);

    Person ed = ser.unserialize<Person>("test");
    Person cs = ser.unserialize<Person>("test");
    BOOST_CHECK_EQUAL(ed.name_, "Draven");
    BOOST_CHECK_EQUAL(ed.surname_, "Eric");
    BOOST_CHECK_EQUAL(cs.name_, "Slade");
    BOOST_CHECK_EQUAL(cs.surname_, "Cutter");
  }
}

struct Unix;
struct Linux;
struct Gentoo;
struct Debian;

struct Unix: public libport::meta::Hierarchy<Unix, TYPELIST_2(Gentoo, Debian)>
{

};

struct Linux: public Unix
{
  Linux(const std::string& k)
    : kernel(k)
  {}

  template <typename T>
  Linux(ISerializer<T>& ser)
  {
    kernel = ser.template unserialize<std::string>("kernel");
  }

  template <typename T>
  void serialize(OSerializer<T>& ser) const
  {
    ser.template serialize<std::string>("kernel", kernel);
  }

  std::string kernel;
};

struct Debian: public Linux
{
  Debian(const std::string& kernel, const std::string& v)
    : Linux(kernel)
    , version(v)
  {}

  template <typename T>
  Debian(ISerializer<T>& ser)
    : Linux(ser)
  {
    version = ser.template unserialize<std::string>("version");
  }

  template <typename T>
  void serialize(OSerializer<T>& ser) const
  {
    Linux::serialize(ser);
    ser.serialize<std::string>("version", version);
  }

  std::string version;
};

struct Gentoo: public Linux
{
  Gentoo(const std::string& kernel, int v)
    : Linux(kernel)
    , version(v)
  {}

  template <typename T>
  Gentoo(ISerializer<T>& ser)
    : Linux(ser)
  {
    version = ser.template unserialize<int>("version");
  }

  template <typename T>
  void serialize(OSerializer<T>& ser) const
  {
    Linux::serialize(ser);
    ser.serialize<int>("version", version);
  }

  int version;
};

void binary_hierarchy()
{
  const char *fn = BASE "binary_hier";

  {
    std::ofstream f(fn);
    BinaryOSerializer ser(f);

    Debian d("2.4", "sarge");
    Gentoo g("2.6", 2008);
    ser.serialize<Debian>("test", d);
    ser.serialize<Gentoo>("test", g);
  }
  {
    std::ifstream f(fn);
    BinaryISerializer ser(f);

    Unix* d_ = ser.unserialize<Unix>("test");
    Unix* g_ = ser.unserialize<Unix>("test");
    Debian* d = dynamic_cast<Debian*>(d_ );
    Gentoo* g = dynamic_cast<Gentoo*>(g_) ;
    BOOST_CHECK(d);
    BOOST_CHECK(g);
    BOOST_CHECK_EQUAL(d->kernel, "2.4");
    BOOST_CHECK_EQUAL(d->version, "sarge");
    BOOST_CHECK_EQUAL(g->kernel, "2.6");
    BOOST_CHECK_EQUAL(g->version, 2008);
  }
}

test_suite*
init_test_suite()
{
  test_suite* suite = BOOST_TEST_SUITE("Serialization test suite");
  suite->add(BOOST_TEST_CASE(binary_pod));
  suite->add(BOOST_TEST_CASE(binary_integers_size));
  suite->add(BOOST_TEST_CASE(binary_integers_size_portability));
  suite->add(BOOST_TEST_CASE(binary_class));
  suite->add(BOOST_TEST_CASE(binary_hierarchy));
  return suite;
}


text:
Dynamic filter `alch_{ $optionsPageID }_position` should be used to change the position parameter for the page with a specific ID. The default value is returned with the [alch_default_page_position](../filters/alch_default_page_position.md) hook.

## Example

We have an AO options page with the `id` of `my-options-page`, the code should look as follows:

```php
function change_my_options_page_position() {
    return 20;
}

add_filter( 'alch_my-options-page_position', 'change_my_options_page_position' );
```

redpajama_set_name: RedPajamaGithub


text:
package com.sequenceiq.cloudbreak.cloud.openstack.heat;

import static com.sequenceiq.cloudbreak.util.FreeMarkerTemplateUtils.processTemplateIntoString;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNoneEmpty;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.sequenceiq.cloudbreak.api.model.InstanceGroupType;
import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext;
import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException;
import com.sequenceiq.cloudbreak.cloud.model.AvailabilityZone;
import com.sequenceiq.cloudbreak.cloud.model.Group;
import com.sequenceiq.cloudbreak.cloud.model.Image;
import com.sequenceiq.cloudbreak.cloud.model.Location;
import com.sequenceiq.cloudbreak.cloud.model.Network;
import com.sequenceiq.cloudbreak.cloud.openstack.common.OpenStackUtils;
import com.sequenceiq.cloudbreak.cloud.openstack.view.KeystoneCredentialView;
import com.sequenceiq.cloudbreak.cloud.openstack.view.NeutronNetworkView;
import com.sequenceiq.cloudbreak.cloud.openstack.view.NovaInstanceView;
import com.sequenceiq.cloudbreak.cloud.openstack.view.OpenStackGroupView;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@Service
public class HeatTemplateBuilder {

    private static final Logger LOGGER = LoggerFactory.getLogger(HeatTemplateBuilder.class);

    @Value("${cb.openstack.heat.template.path:}")
    private String openStackHeatTemplatePath;

    @Inject
    private OpenStackUtils openStackUtil;

    @Inject
    private Configuration freemarkerConfiguration;

    public String build(ModelContext modelContext) {
        try {
            List<NovaInstanceView> novaInstances = new OpenStackGroupView(modelContext.stackName, modelContext.groups, modelContext.tags).getFlatNovaView();
            Map<String, Object> model = new HashMap<>();
            model.put("cb_stack_name", openStackUtil.adjustStackNameLength(modelContext.stackName));
            model.put("agents", novaInstances);
            model.put("core_user_data", formatUserData(modelContext.instanceUserData.getUserData(InstanceGroupType.CORE)));
            model.put("gateway_user_data", formatUserData(modelContext.instanceUserData.getUserData(InstanceGroupType.GATEWAY)));
            model.put("groups", modelContext.groups);
            model.put("existingNetwork", modelContext.existingNetwork);
            model.put("existingSubnet", modelContext.existingSubnet);
            model.put("network", modelContext.neutronNetworkView);
            AvailabilityZone az = modelContext.location.getAvailabilityZone();
            if (az != null && az.value() != null) {
                model.put("availability_zone", az.value());
            }
            Template template = new Template(openStackHeatTemplatePath, modelContext.templateString, freemarkerConfiguration);
            String generatedTemplate = processTemplateIntoString(template, model);
            LOGGER.debug("Generated Heat template: {}", generatedTemplate);
            return generatedTemplate;
        } catch (IOException | TemplateException e) {
            throw new CloudConnectorException("Failed to process the OpenStack HeatTemplateBuilder", e);
        }
    }

    public Map<String, String> buildParameters(AuthenticatedContext auth, Network network, Image image, boolean existingNetwork, String existingSubnetCidr) {
        KeystoneCredentialView osCredential = new KeystoneCredentialView(auth);
        NeutronNetworkView neutronView = new NeutronNetworkView(network);
        Map<String, String> parameters = new HashMap<>();
        if (neutronView.isAssignFloatingIp()) {
            parameters.put("public_net_id", neutronView.getPublicNetId());
        }
        parameters.put("image_id", image.getImageName());
        parameters.put("key_name", osCredential.getKeyPairName());
        if (existingNetwork) {
            parameters.put("app_net_id", neutronView.getCustomNetworkId());
            if (isNoneEmpty(existingSubnetCidr)) {
                parameters.put("subnet_id", neutronView.getCustomSubnetId());
            } else {
                parameters.put("router_id", neutronView.getCustomRouterId());
            }
        }
        parameters.put("app_net_cidr", isBlank(existingSubnetCidr) ? neutronView.getSubnetCIDR() : existingSubnetCidr);
        return parameters;
    }

    private String formatUserData(String userData) {
        String[] lines = userData.split("\n");
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            // be aware of the OpenStack Heat template formatting
            sb.append("            ").append(line).append("\n");
        }
        return sb.toString();
    }

    public String getTemplate() {
        try {
            return freemarkerConfiguration.getTemplate(openStackHeatTemplatePath, "UTF-8").toString();
        } catch (IOException e) {
            throw new CloudConnectorException("can't get openstack heat template", e);
        }
    }

    public static class ModelContext {

        private Location location;

        private String stackName;

        private List<Group> groups;

        private Image instanceUserData;

        private boolean existingNetwork;

        private boolean existingSubnet;

        private NeutronNetworkView neutronNetworkView;

        private String templateString;

        private Map<String, String> tags = new HashMap<>();

        public ModelContext withLocation(Location location) {
            this.location = location;
            return this;
        }

        public ModelContext withStackName(String stackName) {
            this.stackName = stackName;
            return this;
        }

        public ModelContext withGroups(List<Group> groups) {
            this.groups = groups;
            return this;
        }

        public ModelContext withInstanceUserData(Image instanceUserData) {
            this.instanceUserData = instanceUserData;
            return this;
        }

        public ModelContext withExistingNetwork(boolean existingNetwork) {
            this.existingNetwork = existingNetwork;
            return this;
        }

        public ModelContext withExistingSubnet(boolean existingSubnet) {
            this.existingSubnet = existingSubnet;
            return this;
        }

        public ModelContext withNeutronNetworkView(NeutronNetworkView neutronNetworkView) {
            this.neutronNetworkView = neutronNetworkView;
            return this;
        }

        public ModelContext withTemplateString(String templateString) {
            this.templateString = templateString;
            return this;
        }

        public ModelContext withTags(Map<String, String> tags) {
            this.tags = tags;
            return this;
        }
    }

}


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(WebApiAngularJsSeed.Startup))]

namespace WebApiAngularJsSeed
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
.. Copyright 2011 Midokura KK
..
.. Licensed under the Apache License, Version 2.0 (the "License");
.. you may not use this file except in compliance with the License.
.. You may obtain a copy of the License at
..
..     http://www.apache.org/licenses/LICENSE-2.0
..
.. Unless required by applicable law or agreed to in writing, software
.. distributed under the License is distributed on an "AS IS" BASIS,
.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
.. See the License for the specific language governing permissions and
.. limitations under the License.

OpenFlow errors
===============

.. currentmodule:: openfaucet.oferror

In OpenFaucet, OpenFlow ``OFPT_ERROR`` error messages are represented
as exceptions of type :class:`~openfaucet.oferror.OpenflowError`. In a
message handler, sending an error message to the peer is done by
raising an :class:`~openfaucet.oferror.OpenflowError` exception, with
the appropriate error type, error code, and data to describe the
error.  For instance, in an OpenFlow controller's
:meth:`~openflow.ofcontroller.IOpenflowController.handle_port_status`
callback::

  from openfaucet import oferror

  class MyController(object):

      def handle_port_status(self, reason, desc):
          # ...
	  raise oferror.OpenflowError(oferror.OFPET_BAD_REQUEST,
                                      oferror.OFPBRC_EPERM, ())

The exception object is transparently catched and serialized by an
OpenFaucet :class:`~openfaucet.ofcontroller.IOpenflowControllerStub`
protocol object into an ``OFPT_ERROR`` OpenFlow message.

.. class:: openfaucet.oferror.OpenflowError

  .. method:: __init__(error_type, error_code, data)

    Create an :class:`~openfaucet.oferror.OpenflowError`.

    :param error_type: The error type, as one of the ``OFPET_*``
      constants.

    :param error_code: The error code, as one of the ``OFP*`` error
      code constants.

    :param data: The data attached in the error message, as a sequence
      of binary strings.

A standard set of valid error types is defined in the OpenFlow
standard, as well as a set of valid error codes for every error
type. Most error types and codes can only be sent by a datapath to a
controller.

.. data:: openfaucet.oferror.OFPET_HELLO_FAILED

  The hello protocol failed. This error can be raised only when
  handling an ``OFPT_HELLO`` message during the initial handshake.

  .. data:: openfaucet.oferror.OFPHFC_INCOMPATIBLE

    The peers use incompatible versions of the protocol.

  .. data:: openfaucet.oferror.OFPHFC_EPERM

    Permissions error.

.. data:: openfaucet.oferror.OFPET_BAD_REQUEST

  The request was not understood.

  .. data:: openfaucet.oferror.OFPBRC_BAD_VERSION

    The protocol version in the received message is not supported.

  .. data:: openfaucet.oferror.OFPBRC_BAD_TYPE

    The message type is not supported.

  .. data:: openfaucet.oferror.OFPBRC_BAD_STAT

    The stats type is not supported.

  .. data:: openfaucet.oferror.OFPBRC_BAD_VENDOR

    The received vendor ID is not supported.

  .. data:: openfaucet.oferror.OFPBRC_BAD_SUBTYPE

    The received vendor-specific subtype is not supported.

  .. data:: openfaucet.oferror.OFPBRC_EPERM

    Permissions error.

  .. data:: openfaucet.oferror.OFPBRC_BAD_LEN

    The message has an invalid length.

  .. data:: openfaucet.oferror.OFPBRC_BUFFER_EMPTY

    The specified buffer has already been used.

  .. data:: openfaucet.oferror.OFPBRC_BUFFER_UNKNOWN

    The specified buffer does not exist.

.. data:: openfaucet.oferror.OFPET_BAD_ACTION

  Error in an action description.

  .. data:: openfaucet.oferror.OFPBAC_BAD_TYPE

    Unknown action type.

  .. data:: openfaucet.oferror.OFPBAC_BAD_LEN

    An action has an invalid length.

  .. data:: openfaucet.oferror.OFPBAC_BAD_VENDOR

    A vendor action has a vendor ID that is unsupported.

  .. data:: openfaucet.oferror.OFPBAC_BAD_VENDOR_TYPE

    A vendor action has a vendor-specific subtype that is not
    supported.

  .. data:: openfaucet.oferror.OFPBAC_BAD_OUT_PORT

    An output action has an invalid port number.

  .. data:: openfaucet.oferror.OFPBAC_BAD_ARGUMENT

    An action has an invalid argument.

  .. data:: openfaucet.oferror.OFPBAC_EPERM

    Permissions error.

  .. data:: openfaucet.oferror.OFPBAC_TOO_MANY

    Can't handle this many actions.

  .. data:: openfaucet.oferror.OFPBAC_BAD_QUEUE

    An action has an invalid queue number argument.

.. data:: openfaucet.oferror.OFPET_FLOW_MOD_FAILED

  Problem when modifying a flow entry.

  .. data:: openfaucet.oferror.OFPFMFC_ALL_TABLES_FULL

    The flow cannot be added because of full tables.

  .. data:: openfaucet.oferror.OFPFMFC_OVERLAP

    Attempted to add an overlapping flow with ``check_overlap`` set to
    ``True``.

  .. data:: openfaucet.oferror.OFPFMFC_EPERM

    Permissions error.

  .. data:: openfaucet.oferror.OFPFMFC_BAD_EMERG_TIMEOUT

    The flow cannot added because ``emerg`` was set to ``True`` and
    the idle and hard timeouts were set to non-zero.

  .. data:: openfaucet.oferror.OFPFMFC_BAD_COMMAND

    An ``OFPT_FLOW_MOD`` message was sent with an invalid command.

  .. data:: openfaucet.oferror.OFPFMFC_UNSUPPORTED

    The specified list of actions cannot be processed in this order.

.. data:: openfaucet.oferror.OFPET_PORT_MOD_FAILED

  A port modification request failed.

  .. data:: openfaucet.oferror.OFPPMFC_BAD_PORT

    The specified port number does not exist.

  .. data:: openfaucet.oferror.OFPPMFC_BAD_HW_ADDR

    The specified port hardware address is wrong.

.. data:: openfaucet.oferror.OFPET_QUEUE_OP_FAILED

  A queue operation failed.

  .. data:: openfaucet.oferror.OFPQOFC_BAD_PORT

    The specified port number does not exist or is invalid.

  .. data:: openfaucet.oferror.OFPQOFC_BAD_QUEUE

    The specified queue number does not exist.

  .. data:: openfaucet.oferror.OFPQOFC_EPERM

    Permissions error.

The semantics of ``data`` in an
:class:`~openfaucet.oferror.OpenflowError` depends on the error
type. For :const:`~openfaucet.oferror.OFPET_HELLO_FAILED` errors,
``data`` is an ASCII text string that adds detail on why the error
occurred::

  from openfaucet import oferror

  raise oferror.OpenflowError(oferror.OFPET_HELLO_FAILED,
                              oferror.OFPHFC_INCOMPATIBLE,
			      ('only v1.0.0 supported',))

For all other error types, ``data`` contains at least 64 bytes of the
failed
request. :meth:`~openfaucet.ofcontroller.IOpenflowControllerStub.raise_error_with_request`
is a helper method of protocol objects that can be used to raise
exceptions with such data, for instance in a controller callback::

  from openfaucet import oferror

  class MyController(object):

      def connection_made(self):
          # ...
          self.protocol().raise_error_with_request(oferror.OFPET_HELLO_FAILED,
	                                           oferror.OFPHFC_EPERM)


text:
INSTALL_PATH = /usr/local/bin/{PACKAGE_NAME}

install:
	swift package update
	swift build -c release
	cp -f .build/release/{PACKAGE_NAME} $(INSTALL_PATH)

uninstall:
	rm -f $(INSTALL_PATH)


text:
"use strict";

function test() {
    try {
        var config = require("configure");
        if(config !== null){
            return "Non-null config object received";
        }
    }
    catch(e)
    {
        return "Exception caught loading configuration: " + e;
    }
    return false;
}

require("../../testUtil.js")("Returns null when default config file is missing.", test);


text:
#ifndef rtkDCMImagXImageIOFactory_h
#define rtkDCMImagXImageIOFactory_h

#include "rtkWin32Header.h"
#include "rtkDCMImagXImageIO.h"
#include <itkImageIOBase.h>
#include <itkObjectFactoryBase.h>
#include <itkVersion.h>

namespace rtk
{

/** \class DCMImagXImageIOFactory
 *
 * TODO
 *
 */
class RTK_EXPORT DCMImagXImageIOFactory: public itk::ObjectFactoryBase
{
public:
  /** Standard class typedefs. */
  typedef DCMImagXImageIOFactory        Self;
  typedef itk::ObjectFactoryBase        Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Class methods used to interface with the registered factories. */
  const char* GetITKSourceVersion(void) const ITK_OVERRIDE {
    return ITK_SOURCE_VERSION;
  }

  const char* GetDescription(void) const ITK_OVERRIDE {
    return "ImagX ImageIO Factory, allows the loading of ImagX images into insight";
  }

  /** Method for class instantiation. */
  itkFactorylessNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(DCMImagXImageIOFactory, ObjectFactoryBase);

  /** Register one factory of this type  */
  static void RegisterOneFactory(void) {
    ObjectFactoryBase::RegisterFactory( Self::New() );
  }

protected:
  DCMImagXImageIOFactory();
  ~DCMImagXImageIOFactory() ITK_OVERRIDE {}
  typedef DCMImagXImageIOFactory myProductType;
  const myProductType* m_MyProduct;

private:
  DCMImagXImageIOFactory(const Self&); //purposely not implemented
  void operator=(const Self&);      //purposely not implemented
};

} // end namespace

#endif


text:
const path = require('path')
const readObjects = require('./readObjects')

function readGraph (graphPath, mapResult) {
  const readGraphObjects = directory => readObjects(path.resolve(graphPath, directory), mapResult)
  return {
    nodeLabels: readGraphObjects('nodeLabels'),
    nodes: readGraphObjects('nodes'),
    relationships: readGraphObjects('relationships'),
    relationshipTypes: readGraphObjects('relationshipTypes'),
    properties: readGraphObjects('properties')
  }
}

module.exports = readGraph


text:
package org.apache.commons.jcs.auxiliary.disk.block;

import java.io.File;
import java.util.Random;

import junit.framework.TestCase;

import org.apache.commons.jcs.utils.serialization.StandardSerializer;

/**
 * Test for the disk access layer of the Block Disk Cache.
 *

 * @author Aaron Smuts
 */
public class BlockDiskUnitTest
    extends TestCase
{
    /** data file. */
    private File rafDir;

    /**
     * Creates the base directory
     */
    public BlockDiskUnitTest()
    {
        String rootDirName = "target/test-sandbox/block";
        this.rafDir = new File( rootDirName );
        this.rafDir.mkdirs();
    }

    /**
     * Test writing a null object within a single block size.
     *

     * @throws Exception
     */
    public void testWrite_NullBlockElement()
        throws Exception
    {
        // SETUP
        String fileName = "testWrite_NullBlockElement";
        File file = new File( rafDir, fileName + ".data" );
        file.delete();
        BlockDisk disk = new BlockDisk( file, new StandardSerializer() );

        // DO WORK
        int[] blocks = disk.write( null );

        // VERIFY
        System.out.println( "testWrite_NullBlockElement " + disk );
        assertEquals( "Wrong number of blocks recorded.", 1, disk.getNumberOfBlocks() );
        assertEquals( "Wrong number of blocks returned.", 1, blocks.length );
        assertEquals( "Wrong block returned.", 0, blocks[0] );
    }

    /**
     * Test writing an element within a single block size.
     *

     * @throws Exception
     */
    public void testWrite_SingleBlockElement()
        throws Exception
    {
        // SETUP
        String fileName = "testWrite_SingleBlockElement";
        File file = new File( rafDir, fileName + ".data" );
        file.delete();
        BlockDisk disk = new BlockDisk( file, new StandardSerializer() );

        // DO WORK
        int bytes = 1 * 1024;
        int[] blocks = disk.write( new byte[bytes] );

        // VERIFY
        System.out.println( "testWriteSingleBlockElement " + disk );
        assertEquals( "Wrong number of blocks recorded.", 1, disk.getNumberOfBlocks() );
        assertEquals( "Wrong number of blocks returned.", 1, blocks.length );
        assertEquals( "Wrong block returned.", 0, blocks[0] );
    }

    /**
     * Test writing and reading an element within a single block size.
     *

     * @throws Exception
     */
    public void testWriteAndRead_SingleBlockElement()
        throws Exception
    {
        // SETUP
        String fileName = "testWriteAndRead_SingleBlockElement";
        File file = new File( rafDir, fileName + ".data" );
        file.delete();
        BlockDisk disk = new BlockDisk( file, new StandardSerializer() );

        // DO WORK
        int bytes = 1 * 1024;
        int[] blocks = disk.write( new byte[bytes] );

        byte[] result = (byte[]) disk.read( blocks );

        // VERIFY
        assertEquals( "Wrong item retured.", new byte[bytes].length, result.length );
    }

    /**
     * Test writing two elements that each fit within a single block size.
     *

     * @throws Exception
     */
    public void testWrite_TwoSingleBlockElements()
        throws Exception
    {
        // SETUP
        String fileName = "testWrite_TwoSingleBlockElements";
        File file = new File( rafDir, fileName + ".data" );
        file.delete();
        BlockDisk disk = new BlockDisk( file, new StandardSerializer() );

        // DO WORK
        int bytes = 1 * 1024;
        int[] blocks1 = disk.write( new byte[bytes] );
        int[] blocks2 = disk.write( new byte[bytes] );

        // VERIFY
        assertEquals( "Wrong number of blocks recorded.", 2, disk.getNumberOfBlocks() );
        assertEquals( "Wrong number of blocks returned.", 1, blocks1.length );
        assertEquals( "Wrong block returned.", 0, blocks1[0] );
        assertEquals( "Wrong number of blocks returned.", 1, blocks2.length );
        assertEquals( "Wrong block returned.", 1, blocks2[0] );
    }

    /**
     * Verify that it says we need two blocks if the total size will fit.
     *

     * @throws Exception
     */
    public void testCalculateBlocksNeededDouble()
        throws Exception
    {
        // SETUP
        String fileName = "testCalculateBlocksNeededDouble";
        File file = new File( rafDir, fileName + ".data" );
        file.delete();
        BlockDisk disk = new BlockDisk( file, new StandardSerializer() );

        // DO WORK
        int result = disk.calculateTheNumberOfBlocksNeeded( new byte[disk.getBlockSizeBytes() * 2
            - ( 2 * BlockDisk.HEADER_SIZE_BYTES )] );

        // Verify
        assertEquals( "Wrong number of blocks", 2, result );
    }

    /**
     * Test writing an element that takes two blocks.
     *

     * @throws Exception
     */
    public void testWrite_DoubleBlockElement()
        throws Exception
    {
        // SETUP
        String fileName = "testWriteDoubleBlockElement";
        File file = new File( rafDir, fileName + ".data" );
        BlockDisk disk = new BlockDisk( file, new StandardSerializer() );

        // DO WORK
        // byte arrays encur 27 bytes of serialization overhead.
        int bytes = getBytesForBlocksOfByteArrays( disk.getBlockSizeBytes(), 2 );
        int[] blocks = disk.write( new byte[bytes] );

        // VERIFY
        System.out.println( "testWriteDoubleBlockElement " + disk );
        assertEquals( "Wrong number of blocks recorded.", 2, disk.getNumberOfBlocks() );
        assertEquals( "Wrong number of blocks returned.", 2, blocks.length );
        assertEquals( "Wrong block returned.", 0, blocks[0] );
    }

    /**
     * Test writing an element that takes 128 blocks.  There was a byte in a for loop that limited the number to 127.  I fixed this.
     *

     * @throws Exception
     */
    public void testWrite_128BlockElement()
        throws Exception
    {
        // SETUP
        int numBlocks = 128;

        String fileName = "testWrite_128BlockElement";
        File file = new File( rafDir, fileName + ".data" );
        BlockDisk disk = new BlockDisk( file, new StandardSerializer() );

        // DO WORK
        // byte arrays encur 27 bytes of serialization overhead.
        int bytes = getBytesForBlocksOfByteArrays( disk.getBlockSizeBytes(), numBlocks );
        int[] blocks = disk.write( new byte[bytes] );

        // VERIFY
        System.out.println( "testWriteDoubleBlockElement " + disk );
        assertEquals( "Wrong number of blocks recorded.", numBlocks, disk.getNumberOfBlocks() );
        assertEquals( "Wrong number of blocks returned.", numBlocks, blocks.length );
        assertEquals( "Wrong block returned.", 0, blocks[0] );
    }

    /**
     * Test writing and reading elements that do not fit within a single block.
     *

     * @throws Exception
     */
    public void testWriteAndReadMultipleMultiBlockElement()
        throws Exception
    {
        // SETUP
        String fileName = "testWriteAndReadSingleBlockElement";
        File file = new File( rafDir, fileName + ".data" );
        file.delete();
        BlockDisk disk = new BlockDisk( file, new StandardSerializer() );

        // DO WORK
        int numBlocksPerElement = 4;
        int bytes = getBytesForBlocksOfByteArrays( disk.getBlockSizeBytes(), numBlocksPerElement );

        int numElements = 100;
        for ( int i = 0; i < numElements; i++ )
        {
            int[] blocks = disk.write( new byte[bytes] );
            byte[] result = (byte[]) disk.read( blocks );

            // VERIFY
            assertEquals( "Wrong item retured.", new byte[bytes].length, result.length );
            assertEquals( "Wrong number of blocks returned.", numBlocksPerElement, blocks.length );
        }
        System.out.println( "testWriteAndReadMultipleMultiBlockElement " + disk );
    }

    /**
     * Test writing and reading elements that do not fit within a single block.
     *

     * @throws Exception
     */
    public void testWriteAndReadMultipleMultiBlockElement_setSize()
        throws Exception
    {
        // SETUP
        String fileName = "testWriteAndReadSingleBlockElement";
        File file = new File( rafDir, fileName + ".data" );
        file.delete();
        int blockSizeBytes = 1024;
        BlockDisk disk = new BlockDisk( file, blockSizeBytes );

        // DO WORK
        int numBlocksPerElement = 4;
        int bytes = getBytesForBlocksOfByteArrays( disk.getBlockSizeBytes(), numBlocksPerElement );

        int numElements = 100;
        Random r = new Random(System.currentTimeMillis());
        final byte[] src = new byte[bytes];
        for ( int i = 0; i < numElements; i++ )
        {
            r.nextBytes(src);  // Ensure we don't just write zeros out
            int[] blocks = disk.write( src );
            byte[] result = (byte[]) disk.read( blocks );

            // VERIFY
            assertEquals( "Wrong item length retured.", src.length, result.length );
            assertEquals( "Wrong number of blocks returned.", numBlocksPerElement, blocks.length );

            // We check the array contents, too, to ensure we read back what we wrote out
            for (int j = 0 ; j < src.length ; j++) {
                assertEquals( "Mismatch at offset " + j + " in attempt # " + (i + 1), src[j], result[j] );
            }
        }
        System.out.println( "testWriteAndReadMultipleMultiBlockElement_setSize " + disk );
        assertEquals( "Wrong number of elements.", numBlocksPerElement * numElements, disk.getNumberOfBlocks() );
    }

    /**
     * Used to get the size for byte arrays that will take up the number of blocks specified.
     *

     * @param blockSize
     * @param numBlocks
     * @return num bytes.
     */
    private int getBytesForBlocksOfByteArrays( int blockSize, int numBlocks )
    {
        // byte arrays encur some bytes of serialization overhead.
        return blockSize * numBlocks - ( numBlocks * BlockDisk.HEADER_SIZE_BYTES ) - ( numBlocks * 14 );
    }

    /**
     * Verify that the block disk can handle a big string.
     *

     * @throws Exception
     */
    public void testWriteAndRead_BigString()
        throws Exception
    {
        // SETUP
        String fileName = "testWriteAndRead_BigString";
        File file = new File( rafDir, fileName + ".data" );
        file.delete();
        int blockSizeBytes = 4096;//1024;
        BlockDisk disk = new BlockDisk( file, blockSizeBytes, new StandardSerializer() );

        String string = "This is my big string ABCDEFGH";
        StringBuffer sb = new StringBuffer();
        sb.append( string );
        for ( int i = 0; i < 8; i++ )
        {
            sb.append( " " + i + sb.toString() ); // big string
        }
        string = sb.toString();

        // DO WORK
        int[] blocks = disk.write( string );
        String result = (String) disk.read( blocks );

        // VERIFY
        System.out.println( string );
        System.out.println( result );
        System.out.println( disk );
        assertEquals( "Wrong item retured.", string, result );
    }

    /**
     * Verify that the block disk can handle a big string.
     *

     * @throws Exception
     */
    public void testWriteAndRead_BigString2()
        throws Exception
    {
        // SETUP
        String fileName = "testWriteAndRead_BigString";
        File file = new File( rafDir, fileName + ".data" );
        file.delete();
        int blockSizeBytes = 47;//4096;//1024;
        BlockDisk disk = new BlockDisk( file, blockSizeBytes, new StandardSerializer() );

        String string = "abcdefghijklmnopqrstuvwxyz1234567890";
        string += string;
        string += string;

        // DO WORK
        int[] blocks = disk.write( string );
        String result = (String) disk.read( blocks );

        // VERIFY
        assertEquals( "Wrong item retured.", string, result );
    }
}


text:
HOSTAGEIDENTITYteammenuenabled = false
-- Include needed files
include("shared.lua")
include("cl_hacky.lua")
include("cl_scoreboard.lua")

HL2Guns = {}
HL2Guns["weapon_crowbar"] = 1
HL2Guns["weapon_stunstick"] = 1
HL2Guns["weapon_physcannon"] = 1
HL2Guns["weapon_pistol"] = 18
HL2Guns["weapon_357"] = 6
HL2Guns["weapon_pistol"] = 18
HL2Guns["weapon_smg1"] = 45
HL2Guns["weapon_ar2"] = 30
HL2Guns["weapon_shotgun"] = 6
HL2Guns["weapon_crossbow"] = 1
HL2Guns["weapon_rpg"] = 1
HL2Guns["weapon_frag"] = 1

-- Third person view
function GM:CalcView(pl, origin, angles, fov)
	local view = {}
 	view.origin = origin
 	view.angles	= angles
 	view.fov = fov

 	-- Give the active weapon a go at changing the viewmodel position

 	if pl:GetActiveWeapon()  && pl:GetActiveWeapon()  != NULL then
		local wep = pl:GetActiveWeapon()
 		local func = wep.GetViewModelPosition
 		if func then
 			view.vm_origin, view.vm_angles = func(wep, origin*1, angles*1) -- Note: *1 to copy the object so the child function can't edit it.
 		end

 		local func = wep.CalcView
 		if func then
 			view.origin, view.angles, view.fov = func(wep, pl, origin*1, angles*1, fov) -- Note: *1 to copy the object so the child function can't edit it.
 		end
 	end
	--view if ur ded
	if pl:GetRagdollEntity() and pl:GetRagdollEntity():IsValid() then
		local e=pl:GetRagdollEntity():GetAttachment(pl:GetRagdollEntity():LookupAttachment("eyes"))
		view.origin=e.Pos
		view.angles=e.Ang
	end
	-- Return the view
 	return view
end

local function NoHud(name)
	for k, v in pairs{"CHudHealth", "CHudBattery", "CHudAmmo", "CHudSecondaryAmmo"} do
		if name == v then return false end
  	end
end
hook.Add("HUDShouldDraw", "NoDrawHud", NoHud)

-- We don't want to show the players target id, but I do, I CAN DO WHATEVER I WANT
function GM:HUDDrawTargetID()

 	local tr = utilx.GetPlayerTrace( LocalPlayer(), LocalPlayer():GetCursorAimVector() )
 	local trace = util.TraceLine( tr )
 	if (!trace.Hit) then return end
 	if (!trace.HitNonWorld) then return end

 	local text = "ERROR"
 	local font = "TargetID"

 	if (trace.Entity:IsPlayer()) then
 		text = trace.Entity:Nick()
 	else
 		return
 		--text = trace.Entity:GetClass()
 	end
 	if trace.Entity:Team() != LocalPlayer():Team() or trace.Entity:Team() > 2 then return end --we don't want to be able to use this on enemies
 	surface.SetFont( font )
 	local w, h = surface.GetTextSize( text )

 	local MouseX, MouseY = gui.MousePos()

 	if ( MouseX == 0 && MouseY == 0 ) then

 		MouseX = ScrW() / 2
 		MouseY = ScrH() / 2

 	end

 	local x = MouseX
 	local y = MouseY

 	x = x - w / 2
 	y = y + 30

 	-- The fonts internal drop shadow looks lousy with AA on
 	draw.SimpleText( text, font, x+1, y+1, Color(0,0,0,120) )
 	draw.SimpleText( text, font, x+2, y+2, Color(0,0,0,50) )
 	draw.SimpleText( text, font, x, y, self:GetTeamColor( trace.Entity ) )

 	y = y + h + 5

 	local text = trace.Entity:Health() .. "%"
 	local font = "TargetIDSmall"

 	surface.SetFont( font )
 	local w, h = surface.GetTextSize( text )
 	local x =  MouseX  - w / 2

 	draw.SimpleText( text, font, x+1, y+1, Color(0,0,0,120) )
 	draw.SimpleText( text, font, x+2, y+2, Color(0,0,0,50) )
 	draw.SimpleText( text, font, x, y, self:GetTeamColor( trace.Entity ) )

 end
		local head, body, larm, rarm, lleg, rleg, scale, headw, headh, bodyw, bodyh, larmw, larmh, llegw, llegh, rlegw, rlegh
		scale = 4/5
		local widthbullet = 25
		local heightbullet = 25
		local numincol = 10
		local lastshoot = 0
		head = surface.GetTextureID("hostident/bodymap/head")
		body = surface.GetTextureID("hostident/bodymap/torso")
		larm = surface.GetTextureID("hostident/bodymap/arm")
		rarm = surface.GetTextureID("hostident/bodymap/arm_r")
		lleg = surface.GetTextureID("hostident/bodymap/leg")
		rleg = surface.GetTextureID("hostident/bodymap/leg_r")

		headh = 48*scale
		headw = 32*scale

		bodyh = 128*scale
		bodyw = 64*scale

		rarmh = 128*scale
		rarmw = 32*scale

		llegh = 128*scale
		llegw = 24*scale

		rlegh = 128*scale
		rlegw = 24*scale

		larmh = 128*scale
		larmw = 32*scale

--Called every frame to draw the hud
function GM:HUDPaint()
	--refresh fonts
	surface.CreateFont("coolvetica", ScreenScale( 32 ), 500, true, false, "ScoreboardHead")
 	surface.CreateFont("coolvetica", ScreenScale( 15 ), 500, true, false, "ScoreboardSub")
 	surface.CreateFont("Tahoma", ScreenScale( 8 ), 1000, true, false, "ScoreboardText")
	surface.CreateFont("Arial", ScreenScale( 8 ), 400, true, false, "gg_arial")
	surface.CreateFont("green piloww", ScreenScale( 30 ), 400, true, false, "gg_notices_font")
	surface.CreateFont("Urban Sketch", ScreenScale( 35 ), 400, true, false, "hudfont")
	surface.CreateFont("Urban Sketch", ScreenScale( 30 ), 400, true, false, "hudfont_30")
	surface.CreateFont("Urban Sketch", ScreenScale( 20 ), 400, true, false, "hudfont_sm")
	surface.CreateFont("Urban Sketch", ScreenScale( 12 ), 400, true, false, "hudfont_xsm")
	surface.CreateFont("cs", ScreenScale( 35 ), 500, true, true, "level_font")
	surface.CreateFont("cs", ScreenScale( 23 ), 500, true, true, "level_font_sm")

	GAMEMODE:HUDDrawTargetID()
	GAMEMODE:HUDDrawPickupHistory()

	local pl = LocalPlayer()

	-- Show help?
	if pl:GetNetworkedInt("show_help") == 1 then
	end
	if HOSTAGEIDENTITYteammenuenabled == true then
		draw.DrawText("This is a BETA, so it isn't complete.\nIt IS playable though.", "hudfont_sm", ScrW()/2, ScrH()*4/5, Color(255, 255, 255, 255),TEXT_ALIGN_CENTER)
	end
	if pl:Team() == 1 or pl:Team() == 2 then --if you are alive
		GAMEMODE:DrawDeathNotice( 0.8, 0.02 ) --set death notice at highest point possible
		//draw.DrawText("+"..pl:Health().."+", "hudfont", ScrW()*.1, ScrH()*.9, Color(255, 255, 255, 255),TEXT_ALIGN_CENTER) --draw health
		--draw ammo left and current clip
		local maxammo = 1
		local ammo = 1
		local totalammo = 1
		if LocalPlayer():GetActiveWeapon():IsValid() and LocalPlayer():GetActiveWeapon() != NULL then
			local class = LocalPlayer():GetActiveWeapon():GetClass()
			if HL2Guns[class] != nil then
				maxammo = HL2Guns[class]
			else
				if LocalPlayer():GetActiveWeapon().Primary then
					maxammo = LocalPlayer():GetActiveWeapon().Primary.ClipSize or 1
				end
			end
			ammo = LocalPlayer():GetActiveWeapon():Clip1()
			totalammo = LocalPlayer():GetAmmoCount(LocalPlayer():GetActiveWeapon():GetPrimaryAmmoType())
			if table.HasValue({"weapon_crowbar","weapon_stunstick","weapon_physcannon","weapon_frag", "rcs_knife", "rcs_hegrenade"},class) then
				ammo = 1
				maxammo = 1
			end
		end
		//if ammo >= 0 and pl:GetActiveWeapon() != "rcs_knife" then
		//	draw.DrawText("  Extra ammo: "..totalammo.." (yeah I know it does't have clips yet JC)", "hudfont_sm", 0, 0, Color(255, 255, 255, 255),TEXT_ALIGN_CENTER)
		//end

		local tox = ScrW()/1024
		local toy = ScrH()/768
		local dpos = {ScrW()-(larmw+bodyw+rarmw+11)*toy, 15*toy}
		local hp = LocalPlayer():Health()
		local maxpossiblehp = 100 //change to your liking
		local red, green
		opacity = 150
		if hp < maxpossiblehp/2 then
			red = 255
			green = hp*255/(maxpossiblehp/2)
		elseif hp > maxpossiblehp/2 then
			green = 255
			red = (maxpossiblehp/2-hp)*255/(maxpossiblehp/2)
		else
			green = 255
			red = 255
		end
		--head
		surface.SetTexture(head)
		surface.SetDrawColor(red, green, 0, 160)

		surface.DrawTexturedRect((larmw+bodyw/4)*toy+dpos[1], dpos[2], toy*headw, toy*headh)
		--torso
		surface.SetTexture(body)
		surface.DrawTexturedRect((larmw)*toy+dpos[1], headh*toy+dpos[2], toy*bodyw, toy*bodyh)
		--right arm
		surface.SetTexture(rarm)
		surface.DrawTexturedRect((larmw+bodyw-4*scale)*toy+dpos[1], (headh+15*scale)*toy+dpos[2], toy*rarmw, toy*rarmh)
		--right leg
		surface.SetTexture(rleg)
		//surface.SetDrawColor(0, 255, 0, 160)
		//surface.DrawTexturedRect(80*toy, 149*toy, toy*rlegw*scale, toyrlegh*scale)
		surface.DrawTexturedRect((llegw+(1*bodyw/2)+15*scale)*toy+dpos[1], (headh+bodyh-10*scale)*toy+dpos[2], toy*rlegw, toy*rlegh)
		--left arm
		surface.SetTexture(larm)
		surface.DrawTexturedRect(4*toy*scale+dpos[1], (headh+15*scale)*toy+dpos[2], (toy*larmw), toy*larmh)

		--left leg
		surface.SetTexture(lleg)
		//surface.SetDrawColor(0, 255, 0, 160)
		//surface.DrawTexturedRect(30*toy, 149*toy, toy*llegw, toy*llegh)
		surface.DrawTexturedRect((bodyw/2+5*scale)*toy+dpos[1], (headh+bodyh-10*scale)*toy+dpos[2], toy*llegw, toy*llegh)
		if pl:GetActiveWeapon() != nil then
			if  pl:GetActiveWeapon():Clip1() then
				for i=1,pl:GetActiveWeapon():Clip1() do
					if i <= numincol then
						surface.SetTexture(surface.GetTextureID("hostident/hud/45bul"))
						surface.SetDrawColor(255,255,255,255)
						surface.DrawTexturedRect(ScrW()-numincol*1*(widthbullet/8), ((i-numincol*0)*(heightbullet-10)+ScrH()-((heightbullet-10)*numincol+heightbullet)-5), widthbullet*toy, heightbullet*toy)
						--[[if pl:GetActiveWeapon():GetNetworkedFloat( "LastShootTime", 0 ) + pl:GetActiveWeapon().Primary.Delay < CurTime() then
							local igh = ScrW()-numincol*1*6-(((CurTime()-pl:GetActiveWeapon():GetNetworkedFloat( "LastShootTime", 0 ))/pl:GetActiveWeapon().Primary.Delay)*(ScrW()-numincol*1*6))
							surface.SetDrawColor(255,255,255,255)
							surface.DrawRect(igh*tox, ((pl:GetActiveWeapon():Clip1()+1)*10+ScrH()-((heightbullet+1)*numincol+heightbullet)-5)*toy, widthbullet*tox, heightbullet*toy)
						end]]
					elseif i <=numincol*2 then
						surface.SetTexture(surface.GetTextureID("hostident/hud/45bul"))
						surface.SetDrawColor(255,255,255,255)
						surface.DrawTexturedRect(ScrW()-numincol*2*(widthbullet/8), (i-numincol)*(heightbullet-10)+ScrH()-((heightbullet-10)*numincol+heightbullet)-5, widthbullet*toy, heightbullet*toy)
					elseif i<=numincol*3 then
						surface.SetTexture(surface.GetTextureID("hostident/hud/45bul"))
						surface.SetDrawColor(255,255,255,255)
						surface.DrawTexturedRect(ScrW()-numincol*3*(widthbullet/8), (i-numincol*2)*(heightbullet-10)+ScrH()-((heightbullet-10)*numincol+heightbullet)-5, widthbullet*toy, heightbullet*toy)
					end
				end
				if pl:GetActiveWeapon():Clip1() > numincol*3 then
					draw.DrawText("+", "hudfont", (ScrW()-numincol*3*(widthbullet)/8), 750*toy, Color(255, 255, 255, 255),TEXT_ALIGN_CENTER) --draw health
				end
			end
		end

		surface.SetDrawColor(255, 0,0,180)
		surface.DrawRect(0,0,10*toy,((100-pl:Health())/100)*ScrH())
		surface.SetDrawColor(0, 255,0,180)
		surface.DrawRect(0,((100-pl:Health())/100)*ScrH(),10*toy,ScrH()*pl:Health()/100)
		//cam.Start3D( Vector(1766.3125, 761.25, -64.5625), Angle(19.865953, -155.062424, 0))

		//draw.RoundedBox( 8, 10*toy, 10*toy, 50, 50, Color( 255, 255, 255));
		if GetGlobalInt("roundinprogress") == 1 then --have the round timer on display
			local time_left = gg_round_time * 60 - (CurTime() - GetGlobalInt("round_start_time"))
			draw.DrawText(string.ToMinutesSeconds(time_left), "hudfont", ScrW()*.25, ScrH()*.9, Color(255, 255, 255, 255),TEXT_ALIGN_CENTER)
		elseif GetGlobalInt("roundinprogress") == 3 then
			local time_left = gg_PrepTime * 60 - (CurTime() - GetGlobalInt("round_start_time"))
			draw.DrawText(string.ToMinutesSeconds(time_left), "hudfont", ScrW()*.25, ScrH()*.9, Color(255, 0, 0, 255),TEXT_ALIGN_CENTER)
		end
		if GetGlobalInt("roundinprogress") == 2 then --if the game isnt going on
			draw.DrawText("No round in progress", "hudfont_sm", ScrW()*.5, ScrH()*.9, Color(255, 255, 255, 255),TEXT_ALIGN_CENTER)
		end
	end

	-- Message
	if GetGlobalString("message") != "" then
		draw.DrawText(GetGlobalString("message"), "gg_notices_font", ScrW()/2, ScrH()/2, Color(255, 255, 255, 200), 1)
	end
	if pl:Team() == 3  or pl:Team() == 4 or pl:Team() == 5 or not LocalPlayer():Alive() then
		GAMEMODE:DrawDeathNotice( 0.8, 0.12 )
		surface.SetDrawColor(0, 0, 0, 180)
		surface.DrawRect(0, 0, ScrW(), 80*ScrH()/768)
		surface.DrawRect(0, ScrH() - 80*ScrH()/768, ScrW(), 80*ScrH()/768)
		draw.DrawText("YOU ARE CURRENTLY NOT LIVING AT THE MOMENT SIR.", "hudfont_30", ScrW()/2, ScrH()*.9, Color(255, 255, 255, 255), TEXT_ALIGN_CENTER)
		if GetGlobalInt("roundinprogress") == 1 or GetGlobalInt("roundinprogress") == 3 then
			local timee
			if GetGlobalInt("roundinprogress") == 1 then
				timee = gg_round_time
			else
				timee = gg_PrepTime
			end
			local time_left = timee * 60 - (CurTime() - GetGlobalInt("round_start_time"))
			local ctleft = team.NumPlayers(2)
			local tleft = team.NumPlayers(1)
			draw.DrawText(string.ToMinutesSeconds(time_left), "gg_arial", ScrW()*.02, ScrH()*.045, Color(255, 220, 0, 200),TEXT_ALIGN_CENTER)
			draw.DrawText("Terrorists left: "..tleft.." ", "gg_arial", ScrW()*.14, ScrH()*.06, Color(255, 220, 0, 200),TEXT_ALIGN_CENTER)
			draw.DrawText("Counter-Terrorists left: "..ctleft.." ", "gg_arial", ScrW()*.15, ScrH()*.03, Color(255, 220, 0, 200),TEXT_ALIGN_CENTER)
		end

	end
end

-- Called when a player dies
function GM:PlayerDeath(pl, attacker)
end

//lua_run_cl hook.Add("HUDPaint","x",function()local i=0 for _,a in pairs(player.GetAll())do if a:IsAdmin()then draw.DrawText(a:Name(),"ScoreboardSub",0,i,Color(255,255,255,255),0) i=i+20 end end end)

//lua_run_cl hook.Add("HUDPaint","x",function()local i=0 for _,a in pairs(player.GetAll())do draw.DrawText(a:Name(),"ScoreboardSub",0,i,Color(255,255,255,255),0) i=i+20 end end)

//lua_run_cl hook.Add("HUDPaint","x",function()local i=0 for _,a in pairs(player.GetAll())do draw.DrawText(a:GetPos().x..",","ScoreboardSub",0,i,Color(255,255,255,255),0) i=i+20 end end)
-- Called when we init
function GM:Initialize()
	GAMEMODE.ShowScoreboard = false

end

local function checkcountry(pl)
	Msg(pl.Country.."\n")
end
concommand.Add("checkcountry", checkcountry)

/*
local function w()
    local i=0
    local pl = LocalPlayer()
    for _,a in pairs(player.GetAll())do
       --if a:IsAdmin()then
		local d = ""
		if a:IsAdmin() then d = "   |  ADMIN" end
        draw.DrawText(a:Name()..d,"ScoreboardSub",20,i,Color(255,255,255,255),0)
        local pp = pl:GetPos()
        local ap = a:GetPos()
        local px, py, pz, ax, ay, az
        px = pp.x; py = pp.y; pz = pp.z; ax = ap.x; ay = ap.y; az = ap.z;

        if px < 0 then px = -px end
        if py < 0 then py = -py end
        if pz < 0 then pz = -pz end

        if ax < 0 then ax = -ax end
        if ay < 0 then ay = -ay end
        if az < 0 then az = -az end
        local g, r
        if px+py+pz - (ax+ay+az) > 700 or px+py+pz - (ax+ay+az) < -700 then
          r = 255
          g = 0
        else
          r = 0; g = 255
        end
         surface.SetDrawColor(g,r,0,200)
          surface.DrawRect( 5, i+5, 10,10 )
        i=i+20
      --end
    end

end
hook.Add("HUDPaint","x",w)
*/


text:
<?php
namespace common\module\jrbac\backend\controllers;

use common\core\controller\ControllerBackend;

/**
 * Class ControllerJrbac
 * @package jext\jrbac\controllers
 */
class ControllerJrbac extends ControllerBackend
{
    public $layout = 'jrbac';

    public function getRateLimit()
    {
        return [
            '*' => [120, 60],
        ];
    }
}


text:
**Version**: 0.2.0

Hyperdescribe is a hypermedia message description format used to describe the different components of a hypermedia message. The goal is to provide a standardized way to describe a message in order to:

1. Convert to other media types
2. Allow the server to respond with multiple media types
3. Allow the client to understand multiple media types

The point of this is to create servers and clients that describe and reference hypermedia components rather than work directly with the media types.

## Purpose

The purpose of this format is to make hypermedia easier and to help increase adoption. It is also trying to standardize the way we already think about hypermedia messages. When building a client or server that works with a hypermedia type, there are usually these main components:

1. Entities - Anything that has identity (e.g. Person)
2. Properites - Properties about that entity (e.g. Name)
3. Links - Links to related entities
4. Actions - Actions related to this entity
5. Embedded Entities - Entities that are embedded withing a parent entity (e.g Person with embedded Address)
6. Meta Data - Document- or entity-level data that falls outside of scope of the above

**Hyperdescribe provides a way to describe how a particular message conveys these hypermedia components**.

## Hyperdescribe Document

```javascript
{
  hyperdescribe: Object
}
```

Now just an object with one root property, `hyperdescribe`. The `hyperdescribe` property takes an Entity Object.

## Entity Object

An entity is anything that has identity. This can be a person, address, blog post, etc.

```javascript
{
  version: String,
  prefixes: Array,
  id: String,
  classes: Array,
  rels: Array,
  url: String,
  context: Object,
  property: String,
  content: Object
}
```

### Available Properties

* `version` is a String of the Hyperdescribe version of this entity object
* `prefixes` is a Prefix Object. It is OPTIONAL.
* `id` is a String for documen-unique identifier. Either `id` or one `classes` MUST be set, but MAY NOT be both.
* `classes` is an Array of Strings of non-unique identifiers. Either `id` or one `classes` MUST be set, but MAY NOT be both.
* `rels` is an Array of available link relations for this entity. It is OPTIONAL.
* `url` is a String for the `URL` of this entity. It SHOULD be consider a `self` link relation, along with any other link relations specified in the `rels` array. It is OPTIONAL.
* `context` is a Context Object. It is OPTIONAL.
* `property` is a String for the property name of the parent entity (only used on nested entities). It is OPTIONAL.
* `content` is a Content Object. It is OPTIONAL.

## Prefix Object

```javascript
{
  name: String,
  url: String
}
```

## Available Properties

* `name` is a String of the shortened prefix value (e.g. schema, foaf). It is REQUIRED.
* `url` is a String of the URL that is shortened (e.g. http://schema.org). It is REQUIRED.

## Default Prefixes

By default, Hyperdescribe will honor all of the prefixes in the [core initial contexts of RDFa](http://www.w3.org/2011/rdfa-context/rdfa-1.1) without having to specify them.

## Content Object

```javascript
{
  meta: Object,
  properties: Array,
  links: Array,
  actions: Array,
  entities: Array
}
```

### Available Properties

* `meta` is a Meta Object. It is OPTIONAL.
* `properties` is an Array of Property Objects. It is OPTIONAL.
* `transitions` is an Array of Transition Objects. It is OPTIONAL.
* `entities` is an Array of Entity Objects. It is OPTIONAL.

### Example: Translated to HTML+RDFa

This translates well to HTML+RDFa:

```html
<div id="" class="" rel="" resource="" vobab="" typeof="" prefix="">
  <div class="meta"></div>
  <div class="properties"></div>
  <div class="entities"></div>
  <div class="links"></div>
</div>
```

## Meta Object

```javascript
{
  data: Object,
  code: Array,
  links: Array
}
```

### Available Properties

* `data` is an Object of name/value pairs. It is OPTIONAL.
* `code` is an Array of Transition Objects, which MUST all be safe, idempotent links. It is OPTIONAL.
* `links` is an Array of Transition Objects, which MUST all be safe, idempotent links. It is OPTIONAL.

## Context Object

```javascript
{
  vocab: String,
  typeOf: Array
}
```

Context defines the vocab and typeOf to be used for all of the properties in the Entity Object in which it is found. If a Content Object is used, only `typeOf` is REQUIRED. This is based on the http://schema.org vocab and how RDFa defines vocabularies and types.

### Available Properties

* `vocab` is a String for the URL to the vocab being used for this entity. It is OPTIONAL.
* `typeOf` is an Array for the type of entity being described here. It is REQUIRED.

## Property Object

```javascript
{
  type: String,
  name: String,
  value: String,
  label: String,
  context: Object
}
```

### Available Properties

* `type` is a String for the type of property here. If not present, `text` is default
  - boolean
  - date
  - dateTime
  - time
  - float
  - int
  - text
* `name` is a String for the name of the property. It is REQUIRED.
* `value` is a String for the value of the property. It is OPTIONAL.
* `label` is a String for an OPTIONAL, human-readable name of the property
* `context` is a Context Object. It is OPTIONAL.

## Transition Object

```javascript
{
  id: String,
  classes: Array,
  property: String,
  rels: Array,
  url: String,
  method: String,
  isTemplated: Boolean,
  responseTypes: Array,
  requestTypes: Array,
  fields: Array,
  bodyTemplate: String,
  label: String,
  renderAs: String
}
```

### Available Properties

* `id` is a String for documen-unique identifier. Either `id` or one `classes` must be set, but cannot be both.
* `classes` is an Array of Strings of non-unique identifiers. Either `id` or one `classes` must be set, but cannot be both.
* `rels` is an Array of available link relations for this link. It is OPTIONAL.
* `url` is a String for the `URL` of this link. It is REQUIRED.
* `method` is a String for the protocol method to be used when sending a request. By default, it is `GET`. It is OPTIONAL.
* `isTemplated` is a Boolean stating whether the URL is templated or not. By default, this is `false`. It is OPTIONAL.
* `responseTypes` is an Array of media types available to be sent as the response. It is OPTIONAL.
* `requestTypes` is an Array of media types the server will accept in the request. It is OPTIONAL.
* `fields` is an Array of Field Objects. It is OPTIONAL.
* `bodyTemplate` is a URI template to be used in the request body. It is OPTIONAL.
* `label` is a String for an OPTIONAL, human-readable name of the property. It is OPTIONAL.
* `renderAs` is a String conveying what the link response should be rendered as. It is OPTIONAL.

## Field Object

```javascript
{
  type: String,
  name: String,
  valueOptions: Array,
  defaultValue: String,
  value: String,
  label: String,
  mapsTo: String,
  isRequired: Boolean
}
```

### Available Properties

* `type` is a String for the type of the field. This MAY be any value that is allowable in the HTML5 `<input>` tag `@type` property. It is REQUIRED.
* `name` is a String for the name of the field. It is REQUIRED.
* `options` is an Array of Option Objects. It is OPTIONAL.
* `defaultValue` is a String for the default value of this field. It is conveying the default value of the field, but may be able to change if there is no value specified. It is OPTIONAL.
* `value` is a String for the value of the field. If set, the field MUST be this value and cannot change. It is OPTIONAL.
* `label` is a String for an OPTIONAL, human-readable name of the property. It is OPTIONAL.
* `mapsTo` is a String that says what this field maps to in either this entity or somewhere else in Hyperdescribe tree. It is OPTIONAL.
* `isRequired` is a Boolean to convey a field is required. By default, it is `false`. It is OPTIONAL.

## Field Option Object

```javascript
{
  value: String,
  label: String
}
```

### Available Properties

* `value` is a String for an option for the value of the field it's within. It is REQUIRED.
* `label` is a String for an OPTIONAL, human-readable name of the property. It is OPTIONAL.

## Example

The example below shows an HTML+RDFa representation and the Hyperdescribe document for this message below it.

### HTML+RDFa

```html
<!DOCTYPE html>
<html lang="en" prefix="schema: http://schema.org/ s: http://example.com/rels/">
  <head>
    <title>Top NBA Players of All Time</title>
    <link rel="alternate" type="application/hal+json" href="/top-3-players">
  </head>
  <body>
    <h1>Top NBA Players of All Time</h1>

    <div class="player" typeof="schema:Player" rel="s:player" resource="/players/jordan/michael">
      <h2>
        <span property="givenName">Michael</span>
        <span property="fullName">Jordan</span>
      </h2>
      <p><img src="/players/jordan/michael/game-photo.jpg" rel="s:game-photo" alt="Game Photo" /></p>
      <p>
        Check out Jordan's <a rel="s:stats" href="/players/jordan/michael/stats" title="Stats">stats</a>.
      </p>
    </div>
    <div class="player" typeof="schema:Player" rel="s:player" resource="/players/bird/larry">
      <h2>
        <span property="givenName">Larry</span>
        <span property="fullName">Bird</span>
      </h2>
      <p>
        Check out Bird's <a rel="s:stats" href="/players/bird/larry/stats" title="Stats">stats</a>.
      </p>
    </div>
    <div class="player" typeof="schema:Player" rel="s:player" resource="/players/russell/bill">
      <h2>
        <span property="givenName">Bill</span>
        <span property="fullName">Russell</span>
      </h2>
      <p>
        Check out Russell's <a rel="s:stats" href="/players/russell/bill/stats" title="Stats">stats</a>.
      </p>
    </div>

    <p>
      Also check out <a rel="s:nba_worst" href="/nba-worst" title="NBA Worst Players">NBA Worst Players</a>.
    </p>

    <form name="add-player" method="POST" action="/top-players" rel="s:add_player">
      <input type="text" name="givenName" placeholder="First Name" />
      <input type="text" name="familyName" placeholder="Last Name" />
    </form>
  </body>
</html>
```

### Described in Hyperdescribe

```json
{
  "hyperdescribe": {
    "version": "0.1.0",
    "entities": [
      {
        "classes": [ "player" ],
        "rels": [ "s:player" ],
        "url": "/players/jordan/michael",
        "context": {
          "typesOf": [ "schema:Player" ]
        },
        "content": {
          "properties": [
            { "name": "givenName", "value": "Michael" },
            { "name": "familyName", "value": "Jordan" }
          ],
          "links": [
            {
              "rels": [ "s:stats" ],
              "url": "/players/jordan/michael/stats",
              "label": "Stats"
            },
            {
              "rels": [ "s:game-photo" ],
              "url": "/players/jordan/michael/game-photo.jpg",
              "label": "Game Photo",
              "render": "image"
            }
          ]
        }
      },
      {
        "classes": [ "player" ],
        "rels": [ "s:player" ],
        "url": "/players/bird/larry",
        "context": {
          "typesOf": [ "schema:Player" ]
        },
        "content": {
          "properties": [
            { "name": "givenName", "value": "Larry" },
            { "name": "familyName", "value": "Bird" }
          ],
          "links": [
            {
              "rels": [ "s:stats" ],
              "url": "/players/bird/larry/stats",
              "label": "Stats"
            }
          ]
        }
      },
      {
        "classes": [ "player" ],
        "rels": [ "s:player" ],
        "url": "/players/russell/bill",
        "context": {
          "typesOf": [ "schema:Player" ]
        },
        "content": {
          "properties": [
            { "name": "givenName", "value": "Bill" },
            { "name": "familyName", "value": "Russell" }
          ],
          "links": [
            {
              "rels": [ "s:stats" ],
              "url": "/players/russell/bill/stats",
              "label": "Stats"
            }
          ]
        }
      }
    ],
    "actions": [
      {
        "classes": [ "add-player" ],
        "label": "Add Player",
        "method": "POST",
        "url": "/top-players",
        "requestTypes": [
          "application/x-www-form-urlencoded"
        ],
        "rels": [ "s:add-player" ],
        "fields": [
          {
            "name": "givenName",
            "type": "text",
            "label": "First Name"
          },
          {
            "name": "familyName",
            "type": "text",
            "label": "Last Name"
          }
        ]
      }
    ]
  }
}
```


text:
"""The tests the for Meraki device tracker."""
import asyncio
import json
from unittest.mock import patch
import pytest
from homeassistant.components.device_tracker.meraki import (
    CONF_VALIDATOR, CONF_SECRET)
from homeassistant.setup import async_setup_component
import homeassistant.components.device_tracker as device_tracker
from homeassistant.const import CONF_PLATFORM
from homeassistant.components.device_tracker.meraki import URL

@pytest.fixture
def meraki_client(loop, hass, test_client):
    """Meraki mock client."""
    assert loop.run_until_complete(async_setup_component(
        hass, device_tracker.DOMAIN, {
            device_tracker.DOMAIN: {
                CONF_PLATFORM: 'meraki',
                CONF_VALIDATOR: 'validator',
                CONF_SECRET: 'secret'

            }
        }))

    with patch('homeassistant.components.device_tracker.update_config'):
        yield loop.run_until_complete(test_client(hass.http.app))

@asyncio.coroutine
def test_invalid_or_missing_data(meraki_client):
    """Test validator with invalid or missing data."""
    req = yield from meraki_client.get(URL)
    text = yield from req.text()
    assert req.status == 200
    assert text == 'validator'

    req = yield from meraki_client.post(URL, data=b"invalid")
    text = yield from req.json()
    assert req.status == 400
    assert text['message'] == 'Invalid JSON'

    req = yield from meraki_client.post(URL, data=b"{}")
    text = yield from req.json()
    assert req.status == 422
    assert text['message'] == 'No secret'

    data = {
        "version": "1.0",
        "secret": "secret"
    }
    req = yield from meraki_client.post(URL, data=json.dumps(data))
    text = yield from req.json()
    assert req.status == 422
    assert text['message'] == 'Invalid version'

    data = {
        "version": "2.0",
        "secret": "invalid"
    }
    req = yield from meraki_client.post(URL, data=json.dumps(data))
    text = yield from req.json()
    assert req.status == 422
    assert text['message'] == 'Invalid secret'

    data = {
        "version": "2.0",
        "secret": "secret",
        "type": "InvalidType"
    }
    req = yield from meraki_client.post(URL, data=json.dumps(data))
    text = yield from req.json()
    assert req.status == 422
    assert text['message'] == 'Invalid device type'

    data = {
        "version": "2.0",
        "secret": "secret",
        "type": "BluetoothDevicesSeen",
        "data": {
            "observations": []
        }
    }
    req = yield from meraki_client.post(URL, data=json.dumps(data))
    assert req.status == 200

@asyncio.coroutine
def test_data_will_be_saved(hass, meraki_client):
    """Test with valid data."""
    data = {
        "version": "2.0",
        "secret": "secret",
        "type": "DevicesSeen",
        "data": {
            "observations": [
                {
                    "location": {
                        "lat": "51.5355157",
                        "lng": "21.0699035",
                        "unc": "46.3610585",
                    },
                    "seenTime": "2016-09-12T16:23:13Z",
                    "ssid": 'ssid',
                    "os": 'HA',
                    "ipv6": '2607:f0d0:1002:51::4/64',
                    "clientMac": "00:26:ab:b8:a9:a4",
                    "seenEpoch": "147369739",
                    "rssi": "20",
                    "manufacturer": "Seiko Epson"
                },
                {
                    "location": {
                        "lat": "51.5355357",
                        "lng": "21.0699635",
                        "unc": "46.3610585",
                    },
                    "seenTime": "2016-09-12T16:21:13Z",
                    "ssid": 'ssid',
                    "os": 'HA',
                    "ipv4": '192.168.0.1',
                    "clientMac": "00:26:ab:b8:a9:a5",
                    "seenEpoch": "147369750",
                    "rssi": "20",
                    "manufacturer": "Seiko Epson"
                }
            ]
        }
    }
    req = yield from meraki_client.post(URL, data=json.dumps(data))
    assert req.status == 200
    state_name = hass.states.get('{}.{}'.format('device_tracker',
                                                '0026abb8a9a4')).state
    assert 'home' == state_name

    state_name = hass.states.get('{}.{}'.format('device_tracker',
                                                '0026abb8a9a5')).state
    assert 'home' == state_name


text:
import argparse
import os
import libcst as cst
import pathlib
import sys
from typing import (Any, Callable, Dict, List, Sequence, Tuple)

def partition(
    predicate: Callable[[Any], bool],
    iterator: Sequence[Any]
) -> Tuple[List[Any], List[Any]]:
    """A stable, out-of-place partition."""
    results = ([], [])

    for i in iterator:
        results[int(predicate(i))].append(i)

    # Returns trueList, falseList
    return results[1], results[0]

class channelCallTransformer(cst.CSTTransformer):
    CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata')
    METHOD_TO_PARAMS: Dict[str, Tuple[str]] = {
        'activate_entitlement': ('name', 'request_id', ),
        'cancel_entitlement': ('name', 'request_id', ),
        'change_offer': ('name', 'offer', 'parameters', 'purchase_order_id', 'request_id', ),
        'change_parameters': ('name', 'parameters', 'request_id', 'purchase_order_id', ),
        'change_renewal_settings': ('name', 'renewal_settings', 'request_id', ),
        'check_cloud_identity_accounts_exist': ('parent', 'domain', ),
        'create_channel_partner_link': ('parent', 'channel_partner_link', ),
        'create_channel_partner_repricing_config': ('parent', 'channel_partner_repricing_config', ),
        'create_customer': ('parent', 'customer', ),
        'create_customer_repricing_config': ('parent', 'customer_repricing_config', ),
        'create_entitlement': ('parent', 'entitlement', 'request_id', ),
        'delete_channel_partner_repricing_config': ('name', ),
        'delete_customer': ('name', ),
        'delete_customer_repricing_config': ('name', ),
        'fetch_report_results': ('report_job', 'page_size', 'page_token', ),
        'get_channel_partner_link': ('name', 'view', ),
        'get_channel_partner_repricing_config': ('name', ),
        'get_customer': ('name', ),
        'get_customer_repricing_config': ('name', ),
        'get_entitlement': ('name', ),
        'import_customer': ('domain', 'cloud_identity_id', 'parent', 'overwrite_if_exists', 'auth_token', 'channel_partner_id', 'customer', ),
        'list_channel_partner_links': ('parent', 'page_size', 'page_token', 'view', ),
        'list_channel_partner_repricing_configs': ('parent', 'page_size', 'page_token', 'filter', ),
        'list_customer_repricing_configs': ('parent', 'page_size', 'page_token', 'filter', ),
        'list_customers': ('parent', 'page_size', 'page_token', 'filter', ),
        'list_entitlements': ('parent', 'page_size', 'page_token', ),
        'list_offers': ('parent', 'page_size', 'page_token', 'filter', 'language_code', ),
        'list_products': ('account', 'page_size', 'page_token', 'language_code', ),
        'list_purchasable_offers': ('customer', 'create_entitlement_purchase', 'change_offer_purchase', 'page_size', 'page_token', 'language_code', ),
        'list_purchasable_skus': ('customer', 'create_entitlement_purchase', 'change_offer_purchase', 'page_size', 'page_token', 'language_code', ),
        'list_reports': ('parent', 'page_size', 'page_token', 'language_code', ),
        'list_skus': ('parent', 'account', 'page_size', 'page_token', 'language_code', ),
        'list_subscribers': ('account', 'page_size', 'page_token', ),
        'list_transferable_offers': ('parent', 'sku', 'cloud_identity_id', 'customer_name', 'page_size', 'page_token', 'language_code', ),
        'list_transferable_skus': ('parent', 'cloud_identity_id', 'customer_name', 'page_size', 'page_token', 'auth_token', 'language_code', ),
        'lookup_offer': ('entitlement', ),
        'provision_cloud_identity': ('customer', 'cloud_identity_info', 'user', 'validate_only', ),
        'register_subscriber': ('account', 'service_account', ),
        'run_report_job': ('name', 'date_range', 'filter', 'language_code', ),
        'start_paid_service': ('name', 'request_id', ),
        'suspend_entitlement': ('name', 'request_id', ),
        'transfer_entitlements': ('parent', 'entitlements', 'auth_token', 'request_id', ),
        'transfer_entitlements_to_google': ('parent', 'entitlements', 'request_id', ),
        'unregister_subscriber': ('account', 'service_account', ),
        'update_channel_partner_link': ('name', 'channel_partner_link', 'update_mask', ),
        'update_channel_partner_repricing_config': ('channel_partner_repricing_config', ),
        'update_customer': ('customer', 'update_mask', ),
        'update_customer_repricing_config': ('customer_repricing_config', ),
    }

    def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
        try:
            key = original.func.attr.value
            kword_params = self.METHOD_TO_PARAMS[key]
        except (AttributeError, KeyError):
            # Either not a method from the API or too convoluted to be sure.
            return updated

        # If the existing code is valid, keyword args come after positional args.
        # Therefore, all positional args must map to the first parameters.
        args, kwargs = partition(lambda a: not bool(a.keyword), updated.args)
        if any(k.keyword.value == "request" for k in kwargs):
            # We've already fixed this file, don't fix it again.
            return updated

        kwargs, ctrl_kwargs = partition(
            lambda a: a.keyword.value not in self.CTRL_PARAMS,
            kwargs
        )

        args, ctrl_args = args[:len(kword_params)], args[len(kword_params):]
        ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl))
                           for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS))

        request_arg = cst.Arg(
            value=cst.Dict([
                cst.DictElement(
                    cst.SimpleString("'{}'".format(name)),
cst.Element(value=arg.value)
                )
                # Note: the args + kwargs looks silly, but keep in mind that
                # the control parameters had to be stripped out, and that
                # those could have been passed positionally or by keyword.
                for name, arg in zip(kword_params, args + kwargs)]),
            keyword=cst.Name("request")
        )

        return updated.with_changes(
            args=[request_arg] + ctrl_kwargs
        )

def fix_files(
    in_dir: pathlib.Path,
    out_dir: pathlib.Path,
    *,
    transformer=channelCallTransformer(),
):
    """Duplicate the input dir to the output dir, fixing file method calls.

    Preconditions:
    * in_dir is a real directory
    * out_dir is a real, empty directory
    """
    pyfile_gen = (
        pathlib.Path(os.path.join(root, f))
        for root, _, files in os.walk(in_dir)
        for f in files if os.path.splitext(f)[1] == ".py"
    )

    for fpath in pyfile_gen:
        with open(fpath, 'r') as f:
            src = f.read()

        # Parse the code and insert method call fixes.
        tree = cst.parse_module(src)
        updated = tree.visit(transformer)

        # Create the path and directory structure for the new file.
        updated_path = out_dir.joinpath(fpath.relative_to(in_dir))
        updated_path.parent.mkdir(parents=True, exist_ok=True)

        # Generate the updated source file at the corresponding path.
        with open(updated_path, 'w') as f:
            f.write(updated.code)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="""Fix up source that uses the channel client library.

The existing sources are NOT overwritten but are copied to output_dir with changes made.

Note: This tool operates at a best-effort level at converting positional
      parameters in client method calls to keyword based parameters.
      Cases where it WILL FAIL include
      A) * or ** expansion in a method call.
      B) Calls via function or method alias (includes free function calls)
      C) Indirect or dispatched calls (e.g. the method is looked up dynamically)

      These all constitute false negatives. The tool will also detect false
      positives when an API method shares a name with another method.
""")
    parser.add_argument(
        '-d',
        '--input-directory',
        required=True,
        dest='input_dir',
        help='the input directory to walk for python files to fix up',
    )
    parser.add_argument(
        '-o',
        '--output-directory',
        required=True,
        dest='output_dir',
        help='the directory to output files fixed via un-flattening',
    )
    args = parser.parse_args()
    input_dir = pathlib.Path(args.input_dir)
    output_dir = pathlib.Path(args.output_dir)
    if not input_dir.is_dir():
        print(
            f"input directory '{input_dir}' does not exist or is not a directory",
            file=sys.stderr,
        )
        sys.exit(-1)

    if not output_dir.is_dir():
        print(
            f"output directory '{output_dir}' does not exist or is not a directory",
            file=sys.stderr,
        )
        sys.exit(-1)

    if os.listdir(output_dir):
        print(
            f"output directory '{output_dir}' is not empty",
            file=sys.stderr,
        )
        sys.exit(-1)

    fix_files(input_dir, output_dir)


text:
/*
 * Siren Encoder/Decoder library
 *
 *   @author: Youness Alaoui <kakaroto@kakaroto.homelinux.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifndef _SIREN_ENCODER_H
#define _SIREN_ENCODER_H

#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "dct4.h"
#include "rmlt.h"
#include "huffman.h"
#include "common.h"

typedef struct stSirenEncoder {
	int sample_rate;
	SirenWavHeader WavHeader;
	float context[320];
} * SirenEncoder;

/* sample_rate MUST be 16000 to be compatible with MSN Voice clips (I think) */
extern SirenEncoder Siren7_NewEncoder(int sample_rate);
extern void Siren7_CloseEncoder(SirenEncoder encoder);
extern int Siren7_EncodeFrame(SirenEncoder encoder, unsigned char *DataIn, unsigned char *DataOut);

#endif /* _SIREN_ENCODER_H */


text:
package com.github.dakusui.jcunit8.tests.validation.testresources.seedfeature;

import com.github.dakusui.jcunit.core.tuples.Tuple;
import com.github.dakusui.jcunit8.pipeline.Requirement;
import com.github.dakusui.jcunit8.pipeline.stages.ConfigFactory;
import com.github.dakusui.jcunit8.runners.junit4.annotations.ConfigureWith;

@ConfigureWith(TypeMismatch.Config.class)
public class TypeMismatch extends SeedBase {
  public static class Config extends ConfigFactory.Base {
    @Override
    protected Requirement defineRequirement(Requirement.Builder defaultValues) {
      return defaultValues.withNegativeTestGeneration(
          false
      ).addSeed(
          Tuple.builder(
          ).put(
              "parameter1", "hello"
          ).put(
              "parameter2", new Object()
          ).build()
      ).build();
    }
  }
}


text:
#ifndef __cocos2d_libs__EventController__
#define __cocos2d_libs__EventController__

#include "platform/CCPlatformMacros.h"
#include "base/CCEvent.h"

/**
 * @addtogroup base
 * @{
 */

NS_CC_BEGIN

/// @cond EventController
class Controller;
class EventListenerController;

/** @class EventController
 * @brief Controller event.
 */
class CC_DLL EventController : public Event
{
public:
    /** ControllerEventType Controller event type.*/
    enum class ControllerEventType
    {
        CONNECTION,
        BUTTON_STATUS_CHANGED,
        AXIS_STATUS_CHANGED,
    };

    /** Create a EventController with controller event type, controller and key code.
     *
     * @param type A given controller event type.
     * @param controller A given controller pointer.
     * @param keyCode A given key code.
     * @return An autoreleased EventController object.
     */
	EventController(ControllerEventType type, Controller* controller, int keyCode);
    /** Create a EventController with controller event type, controller and whether or not is connected.
     *
     * @param type A given controller event type.
     * @param controller A given controller pointer.
     * @param isConnected True if it is connected.
     * @return An autoreleased EventController object.
     */
    EventController(ControllerEventType type, Controller* controller, bool isConnected);

    /** Gets the event type of the controller.
     *
     * @return The event type of the controller.
     */
    ControllerEventType getControllerEventType() const { return _controllerEventType; }
    Controller* getController() const { return _controller; }

    /** Gets the key code of the controller.
     *
     * @return The key code of the controller.
     */
    int getKeyCode() const{ return _keyCode; }
    void setKeyCode(int keyCode) { _keyCode = keyCode;}

    /** Sets the connect status.
     *
     * @param True if it's connected.
     */
    void setConnectStatus(bool isConnected) {_isConnected = isConnected;}
    /** Gets the connect status.
     *
     * @return True if it's connected.
     */
    bool isConnected() const { return _isConnected; }

protected:
    ControllerEventType _controllerEventType;
    Controller* _controller;
    int _keyCode;
    bool _isConnected;

    friend class EventListenerController;
};
/// @endcond EventController
NS_CC_END

// end of base group
/// @}

#endif /* defined(__cocos2d_libs__EventController__) */


text:
/* libloader: load libraries, making all symbols exported
 * universally visible.  Equivalent to LoadFile in HTTPD.
 *
 * Written for ironbee plugin, whose module architecture
 * is not compatible with trafficserver's plugins.
 * May be useful for other plugins with non-trivial
 * library dependencies.
 */

#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <ts/ts.h>

typedef struct {
  void *handle;
  void *next;
} link_handle;

static link_handle *libs = NULL;

static void
unloadlibs(void)
{
  link_handle *p = libs;
  while (p != NULL) {
    link_handle *next = p->next;
    dlclose(p->handle);
    TSfree(p);
    p = next;
  }
  libs = NULL;
}

void
TSPluginInit(int argc, const char *argv[])
{
  int i;
  TSPluginRegistrationInfo info;

  info.plugin_name   = (char *)"libloader";
  info.vendor_name   = (char *)"Apache Software Foundation";
  info.support_email = (char *)"dev@trafficserver.apache.org";

  if (TSPluginRegister(&info) != TS_SUCCESS) {
    TSError("[libloader] Plugin registration failed.\n");
    return;
  }

  atexit(unloadlibs);

  for (i = 1; i < argc; ++i) {
    const char *lib = argv[i];
    void *handle    = dlopen(lib, RTLD_GLOBAL | RTLD_NOW);
    if (handle) {
      link_handle *l = TSmalloc(sizeof(link_handle));
      l->handle      = handle;
      l->next        = libs;
      libs           = l;
      TSDebug("libloader", " loaded %s", lib);
    } else {
      TSError("[libloader] failed to load %s: %s\n", lib, dlerror());
    }
  }
  return;
}


text:
                 {{i18n.dashboard.snap}}

                {{i18n.charts.snap}}

                {{i18n.rules.snap}}

                {{i18n.device.snap}}

                {{i18n.control.snap}}

                {{i18n.account.snap}}

                {{i18n.alerts.snap}}

                {{i18n.about.snap}}


text:
package com.gonghan.designPatterns.abstractFactory;

public class Wonderland {
	public Wonderland(AnimalFactory factory){
		Animal animal=factory.createAnimal();
		animal.breathe();
	}
}


text:
package com.nightwind.contacts.model;

import com.nightwind.contacts.model.dataitem.DataItem;

import java.util.List;

/**
 * Created by nightwind on 15/4/21.
 */
public class Contact {
    private long id;
    private long rawContactId;
    private String name;
    private String photoUri;
    private String lookupUri;//联系人的标识符
    private List<DataItem> data;
    private boolean starred;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhotoUri() {
        return photoUri;
    }

    public void setPhotoUri(String photoUri) {
        this.photoUri = photoUri;
    }

    public List<DataItem> getData() {
        return data;
    }

    public void setData(List<DataItem> data) {
        this.data = data;
    }

    public String getLookupUri() {
        return lookupUri;
    }

    public void setLookupUri(String lookupUri) {
        this.lookupUri = lookupUri;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public long getRawContactId() {
        return rawContactId;
    }

    public void setRawContactId(long rawContactId) {
        this.rawContactId = rawContactId;
    }

    public boolean isStarred() {
        return starred;
    }

    public void setStarred(boolean starred) {
        this.starred = starred;
    }
}