text:
/** The request root */
var requestRoot = "/aft-servlet/";

/** A set of common / helper functions
 *
 */

/** Parses a date in the form of milliseconds since epoch  into a locale date/time string representing the date
 *
 * @param dateLong The date in milliseconds since epoch
 * @return Locale date/time string
 */

function parseDate(dateLong) {
	var date = new Date(dateLong);
	return date.toLocaleString();
};

/** Retreives the value of the URL parameter with the given name
 *
 * @param name The name of the URL parameter to fetch
 * @returns The value of the url param, or null if it wasnt found
 */
function getURLParameter(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

/** Makes an ajax call with the given options, automatically injecting the CSRF header
 *
 * @param options The options object to send
 * @return The jquery future object
 */
function ajaxCSRF(options) {
	//return the ajax call
	return $.ajax(options);
}

/** Posts the given data using ajax, to the specified url
 *
 * @param url The url to post the content to, the requestRoot will be appended to the begining
 * @param data The data to post
 * @return The jquery future to add done, fail, etc methods to
 */

function ajaxCSRFPost(url, data) {
	return ajaxCSRF( {
		url: requestRoot + url,
		type: "POST",
		data: data,
		contentType: "application/json"
	});
}

/** Redirects the user to view the specified device
 *
 * @param device The device to view, if null, then it will use the calling context (this)
 */
function viewDevice(device) {
	if (!device) {
		device = this;
	}

	//remove any observables
	device = ko.toJS(device);

	//redirect to the view device page
	window.location.href = requestRoot + "/device/view?deviceUID=" + device.deviceUid;
}

/** Redirects the user to view the specified request
 *
 * @param request The request to view, if null, then it will use the calling context (this)
 */
function viewRequest(request) {
	if (!request) {
		request = this;
	}
	//remove any observables
	request = ko.toJS(request);

	//navigate to the view page
	window.location.href = requestRoot + "/request/create?requestID=" + request.id;
}

/** Redirects the user to create request view
 *
 * @param device The device to create the request for, optional
 */
function createRequestView(device) {
	var params = "";

	if (device) {
		device = ko.toJS(device);

		params = "?deviceUID=" + device.deviceUid;
	}

	window.location.href = requestRoot + "/request/create" + params;
}

/** Model for a file to upload
 *
 */
function FileUploadModel(file) {

	var self = this;

	/** The id of this file */
	self.fileId = ko.observable(-1);

	/** The name of the file */
	self.name = ko.observable(file.name);

	/** The js file object */
	self.fileObj = file;

};

/** A knockout binding for a file upload
 *
 */

ko.bindingHandlers.fileUpload = {

	init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {

		//register for change events on the list of files
		$(element).change(function() {
			var filesObj = [];

			//create an array of file upload models
			$.each(this.files, function(index, value) {
				filesObj[index] = new FileUploadModel(value);
			});

			//if it is an observable, put it into the value
			if (ko.isObservable(valueAccessor())) {
				valueAccessor()(filesObj);
			}
		});
	},
	update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
		var fileModels = ko.unwrap(valueAccessor());

		var files = [];
		$.each(fileModels, function(index, value) {
			files[index] = value.fileObj;
		});

		//update the files in the selection list
		this.files = files;
	}
};

/*
ko.bindingHandlers.fileUpload = {
    init: function (element, valueAccessor) {
        $(element).change(function () {
            var file = this.files[0];
            if (ko.isObservable(valueAccessor())) {
                valueAccessor()(file);
            }
        });
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        var file = ko.utils.unwrapObservable(valueAccessor());
        var bindings = allBindingsAccessor();

        if (bindings.fileBinaryData && ko.isObservable(bindings.fileBinaryData)) {
            if (!file) {
                bindings.fileBinaryData(null);
            }
            else {
                var reader = new window.FileReader();
                reader.onload = function (e) {
                    bindings.fileBinaryData(e.target.result);
                };
                reader.readAsBinaryString(file);
            }
        }
    }
};
*/


text:
package com.google.zetasql;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import com.google.zetasql.FunctionProtos.FunctionArgumentTypeProto;
import com.google.zetasql.ZetaSQLFunctions.FunctionEnums.ArgumentCardinality;
import com.google.zetasql.ZetaSQLFunctions.SignatureArgumentKind;
import com.google.zetasql.ZetaSQLType.TypeKind;
import com.google.zetasql.ZetaSQLType.TypeProto;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)

public class FunctionArgumentTypeTest {

  @Test
  public void testFixedType() {
    FunctionArgumentType fixedTypeInt32 =
        new FunctionArgumentType(TypeFactory.createSimpleType(TypeKind.TYPE_INT32));
    assertThat(fixedTypeInt32.isConcrete()).isFalse();
    assertThat(fixedTypeInt32.getType()).isNotNull();
    assertThat(fixedTypeInt32.isRepeated()).isFalse();
    assertThat(fixedTypeInt32.isOptional()).isFalse();
    assertThat(fixedTypeInt32.isRequired()).isTrue();
    assertThat(fixedTypeInt32.getNumOccurrences()).isEqualTo(-1);
    assertThat(fixedTypeInt32.debugString()).isEqualTo("INT32");

    FunctionArgumentType concreteFixedType =
        new FunctionArgumentType(
            TypeFactory.createSimpleType(TypeKind.TYPE_INT32), ArgumentCardinality.REQUIRED, 0);
    assertThat(concreteFixedType.isConcrete()).isTrue();
    assertThat(concreteFixedType.getType()).isNotNull();
    assertThat(concreteFixedType.isRepeated()).isFalse();
    assertThat(concreteFixedType.isOptional()).isFalse();
    assertThat(concreteFixedType.isRequired()).isTrue();
    assertThat(concreteFixedType.getNumOccurrences()).isEqualTo(0);
    assertThat(concreteFixedType.debugString()).isEqualTo("INT32");

    FunctionArgumentType repeatedFixedType =
        new FunctionArgumentType(
            TypeFactory.createSimpleType(TypeKind.TYPE_INT32), ArgumentCardinality.REPEATED, 1);
    assertThat(repeatedFixedType.isConcrete()).isTrue();
    assertThat(repeatedFixedType.getType()).isNotNull();
    assertThat(repeatedFixedType.isRepeated()).isTrue();
    assertThat(repeatedFixedType.isOptional()).isFalse();
    assertThat(repeatedFixedType.isRequired()).isFalse();
    assertThat(repeatedFixedType.getNumOccurrences()).isEqualTo(1);
    assertThat(repeatedFixedType.debugString()).isEqualTo("repeated(1) INT32");

    FunctionArgumentType optionalFixedType =
        new FunctionArgumentType(
            TypeFactory.createSimpleType(TypeKind.TYPE_INT32), ArgumentCardinality.OPTIONAL, 1);
    assertThat(optionalFixedType.isConcrete()).isTrue();
    assertThat(optionalFixedType.getType()).isNotNull();
    assertThat(optionalFixedType.isRepeated()).isFalse();
    assertThat(optionalFixedType.isOptional()).isTrue();
    assertThat(optionalFixedType.isRequired()).isFalse();
    assertThat(optionalFixedType.getNumOccurrences()).isEqualTo(1);
    assertThat(optionalFixedType.debugString()).isEqualTo("optional(1) INT32");

    FunctionArgumentType typeNull =
        new FunctionArgumentType((Type) null, ArgumentCardinality.REPEATED, -1);
    assertThat(typeNull.isConcrete()).isFalse();
    assertThat(typeNull.getType()).isNull();
    assertThat(typeNull.isRepeated()).isTrue();
    assertThat(typeNull.isOptional()).isFalse();
    assertThat(typeNull.isRequired()).isFalse();
    assertThat(typeNull.getNumOccurrences()).isEqualTo(-1);
    assertThat(typeNull.debugString()).isEqualTo("repeated FIXED");
  }

  @Test
  public void testNotFixedType() {
    FunctionArgumentType arrayTypeAny1 =
        new FunctionArgumentType(
            SignatureArgumentKind.ARG_ARRAY_TYPE_ANY_1, ArgumentCardinality.REPEATED, 0);
    assertThat(arrayTypeAny1.isConcrete()).isFalse();
    assertThat(arrayTypeAny1.getType()).isNull();
    assertThat(arrayTypeAny1.isRepeated()).isTrue();
    assertThat(arrayTypeAny1.debugString()).isEqualTo("repeated <array<T1>>");

    FunctionArgumentType arrayTypeAny2 =
        new FunctionArgumentType(
            SignatureArgumentKind.ARG_ARRAY_TYPE_ANY_2, ArgumentCardinality.REQUIRED, 1);
    assertThat(arrayTypeAny2.isConcrete()).isFalse();
    assertThat(arrayTypeAny2.getType()).isNull();
    assertThat(arrayTypeAny2.isRepeated()).isFalse();
    assertThat(arrayTypeAny2.debugString()).isEqualTo("<array<T2>>");

    FunctionArgumentType enumAny =
        new FunctionArgumentType(
            SignatureArgumentKind.ARG_ENUM_ANY, ArgumentCardinality.OPTIONAL, -1);
    assertThat(enumAny.isConcrete()).isFalse();
    assertThat(enumAny.getType()).isNull();
    assertThat(enumAny.isRepeated()).isFalse();
    assertThat(enumAny.debugString()).isEqualTo("optional <enum>");

    FunctionArgumentType protoAny =
        new FunctionArgumentType(
            SignatureArgumentKind.ARG_PROTO_ANY, ArgumentCardinality.OPTIONAL, 3);
    assertThat(protoAny.isConcrete()).isFalse();
    assertThat(protoAny.getType()).isNull();
    assertThat(protoAny.isRepeated()).isFalse();
    assertThat(protoAny.debugString()).isEqualTo("optional <proto>");

    FunctionArgumentType structAny =
        new FunctionArgumentType(
            SignatureArgumentKind.ARG_STRUCT_ANY, ArgumentCardinality.OPTIONAL, 0);
    assertThat(structAny.isConcrete()).isFalse();
    assertThat(structAny.getType()).isNull();
    assertThat(structAny.isRepeated()).isFalse();
    assertThat(structAny.debugString()).isEqualTo("optional <struct>");

    FunctionArgumentType typeAny1 =
        new FunctionArgumentType(
            SignatureArgumentKind.ARG_TYPE_ANY_1, ArgumentCardinality.REQUIRED, 0);
    assertThat(typeAny1.isConcrete()).isFalse();
    assertThat(typeAny1.getType()).isNull();
    assertThat(typeAny1.isRepeated()).isFalse();
    assertThat(typeAny1.debugString()).isEqualTo("<T1>");

    FunctionArgumentType typeAny2 =
        new FunctionArgumentType(
            SignatureArgumentKind.ARG_TYPE_ANY_2, ArgumentCardinality.REQUIRED, 2);
    assertThat(typeAny2.isConcrete()).isFalse();
    assertThat(typeAny2.getType()).isNull();
    assertThat(typeAny2.isRepeated()).isFalse();
    assertThat(typeAny2.debugString()).isEqualTo("<T2>");

    FunctionArgumentType typeArbitrary =
        new FunctionArgumentType(
            SignatureArgumentKind.ARG_TYPE_ARBITRARY, ArgumentCardinality.REQUIRED, -1);
    assertThat(typeArbitrary.isConcrete()).isFalse();
    assertThat(typeArbitrary.getType()).isNull();
    assertThat(typeArbitrary.isRepeated()).isFalse();
    assertThat(typeArbitrary.debugString()).isEqualTo("ANY TYPE");

    FunctionArgumentType typeUnknown =
        new FunctionArgumentType(
            SignatureArgumentKind.__SignatureArgumentKind__switch_must_have_a_default__,
            ArgumentCardinality.REPEATED,
            1);
    assertThat(typeUnknown.isConcrete()).isFalse();
    assertThat(typeUnknown.getType()).isNull();
    assertThat(typeUnknown.isRepeated()).isTrue();
    assertThat(typeUnknown.debugString()).isEqualTo("repeated UNKNOWN_ARG_KIND");
  }

  @Test
  public void testSerializationAndDeserialization() {
    FunctionArgumentType arrayTypeAny1 =
        new FunctionArgumentType(
            SignatureArgumentKind.ARG_ARRAY_TYPE_ANY_1, ArgumentCardinality.REPEATED, 0);
    FunctionArgumentType typeFixed1 =
        new FunctionArgumentType(
            TypeFactory.createSimpleType(TypeKind.TYPE_INT32), ArgumentCardinality.REPEATED, 0);
    TypeFactory factory = TypeFactory.nonUniqueNames();
    FunctionArgumentType typeFixed2 =
        new FunctionArgumentType(
            factory.createProtoType(TypeProto.class), ArgumentCardinality.REPEATED, 0);

    checkSerializeAndDeserialize(arrayTypeAny1);
    checkSerializeAndDeserialize(typeFixed1);
    checkSerializeAndDeserialize(typeFixed2);
  }

  private static void checkSerializeAndDeserialize(FunctionArgumentType functionArgumentType) {
    FileDescriptorSetsBuilder fileDescriptorSetsBuilder = new FileDescriptorSetsBuilder();
    checkEquals(
        functionArgumentType,
        FunctionArgumentType.deserialize(
            functionArgumentType.serialize(fileDescriptorSetsBuilder),
            fileDescriptorSetsBuilder.getDescriptorPools()));
    assertThat(functionArgumentType.serialize(fileDescriptorSetsBuilder))
        .isEqualTo(
            FunctionArgumentType.deserialize(
                    functionArgumentType.serialize(fileDescriptorSetsBuilder),
                    fileDescriptorSetsBuilder.getDescriptorPools())
                .serialize(fileDescriptorSetsBuilder));
  }

  static void checkEquals(FunctionArgumentType type1, FunctionArgumentType type2) {
    assertThat(type2.getNumOccurrences()).isEqualTo(type1.getNumOccurrences());
    assertThat(type2.getCardinality()).isEqualTo(type1.getCardinality());
    assertThat(type2.getKind()).isEqualTo(type1.getKind());
    if (type1.isConcrete()) {
      assertThat(type1.getType().equals(type2.getType())).isTrue();
    }
  }

  @Test
  public void testClassAndProtoSize() {
    assertWithMessage(
            "The number of fields of FunctionArgumentTypeProto has changed, "
                + "please also update the serialization code accordingly.")
        .that(FunctionArgumentTypeProto.getDescriptor().getFields())
        .hasSize(4);
    assertWithMessage(
            "The number of fields in FunctionArgumentType class has changed, "
                + "please also update the proto and serialization code accordingly.")
        .that(TestUtil.getNonStaticFieldCount(FunctionArgumentType.class))
        .isEqualTo(4);
  }
}

redpajama_set_name: RedPajamaGithub


text:
;; Licensed to the .NET Foundation under one or more agreements.
;; The .NET Foundation licenses this file to you under the MIT license.
;; See the LICENSE file in the project root for more information.

#include "AsmMacros.h"

    TEXTAREA

;;-----------------------------------------------------------------------------
;; This helper routine enregisters the appropriate arguments and makes the
;; actual call.
;;
;;  INPUT: x0: pointer to CallDescrData struct
;;
;;-----------------------------------------------------------------------------
;;void RhCallDescrWorker(CallDescrData * pCallDescrData);
    NESTED_ENTRY RhCallDescrWorker

        PROLOG_SAVE_REG_PAIR   fp, lr, #-32!
        PROLOG_SAVE_REG_PAIR   x19, x20, #16

        ;; Save the value of SP before we start pushing any arguments
        mov     x20, sp

        mov     x19, x0 ; save pCallDescrData in x19

        ldr     w1, [x19, #OFFSETOF__CallDescrData__numStackSlots]
        cbz     w1, Ldonestack

        ;; Add frame padding to ensure frame size is a multiple of 16 (a requirement of the OS ABI).
        ;; We push two registers (above) and numStackSlots arguments (below). If this comes to an odd number
        ;; of slots we must pad with another. This simplifies to "if the low bit of numStackSlots is set,
        ;; extend the stack another eight bytes".
        ldr     x0, [x19, #OFFSETOF__CallDescrData__pSrc]
        add     x0, x0, x1 lsl #3               ; pSrcEnd=pSrc+8*numStackSlots
        ands    x2, x1, #1
        beq     Lstackloop

        ;; This loop copies numStackSlots words
        ;; from [pSrcEnd-8,pSrcEnd-16,...] to [sp-8,sp-16,...]

        ;; Pad and store one stack slot as number of slots are odd
        ldr     x4, [x0,#-8]!
        str     x4, [sp,#-16]!
        subs    x1, x1, #1
        beq     Ldonestack
Lstackloop
        ldp     x2, x4, [x0,#-16]!
        stp     x2, x4, [sp,#-16]!
        subs    x1, x1, #2
        bne     Lstackloop
Ldonestack

        ;; If FP arguments are supplied in registers (x9 != NULL) then initialize all of them from the pointer
        ;; given in x9.
        ldr     x9, [x19, #OFFSETOF__CallDescrData__pFloatArgumentRegisters]
        cbz     x9, LNoFloatingPoint
        ldp     d0, d1, [x9]
        ldp     d2, d3, [x9, #16]
        ldp     d4, d5, [x9, #32]
        ldp     d6, d7, [x9, #48]
LNoFloatingPoint

        ;; Copy [pArgumentRegisters, ..., pArgumentRegisters + 64]
        ;; into x0, ..., x7, x8

        ldr     x9, [x19, #OFFSETOF__CallDescrData__pArgumentRegisters]
        ldp     x0, x1, [x9]
        ldp     x2, x3, [x9, #16]
        ldp     x4, x5, [x9, #32]
        ldp     x6, x7, [x9, #48]
        ldr     x8, [x9, #64]

        ;; call pTarget
        ldr     x9, [x19, #OFFSETOF__CallDescrData__pTarget]
        blr     x9

    EXPORT_POINTER_TO_ADDRESS PointerToReturnFromCallDescrThunk

        ;; Symbol used to identify thunk call to managed function so the special
        ;; case unwinder can unwind through this function. Sadly we cannot directly
        ;; export this symbol right now because it confuses DIA unwinder to believe
        ;; it's the beginning of a new method, therefore we export the address
        ;; of an auxiliary variable holding the address instead.

        ldr     w3, [x19, #OFFSETOF__CallDescrData__fpReturnSize]

        ;; Unlike desktop returnValue is a pointer to a return buffer, not the buffer itself
        ldr     x19, [x19, #OFFSETOF__CallDescrData__pReturnBuffer]

        ;; Int return case
        cbz     w3, LIntReturn

        ;; Float return case
        cmp     w3, #4
        beq     LFloatOrDoubleReturn

        ;; Double return case
        cmp     w3, #8
        bne     LCheckHFAReturn

LFloatOrDoubleReturn
        str     d0, [x19]
        b       LReturnDone

LCheckHFAReturn
        cmp     w3, #16
        beq     LFloatOrDoubleHFAReturn
        cmp     w3, #32
        beq     LFloatOrDoubleHFAReturn
        b       LNoHFAReturn

LFloatOrDoubleHFAReturn
        ;;Single/Double HFAReturn  return case
        stp     d0, d1, [x19, #00]
        stp     d2, d3, [x19, #16]
        b       LReturnDone

LNoHFAReturn

        EMIT_BREAKPOINT ; Unreachable

LIntReturn
        ;; Save return value(s) into retbuf for int
        stp     x0, x1, [x19]

LReturnDone

#ifdef _DEBUG
        ;; Trash the floating point registers to ensure that the HFA return values
        ;; won't survive by accident
        ldp     d0, d1, [sp]
        ldp     d2, d3, [sp, #16]
#endif
        ;; Restore the value of SP
        mov     sp, x20

        EPILOG_RESTORE_REG_PAIR x19, x20, #16
        EPILOG_RESTORE_REG_PAIR fp, lr, #32!
        EPILOG_RETURN

    NESTED_END RhCallDescrWorker

    END


text:
/*
 Test libarchfpga, try reading an architecture and print the results to a file

 Date: February 19, 2009
 Author: Jason Luu
 */

#include <stdio.h>
#include <stdlib.h>

#include "read_xml_arch_file.h"

void print_help();

int main(int argc, char **argv) {
	t_arch* arch = (t_arch *)my_calloc(1,sizeof(t_arch));
	t_type_descriptor *types;
	int numTypes;
	;

	if (argc - 1 != 3) {
		printf(
				"Error: Unexpected # of arguments.  Expected 3 found %d arguments\n",
				argc);
		print_help();
	}

	printf(
			"------------------------------------------------------------------------------\n");
	printf(
			"- Read architecture file and print library data structures into an output file\n");
	printf(
			"------------------------------------------------------------------------------\n\n");

	printf("Inputs: \n"
			"architecture %s \n"
			"timing_driven %d \n"
			"output file %s\n", argv[1], atoi(argv[2]), argv[3]);
	printf("Reading in architecture\n");

	/* function declarations */
	XmlReadArch(argv[1], atoi(argv[2]), arch, &types, &numTypes);

	printf("Printing Results\n");

	EchoArch(argv[3], types, numTypes, arch);

	printf("Done\n");
	free(arch);

	return 0;
}

void print_help() {
	printf(
			"\n---------------------------------------------------------------------------------------\n");
	printf(
			"read_arch: Read a VPR architecture file and output internal data structures");
	printf(
			"Usage: read_arch <arch_file.xml> <timing_driven (0|1)> <output_file>\n");
	printf("  ex: read_arch k4_n10.xml 1 arch_data.out\n");
	printf(
			"      Read timing-driven architecture k4_n10.xml and output the results to arch_data.out\n");
	printf(
			"\n---------------------------------------------------------------------------------------\n");
}


text:
"""
Main program for the child process run by
L{twisted.test.test_stdio.StandardInputOutputTestCase.test_loseConnection} to
test that ITransport.loseConnection() works for process transports.
"""

import sys, _preamble

from twisted.internet.error import ConnectionDone
from twisted.internet import stdio, protocol
from twisted.python import reflect, log

class LoseConnChild(protocol.Protocol):
    exitCode = 0

    def connectionMade(self):
        self.transport.loseConnection()

    def connectionLost(self, reason):
        """
        Check that C{reason} is a L{Failure} wrapping a L{ConnectionDone}
        instance and stop the reactor.  If C{reason} is wrong for some reason,
        log something about that in C{self.errorLogFile} and make sure the
        process exits with a non-zero status.
        """
        try:
            try:
                reason.trap(ConnectionDone)
            except:
                log.err(None, "Problem with reason passed to connectionLost")
                self.exitCode = 1
        finally:
            reactor.stop()

if __name__ == '__main__':
    reflect.namedAny(sys.argv[1]).install()
    log.startLogging(file(sys.argv[2], 'w'))
    from twisted.internet import reactor
    protocol = LoseConnChild()
    stdio.StandardIO(protocol)
    reactor.run()
    sys.exit(protocol.exitCode)


text:
package org.terasology.rendering.nui.layers.mainMenu.inputSettings;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.terasology.asset.Assets;
import org.terasology.config.Config;
import org.terasology.engine.SimpleUri;
import org.terasology.engine.module.ModuleManager;
import org.terasology.input.BindButtonEvent;
import org.terasology.input.InputCategory;
import org.terasology.input.InputSystem;
import org.terasology.input.RegisterBindButton;
import org.terasology.math.Vector2i;
import org.terasology.module.DependencyResolver;
import org.terasology.module.Module;
import org.terasology.module.ModuleEnvironment;
import org.terasology.module.ResolutionResult;
import org.terasology.module.predicates.FromModule;
import org.terasology.naming.Name;
import org.terasology.registry.In;
import org.terasology.rendering.nui.CoreScreenLayer;
import org.terasology.rendering.nui.UIWidget;
import org.terasology.rendering.nui.VerticalAlign;
import org.terasology.rendering.nui.databinding.BindHelper;
import org.terasology.rendering.nui.layouts.ColumnLayout;
import org.terasology.rendering.nui.layouts.RowLayout;
import org.terasology.rendering.nui.layouts.ScrollableArea;
import org.terasology.rendering.nui.layouts.relative.HorizontalHint;
import org.terasology.rendering.nui.layouts.relative.RelativeLayout;
import org.terasology.rendering.nui.layouts.relative.VerticalHint;
import org.terasology.rendering.nui.widgets.ActivateEventListener;
import org.terasology.rendering.nui.widgets.UIButton;
import org.terasology.rendering.nui.widgets.UICheckbox;
import org.terasology.rendering.nui.widgets.UIImage;
import org.terasology.rendering.nui.widgets.UILabel;
import org.terasology.rendering.nui.widgets.UISlider;
import org.terasology.rendering.nui.widgets.UISpace;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author Immortius
 */
public class InputSettingsScreen extends CoreScreenLayer {

    private int horizontalSpacing = 4;

    @In
    private Config config;

    @In
    private ModuleManager moduleManager;

    @In
    private InputSystem inputSystem;

    @Override
    public void initialise() {

        ColumnLayout mainLayout = new ColumnLayout();
        mainLayout.setHorizontalSpacing(8);
        mainLayout.setVerticalSpacing(8);
        mainLayout.setFamily("option-grid");
        UISlider mouseSensitivity = new UISlider("mouseSensitivity");
        mouseSensitivity.setIncrement(0.025f);
        mouseSensitivity.setPrecision(3);

        mainLayout.addWidget(new UILabel("mouseLabel", "heading-input", "Mouse"));
        mainLayout.addWidget(new RowLayout(new UILabel("Mouse Sensitivity:"), mouseSensitivity).setColumnRatios(0.4f).setHorizontalSpacing(horizontalSpacing));
        mainLayout.addWidget(new RowLayout(new UILabel("Invert Mouse:"), new UICheckbox("mouseYAxisInverted")).setColumnRatios(0.4f).setHorizontalSpacing(horizontalSpacing));

        Map<String, InputCategory> inputCategories = Maps.newHashMap();
        Map<SimpleUri, RegisterBindButton> inputsById = Maps.newHashMap();
        DependencyResolver resolver = new DependencyResolver(moduleManager.getRegistry());
        for (Name moduleId : moduleManager.getRegistry().getModuleIds()) {
            Module module = moduleManager.getRegistry().getLatestModuleVersion(moduleId);
            if (module.isCodeModule()) {
                ResolutionResult result = resolver.resolve(moduleId);
                if (result.isSuccess()) {
                    try (ModuleEnvironment environment = moduleManager.loadEnvironment(result.getModules(), false)) {
                        for (Class<?> holdingType : environment.getTypesAnnotatedWith(InputCategory.class, new FromModule(environment, moduleId))) {
                            InputCategory inputCategory = holdingType.getAnnotation(InputCategory.class);
                            inputCategories.put(module.getId() + ":" + inputCategory.id(), inputCategory);
                        }
                        for (Class<?> bindEvent : environment.getTypesAnnotatedWith(RegisterBindButton.class, new FromModule(environment, moduleId))) {
                            if (BindButtonEvent.class.isAssignableFrom(bindEvent)) {
                                RegisterBindButton bindRegister = bindEvent.getAnnotation(RegisterBindButton.class);
                                inputsById.put(new SimpleUri(module.getId(), bindRegister.id()), bindRegister);
                            }
                        }
                    }
                }

            }
        }

        addInputSection(inputCategories.remove("engine:movement"), mainLayout, inputsById);
        addInputSection(inputCategories.remove("engine:interaction"), mainLayout, inputsById);
        addInputSection(inputCategories.remove("engine:inventory"), mainLayout, inputsById);
        addInputSection(inputCategories.remove("engine:general"), mainLayout, inputsById);
        for (InputCategory category : inputCategories.values()) {
            addInputSection(category, mainLayout, inputsById);
        }
        mainLayout.addWidget(new UISpace(new Vector2i(1, 16)));

        ScrollableArea area = new ScrollableArea();
        area.setContent(mainLayout);

        ColumnLayout footerGrid = new ColumnLayout("footer");
        footerGrid.setFamily("menu-options");
        footerGrid.setColumns(2);
        footerGrid.addWidget(new UIButton("reset", "Restore Defaults"));
        footerGrid.addWidget(new UIButton("close", "Back"));
        footerGrid.setHorizontalSpacing(8);

        RelativeLayout layout = new RelativeLayout();
        layout.addWidget(new UIImage("title", Assets.getTexture("engine:terasology").get()),
                HorizontalHint.create().fixedWidth(512).center(),
                VerticalHint.create().fixedHeight(128).alignTop(48));
        layout.addWidget(new UILabel("subtitle", "title", "Input Settings"),
                HorizontalHint.create().center(),
                VerticalHint.create().fixedHeight(48).alignTopRelativeTo("title", VerticalAlign.BOTTOM));
        layout.addWidget(area,
                HorizontalHint.create().fixedWidth(640).center(),
                VerticalHint.create().alignTopRelativeTo("subtitle", VerticalAlign.BOTTOM).alignBottomRelativeTo("footer", VerticalAlign.TOP, 48));
        layout.addWidget(footerGrid,
                HorizontalHint.create().center().fixedWidth(400),
                VerticalHint.create().fixedHeight(48).alignBottom(48));

        setContents(layout);
    }

    private void addInputSection(InputCategory category, ColumnLayout layout, Map<SimpleUri, RegisterBindButton> inputsById) {
        if (category != null) {
            layout.addWidget(new UISpace(new Vector2i(0, 16)));

            UILabel categoryHeader = new UILabel(category.displayName());
            categoryHeader.setFamily("heading-input");
            layout.addWidget(categoryHeader);

            Set<SimpleUri> processedBinds = Sets.newHashSet();

            for (String bindId : category.ordering()) {
                SimpleUri bindUri = new SimpleUri(bindId);
                if (bindUri.isValid()) {
                    RegisterBindButton bind = inputsById.get(new SimpleUri(bindId));
                    if (bind != null) {
                        addInputBindRow(bindUri, bind, layout);
                        processedBinds.add(bindUri);
                    }
                }
            }

            List<ExtensionBind> extensionBindList = Lists.newArrayList();
            for (Map.Entry<SimpleUri, RegisterBindButton> bind : inputsById.entrySet()) {
                if (bind.getValue().category().equals(category.id()) && !processedBinds.contains(bind.getKey())) {
                    extensionBindList.add(new ExtensionBind(bind.getKey(), bind.getValue()));
                }
            }
            Collections.sort(extensionBindList);
            for (ExtensionBind extension : extensionBindList) {
                addInputBindRow(extension.uri, extension.bind, layout);
            }
        }
    }

    private void addInputBindRow(SimpleUri uri, RegisterBindButton bind, ColumnLayout layout) {
        UIInputBind inputBind = new UIInputBind();
        inputBind.bindInput(new InputConfigBinding(config.getInput().getBinds(), uri));
        UIInputBind secondaryInputBind = new UIInputBind();
        secondaryInputBind.bindInput(new InputConfigBinding(config.getInput().getBinds(), uri, 1));
        layout.addWidget(new RowLayout(new UILabel(bind.description()), inputBind, secondaryInputBind).setColumnRatios(0.4f).setHorizontalSpacing(horizontalSpacing));
    }

    @Override
    public void setContents(UIWidget contents) {
        super.setContents(contents);
        find("mouseSensitivity", UISlider.class).bindValue(BindHelper.bindBeanProperty("mouseSensitivity", config.getInput(), Float.TYPE));
        find("mouseYAxisInverted", UICheckbox.class).bindChecked(BindHelper.bindBeanProperty("mouseYAxisInverted", config.getInput(), Boolean.TYPE));
        find("reset", UIButton.class).subscribe(new ActivateEventListener() {
            @Override
            public void onActivated(UIWidget button) {
                config.getInput().reset();
            }
        });
        find("close", UIButton.class).subscribe(new ActivateEventListener() {
            @Override
            public void onActivated(UIWidget button) {
                getManager().popScreen();
            }
        });
    }

    @Override
    public void onClosed() {
        config.getInput().getBinds().applyBinds(inputSystem, moduleManager);
    }

    @Override
    public boolean isLowerLayerVisible() {
        return false;
    }

    private static final class ExtensionBind implements Comparable<ExtensionBind> {
        private SimpleUri uri;
        private RegisterBindButton bind;

        private ExtensionBind(SimpleUri uri, RegisterBindButton bind) {
            this.uri = uri;
            this.bind = bind;
        }

        @Override
        public int compareTo(ExtensionBind o) {
            int descriptionOrder = bind.description().compareTo(o.bind.description());
            if (descriptionOrder == 0) {
                return uri.compareTo(o.uri);
            }
            return descriptionOrder;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj instanceof ExtensionBind) {
                ExtensionBind other = (ExtensionBind) obj;
                return Objects.equals(bind.description(), other.bind.description()) && Objects.equals(uri, other.uri);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return Objects.hash(uri, bind.description());
        }
    }

}


text:
Dynamo is a friendly generator that uses [DB Schema Reader](http://dbschemareader.codeplex.com/)
and [DotLiquid Syntax](https://github.com/formosatek/dotliquid) to generate code files.

- [Setup.exe](https://rawgit.com/ellerbus/Dynamo/Setup/Output/setup.exe)

#### Quick Start

For those that simply what to jump in and check things out download and view the [Sample
Solution](https://github.com/ellerbus/Dynamo/tree/master/Sample). For a more in depth
sample there's [NerdBudget](https://github.com/ellerbus/Dynamo/tree/master/NerdBudget).
NerdBudget is a simple application for tracking a budget, but is a completely implemented
system whereby output from a template was modified based on the need of the application.
Whereas the Sample Solution focuses on a straight out-of-the-box implementation of
non-modified templates. For all intents and purposes, NerdBudget is maintained and more
up-to-date compared with the Sample Solution.

#### Helpful Pages

- [Dynamo's API](https://github.com/ellerbus/Dynamo/wiki/Dynamo-API)
- [Dynamo's Filters](https://github.com/ellerbus/Dynamo/wiki/Dynamo-Filters)
- [Provided Templates](https://github.com/ellerbus/Dynamo/tree/master/Templates)

#### SQL Databases Currently Supported
via [DB Schema Reader](http://dbschemareader.codeplex.com/)
- SqlServer
- SqlServer CE 4
- MySQL
- SQLite
- ODP
- Devar
- PostgreSql
- Db2
- System.Data.OracleClient

#### Template Sample (SQL Schema, Template, & Final Code File)

``` sql
CREATE TABLE MEMBER
(
	member_id		int not null,
	member_name		varchar(50) not null,
	primary key		(member_id),
	unique			(member_name)
)
```

```
{% capture BASECLASS %}{{ table.name | pascal }}{% endcapture -%}
{% capture PROJECT %}{{ SOLUTION }}.WebProject{% endcapture -%}
{% capture FILENAME %}{{ PROJECT }}\Models\Generated\{{ BASECLASS }}.cs{% endcapture -%}
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace {{ PROJECT }}.Models
{
	///	<summary>
	///	</summary>
	[Table("{{ table.name }}")]
	public partial class {{ BASECLASS }}
	{
		#region Primary Key Properties
		{% for column in table.primary_keys %}
		///	<summary>
		///	Gets / Sets database column '{{ column.name }}' (primary key)
		///	</summary>
		[Column("{{ column.name }}"), Key]
		public {{ column.clr_type }} {{ column.name | pascal | remove:BASECLASS }} { get; set; }

		{% endfor -%}

		#endregion

		#region Properties
		{% for column in table.columns %}{% if column.is_primary_key == false %}
		///	<summary>
		///	Gets / Sets database column '{{ column.name }}'
		///	</summary>
		[Column("{{ column.name }}")]
		public {{ column.clr_type }} {{ column.name | pascal }} { get; set; }

		{% endif %}{% endfor -%}

		#endregion
	}
}
```

``` csharp
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MySolution.WebProject.Models
{
	///	<summary>
	///	</summary>
	[Table("MEMBER")]
	public partial class Member
	{
		#region Primary Key Properties

		///	<summary>
		///	Gets / Sets database column 'member_id' (primary key)
		///	</summary>
		[Column("member_id"), Key]
		public int Id { get; set; }

		#endregion

		#region Properties

		///	<summary>
		///	Gets / Sets database column 'member_name'
		///	</summary>
		[Column("member_name")]
		public string MemberName { get; set; }  // notice we didn't use remove:BASECLASS here

		#endregion
	}
}
```

#### Screen Shots

Code Generator

![Code Generator](/docs/CodeGenerator.png)

Connection String Builder

![Connection String Builder](/docs/ConnectionStringBuilder.png)


text:
<!--
Copyright 2022 The Chromium Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<!--
This file is used to generate a comprehensive list of ChromeOS clipboard-related
histograms along with a detailed description for each histogram.

For best practices on writing histogram descriptions, see
https://chromium.googlesource.com/chromium/src.git/+/HEAD/tools/metrics/histograms/README.md

Please follow the instructions in the OWNERS file in this directory to find a
reviewer. If no OWNERS file exists, please consider signing up at
go/reviewing-metrics (Googlers only), as all subdirectories are expected to
have an OWNERS file. As a last resort you can send the CL to
chromium-metrics-reviews@google.com.
-->

<histogram-configuration>

<histograms>

<histogram name="Ash.Clipboard.ConsecutiveCopies" units="times"
    expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The number of consecutive copies in the user session. Recorded when a paste
    occurs.

    Warning: This histogram was expired from 2021-09-01 to 2022-01-05; data may
    be missing.
  </summary>
</histogram>

<histogram name="Ash.Clipboard.ConsecutivePastes" units="times"
    expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The number of consecutive pastes in the user session. Includes pastes from
    clipboard history. Recorded when a copy occurs.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ConsecutivePastes" units="times"
    expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The number of consecutive pastes from the clipboard history menu in the user
    session. Recorded at the time of a copy or a paste that is not through the
    clipboard history menu, such as pressing Ctrl+V or using a context menu's
    Paste option.

    Warning: This histogram was expired from 2022-01-02 to 2022-01-05; data may
    be missing.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ContextMenu.DisplayFormatDeleted"
    enum="ClipboardHistoryDisplayFormat" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The data format of an item deleted from the clipboard history menu. Recorded
    when the user deletes an item.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ContextMenu.DisplayFormatPasted"
    enum="ClipboardHistoryDisplayFormat" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The data format of an item pasted from the clipboard history menu. Recorded
    when the user pastes an item.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ContextMenu.DisplayFormatShown"
    enum="ClipboardHistoryDisplayFormat" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The data format of an item shown in the clipboard history menu. Recorded
    when the item's view is created.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ContextMenu.MenuOptionSelected"
    units="index" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The index of a clipboard history menu item selected by the user. Recorded
    when the item is selected.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ContextMenu.NumberOfItemsShown"
    units="Items Shown" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The number of items shown in the clipboard history menu. Recorded each time
    the menu is shown.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ContextMenu.ShowMenu"
    enum="ClipboardHistoryTriggerType" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The way a user made the clipboard history menu show. Recorded each time the
    menu is shown.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ContextMenu.ShowPlaceholderString"
    enum="ClipboardHistoryPlaceholderStringType" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The type of placeholder string shown in a clipboard history item in lieu of
    actual data. Recorded on menu item creation when necessary.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ContextMenu.UserJourneyTime" units="ms"
    expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The length of time between the user opening the clipboard history menu and
    the menu closing. Recorded every time the clipboard history menu is closed,
    regardless of whether the user selected one of the menu's options.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ControlToVDelay" units="ms"
    expires_after="2023-04-25">
  <obsolete>
    Replaced by version 2 in 10/22. This histogram can be deleted when M109
    reaches stable.
  </obsolete>
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The time between a user's Ctrl key press and the user's V key press when
    pasting via keyboard. Recorded when V is pressed. Only recorded for the
    first V press in a sequence. Sample scenario: User holds Ctrl, waits 200ms,
    presses V (histogram entry recorded), and presses V again without releasing
    Ctrl (no histogram entry recorded).
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ControlToVDelayV2" units="ms"
    expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The time between a user's Ctrl key press and the user's V key press when
    pasting via keyboard. Recorded when V is pressed. Only recorded for the
    first V press in a sequence. Sample scenario: User holds Ctrl, waits 200ms,
    presses V (histogram entry recorded), and presses V again without releasing
    Ctrl (no histogram entry recorded).

    Note: Version 1 of this histogram incorrectly recorded the Ctrl pressed time
    in some cases such that it seemed closer to the V pressed time than it
    really was. This histogram's entries are more accurate.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ControlVHeldTime" units="ms"
    expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The time between a user's V key press in a Ctrl+V sequence and the end of
    the paste. Recorded when Ctrl is released, V is released, or a different key
    is pressed.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ImageModelRequest.Lifetime" units="ms"
    expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The lifetime of a request created by the clipboard image model factory. This
    factory reuses one request object for disinct logical requests until no new
    rendering requests are issued for some period of time, at which point the
    request object is deemed idle and destroyed. Recorded when a request object
    is destroyed, either because it was idle or the system is shutting down.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ImageModelRequest.Runtime" units="ms"
    expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The delay between the issue time of a request to render a clipboard history
    item preview and the request's completion time. Recorded when a rendering
    request finishes.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ImageModelRequest.StopReason"
    enum="RequestStopReason" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The end result of a request to render an image preview for the clipboard
    history menu. Recorded when a request finishes, whether successful or not.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.Nudges.{NudgeType}.ShownCount"
    enum="BooleanHit" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The number of times the clipboard history {NudgeType} has been shown.
    Recorded when the {NudgeType} is shown.

    This histogram can be used in conjunction with the ToFeatureOpen and
    ToFeaturePaste histograms to understand a nudge's efficacy in getting users
    to engage with the feature.
  </summary>
  <token key="NudgeType">
    <variant name="OnboardingNudge" summary="onboarding nudge"/>
    <variant name="ScreenshotNotificationNudge"
        summary="screenshot notification nudge"/>
    <variant name="ZeroStateNudge" summary="zero state nudge"/>
  </token>
</histogram>

<histogram name="Ash.ClipboardHistory.Nudges.{NudgeType}.ToFeature{Action}Time"
    units="seconds" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The delay between the user being shown the clipboard history {NudgeType} and
    the user's {Action} action. Recorded at the time of the {Action}.
  </summary>
  <token key="NudgeType">
    <variant name="OnboardingNudge" summary="onboarding nudge"/>
    <variant name="ScreenshotNotificationNudge"
        summary="screenshot notification nudge"/>
    <variant name="ZeroStateNudge" summary="zero state nudge"/>
  </token>
  <token key="Action">
    <variant name="Open" summary="opening the clipboard history menu"/>
    <variant name="Paste" summary="pasting from the clipboard history menu"/>
  </token>
</histogram>

<histogram name="Ash.ClipboardHistory.Operation"
    enum="ClipboardHistoryOperation" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    An operation such as a copy or paste detected by clipboard history. Recorded
    after any duplicate clipboard operations are debounced in clipboard history.

    The total number of copies and pastes in this histogram differ from the
    Clipboard.Write and Clipboard.Read histograms, respectively, because
    clipboard history debounces operations before emitting to this histogram. As
    a result, clipboard history avoids recording programmatic clipboard reads
    and writes that do not correspond to user actions.

    Warning: This histogram was expired from 2022-01-02 to 2022-01-05; data may
    be missing.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.PasteType"
    enum="ClipboardHistoryPasteType" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The type (plain vs. rich text) and input source of a clipboard history
    paste. Recorded when an item is pasted from clipboard history.
  </summary>
</histogram>

<histogram name="Ash.ClipboardHistory.ReorderType"
    enum="ClipboardHistoryReorderType" expires_after="2023-04-25">
  <owner>ckincaid@chromium.org</owner>
  <owner>multipaste@google.com</owner>
  <summary>
    The operation (copy or paste) initiating a clipboard history reorder.
    Recorded each time the clipboard history list is reordered.
  </summary>
</histogram>

</histograms>

</histogram-configuration>


text:
namespace boost
{
  namespace metaparse
  {
    namespace v1
    {
      template <class P, int N>
      struct iterate_c : impl::iterate_impl<N, P, boost::mpl::deque<> > {};
    }
  }
}

#endif


text:
"""Follower (Model) query functions.
"""

__authors__ = [
    '"Lennard de Rijk" <ljvderijk@gmail.com>',
  ]

from soc.logic.models import base
from soc.logic.models import linkable as linkable_logic

import soc.modules.gsoc.models.follower

class Logic(base.Logic):
  """Logic methods for the Follower model.
  """

  def __init__(self, model=soc.modules.gsoc.models.follower.Follower,
               base_model=None, scope_logic=linkable_logic):
    """Defines the name, key_name and model for this entity.
    """

    super(Logic, self).__init__(model, base_model=base_model,
                                scope_logic=scope_logic)

logic = Logic()


text:
from geojson_rest.actions import download_csv
from django.conf import settings
from django.core.urlresolvers import reverse_lazy
from django.contrib import admin
from django.contrib.gis import admin as gisadmin
from django.utils.translation import ugettext_lazy as _
# from geojson_rest.models import PointFeature
# from geojson_rest.models import LinestringFeature
# from geojson_rest.models import PolygonFeature
from geojson_rest.models import Feature
from geojson_rest.models import Property

class HasFeatureFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('is connected to feature')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'feature'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        return (
            ('hasfeature', _('is connected to feature')),
            ('nofeature', _('is not connected to feature')),
        )

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        # Compare the requested value (either '80s' or 'other')
        # to decide how to filter the queryset.
        if self.value() == 'hasfeature':
            return queryset.exclude(feature=None)
        if self.value() == 'nofeature':
            return queryset.filter(feature=None)

class FeatureAdmin(gisadmin.OSMGeoAdmin):
    search_fields = ('user__username', 'group', 'time__create_time')
    list_display = ('user',
                    'group',
                    'get_create_time')
    readonly_fields = ('user',
                       'group',
                       'private',
                       'properties',
                       'time')
    list_filter = ('group', 'private',)
    openlayers_url = '%s%s' % (getattr(settings, 'STATIC_URL', '/'),
                               'js/libs/OpenLayers.js')
    actions = [download_csv]
    modifiable = False
    actions = ['delete_selected']

    def delete_selected(self, request, queryset):
        for obj in queryset:
            obj.delete()

        self.message_user(request, _("successfully deleted the selected features."))

    delete_selected.short_description = _('delete selected features')
    def __str__(self):
        return "Feature"

admin.site.register(Feature, FeatureAdmin)

class PropertyAdmin(admin.ModelAdmin):
    search_fields = ('user__username', 'group', 'time__create_time')
    list_display = ('group',
                    'user',
                    'get_create_time',
                    'json_data')
    readonly_fields = ('user',
                       'group',
                       'json_data',
                       'time')
    list_filter = ('group', HasFeatureFilter, )
    actions = [download_csv]

    def __str__(self):
        return "Property"

admin.site.register(Property, PropertyAdmin)


text:
package resources

import (
	"testing"

	"github.com/google/go-cmp/cmp"
)

func TestGetLabels(t *testing.T) {
	want := map[string]string{
		"receive-adapter":                     "receive-adapter-name",
		"events.cloud.google.com/source-name": "source",
	}
	got := GetLabels("receive-adapter-name", "source")

	if diff := cmp.Diff(want, got); diff != "" {
		t.Errorf("unexpected (-want, +got) = %v", diff)
	}
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

?>

<!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="css/pintuer.css">
    <link rel="stylesheet" href="css/admin.css">

<form method="post" action="" id="listform">

 内容列表 添加字段

  添加数据库

                    <input type="text" placeholder="请输入搜索关键字" name="keywords" class="input" style="width:250px; line-height:17px;display:inline-block" />
                     搜索

        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                'serverName',
                'port',
                'note',
                'userId',
                'createTime:datetime',
                [
                    'class' => 'yii\grid\ActionColumn',
                    'header'=> '操作',
                    'template'=>'{connect}',
                    'buttons' => [
                        'connect' => function ($url, $model, $key) {

                            return  Html::a('连接到redis',
                                "javascript:connect('$model->id','$model->serverName','$model->port','$model->db');",
                                ['title' => "连接到数据库",'data-pjax'=>'0'] ) ;
                        },
//                        'update' => function ($url, $model, $key) {
//                            return  Html::a('编辑', $url, ['title' => 121,'data-pjax'=>'0'] ) ;
//                        },
//                        'delete' => function ($url, $model, $key) {
//                            return  Html::a('删除', $url, ['title' => 121,'data-pjax'=>'0'] ) ;
//                        },
                    ],
                ],
            ],
        ]); ?>

</form>


text:
/

#include <OCRepresentation.h>

#include <boost/lexical_cast.hpp>
#include <algorithm>
#include "ocpayload.h"
#include "ocrandom.h"
#include "oic_malloc.h"
#include "oic_string.h"

namespace OC
{

    void MessageContainer::setPayload(const OCPayload* rep)
    {
        switch(rep->type)
        {
            case PAYLOAD_TYPE_REPRESENTATION:
                setPayload(reinterpret_cast<const OCRepPayload*>(rep));
                break;
            case PAYLOAD_TYPE_DEVICE:
                setPayload(reinterpret_cast<const OCDevicePayload*>(rep));
                break;
            case PAYLOAD_TYPE_PLATFORM:
                setPayload(reinterpret_cast<const OCPlatformPayload*>(rep));
                break;
            default:
                throw OC::OCException("Invalid Payload type in setPayload");
                break;
        }
    }

    void MessageContainer::setPayload(const OCDevicePayload* payload)
    {
        OCRepresentation rep;
        rep.setUri(payload->uri);
        char uuidString[UUID_STRING_SIZE];
        if(payload->sid && RAND_UUID_OK == OCConvertUuidToString(payload->sid, uuidString))
        {
            rep[OC_RSRVD_DEVICE_ID] = std::string(uuidString);
        }
        else
        {
            rep[OC_RSRVD_DEVICE_ID] = std::string();
        }
        rep[OC_RSRVD_DEVICE_NAME] = payload->deviceName ?
            std::string(payload->deviceName) :
            std::string();
        rep[OC_RSRVD_SPEC_VERSION] = payload->specVersion ?
            std::string(payload->specVersion) :
            std::string();
        rep[OC_RSRVD_DATA_MODEL_VERSION] = payload->dataModelVersion ?
            std::string(payload->dataModelVersion) :
            std::string();
        m_reps.push_back(std::move(rep));
    }

    void MessageContainer::setPayload(const OCPlatformPayload* payload)
    {
        OCRepresentation rep;
        rep.setUri(payload->uri);

        rep[OC_RSRVD_PLATFORM_ID] = payload->info.platformID ?
            std::string(payload->info.platformID) :
            std::string();
        rep[OC_RSRVD_MFG_NAME] = payload->info.manufacturerName ?
            std::string(payload->info.manufacturerName) :
            std::string();
        rep[OC_RSRVD_MFG_URL] = payload->info.manufacturerUrl ?
            std::string(payload->info.manufacturerUrl) :
            std::string();
        rep[OC_RSRVD_MODEL_NUM] = payload->info.modelNumber ?
            std::string(payload->info.modelNumber) :
            std::string();
        rep[OC_RSRVD_MFG_DATE] = payload->info.dateOfManufacture ?
            std::string(payload->info.dateOfManufacture) :
            std::string();
        rep[OC_RSRVD_PLATFORM_VERSION] = payload->info.platformVersion ?
            std::string(payload->info.platformVersion) :
            std::string();
        rep[OC_RSRVD_OS_VERSION] = payload->info.operatingSystemVersion ?
            std::string(payload->info.operatingSystemVersion) :
            std::string();
        rep[OC_RSRVD_HARDWARE_VERSION] = payload->info.hardwareVersion ?
            std::string(payload->info.hardwareVersion) :
            std::string();
        rep[OC_RSRVD_FIRMWARE_VERSION] = payload->info.firmwareVersion ?
            std::string(payload->info.firmwareVersion) :
            std::string();
        rep[OC_RSRVD_SUPPORT_URL] = payload->info.supportUrl ?
            std::string(payload->info.supportUrl) :
            std::string();
        rep[OC_RSRVD_SYSTEM_TIME] = payload->info.systemTime ?
            std::string(payload->info.systemTime) :
            std::string();

        m_reps.push_back(std::move(rep));
    }

    void MessageContainer::setPayload(const OCRepPayload* payload)
    {
        const OCRepPayload* pl = payload;
        while(pl)
        {
            OCRepresentation cur;
            cur.setPayload(pl);

            pl = pl->next;
            this->addRepresentation(cur);
        }
    }

    OCRepPayload* MessageContainer::getPayload() const
    {
        OCRepPayload* root = nullptr;
        for(const auto& r : representations())
        {
            if(!root)
            {
                root = r.getPayload();
            }
            else
            {
                OCRepPayloadAppend(root, r.getPayload());
            }
        }

        return root;
    }

    const std::vector<OCRepresentation>& MessageContainer::representations() const
    {
        return m_reps;
    }

    void MessageContainer::addRepresentation(const OCRepresentation& rep)
    {
        m_reps.push_back(rep);
    }
}

namespace OC
{
    struct get_payload_array: boost::static_visitor<>
    {
        template<typename T>
        void operator()(T& /*arr*/)
        {
            throw std::logic_error("Invalid calc_dimensions_visitor type");
        }

        template<typename T>
        void operator()(std::vector<T>& arr)
        {
            root_size_calc<T>();
            dimensions[0] = arr.size();
            dimensions[1] = 0;
            dimensions[2] = 0;
            dimTotal = calcDimTotal(dimensions);

            array = (void*)OICMalloc(dimTotal * root_size);

            for(size_t i = 0; i < dimensions[0]; ++i)
            {
                copy_to_array(arr[i], array, i);
            }

        }
        template<typename T>
        void operator()(std::vector<std::vector<T>>& arr)
        {
            root_size_calc<T>();
            dimensions[0] = arr.size();
            dimensions[1] = 0;
            dimensions[2] = 0;
            for(size_t i = 0; i < arr.size(); ++i)
            {
                dimensions[1] = std::max(dimensions[1], arr[i].size());
            }
            dimTotal = calcDimTotal(dimensions);
            array = (void*)OICCalloc(1, dimTotal * root_size);

            for(size_t i = 0; i < dimensions[0]; ++i)
            {
                for(size_t j = 0; j < dimensions[1] && j < arr[i].size(); ++j)
                {
                    copy_to_array(arr[i][j], array, i*dimensions[1] + j);
                }
            }
        }
        template<typename T>
        void operator()(std::vector<std::vector<std::vector<T>>>& arr)
        {
            root_size_calc<T>();
            dimensions[0] = arr.size();
            dimensions[1] = 0;
            dimensions[2] = 0;
            for(size_t i = 0; i < arr.size(); ++i)
            {
                dimensions[1] = std::max(dimensions[1], arr[i].size());

                for(size_t j = 0; j < arr[i].size(); ++j)
                {
                    dimensions[2] = std::max(dimensions[2], arr[i][j].size());
                }
            }

            dimTotal = calcDimTotal(dimensions);
            array = (void*)OICCalloc(1, dimTotal * root_size);

            for(size_t i = 0; i < dimensions[0]; ++i)
            {
                for(size_t j = 0; j < dimensions[1] && j < arr[i].size(); ++j)
                {
                    for(size_t k = 0; k < dimensions[2] && k < arr[i][j].size(); ++k)
                    {
                        copy_to_array(arr[i][j][k], array,
                                dimensions[2] * j +
                                dimensions[2] * dimensions[1] * i +
                                k);
                    }
                }
            }
        }

        template<typename T>
        void root_size_calc()
        {
            root_size = sizeof(T);
        }

        template<typename T>
        void copy_to_array(T item, void* array, size_t pos)
        {
            ((T*)array)[pos] = item;
        }

        size_t dimensions[MAX_REP_ARRAY_DEPTH];
        size_t root_size;
        size_t dimTotal;
        void* array;
    };

    template<>
    void get_payload_array::root_size_calc<int>()
    {
        root_size = sizeof(int64_t);
    }

    template<>
    void get_payload_array::root_size_calc<std::string>()
    {
        root_size = sizeof(char*);
    }

    template<>
    void get_payload_array::root_size_calc<OC::OCRepresentation>()
    {
        root_size = sizeof(OCRepPayload*);
    }

    template<>
    void get_payload_array::copy_to_array(int item, void* array, size_t pos)
    {
        ((int64_t*)array)[pos] = item;
    }

#ifndef WIN32
    template<>
    void get_payload_array::copy_to_array(std::_Bit_reference br, void* array, size_t pos)
    {
        ((bool*)array)[pos] = static_cast<bool>(br);
    }
#endif

    template<>
    void get_payload_array::copy_to_array(std::string item, void* array, size_t pos)
    {
        ((char**)array)[pos] = OICStrdup(item.c_str());
    }

    template<>
    void get_payload_array::copy_to_array(std::string& item, void* array, size_t pos)
    {
        ((char**)array)[pos] = OICStrdup(item.c_str());
    }

    template<>
    void get_payload_array::copy_to_array(const std::string& item, void* array, size_t pos)
    {
        ((char**)array)[pos] = OICStrdup(item.c_str());
    }

    template<>
    void get_payload_array::copy_to_array(OC::OCRepresentation item, void* array, size_t pos)
    {
        ((OCRepPayload**)array)[pos] = item.getPayload();
    }

    void OCRepresentation::getPayloadArray(OCRepPayload* payload,
                    const OCRepresentation::AttributeItem& item) const
    {
        get_payload_array vis{};
        boost::apply_visitor(vis, m_values[item.attrname()]);

        switch(item.base_type())
        {
            case AttributeType::Integer:
                OCRepPayloadSetIntArrayAsOwner(payload, item.attrname().c_str(),
                        (int64_t*)vis.array,
                        vis.dimensions);
                break;
            case AttributeType::Double:
                OCRepPayloadSetDoubleArrayAsOwner(payload, item.attrname().c_str(),
                        (double*)vis.array,
                        vis.dimensions);
                break;
            case AttributeType::Boolean:
                OCRepPayloadSetBoolArrayAsOwner(payload, item.attrname().c_str(),
                        (bool*)vis.array,
                        vis.dimensions);
                break;
            case AttributeType::String:
                OCRepPayloadSetStringArrayAsOwner(payload, item.attrname().c_str(),
                        (char**)vis.array,
                        vis.dimensions);
                break;
            case AttributeType::OCRepresentation:
                OCRepPayloadSetPropObjectArrayAsOwner(payload, item.attrname().c_str(),
                        (OCRepPayload**)vis.array, vis.dimensions);
                break;
            default:
                throw std::logic_error(std::string("GetPayloadArray: Not Implemented") +
                        std::to_string((int)item.base_type()));
        }
    }

    OCRepPayload* OCRepresentation::getPayload() const
    {
        OCRepPayload* root = OCRepPayloadCreate();
        if(!root)
        {
            throw std::bad_alloc();
        }

        OCRepPayloadSetUri(root, getUri().c_str());

        for(const std::string& type : getResourceTypes())
        {
            OCRepPayloadAddResourceType(root, type.c_str());
        }

        for(const std::string& iface : getResourceInterfaces())
        {
            OCRepPayloadAddInterface(root, iface.c_str());
        }

        for(auto& val : *this)
        {
            switch(val.type())
            {
                case AttributeType::Null:
                    OCRepPayloadSetNull(root, val.attrname().c_str());
                    break;
                case AttributeType::Integer:
                    OCRepPayloadSetPropInt(root, val.attrname().c_str(), static_cast<int>(val));
                    break;
                case AttributeType::Double:
                    OCRepPayloadSetPropDouble(root, val.attrname().c_str(),
                            val.getValue<double>());
                    break;
                case AttributeType::Boolean:
                    OCRepPayloadSetPropBool(root, val.attrname().c_str(), val.getValue<bool>());
                    break;
                case AttributeType::String:
                    OCRepPayloadSetPropString(root, val.attrname().c_str(),
                            static_cast<std::string>(val).c_str());
                    break;
                case AttributeType::OCRepresentation:
                    OCRepPayloadSetPropObjectAsOwner(root, val.attrname().c_str(),
                            static_cast<OCRepresentation>(val).getPayload());
                    break;
                case AttributeType::Vector:
                    getPayloadArray(root, val);
                    break;
                default:
                    throw std::logic_error(std::string("Getpayload: Not Implemented") +
                            std::to_string((int)val.type()));
                    break;
            }
        }

        return root;
    }

    size_t calcArrayDepth(const size_t dimensions[MAX_REP_ARRAY_DEPTH])
    {
        if(dimensions[0] == 0)
        {
            throw std::logic_error("invalid calcArrayDepth");
        }
        else if(dimensions[1] == 0)
        {
            return 1;
        }
        else if (dimensions[2] == 0)
        {
            return 2;
        }
        else
        {
            return 3;
        }
    }

    template<typename T>
    T OCRepresentation::payload_array_helper_copy(size_t index, const OCRepPayloadValue* pl)
    {
        throw std::logic_error("payload_array_helper_copy: unsupported type");
    }
    template<>
    int OCRepresentation::payload_array_helper_copy<int>(size_t index, const OCRepPayloadValue* pl)
    {
        return pl->arr.iArray[index];
    }
    template<>
    double OCRepresentation::payload_array_helper_copy<double>(size_t index, const OCRepPayloadValue* pl)
    {
        return pl->arr.dArray[index];
    }
    template<>
    bool OCRepresentation::payload_array_helper_copy<bool>(size_t index, const OCRepPayloadValue* pl)
    {
        return pl->arr.bArray[index];
    }
    template<>
    std::string OCRepresentation::payload_array_helper_copy<std::string>(
            size_t index, const OCRepPayloadValue* pl)
    {
        if (pl->arr.strArray[index])
        {
            return std::string(pl->arr.strArray[index]);
        }
        else
        {
            return std::string{};
        }
    }
    template<>
    OCRepresentation OCRepresentation::payload_array_helper_copy<OCRepresentation>(
            size_t index, const OCRepPayloadValue* pl)
    {
        OCRepresentation r;
        if (pl->arr.objArray[index])
        {
            r.setPayload(pl->arr.objArray[index]);
        }
        return r;
    }

    template<typename T>
    void OCRepresentation::payload_array_helper(const OCRepPayloadValue* pl, size_t depth)
    {
        if(depth == 1)
        {
            std::vector<T> val(pl->arr.dimensions[0]);

            for(size_t i = 0; i < pl->arr.dimensions[0]; ++i)
            {
                val[i] = payload_array_helper_copy<T>(i, pl);
            }
            this->setValue(std::string(pl->name), val);
        }
        else if (depth == 2)
        {
            std::vector<std::vector<T>> val(pl->arr.dimensions[0]);
            for(size_t i = 0; i < pl->arr.dimensions[0]; ++i)
            {
                val[i].resize(pl->arr.dimensions[1]);
                for(size_t j = 0; j < pl->arr.dimensions[1]; ++j)
                {
                    val[i][j] = payload_array_helper_copy<T>(
                            i * pl->arr.dimensions[1] + j, pl);
                }
            }
            this->setValue(std::string(pl->name), val);
        }
        else if (depth == 3)
        {
            std::vector<std::vector<std::vector<T>>> val(pl->arr.dimensions[0]);
            for(size_t i = 0; i < pl->arr.dimensions[0]; ++i)
            {
                val[i].resize(pl->arr.dimensions[1]);
                for(size_t j = 0; j < pl->arr.dimensions[1]; ++j)
                {
                    val[i][j].resize(pl->arr.dimensions[2]);
                    for(size_t k = 0; k < pl->arr.dimensions[2]; ++k)
                    {
                        val[i][j][k] = payload_array_helper_copy<T>(
                                pl->arr.dimensions[2] * j +
                                pl->arr.dimensions[2] * pl->arr.dimensions[1] * i +
                                k,
                                pl);
                    }
                }
            }
            this->setValue(std::string(pl->name), val);
        }
        else
        {
            throw std::logic_error("Invalid depth in payload_array_helper");
        }
    }

    void OCRepresentation::setPayloadArray(const OCRepPayloadValue* pl)
    {

        switch(pl->arr.type)
        {
            case OCREP_PROP_INT:
                payload_array_helper<int>(pl, calcArrayDepth(pl->arr.dimensions));
                break;
            case OCREP_PROP_DOUBLE:
                payload_array_helper<double>(pl, calcArrayDepth(pl->arr.dimensions));
                break;
            case OCREP_PROP_BOOL:
                payload_array_helper<bool>(pl, calcArrayDepth(pl->arr.dimensions));
                break;
            case OCREP_PROP_STRING:
                payload_array_helper<std::string>(pl, calcArrayDepth(pl->arr.dimensions));
                break;
            case OCREP_PROP_OBJECT:
                payload_array_helper<OCRepresentation>(pl, calcArrayDepth(pl->arr.dimensions));
                break;
            default:
                throw std::logic_error("setPayload array invalid type");
                break;
        }
    }

    void OCRepresentation::setPayload(const OCRepPayload* pl)
    {
        setUri(pl->uri);

        OCStringLL* ll = pl->types;
        while(ll)
        {
            addResourceType(ll->value);
            ll = ll->next;
        }

        ll = pl->interfaces;
        while(ll)
        {
            addResourceInterface(ll->value);
            ll = ll->next;
        }

        OCRepPayloadValue* val = pl->values;

        while(val)
        {
            switch(val->type)
            {
                case OCREP_PROP_NULL:
                    setNULL(val->name);
                    break;
                case OCREP_PROP_INT:
                    setValue<int>(val->name, val->i);
                    break;
                case OCREP_PROP_DOUBLE:
                    setValue<double>(val->name, val->d);
                    break;
                case OCREP_PROP_BOOL:
                    setValue<bool>(val->name, val->b);
                    break;
                case OCREP_PROP_STRING:
                    setValue<std::string>(val->name, val->str);
                    break;
                case OCREP_PROP_OBJECT:
                    {
                        OCRepresentation cur;
                        cur.setPayload(val->obj);
                        setValue<OCRepresentation>(val->name, cur);
                    }
                    break;
                case OCREP_PROP_ARRAY:
                    setPayloadArray(val);
                    break;
                default:
                    throw std::logic_error(std::string("Not Implemented!") +
                            std::to_string((int)val->type));
                    break;
            }
            val = val->next;
        }
    }

    void OCRepresentation::addChild(const OCRepresentation& rep)
    {
        m_children.push_back(rep);
    }

    void OCRepresentation::clearChildren()
    {
        m_children.clear();
    }

    const std::vector<OCRepresentation>& OCRepresentation::getChildren() const
    {
        return m_children;
    }

    void OCRepresentation::setChildren(const std::vector<OCRepresentation>& children)
    {
        m_children = children;
    }
    void OCRepresentation::setUri(const char* uri)
    {
        m_uri = uri ? uri : "";
    }

    void OCRepresentation::setUri(const std::string& uri)
    {
        m_uri = uri;
    }

    std::string OCRepresentation::getUri() const
    {
        return m_uri;
    }

    const std::vector<std::string>& OCRepresentation::getResourceTypes() const
    {
        return m_resourceTypes;
    }

    void OCRepresentation::setResourceTypes(const std::vector<std::string>& resourceTypes)
    {
        m_resourceTypes = resourceTypes;
    }

    void OCRepresentation::addResourceType(const std::string& str)
    {
        m_resourceTypes.push_back(str);
    }

    const std::vector<std::string>& OCRepresentation::getResourceInterfaces() const
    {
        return m_interfaces;
    }

    void OCRepresentation::addResourceInterface(const std::string& str)
    {
        m_interfaces.push_back(str);
    }

    void OCRepresentation::setResourceInterfaces(const std::vector<std::string>& resourceInterfaces)
    {
        m_interfaces = resourceInterfaces;
    }

    bool OCRepresentation::hasAttribute(const std::string& str) const
    {
        return m_values.find(str) != m_values.end();
    }

    bool OCRepresentation::emptyData() const
    {
        // This logic is meant to determine whether based on the JSON serialization rules
        // if this object will result in empty JSON.  URI is only serialized if there is valid
        // data, ResourceType and Interfaces are only serialized if we are a nothing, a
        // child of a default or link item.
        // Our values array is only printed in the if we are the child of a Batch resource,
        // the parent in a 'default' situation, or not in a child/parent relationship.
        if(!m_uri.empty())
        {
            return false;
        }
        else if ((m_interfaceType == InterfaceType::None
                        || m_interfaceType==InterfaceType::DefaultChild
                        || m_interfaceType==InterfaceType::LinkChild)
                    && (m_resourceTypes.size()>0 || m_interfaces.size()>0))
        {
            return false;
        }
        else if((m_interfaceType == InterfaceType::None
                        || m_interfaceType == InterfaceType::BatchChild
                        || m_interfaceType == InterfaceType::DefaultParent)
                    && m_values.size()>0)
        {
            return false;
        }

        if(m_children.size() > 0)
        {
            return false;
        }

        return true;
    }

    int OCRepresentation::numberOfAttributes() const
    {
        return m_values.size();
    }

    bool OCRepresentation::erase(const std::string& str)
    {
        return m_values.erase(str);
    }

    void OCRepresentation::setNULL(const std::string& str)
    {
        m_values[str] = OC::NullType();
    }

    bool OCRepresentation::isNULL(const std::string& str) const
    {
        auto x = m_values.find(str);

        if(m_values.end() != x)
        {
            return x->second.which() == AttributeValueNullIndex;
        }
        else
        {
            throw OCException(OC::Exception::INVALID_ATTRIBUTE+ str);
        }
    }
}

namespace OC
{
    std::ostream& operator <<(std::ostream& os, const AttributeType at)
    {
        switch(at)
        {
            case AttributeType::Null:
                os << "Null";
                break;
            case AttributeType::Integer:
                os << "Integer";
                break;
            case AttributeType::Double:
                os << "Double";
                break;
            case AttributeType::Boolean:
                os << "Boolean";
                break;
            case AttributeType::String:
                os << "String";
                break;
            case AttributeType::OCRepresentation:
                os << "OCRepresentation";
                break;
            case AttributeType::Vector:
                os << "Vector";
                break;
        }
        return os;
    }
}

// STL Container For OCRepresentation
namespace OC
{
    OCRepresentation::AttributeItem::AttributeItem(const std::string& name,
            std::map<std::string, AttributeValue>& vals):
            m_attrName(name), m_values(vals){}

    OCRepresentation::AttributeItem OCRepresentation::operator[](const std::string& key)
    {
        OCRepresentation::AttributeItem attr{key, m_values};
        return std::move(attr);
    }

    const OCRepresentation::AttributeItem OCRepresentation::operator[](const std::string& key) const
    {
        OCRepresentation::AttributeItem attr{key, m_values};
        return std::move(attr);
    }

    const std::string& OCRepresentation::AttributeItem::attrname() const
    {
        return m_attrName;
    }

    template<typename T, typename = void>
    struct type_info
    {
        // contains the actual type
        typedef T type;
        // contains the inner most vector-type
        typedef T base_type;
        // contains the AttributeType for this item
        constexpr static AttributeType enum_type =
            AttributeTypeConvert<T>::type;
        // contains the AttributeType for this base-type
        constexpr static AttributeType enum_base_type =
            AttributeTypeConvert<T>::type;
        // depth of the vector
        constexpr static size_t depth = 0;
    };

    template<typename T>
    struct type_info<T, typename std::enable_if<is_vector<T>::value>::type>
    {
        typedef T type;
        typedef typename type_info<typename T::value_type>::base_type base_type;
        constexpr static AttributeType enum_type = AttributeType::Vector;
        constexpr static AttributeType enum_base_type =
            type_info<typename T::value_type>::enum_base_type;
        constexpr static size_t depth = 1 +
            type_info<typename T::value_type>::depth;
    };

    struct type_introspection_visitor : boost::static_visitor<>
    {
        AttributeType type;
        AttributeType base_type;
        size_t depth;

        type_introspection_visitor() : boost::static_visitor<>(),
            type(AttributeType::Null), base_type(AttributeType::Null), depth(0){}

        template <typename T>
        void operator()(T const& /*item*/)
        {
            type = type_info<T>::enum_type;
            base_type = type_info<T>::enum_base_type;
            depth = type_info<T>::depth;
        }
    };

    AttributeType OCRepresentation::AttributeItem::type() const
    {
        type_introspection_visitor vis;
        boost::apply_visitor(vis, m_values[m_attrName]);
        return vis.type;
    }

    AttributeType OCRepresentation::AttributeItem::base_type() const
    {
        type_introspection_visitor vis;
        boost::apply_visitor(vis, m_values[m_attrName]);
        return vis.base_type;
    }

    size_t OCRepresentation::AttributeItem::depth() const
    {
        type_introspection_visitor vis;
        boost::apply_visitor(vis, m_values[m_attrName]);
        return vis.depth;
    }

    OCRepresentation::iterator OCRepresentation::begin()
    {
        return OCRepresentation::iterator(m_values.begin(), m_values);
    }

    OCRepresentation::const_iterator OCRepresentation::begin() const
    {
         return OCRepresentation::const_iterator(m_values.begin(), m_values);
    }

    OCRepresentation::const_iterator OCRepresentation::cbegin() const
    {
        return OCRepresentation::const_iterator(m_values.cbegin(), m_values);
    }

    OCRepresentation::iterator OCRepresentation::end()
    {
        return OCRepresentation::iterator(m_values.end(), m_values);
    }

    OCRepresentation::const_iterator OCRepresentation::end() const
    {
        return OCRepresentation::const_iterator(m_values.end(), m_values);
    }

    OCRepresentation::const_iterator OCRepresentation::cend() const
    {
        return OCRepresentation::const_iterator(m_values.cend(), m_values);
    }

    size_t OCRepresentation::size() const
    {
        return m_values.size();
    }

    bool OCRepresentation::empty() const
    {
        return m_values.empty();
    }

    bool OCRepresentation::iterator::operator==(const OCRepresentation::iterator& rhs) const
    {
        return m_iterator == rhs.m_iterator;
    }

    bool OCRepresentation::iterator::operator!=(const OCRepresentation::iterator& rhs) const
    {
        return m_iterator != rhs.m_iterator;
    }

    bool OCRepresentation::const_iterator::operator==(
            const OCRepresentation::const_iterator& rhs) const
    {
        return m_iterator == rhs.m_iterator;
    }

    bool OCRepresentation::const_iterator::operator!=(
            const OCRepresentation::const_iterator& rhs) const
    {
        return m_iterator != rhs.m_iterator;
    }

    OCRepresentation::iterator::reference OCRepresentation::iterator::operator*()
    {
        return m_item;
    }

    OCRepresentation::const_iterator::const_reference
        OCRepresentation::const_iterator::operator*() const
    {
        return m_item;
    }

    OCRepresentation::iterator::pointer OCRepresentation::iterator::operator->()
    {
        return &m_item;
    }

    OCRepresentation::const_iterator::const_pointer
        OCRepresentation::const_iterator::operator->() const
    {
        return &m_item;
    }

    OCRepresentation::iterator& OCRepresentation::iterator::operator++()
    {
        m_iterator++;
        if(m_iterator != m_item.m_values.end())
        {
            m_item.m_attrName = m_iterator->first;
        }
        else
        {
            m_item.m_attrName = "";
        }
        return *this;
    }

    OCRepresentation::const_iterator& OCRepresentation::const_iterator::operator++()
    {
        m_iterator++;
        if(m_iterator != m_item.m_values.end())
        {
            m_item.m_attrName = m_iterator->first;
        }
        else
        {
            m_item.m_attrName = "";
        }
        return *this;
    }

    OCRepresentation::iterator OCRepresentation::iterator::operator++(int)
    {
        OCRepresentation::iterator itr(*this);
        ++(*this);
        return itr;
    }

    OCRepresentation::const_iterator OCRepresentation::const_iterator::operator++(int)
    {
        OCRepresentation::const_iterator itr(*this);
        ++(*this);
        return itr;
    }

    struct to_string_visitor : boost::static_visitor<>
    {
        std::string str;
        template <typename T>
        void operator()(T const& item)
        {
            str = boost::lexical_cast<std::string>(item);
        }

        template <typename T>
        void operator()(std::vector<T> const& item)
        {
            to_string_visitor vis;
            std::ostringstream stream;
            stream << "[";

            for(const auto& i : item)
            {
                vis(i);
                stream << vis.str  << " ";
            }
            stream << "]";
            str = stream.str();
        }
    };

    template<>
    void to_string_visitor::operator()(bool const& item)
    {
        str = item ? "true" : "false";
    }

    template<>
    void to_string_visitor::operator()(std::string const& item)
    {
        str = item;
    }

    template<>
    void to_string_visitor::operator()(NullType const& /*item*/)
    {
        str = "(null)";
    }

    template<>
    void to_string_visitor::operator()(OCRepresentation const& /*item*/)
    {
        str = "OC::OCRepresentation";
    }

    std::string OCRepresentation::getValueToString(const std::string& key) const
    {
        auto x = m_values.find(key);
        if(x != m_values.end())
        {
            to_string_visitor vis;
            boost::apply_visitor(vis, x->second);
            return std::move(vis.str);
        }

        return "";
    }

    std::string OCRepresentation::AttributeItem::getValueToString() const
    {
        to_string_visitor vis;
        boost::apply_visitor(vis, m_values[m_attrName]);
        return std::move(vis.str);
    }

    std::ostream& operator<<(std::ostream& os, const OCRepresentation::AttributeItem& ai)
    {
        os << ai.getValueToString();
        return os;
    }
}


text:
#ifndef BOOST_ASIO_DETAIL_WINCE_THREAD_HPP
#define BOOST_ASIO_DETAIL_WINCE_THREAD_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/config.hpp>

#if defined(BOOST_WINDOWS) && defined(UNDER_CE)

#include <memory>
#include <boost/asio/detail/noncopyable.hpp>
#include <boost/asio/detail/socket_types.hpp>
#include <boost/asio/detail/throw_error.hpp>
#include <boost/asio/error.hpp>

#include <boost/asio/detail/push_options.hpp>

namespace boost {
namespace asio {
namespace detail {

DWORD WINAPI wince_thread_function(LPVOID arg);

class wince_thread
  : private noncopyable
{
public:
  // Constructor.
  template <typename Function>
  wince_thread(Function f, unsigned int = 0)
  {
    std::auto_ptr<func_base> arg(new func<Function>(f));
    DWORD thread_id = 0;
    thread_ = ::CreateThread(0, 0, wince_thread_function,
        arg.get(), 0, &thread_id);
    if (!thread_)
    {
      DWORD last_error = ::GetLastError();
      boost::system::error_code ec(last_error,
          boost::asio::error::get_system_category());
      boost::asio::detail::throw_error(ec, "thread");
    }
    arg.release();
  }

  // Destructor.
  ~wince_thread()
  {
    ::CloseHandle(thread_);
  }

  // Wait for the thread to exit.
  void join()
  {
    ::WaitForSingleObject(thread_, INFINITE);
  }

private:
  friend DWORD WINAPI wince_thread_function(LPVOID arg);

  class func_base
  {
  public:
    virtual ~func_base() {}
    virtual void run() = 0;
  };

  template <typename Function>
  class func
    : public func_base
  {
  public:
    func(Function f)
      : f_(f)
    {
    }

    virtual void run()
    {
      f_();
    }

  private:
    Function f_;
  };

  ::HANDLE thread_;
};

inline DWORD WINAPI wince_thread_function(LPVOID arg)
{
  std::auto_ptr<wince_thread::func_base> func(
      static_cast<wince_thread::func_base*>(arg));
  func->run();
  return 0;
}

} // namespace detail
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)

#endif // BOOST_ASIO_DETAIL_WINCE_THREAD_HPP