text:
package strfmt

import (
	"database/sql/driver"
	"fmt"
	"regexp"
	"strings"
	"time"
)

func init() {
	dt := DateTime{}
	Default.Add("datetime", &dt, IsDateTime)
}

// IsDateTime returns true when the string is a valid date-time
func IsDateTime(str string) bool {
	if len(str) < 4 {
		return false
	}
	s := strings.Split(strings.ToLower(str), "t")
	if len(s) < 2 || !IsDate(s[0]) {
		return false
	}

	matches := rxDateTime.FindAllStringSubmatch(s[1], -1)
	if len(matches) == 0 || len(matches[0]) == 0 {
		return false
	}
	m := matches[0]
	res := m[1] <= "23" && m[2] <= "59" && m[3] <= "59"
	return res
}

const (
	// RFC3339Millis represents a ISO8601 format to millis instead of to nanos
	RFC3339Millis = "2006-01-02T15:04:05.000Z07:00"
	// DateTimePattern pattern to match for the date-time format from http://tools.ietf.org/html/rfc3339#section-5.6
	DateTimePattern = `^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$`
)

var (
	dateTimeFormats = []string{RFC3339Millis, time.RFC3339, time.RFC3339Nano}
	rxDateTime      = regexp.MustCompile(DateTimePattern)
)

// ParseDateTime parses a string that represents an ISO8601 time or a unix epoch
func ParseDateTime(data string) (DateTime, error) {
	if data == "" {
		return NewDateTime(), nil
	}
	var lastError error
	for _, layout := range dateTimeFormats {
		dd, err := time.Parse(layout, data)
		if err != nil {
			lastError = err
			continue
		}
		lastError = nil
		return DateTime(dd), nil
	}
	return DateTime{}, lastError
}

// DateTime is a time but it serializes to ISO8601 format with millis
// It knows how to read 3 different variations of a RFC3339 date time.
// Most API's we encounter want either millisecond or second precision times. This just tries to make it worry-free.
//
// swagger:strfmt date-time
type DateTime time.Time

// NewDateTime is a representation of zero value for DateTime type
func NewDateTime() DateTime {
	return DateTime(time.Unix(0, 0).UTC())
}

func (t DateTime) String() string {
	return time.Time(t).Format(RFC3339Millis)
}

// MarshalText implements the text marshaller interface
func (t DateTime) MarshalText() ([]byte, error) {
	return []byte(t.String()), nil
}

// UnmarshalText implements the text unmarshaller interface
func (t *DateTime) UnmarshalText(text []byte) error {
	tt, err := ParseDateTime(string(text))
	if err != nil {
		return err
	}
	*t = tt
	return nil
}

// Scan scans a DateTime value from database driver type.
func (t *DateTime) Scan(raw interface{}) error {
	// TODO: case int64: and case float64: ?
	switch v := raw.(type) {
	case []byte:
		return t.UnmarshalText(v)
	case string:
		return t.UnmarshalText([]byte(v))
	case time.Time:
		*t = DateTime(v)
	case nil:
		*t = DateTime{}
	default:
		return fmt.Errorf("cannot sql.Scan() strfmt.DateTime from: %#v", v)
	}

	return nil
}

// Value converts DateTime to a primitive value ready to written to a database.
func (t DateTime) Value() (driver.Value, error) {
	return driver.Value(t), nil
}


text:
  <link rel="stylesheet" type="text/css" href="shared/shiny.css"/>

HTML UI

    Distribution type:

    <select name="dist">
      <option value="norm">Normal</option>
      <option value="unif">Uniform</option>
      <option value="lnorm">Log-normal</option>
      <option value="exp">Exponential</option>
    </select>

    Number of observations:

    <input type="number" name="n" value="500" min="1" max="1000" />

redpajama_set_name: RedPajamaGithub


text:
package com.jacksay.sgarnish.utils;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Stéphane Bouvry<stephane.bouvry@unicaen.fr>
 */
public class JckFileUtilsTest {

    public JckFileUtilsTest() {
    }

    @Test
    public void testSomeMethod() {
        assertEquals("/home/jacksay/Projets/swing-garnish/build/classes/", JckFileUtils.getAppPath(JckCustomFileFilter.class));
        assertEquals("/home/jacksay/Projets/swing-garnish/build/classes/", JckFileUtils.getAppPath(JckFileUtils.class));
    }
}


text:
<?php

declare(strict_types=1);

namespace Core\Security\ProviderConfiguration\Infrastructure\OpenId\Api\FindOpenIdConfiguration;

use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Security\ProviderConfiguration\Application\OpenId\UseCase\FindOpenIdConfiguration\{
    FindOpenIdConfigurationPresenterInterface,
    FindOpenIdConfigurationResponse
};

class FindOpenIdConfigurationPresenter extends AbstractPresenter implements FindOpenIdConfigurationPresenterInterface
{
    /**
     * {@inheritDoc}
     * @param FindOpenIdConfigurationResponse $response
     */
    public function present(mixed $response): void
    {
        $presenterResponse = [
            'is_active' => $response->isActive,
            'is_forced' => $response->isForced,
            'base_url' => $response->baseUrl,
            'authorization_endpoint' => $response->authorizationEndpoint,
            'token_endpoint' => $response->tokenEndpoint,
            'introspection_token_endpoint' => $response->introspectionTokenEndpoint,
            'userinfo_endpoint' => $response->userInformationEndpoint,
            'endsession_endpoint' => $response->endSessionEndpoint,
            'connection_scopes' => $response->connectionScopes,
            'login_claim' => $response->loginClaim,
            'client_id' => $response->clientId,
            'client_secret' => $response->clientSecret,
            'authentication_type' => $response->authenticationType,
            'verify_peer' => $response->verifyPeer,
            'auto_import' => $response->isAutoImportEnabled,
            'contact_template' => $response->contactTemplate,
            'email_bind_attribute' => $response->emailBindAttribute,
            'fullname_bind_attribute' => $response->userNameBindAttribute,
            'roles_mapping' => $response->aclConditions,
            'authentication_conditions' => $response->authenticationConditions,
            'groups_mapping' => $response->groupsMapping
        ];

        $this->presenterFormatter->present($presenterResponse);
    }
}


text:
<!DOCTYPE animal [
<!ELEMENT animal ANY>
<?ຨ an illegal char #x0ea8
 in PITarget ?>
]>
<animal/>


text:
title: The easiest way to get started with Svelte
description: This'll only take a minute.
pubdate: 2017-08-07
author: Rich Harris
authorURL: https://twitter.com/Rich_Harris
---

Svelte is a [new kind of framework](/blog/frameworks-without-the-framework). Rather than putting a `<script src='svelte.js'>` tag on the page, or bringing it into your app with `import` or `require`, Svelte is a compiler that works behind the scenes to turn your component files into beautifully optimised JavaScript.

Because of that, getting started with it can be a little bit confusing at first. How, you might reasonably ask, do you make a Svelte app?

## 1. Use the REPL

The [Svelte REPL](repl) is the easiest way to begin. You can choose from a list of examples to get you started, and tweak them until they do what you want.

<aside>You'll need to have [Node.js](https://nodejs.org/) installed, and know how to use the terminal</aside>

At some point, your app will outgrow the REPL. Click the **download** button to save a `svelte-app.zip` file to your computer and uncompress it.

Open a terminal window and set the project up...

```bash
cd /path/to/svelte-app
npm install
```

...then start up a development server:

```bash
npm run dev
```

This will serve your app on [localhost:5000](http://localhost:5000) and rebuild it with [Rollup](https://rollupjs.org) every time you make a change to the files in `svelte-app/src`.

## 2. Use degit

When you download from the REPL, you're getting a customised version of the [sveltejs/template](https://github.com/sveltejs/template) repo. You can skip messing around with zip files by using [degit](https://github.com/Rich-Harris/degit), a project scaffolding tool.

In the terminal, install degit globally (you only need to do this once):

```bash
npm install -g degit
```

After that, you can instantly create a new project like so:

```bash
degit sveltejs/template my-new-project
cd my-new-project

npm install
npm run dev
```

Once you've tinkered a bit and understood how everything fits together, you can fork [sveltejs/template](https://github.com/sveltejs/template) and start doing this instead:

```bash
degit your-name/template my-new-project
```

And that's it! Do `npm run build` to create a production-ready version of your app, and check the project template's [README](https://github.com/sveltejs/template/blob/master/README.md) for instructions on how to easily deploy your app to the web with [Now](https://zeit.co/now) or [Surge](http://surge.sh/).

You're not restricted to using Rollup — there are also integrations for [webpack](https://github.com/sveltejs/svelte-loader), [Browserify](https://github.com/tehshrike/sveltify) and others, or you can use the [Svelte CLI](https://github.com/sveltejs/svelte-cli) or the [API](https://github.com/sveltejs/svelte#api) directly. If you make a project template using one of these tools, please share it with the [Svelte Gitter chatroom](https://gitter.im/sveltejs/svelte), or via [@sveltejs](https://twitter.com/sveltejs) on Twitter!


text:
<?php

/**
 * ResourceType filter form base class.
 *
 * @package    symfony12
 * @subpackage filter
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormFilterGeneratedTemplate.php 24171 2009-11-19 16:37:50Z Kris.Wallsmith $
 */
abstract class BaseResourceTypeFormFilter extends BaseFormFilterDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'name' => new sfWidgetFormFilterInput(),
    ));

    $this->setValidators(array(
      'name' => new sfValidatorPass(array('required' => false)),
    ));

    $this->widgetSchema->setNameFormat('resource_type_filters[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'ResourceType';
  }

  public function getFields()
  {
    return array(
      'id'   => 'Enum',
      'name' => 'Text',
    );
  }
}


text:
module RecurringTodos

  class WeeklyRecurringTodosBuilder < AbstractRecurringTodosBuilder
    attr_reader :recurring_todo

    def initialize(user, attributes)
      super(user, attributes, WeeklyRecurrencePattern)
    end

    def attributes_to_filter
      %w{weekly_selector weekly_every_x_week} + %w{monday tuesday wednesday thursday friday saturday sunday}.map{|day| "weekly_return_#{day}" }
    end

    def map_attributes(mapping)
      mapping = map(mapping, :every_other1, 'weekly_every_x_week')

      { monday: 1, tuesday: 2, wednesday: 3, thursday: 4, friday: 5, saturday: 6, sunday: 0 }
      .each do |day, index|
        mapping = map_day(mapping, :every_day, "weekly_return_#{day}", index)
      end

      mapping
    end

    def map_day(mapping, key, source_key, index)
      mapping.set_if_nil(key, '       ')  # avoid nil
      mapping.set_if_nil(source_key, ' ') # avoid nil

      mapping.set(key, mapping.get(key)[0, index] + mapping.get(source_key) + mapping.get(key)[index+1, mapping.get(key).length])
      mapping.except(source_key)
    end

    def selector_key
      nil
    end

    def valid_selector?(key)
      true
    end

  end

end


text:
define([
  'text!./file.html',
  'pentaho/i18n-osgi!repositories-plugin.messages',
  'css!./file.css'
], function (template, i18n, $) {

  'use strict';

  var options = {
    bindings: {},
    controllerAs: "vm",
    template: template,
    controller: pentahoController
  };

  pentahoController.$inject = ["$stateParams"];

  function pentahoController($stateParams) {
    var vm = this;
    vm.error = error;

    if ($stateParams.connection) {
      vm.connection = $stateParams.connection;
      vm.connection.edit = true;
      vm.connection.originalName = vm.connection.displayName;
    } else {
      vm.connection = {
        id: "KettleFileRepository",
        displayName: "",
        location: "",
        doNotModify: false,
        showHiddenFolders: false,
        description: "File repository",
        isDefault: false
      };
    }

    function error(message) {
      vm.errorMessage = {timestamp: Date.now(), message: message};
    }
  }

  return {
    name: "file",
    options: options
  };

});


text:
package jiguang.chat.database;

/**
 * Created by ${chenyn} on 2017/7/18.
 */

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;

@Table(name = "group_apply", id = "_id")
public class GroupApplyEntry extends Model {

    @Column(name = "FromUsername")
    public String fromUsername;

    @Column(name = "ToUsername")
    public String toUsername;

    @Column(name = "AppKey")
    public String appKey;

    @Column(name = "Avatar")
    public String Avatar;

    @Column(name = "FromDisplayName")
    public String fromDisplayName;

    @Column(name = "toDisplayName")
    public String toDisplayName;

    @Column(name = "Reason")
    public String reason;

    @Column(name = "State")
    public String state;

    @Column(name = "EventJson")
    public String eventJson;

    @Column(name = "GroupName")
    public String groupName;

    @Column(name = "User")
    public UserEntry user;

    @Column(name = "BtnState")
    public int btnState;

    @Column(name = "GroupType")
    public int groupType;

    public GroupApplyEntry() {
        super();
    }

    public GroupApplyEntry(String fromUsername, String toUsername, String appKey, String Avatar, String fromDisplayName, String toDisplayName,
                           String reason, String state, String eventJson, String groupName, UserEntry user, int btnState, int groupType) {
        super();
        this.fromUsername = fromUsername;
        this.toUsername = toUsername;
        this.appKey = appKey;
        this.Avatar = Avatar;
        this.fromDisplayName = fromDisplayName;
        this.toDisplayName = toDisplayName;
        this.reason = reason;
        this.state = state;
        this.eventJson = eventJson;
        this.groupName = groupName;
        this.user = user;
        this.btnState = btnState;
        this.groupType = groupType;
    }

    public static GroupApplyEntry getEntry(UserEntry user, String username, String appKey) {
        return new Select().from(GroupApplyEntry.class).where("ToUsername = ?", username)
                .where("AppKey = ?", appKey)
                .where("User = ?", user.getId()).executeSingle();
    }

    public static GroupApplyEntry getEntry(long id) {
        return new Select().from(GroupApplyEntry.class).where("_id = ?", id).executeSingle();
    }

    public static void deleteEntry(GroupApplyEntry entry) {
        new Delete().from(GroupApplyEntry.class).where("_id = ?", entry.getId()).execute();
    }

}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name="ForecastListStyle">
        <!-- Here it's a stub.  In screens of sufficient width, this style includes
        modifications for two-pane layout -->
    </style>

</resources>


text:
module Caddy
  class Cache
    # Default refresh interval, in seconds
    DEFAULT_REFRESH_INTERVAL = 60

    # Percentage to randomly smooth the refresh interval to avoid stampeding herd on expiration
    REFRESH_INTERVAL_JITTER_PCT = 0.15

    # @!attribute refresher
    #   @return [Proc] called on interval {#refresh_interval} with the returned object used as the cache
    attr_accessor :refresher

    # @!attribute refresh_interval
    #   @return [Numeric] number of seconds between calls to {#refresher}; timeout is set to <tt>{#refresher} - 0.1</tt>
    attr_accessor :refresh_interval

    # @!attribute error_handler
    #   @return [Proc] if unset, defaults to the global error handler (see #{Caddy.error_handler});
    #   called when exceptions or timeouts happen within the refresher
    attr_accessor :error_handler

    # Create a new periodically updated cache.
    # @param key [Symbol] the name of this cache
    def initialize(key)
      @task = nil
      @refresh_interval = DEFAULT_REFRESH_INTERVAL
      @cache = nil
      @key = key
    end

    # Convenience method for getting the value of the refresher-returned object at path +k+,
    # assuming the refresher-returned value responds to <tt>[]</tt>.
    #
    # If not, {#cache} can be used instead to access the refresher-returned object.
    # @param k key to access from the refresher-returned cache.
    def [](k)
      cache[k]
    end

    # Returns the refresher-produced value that is used as the cache.
    def cache
      raise "Please run `Caddy.start` before attempting to access the cache" unless @task && @task.running?

      unless @cache
        logger.warn "Caddy cache access of :#{@key} before initial load; doing synchronous load."\
                    "Please allow some more time for your app to start up."
        refresh
      end

      @cache
    end

    # Starts the period refresh cycle.
    #
    # Every +refresh_interval+ seconds -- smoothed by a jitter amount (a random amount +/- +REFRESH_INTERVAL_JITTER_PCT+) --
    # the refresher lambda is called and the results stored in +cache+.
    #
    # Note that the result of the refresh is frozen to avoid multithreading mutations.
    def start
      unless refresher && refresher.respond_to?(:call)
        raise "Please set your cache refresher via `Caddy[:#{@key}].refresher = -> { <code that returns a value> }`"
      end

      raise "`Caddy[:#{@key}].refresh_interval` must be > 0" unless refresh_interval > 0

      jitter_amount = [0.1, refresh_interval * REFRESH_INTERVAL_JITTER_PCT].max
      interval = refresh_interval + rand(-jitter_amount...jitter_amount)
      timeout_interval = [interval - 1, 0.1].max

      stop # stop any existing task from running

      @task = Concurrent::TimerTask.new(
        run_now: true,
        execution_interval: interval,
        timeout_interval: timeout_interval
      ) do
        refresh
        nil # no need for the {#Concurrent::TimerTask} to keep a reference to the value
      end

      @task.add_observer(Caddy::TaskObserver.new(error_handler, @key))

      logger.debug "Starting Caddy refresher for :#{@key}, updating every #{interval.round(1)}s."

      @task.execute

      @task.running?
    end

    # Stops the current executing refresher.
    #
    # The current cache value is persisted even if the task is stopped.
    def stop
      @task.shutdown if @task && @task.running?
    end

    # Updates the internal cache object.
    #
    # Freezes the result to avoid mutation errors.
    def refresh
      @cache = refresher.call.freeze
    end

    private

    # Delegates logging to the module logger
    def logger
      Caddy.logger
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Inácio, Landell, Valente, Wang, Wang, Yang, Manson, Lachance, Rosa & Fonseca, FEMS Yeast Res. 8(3): 506 (2008)

#### Original name
Farysizyma itapuaensis Landell & P. Valente

### Remarks
null


text:
namespace Poco {
namespace Util {

class Util_API IniFileConfiguration: public AbstractConfiguration
	/// This implementation of a Configuration reads properties
	/// from a legacy Windows initialization (.ini) file.
	///
	/// The file syntax is implemented as follows.
	///   - a line starting with a semicolon is treated as a comment and ignored
	///   - a line starting with a square bracket denotes a section key [<key>]
	///   - every other line denotes a property assignment in the form
	///     <value key> = <value>
	///
	/// The name of a property is composed of the section key and the value key,
	/// separated by a period (<section key>.<value key>).
	///
	/// Property names are not case sensitive. Leading and trailing whitespace is
	/// removed from both keys and values.
{
public:
	IniFileConfiguration();
		/// Creates an empty IniFileConfiguration.

	IniFileConfiguration(std::istream& istr);
		/// Creates an IniFileConfiguration and loads the configuration data
		/// from the given stream, which must be in initialization file format.

	IniFileConfiguration(const std::string& path);
		/// Creates an IniFileConfiguration and loads the configuration data
		/// from the given file, which must be in initialization file format.

	void load(std::istream& istr);
		/// Loads the configuration data from the given stream, which
		/// must be in initialization file format.

	void load(const std::string& path);
		/// Loads the configuration data from the given file, which
		/// must be in initialization file format.

protected:
	bool getRaw(const std::string& key, std::string& value) const;
	void setRaw(const std::string& key, const std::string& value);
	void enumerate(const std::string& key, Keys& range) const;
	void removeRaw(const std::string& key);
	~IniFileConfiguration();

private:
	void parseLine(std::istream& istr);

	struct ICompare
	{
		bool operator () (const std::string& s1, const std::string& s2) const;
	};
	typedef std::map<std::string, std::string, ICompare> IStringMap;

	IStringMap _map;
	std::string _sectionKey;
};

} } // namespace Poco::Util

#endif // Util_IniFileConfiguration_INCLUDED


text:
package org.codehaus.griffon.runtime.core.artifact;

import griffon.annotations.core.Nonnull;
import griffon.annotations.inject.Typed;
import griffon.core.GriffonApplication;
import griffon.core.artifact.GriffonClass;
import griffon.core.artifact.GriffonView;
import griffon.core.artifact.GriffonViewClass;

import javax.inject.Inject;

import static java.util.Objects.requireNonNull;

/**
 * Handler for 'View' artifacts.
 *
 * @author Andres Almiray
 */
@Typed(GriffonView.class)
public class ViewArtifactHandler extends AbstractArtifactHandler<GriffonView> {
    @Inject
    public ViewArtifactHandler(@Nonnull GriffonApplication application) {
        super(application, GriffonView.class, GriffonViewClass.TYPE, GriffonViewClass.TRAILING);
    }

    @Nonnull
    public GriffonClass newGriffonClassInstance(@Nonnull Class<GriffonView> clazz) {
        requireNonNull(clazz, ERROR_CLASS_NULL);
        return new DefaultGriffonViewClass(getApplication(), clazz);
    }
}


text:
#ifndef SkRunnable_DEFINED
#define SkRunnable_DEFINED

struct SkRunnable {
    virtual ~SkRunnable() {};
    virtual void run() = 0;
};

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace TraktSharp.Entities.Response {

	/// A structure representing the return data or part of the return data from one or more Trakt API methods
	[Serializable]
	public class TraktWatchedShowsResponseItem {

		/// The number of times the show has been played
		[JsonProperty(PropertyName = "plays")]
		public int? Plays { get; set; }

		/// The UTC date when the show was last watched
		[JsonProperty(PropertyName = "last_watched_at")]
		public DateTimeOffset? LastWatchedAt { get; set; }

		/// The show
		[JsonProperty(PropertyName = "show")]
		public TraktShow Show { get; set; }

		/// A collection of seasons
		[JsonProperty(PropertyName = "seasons")]
		public IEnumerable<TraktWatchedShowsResponseItemSeason> Seasons { get; set; }

	}

}


text:
package com.gentics.mesh.core.actions.impl;

import java.util.function.Predicate;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.gentics.mesh.context.BulkActionContext;
import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.core.action.DAOActionContext;
import com.gentics.mesh.core.action.UserDAOActions;
import com.gentics.mesh.core.data.dao.UserDao;
import com.gentics.mesh.core.data.page.Page;
import com.gentics.mesh.core.data.perm.InternalPermission;
import com.gentics.mesh.core.data.user.HibUser;
import com.gentics.mesh.core.db.Tx;
import com.gentics.mesh.core.rest.user.UserResponse;
import com.gentics.mesh.event.EventQueueBatch;
import com.gentics.mesh.parameter.PagingParameters;

/**
 * @see UserDAOActions
 */
@Singleton
public class UserDAOActionsImpl implements UserDAOActions {

	@Inject
	public UserDAOActionsImpl() {
	}

	@Override
	public HibUser loadByUuid(DAOActionContext ctx, String uuid, InternalPermission perm, boolean errorIfNotFound) {
		UserDao userDao = ctx.tx().userDao();
		if (perm == null) {
			return userDao.findByUuid(uuid);
		} else {
			return userDao.loadObjectByUuid(ctx.ac(), uuid, perm, errorIfNotFound);
		}
	}

	@Override
	public HibUser loadByName(DAOActionContext ctx, String name, InternalPermission perm, boolean errorIfNotFound) {
		UserDao userDao = ctx.tx().userDao();
		if (perm == null) {
			return userDao.findByName(name);
		} else {
			throw new RuntimeException("Not supported");
		}
	}

	@Override
	public Page<? extends HibUser> loadAll(DAOActionContext ctx, PagingParameters pagingInfo) {
		return ctx.tx().userDao().findAll(ctx.ac(), pagingInfo);
	}

	@Override
	public Page<? extends HibUser> loadAll(DAOActionContext ctx, PagingParameters pagingInfo,
		Predicate<HibUser> extraFilter) {
		return ctx.tx().userDao().findAll(ctx.ac(), pagingInfo, extraFilter);
	}

	@Override
	public HibUser create(Tx tx, InternalActionContext ac, EventQueueBatch batch, String uuid) {
		return tx.userDao().create(ac, batch, uuid);
	}

	@Override
	public void delete(Tx tx, HibUser user, BulkActionContext bac) {
		tx.userDao().delete(user, bac);
	}

	@Override
	public boolean update(Tx tx, HibUser user, InternalActionContext ac, EventQueueBatch batch) {
		return tx.userDao().update(user, ac, batch);
	}

	@Override
	public UserResponse transformToRestSync(Tx tx, HibUser user, InternalActionContext ac, int level, String... languageTags) {
		return tx.userDao().transformToRestSync(user, ac, level, languageTags);
	}

	@Override
	public String getAPIPath(Tx tx, InternalActionContext ac, HibUser user) {
		return user.getAPIPath(ac);
	}

	@Override
	public String getETag(Tx tx, InternalActionContext ac, HibUser user) {
		return user.getETag(ac);
	}

}


text:
using System;
using System.Collections.Generic;

namespace Sekhmet.Serialization
{
    partial class BuiltInCollectionsObjectContextFactory
    {
        private class SerializationMemberContext : IMemberContext
        {
            private readonly Type _contractType;
            private readonly IObjectContext _value;

            public IEnumerable<object> Attributes { get; private set; }

            public Type ContractType
            {
                get { return _contractType; }
            }

            public string Name
            {
                get { return "Add"; }
            }

            public SerializationMemberContext(Type contractType, IObjectContext value, IEnumerable<object> attributes)
            {
                _contractType = contractType;
                _value = value;
                Attributes = attributes;
            }

            public void CommitChanges() { }

            public IObjectContext GetValue()
            {
                return _value;
            }

            public void SetValue(IObjectContext value)
            {
                throw new NotSupportedException();
            }
        }
    }
}


text:
import { NgModule, BrowserModule } from '@angular/core';
import { FooDirective } from './foo.directive';
import { FooComponent } from './foo.component';
import { BarDirective } from './bar.directive';
import { BarComponent } from './bar.component';
import { FooService } from './foo.service';
import { BarModule } from './bar.module';
import { FooModule } from './foo.module';

/**
 * AppModule description
 *
 * See {@link BarComponent}
 */
@NgModule({
    declarations: [FooDirective, FooComponent, BarComponent],
    providers: [FooService],
    imports: [BarModule, FooModule],
    bootstrap: [FooComponent]
})
export class AppModule {}


text:
var Aframe = require('aframe-core');
var example = require('../index.js').component;
var entityFactory = require('./helpers').entityFactory;

Aframe.registerComponent('example', example);

describe('example', function () {
  beforeEach(function (done) {
    this.el = entityFactory();
    this.el.addEventListener('loaded', function () {
      done();
    });
  });

  describe('example property', function () {
    it('is good', function () {
      assert.equal(1, 1);
    });
  });
});


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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <import resource="classpath*:*OWFsecurityContext*.xml" />
    <import resource="classpath*:OwfConfig.xml" />

</beans>


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#000000" android:state_checked="false"></item>
    <item android:color="@color/textColorPrimary" android:state_checked="true"></item>
</selector>


text:
package org.testrails.satellite.sensors.analyzer.action;

/**
 * Base class for all implementations of AnalyzerAction.
 *
 * @author Nicolai Kamenzky
 *
 */
public abstract class AbstractAnalyzerAction implements AnalyzerAction {

	/**
	 * Used by the {@link ActionRunner} to get multiple {@link AnalyzerAction}s
	 * in order for execution.
	 */
	@Override
	public int compareTo(AnalyzerAction action) {
		return getExecutionOrderRank() - action.getExecutionOrderRank();
	}

	@Override
	public String toString() {
		return this.getClass().getSimpleName();
	}

}


text:
<?php

namespace StructuredAcceptanceTest;

class StatFindingLocation {

    /* Required — The file path to which this finding applies */
    public $path;

    /* Optional — The first line of text affected (numbering starts with one), defaults to one */
    public $beginLine;

    /* Optional — The first column of text affected (numbering starts with one), defaults to one */
    public $beginColumn;

    /* Optional — The last column of text affected (numbering starts with one), defaults to the last */
    public $endColumn;

    /* Optional — The last line of text affected (numbering starts with one), defaults to the last */
    public $endLine;
}


text:
<?php
define("_ORG",'5');
define("_NAME_TRIAL_CLASS","Trial Flight");
?>


text:
A Crystal joystick controller using SDL, based on Artoo-Joystick gem.

## Installation

Add it to `Projectfile`

```crystal
deps do
  github "https://github.com/juliancheal/crystal-joystick"
end
```

## Usage

```crystal
require "crystal-joystick"

joystick = CrystalJoystick::Adaptors::Joystick.new
joystick.connect
driver = CrystalJoystick::Drivers::Joystick.new(joystick)
driver.start_driver(0.1)
```
Currently only outputs to the command line
And seems to use 100% of the cpu!!

## Development

TODO: Write instructions for development

## Contributing

1. Fork it ( https://github.com/juliancheal/crystal-joystick/fork )
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request

## Contributors

- Julian Cheal(https://github.com/juliancheal) Julian Cheal - creator, maintainer


text:
void xbmc_init(void);
void xbmc_deinit(void);
void xbmc_in_received_handler(DictionaryIterator *iter);
void xbmc_reload_data_and_mark_dirty();
void xbmc_request(uint8_t request);


text:
from django.apps import AppConfig

class TestappConfig(AppConfig):
    name = 'private_files.tests.testapp'


text:
//
//  StringPropertyPart.java
//  blogwt
//
//  Created by William Shakour (billy1380) on 20 Jul 2015.
//  Copyright © 2015 WillShex Limited. All rights reserved.
//
package com.willshex.blogwt.client.part.property;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Focusable;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.TextBoxBase;
import com.google.gwt.user.client.ui.Widget;
import com.willshex.blogwt.client.helper.UiHelper;

/**
 * @author William Shakour (billy1380)
 *
 */
public class StringPropertyPart extends AbstractPropertyPart implements
		Focusable {

	@UiField Element elDescription;
	@UiField Element elName;
	@UiField TextBoxBase txtValue;
	@UiField HTMLPanel pnlValueNote;

	private static StringPropertyPartUiBinder uiBinder = GWT
			.create(StringPropertyPartUiBinder.class);

	interface StringPropertyPartUiBinder extends
			UiBinder<Widget, StringPropertyPart> {}

	protected StringPropertyPart (boolean init) {
		if (init) {
			initWidget(uiBinder.createAndBindUi(this));
		}
	}

	public StringPropertyPart () {
		initWidget(uiBinder.createAndBindUi(this));
	}

	private TextBoxBase textBox () {
		return txtValue;
	}

	/**
	 * @param description
	 */
	public void setDescription (String description) {
		elDescription.setInnerText(description);
		UiHelper.addPlaceholder(textBox(), description);
	}

	/**
	 */
	public void setAutofocus () {
		UiHelper.autoFocus(textBox());
	}

	@UiHandler({ "txtValue" })
	void onTextValueChanged (ValueChangeEvent<String> vce) {
		setValue(vce.getValue(), true);
	}

	/* (non-Javadoc)
	 *
	 * @see com.google.gwt.user.client.ui.HasValue#setValue(java.lang.Object,
	 * boolean) */
	@Override
	public void setValue (String value, boolean fireEvents) {
		if (value == null) {
			value = "";
		}

		String oldValue = getValue();

		textBox().setValue(value);
		this.value = value;

		if (value.equals(oldValue)) { return; }
		if (fireEvents) {
			ValueChangeEvent.fire(this, value);
		}
	}

	/* (non-Javadoc)
	 *
	 * @see com.google.gwt.user.client.ui.HasName#getName() */
	@Override
	public String getName () {
		return elName.getInnerText();
	}

	/* (non-Javadoc)
	 *
	 * @see com.google.gwt.user.client.ui.HasName#setName(java.lang.String) */
	@Override
	public void setName (String name) {
		elName.setInnerText(name);
	}

	/* (non-Javadoc)
	 *
	 * @see com.google.gwt.user.client.ui.Focusable#getTabIndex() */
	@Override
	public int getTabIndex () {
		return textBox().getTabIndex();
	}

	/* (non-Javadoc)
	 *
	 * @see com.google.gwt.user.client.ui.Focusable#setAccessKey(char) */
	@Override
	public void setAccessKey (char key) {
		textBox().setAccessKey(key);
	}

	/* (non-Javadoc)
	 *
	 * @see com.google.gwt.user.client.ui.Focusable#setFocus(boolean) */
	@Override
	public void setFocus (boolean focused) {
		textBox().setFocus(focused);
	}

	/* (non-Javadoc)
	 *
	 * @see com.google.gwt.user.client.ui.Focusable#setTabIndex(int) */
	@Override
	public void setTabIndex (int index) {
		textBox().setTabIndex(index);
	}

}


text:
package com.googlecode.wicketwebbeans.examples.models;

import java.io.Serializable;
import java.util.Arrays;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.googlecode.wicketwebbeans.containers.BeanForm;
import com.googlecode.wicketwebbeans.examples.SerializableBean;
import com.googlecode.wicketwebbeans.model.BeanMetaData;

public class ListModelBeanPage extends WebPage
{
    private static final long serialVersionUID = 2292855853289141029L;

    public ListModelBeanPage()
    {
        SerializableBean[] beans = new SerializableBean[20];
        for (int i = 0; i < beans.length; i++) {
            beans[i] = new SerializableBean("Name" + i, "XYZ" + i);
        }

        IModel beanModel = new Model<Serializable>((Serializable)(Object)Arrays.asList(beans));

        BeanMetaData meta = new BeanMetaData(SerializableBean.class, null, this, null, false);
        add( new BeanForm("beanForm", beanModel, meta) );
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_2756014</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753463167</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Esperloop</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Esperloop</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>Esperloop</Appelation>
        <LocationNameType>stream</LocationNameType>
        <Comments></Comments>
      </LocationName>
      <Coordinates>
        <Longitude>5.696940000000001</Longitude>
        <Latitude>51.52412</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/2756014</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
import json
import boto3
import inflect

def lambda_handler(event,context):
    inflect_engine = inflect.engine()
    number = inflect_engine.number_to_words(event['final_number'])
    message = {"DelMeMessage": "The StepFunctions Result is %r" %number}
    client = boto3.client('sns')
    response = client.publish(
        TargetArn="SNS-TOPIC-ARN",
        Message=json.dumps({'default': json.dumps(message)}),
        MessageStructure='json'
    )


text:
void* qtc_QStyleOptionTab();
void* qtc_QStyleOptionTab1(void*);
long qtc_QStyleOptionTab_cornerWidgets(void*);
void* qtc_QStyleOptionTab_icon(void*);
int qtc_QStyleOptionTab_position(void*);
int qtc_QStyleOptionTab_row(void*);
int qtc_QStyleOptionTab_selectedPosition(void*);
void qtc_QStyleOptionTab_setCornerWidgets(void*,long);
void qtc_QStyleOptionTab_setIcon(void*,void*);
void qtc_QStyleOptionTab_setPosition(void*,long);
void qtc_QStyleOptionTab_setRow(void*,int);
void qtc_QStyleOptionTab_setSelectedPosition(void*,long);
void qtc_QStyleOptionTab_setShape(void*,long);
void qtc_QStyleOptionTab_setText(void*);
long qtc_QStyleOptionTab_shape(void*);
void* qtc_QStyleOptionTab_text(void*);
void qtc_QStyleOptionTab_finalizer(void*);
void* qtc_QStyleOptionTab_getFinalizer();
void qtc_QStyleOptionTab_delete(void*);


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="fr.univ_tours.polytech.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <!-- goes up there ^^
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    -->

    <com.joanzapata.pdfview.PDFView
        android:id="@+id/pdfview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="left" />

</FrameLayout>


text:
const grow = `
    transition-duration: 0.3s;
    transition-property: transform;

    &:hover {
        transform: scale(1.1);
    }
`;

export default grow;


text:
There are a lot of good 360 video players out there but this is just a super simple one that you can then overlay assests on the video.

# How to use the dam thing
- You'll need a 360 video (or not but it will look a little bit funny) in both mp4 and OGV format.

- Place both the mp4 and OGV files in the "StreamingAssets" folder (360-video-player/Assets/StreamingAssets) of the project.
- Open the "360Player" scene and select the MovieSurface GameObject.

- Change the "Movie Name" field of the "Movie Player Sample" script to the name of your mp4 file in the StreamingAssets folder. For example, "YourMP4File.mp4"

- Build and run the "360Player" scene

## Enjoy your 360 video

<img src="https://media3.giphy.com/media/JBk4QkoIjlI5i/giphy.gif" width="100%" />


text:
var program = require('commander');
var pathUtil = require('../utils/path');

program
    .version('1.0.0')
    .usage('<configFile>')
    .option('-f, --framework <framework>', 'Testing framework')
    .option('-s, --session <session>', 'Session id')
    .parse(process.argv);

var frameworkRunner = require('./../frameworks/'+program.framework);

pathUtil.getSpecs(program.session).then(function(specFiles) {
    console.log("Running tests");
    frameworkRunner.run(specFiles).then(function(failed) {
        console.log("Done. Failed specs: "+failed);
    });
}, function(error) {
   console.error(error);
   process.exit(1);
});


text:
package eportfolium.com.karuta.webapp.rest.resource;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import eportfolium.com.karuta.business.contract.PortfolioManager;
import eportfolium.com.karuta.webapp.annotation.InjectLogger;
import eportfolium.com.karuta.webapp.rest.provider.mapper.exception.RestWebApplicationException;
import eportfolium.com.karuta.webapp.util.javaUtils;

/**
 * Managing and listing portfolio groups.
 *
 * @author mlengagne
 *
 */
@Path("/portfoliogroups")
public class PortfolioGroupResource extends AbstractResource {

	@InjectLogger
	private static Logger logger;

	@Autowired
	private PortfolioManager portfolioManager;

	/**
	 * Create a new portfolio group.

	 * POST /rest/api/portfoliogroups
	 *
	 * @param sc
	 * @param httpServletRequest
	 * @param groupname          Name of the group we are creating
	 * @param type               group/portfolio
	 * @param parent             parentid
	 * @return groupid
	 */

	@POST
	public Response postPortfolioGroup(@Context ServletConfig sc, @Context HttpServletRequest httpServletRequest,
			@QueryParam("label") String groupname, @QueryParam("type") String type, @QueryParam("parent") Long parent) {
		UserInfo ui = checkCredential(httpServletRequest, null, null, null); // FIXME
		Long response = -1L;

		// Check type value
		try {
			response = portfolioManager.addPortfolioGroup(groupname, type, parent, ui.userId);
			logger.debug("Portfolio group " + groupname + " created");

			if (response == -1) {
				return Response.status(Status.NOT_MODIFIED).entity("Error in creation").build();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex));
			throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
		}

		return Response.ok(Long.toString(response)).build();
	}

	/**
	 * Put a portfolio in portfolio group.

	 * PUT /rest/api/portfoliogroups
	 *
	 * @param sc
	 * @param httpServletRequest
	 * @param group              group id
	 * @param uuid               portfolio id
	 * @param label
	 * @return Code 200
	 */
	@PUT
	public Response putPortfolioInPortfolioGroup(@Context ServletConfig sc,
			@Context HttpServletRequest httpServletRequest, @QueryParam("group") Long group,
			@QueryParam("uuid") String uuid, @QueryParam("label") String label) {
		UserInfo ui = checkCredential(httpServletRequest, null, null, null);

		try {
			int response = -1;
			response = portfolioManager.addPortfolioInGroup(uuid, group, label, ui.userId); // FIXME
			logger.debug("Portfolio added  in group " + label);
			return Response.ok(Integer.toString(response)).build();
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex));
			throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
		}
	}

	/**
	 * Get portfolio by portfoliogroup, or if there's no group id give, give the
	 * list of portfolio group GET /rest/api/portfoliogroups

	 *
	 * - Without group id <groups> <group id={groupid}> {group name}
	 * </group> ... </groups>
	 *
	 * - With group id <group id={groupid}> <portfolio id={uuid}></portfolio> ...
	 * </group>
	 *
	 * @param sc
	 * @param httpServletRequest
	 * @param group              group id
	 * @param portfolioUuid
	 * @param groupLabel         group label
	 * @return group id or empty str if group id not found
	 */
	@GET
	public String getPortfolioByPortfolioGroup(@Context ServletConfig sc,
			@Context HttpServletRequest httpServletRequest, @QueryParam("group") Long group,
			@QueryParam("uuid") String portfolioUuid, @QueryParam("label") String groupLabel) {
		UserInfo ui = checkCredential(httpServletRequest, null, null, null);
		String xmlUsers = "";

		try {
			if (groupLabel != null) {
				Long groupid = portfolioManager.getPortfolioGroupIdFromLabel(groupLabel, ui.userId);
				if (groupid == -1) {
					throw new RestWebApplicationException(Status.NOT_FOUND, "");
				}
				xmlUsers = Long.toString(groupid);
			} else if (portfolioUuid != null) {
				xmlUsers = portfolioManager.getPortfolioGroupListFromPortfolio(portfolioUuid);
			} else if (group == null)
				xmlUsers = portfolioManager.getPortfolioGroupList();
			else
				xmlUsers = portfolioManager.getPortfoliosByPortfolioGroup(group);
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex));
			throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
		}

		return xmlUsers;
	}

	/**
	 * Remove a portfolio from a portfolio group, or remove a portfoliogroup.

	 * DELETE /rest/api/portfoliogroups
	 *
	 * @param sc
	 * @param httpServletRequest
	 * @param groupId            group id
	 * @param uuid               portfolio id
	 * @return Code 200
	 */
	@DELETE
	public String deletePortfolioByPortfolioGroup(@Context ServletConfig sc,
			@Context HttpServletRequest httpServletRequest, @QueryParam("group") long groupId,
			@QueryParam("uuid") String uuid) {
//		checkCredential(httpServletRequest, null, null, null); //FIXME
		boolean response = false;
		try {
			if (uuid == null)
				response = portfolioManager.removePortfolioGroups(groupId);
			else
				response = portfolioManager.removePortfolioFromPortfolioGroups(uuid, groupId);

		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex));
			throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
		}
		return String.valueOf(response);
	}

}


text:
@implementation UIDevice (SLMFramework)

- (NSString *)slm_macaddress
{
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;

    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;

    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }

    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }

    if ((buf = (char *)malloc(len)) == NULL) {
        printf("Could not allocate memory. error!\n");
        return NULL;
    }

    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        free(buf);
        return NULL;
    }

    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);

    return outstring;
}

- (NSString *)slm_uniqueDeviceIdentifier
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)])
    {
        return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    }
    NSString *macaddress = [[UIDevice currentDevice] slm_macaddress];
    NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];

    NSString *stringToHash = [NSString stringWithFormat:@"%@%@",macaddress,bundleIdentifier];
    NSString *uniqueIdentifier = [stringToHash slm_md5];

    return uniqueIdentifier;
}

- (NSString *)slm_uniqueGlobalDeviceIdentifier
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)])
    {
        return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    }
    NSString *macaddress = [[UIDevice currentDevice] slm_macaddress];
    NSString *uniqueIdentifier = [macaddress slm_md5];

    return uniqueIdentifier;
}

@end


text:
var requirejs = require('../public/js/libs/r.js');

// Sets up the basic configuration
var baseConfig = {

  // All modules are located relative to this path
  baseUrl: "../public/js/",

  // Sets path names and paths for modules relative to the baseUrl
  paths: {

    "mobile": "app/config/MobileInit",

    "desktop": "app/config/DesktopInit"

  },

  // Wraps all scripts in an IIFE (Immediately Invoked Function Expression)
  // (function() { + content + }());
  wrap: true,

  // The optimized build file will use almond.js (AMD shim) instead of the larger Require.js
  name: "libs/almond",

  // Removes third-party license comments
  preserveLicenseComments: false,

  // Uses uglify.js for minification
  optimize: "uglify"

 };

// Creates an array of build configs, the baseConfig will
// be mixed into both the mobile and desktop builds below.

var configs = [

    {

        // Tells Require.js to look at mobileInit.js for all mobile shim and path configurations
        mainConfigFile: "../public/js/app/config/MobileInit.js",

        // Points to mobileInit.js (Remember that "mobile" is the module name for mobileInit.js)
        include: ["mobile"],

        // The optimized mobile build file will put into the app directory
        out: "../public/js/app/config/MobileInit.min.js"

    },

    {

        // Tells Require.js to look at desktopInit.js for all desktop shim and path configurations
        mainConfigFile: "../public/js/app/config/DesktopInit.js",

        // Points to desktopInit.js (Remember that "desktop" is the module name for desktopInit.js)
        include: ["desktop"],

        // The optimized desktop build file will put within the app directory
        out: "../public/js/app/config/DesktopInit.min.js"

    }

];

// Function used to mix in baseConfig to a new config target
function mix(target) {

    for (var prop in baseConfig) {

        if (baseConfig.hasOwnProperty(prop)) {

            target[prop] = baseConfig[prop];

        }

    }

    return target;

}

//Create a runner that will run a separate build for each item
//in the configs array. Thanks to @jwhitley for this cleverness
var runner = configs.reduceRight(function(prev, currentConfig) {

  return function (buildReportText) {

    requirejs.optimize(mix(currentConfig), prev);

  };

}, function(buildReportText) {

    console.log(buildReportText);

});

console.log("Building... this might take a few seconds");

//Run the builds
runner();


text:
namespace browser_sync {

PasswordDataTypeController::PasswordDataTypeController(
    const scoped_refptr<base::SingleThreadTaskRunner>& ui_thread,
    const base::Closure& error_callback,
    sync_driver::SyncClient* sync_client,
    const base::Closure& state_changed_callback)
    : NonUIDataTypeController(ui_thread, error_callback, sync_client),
      sync_client_(sync_client),
      state_changed_callback_(state_changed_callback) {}

syncer::ModelType PasswordDataTypeController::type() const {
  return syncer::PASSWORDS;
}

syncer::ModelSafeGroup PasswordDataTypeController::model_safe_group() const {
  return syncer::GROUP_PASSWORD;
}

PasswordDataTypeController::~PasswordDataTypeController() {}

bool PasswordDataTypeController::PostTaskOnBackendThread(
    const tracked_objects::Location& from_here,
    const base::Closure& task) {
  DCHECK(ui_thread()->BelongsToCurrentThread());
  if (!password_store_.get())
    return false;
  return password_store_->ScheduleTask(task);
}

bool PasswordDataTypeController::StartModels() {
  DCHECK(ui_thread()->BelongsToCurrentThread());
  DCHECK_EQ(MODEL_STARTING, state());

  sync_client_->GetSyncService()->AddObserver(this);

  OnStateChanged();

  password_store_ = sync_client_->GetPasswordStore();
  return !!password_store_.get();
}

void PasswordDataTypeController::StopModels() {
  DCHECK(ui_thread()->BelongsToCurrentThread());
  sync_client_->GetSyncService()->RemoveObserver(this);
}

void PasswordDataTypeController::OnStateChanged() {
  state_changed_callback_.Run();
}

}  // namespace browser_sync


text:
class NeoPixelWheel : public Adafruit_NeoPixel
{
    int _colorAnalogPin;
    int _brightnessAnalogPin;

  public:

    NeoPixelWheel(int numLeds, int dataPin, int colorAnalogPin, int brightnessAnalogPin ) :
      Adafruit_NeoPixel(numLeds, dataPin, NEO_GRB + NEO_KHZ800), _colorAnalogPin(colorAnalogPin),
      _brightnessAnalogPin(brightnessAnalogPin)
    {

    }

    /// <summary>
    /// Initializes this instance.
    /// </summary>
    void initialize()
    {
      // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
      if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
      // End of trinket special code

      begin();
      colorWipe(0);
      checkColorChange();
      show(); // Initialize all pixels to 'off'

    }

    byte colorIndexValue = 0;          // value read from the pot
    float brightnessIndexValue = 1.0;   // value read from the pot

    /// <summary>
    /// Gets a color wheel value (Adafruit function)
    /// </summary>
    /// Input a value 0 to 255 to get a color value.
    /// The colours are a transition r - g - b - back to r.
    /// <param name="WheelPos">The wheel position.</param>
    /// <returns></returns>
    uint32_t colorWheel(byte WheelPos) {
      WheelPos = 255 - WheelPos;
      if (WheelPos < 85) {
        return Color(255 - WheelPos * 3, 0, WheelPos * 3);
      }
      if (WheelPos < 170) {
        WheelPos -= 85;
        return Color(0, WheelPos * 3, 255 - WheelPos * 3);
      }
      WheelPos -= 170;
      return Color(WheelPos * 3, 255 - WheelPos * 3, 0);
    }

    /// <summary>
    /// Sets all pixels to one color, without calling show()
    /// </summary>
    /// <param name="c">The c.</param>
    void setAllPixels(uint32_t c = 0) {
      for (uint16_t i = 0; i < numPixels(); i++) {
        setPixelColor(i, c);
      }
    }

    /// <summary>
    /// Fill the dots one after the other with a color (Adafruit function)
    /// </summary>
    /// <param name="c">The color.</param>
    /// <param name="wait">The wait delay after each pixel is set.</param>
    void colorWipe(uint32_t c = 0, uint8_t wait = 0) {
      for (uint16_t i = 0; i < numPixels(); i++) {
        setPixelColor(i, c);
        if ( wait > 0 )
          show();
        delay(wait);
      }
      if ( wait <= 0 )
        show();
    }

    /// <summary>
    /// Checks the color and brightness change by reading the analog input
    /// </summary>
    /// <returns>true if there was a change</returns>
    bool checkColorChange()
    {
      // read the analog in value:
      byte newSensorValue = map(analogRead(_colorAnalogPin), 0, 1023, 0, 255);
      bool updateNeo = false;
      if ( newSensorValue != colorIndexValue )
      {
        colorIndexValue = newSensorValue;
        updateNeo = true;
      }

      float newSensorBrightness = map(analogRead(_brightnessAnalogPin), 0, 1023, 0, 255);
      if (  brightnessIndexValue != newSensorBrightness )
      {
        updateNeo = true;
        brightnessIndexValue = newSensorBrightness;
        setBrightness(brightnessIndexValue);
      }

      return updateNeo;
    }
};

#endif;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
org.apache.commons.collections.bidimap Class Hierarchy (Commons Collections 3.2.1 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.apache.commons.collections.bidimap

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

org.apache.commons.collections.collection.AbstractCollectionDecorator (implements java.util.Collection)

org.apache.commons.collections.bidimap.AbstractDualBidiMap.View

org.apache.commons.collections.bidimap.AbstractDualBidiMap.EntrySet (implements java.util.Set)

org.apache.commons.collections.bidimap.AbstractDualBidiMap.KeySet (implements java.util.Set)

org.apache.commons.collections.bidimap.AbstractDualBidiMap.Values (implements java.util.Set)

org.apache.commons.collections.bidimap.AbstractDualBidiMap (implements org.apache.commons.collections.BidiMap)

org.apache.commons.collections.bidimap.DualHashBidiMap (implements java.io.Serializable)

org.apache.commons.collections.bidimap.DualTreeBidiMap (implements java.io.Serializable, org.apache.commons.collections.SortedBidiMap)

org.apache.commons.collections.bidimap.AbstractDualBidiMap.BidiMapIterator (implements org.apache.commons.collections.MapIterator, org.apache.commons.collections.ResettableIterator)

org.apache.commons.collections.iterators.AbstractIteratorDecorator (implements java.util.Iterator)

org.apache.commons.collections.bidimap.AbstractDualBidiMap.EntrySetIterator
org.apache.commons.collections.bidimap.AbstractDualBidiMap.KeySetIterator
org.apache.commons.collections.bidimap.AbstractDualBidiMap.ValuesIterator

org.apache.commons.collections.map.AbstractMapDecorator (implements java.util.Map)

org.apache.commons.collections.bidimap.AbstractBidiMapDecorator (implements org.apache.commons.collections.BidiMap)

org.apache.commons.collections.bidimap.AbstractOrderedBidiMapDecorator (implements org.apache.commons.collections.OrderedBidiMap)

org.apache.commons.collections.bidimap.AbstractSortedBidiMapDecorator (implements org.apache.commons.collections.SortedBidiMap)

org.apache.commons.collections.bidimap.UnmodifiableSortedBidiMap (implements org.apache.commons.collections.Unmodifiable)

org.apache.commons.collections.bidimap.UnmodifiableOrderedBidiMap (implements org.apache.commons.collections.Unmodifiable)

org.apache.commons.collections.bidimap.UnmodifiableBidiMap (implements org.apache.commons.collections.Unmodifiable)

org.apache.commons.collections.map.AbstractSortedMapDecorator (implements java.util.SortedMap)

org.apache.commons.collections.bidimap.DualTreeBidiMap.ViewMap

org.apache.commons.collections.keyvalue.AbstractMapEntryDecorator (implements org.apache.commons.collections.KeyValue, java.util.Map.Entry)

org.apache.commons.collections.bidimap.AbstractDualBidiMap.MapEntry

org.apache.commons.collections.bidimap.DualTreeBidiMap.BidiOrderedMapIterator (implements org.apache.commons.collections.OrderedMapIterator, org.apache.commons.collections.ResettableIterator)

org.apache.commons.collections.bidimap.TreeBidiMap (implements org.apache.commons.collections.OrderedBidiMap)

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2001-2008 The Apache Software Foundation. All Rights Reserved.


text:
$LOAD_PATH.unshift File.expand_path('../lib', Dir.pwd)
require 'do_sinatra'


text:
using UnityEngine;
using System.Collections;

public class MinionCard : Card, damageable {

    protected int baseAttack;
    protected int baseHealth;
    protected int useHealth;
	protected int useAttack;

    public void SetBaseAttack(int baseAttack)
    {
        this.baseAttack = baseAttack;
    }
    public int GetBaseAttack()
    {
        return baseAttack;
    }
    public void SetBaseHealth(int baseHealth)
    {
        this.baseHealth = baseHealth;
    }
    public int GetBaseHealth()
    {
        return baseHealth;
    }

    public override void OnPlay()
    {

    }

    public override void OnPull()
    {

    }

    public void ModifyHealth(int amount)
    {
        useHealth += amount;
        cardAvatar.ModifyHealth(amount);
    }

    public int GetHealth()
    {
        return useHealth;
    }

    public void SetHealth(int health)
    {
        baseHealth = health;
		cardAvatar.SetTotalHealth (baseHealth);
    }

	public void SetAttack(int attack)
	{
		useAttack = attack;
		cardAvatar.SetAttack (attack);
	}

	public void ModifyAttack(int amount)
	{
		useAttack += amount;
		cardAvatar.ModifyAttack (amount);
	}

	public int GetAttack()
	{
		return useAttack;
	}

}


text:
var screenTests;

$(document).ready(function(){
    if (!(screenTests instanceof Array)) return;

    var content = document.getElementById('testing-page');
    var controls = $('.testing-controls');
    var testList = $('.testing-list', controls).empty();

    screenTests.forEach(function(test){
        testList.append(
            $('

').addClass('testing-list__item').text(test.title).data('test', test)
        );
    });

    testList.on('click', '.testing-list__item', function(){
        $('.testing-list__item_current', testList).removeClass('testing-list__item_current');
        var test = $(this).addClass('testing-list__item_current').data('test');
        setCurrentTest(test);
    });

    function setCurrentTest(test) {
        content.setAttribute('src', test.page);
        $(content).on('load', function(){
            var page = content.contentDocument;
            var testingElement = $(test.element, page);
            if (!testingElement.length) return;

            var testingOffset = testingElement.offset();

            var screen = $('

').append($('').attr('src', test.screen)).css({
                'position': 'absolute',
                'z-index': 1,
                'width': testingElement.width(),
                'height': testingElement.height()
            });
            testingElement.before(screen).offset(testingOffset).css({
                'opacity':'0.5',
                'z-index': 2
            });
            screen.offset(testingOffset);

        });
    }

});


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.ponyvillelive.pvlmobile.ui.AboutActivity" >
    <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never" />
</menu>


text:
<meta charset="UTF-8">
<title>DatePattern.expr - biomedicus-core</title>
<link rel="stylesheet" href="../../../style.css">

biomedicus-core / edu.umn.biomedicus.time / DatePattern / expr

expr

val expr: SearchExpr


text:
import {HashTable} from './base';
import ConditionsParser from './conditionsParser';

export class Condition {
    static operatorsValue: HashTable<Function> = null;
    static get operators() {
        if (Condition.operatorsValue != null) return Condition.operatorsValue;
        Condition.operatorsValue = {
            empty: function (left, right) { return !left; },
            notempty: function (left, right) { return !(!left); },
            equal: function (left, right) { return left == right; },
            notequal: function (left, right) { return left != right; },
            contains: function (left, right) { return left && left["indexOf"] && left.indexOf(right) > -1; },
            notcontains: function (left, right) { return !left || !left["indexOf"] || left.indexOf(right) == -1; },
            greater: function (left, right) { return left > right; },
            less: function (left, right) { return left < right; },
            greaterorequal: function (left, right) { return left >= right; },
            lessorequal: function (left, right) { return left <= right; }
        };
        return Condition.operatorsValue;
    }
    private opValue: string = "equal";
    public left: any;
    public right: any;
    public get operator(): string { return this.opValue; }
    public set operator(value: string) {
        if (!value) return;
        value = value.toLowerCase();
        if (!Condition.operators[value]) return;
        this.opValue = value;
    }
    public perform(left: any = null, right: any = null): boolean {
        if (!left) left = this.left;
        if (!right) right = this.right;

        return Condition.operators[this.operator](this.getPureValue(left), this.getPureValue(right));
    }
    private getPureValue(val: any): any {
        if (!val || (typeof val != "string")) return val;
        var str = "";
        if (val.length > 0 && (val[0] == "'" || val[0] == '"'))  val = val.substr(1);
        var len = val.length;
        if (len > 0 && (val[len - 1] == "'" || val[len - 1] == '"'))  val = val.substr(0, len - 1);
        return val;
    }
}
export class ConditionNode {
    private connectiveValue: string = "and";
    public children: Array<any> = [];
    public constructor() { }
    public get connective(): string { return this.connectiveValue; }
    public set connective(value: string) {
        if (!value) return;
        value = value.toLowerCase();
        if (value == "&" || value == "&&") value = "and";
        if (value == "|" || value == "||") value = "or";
        if (value != "and" && value != "or") return;
        this.connectiveValue = value;
    }
    public get isEmpty() { return this.children.length == 0; }
    public clear() {
        this.children = [];
        this.connective = "and";
    }
}
export class ConditionRunner {
    private expressionValue: string;
    private root: ConditionNode;
    private values: HashTable<any>;
    public constructor(expression: string) {
        this.root = new ConditionNode();
        this.expression = expression;
    }
    public get expression(): string { return this.expressionValue; }
    public set expression(value: string) {
        if (this.expression == value) return;
        this.expressionValue = value;
        new ConditionsParser().parse(this.expressionValue, this.root);
    }
    public run(values: HashTable<any>): boolean {
        this.values = values;
        return this.runNode(this.root);
    }
    private runNode(node: ConditionNode): boolean {
        var onFirstFail = node.connective == "and";
        for (var i = 0; i < node.children.length; i++) {
            var res = this.runNodeCondition(node.children[i]);
            if (!res && onFirstFail) return false;
            if (res && !onFirstFail) return true;
        }
        return onFirstFail;
    }
    private runNodeCondition(value: any): boolean {
        if (!value) return false;
        if (value["children"]) return this.runNode(value);
        if (value["left"]) return this.runCondition(value);
        return false;
    }
    private runCondition(condition: Condition): boolean {
        var left = condition.left;
        var name = this.getValueName(left);
        if (name) {
            if (!(name in this.values)) return false;
            left = this.values[name];
        }
        var right = condition.right;
        name = this.getValueName(right);
        if (name) {
            if (!(name in this.values)) return false;
            right = this.values[name];
        }
        return condition.perform(left, right);
    }
    private getValueName(nodeValue: any) {
        if (!nodeValue) return null;
        if (typeof nodeValue !== 'string') return null;
        if (nodeValue.length < 3 || nodeValue[0] != '{' || nodeValue[nodeValue.length - 1] != '}') return null;
        return nodeValue.substr(1, nodeValue.length - 2);
    }
}


text:
package mgo

import "fmt"

// ---------------------------------------------------------------------------
// Logging integration.

// Avoid importing the log type information unnecessarily.  There's a small cost
// associated with using an interface rather than the type.  Depending on how
// often the logger is plugged in, it would be worth using the type instead.
type log_Logger interface {
	Output(calldepth int, s string) error
}

var globalLogger log_Logger
var globalDebug bool

// Specify the *log.Logger object where log messages should be sent to.
func SetLogger(logger log_Logger) {
	globalLogger = logger
}

// Enable the delivery of debug messages to the logger.  Only meaningful
// if a logger is also set.
func SetDebug(debug bool) {
	globalDebug = debug
}

func log(v ...interface{}) {
	if globalLogger != nil {
		globalLogger.Output(2, fmt.Sprint(v...))
	}
}

func logln(v ...interface{}) {
	if globalLogger != nil {
		globalLogger.Output(2, fmt.Sprintln(v...))
	}
}

func logf(format string, v ...interface{}) {
	if globalLogger != nil {
		globalLogger.Output(2, fmt.Sprintf(format, v...))
	}
}

func debug(v ...interface{}) {
	if globalDebug && globalLogger != nil {
		globalLogger.Output(2, fmt.Sprint(v...))
	}
}

func debugln(v ...interface{}) {
	if globalDebug && globalLogger != nil {
		globalLogger.Output(2, fmt.Sprintln(v...))
	}
}

func debugf(format string, v ...interface{}) {
	if globalDebug && globalLogger != nil {
		globalLogger.Output(2, fmt.Sprintf(format, v...))
	}
}


text:
Template.category.viewmodel(
  function(category){
    // Add all properties in the category to this view model
    return category;
  },
  {
    hovering: false,
    isActive: function() {
      return this.parent().selected() === this._id();
    },
    select: function() {
      this.parent().selected(this._id());
    },
    delete: function() {
      var self = this;
      Client.alert({
        header: "Are you sure you want to delete category '" + self.name() + "'?",
        description: "You're about to delete category '" + self.name() + "'. This will delete all contacts in this category. Do you want to delete it?",
        image: "trash",
        onApprove: function () {
          Categories.remove(self._id());
        }
      });
    }
  }
);


text:
//
//  ACHotRoutesCitiesController.m
//  A-cyclist
//
//  Created by tunny on 15/8/16.
//  Copyright (c) 2015年 tunny. All rights reserved.
//

#import "ACHotRoutesCitiesController.h"
#import "ACHotRoutesCitesCellModel.h"
#import "ACHotRoutesCitiesCellView.h"

@interface ACHotRoutesCitiesController ()
/** 城市列表 */
@property (nonatomic, strong) NSMutableArray *cityList;
@end

@implementation ACHotRoutesCitiesController

- (NSMutableArray *)cityList
{
    if (_cityList == nil) {
        _cityList = [NSMutableArray array];
    }

    return _cityList;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.rowHeight = 44;
    //从plist中加载城市
    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cities.plist" ofType:nil]];

    [array enumerateObjectsUsingBlock:^(NSString *cityName, NSUInteger idx, BOOL *stop) {
        ACHotRoutesCitesCellModel *cityModel = [ACHotRoutesCitesCellModel citiesWithName:cityName];
        cityModel.option = ^(NSIndexPath *indexPath){
            if ([self.delegate respondsToSelector:@selector(hotRoutesCityClick:cityName:)]) {
                ACHotRoutesCitesCellModel *model = self.cityList[indexPath.row];
                [self.delegate hotRoutesCityClick:self cityName:model.cityName];
            }
        };

        [self.cityList addObject:cityModel];
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.cityList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ACHotRoutesCitiesCellView *cell = [ACHotRoutesCitiesCellView settingViewCellWithTableView:tableView];

    ACHotRoutesCitesCellModel *cellModel = self.cityList[indexPath.row];
    cell.cellModel = cellModel;

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //1.取消选中
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    //取模型
    ACHotRoutesCitesCellModel *cellModel = self.cityList[indexPath.row];

    //2.执行对应的选中操作
    if (cellModel.option) {
        cellModel.option(indexPath);
    }
}

@end


text:
<?php

namespace Google\Cloud\Dev\DocFx\Toc;

use Google\Cloud\Dev\DocFx\Node\ClassNode;

/**
 * Class to output the DocFX Table of Contents
 */
class NamespaceToc
{
    protected array $items = [];
    private bool $isVersionNamespace = false;

    public function __construct(
        private string $namespace,
        private string $name
    ) {}

    public function addNode(ClassNode $classNode): void
    {
        $uid = $classNode->getFullname();
        $namespace = $this->namespace . '\\';
        $parts = explode('\\', str_replace('\\' . $namespace, '', $uid));
        if (count($parts) > 1) {
            $nestedNs = $this->namespace . '\\' . $parts[0];
            $nestedUid = 'ns:' . $nestedNs;
            if (!isset($this->items[$nestedUid])) {
                $this->items[$nestedUid] = new NamespaceToc($nestedNs, $parts[0]);
            }
            $this->items[$nestedUid]->addNode($classNode);
        } else {
            $this->items[$uid] = new ClassToc($classNode);

            if ($this->items[$uid]->isServiceClass()) {
                $this->isVersionNamespace = true;
            }
        }
    }

    public function toToc(): array
    {
        $tocArray = [
            'name' => $this->name,
            'uid'  => 'ns:' . $this->namespace,
            'items' => [],
        ];

        // Organize into "Services", "Messages", and "Enums" for version namespaces
        // e.g. "\Google\Cloud\Vision\V1"
        if ($this->isVersionNamespace) {
            $tocArray['name'] = $this->namespace;
            if ($services = $this->getServicesToc()) {
                $tocArray['items'][] = [
                    'name' => 'Services',
                    'uid'  => 'services:' . $this->namespace,
                    'items' => $services,
                ];
            }
            if ($messages = $this->getMessagesToc()) {
                $tocArray['items'][] = [
                    'name' => 'Messages',
                    'uid'  => 'messages:' . $this->namespace,
                    'items' => $messages,
                ];
            }
            if ($enums = $this->getEnumsToc()) {
                $tocArray['items'][] = [
                    'name' => 'Enums',
                    'uid'  => 'enums:' . $this->namespace,
                    'items' => $enums,
                ];
            };
            $tocArray['items'] = array_merge($tocArray['items'], $this->getOthersToc());
        } else {
            foreach ($this->items as $item) {
                $tocArray['items'][] = $item->toToc();
            }
        }

        return $tocArray;
    }

    protected function getServicesToc(): array
    {
        // Get a list of all Service classes
        $services = [];
        foreach ($this->items as $item) {
            if ($item instanceof ClassToc && $item->isServiceClass()) {
                $services[] = $item->toToc();
            } elseif ($item instanceof NamespaceToc) {
                $services = array_merge($services, $item->getServicesToc());
            }
        }

        // Do not wrap in namespace if none exist or we're in top level namespace
        if (!$services || $this->isVersionNamespace) {
            return $services;
        }

        return [
            [
                'name' => $this->name,
                'uid'  => 'ns:' . $this->namespace,
                'items' => $services,
            ],
        ];
    }

    protected function getMessagesToc(): array
    {
        // Get a list of all protobuf messages
        $messages = [];
        foreach ($this->items as $item) {
            if ($item instanceof ClassToc && $item->isProtobufMessageClass()) {
                $messages[] = $item->toToc();
            } elseif ($item instanceof NamespaceToc) {
                $messages = array_merge($messages, $item->getMessagesToc());
            }
        }

        // Do not wrap in namespace if none exist or we're in top level namespace
        if (!$messages || $this->isVersionNamespace) {
            return $messages;
        }

        return [
            [
                'name' => $this->name,
                'uid'  => 'ns:' . $this->namespace,
                'items' => $messages,
            ],
        ];
    }

    protected function getEnumsToc(): array
    {
        // Get a list of all protobuf enums
        $enums = [];
        foreach ($this->items as $item) {
            if ($item instanceof ClassToc && $item->isProtobufEnumClass()) {
                $enums[] = $item->toToc();
            } elseif ($item instanceof NamespaceToc) {
                $enums = array_merge($enums, $item->getEnumsToc());
            }
        }
        // Do not wrap in namespace if none exist or we're in top level namespace
        if (!$enums || $this->isVersionNamespace) {
            return $enums;
        }

        return [
            [
                'name' => $this->name,
                'uid'  => 'ns:' . $this->namespace,
                'items' => $enums,
            ],
        ];
    }

    protected function getOthersToc(): array
    {
        // Get a list of all other classes which are not gapic clients / enums or protobuf messages / enums
        $others = [];
        foreach ($this->items as $item) {
            if (
                $item instanceof ClassToc
                && !$item->isServiceClass()
                && !$item->isProtobufMessageClass()
                && !$item->isProtobufEnumClass()
            ) {
                $others[] = $item->toToc();
            } elseif ($item instanceof NamespaceToc) {
                $others = array_merge($others, $item->getOthersToc());
            }
        }
        // Do not wrap in namespace if none exist or we're in top level namespace
        if (!$others || $this->isVersionNamespace) {
            return $others;
        }

        return [
            [
                'name' => $this->name,
                'uid'  => 'ns:' . $this->namespace,
                'items' => $others,
            ],
        ];
    }
}


text:
import unittest

import IECore

import Gaffer
import GafferTest
import GafferCortex

class ParameterHandlerTest( GafferTest.TestCase ) :

	def testFactory( self ) :

		p = IECore.IntParameter( "i", "d", 10 )

		n = Gaffer.Node()
		h = GafferCortex.ParameterHandler.create( p )
		h.setupPlug( n )

		self.assertIsInstance( h, GafferCortex.ParameterHandler )
		self.assertIsInstance( n["i"], Gaffer.IntPlug )

	def testCustomHandler( self ) :

		class CustomParameter( IECore.IntParameter ) :

			def __init__( self, name, description, defaultValue ) :

				IECore.IntParameter.__init__( self, name, description, defaultValue )

		IECore.registerRunTimeTyped( CustomParameter )

		class CustomHandler( GafferCortex.ParameterHandler ) :

			def __init__( self, parameter ) :

				GafferCortex.ParameterHandler.__init__( self )

				self.__parameter = parameter
				self.__plug = None

			def parameter( self ) :

				return self.__parameter

			def setupPlug( self, plugParent, direction, flags ) :

				self.__plug = plugParent.getChild( self.__parameter.name )
				if not isinstance( self.__plug, Gaffer.IntPlug ) or self.__plug.direction() != direction :
					self.__plug = Gaffer.IntPlug(
						self.__parameter.name,
						Gaffer.Plug.Direction.In,
						self.__parameter.numericDefaultValue,
						self.__parameter.minValue,
						self.__parameter.maxValue
					)

				## \todo: should ParameterHandler::setupPlugFlags be exposed so we can call it here?
				self.__plug.setFlags( flags )

				plugParent[self.__parameter.name] = self.__plug

			def plug( self ) :

				return self.__plug

			def setParameterValue( self ) :

				self.__parameter.setValue( self.__plug.getValue() * 10 )

			def setPlugValue( self ) :

				self.__plug.setValue( self.__parameter.getNumericValue() // 10 )

		GafferCortex.ParameterHandler.registerParameterHandler( CustomParameter, CustomHandler )

		p = IECore.Parameterised( "" )
		p.parameters().addParameter(

			CustomParameter(

				"i",
				"d",
				10

			)

		)

		ph = GafferCortex.ParameterisedHolderNode()
		ph.setParameterised( p )

		self.assertEqual( ph["parameters"]["i"].getValue(), 1 )

		with ph.parameterModificationContext() as parameters :

			p["i"].setNumericValue( 100 )

		self.assertEqual( ph["parameters"]["i"].getValue(), 10 )

		ph["parameters"]["i"].setValue( 1000 )

		ph.setParameterisedValues()

		self.assertEqual( p["i"].getNumericValue(), 10000 )

	def testPlugMethod( self ) :

		p = IECore.IntParameter( "i", "d", 10 )

		n = Gaffer.Node()
		h = GafferCortex.ParameterHandler.create( p )
		h.setupPlug( n )

		self.assertEqual( h.plug().getName(), "i" )
		self.assertTrue( h.plug().parent().isSame( n ) )

	def testCompoundParameterHandler( self ) :

		c = IECore.CompoundParameter(

			"c",
			"",

			[
				IECore.IntParameter( "i", "" ),
				IECore.FloatParameter( "f", "" )
			]

		)

		n = Gaffer.Node()

		h = GafferCortex.CompoundParameterHandler( c )
		h.setupPlug( n )

		self.assertTrue( h.childParameterHandler( c["i"] ).parameter().isSame( c["i"] ) )
		self.assertTrue( h.childParameterHandler( c["f"] ).parameter().isSame( c["f"] ) )

	def testReadOnly( self ) :

		p = IECore.IntParameter( "i", "d", 10 )

		n = Gaffer.Node()
		h = GafferCortex.ParameterHandler.create( p )
		h.setupPlug( n )

		self.assertFalse( Gaffer.MetadataAlgo.getReadOnly( h.plug() ) )

		p.userData()["gaffer"] = IECore.CompoundObject( {
			"readOnly" : IECore.BoolData( True ),
		} )

		h.setupPlug( n )
		self.assertTrue( Gaffer.MetadataAlgo.getReadOnly( h.plug() ) )

	def testNonDefaultFlags( self ) :

		p = IECore.IntParameter( "i", "d", 10 )

		n = Gaffer.Node()
		h = GafferCortex.ParameterHandler.create( p )

		h.setupPlug( n )
		self.assertTrue( h.plug().getFlags( Gaffer.Plug.Flags.Dynamic ) )
		self.assertTrue( h.plug().getFlags( Gaffer.Plug.Flags.Serialisable ) )

		h.setupPlug( n, flags = Gaffer.Plug.Flags.Default )
		self.assertFalse( h.plug().getFlags( Gaffer.Plug.Flags.Dynamic ) )
		self.assertTrue( h.plug().getFlags( Gaffer.Plug.Flags.Serialisable ) )

		h.setupPlug( n, flags = Gaffer.Plug.Flags.Default & ~Gaffer.Plug.Flags.Serialisable )
		self.assertFalse( h.plug().getFlags( Gaffer.Plug.Flags.Dynamic ) )
		self.assertFalse( h.plug().getFlags( Gaffer.Plug.Flags.Serialisable ) )

	def testHash( self ) :

		c = IECore.CompoundParameter(

			"c",
			"",

			[
				IECore.IntParameter( "i", "" ),
				IECore.FloatParameter( "f", "" )
			]

		)

		n = Gaffer.Node()

		h = GafferCortex.CompoundParameterHandler( c )
		h.setupPlug( n )

		hash1 = h.hash()
		n["c"]["i"].setValue( 10 )
		hash2 = h.hash()
		n["c"]["f"].setValue( 10 )
		hash3 = h.hash()

		self.assertNotEqual( hash1, hash2 )
		self.assertNotEqual( hash1, hash3 )
		self.assertNotEqual( hash2, hash3 )

	def testSubstitutions( self ) :

		p = IECore.StringParameter( "s", "d", "" )

		n = Gaffer.Node()
		h = GafferCortex.ParameterHandler.create( p )
		h.setupPlug( n )
		self.assertEqual( n["s"].substitutions(), IECore.StringAlgo.Substitutions.AllSubstitutions )

		# adding substitutions should affect the plug
		p.userData()["gaffer"] = IECore.CompoundObject( {
			"substitutions" : IECore.IntData( IECore.StringAlgo.Substitutions.AllSubstitutions & ~IECore.StringAlgo.Substitutions.FrameSubstitutions ),
		} )
		h.setupPlug( n )
		self.assertEqual( n["s"].substitutions(), IECore.StringAlgo.Substitutions.AllSubstitutions & ~IECore.StringAlgo.Substitutions.FrameSubstitutions )

		# make sure connections are maintained as well
		nn = Gaffer.Node()
		nn["driver"] = Gaffer.StringPlug()
		n["s"].setInput( nn["driver"] )
		# we're forcing a re-creation of the plug because substitutions have changed
		p.userData()["gaffer"] = IECore.CompoundObject( {
			"substitutions" : IECore.IntData( IECore.StringAlgo.Substitutions.AllSubstitutions & ~IECore.StringAlgo.Substitutions.VariableSubstitutions ),
		} )
		h.setupPlug( n )
		self.assertEqual( n["s"].substitutions(), IECore.StringAlgo.Substitutions.AllSubstitutions & ~IECore.StringAlgo.Substitutions.VariableSubstitutions )
		self.assertEqual( n["s"].getInput(), nn["driver"] )

if __name__ == "__main__":
	unittest.main()


text:
package com.github.rollingmetrics.histogram.accumulator;

import com.codahale.metrics.Reservoir;
import com.codahale.metrics.Snapshot;
import com.github.rollingmetrics.util.Clock;
import com.github.rollingmetrics.histogram.HdrBuilder;
import com.github.rollingmetrics.util.MockExecutor;
import org.junit.Test;

import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import static junit.framework.TestCase.assertEquals;

public class ResetByChunksAccumulatorTest {

    @Test
    public void test() {
        AtomicLong time = new AtomicLong(0);
        Clock wallClock = Clock.mock(time);
        Reservoir reservoir = new HdrBuilder(wallClock)
                .resetReservoirPeriodicallyByChunks(Duration.ofMillis(3000), 3)
                .withBackgroundExecutor(MockExecutor.INSTANCE)
                .buildReservoir();

        reservoir.update(10);
        reservoir.update(20);
        Snapshot snapshot = reservoir.getSnapshot();
        assertEquals(10, snapshot.getMin());
        assertEquals(20, snapshot.getMax());

        time.getAndAdd(900); // 900
        reservoir.update(30);
        reservoir.update(40);
        snapshot = reservoir.getSnapshot();
        assertEquals(10, snapshot.getMin());
        assertEquals(40, snapshot.getMax());

        time.getAndAdd(99); // 999
        reservoir.update(9);
        reservoir.update(60);
        snapshot = reservoir.getSnapshot();
        assertEquals(9, snapshot.getMin());
        assertEquals(60, snapshot.getMax());

        time.getAndAdd(1); // 1000
        reservoir.update(12);
        reservoir.update(70);
        snapshot = reservoir.getSnapshot();
        assertEquals(9, snapshot.getMin());
        assertEquals(70, snapshot.getMax());

        time.getAndAdd(1001); // 2001
        reservoir.update(13);
        reservoir.update(80);
        snapshot = reservoir.getSnapshot();
        assertEquals(9, snapshot.getMin());
        assertEquals(80, snapshot.getMax());

        time.getAndAdd(1000); // 3001
        snapshot = reservoir.getSnapshot();
        assertEquals(9, snapshot.getMin());
        assertEquals(80, snapshot.getMax());

        time.getAndAdd(999); // 4000
        snapshot = reservoir.getSnapshot();
        assertEquals(12, snapshot.getMin());
        assertEquals(80, snapshot.getMax());
        reservoir.update(1);
        reservoir.update(200);
        snapshot = reservoir.getSnapshot();
        assertEquals(1, snapshot.getMin());
        assertEquals(200, snapshot.getMax());

        time.getAndAdd(10000); // 14000
        snapshot = reservoir.getSnapshot();
        assertEquals(0, snapshot.getMin());
        assertEquals(0, snapshot.getMax());
        reservoir.update(3);

        time.addAndGet(3999); // 17999
        snapshot = reservoir.getSnapshot();
        assertEquals(3, snapshot.getMax());

        time.addAndGet(1); // 18000
        snapshot = reservoir.getSnapshot();
        assertEquals(0, snapshot.getMax());
    }

    @Test
    public void testToString() {
        new HdrBuilder().resetReservoirPeriodicallyByChunks(Duration.ofSeconds(60), 3)
                .buildReservoir().toString();
    }

    @Test(timeout = 32000)
    public void testThatConcurrentThreadsNotHungWithThreeChunks() throws InterruptedException {
        Reservoir reservoir = new HdrBuilder()
                .resetReservoirPeriodicallyByChunks(Duration.ofSeconds(3), 3)
                .buildReservoir();

        HistogramUtil.runInParallel(reservoir, TimeUnit.SECONDS.toMillis(30));
    }

}