text:
package org.elasticsearch.ingest.common;

import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matchers;

import java.util.HashMap;
import java.util.Map;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

public class ConvertProcessorFactoryTests extends ESTestCase {

    public void testCreate() throws Exception {
        ConvertProcessor.Factory factory = new ConvertProcessor.Factory();
        Map<String, Object> config = new HashMap<>();
        ConvertProcessor.Type type = randomFrom(ConvertProcessor.Type.values());
        config.put("field", "field1");
        config.put("type", type.toString());
        String processorTag = randomAlphaOfLength(10);
        ConvertProcessor convertProcessor = factory.create(null, processorTag, null, config);
        assertThat(convertProcessor.getTag(), equalTo(processorTag));
        assertThat(convertProcessor.getField(), equalTo("field1"));
        assertThat(convertProcessor.getTargetField(), equalTo("field1"));
        assertThat(convertProcessor.getConvertType(), equalTo(type));
        assertThat(convertProcessor.isIgnoreMissing(), is(false));
    }

    public void testCreateUnsupportedType() throws Exception {
        ConvertProcessor.Factory factory = new ConvertProcessor.Factory();
        Map<String, Object> config = new HashMap<>();
        String type = "type-" + randomAlphaOfLengthBetween(1, 10);
        config.put("field", "field1");
        config.put("type", type);
        try {
            factory.create(null, null, null, config);
            fail("factory create should have failed");
        } catch (ElasticsearchParseException e) {
            assertThat(e.getMessage(), Matchers.equalTo("[type] type [" + type + "] not supported, cannot convert field."));
            assertThat(e.getMetadata("es.processor_type").get(0), equalTo(ConvertProcessor.TYPE));
            assertThat(e.getMetadata("es.property_name").get(0), equalTo("type"));
            assertThat(e.getMetadata("es.processor_tag"), nullValue());
        }
    }

    public void testCreateNoFieldPresent() throws Exception {
        ConvertProcessor.Factory factory = new ConvertProcessor.Factory();
        Map<String, Object> config = new HashMap<>();
        String type = "type-" + randomAlphaOfLengthBetween(1, 10);
        config.put("type", type);
        try {
            factory.create(null, null, null, config);
            fail("factory create should have failed");
        } catch (ElasticsearchParseException e) {
            assertThat(e.getMessage(), Matchers.equalTo("[field] required property is missing"));
        }
    }

    public void testCreateNoTypePresent() throws Exception {
        ConvertProcessor.Factory factory = new ConvertProcessor.Factory();
        Map<String, Object> config = new HashMap<>();
        config.put("field", "field1");
        try {
            factory.create(null, null, null, config);
            fail("factory create should have failed");
        } catch (ElasticsearchParseException e) {
            assertThat(e.getMessage(), Matchers.equalTo("[type] required property is missing"));
        }
    }

    public void testCreateWithExplicitTargetField() throws Exception {
        ConvertProcessor.Factory factory = new ConvertProcessor.Factory();
        Map<String, Object> config = new HashMap<>();
        ConvertProcessor.Type type = randomFrom(ConvertProcessor.Type.values());
        config.put("field", "field1");
        config.put("target_field", "field2");
        config.put("type", type.toString());
        String processorTag = randomAlphaOfLength(10);
        ConvertProcessor convertProcessor = factory.create(null, processorTag, null, config);
        assertThat(convertProcessor.getTag(), equalTo(processorTag));
        assertThat(convertProcessor.getField(), equalTo("field1"));
        assertThat(convertProcessor.getTargetField(), equalTo("field2"));
        assertThat(convertProcessor.getConvertType(), equalTo(type));
        assertThat(convertProcessor.isIgnoreMissing(), is(false));
    }

    public void testCreateWithIgnoreMissing() throws Exception {
        ConvertProcessor.Factory factory = new ConvertProcessor.Factory();
        Map<String, Object> config = new HashMap<>();
        ConvertProcessor.Type type = randomFrom(ConvertProcessor.Type.values());
        config.put("field", "field1");
        config.put("type", type.toString());
        config.put("ignore_missing", true);
        String processorTag = randomAlphaOfLength(10);
        ConvertProcessor convertProcessor = factory.create(null, processorTag, null, config);
        assertThat(convertProcessor.getTag(), equalTo(processorTag));
        assertThat(convertProcessor.getField(), equalTo("field1"));
        assertThat(convertProcessor.getTargetField(), equalTo("field1"));
        assertThat(convertProcessor.getConvertType(), equalTo(type));
        assertThat(convertProcessor.isIgnoreMissing(), is(true));
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="description" content="Networking 3x jinak - jedna ze série neotřelých přednášek, které se možná objeví na Plzeňském Barcampu. Přijď a poslechni si čerstvé pohledy na témata bez
hranic">
        <meta name="keywords" content="přednáška, řečník, záznam, Plzeň, Barcamp, konference, téma, networking, workshop, prezentace, projev">

        <title>Networking 3x jinak - Plzeňský Barcamp 2017</title>

        <meta property="og:title" content="Networking 3x jinak - Plzeňský Barcamp">
        <meta property="og:site_name" content="Plzeňský Barcamp">
        <meta property="og:url" content="https://plzenskybarcamp.cz/2017/prednasky/20d311c7">
        <meta property="og:description" content="Networking 3x jinak - jedna ze série neotřelých přednášek, které se možná objeví na Plzeňském Barcampu. Přijď a poslechni si čerstvé pohledy na témata bez
hranic">
        <meta property="og:locale" content="cs_CZ">
        <meta property="og:image" content="https://cdn.plzenskybarcamp.cz/public/2016/images/barcamp-og.png">
        <meta property="og:image:type" content="image/png">
        <meta property="og:image:width" content="300">
        <meta property="og:image:height" content="300">
        <meta name="google-site-verification" content="X6TDzyeXmaAgvKo48Ce7DVYd3zyyPBrmE-p2wqX-m1Y">

        <link rel="stylesheet" media="screen,projection,tv" href="https://cdn.plzenskybarcamp.cz/public/2017/css/style.css?v1426447760">
        <link rel="stylesheet" media="print" href="https://cdn.plzenskybarcamp.cz/public/2017/css/print.css?v1426447760">
        <link rel="shortcut icon" href="https://cdn.plzenskybarcamp.cz/public/2017/images/favicon.ico">

Úvod

Program

Přednášky

Účastnící

Partneří

Kontakt

Plzeňština ?

Networking 3x jinak

                <time datetime="2017-04-08">8. dubna 2017</time>

Networking 3x jinak

Networking je dnes už skoro takové klišé. Každý ho dělá, každý o něm mluví a každý mu rozumí. Každý si pod tímto slovem také představí něco jiného: MLM, přímý prodej, síťování, provize a meziprovize, marketingový nástroj a jiné zajímavé věci. Ráda se s vámi pobavím o Networkingu 3x jinak:

1. Networking jako osobní růst

2. Networking jako zábava

3. Networking jako zdroj informací

Zjistíte, co je networking, poznáte účastníky přednášky, naučíte se něco nového a rozhodně se zasmějete a pohnete tělem.

Komu je přednáška určena?

Přednáška je určená lidem a zvířátkům (ty jsou pro networking skvělá), kteří se chtějí něco dozvědět o networkingu, chtějí se také podělit o to, co už ví, chtějí poznat nové lidi a rozšířit si obzory.

Jo a taky je to pro ty, co nebudou chtít jen sedět a pasivně něco přijímat, ale budou ochotni vstát a pro nové informace si dojít :-)

Kdy přednáška proběhla?

                    Přednáška byla v místnosti Pivovar od 17:00 do 17:40.

                    Podívej se na kompletní program.

Záznam přednášky

Jana Havlíčková: Networking 3x jinak

                            Zobrazit na YouTube

Jana Havlíčková

                        Facebook

                        Twitter

Bio: Jsem nadšený fanoušek plzeňského Barcampu, obecně potkávání lidí a networkingu.

Stav hlasování: 28 hlasů

                Dal jsi svůj hlas

Twitter

Facebook

Google+

Instagram

Youtube

Plzeňský Barcamp organizují KWLB

2014

2015

2016

2017

                        Předchozí ročníky:

redpajama_set_name: RedPajamaGithub


text:
/******************************************************
	Selector.h

	This is the header file for the Selector class.
******************************************************/
#ifndef SELECTOR_H
#define SELECTOR_H

#include "SDL/SDL.h"
#include <string>
#include "Sprite.h"

class Selector
{
public:
	//constructor and destructor
	Selector();
	~Selector();

	//getters and setters
	inline int getChoice() const;
	void setChoice(const int choice);
	inline void setMoved(const bool moved);

	//reset
	void reset();

	//input, logic, and rendering
	void handleInput(SDL_Event& gEvent);
	bool move();
	void show(SDL_Surface* const destination) const;

private:
	//image surface
	Sprite* selectorImage;

	//choice
	int choice_; //0 is top option, 1 is bottom option

	//isMoved boolean
	bool isMoved;
};

//*****************************************************
inline int Selector::getChoice() const
{
	return choice_;
}

//*****************************************************
inline void Selector::setMoved(const bool moved)
{
	isMoved = moved;
}

//*****************************************************
inline void Selector::show(SDL_Surface* const destination) const
{
	selectorImage->show(destination);
}

#endif


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

-->
<validation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Validator/etc/validation.xsd">
    <entity name="catalog_product">
        <rules>
            <rule name="name_sku_and_price">
                <property_constraints>
                    <property name="name">
                        <constraint alias="some_validator" class="Magento\Framework\Validator_StringLenght">
                            <argument>
                                <option name="min" >
                                    <!-- option can contain only text -->
                                    <option name="1">5</option>
                                </option>
                            </argument>
                        </constraint>
                    </property>
                </property_constraints>
            </rule>
        </rules>
        <groups>
            <group name="create">
                <uses>
                    <use rule="name_sku_and_price"/>
                </uses>
            </group>
        </groups>
    </entity>
</validation>


text:
const writeFile = require('./write-file');

module.exports = function (opts) {
    const file = {
        "presets": [
            ["es2015", { "modules": false }]
        ]
    };
    writeFile({
        directory: opts.directory,
        fileName: '.babelrc',
        data: JSON.stringify(file),
        codeFormat: {
            indent_size: 2
        },
        success () {
            opts.success();
        },
        error () {
            opts.error();
        }
    });
};


text:
package org.apache.kafka.clients.admin;

import org.apache.kafka.common.annotation.InterfaceStability;

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

/**
 * A class representing a configuration entry containing name, value and additional metadata.
 *
 * The API of this class is evolving, see {@link AdminClient} for details.
 */
@InterfaceStability.Evolving
public class ConfigEntry {

    private final String name;
    private final String value;
    private final ConfigSource source;
    private final boolean isSensitive;
    private final boolean isReadOnly;
    private final List<ConfigSynonym> synonyms;

    /**
     * Create a configuration entry with the provided values.
     *
     * @param name the non-null config name
     * @param value the config value or null
     */
    public ConfigEntry(String name, String value) {
        this(name, value, false, false, false);
    }

    /**
     * Create a configuration with the provided values.
     *
     * @param name the non-null config name
     * @param value the config value or null
     * @param isDefault whether the config value is the default or if it's been explicitly set
     * @param isSensitive whether the config value is sensitive, the broker never returns the value if it is sensitive
     * @param isReadOnly whether the config is read-only and cannot be updated
     * @deprecated since 1.1.0. This constructor will be removed in a future release.
     */
    @Deprecated
    public ConfigEntry(String name, String value, boolean isDefault, boolean isSensitive, boolean isReadOnly) {
        this(name,
             value,
             isDefault ? ConfigSource.DEFAULT_CONFIG : ConfigSource.UNKNOWN,
             isSensitive,
             isReadOnly,
             Collections.<ConfigSynonym>emptyList());
    }

    /**
     * Create a configuration with the provided values.
     *
     * @param name the non-null config name
     * @param value the config value or null
     * @param source the source of this config entry
     * @param isSensitive whether the config value is sensitive, the broker never returns the value if it is sensitive
     * @param isReadOnly whether the config is read-only and cannot be updated
     * @param synonyms Synonym configs in order of precedence
     */
    ConfigEntry(String name, String value, ConfigSource source, boolean isSensitive, boolean isReadOnly,
                List<ConfigSynonym> synonyms) {
        Objects.requireNonNull(name, "name should not be null");
        this.name = name;
        this.value = value;
        this.source = source;
        this.isSensitive = isSensitive;
        this.isReadOnly = isReadOnly;
        this.synonyms = synonyms;
    }

    /**
     * Return the config name.
     */
    public String name() {
        return name;
    }

    /**
     * Return the value or null. Null is returned if the config is unset or if isSensitive is true.
     */
    public String value() {
        return value;
    }

    /**
     * Return the source of this configuration entry.
     */
    public ConfigSource source() {
        return source;
    }

    /**
     * Return whether the config value is the default or if it's been explicitly set.
     */
    public boolean isDefault() {
        return source == ConfigSource.DEFAULT_CONFIG;
    }

    /**
     * Return whether the config value is sensitive. The value is always set to null by the broker if the config value
     * is sensitive.
     */
    public boolean isSensitive() {
        return isSensitive;
    }

    /**
     * Return whether the config is read-only and cannot be updated.
     */
    public boolean isReadOnly() {
        return isReadOnly;
    }

    /**
     * Returns all config values that may be used as the value of this config along with their source,
     * in the order of precedence. The list starts with the value returned in this ConfigEntry.
     * The list is empty if synonyms were not requested using {@link DescribeConfigsOptions#includeSynonyms(boolean)}
     */
    public List<ConfigSynonym> synonyms() {
        return  synonyms;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        ConfigEntry that = (ConfigEntry) o;

        return this.name.equals(that.name) &&
                this.value != null ? this.value.equals(that.value) : that.value == null &&
                this.isSensitive == that.isSensitive &&
                this.isReadOnly == that.isReadOnly &&
                this.source == that.source &&
                Objects.equals(this.synonyms, that.synonyms);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + name.hashCode();
        result = prime * result + ((value == null) ? 0 : value.hashCode());
        result = prime * result + (isSensitive ? 1 : 0);
        result = prime * result + (isReadOnly ? 1 : 0);
        result = prime * result + source.hashCode();
        result = prime * result + synonyms.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "ConfigEntry(" +
                "name=" + name +
                ", value=" + value +
                ", source=" + source +
                ", isSensitive=" + isSensitive +
                ", isReadOnly=" + isReadOnly +
                ", synonyms=" + synonyms +
                ")";
    }

    /**
     * Source of configuration entries.
     */
    public enum ConfigSource {
        DYNAMIC_TOPIC_CONFIG,           // dynamic topic config that is configured for a specific topic
        DYNAMIC_BROKER_CONFIG,          // dynamic broker config that is configured for a specific broker
        DYNAMIC_DEFAULT_BROKER_CONFIG,  // dynamic broker config that is configured as default for all brokers in the cluster
        STATIC_BROKER_CONFIG,           // static broker config provided as broker properties at start up (e.g. server.properties file)
        DEFAULT_CONFIG,                 // built-in default configuration for configs that have a default value
        UNKNOWN                         // source unknown e.g. in the ConfigEntry used for alter requests where source is not set
    }

    /**
     * Class representing a configuration synonym of a {@link ConfigEntry}.
     */
    public static class ConfigSynonym {

        private final String name;
        private final String value;
        private final ConfigSource source;

        /**
         * Create a configuration synonym with the provided values.
         *
         * @param name Configuration name (this may be different from the name of the associated {@link ConfigEntry}
         * @param value Configuration value
         * @param source {@link ConfigSource} of this configuraton
         */
        ConfigSynonym(String name, String value, ConfigSource source) {
            this.name = name;
            this.value = value;
            this.source = source;
        }

        /**
         * Returns the name of this configuration.
         */
        public String name() {
            return name;
        }

        /**
         * Returns the value of this configuration, which may be null if the configuration is sensitive.
         */
        public String value() {
            return value;
        }

        /**
         * Returns the source of this configuration.
         */
        public ConfigSource source() {
            return source;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            ConfigSynonym that = (ConfigSynonym) o;
            return Objects.equals(name, that.name) && Objects.equals(value, that.value) && source == that.source;
        }

        @Override
        public int hashCode() {
            return Objects.hash(name, value, source);
        }

        @Override
        public String toString() {
            return "ConfigSynonym(" +
                    "name=" + name +
                    ", value=" + value +
                    ", source=" + source +
                    ")";
        }
    }
}


text:
package vim25

import (
	"encoding/json"
	"net/url"
	"os"
	"testing"

	"github.com/juju/govmomi/vim25/methods"
	"github.com/juju/govmomi/vim25/mo"
	"github.com/juju/govmomi/vim25/soap"
	"github.com/juju/govmomi/vim25/types"
	"golang.org/x/net/context"
)

// Duplicated to prevent cyclic dependency...
func testURL(t *testing.T) *url.URL {
	s := os.Getenv("GOVMOMI_TEST_URL")
	if s == "" {
		t.SkipNow()
	}
	u, err := url.Parse(s)
	if err != nil {
		panic(err)
	}
	return u
}

func sessionLogin(t *testing.T, c *Client) {
	req := types.Login{
		This: *c.ServiceContent.SessionManager,
	}

	u := testURL(t).User
	req.UserName = u.Username()
	if pw, ok := u.Password(); ok {
		req.Password = pw
	}

	_, err := methods.Login(context.Background(), c, &req)
	if err != nil {
		t.Fatal(err)
	}
}

func sessionCheck(t *testing.T, c *Client) {
	var mgr mo.SessionManager

	err := mo.RetrieveProperties(context.Background(), c, c.ServiceContent.PropertyCollector, *c.ServiceContent.SessionManager, &mgr)
	if err != nil {
		t.Fatal(err)
	}
}

func TestClientSerialization(t *testing.T) {
	var c1, c2 *Client

	soapClient := soap.NewClient(testURL(t), true)
	c1, err := NewClient(context.Background(), soapClient)
	if err != nil {
		t.Fatal(err)
	}

	// Login
	sessionLogin(t, c1)
	sessionCheck(t, c1)

	// Serialize/deserialize
	b, err := json.Marshal(c1)
	if err != nil {
		t.Fatal(err)
	}
	c2 = &Client{}
	err = json.Unmarshal(b, c2)
	if err != nil {
		t.Fatal(err)
	}

	// Check the session is still valid
	sessionCheck(t, c2)
}


text:
module Pain
  class Model
    MAX = {
      bug_type: 7,
      likelihood: 5,
      impact: 5
    }.freeze

    INPUT_MESSAGE = {
      bug_type: 'What kind of bug is this?',
      likelihood: 'How likely is this bug to occur?',
      impact: 'How much impact will this bug have?'
    }.freeze

    OPTIONS = {
      bug_type: {
        1 => 'Documentation: a documentation issue',
        2 => 'Localization: missing translations',
        3 => 'Visual Polish: Aesthetic issues',
        4 => 'Balancing: allows poor usage strategy',
        5 => 'Minor UX: Impairs UX in secondary scenarios',
        6 => 'Major UX: Impairs UX in key scenarios',
        7 => 'Crash: Causes crash or data loss'
      },
      likelihood: {
        1 => 'Will affect almost no one',
        2 => 'Will only affect a few users',
        3 => 'Will affect average number of users',
        4 => 'Will affect most users',
        5 => 'Will affect all users'
      },

      impact: {
        1 => 'Nuisance: not a big deal but noticeable.',
        2 => 'A Pain: Users won\'t like this once they notice it.',
        3 => 'Affects Buy-in. Will show up in review. Clearly noticeable.',
        4 => 'A user would return the product. Should not deploy until fixed',
        5 => 'Affects system build'
      }
    }.freeze

    def choices_for(category)
      OPTIONS[category]
    end

    def level_string(category, score)
      OPTIONS.dig(category, score)
    end

    def max_for(category)
      MAX[category]
    end

    def input_message(category)
      INPUT_MESSAGE[category]
    end

    def max_pain
      MAX.values.reduce(&:*)
    end

    def user_pain(type, likelihood, impact)
      100 * (type * likelihood * impact) / max_pain
    end

    def normalize(value, variable)
      value = value.to_i
      max   = MAX[variable]

      return nil if max.nil? || value.nil?
      return nil if value < 1
      return max if value > max

      value
    end
  end
end


text:
// Type definitions for json-schema-traverse 0.4
// Project: https://github.com/epoberezkin/json-schema-traverse#readme
// Definitions by: Piotr Błażejewicz (Peter Blazejewicz) <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/**
 * Traverse JSON Schema passing each schema object to callback
 */
declare function traverse(schema: object, cb: TraverseCallback): void;
declare function traverse(schema: object, opts: TraverseOptions, cb?: TraverseCallback): void;

// aliases
type TraverseCallback = traverse.TraverseCallback;
type TraverseOptions = traverse.TraverseOptions;
type TraverseCallbackDef = traverse.TraverseCallbackDef;

declare namespace traverse {
    const keywords: {
        additionalItems: true;
        items: true;
        contains: true;
        additionalProperties: true;
        propertyNames: true;
        not: true;
        if: true;
        then: true;
        else: true;
    };

    const arrayKeywords: {
        items: true;
        allOf: true;
        anyOf: true;
        oneOf: true;
    };

    const propsKeywords: {
        definitions: true;
        properties: true;
        patternProperties: true;
        dependencies: true;
    };

    const skipKeywords: {
        default: true;
        enum: true;
        const: true;
        required: true;
        maximum: true;
        minimum: true;
        exclusiveMaximum: true;
        exclusiveMinimum: true;
        multipleOf: true;
        maxLength: true;
        minLength: true;
        pattern: true;
        format: true;
        maxItems: true;
        minItems: true;
        uniqueItems: true;
        maxProperties: true;
        minProperties: true;
    };

    interface TraverseOptions {
        /**
         * Callback function `cb` is called for each schema object (not including draft-06 boolean schemas),
         * including the root schema, in pre-order traversal. Schema references (`$ref`) are not resolved,
         * they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre`
         * will be called before traversing child elements, and `post` will be called
         * after all child elementshave been traversed.
         */
        cb?: TraverseCallback;
        /** Without option allKeys: true callback will be called only with root schema. */
        allKeys?: boolean;
    }

    type TraverseCallback =
        | TraverseCallbackDef
        | {
              pre?: TraverseCallbackDef;
              post?: TraverseCallbackDef;
          };

    interface TraverseCallbackDef {
        (
            /** the current schema object */
            schema: object,
            /** from the root schema to the current schema object */
            jsonPtr: string,
            /** the schema passed to traverse object */
            rootSchema: object,
            /** from the root schema to the parent schema object */
            parentJsonPtr: string,
            /** the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) */
            parentKeyword: string,
            /**
             * not necessarily parent `object`/`array`;
             * in the example above the parent schema for `{type: 'string'}` is the root schema
             */
            parentSchema: object,
            /**
             * index or property name in the `array`/`object` containing multiple schemas;
             * in the example above for `{type: 'string'}` the property name is `foo`
             */
            keyIndex: string | number,
        ): void;
    }
}

export = traverse;


text:
import { DateTime, DurationUnit } from "luxon"
import * as d3 from "d3"
import * as d3sc from "d3-scale-chromatic";
import { ChartTable, ChartColumn, ChartRow } from "../../ChartClient"
import { parseLite } from "@framework/Signum.Entities"
import * as Navigator from '@framework/Navigator'
import { coalesce, Dic } from "@framework/Globals";
import { getTypeInfo, tryGetTypeInfo } from "@framework/Reflection";
import { ChartRequestModel } from "../../Signum.Entities.Chart";
import { isFilterGroupOption, isFilterGroupOptionParsed, FilterConditionOptionParsed, FilterOptionParsed, QueryToken, FilterConditionOption } from "@framework/FindOptions";

export function translate(x: number, y: number) {
  if (y == undefined)
    return 'translate(' + x + ')';

  return 'translate(' + x + ',' + y + ')';
}

export function scale(x: number, y: number) {
  if (y == undefined)
    return 'scale(' + x + ')';

  return 'scale(' + x + ',' + y + ')';
}

export function rotate(angle: number, x?: number, y?: number): string {
  if (x == undefined || y == undefined)
    return 'rotate(' + angle + ')';

  return 'rotate(' + angle + ',' + y + ',' + y + ')';
}

export function skewX(angle: number): string {
  return 'skewX(' + angle + ')';
}

export function skewY(angle: number): string {
  return 'skewY(' + angle + ')';
}

export function matrix(a: number, b: number, c: number, d: number, e: number, f: number): string {
  return 'matrix(' + a + ',' + b + ',' + c + ',' + d + ',' + e + ',' + f + ')';
}

export function scaleFor(column: ChartColumn<any>, values: number[], minRange: number, maxRange: number, scaleName: string | null | undefined): d3.ScaleContinuousNumeric<number, number> {

  if (scaleName == "ZeroMax")
    return d3.scaleLinear()
      .domain([0, d3.max(values)!])
      .range([minRange, maxRange])
      .nice();

  if (scaleName == "MinMax") {
    if (column.type == "Date" || column.type == "DateTime") {
      var dates = values.map(d => new Date(d));

      const scale = d3.scaleTime()
        .domain([d3.min(dates)!, d3.max(dates)!])
        .range([minRange, maxRange]);

      const f = function (d: string) { return scale(new Date(d)); } as any as d3.ScaleContinuousNumeric<number, number>;
      f.ticks = scale.ticks as any;
      f.tickFormat = scale.tickFormat as any;
      return f;
    }
    else {
      return d3.scaleLinear()
        .domain([d3.min(values)!, d3.max(values)!])
        .range([minRange, maxRange])
        .nice();
    }
  }

  if (scaleName == "Log")
    return d3.scaleLog()
      .domain([d3.min(values)!, d3.max(values)!])
      .range([minRange, maxRange])
      .nice();

  if (scaleName == "Sqrt")
    return d3.scalePow().exponent(.5)
      .domain([d3.min(values)!, d3.max(values)!])
      .range([minRange, maxRange]);

  throw Error("Unexpected scale: " + scaleName);
}

export function insertPoint(keyColumn: ChartColumn<any>, valueColumn: ChartColumn<any>) : "Middle" | "Before" | "After" {

  if (valueColumn.orderByIndex != null && (keyColumn.orderByIndex == null || valueColumn.orderByIndex < keyColumn.orderByIndex)) {
    if (valueColumn.orderByType == "Ascending")
      return "Before";
    else
      return "After";
  } else {
    return "Middle";
  }
}

export function completeValues(column: ChartColumn<unknown>, values: unknown[], completeValues: string | null | undefined, filterOptions: FilterOptionParsed[], insertPoint: "Middle" | "Before" | "After"): unknown[] {

  if (completeValues == null || completeValues == "No")
    return values;

  function normalizeToken(qt: QueryToken): { normalized: QueryToken, lastPart?: QueryToken } {
    if ((qt.type.name == "Date" || qt.type.name == "DateTime") &&
      qt.parent && (qt.parent.type.name == "Date" || qt.parent.type.name == "DateTime"))
      switch (qt.key) {
        case "SecondStart":
        case "MinuteStart":
        case "HourStart":
        case "Date":
        case "WeekStart":
        case "MonthStart":
        case "MonthStart":
          return {
            normalized: qt.parent,
            lastPart : qt,
          };
      }

    return {
      normalized: qt,
      lastPart: undefined
    };
  }

  function durationUnit(lastPart: string): DurationUnit {
    switch (lastPart) {
      case "SecondStart": return "second";
      case "MinuteStart": return "minute";
      case "HourStart": return "hour";
      case "Date": return "day";
      case "WeekStart": return "week";
      case "MonthStart": return "month";
      default: throw new Error("Unexpected " + lastPart);
    }
  }

  function tryCeil(date: string | null | undefined, unit: DurationUnit) {
    if (date == null)
      return undefined;

    return ceil(DateTime.fromISO(date), unit).toISO();
  }

  function ceil(date: DateTime, unit: DurationUnit) {

    if (date.toMillis() == date.startOf(unit).toMillis())
      return date;

    return date.startOf(unit).plus({ [unit]: 1 });
  }

  function tryFloor(date: string | null | undefined, unit: DurationUnit) {
    if (date == null)
      return undefined;

    return floor(DateTime.fromISO(date), unit).toISO();
  }

  function floor(date: DateTime, unit: DurationUnit) {

    return date.startOf(unit);
  }

  const columnNomalized = normalizeToken(column.token!);

  const machingFilters = column.token && (completeValues == "FromFilters" || completeValues == "Auto") ?
    (filterOptions.filter(f => !isFilterGroupOptionParsed(f)) as FilterConditionOptionParsed[])
      .filter(f => f.token && normalizeToken(f.token).normalized.fullKey == columnNomalized.normalized.fullKey) :
    [];

  if (completeValues == "FromFilters" && machingFilters.length == 0)
    return values;

  const isAuto = completeValues == "Auto";

  const isInFilter = machingFilters.firstOrNull(a => a.operation == "IsIn");

  if (isInFilter)
    return complete(values, isInFilter.value as unknown[], column, insertPoint);

  if (column.type == "Lite" || column.type == "String")
    return values;

  if (column.type == "Date" || column.type == "DateTime") {

    const unit: DurationUnit | null = columnNomalized.lastPart != null ? durationUnit(columnNomalized.lastPart.key) :
      columnNomalized.normalized.type.name == "Date" ? "day" : null;

    if (unit == null)
      return values;

    const min = d3.max(machingFilters.filter(a => a.operation == "GreaterThan" || a.operation == "GreaterThanOrEqual" || a.operation == "EqualTo")
      .map(f => {
        const pair = normalizeToken(f.token!);

        const value = DateTime.fromISO(f.value);

        //Date.MonthStart >  1.4.2000
        //             Min-> 1.5.2000
        //Date.MonthStart >= 1.4.2000
        //             Min-> 1.4.2000
        //Date.MonthStart == 1.4.2000
        //             Min-> 1.4.2000

        var filterUnit = pair.lastPart != null ? durationUnit(pair.lastPart.key) :
          f.token?.type.name == "Date" ? "day" : null;

        if (filterUnit != unit)
          return null;

        const newValue = f.operation == "GreaterThan" ? floor(value, unit).plus({ [unit]: 1 }) : floor(value, unit);

        return newValue.toISO();
      }).notNull()) ?? tryFloor(d3.min(values as string[]), unit);

    const max = d3.min(machingFilters.filter(a => a.operation == "LessThan" || a.operation == "LessThanOrEqual" || a.operation == "EqualTo")
      .map(f => {
        const pair = normalizeToken(f.token!);
        let value = DateTime.fromISO(f.value);

        //Date.MonthStart <  1.4.2000
        //             Max   1.4.2000
        //Date.MonthStart <= 1.4.2000
        //                   1.5.2000
        //Date.MonthStart == 1.4.2000
        //             Max   1.5.2000

        var filterUnit = pair.lastPart != null ? durationUnit(pair.lastPart.key) :
          f.token?.type.name == "Date" ? "day" : null;

        if (filterUnit != unit)
          return null;

        const newValue = f.operation == "LessThan" ? ceil(value, unit) : floor(value, unit).plus({ [unit]: 1 });

        return newValue.toISO();
      }).notNull()) ?? tryCeil(d3.max(values as string[]), unit);

    if (min == undefined  || max == undefined)
      return values;

    const minDate = DateTime.fromISO(min);
    const maxDate = DateTime.fromISO(max);
    let date = minDate;

    const allValues: string[] = [];
    const limit = isAuto ? values.length * 2 : null;
    while (date < maxDate) {

      if (limit != null && allValues.length > limit)
        return values;

      allValues.push(column.token!.type.name == "Date" ? date.toISODate() : date.toISO());
      date = date.plus({ [unit]: 1 });
    }

    return complete(values, allValues, column, insertPoint);
  }

  if (column.type == "Enum") {

    const typeName = column.token!.type.name;

    if (typeName == "boolean") {
      return complete(values, [false, true], column, insertPoint);
    }

    const typeInfo = tryGetTypeInfo(column.token!.type.name);
    if (typeInfo == null)
      throw new Error("No Metadata found for " + typeName);

    const allValues = Dic.getValues(typeInfo.members).filter(a => !a.isIgnoredEnum).map(a => a.name);

    return complete(values, allValues, column, insertPoint);
  }

  if (column.type == "Integer" || column.type == "Real" || column.type == "RealGroupable") {

    const lastPart = column.token!.fullKey.tryAfterLast('.');

    const step: number | null = lastPart != null && lastPart.startsWith("Step") ? parseFloat(lastPart.after("Step").replace("_", ".")) :
      (column.type == "Integer" ? 1 : null);

    if (step == null)
      return values;

    const minFilter = machingFilters.firstOrNull(a => a.operation == "GreaterThan" || a.operation == "GreaterThanOrEqual");
    const min = minFilter == null ? d3.min(values as number[]) :
      minFilter.operation == "GreaterThan" ? minFilter.value as number + step :
        minFilter.operation == "GreaterThanOrEqual" ? minFilter.value : undefined;

    const maxFilter = machingFilters.firstOrNull(a => a.operation == "LessThan" || a.operation == "LessThanOrEqual");
    const max = maxFilter == null ? d3.max(values as number[]) :
      maxFilter.operation == "LessThan" ? maxFilter.value as number - step :
        maxFilter.operation == "LessThanOrEqual" ? maxFilter.value : undefined;

    if (min == undefined || max == undefined)
      return values;

    const allValues: number[] = [];
    const limit = isAuto ? values.length * 2 : null;
    if (step < 1) {
      const inv = 1 / step;
      let v = min;
      while (v <= max) {

        if (limit != null && allValues.length > limit)
          return values;

        allValues.push(v);
        v = Math.round((v + step) * inv) / inv;
      }
    } else {
      let v = min;
      while (v <= max) {
        if (limit != null && allValues.length > limit)
          return values;

        allValues.push(v);
        v += step;
      }
    }
    return complete(values, allValues, column, insertPoint);
  }

  return values;
}

function complete(values: unknown[], allValues: unknown[], column: ChartColumn<unknown>, insertPoint: "Middle" | "Before" | "After"): any[] {

  if (insertPoint == "Middle") {

    const allValuesDic = allValues.toObject(column.getKey);

    const oldValues = values.filter(a => !allValuesDic.hasOwnProperty(column.getKey(a)));

    return [...column.orderByType == "Descending" ? allValues.reverse() : allValues, ...oldValues];
  }
  else {
    const valuesDic = values.toObject(column.getKey);

    const newValues = allValues.filter(a => !valuesDic.hasOwnProperty(column.getKey(a)));

    if (insertPoint == "Before")
      return [...newValues, ...values];
    else if (insertPoint == "After") //Descending
      return [...values, ...newValues];
  }

  throw new Error();
}

export function getStackOffset(curveName: string): ((series: d3.Series<any, any>, order: number[]) => void) | undefined {
  switch (curveName) {
    case "zero": return d3.stackOffsetNone;
    case "expand": return d3.stackOffsetExpand;
    case "silhouette": return d3.stackOffsetSilhouette;
    case "wiggle": return d3.stackOffsetWiggle;
  }

  return undefined;
}

export function getStackOrder(schemeName: string): ((series: d3.Series<any, any>) => number[]) | undefined {
  switch (schemeName) {
    case "none": return d3.stackOrderNone;
    case "ascending": return d3.stackOrderAscending;
    case "descending": return d3.stackOrderDescending;
    case "insideOut": return d3.stackOrderInsideOut;
    case "reverse": return d3.stackOrderReverse;
  }

  return undefined;
}

export function getCurveByName(curveName: string): d3.CurveFactoryLineOnly | undefined {
  switch (curveName) {
    case "basis": return d3.curveBasis;
    case "bundle": return d3.curveBundle.beta(0.5);
    case "cardinal": return d3.curveCardinal;
    case "catmull-rom": return d3.curveCatmullRom;
    case "linear": return d3.curveLinear;
    case "monotone": return d3.curveMonotoneX;
    case "natural": return d3.curveNatural;
    case "step": return d3.curveStep;
    case "step-after": return d3.curveStepAfter;
    case "step-before": return d3.curveStepBefore;
  }

  return undefined;
}

export function getColorInterpolation(interpolationName: string | undefined | null): ((value: number) => string) | undefined {
  switch (interpolationName) {
    case "YlGn": return d3sc.interpolateYlGn;
    case "YlGnBu": return d3sc.interpolateYlGnBu;
    case "GnBu": return d3sc.interpolateGnBu;
    case "BuGn": return d3sc.interpolateBuGn;
    case "PuBuGn": return d3sc.interpolatePuBuGn;
    case "PuBu": return d3sc.interpolatePuBu;
    case "BuPu": return d3sc.interpolateBuPu;
    case "RdPu": return d3sc.interpolateRdPu;
    case "PuRd": return d3sc.interpolatePuRd;
    case "OrRd": return d3sc.interpolateOrRd;
    case "YlOrRd": return d3sc.interpolateYlOrRd;
    case "YlOrBr": return d3sc.interpolateYlOrBr;
    case "Purples": return d3sc.interpolatePurples;
    case "Blues": return d3sc.interpolateBlues;
    case "Greens": return d3sc.interpolateGreens;
    case "Oranges": return d3sc.interpolateOranges;
    case "Reds": return d3sc.interpolateReds;
    case "Greys": return d3sc.interpolateGreys;
    case "PuOr": return d3sc.interpolatePuOr;
    case "BrBG": return d3sc.interpolateBrBG;
    case "PRGn": return d3sc.interpolatePRGn;
    case "PiYG": return d3sc.interpolatePiYG;
    case "RdBu": return d3sc.interpolateRdBu;
    case "RdGy": return d3sc.interpolateRdGy;
    case "RdYlBu": return d3sc.interpolateRdYlBu;
    case "Spectral": return d3sc.interpolateSpectral;
    case "RdYlGn": return d3sc.interpolateRdYlGn;
  }

  return undefined;
}

export function getColorScheme(schemeName: string | null | undefined, k: number | undefined = 11): ReadonlyArray<string> | undefined {
  switch (schemeName) {
    case "category10": return d3.schemeCategory10;
    case "accent": return d3sc.schemeAccent;
    case "dark2": return d3sc.schemeDark2;
    case "paired": return d3sc.schemePaired;
    case "pastel1": return d3sc.schemePastel1;
    case "pastel2": return d3sc.schemePastel2;
    case "set1": return d3sc.schemeSet1;
    case "set2": return d3sc.schemeSet2;
    case "set3": return d3sc.schemeSet3;
    case "BrBG[K]": return d3sc.schemeBrBG[k];
    case "PRGn[K]": return d3sc.schemePRGn[k];
    case "PiYG[K]": return d3sc.schemePiYG[k];
    case "PuOr[K]": return d3sc.schemePuOr[k];
    case "RdBu[K]": return d3sc.schemeRdBu[k];
    case "RdGy[K]": return d3sc.schemeRdGy[k];
    case "RdYlBu[K]": return d3sc.schemeRdYlBu[k];
    case "RdYlGn[K]": return d3sc.schemeRdYlGn[k];
    case "Spectral[K]": return d3sc.schemeSpectral[k];
    case "Blues[K]": return d3sc.schemeBlues[k];
    case "Greys[K]": return d3sc.schemeGreys[k];
    case "Oranges[K]": return d3sc.schemeOranges[k];
    case "Purples[K]": return d3sc.schemePurples[k];
    case "Reds[K]": return d3sc.schemeReds[k];
    case "BuGn[K]": return d3sc.schemeBuGn[k];
    case "BuPu[K]": return d3sc.schemeBuPu[k];
    case "OrRd[K]": return d3sc.schemeOrRd[k];
    case "PuBuGn[K]": return d3sc.schemePuBuGn[k];
    case "PuBu[K]": return d3sc.schemePuBu[k];
    case "PuRd[K]": return d3sc.schemePuRd[k];
    case "RdPu[K]": return d3sc.schemeRdPu[k];
    case "YlGnBu[K]": return d3sc.schemeYlGnBu[k];
    case "YlGn[K]": return d3sc.schemeYlGn[k];
    case "YlOrBr[K]": return d3sc.schemeYlOrBr[k];
    case "YlOrRd[K]": return d3sc.schemeYlOrRd[k];
  }

  return undefined;
}

interface CachedColorOrdinal {
  category: string;
  categorySteps: number;
  scale: d3.ScaleOrdinal<string, string>;
}

export function colorCategory(parameters: { [name: string]: string }, domain: string[]): d3.ScaleOrdinal<string, string> {

  const cacheKey = "_cachedColorOrdinal_";

  var category = parameters["ColorCategory"];
  var categorySteps = parseInt(parameters["ColorCategorySteps"]);
  if (parameters[cacheKey]) {
    const cached = parameters[cacheKey] as any as CachedColorOrdinal;

    if (cached.category == category && cached.categorySteps == categorySteps) {
      domain.forEach(a => cached.scale(a));
      return cached.scale;
    }
  }

  var scheme = getColorScheme(category, categorySteps);

  const newCached: CachedColorOrdinal = {
    category: category,
    categorySteps: categorySteps,
    scale: d3.scaleOrdinal(scheme).domain(domain),
  };

  parameters[cacheKey] = newCached as any;

  return newCached.scale;
}


text:
export const AUTH_USER = 'AUTH_USER';
export const UNAUTH_USER = 'UNAUTH_USER';
export const AUTH_ERROR = 'AUTH_ERROR';
export const FETCH_MESAGE = 'FETCH_MESAGE';


text:
//
// Revit IFC Import library: this library works with Autodesk(R) Revit(R) to import IFC files.
// Copyright (C) 2013  Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.IFC;
using Revit.IFC.Common.Enums;
using Revit.IFC.Common.Utility;
using Revit.IFC.Import.Data;
using Revit.IFC.Import.Enums;

namespace Revit.IFC.Import.Utility
{
    /// <summary>
    /// Provides methods to convert IfcObjectReferenceSelect values to parameter values.
    /// </summary>
    public class IFCObjectReferenceSelect
    {
        private static IList<string> m_TelecomPrefixes = null;

        /// <summary>
        /// Returns an ElementId value corresponding to an handle based on its entity type.
        /// </summary>
        /// <param name="handle">The entity handle that contains information to relate to the user in string format.</param>
        /// <returns>The representation of the data as an ElementId, if valid.</returns>
        static public ElementId ToElementId(IFCAnyHandle handle)
        {
            ElementId valueAsElementId = ElementId.InvalidElementId;

            if (IFCAnyHandleUtil.IsNullOrHasNoValue(handle))
                return valueAsElementId;

            IFCEntityType handleType = IFCAnyHandleUtil.GetEntityType(handle);
            switch (handleType)
            {
                case IFCEntityType.IfcMaterial:
                    IFCMaterial material = IFCMaterial.ProcessIFCMaterial(handle);
                    if (material != null)
                        valueAsElementId = material.GetMaterialElementId();
                    break;
            }

            return valueAsElementId;
        }

        /// <summary>
        /// Returns a string value corresponding to an handle based on its entity type.
        /// </summary>
        /// <param name="handle">The entity handle that contains information to relate to the user in string format.</param>
        /// <returns>The approximate representation of the data as a string.</returns>
        static public string ToString(IFCAnyHandle handle)
        {
            if (IFCAnyHandleUtil.IsNullOrHasNoValue(handle))
                return null;

            string valueAsString = null;

            IFCEntityType handleType = IFCAnyHandleUtil.GetEntityType(handle);
            switch (handleType)
            {
                case IFCEntityType.IfcMaterial:
                    valueAsString = MaterialToString(handle);
                    break;
                case IFCEntityType.IfcPerson:
                    valueAsString = PersonToString(handle);
                    break;
                case IFCEntityType.IfcDateAndTime:
                    valueAsString = DateAndTimeToString(handle);
                    break;
                case IFCEntityType.IfcMaterialList:
                    valueAsString = MaterialListToString(handle);
                    break;
                case IFCEntityType.IfcOrganization:
                    valueAsString = OrganizationToString(handle);
                    break;
                case IFCEntityType.IfcCalendarDate:
                    valueAsString = CalendarDateToString(handle);
                    break;
                case IFCEntityType.IfcLocalTime:
                    valueAsString = LocalTimeToString(handle);
                    break;
                case IFCEntityType.IfcPersonAndOrganization:
                    valueAsString = PersonAndOrganizationToString(handle);
                    break;
                case IFCEntityType.IfcLibraryReference:
                case IFCEntityType.IfcClassificationReference:
                case IFCEntityType.IfcDocumentReference:
                    valueAsString = ExternalReferenceToString(handle);
                    break;
                case IFCEntityType.IfcPostalAddress:
                    valueAsString = PostalAddressToString(handle);
                    break;
                case IFCEntityType.IfcTelecomAddress:
                    valueAsString = TelecomAddressToString(handle);
                    break;
                default:
                    // TODO: Support IfcMaterialLayer, IfcTimeSeries, IfcAppliedValue.
                    // IfcTimeSeries and IfcAppliedValue are abstract supertypes.
                    Importer.TheLog.LogWarning(handle.StepId, "Unhandled sub-type of IFCObjectReferenceSelect: " + handleType.ToString(), true);
                    break;
            }

            return valueAsString;
        }

        private static string ConcatenateString(string originalString, string delimiter, string appenedString)
        {
            if (string.IsNullOrWhiteSpace(appenedString))
                return originalString;
            if (string.IsNullOrWhiteSpace(originalString))
                return appenedString;
            return originalString + appenedString + delimiter;
        }

        /// <summary>
        /// Returns a list of strings as one string.
        /// </summary>
        /// <param name="handle">The handle.</param>
        /// <param name="propertyName">The property name.</param>
        /// <param name="delimiter">The delimiter for the list.</param>
        /// <returns></returns>
        private static string GetListAsString(IFCAnyHandle handle, string propertyName, string delimiter)
        {
            List<string> propertyList = IFCAnyHandleUtil.GetAggregateStringAttribute<List<string>>(handle, propertyName);
            if (propertyList.Count == 0)
                return null;

            string valueAsString = null;
            foreach (string propertyValue in propertyList)
            {
                if (string.IsNullOrWhiteSpace(propertyValue))
                    continue;
                ConcatenateString(valueAsString, delimiter, propertyValue);
            }

            return valueAsString;
        }

        private static string ActorRoleToString(IFCAnyHandle handle)
        {
            string valueAsString = IFCAnyHandleUtil.GetEnumerationAttribute(handle, "Role");
            if (string.Compare(valueAsString, "UserDefined", true) == 0)
            {
                string optionalRole = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "UserDefinedRole", null);
                if (!string.IsNullOrWhiteSpace(optionalRole))
                    valueAsString = optionalRole;
            }

            return valueAsString;
        }

        private static string CalendarDateToString(IFCAnyHandle handle)
        {
            bool found;
            int day = IFCImportHandleUtil.GetRequiredIntegerAttribute(handle, "DayComponent", out found);
            if (!found)
                return null;

            int month = IFCImportHandleUtil.GetRequiredIntegerAttribute(handle, "MonthComponent", out found);
            if (!found)
                return null;

            int year = IFCImportHandleUtil.GetRequiredIntegerAttribute(handle, "YearComponent", out found);
            if (!found)
                return null;

            return year.ToString("D4") + "-" + month.ToString("D2") + "-" + day.ToString("D2");
        }

        private static string CoordinatedUniversalTimeOffsetToString(IFCAnyHandle handle, int daylightSavingHour)
        {
            if (IFCAnyHandleUtil.IsNullOrHasNoValue(handle))
                return null;

            bool found;
            int hour = IFCImportHandleUtil.GetRequiredIntegerAttribute(handle, "HourOffset", out found);
            if (!found)
                return null;

            IFCAheadOrBehind? sense = IFCEnums.GetSafeEnumerationAttribute<IFCAheadOrBehind>(handle, "Sense");
            if (sense.HasValue && sense.Value == IFCAheadOrBehind.Behind)
                hour = -hour;

            hour += daylightSavingHour;

            string valueAsString = "UTC" + hour.ToString();
            int minute = IFCImportHandleUtil.GetRequiredIntegerAttribute(handle, "MinuteOffset", out found);
            if (found)
                valueAsString += ":" + minute.ToString("D2");

            return valueAsString;
        }

        /// <summary>
        /// Convert date and time to string in the format YYYY-MM-DD HH::MM::SS (timezone)
        /// </summary>
        /// <param name="handle">The IfcDateTime handle.</param>
        /// <returns>The date and time string.</returns>
        private static string DateAndTimeToString(IFCAnyHandle handle)
        {
            string dateComponent = CalendarDateToString(handle);
            string timeComponent = LocalTimeToString(handle);
            return ConcatenateString(dateComponent, " ", timeComponent);
        }

        private static string ExternalReferenceToString(IFCAnyHandle handle)
        {
            string valueAsString = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "Location", null);

            string itemReference = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "ItemReference", null);
            ConcatenateString(valueAsString, " : ", itemReference);

            string name = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "Name", null);
            ConcatenateString(valueAsString, " : ", name);

            // TODO: Process the optional ReferencedSource of type IfcClassification for IfcClassificationReference.
            return valueAsString;
        }

        private static string LocalTimeToString(IFCAnyHandle handle)
        {
            bool found;
            int hour = IFCImportHandleUtil.GetRequiredIntegerAttribute(handle, "HourComponent", out found);
            if (!found)
                return null;

            string valueAsString = hour.ToString("D2");
            int minute = IFCImportHandleUtil.GetOptionalIntegerAttribute(handle, "MinuteComponent", out found);
            if (found)
            {
                valueAsString += ":" + minute.ToString("D2");
                int second = IFCImportHandleUtil.GetOptionalIntegerAttribute(handle, "SecondComponent", out found);
                if (found)
                    valueAsString += ":" + second.ToString("D2");
            }

            // Relies on default return of 0 if not found.
            int daylightSavingHour = IFCImportHandleUtil.GetOptionalIntegerAttribute(handle, "DaylightSavingOffset", out found);

            IFCAnyHandle coordinatedUniversalTimeOffset = IFCImportHandleUtil.GetOptionalInstanceAttribute(handle, "CoordinatedUniversalTimeOffset");
            string timezone = CoordinatedUniversalTimeOffsetToString(coordinatedUniversalTimeOffset, daylightSavingHour);
            if (!string.IsNullOrWhiteSpace(timezone))
                valueAsString += " (" + timezone + ")";

            return valueAsString;
        }

        private static string MaterialToString(IFCAnyHandle handle)
        {
            IFCMaterial material = IFCMaterial.ProcessIFCMaterial(handle);
            if (material != null)
                return material.Name;
            return null;
        }

        private static string MaterialListToString(IFCAnyHandle handle)
        {
            string valueAsString = null;

            List<IFCAnyHandle> materials = IFCAnyHandleUtil.GetAggregateInstanceAttribute<List<IFCAnyHandle>>(handle, "Materials");
            foreach (IFCAnyHandle material in materials)
            {
                string currentMaterialAsString = IFCImportHandleUtil.GetRequiredStringAttribute(handle, "Name", false);
                ConcatenateString(valueAsString, ";", currentMaterialAsString);
            }

            return valueAsString;
        }

        private static string OrganizationToString(IFCAnyHandle handle)
        {
            // Ignoring Id, Description, Roles, and Addresses.
            return IFCImportHandleUtil.GetRequiredStringAttribute(handle, "Name", false);
        }

        private static string PersonToString(IFCAnyHandle handle)
        {
            // There is no "person" parameter defintion in Revit.  As such, we try, in order:
            // 1. PrefixTitles GivenName MiddleNames FamilyName SuffixTitles
            // 2. Id
            // 3. Roles
            // We are ignoring the address field, and will alert the user to that if it is set.

            // #1
            string valueAsString = GetListAsString(handle, "PrefixTitles", " ");

            string namePart = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "GivenName", null);
            ConcatenateString(valueAsString, " ", namePart);

            namePart = GetListAsString(handle, "MiddleNames", " ");
            ConcatenateString(valueAsString, " ", namePart);

            namePart = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "FamilyName", null);
            ConcatenateString(valueAsString, " ", namePart);

            namePart = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "FamilyName", null);
            ConcatenateString(valueAsString, " ", namePart);

            namePart = GetListAsString(handle, "SuffixTitles", ",");
            ConcatenateString(valueAsString, " ", namePart);

            if (!string.IsNullOrWhiteSpace(valueAsString))
                return valueAsString;

            // #2
            valueAsString = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "Id", null);
            if (!string.IsNullOrWhiteSpace(valueAsString))
                return valueAsString;

            // #3
            valueAsString = ActorRoleToString(handle);
            return valueAsString;
        }

        /// <summary>
        /// Create a string of the form of Person, Organization.
        /// </summary>
        /// <param name="handle">The IfcPersonAndOrganization handle.</param>
        /// <returns>The string of the form "Person, Organization".</returns>
        private static string PersonAndOrganizationToString(IFCAnyHandle handle)
        {
            IFCAnyHandle person = IFCImportHandleUtil.GetRequiredInstanceAttribute(handle, "ThePerson", false);
            IFCAnyHandle organization = IFCImportHandleUtil.GetRequiredInstanceAttribute(handle, "TheOrganization", false);

            return ConcatenateString(PersonToString(person), ", ", OrganizationToString(organization));
        }

        private static string PostalAddressToString(IFCAnyHandle handle)
        {
            string valueAsString = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "InternalLocation", null);

            string extraLinesAsString = GetListAsString(handle, "AddressLines", ", ");
            ConcatenateString(valueAsString, ", ", extraLinesAsString);

            extraLinesAsString = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "PostalBox", null);
            ConcatenateString(valueAsString, ", ", extraLinesAsString);

            extraLinesAsString = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "Town", null);
            ConcatenateString(valueAsString, ", ", extraLinesAsString);

            extraLinesAsString = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "Region", null);
            ConcatenateString(valueAsString, ", ", extraLinesAsString);

            extraLinesAsString = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "PostalCode", null);
            ConcatenateString(valueAsString, ", ", extraLinesAsString);

            extraLinesAsString = IFCImportHandleUtil.GetOptionalStringAttribute(handle, "Country", null);
            ConcatenateString(valueAsString, ", ", extraLinesAsString);

            return valueAsString;
        }

        private static string TelecomAddressToString(IFCAnyHandle handle)
        {
            IList<string> addresses = new List<string>();
            addresses.Add(GetListAsString(handle, "TelephoneNumbers", ", "));
            addresses.Add(GetListAsString(handle, "FacsimileNumbers", ", "));
            addresses.Add(IFCImportHandleUtil.GetOptionalStringAttribute(handle, "Pager", null));
            addresses.Add(GetListAsString(handle, "ElectronicMailAddresses", ", "));
            addresses.Add(IFCImportHandleUtil.GetOptionalStringAttribute(handle, "WWWHomePageURL", null));

            int numValidEntries = 0;
            IList<bool> addressesValid = new List<bool>();
            foreach (string address in addresses)
            {
                bool addressValid = !string.IsNullOrWhiteSpace(address);
                if (addressValid) numValidEntries++;
                addressesValid.Add(addressValid);
            }

            if (numValidEntries == 0)
                return null;

            if (numValidEntries > 1)
            {
                if (m_TelecomPrefixes == null)
                {
                    m_TelecomPrefixes = new List<string>();
                    m_TelecomPrefixes.Add("TEL: ");
                    m_TelecomPrefixes.Add("FAX: ");
                    m_TelecomPrefixes.Add("PAGER: ");
                    m_TelecomPrefixes.Add("EMAIL: ");
                    m_TelecomPrefixes.Add("WWW: ");
                }
            }

            string valueAsString = null;
            for (int ii = 0; ii < 5; ii++)
            {
                if (addressesValid[ii])
                {
                    if (numValidEntries > 1)
                    {
                        valueAsString = ConcatenateString(valueAsString, ", ", m_TelecomPrefixes + addresses[ii]);
                    }
                    else
                    {
                        valueAsString = addresses[ii];
                        break;
                    }
                }
            }

            return valueAsString;
        }
    }
}


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/proc.h>
#include <sys/mutex.h>
#include <sys/mman.h>
#include <sys/rwlock.h>
#include <sys/sysctl.h>

#include <vm/vm.h>
#include <vm/vm_param.h>
#include <vm/vm_object.h>
#include <vm/vm_page.h>
#include <vm/vm_pager.h>

/* list of phys pager objects */
static struct pagerlst phys_pager_object_list;
/* protect access to phys_pager_object_list */
static struct mtx phys_pager_mtx;

static void
phys_pager_init(void)
{

	TAILQ_INIT(&phys_pager_object_list);
	mtx_init(&phys_pager_mtx, "phys_pager list", NULL, MTX_DEF);
}

/*
 * MPSAFE
 */
static vm_object_t
phys_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
    vm_ooffset_t foff, struct ucred *cred)
{
	vm_object_t object, object1;
	vm_pindex_t pindex;

	/*
	 * Offset should be page aligned.
	 */
	if (foff & PAGE_MASK)
		return (NULL);

	pindex = OFF_TO_IDX(foff + PAGE_MASK + size);

	if (handle != NULL) {
		mtx_lock(&phys_pager_mtx);
		/*
		 * Look up pager, creating as necessary.
		 */
		object1 = NULL;
		object = vm_pager_object_lookup(&phys_pager_object_list, handle);
		if (object == NULL) {
			/*
			 * Allocate object and associate it with the pager.
			 */
			mtx_unlock(&phys_pager_mtx);
			object1 = vm_object_allocate(OBJT_PHYS, pindex);
			mtx_lock(&phys_pager_mtx);
			object = vm_pager_object_lookup(&phys_pager_object_list,
			    handle);
			if (object != NULL) {
				/*
				 * We raced with other thread while
				 * allocating object.
				 */
				if (pindex > object->size)
					object->size = pindex;
			} else {
				object = object1;
				object1 = NULL;
				object->handle = handle;
				TAILQ_INSERT_TAIL(&phys_pager_object_list, object,
				    pager_object_list);
			}
		} else {
			if (pindex > object->size)
				object->size = pindex;
		}
		mtx_unlock(&phys_pager_mtx);
		vm_object_deallocate(object1);
	} else {
		object = vm_object_allocate(OBJT_PHYS, pindex);
	}

	return (object);
}

/*
 * MPSAFE
 */
static void
phys_pager_dealloc(vm_object_t object)
{

	if (object->handle != NULL) {
		VM_OBJECT_WUNLOCK(object);
		mtx_lock(&phys_pager_mtx);
		TAILQ_REMOVE(&phys_pager_object_list, object, pager_object_list);
		mtx_unlock(&phys_pager_mtx);
		VM_OBJECT_WLOCK(object);
	}
}

/*
 * Fill as many pages as vm_fault has allocated for us.
 */
static int
phys_pager_getpages(vm_object_t object, vm_page_t *m, int count, int reqpage)
{
	int i;

	VM_OBJECT_ASSERT_WLOCKED(object);
	for (i = 0; i < count; i++) {
		if (m[i]->valid == 0) {
			if ((m[i]->flags & PG_ZERO) == 0)
				pmap_zero_page(m[i]);
			m[i]->valid = VM_PAGE_BITS_ALL;
		}
		KASSERT(m[i]->valid == VM_PAGE_BITS_ALL,
		    ("phys_pager_getpages: partially valid page %p", m[i]));
		KASSERT(m[i]->dirty == 0,
		    ("phys_pager_getpages: dirty page %p", m[i]));
		/* The requested page must remain busy, the others not. */
		if (i == reqpage) {
			vm_page_lock(m[i]);
			vm_page_flash(m[i]);
			vm_page_unlock(m[i]);
		} else
			vm_page_xunbusy(m[i]);
	}
	return (VM_PAGER_OK);
}

static void
phys_pager_putpages(vm_object_t object, vm_page_t *m, int count, boolean_t sync,
		    int *rtvals)
{

	panic("phys_pager_putpage called");
}

/*
 * Implement a pretty aggressive clustered getpages strategy.  Hint that
 * everything in an entire 4MB window should be prefaulted at once.
 *
 * XXX 4MB (1024 slots per page table page) is convenient for x86,
 * but may not be for other arches.
 */
#ifndef PHYSCLUSTER
#define PHYSCLUSTER 1024
#endif
static boolean_t
phys_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
		   int *after)
{
	vm_pindex_t base, end;

	base = pindex & (~(PHYSCLUSTER - 1));
	end = base + (PHYSCLUSTER - 1);
	if (before != NULL)
		*before = pindex - base;
	if (after != NULL)
		*after = end - pindex;
	return (TRUE);
}

struct pagerops physpagerops = {
	.pgo_init =	phys_pager_init,
	.pgo_alloc =	phys_pager_alloc,
	.pgo_dealloc = 	phys_pager_dealloc,
	.pgo_getpages =	phys_pager_getpages,
	.pgo_putpages =	phys_pager_putpages,
	.pgo_haspage =	phys_pager_haspage,
};


text:
BarneyUtility

service in module utility

Description

Use Utility service

To use Utility service, you have to add BarneyUtility dependency to your component (i.e: directive, controller...).

In this example, I have added dependency of BarneyUtility to a controller:

angular.module('mock').controller('HomePageController', [
    'BarneyUtility', '$scope',
    function(Utility, $scope){
        // we can use "Utility" object here
    }
]);

Note that I included BarneyUtility as dependency but I have renamed it as Utility to use it more easily in controller code.

List Method

addQueryParams

arrayDiff

brutalRedirect

clickAndGo

getCurrentQueryString

Methods

addQueryParams(newParams, newUrl)

This method add one or more query string params to the
current URL or to a new URL

Parameters

Param	Type	Details

newParams	Object

Object with params

newUrl	string

New URL

Example

  //current URL =  http://foo.com?mars=earth
  Utility.addQueryParams({ hello: 'world' })
  //new URL =   http://foo.com?mars=earth&hello=world

  //current URL = http://foo.com?mars=earth
  Utility.addQueryParams({ hello: 'world' }, 'http://var.com')
  //new URL = http://var.com?hello=world

  //current URL = 'http://foo.com?mars=earth'
  Utility.addQueryParams({ hello: 'world' }, 'http://var.com?venus=sun')
  //new URL = 'http://var.com?venus=sun&hello=world'

arrayDiff(first, second)

This method removes from the first array the element of the second

Parameters

Param	Type	Details

first	array

first array

second	array

second (contain the elements to remove)

Example

var array1 = ['1','2','3']
var array2 = ['2'];

Utility.arrayDiff(array1, array2);
// it returns an array ['1', '3']

brutalRedirect(url)

This method does a brutal redirect to the given URL.

Usefull for ios

Parameters

Param	Type	Details

url	string

New url to redirect to

Example

Utility.brutalRedirect('http://my_new.url')

clickAndGo(event)

This function makes sure that a link is followed by the browser
when the user clicks on it, even if the item clicked contains ng-click

Parameters

Param	Type	Details

event	*

Event to catch

Example

Utility.clickAndGo(myEvent)

getCurrentQueryString()

This method return the query string from the URL, before and after the hashbang (#!).

Example

Utility getCurrentQueryString

Here is an example of the getCurrentQueryString method.

?hello=world/#!/category or in #!/category/?hello=world

  Utility.getCurrentQueryString();
  // it returns { hello: 'world' }


text:
package com.helger.json.visit;

import java.util.Map;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;

import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.PresentForCodeCoverage;
import com.helger.json.IJson;
import com.helger.json.IJsonArray;
import com.helger.json.IJsonObject;
import com.helger.json.IJsonValue;

/**
 * Recursively visit all Json nodes and invoke the provided callback.
 *
 * @author Philip Helger
 */
@Immutable
public final class JsonVisitor
{
  @PresentForCodeCoverage
  private static final JsonVisitor INSTANCE = new JsonVisitor ();

  private JsonVisitor ()
  {}

  private static void _recursiveVisit (@Nonnull final IJson aJson, @Nonnull final IJsonVisitorCallback aCB)
  {
    if (aJson.isValue ())
    {
      // Simple value
      aCB.onJsonValue ((IJsonValue) aJson);
    }
    else
      // Complex (array or object)
      if (aJson.isArray ())
      {
        final IJsonArray aArray = (IJsonArray) aJson;
        aCB.onJsonArrayStart (aArray);

        for (final IJson aChild : aArray)
          _recursiveVisit (aChild, aCB);

        aCB.onJsonArrayEnd (aArray);
      }
      else
      {
        // Must be an object
        final IJsonObject aObject = (IJsonObject) aJson;
        aCB.onJsonObjectStart (aObject);

        for (final Map.Entry <String, IJson> aEntry : aObject)
        {
          aCB.onJsonObjectElementName (aEntry.getKey ());
          // Object value
          _recursiveVisit (aEntry.getValue (), aCB);
        }

        aCB.onJsonObjectEnd (aObject);
      }
  }

  /**
   * Visit the whole JSON.
   *
   * @param aJson
   *        The JSON to visit. May not be null.
   * @param aCB
   *        The callback to be invoked. May not be null.
   */
  public static void visit (@Nonnull final IJson aJson, @Nonnull final IJsonVisitorCallback aCB)
  {
    ValueEnforcer.notNull (aJson, "JSON");
    ValueEnforcer.notNull (aCB, "Callback");
    _recursiveVisit (aJson, aCB);
  }
}


text:
/**
 * angular-elastic-builder
 *
 * /src/directives/Chooser.js
 *
 * This file is to help recursively, to decide whether to show a group or rule
 */

(function(angular) {
  'use strict';

  var app = angular.module('angular-elastic-builder');

  app.directive('elasticBuilderChooser', [
    'RecursionHelper',
    'groupClassHelper',

    function elasticBuilderChooser(RH, groupClassHelper) {

      return {
        scope: {
          elasticFields: '=',
          item: '=elasticBuilderChooser',
          onRemove: '&',
        },

        templateUrl: 'angular-elastic-builder/ChooserDirective.html',

        compile: function (element) {
          return RH.compile(element, function(scope, el, attrs) {
            var depth = scope.depth = (+ attrs.depth)
              , item = scope.item;

            scope.getGroupClassName = function() {
              var level = depth;
              if (item.type === 'group') level++;

              return groupClassHelper(level);
            };
          });
        }
      };
    }

  ]);

})(window.angular);


text:
nmrglue.linesh
==============

.. automodule:: nmrglue.analysis.linesh

This module is imported as nmrglue.linesh and can be called as such

High-Level Functions
--------------------

These are the functions the majority of users will use from the linesh module.

.. autofunction:: fit_spectrum
.. autofunction:: fit_NDregion
.. autofunction:: sim_NDregion
.. autofunction:: add_to_table
.. autofunction:: pack_table
.. autofunction:: unpack_table
.. autofunction:: estimate_scales

Low-Level Functions
-------------------

These functions are typically not used directly by users. They are called by
high level functions.  Developers and user who want fine control over lineshape
fitting may be interested in these functions.

.. autofunction:: f_NDregion
.. autofunction:: s_NDregion
.. autofunction:: s_single_NDregion
.. autofunction:: err_NDregion
.. autofunction:: make_slist
.. autofunction:: split_list


text:
/* This source file is part of the Tomviz project, https://tomviz.org/.
   It is released under the 3-Clause BSD License, see "LICENSE". */

/**
 * @class   vtkVolumeScaleRepresentation
 * @brief   represent the vtkDistanceWidget
 *
 * The vtkVolumeScaleRepresentation is a representation for the
 * vtkHandleWidget. This representation consists of a measuring cube. The size
 * of the cube adapts to fit within a minimum and maximum fraction of the
 * viewing area.
 *
 * @sa
 * vtkMeasurementCubeHandleRepresentation3D
*/

#ifndef vtkVolumeScaleRepresentation_h
#define vtkVolumeScaleRepresentation_h

#include "vtkMeasurementCubeHandleRepresentation3D.h"

class vtkTextActor;

class vtkVolumeScaleRepresentation
  : public vtkMeasurementCubeHandleRepresentation3D
{
public:
  /**
   * Instantiate class.
   */
  static vtkVolumeScaleRepresentation* New();

  /**
   * Method to satisfy superclasses' API.
   */
  void BuildRepresentation() override;

  //@{
  /**
   * Standard VTK methods.
   */
  vtkTypeMacro(
    vtkVolumeScaleRepresentation,
    vtkMeasurementCubeHandleRepresentation3D) void PrintSelf(ostream& os,
                                                             vtkIndent indent)
    override;
  //@}

  //@{
  /**
   * Get the label actor
   */
  vtkGetObjectMacro(Label, vtkTextActor);
  //@}

  //@{
  /**
   * Set the visibility of both the cube and the label
   */
  void SetRepresentationVisibility(bool choice);
  //@}

  //@{
  /**
   * Methods to make this class properly act like a vtkWidgetRepresentation.
   */
  void GetActors2D(vtkPropCollection*) override;
  void ReleaseGraphicsResources(vtkWindow*) override;
  int RenderOverlay(vtkViewport*) override;
  int RenderOpaqueGeometry(vtkViewport*) override;
  int RenderTranslucentPolygonalGeometry(vtkViewport*) override;
  int HasTranslucentPolygonalGeometry() override;
  //@}

protected:
  vtkVolumeScaleRepresentation();
  ~vtkVolumeScaleRepresentation() override;

  void Update2DLabel();

  vtkTextActor* Label;

private:
  vtkVolumeScaleRepresentation(const vtkVolumeScaleRepresentation&) = delete;
  void operator=(const vtkVolumeScaleRepresentation&) = delete;
};

#endif


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

/**
 * @file ThroughputTypes.h
 *
 */

#ifndef THROUGHPUTTYPES_H_
#define THROUGHPUTTYPES_H_

#include <fastrtps/TopicDataType.h>
#include <fastdds/dds/log/Log.hpp>
#include <fastdds/dds/log/Colors.hpp>

#include <chrono>

struct TroughputResults
{
    uint32_t payload_size;
    uint32_t recovery_time_ms;
    uint32_t demand;

    struct PublisherResults
    {
        std::chrono::duration<double, std::micro>  totaltime_us;
        uint64_t send_samples;
        double MBitssec;
        double Packssec;
    }
    publisher;

    struct SubscriberResults
    {
        std::chrono::duration<double, std::micro> totaltime_us;
        uint64_t recv_samples;
        uint32_t lost_samples;
        double MBitssec;
        double Packssec;
    }
    subscriber;

    void compute()
    {
        publisher.MBitssec = (double)publisher.send_samples * payload_size * 8 / publisher.totaltime_us.count();
        publisher.Packssec = (double)publisher.send_samples * 1000000 / publisher.totaltime_us.count();
        subscriber.MBitssec = (double)subscriber.recv_samples * payload_size * 8 / subscriber.totaltime_us.count();
        subscriber.Packssec = (double)subscriber.recv_samples * 1000000 / subscriber.totaltime_us.count();
    }

};

inline void print_results(
        std::vector<TroughputResults> results)
{
    printf("\n");
    printf(
        "[            TEST           ][                    PUBLISHER                      ][                            SUBSCRIBER                        ]\n");
    printf(
        "[ Bytes,Demand,Recovery Time][Sent Samples,Send Time(us),   Packs/sec,  MBits/sec][Rec Samples,Lost Samples,Rec Time(us),   Packs/sec,  MBits/sec]\n");
    printf(
        "[------,------,-------------][------------,-------------,------------,-----------][-----------,------------,------------,------------,-----------]\n");
    for (uint32_t i = 0; i < results.size(); i++)
    {
        printf("%7u,%6u,%13u,%13.0f,%13.0f,%12.3f,%11.3f,%12.0f,%12.0f,%12.0f,%12.3f,%11.3f\n",
                results[i].payload_size,
                results[i].demand,
                results[i].recovery_time_ms,
                (double)results[i].publisher.send_samples,
                results[i].publisher.totaltime_us.count(),
                results[i].publisher.Packssec,
                results[i].publisher.MBitssec,
                (double)results[i].subscriber.recv_samples,
                (double)results[i].subscriber.lost_samples,
                results[i].subscriber.totaltime_us.count(),
                (double)results[i].subscriber.Packssec,
                (double)results[i].subscriber.MBitssec);
    }
    printf("\n");
    fflush(stdout);
}

/*
 * This type allocation code cannot be generated by the compiler because the array member
 * size is unknown at build time. The ThroughputDataType must allocate a suitable buffer
 * for this objects based on the array member size given at runtime. A beforehand knowledge
 * of this type alignment is needed to calculate the right buffer size.
 * This structure default alignment turn out to be 4 in msvc and gcc for
 * x86 and x64 architecture. The alignas specifier is used to match this default
 * behaviour in other platforms.
 * This type does not define a comparison operator because the actual data size referenced
 * is unknown. Use the comparison method provided by its DataType.
 * */
typedef struct alignas(4) ThroughputType
{
    // identifies the sample sent
    uint32_t seqnum;
    // actual payload
    uint8_t data[1];
    // This struct overhead
    static const size_t overhead;

} ThroughputType;

class ThroughputDataType : public eprosima::fastrtps::TopicDataType
{
    // Buffer size for the manage type
    const uint32_t buffer_size_;

public:

    // This size defines the expected ThroughputType buffer size
    ThroughputDataType(
            const uint32_t& size)
        : buffer_size_(size)
    {
        setName(type_name_.c_str());
        m_typeSize = sizeof(decltype(ThroughputType::seqnum)) +
                ((size + 3) & ~3) +
                eprosima::fastrtps::rtps::SerializedPayload_t::representation_header_size;
        m_isGetKeyDefined = false;
    }

    ~ThroughputDataType()
    {
    }

    bool serialize(
            void* data,
            eprosima::fastrtps::rtps::SerializedPayload_t* payload) override;

    bool deserialize(
            eprosima::fastrtps::rtps::SerializedPayload_t* payload,
            void* data) override;

    std::function<uint32_t()> getSerializedSizeProvider(
            void* data) override;

    void* createData() override;

    void deleteData(
            void* data) override;

    bool getKey(
            void* /*data*/,
            eprosima::fastrtps::rtps::InstanceHandle_t* /*ihandle*/,
            bool force_md5 = false) override
    {
        (void)force_md5;
        return false;
    }

    bool compare_data(
            const ThroughputType& lt1,
            const ThroughputType& lt2) const;

    bool is_bounded() const override
    {
        // All plain types are bounded
        return is_plain();
    }

    bool is_plain() const override
    {
        // It is plain because the type has a fixed sized
        return true;
    }

    // Name
    static const std::string type_name_;
};

enum e_Command : uint32_t
{
    DEFAULT,
    READY_TO_START,
    BEGIN,
    TEST_STARTS,
    TEST_ENDS,
    TYPE_NEW,
    TYPE_DISPOSE,
    TYPE_REMOVED,
    ALL_STOPS,
    TEST_RESULTS
};

typedef struct ThroughputCommandType
{
    e_Command m_command;
    uint32_t m_size = 0;
    uint32_t m_demand = 0;
    uint32_t m_lostsamples = 0;
    uint64_t m_lastrecsample = 0;
    uint64_t m_totaltime = 0;

    ThroughputCommandType(
            e_Command com = DEFAULT)
        : m_command(com)
    {
    }

} ThroughputCommandType;

inline std::ostream& operator <<(
        std::ostream& output,
        const ThroughputCommandType& com)
{
    switch (com.m_command)
    {
        case (DEFAULT): return output << "DEFAULT";
        case (READY_TO_START): return output << "READY_TO_START";
        case (BEGIN): return output << "BEGIN";
        case (TEST_STARTS): return output << "TEST_STARTS";
        case (TEST_ENDS): return output << "TEST_ENDS";
        case (ALL_STOPS): return output << "ALL_STOPS";
        case (TEST_RESULTS): return output << "TEST RESULTS";
        default: return output << C_B_RED << "UNKNOWN COMMAND" << C_DEF;
    }
    return output;
}

class ThroughputCommandDataType : public eprosima::fastrtps::TopicDataType
{
public:

    ThroughputCommandDataType()
    {
        setName("ThroughputCommand");
        m_typeSize = 4 * sizeof(uint32_t) + 2 * sizeof(uint64_t) + sizeof(double);
        m_isGetKeyDefined = false;
    }

    ~ThroughputCommandDataType()
    {
    }

    bool serialize(
            void* data,
            eprosima::fastrtps::rtps::SerializedPayload_t* payload) override;

    bool deserialize(
            eprosima::fastrtps::rtps::SerializedPayload_t* payload,
            void* data) override;

    std::function<uint32_t()> getSerializedSizeProvider(
            void* data) override;

    void* createData() override;

    void deleteData(
            void* data) override;

    bool getKey(
            void* /*data*/,
            eprosima::fastrtps::rtps::InstanceHandle_t* /*ihandle*/,
            bool force_md5 = false) override
    {
        (void)force_md5;
        return false;
    }

};

#endif /* THROUGHPUTTYPES_H_ */


text:
from __future__ import print_function

import logging
import os
import sys

_LEVEL_STRING = {"DEBUG": 10, "INFO": 20, "WARNING": 30, "ERROR": 40}
_CMT_LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

def log_level_string_to_int(level):
    if level.upper() in ["TRUE", "YES", "ON", "ENABLED"]:
        verbosity = sys.maxsize
    elif level.upper() in ["FALSE", "NO", "OFF", "DISABLED"]:
        verbosity = 0
    else:
        try:
            verbosity = _LEVEL_STRING[level]
        except KeyError:
            raise ValueError(level)

    return verbosity

def get_log_level_from_environ(level):
    try:
        level = int(os.environ["CMT_VERBOSE"])
    except KeyError:
        pass
    except ValueError:
        level = log_level_string_to_int(level)

    return level

def setup_pymt_logging_channel():
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter(_CMT_LOG_FORMAT)
    ch.setFormatter(formatter)
    return ch

class CmtLogger(logging.Logger):
    def __init__(self, name, level):
        level = get_log_level_from_environ(level)

        logging.Logger.__init__(self, name, level=level)
        ch = setup_pymt_logging_channel()
        self.addHandler(ch)

class Verbose:
    def __init__(self, verbosity=0, log=sys.stderr):
        self._verbosity = verbosity
        self._log = log

    def __call__(self, verbosity, msg):
        if verbosity <= self._verbosity:
            print(self._construct_msg(verbosity, msg), file=self._log)

    @staticmethod
    def _construct_msg(verbosity, msg):
        if verbosity == 0:
            return msg
        else:
            return "*" * verbosity + " " + msg

class CmtVerbose(Verbose):
    """
    >>> if 'CMT_VERBOSE' in os.environ: del os.environ['CMT_VERBOSE']
    >>> verbose = CmtVerbose (1, log=sys.stdout)
    >>> verbose (1, "Level one")
    #CMT Level one
    >>> verbose (2, "Level two")
    >>> verbose (0, "Level %d" % 0)
    #CMT Level 0

    >>> os.environ['CMT_VERBOSE'] = '3'
    >>> verbose = CmtVerbose (log=sys.stdout)
    >>> verbose (1, "Level one")
    #CMT Level one
    >>> verbose (2, "Level two")
    #CMT Level two
    >>> verbose (4, "Level %d" % 0)

    >>> os.environ['CMT_VERBOSE'] = 'False'
    >>> verbose = CmtVerbose (log=sys.stdout)
    >>> verbose (0, 'No message')
    #CMT No message
    >>> verbose (1, 'No message')

    >>> os.environ['CMT_VERBOSE'] = 'True'
    >>> verbose = CmtVerbose (log=sys.stdout)
    >>> verbose (1, 'No message')
    #CMT No message
    >>> verbose (0, 'No message')
    #CMT No message
    """

    def __init__(self, verbosity=1, log=sys.stderr):
        if "CMT_VERBOSE" in os.environ:
            level = os.environ["CMT_VERBOSE"]
            if level.upper() in ["TRUE", "YES", "ON", "ENABLED"]:
                verbosity = sys.maxsize
            elif level.upper() in ["FALSE", "NO", "OFF", "DISABLED"]:
                verbosity = 0
            else:
                try:
                    verbosity = int(level)
                except ValueError:
                    verbosity = 0

        Verbose.__init__(self, verbosity, log)

    @staticmethod
    def _construct_msg(verbosity, msg):
        return "#CMT " + msg.strip()


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

<phpunit bootstrap="Bootstrap.php" colors="true">
    <testsuites>
        <testsuite name="NakadeTest">
            <directory>../module/Nakade/test</directory>
        </testsuite>
        <testsuite name="LeagueTest">
            <directory>../module/League/test</directory>
        </testsuite>
        <testsuite name="StatsTest">
            <directory>../module/Stats/test</directory>
        </testsuite>
        <testsuite name="SeasonTest">
            <directory>../module/Season/test</directory>
        </testsuite>
    </testsuites>
</phpunit>


text:
![stability](https://img.shields.io/badge/stability-experimental-red.svg?style=flat-square)

> A (web audio) synth construction kit

`synth-kit` is a collection of functions to make Web Audio API more enjoyable. Here is some taste of what you get:

```js
import { conn, sine, saw, lowpass, adsr, dest, master, inst } from 'synth-kit'

// start an OscillatorNode and connect it to AudioContext's destination
sine('C4').connect(dest()).start()
// start a chain of oscillator -> filter -> envelope -> destination
conn(saw('Db3'), lowpass(500), adsr(), dest()).start()

// start to master
master.start(conn(square('C4'), adsr()))

// create a instrument with an oscillator and an ADSR envelope:
var synth = inst(function (freq) {
  return conn(saw(freq), adsr())
})
synth.start('C4')
synth.start('G5')
synth.stop()

// create a substractive synth instrument with one oscillator:
var mono = inst(substract)
mono.start('C4')
// a substractive synth instrument with three sine oscillators
var duo = inst(substract, { oscillators: { ratios: [1, 2, 2.5 ] } })
duo.start({ note: 'C4', attack: 0.5 })
```

## Usage

#### Oscillators, buffers and sources

The `osc` function creates an OscillatorNode:

```js
osc({ note: 'C4', type: 'square' }).connect(dest()).start()
```

You can use any of its aliases: `sine`, `saw`, `triangle` or `square`:

```js
sine('Db3').connect(dest()).start()
```

You can load a sample with `load` function and play it with the `sample` function:

```js
var kick = load('http://myserver.com/samples/kick.mp3')
sample(kick).start()
```

Notice that the file must be fetched before get any sound, so if in the previous example `start` is called before loading the file, no sound in produced.

#### Filters and envelopes

Filters are created using `filter` function (or any of its aliases: `lowpass`, `hipass` and `bandpass`):

```js
saw(440).connect(lowpass(200)).start()
```

There are several types of envelopes. The typical `adsr(options)`:

```js
o = saw(440).connect(adsr({ release: 1 }))
o.start()
o.stop() // => will have 1 second of exponential decay
```

Or a percutive attack-decay envelope with `perc(attack, decay)`:

```js
o = saw(440).connect(perc()).start()
```

#### Routing

Routing audio unsing node's `connect` function is cumbersome, error prone and makes hard to understand the signal flow.

You can route nodes in series using the `conn(...nodes)` function:

```js
conn(sine(440), gain(0.5))
```

Or route them in parrallel using the `add(...nodes)` function:

```js
add(sine('c4'), sine('c5'), sine('g5'))
```

These two functions can be combined creating complex audio node graphs:

```js
// Add two sines and connect themm to a filter and an envelope
conn(add(sine(440), sine(444)), lowpass(500), adsr())

// Add two simple subtractive chain (osc -> filter -> adsr)
add(
  conn(saw(400), lowpass(800), perc()),
  conn(square(800), hipass(1000), adsr())
).connect(dest()).start()
```

#### Modulation

You can pass a node to any audio parameter value to create modulations. For example, you can modulate the `detune` parameter of an oscillator with another oscillator to create a vibrato effect:

```js
sine({ note: 'A4', detune: mul(50, sine(10)) }).start()
```

Or, for example, you can modulate a `gain` to create a tremolo effect:

```js
connect(saw('C4'), gain({ value: sine(4) })).start()
```

#### Synths

You can create a typical subtract synthetizer with an oscillator, a filter and two envelopes with the `subtract(freq, options)` function:

```js
subtractive(880, { type: 'square', filter: { type: 'hipass' } }).connect(dest()).start()
```

Or a prototypical additive synthetizer:

```js
additive([440, 880, 1200], { gains: [0.6, 0.3, 0.1] }).connect(dest()).start()
```

#### Instruments

Sometime you want a more OOP interface. You want a instrument:

```js
var marimba = inst(function (freq) {
  return add(
    conn(sine(fq), perc(0.1, 1)),
    conn(sine(2 * fq), perc(0.01, 0.1))
  )
})
marimba.start('C4')
marimba.start('G5')
marimba.stop()
```

#### Conversion and utility functions

SynthKit uses frequencies in hertzs to represent pitches, linear gain values to represent amplitudes and number of samples to represent buffer lengths. But sometimes you want to provide those using different units. Here are some conversion utilities:

- `noteToFreq(name)`: convert a note name or note midi number to its frequency
- `midiToFreq(midi)`: convert a note name or note midi number to its frequency
- `tempoToFreq(bpm, subdivision)`: convert from beats per minute to hertzs
- `dBToGain(db)`: convert from decibels to gain value
- `levelToGain(level)`: convert from level (0 to 100 in logaritmic scale) to gain value
- `gainToDb(gain)`: convert from gain to decibels
- `secsToSamples(num)`: convert from seconds to number of samples

## Livecoding in the browser

Setup `synth-kit` for live coding it's easy. Add the [distribution file] to you page:

And then:

```js
SynthKit.live() // => export all `synth-kit` functions to the global environment
sine(note('A4')).start()
```

## Test and examples

To view some examples open: `example/index.html`

## Inspiration and references

- The idea and API organization is taken from cljs-bach: https://github.com/ctford/cljs-bach Thanks ctford!
- Of course, the synth secrets tutorial was the beginning of all: https://github.com/micjamking/synth-secrets (that's a easy to read version). Thanks Gordon Reid (here it is an [awesome PDF version](http://www.mediafire.com/file/7w2dcsqmkbeduea/Synth+Secrets+Complete.pdf))
- Vincent made some nice 808 drum synsthesis: https://github.com/vincentriemer/io-808
- Percussion synthesis tutorial: http://www.cim.mcgill.ca/~clark/nordmodularbook/nm_percussion.html
- Sound Design in Web Audio its an awesome two part blog post: http://nickwritesablog.com/sound-design-in-web-audio-neurofunk-bass-part-1/ and http://nickwritesablog.com/sound-design-in-web-audio-neurofunk-bass-part-2/
- There are a lot of resources about synthesis, here is a nice one: https://www.gearslutz.com/board/electronic-music-instruments-electronic-music-production/460283-how-do-you-synthesize-808-ish-drums.html

## License

MIT License


text:
<?php

namespace Rudak\SeoBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class RudakSeoBundle extends Bundle
{
}


text:
package org.apache.camel.spring.boot.health;

import org.apache.camel.health.HealthCheckConfiguration;

public abstract class AbstractHealthCheckConfiguration {
    /**
     * Set if the check associated to this configuration is enabled or not.
     */
    private Boolean enabled;

    /**
     * Set the check interval.
     */
    private String interval;

    /**
     * Set the number of failure before reporting the service as un-healthy.
     */
    private Integer failureThreshold;

    /**
     * Set if the check associated to this configuration is enabled or not.
     */
    public Boolean isEnabled() {
        return enabled;
    }

    /**
     * Set if the check associated to this configuration is enabled or not.
     */
    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }

    public String getInterval() {
        return interval;
    }

    /**
     * Set the check interval.
     */
    public void setInterval(String interval) {
        this.interval = interval;
    }

    public Integer getFailureThreshold() {
        return failureThreshold;
    }

    /**
     * Set the number of failure before reporting the service as un-healthy.
     */
    public void setFailureThreshold(Integer failureThreshold) {
        this.failureThreshold = failureThreshold;
    }

    /**
     * Convert this configuration to a {@link HealthCheckConfiguration} using default values.
     */
    public HealthCheckConfiguration asHealthCheckConfiguration() {
        return HealthCheckConfiguration.builder()
            .enabled(this.isEnabled())
            .interval(this.getInterval())
            .failureThreshold(this.getFailureThreshold())
            .build();
    }
}


text:
<?php
/**
 * @author: Rogee<rogeeyang@gmail.com>
 */

namespace Models;

use Common\ModelCommon;

class FriendLink extends ModelCommon
{

}


text:
namespace Phonebook
{
    using System;
    using Phonebook.Contracts;

    public class ConsolePrinter : IPrinter
    {
        public void Print(string text)
        {
            Console.WriteLine(text);
        }
    }
}


text:
layout: zh-CN/default
title: 为 Rust 出力 — 社区建设 · Rust 程序设计语言
---

# 为 Rust 出力 — 社区建设

帮助新手、传播它、结识有趣的人。使用 Rust 的
我们都希望它成为开源开发的一个光辉榜样。

请您留意 [#rust-beginners] 频道,这是我们为新 Rust 程序员的询问提供帮助的地方,给他们提供迅速、准确和礼貌的回应很重要。与此类似,[Stack Overflow]、[users.rust-lang.org] 和 [/r/rust] 都是 Rust 程序员常来寻求帮助的地方。
如果您想了解怎样更好地回答程序员的提问,[阅读这份指南吧][helpful]。

If you are already experienced in some area of the project, please
look out for potential [E-easy] bugs. When you see an
easy issue on the bug tracker that you know how to fix, write up a
description of the fix and tag it with E-easy. Note that what is
obvious to you is not obvious to a new Rust contributor, and its
important to describe the problem and the solution clearly. It is
thus also helpful to triage E-easy bugs for poor descrptions and
improve them.

Experienced developers who are patient and communicate clearly should
consider [指导新贡献者][mentor]. Tag easy issues with
[E-mentor] and mention in a comment that you will mentor. Expect people
to contact you about the issue, and attempt to respond promptly.

Maintaining entry-level tasks is good not only for The Rust Project
itself but all projects. If your project has a consistent supply of
entry-level tasks you might institute such a program
yourself. ***Curating entry-level tasks is one of the most effective
methods of bringing new programmers into the project***. If you want
training on mentoring new contributors [read this
guide][mentor-guide].

Talk about what you are working on in the weekly "what's everyone
working on this week" threads on [/r/rust] and [users.rust-lang.org],
and indicate what you need help with. These are great starting points
for collaboration.

Advocate Rust in your own local community. Rust [user groups] and [events]
are a unique and exciting part of the Rust experience: there are so
many, and they are everywhere! If you haven't been yet, go and enjoy
new experiences. If there is nothing Rusty going on near you then
consider organizing something. You can poll for interest and announce
events on [/r/rust] or [users.rust-lang.org]. Contact the [community
team] to put events on the calendar, and thus be announced on [This
Week in Rust].

Remember as you are advocating Rust though to be considerate of
others' views — not everybody is going to be receptive to Rust, and
that's just fine.

在 [#rust-community] 中能遇到其他 Rust 社区建设者。

<!--
Other ideas:
TWIR, podcasts.

experience reports
conf talks

Conduct training on Rust. (link to training material).
-->

[#rust-beginners]: https://client00.chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-beginners
[#rust-community]: https://client00.chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-community
[/r/rust]: https://reddit.com/r/rust
[E-easy]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AE-easy
[E-mentor]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AE-easy+label%3AE-mentor
[Stack Overflow]: https://stackoverflow.com/questions/tagged/rust
[This Week in Rust]: https://this-week-in-rust.org
[community team]: https://www.rust-lang.org/team.html#Community
[events]: https://www.google.com/calendar/embed?src=apd9vmbc22egenmtu5l6c5jbfc@group.calendar.google.com
[helpful]: https://codeblog.jonskeet.uk/2009/02/17/answering-technical-questions-helpfully/
[mentor]: https://users.rust-lang.org/t/mentoring-newcomers-to-the-rust-ecosystem/3088
[mentor-guide]: https://manishearth.github.io/blog/2016/01/03/making-your-open-source-project-newcomer-friendly/
[user groups]: user-groups.html
[users.rust-lang.org]: https://users.rust-lang.org