text:
package elastic

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
)

// MultiSearch executes one or more searches in one roundtrip.
// See http://www.elasticsearch.org/guide/reference/api/multi-search/
type MultiSearchService struct {
	client     *Client
	requests   []*SearchRequest
	indices    []string
	pretty     bool
	debug      bool
	routing    string
	preference string
}

func NewMultiSearchService(client *Client) *MultiSearchService {
	builder := &MultiSearchService{
		client:   client,
		requests: make([]*SearchRequest, 0),
		indices:  make([]string, 0),
		debug:    false,
		pretty:   false,
	}
	return builder
}

func (s *MultiSearchService) Add(requests ...*SearchRequest) *MultiSearchService {
	s.requests = append(s.requests, requests...)
	return s
}

func (s *MultiSearchService) Index(index string) *MultiSearchService {
	s.indices = append(s.indices, index)
	return s
}

func (s *MultiSearchService) Indices(indices ...string) *MultiSearchService {
	s.indices = append(s.indices, indices...)
	return s
}

func (s *MultiSearchService) Pretty(pretty bool) *MultiSearchService {
	s.pretty = pretty
	return s
}

func (s *MultiSearchService) Debug(debug bool) *MultiSearchService {
	s.debug = debug
	return s
}

func (s *MultiSearchService) Do() (*MultiSearchResult, error) {
	// Build url
	urls := "/_msearch"

	// Parameters
	params := make(url.Values)
	if s.pretty {
		params.Set("pretty", fmt.Sprintf("%v", s.pretty))
	}
	if len(params) > 0 {
		urls += "?" + params.Encode()
	}

	// Set up a new request
	req, err := s.client.NewRequest("GET", urls)
	if err != nil {
		return nil, err
	}

	// Set body
	lines := make([]string, 0)
	for _, sr := range s.requests {
		// Set default indices if not specified in the request
		if !sr.HasIndices() && len(s.indices) > 0 {
			sr = sr.Indices(s.indices...)
		}

		header, err := json.Marshal(sr.header())
		if err != nil {
			return nil, err
		}
		body, err := json.Marshal(sr.body())
		if err != nil {
			return nil, err
		}
		lines = append(lines, string(header))
		lines = append(lines, string(body))
	}
	req.SetBodyString(strings.Join(lines, "\n") + "\n") // Don't forget trailing \n

	if s.debug {
		out, _ := httputil.DumpRequestOut((*http.Request)(req), true)
		fmt.Printf("%s\n", string(out))
	}

	// Get response
	res, err := s.client.c.Do((*http.Request)(req))
	if err != nil {
		return nil, err
	}
	if err := checkResponse(res); err != nil {
		return nil, err
	}
	defer res.Body.Close()

	if s.debug {
		out, _ := httputil.DumpResponse(res, true)
		fmt.Printf("%s\n", string(out))
	}

	ret := new(MultiSearchResult)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
}

type MultiSearchResult struct {
	Responses []*SearchResult `json:"responses,omitempty"`
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OnionWallet.Framework.Extensions
{
    public static class StringExtensions
    {
        public static string CreateMD5(this string s)
        {
            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                return sb.ToString();
            }
        }
    }
}


text:
package py.com.fpuna.autotracks.matching2.model;

import static py.com.fpuna.autotracks.matching.LocationUtils.*;

public class Coordinate {

    private double latitude;
    private double longitude;

    public Coordinate() {
    }

    public Coordinate(Coordinate other) {
        this(other.latitude, other.longitude);
    }

    public Coordinate(double latitude, double longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public double distanceTo(Coordinate other) {
        return distance(latitude, longitude, other.latitude, other.longitude);
    }

    public void moveTo(Coordinate other) {
        latitude = other.latitude;
        longitude = other.longitude;
    }

}


text:
package org.frameworkset.spi.support;

import java.util.Locale;

/**
 *
Title: NoSuchMessageException.java

 *
Description:

 *
bboss workgroup

 *
Copyright (c) 2007

 * @Date 2010-9-24 下午04:54:10
 * @author biaoping.yin
 * @version 1.0
 */
public class NoSuchMessageException extends RuntimeException {

	/**
	 * Create a new exception.
	 * @param code code that could not be resolved for given locale
	 * @param locale locale that was used to search for the code within
	 */
	public NoSuchMessageException(String code, Locale locale) {
		super("No message found under code '" + code + "' for locale '" + locale + "'.");
	}

	/**
	 * Create a new exception.
	 * @param code code that could not be resolved for given locale
	 */
	public NoSuchMessageException(String code) {
		super("No message found under code '" + code + "' for locale '" + Locale.getDefault() + "'.");
	}

}


text:
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\ORM\Mapping\GeneratorType;
use Doctrine\Tests\ORM\Functional\DatabaseDriverTestCase;

class DDC2387Test extends DatabaseDriverTestCase
{
    /**
     * @group DDC-2387
     */
    public function testCompositeAssociationKeyDetection()
    {
        $product = new \Doctrine\DBAL\Schema\Table('ddc2387_product');
        $product->addColumn('id', 'integer');
        $product->setPrimaryKey(['id']);

        $attributes = new \Doctrine\DBAL\Schema\Table('ddc2387_attributes');
        $attributes->addColumn('product_id', 'integer');
        $attributes->addColumn('attribute_name', 'string');
        $attributes->setPrimaryKey(['product_id', 'attribute_name']);
        $attributes->addForeignKeyConstraint('ddc2387_product', ['product_id'], ['product_id']);

        $metadata = $this->convertToClassMetadata([$product, $attributes], []);

        self::assertFalse($metadata['Ddc2387Attributes']->getProperty('productId')->hasValueGenerator());
        self::assertEquals(GeneratorType::AUTO, $metadata['Ddc2387Product']->getProperty('id')->getValueGenerator()->getType());
    }
}


text:
namespace Apache.Ignite.ExamplesDll.Binary
{
    using System;
    using Apache.Ignite.Core.Binary;

    /// <summary>
    /// Address.
    /// </summary>
    [Serializable]
    public class Address : IBinarizable
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="street">Street.</param>
        /// <param name="zip">ZIP code.</param>
        public Address(string street, int zip)
        {
            Street = street;
            Zip = zip;
        }

        /// <summary>
        /// Street.
        /// </summary>
        public string Street { get; set; }

        /// <summary>
        /// ZIP code.
        /// </summary>
        public int Zip { get; set; }

        /// <summary>
        /// Writes this object to the given writer.
        /// </summary>
        /// <param name="writer">Writer.</param>
        public void WriteBinary(IBinaryWriter writer)
        {
            writer.WriteString("street", Street);
            writer.WriteInt("zip", Zip);
        }

        /// <summary>
        /// Reads this object from the given reader.
        /// </summary>
        /// <param name="reader">Reader.</param>
        public void ReadBinary(IBinaryReader reader)
        {
            Street = reader.ReadString("street");
            Zip = reader.ReadInt("zip");
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>
        /// A string that represents the current object.
        /// </returns>
        override public string ToString()
        {
            return string.Format("{0} [street={1}, zip={2}]", typeof(Address).Name, Street, Zip);
        }
    }
}


text:
import { StorageAdapterCreator } from "redux-localstorage";
declare const adapterCreator: StorageAdapterCreator<any>;
export = adapterCreator;


text:
BlazeComponent.extendComponent({
  onCreated() {},

  boards() {
    const boards = Boards.find(
      {
        archived: false,
        'members.userId': Meteor.userId(),
        _id: {
          $ne: Meteor.user().getTemplatesBoardId(),
        },
      },
      {
        sort: { sort: 1 /* boards default sorting */ },
      },
    );
    return boards;
  },

  events() {
    return [
      {
        'click .js-create-card-action'(event) {
          const ruleName = this.data().ruleName.get();
          const trigger = this.data().triggerVar.get();
          const cardName = this.find('#card-name').value;
          const listName = this.find('#list-name').value;
          const swimlaneName = this.find('#swimlane-name2').value;
          const boardId = Session.get('currentBoard');
          const desc = Utils.getTriggerActionDesc(event, this);
          const triggerId = Triggers.insert(trigger);
          const actionId = Actions.insert({
            actionType: 'createCard',
            swimlaneName,
            cardName,
            listName,
            boardId,
            desc,
          });
          Rules.insert({
            title: ruleName,
            triggerId,
            actionId,
            boardId,
          });
        },
        'click .js-add-swimlane-action'(event) {
          const ruleName = this.data().ruleName.get();
          const trigger = this.data().triggerVar.get();
          const swimlaneName = this.find('#swimlane-name').value;
          const boardId = Session.get('currentBoard');
          const desc = Utils.getTriggerActionDesc(event, this);
          const triggerId = Triggers.insert(trigger);
          const actionId = Actions.insert({
            actionType: 'addSwimlane',
            swimlaneName,
            boardId,
            desc,
          });
          Rules.insert({
            title: ruleName,
            triggerId,
            actionId,
            boardId,
          });
        },
        'click .js-add-spec-move-action'(event) {
          const ruleName = this.data().ruleName.get();
          const trigger = this.data().triggerVar.get();
          const actionSelected = this.find('#move-spec-action').value;
          const swimlaneName = this.find('#swimlaneName').value || '*';
          const listName = this.find('#listName').value || '*';
          const boardId = Session.get('currentBoard');
          const destBoardId = this.find('#board-id').value;
          const desc = Utils.getTriggerActionDesc(event, this);
          if (actionSelected === 'top') {
            const triggerId = Triggers.insert(trigger);
            const actionId = Actions.insert({
              actionType: 'moveCardToTop',
              listName,
              swimlaneName,
              boardId: destBoardId,
              desc,
            });
            Rules.insert({
              title: ruleName,
              triggerId,
              actionId,
              boardId,
            });
          }
          if (actionSelected === 'bottom') {
            const triggerId = Triggers.insert(trigger);
            const actionId = Actions.insert({
              actionType: 'moveCardToBottom',
              listName,
              swimlaneName,
              boardId: destBoardId,
              desc,
            });
            Rules.insert({
              title: ruleName,
              triggerId,
              actionId,
              boardId,
            });
          }
        },
        'click .js-add-gen-move-action'(event) {
          const desc = Utils.getTriggerActionDesc(event, this);
          const boardId = Session.get('currentBoard');
          const ruleName = this.data().ruleName.get();
          const trigger = this.data().triggerVar.get();
          const actionSelected = this.find('#move-gen-action').value;
          if (actionSelected === 'top') {
            const triggerId = Triggers.insert(trigger);
            const actionId = Actions.insert({
              actionType: 'moveCardToTop',
              listTitle: '*',
              boardId,
              desc,
            });
            Rules.insert({
              title: ruleName,
              triggerId,
              actionId,
              boardId,
            });
          }
          if (actionSelected === 'bottom') {
            const triggerId = Triggers.insert(trigger);
            const actionId = Actions.insert({
              actionType: 'moveCardToBottom',
              listTitle: '*',
              boardId,
              desc,
            });
            Rules.insert({
              title: ruleName,
              triggerId,
              actionId,
              boardId,
            });
          }
        },
        'click .js-add-arch-action'(event) {
          const desc = Utils.getTriggerActionDesc(event, this);
          const boardId = Session.get('currentBoard');
          const ruleName = this.data().ruleName.get();
          const trigger = this.data().triggerVar.get();
          const actionSelected = this.find('#arch-action').value;
          if (actionSelected === 'archive') {
            const triggerId = Triggers.insert(trigger);
            const actionId = Actions.insert({
              actionType: 'archive',
              boardId,
              desc,
            });
            Rules.insert({
              title: ruleName,
              triggerId,
              actionId,
              boardId,
            });
          }
          if (actionSelected === 'unarchive') {
            const triggerId = Triggers.insert(trigger);
            const actionId = Actions.insert({
              actionType: 'unarchive',
              boardId,
              desc,
            });
            Rules.insert({
              title: ruleName,
              triggerId,
              actionId,
              boardId,
            });
          }
        },
      },
    ];
  },
}).register('boardActions');
/* eslint-no-undef */


text:
(function(define, describe) {
    "use strict";

    var dependencies = [
        'bootstrap'
    ];

    define(dependencies, function(AppBootstrap) {

        describe('MenuDropdown directive', function() {
            var item1Called, title = 'Dropdown menu';

            // Instantiate directive.
            var element = '<menu-dropdown menu-open="right" title="' + title + '" menu-items="menuItems"></menu-dropdown>';
            AppTestUtils.appTestSetup.call(this, element, function(scope) {
                scope.menuItems = [
                    {
                        callback: function() {
                            item1Called = true;
                        },
                        text: 'The first choice!'
                    },
                    {
                        divider: true
                    },
                    {
                        link: '#!/home',
                        text: 'This is a link'
                        }
                ];
            });

            afterEach(function() {
                this.$scope.$destroy();
            });

            it('initializes correctly', function() {
                var element = this.$element.find('ul > li');
                expect(element.length).toEqual(this.$scope.menuItems.length);
                expect($(element[2]).find('a').prop('href')).toContain(this.$scope.menuItems[2].link);
                expect($(element[2]).find('a').html()).toEqual(this.$scope.menuItems[2].text);
                expect(this.$element.find('button').text()).toContain(title);
            });

            it('opens menu selection', function() {

                var element = this.$element.find('button');
                var actionElement = this.$element.find('ul > li > a');
                var scope = $(actionElement[0]).scope();

                // Menu is not open after element has been creation
                expect(element[0].outerHTML).toContain('aria-expanded="false"');

                // Menu is open when clicked
                element.click();
                this.$scope.$digest();
                expect(element[0].outerHTML).toContain('aria-expanded="true"');
                expect(scope.status.isopen).toBeTruthy();

                // Menu is aligned on the right side
                expect(this.$element.find('.dropdown-menu').attr('class')).toContain('dropdown-menu-right');

                // Action is called when clicked
                $(actionElement[0]).click();
                this.$scope.$digest();
                expect(item1Called).toBeTruthy();

                // Programmatically closing menu
                scope.toggleDropdown({
                    preventDefault: function() {},
                    stopPropagation: function() {}
                });
                this.$scope.$digest();
                expect(scope.status.isopen).toBeFalsy();
                expect(element[0].outerHTML).toContain('aria-expanded="false"');
            });
        });
    });

})(define, describe);


text:
import math
import sys
import os
import numpy as np
import paddle
import paddle.fluid as fluid
import paddle.fluid.framework as framework
import paddle.fluid.layers as layers
import paddle.fluid.nets as nets
from paddle.fluid.executor import Executor
from paddle.fluid.optimizer import SGDOptimizer

IS_SPARSE = True
USE_GPU = False
BATCH_SIZE = 256

def get_usr_combined_features():
    # FIXME(dzh) : old API integer_value(10) may has range check.
    # currently we don't have user configurated check.

    USR_DICT_SIZE = paddle.dataset.movielens.max_user_id() + 1

    uid = layers.data(name='user_id', shape=[1], dtype='int64')

    usr_emb = layers.embedding(
        input=uid,
        dtype='float32',
        size=[USR_DICT_SIZE, 32],
        param_attr='user_table',
        is_sparse=IS_SPARSE)

    usr_fc = layers.fc(input=usr_emb, size=32)

    USR_GENDER_DICT_SIZE = 2

    usr_gender_id = layers.data(name='gender_id', shape=[1], dtype='int64')

    usr_gender_emb = layers.embedding(
        input=usr_gender_id,
        size=[USR_GENDER_DICT_SIZE, 16],
        param_attr='gender_table',
        is_sparse=IS_SPARSE)

    usr_gender_fc = layers.fc(input=usr_gender_emb, size=16)

    USR_AGE_DICT_SIZE = len(paddle.dataset.movielens.age_table)
    usr_age_id = layers.data(name='age_id', shape=[1], dtype="int64")

    usr_age_emb = layers.embedding(
        input=usr_age_id,
        size=[USR_AGE_DICT_SIZE, 16],
        is_sparse=IS_SPARSE,
        param_attr='age_table')

    usr_age_fc = layers.fc(input=usr_age_emb, size=16)

    USR_JOB_DICT_SIZE = paddle.dataset.movielens.max_job_id() + 1
    usr_job_id = layers.data(name='job_id', shape=[1], dtype="int64")

    usr_job_emb = layers.embedding(
        input=usr_job_id,
        size=[USR_JOB_DICT_SIZE, 16],
        param_attr='job_table',
        is_sparse=IS_SPARSE)

    usr_job_fc = layers.fc(input=usr_job_emb, size=16)

    concat_embed = layers.concat(
        input=[usr_fc, usr_gender_fc, usr_age_fc, usr_job_fc], axis=1)

    usr_combined_features = layers.fc(input=concat_embed, size=200, act="tanh")

    return usr_combined_features

def get_mov_combined_features():

    MOV_DICT_SIZE = paddle.dataset.movielens.max_movie_id() + 1

    mov_id = layers.data(name='movie_id', shape=[1], dtype='int64')

    mov_emb = layers.embedding(
        input=mov_id,
        dtype='float32',
        size=[MOV_DICT_SIZE, 32],
        param_attr='movie_table',
        is_sparse=IS_SPARSE)

    mov_fc = layers.fc(input=mov_emb, size=32)

    CATEGORY_DICT_SIZE = len(paddle.dataset.movielens.movie_categories())

    category_id = layers.data(
        name='category_id', shape=[1], dtype='int64', lod_level=1)

    mov_categories_emb = layers.embedding(
        input=category_id, size=[CATEGORY_DICT_SIZE, 32], is_sparse=IS_SPARSE)

    mov_categories_hidden = layers.sequence_pool(
        input=mov_categories_emb, pool_type="sum")

    MOV_TITLE_DICT_SIZE = len(paddle.dataset.movielens.get_movie_title_dict())

    mov_title_id = layers.data(
        name='movie_title', shape=[1], dtype='int64', lod_level=1)

    mov_title_emb = layers.embedding(
        input=mov_title_id, size=[MOV_TITLE_DICT_SIZE, 32], is_sparse=IS_SPARSE)

    mov_title_conv = nets.sequence_conv_pool(
        input=mov_title_emb,
        num_filters=32,
        filter_size=3,
        act="tanh",
        pool_type="sum")

    concat_embed = layers.concat(
        input=[mov_fc, mov_categories_hidden, mov_title_conv], axis=1)

    # FIXME(dzh) : need tanh operator
    mov_combined_features = layers.fc(input=concat_embed, size=200, act="tanh")

    return mov_combined_features

def model():
    usr_combined_features = get_usr_combined_features()
    mov_combined_features = get_mov_combined_features()

    # need cos sim
    inference = layers.cos_sim(X=usr_combined_features, Y=mov_combined_features)
    scale_infer = layers.scale(x=inference, scale=5.0)

    label = layers.data(name='score', shape=[1], dtype='float32')
    square_cost = layers.square_error_cost(input=scale_infer, label=label)
    avg_cost = layers.mean(square_cost)

    return scale_infer, avg_cost

def train(use_cuda, save_dirname, is_local=True):
    scale_infer, avg_cost = model()

    # test program
    test_program = fluid.default_main_program().clone(for_test=True)

    sgd_optimizer = SGDOptimizer(learning_rate=0.2)
    sgd_optimizer.minimize(avg_cost)

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()

    exe = Executor(place)

    train_reader = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.movielens.train(), buf_size=8192),
        batch_size=BATCH_SIZE)
    test_reader = paddle.batch(
        paddle.dataset.movielens.test(), batch_size=BATCH_SIZE)

    feeding = {
        'user_id': 0,
        'gender_id': 1,
        'age_id': 2,
        'job_id': 3,
        'movie_id': 4,
        'category_id': 5,
        'movie_title': 6,
        'score': 7
    }

    def func_feed(feeding, data):
        feed_tensors = {}
        for (key, idx) in feeding.iteritems():
            tensor = fluid.LoDTensor()
            if key != "category_id" and key != "movie_title":
                if key == "score":
                    numpy_data = np.array(map(lambda x: x[idx], data)).astype(
                        "float32")
                else:
                    numpy_data = np.array(map(lambda x: x[idx], data)).astype(
                        "int64")
            else:
                numpy_data = map(lambda x: np.array(x[idx]).astype("int64"),
                                 data)
                lod_info = [len(item) for item in numpy_data]
                offset = 0
                lod = [offset]
                for item in lod_info:
                    offset += item
                    lod.append(offset)
                numpy_data = np.concatenate(numpy_data, axis=0)
                tensor.set_lod([lod])

            numpy_data = numpy_data.reshape([numpy_data.shape[0], 1])
            tensor.set(numpy_data, place)
            feed_tensors[key] = tensor
        return feed_tensors

    def train_loop(main_program):
        exe.run(framework.default_startup_program())

        PASS_NUM = 100
        for pass_id in range(PASS_NUM):
            for batch_id, data in enumerate(train_reader()):
                # train a mini-batch
                outs = exe.run(program=main_program,
                               feed=func_feed(feeding, data),
                               fetch_list=[avg_cost])
                out = np.array(outs[0])
                if (batch_id + 1) % 10 == 0:
                    avg_cost_set = []
                    for test_data in test_reader():
                        avg_cost_np = exe.run(
                            program=test_program,
                            feed=func_feed(feeding, test_data),
                            fetch_list=[avg_cost])
                        avg_cost_set.append(avg_cost_np[0])
                        break  # test only 1 segment for speeding up CI

                    # get test avg_cost
                    test_avg_cost = np.array(avg_cost_set).mean()
                    if test_avg_cost < 6.0:
                        # if avg_cost less than 6.0, we think our code is good.
                        if save_dirname is not None:
                            fluid.io.save_inference_model(save_dirname, [
                                "user_id", "gender_id", "age_id", "job_id",
                                "movie_id", "category_id", "movie_title"
                            ], [scale_infer], exe)
                        return

                if math.isnan(float(out[0])):
                    sys.exit("got NaN loss, training failed.")

    if is_local:
        train_loop(fluid.default_main_program())
    else:
        port = os.getenv("PADDLE_INIT_PORT", "6174")
        pserver_ips = os.getenv("PADDLE_INIT_PSERVERS")  # ip,ip...
        eplist = []
        for ip in pserver_ips.split(","):
            eplist.append(':'.join([ip, port]))
        pserver_endpoints = ",".join(eplist)  # ip:port,ip:port...
        trainers = int(os.getenv("TRAINERS"))
        current_endpoint = os.getenv("POD_IP") + ":" + port
        trainer_id = int(os.getenv("PADDLE_INIT_TRAINER_ID"))
        training_role = os.getenv("TRAINING_ROLE", "TRAINER")
        t = fluid.DistributeTranspiler()
        t.transpile(trainer_id, pservers=pserver_endpoints, trainers=trainers)
        if training_role == "PSERVER":
            pserver_prog = t.get_pserver_program(current_endpoint)
            pserver_startup = t.get_startup_program(current_endpoint,
                                                    pserver_prog)
            exe.run(pserver_startup)
            exe.run(pserver_prog)
        elif training_role == "TRAINER":
            train_loop(t.get_trainer_program())

def infer(use_cuda, save_dirname=None):
    if save_dirname is None:
        return

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)

    def create_lod_tensor(data, lod=None):
        tensor = fluid.LoDTensor()
        if lod is None:
            # Tensor, the shape is [batch_size, 1]
            index = 0
            lod_0 = [index]
            for l in range(len(data)):
                index += 1
                lod_0.append(index)
            lod = [lod_0]
        tensor.set_lod(lod)

        flattened_data = np.concatenate(data, axis=0).astype("int64")
        flattened_data = flattened_data.reshape([len(flattened_data), 1])
        tensor.set(flattened_data, place)
        return tensor

    inference_scope = fluid.core.Scope()
    with fluid.scope_guard(inference_scope):
        # Use fluid.io.load_inference_model to obtain the inference program desc,
        # the feed_target_names (the names of variables that will be feeded
        # data using feed operators), and the fetch_targets (variables that
        # we want to obtain data from using fetch operators).
        [inference_program, feed_target_names,
         fetch_targets] = fluid.io.load_inference_model(save_dirname, exe)

        # Use the first data from paddle.dataset.movielens.test() as input
        assert feed_target_names[0] == "user_id"
        user_id = create_lod_tensor([[1]])

        assert feed_target_names[1] == "gender_id"
        gender_id = create_lod_tensor([[1]])

        assert feed_target_names[2] == "age_id"
        age_id = create_lod_tensor([[0]])

        assert feed_target_names[3] == "job_id"
        job_id = create_lod_tensor([[10]])

        assert feed_target_names[4] == "movie_id"
        movie_id = create_lod_tensor([[783]])

        assert feed_target_names[5] == "category_id"
        category_id = create_lod_tensor([[10], [8], [9]], [[0, 3]])

        assert feed_target_names[6] == "movie_title"
        movie_title = create_lod_tensor([[1069], [4140], [2923], [710], [988]],
                                        [[0, 5]])

        # Construct feed as a dictionary of {feed_target_name: feed_target_data}
        # and results will contain a list of data corresponding to fetch_targets.
        results = exe.run(inference_program,
                          feed={
                              feed_target_names[0]: user_id,
                              feed_target_names[1]: gender_id,
                              feed_target_names[2]: age_id,
                              feed_target_names[3]: job_id,
                              feed_target_names[4]: movie_id,
                              feed_target_names[5]: category_id,
                              feed_target_names[6]: movie_title
                          },
                          fetch_list=fetch_targets,
                          return_numpy=False)
        print("inferred score: ", np.array(results[0]))

def main(use_cuda):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return

    # Directory for saving the inference model
    save_dirname = "recommender_system.inference.model"

    train(use_cuda, save_dirname)
    infer(use_cuda, save_dirname)

if __name__ == '__main__':
    main(USE_GPU)


text:
"""
 Copyright 2012, The MITRE Corporation::

                              NOTICE
    This software/technical data was produced for the U.S. Government
    under Prime Contract No. NASA-03001 and JPL Contract No. 1295026
      and is subject to FAR 52.227-14 (6/87) Rights in Data General,
        and Article GP-51, Rights in Data  General, respectively.
       This software is publicly released under MITRE case #12-3054
"""

# scapy.contrib.description = Self-Delimiting Numeric Values (SDNV)
# scapy.contrib.status = library

from scapy.fields import Field, FieldLenField, LenField
from scapy.compat import raw

# SDNV definitions

class SDNVValueError(Exception):
    def __init__(self, maxValue):
        self.maxValue = maxValue

class SDNV:
    def __init__(self, maxValue=2**32 - 1):
        self.maxValue = maxValue
        return

    def setMax(self, maxValue):
        self.maxValue = maxValue

    def getMax(self):
        return self.maxValue

    def encode(self, number):
        if number > self.maxValue:
            raise SDNVValueError(self.maxValue)

        foo = bytearray()
        foo.append(number & 0x7F)
        number = number >> 7

        while (number > 0):
            thisByte = number & 0x7F
            thisByte |= 0x80
            number = number >> 7
            temp = bytearray()
            temp.append(thisByte)
            foo = temp + foo

        return(foo)

    def decode(self, ba, offset):
        number = 0
        numBytes = 1

        b = ba[offset]
        number = (b & 0x7F)
        while (b & 0x80 == 0x80):
            number = number << 7
            if (number > self.maxValue):
                raise SDNVValueError(self.maxValue)
            b = ba[offset + numBytes]
            number += (b & 0x7F)
            numBytes += 1
        if (number > self.maxValue):
            raise SDNVValueError(self.maxValue)
        return(number, numBytes)

SDNVUtil = SDNV()

class SDNV2(Field):
    """ SDNV2 field """

    def addfield(self, pkt, s, val):
        return s + raw(SDNVUtil.encode(val))

    def getfield(self, pkt, s):
        b = bytearray(s)
        val, len = SDNVUtil.decode(b, 0)
        return s[len:], val

class SDNV2FieldLenField(FieldLenField, SDNV2):
    def addfield(self, pkt, s, val):
        return s + raw(SDNVUtil.encode(FieldLenField.i2m(self, pkt, val)))

class SDNV2LenField(LenField, SDNV2):
    def addfield(self, pkt, s, val):
        return s + raw(SDNVUtil.encode(LenField.i2m(self, pkt, val)))


text:
from reportlab.lib.units import inch
from common import Barcode
import string

_fim_patterns = {
    'A' : "||  |  ||",
    'B' : "| || || |",
    'C' : "|| | | ||",
    'D' : "||| | |||",
    # XXX There is an E.
    # The below has been seen, but dunno if it is E or not:
    # 'E' : '|||| ||||'
}

_postnet_patterns = {
    '1' : "...||",    '2' : "..|.|",    '3' : "..||.",    '4' : ".|..|",
    '5' : ".|.|.",    '6' : ".||..",    '7' : "|...|",    '8' : "|..|.",
    '9' : "|.|..",    '0' : "||...",    'S' : "|",
}

class FIM(Barcode):
    """
    FIM (Facing ID Marks) encode only one letter.
    There are currently four defined:

    A   Courtesy reply mail with pre-printed POSTNET
    B   Business reply mail without pre-printed POSTNET
    C   Business reply mail with pre-printed POSTNET
    D   OCR Readable mail without pre-printed POSTNET

    Options that may be passed to constructor:

        value (single character string from the set A - D. required.):
            The value to encode.

        quiet (bool, default 0):
            Whether to include quiet zones in the symbol.

    The following may also be passed, but doing so will generate nonstandard
    symbols which should not be used. This is mainly documented here to
    show the defaults:

        barHeight (float, default 5/8 inch):
            Height of the code. This might legitimately be overriden to make
            a taller symbol that will 'bleed' off the edge of the paper,
            leaving 5/8 inch remaining.

        lquiet (float, default 1/4 inch):
            Quiet zone size to left of code, if quiet is true.
            Default is the greater of .25 inch, or .15 times the symbol's
            length.

        rquiet (float, default 15/32 inch):
            Quiet zone size to right left of code, if quiet is true.

    Sources of information on FIM:

    USPS Publication 25, A Guide to Business Mail Preparation
    http://new.usps.com/cpim/ftp/pubs/pub25.pdf
    """
    barWidth = inch * (1.0/32.0)
    spaceWidth = inch * (1.0/16.0)
    barHeight = inch * (5.0/8.0)
    rquiet = inch * (0.25)
    lquiet = inch * (15.0/32.0)
    quiet = 0
    def __init__(self, value='', **args):
        for (k, v) in args.items():
            setattr(self, k, v)

        Barcode.__init__(self, value)

    def validate(self):
        self.valid = 1
        self.validated = ''
        for c in self.value:
            if c in string.whitespace:
                continue
            elif c in "abcdABCD":
                self.validated = self.validated + string.upper(c)
            else:
                self.valid = 0

        if len(self.validated) != 1:
            raise ValueError, "Input must be exactly one character"

        return self.validated

    def decompose(self):
        self.decomposed = ''
        for c in self.encoded:
            self.decomposed = self.decomposed + _fim_patterns[c]

        return self.decomposed

    def computeSize(self):
        self._width = (len(self.decomposed) - 1) * self.spaceWidth + self.barWidth
        if self.quiet:
            self._width += self.lquiet + self.rquiet
        self._height = self.barHeight

    def draw(self):
        self._calculate()
        left = self.quiet and self.lquiet or 0
        for c in self.decomposed:
            if c == '|':
                self.rect(left, 0.0, self.barWidth, self.barHeight)
            left += self.spaceWidth
        self.drawHumanReadable()

    def _humanText(self):
        return self.value

class POSTNET(Barcode):
    """
    POSTNET is used in the US to encode "zip codes" (postal codes) on
    mail. It can encode 5, 9, or 11 digit codes. I've read that it's
    pointless to do 5 digits, since USPS will just have to re-print
    them with 9 or 11 digits.

    Sources of information on POSTNET:

    USPS Publication 25, A Guide to Business Mail Preparation
    http://new.usps.com/cpim/ftp/pubs/pub25.pdf
    """
    quiet = 0
    shortHeight = inch * 0.050
    barHeight = inch * 0.125
    barWidth = inch * 0.018
    spaceWidth = inch * 0.0275
    def __init__(self, value='', **args):

        for (k, v) in args.items():
            setattr(self, k, v)

        Barcode.__init__(self, value)

    def validate(self):
        self.validated = ''
        self.valid = 1
        count = 0
        for c in self.value:
            if c in (string.whitespace + '-'):
                pass
            elif c in string.digits:
                count = count + 1
                if count == 6:
                    self.validated = self.validated + '-'
                self.validated = self.validated + c
            else:
                self.valid = 0

        if len(self.validated) not in [5, 10, 12]:
            self.valid = 0

        return self.validated

    def encode(self):
        self.encoded = "S"
        check = 0
        for c in self.validated:
            if c in string.digits:
                self.encoded = self.encoded + c
                check = check + string.atoi(c)
            elif c == '-':
                pass
            else:
                raise ValueError, "Invalid character in input"
        check = (10 - check) % 10
        self.encoded = self.encoded + `check` + 'S'
        return self.encoded

    def decompose(self):
        self.decomposed = ''
        for c in self.encoded:
            self.decomposed = self.decomposed + _postnet_patterns[c]
        return self.decomposed

    def computeSize(self):
        self._width = len(self.decomposed) * self.barWidth + (len(self.decomposed) - 1) * self.spaceWidth
        self._height = self.barHeight

    def draw(self):
        self._calculate()
        sdown = self.barHeight - self.shortHeight
        left = 0

        for c in self.decomposed:
            if c == '.':
                h = self.shortHeight
            else:
                h = self.barHeight
            self.rect(left, 0.0, self.barWidth, h)
            left = left + self.barWidth + self.spaceWidth
        self.drawHumanReadable()

    def _humanText(self):
        return self.encoded[1:-1]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Bjd.Utils;
using Bjd.Threading;
using System.Threading;
using System.Threading.Tasks;
using Bjd.Memory;

namespace Bjd.Logs
{
    public class LogInteractiveConsoleService : IDisposable, ILogService
    {
        public event EventHandler Appended;

        private const int MaxRows = 100;
        private string[] bufferArray = new string[MaxRows];
        private int currentIndex = -1;
        private bool isDisposed = false;

        public bool DetailEnabled { get; set; } = false;
        public bool InformationEnabled { get; set; } = false;
        public bool WarningEnabled { get; set; } = false;

        public LogInteractiveConsoleService()
        {
        }

        public void Dispose()
        {
            if (isDisposed) return;
            isDisposed = true;
        }

        protected void OnAppended()
        {
            if (Appended == null) return;
            Appended(this, EventArgs.Empty);
        }

        private void Write(string message)
        {
            var idx = Interlocked.Increment(ref currentIndex);
            idx = idx % MaxRows;
            Interlocked.CompareExchange(ref currentIndex, idx, MaxRows + idx);
            bufferArray[idx] = message;
            OnAppended();
        }

        public void Append(CharsData message, LogMessage log)
        {
            //if (!DetailEnabled && log.LogKind == LogKind.Detail) return;
            //Write(message.ToString());
        }

        public void TraceAppend(CharsData message, LogMessage log)
        {
            if (!DetailEnabled && log.LogKind == LogKind.Detail) return;
            Write(message.ToString());
        }

        public void WriteLine(CharsData message)
        {
            Write(message.ToString());
        }

        public void TraceInformation(CharsData message)
        {
            if (!InformationEnabled) return;
            Write(message.ToString());
        }

        public void TraceWarning(CharsData message)
        {
            if (!WarningEnabled) return;
            Write(message.ToString());
        }

        public void TraceError(CharsData message)
        {
            Write(message.ToString());
        }

        public string[] GetBuffer(int row)
        {
            var cIndex = currentIndex;
            string[] result = new string[row];
            for (var i = 0; i < row; i++ )
            {
                var idx = (cIndex + MaxRows - i) % MaxRows;
                result[i] = bufferArray[idx];
            }
            return result;
        }

    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template find</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Compute">
<link rel="up" href="../../boost_compute/reference.html#header.boost.compute.algorithm.find_hpp" title="Header <boost/compute/algorithm/find.hpp>">
<link rel="prev" href="fill_n.html" title="Function template fill_n">
<link rel="next" href="find_end.html" title="Function template find_end">

Home
Libraries
People
FAQ
More

Function template find

boost::compute::find

Synopsis

// In header: <boost/compute/algorithm/find.hpp>

template<typename InputIterator, typename T>
  InputIterator
  find(InputIterator first, InputIterator last, const T & value,
       command_queue & queue = system::default_queue());

Description

Returns an iterator pointing to the first element in the range [first, last) that equals value.

Copyright © 2013, 2014 Kyle Lutz

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
class Test_Component : public QObject
{
    Q_OBJECT

private slots:
    void test_isNested_data();
    void test_isNested();
};

#endif // TEST_COMPONENT_H


text:
package org.springframework.boot.actuate.autoconfigure.metrics;

import java.time.Duration;

import io.micrometer.core.instrument.Meter.Type;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link ServiceLevelObjectiveBoundary}.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 */
class ServiceLevelObjectiveBoundaryTests {

	@Test
	void getValueForTimerWhenFromLongShouldReturnMsToNanosValue() {
		ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf(123L);
		assertThat(slo.getValue(Type.TIMER)).isEqualTo(123000000);
	}

	@Test
	void getValueForTimerWhenFromNumberStringShouldMsToNanosValue() {
		ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf("123");
		assertThat(slo.getValue(Type.TIMER)).isEqualTo(123000000);
	}

	@Test
	void getValueForTimerWhenFromMillisecondDurationStringShouldReturnDurationNanos() {
		ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf("123ms");
		assertThat(slo.getValue(Type.TIMER)).isEqualTo(123000000);
	}

	@Test
	void getValueForTimerWhenFromDaysDurationStringShouldReturnDurationNanos() {
		ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf("1d");
		assertThat(slo.getValue(Type.TIMER)).isEqualTo(Duration.ofDays(1).toNanos());
	}

	@Test
	void getValueForDistributionSummaryWhenFromDoubleShouldReturnDoubleValue() {
		ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf(123.42);
		assertThat(slo.getValue(Type.DISTRIBUTION_SUMMARY)).isEqualTo(123.42);
	}

	@Test
	void getValueForDistributionSummaryWhenFromStringShouldReturnDoubleValue() {
		ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf("123.42");
		assertThat(slo.getValue(Type.DISTRIBUTION_SUMMARY)).isEqualTo(123.42);
	}

	@Test
	void getValueForDistributionSummaryWhenFromDurationShouldReturnNull() {
		ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf("123ms");
		assertThat(slo.getValue(Type.DISTRIBUTION_SUMMARY)).isNull();
	}

}


text:
#import <IMCore/IMHandle.h>

@interface IMHandle (iMessageLogging)
- (void)_sendRemoteLogDumpRequest;
- (void)_sendRemoteLogDumpRequest:(id)arg1;
@end


text:
<?php

class Google_Service_GameServices_ListRealmsResponse extends Google_Collection
{
  protected $collection_key = 'unreachable';
  public $nextPageToken;
  protected $realmsType = 'Google_Service_GameServices_Realm';
  protected $realmsDataType = 'array';
  public $unreachable;

  public function setNextPageToken($nextPageToken)
  {
    $this->nextPageToken = $nextPageToken;
  }
  public function getNextPageToken()
  {
    return $this->nextPageToken;
  }
  /**
   * @param Google_Service_GameServices_Realm
   */
  public function setRealms($realms)
  {
    $this->realms = $realms;
  }
  /**
   * @return Google_Service_GameServices_Realm
   */
  public function getRealms()
  {
    return $this->realms;
  }
  public function setUnreachable($unreachable)
  {
    $this->unreachable = $unreachable;
  }
  public function getUnreachable()
  {
    return $this->unreachable;
  }
}


text:
namespace safe_browsing {

namespace {

const void* const kPingKey = &kPingKey;

class DownloadFeedbackPings : public base::SupportsUserData::Data {
 public:
  DownloadFeedbackPings(const std::string& ping_request,
                        const std::string& ping_response);

  // Stores the ping data in the given |download|.
  static void CreateForDownload(content::DownloadItem* download,
                                const std::string& ping_request,
                                const std::string& ping_response);

  // Returns the DownloadFeedbackPings object associated with |download|.  May
  // return NULL.
  static DownloadFeedbackPings* FromDownload(
      const content::DownloadItem& download);

  const std::string& ping_request() const {
    return ping_request_;
  }

  const std::string& ping_response() const {
    return ping_response_;
  }

 private:
  std::string ping_request_;
  std::string ping_response_;
};

DownloadFeedbackPings::DownloadFeedbackPings(const std::string& ping_request,
                                             const std::string& ping_response)
    : ping_request_(ping_request),
      ping_response_(ping_response) {
}

// static
void DownloadFeedbackPings::CreateForDownload(
    content::DownloadItem* download,
    const std::string& ping_request,
    const std::string& ping_response) {
  DownloadFeedbackPings* pings = new DownloadFeedbackPings(ping_request,
                                                           ping_response);
  download->SetUserData(kPingKey, pings);
}

// static
DownloadFeedbackPings* DownloadFeedbackPings::FromDownload(
    const content::DownloadItem& download) {
  return static_cast<DownloadFeedbackPings*>(download.GetUserData(kPingKey));
}

}  // namespace

DownloadFeedbackService::DownloadFeedbackService(
    net::URLRequestContextGetter* request_context_getter,
    base::TaskRunner* file_task_runner)
    : request_context_getter_(request_context_getter),
      file_task_runner_(file_task_runner),
      weak_ptr_factory_(this) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}

DownloadFeedbackService::~DownloadFeedbackService() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}

// static
void DownloadFeedbackService::MaybeStorePingsForDownload(
    DownloadProtectionService::DownloadCheckResult result,
    content::DownloadItem* download,
    const std::string& ping,
    const std::string& response) {
  switch (result) {
    case DownloadProtectionService::UNKNOWN:
    case DownloadProtectionService::SAFE:
    case DownloadProtectionService::DANGEROUS:
      return;
    case DownloadProtectionService::UNCOMMON:
    case DownloadProtectionService::DANGEROUS_HOST:
    case DownloadProtectionService::POTENTIALLY_UNWANTED:
      break;  // Fall through.
  }
  UMA_HISTOGRAM_COUNTS("SBDownloadFeedback.SizeEligibleKB",
                       download->GetReceivedBytes() / 1024);
  if (download->GetReceivedBytes() > DownloadFeedback::kMaxUploadSize)
    return;

  DownloadFeedbackPings::CreateForDownload(download, ping, response);
}

// static
bool DownloadFeedbackService::IsEnabledForDownload(
    const content::DownloadItem& download) {
  return !!DownloadFeedbackPings::FromDownload(download);
}

// static
bool DownloadFeedbackService::GetPingsForDownloadForTesting(
    const content::DownloadItem& download,
    std::string* ping,
    std::string* response) {
  DownloadFeedbackPings* pings = DownloadFeedbackPings::FromDownload(download);
  if (!pings)
    return false;

  *ping = pings->ping_request();
  *response = pings->ping_response();
  return true;
}

// static
void DownloadFeedbackService::RecordEligibleDownloadShown(
    content::DownloadDangerType danger_type) {
  UMA_HISTOGRAM_ENUMERATION("SBDownloadFeedback.Eligible",
                            danger_type,
                            content::DOWNLOAD_DANGER_TYPE_MAX);
}

void DownloadFeedbackService::BeginFeedbackForDownload(
    content::DownloadItem* download,
    DownloadCommands::Command download_command) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  UMA_HISTOGRAM_ENUMERATION("SBDownloadFeedback.Activations",
                            download->GetDangerType(),
                            content::DOWNLOAD_DANGER_TYPE_MAX);

  DownloadFeedbackPings* pings = DownloadFeedbackPings::FromDownload(*download);
  DCHECK(pings);

  download->StealDangerousDownload(
      download_command == DownloadCommands::DISCARD,
      base::Bind(&DownloadFeedbackService::BeginFeedbackOrDeleteFile,
                 file_task_runner_, weak_ptr_factory_.GetWeakPtr(),
                 pings->ping_request(), pings->ping_response()));
  if (download_command == DownloadCommands::KEEP)
    DownloadCommands(download).ExecuteCommand(download_command);
}

// static
void DownloadFeedbackService::BeginFeedbackOrDeleteFile(
    const scoped_refptr<base::TaskRunner>& file_task_runner,
    const base::WeakPtr<DownloadFeedbackService>& service,
    const std::string& ping_request,
    const std::string& ping_response,
    const base::FilePath& path) {
  if (service) {
    bool is_path_empty = path.empty();
    UMA_HISTOGRAM_BOOLEAN("SBDownloadFeedback.EmptyFilePathFailure",
                          is_path_empty);
    if (is_path_empty)
      return;
    service->BeginFeedback(ping_request, ping_response, path);
  } else {
    base::FileUtilProxy::DeleteFile(file_task_runner.get(),
                                    path,
                                    false,
                                    base::FileUtilProxy::StatusCallback());
  }
}

void DownloadFeedbackService::StartPendingFeedback() {
  DCHECK(!active_feedback_.empty());
  active_feedback_.front()->Start(base::Bind(
      &DownloadFeedbackService::FeedbackComplete, base::Unretained(this)));
}

void DownloadFeedbackService::BeginFeedback(const std::string& ping_request,
                                            const std::string& ping_response,
                                            const base::FilePath& path) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  std::unique_ptr<DownloadFeedback> feedback(DownloadFeedback::Create(
      request_context_getter_.get(), file_task_runner_.get(), path,
      ping_request, ping_response));
  active_feedback_.push(std::move(feedback));
  UMA_HISTOGRAM_COUNTS_100("SBDownloadFeedback.ActiveFeedbacks",
                           active_feedback_.size());

  if (active_feedback_.size() == 1)
    StartPendingFeedback();
}

void DownloadFeedbackService::FeedbackComplete() {
  DVLOG(1) << __func__;
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK(!active_feedback_.empty());
  active_feedback_.pop();
  if (!active_feedback_.empty())
    StartPendingFeedback();
}

}  // namespace safe_browsing


text:
 //TODO: 1) Add a on page load function to associate this function with Onchange event for active. 2) Ensure if tickler is inactive we hide the date selector.
 //document.getElementById('document.newMaintainableObject.active').onchange = inactivateTickler1;
 function inactivateTickler(event)
 {
	var activeFieldName;
	if(event == null)
	{
		activeFieldName = document.getElementById('document.newMaintainableObject.active');
	}
	else
	{
		if(event.srcElement)
		{
			activeFieldName = event.srcElement;
		}
		else
		{
			activeFieldName = event.target;
		}
	}

	var elPrefix = findElPrefix( activeFieldName.name );

	var terminationDate = document.getElementById(elPrefix + '.terminationDate');
	var terminationDatePicker = document.getElementById(elPrefix + '.terminationDate_datepicker');

	var activeChecked = DWRUtil.getValue( activeFieldName.name );

	if(activeChecked)
	{
		terminationDate.readOnly = false;
		terminationDatePicker.style.visibility = 'visible';
	}
	else
	{
		terminationDate.readOnly = true;
		terminationDatePicker.style.visibility = 'hidden';

		var dwrReply = {
			callback:function(data) {
			if ( data != null) {
				setRecipientValue( terminationDate.name, data );
			} else {
				setRecipientValue( terminationDate.name, wrapError( "Error obtaining System Date" ), true );
			} },
			errorHandler:function( errorMessage ) {
				setRecipientValue( terminationDate.name, wrapError( "Error obtaining System Date" ), true );
			}
		};
		KEMService.getCurrentSystemProcessDateFormated(dwrReply);

	}
}

  function registerActiveFlagOnclick()
 {
	  inactivateTickler();
	  var activeFlagName = 'document.newMaintainableObject.active';
	  registerBrowserEvent(activeFlagName,'click',inactivateTickler);
 }

  registerTicklerEvents();

  function registerTicklerEvents()
  {
	  registerBrowserEvent('window','load',registerActiveFlagOnclick);
  }

  function registerBrowserEvent(elementName,eventName,functionName)
  {
	  var element;

	  if(elementName == 'window')
	  {
		  element = window;
	  }
	  else
	  {
		  element =  document.getElementById(elementName);
	  }

	  //Register on Page load  Event for active flag.
	  if(window.addEventListener)
	  {
		  //This is for Gecko(Mozilla) engines
		  element.addEventListener(eventName,functionName,false);
	  }
	  else
	  {
		//This is for Trident(IE) engine
		  element.attachEvent('on' + eventName ,functionName);
	  }
  }


text:
Changelog
=========

3.1 IN DEVELOPMENT
------------------

* Added support for Wagtail 2.10 (no code changes necessary)

3.0.2 (18.06.2020)
------------------

* Added support for Wagtail 2.9 (no code changes necessary) (Sekani Tembo).
* Added compatibility with Django Sites Framework (Sekani Tembo).
* Various documentation updates.

3.0.1 (08.02.2020)
------------------

* Added support for Django 3.0 and Wagtail 2.8 (thanks to Arkadiusz Michał Ryś).

3.0 (07.11.2019)
----------------

* Always fetch/use specific page data when rendering menus (see release notes for more details).
* Optimised 'derive page from URL' and 'derive section root' logic
* Added support for Django 2.2 (no code changes necessary).
* Added support for Wagtail 2.5 (no code changes necessary).
* Added support for Wagtail 2.6 (no code changes necessary).
* Added support for Wagtail 2.7.
* Added support for Python 3.8.
* Removed support for `get_sub_menu_templates()` methods that do not accept a **level** argument.
* Removed recommendation / automatic integration for `wagtail-condensedinlinepanel`.
* Fix: [#329](https://github.com/rkhleics/wagtailmenus/issues/329), which prevented level-specific template naming from working as specified in the docs.
* Fix: [#323](https://github.com/rkhleics/wagtailmenus/issues/323), which prevented `StreamField` from working properly when creating or editing menus with custom item models.

2.13.1 (21.05.2019)
-------------------

* Fix: [#329](https://github.com/rkhleics/wagtailmenus/issues/329), which prevented level-specific template naming from working as specified in the docs.
* Fix: [#323](https://github.com/rkhleics/wagtailmenus/issues/323), which prevented `StreamField` from working properly when creating or editing menus with custom item models.

2.13 (16.03.2019)
-----------------

* Dropped support for `relative_url()` methods on custom menu item models that do not support a `request` keyword argument.
* Added support for Wagtail 2.4.
* Added support for Wagtail 2.3.
* Added support for Django 2.1.
* Minor documentation updates (OktayAltay).
* Updated `MenuPage.get_repeated_menu_item()` to nullify `sub_menu` on the copy to reduce likelihood of infinite recursion errors.
* Updated `Menu._prime_menu_item()` to set `sub_menu` to None if no new value is being added, to reduce likelihood of infinite recursion errors.
* Updated `SectionMenu.prepare_to_render()` to augment `root_page` with `text`, `href` and `active_class` attributes, so that it no longer has to be done in `SectionMenu.get_context_data()`.
* Updated `AbstractLinkPage.get_sitemap_urls()` signature to match Wagtail 2.2 (Dan Bentley).
* Documentation typo correction and other improvements (DanAtShenTech).
* Fix an issue where the `WAGTAILMENUS_USE_CONDENSEDINLINEPANEL` setting wasn't being respected.

2.12.1 (XX.XX.XXXX)
-------------------

* Fix: [#329](https://github.com/rkhleics/wagtailmenus/issues/329), which prevented level-specific template naming from working as specified in the docs.
* Fix: [#323](https://github.com/rkhleics/wagtailmenus/issues/323), which prevented `StreamField` from working properly when creating or editing menus with custom item models.

2.12 (17.11.2018)
-----------------

* Changed the signature of ``Menu.render_from_tag()`` to better indicate common expected/supported arguments for menus.
* Added a custom ``render_from_tag()`` method for each individual menu class, with a signature that highlights all relevant options, including those specific to that menu type.
* Renamed ``Menu.get_contextual_vals_from_context()`` to ``Menu._create_contextualvals_obj_from_context()`` to give a better
indication of what the method does.
* Renamed ``Menu.get_option_vals_from_options`` to ``Menu._create_optionvals_obj_from_values()`` to give a better indication of what the method does.
* Added the ``Menu.get_from_collected_values()`` method, which replaces ``Menu.get_instance_for_rendering()`` for menu classes that also inherit from ``django.db.models.Model``.
* Added the ``Menu.create_from_collected_values()`` method, which replaces ``Menu.get_instance_for_rendering()`` for menu classes that **do not** inherit from ``django.db.models.Model``.
* Added the ``add_sub_menu_items_inline`` option to all template tags. When ``True``, ``SubMenu`` objects are automatically created and set as an attribute for each menu item (where appropriate), allowing developers to render multi-level menus without having to use the ``{% sub_menu %}`` tag.
* Added the ``WAGTAILMENUS_DEFAULT_ADD_SUB_MENUS_INLINE`` setting to allow developers to change the default ``add_sub_menu_items_inline`` option value for all template tags.
* Fixed a bug in ``Menu.get_common_hook_kwargs()`` where the value of ``self.max_levels`` was being used as the value for ``use_specific`` (instead of ``self.use_specific``).
* Changed the "Rendering setings" (typo) heading in ``panels.menu_settings_panels`` to "Render settings".
* Removed support for the deprecated ``WAGTAILMENUS_CHILDREN_MENU_CLASS_PATH`` setting.
* Removed support for the deprecated ``WAGTAILMENUS_SECTION_MENU_CLASS_PATH`` setting.
* Removed the deprecated ``wagtailmenus.constants`` module.

2.11.1 (10.09.2018)
-------------------

* Fixed an issue with the section menu in the release notes section of the docs.
* Updated tox config to test against Python 3.7 and Wagtail 2.2.
* Updated Travis CI config to deploy to PyPi automatically when commits are tagged appropriately.
* Pinned django-cogwheels dependency to version 0.2 to reduce potential for backwards-incompatibility issues.

2.11.0 (15.07.2018)
-------------------

* Added support for Wagtail version 2.1.
* Dropped support for Wagtail versions 1.10 to 1.13.
* Dropped support for Django versions 1.8 to 1.10.
* Updated trove classifiers in `setup.py` to reflect Django and Wagtail version support.
* Updated `runtests.py` to pass on any unparsed option arguments to Django's test method.
* Updated `runtests.py` to filter out deprecation warnings originating from other apps by default.
* Updated `MenuItem.relative_url()` to accept a `request` parameter (for parity with `wagtail.core.models.Page.relative_url()`), so that it can pass it on to the page method.
* Updated `Menu.prime_menu_items()` to send the current `HttpRequest` to that `MenuItem.relative_url()` and `Page.relative_url()`.
* Updated admin views to utilise `wagtail.admin.messages.validation_error()` for reporting field-specific and non-field errors.
* Removed redundant `install_requires` line from `setup.py`. Compatibility is made clear in other places - there's no need to force a minimum installed Wagtail version here.
* Moved custom `wagtail.contrib.modeladmin` classes out of `wagtailmenus.wagtail_hooks` and into a new `wagtailmenus.modeladmin` module.
* Added the `WAGTAILMENUS_FLAT_MENUS_MODELADMIN_CLASS` setting to allow the default `ModelAdmin` class used to enable flat menu editing in the Wagtail admin area to be swapped out for a custom one.
* Added the `WAGTAILMENUS_MAIN_MENUS_MODELADMIN_CLASS` setting to allow the default `ModelAdmin` class used to enable main menu editing in the Wagtail admin area to be swapped out for a custom one.
* Replaced custom app settings module with `django-cogwheels` and removed a lot of the tests that existed to test its workings.
* Moved remaining app settings tests to `wagtailmenus.conf.tests`.

2.10.1 (XX.XX.XXXX)
-------------------

* Fix: [#329](https://github.com/rkhleics/wagtailmenus/issues/329), which prevented level-specific template naming from working as specified in the docs.

2.10.0 (14.06.2018)
-------------------

* Optimised MenuWithMenuItems.get_top_level_items() and AbstractFlatMenu.get_for_site() to use fewer database queries to render menus.
* Configured `sphinxcontrib.spelling` and used to correct spelling errors in docs.
* Updated testing and documentation dependencies.
* Moved `wagtailmenus.constants` and `wagtailmenus.app_settings` into a new `wagtailmenus.conf` app
* Refactored the app settings module to be DRYer and more generic
* Remove `FLAT_MENU_MODEL_CLASS` and `MAIN_MENU_MODEL_CLASS` app settings attributes in favour of using the app settings module's `get_model()` method to return Django models when needed.
* Deprecated the ``WAGTAILMENUS_CHILDREN_MENU_CLASS_PATH`` setting in favour of using just ``WAGTAILMENUS_CHILDREN_MENU_CLASS``.
* Deprecated the ``WAGTAILMENUS_SECTION_MENU_CLASS_PATH`` setting in favour of using just ``WAGTAILMENUS_SECTION_MENU_CLASS``.
* Added Latin American Spanish translations (thanks to José Luis).

2.9.0 (06.05.2018)
------------------

* Added `WAGTAILMENUS_MAIN_MENUS_EDITABLE_IN_WAGTAILADMIN` setting to the 'Main menu' menu item and underlying management functionality to be removed from the Wagtail admin area (thanks to Michael van de Waeter).
* Added `WAGTAILMENUS_FLAT_MENUS_EDITABLE_IN_WAGTAILADMIN` setting to the 'Flat menus' menu item and underlying management functionality to be removed from the Wagtail admin area (thanks to Michael van de Waeter).
* Added the 'sub_menu_templates' option to menu tags to allow sub menu templates to be specified for each level.
* Updated 'get_template_names()' and 'get_sub_menu_template_names()' methods for each class to search for template paths including the level currently being rendered, allowing developers to define level-specific templates in their templates directory, and have wagtailmenus find and use them automatically.

2.8.0 (29.03.2018)
------------------

* Added improved active class attribution behaviour for menu items that link to custom URLs (Enabled using the `WAGTAILMENUS_CUSTOM_URL_SMART_ACTIVE_CLASSES` setting).
* Deprecated the existing active class attribution behaviour in favour of the above.
* Backend-specific template instances are now always used for rendering.
* Removed `get_template_engine()` method from `wagtailmenus.models.menus.Menu`
* Removed `panels` attributes from the `AbstractMainMenu` and `AbstractFlatMenu` models
* Removed `main_menu_panels` and `flat_menu_panels` from `wagtailmenus.panels`.
* Various documentation spelling/formatting corrections (thanks to Sergey Fedoseev and Pierre Manceaux).

2.7.1 (07.03.2018)
------------------

* Fixed a bug in MenuTabbedInterfaceMixin preventing `content_panels` and `settings_panels` being picked up in the editing UI when using Wagtail 2.0.
* Remove the 'alpha' notice and title notation from the 2.7.0 release notes.
* Added a badge to README.rst to indicate the documentation build status.
* Added a missing 'migrate' step to the **Developing locally** instructions in the contribution guidelines.
* Updated the code block in the **.po to .mo** conversion step in the packaging guidelines to the `find` command with `execdir`.

2.7.0 (01.03.2018)
------------------

* Added support for Wagtail 2.0 and Django 2.0
* Dropped support for Python 2 and 3.3.
* Dropped support for Wagtail versions 1.8 to 1.9
* Dropped support for Django versions 1.5 to 1.9
* Made numerous 'Python 3 only' optimisations to code.
* The `wagtailmenus.models.menus.MenuFromRootPage` class was removed.
* The `__init__()` method of `wagtailmenus.models.menus.ChildrenMenu` no
  longer accepts a **root_page** keyword argument. The parent page should be
  passed using the **parent_page** keyword instead.
* The *root_page* attribute has been removed from the
  `wagtailmenus.models.menus.ChildrenMenu` class. Use the *parent_page*
  attribute instead.
* The `sub_menu` template tag no longer accepts a *stop_at_this_level*
  keyword argument.
* The `get_sub_menu_items_for_page()` and `prime_menu_items()` methods
  have been removed from `wagtailmenus.templatetags.menu_tags`.
* The `get_attrs_from_context()` method has been removed from
  `wagtailmenus.utils.misc`.
* The `get_template_names()` and `get_sub_menu_template_names()` methods
  have been removed from `wagtailmenus.utils.template` and the redundant
  `wagtailmenus.utils.template` module removed.
* Fixed an issue that was preventing translated field label text appearing for
  the `handle` field when using the `FLAT_MENUS_HANDLE_CHOICES` setting
  (Contributed by @jeromelebleu)

2.6.0 (22.12.2017)
------------------

* Improve compatibility with alternative template backends such as `jinja2`.
  Implementation by @hongquan.
* Added compatibility with `wagtail-condensedinlinepanel`.
* Updated the menu CMS editing UI to split rendering setting field out into
  their own tab.
* Updated tests to test compatibility with Wagtail 1.13.

2.5.1 (27.10.2017)
------------------

* Fixed a bug that was causing Django to create new migrations for wagtailmenus
  after changing Django's `LANGUAGE_CODE` setting for a project. Thanks to
  @philippbosch from A Color Bright for the fix.

2.5.0 (14.10.2017)
------------------

* Added rendering logic to Menu classes and refactored all existing template
  tags to make use of it (massively reducing code duplication in menu_tags.py).
* Added support for several 'hooks', allowing for easier customisation of base
  querysets and manipulation of menu items during rendering. For more
  information and examples, see the 'Hooks' section of the documentation:
  http://wagtailmenus.readthedocs.io/en/latest/advanced_topics/hooks.html
* Updated the 'sub_menu' tag to raise an error if used in a way that isn't
  supported.
* Deprecated `get_sub_menu_items_for_page` and `prime_menu_items` methods from
  `wagtailmenus.templatetags.menu_tags` (logic moved to menu classes).
* Deprecated `get_template` and `get_sub_menu_template_names` methods from
  `wagtailmenus.utils.template` (logic moved to menu classes).
* Deprecated `get_attrs_from_context` method from `wagtailmenus.utils.misc`
  (logic moved to menu classes).
* Deprecated the `MenuFromRootPage` class from `wagtailmenus.models.menus` in
  favour of using a new `MenuFromPage` class that fits better with how it's
  used in menu classes.
* Minor tidying / renaming of tests.
* Added a 'add_menu_items_for_pages()' method to the `MenuWithMenuItems` model,
  which adds menu item to a menu object, linking to any pages passed in as a `PageQuerySet`.
* Added the 'autopopulate_main_menus' command, that can be run as part of the
  installation process to help populate main menus based on the 'home' and
  'section root' pages for each site.
* Fixed an issue with runtests.py that was causing tox builds in Travis CI
  to report as successful, even when tests were failing. Contributed by
  Oliver Bestwalter (obestwalter).
* Deprecated the `stop_at_this_level` argument for the `sub_menu` tag, which
  hasn't worked for a few versions.
* Added support for Wagtail 1.12.
* Made the logic in menu classes 'page_children_dict' method easier to override
  by moving it out into a separate 'get_page_children_dict()' method, which the
  original (@cached_property decorated) method calls.
* Made the logic in menu classes 'pages_for_display' method easier to override
  by moving it out into a separate 'get_pages_for_display()' method, which the
  original (@cached_property decorated) method calls.
* Made the logic in menu classes 'top_level_items' method easier to override
  by moving it out into a separate 'get_top_level_items()' method, which the
  original (@cached_property decorated) method calls.

2.4.0 (04.08.2017)
------------------

* Adjusted Meta classes on menu item models so that common behaviour is defined
  once in AbastractMenuItem.Meta.
* Refactored the AbstractMenuItem's `menu_text` property method to improve code
  readability, and better handle instances where neither link_text or link_page
  are set.
* Replaced overly long README.md with brand new documentation and a new
  README.rst which will render better on PyPi. The documentation is kindly
  hosted by readthedocs.org and can be found at
  http://wagtailmenus.readthedocs.io/
* Added Chinese translations, kindly submitted by 汇民 王 (levinewong)
* Added the 'use_absolute_page_urls' argument to all template tags. When a
  value equating to `True` is provided, the menu will be rendered using the
  'full URL' for each page (including the protocol/domain derived from the
  relevant `wagtailcore.models.Site` object), instead the 'relative URL' used
  by default. Developed by Trent Holliday of Morris Technology and Andy Babic.

2.3.2 (21.07.2017)
------------------

* Fixed a bug that would result in {% sub_menu %} being called recursively (
  until raising a "maximum recursion depth exceeded" exception) if a
  'repeated menu item' was added at anything past the 2nd level. Thanks to
  @pyMan for raising/investigating.

2.3.1 (01.07.2017)
------------------

* Code example formatting fixes, and better use of headings in README.md.
* Added 'on_delete=models.CASCADE' to all relationship fields on models where
  no 'on_delete' behaviour was previously set (Django 2.0 compatibility).
* Marked a missing string for translation (@einsfr).
* Updated translations for Lithuanian, Portuguese (Brazil), and Russian.
  Many thanks to @mamorim, @matas.dailyda and @einsfr!

2.3.0 (21.06.2017)
------------------

* Added an 'AbstractLinkPage' model to wagtailmenus.models that can be easily
  sub-classed and used in projects to create 'link pages' that act in a similar
  fashion to menu items when appearing in menus, but can be placed in any part
  of the page tree.
* Updated 'modify_submenu_items', 'has_submenu_items' and
  'get_repeated_menu_item' methods on MenuPageMixin / MenuPage to accept a
  'request' parameter, which is used to pass in the current `HttpRequest`
  object the menu is being rendered for.
* Added the `WAGTAILMENUS_SECTION_MENU_CLASS_PATH` setting, which can be used
  to override the `Menu` class used when using the `{% section_menu %}` tag.
* Added the `WAGTAILMENUS_CHILDREN_MENU_CLASS_PATH` setting, which can be used
  to override the `Menu` class used when using the `{% children_menu %}` tag.
* All `Menu` classes are now 'request aware', meaning `self.request` will
  return the current `HttpRequest` object within most methods.
* Added a `get_base_page_queryset()` method to all `Menu` classes, that can be
  overridden to change the base page QuerySet used when identifying pages to
  be included in a menu when rendering. For example developers could use
  `self.request.user` to only ever include pages that the current user has
  some permission for.
* Abstracted out most model functionality from `MenuPage` to a `MenuPageMixin`
  model, that can be used with existing page type models.
* Added wagtail 1.10 and django 1.11 test environments to tox.
* Renamed `test_frontend.py` to `test_menu_rendering.py`
* In situations where `request.site` hasn't been set by wagtail's
  `SiteMiddleware`, the wagtailmenus context processor use the default
  site to generate menus with.
* Updated AbstractMenuItem.clean() to only ever return field-specific
  validation errors, because Wagtail doesn't render non-field errors for
  related models added to the editor interface using `InlinePanel`.
* Added Russian translations (submitted by Alex einsfr).

2.2.3 (21.07.2017)
------------------

* Fixed a bug that would result in {% sub_menu %} being called recursively (
  until raising a "maximum recursion depth exceeded" exception) if a
  'repeated menu item' was added at anything past the 2nd level. Thanks to
  @pyMan for raising/investigating.

2.2.2 (27.03.2017)
------------------

* Got project set up in Transifex.
* Updated translatable strings throughout the project to use named variable
  substitution, and unmarked a few exception messages.
* Add Lithuanian translations (submitted by Matas Dailyda).
* Better handle situations where `request` isn't available in the context, or
  `request.site` hasn't been set.

2.2.1 (06.03.2017)
------------------

* Updated travis/tox test settings to test against Wagtail 1.9 & Django 1.10.
* Removed a couple of less useful travis/tox environment tests to help with
  test speed.
* Made use of 'extras_require' in setup.py to replace multiple requirements
  files.
* Optimised the app_settings module so that we can ditch the questionably stuff
  we're doing with global value manipulation on app load (solution inspired by
  django-allauth).
* Added new symantic version handling to the project (solution inspired by
  wagtail)

2.2.0 (20.02.2017)
------------------

* Utilise Django's 'django.template.loader.select_template()' method
  to provide a more intuitive way for developers to override templates for
  specific menus without having to explicitly specify alternative templates
  via settings or via the `template` and `sub_menu_template` options for
  each menu tag. See the updated documentation for each tag for information
  about where wagtailmenus looks for templates.
* Added the `WAGTAILMENUS_SITE_SPECIFIC_TEMPLATE_DIRS` setting to allow
  developers to choose to have wagtailmenus look in additional site-specific
  locations for templates to render menus.
* Moved some methods out of `template_tags/menu_tags.py` into a new `utils.py`
  file to make `menu_tags.py` easier to read / maintain in future.
* Brazilian Portuguese language translations added by @MaxKurama.
* Added try/except to `AbstractMenuItem.relative_url()` so that errors aren't
  thrown when `Page.relative_url` returns `None` for some reason.

2.1.4 (21.07.2017)
------------------

* Fixed a bug that would result in {% sub_menu %} being called recursively (
  until raising a "maximum recursion depth exceeded" exception) if a
  'repeated menu item' was added at anything past the 2nd level. Thanks to
  @pyMan for raising/investigating.

2.1.3 (20.01.2017)
------------------

* Fixed a bug in the `section_menu` tag when attempting to apply the correct
  active class to `section_root` when the `modify_submenu_items()` method has
  been overridden to return additional items without an `active_class`
  attribute (like in the example code in README).

2.1.2 (07.01.2017)
------------------

* Fixed a bug preventing reordered menu items from retaining their new order
  after saving. The Meta class on the new abstract models had knocked out the
  `sort_order` ordering from `wagtail.wagtailcore.models.Orderable`.

2.1.1 (02.01.2017)
------------------

* Fixed import error on pip install from version 2.1.0 (Adriaan Tijsseling)

2.1.0 (28.12.2016)
------------------

* Added official support for wagtail v1.8.
* Turned `wagtailmenus.app_settings` into a real settings module.
* Added `WAGTAILMENUS_MAIN_MENU_MODEL` and `WAGTAILMENUS_FLAT_MENU_MODEL`
  settings to allow the default main and flat menu models to be swapped out for
  custom models.
* Added `WAGTAILMENUS_MAIN_MENU_ITEMS_RELATED_NAME` and
  `WAGTAILMENUS_FLAT_MENU_ITEMS_RELATED_NAME` settings to allow the default
  menu item models to be swapped out for custom models.
* Added the `WAGTAILMENUS_PAGE_FIELD_FOR_MENU_ITEM_TEXT` setting to allow
  developers to specify a page attribute other than `title` to be used to
  populate the `text` attribute for menu items linking to pages.
* Added german translation by Pierre (@bloodywing).
* Split models.py into 3 logically-named files to make models easier to find.

2.0.3 (08.12.2016)
------------------

Fixed migration related issue raised by @urlsangel.

2.0.2 (08.12.2016)
------------------

This release is broken and shouldn't be used. Skip to v2.0.3 instead.

2.0.1 (22.11.2016)
------------------

Bug fix for `main_menu` template tag.

2.0.0 (19.11.2016)
------------------

* The `use_specific` menu tag argument can now be one of 4 integer values,
  allowing for more fine-grained control over the use of `Page.specific` and
  `PageQuerySet.specific()` when rendering menu tags (see README.md for further
  details).
* `MainMenu` and `FlatMenu` models now have a `use_specific` field, to allow
  the default `use_specific` setting when rendering that menu to be changed
  via the admin area.
* `MainMenu` and `FlatMenu` models now have a `max_levels` field, to allow the
  default `max_levels` setting when rendering that menu to be changed via the
  admin area.
* When rendering a multi-level `MainMenu` or `FlatMenu, the model instances for
  those menus pre-fetch all of pages needed to generate the entire menu.
  The menu tags then request lists of child pages from menu instance as they
  are needed, reducing the need to hit the database at every single branch.
* The `max_levels`, `use_specific`, `parent_page` and `menuitem_or_page`
  arguments passed to all template tags are now checked to ensure their values
  are valid, and if not, raise a `ValueError` with a helpful message to aid
  debugging.
* Developers not using the `MenuPage` class or overriding any of wagtail `Page`
  methods involved in URL generation can now enjoy better performance by
  choosing not to fetch any specific pages at all during rendering. Simply
  pass `use_specific=USE_SPECIFIC_OFF` or `use_specific=0` to the tag, or
  update the `use_specific` field value on your `MainMenu` or `FlatMenu`
  instances via the Wagtail admin area.
* Dropped support for the `WAGTAILMENUS_DEFAULT_MAIN_MENU_MAX_LEVELS` and
  `WAGTAILMENUS_DEFAULT_FLAT_MENU_MAX_LEVELS` settings. Default values are now
  set using the `max_levels` field on the menu objects themselves.
* Dropped support for the `WAGTAILMENUS_DEFAULT_MAIN_MENU_USE_SPECIFIC` and
  `WAGTAILMENUS_DEFAULT_FLAT_MENU_USE_SPECFIC` settings. Default values are now
  set using the `use_specific` field on the menu objects themselves.
* Eliminated a lot of code duplication in template tags by adding the
  `get_sub_menu_items_for_page` method, which is used by `sub_menu`,
  `section_menu` and `children_menu` to do most of their work.
* The default `show_multiple_levels` value for the `flat_menu` tag is now
  `True` instead of `False`. The default `max_levels` field value for
  `FlatMenu` instances is `1`, which has the same effect. Only, the value can
  be changed via the admin area,     and the changes will reflected immediately
  without having to explicitly add `show_multiple_levels=True` to the tag in
  templates.
* The `has_submenu_items()` method on `MenuPage` no longer accepts a
  `check_for_children` argument.
* The `modify_submenu_items()` and `has_submenu_items()` methods on the
  `MenuPage` model now both accept an optional `menu_instance` value, so that
  menu_instance might be called to access pre-fetched page data without hitting
  the database.
* Added the `WAGTAILMENUS_ADD_EDITOR_OVERRIDE_STYLES` setting to allow override
  styles to be disabled.
* Other minor performance improvements.

1.6.1 (04.11.2016)
------------------

* French translations added by François GUÉRIN (frague59)

1.6.0 (28.10.2016)
------------------

* Improved confirmation messages when saving a menu in the admin area.
* Added a new test to submit the `MainMenu` edit form and check that
  it behaves as expected.
* Added some styles to menu add/edit/copy views to improve the UI.
* Added a new `context_processor` to handle some of the logic that was
  previously being done in template tags. Django's `SimpleLazyObject` class is
  used to reduce the overhead as much as possible, only doing the work when the
  values are accessed by menu tags.
* Added the `WAGTAILMENUS_GUESS_TREE_POSITION_FROM_PATH` setting to allow
  developers to disable the 'guess tree position from path' functionality
  that comes into play when serving custom views, where the `before_serve_page`
  hook isn't activated, and `wagtailmenu_params_helper()` in `wagtail_hooks.py`
  doesn't get to add it's helpful values to the request/context.
* Updated tox environment settings to run tests against wagtail==1.7, and
  updated pinned wagtail version in `setup.py` to reflect compatibility.
* Added unicode support for python 2.7 and added missing verbose_names to
  fields so that they can be translated (Alexey Krasnov & Andy Babic).
* Added support for a `WAGTAILMENUS_FLAT_MENUS_HANDLE_CHOICES` setting that, if
  set, will turn the `CharField` used for FlatMenu.handle in add/edit/copy
  forms into a `ChoiceField`, with that setting as the available choices.

1.5.1 (10.10.2016)
------------------

* `MenuPage.has_submenu_items()` is now only ever called if
  `check_for_children` is True in `menu_tags.prime_menu_items()`.
  This way, the `max_levels` value supplied to the original menu tag is always
  respected, with no additional levels ever being rendered.
  The `check_for_chilren` value passed to `has_submenu_items()` is now always
  True. Since removing would add breaking changes, it will be removed in a
  later feature release.
* Fixed a migration-related issue that was Django to create new migrations for
  the app.
* Fixed an issue where not all help text was marked for translation.

1.5.0 (05.10.2016)
------------------

* Updated FlatMenu listing in CMS to only show site column and filters if menus
  are defined for more than one site.
* Added the `fall_back_to_default_site_menus` option to the `flat_menu` tag, to
  allow flat menus defined for the default site to be used as fall-backs, in
  cases where the 'current' site doesn't have its own menus set up with the
  specified handle.
* Added a custom ValidationError to FlatMenu's `clean()` method that better
  handles the `unique_together` rule that applied to `site` and `handle`
  fields.
* Added the ability to copy/duplicate existing FlatMenu objects between sites
  (or to the same site with a different handle) via Wagtail's admin area. The
  'Copy' button appears in the listing for anyone with 'add' permission, and
  the view allows the user to make changes before anything is saved.
* Apply `active` classes to menu items that link to custom URLs (if
  `request.path` and `link_url` are exact matches).
* Added a `handle` to `MenuItem` model to provide a string which can be
  used to do specific matching of menu items in the template. (Tim Leguijt)

1.4.1 (02.10.2016)
------------------

* Updated FlatMenu listing in CMS to include a column for `site`, a filter for
  `handle`, and a MenuItem count for each object. Also added default ordering,
  and output the handle value in a <code></code> tag to make it stand out.
* Made it easier to develop and debug wagtailmenus locally, by running it as a
  Django project. See CONTRIBUTING.md for instructions.
* Added a `get_for_site` class method to the FlatMenu model, to be consistent
  with the MainMenu model, and renamed the `for_site` method on MainMenu to
  `get_for_site` for consistency. `main_menu` and `flat_menu` tags now make use
  of these.
* Fixed an minor bug in the `prime_menu_items` method, where a `depth`
  value was hard-coded, instead of utilising the `SECTION_ROOT_LEVEL` setting.

1.4.0 (22.09.2016)
------------------

* Added a `has_submenu_items()` method to `MenuPage` model to compliment
  `modify_submenu_items()` in version 1.3. Allows for far better control and
  consistency when overriding `modify_submenu_items()` to add additional
  menu items for specific page types.
* Added a `sub_menu_template` option to `main_menu`, `section_menu`,
  `flat_menu` and `children_menu` that will be automatically picked up by the
  `sub_menu` tag and used as the template (if no `template` value is provided).
* Added a `fetch_specific_pages` option to all template tags, that if True,
  will used PageQuerySet's `specific()` method to return instances of the
  most specific page-type model as menu items, instead of just vanilla `Page`
  objects.
* Added settings to allow default `fetch_specific_pages` value to be
  altered for each individual menu tag.
* If `fetch_specific_pages` is True, `prime_menu_items` will call the
  `relative_url` method on the specific page to determine a menu item's `href`
  value, meaning overrides to that method will be respected.

1.3.1 (09.08.2016)
------------------

* Configured additional tox test environments for Wagtail>=1.6 with Django=1.9
  and 1.10.
* Extended the 'section matching by path' functionality added in 1.3.0 to
  also identify a 'current page' if the found page matches the exact path.
* Added further tests for path matching.
* Reduced the number of unnecessary calls to `Page.specific` in `menu_tags.py`
  where possible.

1.3.0 (06.08.2016)
------------------

* Added the ability for all menu tags to (attempt to) identify ancestor pages
  and section root page by using components from the request path when serving
  a custom URL (not routed via the page tree / served by `wagtail_serve`)
* Added `modify_submenu_items()` method to `MenuPage` model, which takes
  responsibility for modifying the initial menu_items list in `section_menu`
  and `sub_menu` tags. A DRYer approach, that is easier to extend/override to
  meet custom needs.

1.2.3 (25.07.2016)
------------------

* Added PyPi version and coveralls test coverage badges to README
* Altered Travis CI test configuration to use tox, allowing for much better
  control over test environments
* Added tests for Python 3.4 and 3.5 to confirm compatibility
* Added CONTRIBUTORS.rst

1.2.2 (06.07.2016)
------------------

 * Added this changelog :)
 * Added `WAGTAILMENUS_SECTION_ROOT_DEPTH` setting support, for more consistent identification of 'section root' pages


text:
/* tslint:disable */
/* eslint-disable */

import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type FollowGeneButton_gene = {
    readonly id: string;
    readonly internalID: string;
    readonly slug: string;
    readonly name: string | null;
    readonly is_followed: boolean | null;
    readonly " $refType": "FollowGeneButton_gene";
};
export type FollowGeneButton_gene$data = FollowGeneButton_gene;
export type FollowGeneButton_gene$key = {
    readonly " $data"?: FollowGeneButton_gene$data;
    readonly " $fragmentRefs": FragmentRefs<"FollowGeneButton_gene">;
};

const node: ReaderFragment = {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "FollowGeneButton_gene",
  "selections": [
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "id",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "internalID",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "slug",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "name",
      "storageKey": null
    },
    {
      "alias": "is_followed",
      "args": null,
      "kind": "ScalarField",
      "name": "isFollowed",
      "storageKey": null
    }
  ],
  "type": "Gene"
};
(node as any).hash = '76484c1820e13b5b07970107b5e1f5ca';
export default node;


text:
package com.ovoenergy.comms.composer

import java.util.concurrent._
import scala.collection.JavaConverters._
import scala.concurrent.duration._
import scala.compat.java8.DurationConverters._

import cats._, implicits._
import cats.effect.{Sync, Resource}

import io.chrisdavenport.cats.time._

import io.micrometer.datadog._
import io.micrometer.core.{instrument => micrometer}
import io.micrometer.core.instrument.{Clock, MeterRegistry, Tag}
import io.micrometer.core.instrument.simple.SimpleMeterRegistry

package object metrics {

  def createMeterRegistry[F[_]: Sync](c: Config.Metrics): Resource[F, MeterRegistry] = {

    val datadogConfig: DatadogConfig = new DatadogConfig {
      override val apiKey = c.apiKey
      override val applicationKey = c.applicationKey
      override val enabled = true
      override val step = java.time.Duration.ofSeconds(c.rate.toSeconds.toInt)
      override val uri = c.endpoint.toString
      // The parent of DatadogConfig need this abstract method to return null
      // to apply the default value
      def get(id: String): String = null
    }

    if (c.enabled) {
      Resource
        .make(
          Sync[F].delay(
            DatadogMeterRegistry
              .builder(datadogConfig)
              .build
          )
        )(toStop => Sync[F].delay(toStop.stop))
        .widen[MeterRegistry]
    } else {
      Resource.pure[F, MeterRegistry](new SimpleMeterRegistry)
    }
  }
}


text:
/*****************************************************************************

  sc_signal_ifs.h -- The sc_signal<T> interface classes.

  Original Author: Martin Janssen, Synopsys, Inc., 2001-05-21

  CHANGE LOG IS AT THE END OF THE FILE
 *****************************************************************************/

#ifndef SC_SIGNAL_IFS_H
#define SC_SIGNAL_IFS_H

#include "sysc/communication/sc_interface.h"
#include "sysc/communication/sc_writer_policy.h"

namespace sc_dt
{
    class sc_logic;
}

namespace sc_core {

class sc_signal_bool_deval;
class sc_signal_logic_deval;

// ----------------------------------------------------------------------------
//  CLASS : sc_signal_in_if<T>
//
//  The sc_signal<T> input interface class.
// ----------------------------------------------------------------------------

template <class T>
class sc_signal_in_if
: virtual public sc_interface
{
public:

    // get the value changed event
    virtual const sc_event& value_changed_event() const = 0;

    // read the current value
    virtual const T& read() const = 0;

    // get a reference to the current value (for tracing)
    virtual const T& get_data_ref() const = 0;

    // was there a value changed event?
    virtual bool event() const = 0;

protected:

    // constructor

    sc_signal_in_if()
	{}

private:

    // disabled
    sc_signal_in_if( const sc_signal_in_if<T>& );
    sc_signal_in_if<T>& operator = ( const sc_signal_in_if<T>& );
};

// ----------------------------------------------------------------------------
//  CLASS : sc_signal_in_if<bool>
//
//  Specialization of sc_signal_in_if<T> for type bool.
// ----------------------------------------------------------------------------

class sc_reset;

template <>
class sc_signal_in_if<bool>
: virtual public sc_interface
{
    friend class sc_reset;
public:

    // get the value changed event
    virtual const sc_event& value_changed_event() const = 0;

    // get the positive edge event
    virtual const sc_event& posedge_event() const = 0;

    // get the negative edge event
    virtual const sc_event& negedge_event() const = 0;

    // read the current value
    virtual const bool& read() const = 0;

    // get a reference to the current value (for tracing)
    virtual const bool& get_data_ref() const = 0;

    // was there a value changed event?
    virtual bool event() const = 0;

    // was there a positive edge event?
    virtual bool posedge() const = 0;

    // was there a negative edge event?
    virtual bool negedge() const = 0;

protected:

    // constructor

    sc_signal_in_if()
	{}

private:

    // disabled
    sc_signal_in_if( const sc_signal_in_if<bool>& );
    sc_signal_in_if<bool>& operator = ( const sc_signal_in_if<bool>& );

    // designate this object as a reset signal
    virtual sc_reset* is_reset() const
      { return NULL; }
};

// ----------------------------------------------------------------------------
//  CLASS : sc_signal_in_if<sc_dt::sc_logic>
//
//  Specialization of sc_signal_in_if<T> for type sc_dt::sc_logic.
// ----------------------------------------------------------------------------

template <>
class sc_signal_in_if<sc_dt::sc_logic>
: virtual public sc_interface
{
public:

    // get the value changed event
    virtual const sc_event& value_changed_event() const = 0;

    // get the positive edge event
    virtual const sc_event& posedge_event() const = 0;

    // get the negative edge event
    virtual const sc_event& negedge_event() const = 0;

    // read the current value
    virtual const sc_dt::sc_logic& read() const = 0;

    // get a reference to the current value (for tracing)
    virtual const sc_dt::sc_logic& get_data_ref() const = 0;

    // was there a value changed event?
    virtual bool event() const = 0;

    // was there a positive edge event?
    virtual bool posedge() const = 0;

    // was there a negative edge event?
    virtual bool negedge() const = 0;

protected:

    // constructor

    sc_signal_in_if()
	{}

private:

    // disabled
    sc_signal_in_if( const sc_signal_in_if<sc_dt::sc_logic>& );
    sc_signal_in_if<sc_dt::sc_logic>& operator = (
	const sc_signal_in_if<sc_dt::sc_logic>& );
};

// ----------------------------------------------------------------------------
//  CLASS : sc_signal_write_if<T>
//
//  The standard output interface class.
// ----------------------------------------------------------------------------
template< typename T >
class sc_signal_write_if : public virtual sc_interface
{
public:
    sc_signal_write_if() {}
    // write the new value
    virtual void write( const T& ) = 0;
    virtual sc_writer_policy get_writer_policy() const
        { return SC_ONE_WRITER; }
private:
    // disabled
    sc_signal_write_if( const sc_signal_write_if<T>& );
    sc_signal_write_if<T>& operator = ( const sc_signal_write_if<T>& );
};

// ----------------------------------------------------------------------------
//  CLASS : sc_signal_inout_if<T>
//
//  The sc_signal<T> input/output interface class.
// ----------------------------------------------------------------------------

template <class T>
class sc_signal_inout_if
: public sc_signal_in_if<T>, public sc_signal_write_if<T>
{

protected:

    // constructor

    sc_signal_inout_if()
	{}

private:

    // disabled
    sc_signal_inout_if( const sc_signal_inout_if<T>& );
    sc_signal_inout_if<T>& operator = ( const sc_signal_inout_if<T>& );
};

// ----------------------------------------------------------------------------
//  CLASS : sc_signal_out_if<T>
//
//  The sc_signal<T> output interface class.
// ----------------------------------------------------------------------------

// sc_signal_out_if can also be read from, hence no difference with
// sc_signal_inout_if.

#define sc_signal_out_if sc_signal_inout_if

} // namespace sc_core

//$Log: sc_signal_ifs.h,v $
//Revision 1.4  2011/08/26 20:45:43  acg
// Andy Goodrich: moved the modification log to the end of the file to
// eliminate source line number skew when check-ins are done.
//
//Revision 1.3  2011/02/18 20:23:45  acg
// Andy Goodrich: Copyright update.
//
//Revision 1.2  2010/12/07 19:50:37  acg
// Andy Goodrich: addition of writer policies, courtesy of Philipp Hartmann.
//
//Revision 1.1.1.1  2006/12/15 20:20:04  acg
//SystemC 2.3
//
//Revision 1.4  2006/08/29 23:35:00  acg
// Andy Goodrich: added bind_count() method to allow users to determine which
// ports are connected in before_end_of_elaboration().
//
//Revision 1.3  2006/04/11 23:11:57  acg
//  Andy Goodrich: Changes for reset support that only includes
//  sc_cthread_process instances.
//
//Revision 1.2  2006/01/03 23:18:26  acg
//Changed copyright to include 2006.
//
//Revision 1.1.1.1  2005/12/19 23:16:43  acg
//First check in of SystemC 2.1 into its own archive.
//
//Revision 1.10  2005/09/15 23:01:51  acg
//Added std:: prefix to appropriate methods and types to get around
//issues with the Edison Front End.
//
//Revision 1.9  2005/06/29 18:12:12  acg
//Added $log.
//
//Revision 1.8  2005/06/10 22:43:55  acg
//Added CVS change log annotation.
//

#endif

// Taf!