text:
package com.enigmabridge.create;

import com.enigmabridge.EBEndpointInfo;
import com.enigmabridge.EBEngine;
import com.enigmabridge.EBSettings;
import com.enigmabridge.EBUtils;
import com.enigmabridge.comm.*;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Create UO call.
 * EB template needs to be prepared when calling this
 *
 * Created by dusanklinec on 30.06.16.
 */
public class EBCreateUOCall extends EBAPICall implements EBResponseParser {
    private static final Logger LOG = LoggerFactory.getLogger(EBCreateUOCall.class);
    public static final String FIELD_DATA = "data";
    public static final String FIELD_RESULT = "result";

    protected EBCreateUORequest pkRequest;
    protected EBCreateUOResponse pkResponse;

    /**
     * Separate abstract builder, chain from EBApiCall broken on purpose, restrict setters of this builder, e.g. callFunction.
     * @param <T>
     * @param <B>
     */
    public static abstract class AbstractBuilder<T extends EBCreateUOCall, B extends EBCreateUOCall.AbstractBuilder> {
        public B setEndpoint(EBEndpointInfo a) {
            getObj().setEndpoint(a);
            return getThisBuilder();
        }

        public B setSettings(EBConnectionSettings b) {
            getObj().setSettings(b);
            return getThisBuilder();
        }

        public B setSettings(EBSettings settings) {
            if (settings.getApiKey() != null){
                getObj().setApiKey(settings.getApiKey());
            }
            if (settings.getEndpointInfo() != null){
                getObj().setEndpoint(settings.getEndpointInfo());
            }
            if (settings.getConnectionSettings() != null){
                getObj().setSettings(settings.getConnectionSettings());
            }
            return getThisBuilder();
        }

        public B setApiKey(String apiKey){
            getObj().setApiKey(apiKey);
            return getThisBuilder();
        }

        public B setEngine(EBEngine engine){
            getObj().setEngine(engine);

            // Take enrollment endpoint preferably if configured via engine
            if (engine != null && engine.getEndpointEnrollment() != null){
                getObj().setEndpoint(engine.getEndpointEnrollment());
            }

            final EBSettings settings = engine == null ? null : engine.getDefaultSettings();
            if (settings != null){
                if (settings.getApiKey() != null && getObj().getApiKey() == null){
                    getObj().setApiKey(settings.getApiKey());
                }
                if (settings.getEndpointInfo() != null && getObj().getEndpoint() == null){
                    getObj().setEndpoint(settings.getEndpointInfo());
                }
                if(settings.getConnectionSettings() != null && getObj().getSettings() == null){
                    getObj().setSettings(settings.getConnectionSettings());
                }
            }
            return getThisBuilder();
        }

        public B setNonce(byte[] nonce){
            getObj().setNonce(nonce);
            return getThisBuilder();
        }

        public abstract T build();
        public abstract B getThisBuilder();
        public abstract T getObj();
    }

    public static class Builder extends EBCreateUOCall.AbstractBuilder<EBCreateUOCall, EBCreateUOCall.Builder> {
        private final EBCreateUOCall child = new EBCreateUOCall();

        @Override
        public EBCreateUOCall getObj() {
            return child;
        }

        @Override
        public EBCreateUOCall build() {
            if (child.getApiKey() == null){
                throw new NullPointerException("ApiKey is null");
            }

            if (child.getEndpoint() == null){
                throw new NullPointerException("Endpoint info is null");
            }

            child.setCallFunction("CreateUserObject");
            return child;
        }

        @Override
        public EBCreateUOCall.Builder getThisBuilder() {
            return this;
        }
    }

    /**
     * Builds request data.
     */
    public void build(EBCreateUORequest request) throws IOException {
        this.buildApiBlock(getApiKey(), request.getObjectId(), request.getObjectType());

        // Build raw request.
        rawRequest = new EBRawRequest();
        if (settings != null) {
            rawRequest.setMethod(settings.getMethod());
        }

        this.pkRequest = request;

        // Build request - body.
        final JSONObject jreq = new JSONObject();
        final JSONObject jdat = new JSONObject();
        jreq.put("data", jdat);

        jdat.put("objectid",        String.format("%08x", request.getObjectId()));
        jdat.put("object",          EBUtils.byte2hex(request.getObject()));
        jdat.put("authorization",   request.getAuthorization());
        jdat.put("importkey",       request.getImportKeyId());
        jdat.put("contextparams",   request.getContextparams());

        // Build the rest of the request - headers.
        rawRequest.setBody(jreq.toString());
        rawRequest.setPath(String.format("%s/%s/%s/%s",
                this.apiVersion,
                this.apiBlock,
                this.callFunction,
                EBUtils.byte2hex(this.getNonce())
        ));
    }

    /**
     * Performs request to the remote endpoint with built request.
     * @throws IOException
     * @throws EBCorruptedException
     */
    public EBCreateUOResponse doRequest(EBCreateUORequest request) throws IOException, EBCorruptedException {
        if (apiBlock == null || request != null){
            build(request);
        }

        this.connector = engine.getConMgr().getConnector(this.endpoint);
        this.connector.setEndpoint(this.endpoint);
        this.connector.setSettings(this.settings);
        this.connector.setRawRequest(rawRequest);

        LOG.trace("Going to call request...");
        this.rawResponse = this.connector.request();

        // Empty response to parse data to.
        final EBCreateUOResponse.Builder builder = new EBCreateUOResponse.Builder();
        builder.setRawResponse(rawResponse);

        if (!rawResponse.isSuccessful()){
            LOG.info("Response was not successful: " + rawResponse.toString());
            pkResponse = builder.build();
            return pkResponse;
        }

        // Parse process data response.
        final EBResponseParserBase parser = new EBResponseParserBase();
        parser.setSubParser(this);
        parser.parseResponse(new JSONObject(rawResponse.getBody()), builder, null);

        // Return connector.
        engine.getConMgr().doneWithConnector(connector);
        this.connector = null;

        pkResponse = builder.build();
        return pkResponse;
    }

    @Override
    public EBResponse.ABuilder parseResponse(JSONObject data, EBResponse.ABuilder resp, EBResponseParserOptions options) throws EBCorruptedException {
        if (data == null || !data.has(FIELD_RESULT)){
            throw new EBCorruptedException("Create UO response corrupted: " + data);
        }

        if (resp == null){
            resp = new EBGetPubKeyResponse.Builder();
        }

        if (!resp.getObj().isCodeOk()){
            LOG.debug(String.format("Error in processing, status: %04X, message: %s",
                    (long)resp.getObj().getStatusCode(), resp.getObj().getStatusDetail()));
            return resp;
        }

        final EBCreateUOResponse.ABuilder resp2ret = (EBCreateUOResponse.ABuilder) resp;
        final JSONObject res = data.getJSONObject(FIELD_RESULT);

        resp2ret.setHandle(res.getString("handle"));

        // publickey?
        if (res.has("publickey")){
            resp2ret.setPublicKey(EBUtils.hex2byte(res.getString("publickey"), true));
        }

        // Signature?
        if (res.has("signature")){
            resp2ret.setSignature(EBUtils.hex2byte(res.getString("signature"), true));
        }

        // Certificate?
        if (res.has("certificate")){
            resp2ret.setCertificate(EBUtils.hex2byte(res.getString("certificate"), true));
        }

        // TODO: certificate chain processing.
        return resp2ret;
    }

    @Override
    public EBResponseParser getSubParser() {
        return null;
    }

}


text:
module GraphQL
  module Language
    class Printer
      # Turn an arbitrary AST node back into a string.
      #
      # @example Turning a document into a query string
      #    document = GraphQL.parse(query_string)
      #    GraphQL::Language::Printer.new.print(document)
      #    # => "{ ... }"
      #
      #
      # @example Building a custom printer
      #
      #  class MyPrinter < GraphQL::Language::Printer
      #    def print_argument(arg)
      #      "#{arg.name}: <HIDDEN>"
      #    end
      #  end
      #
      #  MyPrinter.new.print(document)
      #  # => "mutation { pay(creditCard: <HIDDEN>) { success } }"
      #
      #
      # @param indent [String] Whitespace to add to the printed node
      # @return [String] Valid GraphQL for `node`
      def print(node, indent: "")
        print_node(node, indent: indent)
      end

      protected

      def print_document(document)
        document.definitions.map { |d| print_node(d) }.join("\n\n")
      end

      def print_argument(argument)
        "#{argument.name}: #{print_node(argument.value)}".dup
      end

      def print_directive(directive)
        out = "@#{directive.name}".dup

        if directive.arguments.any?
          out << "(#{directive.arguments.map { |a| print_argument(a) }.join(", ")})"
        end

        out
      end

      def print_enum(enum)
        "#{enum.name}".dup
      end

      def print_null_value
        "null".dup
      end

      def print_field(field, indent: "")
        out = "#{indent}".dup
        out << "#{field.alias}: " if field.alias
        out << "#{field.name}"
        out << "(#{field.arguments.map { |a| print_argument(a) }.join(", ")})" if field.arguments.any?
        out << print_directives(field.directives)
        out << print_selections(field.selections, indent: indent)
        out
      end

      def print_fragment_definition(fragment_def, indent: "")
        out = "#{indent}fragment #{fragment_def.name}".dup
        if fragment_def.type
          out << " on #{print_node(fragment_def.type)}"
        end
        out << print_directives(fragment_def.directives)
        out << print_selections(fragment_def.selections, indent: indent)
        out
      end

      def print_fragment_spread(fragment_spread, indent: "")
        out = "#{indent}...#{fragment_spread.name}".dup
        out << print_directives(fragment_spread.directives)
        out
      end

      def print_inline_fragment(inline_fragment, indent: "")
        out = "#{indent}...".dup
        if inline_fragment.type
          out << " on #{print_node(inline_fragment.type)}"
        end
        out << print_directives(inline_fragment.directives)
        out << print_selections(inline_fragment.selections, indent: indent)
        out
      end

      def print_input_object(input_object)
        "{#{input_object.arguments.map { |a| print_argument(a) }.join(", ")}}"
      end

      def print_list_type(list_type)
        "[#{print_node(list_type.of_type)}]".dup
      end

      def print_non_null_type(non_null_type)
        "#{print_node(non_null_type.of_type)}!".dup
      end

      def print_operation_definition(operation_definition, indent: "")
        out = "#{indent}#{operation_definition.operation_type}".dup
        out << " #{operation_definition.name}" if operation_definition.name

        if operation_definition.variables.any?
          out << "(#{operation_definition.variables.map { |v| print_variable_definition(v) }.join(", ")})"
        end

        out << print_directives(operation_definition.directives)
        out << print_selections(operation_definition.selections, indent: indent)
        out
      end

      def print_type_name(type_name)
        "#{type_name.name}".dup
      end

      def print_variable_definition(variable_definition)
        out = "$#{variable_definition.name}: #{print_node(variable_definition.type)}".dup
        out << " = #{print_node(variable_definition.default_value)}" unless variable_definition.default_value.nil?
        out
      end

      def print_variable_identifier(variable_identifier)
        "$#{variable_identifier.name}".dup
      end

      def print_schema_definition(schema)
        if (schema.query.nil? || schema.query == 'Query') &&
           (schema.mutation.nil? || schema.mutation == 'Mutation') &&
           (schema.subscription.nil? || schema.subscription == 'Subscription') &&
           (schema.directives.empty?)
          return
        end

        out = "schema".dup
        if schema.directives.any?
          schema.directives.each do |dir|
            out << "\n  "
            out << print_node(dir)
          end
          out << "\n{"
        else
          out << " {\n"
        end
        out << "  query: #{schema.query}\n" if schema.query
        out << "  mutation: #{schema.mutation}\n" if schema.mutation
        out << "  subscription: #{schema.subscription}\n" if schema.subscription
        out << "}"
      end

      def print_scalar_type_definition(scalar_type)
        out = print_description(scalar_type)
        out << "scalar #{scalar_type.name}"
        out << print_directives(scalar_type.directives)
      end

      def print_object_type_definition(object_type)
        out = print_description(object_type)
        out << "type #{object_type.name}"
        out << print_implements(object_type) unless object_type.interfaces.empty?
        out << print_directives(object_type.directives)
        out << print_field_definitions(object_type.fields)
      end

      def print_implements(type)
        " implements #{type.interfaces.map(&:name).join(" & ")}"
      end

      def print_input_value_definition(input_value)
        out = "#{input_value.name}: #{print_node(input_value.type)}".dup
        out << " = #{print_node(input_value.default_value)}" unless input_value.default_value.nil?
        out << print_directives(input_value.directives)
      end

      def print_arguments(arguments, indent: "")
        if arguments.all?{ |arg| !arg.description }
          return "(#{arguments.map{ |arg| print_input_value_definition(arg) }.join(", ")})"
        end

        out = "(\n".dup
        out << arguments.map.with_index{ |arg, i|
          "#{print_description(arg, indent: "  " + indent, first_in_block: i == 0)}  #{indent}"\
          "#{print_input_value_definition(arg)}"
        }.join("\n")
        out << "\n#{indent})"
      end

      def print_field_definition(field)
        out = field.name.dup
        unless field.arguments.empty?
          out << print_arguments(field.arguments, indent: "  ")
        end
        out << ": #{print_node(field.type)}"
        out << print_directives(field.directives)
      end

      def print_interface_type_definition(interface_type)
        out = print_description(interface_type)
        out << "interface #{interface_type.name}"
        out << print_implements(interface_type) if interface_type.interfaces.any?
        out << print_directives(interface_type.directives)
        out << print_field_definitions(interface_type.fields)
      end

      def print_union_type_definition(union_type)
        out = print_description(union_type)
        out << "union #{union_type.name}"
        out << print_directives(union_type.directives)
        out << " = " + union_type.types.map(&:name).join(" | ")
      end

      def print_enum_type_definition(enum_type)
        out = print_description(enum_type)
        out << "enum #{enum_type.name}#{print_directives(enum_type.directives)} {\n"
        enum_type.values.each.with_index do |value, i|
          out << print_description(value, indent: '  ', first_in_block: i == 0)
          out << print_enum_value_definition(value)
        end
        out << "}"
      end

      def print_enum_value_definition(enum_value)
        out = "  #{enum_value.name}".dup
        out << print_directives(enum_value.directives)
        out << "\n"
      end

      def print_input_object_type_definition(input_object_type)
        out = print_description(input_object_type)
        out << "input #{input_object_type.name}"
        out << print_directives(input_object_type.directives)
        out << " {\n"
        input_object_type.fields.each.with_index do |field, i|
          out << print_description(field, indent: '  ', first_in_block: i == 0)
          out << "  #{print_input_value_definition(field)}\n"
        end
        out << "}"
      end

      def print_directive_definition(directive)
        out = print_description(directive)
        out << "directive @#{directive.name}"

        if directive.arguments.any?
          out << print_arguments(directive.arguments)
        end

        if directive.repeatable
          out << " repeatable"
        end

        out << " on #{directive.locations.map(&:name).join(' | ')}"
      end

      def print_description(node, indent: "", first_in_block: true)
        return ''.dup unless node.description

        description = indent != '' && !first_in_block ? "\n".dup : "".dup
        description << GraphQL::Language::BlockString.print(node.description, indent: indent)
      end

      def print_field_definitions(fields)
        if fields.empty?
          ""
        else
          out = " {\n".dup
          fields.each.with_index do |field, i|
            out << print_description(field, indent: '  ', first_in_block: i == 0)
            out << "  #{print_field_definition(field)}\n"
          end
          out << "}"
        end
      end

      def print_directives(directives)
        if directives.any?
          directives.map { |d| " #{print_directive(d)}" }.join
        else
          ""
        end
      end

      def print_selections(selections, indent: "")
        if selections.any?
          out = " {\n".dup
          selections.each do |selection|
            out << print_node(selection, indent: indent + "  ") << "\n"
          end
          out << "#{indent}}"
        else
          ""
        end
      end

      def print_node(node, indent: "")
        case node
        when Nodes::Document
          print_document(node)
        when Nodes::Argument
          print_argument(node)
        when Nodes::Directive
          print_directive(node)
        when Nodes::Enum
          print_enum(node)
        when Nodes::NullValue
          print_null_value
        when Nodes::Field
          print_field(node, indent: indent)
        when Nodes::FragmentDefinition
          print_fragment_definition(node, indent: indent)
        when Nodes::FragmentSpread
          print_fragment_spread(node, indent: indent)
        when Nodes::InlineFragment
          print_inline_fragment(node, indent: indent)
        when Nodes::InputObject
          print_input_object(node)
        when Nodes::ListType
          print_list_type(node)
        when Nodes::NonNullType
          print_non_null_type(node)
        when Nodes::OperationDefinition
          print_operation_definition(node, indent: indent)
        when Nodes::TypeName
          print_type_name(node)
        when Nodes::VariableDefinition
          print_variable_definition(node)
        when Nodes::VariableIdentifier
          print_variable_identifier(node)
        when Nodes::SchemaDefinition
          print_schema_definition(node)
        when Nodes::ScalarTypeDefinition
          print_scalar_type_definition(node)
        when Nodes::ObjectTypeDefinition
          print_object_type_definition(node)
        when Nodes::InputValueDefinition
          print_input_value_definition(node)
        when Nodes::FieldDefinition
          print_field_definition(node)
        when Nodes::InterfaceTypeDefinition
          print_interface_type_definition(node)
        when Nodes::UnionTypeDefinition
          print_union_type_definition(node)
        when Nodes::EnumTypeDefinition
          print_enum_type_definition(node)
        when Nodes::EnumValueDefinition
          print_enum_value_definition(node)
        when Nodes::InputObjectTypeDefinition
          print_input_object_type_definition(node)
        when Nodes::DirectiveDefinition
          print_directive_definition(node)
        when FalseClass, Float, Integer, NilClass, String, TrueClass, Symbol
          GraphQL::Language.serialize(node)
        when Array
          "[#{node.map { |v| print_node(v) }.join(", ")}]".dup
        when Hash
          "{#{node.map { |k, v| "#{k}: #{print_node(v)}" }.join(", ")}}".dup
        else
          GraphQL::Language.serialize(node.to_s)
        end
      end

      private

      attr_reader :node
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
#include <string.h>

#include <grpc/grpc.h>
#include <grpc/support/alloc.h>

#include "src/core/ext/client_channel/resolver.h"
#include "src/core/ext/client_channel/resolver_registry.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/iomgr/timer.h"
#include "test/core/util/test_config.h"

static gpr_mu g_mu;
static bool g_fail_resolution = true;
static grpc_combiner *g_combiner;

static grpc_error *my_resolve_address(const char *name, const char *addr,
                                      grpc_resolved_addresses **addrs) {
  gpr_mu_lock(&g_mu);
  GPR_ASSERT(0 == strcmp("test", name));
  if (g_fail_resolution) {
    g_fail_resolution = false;
    gpr_mu_unlock(&g_mu);
    return GRPC_ERROR_CREATE("Forced Failure");
  } else {
    gpr_mu_unlock(&g_mu);
    *addrs = gpr_malloc(sizeof(**addrs));
    (*addrs)->naddrs = 1;
    (*addrs)->addrs = gpr_malloc(sizeof(*(*addrs)->addrs));
    (*addrs)->addrs[0].len = 123;
    return GRPC_ERROR_NONE;
  }
}

static grpc_resolver *create_resolver(grpc_exec_ctx *exec_ctx,
                                      const char *name) {
  grpc_resolver_factory *factory = grpc_resolver_factory_lookup("dns");
  grpc_uri *uri = grpc_uri_parse(exec_ctx, name, 0);
  GPR_ASSERT(uri);
  grpc_resolver_args args;
  memset(&args, 0, sizeof(args));
  args.uri = uri;
  args.combiner = g_combiner;
  grpc_resolver *resolver =
      grpc_resolver_factory_create_resolver(exec_ctx, factory, &args);
  grpc_resolver_factory_unref(factory);
  grpc_uri_destroy(uri);
  return resolver;
}

static void on_done(grpc_exec_ctx *exec_ctx, void *ev, grpc_error *error) {
  gpr_event_set(ev, (void *)1);
}

// interleave waiting for an event with a timer check
static bool wait_loop(int deadline_seconds, gpr_event *ev) {
  while (deadline_seconds) {
    gpr_log(GPR_DEBUG, "Test: waiting for %d more seconds", deadline_seconds);
    if (gpr_event_wait(ev, grpc_timeout_seconds_to_deadline(1))) return true;
    deadline_seconds--;

    grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
    grpc_timer_check(&exec_ctx, gpr_now(GPR_CLOCK_MONOTONIC), NULL);
    grpc_exec_ctx_finish(&exec_ctx);
  }
  return false;
}

typedef struct next_args {
  grpc_resolver *resolver;
  grpc_channel_args **result;
  grpc_closure *on_complete;
} next_args;

static void call_resolver_next_now_lock_taken(grpc_exec_ctx *exec_ctx,
                                              void *arg,
                                              grpc_error *error_unused) {
  next_args *a = arg;
  grpc_resolver_next_locked(exec_ctx, a->resolver, a->result, a->on_complete);
  gpr_free(a);
}

static void call_resolver_next_after_locking(grpc_exec_ctx *exec_ctx,
                                             grpc_resolver *resolver,
                                             grpc_channel_args **result,
                                             grpc_closure *on_complete) {
  next_args *a = gpr_malloc(sizeof(*a));
  a->resolver = resolver;
  a->result = result;
  a->on_complete = on_complete;
  grpc_closure_sched(
      exec_ctx,
      grpc_closure_create(call_resolver_next_now_lock_taken, a,
                          grpc_combiner_scheduler(resolver->combiner, false)),
      GRPC_ERROR_NONE);
}

int main(int argc, char **argv) {
  grpc_test_init(argc, argv);

  grpc_init();
  gpr_mu_init(&g_mu);
  g_combiner = grpc_combiner_create(NULL);
  grpc_blocking_resolve_address = my_resolve_address;
  grpc_channel_args *result = (grpc_channel_args *)1;

  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_resolver *resolver = create_resolver(&exec_ctx, "dns:test");
  gpr_event ev1;
  gpr_event_init(&ev1);
  call_resolver_next_after_locking(
      &exec_ctx, resolver, &result,
      grpc_closure_create(on_done, &ev1, grpc_schedule_on_exec_ctx));
  grpc_exec_ctx_flush(&exec_ctx);
  GPR_ASSERT(wait_loop(5, &ev1));
  GPR_ASSERT(result == NULL);

  gpr_event ev2;
  gpr_event_init(&ev2);
  call_resolver_next_after_locking(
      &exec_ctx, resolver, &result,
      grpc_closure_create(on_done, &ev2, grpc_schedule_on_exec_ctx));
  grpc_exec_ctx_flush(&exec_ctx);
  GPR_ASSERT(wait_loop(30, &ev2));
  GPR_ASSERT(result != NULL);

  grpc_channel_args_destroy(&exec_ctx, result);
  GRPC_RESOLVER_UNREF(&exec_ctx, resolver, "test");
  GRPC_COMBINER_UNREF(&exec_ctx, g_combiner, "test");
  grpc_exec_ctx_finish(&exec_ctx);

  grpc_shutdown();
  gpr_mu_destroy(&g_mu);
}


text:
package sched // import "github.com/leapar/bosun/cmd/bosun/sched"
import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"github.com/leapar/bosun/metadata"
	"github.com/leapar/bosun/opentsdb"
	"github.com/leapar/bosun/slog"
)

func (s *Schedule) Host(filter, uid string) (map[string]*HostData, error) {
	timeFilterAge := time.Hour * 2 * 24
	hosts := make(map[string]*HostData)
	allHosts, err := s.Search.TagValuesByTagKey("host", uid, timeFilterAge)
	if err != nil {
		return nil, err
	}
	for _, h := range allHosts {
		hosts[h] = newHostData()
	}
	states, err := s.GetOpenStates()
	if err != nil {
		return nil, err
	}
	silences := s.Silenced()
	// These are all fetched by metric since that is how we store it in redis,
	// so this makes for the fastest response
	tagsByKey := func(metric, hostKey string) (map[string][]opentsdb.TagSet, error) {
		byKey := make(map[string][]opentsdb.TagSet)
		tags, err := s.Search.FilteredTagSets(metric, uid, nil, 0)
		if err != nil {
			return byKey, err
		}
		for _, ts := range tags {
			if host, ok := ts[hostKey]; ok {
				// Make sure the host exists based on our time filter
				if _, ok := hosts[host]; ok {
					byKey[host] = append(byKey[host], ts)
				}
			}
		}
		return byKey, nil
	}
	oldTimestamp := utcNow().Add(-timeFilterAge).Unix()
	oldOrErr := func(ts int64, err error) bool {
		if ts < oldTimestamp || err != nil {
			return true
		}
		return false
	}
	osNetBytesTags, err := tagsByKey("os.net.bytes", "host")
	if err != nil {
		return nil, err
	}
	osNetVirtualBytesTags, err := tagsByKey("os.net.virtual.bytes", "host")
	if err != nil {
		return nil, err
	}
	osNetBondBytesTags, err := tagsByKey("os.net.bond.bytes", "host")
	if err != nil {
		return nil, err
	}
	osNetTunnelBytesTags, err := tagsByKey("os.net.tunnel.bytes", "host")
	if err != nil {
		return nil, err
	}
	osNetOtherBytesTags, err := tagsByKey("os.net.other.bytes", "host")
	if err != nil {
		return nil, err
	}
	osNetIfSpeedTags, err := tagsByKey("os.net.ifspeed", "host")
	if err != nil {
		return nil, err
	}
	osNetVirtualIfSpeedTags, err := tagsByKey("os.net.virtual.ifspeed", "host")
	if err != nil {
		return nil, err
	}
	osNetBondIfSpeedTags, err := tagsByKey("os.net.bond.ifspeed", "host")
	if err != nil {
		return nil, err
	}
	osNetTunnelIfSpeedTags, err := tagsByKey("os.net.tunnel.ifspeed", "host")
	if err != nil {
		return nil, err
	}
	osNetOtherIfSpeedTags, err := tagsByKey("os.net.other.ifspeed", "host")
	if err != nil {
		return nil, err
	}
	hwChassisTags, err := tagsByKey("hw.chassis", "host")
	if err != nil {
		return nil, err
	}
	hwPhysicalDiskTags, err := tagsByKey("hw.storage.pdisk", "host")
	if err != nil {
		return nil, err
	}
	hwVirtualDiskTags, err := tagsByKey("hw.storage.vdisk", "host")
	if err != nil {
		return nil, err
	}
	hwControllersTags, err := tagsByKey("hw.storage.controller", "host")
	if err != nil {
		return nil, err
	}
	hwBatteriesTags, err := tagsByKey("hw.storage.battery", "host")
	if err != nil {
		return nil, err
	}
	hwPowerSuppliesTags, err := tagsByKey("hw.ps", "host")
	if err != nil {
		return nil, err
	}
	hwTempsTags, err := tagsByKey("hw.chassis.temps.reading", "host")
	if err != nil {
		return nil, err
	}
	hwBoardPowerTags, err := tagsByKey("hw.chassis.power.reading", "host")
	if err != nil {
		return nil, err
	}
	diskTags, err := tagsByKey("os.disk.fs.space_total", "host")
	if err != nil {
		return nil, err
	}
	serviceTags, err := tagsByKey("os.service.running", "host")
	if err != nil {
		return nil, err
	}
	// Will assume the same tagsets exist .mem_real, .mem_virtual and possibly .count
	processTags, err := tagsByKey("os.proc.cpu", "host")
	if err != nil {
		return nil, err
	}
	// Will make the assumption that the metric bosun.ping.timeout, resolved, and rtt
	// all share the same tagset
	icmpTimeOutTags, err := tagsByKey("bosun.ping.timeout", "dst_host")
	if err != nil {
		return nil, err
	}
	for name, host := range hosts {
		host.Name = name
		hostTagSet := opentsdb.TagSet{"host": host.Name}
		hostMetadata, err := s.GetMetadata("", hostTagSet)
		if err != nil {
			slog.Error(err)
		}
		processHostIncidents(host, states, silences)
		for _, ts := range icmpTimeOutTags[host.Name] {
			// The host tag represents the polling source for these set of metrics
			source, ok := ts["host"]
			if !ok {
				slog.Errorf("couldn't find source tag for icmp data for host %s", host.Name)
			}
			// 1 Means it timed out
			timeout, timestamp, err := s.Search.GetLast("bosun.ping.timeout", ts.String(), false)
			if oldOrErr(timestamp, err) {
				continue
			}
			rtt, rttTimestamp, _ := s.Search.GetLast("bosun.ping.rtt", ts.String(), false)
			// 1 means dns resolution was successful
			dnsLookup, dnsTimestamp, dnsErr := s.Search.GetLast("bosun.ping.resolved", ts.String(), false)
			host.ICMPData[source] = &ICMPData{
				TimedOut:               timeout == 1 && err == nil,
				TimedOutLastUpdated:    timestamp,
				DNSResolved:            dnsLookup == 1 && dnsErr == nil,
				DNSResolvedLastUpdated: dnsTimestamp,
				RTTMS:          rtt,
				RTTLastUpdated: rttTimestamp,
			}

		}
		for _, ts := range serviceTags[host.Name] {
			name, ok := ts["name"]
			if !ok {
				slog.Errorf("couldn't find service name tag %s for host %s", name, host.Name)
				continue
			}
			fstatus, timestamp, err := s.Search.GetLast("os.service.running", ts.String(), false)
			running := false
			if fstatus != 0 {
				running = true
			}
			if !oldOrErr(timestamp, err) {
				host.Services[name] = &ServiceStatus{
					Running:            running,
					RunningLastUpdated: timestamp,
				}
			}
		}
		for _, ts := range processTags[host.Name] {
			name, ok := ts["name"]
			if !ok {
				slog.Errorf("couldn't find process name tag %s for host %s", name, host.Name)
				continue
			}
			p := &Process{}
			p.CPUPercentUsed, p.CPUPercentLastUpdated, err = s.Search.GetLast("os.proc.cpu", ts.String(), true)
			if oldOrErr(p.CPUPercentLastUpdated, err) {
				continue
			}
			p.UsedRealBytes, p.UsedRealBytesLastUpdated, _ = s.Search.GetLastInt64("os.proc.mem.real", ts.String(), false)
			p.UsedVirtualBytes, p.UsedVirtualBytesLastUpdated, _ = s.Search.GetLastInt64("os.proc.mem.virtual", ts.String(), false)
			p.Count, p.CountLastUpdated, _ = s.Search.GetLastInt64("os.proc.count", ts.String(), false)
			host.Processes[name] = p
		}
		// Process Hardware Chassis States
		for _, ts := range hwChassisTags[host.Name] {
			component, ok := ts["component"]
			if !ok {
				return nil, fmt.Errorf("couldn't find component tag for host %s", host.Name)
			}
			fstatus, timestamp, err := s.Search.GetLast("hw.chassis", ts.String(), false)
			if !oldOrErr(timestamp, err) {
				host.Hardware.ChassisComponents[component] = &ChassisComponent{
					Status:            statusString(int64(fstatus), 0, "Ok", "Bad"),
					StatusLastUpdated: timestamp,
				}
			}
		}
		for _, ts := range hwTempsTags[host.Name] {
			name, ok := ts["name"]
			if !ok {
				slog.Errorf("couldn't find name tag %s for host %s", name, host.Name)
			}
			t := &Temp{}
			var tStatus float64
			tStatus, t.StatusLastUpdated, err = s.Search.GetLast("hw.chassis.temps", ts.String(), false)
			t.Celsius, t.CelsiusLastUpdated, _ = s.Search.GetLast("hw.chassis.temps.reading", ts.String(), false)
			if oldOrErr(t.StatusLastUpdated, err) {
				continue
			}
			t.Status = statusString(int64(tStatus), 0, "Ok", "Bad")
			host.Hardware.Temps[name] = t
		}
		for _, ts := range hwPowerSuppliesTags[host.Name] {
			id, ok := ts["id"]
			if !ok {
				return nil, fmt.Errorf("couldn't find power supply tag for host %s", host.Name)
			}
			idPlus, err := strconv.Atoi(id)
			if err != nil {
				slog.Errorf("couldn't conver it do integer for power supply id %s", id)
			}
			idPlus++
			ps := &PowerSupply{}
			fstatus, timestamp, err := s.Search.GetLast("hw.ps", ts.String(), false)
			ps.Amps, ps.AmpsLastUpdated, _ = s.Search.GetLast("hw.chassis.current.reading", opentsdb.TagSet{"host": host.Name, "id": fmt.Sprintf("PS%v", idPlus)}.String(), false)
			ps.Volts, ps.VoltsLastUpdated, _ = s.Search.GetLast("hw.chassis.volts.reading", opentsdb.TagSet{"host": host.Name, "name": fmt.Sprintf("PS%v_Voltage_%v", idPlus, idPlus)}.String(), false)
			if oldOrErr(timestamp, err) {
				continue
			}
			ps.Status = statusString(int64(fstatus), 0, "Ok", "Bad")
			host.Hardware.PowerSupplies[id] = ps
			for _, m := range hostMetadata {
				if m.Name != "psMeta" || m.Time.Before(utcNow().Add(-timeFilterAge)) || !m.Tags.Equal(ts) {
					continue
				}
				if val, ok := m.Value.(string); ok {
					err = json.Unmarshal([]byte(val), &ps)
					if err != nil {
						slog.Errorf("error unmarshalling power supply meta for host %s, while generating host api: %s", host.Name, err)
					} else {
						host.Hardware.PowerSupplies[id] = ps
					}
				}
			}
		}
		for _, ts := range hwBatteriesTags[host.Name] {
			id, ok := ts["id"]
			if !ok {
				slog.Errorf("couldn't find battery id tag %s for host %s", id, host.Name)
				continue
			}
			fstatus, timestamp, err := s.Search.GetLast("hw.storage.battery", ts.String(), false)
			if !oldOrErr(timestamp, err) {
				host.Hardware.Storage.Batteries[id] = &Battery{
					Status:            statusString(int64(fstatus), 0, "Ok", "Bad"),
					StatusLastUpdated: timestamp,
				}
			}
		}
		for _, ts := range hwBoardPowerTags[host.Name] {
			fstatus, timestamp, err := s.Search.GetLast("hw.chassis.power.reading", ts.String(), false)
			if !oldOrErr(timestamp, err) {
				host.Hardware.BoardPowerReading = &BoardPowerReading{
					Watts:            int64(fstatus),
					WattsLastUpdated: timestamp,
				}
			}
		}
		for _, ts := range hwPhysicalDiskTags[host.Name] {
			id, ok := ts["id"]
			if !ok {
				return nil, fmt.Errorf("couldn't find physical disk id tag for host %s", host.Name)
			}
			pd := &PhysicalDisk{}
			fstatus, timestamp, err := s.Search.GetLast("hw.storage.pdisk", ts.String(), false)
			if !oldOrErr(timestamp, err) {
				pd.Status = statusString(int64(fstatus), 0, "Ok", "Bad")
				pd.StatusLastUpdated = timestamp
				host.Hardware.Storage.PhysicalDisks[id] = pd
			}
			for _, m := range hostMetadata {
				if m.Name != "physicalDiskMeta" || m.Time.Before(utcNow().Add(-timeFilterAge)) || !m.Tags.Equal(ts) {
					continue
				}
				if val, ok := m.Value.(string); ok {
					err = json.Unmarshal([]byte(val), &pd)
					if err != nil {
						slog.Errorf("error unmarshalling addresses for host %s, interface %s while generating host api: %s", host.Name, m.Tags["iface"], err)
					} else {
						host.Hardware.Storage.PhysicalDisks[id] = pd
					}
				}
			}
		}
		for _, ts := range hwVirtualDiskTags[host.Name] {
			id, ok := ts["id"]
			if !ok {
				return nil, fmt.Errorf("couldn't find virtual disk id tag for host %s", host.Name)
			}
			fstatus, timestamp, err := s.Search.GetLast("hw.storage.vdisk", ts.String(), false)
			if !oldOrErr(timestamp, err) {
				host.Hardware.Storage.VirtualDisks[id] = &VirtualDisk{
					Status:            statusString(int64(fstatus), 0, "Ok", "Bad"),
					StatusLastUpdated: timestamp,
				}
			}
		}
		for _, ts := range hwControllersTags[host.Name] {
			id, ok := ts["id"]
			if !ok {
				return nil, fmt.Errorf("couldn't find controller id tag for host %s", host.Name)
			}
			fstatus, timestamp, err := s.Search.GetLast("hw.storage.controller", ts.String(), false)
			c := &Controller{}
			if !oldOrErr(timestamp, err) {
				c.Status = statusString(int64(fstatus), 0, "Ok", "Bad")
				c.StatusLastUpdated = timestamp
				host.Hardware.Storage.Controllers[id] = c
			}
			for _, m := range hostMetadata {
				if m.Name != "controllerMeta" || m.Time.Before(utcNow().Add(-timeFilterAge)) || !m.Tags.Equal(ts) {
					continue
				}
				if val, ok := m.Value.(string); ok {
					err = json.Unmarshal([]byte(val), &c)
					if err != nil {
						slog.Errorf("error unmarshalling controller meta for host %s: %s", host.Name, err)
					} else {
						host.Hardware.Storage.Controllers[id] = c
					}
				}
			}
		}
		for _, ts := range diskTags[host.Name] {
			disk, ok := ts["disk"]
			if !ok {
				return nil, fmt.Errorf("couldn't find disk tag for host %s", host.Name)
			}
			d := &Disk{}
			d.TotalBytes, d.StatsLastUpdated, err = s.Search.GetLastInt64("os.disk.fs.space_total", ts.String(), false)
			d.UsedBytes, _, _ = s.Search.GetLastInt64("os.disk.fs.space_used", ts.String(), false)
			if oldOrErr(d.StatsLastUpdated, err) {
				continue
			}
			host.Disks[disk] = d
			for _, m := range hostMetadata {
				if m.Name != "label" || m.Time.Before(utcNow().Add(-timeFilterAge)) || !m.Tags.Equal(ts) {
					continue
				}
				if label, ok := m.Value.(string); ok {
					host.Disks[disk].Label = label
					break
				}
			}
		}
		// Get CPU, Memory, Uptime
		var timestamp int64
		var cpu float64
		if cpu, timestamp, err = s.Search.GetLast("os.cpu", hostTagSet.String(), true); err != nil {
			cpu, timestamp, _ = s.Search.GetLast("cisco.cpu", hostTagSet.String(), false)
		}
		host.CPU.PercentUsed = cpu
		host.CPU.StatsLastUpdated = timestamp
		host.Memory.TotalBytes, host.Memory.StatsLastUpdated, _ = s.Search.GetLast("os.mem.total", hostTagSet.String(), false)
		host.Memory.UsedBytes, _, _ = s.Search.GetLast("os.mem.used", hostTagSet.String(), false)
		host.UptimeSeconds, _, _ = s.Search.GetLastInt64("os.system.uptime", hostTagSet.String(), false)
		for _, m := range hostMetadata {
			if m.Time.Before(utcNow().Add(-timeFilterAge)) {
				continue
			}
			var iface *HostInterface
			if name := m.Tags["iface"]; name != "" {
				if host.Interfaces[name] == nil {
					h := new(HostInterface)
					host.Interfaces[name] = h
				}
				iface = host.Interfaces[name]
			}
			if name := m.Tags["iname"]; name != "" && iface != nil {
				iface.Name = name
			}
			switch val := m.Value.(type) {
			case string:
				switch m.Name {
				case "addresses":
					if iface != nil {
						addresses := []string{}
						err = json.Unmarshal([]byte(val), &addresses)
						if err != nil {
							slog.Errorf("error unmarshalling addresses for host %s, interface %s while generating host api: %s", host.Name, m.Tags["iface"], err)
						}
						for _, address := range addresses {
							iface.IPAddresses = append(iface.IPAddresses, address)
						}
					}
				case "cdpCacheEntries":
					if iface != nil {
						var cdpCacheEntries CDPCacheEntries
						err = json.Unmarshal([]byte(val), &cdpCacheEntries)
						if err != nil {
							slog.Errorf("error unmarshalling cdpCacheEntries for host %s, interface %s while generating host api: %s", host.Name, m.Tags["iface"], err)
						} else {
							iface.CDPCacheEntries = cdpCacheEntries
						}
					}
				case "remoteMacs":
					if iface != nil {
						remoteMacs := []string{}
						err = json.Unmarshal([]byte(val), &remoteMacs)
						if err != nil {
							slog.Errorf("error unmarshalling remoteMacs for host %s, interface %s while generating host api: %s", host.Name, m.Tags["iface"], err)
						} else {
							iface.RemoteMacs = remoteMacs
						}
					}
				case "description", "alias":
					if iface != nil {
						iface.Description = val
					}
				case "dataStores":
					dataStores := []string{}
					err = json.Unmarshal([]byte(val), &dataStores)
					if err != nil {
						slog.Errorf("error unmarshalling datastores for host %s while generating host api: %s", host.Name, err)
					}
					for _, dataStore := range dataStores {
						tags := opentsdb.TagSet{"disk": dataStore}.String()
						total, totalTs, totalErr := s.Search.GetLastInt64("vsphere.disk.space_total", tags, false)
						used, usedTs, usedErr := s.Search.GetLastInt64("vsphere.disk.space_used", tags, false)
						if totalErr != nil || usedErr != nil || totalTs < 1 || usedTs < 1 {
							continue
						}
						host.Disks[dataStore] = &Disk{
							TotalBytes: total,
							UsedBytes:  used,
						}
					}
				case "mac":
					if iface != nil {
						iface.MAC = val
					}
				case "manufacturer":
					host.Manufacturer = val
				case "master":
					if iface != nil {
						iface.Master = val
					}
				case "memory":
					if name := m.Tags["name"]; name != "" {
						fstatus, timestamp, err := s.Search.GetLast("hw.chassis.memory", opentsdb.TagSet{"host": host.Name, "name": name}.String(), false)
						// Status code uses the severity function in collectors/dell_hw.go. That is a binary
						// state that is 0 for non-critical or Ok. Todo would be to update this with more
						// complete status codes when HW collector is refactored and we have something to
						// clean out addr entries from the tagset metadata db
						host.Hardware.Memory[name] = &MemoryModule{
							StatusLastUpdated: timestamp,
							Size:              val,
						}
						// Only set if we have a value
						if err == nil && timestamp > 0 {
							host.Hardware.Memory[name].Status = statusString(int64(fstatus), 0, "Ok", "Bad")
						}
					}
				case "hypervisor":
					host.VM = &VM{}
					host.VM.Host = val
					powerstate, timestamp, err := s.Search.GetLast("vsphere.guest.powered_state", opentsdb.TagSet{"guest": host.Name}.String(), false)
					if timestamp > 0 && err != nil {
						switch int64(powerstate) {
						case 0:
							host.VM.PowerState = "poweredOn"
						case 1:
							host.VM.PowerState = "poweredOff"
						case 2:
							host.VM.PowerState = "suspended"
						}
						host.VM.PowerStateLastUpdated = timestamp
					}
					if hostsHost, ok := hosts[val]; ok {
						hostsHost.Guests = append(hostsHost.Guests, host.Name)
					}
				case "model":
					host.Model = val
				case "name":
					if iface != nil {
						iface.Name = val
					}
				case "processor":
					if name := m.Tags["name"]; name != "" {
						host.CPU.Processors[name] = val
					}
				case "serialNumber":
					host.SerialNumber = val
				case "version":
					host.OS.Version = val
				case "versionCaption", "uname":
					host.OS.Caption = val
				}
			case float64:
				switch m.Name {
				case "speed":
					if iface != nil {
						iface.LinkSpeed = int64(val)
					}
				}
			}
		}
		GetIfaceBits := func(netType string, ifaceId string, iface *HostInterface, host string, tags []opentsdb.TagSet) error {
			metric := "os.net." + netType + ".bytes"
			if netType == "" {
				metric = "os.net.bytes"
			}
			for _, ts := range tags {
				if ts["iface"] != ifaceId {
					continue
				}
				dir, ok := ts["direction"]
				if !ok {
					continue
				}
				val, timestamp, _ := s.Search.GetLastInt64(metric, ts.String(), true)
				if dir == "in" {
					iface.Inbps = val * 8
				}
				if dir == "out" {
					iface.Outbps = val * 8
				}
				iface.StatsLastUpdated = timestamp
				iface.Type = netType
			}
			return nil
		}
		GetIfaceSpeed := func(netType string, ifaceId string, iface *HostInterface, host string, tags []opentsdb.TagSet) error {
			metric := "os.net." + netType + ".ifspeed"
			if netType == "" {
				metric = "os.net.ifspeed"
			}
			for _, ts := range tags {
				if ts["iface"] != ifaceId {
					continue
				}
				val, timestamp, err := s.Search.GetLastInt64(metric, ts.String(), false)
				if !oldOrErr(timestamp, err) {
					iface.LinkSpeed = val
				}
			}
			return nil
		}
		for ifaceId, iface := range host.Interfaces {
			if err := GetIfaceBits("", ifaceId, iface, host.Name, osNetBytesTags[host.Name]); err != nil {
				return nil, err
			}
			if err := GetIfaceBits("virtual", ifaceId, iface, host.Name, osNetVirtualBytesTags[host.Name]); err != nil {
				return nil, err
			}
			if err := GetIfaceBits("bond", ifaceId, iface, host.Name, osNetBondBytesTags[host.Name]); err != nil {
				return nil, err
			}
			if err := GetIfaceBits("tunnel", ifaceId, iface, host.Name, osNetTunnelBytesTags[host.Name]); err != nil {
				return nil, err
			}
			if err := GetIfaceBits("other", ifaceId, iface, host.Name, osNetOtherBytesTags[host.Name]); err != nil {
				return nil, err
			}
			if err := GetIfaceSpeed("", ifaceId, iface, host.Name, osNetIfSpeedTags[host.Name]); err != nil {
				return nil, err
			}
			if err := GetIfaceSpeed("virtual", ifaceId, iface, host.Name, osNetVirtualIfSpeedTags[host.Name]); err != nil {
				return nil, err
			}
			if err := GetIfaceSpeed("bond", ifaceId, iface, host.Name, osNetBondIfSpeedTags[host.Name]); err != nil {
				return nil, err
			}
			if err := GetIfaceSpeed("tunnel", ifaceId, iface, host.Name, osNetTunnelIfSpeedTags[host.Name]); err != nil {
				return nil, err
			}
			if err := GetIfaceSpeed("other", ifaceId, iface, host.Name, osNetOtherIfSpeedTags[host.Name]); err != nil {
				return nil, err
			}
		}
		host.Clean()
	}
	return hosts, nil
}

func statusString(val, goodVal int64, goodName, badName string) string {
	if val == goodVal {
		return goodName
	}
	return badName
}

func processHostIncidents(host *HostData, states States, silences SilenceTester) {
	for ak, state := range states {
		if stateHost, ok := state.AlertKey.Group()["host"]; !ok {
			continue
		} else if stateHost != host.Name {
			continue
		}
		silenced := silences(ak)
		is := IncidentStatus{
			IncidentID:         state.Id,
			Active:             state.IsActive(),
			AlertKey:           state.AlertKey,
			Status:             state.CurrentStatus,
			StatusTime:         state.Last().Time.Unix(),
			Subject:            state.Subject,
			Silenced:           silenced != nil,
			LastAbnormalStatus: state.LastAbnormalStatus,
			LastAbnormalTime:   state.LastAbnormalTime,
			NeedsAck:           state.NeedAck,
		}
		host.OpenIncidents = append(host.OpenIncidents, is)
	}
}

// Cisco Discovery Protocol
type CDPCacheEntry struct {
	DeviceID   string
	DevicePort string
}

type CDPCacheEntries []CDPCacheEntry

type HostInterface struct {
	Description      string          `json:",omitempty"`
	IPAddresses      []string        `json:",omitempty"`
	RemoteMacs       []string        `json:",omitempty"`
	CDPCacheEntries  CDPCacheEntries `json:",omitempty"`
	Inbps            int64
	LinkSpeed        int64  `json:",omitempty"`
	MAC              string `json:",omitempty"`
	Master           string `json:",omitempty"`
	Name             string `json:",omitempty"`
	Outbps           int64
	StatsLastUpdated int64
	Type             string
}

type Disk struct {
	UsedBytes        int64
	TotalBytes       int64
	Label            string `json:",omitempty"`
	StatsLastUpdated int64
}

type MemoryModule struct {
	// Maybe this should be a bool but that might be limiting
	Status            string
	StatusLastUpdated int64
	Size              string
}

type ChassisComponent struct {
	Status            string
	StatusLastUpdated int64
}

type PowerSupply struct {
	Status                     string
	StatusLastUpdated          int64
	Amps                       float64
	AmpsLastUpdated            int64
	Volts                      float64
	VoltsLastUpdated           int64
	metadata.HWPowerSupplyMeta //Should be renamed to Meta
}

type PhysicalDisk struct {
	Status            string
	StatusLastUpdated int64
	metadata.HWDiskMeta
}

type VirtualDisk struct {
	Status            string
	StatusLastUpdated int64
}

type Controller struct {
	Status            string
	StatusLastUpdated int64
	metadata.HWControllerMeta
}

type Temp struct {
	Celsius            float64
	Status             string
	StatusLastUpdated  int64
	CelsiusLastUpdated int64
}

type ICMPData struct {
	TimedOut               bool
	TimedOutLastUpdated    int64
	DNSResolved            bool
	DNSResolvedLastUpdated int64
	RTTMS                  float64
	RTTLastUpdated         int64
}

func newHostData() *HostData {
	hd := &HostData{}
	hd.CPU.Processors = make(map[string]string)
	hd.Interfaces = make(map[string]*HostInterface)
	hd.Disks = make(map[string]*Disk)
	hd.Services = make(map[string]*ServiceStatus)
	hd.Processes = make(map[string]*Process)
	hd.ICMPData = make(map[string]*ICMPData)
	hd.Hardware = &Hardware{}
	hd.Hardware.ChassisComponents = make(map[string]*ChassisComponent)
	hd.Hardware.Temps = make(map[string]*Temp)
	hd.Hardware.PowerSupplies = make(map[string]*PowerSupply)
	hd.Hardware.Memory = make(map[string]*MemoryModule)
	hd.Hardware.Storage.PhysicalDisks = make(map[string]*PhysicalDisk)
	hd.Hardware.Storage.VirtualDisks = make(map[string]*VirtualDisk)
	hd.Hardware.Storage.Controllers = make(map[string]*Controller)
	hd.Hardware.Storage.Batteries = make(map[string]*Battery)
	return hd
}

// Clean sets certain maps to nil so they don't get marshalled in JSON
// The logic is to remove ones that monitored devices might lack, such
// as hardware information
func (hd *HostData) Clean() {
	if len(hd.CPU.Processors) == 0 {
		hd.CPU.Processors = nil
	}
	if len(hd.Disks) == 0 {
		hd.Disks = nil
	}
	if len(hd.Services) == 0 {
		hd.Services = nil
	}
	if len(hd.Processes) == 0 {
		hd.Processes = nil
	}
	hwLen := len(hd.Hardware.ChassisComponents) +
		len(hd.Hardware.Memory) +
		len(hd.Hardware.Storage.PhysicalDisks) +
		len(hd.Hardware.Storage.VirtualDisks) +
		len(hd.Hardware.Storage.Controllers) +
		len(hd.Hardware.PowerSupplies) +
		len(hd.Hardware.Temps) +
		len(hd.Hardware.Storage.Batteries)
	if hwLen == 0 {
		hd.Hardware = nil
	}
}

type Hardware struct {
	Memory            map[string]*MemoryModule     `json:",omitempty"`
	ChassisComponents map[string]*ChassisComponent `json:",omitempty"`
	Storage           struct {
		Controllers   map[string]*Controller   `json:",omitempty"`
		PhysicalDisks map[string]*PhysicalDisk `json:",omitempty"`
		VirtualDisks  map[string]*VirtualDisk  `json:",omitempty"`
		Batteries     map[string]*Battery
	}
	Temps             map[string]*Temp
	PowerSupplies     map[string]*PowerSupply `json:",omitempty"`
	BoardPowerReading *BoardPowerReading
}

type BoardPowerReading struct {
	Watts            int64
	WattsLastUpdated int64
}

type VM struct {
	Host                  string `json:",omitempty"`
	PowerState            string `json:",omitempty"`
	PowerStateLastUpdated int64  `json:",omitempty"`
}

type Battery struct {
	Status            string
	StatusLastUpdated int64
}

type ServiceStatus struct {
	Running            bool
	RunningLastUpdated int64
}

type Process struct {
	CPUPercentUsed              float64
	CPUPercentLastUpdated       int64
	UsedRealBytes               int64
	UsedRealBytesLastUpdated    int64
	UsedVirtualBytes            int64
	UsedVirtualBytesLastUpdated int64
	Count                       int64
	CountLastUpdated            int64
}

type HostData struct {
	CPU struct {
		Logical          int64 `json:",omitempty"`
		Physical         int64 `json:",omitempty"`
		PercentUsed      float64
		StatsLastUpdated int64
		Processors       map[string]string `json:",omitempty"`
	}
	ICMPData      map[string]*ICMPData
	Disks         map[string]*Disk
	OpenIncidents []IncidentStatus
	Interfaces    map[string]*HostInterface
	UptimeSeconds int64     `json:",omitempty"`
	Manufacturer  string    `json:",omitempty"`
	Hardware      *Hardware `json:",omitempty"`
	Memory        struct {
		TotalBytes       float64
		UsedBytes        float64
		StatsLastUpdated int64
	}
	Processes map[string]*Process       `json:",omitempty"`
	Services  map[string]*ServiceStatus `json:",omitempty"`
	Model     string                    `json:",omitempty"`
	Name      string                    `json:",omitempty"`
	OS        struct {
		Caption string `json:",omitempty"`
		Version string `json:",omitempty"`
	}
	SerialNumber string   `json:",omitempty"`
	VM           *VM      `json:",omitempty"`
	Guests       []string `json:",omitempty"`
}


text:
#include "coreprivshared.hpp"
#include "fxiotarget.hpp"

extern "C" {
#include "FxDeviceApiKm.tmh"
}

//
// extern "C" the entire file
//
extern "C" {

//
// Verifier Functions
//
// Do not specify argument names
FX_DECLARE_VF_FUNCTION_P3(
VOID,
VerifyWdfDeviceWdmDispatchIrp,
    _In_ PWDF_DRIVER_GLOBALS,
    _In_ FxDevice*,
    _In_ WDFCONTEXT
    );

// Do not specify argument names
FX_DECLARE_VF_FUNCTION_P4(
NTSTATUS,
VerifyWdfDeviceWdmDispatchIrpToIoQueue,
    _In_ FxDevice*,
    _In_ MdIrp,
    _In_ FxIoQueue*,
    _In_ ULONG
    );

__drv_maxIRQL(DISPATCH_LEVEL)
WDFDEVICE
WDFEXPORT(WdfWdmDeviceGetWdfDeviceHandle)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    PDEVICE_OBJECT DeviceObject
    )
{
    FxPointerNotNull(GetFxDriverGlobals(DriverGlobals), DeviceObject);

    return FxDevice::GetFxDevice(DeviceObject)->GetHandle();
}

__drv_maxIRQL(DISPATCH_LEVEL)
PDEVICE_OBJECT
WDFEXPORT(WdfDeviceWdmGetDeviceObject)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device
    )
{
    FxDeviceBase *pDevice;

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Device,
                         FX_TYPE_DEVICE_BASE,
                         (PVOID*) &pDevice);

    return pDevice->GetDeviceObject();
}

__drv_maxIRQL(DISPATCH_LEVEL)
PDEVICE_OBJECT
WDFEXPORT(WdfDeviceWdmGetAttachedDevice)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device
    )
{
    FxDeviceBase *pDevice;

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Device,
                         FX_TYPE_DEVICE_BASE,
                         (PVOID*) &pDevice);

    return pDevice->GetAttachedDevice();
}

__drv_maxIRQL(DISPATCH_LEVEL)
PDEVICE_OBJECT
WDFEXPORT(WdfDeviceWdmGetPhysicalDevice)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device
    )
{
    FxDeviceBase *pDevice;

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Device,
                         FX_TYPE_DEVICE_BASE,
                         (PVOID*) &pDevice);

    return pDevice->GetPhysicalDevice();
}

__drv_maxIRQL(DISPATCH_LEVEL)
WDFFILEOBJECT
WDFEXPORT(WdfDeviceGetFileObject)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    MdFileObject FileObject
    )
/*++

Routine Description:

    This functions returns the WDFFILEOBJECT corresponding to the WDM fileobject.

Arguments:

    Device - Handle to the device to which the WDM fileobject is related to.

    FileObject - WDM FILE_OBJECT structure.

Return Value:

--*/

{
    PFX_DRIVER_GLOBALS pFxDriverGlobals;
    NTSTATUS status;
    FxFileObject* pFxFO;
    FxDevice *pDevice;

    pFxDriverGlobals = GetFxDriverGlobals(DriverGlobals);

    pFxFO = NULL;

    //
    // Validate the Device object handle, and get its FxDevice*
    //
    FxObjectHandleGetPtr(pFxDriverGlobals,
                         Device,
                         FX_TYPE_DEVICE,
                         (PVOID*)&pDevice);

    //
    // Call the static GetFileObjectFromWdm function. This will return an error if the
    // WDM fileObject is NULL and the device is not exclusive or the device is
    // configured to have a WDFFILEOBJECT for every open handle.
    //
    status = FxFileObject::_GetFileObjectFromWdm(
        pDevice,
        pDevice->GetFileObjectClass(),
        FileObject,
        &pFxFO
        );

    if (!NT_SUCCESS(status)) {
         DoTraceLevelMessage(
             pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
             "FxFileObject::_GetFileObjectFromWdm returned an error %!STATUS!",
             status);
         return NULL;
    }

    //
    // pFxFO can be NULL if the device is configured with FileObjectClass WdfFileObjectNotRequired.
    //
    return pFxFO != NULL ? pFxFO->GetHandle() : NULL;
}

_Must_inspect_result_
__drv_maxIRQL(DISPATCH_LEVEL)
NTSTATUS
WDFEXPORT(WdfDeviceWdmDispatchPreprocessedIrp)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    MdIrp Irp
    )
{
    FxDevice            *device;
    PFX_DRIVER_GLOBALS  fxDriverGlobals;

    FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals),
                                   Device,
                                   FX_TYPE_DEVICE,
                                   (PVOID*) &device,
                                   &fxDriverGlobals);

    FxPointerNotNull(fxDriverGlobals, Irp);

    //
    // Verifier checks.
    // This API can only be called by the client driver, Cx must call
    // WdfDeviceWdmDispatchIrp from its preprocess callback.
    // Also, Cx must register for a Preprocessor routine using
    // WdfCxDeviceInitAssignWdmIrpPreprocessCallback.
    //
    if (fxDriverGlobals->IsVerificationEnabled(1, 11, OkForDownLevel)) {
        if (device->IsCxInIoPath()) {
            FxDriver* driver = GetFxDriverGlobals(DriverGlobals)->Driver;

            if (IsListEmpty(&device->m_PreprocessInfoListHead) ||
                device->IsCxDriverInIoPath(driver)) {

                DoTraceLevelMessage(
                        fxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGIO,
                        "This API can only be called by client driver from its "
                        "pre-process IRP callback, STATUS_INVALID_DEVICE_REQUEST");
                FxVerifierDbgBreakPoint(fxDriverGlobals);
            }
        }
    }

    //
    // OK, ready to dispatch IRP.
    //
    return device->DispatchPreprocessedIrp(
                        Irp,
                        device->m_PreprocessInfoListHead.Flink->Flink);
}

VOID
FX_VF_FUNCTION(VerifyWdfDeviceWdmDispatchIrp) (
    _In_ PFX_DRIVER_GLOBALS FxDriverGlobals,
    _In_ PWDF_DRIVER_GLOBALS DriverGlobals,
    _In_ FxDevice* device,
    _In_ WDFCONTEXT  DispatchContext
    )
{
    UNREFERENCED_PARAMETER(FxDriverGlobals);
    FxDriver*   driver;
    BOOLEAN     ctxValid;
    PLIST_ENTRY next;
    NTSTATUS    status;

    PAGED_CODE_LOCKED();

    status = STATUS_SUCCESS;
    driver = GetFxDriverGlobals(DriverGlobals)->Driver;
    ctxValid = (PLIST_ENTRY)DispatchContext ==
                &device->m_PreprocessInfoListHead ? TRUE : FALSE;
    //
    // Driver should be a cx.
    //
    if (device->IsCxDriverInIoPath(driver) == FALSE) {
        status = STATUS_INVALID_DEVICE_REQUEST;
        DoTraceLevelMessage(
                device->GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGIO,
                "This API can only be called by wdf extension driver "
                "from its pre-process IRP callback, %!STATUS!",
                status);
        FxVerifierDbgBreakPoint(device->GetDriverGlobals());
    }

    //
    // Validate DispatchContext.
    //

    for (next = device->m_PreprocessInfoListHead.Flink;
         next != &device->m_PreprocessInfoListHead;
         next = next->Flink) {
        if ((PLIST_ENTRY)DispatchContext == next) {
            ctxValid = TRUE;
            break;
        }
    }

    if (FALSE == ctxValid) {
        status = STATUS_INVALID_PARAMETER;
        DoTraceLevelMessage(
                device->GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGIO,
                "DispatchContext 0x%p is invalid, %!STATUS!",
                DispatchContext, status);
        FxVerifierDbgBreakPoint(device->GetDriverGlobals());
    }
}

_Must_inspect_result_
__drv_maxIRQL(DISPATCH_LEVEL)
NTSTATUS
WDFEXPORT(WdfDeviceWdmDispatchIrp)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    MdIrp Irp,
    __in
    WDFCONTEXT DispatchContext
    )

/*++

Routine Description:

    Client driver calls this API from its dispatch callback when it decides to hand the IRP
    back to framework.

    Cx calls this API from (a) its pre-process callback or (b) its dispatch callback when
    it decides to hand the IRP back to the framework.

Arguments:
    Device - WDF Device handle.

    IRP - WDM request.

    DispatchContext - WDF's context (input arg to callback).

Returns:
    IRP's status.

--*/

{
    FxDevice *device;
    NTSTATUS status;

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Device,
                         FX_TYPE_DEVICE,
                         (PVOID*) &device);

    FxPointerNotNull(device->GetDriverGlobals(), Irp);
    FxPointerNotNull(device->GetDriverGlobals(), DispatchContext);

    if ((UCHAR)DispatchContext & FX_IN_DISPATCH_CALLBACK) {
        //
        // Called from a dispach irp callback.
        //
        DispatchContext =
            (WDFCONTEXT)((ULONG_PTR)DispatchContext & ~FX_IN_DISPATCH_CALLBACK);

        //
        // DispatchContext is validated by DispatchStep1.
        //
        status = device->m_PkgIo->DispatchStep1(Irp, DispatchContext);
    }
    else {
        //
        // Called from a pre-process irp callback.
        //

        //
        // Verifier checks.
        //
        VerifyWdfDeviceWdmDispatchIrp(device->GetDriverGlobals(),
                                      DriverGlobals,
                                      device,
                                      DispatchContext);

        status = device->DispatchPreprocessedIrp(Irp, DispatchContext);
    }

    return status;
}

_Must_inspect_result_
__drv_maxIRQL(DISPATCH_LEVEL)
NTSTATUS
WDFEXPORT(WdfDeviceWdmDispatchIrpToIoQueue)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    MdIrp Irp,
    __in
    WDFQUEUE Queue,
    __in
    ULONG Flags
    )
{
    FxIoQueue           *queue;
    FxDevice            *device;
    PFX_DRIVER_GLOBALS  fxDriverGlobals;
    PIO_STACK_LOCATION  stack;
    NTSTATUS            status;
    FxIoInCallerContext* ioInCallerCtx;

    queue = NULL;
    ioInCallerCtx = NULL;

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Device,
                         FX_TYPE_DEVICE,
                         (PVOID*) &device);

    fxDriverGlobals = device->GetDriverGlobals();
    FX_TRACK_DRIVER(fxDriverGlobals);

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Queue,
                         FX_TYPE_QUEUE,
                         (PVOID*)&queue);

    FxPointerNotNull(fxDriverGlobals, Irp);

    //
    // If the caller is a preprocess routine, the contract for this DDI is just like IoCallDriver.
    // The caller sets up their stack location and then the DDI advances to the next stack
    // location. This means that the caller either has to call IoSkipCurrentIrpStackLocation
    // or IoCopyCurrentIrpStackLocationToNext before calling this DDI.
    //
    if (Flags & WDF_DISPATCH_IRP_TO_IO_QUEUE_PREPROCESSED_IRP) {
        IoSetNextIrpStackLocation(Irp);
    }

    //
    // Verifier checks.
    //
    status = VerifyWdfDeviceWdmDispatchIrpToIoQueue(fxDriverGlobals,
                                                    device,
                                                    Irp,
                                                    queue,
                                                    Flags);
    if(!NT_SUCCESS(status)) {
        Irp->IoStatus.Status = status;
        Irp->IoStatus.Information = 0;
        IoCompleteRequest(Irp, IO_NO_INCREMENT);

        return status;
    }

    //
    // Adjust stack if IRP needs to be forwarded to parent device.
    //
    if (device->m_ParentDevice == queue->GetDevice()) {
        IoCopyCurrentIrpStackLocationToNext(Irp);
        IoSetNextIrpStackLocation(Irp);

        //
        // From now on use new device.
        //
        device = device->m_ParentDevice;

        //
        // Save a pointer to the device object for this request so that it can
        // be used later in completion.
        //
        stack = IoGetCurrentIrpStackLocation(Irp);
        stack->DeviceObject = device->GetDeviceObject();
    }

    //
    // Get in-context caller callback if required.
    //
    if (Flags & WDF_DISPATCH_IRP_TO_IO_QUEUE_INVOKE_INCALLERCTX_CALLBACK) {
        ioInCallerCtx = device->m_PkgIo->GetIoInCallerContextCallback(
                                                queue->GetCxDeviceInfo());
    }

    //
    // DispatchStep2 will convert the IRP into a WDFREQUEST, queue it and if
    // possible dispatch the request to the driver.
    //
    return device->m_PkgIo->DispatchStep2(Irp, ioInCallerCtx, queue);
}

_Must_inspect_result_
__drv_maxIRQL(DISPATCH_LEVEL)
NTSTATUS
WDFEXPORT(WdfDeviceAddDependentUsageDeviceObject)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    PDEVICE_OBJECT DependentDevice
    )
{
    PFX_DRIVER_GLOBALS pFxDriverGlobals;
    FxDevice *pDevice;

    FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals),
                                   Device,
                                   FX_TYPE_DEVICE,
                                   (PVOID *) &pDevice,
                                   &pFxDriverGlobals);

    FxPointerNotNull(pFxDriverGlobals, DependentDevice);

    return pDevice->m_PkgPnp->AddUsageDevice(DependentDevice);
}

__drv_maxIRQL(DISPATCH_LEVEL)
VOID
WDFEXPORT(WdfDeviceRemoveDependentUsageDeviceObject)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    PDEVICE_OBJECT DependentDevice
    )
{
    PFX_DRIVER_GLOBALS pFxDriverGlobals;
    FxDevice *pDevice;

    FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals),
                                   Device,
                                   FX_TYPE_DEVICE,
                                   (PVOID *) &pDevice,
                                   &pFxDriverGlobals);

    FxPointerNotNull(pFxDriverGlobals, DependentDevice);

    return pDevice->m_PkgPnp->RemoveUsageDevice(DependentDevice);
}

_Must_inspect_result_
__drv_maxIRQL(PASSIVE_LEVEL)
NTSTATUS
WDFEXPORT(WdfDeviceAssignMofResourceName)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    PCUNICODE_STRING MofResourceName
    )
{
    PFX_DRIVER_GLOBALS pFxDriverGlobals;
    FxDevice *pDevice;
    NTSTATUS status;

    FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals),
                                   Device,
                                   FX_TYPE_DEVICE,
                                   (PVOID *) &pDevice,
                                   &pFxDriverGlobals);

    FxPointerNotNull(pFxDriverGlobals, MofResourceName);

    status = FxVerifierCheckIrqlLevel(pFxDriverGlobals, PASSIVE_LEVEL);
    if (!NT_SUCCESS(status)) {
        return status;
    }

    status = FxValidateUnicodeString(pFxDriverGlobals, MofResourceName);
    if (!NT_SUCCESS(status)) {
        return status;
    }

    if (pDevice->m_MofResourceName.Buffer !=  NULL) {
        status = STATUS_INVALID_DEVICE_REQUEST;

        DoTraceLevelMessage(
            pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
            "WDFDEVICE %p MofResourceName already assigned, %!STATUS!",
            Device, status);

        return status;
    }

    status = FxDuplicateUnicodeString(pFxDriverGlobals,
                                      MofResourceName,
                                      &pDevice->m_MofResourceName);

    if (!NT_SUCCESS(status)) {
        DoTraceLevelMessage(
            pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
            "WDFDEVICE %p couldn't creat duplicate buffer, %!STATUS!",
            Device, status);
    }

    return status;
}

__drv_maxIRQL(DISPATCH_LEVEL)
VOID
WDFEXPORT(WdfDeviceSetSpecialFileSupport)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    WDF_SPECIAL_FILE_TYPE FileType,
    __in
    BOOLEAN Supported
    )
{
    FxDevice* pDevice;
    PFX_DRIVER_GLOBALS pFxDriverGlobals;

    FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals),
                                   Device,
                                   FX_TYPE_DEVICE,
                                   (PVOID *) &pDevice,
                                   &pFxDriverGlobals);

    if (FileType < WdfSpecialFilePaging  || FileType >= WdfSpecialFileMax) {
        DoTraceLevelMessage(
            pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
            "WDFDEVICE 0x%p FileType %d specified is not in valid range",
            Device, FileType);
        FxVerifierDbgBreakPoint(pFxDriverGlobals);
        return;
    }

    FxObjectHandleGetPtr(pFxDriverGlobals,
                         Device,
                         FX_TYPE_DEVICE,
                         (PVOID*) &pDevice);

    pDevice->m_PkgPnp->SetSpecialFileSupport(FileType, Supported);
}

_Must_inspect_result_
__drv_maxIRQL(DISPATCH_LEVEL)
NTSTATUS
WDFEXPORT(WdfDeviceIndicateWakeStatus)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    NTSTATUS WaitWakeStatus
    )
{
    NTSTATUS status;
    FxDevice *pDevice;
    PFX_DRIVER_GLOBALS pFxDriverGlobals;

    FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals),
                                   Device,
                                   FX_TYPE_DEVICE,
                                   (PVOID *) &pDevice,
                                   &pFxDriverGlobals);

    if (Device == NULL ||
        WaitWakeStatus == STATUS_PENDING || WaitWakeStatus == STATUS_CANCELLED) {
        DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
                            "NULL WDFDEVICE handle %p or invalid %!STATUS!",
                            Device, WaitWakeStatus);
        return STATUS_INVALID_PARAMETER;
    }

    if (pDevice->m_PkgPnp->m_SharedPower.m_WaitWakeOwner) {
        if (pDevice->m_PkgPnp->PowerIndicateWaitWakeStatus(WaitWakeStatus)) {
            status = STATUS_SUCCESS;
        }
        else {
            //
            // There was no request to complete
            //
            DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
                                "WDFDEVICE 0x%p  No request to complete"
                                " STATUS_INVALID_DEVICE_REQUEST",
                                Device);

            status = STATUS_INVALID_DEVICE_REQUEST;
        }
    }
    else {
        //
        // We cannot complete what we do not own
        //
        DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
                            "WDFDEVICE 0x%p  Not the waitwake owner"
                            " STATUS_INVALID_DEVICE_STATE",
                            Device);

        status = STATUS_INVALID_DEVICE_STATE;
    }

    return status;
}

__drv_maxIRQL(DISPATCH_LEVEL)
VOID
WDFEXPORT(WdfDeviceSetBusInformationForChildren)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    PPNP_BUS_INFORMATION BusInformation
    )
{
    FxDevice* pDevice;

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Device,
                         FX_TYPE_DEVICE,
                         (PVOID*) &pDevice);

    FxPointerNotNull(pDevice->GetDriverGlobals(), BusInformation);

    pDevice->m_PkgPnp->SetChildBusInformation(BusInformation);
}

_Must_inspect_result_
__drv_maxIRQL(DISPATCH_LEVEL)
NTSTATUS
WDFEXPORT(WdfDeviceAddRemovalRelationsPhysicalDevice)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    PDEVICE_OBJECT PhysicalDevice
    )
/*++

Routine Description:
    Registers a PDO from another non descendant (not verifiable though) pnp
    stack to be reported as also requiring removal when this PDO is removed.

    The PDO could be another device enumerated by this driver.

Arguments:
    Device - this driver's PDO

    PhysicalDevice - PDO for another stack

Return Value:
    NTSTATUS

  --*/
{
    FxDevice* pDevice;

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Device,
                         FX_TYPE_DEVICE,
                         (PVOID*) &pDevice);

    FxPointerNotNull(pDevice->GetDriverGlobals(), PhysicalDevice);

    return pDevice->m_PkgPnp->AddRemovalDevice(PhysicalDevice);
}

__drv_maxIRQL(DISPATCH_LEVEL)
VOID
WDFEXPORT(WdfDeviceRemoveRemovalRelationsPhysicalDevice)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    PDEVICE_OBJECT PhysicalDevice
    )
/*++

Routine Description:
    Deregisters a PDO from another non descendant (not verifiable though) pnp
    stack to not be reported as also requiring removal when this PDO is removed.

    The PDO could be another device enumerated by this driver.

Arguments:
    Device - this driver's PDO

    PhysicalDevice - PDO for another stack

Return Value:
    None

  --*/
{
    FxDevice* pDevice;

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Device,
                         FX_TYPE_DEVICE,
                         (PVOID*) &pDevice);

    FxPointerNotNull(pDevice->GetDriverGlobals(), PhysicalDevice);

    pDevice->m_PkgPnp->RemoveRemovalDevice(PhysicalDevice);
}

__drv_maxIRQL(DISPATCH_LEVEL)
VOID
WDFEXPORT(WdfDeviceClearRemovalRelationsDevices)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device
    )
/*++

Routine Description:
    Deregisters all PDOs to not be reported as also requiring removal when this
    PDO is removed.

Arguments:
    Device - this driver's PDO

Return Value:
    None

  --*/
{
    FxDevice* pDevice;

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Device,
                         FX_TYPE_DEVICE,
                         (PVOID*) &pDevice);

    pDevice->m_PkgPnp->ClearRemovalDevicesList();
}

_Must_inspect_result_
__drv_maxIRQL(PASSIVE_LEVEL)
NTSTATUS
WDFEXPORT(WdfDeviceWdmAssignPowerFrameworkSettings)(
    __in
    PWDF_DRIVER_GLOBALS DriverGlobals,
    __in
    WDFDEVICE Device,
    __in
    PWDF_POWER_FRAMEWORK_SETTINGS PowerFrameworkSettings
    )
/*++

Routine Description:
    The DDI is invoked by KMDF client drivers for single-component devices to
    specify their power framework settings to KMDF. KMDF uses these settings on
    Win8+ when registering with the power framework.

    On Win7 and older operating systems the power framework is not available, so
    KMDF does nothing.

Arguments:

    Device - Handle to the framework device object for which power framework
      settings are being specified.

    PowerFrameworkSettings - Pointer to a WDF_POWER_FRAMEWORK_SETTINGS structure
      that contains the client driver's power framework settings.

Return Value:
    An NTSTATUS value that denotes success or failure of the DDI

--*/
{
    NTSTATUS status;
    PFX_DRIVER_GLOBALS pFxDriverGlobals;
    FxDevice *pDevice;

    //
    // Validate the Device object handle and get its FxDevice. Also get the
    // driver globals pointer.
    //
    FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals),
                                   Device,
                                   FX_TYPE_DEVICE,
                                   (PVOID *) &pDevice,
                                   &pFxDriverGlobals);

    FxPointerNotNull(pFxDriverGlobals, PowerFrameworkSettings);

    //
    // Only power policy owners should call this DDI
    //
    if (pDevice->m_PkgPnp->IsPowerPolicyOwner() == FALSE) {
        status = STATUS_INVALID_DEVICE_REQUEST;
        DoTraceLevelMessage(
            pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
            "WDFDEVICE 0x%p is not the power policy owner, so the caller cannot"
            " assign power framework settings %!STATUS!", Device, status);
        FxVerifierDbgBreakPoint(pFxDriverGlobals);
        return status;
    }

    //
    // Validate the Settings parameter
    //
    if (PowerFrameworkSettings->Size != sizeof(WDF_POWER_FRAMEWORK_SETTINGS)) {
        status = STATUS_INFO_LENGTH_MISMATCH;
        DoTraceLevelMessage(
            pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
            "WDFDEVICE 0x%p Expected PowerFrameworkSettings size %d, actual %d,"
            " %!STATUS!",
            Device,
            sizeof(WDF_POWER_FRAMEWORK_SETTINGS),
            PowerFrameworkSettings->Size,
            status);
        FxVerifierDbgBreakPoint(pFxDriverGlobals);
        return status;
    }

    //
    // If settings for component 0 are specified, make sure it contains at least
    // one F-state.
    //
    if (NULL != PowerFrameworkSettings->Component) {

        if (0 == PowerFrameworkSettings->Component->IdleStateCount) {
            status = STATUS_INVALID_PARAMETER;
            DoTraceLevelMessage(
                pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
                "WDFDEVICE 0x%p Component settings are specified but "
                "IdleStateCount is 0. %!STATUS!", Device, status);
            FxVerifierDbgBreakPoint(pFxDriverGlobals);
            return status;
        }

        if (NULL == PowerFrameworkSettings->Component->IdleStates) {
            status = STATUS_INVALID_PARAMETER;
            DoTraceLevelMessage(
                pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDEVICE,
                "WDFDEVICE 0x%p Component settings are specified but IdleStates"
                " is NULL. %!STATUS!", Device, status);
            FxVerifierDbgBreakPoint(pFxDriverGlobals);
            return status;
        }
    }

    //
    // Assign the driver's settings
    //
    status = pDevice->m_PkgPnp->AssignPowerFrameworkSettings(
                                            PowerFrameworkSettings);

    return status;
}

_Must_inspect_result_
_IRQL_requires_max_(PASSIVE_LEVEL)
WDFAPI
NTSTATUS
WDFEXPORT(WdfDeviceRetrieveCompanionTarget)(
    _In_
    PWDF_DRIVER_GLOBALS DriverGlobals,
    _In_
    WDFDEVICE Device,
    _Out_
    WDFCOMPANIONTARGET* CompanionTarget
    )
/*++

Routine Description:
    The DDI is invoked by KMDF drivers to retrieve the WDFCOMPANIONTARGET handle
    that can be used to send tasks to the companion.

Arguments:
    Device - Handle to the framework device object. This must not be control or
            miniport device.

    CompanionTarget - Pointer to CompanionTarget handle

Return Value:
    An NTSTATUS value that denotes success or failure of the DDI. These are the
    known failures, others could also be reported  -
        STATUS_INVALID_DEVICE_REQUEST - Invalid device type.
        STATUS_NOT_FOUND              - Companion not registered for device.
--*/
{
    FxDevice *pDevice;
    FxPkgPnp* pkgPnP;

    FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
                         Device,
                         FX_TYPE_DEVICE,
                         (PVOID*) &pDevice);

    if (!pDevice->IsPnp()) {
        return STATUS_INVALID_DEVICE_REQUEST;
    }

    pkgPnP = pDevice->m_PkgPnp;
    if (NT_SUCCESS(pkgPnP->m_CompanionTargetStatus)) {
        *CompanionTarget = (WDFCOMPANIONTARGET)
                                pkgPnP->m_CompanionTarget->GetObjectHandle();
    }

    return pkgPnP->m_CompanionTargetStatus;
}

} // extern "C"


text:
import isFunction from './isFunction.js';
import isMasked from './_isMasked.js';
import isObject from './isObject.js';
import toSource from './_toSource.js';

/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used for built-in method references. */
var funcProto = Function.prototype,
    objectProto = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);

/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  if (!isObject(value) || isMasked(value)) {
    return false;
  }
  var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}

export default baseIsNative;


text:
using UnrealBuildTool;

public class NekoNekoSandbox : ModuleRules
{
	public NekoNekoSandbox(TargetInfo Target)
	{
		PublicDependencyModuleNames.AddRange(
			new string[]
			{
				"Core",
				"CoreUObject",
				"Engine",
			}
		);

		PrivateDependencyModuleNames.AddRange(
			new string[]
			{
			}
		);

		if (Target.Type != TargetRules.TargetType.Server)
		{
			PublicDependencyModuleNames.AddRange(
				new string[]
				{
					"InputCore",
				}
			);
		}

		if (UEBuildConfiguration.bBuildDeveloperTools || (Target.Configuration != UnrealTargetConfiguration.Shipping && Target.Configuration != UnrealTargetConfiguration.Test))
		{
			PrivateDependencyModuleNames.Add("GameplayDebugger");
			Definitions.Add("WITH_GAMEPLAY_DEBUGGER=1");
		}
	}
}


text:
package org.apache.spark.sql.catalyst.plans.logical

import org.apache.spark.sql.catalyst.analysis.{FieldName, FieldPosition}
import org.apache.spark.sql.catalyst.catalog.CatalogTypes.TablePartitionSpec
import org.apache.spark.sql.catalyst.util.TypeUtils
import org.apache.spark.sql.connector.catalog.{TableCatalog, TableChange}
import org.apache.spark.sql.errors.QueryCompilationErrors
import org.apache.spark.sql.types.DataType

/**
 * The base trait for commands that need to alter a v2 table with [[TableChange]]s.
 */
trait AlterTableCommand extends UnaryCommand {
  def changes: Seq[TableChange]
  def table: LogicalPlan
  final override def child: LogicalPlan = table
}

/**
 * The logical plan that defines or changes the comment of an TABLE for v2 catalogs.
 *
 * {{{
 *   COMMENT ON TABLE tableIdentifier IS ('text' | NULL)
 * }}}
 *
 * where the `text` is the new comment written as a string literal; or `NULL` to drop the comment.
 */
case class CommentOnTable(table: LogicalPlan, comment: String) extends AlterTableCommand {
  override def changes: Seq[TableChange] = {
    Seq(TableChange.setProperty(TableCatalog.PROP_COMMENT, comment))
  }
  override protected def withNewChildInternal(newChild: LogicalPlan): LogicalPlan =
    copy(table = newChild)
}

/**
 * The logical plan of the ALTER TABLE ... SET LOCATION command.
 */
case class SetTableLocation(
    table: LogicalPlan,
    partitionSpec: Option[TablePartitionSpec],
    location: String) extends AlterTableCommand {
  override def changes: Seq[TableChange] = {
    if (partitionSpec.nonEmpty) {
      throw QueryCompilationErrors.alterV2TableSetLocationWithPartitionNotSupportedError()
    }
    Seq(TableChange.setProperty(TableCatalog.PROP_LOCATION, location))
  }
  override protected def withNewChildInternal(newChild: LogicalPlan): LogicalPlan =
    copy(table = newChild)
}

/**
 * The logical plan of the ALTER TABLE ... SET TBLPROPERTIES command.
 */
case class SetTableProperties(
    table: LogicalPlan,
    properties: Map[String, String]) extends AlterTableCommand {
  override def changes: Seq[TableChange] = {
    properties.map { case (key, value) =>
      TableChange.setProperty(key, value)
    }.toSeq
  }
  override protected def withNewChildInternal(newChild: LogicalPlan): LogicalPlan =
    copy(table = newChild)
}

/**
 * The logical plan of the ALTER TABLE ... UNSET TBLPROPERTIES command.
 */
case class UnsetTableProperties(
    table: LogicalPlan,
    propertyKeys: Seq[String],
    ifExists: Boolean) extends AlterTableCommand {
  override def changes: Seq[TableChange] = {
    propertyKeys.map(key => TableChange.removeProperty(key))
  }
  override protected def withNewChildInternal(newChild: LogicalPlan): LogicalPlan =
    copy(table = newChild)
}

/**
 * The logical plan of the ALTER TABLE ... ADD COLUMNS command.
 */
case class AddColumns(
    table: LogicalPlan,
    columnsToAdd: Seq[QualifiedColType]) extends AlterTableCommand {
  columnsToAdd.foreach { c =>
    TypeUtils.failWithIntervalType(c.dataType)
  }

  override lazy val resolved: Boolean = table.resolved && columnsToAdd.forall(_.resolved)

  override def changes: Seq[TableChange] = {
    columnsToAdd.map { col =>
      require(col.path.forall(_.resolved),
        "FieldName should be resolved before it's converted to TableChange.")
      require(col.position.forall(_.resolved),
        "FieldPosition should be resolved before it's converted to TableChange.")
      TableChange.addColumn(
        col.name.toArray,
        col.dataType,
        col.nullable,
        col.comment.orNull,
        col.position.map(_.position).orNull,
        col.default.orNull)
    }
  }

  override protected def withNewChildInternal(newChild: LogicalPlan): LogicalPlan =
    copy(table = newChild)
}

/**
 * The logical plan of the ALTER TABLE ... REPLACE COLUMNS command.
 */
case class ReplaceColumns(
    table: LogicalPlan,
    columnsToAdd: Seq[QualifiedColType]) extends AlterTableCommand {
  columnsToAdd.foreach { c =>
    TypeUtils.failWithIntervalType(c.dataType)
  }

  override lazy val resolved: Boolean = table.resolved && columnsToAdd.forall(_.resolved)

  override def changes: Seq[TableChange] = {
    // REPLACE COLUMNS deletes all the existing columns and adds new columns specified.
    require(table.resolved)
    val deleteChanges = table.schema.fieldNames.map { name =>
      // REPLACE COLUMN should require column to exist
      TableChange.deleteColumn(Array(name), false /* ifExists */)
    }
    val addChanges = columnsToAdd.map { col =>
      assert(col.path.isEmpty)
      assert(col.position.isEmpty)
      TableChange.addColumn(
        col.name.toArray,
        col.dataType,
        col.nullable,
        col.comment.orNull,
        null,
        col.default.orNull)
    }
    deleteChanges ++ addChanges
  }

  override protected def withNewChildInternal(newChild: LogicalPlan): LogicalPlan =
    copy(table = newChild)
}

/**
 * The logical plan of the ALTER TABLE ... DROP COLUMNS command.
 */
case class DropColumns(
    table: LogicalPlan,
    columnsToDrop: Seq[FieldName],
    ifExists: Boolean) extends AlterTableCommand {
  override def changes: Seq[TableChange] = {
    columnsToDrop.map { col =>
      require(col.resolved, "FieldName should be resolved before it's converted to TableChange.")
      TableChange.deleteColumn(col.name.toArray, ifExists)
    }
  }

  override protected def withNewChildInternal(newChild: LogicalPlan): LogicalPlan =
    copy(table = newChild)
}

/**
 * The logical plan of the ALTER TABLE ... RENAME COLUMN command.
 */
case class RenameColumn(
    table: LogicalPlan,
    column: FieldName,
    newName: String) extends AlterTableCommand {
  override def changes: Seq[TableChange] = {
    require(column.resolved, "FieldName should be resolved before it's converted to TableChange.")
    Seq(TableChange.renameColumn(column.name.toArray, newName))
  }

  override protected def withNewChildInternal(newChild: LogicalPlan): LogicalPlan =
    copy(table = newChild)
}

/**
 * The logical plan of the ALTER TABLE ... ALTER COLUMN command.
 */
case class AlterColumn(
    table: LogicalPlan,
    column: FieldName,
    dataType: Option[DataType],
    nullable: Option[Boolean],
    comment: Option[String],
    position: Option[FieldPosition],
    setDefaultExpression: Option[String]) extends AlterTableCommand {
  override def changes: Seq[TableChange] = {
    require(column.resolved, "FieldName should be resolved before it's converted to TableChange.")
    val colName = column.name.toArray
    val typeChange = dataType.map { newDataType =>
      TableChange.updateColumnType(colName, newDataType)
    }
    val nullabilityChange = nullable.map { nullable =>
      TableChange.updateColumnNullability(colName, nullable)
    }
    val commentChange = comment.map { newComment =>
      TableChange.updateColumnComment(colName, newComment)
    }
    val positionChange = position.map { newPosition =>
      require(newPosition.resolved,
        "FieldPosition should be resolved before it's converted to TableChange.")
      TableChange.updateColumnPosition(colName, newPosition.position)
    }
    val defaultValueChange = setDefaultExpression.map { newDefaultExpression =>
      TableChange.updateColumnDefaultValue(colName, newDefaultExpression)
    }
    typeChange.toSeq ++ nullabilityChange ++ commentChange ++ positionChange ++ defaultValueChange
  }

  override protected def withNewChildInternal(newChild: LogicalPlan): LogicalPlan =
    copy(table = newChild)
}


text:
@extends('my.base')

@section('content')

@lang('acp.trips.create')

<form action="@lng/my/trips" method="post">

  @include('my.trips.form')

  <button class="btn btn-primary">@lang('acp.trips.add')</button>

</form>
@endsection


text:
package org.uberfire.ext.editor.commons.client.file.exports;

import java.util.List;

import org.junit.Test;
import org.uberfire.ext.editor.commons.file.exports.PdfExportPreferences;

import static org.junit.Assert.*;

public class PdfDocumentTest {

    @Test
    public void testText() {
        PdfDocument document = PdfDocument.create(PdfExportPreferences.create(PdfExportPreferences.Orientation.PORTRAIT,
                                                                              PdfExportPreferences.Unit.MM,
                                                                              PdfExportPreferences.Format.A4));
        document.addText("text1",
                         13,
                         453);
        // Assert settings.
        assertEquals(PdfExportPreferences.Orientation.PORTRAIT,
                     document.getSettings().getOrientation());
        assertEquals(PdfExportPreferences.Unit.MM,
                     document.getSettings().getUnit());
        assertEquals(PdfExportPreferences.Format.A4,
                     document.getSettings().getFormat());
        // Assert entries.
        final List<PdfDocument.PdfEntry> pdfEntries = document.getPdfEntries();
        assertNotNull(pdfEntries);
        assertEquals(1,
                     pdfEntries.size());
        assertTrue(pdfEntries.get(0) instanceof PdfDocument.Text);
        final PdfDocument.Text entry = (PdfDocument.Text) pdfEntries.get(0);
        assertEquals("text1",
                     entry.getText());
        assertEquals(13,
                     entry.getX());
        assertEquals(453,
                     entry.getY());
    }

    @Test
    public void testImage() {
        PdfDocument document = PdfDocument.create(PdfExportPreferences.create(PdfExportPreferences.Orientation.LANDSCAPE,
                                                                              PdfExportPreferences.Unit.MM,
                                                                              PdfExportPreferences.Format.A4));
        document.addImage("data-url1",
                          "jpeg",
                          13,
                          453,
                          345,
                          234);
        // Assert settings.
        assertEquals(PdfExportPreferences.Orientation.LANDSCAPE,
                     document.getSettings().getOrientation());
        assertEquals(PdfExportPreferences.Unit.MM,
                     document.getSettings().getUnit());
        assertEquals(PdfExportPreferences.Format.A4,
                     document.getSettings().getFormat());
        // Assert entries.
        final List<PdfDocument.PdfEntry> pdfEntries = document.getPdfEntries();
        assertNotNull(pdfEntries);
        assertEquals(1,
                     pdfEntries.size());
        assertTrue(pdfEntries.get(0) instanceof PdfDocument.Image);
        final PdfDocument.Image entry = (PdfDocument.Image) pdfEntries.get(0);
        assertEquals("data-url1",
                     entry.getToDataURL());
        assertEquals("jpeg",
                     entry.getImgType());
        assertEquals(13,
                     entry.getX());
        assertEquals(453,
                     entry.getY());
        assertEquals(345,
                     entry.getWidth());
        assertEquals(234,
                     entry.getHeight());
    }

    @Test
    public void testCustomSettings() {
        PdfDocument document = PdfDocument.create(PdfExportPreferences.create(PdfExportPreferences.Orientation.LANDSCAPE,
                                                                              PdfExportPreferences.Unit.IN,
                                                                              PdfExportPreferences.Format.B6));
        // Assert settings.
        assertEquals(PdfExportPreferences.Orientation.LANDSCAPE,
                     document.getSettings().getOrientation());
        assertEquals(PdfExportPreferences.Unit.IN,
                     document.getSettings().getUnit());
        assertEquals(PdfExportPreferences.Format.B6,
                     document.getSettings().getFormat());
    }
}


text:
<polymer-element name="cxx-table" extends="table" constructor="CxxTableElement" attributes="columns">
  <template>

Table {{table_num}} — <wbr><content select="caption"></content>

    <content></content>
  </template>

</polymer-element>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>inet_dns_extension: Class Members - Variables</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

inet_dns_extension

OmnetPPDNSExtension

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Variables

Enumerations

Enumerator

_

a

c

d

e

f

h

i

j

k

l

m

n

o

p

q

r

s

t

u

w

z

- d -

data
: INETDNS::TimeEvent
, zone_entry

delivery
: INETDNS::MDNSProbeJob
, INETDNS::MDNSQueryJob
, INETDNS::MDNSResponseJob

device_map
: MDNSNetworkConfigurator

displayString_var
: DNSPacket

distribution
: MDNSNetworkConfigurator

dns_servers
: DNSClient

dnsRecordPriorityCache
: INETDNS::DNSTTLCache

domain
: zone_entry

done
: INETDNS::MDNSProbeJob
, INETDNS::MDNSQueryJob
, INETDNS::MDNSResponseJob

Generated on Wed Jun 3 2015 12:38:03 for inet_dns_extension by

     1.8.9.1


text:
using System;
using System.Linq;
using LinqToDB;
using LinqToDB.Mapping;
using NUnit.Framework;

namespace Tests.UserTests
{
	[TestFixture]
	public class Issue2564Tests : TestBase
	{
		class Issue2564Class
		{
			public long Id { get; set; }
			public DateTime TimestampGenerated { get; set; }
			public DateTime? TimestampGone { get; set; }
			public string? MessageClassName { get; set; }
			public string? ExternID1 { get; set; }
			public string? TranslatedMessageGroup { get; set; }
			public string? TranslatedMessage1 { get; set; }
		}

		[Test]
		public void TestIssue2564([IncludeDataSources(TestProvName.AllOracle, TestProvName.AllClickHouse)] string context)
		{
			var ms = new MappingSchema();

			ms.GetFluentMappingBuilder()
				.Entity<Issue2564Class>()
				.HasTableName("Issue2564Table")
				.Property(e => e.Id).IsPrimaryKey();

			using (var db = GetDataContext(context, ms))
			{
				db.DropTable<Issue2564Class>(throwExceptionIfNotExists: false);
				db.CreateTable<Issue2564Class>();
				{
					var from = TestData.DateTime.AddDays(-1);
					var to   = TestData.DateTime;

					var qry = (from m in db.GetTable<Issue2564Class>()
							   where m.TimestampGone.HasValue &&
								 m.TimestampGenerated >= @from &&
								 m.TimestampGenerated <= to &&
								 m.MessageClassName == "Error"
							   group m by new { m.ExternID1, m.TranslatedMessageGroup, m.TimestampGenerated.Hour } into tgGroup
							   select new
							   {
								   MessageText       = tgGroup.Min(x => x.TranslatedMessage1)!.Trim(),
								   GroupName         = tgGroup.Key.TranslatedMessageGroup,
								   Hour              = tgGroup.Key.Hour,
								   Count             = tgGroup.Count(),
								   DurationInSeconds = (long)tgGroup.Sum(x => (x.TimestampGone!.Value - x.TimestampGenerated).TotalMilliseconds),
							   });

					var data = qry.ToList();
				}
			}
		}
	}
}


text:
	const cdata = /\&|<|>|\"|\'|\t|\r|\n|\@|\$/,
		boolean_number_string = /boolean|number|string/;

	function iterate (obj, fn, ctx = obj) {
		Object.keys(obj).forEach(i => {
			fn.call(ctx, obj[i], i);
		});
	}

	function parse (arg) {
		return new DOMParser().parseFromString(arg, "text/xml");
	}

	function node (arg = "", value) {
		const name = arg.replace(/\s/g, "");

		let start = "",
			end = "";

		if (name !== "") {
			start = `<${name}>`;
			end = `</${name}>`;
		}

		return start + (cdata.test(value) ? "<![CDATA[" + value + "]]>" : value) + end;
	}

	function serialize (arg, key = "xml", wrap = true, top = true) {
		let x = wrap ? `<${key}>` : "",
			larg = arg;

		if (larg !== null && larg.xml) {
			larg = larg.xml;
		}

		if (typeof Document !== "undefined" && larg instanceof Document) {
			larg = new XMLSerializer().serializeToString(larg);
		}

		if (boolean_number_string.test(typeof larg)) {
			x += node(isNaN(key) ? key : "item", larg);
		} else if (larg === null || larg === undefined) {
			x += "null";
		} else if (larg instanceof Array) {
			larg.forEach(function (v) {
				x += serialize(v, "item", boolean_number_string.test(typeof v) ? false : true, false);
			});
		} else if (larg instanceof Object) {
			iterate(larg, function (v, k) {
				x += boolean_number_string.test(typeof v) ? node(k, v) : serialize(v, k, top, false);
			});
		}

		x += wrap ? "</" + key + ">" : "";

		if (top) {
			x = "<?xml version=\"1.0\" encoding=\"UTF8\"?>" + x;
		}

		return x;
	}

	function valid (arg) {
		return parse(arg).getElementsByTagName("parsererror").length === 0;
	}

	const xml = {
		parse: parse,
		serialize: serialize,
		valid: valid,
		version: "{{VERSION}}"
	};


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta name="renderer" content="webkit">
    <title>后台管理中心</title>

	<link rel="stylesheet" href="assets/css/pintuer.css">
	<link rel="stylesheet" href="assets/css/admin.css">

管理后台

  	 客服  【退出系统】

菜单列表

个人设置

修改密码

栏目管理

疾病添加

资讯

视频管理

首页轮播

 首页

网站信息