text:
package br.cefetrj.sagitarii.nunki;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import br.cefetrj.sagitarii.nunki.comm.ProxyInfo;

public class Configurator {

	private String hostURL;
	private int poolIntervalMilliSeconds;
	private int activationsMaxLimit;
	private ProxyInfo proxyInfo;
	private int useProxy;
	private Document doc;
	private boolean showConsole;
	private boolean clearDataAfterFinish;
	private char CSVDelimiter;
	private int fileSenderDelay;
	private String storageHost;
	private String rPath;
	private int storagePort;
	private boolean useSpeedEqualizer;
	private boolean enforceTaskLimitToCores;
	private SystemProperties systemProperties;
	private int DLBFrequency;
	private int maximunRamToUse;
	private int maximunCPULimit;
	private int minimunCPULimit;
	private int maxUploadThreads;

	private String dbUrl;
	private String dbUser;
	private String dbPassword;
	private String dbPort;
	private String dbDatabase;

	public String getDbDatabase() {
		return dbDatabase;
	}

	public String getDbPassword() {
		return dbPassword;
	}

	public String getDbPort() {
		return dbPort;
	}

	public String getDbUrl() {
		return dbUrl;
	}

	public String getDbUser() {
		return dbUser;
	}

	public int getMaximunCPULimit() {
		return maximunCPULimit;
	}

	public int getMaxUploadThreads() {
		return maxUploadThreads;
	}

	public int getMinimunCPULimit() {
		return minimunCPULimit;
	}

	private Logger logger = LogManager.getLogger( this.getClass().getName()  );

	public SystemProperties getSystemProperties() {
		return this.systemProperties;
	}

	public char getCSVDelimiter() {
		return CSVDelimiter;
	}

	public void setPoolIntervalMilliSeconds( int millis ) {
		poolIntervalMilliSeconds = millis;
	}

	public boolean enforceTaskLimitToCores() {
		return this.enforceTaskLimitToCores;
	}

	public int getFileSenderDelay() {
		return fileSenderDelay;
	}

	public String getStorageHost() {
		return storageHost;
	}

	public int getStoragePort() {
		return storagePort;
	}

	public boolean getClearDataAfterFinish() {
		return clearDataAfterFinish;
	}

	public void setClearDataAfterFinish(boolean clearDataAfterFinish) {
		this.clearDataAfterFinish = clearDataAfterFinish;
	}

	public boolean useSpeedEqualizer() {
		return useSpeedEqualizer;
	}

	public boolean getShowConsole() {
		return this.showConsole;
	}

	public int getMaximunRamToUse() {
		return maximunRamToUse;
	}

	public ProxyInfo getProxyInfo() {
		return proxyInfo;
	}

	public boolean useProxy() {
		return this.useProxy == 1;
	}

	public String getHostURL() {
		return hostURL;
	}

	public int getPoolIntervalMilliSeconds() {
		if ( poolIntervalMilliSeconds < 200 ) {
			poolIntervalMilliSeconds = 200;
		}
		return poolIntervalMilliSeconds;
	}

	public void setActivationsMaxLimit(int activationsMaxLimit) {
		this.activationsMaxLimit = activationsMaxLimit;
	}

	public int getActivationsMaxLimit() {
		return activationsMaxLimit;
	}

	private String getTagValue(String sTag, Element eElement) throws Exception{
		try {
			NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
	        Node nValue = (Node) nlList.item(0);
			return nValue.getNodeValue();
		} catch ( Exception e ) {
			logger.error("Element " + sTag + " not found in configuration file.");
			throw e;
		}
	 }

	public String getValue(String container, String tagName) {
		String tagValue = "";
		try {
			NodeList postgis = doc.getElementsByTagName(container);
			Node pgconfig = postgis.item(0);
			Element pgElement = (Element) pgconfig;
			tagValue = getTagValue(tagName, pgElement) ;
		} catch ( Exception e ) {
		}
		return tagValue;
	}

	public Configurator(String file) throws Exception {
		logger.debug("loading XML data from " + file);

		File fil = new File( file );
		if ( !fil.exists() ) {
			System.out.println("xml config file not found at folder");
			System.out.println( file );
			System.exit(0);
		}

		try {
			InputStream is = new FileInputStream( file );
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(is);
			doc.getDocumentElement().normalize();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("XML file " + file + " not found.");
		}

		systemProperties = new SystemProperties();
	}

	public List<Wrapper> getRepositoryList() {
		List<Wrapper> resp = new ArrayList<Wrapper>();
		NodeList mapconfig = doc.getElementsByTagName("wrapper");
		for ( int x = 0; x < mapconfig.getLength(); x++ ) {
			try {
				Node mpconfig = mapconfig.item(x);
				Element mpElement = (Element) mpconfig;
				String version = mpElement.getAttribute("version");
				String type = mpElement.getAttribute("type");
				String wrapperName = mpElement.getAttribute("activity");
				String hash = mpElement.getAttribute("hash");
				String target = mpElement.getAttribute("target");

				Wrapper acc = new Wrapper();
				acc.fileName = wrapperName;
				acc.type = type;
				acc.version = version;
				acc.target = target;
				acc.hash = hash;
				resp.add(acc);
			} catch (Exception e){
				System.out.println( e.getMessage() );
			}
		}

		return resp;
	}

	public String getrPath() {
		return rPath;
	}

	public int getDLBFrequency() {
		return DLBFrequency;
	}

	public void loadMainConfig()  {

			NodeList mapconfig = doc.getElementsByTagName("cluster");
			Node mpconfig = mapconfig.item(0);
			Element mpElement = (Element) mpconfig;
			try {
				hostURL = getTagValue("hostURL", mpElement);
				CSVDelimiter = getTagValue("CSVDelimiter", mpElement).charAt(0);
				poolIntervalMilliSeconds = Integer.valueOf( getTagValue("poolIntervalMilliSeconds", mpElement) );

				activationsMaxLimit = systemProperties.getAvailableProcessors();

				storageHost = getTagValue("storageHost", mpElement);
				rPath = getTagValue("rPath", mpElement);

				storagePort = Integer.valueOf( getTagValue("storagePort", mpElement) );
				fileSenderDelay = Integer.valueOf( getTagValue("fileSenderDelay", mpElement) );
				showConsole = Boolean.parseBoolean( getTagValue("activationShowConsole", mpElement) );
				clearDataAfterFinish = Boolean.parseBoolean( getTagValue("clearDataAfterFinish", mpElement) );
				useSpeedEqualizer = Boolean.parseBoolean( getTagValue("useSpeedEqualizer", mpElement) );
				enforceTaskLimitToCores = Boolean.parseBoolean( getTagValue("enforceTaskLimitToCores", mpElement) );
				DLBFrequency = Integer.valueOf( getTagValue("DLBFrequency", mpElement) );
				maximunRamToUse = Integer.valueOf( getTagValue("maximunRamToUse", mpElement) );

				maximunCPULimit = Integer.valueOf( getTagValue("maximunCPULimit", mpElement) );
				minimunCPULimit = Integer.valueOf( getTagValue("minimunCPULimit", mpElement) );
				maxUploadThreads = Integer.valueOf( getTagValue("maxUploadThreads", mpElement) );

				dbUrl = getTagValue("dbUrl", mpElement);
				dbUser = getTagValue("dbUser", mpElement);
				dbPassword = getTagValue("dbPassword", mpElement);
				dbPort = getTagValue("dbPort", mpElement);
				dbDatabase = getTagValue("dbDatabase", mpElement);

				if ( enforceTaskLimitToCores ) {
					useSpeedEqualizer = false;
				}

				useProxy = Integer.parseInt( getValue("proxy", "useProxy") );

				if (useProxy == 1) {
					proxyInfo = new ProxyInfo();
					proxyInfo.setHost( getValue("proxy", "proxy-host") );
					proxyInfo.setPort( Integer.parseInt(getValue("proxy", "proxy-port"))  );
					proxyInfo.setPassword( getValue("proxy", "proxy-password") );
					proxyInfo.setUser( getValue("proxy", "proxy-user") );
				}

			} catch ( Exception e ) {
				System.out.println( e.getMessage() );
			}

	}

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Cmajalisfting.GitHub.io by CmajalisFting</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">

Cmajalisfting.GitHub.io

erjuan's blog

Hello World! erjuan.

大海中的一颗星辰,天空中的一枚卷花。

        This page was generated by GitHub Pages using the Cayman theme by Jason Long.

redpajama_set_name: RedPajamaGithub


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

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.hamcrest.Description;
import org.hamcrest.SelfDescribing;

import static org.hobsoft.hamcrest.submatcher.Preconditions.checkNotNull;

/**
 * Defines an invocation of a Java method.
 */
class MethodInvocation implements SelfDescribing
{
	// ----------------------------------------------------------------------------------------------------------------
	// fields
	// ----------------------------------------------------------------------------------------------------------------

	private final Method method;

	private final Object[] arguments;

	// ----------------------------------------------------------------------------------------------------------------
	// constructors
	// ----------------------------------------------------------------------------------------------------------------

	public MethodInvocation(Method method, Object... arguments)
	{
		this.method = checkNotNull(method, "method");
		this.arguments = checkNotNull(arguments, "arguments");
	}

	// ----------------------------------------------------------------------------------------------------------------
	// SelfDescribing methods
	// ----------------------------------------------------------------------------------------------------------------

	public void describeTo(Description description)
	{
		description.appendText(method.getName())
			.appendValueList("(", ", ", ")", arguments);
	}

	// ----------------------------------------------------------------------------------------------------------------
	// public methods
	// ----------------------------------------------------------------------------------------------------------------

	public Object invoke(Object instance) throws IllegalAccessException, InvocationTargetException
	{
		return method.invoke(instance, arguments);
	}

	public Method getMethod()
	{
		return method;
	}

	public Object[] getArguments()
	{
		return arguments;
	}
}


text:
from django.contrib import admin
from metatags.models import Metatag, MetatagType

class MetatagAdmin(admin.ModelAdmin):
    list_display = ('type', '_content_object', 'content_type', 'object_id')
    list_filter = ('type','content_type')
    ordering = ('content_type','object_id')

admin.site.register(MetatagType)
admin.site.register(Metatag, MetatagAdmin)


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Logania campanulata R.Br.

### Remarks
null


text:
package logics

import (
	"github.com/qb0C80aE/clay/extensions"
	clayLogics "github.com/qb0C80aE/clay/logics"
	"github.com/qb0C80aE/loam/models"
)

type portGroupLogic struct {
	*clayLogics.BaseLogic
}

func newPortGroupLogic() *portGroupLogic {
	logic := &portGroupLogic{
		BaseLogic: clayLogics.NewBaseLogic(
			models.SharedPortGroupModel(),
		),
	}
	return logic
}

var uniquePortGroupLogic = newPortGroupLogic()

// UniquePortGroupLogic returns the unique portGroup logic instance
func UniquePortGroupLogic() extensions.Logic {
	return uniquePortGroupLogic
}

func init() {
	extensions.RegisterLogic(models.SharedPortGroupModel(), UniquePortGroupLogic())
	extensions.RegisterDesignAccessor(uniquePortGroupLogic)
}


text:
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#ifndef _FX_ARABIC_IMP
#define _FX_ARABIC_IMP
class CFX_BidiChar FX_FINAL : public IFX_BidiChar, public CFX_Object
{
public:
    CFX_BidiChar();
    virtual void		Release() FX_OVERRIDE
    {
        delete this;
    }
    virtual void		SetPolicy(FX_BOOL bSeparateNeutral = TRUE) FX_OVERRIDE
    {
        m_bSeparateNeutral = bSeparateNeutral;
    }
    virtual FX_BOOL		AppendChar(FX_WCHAR wch) FX_OVERRIDE;
    virtual FX_BOOL		EndChar() FX_OVERRIDE;
    virtual FX_INT32	GetBidiInfo(FX_INT32 &iStart, FX_INT32 &iCount) FX_OVERRIDE;
    virtual void		Reset() FX_OVERRIDE;
protected:
    FX_BOOL		m_bSeparateNeutral;
    FX_INT32	m_iCurStart;
    FX_INT32	m_iCurCount;
    FX_INT32	m_iCurBidi;
    FX_INT32	m_iLastBidi;
    FX_INT32	m_iLastStart;
    FX_INT32	m_iLastCount;
};
#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cenangium magnoliae Berk. & M.A. Curtis

### Remarks
null


text:
'use strict';function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
var post_message_bus_1 = require('angular2/src/web_workers/shared/post_message_bus');
var application_common_1 = require("angular2/src/web_workers/worker/application_common");
__export(require("angular2/src/web_workers/shared/message_bus"));
var _postMessage = postMessage;
/**
 * Bootstrapping a Webworker Application
 *
 * You instantiate the application side by calling bootstrapWebworker from your webworker index
 * script.
 * You can call bootstrapWebworker() exactly as you would call bootstrap() in a regular Angular
 * application
 * See the bootstrap() docs for more details.
 */
function bootstrapWebWorker(appComponentType, componentInjectableBindings) {
    if (componentInjectableBindings === void 0) { componentInjectableBindings = null; }
    var sink = new post_message_bus_1.PostMessageBusSink({
        postMessage: function (message, transferrables) { _postMessage(message, transferrables); }
    });
    var source = new post_message_bus_1.PostMessageBusSource();
    var bus = new post_message_bus_1.PostMessageBus(sink, source);
    return application_common_1.bootstrapWebWorkerCommon(appComponentType, bus, componentInjectableBindings);
}
exports.bootstrapWebWorker = bootstrapWebWorker;
//# sourceMappingURL=application.js.map


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Fusion;
using Fusion.Core.Mathematics;
using Fusion.Core.Development;
using Fusion.Build;

namespace SpriteDemo {
	class Program {

		[STAThread]
		static void Main ( string[] args )
		{
			Trace.Listeners.Add( new ColoredTraceListener() );

			Fusion.Core.Test.Tester.Run();

			try {
				Builder.Build( @"..\..\..\Content", @"Content", @"..\..\..\Temp", false );
			} catch ( Exception e ) {
				Log.Error( e.Message );
				return;
			}

			using ( var game = new SpriteDemo() ) {
				game.Run(args);
			}
		}
	}
}


text:
OpenShift V3 Reliability
===========================
Software reliability testing is a field of software testing that relates to testing a software's ability to function, given environmental conditions, for a particular amount of time.
Openshift Reliability testing is an operational testing scheme that uses a baseline work efficiency specification to evaluate the stability of openshift system in the given amount of time. The purpose is to discover problems in functionality. The baseline work efficiency specification was made up of daily tasks such as applications developing, hosting and scaling.

Design
===========================
Openshift Task are classified by hourly, daily, weekly and monthly and run in different termly.  The tasks include user creation ,project creation, Project modification. openshift monitor and log analysis. System log and Operation logs will be analysed regularly. Jobs elapsed time, openshift process memory usage, openshift process CPU usage, system memory and system CPU usage are gathered.

Serveral tasks are defined as following

      create "10" user

      login "100%" users

      create "10" projects

      create "10" applications

      modify "100%" projecs

      scale up "100%" appplications

      scale down "100%" app

      delete "100%" project

      delete "all" user

      check project info

      clean environment

      monitor openshift

      monitor masters

      monitor nodes

      monitor etcds

A bundle of tasks are grouped by time files under config/tasks, these files will be executed during testing

For example:

*cat config/tasks/day*

*login "100%" users*

*create "5" user*

*visit "100%" app*

*modify "20%" project*

*scale up "80%" app*

*check project info*

Execute
===========================
1) pre execution

  edit config/config.yaml

  update awscreds file with AWSAccessKeyId and AWSSecretKey which will be used for cloudwatch monitoring.

  ansible-playbook setup.yml

  define tasks under config/tasks/

2) run testing

   ./reliabilityTests.sh start (to start the tests)

   ./reliabilityTests.sh stop (to stop the tests)

   ./reliabilityTests.sh pause (to pause the running tests)

   ./reliabilityTests.sh resume (to resume the tests)

3) post execution

   The log are under logs directory

   analyst directory has a parse-logs.sh script which parses data and creates results directory

   results directory will have csv files with CPU and Memory consumptions and all the activities done by tests.

   PBench results are available on server configured in /opt/pbench-agent/config/pbench-agent.conf

Execute in Docker Container
===========================
1) pre execution

   clone the git repo on docker host

   edit config/config.yaml

   define tasks under config/tasks/

   update awscreds file with AWSAccessKeyId and AWSSecretKey which will be used for cloudwatch monitoring.

2) run testing

   build image using Dockerfile

   `docker build -t <image_name>:<version>`
   run image using following command

   `docker run -v <path_to_svt_clone>:/root/svt -v <ssh_key1>:/root/.ssh/id_rsa -v <updated_pbench-agent.conf>:/opt/pbench-agent/config/pbench-agent.conf -v <ssh_key2>:/opt/pbench-agent/id_rsa -t -i <image_name>:<version>

   ssh_key1=ssh key for nodes and master hosts
   ssh_key2=ssh key for pbench server to move results.`

3) post execution

   The log are under logs/

   analyst directory has a parse-logs.sh script which parses data and creates results directory

   results directory will have csv files with CPU and Memory consumptions and all the activities done by tests.

   PBench results are available on server configured in /opt/pbench-agent/config/pbench-agent.conf

TODO

======================

crontab support

GUI configure

Cloud running

Reference

======================

1. Crontab https://bitbucket.org/dbenamy/devcron#egg=devcron

2. http://www.pcp.io/docs/installation.html


text:
package org.apache.hadoop.hbase;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ClassSize;
import org.apache.yetus.audience.InterfaceAudience;

@InterfaceAudience.Private
public class IndividualBytesFieldCell implements ExtendedCell, Cloneable {
  // do alignment(padding gap)
  private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT // object header
    // timestamp and type
    + KeyValue.TIMESTAMP_TYPE_SIZE
    // sequence id
    + Bytes.SIZEOF_LONG
    // references to all byte arrays: row, family, qualifier, value, tags
    + 5 * ClassSize.REFERENCE);

  // The following fields are backed by individual byte arrays
  private final byte[] row;
  private final int rOffset;
  private final int rLength;
  private final byte[] family;
  private final int fOffset;
  private final int fLength;
  private final byte[] qualifier;
  private final int qOffset;
  private final int qLength;
  private final byte[] value;
  private final int vOffset;
  private final int vLength;
  private final byte[] tags;  // A byte array, rather than an array of org.apache.hadoop.hbase.Tag
  private final int tagsOffset;
  private final int tagsLength;

  // Other fields
  private long timestamp;
  private final byte type;  // A byte, rather than org.apache.hadoop.hbase.KeyValue.Type
  private long seqId;

  public IndividualBytesFieldCell(byte[] row, byte[] family, byte[] qualifier, long timestamp,
      KeyValue.Type type, long seqId, byte[] value, byte[] tags) {
    this(row, 0, ArrayUtils.getLength(row),
            family, 0, ArrayUtils.getLength(family),
            qualifier, 0, ArrayUtils.getLength(qualifier),
            timestamp, type, seqId,
            value, 0, ArrayUtils.getLength(value),
            tags, 0, ArrayUtils.getLength(tags));
  }

  public IndividualBytesFieldCell(byte[] row, int rOffset, int rLength, byte[] family, int fOffset,
      int fLength, byte[] qualifier, int qOffset, int qLength, long timestamp, KeyValue.Type type,
      long seqId, byte[] value, int vOffset, int vLength, byte[] tags, int tagsOffset,
      int tagsLength) {
    // Check row, family, qualifier and value
    KeyValue.checkParameters(row, rLength,     // row and row length
                             family, fLength,  // family and family length
                             qLength,          // qualifier length
                             vLength);         // value length

    // Check timestamp
    if (timestamp < 0) {
      throw new IllegalArgumentException("Timestamp cannot be negative. ts=" + timestamp);
    }

    // Check tags
    RawCell.checkForTagsLength(tagsLength);
    checkArrayBounds(row, rOffset, rLength);
    checkArrayBounds(family, fOffset, fLength);
    checkArrayBounds(qualifier, qOffset, qLength);
    checkArrayBounds(value, vOffset, vLength);
    checkArrayBounds(tags, tagsOffset, tagsLength);
    // No local copy is made, but reference to the input directly
    this.row        = row;
    this.rOffset    = rOffset;
    this.rLength    = rLength;
    this.family     = family;
    this.fOffset    = fOffset;
    this.fLength    = fLength;
    this.qualifier  = qualifier;
    this.qOffset    = qOffset;
    this.qLength    = qLength;
    this.value      = value;
    this.vOffset    = vOffset;
    this.vLength    = vLength;
    this.tags       = tags;
    this.tagsOffset = tagsOffset;
    this.tagsLength = tagsLength;

    // Set others
    this.timestamp  = timestamp;
    this.type       = type.getCode();
    this.seqId      = seqId;
  }

  private void checkArrayBounds(byte[] bytes, int offset, int length) {
    if (offset < 0 || length < 0) {
      throw new IllegalArgumentException("Negative number! offset=" + offset + "and length="
        + length);
    }
    if (bytes == null && (offset != 0 || length != 0)) {
      throw new IllegalArgumentException("Null bytes array but offset=" + offset + "and length="
        + length);
    }
    if (bytes != null && bytes.length < offset + length) {
      throw new IllegalArgumentException("Out of bounds! bytes.length=" + bytes.length
        + ", offset=" + offset + ", length=" + length);
    }
  }

  private long heapOverhead() {
    return FIXED_OVERHEAD
           + ClassSize.ARRAY                               // row      , can not be null
           + ((family    == null) ? 0 : ClassSize.ARRAY)   // family   , can be null
           + ((qualifier == null) ? 0 : ClassSize.ARRAY)   // qualifier, can be null
           + ((value     == null) ? 0 : ClassSize.ARRAY)   // value    , can be null
           + ((tags      == null) ? 0 : ClassSize.ARRAY);  // tags     , can be null
  }

  /**
   * Implement Cell interface
   */
  // 1) Row
  @Override
  public byte[] getRowArray() {
    // If row is null, the constructor will reject it, by {@link KeyValue#checkParameters()},
    // so it is safe to return row without checking.
    return row;
  }

  @Override
  public int getRowOffset() {
    return rOffset;
  }

  @Override
  public short getRowLength() {
    // If row is null or rLength is invalid, the constructor will reject it, by
    // {@link KeyValue#checkParameters()}, so it is safe to call rLength and make the type
    // conversion.
    return (short)(rLength);
  }

  // 2) Family
  @Override
  public byte[] getFamilyArray() {
    // Family could be null
    return (family == null) ? HConstants.EMPTY_BYTE_ARRAY : family;
  }

  @Override
  public int getFamilyOffset() {
    return fOffset;
  }

  @Override
  public byte getFamilyLength() {
    // If fLength is invalid, the constructor will reject it, by {@link KeyValue#checkParameters()},
    // so it is safe to make the type conversion.
    return (byte)(fLength);
  }

  // 3) Qualifier
  @Override
  public byte[] getQualifierArray() {
    // Qualifier could be null
    return (qualifier == null) ? HConstants.EMPTY_BYTE_ARRAY : qualifier;
  }

  @Override
  public int getQualifierOffset() {
    return qOffset;
  }

  @Override
  public int getQualifierLength() {
    return qLength;
  }

  // 4) Timestamp
  @Override
  public long getTimestamp() {
    return timestamp;
  }

  //5) Type
  @Override
  public byte getTypeByte() {
    return type;
  }

  //6) Sequence id
  @Override
  public long getSequenceId() {
    return seqId;
  }

  //7) Value
  @Override
  public byte[] getValueArray() {
    // Value could be null
    return (value == null) ? HConstants.EMPTY_BYTE_ARRAY : value;
  }

  @Override
  public int getValueOffset() {
    return vOffset;
  }

  @Override
  public int getValueLength() {
    return vLength;
  }

  // 8) Tags
  @Override
  public byte[] getTagsArray() {
    // Tags can could null
    return (tags == null) ? HConstants.EMPTY_BYTE_ARRAY : tags;
  }

  @Override
  public int getTagsOffset() {
    return tagsOffset;
  }

  @Override
  public int getTagsLength() {
    return tagsLength;
  }

  /**
   * Implement HeapSize interface
   */
  @Override
  public long heapSize() {
    // Size of array headers are already included into overhead, so do not need to include it for
    // each byte array
    return   heapOverhead()                         // overhead, with array headers included
           + ClassSize.align(getRowLength())        // row
           + ClassSize.align(getFamilyLength())     // family
           + ClassSize.align(getQualifierLength())  // qualifier
           + ClassSize.align(getValueLength())      // value
           + ClassSize.align(getTagsLength());      // tags
  }

  /**
   * Implement Cloneable interface
   */
  @Override
  public Object clone() throws CloneNotSupportedException {
    return super.clone();  // only a shadow copy
  }

  @Override
  public void setSequenceId(long seqId) {
    if (seqId < 0) {
      throw new IllegalArgumentException("Sequence Id cannot be negative. ts=" + seqId);
    }
    this.seqId = seqId;
  }

  @Override
  public void setTimestamp(long ts) {
    if (ts < 0) {
      throw new IllegalArgumentException("Timestamp cannot be negative. ts=" + ts);
    }
    this.timestamp = ts;
  }

  @Override
  public void setTimestamp(byte[] ts) {
    setTimestamp(Bytes.toLong(ts, 0));
  }

  @Override
  public String toString() {
    return CellUtil.toString(this, true);
  }
}


text:
#import "PNReachability.h"
#import "PubNub+CorePrivate.h"
#import "PNConfiguration.h"
#import "PNLogMacro.h"
#import "PubNub.h"

NS_ASSUME_NONNULL_BEGIN

#pragma mark - Protected interface declaration

@interface PNReachability ()

#pragma mark - Information

/**
 @brief  Reference on client which created this reachability helper instance and will be used to
         call \b time API for \c ping requests.

 @since 4.0
 */
@property (nonatomic, weak) PubNub *client;

/**
 @brief  Stores reference on queue which is used to serialize access to shared reachability helper
         resources.

 @since 4.0
 */
@property (nonatomic, strong) dispatch_queue_t resourceAccessQueue;

/**
 @brief  Stores whether remote service ping active at this moment or not.

 @since 4.0
 */
@property (nonatomic, assign, getter = pingingRemoteService) BOOL pingRemoteService;

/**
 @brief  Stores reference on copy of block which should be called every time when \b ping API
         receives response from \b PubNub network or network sub-system.

 @since 4.0
 */
@property (nonatomic, copy) void(^pingCompleteBlock)(BOOL pingSuccessful);

/**
 @brief  Stores reference on reachability monitor used to track state of network connection.

 @since 4.0
 */
@property (nonatomic, assign) BOOL reachable;

#pragma mark - Initialization and Configuration

/**
 @brief  Initialize reachability helper which will allow to identify current \b PubNub network state.

 @param client Reference on \b PubNub client for which this helper has been created.
 @param block  Reference on block which is called by helper to inform about current ping round
               results.

 @return Initialized and ready to use reachability helper instance.

 @since 4.0
 */
- (instancetype)initForClient:(PubNub *)client withPingStatus:(void(^)(BOOL pingSuccessful))block;

#pragma mark - Handlers

/**
 @brief  Process service response.
 @note   In case if there is no response object or it's content malformed reachability will be set
         to 'not available'.

 @param result Time API calling result object.
 */
- (void)handleServicePingResult:(PNTimeResult *)result;

#pragma mark -

@end

NS_ASSUME_NONNULL_END

#pragma mark - Interface implementation

@implementation PNReachability

@synthesize pingRemoteService = _pingRemoteService;

#pragma mark - Initialization and Configuration

+ (instancetype)reachabilityForClient:(PubNub *)client withPingStatus:(void (^)(BOOL))block {

    return [[self alloc] initForClient:client withPingStatus:block];
}

- (instancetype)initForClient:(PubNub *)client withPingStatus:(void(^)(BOOL pingSuccessful))block {

    // Check whether initialization was successful or not.
    if ((self = [super init])) {

        _client = client;
        [_client.logger enableLogLevel:PNReachabilityLogLevel];
        _pingCompleteBlock = [block copy];
        _resourceAccessQueue = dispatch_queue_create("com.pubnub.reachability",
                                                     DISPATCH_QUEUE_CONCURRENT);
        _reachable = YES;
    }

    return self;
}

- (BOOL)pingingRemoteService {

    __block BOOL pingingRemoteService = NO;
    dispatch_sync(self.resourceAccessQueue, ^{ pingingRemoteService = self->_pingRemoteService; });

    return pingingRemoteService;
}

- (void)setPingRemoteService:(BOOL)pingRemoteService {

    dispatch_barrier_async(self.resourceAccessQueue, ^{ self->_pingRemoteService = pingRemoteService; });
}

#pragma mark - Service ping

- (void)startServicePing {

    if (!self.pingingRemoteService) {

        self.pingRemoteService = YES;
        // Try to request 'time' API to ensure what network really available.
        __weak __typeof(self) weakSelf = self;
        [self.client timeWithCompletion:^(PNTimeResult *result, __unused PNErrorStatus *status) {

            [weakSelf handleServicePingResult:result];
        }];
    }
}

- (void)stopServicePing {

    self.pingRemoteService = NO;
}

#pragma mark - Handlers

- (void)handleServicePingResult:(PNTimeResult *)result {

    BOOL successfulPing = (result.data != nil);
    if (self.reachable && !successfulPing) {

        DDLogReachability(self.client.logger, @"<PubNub::Reachability> Connection went down.");
    }
    if (!self.reachable && successfulPing) {

        DDLogReachability(self.client.logger, @"<PubNub::Reachability> Connection restored.");
    }
    if (self.pingCompleteBlock) { self.pingCompleteBlock(successfulPing); }
    if (self.pingingRemoteService) {

        NSTimeInterval delay = ((self.reachable && !successfulPing) ? 1.f : 10.0f);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)),
                       dispatch_get_main_queue(), ^{

           self.pingRemoteService = NO;
           [self startServicePing];
       });
    }
    self.reachable = successfulPing;
}

#pragma mark -

@end


text:
Paperclip.interpolates :safe_filename do |attachment, style|
  filename(attachment, style).tr("#", "-")
end

Paperclip.interpolates :rails_relative_url_root do |_, _|
  ENV["RAILS_RELATIVE_URL_ROOT"] || ""
end

# XLS files created by the spreadsheet gem have problems with their filetypes
# https://github.com/zdavatz/spreadsheet/issues/97
Paperclip.options[:content_type_mappings] = {
  xls: "CDF V2 Document, No summary info",
}

class PaperclipSettings

  def self.config
    Settings.paperclip.to_hash
  end

end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>GNUtoMS — CMake 3.8.2 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="HAS_CXX" href="HAS_CXX.html" />
    <link rel="prev" title="GENERATOR_FILE_NAME" href="GENERATOR_FILE_NAME.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.8.2 Documentation »

cmake-properties(7) »

GNUtoMS¶

Convert GNU import library (.dll.a) to MS format (.lib).

When linking a shared library or executable that exports symbols using
GNU tools on Windows (MinGW/MSYS) with Visual Studio installed convert
the import library (.dll.a) from GNU to MS format (.lib).  Both import
libraries will be installed by install(TARGETS) and exported by
install(EXPORT) and export() to be linked by applications with either
GNU- or MS-compatible tools.

If the variable CMAKE_GNUtoMS is set when a target is created its
value is used to initialize this property.  The variable must be set
prior to the first command that enables a language such as project()
or enable_language().  CMake provides the variable as an option to the
user automatically when configuring on Windows with GNU tools.

Previous topic

GENERATOR_FILE_NAME

Next topic

HAS_CXX

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.8.2 Documentation »

cmake-properties(7) »

        © Copyright 2000-2017 Kitware, Inc. and Contributors.
      Created using Sphinx 1.5.2.


text:
namespace boost{
namespace math{

// Recurrance relation for legendre P and Q polynomials:
template <class T1, class T2, class T3>
inline typename tools::promote_args<T1, T2, T3>::type
   legendre_next(unsigned l, T1 x, T2 Pl, T3 Plm1)
{
   typedef typename tools::promote_args<T1, T2, T3>::type result_type;
   return ((2 * l + 1) * result_type(x) * result_type(Pl) - l * result_type(Plm1)) / (l + 1);
}

namespace detail{

// Implement Legendre P and Q polynomials via recurrance:
template <class T, class Policy>
T legendre_imp(unsigned l, T x, const Policy& pol, bool second = false)
{
   static const char* function = "boost::math::legrendre_p<%1%>(unsigned, %1%)";
   // Error handling:
   if((x < -1) || (x > 1))
      return policies::raise_domain_error<T>(
         function,
         "The Legendre Polynomial is defined for"
         " -1 <= x <= 1, but got x = %1%.", x, pol);

   T p0, p1;
   if(second)
   {
      // A solution of the second kind (Q):
      p0 = (boost::math::log1p(x, pol) - boost::math::log1p(-x, pol)) / 2;
      p1 = x * p0 - 1;
   }
   else
   {
      // A solution of the first kind (P):
      p0 = 1;
      p1 = x;
   }
   if(l == 0)
      return p0;

   unsigned n = 1;

   while(n < l)
   {
      std::swap(p0, p1);
      p1 = boost::math::legendre_next(n, x, p0, p1);
      ++n;
   }
   return p1;
}

} // namespace detail

template <class T, class Policy>
inline typename boost::enable_if_c<policies::is_policy<Policy>::value, typename tools::promote_args<T>::type>::type
   legendre_p(int l, T x, const Policy& pol)
{
   typedef typename tools::promote_args<T>::type result_type;
   typedef typename policies::evaluation<result_type, Policy>::type value_type;
   static const char* function = "boost::math::legendre_p<%1%>(unsigned, %1%)";
   if(l < 0)
      return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_imp(-l-1, static_cast<value_type>(x), pol, false), function);
   return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_imp(l, static_cast<value_type>(x), pol, false), function);
}

template <class T>
inline typename tools::promote_args<T>::type
   legendre_p(int l, T x)
{
   return boost::math::legendre_p(l, x, policies::policy<>());
}

template <class T, class Policy>
inline typename boost::enable_if_c<policies::is_policy<Policy>::value, typename tools::promote_args<T>::type>::type
   legendre_q(unsigned l, T x, const Policy& pol)
{
   typedef typename tools::promote_args<T>::type result_type;
   typedef typename policies::evaluation<result_type, Policy>::type value_type;
   return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_imp(l, static_cast<value_type>(x), pol, true), "boost::math::legendre_q<%1%>(unsigned, %1%)");
}

template <class T>
inline typename tools::promote_args<T>::type
   legendre_q(unsigned l, T x)
{
   return boost::math::legendre_q(l, x, policies::policy<>());
}

// Recurrence for associated polynomials:
template <class T1, class T2, class T3>
inline typename tools::promote_args<T1, T2, T3>::type
   legendre_next(unsigned l, unsigned m, T1 x, T2 Pl, T3 Plm1)
{
   typedef typename tools::promote_args<T1, T2, T3>::type result_type;
   return ((2 * l + 1) * result_type(x) * result_type(Pl) - (l + m) * result_type(Plm1)) / (l + 1 - m);
}

namespace detail{
// Legendre P associated polynomial:
template <class T, class Policy>
T legendre_p_imp(int l, int m, T x, T sin_theta_power, const Policy& pol)
{
   // Error handling:
   if((x < -1) || (x > 1))
      return policies::raise_domain_error<T>(
      "boost::math::legendre_p<%1%>(int, int, %1%)",
         "The associated Legendre Polynomial is defined for"
         " -1 <= x <= 1, but got x = %1%.", x, pol);
   // Handle negative arguments first:
   if(l < 0)
      return legendre_p_imp(-l-1, m, x, sin_theta_power, pol);
   if(m < 0)
   {
      int sign = (m&1) ? -1 : 1;
      return sign * boost::math::tgamma_ratio(static_cast<T>(l+m+1), static_cast<T>(l+1-m), pol) * legendre_p_imp(l, -m, x, sin_theta_power, pol);
   }
   // Special cases:
   if(m > l)
      return 0;
   if(m == 0)
      return boost::math::legendre_p(l, x, pol);

   T p0 = boost::math::double_factorial<T>(2 * m - 1, pol) * sin_theta_power;

   if(m&1)
      p0 *= -1;
   if(m == l)
      return p0;

   T p1 = x * (2 * m + 1) * p0;

   int n = m + 1;

   while(n < l)
   {
      std::swap(p0, p1);
      p1 = boost::math::legendre_next(n, m, x, p0, p1);
      ++n;
   }
   return p1;
}

template <class T, class Policy>
inline T legendre_p_imp(int l, int m, T x, const Policy& pol)
{
   BOOST_MATH_STD_USING
   // TODO: we really could use that mythical "pow1p" function here:
   return legendre_p_imp(l, m, x, static_cast<T>(pow(1 - x*x, T(abs(m))/2)), pol);
}

}

template <class T, class Policy>
inline typename tools::promote_args<T>::type
   legendre_p(int l, int m, T x, const Policy& pol)
{
   typedef typename tools::promote_args<T>::type result_type;
   typedef typename policies::evaluation<result_type, Policy>::type value_type;
   return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_p_imp(l, m, static_cast<value_type>(x), pol), "bost::math::legendre_p<%1%>(int, int, %1%)");
}

template <class T>
inline typename tools::promote_args<T>::type
   legendre_p(int l, int m, T x)
{
   return boost::math::legendre_p(l, m, x, policies::policy<>());
}

} // namespace math
} // namespace boost

#endif // BOOST_MATH_SPECIAL_LEGENDRE_HPP


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Interfaz;

import java.awt.Color;

/**
 *
 * @author Sergio
 */
public class MenuBuscar extends javax.swing.JFrame {

    /**
     * Creates new form MenuBuscar
     */
    public MenuBuscar() {
        initComponents();
        this.getContentPane().setBackground(Color.white);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 2, true));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Buscar:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Por");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 497, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(38, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(41, 41, 41)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(69, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(50, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MenuBuscar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MenuBuscar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MenuBuscar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MenuBuscar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MenuBuscar().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}


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

using Microsoft.Azure.Commands.Automation.Model;
using Microsoft.Azure.Commands.Automation.Properties;
using System;
using System.Collections;
using System.Globalization;
using System.Management.Automation;
using System.Security.Permissions;

namespace Microsoft.Azure.Commands.Automation.Cmdlet
{
    /// <summary>
    /// starts azure automation compilation job
    /// </summary>
    [Cmdlet("Start", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "AutomationDscCompilationJob", SupportsShouldProcess = true)]
    [OutputType(typeof(CompilationJob))]
    public class StartAzureAutomationDscCompilationJob : AzureAutomationBaseCmdlet
    {

        /// <summary>
        /// Gets or sets the configuration name.
        /// </summary>
        [Parameter(Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The configuration name.")]
        [Alias("Name")]
        public string ConfigurationName { get; set; }

        /// <summary>
        /// Gets or sets the configuration parameters.
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, HelpMessage = "The compilation job parameters.")]
        public IDictionary Parameters { get; set; }

        /// <summary>
        /// Gets or sets the configuration data.
        /// </summary>
        [Parameter(Mandatory = false, HelpMessage = "The compilation job configuration data.")]
        public IDictionary ConfigurationData { get; set; }

        /// <summary>
        /// Gets or sets switch parameter to confirm building a new build version of the NodeConfiguration.
        /// </summary>
        [Parameter(Mandatory = false, HelpMessage = "Creates a new Node Configuration build version.")]
        public SwitchParameter IncrementNodeConfigurationBuild;

        /// <summary>
        /// Execute this cmdlet.
        /// </summary>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        protected override void AutomationProcessRecord()
        {
            if (ShouldProcess(ConfigurationName, VerbsLifecycle.Start))
            {
                CompilationJob job = null;

                if (this.Parameters != null && this.Parameters.Contains("ConfigurationData"))
                {
                    throw new ArgumentException(string.Format(
                        CultureInfo.CurrentCulture, Resources.ConfigurationDataShouldNotBeInJobParameters,
                        "-ConfigurationData"));
                }

                job = this.AutomationClient.StartCompilationJob(this.ResourceGroupName,
                    this.AutomationAccountName,
                    this.ConfigurationName,
                    this.Parameters,
                    this.ConfigurationData,
                    this.IncrementNodeConfigurationBuild.IsPresent);

                this.WriteObject(job);
            }
        }
    }
}


text:
<?php
require_once 'common.php';

$contactRepository = new \App\Repository\ContactRepository($db);
$contactService = new \App\Service\ContactService($contactRepository);
$contactHttpHandler = new \App\Http\ContactHttpHandler($template, $binder);
$contactHttpHandler->ListAll($contactService, $_GET);


text:
using System;
using System.Runtime.Serialization;
using PokerLeagueManager.Common.DTO.Infrastructure;

namespace PokerLeagueManager.Common.DTO.DataTransferObjects.Lookups
{
    public class LookupGamePlayersDto : BaseDataTransferObject
    {
        [DataMember]
        public Guid GameId { get; set; }

        [DataMember]
        public string PlayerName { get; set; }

        [DataMember]
        public int Placing { get; set; }

        [DataMember]
        public int Winnings { get; set; }

        [DataMember]
        public int PayIn { get; set; }
    }
}


text:
package com.roselism.start4result_demo;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.roselism.start4result.RoselismActivity;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;

public class JavaActivity extends RoselismActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        Button kotlinButton = (Button) findViewById(R.id.kotlin);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(JavaActivity.this, TargetActivity.class);
                startActivityForResult(intent, Constants.Main.REQUEST_CODE_4_DEMO, new Function2<Intent, Integer, Unit>() {
                    @Override
                    public Unit invoke(Intent intent, Integer integer) {
                        // integer is result code
                        Toast.makeText(JavaActivity.this, intent.getStringExtra(Constants.Target.ARG_DEMO), Toast.LENGTH_SHORT).show();
                        return Unit.INSTANCE;
                    }
                });
            }
        });

        kotlinButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KotlinActivity.Companion.start(JavaActivity.this);
                finish();
            }
        });
    }
}


text:
[Building HandsUp: an OS real-time Q&A App using GraphQL and React](https://medium.com/@gerard.sans/building-handsup-an-os-real-time-voting-app-using-graphql-and-react-b2b7dcd0e136)

## HandsUp 🙌
Make your events more interactive allowing attendees to participate by adding questions and voting using their phone or laptop.

Organisers and speakers can use it to answer questions and run Q&A or panels sessions.

## Technology stack

This application integrates the following technologies:
- [Auth0](http://auth0.com) to authenticate users using their social profiles (Google, Twitter)
- [Apollo Client](http://dev.apollodata.com) to communicate with GraphQL Server
- [graphcool](http://graph.cool) providing the GraphQL Server

## Usage

Log in using your social account to be able to add new questions. In order to vote click on the heart button besides each question.

## Development

If you have any questions feel free to ping me on [@gerardsans](http://twitter.com/gerardsans).

### Install

First, clone the repo via git:

```bash
$ git clone https://github.com/gsans/handsup-react.git
```

And then install dependencies:

```bash
$ cd handsup-react && yarn
```

### Run
```bash
$ yarn run dev
```

> Note: requires a node version >=6.x

## Getting Started

In order to run this project you need to create the data model (schema) below using [graphcool](http://graph.cool) console online and setup Auth0.

### graphcool - HandsUp Schema

This is the schema used

```graphql
type Question @model {
  id: ID! @isUnique
  body: String!
  votes: [Vote!]! @relation(name: "VoteOnQuestion")
  user: User @relation(name: "UserOnQuestion")
  createdAt: DateTime!
  updatedAt: DateTime!
}

type Vote @model {
  id: ID! @isUnique
  question: Question @relation(name: "VoteOnQuestion")
  createdAt: DateTime!
  updatedAt: DateTime!
}

type User @model {
  auth0UserId: String
  id: ID! @isUnique
  name: String
  username: String
  pictureUrl: String
  questions: [Question!]! @relation(name: "UserOnQuestion")
  role: USER_ROLE
  createdAt: DateTime!
  updatedAt: DateTime!
}

enum USER_ROLE {
  Admin
  Organiser
  Moderator
  User
}
```

You can read the following blog as reference for an example as how you would create a schema from scratch
- [Setting up a GraphQL backend in 5 minutes](https://www.graph.cool/docs/tutorials/quickstart-1-thaeghi8ro)

### Auth0 + graphcool setup

In order to use Auth0 you need to do few steps. You can find some assistance by reading the articles below.

- [User Authentication with Auth0 for React and Apollo](https://www.graph.cool/docs/tutorials/react-apollo-auth0-pheiph4ooj)
- [Auth0 - React Getting Started](https://auth0.com/docs/quickstart/spa/react/00-getting-started)
- [Connect your app to Google](https://auth0.com/docs/connections/social/google)
- [Connect your app to Twitter](https://auth0.com/docs/connections/social/twitter)

## License
MIT © [Gerard Sans](https://github.com/gsans)


text:
require File.join(File.dirname(__FILE__), 'spec_helper')

describe 'more_like_this' do
  before :all do
    Sunspot.remove_all
    @posts = [
      Post.new(:body => "one two three", :tags => %w(ruby sunspot rsolr)),
      Post.new(:body => "four five six", :tags => %w(ruby solr lucene)),
      Post.new(:body => "two three four", :tags => %w(python sqlalchemy)),
      Post.new(:body => "three four five", :tags => %w(ruby sunspot mat)),
      Post.new(:body => "six seven eight", :tags => %w(bogus airplane))
    ]
    Sunspot.index!(@posts)
  end

  it 'should return results for all MLT fields' do
    Sunspot.more_like_this(@posts.first).results.to_set.should == @posts[1..3].to_set
  end

  it 'should return results for specified text field' do
    Sunspot.more_like_this(@posts.first) do
      fields :body
    end.results.to_set.should == @posts[2..3].to_set
  end

  it 'should return empty result set if no results' do
    Sunspot.more_like_this(@posts.last) do
      with(:title, 'bogus')
    end.results.should == []
  end

  describe 'when non-indexed object searched' do
    before(:each) { @mlt = Sunspot.more_like_this(Post.new) }

    it 'should return empty result set' do
      @mlt.results.should == []
    end

    it 'shoult return a total of 0' do
      @mlt.total.should == 0
    end
  end
end


text:
from django.shortcuts import get_object_or_404
from django.db import transaction
from rest_framework import viewsets
from rest_framework import status as RESTstatus
from rest_framework.response import Response as RESTResponse
from mediaviewer.api.serializers import (FileSerializer,
                                         MovieFileSerializer,
                                         )
from mediaviewer.models.file import File
from mediaviewer.log import log

class FileViewSet(viewsets.ModelViewSet):
    queryset = File.objects.all()
    serializer_class = FileSerializer

    def get_queryset(self):
        pathid = self.request.query_params.get('pathid', None)
        queryset = self.queryset
        log.debug('Returning File objects')
        if pathid:
            queryset = queryset.filter(path__id=pathid)
            log.debug('Filtering file objects by pathid = %s' % pathid)
        return queryset

    def retrieve(self, request, pk=None):
        log.debug('Attempting to find file with id = %s' % pk)
        queryset = self.queryset
        obj = get_object_or_404(queryset, pk=pk)
        serializer = self.serializer_class(obj)
        return RESTResponse(serializer.data)

    def validate_path(self, serializer):
        pass

    def create_file_obj(self, data):
        serializer = self.serializer_class(data=data)
        if serializer.is_valid():
            serializer.save()
            self.validate_path(serializer)
        else:
            raise Exception('Invalid serializer')

        newFile = serializer.instance
        path = newFile.path
        if not path.lastCreatedFileDate or path.lastCreatedFileDate < newFile.datecreated:
            path.lastCreatedFileDate = newFile.datecreated
            path.save()
        log.info('New file record created for %s' % newFile.filename)
        return serializer

    def create(self, request):
        data = request.data

        try:
            with transaction.atomic():
                serializer = self.create_file_obj(data)
        except Exception, e:
            log.error(str(e))
            log.error('File creation failed!')
            return RESTResponse(status=RESTstatus.HTTP_400_BAD_REQUEST)

        headers = self.get_success_headers(serializer.data)
        return RESTResponse(serializer.data,
                            status=RESTstatus.HTTP_201_CREATED,
                            headers=headers)

    # Implements PUT
    def update(self, request, pk=None):
        data = request.data
        instance = get_object_or_404(self.queryset, pk=pk)

        serializer = self.serializer_class(instance, data=data)
        if serializer.is_valid():
            serializer.save()
            headers = self.get_success_headers(serializer.data)

            return RESTResponse(serializer.data,
                                status=RESTstatus.HTTP_200_OK,
                                headers=headers)
        else:
            return RESTResponse(status=RESTstatus.HTTP_400_BAD_REQUEST)

class TvFileViewSet(FileViewSet):
    queryset = File.objects.filter(path__is_movie=False)

    def validate_path(self, serializer):
        if serializer.instance.path.is_movie:
            raise Exception('Attempting to use a movie path with a tv obj')

    def create(self, request):
        try:
            return super(TvFileViewSet, self).create(request)
        except Exception, e:
            log.error(str(e))
            log.error('TvFile creation failed!')

            return RESTResponse(None,
                                status=RESTstatus.HTTP_500_INTERNAL_SERVER_ERROR,
                                headers=None)

class MovieFileViewSet(FileViewSet):
    queryset = File.objects.filter(path__is_movie=True)
    serializer_class = MovieFileSerializer

    def validate_path(self, serializer):
        if not serializer.instance.path.is_movie:
            raise Exception('Attempting to use a tv path with a movie obj')

    def create(self, request):
        try:
            return super(MovieFileViewSet, self).create(request)
        except Exception, e:
            log.error(str(e))
            log.error('MovieFile creation failed!')

            return RESTResponse(None,
                                status=RESTstatus.HTTP_500_INTERNAL_SERVER_ERROR,
                                headers=None)

class UnstreamableFileViewSet(FileViewSet):
    queryset = File.objects.filter(streamable=False)
    serializer_class = FileSerializer


text:
#import <Availability2.h>

#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_3_2

#import "UIKit-Structs.h"
#import <Foundation/NSObject.h>

@class DOMNode, UIView;
@protocol UIFormPeripheral;

@interface UIPeripheralTransition : NSObject {
	DOMNode* _nextNode;
	UIView<UIFormPeripheral>* _nextPeripheral;
}
@property(retain, nonatomic) DOMNode* _nextNode;
@property(retain, nonatomic) UIView<UIFormPeripheral>* _nextPeripheral;
-(id)initWithNode:(id)node withPeripheral:(id)peripheral;
-(void)dealloc;
-(id)completeWithCurrentPeripheral:(id)currentPeripheral;
-(CGRect)frame;
@end

#endif


text:
package com.rosaloves.bitlyj;

import org.junit.Assert;
import org.junit.Test;

/**
 * UrlTest
 *
 * $Id$
 *
 * @author clewis Jul 26, 2010
 *
 */
public class UrlTest {

	private Url url = new Url("http://nonsen.se", "global", "user", "http://foo.ly/user", "http://longdomain.com/long/path/");

	@Test
	public void expectedUserHash() {
		Assert.assertEquals("user", url.getUserHash());
	}

	@Test
	public void expectedShortUrl() {
		Assert.assertEquals("http://foo.ly/user", url.getShortUrl());
	}

	@Test
	public void resolvedShortUrl() {
		url = new Url("http://foo.ly/", "global", "user", "", "http://longdomain.com/long/path/");
		Assert.assertEquals("http://foo.ly/user", url.getShortUrl());
	}

}


text:
extern VALUE rb_mAMF;
extern VALUE rb_mAMF_C;

void Init_ramf_core();


text:
class StubDecoratedReader : public paddle::framework::DecoratedReader {
 public:
  explicit StubDecoratedReader(const std::shared_ptr<ReaderBase> &reader)
      : DecoratedReader(reader) {}

  void ReadNextImpl(std::vector<paddle::framework::LoDTensor> *out) override {}
};

class StubRootReader : public paddle::framework::ReaderBase {
 public:
  explicit StubRootReader(
      const std::vector<paddle::framework::DDim> &dims,
      const std::vector<paddle::framework::proto::VarType::Type> &var_types,
      const std::vector<bool> &need_check_feed)
      : paddle::framework::ReaderBase(dims, var_types, need_check_feed) {}
  void ReadNextImpl(std::vector<paddle::framework::LoDTensor> *out) override {}
};

TEST(READER, decorate_chain) {
  paddle::framework::proto::VarType::Type dtype =
      paddle::framework::proto::VarType::FP32;
  paddle::framework::DDim dim = paddle::framework::make_ddim({5, 7});
  std::vector<paddle::framework::DDim> init_dims(4, dim);
  std::vector<paddle::framework::proto::VarType::Type> init_types(4, dtype);
  std::vector<bool> init_need_check(4, true);
  auto root =
      std::make_shared<StubRootReader>(init_dims, init_types, init_need_check);
  auto end_point1 =
      paddle::framework::MakeDecoratedReader<StubDecoratedReader>(root);
  auto end_point2 =
      paddle::framework::MakeDecoratedReader<StubDecoratedReader>(root);

  {
    auto endpoints = root->GetEndPoints();
    ASSERT_EQ(endpoints.size(), 2U);
    ASSERT_NE(endpoints.count(end_point1.get()), 0UL);
    ASSERT_NE(endpoints.count(end_point2.get()), 0UL);
  }

  {
    auto end_point3 =
        paddle::framework::MakeDecoratedReader<StubDecoratedReader>(root);
    ASSERT_EQ(root->GetEndPoints().size(), 3U);
  }
  { ASSERT_EQ(root->GetEndPoints().size(), 2U); }

  {
    ASSERT_EQ(end_point1->Shapes(), init_dims);
    ASSERT_EQ(end_point1->VarTypes(), init_types);
    ASSERT_EQ(end_point1->NeedCheckFeed(), init_need_check);
  }
}


text:
package com.ikasoa.rpc.handler;

/**
 * 客户端调用拦截器接口
 *
 * @author Larry
 * @version 0.1
 */
public interface ClientInvocationHandler {

	/**
	 * 开始
	 *
	 * @param context
	 *            上下文
	 * @return ClientInvocationContext
	 */
	ClientInvocationContext before(ClientInvocationContext context);

	/**
	 * 执行前
	 *
	 * @param context
	 *            上下文
	 * @return ClientInvocationContext
	 */
	ClientInvocationContext invoke(ClientInvocationContext context);

	/**
	 * 正常结束
	 *
	 * @param context
	 *            上下文
	 */
	void after(ClientInvocationContext context);

	/**
	 * 异常结束
	 *
	 * @param context
	 *            上下文
	 * @param throwable
	 *            异常对象
	 */
	void exception(ClientInvocationContext context, Throwable throwable);

}


text:
''' signed cookie based sessions '''
''' tested only for simple session key values (implementation/test for nested structures soon) '''

__all__ = ['sessions']

import base64
import json

def sessions(cookiename='ripple.session',
             cookiedomain = '',
             cookiepath = '/',
             expires = 24 * 60 * 60, # one day
             permanent = True,
             http_only = True,
             secure = False):
  if permanent: expires = 10 * 365 * expires # ten years of timeout :O

  def middleware(app):

    def encode(session_dict):
      return json.dumps(session_dict)

    def decode(session_string):
      return json.loads(session_string)

    def sessionapp(environ):
      session_cookie = environ['cookies'].get(cookiename, '')
      environ['session'] = session_cookie and decode(session_cookie) or {}
      session_copy = environ['session'].copy() # support for nested dicts soon
      status, headers, body = app(environ)
      if environ['session'] != session_copy:
        environ['cookies'][cookiename] = encode(environ['session'])
      return status, headers, body

    return sessionapp

  return middleware


text:
<!DOCTYPE html>
<title>Layout using slot elements</title>
<link rel="author" title="Hayato Ito" href="mailto:hayato@google.com"/>
<link rel="help" href="https://dom.spec.whatwg.org/#shadow-tree-slots">
<link rel="match" href="reference/empty.html"/>


text:
module.exports = function (five) {
  return (function () {
    function RemoteSwitch (opts) {
      if (!(this instanceof RemoteSwitch)) {
        return new RemoteSwitch(opts);
      }
      five.Board.Component.call(this, opts = five.Board.Options(opts));

      this.pins     = opts.pins;
      this.duration = opts.duration || 500;
      this.isOn     = undefined;
      this.isActive = false;
      this.queue    = [];

      this.io.pinMode(this.pins.on, this.io.MODES.OUTPUT);
      this.io.pinMode(this.pins.off, this.io.MODES.OUTPUT);
    }

    RemoteSwitch.prototype.toggle = function (turnOn) {
      if (this.isActive) {
        this.queue.push(turnOn);
        return;
      }
      this.isActive = true;
      if (typeof turnOn === 'undefined') {
        turnOn = !this.isOn;
      }
      const pin = (turnOn) ? this.pins.on : this.pins.off;
      this.io.digitalWrite(pin, 1);
      setTimeout(() => {
        this.io.digitalWrite(pin, 0);
        this.isActive = false;
        this.isOn = !!turnOn;
        if (this.queue.length) {
          this.toggle(this.queue.shift());
        }
      }, this.duration);
    };

    RemoteSwitch.prototype.on = function () {
      this.toggle(true);
    };
    RemoteSwitch.prototype.off = function () {
      this.toggle(false);
    };
    return RemoteSwitch;
  }());
};


text:
@interface SPDYStreamNode : NSObject
@end

@implementation SPDYStreamNode
{
  @public
    __strong SPDYStreamNode *next;
    __strong SPDYStreamNode *prev;
    __strong SPDYStream *stream;
    __unsafe_unretained SPDYProtocol *protocol;
    SPDYStreamId streamId;
}
@end

@interface SPDYStreamManager ()
- (void)_removeListNode:(SPDYStreamNode *)node;
@end

@implementation SPDYStreamManager
{
    SPDYStreamNode *_priorityHead[8];
    SPDYStreamNode *_priorityLast[8];
    CFMutableDictionaryRef _nodesByStreamId;
    CFMutableDictionaryRef _nodesByProtocol;
    NSUInteger _localCount;
    NSUInteger _remoteCount;
    unsigned long _mutations;
}

Boolean SPDYStreamIdEqual(const void *key1, const void *key2) {
    return (SPDYStreamId)key1 == (SPDYStreamId)key2;
}

CFHashCode SPDYStreamIdHash(const void *key) {
    return (CFHashCode)((SPDYStreamId)key);
}

CFStringRef SPDYStreamIdCopyDescription(const void *key) {
    return CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%d"), (SPDYStreamId)key);
}

- (id)init
{
    NSAssert(sizeof(void *) <= sizeof(unsigned long), @"pointer width must be <= unsigned long width");
    NSAssert(sizeof(void *) >= sizeof(SPDYStreamId), @"pointer width must be >= SPDYStreamId width");

    self = [super init];
    if (self) {
        CFDictionaryKeyCallBacks SPDYStreamIdKeyCallbacks = {
            0, NULL, NULL,
            SPDYStreamIdCopyDescription,
            SPDYStreamIdEqual,
            SPDYStreamIdHash
        };
        _nodesByStreamId = CFDictionaryCreateMutable(
            kCFAllocatorDefault, 100,
            &SPDYStreamIdKeyCallbacks,
            &kCFTypeDictionaryValueCallBacks
        );
        _nodesByProtocol = CFDictionaryCreateMutable(
            kCFAllocatorDefault, 100,
            &kCFTypeDictionaryKeyCallBacks,
            &kCFTypeDictionaryValueCallBacks
        );
        _localCount = 0;
        _remoteCount = 0;
        _mutations = 0;
    }
    return self;
}

- (void)dealloc
{
    CFRelease(_nodesByStreamId);
    CFRelease(_nodesByProtocol);
}

- (NSUInteger)count
{
    return _localCount + _remoteCount;
}

- (id)objectAtIndexedSubscript:(NSUInteger)idx
{
    SPDYStreamNode *node = (id)CFDictionaryGetValue(_nodesByStreamId, (void *)idx);
    return node ? node->stream : nil;
}

- (id)objectForKeyedSubscript:(id)key
{
    SPDYStreamNode *node = (id)CFDictionaryGetValue(_nodesByProtocol, (__bridge CFTypeRef)key);
    return node ? node->stream : nil;
}

- (SPDYStream *)nextPriorityStream
{
    SPDYStreamNode *currentNode;
    for (int priority = 0; priority < 8 && currentNode == NULL; priority++) {
        currentNode = _priorityHead[priority];
    }

    if (currentNode) {
        return currentNode->stream;
    }

    return nil;
}

- (void)addStream:(SPDYStream *)stream
{
    SPDYStreamNode *node = [[SPDYStreamNode alloc] init];
    node->stream = stream;
    node->protocol = stream.protocol;
    node->streamId = stream.streamId;
    [self _addListNode:node];
}

- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx
{
    if (obj) {
        SPDYStreamNode *node = [[SPDYStreamNode alloc] init];
        SPDYStream *stream = obj;
        node->stream = stream;
        node->protocol = stream.protocol;
        node->streamId = (SPDYStreamId)idx;

        [self _addListNode:node];
    } else {
        [self removeStreamWithStreamId:(SPDYStreamId)idx];
    }
}

- (void)_addListNode:(SPDYStreamNode *)node
{
    // Update linked list
    uint8_t priority = node->stream.priority;
    if (_priorityHead[priority] == NULL) {
        _priorityHead[priority] = node;
        _priorityLast[priority] = node;
    } else {
        _priorityLast[priority]->next = node;
        node->prev = _priorityLast[priority];
        _priorityLast[priority] = node;
    }

    // Update hash maps
    NSAssert(node->streamId != 0 || node->protocol != nil, @"cannot insert unaddressable stream");
    NSAssert(CFDictionaryGetValue(_nodesByStreamId, (void *)(uintptr_t)node->streamId) == NULL, @"cannot insert stream with duplicate streamId");
    if (node->streamId) {
        CFDictionarySetValue(_nodesByStreamId, (void *)(uintptr_t)node->streamId, (__bridge CFTypeRef)node);
    }
    if (node->protocol) {
        CFDictionarySetValue(_nodesByProtocol, (__bridge CFTypeRef)node->protocol, (__bridge CFTypeRef)node);
    }

    // Update counts
    if (node->stream.local) {
        _localCount += 1;
    } else {
        _remoteCount += 1;
    }

    _mutations += 1;
}

- (void)removeStreamWithStreamId:(SPDYStreamId)streamId
{
    SPDYStreamNode *node = (id)CFDictionaryGetValue(_nodesByStreamId, (void *)(uintptr_t)streamId);
    if (node) [self _removeListNode:node];
}

- (void)removeStreamForProtocol:(SPDYProtocol *)protocol
{
    SPDYStreamNode *node = (id)CFDictionaryGetValue(_nodesByProtocol, (__bridge CFTypeRef)protocol);
    if (node) [self _removeListNode:node];
}

- (void)_removeListNode:(SPDYStreamNode *)node
{
    // Update linked list
    uint8_t priority = node->stream.priority;
    if (node->next != NULL) node->next->prev = node->prev;
    if (node->prev != NULL) node->prev->next = node->next;
    if (_priorityHead[priority] == node) _priorityHead[priority] = node->next;
    if (_priorityLast[priority] == node) _priorityLast[priority] = node->prev;

    // Update hash maps
    if (node->streamId) {
        CFDictionaryRemoveValue(_nodesByStreamId, (void *)(uintptr_t)node->streamId);
    }
    if (node->protocol) {
        CFDictionaryRemoveValue(_nodesByProtocol, (__bridge CFTypeRef)node->protocol);
    }

    // Update counts
    if (node->stream.local) {
        _localCount -= 1;
    } else {
        _remoteCount -= 1;
    }

    _mutations += 1;
}

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len
{
    SPDYStreamNode *currentNode = (__bridge SPDYStreamNode *)((void *)state->extra[0]);
    unsigned long *priority = &(state->state);

    for (; *priority < 8 && currentNode == NULL; *priority += 1) {
        currentNode = _priorityHead[*priority];
    }

    if (currentNode == NULL) {
        return 0;
    }

    NSUInteger i;
    for (i = 0; i < len && currentNode != NULL; i++) {
        buffer[i] = currentNode->stream;
        currentNode = currentNode->next;
    }

    state->extra[0] = (unsigned long)currentNode;
    state->itemsPtr = buffer;
    state->mutationsPtr = &_mutations;
    return i;
}

- (void)removeAllStreams
{
    // Update linked list
    for (int i = 0; i < 8; i++) {
        _priorityHead[i] = NULL;
        _priorityLast[i] = NULL;
    }

    // Update hash maps
    CFDictionaryRemoveAllValues(_nodesByStreamId);
    CFDictionaryRemoveAllValues(_nodesByProtocol);

    // Update counts
    _localCount = 0;
    _remoteCount = 0;

    _mutations += 1;
}

@end


text:
package com.truphone.cascades.commands;

import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import org.junit.Assert;
import org.junit.Test;

import com.truphone.cascades.TimeoutException;
import com.truphone.cascades.replys.IReply;
import com.truphone.cascades.testutils.FakeDevice;
import com.truphone.cascades.testutils.FakeDevice.FakeDeviceListener;

/**
 * Test class.
 * @author STruscott
 *
 */
public final class TestContactsCommand {
	/**
	 * Test the Contacts (Add) command.
	 * @throws TimeoutException Thrown if the command times out
	 */
	@Test
	public void testContactsAddCommand() throws TimeoutException {
		final FakeDeviceListener response = new FakeDeviceListener() {
			@Override
			public void messageReceived(String message, PrintStream replyStream) {
				if ("contacts create forename=Some,surname=Person,mobile=+44123,".equals(message)) {
					replyStream.println(FakeDevice.OK_MESSAGE);
				} else {
					Assert.fail(message);
				}
			}
		};
		FakeDevice.DEVICE.getProcess().addListener(response);
		final SortedMap<ContactsCommand.Attribute, String> data = new TreeMap<ContactsCommand.Attribute, String>();
		data.put(ContactsCommand.Attribute.FORENAME, "Some");
		data.put(ContactsCommand.Attribute.SURNAME, "Person");
		data.put(ContactsCommand.Attribute.MOBILE, "+44123");
		final IReply reply = FakeDevice.CONN.transmit(new ContactsCommand(data), FakeDevice.DEFAULT_TIMEOUT);
		FakeDevice.DEVICE.getProcess().removeListener(response);
		Assert.assertTrue(reply.isSuccess());
	}

	/**
	 * Test the Contacts (Modify-Remove) command.
	 * @throws TimeoutException Thrown if the command times out
	 */
	@Test
	public void testContactsModifyRemoveCommand() throws TimeoutException {
		final FakeDeviceListener response = new FakeDeviceListener() {
			@Override
			public void messageReceived(String message, PrintStream replyStream) {
				if ("contacts modify Some Person forename,surname,mobile,".equals(message)) {
					replyStream.println(FakeDevice.OK_MESSAGE);
				}
			}
		};
		FakeDevice.DEVICE.getProcess().addListener(response);
		final List<ContactsCommand.Attribute> data = new LinkedList<ContactsCommand.Attribute>();
		data.add(ContactsCommand.Attribute.FORENAME);
		data.add(ContactsCommand.Attribute.SURNAME);
		data.add(ContactsCommand.Attribute.MOBILE);
		final IReply reply = FakeDevice.CONN.transmit(new ContactsCommand("Some Person", data), FakeDevice.DEFAULT_TIMEOUT);
		FakeDevice.DEVICE.getProcess().removeListener(response);
		Assert.assertTrue(reply.isSuccess());
	}

	/**
	 * Test the Contacts (Modify-Edit) command.
	 * @throws TimeoutException Thrown if the command times out
	 */
	@Test
	public void testContactsModifyEditCommand() throws TimeoutException {
		final FakeDeviceListener response = new FakeDeviceListener() {
			@Override
			public void messageReceived(String message, PrintStream replyStream) {
				if ("contacts modify Some Person forename=Somee,surname=Personn,mobile=+441234,".equals(message)) {
					replyStream.println(FakeDevice.OK_MESSAGE);
				}
			}
		};
		FakeDevice.DEVICE.getProcess().addListener(response);
		final SortedMap<ContactsCommand.Attribute, String> data = new TreeMap<ContactsCommand.Attribute, String>();
		data.put(ContactsCommand.Attribute.FORENAME, "Somee");
		data.put(ContactsCommand.Attribute.SURNAME, "Personn");
		data.put(ContactsCommand.Attribute.MOBILE, "+441234");
		final IReply reply = FakeDevice.CONN.transmit(new ContactsCommand("Some Person", data), FakeDevice.DEFAULT_TIMEOUT);
		FakeDevice.DEVICE.getProcess().removeListener(response);
		Assert.assertTrue(reply.isSuccess());
	}

	/**
	 * Test the Contacts (Delete) command.
	 * @throws TimeoutException Thrown if the command times out
	 */
	@Test
	public void testContactsDeleteCommand() throws TimeoutException {
		final FakeDeviceListener response = new FakeDeviceListener() {
			@Override
			public void messageReceived(String message, PrintStream replyStream) {
				if ("contacts delete Some Person".equals(message)) {
					replyStream.println(FakeDevice.OK_MESSAGE);
				}
			}
		};
		FakeDevice.DEVICE.getProcess().addListener(response);
		final IReply reply = FakeDevice.CONN.transmit(new ContactsCommand("Some Person"), FakeDevice.DEFAULT_TIMEOUT);
		FakeDevice.DEVICE.getProcess().removeListener(response);
		Assert.assertTrue(reply.isSuccess());
	}

	/**
	 * Test the Contacts (RemoveAll) command.
	 * @throws TimeoutException Thrown if the command times out
	 */
	@Test
	public void testContactsRemoveAllYesCommand() throws TimeoutException {
		final FakeDeviceListener response = new FakeDeviceListener() {
			@Override
			public void messageReceived(String message, PrintStream replyStream) {
				if ("contacts removeAll yesImSure".equals(message)) {
					replyStream.println(FakeDevice.OK_MESSAGE);
				}
			}
		};
		FakeDevice.DEVICE.getProcess().addListener(response);
		final IReply reply = FakeDevice.CONN.transmit(
				new ContactsCommand(ContactsCommand.AreYouSure.SURE_GO), FakeDevice.DEFAULT_TIMEOUT);
		FakeDevice.DEVICE.getProcess().removeListener(response);
		Assert.assertTrue(reply.isSuccess());
	}

	/**
	 * Test the Contacts (RemoveAll) command.
	 * @throws TimeoutException Thrown if the command times out
	 */
	@Test
	public void testContactsRemoveAllNoCommand() throws TimeoutException {
		final FakeDeviceListener response = new FakeDeviceListener() {
			@Override
			public void messageReceived(String message, PrintStream replyStream) {
				if ("contacts removeAll notSure".equals(message)) {
					replyStream.println(FakeDevice.OK_MESSAGE);
				}
			}
		};
		FakeDevice.DEVICE.getProcess().addListener(response);
		final IReply reply = FakeDevice.CONN.transmit(
				new ContactsCommand(ContactsCommand.AreYouSure.NOT_SURE), FakeDevice.DEFAULT_TIMEOUT);
		FakeDevice.DEVICE.getProcess().removeListener(response);
		Assert.assertTrue(reply.isSuccess());
	}
}


text:
package com.mithrilclient.updater.regex;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;

public final class InvokeVirtualInstruction extends Instruction {
	private final String methodSignature;

	public InvokeVirtualInstruction(String methodSignature, boolean capture) {
		super(Opcodes.INVOKEVIRTUAL, capture);
		this.methodSignature = methodSignature;
	}

	@Override
	public boolean matches(AbstractInsnNode instruction) {
		if (!super.matches(instruction)) return false;
		MethodInsnNode mn = (MethodInsnNode) instruction;
		return methodSignature.equals(mn.owner + "." + mn.name + ":" + mn.desc);
	}
}


text:
<?php

namespace Tests\Unit\Wye;

use PDOException;
use Stratedge\Wye\Wye;

class CommitTransactionTest extends \Tests\TestCase
{
    public function testNoTransactionThrowsException()
    {
        $this->setExpectedException(PDOException::class);
        Wye::commitTransaction();
    }

    public function testMarksTransactionCommitted()
    {
        Wye::beginTransaction();

        $transaction = Wye::currentTransaction();

        $this->assertFalse($transaction->getCommitted());

        Wye::commitTransaction();

        $this->assertTrue($transaction->getCommitted());
    }

    public function testSetsInTransactionToFalse()
    {
        $this->assertFalse(Wye::getInTransaction());

        Wye::beginTransaction();

        $this->assertTrue(Wye::getInTransaction());

        Wye::commitTransaction();

        $this->assertFalse(Wye::getInTransaction());
    }
}


text:
def lib_require(dir_name)
  Dir[Rails.root + "lib/#{dir_name}/*.rb"].each do |file|
    load file
  end
end


text:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//var index = require('./routes/index');
//var todos = require('./routes/todos');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname + '/..', 'public')));
app.use(require('connect-livereload')());

//app.use('/', index);
//app.use('/api/v1/', todos);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

var server = app.listen(3000, function() {
    var host = 'localhost';
    var port = server.address().port;
    console.log('App listening at http://%s:%s', host, port);
});

module.exports = app;


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PrivilegedMethodExample02</title>
</head>
<body>
    <script type="text/javascript">
        (function () {
            //Private variables and functions
            var name = "";

            //Constructor
            Person = function (value) {
                name = value;
            }
            //public and privileged function
            Person.prototype.getName = function () {
                return name;
            }

            Person.prototype.setName = function (value) {
                name = value;
            }

        })();

        var person1 = new Person("Nicholas");
        alert(person1.getName());
        person1.setName("Greg");
        alert(person1.getName());

        var person2 = new Person("Michael");
        alert(person1.getName());
        alert(person2.getName());

        /*
         Since the privileged method is defined on the prototype,
         all instances use that same function.

         The privileged method, being a closure,
         always holds a reference to the containing scope.
         */
    </script>
</body>
</html>


text:
#ifndef __HWDB_INDEX_MAP__
#define __HWDB_INDEX_MAP__

#include "hashtable.h"

#include "timestamp.h"

#include "linkedlist.h"

#include "sqlstmts.h"
#include "rtab.h"

typedef struct ndx {
    tstamp_t timeStamp;
    off_t byteOffset;
} Ndx;

typedef struct _f {
    char *name;
    FILE *fs;
    tstamp_t oldest;
    tstamp_t newest;
    unsigned char indexed;
} F;

F *f_init(char *filename);

int f_index(F *f, char *in, char *out);

typedef struct _t {
    int n;
    char **name;
    int  **type;
    List *files;
    pthread_mutex_t t_mutex;
} T;

FILE *t_file(T *t, tstamp_t tstamp);

void t_closefiles(T *t);

void t_extract_relevant_columns(T *t, sqlselect *select,
                                Rtab *results);

void t_extract_relevant_types(T *t, Rtab *results);

int t_lookup_colindex(T *t, char *name);

typedef struct _map {
    Hashtable *ht;
    pthread_mutex_t *m_mutex;
    char *directory;
} Map;

Map *map_new(char *directory);

void map_destroy(Map *map);

int map_create_table(Map *map, char *tablename, int ncols,
                     char **colnames, int **coltypes);

int map_update_table(Map *map, char *filename);

Rtab *map_build_results(Map *map, char *tablename, sqlselect *select);

int map_load(Map *map, char *cmd);

#endif /* __HWDB_INDEX_MAP__ */


text:
<!DOCTYPE html>

<link id="themeStyles" rel="stylesheet" href="../../../dijit/themes/claro/claro.css"/>

This is a prototype tool to assist starting a DOH test on an Android WebDriver. The goal is to automate this process into just one form submit.

To start a test:

On your Android device, download the patched WebDriver apk and start it. You will get a black screen that says WebDriver at the top.

Enter the IP of your Android device: <input type=text id="baseIP" name="baseIP" value="myandroidIP" />

Open the Network tab in the browser's debugger

Press <button type="button" id="button" data-dojo-type="dijit/form/Button" data-dojo-props='type:"button",label:"Submit"'>

</button>

Enter the number you see in the Network tab for the failed redirect (should look something like 1342108893269 for instance): <input type=text id="sessionID" name="sessionID" value="1342108893269" />

Enter the DOH mobileRunner.html URL you want to test (note the loaded plugin at the end): <input type=text id="testURL" name="testURL" value="http://mywebserver/util/doh/mobileRunner.html?test=dojox/mobile/tests/robot/module&dohPlugins=doh/plugins/remoteRobot" />

Press <button type="button" id="button2" data-dojo-type="dijit/form/Button" data-dojo-props='type:"button",label:"Submit"'>

</button>

The test should momentarily start (after ~10s) on the device (if it doesn't load after a minute, repeat the procedure; some times an unbuilt Dojo will time out while the browser is caching everything for the first time.)


text:
<?php

namespace GraphAware\Neo4j\Client\Transaction;

use GraphAware\Common\Cypher\Statement;
use GraphAware\Common\Transaction\TransactionInterface;
use GraphAware\Neo4j\Client\Exception\Neo4jException;
use GraphAware\Neo4j\Client\Stack;

class Transaction
{
    /**
     * @var \GraphAware\Common\Transaction\TransactionInterface
     */
    private $driverTransaction;

    /**
     * @var array()
     */
    protected $queue = [];

    /**
     * Transaction constructor.
     * @param \GraphAware\Common\Transaction\TransactionInterface $driverTransaction
     */
    public function __construct(TransactionInterface $driverTransaction)
    {
        $this->driverTransaction = $driverTransaction;
    }

    /**
     * Push a statement to the queue, without actually sending it
     *
     * @param string $statement
     * @param array $parameters
     * @param string|null $tag
     */
    public function push($statement, array $parameters = array(), $tag = null)
    {
        $this->queue[] = Statement::create($statement, $parameters, $tag);
    }

    /**
     * Push a statements Stack to the queue, without actually sending it
     *
     * @param \GraphAware\Neo4j\Client\Stack $stack
     */
    public function pushStack(Stack $stack)
    {
        $this->queue[] = $stack;
    }

    public function runStack(Stack $stack)
    {
        if (!$this->driverTransaction->isOpen() && !in_array($this->driverTransaction->status(), ['COMMITED', 'ROLLED_BACK'])) {
            $this->driverTransaction->begin();
        }
        $sts = [];
        foreach ($stack->statements() as $statement) {
            $sts[] = $statement;
        }

        return $this->driverTransaction->runMultiple($sts);
    }

    public function begin()
    {
        $this->driverTransaction->begin();
    }

    public function isOpen()
    {
        return $this->driverTransaction->isOpen();
    }

    public function isCommited()
    {
        return $this->driverTransaction->isCommited();
    }

    public function isRolledBack()
    {
        return $this->driverTransaction->isRolledBack();
    }

    public function status()
    {
        return $this->driverTransaction->status();
    }

    public function commit()
    {
        if (!$this->driverTransaction->isOpen() && !in_array($this->driverTransaction->status(), ['COMMITED', 'ROLLED_BACK'])) {
            $this->driverTransaction->begin();
        }
        if (!empty($this->queue)) {
            $stack = [];
            foreach ($this->queue as $element) {
                if ($element instanceof Stack) {
                    foreach ($element->statements() as $statement) {
                        $stack[] = $statement;
                    }
                } else {
                    $stack[] = $element;
                }
            }

            $result = $this->driverTransaction->runMultiple($stack);
            $this->driverTransaction->commit();
            $this->queue = [];
            return $result;
        } else {
            return $this->driverTransaction->commit();
        }
    }

    public function rollback()
    {
        return $this->driverTransaction->rollback();
    }
}


text:
/**
 *
 */
package com.xenonteam.xenonlib.client.gui.element;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import net.minecraft.util.ResourceLocation;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.xenonteam.xenonlib.client.gui.element.IGuiElement.IGuiElementParser;
import com.xenonteam.xenonlib.util.XUtils;

/**
 * @author tim4242
 * @author philipas
 *
 */
public class ElementLoader
{

	public static class LoaderInfo
	{
		public final LoaderType Type;
		public final ResourceLocation Location;

		public LoaderInfo(LoaderType t, ResourceLocation rl)
		{
			Type = t;
			Location = rl;
		}

		public List<IGuiElement> load()
		{
			return ElementLoader.getElements(Type, Location);
		}
	}

	private static HashMap<String, IGuiElementParser<?>> m_parsers = new HashMap<String, IGuiElementParser<?>>();

	public static void addTypeToParse(String type, IGuiElementParser<?> elm)
	{
		m_parsers.put(type, elm);
	}

	public static List<IGuiElement> getElements(LoaderType type, ResourceLocation loc)
	{
		try
		{

			switch(type)
			{
				case XML:
					return getElementsFromXML(loc);
			}

		} catch(Exception e)
		{
			e.printStackTrace();
		}

		return null;
	}

	public static List<IGuiElement> getElementsFromXML(ResourceLocation loc) throws Exception
	{
		List<IGuiElement> res = new ArrayList<IGuiElement>();

		InputStream stream = XUtils.getStreamFromRL(loc);

		if (stream == null)
			return null;

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		dbf.setValidating(false);
		dbf.setIgnoringComments(false);
		dbf.setIgnoringElementContentWhitespace(true);
		dbf.setNamespaceAware(true);

		DocumentBuilder db = null;
		db = dbf.newDocumentBuilder();

		Document doc = db.parse(stream);

		NodeList root = doc.getChildNodes();

		for (int i = 0; i < root.getLength(); i++)
		{

			Node node = root.item(i);

			if (node.getNodeType() != Node.ELEMENT_NODE)
			{
				return null;
			}

			Element XMLElm = (Element) node;

			if (!XMLElm.getNodeName().equalsIgnoreCase("element"))
			{
				return null;
			}

			IGuiElement elm = parseFromXML(XMLElm);

			if (elm == null)
				return null;

			res.add(elm);
		}

		return res;
	}

	public static IGuiElement parseFromXML(Element elm)
	{

		String name = null;
		String type = null;
		int x = 0;
		int y = 0;
		int w = 0;
		int h = 0;
		int prio = 0;

		if (!elm.hasAttribute("name"))
		{
			return null;
		} else
		{
			name = elm.getAttribute("name");
		}

		if (!elm.hasAttribute("type"))
		{
			return null;
		} else
		{
			name = elm.getAttribute("type");
		}

		if (elm.hasAttribute("x"))
			x = Integer.parseInt(elm.getAttribute("x"));
		if (elm.hasAttribute("y"))
			x = Integer.parseInt(elm.getAttribute("y"));
		if (elm.hasAttribute("w"))
			x = Integer.parseInt(elm.getAttribute("w"));
		if (elm.hasAttribute("h"))
			x = Integer.parseInt(elm.getAttribute("h"));
		if (elm.hasAttribute("prio"))
			x = Integer.parseInt(elm.getAttribute("prio"));

		return m_parsers.get(type).parseXML(elm, x, y, prio, w, h);

	}

	public static enum LoaderType
	{
		XML;
	}

}


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

namespace mtsuite.shared.Tasks.Experimental {
  public class CustomTaskCollection : ITaskCollection {
    private readonly CustomTaskFactory _factory;
    private readonly List<ITask> _tasks = new List<ITask>();

    public CustomTaskCollection(CustomTaskFactory factory) {
      _factory = factory;
    }

    public CustomTaskCollection(CustomTaskFactory factory, IEnumerable<ITask> source)
      : this(factory) {
      AddRange(source);
    }

    public IEnumerator<ITask> GetEnumerator() {
      return _tasks.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() {
      return GetEnumerator();
    }

    public void Add(ITask task) {
      _tasks.Add(task);
    }

    public void AddRange(IEnumerable<ITask> tasks) {
      _tasks.AddRange(tasks);
    }

    public ITask ContinueWith(Action<ITaskCollection> continuation) {
      var task = new CollectionContinuationTask(_factory, this, continuation);
      return _factory.EnqueueTaskForCollection(task, this);
    }

    public ITask<TResult> ContinueWith<TResult>(Func<ITaskCollection, TResult> continuation) {
      throw new NotImplementedException();
    }

    public ITask Then(Func<ITaskCollection, ITask> taskFactory) {
      var task = new CollectionThenTask(_factory, this, taskFactory);
      return _factory.EnqueueTaskForCollection(task, this);
    }

    public ITask<TResult> Then<TResult>(Func<ITaskCollection, ITask<TResult>> taskFactory) {
      throw new NotImplementedException();
    }
  }

  public class CustomTaskCollection<TResult> : ITaskCollection<TResult> {
    private readonly CustomTaskFactory _factory;
    private readonly List<ITask<TResult>> _tasks = new List<ITask<TResult>>();

    public CustomTaskCollection(CustomTaskFactory factory) {
      _factory = factory;
    }

    public CustomTaskCollection(CustomTaskFactory factory, IEnumerable<ITask<TResult>> source)
      : this(factory) {
      AddRange(source);
    }

    public IEnumerator<ITask<TResult>> GetEnumerator() {
      return _tasks.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() {
      return GetEnumerator();
    }

    public void Add(ITask<TResult> task) {
      _tasks.Add(task);
    }

    public void AddRange(IEnumerable<ITask<TResult>> tasks) {
      _tasks.AddRange(tasks);
    }

    public ITask ContinueWith(Action<ITaskCollection<TResult>> continuation) {
      var task = new CollectionContinuationTask<TResult>(_factory, this, continuation);
      return _factory.EnqueueTaskForCollection(task, this);
    }

    public ITask<TNewResult> ContinueWith<TNewResult>(Func<ITaskCollection<TResult>, TNewResult> continuation) {
      var task = new CollectionContinuationTask<TResult, TNewResult>(_factory, this, continuation);
      return _factory.EnqueueTaskForCollection(task, this);
    }

    public ITask Then(Func<ITaskCollection<TResult>, ITask> taskFactory) {
      throw new NotImplementedException();
    }

    public ITask<TNewResult> Then<TNewResult>(Func<ITaskCollection<TResult>, ITask<TNewResult>> taskFactory) {
      throw new NotImplementedException();
    }
  }
}