text:
'use strict';

import * as appInsights from 'applicationinsights';
import {isObject} from 'vs/base/common/types';
import {safeStringify, mixin} from 'vs/base/common/objects';
import {TPromise} from 'vs/base/common/winjs.base';

namespace AI {

	let _initialized = false;

	function ensureAIEngineIsInitialized(): void {
		if (_initialized === false) {
			// we need to pass some fake key, otherwise AI throws an exception
			appInsights.setup('2588e01f-f6c9-4cd6-a348-143741f8d702')
				.setAutoCollectConsole(false)
				.setAutoCollectExceptions(false)
				.setAutoCollectPerformance(false)
				.setAutoCollectRequests(false);

			_initialized = true;
		}
	}

	export function getClient(aiKey: string): typeof appInsights.client {

		ensureAIEngineIsInitialized();

		const client = appInsights.getClient(aiKey);
		client.channel.setOfflineMode(true);
		client.context.tags[client.context.keys.deviceMachineName] = ''; //prevent App Insights from reporting machine name
		if (aiKey.indexOf('AIF-') === 0) {
			client.config.endpointUrl = 'https://vortex.data.microsoft.com/collect/v1';
		}
		return client;
	}
}

interface Properties {
	[key: string]: string;
}

interface Measurements {
	[key: string]: number;
}

export class AIAdapter {

	private _aiClient: typeof appInsights.client;

	constructor(
		private _eventPrefix: string,
		private _defaultData: { [key: string]: any },
		aiKeyOrClientFactory: string | (() => typeof appInsights.client) // allow factory function for testing
	) {
		if (!this._defaultData) {
			this._defaultData = Object.create(null);
		}

		if (typeof aiKeyOrClientFactory === 'string') {
			this._aiClient = AI.getClient(aiKeyOrClientFactory);
		} else if (typeof aiKeyOrClientFactory === 'function') {
			this._aiClient = aiKeyOrClientFactory();
		}
	}

	private static _getData(data?: any): { properties: Properties, measurements: Measurements } {

		const properties: Properties = Object.create(null);
		const measurements: Measurements = Object.create(null);

		const flat = Object.create(null);
		AIAdapter._flaten(data, flat);

		for (let prop in flat) {
			// enforce property names less than 150 char, take the last 150 char
			prop = prop.length > 150 ? prop.substr(prop.length - 149) : prop;
			var value = flat[prop];

			if (typeof value === 'number') {
				measurements[prop] = value;

			} else if (typeof value === 'boolean') {
				measurements[prop] = value ? 1 : 0;

			} else if (typeof value === 'string') {
				//enforce property value to be less than 1024 char, take the first 1024 char
				properties[prop] = value.substring(0, 1023);

			} else if (typeof value !== 'undefined' && value !== null) {
				properties[prop] = value;
			}
		}

		return {
			properties,
			measurements
		};
	}

	private static _flaten(obj: any, result: {[key: string]: any }, order: number = 0, prefix?: string): void {
		if (!obj) {
			return;
		}

		for(var item of Object.getOwnPropertyNames(obj)){
			const value = obj[item];
			const index = prefix ? prefix + item : item;

			if (Array.isArray(value)) {
				result[index] = safeStringify(value);

			} else if (value instanceof Date) {
				// TODO unsure why this is here and not in _getData
				result[index] = value.toISOString();

			} else if (isObject(value)) {
				if (order < 2) {
					AIAdapter._flaten(value, result, order + 1, index + '.');
				} else {
					result[index] = safeStringify(value);
				}
			} else {
				result[index] = value;
			}
		}
	}

	public log(eventName: string, data?: any): void {
		if (!this._aiClient) {
			return;
		}
		data = mixin(data, this._defaultData);
		let {properties, measurements} = AIAdapter._getData(data);
		this._aiClient.trackEvent(this._eventPrefix + '/' + eventName, properties, measurements);
	}

	public dispose(): TPromise<any> {
		if (this._aiClient) {
			return new TPromise(resolve => {
				this._aiClient.sendPendingData(() => {
					// all data flushed
					this._aiClient = undefined;
					resolve(void 0);
				});
			});
		}
	}
}


text:
package com.thoughtworks.go.server.service.dd;

import com.thoughtworks.go.domain.materials.MaterialConfig;

/*
* Understands: Throws this exception when FainIn backtracking reaches the set limit
*/
public class MaxBackTrackLimitReachedException extends RuntimeException {
    public MaxBackTrackLimitReachedException(MaterialConfig material) {
        super("Maximum Backtracking limit reached while trying to resolve revisions for material " + material);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef	_FCNTL_
#ifdef __cplusplus
extern "C" {
#endif
#define	_FCNTL_
#include <_ansi.h>
#define	_FOPEN		(-1)	/* from sys/file.h, kernel use only */
#define	_FREAD		0x0001	/* read enabled */
#define	_FWRITE		0x0002	/* write enabled */
#define	_FAPPEND	0x0008	/* append (writes guaranteed at the end) */
#define	_FMARK		0x0010	/* internal; mark during gc() */
#define	_FDEFER		0x0020	/* internal; defer for next gc pass */
#define	_FASYNC		0x0040	/* signal pgrp when data ready */
#define	_FSHLOCK	0x0080	/* BSD flock() shared lock present */
#define	_FEXLOCK	0x0100	/* BSD flock() exclusive lock present */
#define	_FCREAT		0x0200	/* open with file create */
#define	_FTRUNC		0x0400	/* open with truncation */
#define	_FEXCL		0x0800	/* error on open if file exists */
#define	_FNBIO		0x1000	/* non blocking I/O (sys5 style) */
#define	_FSYNC		0x2000	/* do all writes synchronously */
#define	_FNONBLOCK	0x4000	/* non blocking I/O (POSIX style) */
#define	_FNDELAY	_FNONBLOCK	/* non blocking I/O (4.2 style) */
#define	_FNOCTTY	0x8000	/* don't assign a ctty on this open */

#define	O_ACCMODE	(O_RDONLY|O_WRONLY|O_RDWR)

/*
 * Flag values for open(2) and fcntl(2)
 * The kernel adds 1 to the open modes to turn it into some
 * combination of FREAD and FWRITE.
 */
#define	O_RDONLY	0		/* +1 == FREAD */
#define	O_WRONLY	1		/* +1 == FWRITE */
#define	O_RDWR		2		/* +1 == FREAD|FWRITE */
#define	O_APPEND	_FAPPEND
#define	O_CREAT		_FCREAT
#define	O_TRUNC		_FTRUNC
#define	O_EXCL		_FEXCL
/*	O_SYNC		_FSYNC		not posix, defined below */
/*	O_NDELAY	_FNDELAY 	set in include/fcntl.h */
/*	O_NDELAY	_FNBIO 		set in 5include/fcntl.h */
#define	O_NONBLOCK	_FNONBLOCK
#define	O_NOCTTY	_FNOCTTY
/* For machines which care - */
#if defined (_WIN32) || defined (__CYGWIN__)
#define _FBINARY        0x10000
#define _FTEXT          0x20000
#define _FNOINHERIT	0x40000

#define O_BINARY	_FBINARY
#define O_TEXT		_FTEXT
#define O_NOINHERIT	_FNOINHERIT

/* The windows header files define versions with a leading underscore.  */
#define _O_RDONLY	O_RDONLY
#define _O_WRONLY	O_WRONLY
#define _O_RDWR		O_RDWR
#define _O_APPEND	O_APPEND
#define _O_CREAT	O_CREAT
#define _O_TRUNC	O_TRUNC
#define _O_EXCL		O_EXCL
#define _O_TEXT		O_TEXT
#define _O_BINARY	O_BINARY
#define _O_RAW		O_BINARY
#define _O_NOINHERIT	O_NOINHERIT
#endif

#ifndef	_POSIX_SOURCE

#define	O_SYNC		_FSYNC

/*
 * Flags that work for fcntl(fd, F_SETFL, FXXXX)
 */
#define	FAPPEND		_FAPPEND
#define	FSYNC		_FSYNC
#define	FASYNC		_FASYNC
#define	FNBIO		_FNBIO
#define	FNONBIO		_FNONBLOCK	/* XXX fix to be NONBLOCK everywhere */
#define	FNDELAY		_FNDELAY

/*
 * Flags that are disallowed for fcntl's (FCNTLCANT);
 * used for opens, internal state, or locking.
 */
#define	FREAD		_FREAD
#define	FWRITE		_FWRITE
#define	FMARK		_FMARK
#define	FDEFER		_FDEFER
#define	FSHLOCK		_FSHLOCK
#define	FEXLOCK		_FEXLOCK

/*
 * The rest of the flags, used only for opens
 */
#define	FOPEN		_FOPEN
#define	FCREAT		_FCREAT
#define	FTRUNC		_FTRUNC
#define	FEXCL		_FEXCL
#define	FNOCTTY		_FNOCTTY

#endif	/* !_POSIX_SOURCE */

/* XXX close on exec request; must match UF_EXCLOSE in user.h */
#define	FD_CLOEXEC	1	/* posix */

/* fcntl(2) requests */
#define	F_DUPFD		0	/* Duplicate fildes */
#define	F_GETFD		1	/* Get fildes flags (close on exec) */
#define	F_SETFD		2	/* Set fildes flags (close on exec) */
#define	F_GETFL		3	/* Get file flags */
#define	F_SETFL		4	/* Set file flags */
#ifndef	_POSIX_SOURCE
#define	F_GETOWN 	5	/* Get owner - for ASYNC */
#define	F_SETOWN 	6	/* Set owner - for ASYNC */
#endif	/* !_POSIX_SOURCE */
#define	F_GETLK  	7	/* Get record-locking information */
#define	F_SETLK  	8	/* Set or Clear a record-lock (Non-Blocking) */
#define	F_SETLKW 	9	/* Set or Clear a record-lock (Blocking) */
#ifndef	_POSIX_SOURCE
#define	F_RGETLK 	10	/* Test a remote lock to see if it is blocked */
#define	F_RSETLK 	11	/* Set or unlock a remote lock */
#define	F_CNVT 		12	/* Convert a fhandle to an open fd */
#define	F_RSETLKW 	13	/* Set or Clear remote record-lock(Blocking) */
#endif	/* !_POSIX_SOURCE */

/* fcntl(2) flags (l_type field of flock structure) */
#define	F_RDLCK		1	/* read lock */
#define	F_WRLCK		2	/* write lock */
#define	F_UNLCK		3	/* remove lock(s) */
#ifndef	_POSIX_SOURCE
#define	F_UNLKSYS	4	/* remove remote locks for a given system */
#endif	/* !_POSIX_SOURCE */

/*#include <sys/stdtypes.h>*/

#ifndef __CYGWIN__
/* file segment locking set data type - information passed to system by user */
struct flock {
	short	l_type;		/* F_RDLCK, F_WRLCK, or F_UNLCK */
	short	l_whence;	/* flag to choose starting offset */
	long	l_start;	/* relative offset, in bytes */
	long	l_len;		/* length, in bytes; 0 means lock to EOF */
	short	l_pid;		/* returned with F_GETLK */
	short	l_xxx;		/* reserved for future use */
};
#endif /* __CYGWIN__ */

#ifndef	_POSIX_SOURCE
/* extended file segment locking set data type */
struct eflock {
	short	l_type;		/* F_RDLCK, F_WRLCK, or F_UNLCK */
	short	l_whence;	/* flag to choose starting offset */
	long	l_start;	/* relative offset, in bytes */
	long	l_len;		/* length, in bytes; 0 means lock to EOF */
	short	l_pid;		/* returned with F_GETLK */
	short	l_xxx;		/* reserved for future use */
	long	l_rpid;		/* Remote process id wanting this lock */
	long	l_rsys;		/* Remote system id wanting this lock */
};
#endif	/* !_POSIX_SOURCE */

#include <sys/types.h>
#include <sys/stat.h>		/* sigh. for the mode bits for open/creat */

extern int open _PARAMS ((const char *, int, ...));
extern int creat _PARAMS ((const char *, mode_t));
extern int fcntl _PARAMS ((int, int, ...));

/* Provide _<systemcall> prototypes for functions provided by some versions
   of newlib.  */
#ifdef _COMPILING_NEWLIB
extern int _open _PARAMS ((const char *, int, ...));
extern int _fcntl _PARAMS ((int, int, ...));
#ifdef __LARGE64_FILES
extern int _open64 _PARAMS ((const char *, int, ...));
#endif
#endif

#ifdef __cplusplus
}
#endif
#endif	/* !_FCNTL_ */


text:
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.airavata.cloud.aurora.client.sdk;

import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;

/**
 * Status of the coordinated update. Intended as a response to pulseJobUpdate RPC.
 */
public enum JobUpdatePulseStatus implements org.apache.thrift.TEnum {
  /**
   * Update is active. See ACTIVE_JOB_UPDATE_STATES for statuses considered active.
   */
  OK(1),
  /**
   * Update has reached terminal state. See TERMINAL_JOB_UPDATE_STATES for statuses
   * considered terminal.
   */
  FINISHED(2);

  private final int value;

  private JobUpdatePulseStatus(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static JobUpdatePulseStatus findByValue(int value) {
    switch (value) {
      case 1:
        return OK;
      case 2:
        return FINISHED;
      default:
        return null;
    }
  }
}


text:
module Shipit
  class CommitChecksController < ShipitController
    def show
      checks.schedule
    end

    params do
      accepts :since, Integer, default: 0
    end
    def tail
      output = checks.output(since: params.since)
      url = nil
      unless checks.finished?
        next_offset = params.since + output.bytesize
        url = stack_tail_commit_checks_path(stack, sha: commit.sha, since: next_offset)
      end

      render(json: { url: url, output: output, status: checks.status })
    end

    private

    delegate :checks, to: :commit

    def commit
      @commit ||= stack.commits.find_by!(sha: params[:sha])
    end

    def stack
      @stack ||= Stack.from_param!(params[:stack_id])
    end
  end
end


text:
<title>OIOSAML.java Patches information</title>

Multiple IdPs (patch)

Description of the patch work.

Configuration wise, some changes has been made. The default implementation is filebased, eg. IDP and
		SP metadata, keystore and log configuration files are located in files. To change the implementation just
		change ..META-INF/services/dk.itst.oiosaml.configuration.SAMLConfiguration file.

The filebased configuration do now contain to major ways of configuring OIOSAML:

Load one file per IDP and SP

Load more IDP's and SP's

	Loading one file just apply "common.saml2.metadata.sp.filename" and "common.saml2.metadata.idp.filename" to
	the configuration file. If more files files are needed, apply "common.saml2.metadata.sp.directory" and
	"common.saml2.metadata.idp.directory".

The configuration part has a minor change. Applying the context-param "oiosaml-j.file" in the
		webapplication is a path to a specific configuration file, exam.

            <env-entry>
                <env-entry-name>oiosaml-j.file</env-entry-name>
                <env-entry-value>/websrv/jboss/jboss51/server/justica/deploy/oio-sp-con.properties</env-entry-value>
                <env-entry-type>java.lang.String</env-entry-type>
            </env-entry>

		The databasebased configuration uses a JDBC based database for IDP'S, the SP, the keystore and the log4j
		file. Replace the content of ..META-INF/services/dk.itst.oiosaml.configuration.SAMLConfiguration with
		'dk.itst.oiosaml.configuration.DatabaseConfiguration' and place a standard datasource file in the same
		folder. If the datasouce is JNDI based the resource is being looked up.
 The necessary SQL files are
		provided in the 'dk.itst.oiosaml.configuration' package and the 'dk.itst.oiosaml.configuration.util'
		package contains basic java applications to save the configuration parts in the database and reverse.

		The autoconfiguration part in configurationhandler do only apply for the
		filebased configuration (default).

Class changes

These classes have been changed.

				Class
				Issue
				Solution

				dk.itst.oiosaml.logging.Audit
				Filereference to log4jfile
				Getting stream trough SAMLConfiguration

				dk.itst.oiosaml.configuration.FileConfiguration
				The getStringPrefixedWithBRSHome method
				Refactored, implementation of SAMLConfiguration

				dk.itst.oiosaml.sp.UserAttributeQuery
				The getStringPrefixedWithBRSHome method
				Refactored

				dk.itst.oiosaml.security.CredentialRepository
				Filereference to keystore
				Getting stream trough SAMLConfiguration

				dk.itst.oiosaml.sp.service.SPFilter
				The getStringPrefixedWithBRSHome method
				Refactored

				dk.itst.oiosaml.sp.service.DispatcherServlet
				The getStringPrefixedWithBRSHome method
				Refactored

				dk.itst.oiosaml.sp.metadata.CRLChecker
				The getStringPrefixedWithBRSHome method
				Refactored

				dk.itst.oiosaml.sp.service.util.Constants
				Refactor
				Added fileconstants

				dk.itst.oiosaml.sp.metadata.SPMetadata
				Unmarshal from file
				Unmarshal trough SAMLConfiguration

				dk.itst.oiosaml.sp.metadata.IDPMetadata
				Unmarshal from file
				Unmarshal trough SAMLConfiguration

				dk.itst.oiosaml.sp.metadata.ConfigurationHandler
				Runtime exception when keystore load
				Catching and logging exception

				dk.itst.oiosaml.sp.bindings.PostBindingHandler
				Property lookup
				Refactored

Test classes

				Class
				Issue
				Solution

				dk.itst.oiosaml.sp.service.util.UtilsTest
				Filereference
				Streamreference

				dk.itst.oiosaml.sp.model.OIOAttributeQueryTest
				Filereference
				Streamreference

				dk.itst.oiosaml.configuration.SAMLConfigurationTest
				The getStringPrefixedWithBRSHome method
				Refactored

				dk.itst.oiosaml.configuration.SPFilterTest
				The getStringPrefixedWithBRSHome method
				Refactored

				dk.itst.oiosaml.sp.UserAttributeQueryTest
				The getStringPrefixedWithBRSHome method
				Refactored

				dk.itst.oiosaml.sp.IntegrationTests
				Setup webapp to use oiosaml-j.file parameter
				Fixed

New classes

				Class
				Purpose

				dk.itst.oiosaml.configuration.SAMLConfigurationFactory
				Factory (ServiceLoader) to retrieve the configuration

				dk.itst.oiosaml.configuration.SAMLConfiguration
				Configuration interface

				dk.itst.oiosaml.configuration.DatabaseConfiguration
				Implementation of SAMLConfiguration

				dk.itst.oiosaml.configuration.jdbc.JdbcConfiguration
				Handle connection to database

				dk.itst.oiosaml.configuration.jdbc.JdbcConfigurationTest
				Test class

				dk.itst.oiosaml.configuration.util.FileToDatabaseConfiguration
				Utility to import/export configurations

				dk.itst.oiosaml.configuration.util.FileToDatabaseMetadata
				Utility to import/export metadata

				dk.itst.oiosaml.configuration.util.FileToDatabaseLogger
				Utility to import/export log4j file

The package 'dk.itst.oiosaml.configuration' contains an SQL files with the necessary DDL.


text:
import { expect } from 'chai';

import React from 'react-native';

import Actions from '../src/Actions';
import Scene from '../src/Scene';

let id = 0;
const guid = () => id++;

const scenesData = (
  <Scene
    key="root"
    component="Modal"
    getInitialState={() => ({ foo: guid() })}
  >
    <Scene key="launch" component="Launch" />
    <Scene key="sideMenu" component="Drawer" initial>
      <Scene component="CubeBar" key="cubeBar" type="tabs">
        <Scene key="main" tabs>
          <Scene key="home" component="Home" />
          <Scene key="map" component="Map" />
          <Scene key="myAccount" component="MyAccount" />
        </Scene>
        <Scene key="messaging" initial>
          <Scene
            key="conversations"
            component="Conversations"
            getInitialState={() => ({ foo: 'what', bar: guid() })}
          />
        </Scene>
      </Scene>
    </Scene>
    <Scene key="privacyPolicy" component="PrivacyPolicy" type="modal" />
    <Scene key="termsOfService" component="TermsOfService" type="modal" />
    <Scene key="login">
      <Scene key="loginModal1" component="Login1" />
      <Scene key="loginModal2" component="Login2" />
    </Scene>
  </Scene>);

let scenes;

describe('Actions', () => {
  before(() => {
    scenes = Actions.create(scenesData);
  });
  it('should produce needed actions', () => {
    // check scenes
    expect(scenes.conversations.component).to.equal('Conversations');

    // set callback which will extract generated action
    let latestAction = null;
    Actions.callback = action => { latestAction = action; };

    // test generated actions
    Actions.conversations({ param1: 'Hello world' });
    expect(latestAction.param1).equal('Hello world');
    expect(latestAction.key).equal('conversations');

    Actions.sideMenu({ param2: 'Hello world2' });
    expect(latestAction.param1).equal(undefined);
    expect(latestAction.param2).equal('Hello world2');
    expect(latestAction.key).equal('sideMenu');

    Actions.messaging({ param3: 'Hello world3' });
    expect(latestAction.param3).equal('Hello world3');
    expect(latestAction.key).equal('messaging');
  });
});


text:
require 'thor'

module Onboard
  class Confirm < Thor
    attr_reader :message, :full_stop

    no_tasks do
      def initialize(message, full_stop = false)
        @message = message
        @full_stop = full_stop
      end

      def q(prefill = '')
        return response(prefill) if prefill =~ /^[N]$/i || prefill =~ /^[Y]$/i
        answer = ''
        while answer !~ /^[Y|N]$/i
          answer = ask(message + ' [Y|N]: ')
          puts ''
        end
        response(answer)
      end

      def no
        if full_stop
          say('Script was exited.')
          exit
        else
          say('Action was aborted.')
          return false
        end
      end

      def response(answer)
        if answer =~ /^[N]$/i
          no
        elsif answer =~ /^[Y]$/i
          return true
        end
      end
    end
  end
end


text:
package com.automationrockstars.gunter;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface EventDescription {

    String name();
}


text:
namespace TraktApiSharp.Requests.Seasons
{
    using Base;
    using Extensions;
    using Interfaces;
    using System;
    using System.Collections.Generic;

    internal abstract class ASeasonRequest<TResponseContentType> : AGetRequest<TResponseContentType>, IHasId
    {
        public string Id { get; set; }

        internal uint SeasonNumber { get; set; }

        public virtual RequestObjectType RequestObjectType => RequestObjectType.Seasons;

        public override IDictionary<string, object> GetUriPathParameters()
            => new Dictionary<string, object>
            {
                ["id"] = Id,
                ["season"] = SeasonNumber.ToString()
            };

        public override void Validate()
        {
            if (Id == null)
                throw new ArgumentNullException(nameof(Id));

            if (Id == string.Empty || Id.ContainsSpace())
                throw new ArgumentException("show id not valid", nameof(Id));
        }
    }
}


text:
const hibp = require('hibp');

hibp
  .breach('Adobe')
  .then((data) => {
    if (data) {
      // Breach data found
      console.log(data);
    } else {
      console.log('No breach data found by that name.');
    }
  })
  .catch((err) => {
    // Something went wrong.
    console.log(err.message);
  });


text:
package uk.gov.nationalarchives.droid.profile;

import java.nio.file.Path;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author rflitcroft
 *
 */
@XmlRootElement(name = "Dir")
public class DirectoryProfileResource extends FileProfileResource {

    @XmlAttribute(name = "Recursive")
    private boolean recursive;

    /**
     * Default Constructor.
     */
    DirectoryProfileResource() {
    }

    /**
     *
     * @param file
     *            the directory to represent.
     * @param recursive
     *            whether the resource should recurse into subdirectorie
     */
    public DirectoryProfileResource(final Path file, boolean recursive) {
        super(file);
        this.recursive = recursive;
    }

    /**
     * @return the recursive
     */
    @Override
    public boolean isRecursive() {
        return recursive;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isDirectory() {
        return true;
    }

    /**
     * setting an arbitrary size of 0 for the folder resource.
     * @param filePath - ignored for the folder
     */
    @Override
    public void setSize(Path filePath) {
        setSize(-1L);
    }
}


text:
/**
 * @LICENSE@
 */

package org.opensims.doc.taglet;

/**
 * A Taglet representing @TODO - based on the example from Sum by Jamie Ho
 */

public class
    TagTODO
    implements com.sun.tools.doclets.Taglet
{
    // local definitions

    protected static final String NAME = "TODO";
    protected static final String HEADER = "To-Do:";

    //////////////////////////////////////////////////////////////////////
    // how it gets called...
    //////////////////////////////////////////////////////////////////////

    public static void
	register (java.util.Map tagletMap)
    {
       org.opensims.doc.taglet.TagTODO tag = new org.opensims.doc.taglet.TagTODO();
       com.sun.tools.doclets.Taglet t = (com.sun.tools.doclets.Taglet) tagletMap.get(tag.getName());

       if (t != null) {
           tagletMap.remove(tag.getName());
       }

       tagletMap.put(tag.getName(), tag);
    }

    public String
	toString (com.sun.javadoc.Tag tag)
    {
	StringBuffer buf = new StringBuffer();

	buf.append("\n
");
	buf.append(HEADER);
	buf.append("
");
	buf.append("

");

	buf.append(tag.text());

	buf.append("

\n");

	return buf.toString();
    }

    public String
	toString (com.sun.javadoc.Tag[] tags)
    {
	String result = null;

        if (tags.length > 0) {
	    StringBuffer buf = new StringBuffer();

	    buf.append("\n
");
	    buf.append(HEADER);
	    buf.append("
");
	    buf.append("

");

	    for (int i = 0; i < tags.length; i++) {
		if (i > 0) {
		    buf.append(", ");
		}

		buf.append(tags[i].text());
	    }

	    buf.append("

\n");
	    result = buf.toString();
	}

	return result;
    }

    //////////////////////////////////////////////////////////////////////
    // access methods
    //////////////////////////////////////////////////////////////////////

    public String
	getName ()
    {
        return NAME;
    }

    //////////////////////////////////////////////////////////////////////
    // misc. interface stubs
    //////////////////////////////////////////////////////////////////////

    public boolean
	isInlineTag ()
    {
        return false;
    }

    public boolean
	inField ()
    {
        return true;
    }

    public boolean
	inConstructor ()
    {
        return true;
    }

    public boolean
	inMethod ()
    {
        return true;
    }

    public boolean
	inOverview ()
    {
        return true;
    }

    public boolean
	inPackage ()
    {
        return true;
    }

    public boolean
	inType ()
    {
        return true;
    }
}


text:
namespace tblis
{

extern "C"
{

#endif

void tblis_matrix_set(const tblis_comm* comm, const tblis_config* cfg,
                      const tblis_scalar* alpha, tblis_matrix* A);

#ifdef __cplusplus
}
#endif

#if defined(__cplusplus) && !defined(TBLIS_DONT_USE_CXX11)

template <typename T>
void set(T alpha, matrix_view<T> A)
{
    tblis_scalar alpha_s(alpha);
    tblis_matrix A_s(A);

    tblis_matrix_set(nullptr, nullptr, &alpha_s, &A_s);
}

template <typename T>
void set(const communicator& comm, T alpha, matrix_view<T> A)
{
    tblis_scalar alpha_s(alpha);
    tblis_matrix A_s(A);

    tblis_matrix_set(comm, nullptr, &alpha_s, &A_s);
}

#endif

#ifdef __cplusplus
}
#endif

#endif


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Events Language Lines
    |--------------------------------------------------------------------------
    */

    'home'                      => 'Zuhause',
    'name'                      => 'Name',
    'actions'                   => 'Aktionen',
    'delete'                    => 'Löschen',
    'edit'                      => 'Bearbeiten',
    'update'                    => 'Aktualisieren',
    'create'                    => 'Erstellen',
    'title'                     => 'Titel',
    'title_ph'                  => 'Geben Sie den Titel für diese Veranstaltung ein',
    'start_date'                => 'Anfangsdatum',
    'start_date_ph'             => 'Geben Sie das Datum ein, an dem dieses Ereignis beginnt',
    'end_date'                  => 'Enddatum',
    'end_date_ph'               => 'Geben Sie das Datum ein, an dem dieses Ereignis endet',
    'start_time'                => 'Startzeit',
    'start_time_ph'             => 'Geben Sie die Uhrzeit ein, wenn dieses Ereignis beginnt',
    'end_time'                  => 'Endzeit',
    'end_time_ph'               => 'Geben Sie die Zeit ein, wenn dieses Ereignis endet',
    'color'                     => 'Farbe',
    'color_ph'                  => 'Geben Sie eine Hex-Farbe für dieses Ereignis ein',
    'description'               => 'Beschreibung',
    'description_ph'            => 'Geben Sie eine Beschreibung für diese Veranstaltung ein',
    'place'                     => 'Ort',
    'place_ph'                  => 'Geben Sie den Ort ein, an dem diese Veranstaltung stattfindet',
    'price'                     => 'Preis',
    'price_ph'                  => 'Geben Sie den Preis ein, um auf diese Veranstaltung zuzugreifen',
    'submit'                    => 'Einreichen',
    'cancel'                    => 'Stornieren',
    'content'                   => 'Inhalt',
    'public'                    => 'Öffentlichkeit',
    'view'                      => 'Aussicht',
    'author'                    => 'Autor',
    'users'                     => 'Benutzer',
    'information'               => 'Information',
    'email'                     => 'Email',
    'duration'                  => 'Dauer',
    'status'                    => 'Status',
    'published'                 => 'Veröffentlicht',
    'unpublished'               => 'Unveröffentlicht',
    'event'                     => 'Event',
    'view_event'                => 'Ereignis ansehen',
    'event_id'                  => 'Ereignis #:id',
    'events_list'               => 'Veranstaltungsliste',
    'event_added'               => 'Event hinzugefügt!',
    'event_updated'             => 'Veranstaltung #:id aktualisiert!',
    'event_deleted'             => 'Veranstaltung #:id gelöscht!',
    'event_celebrated'          => 'Die Veranstaltung wurde bereits gefeiert.',
    'edit_event'                => 'Ereignis bearbeiten',
    'create_event'              => 'Ereignis erstellen',
    'events_desc'               => 'Veranstaltungen ermöglichen es Ihnen, Ereignisse mit Menschen zu teilen.',
    'events'                    => 'Veranstaltungen',
    'create_event_desc'         => 'Erstellen Sie ein neues Ereignis in der Datenbank',
    'edit_event_desc'           => 'Sie bearbeiten das Ereignis #:id erstellt :time_ago',
    'time_left_starts'          => 'Zeit links zum Ereignis beginnt',
    'time_left_ends'            => 'Zeit nach links endet',
    'you_were_late'             => 'Du warst spät',
    'hours'                     => 'Std',
    'days'                      => 'Tage',
    'minutes'                   => 'Protokoll',
    'seconds'                   => 'Sekunden',
    'end_date_after_start_date' => 'Die Veranstaltung muss nach dem Start beginnen',
    'image_url'                 => 'Bild URL',
    'image_url_ph'              => 'Fügen Sie eine Bild-URL ein, um das Ereignis darzustellen',
    'sure_del_event'            => 'Bist du sicher, dass du die Veranstaltung ":event" löschen möchtest?',
    'public_url'                => 'Öffentliche URL',
    'select_editor'             => 'Bitte wählen Sie einen Texteditor',
    'text_editor'               => 'Text-Editor',
    'plain_text'                => 'Klartext',
    'markdown'                  => 'Abschlag',
    'wysiwyg'                   => 'WYSIWYG',
    'text_editor_desc'          => 'Wählen Sie einen Text-Editor für die Ereignisbeschreibung',
    'unauthorized_action'       => 'Unbefugte Handlung',
    'unauthorized_desc'         => 'Sie dürfen die Ereignisse nicht aktualisieren.',
    'contact_webmaster'         => 'Wenn du denkst, du solltest es in der Lage sein, es zu aktualisieren, bitte wenden Sie sich an webmaster.',
    'save_settings'             => 'Ereignisse speichern',
    'events_settings_updated'   => 'Ereignisse Einstellungen aktualisiert',
    'joined_event'              => 'Sie sind der Veranstaltung #:id beigetreten',
    'left_event'                => 'Sie haben die Veranstaltung #:id verlassen',
    'join'                      => 'Beitreten',
    'leave'                     => 'Verlassen',
    'public_routes'             => 'Öffentliche Wege',
    'public_routes_desc'        => 'Aktivieren öffentliche Straßen',
];


text:
import express = require('express');
import http = require('http');
import fs = require('fs');
import path = require('path');
import crypto = require('crypto');

var  CONFIG = require('config');

var app = express();
app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.static(path.join(__dirname, CONFIG.Files)));
    app.use(express.bodyParser({ uploadDir: CONFIG.Files }));
});

app.post('/upload', function(req, res) {
    var sourcepath = req.files.imagedata.path;
    var md5 = crypto.createHash('md5');

    var s = fs.createReadStream('./' + sourcepath);
    s.on('data', function(d) {
        md5.update(d);
    });

    s.on('end', function() {
        var digest = md5.digest('hex');
        var targetpath = CONFIG.Files + digest + '.png';
        fs.rename(sourcepath, targetpath, (err?) => {
          if (err) {
            console.log(err);
            res.send(400);
          }
          res.send('http://' + CONFIG.Host + '/' + path.basename(CONFIG.Files + digest));
        });
    });
});

app.get(/([0-9a-f]+)/, function(req, res) {
    var fileid = req.params[0];
    var filepath = CONFIG.Files + fileid + CONFIG.FileType;
    fs.stat(filepath, (err, stats) => {
        if (err) {
            console.log(err);
            res.send(400);
        }
        var params = {
            ImageSource: 'http://' + CONFIG.Host + '/' + fileid + CONFIG.FileType,
            Domain: CONFIG.Host
        }
        res.render('index',  params);
    });
});

app.get('/', (req, res) => {
    res.send('This site serves as Gyazo. (More detail at gyazo.com)');
});

if (!module.parent) {
    http.createServer(app).listen(app.get('port'), function () {
        console.log('Express server listening on port ' + app.get('port'));
    });
}


text:
export default function commitlintLoad(): Promise<CommitlintConfig>;

export type Case =
    | 'lower-case'
    | 'lowercase'
    | 'lowerCase'
    | 'upper-case'
    | 'uppercase'
    | 'camel-case'
    | 'kebab-case'
    | 'pascal-case'
    | 'sentence-case'
    | 'sentencecase'
    | 'start-case'
    | 'snake-case';

export type Applicability = 'always' | 'never';

export type Rule<T> = [Level | 0 | 1 | 2, Applicability, T];

export interface Rules {
    'body-leading-blank'?: Rule<undefined>;
    'body-max-length'?: Rule<number>;
    'body-max-line-length'?: Rule<number>;
    'body-min-length'?: Rule<number>;
    'footer-leading-blank'?: Rule<undefined>;
    'footer-max-length'?: Rule<number>;
    'footer-min-length'?: Rule<number>;
    'footer-max-line-length'?: Rule<number>;
    'header-case'?: Rule<Case>;
    'header-full-stop'?: Rule<string>;
    'header-max-length'?: Rule<number>;
    'header-min-length'?: Rule<number>;
    'references-empty'?: Rule<undefined>;
    'scope-enum'?: Rule<string[]>;
    'scope-case'?: Rule<Case>;
    'scope-empty'?: Rule<undefined>;
    'scope-max-length'?: Rule<number>;
    'scope-min-length'?: Rule<number>;
    'subject-case'?: Rule<Case | Case[]>;
    'subject-empty'?: Rule<undefined>;
    'subject-full-stop'?: Rule<string>;
    'subject-max-length'?: Rule<number>;
    'subject-min-length'?: Rule<number>;
    'type-enum'?: Rule<string[]>;
    'type-case'?: Rule<Case>;
    'type-empty'?: Rule<undefined>;
    'type-max-length'?: Rule<number>;
    'type-min-length'?: Rule<number>;
    'signed-off-by'?: Rule<string>;
}

export interface CommitlintConfig {
    extends?: string[];
    rules: Rules;
}

// tslint:disable-next-line:no-const-enum
export const enum Level {
    Disable = 0,
    Warn = 1,
    Error = 2,
}


text:
import {
  create,
  visitable,
  fillable,
  selectable,
} from 'ember-cli-page-object';

import makeButton from '../helpers/make-button';
import makeField from '../helpers/make-field';

export default create({
  visit: visitable('/reset-changeset'),

  form: {
    scope: '#test-form',

    firstName: makeField('[data-test-first-name]', '#form-first-name', ['fillIn', fillable]),
    lastName: makeField('[data-test-last-name]', '#form-last-name', ['fillIn', fillable]),
    favoriteBand: makeField('[data-test-favorite-band]', '#form-favorite-band', ['select', selectable]),

    submitButton: makeButton('[data-test-submit-button]'),
    cancelButton: makeButton('[data-test-cancel-button]')
  }
});


text:
package io.primeval.saga.http.client.header.spi;

import io.primeval.common.type.TypeTag;
import io.primeval.saga.http.client.header.HeaderAttributeEntry;

public interface HeaderAttributeMapperProvider<T> {

    boolean supportsHeader(String headerName);

    HeaderAttributeEntry toHeader(TypeTag<? extends T> typeTag, T value);

    Class<T> getMapperType();

}


text:
Router.configure({
  layoutTemplate: 'layout'
});

Router.onBeforeAction(function () {
  // all properties available in the route function
  // are also available here such as this.params

  if (!Meteor.userId()) {
    // if the user is not logged in, render the Login template
    this.layout("landing");
    $('body').addClass('body-landing');

  } else {
    // otherwise don't hold up the rest of hooks or our route/action function
    // from running
    this.layout('layout');
    $('body').removeClass('body-landing');
    this.next();
  }
});

Router.map(function routerMap() {

  this.route('dashboard', {
    path: '/',
    template: 'dashboard',
    data:function(){
      var filter = Session.get('filter');
      if(filter === undefined){
        filter = {};
      }
      return {interaction:Interactions.find(filter).fetch()};
    }
  });

  this.route('contactList', {
    path: '/contacts',
    template: 'contacts',
    data:function(){
      return {contacts: Contacts.find().fetch()};
    }
  });

  this.route('newContact', {
    path: '/newContact',
    template: 'createContact'
  });

  this.route('contact', {
        path: '/contact/:_id',
        waitOn: function() {
                return Meteor.subscribe('contacts');
        },
        data: function() {
                var findById = Contacts.findOne(this.params._id);
                console.log(findById);
                var list = Interactions.find({contactID: findById._id },{sort: {createdAt: -1}}).fetch();
                console.log(list);
                if (typeof findById !== "undefined") {
                  return {
                    name: findById.name,
                    email: findById.email,
                    phone: findById.phone,
                    org: findById.organization,
                    notes: findById.notes,
                    since: moment(findById.createdAt).format('MMMM Do YYYY'),
                    interaction: list
                  };
                }else{
                  return {};
                }

        }
    });
});


text:
/*=======================================
Template Design By WpFreeware Team.
Author URI : http://www.wpfreeware.com/
========================================*/

.scrollToTop {
  background-color: #37c6f5;
  border:1px solid #37c6f5;
}
.scrollToTop:hover, .scrollToTop:focus,.readmore_area a::before,.sl-slider h2> strong,.sl-slider p> strong,
.single-top-feature .readmore_area a span,.service-icon-effect,.service-icon .service-icon-effect:hover,.single-service>h3 a:hover,.single-service>h3 a:focus,
.whyChoose-right .media-heading,.whyChoose-right .media:hover .media-icon,.doctors-nav figcaption h2,
.testimonial-cotent > p span,.testimonial-nav .slick-dots li.slick-active button::before,.blog-comments-box li > h2,.blog-comments-box li span,
.blog-author > ul > li a:hover,.footer-service li > a:hover,.footer-service li > a span,.contact-info > p span,.footer-copyright>p>a,
.blog-breadcrumbs-right .breadcrumb > li a:hover,.blog-breadcrumbs-right .breadcrumb > .active,.blog-details blockquote::before,.blog-details blockquote::after,
.sidebar-widget p>a,.sidebar-widget>ul li>a:hover,.postnav-left:hover .navg-title,.postnav-right:hover .navg-title,.author-name:hover,
.similar-post .media-body a:hover,.similar-post > h2,.nav-tabs > li.active > a, .nav-tabs > li.active > a:focus, .nav-tabs > li.active > a:hover,
.button--itzel .button__icon,.button--itzel > span,#myModal .modal-title,
.form-submit input:hover,.error-page-area h1,.error-page-area h3{
  color: #37c6f5;
}
.navbar-default {
  background-color: #37c6f5;
  border-color: #37c6f5;
}
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:focus, .navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:focus, .navbar-default .navbar-nav > .open > a:hover,
.dropdown-menu > li > a:hover,.dropdown-menu > li > a:focus,.dropdown-menu > .active > a, .dropdown-menu > .active > a:focus, .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,.readmore_area a span,.single-top-feature,
.single-top-feature .readmore_area a::before,.testimonial-nav .slick-dots li.slick-active,figure.blog-figure .image-effect::before,
.footer-middle,.social-share ul li > a,.custom-panel .panel-heading a,.nav-tabs > li > a,a.gallery-iteam .image-effect::before,.comments-title::after,
.reply-btn,.author-tag  {
  background-color: #37c6f5;
}
.navbar-right .dropdown-menu,.navbar-nav .open .dropdown-menu,
.wp-form-control:focus {
  border: 1px solid #37c6f5;
}
.navbar-right .dropdown-menu::before {
  border-left: 1px solid #37c6f5;
  border-top: 1px solid #37c6f5;
}
.nav-arrows span:hover {
  border-color: #37c6f5;
  color: #37c6f5;
}
.line {
  border-bottom: 2px solid #37c6f5;
  background: none repeat scroll 0 0 transparent;
  height: 1px;
  margin: 0 auto 45px;
  padding: 5px;
  position: relative;
  width: 120px;
}
.line::after, .line::before {
  border: medium solid transparent;
  content: " ";
  height: 0;
  left: 50%;
  pointer-events: none;
  position: absolute;
  top: 100%;
  width: 0;
}
.line::before {
  border-width: 9px;
  margin-left: -6px;
}
.line::after {
  border-top-color: #37c6f5;
  border-width: 8px;
  margin-left: -8px;
}
.service-icon .service-icon-effect {
  box-shadow: 0 0 0 4px #37c6f5;
}
.service-icon .service-icon-effect:after {
  box-shadow: 3px 3px #37c6f5;
}
.media-icon {
  background-color: #37c6f5;
  border: 2px solid #37c6f5;
}
.doctors-nav figure button:hover{
  border-color: #37c6f5;
  color:#37c6f5;
}
.single-doctor-social > a:hover{
  color: #37c6f5;
  border-color: #37c6f5;
}
.testimonial-img {
  border: 3px solid #37c6f5;
}
.testimonial-nav .slick-dots li,.blog-content .readmore_area a,.wp-form-control,
.button--itzel::before,.error-page-area .readmore_area a {
  border: 2px solid #37c6f5;
}
.tag-nav a:hover,.tag-nav a:focus{
  background-color: #37c6f5;
  border-color: #37c6f5;
}
.footer-service li > a{
  border-bottom: 1px solid #37c6f5;
}
.footer-copyright>p>a:hover{
 border-bottom: 1px solid #37c6f5;
}
.footer-social a {
  border: 1px solid #37c6f5;
  color: #37c6f5;
}
.footer-bottom p a:hover,.footer-bottom p a:focus{
  border-color: #37c6f5;
  color: #37c6f5;
}
.blog-pagination .pagination > li > a:focus, .blog-pagination .pagination > li > a:hover, .blog-pagination .pagination > li > span:focus,
.blog-pagination .pagination > li > span:hover {
  background-color: #37c6f5;
  border-color: #37c6f5;
}
.sidebar-widget h3::after {
  background: none repeat scroll 0 0 #37c6f5;
}
.archives li > a:hover {
  background-color: #37c6f5;
  border-color: #37c6f5;
}
.postnav-left a:hover, .postnav-right a:hover {
  border: 1px solid #37c6f5;
  color: #37c6f5;
}
.postnav-left:hover .prev-icon,.postnav-right:hover .next-icon{
  color: #37c6f5;
  border-color: #37c6f5;
}
.post-author > h3 {
  border-bottom: 1px solid #37c6f5;
  color: #37c6f5;
}
.author-morepost:hover,.author-morepost:focus {
  border-bottom: 1px solid #37c6f5;
  color: #37c6f5;
}
.nav-tabs > li > a:hover,.nav-tabs > li > a:focus{
  background-color: #37c6f5;
  border-color: #37c6f5;
}
.form-submit input {
  background-color: #37c6f5;
  border: 1px solid #37c6f5;
}
.pswp__caption__center {
  color: #37c6f5 !important;
}
.pswp__button--arrow--left::before, .pswp__button--arrow--right::before {
  background-color: #37c6f5 !important;
}
.comments-pagination li a:hover {
  background-color:#37c6f5;
  border-color: #37c6f5;
}
#respond input[type="text"]:focus,#respond input[type="email"]:focus,#respond input[type="url"]:focus {
  border-color: #37c6f5;
}
#respond textarea:focus{
  border-color: #37c6f5;
}
.blog-details .table-hover tbody tr:hover{
  background-color: #37c6f5;
  border-color: #37c6f5;
}
.blog-details>a:hover,
.blog-details>a:focus,
.blog-details > p>a:hover,
.blog-details > p>a:focus{
  color: #37c6f5;
  border-bottom: 1px solid #37c6f5;
}
.testimonial-parg::before {
  color: #37c6f5;
}
.testimonial-parg:after{
  color: #37c6f5;
}
.top-slider .slick-prev:hover,
.top-slider .slick-next:hover{
  border-color: #37c6f5;
  color: #37c6f5;
}
.slider-text h2>strong{
  color: #37c6f5;
}
.slider-text p>strong{
  color: #37c6f5;
}

/*=======================================
Template Design By WpFreeware Team.
Author URI : http://www.wpfreeware.com/
========================================*/


text:
var React = require("react");
var ReactDOM = require("react-dom");
var CommentBox = require("./CommentBox");

// Static content
ReactDOM.render(

Hello again, world.

Some static content in ReactDOM render method

This replaces the thing with ID of "example"

,

	document.getElementById("example")
);

// Using module
ReactDOM.render(
	<CommentBox
		url="/api/data.json"
		pollInterval={ 2000 } />,

	document.getElementById("content")
);


text:
import {BaseIfc} from "./BaseIfc"

// http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcspecularroughness.htm
export type IfcSpecularRoughness = number


text:
<!--
id: 1558199337
link: http://tumblr.atmos.org/post/1558199337/articlecontentsniffing-doctype-howto-protect
slug: articlecontentsniffing-doctype-howto-protect
date: Fri Nov 12 2010 19:48:29 GMT-0800 (PST)
publish: 2010-11-012
tags:
title: ArticleContentSniffing - doctype - HOWTO protect against malicious images and other non-HTML content - Project Hosting on Google Code
-->

ArticleContentSniffing - doctype - HOWTO protect against malicious images and other non-HTML content - Project Hosting on Google Code
=====================================================================================================================================

[http://code.google.com/p/doctype/wiki/ArticleContentSniffing](http://code.google.com/p/doctype/wiki/ArticleContentSniffing)


text:
package com.personlife.view.activity.personcenter;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.example.personlifep.R;
import com.fasterxml.jackson.core.type.TypeReference;
import com.loopj.android.http.RequestParams;
import com.personlife.bean.Message;
import com.personlife.bean.SystemNotification;
import com.personlife.net.BaseAsyncHttp;
import com.personlife.net.JSONArrayHttpResponseHandler;
import com.personlife.utils.ComplexPreferences;
import com.personlife.utils.Constants;
import com.personlife.utils.ImageLoaderUtils;
import com.personlife.utils.PersonInfoLocal;
import com.personlife.utils.Utils;
import com.personlife.view.activity.circle.CircleActivity;

public class MessageActivity extends Activity implements OnClickListener {
	Button mBtnBack;
	TextView mTitle;
	ListView listview;
	List<Message> messages;
	MessageAdapter messageApdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_listview);
		mBtnBack = (Button) findViewById(R.id.txt_left);
		mBtnBack.setVisibility(View.VISIBLE);
		mBtnBack.setOnClickListener(this);
		mTitle = (TextView) findViewById(R.id.txt_title);
		mTitle.setText("消息列表");
		listview = (ListView) findViewById(R.id.listview);
		messages = new ArrayList<Message>();
		messageApdapter = new MessageAdapter(getApplicationContext(), messages);
		RequestParams request = new RequestParams();
		request.add("phone", PersonInfoLocal.getPhone(getApplicationContext()));
		BaseAsyncHttp.postReq(this, "/users/notify", request,
				new JSONArrayHttpResponseHandler() {
					@Override
					public void jsonSuccess(JSONArray resp) {
						// TODO Auto-generated method stub
						for (int i = 0; i < resp.length(); i++) {
							Message message = new Message();
							JSONObject messagejson = resp.optJSONObject(i);
							message.setKind(messagejson.optString("kind"));
							message.setContent(messagejson.optString("content"));
							message.setNickname(messagejson
									.optString("nickname"));
							message.setPhone(messagejson.optString("phone"));
							message.setTime(messagejson.optLong("created_at"));
							message.setThumb(messagejson.optString("thumb"));
							messages.add(message);
						}
						if (messages.size() == 0)
							messages = ComplexPreferences.getObject(
									getApplicationContext(), Constants.MESSAGE,
									new TypeReference<ArrayList<Message>>() {
									});
						if (messages != null)
							ComplexPreferences.putObject(
									getApplicationContext(), Constants.MESSAGE,
									messages);
						listview.setAdapter(messageApdapter);
					}

					@Override
					public void jsonFail(JSONArray resp) {
						// TODO Auto-generated method stub
						messages = ComplexPreferences.getObject(
								getApplicationContext(), Constants.MESSAGE,
								new TypeReference<ArrayList<Message>>() {
								});
						if (messages != null)
							listview.setAdapter(messageApdapter);
					}
				});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.txt_left:
			finish();
			break;
		}
	}

	class MessageAdapter extends BaseAdapter implements SectionIndexer {
		private Context mContext;
		private List<Message> messages;

		public MessageAdapter(Context mContext, List<Message> messages) {
			this.mContext = mContext;
			this.messages = messages;

		}

		@Override
		public int getCount() {
			return messages.size();
		}

		@Override
		public Object getItem(int position) {
			return messages.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.layout_item_message, null);
			}
			TextView nickname = (TextView) convertView
					.findViewById(R.id.nickname);
			TextView content = (TextView) convertView
					.findViewById(R.id.content);
			TextView time = (TextView) convertView.findViewById(R.id.time);
			TextView kind = (TextView) convertView.findViewById(R.id.kind);
			ImageView thumb = (ImageView) convertView.findViewById(R.id.thumb);
			final Message message = messages
					.get(messages.size() - position - 1);
			nickname.setText(message.getNickname());
			content.setText(message.getContent());
			time.setText(Utils.TimeStamp2SystemNotificationDate(message
					.getTime()));
			kind.setText(message.getKind());
			ImageLoaderUtils.displayImageView(message.getThumb(), thumb);
			nickname.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utils.start_Activity(MessageActivity.this,
							CircleActivity.class, new BasicNameValuePair(
									"starphone", message.getPhone()));
				}
			});
			return convertView;
		}

		@Override
		public int getPositionForSection(int section) {
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			return 0;
		}

		@Override
		public Object[] getSections() {
			return null;
		}
	}
}


text:
#ifndef PADDLE_ONLY_CPU
/**
 * This test file use autotest::AutoCompare and cmpWithArg to compares the
 * implementation of CPU and GPU member function in Matrix.cpp.
 */

#include <gtest/gtest.h>
#include "TestUtils.h"

using paddle::BaseMatrix;
using paddle::Matrix;
using paddle::CpuMatrix;
using paddle::CpuIVector;
using paddle::CpuSparseMatrix;
using autotest::AutoCompare;

void testBilinearFwdBwd(int numSamples,
                        int imgSizeH,
                        int imgSizeW,
                        int channels) {
  int inWidth = imgSizeH * imgSizeW * channels;
  int outWidth = 2 * imgSizeH * 2 * imgSizeW * channels;
  real ratioH = 0.5;
  real ratioW = 0.5;

  AutoCompare forward(numSamples, outWidth);
  CpuMatrix arg1(numSamples, inWidth);
  arg1.randomizeUniform();
  forward.cmpWithArg(&Matrix::bilinearForward,
                     arg1,
                     imgSizeH,
                     imgSizeW,
                     2 * imgSizeH,
                     2 * imgSizeW,
                     channels,
                     ratioH,
                     ratioW);

  AutoCompare backward(numSamples, inWidth);
  CpuMatrix arg2(numSamples, outWidth);
  arg2.randomizeUniform();
  backward.cmpWithArg(&Matrix::bilinearBackward,
                      arg2,
                      2 * imgSizeH,
                      2 * imgSizeW,
                      imgSizeH,
                      imgSizeW,
                      channels,
                      ratioH,
                      ratioW);
}

TEST(Matrix, BilinearFwdBwd) {
  for (auto numSamples : {5, 10}) {
    for (auto channels : {8, 16}) {
      for (auto imgSizeH : {14, 28}) {
        for (auto imgSizeW : {16, 30}) {
          VLOG(3) << " numSamples=" << numSamples << " channels=" << channels
                  << " imgSizeH=" << imgSizeH << " imgSizeW=" << imgSizeW;
          testBilinearFwdBwd(numSamples, imgSizeH, imgSizeW, channels);
        }
      }
    }
  }
}

void testMatrixAddBias(int height, int width, real scale) {
  AutoCompare test(height, width);
  CpuMatrix arg1(1, width);
  arg1.randomizeUniform();
  test.cmpWithArg(
      static_cast<void (Matrix::*)(Matrix&, real)>(&Matrix::addBias),
      arg1,
      scale);
}

void testMatrixAddDotMulMMV(int height, int width) {
  AutoCompare test(height, width);
  CpuMatrix arg1(height, width);
  CpuMatrix arg2(1, width);
  arg1.randomizeUniform();
  arg2.randomizeUniform();
  test.cmpWithArg(&BaseMatrix::addDotMulMMV, arg1, arg2);
}

TEST(Matrix, unary) {
  for (auto height : {1, 3, 11, 73, 128, 200, 330}) {
    for (auto width : {1, 3, 32, 100, 512, 1000, 3210}) {
      VLOG(3) << " height=" << height << " width=" << width;
      testMatrixAddBias(height, width, 1.0);
      testMatrixAddBias(height, width, 3.5);
      testMatrixAddDotMulMMV(height, width);
    }
  }
}

void testMatrixAddAtOffset(int height, int width1, int width2, int offset) {
  AutoCompare test(height, width2);
  CpuMatrix arg1(height, width1);
  arg1.randomizeUniform();
  test.cmpWithArg(&Matrix::addAtOffset, arg1, offset);
}

void testMatrixAssignAtOffset(int height, int width1, int width2, int offset) {
  AutoCompare test(height, width2);
  CpuMatrix arg1(height, width1);
  arg1.randomizeUniform();
  test.cmpWithArg(&Matrix::assignAtOffset, arg1, offset);
}

TEST(Matrix, AtOffset) {
  for (auto height : {1, 11, 73, 128, 200}) {
    for (auto width1 : {1, 32, 100, 512, 1000}) {
      for (auto width2 : {1, 32, 100, 512, 1000}) {
        int columnOffset = 0;
        int offset = std::abs(width1 - width2);
        if (offset) {
          columnOffset = std::rand() % offset;
        }
        VLOG(3) << " height=" << height << " width1=" << width1
                << " width2=" << width2 << " columnOffset = " << columnOffset;
        testMatrixAddAtOffset(height, width1, width2, columnOffset);
        testMatrixAssignAtOffset(height, width1, width2, columnOffset);
      }
    }
  }
}

void testMatrixSelectRows(int numSamples, int tableSize, int inputDim) {
  AutoCompare test(numSamples, inputDim);
  CpuMatrix arg1(tableSize, inputDim);
  CpuIVector arg2(numSamples);
  arg1.randomizeUniform();
  arg2.rand(tableSize);
  test.cmpWithArg(&Matrix::selectRows, arg1, arg2);
}

TEST(Matrix, tableProjection) {
  for (auto numSamples : {10, 100, 1000, 10000, 80000}) {
    for (auto tableSize : {10, 100}) {
      for (auto inputDim : {20, 50}) {
        VLOG(3) << " numSamples=" << numSamples << " tableSize=" << tableSize
                << " inputDim=" << inputDim;
        testMatrixSelectRows(numSamples, tableSize, inputDim);
      }
    }
  }
}

void testMatrixCopyByRowIndex(int outHeight, int inHeight, int width) {
  AutoCompare test(outHeight, width);
  CpuMatrix arg1(inHeight, width);
  CpuIVector arg2(outHeight);
  arg1.randomizeUniform();
  arg2.rand(inHeight);
  test.cmpWithArg(&Matrix::copyByRowIndex, arg1, arg2);
}

TEST(Matrix, copyByRowIndex) {
  for (auto outHeight : {31, 500, 1000}) {
    for (auto inHeight : {17, 257, 500, 1200}) {
      for (auto width : {512, 1024}) {
        VLOG(3) << outHeight << " " << inHeight << " " << width;
        testMatrixCopyByRowIndex(outHeight, inHeight, width);
      }
    }
  }
}

void testParamReluForward(int height, int width, int w_height, int w_width) {
  AutoCompare test(height, width);
  CpuMatrix arg1(height, width);
  CpuMatrix arg2(w_height, w_width);
  arg1.randomizeUniform();
  arg2.randomizeUniform();
  arg1.add(-0.5);
  test.cmpWithArg(&Matrix::paramReluForward, arg1, arg2);
}

void testParamReluBackwardW(int height, int width, int w_height, int w_width) {
  AutoCompare test(w_height, w_width);
  CpuMatrix arg1(height, width);
  CpuMatrix arg2(height, width);
  arg1.randomizeUniform();
  arg2.randomizeUniform();
  arg2.add(-0.5);
  test.cmpWithArg(&Matrix::paramReluBackwardW, arg1, arg2);
}

TEST(Matrix, paramRelu) {
  for (auto height : {10, 40, 100}) {
    for (auto width : {10, 40, 100}) {
      for (auto w_height : {1, 2}) {
        for (auto w_width : {1, 2}) {
          if (width % (w_height * w_width)) continue;
          testParamReluForward(height, width, w_height, w_width);
          testParamReluBackwardW(height, width, w_height, w_width);
        }
      }
    }
  }
}

void testAddSharedBias(int numSamples, int dim, int channel) {
  AutoCompare test(numSamples, dim);
  CpuMatrix arg1(1, channel);
  arg1.randomizeUniform();
  test.cmpWithArg(&Matrix::addSharedBias, arg1, 1.0);
}

void testCollectSharedBias(int numSamples, int dim, int channel) {
  AutoCompare test(1, channel);
  CpuMatrix arg1(numSamples, dim);
  arg1.randomizeUniform();
  test.cmpWithArg(&Matrix::collectSharedBias, arg1, 1.0);
}

TEST(Matrix, sharedBias) {
  for (auto numSamples : {1, 100, 520}) {
    for (auto dim : {100 * 16, 100 * 32}) {
      for (auto channel : {8, 16}) {
        VLOG(3) << " numSamples=" << numSamples << " dim=" << dim
                << " channel=" << channel;
        testAddSharedBias(numSamples, dim, channel);
        testCollectSharedBias(numSamples, dim, channel);
      }
    }
  }
}

void testMultiBinaryLabelCrossEntropy(int numSamples, int dim) {
  AutoCompare forward(numSamples, 1);
  CpuMatrix arg1(numSamples, dim);
  CpuSparseMatrix arg2(
      numSamples, dim, numSamples, paddle::NO_VALUE, paddle::SPARSE_CSR);

  CpuMatrix output1(numSamples, dim);
  output1.randomizeUniform();
  output1.softmax(arg1);
  for (int i = 0; i < numSamples; i++) {
    const unsigned int id = std::rand() % dim;
    arg2.setRow(i, 1, &id, nullptr);
  }
  forward.cmpWithArg(&Matrix::multiBinaryLabelCrossEntropy, arg1, arg2);

  AutoCompare backward(numSamples, dim);
  backward.cmpWithArg(&Matrix::multiBinaryLabelCrossEntropyBp, arg1, arg2);
}

TEST(Matrix, multiBinaryCrossEntropy) {
  for (auto numSamples : {100, 1000, 10000}) {
    for (auto dim : {100, 1000, 10000}) {
      VLOG(3) << " numSamples=" << numSamples << " dim=" << dim;
      testMultiBinaryLabelCrossEntropy(numSamples, dim);
    }
  }
}

#endif


text:
using namespace arangodb::cache;

Metadata::Metadata()
    : fixedSize(0),
      tableSize(0),
      maxSize(0),
      allocatedSize(0),
      deservedSize(0),
      usage(0),
      softUsageLimit(0),
      hardUsageLimit(0),
      _lock(),
      _migrating(0),
      _resizing(0) {}

Metadata::Metadata(uint64_t usageLimit, uint64_t fixed, uint64_t table, uint64_t max)
    : fixedSize(fixed),
      tableSize(table),
      maxSize(max),
      allocatedSize(usageLimit + fixed + table + Manager::cacheRecordOverhead),
      deservedSize(allocatedSize),
      usage(0),
      softUsageLimit(usageLimit),
      hardUsageLimit(usageLimit),
      _lock(),
      _migrating(0),
      _resizing(0) {
  TRI_ASSERT(allocatedSize <= maxSize);
}

Metadata::Metadata(Metadata&& other)
    : fixedSize(other.fixedSize),
      tableSize(other.tableSize),
      maxSize(other.maxSize),
      allocatedSize(other.allocatedSize),
      deservedSize(other.deservedSize),
      usage(other.usage.load()),
      softUsageLimit(other.softUsageLimit),
      hardUsageLimit(other.hardUsageLimit),
      _lock(std::move(other._lock)),
      _migrating(other._migrating),
      _resizing(other._resizing) {}

Metadata& Metadata::operator=(Metadata&& other) {
  if (this != &other) {
    _lock = std::move(other._lock);
    _migrating = other._migrating;
    _resizing = other._resizing;
    fixedSize = other.fixedSize;
    tableSize = other.tableSize;
    maxSize = other.maxSize;
    allocatedSize = other.allocatedSize;
    deservedSize = other.deservedSize;
    usage = other.usage.load();
    softUsageLimit = other.softUsageLimit;
    hardUsageLimit = other.hardUsageLimit;
  }

  return *this;
}

bool Metadata::adjustUsageIfAllowed(int64_t usageChange) noexcept {
  while (true) {
    uint64_t expected = usage.load(std::memory_order_acquire);
    uint64_t desired = (usageChange < 0)
                           ? expected - static_cast<uint64_t>(-usageChange)
                           : expected + static_cast<uint64_t>(usageChange);

    if ((desired > hardUsageLimit) ||
        ((expected <= softUsageLimit) && (desired > softUsageLimit))) {
      return false;
    }

    bool success = usage.compare_exchange_weak(expected, desired, std::memory_order_acq_rel,
                                               std::memory_order_relaxed);
    if (success) {
      break;
    }
  }

  return true;
}

bool Metadata::adjustLimits(uint64_t softLimit, uint64_t hardLimit) noexcept {
  TRI_ASSERT(isWriteLocked());
  uint64_t fixed = tableSize + fixedSize + Manager::cacheRecordOverhead;
  auto approve = [&]() -> bool {
    softUsageLimit = softLimit;
    hardUsageLimit = hardLimit;
    allocatedSize = hardUsageLimit + fixed;

    return true;
  };

  // special case: start shrink to minimum, ignore deserved/max (table may be
  // too big, should shrink during process)
  if ((softLimit == Cache::minSize) && hardLimit == hardUsageLimit) {
    return approve();
  }

  // special case: finalize shrinking case above
  if ((softLimit == Cache::minSize) && (hardLimit == Cache::minSize) && (usage <= hardLimit)) {
    return approve();
  }

  // general case: start shrinking
  if ((hardLimit == hardUsageLimit) && (softLimit < hardLimit) &&
      (softLimit + fixed <= std::min(deservedSize, maxSize))) {
    return approve();
  }

  // general case: finish shrinking
  if ((softLimit == softUsageLimit) && (softLimit == hardLimit) && (usage <= hardLimit)) {
    return approve();
  }

  // general case: adjust both above usage but below deserved/maxSize
  if ((softLimit == hardLimit) && (usage <= hardLimit) &&
      ((hardLimit + fixed) <= std::min(deservedSize, maxSize))) {
    return approve();
  }

  return false;
}

uint64_t Metadata::adjustDeserved(uint64_t deserved) noexcept {
  TRI_ASSERT(isWriteLocked());
  deservedSize = std::min(deserved, maxSize);
  return deservedSize;
}

uint64_t Metadata::newLimit() const noexcept {
  TRI_ASSERT(isLocked());
  uint64_t fixed = fixedSize + tableSize + Manager::cacheRecordOverhead;
  return ((Cache::minSize + fixed) >= deservedSize)
             ? Cache::minSize
             : std::min((deservedSize - fixed), 4 * hardUsageLimit);
}

bool Metadata::migrationAllowed(uint64_t newTableSize) noexcept {
  TRI_ASSERT(isLocked());
  return (hardUsageLimit + fixedSize + newTableSize + Manager::cacheRecordOverhead <=
          std::min(deservedSize, maxSize));
}

void Metadata::changeTable(uint64_t newTableSize) noexcept {
  TRI_ASSERT(isWriteLocked());
  tableSize = newTableSize;
  allocatedSize = hardUsageLimit + fixedSize + tableSize + Manager::cacheRecordOverhead;
}


text:
FOUNDATION_EXPORT double ParityVersionNumber;
FOUNDATION_EXPORT const unsigned char ParityVersionString[];


text:
3:19 changes
making changes
made some local changes
more changes


text:
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using Orchard.Mvc.Routes;

namespace Orchard.Setup {
    public class Routes : IRouteProvider {
        public void GetRoutes(ICollection<RouteDescriptor> routes) {
            foreach (var routeDescriptor in GetRoutes())
                routes.Add(routeDescriptor);
        }

        public IEnumerable<RouteDescriptor> GetRoutes() {
            return new[] {
                new RouteDescriptor {
                    Route = new Route(
                        "{controller}/{action}",
                        new RouteValueDictionary {
                            {"area", "Orchard.Setup"},
                            {"controller", "Setup"},
                            {"action", "Index"}
                        },
                        new RouteValueDictionary {
                            {"area", "Orchard.Setup"},
                            {"controller", "Setup"},
                        },
                        new RouteValueDictionary {
                            {"area", "Orchard.Setup"}
                        },
                        new MvcRouteHandler())
                }
            };
        }
    }
}


text:
package plp_plugin.launcher;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * This class exists to hold the ServerSockets and Sockets
 * which are connected to the simulation process so that
 * other classes and methods may access them.
 *
 * It also contains a method which allows for the addition of
 * a shutdown hook which closes all the Sockets.
 *
 * @author Cameron Bartee
 */
public class PLPLaunchSockets {

	public static ServerSocket serverSocketTo;
	public static ServerSocket serverSocketFrom;
	public static Socket toSim;
	public static Socket fromSim;

	/**
	 * Whatever calls this method will add a shutdown hook that safely
	 * closes the all the ServerSockets and Sockets.
	 *
	 * Currently, at the time of this writing, it is called in the
	 * plp_plugin.Activator class, in the method stop().
	 */
	public static void closeSockets(){
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
	        public void run() {
	        	try {
	        		if(serverSocketTo != null)
	        			serverSocketTo.close();
	        		if(serverSocketFrom != null)
	        			serverSocketFrom.close();
	        		if(toSim != null)
	        			toSim.close();
	        		if(fromSim != null)
	        			fromSim.close();
	    		} catch (IOException e) {
	    			System.out.println("Error closing sockets!");
	    			e.printStackTrace();
	    		}
	        }
	    }, "Shutdown-thread"));
	}
}


text:
// <copyright file="IProvideGaugeMetrics.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>

using System;

namespace App.Metrics.Gauge
{
    public interface IProvideGaugeMetrics
    {
        IGauge Instance(GaugeOptions options);

        IGauge Instance(GaugeOptions options, MetricTags tags);

        IGauge Instance<T>(GaugeOptions options, Func<T> builder)
            where T : IGaugeMetric;

        IGauge Instance<T>(GaugeOptions options, MetricTags tags, Func<T> builder)
            where T : IGaugeMetric;
    }
}


text:
<?php

declare(strict_types=1);

namespace OpenTelemetry\Tests\Unit\SDK\Trace;

use AssertWell\PHPUnitGlobalState\EnvironmentVariables;
use Exception;
use OpenTelemetry\SDK\Trace\SamplerFactory;
use PHPUnit\Framework\TestCase;

/**
 * @coversDefaultClass OpenTelemetry\SDK\Trace\SamplerFactory
 */
class SamplerFactoryTest extends TestCase
{
    use EnvironmentVariables;

    protected function tearDown(): void
    {
        $this->restoreEnvironmentVariables();
    }

    /**
     * @covers ::create
     * @dataProvider samplerProvider
     */
    public function test_create_sampler_from_environment(string $samplerName, string $expected, string $arg = null): void
    {
        $this->setEnvironmentVariable('OTEL_TRACES_SAMPLER', $samplerName);
        $this->setEnvironmentVariable('OTEL_TRACES_SAMPLER_ARG', $arg);
        $factory = new SamplerFactory();
        $sampler = $factory->create();
        $this->assertStringContainsString($expected, $sampler->getDescription());
    }

    public function samplerProvider(): array
    {
        return [
            'default sampler' => ['', 'ParentBased+AlwaysOn'],
            'always on' => ['always_on', 'AlwaysOn'],
            'always off' => ['always_off', 'AlwaysOff'],
            'trace id ratio' => ['traceidratio', 'TraceIdRatio', '0.95'],
            'parent based always on' => ['parentbased_always_on', 'ParentBased+AlwaysOn'],
            'parent based always off' => ['parentbased_always_off', 'ParentBased+AlwaysOff'],
            'parent based trade id ratio' => ['parentbased_traceidratio', 'ParentBased+TraceIdRatio', '0.95'],
        ];
    }
    /**
     * @covers ::create
     * @dataProvider invalidSamplerProvider
     */
    public function test_throws_exception_for_invalid_or_unsupported(?string $sampler, string $arg = null): void
    {
        $this->setEnvironmentVariable('OTEL_TRACES_SAMPLER', $sampler);
        $this->setEnvironmentVariable('OTEL_TRACES_SAMPLER_ARG', $arg);
        $factory = new SamplerFactory();
        $this->expectException(Exception::class);
        $factory->create();
    }

    public function invalidSamplerProvider(): array
    {
        return [
            'ratio without arg' => ['traceidratio'],
            'parent ratio without arg' => ['parentbased_traceidratio'],
            'ratio with invalid arg' => ['traceidratio', 'foo'],
            'parent ratio with invalid arg' => ['parentbased_traceidratio', 'foo'],
            'unknown sampler' => ['foo'],
        ];
    }
}


text:
using System;
using System.Collections;

namespace CotcSdk
{
	internal class PromiseHandler<T> {
		/// Delegate to call in case of resolved (success) Promise.
		/// Provides a promised type result when resolved.
		public Action<T> Callback;
		public Action<Exception> OnFailure;
	}

	/// @ingroup main_classes
	///
	/// %Promise of future result, which may fail or succeed. Returned as a result of any asnychronous operation.
	///
	/// Complies to the standard %Promise specification: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
	///
	/// Used throughout most API calls to ease the manipulation of asynchronous methods. See [this chapter](#getting_started_ref) for a
	/// tutorial on how to use promises with the SDK.
	///
	/// <typeparam name="PromisedT">Expected result type (in case of success, else an exception is returned).</typeparam>
	public class Promise<PromisedT> {
		private ArrayList ResolvedHandlers = new ArrayList(), RejectedHandlers = new ArrayList();
		private PromisedT ResolvedValue;
		private Exception RejectedValue;
		private PromiseState State = PromiseState.Pending;

		/// Catches a failure at that point in the chain.
		/// <param name="onRejected">Block handling the exception.</param>
		/// <returns>Another promise which is rejected under any circumstances: either for the same reason as this one (if
		/// the promise is caught further in the chain and this block executes well) or with another exception (if the
		/// onRejected block throws an exception). As such, it is highly recommended to provide a .Done() block after your
		/// Catch block, so that any exception in the catch body can be propagated to the unhandled exception handler.</returns>
		public Promise<PromisedT> Catch(Action<Exception> onRejected) {
			var resultPromise = new Promise<PromisedT>();
			Action<PromisedT> resolveHandler = v => {
				resultPromise.Resolve(v);
			};
			Action<Exception> rejectHandler = ex => {
				onRejected(ex);
				resultPromise.Reject(ex);
			};
			ActionHandlers(resolveHandler, rejectHandler, ex => resultPromise.Reject(ex));
			return resultPromise;
		}

		/// Put this at the end of a promise chain. It ensures that unhandled exceptions can be delivered properly.
		/// <param name="onResolved">Execute upon success of all the chain steps.</param>
		/// <param name="onRejected">Execute upon rejection of the promise chain (any failure within the chain).</param>
		public void Done(Action<PromisedT> onResolved, Action<Exception> onRejected) {
			var resultPromise = new Promise<PromisedT>();
			ActionHandlers(onResolved, onRejected, ex => resultPromise.Reject(ex));
		}

		/// Put this at the end of a promise chain.
		/// <param name="onResolved">Execute upon success (as is, this is nearly equivalent to providing a simple Then block, except
		/// that you can not do further chain the promise. Therefore, it ensures that an exception not handled at that point will never
		/// be and allows unhandled exceptions to be delivered properly.</param>
		public void Done(Action<PromisedT> onResolved) {
			var resultPromise = new Promise<PromisedT>();
			ActionHandlers(onResolved, ex => Promise.PropagateUnhandledException(this, ex), ex => resultPromise.Reject(ex));
		}

		/// Put this at the end of a promise chain. It ensures that unhandled exceptions can be delivered properly.
		public void Done() {
			var resultPromise = new Promise<PromisedT>();
			ActionHandlers(value => { }, ex => Promise.PropagateUnhandledException(this, ex), ex => resultPromise.Reject(ex));
		}

		/// Reject this promise (indicate that the process failed for some reason).
		/// <param name="ex">Exception to return as the failure result.</param>
		public void Reject(Exception ex) {
			if (State != PromiseState.Pending) throw new InvalidOperationException("Illegal promise state transition (" + State + " to Rejected)");
			RejectedValue = ex;
			State = PromiseState.Rejected;
			if (Promise.Debug_OutputAllExceptions) {
				Common.LogError("Rejected promise because of exception " + ex.ToString());
			}
			foreach (PromiseHandler<Exception> handler in RejectedHandlers) {
				InvokeHandler(handler.Callback, handler.OnFailure, ex);
			}
			RejectedHandlers.Clear();
		}

		/// Shorthand to create a promise that is already rejected.
		/// <param name="ex">Exception to reject the promise with.</param>
		/// <returns>A promise that is rejected right away.</returns>
		public static Promise<PromisedT> Rejected(Exception ex) {
			Promise<PromisedT> result = new Promise<PromisedT>();
			result.Reject(ex);
			return result;
		}

		/// Resolves the promise, i.e. notifies a successful result of the async operation.
		/// <param name="value">Result of the async operation. Caught by subscribers to this promise via a Then block.</param>
		public void Resolve(PromisedT value) {
			if (State != PromiseState.Pending) throw new InvalidOperationException("Illegal promise state transition (" + State + " to Resolved)");
			ResolvedValue = value;
			State = PromiseState.Fulfilled;
			foreach (PromiseHandler<PromisedT> handler in ResolvedHandlers) {
				InvokeHandler(handler.Callback, handler.OnFailure, value);
			}
			ResolvedHandlers.Clear();
		}

		///
		/// Add a resolved callback and a rejected callback.
		/// The resolved callback chains a value promise (optionally converting to a different value type).
		///
		/// <typeparam name="ConvertedT">Type of the expected result (it should be guessed automatically).</typeparam>
		/// <param name="onResolved">Executed upon successful result.</param>
		/// <returns>A new promise from another type.</returns>
		public Promise<ConvertedT> Then<ConvertedT>(Func<PromisedT, Promise<ConvertedT>> onResolved) {
			return Then(onResolved, null);
		}

		///
		/// Registers a block of code to be executed when the promise returns a successful result.
		///
		/// <param name="onResolved">Executed upon successful result.</param>
		/// <returns>A new promise to be used for chaining (you can Catch an exception that happened in the block for
		/// instance.</returns>
		public Promise<PromisedT> Then(Action<PromisedT> onResolved) {
			return Then(onResolved, null);
		}

		///
		/// Add a resolved callback and a rejected callback.
		/// The resolved callback chains a non-value promise.
		///
		/// <param name="onResolved">Executed upon successful result.</param>
		/// <param name="onRejected">Executed upon failure (promise rejected).</param>
		/// <returns>A promise that can be further chained.</returns>
		public Promise<PromisedT> Then(Action<PromisedT> onResolved, Action<Exception> onRejected) {
			var resultPromise = new Promise<PromisedT>();
			Action<PromisedT> resolveHandler = v => {
				if (onResolved != null) {
					onResolved(v);
				}
				resultPromise.Resolve(v);
			};
			Action<Exception> rejectHandler = ex => {
				if (onRejected != null) {
					onRejected(ex);
				}
				resultPromise.Reject(ex);
			};
			ActionHandlers(resolveHandler, rejectHandler, ex => resultPromise.Reject(ex));
			return resultPromise;
		}

		///
		/// Adds a resolved and rejected callback. Allows for chaining (i.e. return another promise, potentially of another type,
		/// indicating an operation to be waited for). Example:
		/// @code{.cs}
		/// Promise<int> longIntOperation();
		/// Promise<bool> longBoolOperation();
		/// longIntOperation()
		/// .Then((int result) => {
		///     Debug.Log("Result of longIntOperation: " + result");
		///     return longBoolOperation();
		/// })
		/// .Then((bool result) => {
		///     Debug.Log("Result of longBoolOperation: " + result");
		/// })
		/// .Catch((Exception ex) => {
		///     Debug.LogError("Any of the two operations has failed: " + ex.ToString());
		/// }).Done(); @endcode
		///
		/// <typeparam name="ConvertedT">Type of the returned promise (should be guessed automatically).</typeparam>
		/// <param name="onResolved">Executed upon successful result.</param>
		/// <param name="onRejected">Executed upon failure (promise rejected).</param>
		/// <returns>A new promise that can be chained as shown in the summary.</returns>
		public Promise<ConvertedT> Then<ConvertedT>(Func<PromisedT, Promise<ConvertedT>> onResolved, Action<Exception> onRejected) {
			// This version of the function must supply an onResolved.
			// Otherwise there is now way to get the converted value to pass to the resulting promise.
			var resultPromise = new Promise<ConvertedT>();
			Action<PromisedT> resolveHandler = v => {
				onResolved(v)
					.Then(
						(ConvertedT chainedValue) => resultPromise.Resolve(chainedValue),
						ex => resultPromise.Reject(ex)
					)
					.Done();
			};

			Action<Exception> rejectHandler = ex => {
				if (onRejected != null) {
					onRejected(ex);
				}
				resultPromise.Reject(ex);
			};

			ActionHandlers(resolveHandler, rejectHandler, ex => resultPromise.Reject(ex));
			return resultPromise;
		}

		private void ActionHandlers(Action<PromisedT> onResolved, Action<Exception> onRejected, Action<Exception> onRejectResolved) {
			if (State == PromiseState.Pending) {
				if (onResolved != null) {
					ResolvedHandlers.Add(new PromiseHandler<PromisedT>() {
						Callback = onResolved,
						OnFailure = onRejectResolved
					});
				}
				if (onRejected != null) {
					RejectedHandlers.Add(new PromiseHandler<Exception>() {
						Callback = onRejected,
						OnFailure = onRejectResolved
					});
				}
			}
			else if (State == PromiseState.Fulfilled) {
				InvokeHandler(onResolved, onRejectResolved, ResolvedValue);
			}
			else if (State == PromiseState.Rejected) {
				InvokeHandler(onRejected, onRejectResolved, RejectedValue);
			}
		}

		private void InvokeHandler<T>(Action<T> callback, Action<Exception> onFailure, T value) {
			try {
				callback(value);
			}
			catch (Exception ex) {
				if (Promise.Debug_OutputAllExceptions) {
					Common.LogError("Exception in promise Then/Catch/Done block: " + ex.ToString());
				}
				onFailure(ex);
			}
		}

		/// Gets some Promise's stats as a human readable string, like its state and its
		/// resolved/rejected callbacks counts.
		/// <returns>Some Promise's stats as a human readable string.</returns>
		public override string ToString() {
			return base.ToString() + ", State: " + State.ToString() + ", Res: " + ResolvedHandlers.Count + ", Rej: " + RejectedHandlers.Count;
		}
	}
}


text:
package org.apache.wsrp4j.commons.util.impl;

import java.util.ArrayList;
import java.util.Iterator;

import org.apache.wsrp4j.commons.util.StateChangedService;
import org.apache.wsrp4j.commons.util.StateChangedListener;
import org.apache.wsrp4j.commons.util.StateChangedEvent;

/**
 * This class implements the StateChangedService interface and is
 * the parent of all classes with StateChangeService functionality.
 *
 * @version $Id: StateChangedServiceImpl.java 374672 2006-02-03 14:10:58Z cziegeler $
 */
public class StateChangedServiceImpl implements StateChangedService {

    // internal list of StateChangedListeners
    private ArrayList _listeners = new ArrayList();

    /**
     * Constructor
     */
    public StateChangedServiceImpl() {

    }

    /**
     * Adds a StateChangedListener object to the internal
     * array list.
     *
     * @param changeListener to be added
     */
    public void addListener(StateChangedListener changeListener) {

        _listeners.add(changeListener);

    }

    /**
     * Notifies all registered listeners by calling the
     * stateChanged(StateChangedEvent e) method on the
     * target object.
     */
    public void stateChanged() {
        Iterator iterator = _listeners.iterator();
        while (iterator.hasNext()) {
            StateChangedListener listener =
                    (StateChangedListener)iterator.next();
            listener.stateChanged(new StateChangedEvent(this));
        }
    }
}


text:
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Controls;
using StockTraderRI.Infrastructure;

namespace StockTraderRI.Modules.Watch.WatchList
{
    /// <summary>
    /// Interaction logic for WatchListView.xaml
    /// </summary>
    [ViewExport(RegionName = RegionNames.MainRegion)]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public partial class WatchListView : UserControl
    {
        public WatchListView()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Sets the ViewModel.
        /// </summary>
        /// <remarks>
        /// This set-only property is annotated with the <see cref="ImportAttribute"/> so it is injected by MEF with
        /// the appropriate view model.
        /// </remarks>
        [Import]
        [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly", Justification = "Needs to be a property to be composed by MEF")]
        WatchListViewModel ViewModel
        {
            set
            {
                this.DataContext = value;
            }
        }
    }
}


text:
require 'spec_helper'

describe 'codedeploy' do
  context "on redhat-x86_64" do
    let(:facts) do
      {
        :osfamily        => 'RedHat',
        :operatingsystem => 'RedHat',
      }
    end

    context "codedeploy class without any parameters" do
      let(:params) {{ }}

      it { is_expected.to compile.with_all_deps }

      it { is_expected.to contain_package('codedeploy-agent').with_ensure('present') }
    end
  end
  context "on debian-x86_64" do
    let(:facts) do
      {
        :osfamily        => 'Debian',
        :operatingsystem => 'Debian',
      }
    end

    context "codedeploy class without any parameters" do
      let(:params) {{ }}

      it { is_expected.to compile.with_all_deps }

      it { is_expected.to contain_exec('download_codedeploy_installer').with_command('/usr/bin/aws s3 cp s3://aws-codedeploy-us-east-1/latest/install . --region us-east-1') }
      it { is_expected.to contain_exec('install_codedeploy_agent').with_command('/tmp/install auto') }
      it { is_expected.to contain_file('/tmp/install').with({'mode' => '0740'}) }
      it { is_expected.to contain_package('awscli').with({'ensure' => 'present'}) }
      it { is_expected.to contain_package('ruby2.0').with({'ensure' => 'present'}) }
    end
  end
end


text:
package com.basistech.tclre;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import com.google.common.collect.BoundType;
import com.google.common.collect.Lists;

import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.TreeRangeMap;
import com.ibm.icu.lang.UCharacter;

/**
 * Manage the assignment of colors for characters. Arcs are labelled with colors, which group characters.
 * Original code was in regc_color.c.
 *

 * At any point in time, all possible characters are assigned a color.
 * Initially, all characters are color 0 (WHITE). Characters get other colors when the compiler encounters them
 * in an expression. The compiler processes characters two ways: either as single characters,
 * or in ranges. When the compiler sees a single character in isolation, it calls {@link #subcolor(int)}.
 * When it processes a range, it calls {@link #subrange}.
 *

 * This class expects the compiler to call {@link #okcolors} at the end of each 'atom'. An atom is character in isolation, a range, or a subexpression.
 *

 * During the period from one call to {@link #okcolors} to the next, this class can maintain an open 'subcolor' for each color.
 * The idea here is that each new item moves some characters from the color they have at the beginning of the period to a new color.
 * One period is always connecting two states with one or more arcs. If all the characters have the same color, there is one arc;
 * if the characters end up with disparate colors, it is multiple arcs. In a single period, all the characters that are moved out of
 * a particular color have to move into the same new color. Thus, the process of allocating a subcolor works like:
 *
 *

 * - It gets the ColorDesc for the color currently assigned to the character.
 * - It allocates a new color desc and color number.
 * - It fills in the new color number as the 'sub' of the old color.
 * - It returns the sub color number to the rest of the compiler.
 *

 *
 * Subsequent calls to subcolor in an epoch for other characters with the same current color get the same subcolor.
 * Note that in the subrange case, it will call newsub for each item, but once a color has a subcolor, it reuses it, so all the other characters
 * in the range end up (sub)colored identically.
 *
 * So, for an expression like [a-z]ab, we start with color 0 owning everything. When we hit the range, we allocate subcolors for all of a-z -- but they
 * all get the same subcolor. At the ']', okcolors ends the epoch, and 'promotes' the subcolors to colors. Then it processes 'a'. Now a is in color 1,
 * which gets a subcolor of 2. At the end of the epoch, that promotes, and now a is color 2 and color 1 has no subcolor. The same thing
 * happens to 'b', giving it yet another color split from color 1.
 *
 * As colors are promoted, the nfa gets new arcs. It does not appear to lose the old arcs; I suspect that the optimization process somehow
 * removes them.
 */
class ColorMap {
    private final RangeMap<Integer, Short> map;
    // this is called 'v' in the C code.
    private Compiler compiler; // for compile error reporting
    private final List<ColorDesc> colorDescs; // all the color descs. A list for resizability.

    ColorMap(Compiler compiler) {
        map = TreeRangeMap.create();
        // the color map starts by assigning all characters to WHITE
        map.put(Range.closed(0, Character.MAX_CODE_POINT), Constants.WHITE);
        this.compiler = compiler;

        colorDescs = Lists.newArrayList();

        ColorDesc white = new ColorDesc(); // [WHITE]
        colorDescs.add(white);
        assert colorDescs.size() == 1;
        white.sub = Constants.NOSUB;
        white.setNChars(65536);
    }

    /**
     * Retrieve the color for a character.
     * @param c input char.
     * @return output color.
     */
    private short getcolor(int c) {
        try {
            return map.get(c);
        } catch (NullPointerException npe) {
            throw new RegexRuntimeException(String.format("Failed to map codepoint U+%08X.", c));
        }
    }

    /**
     * Maximum valid color, which might encompass some free colors.
     *
     * @return
     */
    short maxcolor() {
        return (short)(colorDescs.size() - 1);
    }

    private short newcolor() {
        short colorIndex = -1;
        for (short x = 0; x < colorDescs.size(); x++) {
            if (colorDescs.get(x) == null) {
                colorIndex = x;
                break;
            }
        }

        ColorDesc newcd = new ColorDesc();
        if (colorIndex == -1) {
            colorIndex = (short)colorDescs.size();
            colorDescs.add(newcd);
        } else {
            colorDescs.set(colorIndex, newcd);
        }
        return colorIndex;
    }

    private void freecolor(short co) {
        assert co >= 0;
        if (co == Constants.WHITE) {
            return;
        }

        // if this is the very last one, shrink
        if (co == colorDescs.size() - 1) {
            colorDescs.remove(co); // just shrink the List.
            return;
        }

        colorDescs.set(co, null);
    }

    /**
     * pseudocolor - allocate a false color to be managed by other means.
     *
     * @return a color, otherwise unused.
     */
    short pseudocolor() {
        short co = newcolor();
        ColorDesc cd = colorDescs.get(co);
        cd.setNChars(1);
        cd.markPseudo();
        return co;
    }

    /**
     * subcolor - allocate a new subcolor (if necessary) to this char
     * Internal API that can do a range of characters; called from
     * {@link #subrange}.
     *
     * @param c The character, or first character in a range, to process.
     * @param rangeCount the number of characters.
     */
    private short subcolor(int c, int rangeCount) throws RegexException {
        short co;           /* current color of c */
        short sco;          /* new subcolor */

        co = getcolor(c);
        sco = newsub(co);
        assert sco != Constants.COLORLESS;

        if (co == sco)      /* already in an open subcolor */ {
            return co;  /* rest is redundant */
        }

        ColorDesc cd = colorDescs.get(co);
        cd.incrementNChars(-rangeCount);
        ColorDesc scd = colorDescs.get(sco);
        scd.incrementNChars(rangeCount);

        map.put(Range.closedOpen(c, c + rangeCount), sco);
        return sco;
    }

    /**
     * Allocate a color for one character. In the range case, call {@link #subrange}.
     * @param c the character
     * @return the subcolor
     * @throws RegexException
     */
    short subcolor(int c) throws RegexException {
        return subcolor(c, 1);
    }

    /**
     * newsub - allocate a new subcolor (if necessary) for a color
     */
    private short newsub(short co) throws RegexException {
        short sco; // new subcolor.

        ColorDesc cd = colorDescs.get(co);

        sco = colorDescs.get(co).sub;
        if (sco == Constants.NOSUB) {       /* color has no open subcolor */
            if (cd.getNChars() == 1) { /* optimization */
                return co;
            }
            sco = newcolor();   /* must create subcolor */
            if (sco == Constants.COLORLESS) {
                throw new RegexException("Invalid color allocation");
            }

            ColorDesc subcd = colorDescs.get(sco);
            cd.sub = sco;
            subcd.sub = sco;    /* open subcolor points to self */
        }

        return sco;
    }

    /**
     * subrange - allocate new subcolors to this range of chars, fill in arcs.
     * The range will overlap existing ranges; even in the simplest case,
     * it will overlap the initial WHITE range. For each existing range that
     * it overlaps, allocate a new color, mark the range as mapping to that color,
     * and add an arc between the states for that color.
     */
    void subrange(int from, int to, State lp, State rp) throws RegexException {
        /* Avoid one call to map.get() for each character in the range.
         * This map will usually contain one item, but in complex cases more.
         * For example, if we had [a-f][g-h] and then someone asked for [f-g], there
         * would be two. Each of these new ranges will get a new color via subcolor.
         */
        Map<Range<Integer>, Short> curColors = map.subRangeMap(Range.closed(from, to)).asMapOfRanges();
        /*
         * To avoid concurrent mod problems, we need to copy the ranges we are working from.
         */
        List<Range<Integer>> ranges = Lists.newArrayList(curColors.keySet());
        for (Range<Integer> rangeToProcess : ranges) {
            // bound management here irritating.
            int start = rangeToProcess.lowerEndpoint();
            if (rangeToProcess.lowerBoundType() == BoundType.OPEN) {
                start++;
            }
            int end = rangeToProcess.upperEndpoint();
            if (rangeToProcess.upperBoundType() == BoundType.CLOSED) {
                end++;
            }
            // allocate a new subcolor and account it owning the entire range.
            short color = subcolor(start, end - start);
            compiler.getNfa().newarc(Compiler.PLAIN, color, lp, rp);
        }
    }

    /**
     * okcolors - promote subcolors to full colors
     */
    void okcolors(Nfa nfa) {
        ColorDesc cd;
        ColorDesc scd;
        Arc a;
        short sco;

        for (short co = 0; co < colorDescs.size(); co++) {
            cd = colorDescs.get(co);
            if (cd == null) {
                continue; // not in use at all, so can't have a subcolor.
            }

            sco = cd.sub;

            if (sco == Constants.NOSUB) {
            /* has no subcolor, no further action */
            } else if (sco == co) {
            /* is subcolor, let parent deal with it */
            } else if (cd.getNChars() == 0) {
            /* parent empty, its arcs change color to subcolor */
                cd.sub = Constants.NOSUB;
                scd = colorDescs.get(sco);

                assert scd.getNChars() > 0;
                assert scd.sub == sco;

                scd.sub = Constants.NOSUB;
                while ((a = cd.arcs) != null) {
                    assert a.co == co;
                    cd.arcs = a.colorchain;
                    a.setColor(sco);
                    a.colorchain = scd.arcs;
                    scd.arcs = a;
                }
                freecolor(co);
            } else {
                /* parent's arcs must gain parallel subcolor arcs */
                cd.sub = Constants.NOSUB;
                scd = colorDescs.get(sco);

                assert scd.getNChars() > 0;
                assert scd.sub == sco;

                scd.sub = Constants.NOSUB;

                for (a = cd.arcs; a != null; a = a.colorchain) {
                    assert a.co == co;
                    nfa.newarc(a.type, sco, a.from, a.to);
                }
            }
        }
    }

    /**
     * colorchain - add this arc to the color chain of its color
     */
    void colorchain(Arc a) {
        ColorDesc cd = colorDescs.get(a.co);
        a.colorchain = cd.arcs;
        cd.arcs = a;
    }

    /**
     * uncolorchain - delete this arc from the color chain of its color
     */
    void uncolorchain(Arc a) {
        ColorDesc cd = colorDescs.get(a.co);
        Arc aa;

        aa = cd.arcs;
        if (aa == a) {      /* easy case */
            cd.arcs = a.colorchain;
        } else {
            for (; aa != null && aa.colorchain != a; aa = aa.colorchain) {
                //
            }
            assert aa != null;
            aa.colorchain = a.colorchain;
        }

        a.colorchain = null;    /* paranoia */
    }

    /**
     * rainbow - add arcs of all full colors (but one) between specified states
     *
     * @param but is COLORLESS if no exceptions
     */
    void rainbow(Nfa nfa, int type, short but, State from, State to) {
        ColorDesc cd;
        short co;

        for (co = 0; co < colorDescs.size(); co++) {
            cd = colorDescs.get(co);
            if (cd != null
                    && cd.sub != co
                    && co != but
                    && !cd.pseudo()) {
                nfa.newarc(type, co, from, to);
            }
        }
    }

    /**
     * colorcomplement - add arcs of complementary colors
     * The calling sequence ought to be reconciled with cloneouts().
     *
     * @param of complements of this guy's PLAIN outarcs
     */
    void colorcomplement(Nfa nfa, int type, State of, State from, State to) {
        ColorDesc cd;
        short co;

        assert of != from;
        for (co = 0; co < colorDescs.size(); co++) {
            cd = colorDescs.get(co);
            if (cd != null && !cd.pseudo()) {
                if (of.findarc(Compiler.PLAIN, co) == null) {
                    nfa.newarc(type, co, from, to);
                }
            }
        }
    }

    /**
     * Return the map for use in the runtime.
     * @return the map.
     */
    RangeMap<Integer, Short> getMap() {
        return map;
    }

    /**
     * dumpcolors - debugging output
     */
    void dumpcolors() {
        /*
         * we want to organize this by colors.
         */
        for (int co = 0; co < colorDescs.size(); co++) {
            ColorDesc cd = colorDescs.get(co);
            if (cd != null) {
                dumpcolor(co, cd);
            }
        }
    }

    /*
     * Not speedy. This is for debugging.
     */
    private void dumpcolor(int co, ColorDesc cd) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pw.format("Color %d - %d chars %s\n", co, cd.getNChars(), cd.pseudo() ? " (pseudo)" : "");
        for (Map.Entry<Range<Integer>, Short> me : map.asMapOfRanges().entrySet()) {
            if (me.getValue() == co) {
                pw.format(" %s %s\n", me.getKey(), UCharacter.getExtendedName(me.getKey().lowerEndpoint()));
            }
        }
        pw.flush();
        String r = sw.toString();
        System.out.println(r);
    }
}